body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>Can you please help me fulfill the following?</p>
<p>Requirements:</p>
<ol>
<li><p>Create an iterable with unique elements. Their order should be preserved:</p>
<pre><code>a | b | a | c → a | b | c
</code></pre></li>
<li><p>The program must continually write to stdout.</p></li>
<li><p>The program must be computationally efficient.</p></li>
<li><p>The program must be written in the <a href="https://en.wikipedia.org/wiki/Functional_programming" rel="nofollow noreferrer">Functional programming</a> paradigm.</p></li>
</ol>
<hr>
<p>Attempts:</p>
<ol>
<li><p>Imperative style (violates 4):</p>
<pre class="lang-scala prettyprint-override"><code>def filterUnique[A](inSeq: Seq[A]): Seq[A] = {
val inSeqIt = inSeq.iterator
val mutableSet: scala.collection.mutable.Set[A] =
scala.collection.mutable.Set.empty
def go(it: Iterator[A], s: scala.collection.mutable.Set[A]): Stream[A] = {
if (it.hasNext) {
val cur: A = it.next
if (mutableSet.contains(cur)) {
go(it, s)
} else {
s += cur
Stream.cons(cur, go(it, s))
}
} else {
Stream.empty
}
}
go(inSeqIt, mutableSet).toSeq
}
</code></pre></li>
<li><p>Functional style with recursion (violates 2):</p>
<pre><code>@tailrec
def filterUnique[A](
inSeq: Seq[A],
set: Set[A] = Set.empty,
outSeq: Seq[A] = Seq.empty
): Seq[A] = {
if (inSeq.isEmpty) outSeq
else {
if (set.contains(inSeq.head))
filterUnique(inSeq.tail, set, outSeq)
else
filterUnique(inSeq.tail, set + inSeq.head, outSeq :+ inSeq.head)
}
}
</code></pre></li>
<li><p>Functional style with streams (violates 3; very unreadable):</p>
<pre><code>def filterUnique[A](inSeq: Seq[A]): Seq[A] = {
def grownSetSeq: Stream[Set[A]] = (
(Set.empty: Set[A])
#:: Set(inSeq.head)
#:: inSeq.tail.toStream
.zip(grownSetSeq.tail)
.map(
x ⇒ if (x._2.contains(x._1)) x._2 else x._2 + x._1
)
)
inSeq.zip(grownSetSeq).filter(x ⇒ !x._2.contains(x._1)).map(_._1).toStream
}
</code></pre></li>
</ol>
<hr>
<p>Trivia: this is part of one of my personal projects: <a href="https://github.com/fmv1992/fmv1992_scala_utilities" rel="nofollow noreferrer">https://github.com/fmv1992/fmv1992_scala_utilities</a>.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-01T20:31:24.667",
"Id": "455811",
"Score": "2",
"body": "Unfortunately, we don't provide code, we review code you've written. Depending on your problem, another site of the [StackExchange network](//stackexchange.com/) can help you. Please see our [help/on-topic] for more information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-01T20:52:53.110",
"Id": "455817",
"Score": "2",
"body": "2 and 4 aren't really compatible with each other. One of the cores of FP is use of pure functions, and a pure function doesn't \"continually write to stdout\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T04:40:27.347",
"Id": "455977",
"Score": "0",
"body": "\"continually write to stdout\"? None of the 3 write anything to stdout. Continually or otherwise."
}
] |
[
{
"body": "<p>So I tried this for a couple of hours (even before posting here) and the following approach proved useful:</p>\n\n<p>Work your way from the imperative approach back to the functional approach (rather than rewriting from scratch):</p>\n\n<pre><code>def filterUnique[A](inSeq: Seq[A]): Seq[A] = {\n\n def go(it: Iterator[A], s: Set[A]): Stream[A] = {\n if (it.hasNext) {\n val cur: A = it.next\n if (s.contains(cur)) {\n go(it, s)\n } else {\n Stream.cons(cur, go(it, s + cur))\n }\n } else {\n Stream.empty\n }\n }\n\n go(inSeq.iterator, Set.empty).toSeq\n}\n</code></pre>\n\n<p>Relevant commit is: <a href=\"https://github.com/fmv1992/fmv1992_scala_utilities/commit/4a6e844e474fb7360465e2b7977345a566e34123\" rel=\"nofollow noreferrer\">4a6e844</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-01T13:58:21.610",
"Id": "233226",
"ParentId": "233225",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-01T13:05:27.363",
"Id": "233225",
"Score": "-1",
"Tags": [
"functional-programming",
"scala",
"stream"
],
"Title": "Functional filter unique elements in sequence is not as good as imperative"
}
|
233225
|
<p>I have the following Django models setup:</p>
<pre><code>class Publication(models.Model):
value=models.CharField(max_length=255, unique=True)
class Article(models.Model):
filename = models.CharField(max_length=255)
publication = models.ForeignKey(Publication, on_delete=models.CASCADE)
class Image(models.Model):
name = models.CharField(max_length=255)
articles = models.ManyToManyField(Article)
</code></pre>
<p>I wanted to add an 'images' property to the Publication model. I have implemented it like this</p>
<pre><code>@property
def images(self):
images = []
for article in self.article_set.all():
images += list(article.images.all())
return list(set(images))
</code></pre>
<p>This works. I also considered trying something like</p>
<pre><code>return Images.objects.filter(articles__publication=self)
</code></pre>
<p>But I don't think that I can do this because then I have to define Images above Publications, which won't work with Articles and Images.</p>
<p>Is there a way for me to improve this query to handle less of the filtering in application logic and more of it in the database?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T15:11:49.800",
"Id": "455900",
"Score": "4",
"body": "Please edit your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!"
}
] |
[
{
"body": "<blockquote>\n<p>I also considered trying something like</p>\n<pre><code>return Images.objects.filter(articles__publication=self) \n</code></pre>\n<p>But I don't think that I can do this because then I have to define <code>Images</code> above\n<code>Publications</code>, which won't work with <code>Articles</code> and <code>Images</code>.</p>\n</blockquote>\n<p>Did you try this? It seems like it would work and would be the best approach. You could add a <code>.distinct()</code> clause at the end of the query to avoid converting to a set.</p>\n<p>It is best practice to set the <code>related_name</code> and <code>related_query_name</code> variables on your model related fields. This will make your queries less verbose; <code>article_set</code> and <code>image_set</code> become <code>articles</code> and <code>images</code>, respectively. See example below</p>\n<pre><code>class Article(models.Model):\n filename = models.CharField(max_length=255)\n publication = models.ForeignKey(to=Publication,\n on_delete=models.CASCADE,\n related_name='articles',\n related_query_name='article')\n\n\nclass Image(models.Model):\n name = models.CharField(max_length=255)\n articles = models.ManyToManyField(to=Article,\n related_name='images',\n related_query_name='image')\n</code></pre>\n<p>Look at the <a href=\"https://docs.djangoproject.com/en/3.0/ref/models/querysets/#prefetch-related\" rel=\"nofollow noreferrer\"><code>prefetch_related</code></a> documentation. You are querying the db for every image set on each article.</p>\n<pre><code>@property\ndef images(self):\n images = []\n for article in self.article_set.all():\n images += list(article.images.all())\n return list(set(images))\n</code></pre>\n<p>Using <code>prefetch_related</code>:</p>\n<pre><code>@property\ndef images(self):\n images = []\n publication = self.objects.prefetch_related('articles__images')\n for article in publication.articles.all():\n for image in article.images.all():\n images.append(image)\n\n return set(images)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-18T13:03:34.823",
"Id": "234257",
"ParentId": "233228",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-01T16:01:51.613",
"Id": "233228",
"Score": "4",
"Tags": [
"python",
"django"
],
"Title": "Querying all items that are in a many-to-many relationship with a child of an object"
}
|
233228
|
<p>I'm new to using VBA. What I'm working on is to copy details from a master file to multiple sheets within a worksheet.</p>
<p>I'm facing a performance problem when I run my code, my Excel file keeps blinking and not responding.</p>
<p>My code is as follows.</p>
<pre><code>Sub Button1_Click()
Dim lastrow As Long
Dim erow As Long
Dim i As Integer
MsgBox ("Clear details of the destination sheets.")
Worksheets("15 Tax Class").Range("A7:V5000").Clear
Worksheets("14 Long Texts").Range("A7:I5000").Clear
Worksheets("12 UoM").Range("A7:V5000").Clear
Worksheets("11 Description").Range("A7:E5000").Clear
Worksheets("09 Sales").Range("A7:AS5000").Clear
Worksheets("03 Plant").Range("A7:FI5000").Clear
Worksheets("02 Client").Range("A7:CR5000").Clear
Worksheets("01 Header").Range("A7:U5000").Clear
MsgBox ("Please wait while template is being populated.")
lastrow = Worksheets("Masterfile").Cells(Rows.Count, 1).End(xlUp).Row
For i = 7 To lastrow
'01 Header Data
Worksheets("Masterfile").Cells(i, 1).Copy
erow = Worksheets("01 Header").Cells(Rows.Count, 1).End(xlUp).Row
Worksheets("Masterfile").Paste Destination:=Worksheets("01 Header").Cells(erow + 1, 1)
Worksheets("01 Header").Cells(i, 2) = "Z"
Worksheets("01 Header").Cells(i, 3) = "DIEN"
Worksheets("01 Header").Cells(i, 4) = "X"
Worksheets("01 Header").Cells(i, 5) = "X"
Worksheets("01 Header").Cells(i, 6) = "X"
Worksheets("01 Header").Cells(i, 7) = "X"
'02 Client Data
Worksheets("Masterfile").Cells(i, 1).Copy
erow = Worksheets("02 Client").Cells(Rows.Count, 1).End(xlUp).Row
Worksheets("Masterfile").Paste Destination:=Worksheets("02 Client").Cells(erow + 1, 1)
Worksheets("Masterfile").Range("D7:D5000").Copy
erow = Worksheets("02 Client").Cells(Rows.Count, 3).End(xlUp).Row
Worksheets("02 Client").Range("C7").PasteSpecial Paste:=xlPasteValues, SkipBlanks:=False
Worksheets("Masterfile").Range("E7:E5000").Copy
erow = Worksheets("02 Client").Cells(Rows.Count, 4).End(xlUp).Row
Worksheets("02 Client").Range("D7").PasteSpecial Paste:=xlPasteValues, SkipBlanks:=False
Worksheets("Masterfile").Range("F7:F5000").Copy
erow = Worksheets("02 Client").Cells(Rows.Count, 5).End(xlUp).Row
Worksheets("02 Client").Range("E7").PasteSpecial Paste:=xlPasteValues, SkipBlanks:=False
Worksheets("Masterfile").Range("G7:G5000").Copy
erow = Worksheets("02 Client").Cells(Rows.Count, 5).End(xlUp).Row
Worksheets("02 Client").Range("F7").PasteSpecial Paste:=xlPasteValues, SkipBlanks:=False
Worksheets("02 Client").Cells(i, 82) = "NORM"
'03 Plant Data
Worksheets("Masterfile").Cells(i, 1).Copy
erow = Worksheets("03 Plant").Cells(Rows.Count, 1).End(xlUp).Row
Worksheets("Masterfile").Paste Destination:=Worksheets("03 Plant").Cells(erow + 1, 1)
Worksheets("Masterfile").Range("H7:H5000").Copy
erow = Worksheets("03 Plant").Cells(Rows.Count, 2).End(xlUp).Row
Worksheets("03 Plant").Range("B7").PasteSpecial Paste:=xlPasteValues, SkipBlanks:=False
Worksheets("Masterfile").Range("I7:I5000").Copy
erow = Worksheets("03 Plant").Cells(Rows.Count, 75).End(xlUp).Row
Worksheets("03 Plant").Range("BW7").PasteSpecial Paste:=xlPasteValues, SkipBlanks:=False
'09 Sales Data
Worksheets("Masterfile").Cells(i, 1).Copy
erow = Worksheets("09 Sales").Cells(Rows.Count, 1).End(xlUp).Row
Worksheets("Masterfile").Paste Destination:=Worksheets("09 Sales").Cells(erow + 1, 1)
Worksheets("Masterfile").Range("J7:J5000").Copy
erow = Worksheets("09 Sales").Cells(Rows.Count, 2).End(xlUp).Row
Worksheets("09 Sales").Range("B7").PasteSpecial Paste:=xlPasteValues, SkipBlanks:=False
Worksheets("Masterfile").Range("K7:K5000").Copy
erow = Worksheets("09 Sales").Cells(Rows.Count, 3).End(xlUp).Row
Worksheets("09 Sales").Range("C7").PasteSpecial Paste:=xlPasteValues, SkipBlanks:=False
Worksheets("Masterfile").Range("L7:L5000").Copy
erow = Worksheets("09 Sales").Cells(Rows.Count, 17).End(xlUp).Row
Worksheets("09 Sales").Range("Q7").PasteSpecial Paste:=xlPasteValues, SkipBlanks:=False
Worksheets("Masterfile").Range("O7:O5000").Copy
erow = Worksheets("09 Sales").Cells(Rows.Count, 25).End(xlUp).Row
Worksheets("09 Sales").Range("Y7").PasteSpecial Paste:=xlPasteValues, SkipBlanks:=False
Worksheets("Masterfile").Range("P7:P5000").Copy
erow = Worksheets("09 Sales").Cells(Rows.Count, 26).End(xlUp).Row
Worksheets("09 Sales").Range("Z7").PasteSpecial Paste:=xlPasteValues, SkipBlanks:=False
Worksheets("Masterfile").Range("Q7:Q5000").Copy
erow = Worksheets("09 Sales").Cells(Rows.Count, 27).End(xlUp).Row
Worksheets("09 Sales").Range("AA7").PasteSpecial Paste:=xlPasteValues, SkipBlanks:=False
Worksheets("Masterfile").Range("R7:R5000").Copy
erow = Worksheets("09 Sales").Cells(Rows.Count, 27).End(xlUp).Row
Worksheets("09 Sales").Range("AB7").PasteSpecial Paste:=xlPasteValues, SkipBlanks:=False
Worksheets("Masterfile").Range("S7:S5000").Copy
erow = Worksheets("09 Sales").Cells(Rows.Count, 27).End(xlUp).Row
Worksheets("09 Sales").Range("AC7").PasteSpecial Paste:=xlPasteValues, SkipBlanks:=False
'11 Description Data
Worksheets("Masterfile").Cells(i, 1).Copy
erow = Worksheets("11 Description").Cells(Rows.Count, 1).End(xlUp).Row
Worksheets("Masterfile").Paste Destination:=Worksheets("11 Description").Cells(erow + 1, 1)
Worksheets("11 Description").Cells(i, 2) = "EN"
Worksheets("Masterfile").Range("B7:B5000").Copy
erow = Worksheets("11 Description").Cells(Rows.Count, 4).End(xlUp).Row
Worksheets("11 Description").Range("D7").PasteSpecial Paste:=xlPasteValues, SkipBlanks:=False
'12 UoM Data
Worksheets("Masterfile").Cells(i, 1).Copy
erow = Worksheets("12 UoM").Cells(Rows.Count, 1).End(xlUp).Row
Worksheets("Masterfile").Paste Destination:=Worksheets("12 UoM").Cells(erow + 1, 1)
Worksheets("Masterfile").Range("L7:L5000").Copy
erow = Worksheets("12 UoM").Cells(Rows.Count, 2).End(xlUp).Row
Worksheets("12 UoM").Range("B7").PasteSpecial Paste:=xlPasteValues, SkipBlanks:=False
Worksheets("Masterfile").Range("M7:M5000").Copy
erow = Worksheets("12 UoM").Cells(Rows.Count, 4).End(xlUp).Row
Worksheets("12 UoM").Range("D7").PasteSpecial Paste:=xlPasteValues, SkipBlanks:=False
Worksheets("Masterfile").Range("N7:N5000").Copy
erow = Worksheets("12 UoM").Cells(Rows.Count, 5).End(xlUp).Row
Worksheets("12 UoM").Range("E7").PasteSpecial Paste:=xlPasteValues, SkipBlanks:=False
'14 Long Texts Data
Worksheets("Masterfile").Cells(i, 1).Copy
erow = Worksheets("14 Long Texts").Cells(Rows.Count, 1).End(xlUp).Row
Worksheets("Masterfile").Paste Destination:=Worksheets("14 Long Texts").Cells(erow + 1, 1)
Worksheets("Masterfile").Paste Destination:=Worksheets("14 Long Texts").Cells(erow + 1, 3)
Worksheets("14 Long Texts").Cells(i, 2) = "MATERIAL"
Worksheets("14 Long Texts").Cells(i, 4) = "GRUN"
Worksheets("14 Long Texts").Cells(i, 5) = "EN"
Worksheets("Masterfile").Range("C7:C5000").Copy
erow = Worksheets("14 Long Texts").Cells(Rows.Count, 8).End(xlUp).Row
Worksheets("14 Long Texts").Range("H7").PasteSpecial Paste:=xlPasteValues, SkipBlanks:=False
'15 Tax Class Data
Worksheets("Masterfile").Cells(i, 1).Copy
erow = Worksheets("15 Tax Class").Cells(Rows.Count, 1).End(xlUp).Row
Worksheets("Masterfile").Paste Destination:=Worksheets("15 Tax Class").Cells(erow + 1, 1)
Worksheets("15 Tax Class").Cells(i, 2) = "PH"
Worksheets("15 Tax Class").Cells(i, 4) = "MWST"
Worksheets("15 Tax Class").Cells(i, 5) = "1"
Next i
MsgBox ("Generating of Upload Template already done!")
End Sub
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-01T20:43:10.190",
"Id": "455816",
"Score": "1",
"body": "Have you tried decreasing the amount of data and see if it completes eventually? Excel not responding is not uncommon when it's working on large datasets, but we need to know whether it works eventually."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T08:57:00.977",
"Id": "455846",
"Score": "0",
"body": "Thank you, guys. I've learned a lot."
}
] |
[
{
"body": "<blockquote>\n<pre><code>Sub Button1_Click()\n</code></pre>\n</blockquote>\n\n<p>I know it's tempting to just double-click the ActiveX control and code everything in the auto-generated event handler procedure, but that's a very bad habit you will need to lose early on. The handler was generated with an explicit <code>Private</code> access modifier, too - it being absent means it was <em>removed</em>, leaving the procedure <em>implicitly</em> public, exposed to whatever caller code that might feel like invoking an <em>event handler</em> procedure... and event handlers are meant to be invoked by an <em>event</em> - like a button being clicked. Don't make event handlers public, they have no business being invoked by anything else, and thus no business ever being <code>Public</code> - explicitly or not.</p>\n\n<blockquote>\n<pre><code>Dim lastrow As Long\nDim erow As Long\nDim i As Integer\n</code></pre>\n</blockquote>\n\n<p>You may have been taught, or have read somewhere, that declaring all your local variables at the top of the procedure was a good idea - it's not. It only serves to lose track of what's declared with what data type, and in a long procedure it makes the maintainer constantly scroll back and forth, especially with many variables... one problem is that this block of declarations inevitably becomes a <em>wall</em> of declarations, and it becomes very hard to track what's used, and that's exactly how code rots and starts stinking.</p>\n\n<p>But there's another problem: <code>lastRow</code> is a 32-bit integer (<code>Long</code>), but <code>i</code> is only a 16-bit integer (<code>Integer</code>), which means the last row could very well be 32,768... and then that would overflow the 16 bits of <code>Integer</code>, and blow up at run-time: that declaration is a ticking time bomb that needs to be fixed: you want <code>i</code> to be <code>As Long</code>. In fact, there's hardly ever any reason to declare anything <code>As Integer</code> - best stay clear of 16-bit data types for a value representing a row number on a worksheet.</p>\n\n<blockquote>\n<pre><code>MsgBox (\"Clear details of the destination sheets.\")\n</code></pre>\n</blockquote>\n\n<p>Watch out here, these parentheses aren't delimiting the <code>MsgBox</code> function call's argument list: they are redundantly wrapping up the first argument (the string literal expression), and if you were to decide to add a title and/or an icon (i.e. pass a 2nd and/or a 3rd argument), you'd find that you need to specify them <em>after</em> the <code>)</code> closing parenthesis, or face a compile-time syntax error.</p>\n\n<pre><code>MsgBox (\"Clear details of the destination sheets.\"), \"Awkward\", vbOkOnly\n</code></pre>\n\n<p>When you invoke a function <em>without capturing its return value into a local variable</em>, you do not use any parentheses. What you did here, is force VBA to evaluate the string literal as a value, and pass <em>the result</em> of this evaluation as an argument to the function. When the argument is a string literal this has little impact, but these mechanics will bite you in the rear end sooner or later, and wreck everything as soon as you start passing object references between procedures: best not make it a habit.</p>\n\n<blockquote>\n<pre><code>Worksheets(\"15 Tax Class\").Range(\"A7:V5000\").Clear\n</code></pre>\n</blockquote>\n\n<p>This code is implicitly working off whatever the <code>ActiveWorkbook</code> is. If the sheets all exist in <code>ThisWorkbook</code>, then there is no need to ever dereference any of these sheets from any <code>Sheets</code> collection (kudos for using <code>Worksheets</code> though: the <code>Sheets</code> property yields all kinds of objects including <code>Chart</code>, not just <code>Worksheet</code> items, so it's best to use it when dereferencing worksheets). Worksheets that exist in <code>ThisWorkbook</code> (the host document) at compile-time, have a named code module that you can reference anywhere in your project - simply set the sheets' <code>(Name)</code> property to a valid VBA identifier name like <code>TaxClassSheet</code>, and then you can do this:</p>\n\n<pre><code>TaxClassSheet.Range(\"A7:V5000\").Clear\n</code></pre>\n\n<p>That hard-coded range address is suspicious: why not work out what the actual range is, instead of crossing fingers and hope that'll do?</p>\n\n<p>Of course that means <em>more code</em>... or does it?</p>\n\n<blockquote>\n<pre><code>lastrow = Worksheets(\"Masterfile\").Cells(Rows.Count, 1).End(xlUp).Row\n</code></pre>\n</blockquote>\n\n<p>If you had a function whose only job was to return the last row in the specified column of a specified worksheet...</p>\n\n<pre><code>Private Function GetLastRowIn(ByVal sheet As Worksheet, ByVal columnIndex As Long = 1) As Long\n GetLastRowIn = sheet.Cells(sheet.Rows.Count, columnIndex).End(xlUp).Row\nEnd Function\n</code></pre>\n\n<p>...then you could easily get the last row for every sheet you could want the last row for, without repeating the logic every time.</p>\n\n<p>Problem is, with everything in a single scope, the last thing you want is a <code>lastRow</code> variable for which <em>what sheet it's from</em> depends where you're at in the procedure.</p>\n\n<p>Variables that have one meaning at one place, and another meaning in another place, are evil. <code>erow</code> is one such variable: its meaning and purpose evolves as the procedure progresses - and that's a tell-tale sign of a missed opportunity, confirmed with every single one of these headings:</p>\n\n<blockquote>\n<pre><code>'02 Client Data\n</code></pre>\n</blockquote>\n\n<p>Whenever you feel the need for a comment to say \"this chunk of code does X\", stop. Don't do it. Instead, start a new \"do X\" procedure:</p>\n\n<pre><code>Private Sub DoX()\n</code></pre>\n\n<p>In this case it could be <code>ProcessClientData</code>, and then there would be another <code>ProcessPlantData</code> procedure, and then another for the other source sheet, and so on, until the \"main\" public procedure looks like it doesn't do much more than call a bunch of more specialized, smaller procedures: you get an instant bird's eye view of what the macro does, without all the details that aren't relevant to the big picture - the gory details are in the other, lower-abstraction procedures further down the code module.</p>\n\n<p>I want to slip a word about performance too, but it would be wrong to just say \"turn off screen updating and automatic calculations\" and call the resulting code anywhere near efficient: these tweaks will stop Excel going \"(not responding)\" and will make everything run much faster too, but it does not make an inefficient algorithm any better.</p>\n\n<p>Also to be considered, is error handling: whenever this global <code>Application</code> state gets toggled, you absolutely want error handling to ensure the state gets reset back to what it was when the procedure was invoked, otherwise problems can be expected:</p>\n\n<pre><code> On Error GoTo CleanFail\n Application.EnableEvents = False\n Application.ScreenUpdating = False\n Application.Calculation = xlCalculationManual\n\n '...\n\nCleanExit:\n Application.EnableEvents = False\n Application.ScreenUpdating = False\n Application.Calculation = xlCalculationManual\n Exit Sub\nCleanFail:\n MsgBox Err.Description\n Resume CleanExit\nEnd Sub\n</code></pre>\n\n<p>Note how the error-handling subroutine is only accessible while execution is in an error state: this separation is critical to avoid the spaghettification easily induced by intertwined \"happy\" and \"error\" execution paths.</p>\n\n<p>So that alone should help a lot performance-wise, but as I said above it doesn't make your code any more efficient.</p>\n\n<p>But what's wrong with the approach anyway?</p>\n\n<p>Copying the source data <em>Row By Agonizing Row</em> (RBAR) is what's wrong: the <code>i</code> loop shouldn't even exist - you want to copy the whole source range and paste it at its destination <em>once</em>, ideally for all needed columns together, or at least once per contiguous range of cells. In fact, since all we care about is values (no borders, formats, or validations), we don't even need to get the clipboard involved; just assign <code>destinationRange.Value = sourceRange.Value</code>, and done.</p>\n\n<p>Follow the execution of the loop, and consider how many times cells in rows 7 through 5000 are copied and pasted over: you're copying close to 5K cells every time, to paste at row <code>i</code>.</p>\n\n<p>The result is probably not what you are expecting... and it's only after writing all this that I realize that your code very likely doesn't work as intended after all.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T15:02:24.517",
"Id": "455897",
"Score": "1",
"body": "*\"[...] and it's only after writing all this that I realize that your code very likely doesn't work as intended after all\"* - then shouldn't you un-reopen the question :/? (Just playing devil's advocate - I think this answer brings enough value not to close the question and lose it)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T16:47:32.433",
"Id": "455917",
"Score": "2",
"body": "@Greedo I've painted myself into a corner here; question was closed as broken code as per OP's \"not responding\" host app, then I reopened it because Excel going \"not responding\" does not mean VBA code is broken - as a moderator my votes are binding, I can't just *vote* to close, ...this answer puts me in a conflicted weird place where if I delete it to do what's right then I remove valuable information (I don't really care for the rep or the two hours I sunk into it), and if I close the OP then I reopened only to post an answer and close it again, which feels very wrong. Vote as you see fit =)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T00:57:30.597",
"Id": "233245",
"ParentId": "233236",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-01T18:11:55.023",
"Id": "233236",
"Score": "0",
"Tags": [
"vba",
"excel"
],
"Title": "Copying data from a \"master\" sheet onto multiple \"detail\" sheets"
}
|
233236
|
<p>I was wondering if any of you would mind reviewing my program? I'm a beginner / aspiring programmer and I'm looking for tips on how I could make my program more efficient. For example, have I made good use of sub-routines / functions? Am I using classes properly? Is there anything I could do to perhaps shorten the length of the program?</p>
<pre><code>// Created by George Austin Bradley on 19/11/2019.
// Copyright © 2019 George Austin Bradley. All rights reserved.
#include <iostream>
#include <iomanip>
#include <vector>
#include <cctype>
using namespace std;
class cCar{
private:
string _sName;
double _dPrice;
public:
cCar(string s, double d){
_sName = s;
_dPrice = d;
}
string getName(){return _sName;}
double getPrice(){return _dPrice;}
};
vector<cCar>CarDatabase(vector<cCar>&car_list){
car_list.push_back(cCar("Blue Nissan Skyline",1000));
car_list.push_back(cCar("Red Mini",3000));
car_list.push_back(cCar("Black Land Rover",4000));
car_list.push_back(cCar("Beatle",9000));
car_list.push_back(cCar("Ferrari",300000));
return car_list;
}
class Finance{
private:
string _sUserName;
double _dCostOfCar;
string _sChosenCar;
int _iFinancePlan;
double _dDepositedAmount;
double _dMonthlyPayments;
double _dTotalLeftToPay;
public:
Finance(string sName, double dCostOfCar, string sChosenCar, int iFinancePlan, double dDepositedAmount, double dDMonthlyPayments, double dTotalLeftToPay){
_sUserName = sName;
_dCostOfCar = dCostOfCar;
_sChosenCar = sChosenCar;
_iFinancePlan = iFinancePlan;
_dDepositedAmount = dDepositedAmount;
_dMonthlyPayments = dDMonthlyPayments;
_dTotalLeftToPay = dTotalLeftToPay;
}
string getUserName(){return _sUserName;}
double getdCostOfCar(){return _dCostOfCar;}
string getChosenCar(){return _sChosenCar;}
int getFinancePlan(){return _iFinancePlan;}
double getDepositAmount(){return _dDepositedAmount;}
double getMonthlyAmount(){return _dMonthlyPayments;}
double getTotalLeftToPay(){return _dTotalLeftToPay;}
};
//START OF PROTOTYPE
void ViewPurchases(vector<Finance>&buyers, char &cOption, bool &bExit);
//END OF PROTOTYPE
//1. This displays the car menu items.
void display_menu(vector<cCar>&car_list)
{
cout << "\nMENU";
for (int iCount = 0; iCount != car_list.size(); iCount++)
{
cout << "\n" << iCount + 1 << ". " << car_list[iCount].getName();
cout << "\n\tPrice: £" << car_list[iCount].getPrice();
cout << "\n";
}
}
//This procedure proccesses the user's selection and all information regarding price and name of car are then transferred to transaction variables.
void selectedCar(vector<cCar>&car_list, string &sNameOfChosenCar, double &dCostOfChosenCar)
{
int iSelectionFromMenu = -1;
do{
cout << "\nChoose a car that you'd wish to buy from the menu (1 - " << car_list.size() << "): ";
cin >> iSelectionFromMenu;
if(iSelectionFromMenu > 0 && iSelectionFromMenu <= car_list.size())
{
sNameOfChosenCar = car_list[iSelectionFromMenu - 1].getName();
dCostOfChosenCar = car_list[iSelectionFromMenu - 1].getPrice();
}
else
{
cout << "\nPlease enter valid number!";
iSelectionFromMenu = -1;
}
}while(iSelectionFromMenu == -1);
}
//This procedure gets from the user their preferred finance plan through their input.
void FinanceLength(int &iFinanceLength)
{
do{
cout << "\nHow long do you wish for your finance plan to last? (1 - 4 years): ";
cin >> iFinanceLength;
if (iFinanceLength < 0 || iFinanceLength > 4)
{
cout << "\nOops, try again! Please enter between 1 - 4!";
}
}while(iFinanceLength < 0 || iFinanceLength > 4);
}
//This procedure gets the user's deposit.
void DepositMoney(double &dDepositAmount)
{
do{
cout << "\nEnter deposit amount (minimum £500 accepted): £";
cin >> dDepositAmount;
if (dDepositAmount < 500)
{
cout << "\nTry again! Deposit an amount greater than or equal to £500.";
}
}while(dDepositAmount < 500);
}
//This function calculates the amount of money the user has to pay after deposit, added tax and charge percentage of 10%
double TotalLeftToPay(double iFinanceLength, double dDepositAmount, double dCostOfChosenCar)
{
double dChargePercentage = 0.10;
double dTotalLeftToPay = dCostOfChosenCar + (dCostOfChosenCar * dChargePercentage) - dDepositAmount + 135;
return dTotalLeftToPay;
}
//This calculates monthly payments.
double MonthlyPayments(double dTotalLeftToPay, int iFinanceLength)
{
double dMonthlyPayments = (dTotalLeftToPay / iFinanceLength) / 12;
return dMonthlyPayments;
}
void EndOfProgramOptions(vector<Finance>&buyers, char &cOption, bool &bExit)
{
char cInputSelection = 0;
do{
cout << "View your purchases (y/n): ";
cin >> cInputSelection;
cInputSelection = toupper(cInputSelection);
if (cInputSelection == 'Y')
{
ViewPurchases(buyers, cOption, bExit);
}
}while(cInputSelection != 'Y' && cInputSelection != 'N');
}
//This asks the user whether they'd like to restart the application.
void RestartOptions(char &cOption, bool &bExit, vector<Finance>&buyers)
{
do{
cout << "\nDo you wish to make another purchase? (y/n): ";
cin >> cOption;
cOption = toupper(cOption);
switch(cOption)
{
case 'Y':
bExit = false;
break;
case 'N':
EndOfProgramOptions(buyers, cOption, bExit);
bExit = true;
break;
default:
cout << "Sorry, that's an invalid input, please try again!";
continue;
}
}while(cOption != 'Y' && cOption != 'N');
}
//This string function returns either year or years (plural)
string YearOrYears(int iFinanceLength)
{
return (iFinanceLength > 1)? "years" : "year";
}
//This displays receipt of the user's transaction.
void Receipt(const string &sUserName, const int &iFinanceLength, const double &dDepositAmount, char cOption, bool &bExit, const string &sNameOfChosenCar, const double &dCostOfChosenCar, vector<Finance>&buyers)
{
double dTotalLeftToPay = TotalLeftToPay(iFinanceLength, dDepositAmount, dCostOfChosenCar);
double dMonthlyPayments = MonthlyPayments(dTotalLeftToPay, iFinanceLength);
buyers.push_back(Finance(sUserName,dCostOfChosenCar,sNameOfChosenCar,iFinanceLength,dDepositAmount, dMonthlyPayments,dTotalLeftToPay));
cout << "\nReceipt for: " << sUserName << ". ";
cout << "\nYou have chosen " << sNameOfChosenCar << ".";
cout << "\nYour finance plan timescale is " << iFinanceLength << " " << YearOrYears(iFinanceLength) << ".";
cout << "\nYou've deposited £" << dDepositAmount << ".";
cout << "\nTotal left to pay: £" << dTotalLeftToPay;
cout << "\nMonthly Payments: £" << dMonthlyPayments;
cout << "\n";
RestartOptions(cOption, bExit, buyers);
}
//This displays receipt of the user's transaction.
void ViewPurchases(vector<Finance>&buyers, char &cOption, bool &bExit)
{
for (int iCount = 0; iCount != buyers.size(); iCount++)
{
cout << "\nPurchase " << iCount + 1 << " by " << buyers[iCount].getUserName() << ". ";
cout << "\nYou have chosen " << buyers[iCount].getChosenCar() << ".";
cout << "\nYour finance plan timescale is " << buyers[iCount].getFinancePlan() << " " << YearOrYears(buyers[iCount].getFinancePlan()) << ".";
cout << "\nYou've deposited £" << buyers[iCount].getDepositAmount() << ".";
cout << "\nTotal left to pay: £" << buyers[iCount].getTotalLeftToPay() << ".";
cout << "\nMonthly Payments: £" << buyers[iCount].getMonthlyAmount() << ".";
cout << "\n";
}
RestartOptions(cOption, bExit,buyers);
}
//This asks the user whether they're happy with the options of they've chosen.
void AcceptDeclineOptions(string &sUserName, int &iFinanceLength, double &dDepositAmount, bool &bExit, string &sNameOfChosenCar, double &dCostOfChosenCar, vector<Finance>&buyers)
{
char cOption = 0;
do
{
cout << "\nConfirm finance plan (y/n): ";
cin >> cOption;
cOption = toupper(cOption);
if (cOption == 'Y')
{
Receipt(sUserName, iFinanceLength, dDepositAmount, cOption, bExit, sNameOfChosenCar, dCostOfChosenCar, buyers);
}
else if (cOption == 'N')
{
RestartOptions(cOption, bExit, buyers);
}
else
{
cout << "\nSorry, that's not a valid command.";
}
}while(cOption != 'Y' && cOption != 'N');
}
int main()
{
bool bExit = false;
int iFinanceLength = 0;
double dDepositAmount = 0;
string sNameOfChosenCar = "";
double dCostOfChosenCar = 0;
vector<cCar>car_list;
CarDatabase(car_list);
vector<cCar>car_purchases;
vector<Finance>buyers;
cout << "Welcome!";
string sUserName = "";
cout << "\nEnter your name: ";
cin >> sUserName;
do{
display_menu(car_list);
selectedCar(car_list, sNameOfChosenCar, dCostOfChosenCar);
FinanceLength(iFinanceLength);
DepositMoney(dDepositAmount);
AcceptDeclineOptions(sUserName, iFinanceLength,dDepositAmount,bExit, sNameOfChosenCar, dCostOfChosenCar, buyers);
}while(bExit == false);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T00:49:09.880",
"Id": "455833",
"Score": "5",
"body": "This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you. [Questions should include a description of what the code does](//codereview.meta.stackexchange.com/q/1226)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T09:54:00.403",
"Id": "455863",
"Score": "0",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
}
] |
[
{
"body": "<p>A big issue with your code is consistency and there are a lot of duplicated points of pain in your code. I've not repeated them in every case.</p>\n\n<p><strong>Just a nitpick, but sorting your headers makes them easier to read.</strong></p>\n\n<pre><code>#include <iostream>\n#include <iomanip>\n#include <vector>\n#include <cctype>\n</code></pre>\n\n<p><strong>Avoid declaring <code>using namespace std;</code>, especially in a header file.</strong></p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p><strong>Don't prefix your types.</strong></p>\n\n<pre><code>class cCar {\n</code></pre>\n\n<p><strong>Declare access modifiers in public, protected, private order.</strong></p>\n\n<pre><code>private:\n</code></pre>\n\n<p><strong>Systems Hungarian notation is out-dated by many decades and isn't useful anymore with modern inventions like intellisense.</strong></p>\n\n<p><strong>Avoid starting a variable declaration with an underscore (and never containing two back-to-back), the rules are obscure and you may clash with a reserved-for-implementation declaration.</strong></p>\n\n<pre><code> string _sName;\n</code></pre>\n\n<p><strong>From a rounding error perspective, never use floating-point datatypes when dealing with money. Prefer <code>long long</code> and then divide by the appropriate conversion from smallest unit to whole unit amounts at the end.</strong></p>\n\n<p><strong>i.e. if units are in dollars and cents, you'd store the values in cents/pennies and divide by 100 at the end; if the units are in pounds and pence (after 1971), you'd store the values in pence and divide by 100 at the end as well.</strong></p>\n\n<pre><code> double _dPrice;\npublic:\n</code></pre>\n\n<p><strong>Use constructor initializer lists instead of copying data twice in the body.</strong></p>\n\n<p><strong>The argument names aren't helpful. Consider naming them more appropriately such as <code>name</code> and <code>price</code>.</strong></p>\n\n<pre><code> cCar(string s, double d) {\n _sName = s;\n _dPrice = d;\n }\n string getName() { return _sName; }\n double getPrice() { return _dPrice; }\n};\n</code></pre>\n\n<p><strong>You append the argument vector AND return it. Why?</strong></p>\n\n<pre><code>vector<cCar>CarDatabase(vector<cCar>& car_list) {\n</code></pre>\n\n<p><strong>You aren't declaring <code>cCar</code>'s constructor <code>explicit</code>. Because of this, consider using an initializer list instead of explicitly calling the constructor.</strong></p>\n\n<p><strong>i.e. <code>car_list.push_back({\"Blue Nissan Skyline\", 1000});</code>.</strong></p>\n\n<pre><code> car_list.push_back(cCar(\"Blue Nissan Skyline\", 1000));\n car_list.push_back(cCar(\"Red Mini\", 3000));\n car_list.push_back(cCar(\"Black Land Rover\", 4000));\n car_list.push_back(cCar(\"Beatle\", 9000));\n car_list.push_back(cCar(\"Ferrari\", 300000));\n return car_list;\n}\n</code></pre>\n\n<p><strong>Be consistent. You prefixed <code>cCar</code> but nothing else. Prefer removing the prefix of <code>cCar</code>.</strong></p>\n\n<p><strong>Put unrelated classes in their own header and implementation files.</strong></p>\n\n<p><strong>See previous about avoiding floating-point types when dealing with money.</strong></p>\n\n<pre><code>class Finance {\nprivate:\n string _sUserName;\n double _dCostOfCar;\n string _sChosenCar;\n int _iFinancePlan;\n double _dDepositedAmount;\n double _dMonthlyPayments;\n double _dTotalLeftToPay;\n\npublic:\n</code></pre>\n\n<p><strong>Consistency. You have well-defined argument names here but not in <code>cCar</code>.</strong></p>\n\n<p><strong>Use constructor initializer list instead of copying in the body.</strong></p>\n\n<p><strong>Systems Hungarian notation is out-dated.</strong></p>\n\n<pre><code> Finance(string sName, double dCostOfCar, string sChosenCar, int iFinancePlan, double dDepositedAmount, double dDMonthlyPayments, double dTotalLeftToPay) {\n _sUserName = sName;\n _dCostOfCar = dCostOfCar;\n _sChosenCar = sChosenCar;\n _iFinancePlan = iFinancePlan;\n _dDepositedAmount = dDepositedAmount;\n _dMonthlyPayments = dDMonthlyPayments;\n _dTotalLeftToPay = dTotalLeftToPay;\n }\n //...\n};\n</code></pre>\n\n<p><strong>Useless comments. A professional programmer is going to know what this is.</strong></p>\n\n<p><strong>Consistency as well. Why didn't you prototype every function?</strong></p>\n\n<pre><code>//START OF PROTOTYPE\nvoid ViewPurchases(vector<Finance>& buyers, char& cOption, bool& bExit);\n//END OF PROTOTYPE\n</code></pre>\n\n<p><strong>Comments that simply repeat information given by the function's name are less than useful and should be removed.</strong></p>\n\n<pre><code>//1. This displays the car menu items.\nvoid display_menu(vector<cCar>& car_list)\n{\n //...\n</code></pre>\n\n<p><strong>Again, consistency. This function and its arguments use camalCase and C-style lower-case with underscores. Other functions use just C-style. Pick one.</strong></p>\n\n<pre><code>//This procedure proccesses the user's selection and all information regarding price and name of car are then transferred to transaction variables.\nvoid selectedCar(vector<cCar>& car_list, string& sNameOfChosenCar, double& dCostOfChosenCar)\n{\n //...\n</code></pre>\n\n<p><strong>The following comments are unhelpful as they add no more information than what the function name already provides.</strong></p>\n\n<pre><code>//This procedure gets the user's deposit.\nvoid DepositMoney(double& dDepositAmount)\n{\n //...\n\n//This function calculates the amount of money the user has to pay after deposit, added tax and charge percentage of 10%\ndouble TotalLeftToPay(double iFinanceLength, double dDepositAmount, double dCostOfChosenCar)\n{\n //...\n\n//This calculates monthly payments.\ndouble MonthlyPayments(double dTotalLeftToPay, int iFinanceLength)\n{\n //...\n\n//This asks the user whether they'd like to restart the application.\nvoid RestartOptions(char& cOption, bool& bExit, vector<Finance>& buyers)\n{\n //...\n\n//This string function returns either year or years (plural)\nstring YearOrYears(int iFinanceLength)\n{\n return (iFinanceLength > 1) ? \"years\" : \"year\";\n}\n//...\n\n//This displays receipt of the user's transaction.\nvoid Receipt(const string& sUserName, const int& iFinanceLength, const double& dDepositAmount, char cOption, bool& bExit, const string& sNameOfChosenCar, const double& dCostOfChosenCar, vector<Finance>& buyers)\n{\n //...\n\n//This displays receipt of the user's transaction.\nvoid ViewPurchases(vector<Finance>& buyers, char& cOption, bool& bExit)\n{\n //...\n\n//This asks the user whether they're happy with the options of they've chosen.\nvoid AcceptDeclineOptions(string& sUserName, int& iFinanceLength, double& dDepositAmount, bool& bExit, string& sNameOfChosenCar, double& dCostOfChosenCar, vector<Finance>& buyers)\n{\n //...\n</code></pre>\n\n<p><strong>Personally, main should be the first function after the prototype list and every other function should appear after it in logical order as they are first called.</strong></p>\n\n<pre><code>int main()\n{\n</code></pre>\n\n<p><strong>Don't declare all your variables at the top of the function. Declare them closest to first use as possible.</strong></p>\n\n<p><strong>Systems Hungarian notation is outdated.</strong></p>\n\n<pre><code> bool bExit = false;\n int iFinanceLength = 0;\n double dDepositAmount = 0;\n string sNameOfChosenCar = \"\";\n double dCostOfChosenCar = 0;\n</code></pre>\n\n<p><strong>Modern compilers are smart. It's better to return the <code>car_list</code> than fill it via a pass-by-reference.</strong></p>\n\n<pre><code> vector<cCar>car_list;\n CarDatabase(car_list);\n</code></pre>\n\n<p><strong><code>car_purchases</code> isn't used at all. Remove it.</strong></p>\n\n<pre><code> vector<cCar>car_purchases;\n</code></pre>\n\n<p><strong><code>buyers</code> is only ever used internally. Consider moving it closer to its intended scope or, for such a small program, making it a <code>static</code> global.</strong></p>\n\n<pre><code> vector<Finance>buyers;\n //...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T15:14:51.923",
"Id": "455902",
"Score": "1",
"body": "You might be able to shorten the answer by not including the entire function in each of the unnecessary comment items. The reason why the comments are unnecessary is almost hidden because of the length of the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T17:58:06.423",
"Id": "455931",
"Score": "1",
"body": "@pacmaninbw Point taken. I removed all but the surrounding lines for context and clarified \"Systems Hungarian\" rather than \"all Hungarian\". (Apps Hungarian is useful for GUI variable names, after all...)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T18:13:47.613",
"Id": "455935",
"Score": "0",
"body": "Many thanks for reviewing my program, I will definitely improve on the points you’ve mentioned. I’m having to use Hungarian notation as my teacher requires it apparently. Almost comical, I asked someone to review my program and someone answers, then the answer is reviewed and feedback is given on the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T14:42:47.850",
"Id": "456039",
"Score": "0",
"body": "@GeorgeBradley I don't know if you can anymore because the question was put on hold; but it's customary to mark an answer as accepted. :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T02:42:17.647",
"Id": "233248",
"ParentId": "233244",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "233248",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-01T23:46:38.363",
"Id": "233244",
"Score": "-3",
"Tags": [
"c++"
],
"Title": "Has my program made good use of c++ features and is there anything in my program I've done which I should avoid?"
}
|
233244
|
<h1>Context</h1>
<p>I'm looking into design patterns. My first try is using the Decorator Pattern.</p>
<h1>Question:</h1>
<p>Is there another (maybe standard) approach to applying modifications in a decorator other than explicitly overwriting in the constructor?
- </p>
<h1>Car Interface</h1>
<pre><code><?php
interface CarInterface
{
public function drive();
}
</code></pre>
<h1>Care Base Class</h1>
<pre><code><?php
class CarBaseClass implements CarInterface
{
public $model = 'Base Model';
public $top_speed = null;
public $features = ['AC', 'Radio'];
public function __construct($top_speed)
{
$this->top_speed = $top_speed;
}
public function drive(): void
{
echo $this->model . " speed: " . $this->top_speed;
}
}
</code></pre>
<h1>Tesla</h1>
<pre><code><?php
class Tesla extends CarBaseClass
{
public $model = 'Tesla';
}
</code></pre>
<h1>Engine Feature Decorator</h1>
<pre><code><?php
class V20Engine extends CarBaseClass
{
public $SPEED_BOOST = 1.5;
public $new_features = ['V20 Engine'];
public function __construct(CarBaseClass $car)
{
$this->model = 'V20 ' . $car->model;
$this->top_speed = $car->top_speed * $this->SPEED_BOOST;;
$this->features = array_merge($car->features, $this->new_features);
}
}
</code></pre>
<h1>Turbo Decorator</h1>
<pre><code><?php
class TurboEnabled extends CarBaseClass
{
public $TURBO_BOOST = 1.75;
public $new_features = ['Turbo Enabled', 'Snoop Dog GPS'];
public function __construct(CarBaseClass $car)
{
$this->model = 'Turbo Enabled ' . $car->model;
$this->top_speed = $car->top_speed;
$this->features = array_merge($car->features, $this->new_features);
}
public function activateTurbo() {
$this->top_speed = $this->top_speed * $this->TURBO_BOOST;
return $this;
}
}
</code></pre>
<h1>index.php</h1>
<pre><code><?php
require 'classes/Car/CarInterface.php';
require 'classes/Car/CarBaseClass.php';
require 'classes/Car/Tesla.php';
require 'classes/Car/Feature/TurboEnabled.php';
require 'classes/Car/Feature/V20Engine.php';
echo "<pre>";
$tesla = new Tesla(100);
$tesla->drive();
echo "<br>";
$turbo_tesla = new TurboEnabled($tesla);
$turbo_tesla->activateTurbo()->drive();
echo "<br>";
$v20_tesla = new V20Engine($tesla);
$v20_tesla->drive();
echo "<br>";
$v20_turbo_tesla = new V20Engine($turbo_tesla);
$v20_turbo_tesla->drive();
echo "<br>";
$car = new V20Engine( new TurboEnabled( new CarBaseClass(100) ) );
print_r( $car->features );
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-12-26T17:21:41.763",
"Id": "500790",
"Score": "0",
"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 [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<p>Decorators usually add more functional behaviors so if you had a method drive and TurboClass has a new functionality driveFast, you could probably call the Cars driveFast and then the some other special logic which turboClass has to do eg. checkTyres after driving fast. Here since you want the object construction to do it, this is the right way. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T07:43:52.220",
"Id": "233261",
"ParentId": "233247",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T02:09:39.477",
"Id": "233247",
"Score": "3",
"Tags": [
"php",
"design-patterns"
],
"Title": "Implementing Decorator Pattern"
}
|
233247
|
<p>I've decided to write a very simply output programming language. All the user does is write ASCII values inside ASCII fish, and the interpreter pieces the values together and outputs them.</p>
<p>I'm mainly looking for feedback on the interpreter, as the language itself is very easy to understand.</p>
<p>Here's what a <code>Hello, World!</code> program looks like in <code>Fishy</code>:</p>
<pre><code>><72> ><101> ><108> ><108> ><111> ><44> ><32> ><87> ><111> ><114> ><108> ><100> ><33>
</code></pre>
<p>All the rules of the language are listed in the module docstring of the program.</p>
<pre><code>"""
Fishy (.fishy extension)
><> Frontfish
Implementation is simple:
You enter ASCII values between the facing signs <>
Commands on separate lines will have output separated by a new line
Example:
><98> ><112> ><113> ><107>
bpqk
><97>
><108>
><101>
a
l
e
NO TRAILING WHITESPACE!
Trailing whitespace after the last fish on the line will result in a syntax error
"""
import argparse
import os
import sys
from typing import List
def run_code(code: List[str]):
"""
Runs the passed Fishy Code
"""
for line in code:
# Clean up code and separate commands#
line = line.strip("\n")
commands = line.split(" ")
# Check if line has multiple statements in it
if len(commands) > 1:
if correct_syntax(commands):
output = "".join(chr(get_number(fish)) for fish in commands)
print(output)
else:
if correct_syntax(commands):
print(chr(get_number(commands[0])))
def correct_syntax(pond: List[str]) -> bool:
"""
Checks the syntax of the passed list of commands on the following criteria:
Is a fish ><..>
Correct Example:
><98> ><108> ><56>
Incorrect Example:
><98> >><<76>> ><[108>
"""
for fish in pond:
if not is_fish(fish):
sys.exit(f"Incorrect Syntax: {fish}")
return True
def is_fish(fish: str) -> bool:
"""
Returns if the passed fish is the fish or not
Fish: Starts with >< ends with >
A fish like so ><98g> will be caught by "get_number()" function
"""
return fish.startswith("><") and fish.endswith(">")
def get_number(fish: str) -> int:
"""
Returns the number in the fish
"""
# Check font fish first #
try:
number = int(fish[2:-1])
except ValueError:
sys.exit(f"Incorrect Syntax: {fish}")
return number
def get_content(file: str) -> List[str]:
"""
Returns all the content in the passed file path
:param file -> str: File to read content
:return List[str]: Content in file
"""
with open(file, "r") as file:
return [line for line in file]
def main() -> None:
"""
Sets up argparser and runs main program
"""
parser = argparse.ArgumentParser(description="Enter path to .fishy program file")
parser.add_argument("Path", metavar="path", type=str, help="path to .fishy program file")
args = parser.parse_args()
file_path = args.Path
if not os.path.isfile(file_path):
sys.exit("The file does not exist")
content = get_content(file_path)
run_code(content)
if __name__ == "__main__":
main()
</code></pre>
|
[] |
[
{
"body": "<p>Here is a potential solution which was minimized from a finite automata. To make this solution more maintainable, a parse tree could have been created (or an explicit finite automata) so that the syntax can be modified in the future.</p>\n\n<p>Note: this answer is a bit academic in that its practical use is limited, however, provides a starting point to convert this program into a parse tree.</p>\n\n<p>It doesn't have the file reading capabilities or the <code>argparse</code> abilities, but it has the core of the solution (checks if the program is valid and if so, run it.)</p>\n\n<pre><code>import re\n\ninput_program = \"><72> ><101> ><108> ><108> ><111> ><44> ><32> ><87> ><111> ><114> ><108> ><100> ><33>\"\n\nregex = r\"(?:^\\>\\<((1|2|3|4|5|6|7|8|9|10|1{2}|12|13|14|15|16|17|18|19|20|21|2{2}|23|24|25|26|27|28|29|30|31|32|3{2}|34|35|36|37|38|39|40|41|42|43|4{2}|45|46|47|48|49|50|51|52|53|54|5{2}|56|57|58|59|60|61|62|63|64|65|6{2}|67|68|69|70|71|72|73|74|75|76|7{2}|78|79|80|81|82|83|84|85|86|87|8{2}|89|90|91|92|93|94|95|96|97|98|9{2}|10{2}|101|102|103|104|105|106|107|108|109|1{2}0|1{3}|1{2}2|1{2}3|1{2}4|1{2}5|1{2}6|1{2}7|1{2}8|1{2}9|120|121|12{2}|123|124|125|126|127))\\> )+(?:\\>\\<(1|2|3|4|5|6|7|8|9|10|1{2}|12|13|14|15|16|17|18|19|20|21|2{2}|23|24|25|26|27|28|29|30|31|32|3{2}|34|35|36|37|38|39|40|41|42|43|4{2}|45|46|47|48|49|50|51|52|53|54|5{2}|56|57|58|59|60|61|62|63|64|65|6{2}|67|68|69|70|71|72|73|74|75|76|7{2}|78|79|80|81|82|83|84|85|86|87|8{2}|89|90|91|92|93|94|95|96|97|98|9{2}|10{2}|101|102|103|104|105|106|107|108|109|1{2}0|1{3}|1{2}2|1{2}3|1{2}4|1{2}5|1{2}6|1{2}7|1{2}8|1{2}9|120|121|12{2}|123|124|125|126|127)\\>)$\"\n\npattern = re.compile(regex)\n\ndef extract_ascii_codes(input_text):\n \"\"\"\n Converts the ASCII codes into text\n \"\"\"\n matches = re.finditer(r\"\\d+\", input_text)\n for matchNum, match in enumerate(matches, start=1):\n yield int(match.group())\n\ndef parse_line(input_program):\n \"\"\"\n Checks if the line in the program is syntatically valid; returns if it is\n \"\"\"\n if pattern.match(input_program) is not None:\n return (''.join(map(chr, extract_ascii_codes(input_program))))\n\nparsed_program = list(map(parse_line, input_program.split(\"\\n\")))\n\nif all(parsed_program):\n for a_line in parsed_program:\n print(a_line)\nelse:\n print(\"Syntax error\")\n</code></pre>\n\n<p>Finite automata (condensed):</p>\n\n<p><a href=\"https://i.stack.imgur.com/K6JIp.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/K6JIp.png\" alt=\"enter image description here\"></a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T13:20:03.623",
"Id": "455879",
"Score": "0",
"body": "Why `1{2}` instead of `11` in the regex?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T14:06:23.807",
"Id": "455894",
"Score": "0",
"body": "I guess if its automatically generated the regex is simplified anywhere the generator finds repitition"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T05:57:12.453",
"Id": "233256",
"ParentId": "233250",
"Score": "5"
}
},
{
"body": "<h3>Restructuring and optimization</h3>\n\n<p>The initial approach introduces inefficient file processing as <code>get_content</code> function reads <strong>all</strong> lines from the input file into a list at once and holds that list in memory throughout the entire processing. The traversal of the lines that were read is then redundantly repeated in <code>run_code</code> function.<br>The more efficient way is to convert <code>get_content</code> into a <em>generator</em> function and consume one line from file at a time on demand.</p>\n\n<p>The optimized <strong><code>get_content</code></strong> function:</p>\n\n<pre><code>def get_content(file: str) -> List[str]:\n \"\"\"\n Yields lines from the passed file path\n :param file -> str: File to read content\n :return List[str]: Content in file\n \"\"\"\n with open(file, \"r\") as file:\n for line in file:\n yield line.rstrip()\n</code></pre>\n\n<hr>\n\n<p><code>run_code</code> function is renamed to <strong><code>parse_code</code></strong></p>\n\n<hr>\n\n<p><em>Inefficiency of validating and traversing <code>commands</code></em></p>\n\n<p>In <code>parse_code</code> (formerly <code>run_code</code>) function the <strong><code>commands</code></strong> sequence is potentially being traversed <strong>twice</strong>:\nonce on <code>correct_syntax(commands)</code> call and then - on getting numbers <code>chr(get_number(fish)) for fish in commands</code>.<br>Moreover, consequent validations in this case may lead to redundant calculations.<br>Consider the following situation: <code>commands</code> contains 10 items, all of them passed <code>correct_syntax</code> check but then, the 9th item fails on <code>get_number</code> check. That causes 10 redundant operations/checks.</p>\n\n<p>To optimize validations we notice that <code>is_fish</code> and <code>get_number</code> are conceptually dependent on the same context - <em>\"<strong>fish</strong>\"</em> and are intended to validate the same <em>\"fish\"</em> object.<br>Thus, those 2 validations are reasonably combined/consolidated into one validation function <strong><code>is_fish</code></strong>:</p>\n\n<pre><code>def is_fish(fish: str) -> bool:\n \"\"\"\n Validates \"fish\" item\n Fish: Starts with >< ends with > and has number inside\n A fish like so ><98g> will fail the check\n\n \"\"\"\n return fish.startswith(\"><\") and fish.endswith(\">\") and fish[2:-1].isdigit()\n</code></pre>\n\n<p><code>get_number</code> function is now removed. <br>The <code>correct_syntax</code> function is renamed to <strong><code>get_fish_numbers</code></strong> and its responsibility now is <em>\"Collect fish numbers from <strong>valid</strong> fishes\"</em>:</p>\n\n<pre><code>def get_fish_numbers(pond: List[str]) -> bool:\n \"\"\"\n Collects fish numbers with checking the syntax of the passed list of commands on the following criteria:\n\n Is a fish ><..>\n\n Correct Example:\n ><98> ><108> ><56>\n\n Incorrect Example:\n ><98> >><<76>> ><[108>\n\n \"\"\"\n fish_numbers = []\n for fish in pond:\n if not is_fish(fish):\n sys.exit(f\"Incorrect Syntax: {fish}\")\n fish_numbers.append(int(fish[2:-1]))\n\n return fish_numbers\n</code></pre>\n\n<hr>\n\n<p>And finally the optimized <strong><code>parse_code</code></strong> function:</p>\n\n<pre><code>def parse_code(code: List[str]):\n \"\"\"\n Parse and output the passed Fishy Code\n \"\"\"\n for line in code:\n # Clean up code and separate commands#\n commands = line.split(\" \")\n\n # Check if line has multiple statements in it\n fish_numbers = get_fish_numbers(commands)\n if len(fish_numbers) > 1:\n output = \"\".join(chr(num) for num in fish_numbers)\n print(output)\n else:\n print(chr(fish_numbers[0]))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T09:49:12.670",
"Id": "233264",
"ParentId": "233250",
"Score": "11"
}
}
] |
{
"AcceptedAnswerId": "233264",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T03:46:53.437",
"Id": "233250",
"Score": "13",
"Tags": [
"python",
"python-3.x",
"language-design"
],
"Title": "Fishy: An ASCII Programming Language"
}
|
233250
|
<p><a href="https://github.com/dmitrynogin/dynoproxy" rel="noreferrer">GitHub</a> and <a href="https://www.nuget.org/packages/Dynoproxy" rel="noreferrer">NuGet</a></p>
<p>Allows to invoke public/private REST API just by defining an interface. 200 lines of C# in total.</p>
<h3>Demo</h3>
<p>Sample API is publicly available at <a href="http://jsonplaceholder.typicode.com" rel="noreferrer">http://jsonplaceholder.typicode.com</a>:</p>
<pre><code>public interface ITypicode : IDisposable
{
[Description("GET posts")]
Task<BlogPost[]> GetAsync();
[Description("GET posts/{0}")]
Task<BlogPost> GetAsync(int id);
[Description("PUT posts/{0} {1}")]
Task<BlogPost> PutAsync(int id, BlogPost data);
}
public class BlogPost
{
public int UserId { get; set; }
public int Id { get; set; }
public string Title { get; set; }
public string Body { get; set; }
}
</code></pre>
<p>Now we could test proxy generator:</p>
<pre><code>[TestMethod]
public async Task Call_REST_API()
{
using (var proxy = Proxy.Create<ITypicode>("http://jsonplaceholder.typicode.com"))
{
var posts = await proxy.GetAsync();
Assert.AreEqual(100, posts.Length);
var post = await proxy.GetAsync(1);
Assert.AreEqual(1, post.Id);
post.Title = "XYZ";
post = await proxy.PutAsync(1, post);
Assert.AreEqual("XYZ", post.Title);
}
}
</code></pre>
<p>Optional <code>authenticate</code> parameter supports custom authentication schemas using ad-hoc <code>HttpClient</code> extension method to setup <code>HttpClient.DefaultRequestHeaders</code> in a way like this:</p>
<pre><code>Proxy.Create<ITypicode>(url, (HttpClient client) => client.AuthenticateAsync(...))
</code></pre>
<h3>Library</h3>
<p>Library code contains a unified proxy generator based on Castle.Core:</p>
<pre><code>public static class Proxy
{
public static T Create<T>(object target) where T : class =>
Create<T>(call => Dynamic.InvokeMember(
target, call.Name, call.Args.ToArray()));
public static T Create<T>(string apiUrl, Func<HttpClient, Task> authenticate = null) where T : class, IDisposable =>
Create<T>(new Uri(apiUrl, UriKind.Absolute), authenticate);
public static T Create<T>(Uri apiUrl, Func<HttpClient, Task> authenticate = null) where T : class, IDisposable =>
RestProxy.Create<T>(apiUrl, authenticate);
public static T Create<T>(Func<ProxyCall, object> target) where T : class
{
var proxyGenerator = new ProxyGenerator();
return proxyGenerator.CreateInterfaceProxyWithoutTarget<T>(
ProxyGenerationOptions.Default,
new Interceptor(target));
}
class Interceptor : IInterceptor
{
public Interceptor(Func<ProxyCall, object> target) => Target = target;
Func<ProxyCall, object> Target { get; }
public void Intercept(IInvocation invocation) =>
invocation.ReturnValue = Target(
new ProxyCall(invocation.Method.Name, invocation.Arguments)
.Returns(invocation.Method.ReturnType)
.Define(invocation.Method.GetCustomAttributes()));
}
}
</code></pre>
<p>Where helpers are:</p>
<pre><code>public class ProxyCall
{
public ProxyCall(string name, IEnumerable<object> args)
: this(name, args.ToArray())
{
}
public ProxyCall(string name, params object[] args)
{
Name = name;
Args = args;
}
public string Name { get; }
public IReadOnlyList<object> Args { get; }
public CallResult Result { get; private set; } = CallResult.None;
public ProxyCall Returns<T>() => Returns(typeof(T));
public ProxyCall ReturnsAsync<T>() => Returns(typeof(Task<T>));
public ProxyCall Returns(Type type) => With(result: new CallResult(type));
public CallMethod Method { get; private set; } = CallMethod.Undefined;
public ProxyCall Define(string description) =>
Define(new DescriptionAttribute(description));
public ProxyCall Define<TAttribute>() where TAttribute : Attribute, new() =>
Define(new TAttribute());
public ProxyCall Define(IEnumerable<Attribute> attributes) =>
Define(attributes.ToArray());
public ProxyCall Define(params Attribute[] attributes) =>
With(method: new CallMethod(attributes.Concat(Method)));
ProxyCall With(CallResult result = null, CallMethod method = null) =>
new ProxyCall(Name, Args)
{
Result = result ?? Result,
Method = method ?? Method
};
public bool IsDispose =>
Name == nameof(IDisposable.Dispose) &&
Result.Void &&
!Args.Any();
}
</code></pre>
<p>And:</p>
<pre><code>public class CallResult
{
public static readonly CallResult None = new CallResult(typeof(void));
internal CallResult(Type raw) => Raw = raw;
public Type Raw { get; }
public bool Sync => !Async;
public bool Async => typeof(Task).IsAssignableFrom(Raw);
public bool Void => Raw == typeof(void) || Raw == typeof(Task);
public Type Type => Async
? (Void ? typeof(void) : Raw.GetGenericArguments()[0])
: Raw;
}
</code></pre>
<p>And:</p>
<pre><code>public class CallMethod : ReadOnlyCollection<Attribute>
{
public static readonly CallMethod Undefined = new CallMethod();
internal CallMethod(IEnumerable<Attribute> attributes)
: this(attributes.ToArray())
{
}
internal CallMethod(params Attribute[] attributes)
: base(attributes)
{
}
public bool Contains<TAttribute>() where TAttribute : Attribute =>
Select<TAttribute>().Any();
public T Peek<TAttribute, T>(Func<TAttribute, T> selector) where TAttribute : Attribute =>
Select(selector).FirstOrDefault();
public IEnumerable<Attribute> Select<TAttribute>() where TAttribute : Attribute =>
Select((TAttribute a) => a);
public IEnumerable<T> Select<TAttribute, T>(Func<TAttribute, T> selector) where TAttribute : Attribute =>
Items.OfType<TAttribute>().Select(selector);
public string Description => Peek((DescriptionAttribute a) => a.Description);
}
</code></pre>
<p>The following class provides all necessary support for REST API calls:</p>
<pre><code>static class RestProxy
{
public static T Create<T>(Uri apiUrl, Func<HttpClient, Task> authenticate = null)
where T : class, IDisposable
{
var client = new HttpClient() { BaseAddress = apiUrl };
return Proxy.Create<T>(Execute);
object Execute(ProxyCall call)
{
if(call.IsDispose)
{
client.Dispose();
return null;
}
return call.Result.Void ? Send() : SendAndReceive();
object Send() => client.SendAsync(call, authenticate);
object SendAndReceive() =>
typeof(RestProxy)
.GetMethod(nameof(SendAndReceiveAsync), BindingFlags.Static | BindingFlags.NonPublic)
.MakeGenericMethod(call.Result.Type)
.Invoke(null, new object[] { client, call, authenticate });
}
}
static async Task<T> SendAndReceiveAsync<T>(
HttpClient client, ProxyCall call, Func<HttpClient, Task> authenticate)
{
var response = await client.SendAsync(call, authenticate);
var json = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(json);
}
static async Task<HttpResponseMessage> SendAsync(
this HttpClient client, ProxyCall call, Func<HttpClient, Task> authenticate = null)
{
var description = call.Method.Description
.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
var request = new HttpRequestMessage(
new HttpMethod(description[0]),
new Uri(
string.Format(description[1], call.Args.ToArray()),
UriKind.Relative))
{
Content = description.Length < 3 ||
!int.TryParse(description[2].Trim("{}".ToCharArray()), out var index)
? null
: new StringContent(
JsonConvert.SerializeObject(call.Args[index]),
Encoding.UTF8,
"application/json")
};
var response = await client.SendAsync(request);
if (response.StatusCode == HttpStatusCode.Unauthorized)
if(authenticate == null)
throw new AuthenticationException();
else
{
await authenticate(client);
return await SendAsync(client, call);
}
response.EnsureSuccessStatusCode();
return response;
}
}
</code></pre>
<p><em>P.S. Let me know please if something is missing here which could prevent it from being really useful :)</em></p>
|
[] |
[
{
"body": "<p>You require the interface to be <code>IDisposable</code> which is a bit of a shame. You're only doing this so that you can dispose of the HttpClient, but as it says in the Microsoft docs:</p>\n\n<p><a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.8\" rel=\"noreferrer\">HttpClient is intended to be instantiated once and re-used throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads.</a></p>\n\n<p>Unfortunately it's a difficult class to use correctly so I recomend swapping it out for something that's already got many of the common mistakes taken care of, like the <a href=\"https://github.com/NimaAra/Easy.Common/blob/master/Easy.Common/RestClient.cs\" rel=\"noreferrer\">Easy.Common RestClient</a>. This will make sure the clients are cached and as a bonus will not require the interface to be <code>IDisposable</code>.</p>\n\n<p>It will bring a dependency but since you're already depending on some dependency injection package this may not be an issue.</p>\n\n<hr>\n\n<p>In the <code>RestProxy</code> you have many <code>await</code>s but you do not <code>ConfigureAwait(false)</code>. You should really use that in library code unless you're only targeting .NET Core, it will perform slightly better and may prevent deadlocks for callers who use the async methods incorrectly.</p>\n\n<p>When you send messages and recieve responses you turn the objects into strings but throw the strings away, this is wasteful and creates work for the Garbage Collector. Netwonsoft supports serializing and deserialzing to and from streams. You should stream the data out in. Follow <a href=\"https://johnthiriet.com/efficient-api-calls/\" rel=\"noreferrer\">this guide</a> or ask if you are unsure how.</p>\n\n<p>You do not dispose of your <code>HttpRequestMessages</code> and <code>HttpResponseMessages</code> or your <code>StringContent</code>s. <code>StringContent</code> would be disposed of by the <code>HttpRequestMessages</code> but you should really be disposing of every <code>IDisposable</code> you create (except the <code>HttpClient</code>, as mentioned above!).</p>\n\n<p>You do not support cancellation tokens it looks like. You should consider the case when an interface looks like:</p>\n\n<pre><code>public interface ITypicode : IDisposable\n{\n [Description(\"GET posts\")]\n Task<BlogPost[]> GetAsync(CancellationToken cancellationToken);\n\n [Description(\"GET posts/{0}\")]\n Task<BlogPost> GetAsync(int id, CancellationToken cancellationToken);\n\n [Description(\"PUT posts/{0} {1}\")]\n Task<BlogPost> PutAsync(int id, BlogPost data, CancellationToken cancellationToken);\n}\n</code></pre>\n\n<p>as most async interfaces <em>should</em> look (It's a common use case to want to cancel an async request after you've already sent it).</p>\n\n<p>That's all the improvements I can think of so far, but I don't want you think I'm being negative - it's actually a really nice package and a great idea well executed, very impressive.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T17:44:59.503",
"Id": "456077",
"Score": "2",
"body": "Thanks for this great answer - I hope to see more from you in future!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T17:35:30.390",
"Id": "233352",
"ParentId": "233251",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "233352",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T04:25:50.173",
"Id": "233251",
"Score": "5",
"Tags": [
"c#",
"rest",
"proxy"
],
"Title": "Testable REST API Client"
}
|
233251
|
<pre><code>def start():
import time
ans = input("Do you wish to start again? [y/n]\n")
if ans == 'y' or ans == "yes" or ans == "":
print(' \n' * 30)
main()
elif ans == 'n' or ans == "no":
exit()
else:
print("Invalid Input\n")
time.sleep(3)
start()
def main():
import math
import time
print("Calculator:\n")
aa = float(input("First number- "))
ans = float(
input(" do you want to:\n Add (1)\n Subtract (2)\n Multiply (3)\n Devide (4)\n Calculate an Exponent (5)\n "
"Calculate Circumference(6)\n Calculate the Area of a Circle(7)\n Square Root(8)\n"))
if ans == 6:
print("If given diameter, Circumference is " + (aa * math.pi))
start()
if ans == 7:
print("If given radius, Area is ")
print(aa ** 2 * math.pi)
if ans == 8:
print("the square root of", + aa, "is", + (aa ** (1.0 / 2)))
time.sleep(3)
start()
bb = float(input("Second Number- "))
if ans == 1:
print(aa + bb)
elif ans == 2:
print(aa - bb)
elif ans == 3:
print(aa * bb)
elif ans == 4:
print(aa / bb)
elif ans == 5:
print(aa ** bb)
else:
print("Invalid input")
time.sleep(2.5)
print(' \n' * 30)
start()
main()
</code></pre>
<p>I was curious if my calculator is good or needs more functions, how I would do that, etc. I really want to make it able to keep the output and assign it to a variable that I can call to add, subtract, multiply, etc. I'm new to python, or coding for that matter, but I just want to make a great calculator that has easy to use and useful functions. So I just want to know, what should I add or change?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T09:15:35.733",
"Id": "455854",
"Score": "3",
"body": "This community is called Code Review - you seem to be asking for a *product specification* review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T13:46:28.237",
"Id": "455889",
"Score": "0",
"body": "What kind of calculator is it? The use of `math.pi` isn't something I would expect in a normal calculator."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T15:50:42.707",
"Id": "455907",
"Score": "0",
"body": "Hello Jaxon, as greybeard stated, we can review your actual code with the functions it has right now, but we can't really help you figure out which functions to add, this is up to you to figure it out :)\n\nIf you'd like for the code you have right now to be reviewed, you should edit your post to make it clear, otherwise your post will get closed for being off-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T01:39:05.223",
"Id": "455970",
"Score": "0",
"body": "It's easy to add new features to a well-written program. I'd suggest the next function to be added to this is #9: take a number and add it to the previous result."
}
] |
[
{
"body": "<p>\"<em>What you should add</em>\" is an off-topic question for <strong>Code Review</strong>. Here, we only review complete, working code. You will get feedback on areas of your program that need work, where code could be designed better, perform better, handle input or errors more gracefully. \"<em>What you should add</em>\" is an open-ended question that you (or your program's users) should answer.</p>\n\n<hr>\n\n<h2>Imports</h2>\n\n<p>Imports should be listed at the top of the file, preceded only by a <code>\"\"\"docstring\"\"\"</code> if one is present.</p>\n\n<p>Importing inside of functions</p>\n\n<pre><code>def start():\n import time\n ...\n</code></pre>\n\n<p>leads to needed to import the same modules over and over again, and provides little benefit. It is only useful in cases of optional functionality, where an module may not be installed and failing to importing it would not prevent the rest of the program from running. This is not the case here. Move all your imports out of method to the top of the file:</p>\n\n<pre><code>import time\nimport math\n\ndef start():\n ...\n</code></pre>\n\n<h2>Infinite Recursion</h2>\n\n<p>If you eventually add the capability of storing values in variables, so you could do more complex calculations, involving long chains of operations, would you want your calculator to <em><strong>CRASH</strong></em> after 500 computations?</p>\n\n<p>Python's stack is not unlimited.</p>\n\n<pre><code>>>> import sys\n>>> sys.getrecursionlimit()\n1000\n</code></pre>\n\n<p>With a limit of 1000 calls, your implementation of <code>main()</code> calling <code>start()</code>, which calls <code>main()</code>, which calls <code>start()</code>, which calls <code>main()</code>, which calls <code>start()</code>, which calls ... will crash after 500 calls of <code>main()</code> and 500 calls of <code>start()</code>. And any values stored in variables would probably be lost.</p>\n\n<p>Don't use infinite recursion where a simple <code>while ...:</code> loop would do.</p>\n\n<h2>Exit</h2>\n\n<p>Don't use <code>exit()</code>. This unconditionally terminates the Python interpreter. Unit tests written in Python will not be able to examine results and report success or failure if the code it is testing calls <code>exit()</code>. A caller which expects to continue executing after using the calculator cannot recover from <code>exit()</code>. Never, ever use it.</p>\n\n<h2>Garbage Output</h2>\n\n<pre><code>print(' \\n' * 30)\n</code></pre>\n\n<p>Why is there a space before the newline? Did you mean to print out \"space\" \"newline\" \"space\" \"newline\" \"space\" \"newline\" ... \"space\" \"newline\" \"space\" \"newline\"? How is that different from just printing out 30 newlines?</p>\n\n<h2>Error Recovery</h2>\n\n<p>If the user enters an invalid value at the <code>\"First number- \"</code> prompt, such as <code>1.000.000</code>, the program will crash with a <code>ValueError</code>. You should use <code>try: ... catch ...: ...</code> blocks to catch illegal input problems, and recover.</p>\n\n<p>Similarly, you should be prepared for errors in calculation, such as division by zero, or square-roots of negative numbers.</p>\n\n<h2>Printing</h2>\n\n<pre><code> print(\"If given diameter, Circumference is \" + (aa * math.pi))\n\n print(\"If given radius, Area is \")\n print(aa ** 2 * math.pi)\n\n print(\"the square root of\", + aa, \"is\", + (aa ** (1.0 / 2)))\n</code></pre>\n\n<p>In the first case, you are joining a string and the results of a calculation. In the second, you are using 2 print statements. In the third, you're using separate arguments to the print statement to print multiple values. Pick one style, and be consistent.</p>\n\n<p>Additionally, the leading <code>+</code> signs are not needed in the expression arguments <code>+ aa</code> or <code>+ (aa ** (1.0 / 2))</code>. You are not concatenating the value with the previous string; it is a separate argument. Parenthesis are not required around the <code>(aa ** (1.0 / 2))</code> calculation. It is not necessary to write <code>(1.0 / 2)</code>; using <code>(1 / 2)</code> would work just fine, as would simply <code>0.5</code>.</p>\n\n<pre><code> print(\"If given diameter, Circumference is\", aa * math.pi)\n\n print(\"If given radius, Area is\", aa ** 2 * math.pi)\n\n print(\"the square root of\", aa, \"is\", aa ** 0.5)\n</code></pre>\n\n<h2>Bug</h2>\n\n<p>If you ask for \"area\", after printing the result, the program will then ask for the second number, and will then <code>print(\"Invalid input\")</code>.</p>\n\n<h2>Flotsam & Jetsam</h2>\n\n<ul>\n<li>After most calculations, you have a delay of 2.5 seconds. After square root, you have a delay of 3 seconds. After circumference, no delay at all. Intended differences? Accidental? Maybe you should have the delay in exactly one spot, so it is consistent.</li>\n<li><code>Devide</code> should be spelt <code>Divide</code></li>\n<li>When you ask for a function value, 1 through 8, you accept floating point values, instead of integers. It works, but is odd.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T05:19:52.333",
"Id": "233254",
"ParentId": "233252",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T04:28:28.423",
"Id": "233252",
"Score": "-2",
"Tags": [
"python",
"beginner",
"python-3.x",
"calculator"
],
"Title": "Python Calculator: What should I add?"
}
|
233252
|
<p>I wish to generate an online feedback system. Requirements are</p>
<ul>
<li>Admin can enter feedback questions</li>
<li>Admin will select these questions and create a feedback session</li>
<li>One Question can be used in many feedback session</li>
<li>User can select any feedback session and answer/rate </li>
<li>one user can answer same feedback session more than once</li>
</ul>
<p>My table structure is</p>
<p><a href="https://i.stack.imgur.com/GYU2a.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GYU2a.png" alt="enter image description here"></a></p>
<p>dummy data (not all columns)</p>
<pre><code>Questions
---------
QuestionId Question
1 Question 1
2 Question 2
3 Question 3
4 Question 4
5 Question 5
Feedback
--------
FeedbackId Questions
2 1,2,3,4,5 -- Questions column has questionid from Question table
FeedbackResults
---------------
FeedbackResId FeedbackId QuetionID Answers UserId
1 2 4 4 1
2 2 1 3 1
3 2 5 3 1
4 2 1 2 2
</code></pre>
<p>Please rate this design and provide valuable suggestions. Comma separated values are affordable ?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T06:47:07.207",
"Id": "456355",
"Score": "0",
"body": "can anyone please help"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-07T19:13:20.550",
"Id": "456697",
"Score": "0",
"body": "User = Customer? It would help to post the DDL of these tables to make it easier to propose improvements. My first impression is that this model doesn't enable one (same) feedback session to be answered by one user more than once."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-09T07:39:47.043",
"Id": "456810",
"Score": "0",
"body": "yes user is customer"
}
] |
[
{
"body": "<p>The design need to be simplified. From your explanation, it seems you only need 3 tables (Questions, Answers, and Feedback) the rest are not needed, since you can <code>JOIN</code> these tables. </p>\n\n<blockquote>\n <p>Comma separated values are affordable ?</p>\n</blockquote>\n\n<p>For your design, no you don't need to, and it's not always a good idea to do it. There is some cases you can do it, and might be benefit you, but these are rare cases. Keep things simple and standard, don't join columns or rows into a single value, unless it's a requirement! </p>\n\n<p>So, if your <code>Feedback.Questions</code> meant to store values of questions in comma separated value, I suggest you change that. just give each question a new feedback id, this way it'll be much more manageable. And instead of storing the question string, just store the questionId (FK) instead. this way it'll be more appropriate and would process faster. </p>\n\n<p>So I suggest you remodel it to : </p>\n\n<pre><code>#ListStatus\n- Id [PK|IDENTITY]\n- Description\n\n#ListRate \n- Id [PK|IDENTITY]\n- Description\n\n#FeedbackQuestions \n- Id [PK|IDENTITY]\n- Question \n- CreatedAt\n- UpdatedAt \n- Deleted\n- StatusId\n- UserId\n\n#FeedbackAnswers \n- Id [PK|IDENTITY]\n- QuestionId \n- Answer \n- CreatedAt \n- UpdatedAt \n- Deleted\n- UserId \n\n#Feedback \n- Id [PK|IDENTITY]\n- RateId\n- QuestionId\n- AnswerId \n- CreatedAt \n- Deleted\n- UserId \n</code></pre>\n\n<p>The <code>Listxxx</code> tables would store a list of fixed descriptive values. For instance, <code>ListRate</code> would store the rate options such as Excellent, Very Good, Good, Fair, Poor ..etc. When a user rates an answer, the Id of <code>ListRate</code> would be inserted into <code>Feedback</code> table.</p>\n\n<p>Also, since we defined them with a prefix <code>List</code> it would be standardized in the system design, for general use purpose on other tables, and best yet, easier to understand (so developers would know the purpose of these tables just from the table name). </p>\n\n<p>I got confused between <code>UserId</code> & <code>CustomerId</code>, but I used <code>userId</code> so you're working with <code>logged-in users</code> doesn't matter if is it from <code>Admin</code> or some customer using the system, at the end, you need to record the <code>Username</code> that made this changes . </p>\n\n<p>Another thing you might need is to add a category for the questions, and maybe the Feedback as well. This will be very helpful in filtering the results. You don't want to depend on any column that store user input with open text, it'll be a real pain in the neck. So, adding a category to the questions, which will store it's values in another table to have two columns (one for displaying text for user, the other one is the id) will make things easier to work with, and if you see that you can add more filtering options (either supporting sub-category or tags ..etc) go for it. </p>\n\n<p>Sample :</p>\n\n<p><strong>Questions Table</strong></p>\n\n<pre><code>| Id | Question | CreatedAt | UpdatedAt | Deleted | StatusId | UserId |\n|----|------------|----------------------|-----------|---------|----------|--------|\n| 1 | Question 1 | 2019-12-14T00:00:00Z | (null) | (null) | 1 | User 1 |\n| 2 | Question 2 | 2019-12-14T20:40:15Z | (null) | (null) | 2 | User 2 |\n| 3 | Question 3 | 2019-12-14T07:05:01Z | (null) | (null) | 3 | User 3 |\n</code></pre>\n\n<p><strong>Answers Table</strong></p>\n\n<pre><code>| Id | QuestionId | Answer | CreatedAt | UpdatedAt | Deleted | UserId |\n|----|------------|----------|----------------------|-----------|---------|---------|\n| 1 | 1 | Answer 1 | 2019-07-05T00:00:00Z | (null) | (null) | User 50 |\n| 2 | 1 | Answer 2 | 2019-07-05T00:00:00Z | (null) | (null) | User 50 |\n| 3 | 1 | Answer 3 | 2019-07-05T00:00:00Z | (null) | (null) | User 70 |\n| 4 | 2 | Answer 1 | 2019-07-05T00:00:00Z | (null) | (null) | User 70 |\n</code></pre>\n\n<p><strong>Feedback Table</strong></p>\n\n<pre><code>| Id | RateId | QuestionId | AnswerId | CreatedAt | UpdatedAt | Deleted | UserId |\n|----|--------|------------|----------|----------------------|-----------|---------|---------|\n| 1 | 1 | 1 | 3 | 2019-07-05T00:00:00Z | (null) | (null) | Admin |\n| 2 | 2 | 2 | 4 | 2019-07-05T00:00:00Z | (null) | (null) | User 23 |\n| 3 | 2 | 1 | 2 | 2019-07-05T00:00:00Z | (null) | (null) | User 5 |\n| 4 | 5 | 1 | 3 | 2019-07-05T00:00:00Z | (null) | (null) | User 23 |\n</code></pre>\n\n<h1><a href=\"http://sqlfiddle.com/#!18/ab421/1\" rel=\"nofollow noreferrer\">Fiddle Demo</a></h1>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-14T09:21:05.673",
"Id": "457612",
"Score": "0",
"body": "Thank you for your answer. But i am not still clear with your design. which table has feedback sessions (refer my point 2: Admin will select these questions and create a feedback session). There can be multiple feedback sessions from which a user/customer can select the feedback to answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-14T10:10:01.673",
"Id": "457613",
"Score": "0",
"body": "@SachuMine Feedback table(the last one) should stores the feedback sessions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-14T10:23:01.160",
"Id": "457614",
"Score": "0",
"body": "could you please put some sample data in tables. The id of Feedback table is unique? How we we know which feedbak session is answered?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-14T12:27:26.737",
"Id": "457639",
"Score": "0",
"body": "@SachuMine I have added a sample data and a live demo so you'll have a better view on the model."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-13T18:02:45.403",
"Id": "233997",
"ParentId": "233253",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T05:15:51.483",
"Id": "233253",
"Score": "2",
"Tags": [
"sql",
"sql-server",
"database"
],
"Title": "Database Model for Feedback Module"
}
|
233253
|
<p>So, I'm implementing LZ77 compression algorithm. To compress any file type, I use its binary representation and then read it as <code>chars</code> (because 1 <code>char</code> is equal to 1 byte, afaik) to a <code>std::string</code>. Current program version compresses and decompresses files (.txt, .bmp, etc) just fine – size of raw file in bytes matches the size of uncompressed file. Though I started to wonder, if usage of byte representation instead of bits is optimal at all:</p>
<blockquote>
<ol>
<li>Is it optimal to use <code>chars</code> (bytes) instead of single bits? No possible loss of bits?</li>
</ol>
</blockquote>
<p>Also, is there a way to compare file sizes in bits instead of bytes? (forgive me for stupid questions) </p>
<hr>
<p>And now for the actual <em>code</em> part. Here's the short info on how LZ77 handles compression:
<a href="https://i.stack.imgur.com/Ex4sb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Ex4sb.png" alt="Sliding window consists of 2 buffers"></a>
<a href="https://i.stack.imgur.com/HeMMJ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HeMMJ.png" alt="Example of compression"></a></p>
<p>Below are 2 main functions: <em>compress</em> and <em>findLongestMatch</em>:</p>
<ul>
<li><code>compress</code> moves char data between 2 buffers and saves encoded tuple <em>⟨offset, length, nextchar⟩</em></li>
<li><code>findLongestMatch</code> finds the longest match of lookheadBuffer in
historyBuffer</li>
</ul>
<blockquote>
<ol start="2">
<li>Is there a more elegant and effective way of searching for longest match? </li>
</ol>
</blockquote>
<p>(also in theory algo should search right to left, but is there any complexity difference? even if the <code>offset</code> is actually <em>longer</em>, it's still int and still 4 bytes – I convert every <code>int</code> into 4 <code>chars</code> (bytes) to save into output binary file)</p>
<hr>
<pre><code>LZ77::Triplet LZ77::slidingWindow::findLongestPrefix()
{
// Minimal tuple (if no match >1 is found)
Triplet n(0, 0, lookheadBuffer[0]);
size_t lookCurrLen = lookheadBuffer.length() - 1;
size_t histCurrLen = historyBuffer.length();
// Increasing the substring (match) length on every iteration
for (size_t i = 1; i <= std::min(lookCurrLen, histCurrLen); i++)
{
// Getting the substring
std::string s = lookheadBuffer.substr(0, i);
size_t pos = historyBuffer.find(s);
if (pos == std::string::npos)
break;
if ((historyBuffer.compare(histCurrLen - i, i, s) == 0) && (lookheadBuffer[0] == lookheadBuffer[i]))
pos = histCurrLen - i;
// If the longest match is found, check if there are any repeats
// following the of current longest substring in lookheadBuffer
int extra = 0;
if (histCurrLen == pos + i)
{
// Check for full following repeats
while ((lookCurrLen >= i + extra + i) && (lookheadBuffer.compare(i + extra, i, s) == 0))
extra += i;
// Check for partial following repeats
int extraextra = i - 1;
while (extraextra > 0)
{
if ((lookCurrLen >= i + extra + extraextra) && (lookheadBuffer.compare(i + extra, extraextra, s, 0, extraextra) == 0))
break;
extraextra--;
}
extra += extraextra;
}
// Compare the lengths of matches
if (n.length <= i + extra)
n = Triplet(histCurrLen - pos, i + extra, lookheadBuffer[i + extra]);
}
return n;
}
void LZ77::compress()
{
do
{
if ((window.lookheadBuffer.length() < window.lookBufferMax) && (byteDataString.length() != 0))
{
int len = window.lookBufferMax - window.lookheadBuffer.length();
window.lookheadBuffer.append(byteDataString, 0, len);
byteDataString.erase(0, len);
}
LZ77::Triplet tiplet = window.findLongestPrefix();
// Move the used part of lookheadBuffer to historyBuffer
window.historyBuffer.append(window.lookheadBuffer, 0, tiplet.length + 1);
window.lookheadBuffer.erase(0, tiplet.length + 1);
// If historyBuffer's size exceeds max, delete oldest part
if (window.historyBuffer.length() > window.histBufferMax)
window.historyBuffer.erase(0, window.historyBuffer.length() - window.histBufferMax);
encoded.push_back(tiplet);
} while (window.lookheadBuffer.length());
}
</code></pre>
<hr>
<p>Accessory functions:</p>
<pre><code>int intFromBytes(std::istream& is)
{
char bytes[4];
for (int i = 0; i < 4; ++i)
is.get(bytes[i]);
int integer;
std::memcpy(&integer, &bytes, 4);
return integer;
}
void intToBytes(std::ostream& os, int value)
{
char bytes[4];
std::memcpy(&bytes, &value, 4);
os.write(bytes, 4);
}
struct Triplet
{
int offset;
int length;
char next;
}
</code></pre>
|
[] |
[
{
"body": "<p>In answer to your first question, it may depend on whether you wish to optimise for speed or compression ratio. If optimising for speed, it would seem that using bytes is best, as that is what the <a href=\"https://github.com/lz4/lz4/blob/dev/doc/lz4_Block_format.md\" rel=\"nofollow noreferrer\">LZ4</a> algorithm does. LZ4 is a variant of LZ77, highly optimised for speed. If your optimisation is for the compression ratio, I am unsure which would be better, as I have never run a bitwise LZ77 compressor.</p>\n\n<p>In answer to your second question: How about, instead of your historyBuffer.find() method returning the first position of a match, you return an ArrayList of Triplets which match? This is because if you find a match, you know you will perform another iteration of the loop, (provided <code>i</code> is not at its maximum value which is unlikely). Next time you perform the iteration, instead of going through your entire sliding window looking for a match, simply check whether or not any of the phrases in your <code>ArrayList</code> of <code>Triplets</code> will still match when the string <code>s</code> has that additional character appended. This is because a match longer than the current match must build upon either that current match, or some other equally long match. This way, you don't redo work that has already been done. This approach means you can get rid of the lines</p>\n\n<pre><code>if ((historyBuffer.compare(histCurrLen - i, i, s) == 0) && (lookheadBuffer[0] == lookheadBuffer[i]))\n pos = histCurrLen - i;\n\n// If the longest match is found, check if there are any repeats\n// following the of current longest substring in lookheadBuffer\nint extra = 0;\nif (histCurrLen == pos + i)\n{\n // Check for full following repeats\n while ((lookCurrLen >= i + extra + i) && (lookheadBuffer.compare(i + extra, i, s) == 0))\n extra += i;\n\n // Check for partial following repeats\n int extraextra = i - 1;\n while (extraextra > 0)\n {\n if ((lookCurrLen >= i + extra + extraextra) && (lookheadBuffer.compare(i + extra, extraextra, s, 0, extraextra) == 0))\n break;\n extraextra--;\n }\n\n extra += extraextra;\n}\n</code></pre>\n\n<p>without losing any performance. </p>\n\n<p>With regards to your question about the complexity of searching left-to-right or vice versa, the time complexity of the two will be identical.</p>\n\n<p>One final note, however, is that incorporating my suggestion, where you look for multiple matches rather than one match, will influence which string searching algorithm would be optimal to implement in your <code>historyBuffer.find()</code> method. The <a href=\"https://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm\" rel=\"nofollow noreferrer\">Rabin-Karp substring matching algorithm</a>, is generally best for finding multiple matches. This algorithm uses hashing to discard parts of the <code>historyBuffer</code> which will definitely not match the substring, leaving you to easily check the parts of the <code>historyBuffer</code> which are likely to match. However, if you are simply finding one match, as your current implementation does, then the <a href=\"https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string-search_algorithm\" rel=\"nofollow noreferrer\">Boyer-Moore</a> algorithm is your best choice.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T13:37:58.440",
"Id": "455886",
"Score": "1",
"body": "Thank you for your thorough answer. \nI'm kinda new to compression algorithms, so I hope you don't mind a couple more questions:\n\n1. Is there a chance for data (bit) loss when reading blobs (bytes)?\n2. Any way to compare raw and uncompressed file bitwise?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T23:19:10.500",
"Id": "455967",
"Score": "1",
"body": "1. No chance to lose any bits of information when reading bytes as opposed to bits. Just make sure you don't perform signed arithmetic with unsigned variables."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T23:26:50.690",
"Id": "455968",
"Score": "2",
"body": "2. You could read the two files each into an array of bytes, and then use bitwise AND to compare the two arrays: `if(c_1[i] & c_2[i] == c_1[i])` -> then the two arrays are equal for byte i. `Else`, use bit masking to identify the bit of `(c_1[i] & c_2[i])` which is not equal to `c_1[i]`. This will show the bit position at which arrays c_1 and c_2 differ. Does this answer your question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T04:29:03.840",
"Id": "455976",
"Score": "0",
"body": "Yes, thank you very much!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T13:13:39.927",
"Id": "233270",
"ParentId": "233262",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T07:49:10.953",
"Id": "233262",
"Score": "7",
"Tags": [
"c++",
"compression"
],
"Title": "LZ77 compression (also longest string match)"
}
|
233262
|
<p>I have a struct of integers and I am trying to increase them based on rules. For example, rule_1 is the max limit that the first increase should reach. </p>
<p>I want to change the order of additions based on priorities map (a=1,b=2,c=3), increase first "a", then "b", then "c". If I change the priorities (a=3,b=2,c=1), the additions should be made first first for "c", then "b", then "c". </p>
<p>I would like code review comments in terms of correct use of language and any suggestions for a better approach on this problem.</p>
<pre><code>#include <iostream>
#include <string>
#include <map>
struct data {
int a;
int b;
int c;
};
struct rules {
int rule_1;
int rule_2;
int rule_3;
};
void set_priorities(const std::map<std::string, int>& priorities, data& d, int *&it_1, int *&it_2, int *&it_3) {
for (const auto& p : priorities) {
if (p.first == "a") {
if (p.second == 1) {
it_1 = &(d.a);
} else if (p.second == 2) {
it_2 = &(d.a);
} else {
it_3 = &(d.a);
}
}
if (p.first == "b") {
if (p.second == 1) {
it_1 = &(d.b);
} else if (p.second == 2) {
it_2 = &(d.b);
} else {
it_3 = &(d.b);
}
}
if (p.first == "c") {
if (p.second == 1) {
it_1 = &(d.c);
} else if (p.second == 2) {
it_2 = &(d.c);
} else {
it_3 = &(d.c);
}
}
}
return;
}
void compute_data(const std::map<std::string, int> &p, const rules r, data& d) {
int* it_1 = nullptr;
int* it_2 = nullptr;
int* it_3 = nullptr;
set_priorities(p, d, it_1, it_2, it_3);
do {
if (*it_1 == r.rule_1) {
if (*it_2 == r.rule_2) {
if (*it_3 == r.rule_3) {
return;
} else {
(*it_3)++;
std::cout << "> > > a: " << d.a << ", b: " << d.b << ", c: " << d.c << std::endl;
}
} else {
(*it_2)++;
std::cout << "> > a: " << d.a << ", b: " << d.b << ", c: " << d.c << std::endl;
}
} else {
(*it_1)++;
std::cout << "> a: " << d.a << ", b: " << d.b << ", c: " << d.c << std::endl;
}
} while (true);
return;
}
int main()
{
std::map<std::string, int> priorities;
priorities.insert(std::pair<std::string, int>("a", 1));
priorities.insert(std::pair<std::string, int>("b", 2));
priorities.insert(std::pair<std::string, int>("c", 3));
rules r{};
r.rule_1 = 2;
r.rule_2 = 4;
r.rule_3 = 6;
data d{};
std::cout << "a: " << d.a << ", b: " << d.b << ", c: " << d.c << std::endl;
int repetitions = 2;
do {
compute_data(priorities, r, d);
--repetitions;
} while (repetitions > 0);
std::cout << "a: " << d.a << ", b: " << d.b << ", c: " << d.c << std::endl;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T12:54:51.173",
"Id": "455876",
"Score": "0",
"body": "I'm still not entirely sure what the code does. Can you add an example to your explanation?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T13:31:17.720",
"Id": "455883",
"Score": "0",
"body": "@L.F. I want to increase a, b, c up to what rules structure defines, based on the priorities being set. For example, if priorities are a = 1, b = 2, c = 3, data.a will increase up to the number defined in r.rule_1. If priorites are a = 3, b = 2, c = 1, then data.a will increase up to the number defined in r.rule_3. Hope I explained better now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T10:06:37.173",
"Id": "456002",
"Score": "0",
"body": "Please edit the question to include the information. Thanks!"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T09:57:18.177",
"Id": "233265",
"Score": "3",
"Tags": [
"c++"
],
"Title": "Increase members based on priorities"
}
|
233265
|
<p>Inspired by <a href="https://codereview.stackexchange.com/questions/233250/fishy-an-ascii-programming-languageby">this</a> question.</p>
<p>Here's the code:</p>
<pre class="lang-py prettyprint-override"><code>class FishyError(Exception):
__module__ = Exception.__module__
def string_to_fishy(string: str) -> str:
"""
Converts a string to fishy code
Examples:
Hello World!
><72> ><101> ><108> ><108> ><111> ><32> ><87> ><111> ><114> ><108> ><100> ><33>
007 James bond
><48> ><48> ><55> ><32> ><74> ><97> ><109> ><101> ><115> ><32> ><98> ><111> ><110> ><100>
"""
l = []
for char in string:
l.append(f'><{ord(char)}>')
return ' '.join(l)
def fishy_to_string(fishy: str) -> str:
"""
Converts a fishy code to string
Examples:
><72> ><101> ><108> ><108> ><111> ><32> ><87> ><111> ><114> ><108> ><100> ><33>
Hello World!
><48> ><48> ><55> ><32> ><74> ><97> ><109> ><101> ><115> ><32> ><98> ><111> ><110> ><100>
007 James bond
"""
if not fishy:
return ''
fishy_chars = fishy.split(' ')
string = ''
for char in fishy_chars:
if not char:
raise FishyError('Invalid syntax: Extra whitespace')
if not (char.startswith('><') and char.endswith('>')):
raise FishyError('Invalid syntax: ' + char)
try:
value = int(char[2:-1])
string += chr(value)
except ValueError:
raise FishyError('Invalid syntax: ' + char)
return string
while True:
print(fishy_to_string(input()))
</code></pre>
<p>This works well, but doesn't look that great. Any ideas?</p>
|
[] |
[
{
"body": "<p>I'm not entirely sure why you are not satisfied with your code as it looks quite good. Maybe too many blank lines that seem to stretch the code length. There are also a few things on the Python side that could be changed to reduce the amount of source lines needed for the task:</p>\n\n<h1><code>string_to_fishy</code></h1>\n\n<p><code>string_to_fishy</code> can be rewritten using a list comprehension:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def string_to_fishy(string: str) -> str:\n \"\"\"...\"\"\"\n return ' '.join(f'><{ord(char)}>' for char in string)\n</code></pre>\n\n<h1><code>fishy_to_string</code></h1>\n\n<p>The inverse function could use a similar technique in order to avoid repeated creations of new strings in <code>string += chr(value)</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def fishy_to_string(fishy: str) -> str:\n \"\"\"\n Converts a fishy code to string\n\n Examples:\n ><72> ><101> ><108> ><108> ><111> ><32> ><87> ><111> ><114> ><108> ><100> ><33>\n Hello World!\n\n ><48> ><48> ><55> ><32> ><74> ><97> ><109> ><101> ><115> ><32> ><98> ><111> ><110> ><100>\n 007 James bond\n \"\"\"\n if not fishy:\n return ''\n\n def parse_fish(token):\n if not token:\n raise FishyError('Invalid syntax: Extra whitespace')\n\n if not (token.startswith('><') and token.endswith('>')):\n raise FishyError('Invalid syntax: ' + token)\n\n try:\n value = int(token[2:-1])\n string += chr(value)\n except ValueError:\n raise FishyError('Input cannot be parsed as character: ' + token)\n\n return ''.join(parse_fish(token) for token in fishy.split(' '))\n</code></pre>\n\n<p>I also allowed myself to change the variable name <code>char</code> to <code>token</code>, because I find it more appropriate in that context, and also slightly reworded the last error message to make it more expressive.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T15:11:57.610",
"Id": "233275",
"ParentId": "233274",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T14:55:15.230",
"Id": "233274",
"Score": "5",
"Tags": [
"python",
"python-3.x"
],
"Title": "Convert string to fishy and fishy to string"
}
|
233274
|
<p>I am trying to improve the efficiency of my code,</p>
<p>The Question is:</p>
<p>Given a value <code>n</code>, where <code>n</code> is in the range <code>[0 .. 500]</code>, return the number of digits equal to <code>1</code> in the decimal representation of the number <span class="math-container">\$11^n\$</span>.</p>
<p>Naturally when dealing with a larger power (where <code>n</code> is a large number), this reduces the efficiency drastically.</p>
<p>I managed to produce a quick but inefficient rough solution, that seems to work, but what could I do to improve the code and its efficiency?</p>
<pre><code>import java.util.ArrayList;
public class Solution {
private static int num = 11;
public static int solution(int n) {
int counter = 0;
String compare = "1";
double answer = Math.round(Math.pow(num, n));
System.out.println(answer);
String s = String.valueOf(answer);
String[] parts = s.split("");
for (int i=0; i<parts.length; i++){
if (parts[i].equals(compare)){
counter++;
}
}
System.out.println(counter);
return counter;
}
public static void main(String[] args) {
solution(8);
solution(3);
}
}
</code></pre>
<p>Any help in improving my understanding of the techniques of writing more efficient code would be much appreciated as well as improvements to the code example above.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T16:15:43.623",
"Id": "455911",
"Score": "0",
"body": "Welcome to Code Review! Is this from a programming challenge or some kind of homework? If so, please include a (or at least link to) the description of the task."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T16:18:49.460",
"Id": "455912",
"Score": "0",
"body": "Hi @AlexV, its from a programming challenge i was completing, but did not think my code was up to scratch, i will add the question in an edit, thanks in advance"
}
] |
[
{
"body": "<p>This looks like its complexity will scale linearly with <code>n</code>, so I'm surprised it's a performance bottleneck. Consider just leaving it as-is.</p>\n\n<p>Discussion about <a href=\"https://stackoverflow.com/questions/3389264/how-to-get-the-separate-digits-of-an-int-number\">counting the digits</a> <a href=\"https://www.baeldung.com/java-number-of-digits-in-int\" rel=\"nofollow noreferrer\">of an int</a> suggests that the overhead of <code>String</code> allocation may be worth the bother of avoiding.<br>\n(I'm a little surprised; I wonder if we'd see the same difference in C or not.)<br>\nOn the other hand, your situation is a little more complicated than theirs; you may not see the same efficiency if you take the (larger) pains of implementing the int-only solution.</p>\n\n<p>Within the space of string-based solutions, you may be better off without an explicit loop. A <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html\" rel=\"nofollow noreferrer\">compiled regex</a> would look good on paper, but I bet its heavy under the hood.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private static Pattern not_1 = Pattern.compile(\"[^1]+\");\n\n...\n\n int counter = not_1.matcher(String.valueOf(answer)).replaceAll(\"\").length();\n</code></pre>\n\n<p>If it's clear enough to you and your peers what that says, then I'd advocate using it because it's clear and concise. If you've specifically identified this function as a performance bottleneck though, then you'll need to write up a couple implementations and do some bench-marking to know which one's best. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T16:24:41.200",
"Id": "233281",
"ParentId": "233278",
"Score": "1"
}
},
{
"body": "<p>The implementation is <strong>wrong</strong>, and will return <strong>incorrect</strong> results once <code>n</code> exceeds 15.</p>\n\n<p>A <code>double</code> stores values using a 53 bit mantissa, allowing accurate representation of values with approximately 16 digits of precision. When <span class=\"math-container\">\\$n \\gt 16\\$</span>, then <span class=\"math-container\">\\$11^n \\gt 10^{16}\\$</span>, and the <code>double</code> value runs out of precision, and cannot represent the value precisely. This inaccuracy implies that you cannot count the number of <code>1</code> digits in the result with any hope of returning the correct value.</p>\n\n<p>It should not take long to convince yourself that <span class=\"math-container\">\\$11^n\\$</span> will always end in a <code>1</code> digit. Now, consider, <span class=\"math-container\">\\$11^{16} = 45949729863572161\\$</span>, and compare with:</p>\n\n<pre><code>jshell> String.valueOf(Math.round(Math.pow(11, 16)))\n$20 ==> \"45949729863572160\"\n</code></pre>\n\n<p>To accurately count the number of <code>1</code> digits, you need to use extended precision integers (ie, <a href=\"https://docs.oracle.com/javase/10/docs/api/java/math/BigInteger.html\" rel=\"nofollow noreferrer\"><code>BigInteger</code></a>) or an algorithm which determines the desired value in a different fashion.</p>\n\n<hr>\n\n<p>Splitting a string with a regular expression is probably the least efficient way of counting <code>1</code> digits. On top of the regular expression penalty, the JVM needs to allocate a <code>String[]</code>, as well as one <code>String</code> per character in the string. A much more efficient way of counting <code>1</code> digits is to extract the digits one at a time as characters (not strings):</p>\n\n<pre><code>int counter = 0;\nfor(int i = 0; i < s.length; i++)\n if (s.charAt(i) == '1')\n counter++;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T00:23:31.947",
"Id": "233302",
"ParentId": "233278",
"Score": "8"
}
},
{
"body": "<p>You should put your programming skills aside for a bit and think. Think mathematically, what it actually means.</p>\n\n<p><span class=\"math-container\">$$ 11^n = (10+1)^n $$</span></p>\n\n<p>Lets say a=10, b=1 => <span class=\"math-container\">\\$(a+b)^n\\$</span>, this can be expanded using pascal triangle:</p>\n\n<pre><code> 1\n 1 1\n 1 2 1\n1 3 3 1\n...\n</code></pre>\n\n<p>I suppose everybody knows how this continues...</p>\n\n<p>It then goes like this:</p>\n\n<p><span class=\"math-container\">$$ (a+b)^n = {n \\choose 0} a^n b^0 + {n \\choose 1} a^{n-1} b^1 + \\dots + {n \\choose n} a^0 b^n $$</span></p>\n\n<p>You can notice that since b=1 we can erase all those terms <span class=\"math-container\">\\$b^x\\$</span></p>\n\n<p>And we are left with\n<span class=\"math-container\">$$ (a+b)^n = {n \\choose 0} a^n + {n \\choose 1} a^{n-1} + \\dots + {n \\choose n} a^0 $$</span></p>\n\n<p>Since a=10, we know <span class=\"math-container\">\\$a^n\\$</span> is basically a 1 followed by n zeroes.</p>\n\n<p>Simple add and carry of the coefficients should now show you when a digit is 1 and when it is anything else.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T08:06:22.217",
"Id": "455994",
"Score": "0",
"body": "+1 I'm writing an answer, but probably this is the best method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T22:04:25.873",
"Id": "456304",
"Score": "0",
"body": "Curiosity got the better of me. \\${500 \\choose 9} = 5006325637513057000\\$, which is 63 bits (the limit of `long`). The largest coefficient, \\${500 \\choose 250}\\$, takes 496 bits, so you're still well into the range of needing extended precision integers. \\$11^{500}\\$ requires 1730 bits, so you have reduced the range of extended precision integers required by 70%, which is a win, but doesn't win enough to avoid needing `BigInteger` or similar to solve the problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T22:30:29.577",
"Id": "456307",
"Score": "0",
"body": "To be fair, the largest exponent, where \\${n \\choose r}\\$ is still within a 64 bit `long` for all \\$r\\$ would be \\$n = 66\\$, which is a huge improvement over the \\$n \\le 15\\$ limit for the 53-bit mantissa `double` implementation in the original post. My testing shows that even intermediate accumulations do not exceed 63 bits for \\$n \\le 66\\$."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T22:49:16.980",
"Id": "456308",
"Score": "0",
"body": "Note: Without heroic efforts, \\${n \\choose r}\\$'s internal calculations will overflow 63 bits for some \\$r\\$, when \\$n \\ge 62\\$, even though the return value can be properly represented by a `long`, placing a slightly lower limit on this approach: \\$n \\le 61\\$, instead of \\$n \\le 66\\$, if not using `BigInteger` or similar."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T07:51:44.850",
"Id": "456554",
"Score": "0",
"body": "@AJNeufeld You have a sharp eye, sir! I have actually realized that later on. But I wanted to think about it a bit deeper before I make an edit to mention that. But I haven't yet had the time for that. And honestly I was really curious if anyone would notice :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-07T10:43:55.817",
"Id": "456671",
"Score": "0",
"body": "@AJNeufeld Alright, so I think I came up with a way of doing it without needing integers larger than 500. But it requires to create an integer represenation as its prime factors (but there is no integer less than 501 with more than 8 prime factors and a static table with constant access can be created). The point is I am able to evaluate last digit of the coefficients and at the same time provide prime factor represantation of the carry without having to evaluate its real (big) value. Altogether it is quite complex (on paper anyway), not sure if it would beat BigInteger. Are you interested?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-07T12:25:25.403",
"Id": "456678",
"Score": "0",
"body": "@AJNeufeld Anyway, because the algorithm does not only tell which digits of `11^n` are ones, it tells what exactly all those digits are. And because it can be generalized for any base, it can reveal all digits of any integer `(b+m)^n` in any base `b`, and thus any `k^n` in base `b`. (with some limitations ofc...)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-07T17:21:56.977",
"Id": "456693",
"Score": "0",
"body": "@slepic Interested? Absolutely! But you should post your solution as its own question for review, not as an answer to this question, since it would not be “reviewing” this code."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T07:35:55.673",
"Id": "233314",
"ParentId": "233278",
"Score": "9"
}
},
{
"body": "<p>Like the other answers before mine, the problem is about big values of exp n. If you took pen and paper and try for example to multiplicate 1331 (<span class=\"math-container\">\\$11^3\\$</span>) and 11 to obtain number 14641 (<span class=\"math-container\">\\$11^4\\$</span>) you do in this way:</p>\n\n<pre><code> 1331 x \n 11\n-------\n 1331 +\n1331\n-------\n14641\n</code></pre>\n\n<p>So basically if you have <span class=\"math-container\">\\$11^n\\$</span> and you want to calculate <span class=\"math-container\">\\$11^{n+1}\\$</span> it can be calculated with the sum of the <span class=\"math-container\">\\$11^n\\$</span> and <span class=\"math-container\">\\$11^n * 10\\$</span>. To avoid problem due to the dimensions of numbers you can write the the numbers with strings. In the case of number 1331 we can use sum the strings <code>01331</code> and <code>13310</code> and calculate string <code>14641</code>.</p>\n\n<p>I defined a class called <code>PowerOfEleven</code> and a main method containing the tests below:</p>\n\n<pre><code>public class PowerOfEleven {\n private static String ELEVEN = \"11\";\n private static String ZERO = \"0\";\n private static String ONE = \"1\";\n\n public static void main(String[] args) {\n assertEquals(calculatePower(0), \"1\");\n assertEquals(calculatePower(1), \"11\");\n assertEquals(calculatePower(2), \"121\");\n assertEquals(calculatePower(3), \"1331\");\n assertEquals(calculatePower(4), \"14641\");\n assertEquals(calculatePower(5), \"161051\");\n assertEquals(calculatePower(6), \"1771561\");\n }\n}\n</code></pre>\n\n<p>The method <code>calculatePower</code> calculates for every n the number <span class=\"math-container\">\\$11^n\\$</span> using the sum of strings like when you use pen and paper:</p>\n\n<pre><code>public static String calculatePower(int n) {\n if (n == 0) { return ONE; }\n String number = ELEVEN ;\n for (int i = 1; i < n; ++i) {\n String first = ZERO + number;\n String second = number + ZERO;\n number = sum(first, second);\n }\n return number;\n}\n</code></pre>\n\n<p>I'm adding the strings putting one zero before the first string and another zero after the second string, so for example for number 1331 you obtain strings <code>01331</code> and <code>13310</code>.\nI defined a method for the sum of the strings like below:</p>\n\n<pre><code>private static String sum(String s1, String s2) {\n final int n = s1.length();\n char[] arr1 = s1.toCharArray();\n char[] arr2 = s2.toCharArray();\n\n StringBuilder result = new StringBuilder();\n int remainder = 0;\n for (int i = n - 1; i >= 0; --i) {\n int firstDigit = Character.getNumericValue(arr1[i]);\n int secondDigit = Character.getNumericValue(arr2[i]);\n int value = firstDigit + secondDigit + remainder;\n remainder = 0;\n if (value >= 10) {\n value = value - 10;\n remainder = 1;\n }\n result.append(Character.forDigit(value, 10));\n }\n if (remainder > 0) {\n result.append(remainder);\n }\n\n return result.reverse().toString();\n}\n</code></pre>\n\n<p>The method uses a <code>StringBuilder</code> object to store the result : when you sum the digits of the two strings starting from the end you obtain a new digit and a remainder that can be 0 or 1. The new digit obtained from the sum is appended at the of the <code>StringBuilder</code>, so you have to reverse the <code>StringBuilder</code> result to obtain the real value. </p>\n\n<p>Note : @slepic idea of using Pascal triangle if implemented simplifies my idea of sum of strings and surely improves performance.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T16:26:01.603",
"Id": "456055",
"Score": "0",
"body": "`11^(n+1) = 10 * 11^n + 11^n` is a very nice identity. I wonder why your answer is on the bottom. But i suppose it's because your answer came the last... Big thumbs up for thinking about the math behind the problem first!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T09:02:01.180",
"Id": "233316",
"ParentId": "233278",
"Score": "3"
}
},
{
"body": "<p>Your raw solution should use BigInteger:</p>\n\n<pre><code>public static int solution(int n) {\n BigInteger elevenUpN = BigInteger.valueOf(11).pow(n);\n\n String repr = elevenUpN.toString();\n int ones = (int) repr.codePoints().filter(cp -> cp == '1').count();\n System.out.printf(\"11^%d = %s with %d ones%n\", n, repr, ones);\n return ones;\n}\n</code></pre>\n\n<p>As multiplication by 11 is a shift and addition (*1 + *10), 11<sup>n</sup> can be done\nsymbolicly by n such steps.</p>\n\n<p>Use an array of n+1 digit values, the least significant at index 0 (hence reversed).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T21:17:49.723",
"Id": "456138",
"Score": "0",
"body": "From [How do I write a good answer?](https://codereview.stackexchange.com/help/how-to-answer): \"_Every answer **must make at least one insightful observation about the code in the question**. Answers that merely provide an alternate solution with no explanation or justification do not constitute valid Code Review answers and may be deleted._\" This is not a valid answer; it is just an alternate (working) solution. Do not solve programming challenges for other users; do review their code, point out bugs, inefficiencies, style issues, etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T21:25:33.577",
"Id": "456143",
"Score": "0",
"body": "\"_Use an array of `n+1` digit values_\": This is incorrect. \\$11^{500}\\$ has 521 digits in the result, not a mere 1 more than 500."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T17:58:38.787",
"Id": "233354",
"ParentId": "233278",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T15:49:03.523",
"Id": "233278",
"Score": "4",
"Tags": [
"java",
"performance",
"algorithm",
"array"
],
"Title": "Counting number of `1` digits in the value of \\$11^n\\$"
}
|
233278
|
<p>Here's what I've come up with:</p>
<pre class="lang-py prettyprint-override"><code>def bf_interpreter(code: str) -> str:
"""
Interprets BrainF**k code
Examples:
++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.
Hello World!
+++++>++++[<+>-]++++++++[<++++++>-]<.
9
"""
outputs = []
ptr = 0
values = [0]
length = 1
brackets = []
index = 0
code_length = len(code)
while index < code_length:
char = code[index]
while length <= ptr:
length += 1
values.append(0)
if char == '>': ptr += 1
if char == '<': ptr -= 1
if char == '+': values[ptr] = (values[ptr] + 1) % 256
if char == '-': values[ptr] = (values[ptr] - 1) % 256
if char == '[':
brackets.append(index)
if char == ']':
if values[ptr] == 0:
brackets.pop()
else:
index = brackets[-1]
if char == '.':
outputs.append(chr(values[ptr]))
if char == ',':
values[ptr] = ord(input())
index += 1
return ''.join(outputs)
</code></pre>
<p>How do I make this look better? (More consistent, as well as strictly following PEP 8 conventions)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T17:02:48.207",
"Id": "455919",
"Score": "0",
"body": "Can you describe the initial intention, what are the parsing rules in your custom \"interpreter\" ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T17:15:53.143",
"Id": "455920",
"Score": "0",
"body": "@AlexV Thanks for pointing that out. I've updated my question as such."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T17:16:54.160",
"Id": "455921",
"Score": "0",
"body": "@RomanPerekhrest I don't quite understand what you mean by `parsing rules`. Could you please elaborate?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T00:44:31.020",
"Id": "455969",
"Score": "1",
"body": "When `char == '['`, you're supposed to check whether the value at the pointer is zero; if it is, you need to jump to after the corresponding `]`."
}
] |
[
{
"body": "<p>All of your <code>if char == '>': ptr += 1</code> and similar checks should use <code>elif</code> after the first check. By using <code>if</code> for all of the checks, you're forcing them all to run, even once you've found a match. This is wasteful because the checks are necessarily exclusive of each other. Once one check is true, none of the other checks can be. For example, you should have:</p>\n\n<pre><code>if char == '>': ptr += 1\nelif char == '<': ptr -= 1\n\nelif char == '+': values[ptr] = (values[ptr] + 1) % 256\nelif char == '-': values[ptr] = (values[ptr] - 1) % 256\n</code></pre>\n\n<p>Now the checks stop once a match is found which prevents unnecessary equality checks. </p>\n\n<hr>\n\n<p>I'd also try to break this down into a few functions to help testing. Right now, you can only test <code>bf_interpreter</code> as one whole. You could have a function that takes the current character, and the state of the program (the <code>brackets</code>, <code>ptr</code>, <code>outputs</code>...), and returns a new state. That way you can easily test for a given state if a certain command produces a correct new state.</p>\n\n<hr>\n\n<p>I'm assuming this loop is just to add padding so you don't go off the end of the slots?:</p>\n\n<pre><code>while length <= ptr:\n length += 1\n values.append(0)\n</code></pre>\n\n<p>You could make that a little neater by just using math and some concatenation. You could also just get rid of <code>length</code> and use <code>len(values)</code>:</p>\n\n<pre><code>needed = ptr - len(values)\nvalues += [0] * needed\n</code></pre>\n\n<p><code>ptr - len(values)</code> calculates how many slots are needed, then <code>[0] * needed</code> produces that many <code>0</code>s, and <code>+=</code> adds them to <code>values</code>. If <code>needed</code> is negative, <code>[0] * needed</code> will produce <code>[]</code>, and essentially cause no change.</p>\n\n<p>If you want to avoid the temporary list that <code>[0] * needed</code> creates, you could replace that with:</p>\n\n<pre><code>values += (0 for _ in range(needed))\n</code></pre>\n\n<p>Now <code>+=</code> just pulls from a generator that produces values as needed.</p>\n\n<hr>\n\n<p>And then, just like how you don't need <code>length</code>, you don't need <code>code_length</code> either. <code>len(code)</code> is fine; <code>len</code> runs in constant time. You don't need to cache it for performance reasons.</p>\n\n<p>Here's some timings to show the difference in runtime this can cause:</p>\n\n<pre><code>import timeit\n\nTEST_CODE = \"++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.\"\n\n>>> timeit.timeit(lambda: bf_interpreter_orig(TEST_CODE), number=int(2e5)) # Two hundred thousand tests\n77.3481031 # Takes 77 seconds\n\n>>> timeit.timeit(lambda: bf_interpreter_len(TEST_CODE), number=int(2e5))\n88.93794809999997\n</code></pre>\n\n<p>Where <code>bf_interpreter_orig</code> is your original code, and <code>bf_interpreter_len</code> is your original code but using <code>len</code>.</p>\n\n<p>Yes, there's a difference. Note though, that's a ~11 second difference across <em>200,000</em> calls. That works out to roughly 58 <em>microseconds per call</em> to the interpreting function.</p>\n\n<p>Unless you're calling <code>bf_interpreter</code> hundreds of thousands of times in a tight loop, the difference is unlikely to matter. This also likely has nothing to do with the fact that you're requesting a length, and more to do with one extra function call. Function calls aren't super fast in Python. Likely any extra call to any function would have similar effects.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T17:23:55.617",
"Id": "455923",
"Score": "0",
"body": "Yes, it would be possible to use `len(values)`, but wouldn't it be more time consuming? If having a variable to calculate the length takes `4.78` seconds, using `len(values)` takes `7.549` seconds."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T18:06:57.077",
"Id": "455933",
"Score": "0",
"body": "@Srivaths See my edit at the bottom. The time difference isn't as big as your findings show. You're likely using too small of a sample, or a poor benchmarking method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T18:16:28.323",
"Id": "455937",
"Score": "0",
"body": "I did not exactly use the `bf_interpreter` function to time the difference. See https://pastebin.com/uZNR3ArW"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T18:30:16.110",
"Id": "455941",
"Score": "0",
"body": "@Srivaths When I run that exact test, I get 13.8 seconds for `code1`, and 11.2 seconds for `code2`. That's in the neighborhood of the results that I got with my full test (81% as fast for my test vs 86% as fast with your test)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T18:35:10.080",
"Id": "455942",
"Score": "0",
"body": "Your tests seem *abnormally* slow. Do you have something running in the background that could be messing with tests?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T05:38:03.220",
"Id": "455983",
"Score": "0",
"body": "Hmm... No, I don't think so. But maybe the IDEs make a difference. I use PyCharm."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-09T22:57:09.903",
"Id": "456951",
"Score": "0",
"body": "I would find `values.extend(0 for _ in range(needed))` more readable than `values += (0 for _ in range(needed))`. As far as performance is concerned, they seem to be about equally fast (not that it would matter in this case). This whole `list` business is kinda inelegant and would be handled more nicely with `defaultdict(int)`."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T16:38:40.007",
"Id": "233282",
"ParentId": "233279",
"Score": "8"
}
},
{
"body": "<p>+1 on specifying argument <code>code: str</code> and return type <code>-> str</code>. </p>\n\n<p>I implemented a class seen below which has the advantage of seeing chars and their corresponding functions at a glance. Adding new chars if need be is incredibly easy. </p>\n\n<pre class=\"lang-py prettyprint-override\"><code> self.actions = {\n '>': self.greater_than,\n '<': self.less_than,\n '+': self.plus,\n '-': self.minus,\n '[': self.left_bracket,\n ']': self.right_bracket,\n '.': self.dot,\n ',': self.comma\n }\n</code></pre>\n\n<p>You can use a </p>\n\n<pre><code>try:\n ...\nexcept KeyError:\n ...\n</code></pre>\n\n<p>to detect unrecognised chars.</p>\n\n<h1>Complete Class</h1>\n\n<pre class=\"lang-py prettyprint-override\"><code>\nclass BFInterpreter:\n def __init__(self):\n self.outputs = []\n\n self.ptr = 0\n\n self.values = [0]\n self.length = 1\n\n self.brackets = []\n\n self.index = 0\n\n def greater_than(self):\n self.ptr += 1\n\n def less_than(self):\n self.ptr -= 1\n\n def plus(self):\n self.values[self.ptr] = (self.values[self.ptr] + 1) % 256\n\n def minus(self):\n self.values[self.ptr] = (self.values[self.ptr] - 1) % 256\n\n def left_bracket(self):\n self.brackets.append(self.index)\n\n def right_bracket(self):\n if self.values[self.ptr] == 0:\n self.brackets.pop()\n else:\n self.index = self.brackets[-1]\n\n def dot(self):\n self.outputs.append(chr(self.values[self.ptr]))\n\n def comma(self):\n self.values[self.ptr] = ord(input())\n\n def evaluate(self, code):\n self.code = code\n self.code_length = len(self.code)\n\n self.actions = {\n '>': self.greater_than,\n '<': self.less_than,\n '+': self.plus,\n '-': self.minus,\n '[': self.left_bracket,\n ']': self.right_bracket,\n '.': self.dot,\n ',': self.comma\n }\n\n while self.index < self.code_length:\n char = self.code[self.index]\n\n while self.length <= self.ptr:\n self.length += 1\n self.values.append(0)\n\n self.actions[char]()\n\n self.index += 1\n\n return ''.join(self.outputs)\n</code></pre>\n\n<h1>Usage</h1>\n\n<pre class=\"lang-py prettyprint-override\"><code>bf = BFInterpreter()\nprint(bf.evaluate('+++++>++++[<+>-]++++++++[<++++++>-]<.'))\n</code></pre>\n\n<p>code has been specified as an argument in the evaluate method rather than in the constructor to be able to evaluate without creating new objects.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T13:12:05.180",
"Id": "456388",
"Score": "5",
"body": "Now change `BFInterpreter` to `BFCode(str)` and change `evaluate(self, code)` to `__call__(self)`. Boom."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-09T22:44:01.643",
"Id": "456949",
"Score": "1",
"body": "_\"…to be able to evaluate without creating new objects.\"_ And what exactly is the point of that? You cannot reuse the object after calling `evaluate` anyways. Your concept of `__init__` + `evaluate` is bad for readability and usability of your code. I would either make a wrapper method that creates a `BFInterpreter`, then calls `evaluate` on it and returns the result; or create what I call a \"function-like class\": a class with `__new__` method in which you create an instance, call some method(s) on it (such as `evaluate`), and return the result (instead of returning an instance of the class)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-10T05:36:50.813",
"Id": "456986",
"Score": "0",
"body": "In the spirit of you once forge a spoon and use it may times, not creating a spoon each time you want to use it. You create an object then use a method many times versus creating a new instance each time you want to evaluate"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-10T12:02:05.057",
"Id": "457026",
"Score": "0",
"body": "Have you read and understood my comment? You _cannot_ use your instance multiple times, since you don't reset the variables `self.outputs`, `self.values`, etc. in the `evaluate` method. You could use the object multiple times if you _did_ reset those variables in the `evaluate` method, but then there would be absolutely no point in creating and reusing the object, since there would be no initialization of the object done in the constructor. You might as well change `evaluate` to a `classmethod` and create a new instance in that method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-10T12:14:23.847",
"Id": "457030",
"Score": "0",
"body": "Oh and by the way, your implementation is neither thread- nor exception-safe. It would be, however, if you did what I told you. **PS.** if you still believe that your object is reusable, just try to reuse it on these inputs: `'+++++>++++[<+>-]++++++++[<++++++>-]<.'` and `''` (an empty string). The first should (and does) print `9`; however the second should print nothing but prints `9` instead. And one more thing, your program fails for inputs which contain other characters than the 8 control ones, which makes it neither a valid BF interpreter, nor equivalent with OP's original program."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-11T13:32:48.823",
"Id": "457243",
"Score": "0",
"body": "@kyrill those comments are by far most understandable. Will amend!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T17:08:16.527",
"Id": "233350",
"ParentId": "233279",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "233282",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T16:09:18.010",
"Id": "233279",
"Score": "11",
"Tags": [
"python",
"python-3.x",
"interpreter",
"brainfuck"
],
"Title": "BrainF**k interpreter in python"
}
|
233279
|
<p>I have a small todo app where you can add and mark todos as completed. I structured it that all the data is kept in the parent container (<code>TodoWrapper</code>), that renders 2 components which are the toDo list and the createTodo component. I see others who are having state inside the <code>createTodo</code> component wonder if that is good practice or keeping it in parent and only invoking the event handler from child. I also left some questions inside the code to explain better. I know it's not just a few lines of code, but I would really appreciate so much if I get some feedback because Im trying to improve!</p>
<pre><code>class TodoWrapper extends React.Component {
state = {
todos: [],
currentItem: {text: "", id: "", checked: false}
};
onChange = (input, check) => {
this.setState({
currentItem: {
text: input,
id: Date.now() / Math.random(),
checked: false
}
})
};
addItem = (e) => {
e.preventDefault()
const newItem = this.state.currentItem
if (newItem.text !== '') {
const todos = [...this.state.todos, newItem]
this.setState({
todos: todos,
currentItem: { text: '', id: '', checked: false },
})
}
};
// please see below I have implemented handleCheck differently
handleCheck = (isChecked, id) => {
const filteredItems = this.state.todos.map(item => {
if (item.id === id) {
return {...item, ["checked"]: isChecked}
} else {
return {...item};
}
});
this.setState({
todos: filteredItems,
})
};
//below function (which i do not use)is faster since its only look up but is it better since I only rely on index?
//Also, since I have an array with nested objects - did I directly mutate,since I only have shallow copy?
//Thus, is it better to iterate (which is slower, but not directly mutate state which I believe I did not in first example of handleCheck function)
(
handleCheck = (index) => {
const newTodos = [...this.state.todos];
newTodos[index].checked =!newTodos[index].checked;
this.setState({
todos: newTodos,
})
};
)
render () {
console.log("render todos", this.state.todos)
return (
<div className="todo-container">
<CreateTodo
addItem={this.addItem}
onChange={this.onChange}
currentItem={this.currentItem}
/>
<TodoList
todos={this.state.todos}
handleCheck={this.handleCheck}
/>
</div>
)
}
}
const TodoList = ({todos, handleCheck}) => {
const renderList = todos.map((item, index) => {
const checkedOf = item.checked ? "checked" : "";
return (
<TodoItem
id={item.id}
index={index}
key={item.id}
style={checkedOf}
text={item.text}
checked={item.isChecked}
handleCheck={handleCheck}
/>
)
});
return (
<ul className="list">
{renderList}
</ul>
)
};
const TodoItem = ({style, id, index, text, checked, handleCheck}) => {
return (
<li className={`item_text ${style}`}>
{text}
<input
type="checkbox"
checked={checked}
onClick={({target})=> handleCheck(target.checked, id, index)}
/>
</li>
)
};
const CreateTodo = ({addItem, currentItem, onChange}) => {
//When does it make sense to have state inside the component with the input?
//I passed from parent the onChange function, that I invoke here and SEND BACK the value ONLY to receive BACK the value which doesnt seem to make sense to me.
//On the other hand it makes sense to keep state in the parent.
const onInputChange = (event) => {
onChange(event.target.value)
};
return (
<form className="submit_task_form" onSubmit={addItem}>
<input className="submit_task_form__input" value={currentItem} onChange={onInputChange}/>
<button type="submit">Add</button>
</form>
)
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T17:35:45.290",
"Id": "455927",
"Score": "2",
"body": "The multiple versions of some functions make the post confusing IMO. Consider editing your question to make it clearer what code you're actually using - you can even add an executable \"stack snippet\" (hit Ctrl+M when editing) to showcase & demonstrate your app. I find the \"//\" notes confusing, too: they look like they're in-code comments but read like they're part of the body"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T16:26:51.927",
"Id": "456057",
"Score": "0",
"body": "I don't see why TodoWrapper needs to know when you edit the Todo unless you are going to let the user edit previous Todos so you need to know which one is being edited. The way it is right now, I would only call addItem() and pass as a parameter the current todo that CreateTodo would have on its state. In other words, the only time TodoWrapper uses the current todo is when addItem gets called, but this could get called with the todo as a parameter coming from CreateTodo."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T17:01:25.257",
"Id": "233285",
"Score": "1",
"Tags": [
"javascript",
"react.js"
],
"Title": "Small React todo app"
}
|
233285
|
<p>I am learning OOP, concretely Java, by developing a real life business application for aimed for repair shops. I have followed MVC pattern design for GUI elements of my application. I was wondering do my input dialog controller classes has to much responsibilities. They set ComboBox models, button ActionListeners, verify user input, show input errors, and save data to model. Is that to much responsibilities, or is that actually a single responsibility, connecting the view with the model? I am aware of <a href="https://softwareengineering.stackexchange.com/questions/237827/mvc-does-the-controller-break-the-single-responsibility-principle">this topic</a> in the Software Engineering website.</p>
<p>===========================================================================</p>
<p>This is my abstract input dialog controller class that is a super class for all input dialog controllers. It is responsible for setting the ID label value, setting Add and Cancel buttons ActionListeners, and has the main function of input controllers, saving data.</p>
<pre><code> public abstract class InputDialogController implements WindowController
{
protected DataType dataType;
protected int id;
protected InputDialog gui;
protected InputDialogController(WindowController owner, DataType dataType)
{
this.dataType = dataType;
gui = InputDialogFactory.getWindow(owner.getWindow(), dataType);
id = IDGenerator.getNewID(dataType);
gui.getIdPanel().setIdValue(IDGenerator.formatRegularID(id));
gui.getInputButtonPanel().setBtnAddActionListener(ActionListenerFactory.saveData(this));
gui.getInputButtonPanel().setBtnCancelActionListener(ActionListenerFactory.closeWindow(this));
}
@Override
public Window getWindow()
{
return (Window) gui;
}
public void trySavingDataElement()
{
if(isInputValid())
{
DataManager.save(createDataElement());
getWindow().dispose();
}
else
{
showInputErrors();
}
}
protected abstract boolean isInputValid();
protected abstract DataElement createDataElement();
protected abstract void showInputErrors();
}
</code></pre>
<p>This is one of mine concrete input dialog controllers, the ClientRegistrationController class.</p>
<pre><code>public class ClientRegistrationController extends InputDialogController
{
private ClientRegistrationDialog clientGUI;
public ClientRegistrationController(WindowController owner, DataType dataType)
{
super(owner, dataType);
clientGUI = (ClientRegistrationDialog) super.gui;
clientGUI.getMarketingPanel().setMarketingCmbModel(CmbModelFactory.getModel(dataType));
clientGUI.getMarketingPanel()
.setBtnMarketingActionListener(ActionListenerFactory
.openNewWindow(this, DataType.MARKETING_TYPE));
}
public void updateComboBoxes(String item)
{
clientGUI.getMarketingPanel().setMarketing(item);
}
@Override
protected boolean isInputValid()
{
return isNameValid()
&& isPhoneNumberValid()
&& isMarketingSelected();
}
private boolean isNameValid( )
{
return !("".equals(clientGUI.getPersonalInfoPanel().getName()));
}
private boolean isPhoneNumberValid()
{
String phoneNumber = clientGUI.getPersonalInfoPanel().getPrimePhoneNumber();
return !(DataManager.clientsDataTable.uniqueStringCollision(phoneNumber)
|| ("".equals(phoneNumber)));
}
private boolean isMarketingSelected()
{
return clientGUI.getMarketingPanel().getMarketing() != "";
}
@Override
protected Client createDataElement()
{
Client newClient= new Client();
newClient.setId(id);
newClient.setName(clientGUI.getPersonalInfoPanel().getName());
newClient.setPrimePhoneNumber(clientGUI.getPersonalInfoPanel().getPrimePhoneNumber());
newClient.setAlternativePhoneNumber(clientGUI.getPersonalInfoPanel().getAltPoneNumber());
newClient.setEmail(clientGUI.getPersonalInfoPanel().getEmail());
newClient.setAddress(clientGUI.getPersonalInfoPanel().getAddress());
newClient.setMarketing(DataElementGetter.getMarketing(clientGUI.getMarketingPanel().getMarketing()));
return newClient;
}
@Override
protected void showInputErrors()
{
checkName();
checkPhoneNumber();
checkMarketing();
}
private void checkName()
{
if(isNameValid())
{
clientGUI.getPersonalInfoPanel().showNameDefault();
}
else
{
clientGUI.getPersonalInfoPanel().showNameError();
}
}
private void checkPhoneNumber()
{
if(isPhoneNumberValid())
{
clientGUI.getPersonalInfoPanel().showPhoneDefault();
}
else
{
clientGUI.getPersonalInfoPanel().showPhoneError();
}
}
private void checkMarketing()
{
if(isMarketingSelected())
{
clientGUI.getMarketingPanel().showMarketingDefault();
}
else
{
clientGUI.getMarketingPanel().showMarketingError();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T19:36:51.247",
"Id": "455948",
"Score": "0",
"body": "I have a feeling that your question might be better placed at [SE Software Engineering](https://softwareengineering.stackexchange.com/questions) (but maybe closed for a duplicate of what you mentioned)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T19:42:02.157",
"Id": "455949",
"Score": "0",
"body": "Regarding the [tag:swing] tag. Specifically a _Controller_ class shouldn't need to know about anything of the GUI interfaces."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T19:50:19.160",
"Id": "455950",
"Score": "0",
"body": "@πάνταῥεῖ ῥεῖ - What interacts with GUI interfaces then?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T17:01:52.343",
"Id": "233286",
"Score": "3",
"Tags": [
"java",
"object-oriented",
"swing",
"controller"
],
"Title": "Controller class for an input dialog"
}
|
233286
|
<p>This question is the adaptation of <a href="https://codereview.stackexchange.com/questions/233279/brainfk-interpreter-in-python">this</a> question in C++. (I'm the author of that code as well).</p>
<p>The code:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <bits/stdc++.h>
std::string bf_interpreter(std::string code){
long long int ptr = 0;
std::vector<int> values = {0};
long long int length = 1;
std::vector<int> brackets;
std::string result = "";
for(unsigned long long int index = 0; index < code.size(); index++){
while(length <= ptr){
length++;
values.push_back(0);
}
char character = code[index];
switch(character){
case '>': ptr++; break;
case '<': ptr--; break;
case '+': values[ptr] = (values[ptr] + 1) % 256; break;
case '-': values[ptr] = (values[ptr] - 1) % 256; break;
case '[':
brackets.push_back(index);
break;
case ']':
if(values[ptr] == 0)
brackets.pop_back();
else
index = brackets[brackets.size() - 1];
break;
case '.':
result += (char)values[ptr];
break;
case ',':
char input; std::cin >> input;
values[ptr] = (int)input;
break;
}
}
return result;
}
int main()
{
std::string s;
std::cin >> s;
std::cout << bf_interpreter(s);
}
</code></pre>
<p>I'm quite a beginner in C++, so please excuse me if I'm not following any standard conventions.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T18:29:43.410",
"Id": "455940",
"Score": "8",
"body": "_`#include <bits/stdc++.h>`_ is one of the [worst things to do in c++](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h)!"
}
] |
[
{
"body": "<h2>Bug</h2>\n\n<p>The only issue I see is that the data array is never expanded.</p>\n\n<p>As a result any value of <code>ptr</code> that is not zero will cause undefined behavior. What you want to do is give a fixed but reasonable size for the data.</p>\n\n<pre><code>std::size_t const maxDataSize = 10000;\n\n...\n\n std::vector<int> values;\n values.resize(maxDataSize);\n</code></pre>\n\n<p>Then make sure when you access the data you mod it to the correct range:</p>\n\n<pre><code> case '>': ptr = (ptr + 1) % maxDataSize; break;\n case '<': ptr = (ptr - 1) % maxDataSize; break;\n</code></pre>\n\n<h2>Comment</h2>\n\n<p>This is not a standard C++ header.</p>\n\n<pre><code>#include <bits/stdc++.h>\n</code></pre>\n\n<p>What you want is</p>\n\n<pre><code>#include <vector>\n#include <string>\n#include <iostream>\n</code></pre>\n\n<h2>Comment</h2>\n\n<p>The code is non modifiable so the the code parameter should be constant. I would also pass by const reference to prevent a copy or require a move operation to pass the code into the interpretor.</p>\n\n<hr>\n\n<p>I can see how you would interpret the output as what is printed to the output stream by the interpreter as the result. But is not the whole of memory the actual output?</p>\n\n<hr>\n\n<p>Two things I would do:</p>\n\n<ol>\n<li><p>Make <code>.</code> output to the output stream (like <code>,</code> takes from the input stream.</p></li>\n<li><p>I would give the <code>bf_interpreter()</code> two parameters. The code to execute and the data memory that can be used by the program. The data memory is passed by reference so that any changes can be inspected after the interpreter has finished.</p></li>\n<li><p>Potentially I would even pass two streams (input/output) as parameters to <code>bf_interpreter()</code>. Though that is a bit more subjective.</p></li>\n</ol>\n\n<p>Thus my function definition would be this:</p>\n\n<pre><code> std::string bf_interpreter(std::string const& code,\n std::vector<int>& memory,\n std::istream& input = std::cin,\n std::ostream& output = std::cout\n );\n</code></pre>\n\n<h2>ReDesign</h2>\n\n<p>OK. So given there is a lot more state here than I really want to pass as a function. I would change this a bit and create a \"Brain Fuck\" class where all the important state is passed to the constructor then you can call interpret on the object.</p>\n\n<pre><code>class BF_Engine\n{\n // Add Members here\n void nextStep() {\n // Add interpreter here\n }\n public:\n BF_Engine(std::string const& code,\n std::vector<int>& memory,\n std::istream& input = std::cin,\n std::ostream& output = std::cout\n );\n\n void interpret(std::size_t steps = 1)\n {\n while (!finished && steps > 0) {\n nextStep();\n --steps;\n }\n }\n void interpretRun()\n {\n while (!finished) {\n nextStep();\n }\n }\n };\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T23:36:24.833",
"Id": "233299",
"ParentId": "233287",
"Score": "6"
}
},
{
"body": "<h3>Naming</h3>\n\n<p>Functions <em>do</em> things, so the name for a function should normally be a verb. In your case, the function should be something like <code>bf_interpret</code>, not <code>...interpreter</code>.</p>\n\n<p>I'd also at least consider making <code>bf</code> a namespace, so the call in <code>main</code> would be something like:</p>\n\n<pre><code>bf::interpret(s);\n</code></pre>\n\n<h3>Prefix operators</h3>\n\n<p>Lacking a reason to do otherwise, I'd prefer to use prefix operators rather than postfix.</p>\n\n<pre><code> case '>': ++ptr; break;\n case '<': --ptr; break;\n</code></pre>\n\n<h3>Use the right types</h3>\n\n<p>Since you're restricting the items in <code>values</code> to the range 0..255 anyway, I'd at least consider making them <code>uint8_t</code>, which guarantees exactly that range. This lets you simplify the code somewhat:</p>\n\n<pre><code> case '+': ++values[ptr]; break;\n case '-': --values[ptr]; break;\n</code></pre>\n\n<p>If you wanted the values to act differently, I'd still just use increment and decrement here, and implement the desired wrapping (or whatever) behavior in a separate data type, and make <code>values</code> a vector of that data type.</p>\n\n<h3>Input/Output</h3>\n\n<p>While I think Martin York is on the right track in saying that the input to and output from interpretation should be passed as parameters, I'd disagree about the exact form of those parameters. Rather than streams, I'd make them iterators, whose exact types are specified as template parameters. A user who wants to read/write streams for the I/O can do so by passing stream iterators. At the same time, a user who wants to read from a vector and write to a string (or whatever) can do that as well.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T18:21:07.893",
"Id": "456083",
"Score": "0",
"body": "I like iterators at first glance, but the interface to streams is easier concept to pass. As iterators require a beginning and end for each stream. On the other hand it would be simple to provide a stream buffer that wraps two iterators giving you the advantage of the iterator but using the stream interface."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T08:31:19.340",
"Id": "233315",
"ParentId": "233287",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "233299",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T18:26:14.203",
"Id": "233287",
"Score": "5",
"Tags": [
"c++",
"c++14",
"interpreter",
"brainfuck"
],
"Title": "BrainF**k interpreter in C++"
}
|
233287
|
<p>Is this good way of creating tests? I have no experience how they do it in companies. Ignore uppercase names of variables.. I may change it eventually.</p>
<p><code>reduction_strategy.py</code> defines my <code>ListArray</code> class, which I've written unit tests for.</p>
<p><code>ListArray</code> defines object that takes care of matrices containing symbolic elements. Basic matrix operations adding and multiplying, syntax for using this object slicing, Changing rows and columns. This class let me keep 2d object, and make <code>slice</code>'s easier, <code>Matrix</code> object has indexing from <code>0 to n</code> as 1d always.</p>
<p>Examples: </p>
<p><img src="https://latex.codecogs.com/gif.latex?A%20%3D%20%5Cbegin%7Bbmatrix%7D%20%27a%27%20%26%20%27b%27%5C%5C%20%27c%27%20%26%20%27d%27%20%5Cend%7Bbmatrix%7D%20%2C%20B%20%3D%20%5Cbegin%7Bbmatrix%7D%20%27e%27%20%26%20%27f%27%5C%5C%20%27g%27%20%26%20%27h%27%20%5Cend%7Bbmatrix%7D%20%2C%20A%20+%20B%20%3D%20%5Cbegin%7Bbmatrix%7D%20%27a%20+%20e%27%20%26%20%27b%20+%20f%27%5C%5C%20%27c%20+%20g%27%20%26%20%27d%20+%20h%27%20%5Cend%7Bbmatrix%7D" alt="Matrix equations">
<img src="https://latex.codecogs.com/gif.latex?A%20%3D%20%5Cbegin%7Bbmatrix%7D%20%27a%27%20%26%20%27b%27%5C%5C%20%27c%27%20%26%20%27d%27%20%5Cend%7Bbmatrix%7D%20%2C%20B%20%3D%20%5Cbegin%7Bbmatrix%7D%20%27e%27%20%26%20%27f%27%5C%5C%20%27g%27%20%26%20%27h%27%20%5Cend%7Bbmatrix%7D%20%2C%20A%20*%20B%20%3D%20%5Cbegin%7Bbmatrix%7D%20%27a*e%20+%20b*g%27%20%26%20%27a*f%20+%20b*h%27%5C%5C%20%27c*e%20+%20d*g%27%20%26%20%27c*f%20+%20d*h%27%20%5Cend%7Bbmatrix%7D" alt="Multiply"></p>
<pre class="lang-py prettyprint-override"><code># reduction_strategy.py
import numpy as np
from copy import copy, deepcopy
from sympy import Matrix, zeros, ones, eye, diag
from itertools import permutations
class ListArray:
def __init__(self, array):
# self.__class__ = 'ListArray'
if type(array) == int:
array = [array]
if type(array[0]) != list:
self.single = True
self.size = (1, len(array))
array = [array] # Matrix always uses 2d !
else:
self.single = False
self.size = (len(array), len(array[0]))
if len(array) == 1:
self.single = True
for row in array:
if type(row[0]) == list:
print('To deep Array:', array)
break
self.array = Matrix(array)
self.history = [{'created': array}]
def __add__(self, other):
return ListArray([[
self.array[r * self.size[1] + c] +
other.array[r * self.size[1] + c]
for c in range(self.size[1])
]
for r in range(self.size[0])
])
def __eq__(self, other):
return self.array == other.array
def __getitem__(self, i):
# Condition to extract row!
if type(i) is slice:
rstart = i.start if i.start else 0
rstop = i.stop if i.stop else self.size[0]
rstep = i.step if i.step else 1
cstart = 0
cstop = self.size[1]
cstep = 1
# Condition to Slice with number -> one Row
elif type(i) is int:
rstart = i
rstop = i + 1
rstep = 1
cstart = 0
cstop = self.size[1]
cstep = 1
# Condition Double slice
elif type(i[0]) is slice and type(i[1]) is slice:
rslice = i[0]
cslice = i[1]
rstart = rslice.start if rslice.start else 0
rstop = rslice.stop if rslice.stop else self.size[0]
rstep = rslice.step if rslice.step else 1
cstart = cslice.start if cslice.start else 0
cstop = cslice.stop if cslice.stop else self.size[1]
cstep = cslice.step if cslice.step else 1
else:
raise ValueError(f"Incorrect Slice params: {i}")
array = self.array
if self.single:
# array = array]
out = [
array[r * self.size[1] + c]
for c in range(cstart, cstop, cstep)
for r in range(rstart, rstop, rstep)
]
else:
out = [[
array[r * self.size[1] + c]
for c in range(cstart, cstop, cstep)
]
for r in range(rstart, rstop, rstep)
]
return ListArray(out)
def __repr__(self):
txt = '['
for row in range(self.size[0]):
if row == 0:
txt += f"{'[':>1}"
else:
txt += f'\n{"[":>3}'
for col in range(self.size[1]):
txt += f' {self.array[self.size[1]*row +col]},'
if row >= self.size[0] - 1:
txt += ']'
else:
txt += f'],'
txt += f']'
return txt
def __sub__(self, other):
return ListArray([[
self.array[r * self.size[1] + c] -
other.array[r * self.size[1] + c]
for c in range(self.size[1])
]
for r in range(self.size[0])
])
# def __class__(self):
# pass
def __len__(self):
# print(len(self.array))
if self.single:
return self.size[1]
return self.size[0]
def __mul__(self, other):
result = self.array * other.array
result = [result[other.size[1]*row: other.size[1]*row + other.size[1]]
for row in range(self.size[0])
]
return ListArray(result)
def switch_Rows(self):
print("Finish this")
def switch_cols(self):
print("Finish this")
def transp(self):
c = self.size[0]
r = self.size[1]
array_t = self.array.T
return ListArray([array_t[row*c:row*c + c] for row in range(r)])
def match_patern_any(self):
# A | B
# --|--
# C | D
if self.size[0] % 2 == 1 or self.size[1] % 2 == 1:
raise ValueError("Matrix has to be even size!")
half_rows = int(self.size[0]/2)
half_cols = int(self.size[1]/2)
square_a = self[0:half_rows, 0:half_cols]
square_b = self[0:half_rows, half_cols:self.size[1]]
square_c = self[half_rows:self.size[0], 0:half_cols]
square_d = self[half_rows:self.size[0], half_cols:self.size[1]]
return any([
square_a == square_b,
square_a == square_c,
square_a == square_d,
square_b == square_c,
square_b == square_d,
square_c == square_d
])
class Reduktor(ListArray):
def __init__(self, matrix_input):
ListArray.__init__(self, array=matrix_input)
assert (self.size[0] == self.size[0] and self.size[0] % 2 == 0)
print("R:", len(matrix_input))
print("C:", len(matrix_input[0]))
self.matrix = matrix_input
def col_order(self):
pass
if __name__ == "__main__":
a = [['a', 'b', 'c', 'g'],
['d', 'e', 'f', 'x'],
['q', 't', 'i', 'y'],
['i', 'o', 'p', 's']]
b = [['d', 'e', 'f'], ['g', 'h', 'i']]
c = ['x', 'y', 'z']
d = [['i', 'b', 'c', 'd']]
A = ListArray(a)
print(type(A))
red = Reduktor(a)
</code></pre>
<p><code>testing_ListArray.py</code> contains the unit tests:</p>
<pre class="lang-py prettyprint-override"><code># testing_ListArray.py
from reduction_strategy import ListArray
import unittest
class TestinglistArray(unittest.TestCase):
def setUp(self):
self.a = \
[['a', 'b', 'c', 'g'],
['d', 'e', 'f', 'x'],
['q', 't', 'i', 'y'],
['i', 'o', 'p', 's']]
self.b = \
[['a', 'c', 'j', 'v'],
['d', 'e', 'f', 'x'],
['q', 't', 'i', 'y'],
['i', 'o', 'p', 's']]
def test_equal(self):
A = ListArray(self.a)
B = ListArray(self.b)
Aprim = ListArray(self.a)
cut_A = A[2:, 0:2]
cut_B = B[2:, 0:2]
assert A == Aprim
assert not A == B
assert cut_A == cut_B
assert A[2] == ListArray([['q', 't', 'i', 'y']])
assert A[2] == ListArray(['q', 't', 'i', 'y'])
def test_fit(self):
a = \
[['a', 'b', 'a', 'b'],
['a', 'b', 'a', 'b']]
b = [['a', 'b'],
['c', 'd']]
c = ['a', 'b', 'c']
A = ListArray(a)
B = ListArray(b)
C = ListArray(c)
assert A.match_patern_any()
assert not B.match_patern_any()
self.assertRaises(ValueError, C.match_patern_any)
def test_traspose(self):
a = [['a', 'g'],
['b', 'x']]
b = [['a', 'b'],
['g', 'x']]
a2 = [['a', 'g', 'j'],
['b', 'x', 'k']]
b2 = [['a', 'b'],
['g', 'x'],
['j', 'k']]
A = ListArray(a)
B = ListArray(b)
A2 = ListArray(a2)
B2 = ListArray(b2)
assert A.transp() == B # Transposed A = A'
assert A2.transp() == B2 # Transposed A2 = A2'
def test_mult(self):
a = [['a', 'g'],
['b', 'x']]
b = [['b', 'b'],
['d', 'b']]
res1 = [['a*a + b*g', 'a*g + x*g'],
['b*a + x*b', 'g*b + x*x']]
res2 = [['a*b + d*g', 'a*b + b*g'],
['b*b + d*x', 'b*b + x*b']]
A = ListArray(a)
B = ListArray(b)
Res1 = ListArray(res1)
Res2 = ListArray(res2)
assert(A*A == Res1)
assert(A*B == Res2)
def test_arra_length(self):
A = ListArray(self.a)
assert A.size[0] == len(A)
assert A.size[0] == 4
assert A.size[1] == len(A[0])
assert A.size[1] == 4
if __name__ == '__main__':
unittest.main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T19:11:47.893",
"Id": "455943",
"Score": "3",
"body": "Welcome to CR! You'll want to [edit] your post to tell reviewers more about what `ListArray` does, make the title of your post describe the purpose of that code, and then clean up the variable names, because reviewers are expecting to see your finished, working, production-ready code. As it stands, there's very little context, and it's debatable whether there's enough for reviewers to go on: FYI a reviewer has voted to close for *lack of concrete context*. Please take a few moments to fix the typos and add the missing information; reviewers will be spending much more time than that reviewing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T20:54:55.100",
"Id": "455959",
"Score": "0",
"body": "But it it is just about reviewing second script, I could not attach main script..."
}
] |
[
{
"body": "<p>If you are using the <code>unittest</code> module, you should use it to its full potential. You are already using <code>assertRaises</code>, but there is also <a href=\"https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertEqual\" rel=\"nofollow noreferrer\"><code>assertEqual</code></a>, <a href=\"https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertTrue\" rel=\"nofollow noreferrer\"><code>assertTrue</code></a> and <a href=\"https://docs.python.org/3/library/unittest.html#unittest.TestCase.debug\" rel=\"nofollow noreferrer\">many more</a>. The difference is in the amount of information you get when the test case fails:</p>\n\n<pre><code>import unittest\n\nclass Test(unittest.TestCase):\n def setUp(self):\n self.a, self.b = [1, 2, 3], [2, 3, 4]\n\n def test_a(self):\n assert self.a == self.b\n\n def test_b(self):\n self.assertEqual(self.a, self.b)\n\nif __name__ == \"__main__\":\n unittest.main()\n</code></pre>\n\n<p>produces this output:</p>\n\n<pre><code>$ python3 /tmp/test.py\nFF\n======================================================================\nFAIL: test_a (__main__.Test)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"/tmp/test.py\", line 7, in test_a\n assert self.a == self.b\nAssertionError\n\n======================================================================\nFAIL: test_b (__main__.Test)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"/tmp/test.py\", line 10, in test_b\n self.assertEqual(self.a, self.b)\nAssertionError: Lists differ: [1, 2, 3] != [2, 3, 4]\n\nFirst differing element 0:\n1\n2\n\n- [1, 2, 3]\n+ [2, 3, 4]\n\n----------------------------------------------------------------------\nRan 2 tests in 0.000s\n\nFAILED (failures=2)\n</code></pre>\n\n<p>Note how <code>test_a</code>, which uses <code>assert</code> like your code, gives you almost no information on what went wrong, whereas <code>test_b</code> tells you very explicitly what went wrong.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T14:06:24.833",
"Id": "456238",
"Score": "0",
"body": "Yes, thanks, I have forget about it :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T13:59:07.017",
"Id": "233334",
"ParentId": "233288",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "233334",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T19:05:09.417",
"Id": "233288",
"Score": "2",
"Tags": [
"python",
"unit-testing"
],
"Title": "Unit tests of matrix arithmetic"
}
|
233288
|
<p>I am trying to practice <a href="https://en.wikipedia.org/wiki/Object-oriented_programming" rel="nofollow noreferrer">OOP</a> and <a href="https://en.wikipedia.org/wiki/Test-driven_development" rel="nofollow noreferrer">TDD</a> concepts,
I have written this code for Mars rover challenge from
<a href="https://code.google.com/archive/p/marsrovertechchallenge" rel="nofollow noreferrer">marsrovertechchallenge</a> .</p>
<p>Can you please review my code from my <a href="https://github.com/SaraElmenshawy/MarsRoverChallenge/tree/master/codechallenge/src" rel="nofollow noreferrer">GitHub</a> repository?</p>
<p>Or you can review the four files below.</p>
<p>This would be really helpful for me to improve my <a href="https://en.wikipedia.org/wiki/Object-oriented_programming" rel="nofollow noreferrer">OOP</a> skills.</p>
<p>The MarsRoverCode.java contain the main program which runs the code.</p>
<p>RoverPosition.java contains all the logic with error handling. I think I should structure this in a better way but I don't know what to improve and how.</p>
<p>I created some Test Driven Test Cases using <a href="https://en.wikipedia.org/wiki/JUnit" rel="nofollow noreferrer">JUnit</a> framework. I used parameterized methods for which I don't know if it is the best way or not . I created two classes one for the direct test cases, and one for the exception handling:</p>
<p>MarsRoverTests.java</p>
<p>MarsRoverTestsNegativeSenarios.java</p>
<p>Please let me know what you think this will be very helpful for me to optimize my code.</p>
<p><strong>MarsRoverCode.java</strong></p>
<pre class="lang-java prettyprint-override"><code>package codechallenge;
import java.util.Scanner;
public class MarsRoverCode {
public static void main(String[] args) {
System.out.println("please enter the pleteu dimentions");
Scanner input = new Scanner(System.in);
String plateauDimentions = input.nextLine();
System.out.println("please enter the first rover position and instructions.");
String firstRoverPosition = input.nextLine();
String firstRoverInstructions = input.nextLine();
System.out.println("please enter the second rover position and instructions.");
String secondRoverPosition = input.nextLine();
String secondRoverInstructions = input.nextLine();
input.close();
RoverPosition roverPositionInstruction=new RoverPosition();
roverPositionInstruction.roversFinalPositionAndDirection(plateauDimentions, firstRoverPosition, firstRoverInstructions, secondRoverPosition, secondRoverInstructions);
}
}
</code></pre>
<p><strong>RoverPosition.java</strong></p>
<pre class="lang-java prettyprint-override"><code>package codechallenge;
public class RoverPosition {
public String roversFinalPositionAndDirection(String plateuDimentionsInput, String rover1Position, String rover1Instructions, String rover2Position, String rover2Instructions) {
validateInputsAreNotEmptyOrNegative(plateuDimentionsInput, rover1Position, rover1Instructions);
validateInputsAreNotEmptyOrNegative(plateuDimentionsInput, rover2Position, rover2Instructions);
validateRoversStartPositionNotIntersected(rover1Position, rover2Position);
validatePositionOfRoverCannotBeOutsidePlateu(plateuDimentionsInput, rover1Position);
validatePositionOfRoverCannotBeOutsidePlateu(plateuDimentionsInput, rover2Position);
String finalPosition1 = roverPositionAndDirection(plateuDimentionsInput, rover1Position, rover1Instructions);
String finalPosition2 = roverPositionAndDirection(plateuDimentionsInput, rover2Position, rover2Instructions);
String finalPositionRover1Rover2=finalPosition1+"\n"+finalPosition2;
validatePositionOfRoverCannotBeOutsidePlateu(plateuDimentionsInput, finalPosition1);
validatePositionOfRoverCannotBeOutsidePlateu(plateuDimentionsInput, finalPosition2);
validateRoverDirection(rover1Position);
validateRoverDirection(rover2Position);
validateRoversPositionToNotIntersect( finalPosition1, finalPosition2,rover2Position,rover1Position);
return finalPositionRover1Rover2;
}
private String roverPositionAndDirection(String plateuDimentionsInput, String roverPosition, String roverInstructions) {
String [] directionArr={"N","E","S","W"};
String roverInitialDirection=roverPosition.split(" ")[2];
int[] arr = extractXAndYAxisOfRovers(roverPosition);
int roverX=arr[0];
int roverY=arr[1];
int directionIndex=0;
directionIndex = getInitialDirectionIndex(directionArr, roverInitialDirection, directionIndex);
for (int s=0;s<roverInstructions.length();s++){
String currentDirection=directionArr[directionIndex];
if(s==0&&roverInstructions.charAt(s)=='M'){
if(currentDirection.equals("N"))
roverY++;
else if(currentDirection.equals("S"))
roverY--;
else if(currentDirection.equals("E"))
roverX++;
else if(currentDirection.equals("W"))
roverX--;
}
directionIndex = moveDirectionRL(roverInstructions, directionArr, directionIndex, s);
currentDirection=directionArr[directionIndex];
char nextChar = 0;
if(s!=roverInstructions.length()-1)
nextChar=roverInstructions.charAt(s+1);
if(nextChar=='M'){
if(currentDirection.equals("N"))
roverY++;
else if(currentDirection.equals("S"))
roverY--;
else if(currentDirection.equals("E"))
roverX++;
else if(currentDirection.equals("W"))
roverX--;
}
}
String finalPosition=roverX+" "+roverY+" "+directionArr[directionIndex];
return finalPosition;
}
private int getInitialDirectionIndex(String[] directionArr, String roverInitialDirection, int directionIndex) {
for(int i=0;i<directionArr.length;i++){
if(directionArr[i].equals(roverInitialDirection)){
directionIndex=i;
break;
}
}
return directionIndex;
}
private int moveDirectionRL(String roverInstructions, String[] directionArr, int directionIndex, int s) {
if(roverInstructions.charAt(s)=='R'){
if(directionIndex==directionArr.length-1)
directionIndex=0;
else
directionIndex++;
}
else if (roverInstructions.charAt(s)=='L'){
if(directionIndex==0)
directionIndex=directionArr.length-1;
else
directionIndex--;
}
return directionIndex;
}
private void validateRoversStartPositionNotIntersected(String rover1Position, String rover2Position) {
int[] arr1 = extractXAndYAxisOfRovers(rover1Position);
int[] arr2 = extractXAndYAxisOfRovers(rover2Position);
int rover1X=arr1[0];
int rover1Y=arr1[1];
int rover2X=arr2[0];
int rover2Y= arr2[1];
if(rover1X==rover2X&&rover1Y==rover2Y){
throw new IllegalArgumentException("Error: Both Rovers cannot start in the same position.");
}
}
private int[] extractXAndYAxisOfRovers( String roverPosition) {
int roverX=0;
int roverY=0;
roverX=Integer.parseInt(roverPosition.split(" ")[0]);
roverY=Integer.parseInt(roverPosition.split(" ")[1]);
int arr[]= new int[4];
arr[0]=roverX;
arr[1]=roverY;
return arr;
}
private void validateRoversPositionToNotIntersect(String finalPosition1,String finalPosition2,String rover2Position, String rover1Position) {
int[] arr2 = extractXAndYAxisOfRovers(rover2Position);
int rover2X=arr2[0];
int rover2Y= arr2[1];
int rover1FinalX=Integer.parseInt(finalPosition1.split(" ")[0]);
int rover1FinalY=Integer.parseInt(finalPosition1.split(" ")[1]);
int rover2FinalX=Integer.parseInt(finalPosition2.split(" ")[0]);
int rover2FinalY=Integer.parseInt(finalPosition2.split(" ")[1]);
if((rover1FinalX==rover2X &&rover1FinalY==rover2Y)||(rover2FinalX==rover1FinalX&&rover2FinalY==rover1FinalY))
{
throw new IllegalArgumentException("Error: Rovers positions cannot intersect.");
}
}
private void validateRoverDirection(String roverPosition) {
if(!roverPosition.contains("N")&&!roverPosition.contains("S")&&!roverPosition.contains("E")&&!roverPosition.contains("W"))
{
throw new IllegalArgumentException("Error: Rover position must be N S W or E.");
}
}
private void validatePositionOfRoverCannotBeOutsidePlateu(String plateuDimentionsInput, String roverPosition) {
int[] arr = extractXAndYAxisOfRovers(roverPosition);
int roverX=arr[0];
int roverY=arr[1];
int plateuX=Integer.parseInt(plateuDimentionsInput.split(" ")[0]);
int plateuY=Integer.parseInt(plateuDimentionsInput.split(" ")[1]);
if(roverX>plateuX||roverY>plateuY)
{
throw new IllegalArgumentException("Error: The position of the rover cannot be outside the dimentions of the plateu");
}
}
private void validateInputsAreNotEmptyOrNegative(String plateuDimentionsInput, String roverPosition,String roverInstructions) {
if(roverPosition.isEmpty()||roverPosition.contains("-"))
throw new IllegalArgumentException("Error: Rover position cannot be empty or contain any negative number and the position must be N S W or E.");
else if(plateuDimentionsInput.isEmpty()||plateuDimentionsInput.contains("-"))
throw new IllegalArgumentException("Error: Plateu dimentions cannot be empty or contain any negative number.");
else if(roverInstructions.isEmpty())
throw new IllegalArgumentException("Error: Instructions cannot be empty.");
}
}
</code></pre>
<p><strong>MarsRoverTest.java</strong></p>
<pre class="lang-java prettyprint-override"><code>package codechallenge;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class MarsRoverTests {
RoverPosition marsRover=new RoverPosition();
private String plateuDimentionsInput;
private String rover1Position;
private String rover1Instructions;
private String rover2Position;
private String rover2Instructions;
private String expectedoutput;
public MarsRoverTests(String plateuDimentionsInput,String rover1Position,String rover1Instructions,String rover2Position,String rover2Instructions, String expectedoutput) {
this.plateuDimentionsInput=plateuDimentionsInput;
this.rover1Instructions=rover1Instructions;
this.rover1Position=rover1Position;
this.rover2Instructions=rover2Instructions;
this.rover2Position=rover2Position;
this.expectedoutput = expectedoutput;
}
@Parameters
public static Collection<Object[]> testConditions(){
return Arrays.asList(new Object[][] {
{ "5 5","1 2 N","LMLMLMLMM","3 3 E","MMRMMRMRRM", "1 3 N\n5 1 E" },
{ "5 5","3 3 E","MMRMMRMRRM","1 2 N","LMLMLMLMM", "5 1 E\n1 3 N" },
{ "1000 1000","10 7 S","MMMMMMRLMLLL","3 3 E","MMRMMRMRRM", "10 0 W\n5 1 E" },
{ "20 20","3 3 W","MMRMMRMRRMS","10 7 S","MMMMMMRLMLLL", "1 5 W\n10 0 W" }
});
}
@Test
public void testRoverPosition() {
assertEquals(expectedoutput, marsRover.roversFinalPositionAndDirection(plateuDimentionsInput,rover1Position,rover1Instructions,rover2Position,rover2Instructions));
}
}
</code></pre>
<p><strong>MarsRoverTestsNegativeSenarios.java</strong></p>
<pre class="lang-java prettyprint-override"><code>package codechallenge;
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class MarsRoverTestsNegativeSenarios {
RoverPosition marsRover=new RoverPosition();
private String plateuDimentionsInput;
private String rover1Position;
private String rover1Instructions;
private String rover2Position;
private String rover2Instructions;
private String expectedoutput;
public MarsRoverTestsNegativeSenarios(String plateuDimentionsInput, String rover1Position,
String rover1Instructions, String rover2Position,
String rover2Instructions, String expectedoutput) {
this.plateuDimentionsInput = plateuDimentionsInput;
this.rover1Position = rover1Position;
this.rover1Instructions = rover1Instructions;
this.rover2Instructions=rover2Instructions;
this.rover2Position=rover2Position;
this.expectedoutput = expectedoutput;
}
@Parameters
public static Collection<Object[]> testConditions(){
return Arrays.asList(new Object[][] {
{ "5 5","3 3 X","MMRMMRMRRM","3 4 E","MMRMMRMRRM", "Error: Rover position must be N S W or E." },
{ "-5 -5","3 3 E","MMRMMRMRRM","3 4 E","MMRMMRMRRM", "Error: Plateu dimentions cannot be empty or contain any negative number." },
{ "5 5","-3 3 E","MMRMMRMRRM","3 3 E","MMRMMRMRRM", "Error: Rover position cannot be empty or contain any negative number and the position must be N S W or E."},
{ "5 5","3 3 E","MMRMMRMRRM","-3 3 E","MMRMMRMRRM", "Error: Rover position cannot be empty or contain any negative number and the position must be N S W or E."},
{ "10 10","20 3 E","MMRMMRMRRM","3 3 E","MMRMMRMRRM", "Error: The position of the rover cannot be outside the dimentions of the plateu" },
{ "10 10","3 3 E","MMRMMRMRRM","20 3 E","MMRMMRMRRM", "Error: The position of the rover cannot be outside the dimentions of the plateu" },
{ "10 10","10 3 E","MMRMMRMRRM","3 3 E","MMRMMRMRRM", "Error: The position of the rover cannot be outside the dimentions of the plateu" },
{ "10 10","10 3 E","","3 3 E","MMRMMRMRRM", "Error: Instructions cannot be empty." },
{ "10 10","","MMRMMRMRRM","3 3 E","MMRMMRMRRM", "Error: Rover position cannot be empty or contain any negative number and the position must be N S W or E." },
{ "","10 3 E","MMRMMRMRRM","3 3 E","MMRMMRMRRM", "Error: Plateu dimentions cannot be empty or contain any negative number." },
{ "5 5","1 2 N","LMLMLMLMM","1 2 E","MMRMMRMRRM", "Error: Both Rovers cannot start in the same position." },
{ "5 5","1 2 N","LMLMLMLMM","1 3 N","MMRMMRMRRM", "Error: Rovers positions cannot intersect." },
{ "5 5","1 2 N","LMLMLMLMM","3 3 E","MMRMMRMRRMLMMLMMMM", "Error: Rovers positions cannot intersect." }
});
}
@Test(expected=IllegalArgumentException.class)
public void testRoverPositionNegativeSenarios() {
try
{
assertEquals(expectedoutput, marsRover.roversFinalPositionAndDirection(plateuDimentionsInput,rover1Position,rover1Instructions,rover2Position,rover2Instructions));
}
catch(IllegalArgumentException re)
{
assertEquals(expectedoutput, re.getMessage());
throw re;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Welcome to our community. First of all your <code>roverPositionAndDirection()</code> method, and <code>MarsRoverTestsNegativeSenarios()</code> and <code>MarsRoverTests()</code> constructors have to many parameters. Use up to two or if you absolutely need at most three, but mostly only just one. This is needed for the code to be more clear. Maybe you should use a custom data object to be used as a parameter for these methods, some kind of <code>RoverCommand</code> class that contains <code>String plateuDimentionsInput, String rover1Position, String rover1Instructions, String rover2Position, String rover2Instructions</code>.</p>\n\n<p>For this kind of code best use <code>switch</code> rather than <code>if</code> statements for more readability.</p>\n\n<pre><code>if(currentDirection.equals(\"N\"))\n roverY++;\nelse if(currentDirection.equals(\"S\"))\n roverY--;\nelse if(currentDirection.equals(\"E\"))\n roverX++;\nelse if(currentDirection.equals(\"W\"))\n roverX--;\n</code></pre>\n\n<p>And here I see code duplication.</p>\n\n<pre><code>directionIndex = getInitialDirectionIndex(directionArr, roverInitialDirection, directionIndex);\n for (int s=0;s<roverInstructions.length();s++){\n String currentDirection=directionArr[directionIndex];\n if(s==0&&roverInstructions.charAt(s)=='M'){\n if(currentDirection.equals(\"N\"))\n roverY++;\n else if(currentDirection.equals(\"S\"))\n roverY--;\n else if(currentDirection.equals(\"E\"))\n roverX++;\n else if(currentDirection.equals(\"W\"))\n roverX--;\n }\n directionIndex = moveDirectionRL(roverInstructions, directionArr, directionIndex, s);\n currentDirection=directionArr[directionIndex];\n char nextChar = 0;\n if(s!=roverInstructions.length()-1)\n nextChar=roverInstructions.charAt(s+1);\n\n if(nextChar=='M'){\n if(currentDirection.equals(\"N\"))\n roverY++;\n else if(currentDirection.equals(\"S\"))\n roverY--;\n else if(currentDirection.equals(\"E\"))\n roverX++;\n else if(currentDirection.equals(\"W\"))\n roverX--;\n }\n }\n</code></pre>\n\n<p>You should make a method that is uses to calculate any direction, and not to write the same code multiple times. </p>\n\n<p>In <code>if</code> statement it is preferred to use <code>boolean</code> methods, again for more clear code.</p>\n\n<p>So instead of:</p>\n\n<pre><code>if(roverX>plateuX||roverY>plateuY)\n {\n throw new IllegalArgumentException(\"Error: The position of the rover cannot be outside the dimentions of the plateu\");\n }\n</code></pre>\n\n<p>You should have:</p>\n\n<pre><code>if(!isOnThePlateu())\n{\n throw new IllegalArgumentException(\"Error: The position of the rover cannot be outside the dimentions of the plateu\");\n}\n\nprivate boolean isOnThePlateu()\n{\n return roverX>plateuX||roverY>plateuY;\n}\n</code></pre>\n\n<p>Overall your code looks far to complex for it's simple task. Hope this helps you to improve yourself in coding.</p>\n\n<p>I suggest you use <a href=\"https://github.com/\" rel=\"nofollow noreferrer\">GitHub</a> if you don't already use it, and than in the <a href=\"https://github.com/marketplace\" rel=\"nofollow noreferrer\">Marketplace</a> page you should subscribe to <a href=\"https://codebeat.co/\" rel=\"nofollow noreferrer\">CodeBeat</a>, <a href=\"https://app.codacy.com/\" rel=\"nofollow noreferrer\">Codacy</a> and <a href=\"https://bettercodehub.com/\" rel=\"nofollow noreferrer\">BetterCodeHub</a> apps for <a href=\"https://en.wikipedia.org/wiki/Automated_code_review\" rel=\"nofollow noreferrer\">automated code review</a>. It is free of charge for public repositories. It is very helpful. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T08:51:30.557",
"Id": "233394",
"ParentId": "233294",
"Score": "2"
}
},
{
"body": "<p>You did a good job. Program does what it should and you are validating your values, which is important. As for the issues I must say that this program is not object oriented. As in not at all. It is one big procedure with some sub-procedures. While this might be ok when the program is some kind of one-time effort that is not supposed to change, in the real world programs and their requirements tend to change. This change is what OOP can help you manage.</p>\n\n<p>First issue that strikes the eyes is what is called <a href=\"https://wiki.c2.com/?StringlyTyped\" rel=\"nofollow noreferrer\">Stringly Typed</a> programming(Also called primitive obsession. One of so called design smells). It is something you will encounter very often. The problem is, that even though the Java is strongly typed language people often encode logic into Strings and other primitive types. Instead of encoding everything as a String you should introduce types that will represent those pieces of logic within your codebase.</p>\n\n<p>Looking at the challenge description there are a couple concepts you could start with. Obvious ones are Instructions, Position of the rover which works with its sub-concepts a Coordinate and a Direction. </p>\n\n<p>I quickly went through the code and extracted all position related code into a Position class which represents a position of a rover and produces a new position based on the incoming instruction. Notice that it is still quite ugly piece of code. This is because it does too many things. I.E. it does not have a single responsibility.</p>\n\n<pre><code>class Position {\n private final int x;\n private final int y;\n private final char direction;\n\n Position(final int x, final int y, final char direction) {\n this.x = x;\n this.y = y;\n this.direction = direction;\n }\n\n public Position move(final char instruction) {\n final int x;\n final int y;\n final char direction;\n if (instruction == 'M') {\n direction = this.direction;\n if(this.direction == 'N') {\n y = this.y + 1;\n x = this.x;\n } else if(this.direction == 'S') {\n y = this.y - 1;\n x = this.x;\n } else if(this.direction == 'E') {\n x = this.x + 1;\n y = this.y;\n } else if(this.direction == 'W') {\n x = this.x - 1;\n y = this.y;\n } else {\n throw new IllegalArgumentException(\"Unknown direction\");\n }\n } else if (instruction == 'R') {\n x = this.x;\n y = this.y;\n if (this.direction == 'N') {\n direction = 'E';\n } else if (this.direction == 'S') {\n direction = 'W';\n } else if (this.direction == 'E') {\n direction = 'S';\n } else if (this.direction == 'W') {\n direction = 'N';\n } else {\n throw new IllegalArgumentException(\"Unknown direction\");\n }\n } else if (instruction == 'L') {\n x = this.x;\n y = this.y;\n if (this.direction == 'N') {\n direction = 'W';\n } else if (this.direction == 'S') {\n direction = 'E';\n } else if (this.direction == 'E') {\n direction = 'N';\n } else if (this.direction == 'W') {\n direction = 'S';\n } else {\n throw new IllegalArgumentException(\"Unknown direction\");\n }\n } else {\n throw new IllegalArgumentException(\"Unknown instruction\");\n }\n return new Position(x, y, direction);\n }\n}\n</code></pre>\n\n<p>If you extract these additional responsibilities into their respective classes you could end up with something like this:</p>\n\n<pre><code>class Position {\n private final Coordinate coordinate;\n private final Direction direction;\n\n Position(final Coordinate coordinate, final Direction direction) {\n this.coordinate = coordinate;\n this.direction = direction;\n }\n\n public Position move(final Instruction instruction) {\n final Direction direction = this.direction.turn(instruction);\n final Coordinate coordinate;\n if (instruction == Instruction.Move) {\n coordinate = this.coordinate.move(direction);\n } else {\n coordinate = this.coordinate;\n }\n return new Position(coordinate, direction);\n }\n}\n\nclass Coordinate {\n private final int x;\n private final int y;\n\n Coordinate(final int x, final int y) {\n this.x = x;\n this.y = y;\n }\n public Coordinate move(final Direction direction) {\n final int x;\n final int y;\n if(direction == Direction.North) {\n y = this.y + 1;\n x = this.x;\n } else if(direction == Direction.South) {\n y = this.y - 1;\n x = this.x;\n } else if(direction == Direction.East) {\n x = this.x + 1;\n y = this.y;\n } else if(direction == Direction.West) {\n x = this.x - 1;\n y = this.y;\n } else {\n throw new IllegalArgumentException(\"Unknown direction\");\n }\n return new Coordinate(x, y);\n }\n\n}\n\nenum Instruction {\n Move('M'),\n Left('L'),\n Right('R');\n\n private static final Map<Character, Instruction> LOOKUP = new HashMap<>();\n\n private final Character symbol;\n\n Instruction(final Character symbol) {\n this.symbol = symbol;\n }\n\n static {\n for (final Instruction i : Instruction.values()) {\n LOOKUP.put(i.symbol, i);\n }\n }\n\n public static Instruction of(final Character symbol) {\n final Instruction instruction = LOOKUP.get(symbol);\n if (instruction == null) {\n throw new IllegalArgumentException(\"Unknown instruction: '\" + symbol + \"'!\");\n }\n return instruction;\n }\n\n}\n\nenum Direction {\n North('N') {\n @Override\n public Direction turn(final Instruction instruction) {\n final Direction direction;\n if (instruction == Instruction.Left) {\n direction = West;\n } else if (instruction == Instruction.Right) {\n direction = East;\n } else {\n direction = North;\n }\n return direction;\n }\n },\n South('S') {\n @Override\n public Direction turn(final Instruction instruction) {\n final Direction direction;\n if (instruction == Instruction.Left) {\n direction = East;\n } else if (instruction == Instruction.Right) {\n direction = West;\n } else {\n direction = South;\n }\n return direction;\n }\n },\n East('E') {\n @Override\n public Direction turn(final Instruction instruction) {\n final Direction direction;\n if (instruction == Instruction.Left) {\n direction = North;\n } else if (instruction == Instruction.Right) {\n direction = South;\n } else {\n direction = East;\n }\n return direction;\n }\n },\n West('W') {\n @Override\n public Direction turn(final Instruction instruction) {\n final Direction direction;\n if (instruction == Instruction.Left) {\n direction = South;\n } else if (instruction == Instruction.Right) {\n direction = North;\n } else {\n direction = West;\n }\n return direction;\n }\n };\n\n private static final Map<Character, Direction> LOOKUP = new HashMap<>();\n\n private final Character symbol;\n\n Direction(final Character symbol) {\n this.symbol = symbol;\n }\n\n static {\n for (final Direction d : Direction.values()) {\n LOOKUP.put(d.symbol, d);\n }\n }\n\n public abstract Direction turn(final Instruction instruction);\n\n public static Direction of(final Character symbol) {\n final Direction direction = LOOKUP.get(symbol);\n if (direction == null) {\n throw new IllegalArgumentException(\"Unknown direction: '\" + symbol + \"'!\");\n }\n return direction;\n }\n}\n</code></pre>\n\n<p>These are just examples of what can be done. I haven't tested if everything works and there might be some typos.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-10T14:35:18.323",
"Id": "233790",
"ParentId": "233294",
"Score": "4"
}
},
{
"body": "<p><strong>Console Isolation</strong></p>\n\n<p>You've done a good job separating the console from the actual logic of your code. This small thing makes your code much easier to reuse in different applications.</p>\n\n<p><strong>Parameterised Tests</strong></p>\n\n<p>Parameterised tests can be great for running related tests against test data. However, there's a risk that they can obscure what it is that you're trying to test. So, looking at one of your test cases:</p>\n\n<blockquote>\n<pre><code>{ \"10 10\",\"\",\"MMRMMRMRRM\",\"3 3 E\",\"MMRMMRMRRM\", \"Error: Rover position cannot be empty or contain any negative number and the position must be N S W or E.\" }\n</code></pre>\n</blockquote>\n\n<p>The error message at the end gives you a hint what to look for, however if the test fails, you then have to try and understand which bit(s) of the parameter block are relevant to the failure / test case. A suite of smaller, more targeted tests can be both easier to understand and can encourage you to break down your application into smaller parts.</p>\n\n<p>As has been been mentioned, there's various ways that the application could be broken down. One approach might be to create a <code>CardinalVector</code> class to represent a movement direction/size along the primary compass directions. One way of implementing it might be:</p>\n\n<pre><code>class CardinalVector {\n public final int x;\n public final int y;\n public final String direction;\n\n private final String rotateRightDirection;\n private final String rotateLeftDirection;\n\n private final static Map<String, CardinalVector> cardinalDirections = Map.of(\n \"N\", new CardinalVector(\"N\", 0, 1, \"E\", \"W\"),\n \"E\", new CardinalVector(\"E\", 1, 0, \"S\", \"N\"),\n \"S\", new CardinalVector(\"S\", 0, -1, \"W\", \"E\"),\n \"W\", new CardinalVector(\"W\", -1, 0, \"N\", \"S\"));\n\n private CardinalVector(String direction, int x, int y, \n String rotateRightDirection, String rotateLeftDirection) {\n this.direction = direction;\n this.x = x;\n this.y = y;\n this.rotateRightDirection = rotateRightDirection;\n this.rotateLeftDirection = rotateLeftDirection;\n }\n\n public static CardinalVector of(String direction) {\n return cardinalDirections.get(direction);\n }\n\n public CardinalVector rotated(String rotationDirection) {\n return rotationDirection.equals(\"R\") ? of(rotateRightDirection) \n : of(rotateLeftDirection);\n }\n}\n</code></pre>\n\n<p>As this class represents a smaller subset of the functionality, it's possible to create some more fine-grained unit-tests. For example, when creating a vector for a given direction (NSEW), are the x/y movement fields set correctly:</p>\n\n<pre><code>@ParameterizedTest\n@MethodSource(\"direction_expectedX_expectedY\")\nvoid of_direction_expectedX_expectedY(String direction, int expectedX, int expectedY) {\n CardinalVector north = CardinalVector.of(direction);\n assertThat(north.x).isEqualTo(expectedX);\n assertThat(north.y).isEqualTo(expectedY);\n\n}\n\nstatic Stream<Arguments> direction_expectedX_expectedY() {\n return Stream.of(\n arguments(\"N\", 0, 1),\n arguments(\"E\", 1, 0),\n arguments(\"S\", 0, -1),\n arguments(\"W\", -1, 0)\n );\n}\n</code></pre>\n\n<p>I try to keep my test names following something along the lines of method being tested (of), condition being tested (direction), desired outcome (expectedX, expectedY). By keeping the arguments for the parameterised test in the same order, it can make the test results easier to understand. So, with a test to validate that from a given starting direction, rotating results in a different direction:</p>\n\n<pre><code>@ParameterizedTest\n@MethodSource(\"fromDirection_rotationDirection_expectedDirection\")\nvoid rotated_fromDirection_rotationDirection_expectedDirection(String fromDirection,\n String rotationDirection,\n String expectedDirection) {\n CardinalVector rotatedDirection = CardinalVector.of(fromDirection)\n .rotated(rotationDirection);\n assertThat(rotatedDirection).isEqualTo(CardinalVector.of(expectedDirection));\n}\n\nstatic Stream<Arguments> fromDirection_rotationDirection_expectedDirection() {\n return Stream.of(\n arguments(\"N\", \"R\", \"E\"),\n arguments(\"N\", \"L\", \"W\"),\n arguments(\"E\", \"R\", \"S\"),\n arguments(\"E\", \"L\", \"N\"),\n arguments(\"S\", \"R\", \"W\"),\n arguments(\"S\", \"L\", \"E\"),\n arguments(\"W\", \"R\", \"N\"),\n arguments(\"W\", \"L\", \"S\")\n );\n}\n</code></pre>\n\n<p>In my test runner the output looks like this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/zutaO.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zutaO.png\" alt=\"test results\"></a></p>\n\n<p>You can see that the test name helps to understand each of the inputs / results for the parameterised test runs below.</p>\n\n<p><strong>Some other things to think about</strong></p>\n\n<ul>\n<li><p>The problem description you link to talks about a squad of rovers. So, whilst the the example input/output is for two rovers, I would expect a solution to be able to handle a different number of rovers (1, 3 etc). At the moment, you've got a <code>RoverPosition</code> class that actually tracks the position + instructions for two different rovers, along with the plateau. To add another Rover, we'd need to add another two parameters to the <code>roversFinalPositionAndDirection</code> method, which quickly gets unwieldy.</p></li>\n<li><p>Method names should describe what it is the method does, consequently you'd expect some kind of 'action'. This isn't always the case, for example <code>roverPositionAndDirection</code>. This sounds like the name of a variable that contains the rover's current position and direction, whereas it actually calculates the final position of the rover. This is misleading.</p></li>\n<li>Unused parameters. Don't pass things to methods that you don't need. So, for example <code>roverPositionAndDirection</code> never uses its <code>plateuDimentionsInput</code> parameter.</li>\n<li><p>Redundant variables. Rather than declaring a variable and assigning it a value then immediately returning it, it's often better to just return the assigned value (if the function is named correctly then it should be obvious what's being returned). So, for example, instead of:</p>\n\n<blockquote>\n<pre><code>String finalPosition=roverX+\" \"+roverY+\" \"+directionArr[directionIndex];\nreturn finalPosition;\n</code></pre>\n</blockquote>\n\n<p>Consider</p>\n\n<pre><code>return roverX+\" \"+roverY+\" \"+directionArr[directionIndex];\n</code></pre></li>\n<li><p>Consistency is key... Most modern IDEs are able to format your code for you. Java tends to favour more spacing than some other languages, for me personally, I just like consistency... so rather than:</p>\n\n<blockquote>\n<pre><code>int rover2X=arr2[0];\nint rover2Y= arr2[1];\n</code></pre>\n</blockquote>\n\n<p>Pick a consistent spacing and use it everywhere, or get your IDE to do it for you. Generally, the preference is:</p>\n\n<pre><code>int rover2X = arr2[0];\n</code></pre></li>\n<li><p>Array declarations in java should be: <code>int[] arr = new int[4];</code>, rather than <code>int arr[]= new int[4];</code></p></li>\n<li><p><code>moveDirectionRL</code>, it's great that you've created a method to encapsulate the logic for turning the rover. I would have perhaps gone with rotate or turn to make it clearer what it was responsible for. It would also have been good to do a similar thing to encapsulate the logic for actually moving the rover in it's current direction.</p></li>\n<li><p>Plateau safety... You check if the rover position is outside the top/right, however you don't check if it goes off the bottom/left, so negative positions don't throw an exception. You also only check the rover is outside of the plateau at the beginning and end. So, it's acceptable for the rover to wonder off outside the limits, as long as it comes back. This would obviously be dangerous for an actual rover.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-24T10:19:32.927",
"Id": "237825",
"ParentId": "233294",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T21:31:32.280",
"Id": "233294",
"Score": "5",
"Tags": [
"java",
"object-oriented",
"programming-challenge",
"unit-testing",
"junit"
],
"Title": "Mars Rover technical Challenge in OOP"
}
|
233294
|
<p>I created a simple script that is used to implement Google's Chromecast wallpaper-images as the wallpaper of my Gnome desktop. </p>
<p>The script extract the images from 2 different sources: </p>
<ol>
<li>A static webpage containing a collection of the Chromecast images</li>
<li>A dynamic (javscript driven) webpage that shows a different wallpaper at an interval set by Google. </li>
</ol>
<p>The reasons I use two different sources are:</p>
<ol>
<li>I already had a working script that used only the static page & wanted to challenge myself</li>
<li>When only using the dynamic page somehow the first image when loading that webpage is always the same (or one from a very minor subset with little variation) and I want to see an immediately different wallpaper each time I run the script. </li>
</ol>
<p><strong>My current code looks like this:</strong></p>
<pre><code>#!/usr/bin/env python
"""This script runs in the background to download wallpapers used by Google's
chromecast devices and set them as a desktop wallpaper in Linux environments
using Gnome desktop. The wallpaper that is being set will change
automatically within a given interval."""
import io
import os
import subprocess
import time
from random import shuffle
from bs4 import BeautifulSoup
from PIL import Image
from pyvirtualdisplay import Display
import requests
from selenium import webdriver
from selenium.webdriver import DesiredCapabilities
def first_picture():
"""Retrieve a random image from a non-interactive website. This
will be the first image to which the Gnome desktop will be set. It
will (1) give the user visual feedback that the script is working
and (2) prevent the same image (or minor set of images) to be shown
whenever the script is run."""
request = requests.get('https://github.com/dconnolly/'\
'chromecast-backgrounds')
content = request.content
soup = BeautifulSoup(content, features="lxml")
images = soup.find_all("img")
sourcelist = []
current_dir = os.path.dirname(os.path.realpath(__file__))
for image in images:
if "camo" in image["src"]:
sourcelist.append(image["src"])
# Implemented a try-except because pil_image sometimes raises an error:
# raise IOError("cannot identify image file %r" % (filename if filename
# else fp))
# OSError: cannot identify image file <_io.BytesIO object at
# 0x66d3bea6d3b0>
try:
shuffle(sourcelist)
raw_image = requests.get(sourcelist[0])
pil_image = Image.open(io.BytesIO(raw_image.content))
except IOError:
first_picture()
temp_local_image_location = (current_dir + "/interactive_wallpaper."
+ pil_image.format)
pil_image.save(temp_local_image_location)
subprocess.Popen(["/usr/bin/gsettings", "set",
"org.gnome.desktop.background",
"picture-uri", "'" + temp_local_image_location + "'"],
stdout=subprocess.PIPE)
time.sleep(40)
def change_desktop(image_source):
"""Tap into the dynamic webpage that is displaying a different
wallpapers-like images at a given interval."""
request = requests.get(image_source)
image = Image.open(io.BytesIO(request.content))
image_format = image.format
current_dir = os.path.dirname(os.path.realpath(__file__))
temp_local_image_location = (current_dir + "/interactive_wallpaper."
+ image_format)
image.save(temp_local_image_location)
subprocess.Popen(["/usr/bin/gsettings", "set",
"org.gnome.desktop.background",
"picture-uri", "'" + temp_local_image_location + "'"],
stdout=subprocess.PIPE)
time.sleep(20)
def set_display_and_start_browser():
"""Start virtual display and selenium driver. This is needed
for the selenium-initiated browser to grab the dynamically
loaded images dfrom the webpage"""
display = Display(visible=0, size=(1920, 1080))
display.start()
desired_capabilities = DesiredCapabilities.CHROME.copy()
desired_capabilities['connection'] = "keep-alive"
browser = webdriver.Chrome(desired_capabilities=desired_capabilities)
url = "https://clients3.google.com/cast/chromecast/home/"
browser.get(url)
first_picture()
while True:
element = browser.find_element_by_id("picture-background")
image_source = element.get_attribute("src")
change_desktop(image_source)
time.sleep(20)
</code></pre>
<p>Any tips, insights, remarks, opinions, etc. more then welcome!</p>
<p>Curious to learn what you think. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T23:17:35.967",
"Id": "456312",
"Score": "1",
"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": "2019-12-04T23:55:14.923",
"Id": "456317",
"Score": "0",
"body": "Ah, thanks for the heads-up, happy to learn. I see you've already corrected it, great!"
}
] |
[
{
"body": "<h3><em>Restructuring and corrections</em></h3>\n\n<p>Let's start with <code>first_picture</code> function issues.<br>\nI'd renamed it at least to <strong><code>get_first_picture</code></strong>. <br></p>\n\n<p><code>BeautifulSoup.find_all</code> allows using regular expression to find images tags with <code>src</code> attribute that meets some condition. Thus the condition:</p>\n\n<pre><code>sourcelist = []\n...\n if \"camo\" in image[\"src\"]:\n ...\n</code></pre>\n\n<p>can be eliminated and images are filtered by <strong><code>images = soup.find_all(\"img\", src=re.compile(r'.*camo.*'))</code></strong>.</p>\n\n<p>The <code>except</code> block:</p>\n\n<pre><code>except IOError:\n first_picture()\n</code></pre>\n\n<p>doesn't provide any <em>\"exit\"</em> condition. When the control flow will get into this <code>except</code> block and call the current function <code>first_picture()</code> again - that doesn't mean that all subsequent statements below (from previous context) won't be executed.<br>You would need to either enclose all statements after that block into <strong><code>else:</code></strong> block to make them execute on successful image opening or put <strong><code>return</code></strong> statement right below <code>first_picture()</code> call. </p>\n\n<p><strong>But</strong> instead, what should be noticed beforehand is that both <code>get_first_picture</code> and <code>change_desktop</code> functions share the same common behavior that covers the following set of actions:</p>\n\n<ul>\n<li>extracting image from remote resource</li>\n<li>saving image</li>\n<li>setting desktop background in separate <code>subprocess</code></li>\n</ul>\n\n<p>The time delay is also has a common amount - <code>40</code> (In your <code>set_display_and_start_browser</code> function <code>time.sleep(20)</code> + <code>time.sleep(20)</code>, are indirectly added).<br><br>\nThat definitely calls for <strong><em>Extract function</em></strong> technique - the common/repeated behavior is extracted into a separate function, say <strong><code>set_desktop_background</code></strong>:</p>\n\n<pre><code>def set_desktop_background(image_source):\n \"\"\"Tap into the dynamic webpage that is displaying a different\n wallpapers-like images at a given interval.\"\"\"\n\n request = requests.get(image_source)\n image = Image.open(io.BytesIO(request.content))\n image_format = image.format\n current_dir = os.path.dirname(os.path.realpath(__file__))\n temp_local_image_location = f'{current_dir}/interactive_wallpaper.{image_format}'\n image.save(temp_local_image_location)\n subprocess.Popen([\"/usr/bin/gsettings\", \"set\",\n \"org.gnome.desktop.background\",\n \"picture-uri\", f\"'{temp_local_image_location}'\"],\n stdout=subprocess.PIPE)\n time.sleep(40)\n</code></pre>\n\n<p>Now <code>change_desktop</code> function is removed in favor of <code>set_desktop_background</code> function.</p>\n\n<p>As for your mentioned periodical error <code>OSError: cannot identify image file ...</code> - I believe that can be fixed separately and is related to whether some particular image type or truncated image or failing to save image; you may find various fixes online. </p>\n\n<p>The <strong><code>get_first_picture</code></strong> function is now shortened to the following:</p>\n\n<pre><code>def get_first_picture():\n \"\"\"Retrieve a random image from a non-interactive website. This \n will be the first image to which the Gnome desktop will be set. It \n will (1) give the user visual feedback that the script is working \n and (2) prevent the same image (or minor set of images) to be shown\n whenever the script is run.\"\"\"\n\n request = requests.get('https://github.com/dconnolly/chromecast-backgrounds') \n soup = BeautifulSoup(request.content, features=\"lxml\")\n images = soup.find_all(\"img\", src=re.compile(r'.*camo.*'))\n sourcelist = [image[\"src\"] for image in images]\n\n shuffle(sourcelist)\n set_desktop_background(sourcelist[0])\n</code></pre>\n\n<hr>\n\n<p><code>set_display_and_start_browser</code> is a bad pattern for function naming as it points to excessive responsibility (the function doing too much). <br>It's better to split it into a separate functions (considering all above optimizations):</p>\n\n<p><strong><code>start_display</code></strong> function:</p>\n\n<pre><code>def start_display():\n display = Display(visible=0, size=(1920, 1080))\n display.start()\n</code></pre>\n\n<p><strong><code>start_browser</code></strong> function:</p>\n\n<pre><code>def start_browser():\n \"\"\"Start selenium driver. This is needed\n for the selenium-initiated browser to grab the dynamically\n loaded images from the webpage.\n \"\"\"\n desired_capabilities = DesiredCapabilities.CHROME.copy()\n desired_capabilities['connection'] = \"keep-alive\"\n browser = webdriver.Chrome(desired_capabilities=desired_capabilities)\n url = \"https://clients3.google.com/cast/chromecast/home/\"\n browser.get(url)\n return browser\n</code></pre>\n\n<p>and <strong><code>load_images_to_desktop</code></strong> function (as the main <em>supervisor</em> function):</p>\n\n<pre><code>def load_images_to_desktop():\n start_display()\n browser = start_browser()\n get_first_picture()\n\n while True:\n element = browser.find_element_by_id(\"picture-background\")\n image_source = element.get_attribute(\"src\")\n set_desktop_background(image_source)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T23:06:22.813",
"Id": "456309",
"Score": "0",
"body": "Wow, thanks for your very extended and clear answer! Not only did it help me gain some extra insights into my own piece of code & some of the concepts you explicitly mentioned in your answer. But it also sneaked in some other interesting things I didn't yet know about like [Python f-strings](https://realpython.com/python-f-strings/)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T23:12:06.510",
"Id": "456310",
"Score": "0",
"body": "@Montmons, great, I'm glad you liked it. BTW, I noticed a lot of beautiful pictures on that repository :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T00:18:40.107",
"Id": "233301",
"ParentId": "233295",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "233301",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T21:37:05.163",
"Id": "233295",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"selenium"
],
"Title": "Using Python & Selenium to set Gnome desktop to Google's Chromecast wallpapers"
}
|
233295
|
<p>I've been trying to remember old programming concepts like data structures.</p>
<p>My first challenge was about implementing my own array of positive integers:</p>
<pre><code>#include<stdio.h>
#include<stdlib.h>
int* array_initialize(int size) {
return calloc(size, size * sizeof(int));
}
void array_set(int *array, int index, int value) {
array += index;
*array = value;
}
int array_get(int *array, int index) {
array += index;
return *array;
}
int array_size(int *array) {
int size = 0;
while(*array != 0) {
size++;
array++;
}
return size;
}
int main() {
int* array = array_initialize(5);
array_set(array, 0, 2);
array_set(array, 1, 4);
array_set(array, 2, 6);
array_set(array, 3, 8);
array_set(array, 4, 10);
for (int i = 0; i < array_size(array); i++) {
printf("Index #%d -> %d\n", i, array_get(array, i));
}
printf("\nSize: %d\n", array_size(array));
free(array);
return 0;
}
</code></pre>
<p>Can I call it an array?</p>
<p>Is it a good starting point? What would you change?</p>
<p>Can I implement my custom array with <code>[]</code> to read/write values to my array?</p>
|
[] |
[
{
"body": "<p>Your array set could be written as <code>*(array + index) = value;</code> and your array get could be written as <code>return *(array + index);</code>.</p>\n\n<p><code>array[index]</code> could also be written as <code>*(array + index)</code>. Those two functions don't do anything you can't already do with <code>[]</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T16:30:30.837",
"Id": "456058",
"Score": "0",
"body": "Why do you suggest to write `*(array + index)` instead of the much more beautiful `array[index]`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T16:44:35.047",
"Id": "456061",
"Score": "0",
"body": "I don't. I was trying to illustrate the point that those two functions were the equivalent of writing `array[index]`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T23:26:10.277",
"Id": "233297",
"ParentId": "233296",
"Score": "3"
}
},
{
"body": "<h2>Error Checking</h2>\n<p>When using <code>malloc()</code>, <code>calloc()</code> or <code>realloc()</code> in C make sure to check the return value before using the memory, if any of these functions fail they return <code>NULL</code>. Accessing memory through a <code>NULL</code> pointer causes unknown behavior, the best you can hope for is the program crashes, the worst in the point corrupts memory yielding incorrect results.</p>\n<pre><code>int* array_initialize(int size) {\n int *array = calloc(size, size * sizeof(int));\n if (array == NULL)\n {\n fprintf(stderr, "calloc failed in array_initialize\\n");\n exit(EXIT_FAILURE);\n }\n}\n</code></pre>\n<p>The function <code>array_size()</code> is not safe, if the array is completely full, the pointer will walk off the end of the array and into other memory. The code should pass the maximum size of the array into the function as well and limit the while loop.</p>\n<p>A better implementation might be to use a struct that contains the size of the memory allocated as well as the memory allocated.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T12:51:58.363",
"Id": "233330",
"ParentId": "233296",
"Score": "1"
}
},
{
"body": "<h1>Is it a good starting point?</h1>\n<p>A starting point for what?\nThe only obvious purpose for code like this is to provide error checking for accidentally indexing out of bounds, but this code doesn't do that.</p>\n<p>And note that <code>free(array)</code> makes assumptions about the implementation.\nThere should be an <code>array_free(array)</code> function that can be internally changed in future development without affecting any calling code.</p>\n<h1>Can I implement my custom array with [] to read/write values to my array?</h1>\n<p>Yes, but that's exactly what you <em>don't</em> want to do.</p>\n<p>The most significant problem with this design is that it returns a value that the caller can use with <code>[…]</code>.\nThat allows it to bypass the error checking (which I assume will eventually be added).</p>\n<p>The type returned should be something that is incompatible with accidental misuse.\nIf someone calls array_set() with an argument that wasn't created by array_initialize(), you want that mistake caught at compile time, not\nduring critical execution time.</p>\n<h1>Can I call it an array?</h1>\n<p>Yes, but it's not a generic array; it is an array of <code>(int)</code>.</p>\n<p>And, note that storing a zero value in the array will break <code>array_size()</code>.</p>\n<hr />\n<p>You're going in the right direction, but started on the wrong foot.</p>\n<p>Define your basic data structure first, and then the rest of the design should flow naturally from that.\ne.g.</p>\n<pre><code>typedef struct {\n size_t size;\n size_t used;\n int *value;\n} intArray;\n</code></pre>\n<p>Now it becomes obvious that the initialization function needs to allocate <code>*value</code> and should return a pointer to an <code>intArray</code> structure:</p>\n<pre><code> intArray *\nintArray_initialize(int size) {\n …\n}\n</code></pre>\n<p>Then in <code>intArray_set()</code> and <code>intArray_get()</code> add code to verify that <code>0 <= index < size</code>.</p>\n<p>And <code>intArray_size()</code> becomes trivial: <code>array->used</code>.</p>\n<p>Finally, <code>intArray_free(intArray *array)</code> will need to free both <code>array->value</code> and <code>*array</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T16:33:34.000",
"Id": "456060",
"Score": "0",
"body": "Just a small addition. This data structure is exactly what is called a slice in the Go programming language. [Here's an article with more details.](https://blog.golang.org/go-slices-usage-and-internals)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T01:35:07.683",
"Id": "456160",
"Score": "0",
"body": "@RolandIllig, interesting. A reading of that article suggests that the next thing the OP can add to the module is a function to grow an existing array. Then perhaps an addAnElementAndGrowIfNecessary() function."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T14:50:23.287",
"Id": "233339",
"ParentId": "233296",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T22:46:22.630",
"Id": "233296",
"Score": "2",
"Tags": [
"algorithm",
"c",
"array"
],
"Title": "My own array implementation in C"
}
|
233296
|
<p>I'm new in Prolog. So, I'm not sure if my code is ok and optimized. I'm also not sure if I use recursion correctly.</p>
<p>Task: find students that has at least 1 bad grade (1 or 2) and print them in table</p>
<pre><code>
hasBadGrades(N) :- student(_, N, G), containsBadGrades(G).
containsBadGrades([H|T]) :- wildcard_match('*/[1-2]', H); containsBadGrades(T).
printStudent(N, I) :- student(G, N, [M, C, O, P]),
format("| ~a~t~5+ | ~a~t~5+ | ~a~t~16+ | ~a, ~a, ~a, ~a~t~41+ |~n", [I, G, N, M, C, O, P]).
printTHead :-
printLine(),
format("| ~a~t~5+ | ~a~t~5+ | ~a~t~16+ | ~a~t~40+ |~n", ['#', group, name, grades]),
printLine().
printLine :- format("|~`-t~70||~n").
printList([S|T], N) :- printStudent(S, N), printLine(), K is N + 1, printList(T, K).
printFaildStudents :- printTHead(), setof(N, hasBadGrades(N), L), printList(L, 1).
student(1050, adams, ['math/4', 'c++/3', 'oop/4', 'physics/3']).
student(2100, alexander, ['math/3', 'c++/2', 'oop/4', 'physics/3']).
student(3151, allen, ['math/3', 'c++/4', 'oop/3', 'physics/3']).
student(4200, anderson, ['math/3', 'c++/2', 'oop/2', 'physics/3']).
student(5250, bailey, ['math/4', 'c++/3', 'oop/3', 'physics/4']).
student(1050, baker, ['math/3', 'c++/3', 'oop/4', 'physics/2']).
student(2100, barnes, ['math/4', 'c++/3', 'oop/3', 'physics/2']).
student(3151, bell, ['math/4', 'c++/3', 'oop/4', 'physics/4']).
student(4200, bennett, ['math/4', 'c++/3', 'oop/4', 'physics/3']).
student(5250, brooks, ['math/4', 'c++/3', 'oop/3', 'physics/3']).
student(1050, brown, ['math/3', 'c++/4', 'oop/4', 'physics/2']).
student(1050, flores, ['math/4', 'c++/3', 'oop/4', 'physics/3']).
student(2100, foster, ['math/4', 'c++/4', 'oop/3', 'physics/4']).
student(3151, garcia, ['math/3', 'c++/3', 'oop/2', 'physics/3']).
student(4200, gonzales, ['math/3', 'c++/4', 'oop/4', 'physics/3']).
student(5250, gonzalez, ['math/4', 'c++/2', 'oop/3', 'physics/3']).
student(1050, gray, ['math/3', 'c++/4', 'oop/3', 'physics/4']).
student(2100, green, ['math/2', 'c++/4', 'oop/1', 'physics/4']).
% . . .
</code></pre>
<p><a href="https://i.stack.imgur.com/M2u2p.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/M2u2p.png" alt="enter image description here"></a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T23:35:51.483",
"Id": "233298",
"Score": "2",
"Tags": [
"prolog"
],
"Title": "Simple task with recursion on Prolog"
}
|
233298
|
<p>I wrote a program which solves <a href="https://en.wikipedia.org/wiki/Pentomino" rel="noreferrer">Pentomino</a> puzzles by using <a href="https://en.wikipedia.org/wiki/Knuth%27s_Algorithm_X" rel="noreferrer">Knuth's Algorithm X</a>. My priorities were: readability, straightforwardness and brevity of the solution, so I didn't try to squeeze as much performance as possible by eliminating function calls in some places or similar tricks.</p>
<p><strong>I am interested in:</strong></p>
<ol>
<li><p>The code review. How this code can be better?</p></li>
<li><p>Performance improvement. Do you see a way to increase performance? May be <strong>numpy</strong> can help here? At this moment the fastest version takes <strong>1 hour 57 minutes</strong> on <strong>Intel i5-2500</strong> to find all solutions of <strong>5 x 12</strong> board. The second version is slower by three times, but it is having less of code duplicity, so it is more beautiful in my opinion - what do you think?</p></li>
<li><p>Reducing a code duplicity of the faster version but without of large performance drop, as I have in my second version.</p></li>
</ol>
<h3>Usage:</h3>
<p><strong>5 x 12 board</strong></p>
<pre><code>rows = 5
cols = 12
board = [[0] * cols for _ in range(rows)]
solver = Solver(board, figures, rows, cols, 1)
solver.find_solutions()
</code></pre>
<p><strong>Output</strong> (partial - the first solution only)</p>
<pre><code>The solution № 1
12 12 5 5 5 5 8 8 7 7 7 7
9 12 12 12 5 6 6 8 7 11 3 3
9 9 9 2 6 6 10 8 8 11 3 3
1 9 1 2 6 10 10 10 11 11 11 3
1 1 1 2 2 2 10 4 4 4 4 4
####################################################################
</code></pre>
<p><strong>8 x 8 board with 4 prefilled cells in the middle.</strong></p>
<pre><code>rows = 8
cols = 8
board = [[0] * cols for _ in range(rows)]
board[3][3] = '#'
board[3][4] = '#'
board[4][3] = '#'
board[4][4] = '#'
solver = Solver(board, figures, rows, cols, 1)
solver.find_solutions()
</code></pre>
<p><strong>Output</strong> (partial)</p>
<pre><code>1614 variants have tried
Time has elapsed: 0:00:05.104412
The solution № 1
12 12 4 4 4 4 4 11
6 12 12 12 5 11 11 11
6 6 5 5 5 5 10 11
8 6 6 # # 10 10 10
8 8 8 # # 9 10 7
2 1 8 1 9 9 9 7
2 1 1 1 3 3 9 7
2 2 2 3 3 3 7 7
#################################################################
</code></pre>
<h3>The program</h3>
<p>The slower version's methods are commented out, remove comments to test it (and comment out corresponding methods of the first version).</p>
<pre><code>#!/usr/bin/python3
from time import time
from datetime import timedelta
figures = {
(
(1,1,1,1,1),
),
(
(1,1,1,1),
(1,0,0,0),
),
(
(1,1,1,1),
(0,1,0,0),
),
(
(1,1,1,0),
(0,0,1,1),
),
(
(1,1,1),
(1,0,1),
),
(
(1,1,1),
(0,1,1),
),
(
(1,1,1),
(1,0,0),
(1,0,0)
),
(
(1,1,0),
(0,1,1),
(0,0,1)
),
(
(1,0,0),
(1,1,1),
(0,0,1)
),
(
(0,1,0),
(1,1,1),
(1,0,0)
),
(
(0,1,0),
(1,1,1),
(0,1,0)
),
(
(1,1,1),
(0,1,0),
(0,1,0)
)
}
class Node():
def __init__(self, value):
self.value = value
self.up = None
self.down = None
self.left = None
self.right = None
self.row_head = None
self.col_head = None
class Linked_list_2D():
def __init__(self, width):
self.width = width
self.head = None
self.size = 0
def append(self, value):
new_node = Node(value)
if self.head is None:
self.head = left_neigh = right_neigh = up_neigh = down_neigh = new_node
elif self.size % self.width == 0:
up_neigh = self.head.up
down_neigh = self.head
left_neigh = right_neigh = new_node
else:
left_neigh = self.head.up.left
right_neigh = left_neigh.right
if left_neigh is left_neigh.up:
up_neigh = down_neigh = new_node
else:
up_neigh = left_neigh.up.right
down_neigh = up_neigh.down
new_node.up = up_neigh
new_node.down = down_neigh
new_node.left = left_neigh
new_node.right = right_neigh
# Every node has links to the first node of row and column
# These nodes are used as the starting point to deletion and insertion
new_node.row_head = right_neigh
new_node.col_head = down_neigh
up_neigh.down = new_node
down_neigh.up = new_node
right_neigh.left = new_node
left_neigh.right = new_node
self.size += 1
def print_list(self, separator=' '):
for row in self.traverse_node_line(self.head, "down"):
for col in self.traverse_node_line(row, "right"):
print(col.value, end=separator)
print()
def traverse_node_line(self, start_node, direction):
cur_node = start_node
while cur_node:
yield cur_node
cur_node = getattr(cur_node, direction)
if cur_node is start_node:
break
### First approach - a lot of code duplicity
def col_nonzero_nodes(self, node):
cur_node = node
while cur_node:
if cur_node.value and cur_node.row_head is not self.head:
yield cur_node
cur_node = cur_node.down
if cur_node is node:
break
def row_nonzero_nodes(self, node):
cur_node = node
while cur_node:
if cur_node.value and cur_node.col_head is not self.head:
yield cur_node
cur_node = cur_node.right
if cur_node is node:
break
def delete_row(self, node):
cur_node = node
while cur_node:
up_neigh = cur_node.up
down_neigh = cur_node.down
if cur_node is self.head:
self.head = down_neigh
if cur_node is down_neigh:
self.head = None
up_neigh.down = down_neigh
down_neigh.up = up_neigh
cur_node = cur_node.right
if cur_node is node:
break
def insert_row(self, node):
cur_node = node
while cur_node:
up_neigh = cur_node.up
down_neigh = cur_node.down
up_neigh.down = cur_node
down_neigh.up = cur_node
cur_node = cur_node.right
if cur_node is node:
break
def insert_col(self, node):
cur_node = node
while cur_node:
left_neigh = cur_node.left
right_neigh = cur_node.right
left_neigh.right = cur_node
right_neigh.left = cur_node
cur_node = cur_node.down
if cur_node is node:
break
def delete_col(self, node):
cur_node = node
while cur_node:
left_neigh = cur_node.left
right_neigh = cur_node.right
if cur_node is self.head:
self.head = right_neigh
if cur_node is right_neigh:
self.head = None
left_neigh.right = right_neigh
right_neigh.left = left_neigh
cur_node = cur_node.down
if cur_node is node:
break
### Second approach - moving the common parts of code to separate functions.
### Then these functions are used in needed places, instead of duplicating the same code
### every time. But the perfomance was dropped by three times, so I decided to not use this
### methods in the program.
###
# def delete_node(self, cur_node, a_node, a_neigh, b_node, b_neigh):
# if cur_node is self.head:
# self.head = b_node
# if cur_node is b_node:
# self.head = None
# setattr(a_node, a_neigh, b_node)
# setattr(b_node, b_neigh, a_node)
# self.size -= 1
#
# def insert_node(self, cur_node, a_node, a_neigh, b_node, b_neigh):
# setattr(a_node, a_neigh, cur_node)
# setattr(b_node, b_neigh, cur_node)
# self.size += 1
#
# def col_nonzero_nodes(self, node):
# for cur_node in self.traverse_node_line(node.col_head, "down"):
# if cur_node.value and cur_node.row_head is not self.head:
# yield cur_node
#
# def row_nonzero_nodes(self, node):
# for cur_node in self.traverse_node_line(node.row_head, "right"):
# if cur_node.value and cur_node.col_head is not self.head:
# yield cur_node
#
# def delete_row(self, node):
# for cur_node in self.traverse_node_line(node, "right"):
# self.delete_node(cur_node, cur_node.up, "down", cur_node.down, "up")
#
# def delete_col(self, node):
# for cur_node in self.traverse_node_line(node, "down"):
# self.delete_node(cur_node, cur_node.left, "right", cur_node.right, "left")
#
# def insert_row(self, node):
# for cur_node in self.traverse_node_line(node, "right"):
# self.insert_node(cur_node, cur_node.up, "down", cur_node.down, "up")
#
# def insert_col(self, node):
# for cur_node in self.traverse_node_line(node, "down"):
# self.insert_node(cur_node, cur_node.left, "right", cur_node.right, "left")
class Solver():
def __init__(self, board, figures, rows, cols, figures_naming_start):
self.rows = rows
self.cols = cols
self.fig_name_start = figures_naming_start
self.figures = figures
self.solutions = set()
self.llist = None
self.start_board = board
self.tried_variants_num = 0
def find_solutions(self):
named_figures = set(enumerate(self.figures, self.fig_name_start))
all_figure_postures = self.unique_figure_postures(named_figures)
self.llist = Linked_list_2D(self.rows * self.cols + 1)
pos_gen = self.generate_positions(all_figure_postures, self.rows, self.cols)
for line in pos_gen:
for val in line:
self.llist.append(val)
self.delete_filled_on_start_cells(self.llist)
self.starttime = time()
self.prevtime = self.starttime
self.dlx_alg(self.llist, self.start_board)
# Converts a one dimensional's element index to two dimensional's coordinates
def num_to_coords(self, num):
row = num // self.cols
col = num - row * self.cols
return row, col
def delete_filled_on_start_cells(self, llist):
for col_head_node in llist.row_nonzero_nodes(llist.head):
row, col = self.num_to_coords(col_head_node.value - 1)
if self.start_board[row][col]:
llist.delete_col(col_head_node)
def print_progress(self, message, interval):
new_time = time()
if (new_time - self.prevtime) >= interval:
print(message)
print(f"Time has elapsed: {timedelta(seconds=new_time - self.starttime)}")
self.prevtime = new_time
def check_solution_uniqueness(self, solution):
reflected_solution = self.reflect(solution)
for sol in [solution, reflected_solution]:
if sol in self.solutions:
return
for _ in range(3):
sol = self.rotate(sol)
if sol in self.solutions:
return
return 1
def dlx_alg(self, llist, board):
# If no rows left - all figures are used
if llist.head.down is llist.head:
self.print_progress(f"{self.tried_variants_num} variants have tried", 5.0)
self.tried_variants_num += 1
# If no columns left - all cells are filled, the solution is found.
if llist.head.right is llist.head:
solution = tuple(tuple(row) for row in board)
if self.check_solution_uniqueness(solution):
print(f"The solution № {len(self.solutions) + 1}")
self.print_board(solution)
self.solutions.add(solution)
return
# Search a column with a minimum of intersected rows
min_col, min_col_sum = self.find_min_col(llist, llist.head)
# The perfomance optimization - stops branch analyzing if empty columns appears
if min_col_sum == 0:
self.tried_variants_num += 1
return
intersected_rows = []
for node in llist.col_nonzero_nodes(min_col):
intersected_rows.append(node.row_head)
# Pick one row (the variant of figure) and try to solve puzzle with it
for selected_row in intersected_rows:
rows_to_restore = []
new_board = self.add_posture_to_board(selected_row, board)
# If some figure is used, any other variants (postures) of this figure
# could be discarded in this branch
for posture_num_node in llist.col_nonzero_nodes(llist.head):
if posture_num_node.value == selected_row.value:
rows_to_restore.append(posture_num_node)
llist.delete_row(posture_num_node)
cols_to_restore = []
for col_node in llist.row_nonzero_nodes(selected_row):
for row_node in llist.col_nonzero_nodes(col_node.col_head):
# Delete all rows which are using the same cell as the picked one,
# because only one figure can fill the specific cell
rows_to_restore.append(row_node.row_head)
llist.delete_row(row_node.row_head)
# Delete the columns the picked figure fill, they are not
# needed in this branch anymore
cols_to_restore.append(col_node.col_head)
llist.delete_col(col_node.col_head)
# Pass the shrinked llist and the board with the picked figure added
# to the next processing
self.dlx_alg(llist, new_board)
for row in rows_to_restore:
llist.insert_row(row)
for col in cols_to_restore:
llist.insert_col(col)
def find_min_col(self, llist, min_col):
min_col_sum = float("inf")
for col in llist.row_nonzero_nodes(llist.head):
tmp = sum(1 for item in llist.col_nonzero_nodes(col))
if tmp < min_col_sum:
min_col = col
min_col_sum = tmp
return min_col, min_col_sum
def add_posture_to_board(self, posture_row, prev_steps_result):
new_board = prev_steps_result.copy()
for node in self.llist.row_nonzero_nodes(posture_row):
row, col = self.num_to_coords(node.col_head.value - 1)
new_board[row][col] = node.row_head.value
return new_board
def print_board(self, board):
for row in board:
for cell in row:
print(f"{cell: >3}", end='')
print()
print()
print("#" * 80)
def unique_figure_postures(self, named_figures):
postures = set(named_figures)
for name, fig in named_figures:
postures.add((name, self.reflect(fig)))
all_postures = set(postures)
for name, posture in postures:
for _ in range(3):
posture = self.rotate(posture)
all_postures.add((name, posture))
return all_postures
# Generates entries for all possible positions of every figure's posture.
# Then the items of these entires will be linked into the 2 dimensional circular linked list
# The entry looks like:
# figure's name {board cells filled by figure} empty board's cells
# | | | | | | | | |
# 5 0 0 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ................
def generate_positions(self, postures, rows, cols):
def apply_posture(name, posture, y, x, wdth, hght):
# Flattening of 2d list
line = [cell for row in self.start_board for cell in row]
# Puts the figure onto the flattened start board
for r in range(hght):
for c in range(wdth):
if posture[r][c]:
num = (r + y) * cols + x + c
if line[num]:
return
line[num] = posture[r][c]
# And adds name into the beginning
line.insert(0, name)
return line
# makes columns header in a llist
yield [i for i in range(rows * cols + 1)]
for name, posture in postures:
posture_height = len(posture)
posture_width = len(posture[0])
for row in range(rows):
if row + posture_height > rows:
break
for col in range(cols):
if col + posture_width > cols:
break
new_line = apply_posture(name, posture, row, col, posture_width, posture_height)
if new_line:
yield new_line
def rotate(self, fig):
return tuple(zip(*fig[::-1]))
def reflect(self, fig):
return tuple(fig[::-1])
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T15:41:21.497",
"Id": "456047",
"Score": "1",
"body": "Comments mate, comments. This seems a nice piece of code to dive in and comments might've helped."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T16:46:52.527",
"Id": "456063",
"Score": "2",
"body": "@Abdur-RahmaanJanhangeer I heard the opinion that comments overloading isn't good as well as a scarce of them. The idea was something like: *\"Allow code to speak\"*. So, I didn't make a lot of comments, but have tried to write a \"speaking code\" instead. The hardest part of the program is algorithm, it has comments in key places. And the algorithm has good explanation in the Wikipedia. Also, I read many source codes of big programs, like **CPython** - they are not having a lot of comments to explain everything, only for key things, so I did the same."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T16:51:14.747",
"Id": "456065",
"Score": "1",
"body": "@Abdur-RahmaanJanhangeer For example, do the `insert_col` or `delete_col` methods need comments?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T17:18:31.430",
"Id": "456072",
"Score": "1",
"body": "One of the reasons it's hard to get answers to your question is that it's long. Removing those commented out codes shorten it for one thing. One of the non-breaking code reading ways is to write comments after codes `code # comment` so that the code is read and when not understood, you just glance sideways. What i feel lack is the big picture like a docstring to `def dlx_alg(self, llist, board):` . Your linkedlist for example is too long. Compare with [this](https://runestone.academy/runestone/books/published/pythonds/BasicDS/ImplementinganUnorderedListLinkedLists.html)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T17:21:26.143",
"Id": "456073",
"Score": "0",
"body": "A linkedlist is a common data structure and does not need a lot of deriving, They are the basic tools for solving problems. Memorising how to write good one allows one to focus on the algo at hand. That's another way of reducing the code, putting the focus on the algo part."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T17:55:49.620",
"Id": "456079",
"Score": "2",
"body": "@Abdur-RahmaanJanhangeer I looked at the article about **Linked List** you gave. There is a simple linked list, not my case. In my case it is a **interlinked 2-d matrix**, where every node has 4 neighbors: up, down, left, right. And it is customized specially for this program, because the program needs methods to manipulate rows and columns. I didn't find an explanation article about this to give you. May be this will be useful: [Dancing Links](https://en.wikipedia.org/wiki/Dancing_Links#Implementation)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T04:33:33.973",
"Id": "456171",
"Score": "0",
"body": "agree, the was trying to illustrate that data structs are to be as as simple as possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-03T08:57:07.303",
"Id": "463687",
"Score": "0",
"body": "@MiniMax Hi, are you still working on that? I'd like to review your code, but it requires some questions to understand it, it lacks a lot of comments I think."
}
] |
[
{
"body": "<h1>Low Hanging Fruit</h1>\n\n<p>I obtained a 27% speed-up with one tiny change.</p>\n\n<p>For this speed-up, I didn't want to wait 2 hours for tests to run, so I used a 3x20 board. Elapsed times: </p>\n\n<ul>\n<li>0:01:44 - before the change</li>\n<li>0:01:16 - after the change</li>\n</ul>\n\n<p>I'm sure you'd like to know what the change was. I can't drag it out much more, so here it is. I added this line to the <code>Nodes</code> class:</p>\n\n<pre><code> __slots__ = ('value', 'up', 'down', 'left', 'right', 'row_head', 'col_head')\n</code></pre>\n\n<p>This eliminates the <code>__dict__</code> member of the <code>Nodes</code> objects. So instead of <code>self.down</code> being interpreted as <code>self.__dict__['down']</code>, the value referenced is in a predefined \"slot\" in the <code>Nodes</code> object. Not only do the references become faster, but the object uses less space, which reduces the memory footprint, which increases locality of reference which again helps performance.</p>\n\n<p>(Adding the <code>__slots__</code> to <code>Linked_list_2D</code> and <code>Solver</code> didn't change my performance numbers at all.)</p>\n\n<h1>Interface</h1>\n\n<pre><code>class Solver():\n def __init__(self, board, figures, rows, cols, figures_naming_start):\n ...\n</code></pre>\n\n<p>This is an \"unfriendly\" interface. You have to pass all 5 values to the <code>Solver()</code>. But some of these parameters are redundant.</p>\n\n<p>You've got <code>board</code> and you have <code>rows</code> and <code>cols</code>. Given a <code>board</code>, the <code>Solver</code> could determine <code>rows = len(board)</code> and <code>cols = len(board[0])</code>. Or given <code>rows</code> and <code>cols</code>, the <code>Solver()</code> could construct an empty board.</p>\n\n<p><code>figures_naming_start</code> is likely always going to be <code>1</code>. Why not use a default value of <code>1</code> for that parameter? Or pass a dictionary to <code>figures</code> with the key names the \"name\" for the figures. And since <code>figures</code> is a predefined set, why not default it to a class constant?</p>\n\n<pre><code>class Solver():\n STANDARD_FIGURES = { 'I' : ((1, 1, 1, 1, 1)),\n 'Q' : ((1, 1, 1, 1),\n (1, 0, 0, 0)),\n ...\n }\n def __init__(self, board=None, rows=None, cols=None, figures=STANDARD_FIGURES):\n if board is None:\n board = [[0] * cols for _ in range(len(rows))]\n if rows is None and cols is None:\n rows = len(board)\n cols = len(board[0])\n ...\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>solver = Solver(rows=3, cols=20)\nsolver.find_solutions()\n</code></pre>\n\n<h1>Finding Solutions</h1>\n\n<p>When a solution is found, it is printed. What if you wanted to display it in a GUI of some kind, with coloured tiles?</p>\n\n<p>It would be better for <code>find_solutions()</code> to <code>yield solution</code>, and then the caller could print the solutions, or display them in some fashion, or simply count them:</p>\n\n<pre><code>solver = Solver(rows=3, cols=20)\nfor solution in solver.find_solutions():\n solver.print_board(solution)\n</code></pre>\n\n<h1>Progress</h1>\n\n<p>The progress / timing messages should be presented via the <code>logging</code> module, where they could be printed, or written to a file, or turned off all together.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T22:56:55.373",
"Id": "239293",
"ParentId": "233300",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "239293",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T23:54:03.057",
"Id": "233300",
"Score": "10",
"Tags": [
"python",
"performance",
"algorithm",
"python-3.x"
],
"Title": "Solving Pentomino puzzles by using Knuth's Algorithm X"
}
|
233300
|
<p>I am making a Reddit bot and to prevent my bot from posting to the same comment twice, instead of making a database, I decided I would rather create a temporary list (or "queue") that once appended to, checks to ensure the maximum length of the queue hasn't been exceeded. Once exceeded, however, the queue is cleared.</p>
<pre class="lang-py prettyprint-override"><code>class TemporaryQueue:
def __init__(self, max_items=10):
self._queue = []
self.max_items = max_items
def __repr__(self):
return "<TemporaryQueue max_items={}>".format(self.max_items)
def __iter__(self):
yield from self._queue
def __eq__(self, other):
return other in self._queue
def _exceed_check(self):
if len(self._queue) > self.max_items:
return True
return False
def append(self, value):
if self._exceed_check():
self._queue.clear()
return self._queue.append(value)
</code></pre>
<p>Example usage:</p>
<pre class="lang-py prettyprint-override"><code>for submission in reddit.subreddit("funny").stream.submissions():
queue = TemporaryQueue()
if submission.id not in queue:
if "foo" in title:
submission.reply("Bar!")
queue.append(submission.id)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T18:05:28.893",
"Id": "456080",
"Score": "0",
"body": "You are using a database, just a very limited in-memory database. Also, you might want to retain the last *n* recently used items instead of discarding all the items when the limit is reached."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T18:24:14.613",
"Id": "456084",
"Score": "0",
"body": "It will post to the same comment twice, if the queue happens to clear itself in between."
}
] |
[
{
"body": "<p>I made a few adjustments (simplified the return handling for max queue size) and added in a dequeue method:</p>\n\n<pre><code>class TemporaryQueue:\n def __init__(self, max_items=10):\n self._queue = []\n self.max_items = max_items\n\n def __repr__(self):\n return \"<TemporaryQueue max_items={}>\".format(self.max_items)\n\n def __iter__(self):\n yield from self._queue\n\n def __eq__(self, other):\n return other in self._queue\n\n def _full(self):\n return len(self._queue) >= self.max_items\n\n def enqueue(self, value):\n if self._full():\n self._queue.clear()\n\n return self._queue.append(value)\n\n def dequeue(self):\n return self._queue.pop()\n</code></pre>\n\n<p>A queue doesn't seem like a good data structure for this problem. A ring buffer might be more applicable; it creates a fixed size list of elements (say 10) and when there isn't enough room left, it overwrites the oldest one. Depending on the implementation, the entire buffer can be searched to see if it contains a string (taken directly from <a href=\"https://www.oreilly.com/library/view/python-cookbook/0596001673/ch05s19.html\" rel=\"nofollow noreferrer\">https://www.oreilly.com/library/view/python-cookbook/0596001673/ch05s19.html</a>):</p>\n\n<pre><code>class RingBuffer:\n \"\"\" class that implements a not-yet-full buffer \"\"\"\n def __init__(self,size_max):\n self.max = size_max\n self.data = []\n\n class __Full:\n \"\"\" class that implements a full buffer \"\"\"\n def append(self, x):\n \"\"\" Append an element overwriting the oldest one. \"\"\"\n self.data[self.cur] = x\n self.cur = (self.cur+1) % self.max\n def get(self):\n \"\"\" return list of elements in correct order \"\"\"\n return self.data[self.cur:]+self.data[:self.cur]\n\n def append(self,x):\n \"\"\"append an element at the end of the buffer\"\"\"\n self.data.append(x)\n if len(self.data) == self.max:\n self.cur = 0\n # Permanently change self's class from non-full to full\n self._ _class_ _ = self._ _Full\n\n def get(self):\n \"\"\" Return a list of elements from the oldest to the newest. \"\"\"\n return self.data\n\n# sample usage\nif __name__=='__main__':\n x=RingBuffer(5)\n x.append(1); x.append(2); x.append(3); x.append(4)\n print x.__class__, x.get( )\n x.append(5)\n print x.__class__, x.get( )\n x.append(6)\n print x.data, x.get( )\n x.append(7); x.append(8); x.append(9); x.append(10)\n print x.data, x.get( )\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T02:18:25.410",
"Id": "233307",
"ParentId": "233305",
"Score": "6"
}
},
{
"body": "<h3>collections.deque</h3>\n\n<p>Why not use a collections.deque with a max_len?</p>\n\n<pre><code>from collections import deque\n\nfor submission in reddit.subreddit(\"funny\").stream.submissions():\n queue = deque(max_len=10)\n\n if submission.id not in queue:\n if \"foo\" in title:\n submission.reply(\"Bar!\")\n queue.append(submission.id)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T02:34:28.097",
"Id": "233308",
"ParentId": "233305",
"Score": "13"
}
},
{
"body": "<p>This is a weird unique queue. It does not actually guarantee uniqueness on its own:</p>\n\n<pre><code>queue = TemporaryQueue()\nfor x in range(10):\n queue.append(x)\nqueue.append(0)\nprint(list(queue))\n# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0]\n</code></pre>\n\n<p>And it does not guarantee that all of the elements are even there:</p>\n\n<pre><code>queue = TemporaryQueue()\nfor x in range(10):\n queue.append(x)\nprint(list(queue))\n# [11]\n</code></pre>\n\n<p>If I add more than <code>max_items</code> elements to a queue, I expect the queue to always grow until it reaches its maximum size and then stay constant (in size). Not shrink again to one element.</p>\n\n<p>The <code>max_items</code> argument is also not followed correctly:</p>\n\n<pre><code>queue = TemporaryQueue()\nfor x in range(11):\n queue.append(x)\nprint(len(list(queue)))\n# 11\n</code></pre>\n\n<p>Your <code>__eq__</code> method is not needed. It looks like you wanted to implement <code>__contains__</code> in order to be able to do <code>x in queue</code>.\nYour code still works because Python just uses <code>x in list(self)</code>, which in this case is just as inefficient as your implementation.</p>\n\n<p>In your <code>append</code> method you do <code>return self._queue.append(value)</code>. Since <code>list.append</code> modifies the list inplace, it returns <code>None</code>, which your method will implicitly return anyways. Instead just have the call in its line as the last line of the method</p>\n\n<p>On the other hand, your capacity check can be simplified by putting the call in the <code>return</code>:</p>\n\n<pre><code>def _exceed_check(self):\n return len(self._queue) > self.max_items\n</code></pre>\n\n<p>You might want to add a <code>extend</code> method for convenience. A simple implementation such as this would already suffice:</p>\n\n<pre><code>def extend(self, values):\n for x in values:\n self.append(x)\n</code></pre>\n\n<hr>\n\n<p>If you want truly unique comments, either collect them in a <a href=\"https://docs.python.org/3/library/stdtypes.html#set\" rel=\"nofollow noreferrer\"><code>set</code></a> beforehand, or use the <a href=\"https://docs.python.org/3/library/itertools.html#itertools-recipes\" rel=\"nofollow noreferrer\"><code>itertools</code> recipe</a> <code>unique_everseen</code> if you want to process them as they come in. Of course, this needs <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span> memory, where <span class=\"math-container\">\\$n\\$</span> is the number of unique comments.</p>\n\n<p>If you want an efficient maximum size queue from which you can get elements from both sides, use a <a href=\"https://docs.python.org/3/library/collections.html#collections.deque\" rel=\"nofollow noreferrer\"><code>collections.deque</code></a>, as recommended in <a href=\"https://codereview.stackexchange.com/a/233308/98493\">the answer</a> by <a href=\"https://codereview.stackexchange.com/users/98633/roottwo\">@RootTwo</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T11:50:31.540",
"Id": "233328",
"ParentId": "233305",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "233308",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T01:55:24.357",
"Id": "233305",
"Score": "8",
"Tags": [
"python",
"python-3.x",
"queue"
],
"Title": "Temporary queue to prevent duplication"
}
|
233305
|
<p>I'm trying to do a simple implementation of a <code>scp</code> wrapper in Elixir.</p>
<p>The code is working as intended, but I got a feeling that the error conditions can be simplified. Besides error handling, I don't the best way to append the <code>-r</code> flag if the <code>source_path</code> is a directory with a <code>cond</code> keyword.</p>
<pre><code>defmodule Scp do
def scp(user, ip, source_path, destination_path, timeout \\ 30) do
scp_flags = [
"-oStrictHostKeyChecking=no",
"-oConnectTimeout=#{timeout}",
"-oPasswordAuthentication=no",
source_path,
"#{user}@#{ip}:#{destination_path}"
]
scp_flags =
case File.dir?(source_path) do
true -> ["-r" | scp_flags]
_ -> scp_flags
end
if File.exists?(source_path) do
case System.cmd("scp", scp_flags, stderr_to_stdout: true) do
{resp, 0} ->
{:ok, resp, 0}
{resp, exit_code} ->
cond do
String.contains?(resp, "Permission denied") ->
{:error, :permdenied, exit_code}
String.contains?(resp, "Connection timed out") ->
{:error, :conntimeout, exit_code}
true ->
{:error, :errunkown, exit_code}
end
end
else
{:error, :enoent, -1}
end
end
end
</code></pre>
|
[] |
[
{
"body": "<p>I have never used Elixir in my life until seeing this question, so my feedback is very limited and I probably shouldn't be putting an answer on here. However, there are a few ways it could be simplified:</p>\n\n<ul>\n<li><p>the module <code>lstat(path, opts \\\\ [])</code> reads information about a path, returns a <code>FileStat</code> struct which has a <code>type:</code> field which can be <code>type: :device | :directory | :regular | :other | :symlink</code>; this could be used to determine what the path is (and whether to use <code>-r</code>), and if there is an error it means that the path does not exist (thus adding in the error handling)</p></li>\n<li><p>in the case <code>{resp, exit_code} -></code> instead of checking the error message contents via <code>String.contains?</code>, do the switching based on exit code and then return the appropriate error messages.</p></li>\n<li><p>in the case <code>{resp, exit_code} -></code>, I'd add a few extra error-handlers for statuses (for example directory not found on destination, invalid credentials, etc.)</p></li>\n<li><p>for the inputs (user and ip address), a regex could be used to ensure sanity (the ip address looks like an ip, the username is not blank, etc.)</p></li>\n<li><p>the case <code>true -> {:error, :errunkown, exit_code}</code> could be replaced with <code>_ -> {:error, :errunkown, exit_code}</code> as <code>_</code> appears to be a fall through (I'm unsure about this)</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T04:36:06.607",
"Id": "233309",
"ParentId": "233306",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "233309",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T02:12:15.397",
"Id": "233306",
"Score": "2",
"Tags": [
"error-handling",
"elixir"
],
"Title": "Naive SCP module in Elixir"
}
|
233306
|
<p>I have a part of my code I want to optimize.
I use <code>if</code> statement to skip the analyze if the values are not the one I want.
Just to help the comprehension, in my data, R1 is between range(6,15); mis in range(0,1); spacer in range (0,10).</p>
<p>My code is working, but it would be better if it will run faster according to the amount of data I have.</p>
<pre class="lang-py prettyprint-override"><code>R1 = len(hit_splitted_line1[1])
hit = re.sub(r"\s+", "", lines[i+1])
hit_nb = len(hit)
spacer = pos2_spacer - pos1_spacer - 1
mis = R1 - hit_nb
if (R1 == 6 and mis ==1):
pass
elif (R1 == 6 and mis == 0 and spacer in range(0,4)) :
pass
elif (R1 == 7 and mis == 0 and spacer in range(0,2)) :
pass
elif (R1 == 7 and mis == 1 and spacer in range(0,4)) :
pass
else :
if (R1 == 8 and spacer in range(0,1)):
goodAln = re.search('^\s*\|\|\|\|\|\|', lines[i+1])
if (not goodAln):
pass
else :
name_list=[str(chr),str(pos_start),str(pos_end)]
name = '_'.join(name_list)
ID = "ID="+name+";spacer="+str(spacer)+";repeat="+str(R1)+";mismatch="+str(mis)
print (chr,"pal2gff","IR",pos_start,pos_end,".","+",".",str(ID),sep='\t')
else :
name_list=[str(chr),str(pos_start),str(pos_end)]
name = '_'.join(name_list)
ID = "ID="+name+";spacer="+str(spacer)+";repeat="+str(R1)+";mismatch="+str(mis)
print (chr,"pal2gff","IR",pos_start,pos_end,".","+",".",str(ID),sep='\t')
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T09:18:54.877",
"Id": "455998",
"Score": "6",
"body": "1) Change your title properly to reflect the purpose of the program 2) Add more context if you asking for performance optimization: what is `lines` and what's its contents? what are `pos_start`, `pos_end` ???"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T14:02:50.167",
"Id": "456027",
"Score": "1",
"body": "Hey Leelouh, could you maybe include a sample of your data :) Also, as Roman stated, we'd need to see the variable declarations in order to help you out with a review."
}
] |
[
{
"body": "<h2><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> Conventions</h2>\n\n<ul>\n<li><strong>Do not</strong> use parentheses to cover the <code>if</code> statements.</li>\n<li><strong>Do not</strong> leave a whitespace before the <code>:</code> in the <code>if else</code> statements.</li>\n<li><strong>Use</strong> whitespace around operators and commas. <code>some1,some2</code> should be <code>some1, some2</code></li>\n</ul>\n\n<h2>General</h2>\n\n<ul>\n<li>Use <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\">formatting</a></li>\n<li>Use <a href=\"https://www.geeksforgeeks.org/chaining-comparison-operators-python/\" rel=\"nofollow noreferrer\">chained comparisons</a> instead of <code>range(x, y)</code></li>\n</ul>\n\n<p>Here's what the code might look like in the end:</p>\n\n<pre><code>R1 = len(hit_splitted_line1[1])\nhit = re.sub(r\"\\s+\", \"\", lines[i + 1])\nhit_nb = len(hit)\n\nspacer = pos2_spacer - pos1_spacer - 1\n\nmis = R1 - hit_nb\n\nif R1 == 6 and mis == 1:\n pass\n\nelif R1 == 6 and mis == 0 and 0 <= spacer <= 3:\n pass\n\nelif R1 == 7 and mis == 0 and 0 <= spacer <= 1:\n pass\n\nelif R1 == 7 and mis == 1 and 0 <= spacer <= 3:\n pass\n\nelse:\n if R1 == 8 and spacer in range(0, 1):\n goodAln = re.search('^\\s*\\|\\|\\|\\|\\|\\|', lines[i + 1])\n\n if not goodAln:\n pass\n\n else:\n name_list = [str(chr), str(pos_start), str(pos_end)]\n name = '_'.join(name_list)\n ID = f\"ID={name};spacer={spacer};repeat={R1};mismatch={mis}\"\n print(chr, \"pal2gff\", \"IR\", pos_start, pos_end, \".\", \"+\", \".\", str(ID), sep='\\t')\n\n else:\n name_list = [str(chr), str(pos_start), str(pos_end)]\n name = '_'.join(name_list)\n ID = f\"ID={name};spacer={spacer};repeat={R1};mismatch={mis}\"\n print(chr, \"pal2gff\", \"IR\", pos_start, pos_end, \".\", \"+\", \".\", str(ID), sep='\\t')\n</code></pre>\n\n<p>Note:</p>\n\n<pre><code>if R1 == 6 and mis == 1:\n pass\n\nelif R1 == 6 and mis == 0 and 0 <= spacer <= 3:\n pass\n\nelif R1 == 7 and mis == 0 and 0 <= spacer <= 1:\n pass\n\nelif R1 == 7 and mis == 1 and 0 <= spacer <= 3:\n pass\n</code></pre>\n\n<p>You can replace these statements with an if statement, but I did not replace them as the code might still be in development.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T10:56:13.623",
"Id": "233323",
"ParentId": "233317",
"Score": "2"
}
},
{
"body": "<p>Nesting <code>if</code> statements isn't considered as clean code. I advise you'd use <code>bouncer</code> design pattern. Check your constraints first. If they're are not satisfied, just return.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T11:11:39.523",
"Id": "233324",
"ParentId": "233317",
"Score": "0"
}
},
{
"body": "<p>Your if statements can be optimized from:</p>\n\n<pre><code>if R1 == 6 and mis == 1:\n pass\n\nelif R1 == 6 and mis == 0 and 0 <= spacer <= 3:\n pass\n\nelif R1 == 7 and mis == 0 and 0 <= spacer <= 1:\n pass\n\nelif R1 == 7 and mis == 1 and 0 <= spacer <= 3:\n pass\n</code></pre>\n\n<p>to </p>\n\n<pre><code>if R1 == 6:\n if miss == 1:\n pass\n elif 0 <= spacer <= 3:\n pass\n\nelif R1 == 7:\n if miss == 1 and 0 <= spacer <= 3:\n pass\n elif miss == 0 and 0 <= spacer <= 1:\n pass\n</code></pre>\n\n<p>You will generate less python internal instructions (opcodes)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T11:29:02.133",
"Id": "233326",
"ParentId": "233317",
"Score": "2"
}
},
{
"body": "<p>On what is slow. Not the if-chain.</p>\n\n<p><code>ID=...</code> is very slow, maybe you can pass the terms to <code>print</code> individually.</p>\n\n<p>The regular expression usage is slow too. Precompiling regex outside the looping is faster.</p>\n\n<p>The if-chain can be reduced, but to some extent the compiler should be able to do it better. As the code can become a difficult and-or chaos.</p>\n\n<p>Doing it yourself, I would transform</p>\n\n<pre><code>if R1 == 6 and mis == 1:\n pass\n\nelif R1 == 6 and mis == 0 and 0 <= spacer <= 3:\n pass\n\nelif R1 == 7 and mis == 0 and 0 <= spacer <= 1:\n pass\n\nelif R1 == 7 and mis == 1 and 0 <= spacer <= 3:\n pass\n</code></pre>\n\n<p>first <em>suboptimally</em> into:</p>\n\n<pre><code>r16 = R1 == 6\nr17 = R1 == 7\nmis0 = mis == 0\nmis1 = mis == 1\nspg0 = 0 <= spacer\nspl1 = spacer <= 1\nspl3 = spacer <= 3\n</code></pre>\n\n<p>Receiving the or'ed conditions:</p>\n\n<pre><code>r16 and mis1\nr16 and mis0 and spg0 and spg3\nr17 and mis0 and spg0 and spg1\nr17 and mis1 and spg0 and spg3\n</code></pre>\n\n<p>transformed into</p>\n\n<pre><code>(r16 and (mis1 \n or (mis0 and spg0 and spg3)\n )\n)\nor\n(r17 and ((mis0 and spg0 and spg1)\n or (mis1 and spg0 and spg3)\n )\n)\n</code></pre>\n\n<p>transformed into</p>\n\n<pre><code>(r16 and (mis1 \n or (mis0 and spg0 and spg3)\n )\n)\nor\n(r17 and spg0 and ((mis0 and spg1)\n or (mis1 and spg3)\n )\n)\n</code></pre>\n\n<p>transformed into</p>\n\n<pre><code>(r16 and (mis1 \n or (mis0 and spg0 and spg3)\n )\n)\nor\n(r17 and spg0 and ((mis0 and spg1)\n or (mis1 and spg3)\n )\n)\n</code></pre>\n\n<p>These 7 boolean variables would lean themselves using a <a href=\"https://en.wikipedia.org/wiki/Karnaugh_map\" rel=\"nofollow noreferrer\">Karnaugh map</a>\nto the most compact boolean expression.</p>\n\n<p>As said the gain/effort ratio is little.</p>\n\n<p>I would just exploit the exclusive conditions to make a simple nested if.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T13:21:50.273",
"Id": "233332",
"ParentId": "233317",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T09:09:37.047",
"Id": "233317",
"Score": "-1",
"Tags": [
"python",
"performance",
"python-3.x"
],
"Title": "How to optimize if statement in python from a parsing script"
}
|
233317
|
<p>Consider I have many enums (Java) that looks somewhat like this:</p>
<pre><code>@AllArgsConstructor
@Getter
public enum PopularPeriod {
MONTHLY ("MON"),
BIMONTHLY ("BMN"),
QUARTERLY ("QTR"),
SEMI_ANNUALLY ("SMA"),
ANNUALLY ("ANL");
private final String value;
}
</code></pre>
<p>Now, a usual use, I'd think, would be to get the enum object using its value (the string) - there's an input you're parsing and you want to turn the string into some nice objects that make the code more readable.</p>
<p>So I added this to the enum above - </p>
<pre><code>public static PopularPeriod fromString(String value) {
for (PopularPeriod pp : PopularPeriod.values()) {
if (pp.getValue().equalsIgnoreCase(value)) return pp;
}
return null;
}
</code></pre>
<p>(don't mind the returning of null the casing).
This works quite good.
But if you have dozens of those enums - you need to write it for each one.</p>
<p>I tried approaches like adding something like this to a utility class -</p>
<pre><code>public static <T extends Enum<T>> T safeEnumByValue(Class<T> enumType, Object value) { ... }
</code></pre>
<p>but there I don't know of the private field (value).</p>
<p>So I though of "implementing" an interface instead (as enum may not extend base classes), and make the search as a default method in the interface.</p>
<pre><code>public interface IEnum<T> {
T getValue();
}
@AllArgsConstructor
@Getter
public enum PopularPeriod implements IEnum<String> { ... }
</code></pre>
<p>and adding a default method in the interface - but that's impossible as I don't have the <code>PopularPeriod.values()</code> there to work with.</p>
<p>In the end, I combined the two approaches.
I have this method in a utility class:</p>
<pre><code>public static <T extends IEnum> T safeEnumByValue(Class<T> enumType, Object value) {
for (T enumConstant : enumType.getEnumConstants()) {
if (enumConstant.getValue().equals(value)) return enumConstant;
}
return null;
}
</code></pre>
<p>Just got there.<br>
It works.<br>
I thought maybe I'd delete this question,but I would love to hear if there's any elegant way to do it.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T11:15:48.023",
"Id": "456010",
"Score": "0",
"body": "Can you tell why you don't like the approach so we can tell you specifically why it can't be fixed. In other words, this is as elegant as you're going to get."
}
] |
[
{
"body": "<p>There may be a more fundamental problem here beyond <em>converting a string to enum</em>.</p>\n\n<p>By adding a <code>fromString(String)</code> into the enum and defining the format specific strings in the enum constructor, you are coupling the enum tightly to the data format and making it an integral part of the input parser. Your enum now has two responsibilities, being clearly in violation of the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"noreferrer\">single responsibility principle</a></p>\n\n<p>Instead you should implement a format specific converter that converts the string used in transport to the enum used in computing and make the enum as bare as possible.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T13:24:53.977",
"Id": "233333",
"ParentId": "233318",
"Score": "6"
}
},
{
"body": "<p>Agreed with the above if we implement the above function fromString(String value) we would definitely violate the SRP. However, we can implement a simple class with reverse mapping i.e. which would provide an easy way to convert between String and Enum. After that comparison is a cakewalk.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-09T18:43:31.003",
"Id": "233720",
"ParentId": "233318",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "233333",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T09:16:12.770",
"Id": "233318",
"Score": "6",
"Tags": [
"java",
"design-patterns",
"enum",
"interface"
],
"Title": "Opposite access to enums"
}
|
233318
|
<p>The following works as expected <strong>but I wonder if there is a more idiomatic way to check the input <code>kwargs</code> against the user-required (non-defaulted) arguments.</strong></p>
<p><strong>It is written in this way:</strong> so that as I continue to develop and modify my script and add attributes, I simply need to add them to the class variable <code>defaults = {'A':None, 'B':0, 'C':0}</code> and set it to <code>None</code> if the user is required to specify it. I also like that managing this as a class variable is visible at this time.</p>
<p>I've included a modified adaptation from item #6 in <a href="https://codereview.stackexchange.com/a/233169/145009">this excellent answer</a> that makes sure all of the arguments end up as either floats or np.arrays with all the same length. </p>
<ul>
<li><p>If they are: the attributes are set to default or user values and <code>.ok</code> set to <code>True</code></p></li>
<li><p>If not: attributes <strong>are not set</strong> to defaults or user values and <code>.ok</code> remains <code>False</code></p></li>
</ul>
<p>In this example, a value for <code>A</code> is required of the user. They may enter values for <code>B</code> and <code>C</code> but if not those are initialized to 0.0. Any extra arguments such as <code>D=42</code> will just be ignored.</p>
<pre><code>import numpy as np
class O(object):
defaults = {'A':None, 'B':0, 'C':0}
required = [key for (key, value) in defaults.items() if value == None]
ok = False
def __init__(self, **kwargs):
if not all([key in kwargs for key in self.required]):
print('problem, something required is missing')
setup = self.defaults.copy()
for (key, value) in kwargs.items():
if key in setup:
setup[key] = kwargs[key] # user specified overrides default
setup = self.fixem(setup)
if setup:
for (key, value) in setup.items():
setattr(self, key, value)
self.ok = True
else:
print('something did not work')
def fixem(self, setup):
# adapted from https://codereview.stackexchange.com/a/233169/145009
results = None
keys, values = zip(*setup.items())
arrays = list(map(np.atleast_1d, values))
sizes_ok = len(set(map(np.size, arrays)).difference(set((1,)))) <= 1
all_1d = set(map(np.ndim, arrays)) == set((1,))
all_good_types = all(array.dtype in (np.int64, np.float64) for array in arrays)
if all([sizes_ok, all_1d, all_good_types]):
arrays = [array.astype(float) for array in arrays] # make all arrays np.float64
values = list(map(lambda x: float(x) if len(x) == 1 else x, arrays)) # downcast length=1 arrays to float
results = dict(zip(keys, values))
return results
# TESTING:
attrs = ('A', 'B', 'C')
print('\nBEGIN good seup testing: ')
o = O(A=42)
print("\nEXPECT:[('A', 42.0), ('B', 0.0), ('C', 0.0)]")
print('GOT: ', [(attr, getattr(o, attr)) for attr in attrs if hasattr(o, attr)])
o = O(A=[1, 2, 3], B=np.exp(1), C=np.array([2, 3, 4]))
print("\nEXPECT:[('A'. array([1., 2., 3.])), ('B', 2.718281828459045), ('C', array([2., 3., 4.]))]")
print('GOT: ', [(attr, getattr(o, attr)) for attr in attrs if hasattr(o, attr)])
print('\nBEGIN bad seup testing: \n')
o = O(B=42)
print('\nEXPECT:[] (i.e. nothing!)')
print('GOT: ', [(attr, getattr(o, attr)) for attr in attrs if hasattr(o, attr)])
o = O(A=[1, 2, 3], B=[1, 2, 3, 4])
print('\nEXPECT:[] (i.e. nothing!)')
print('GOT: ', [(attr, getattr(o, attr)) for attr in attrs if hasattr(o, attr)])
</code></pre>
<p>OUTPUT:</p>
<pre><code>BEGIN good seup testing:
EXPECT:[('A', 42.0), ('B', 0.0), ('C', 0.0)]
GOT: [('A', 42.0), ('B', 0.0), ('C', 0.0)]
EXPECT:[('A'. array([1., 2., 3.])), ('B', 2.718281828459045), ('C', array([2., 3., 4.]))]
GOT: [('A', array([1., 2., 3.])), ('B', 2.718281828459045), ('C', array([2., 3., 4.]))]
BEGIN bad seup testing:
problem, something required is missing
something did not work
EXPECT:[] (i.e. nothing!)
GOT: []
something did not work
EXPECT:[] (i.e. nothing!)
GOT: []
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T10:22:41.880",
"Id": "456004",
"Score": "2",
"body": "In the constructor you may want to through exceptions such as \"ValueError\" instead your print statements for example. In general I dont like to have classes that can process different parameters depending on types and so on, this normally brings me the idea that my class is not correctly defined."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T10:29:51.683",
"Id": "456006",
"Score": "0",
"body": "@camp0 Yes indeed, the print statements are (unattractive) placeholders. Once I finalize the the overall way this is going to work I'll treat exceptions in a systematic way."
}
] |
[
{
"body": "<p>If there are required parameters, you should state them explicitly.</p>\n\n<pre><code>class O:\n\n def __init__(self, A=None, B=0, C=0, **kwargs):\n</code></pre>\n\n<p>By all means I would advise stronly against your solution. Class members should be clearly readable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T11:26:11.007",
"Id": "456011",
"Score": "0",
"body": "I know this is the standard way, but in what way is having the next line with the class variable `defaults = {'A':None, 'B':0, 'C':0}` *unreadable* in comparison? I'll need to check again why I wanted `defaults` available as a class variable. If I can't identify a clear need for that then this is fine; if there is a need for it I'll update. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T12:08:05.777",
"Id": "456012",
"Score": "0",
"body": "You're dynamically adding members, which are not dynamic. What for? Intellisense won't help you in any way later."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T12:09:06.887",
"Id": "456013",
"Score": "0",
"body": "And of course, your solution is far less readable. In professional setting maintenance is crucial."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T12:50:48.030",
"Id": "456014",
"Score": "0",
"body": "I've tracked down why I wanted to do it with dictionaries; you are right, it's not dynamic. Since you've posted an answer I shouldn't modify the question to show this without your \"ok\", but there will be several different subclasses that will share the same default values, and keeping them as a single dictionary in the main class means there will be one copy, but if they have to be retyped explicitly in the `__init__()` of each subclass then there's a risk of them diverging over time, which presents a maintenance complexity. The way I'm doing it there will only be a single instance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T13:08:56.840",
"Id": "456016",
"Score": "0",
"body": "**update:** Actually my previous point is moot; I can get one class to work for all cases, and so will not need to subclass. So this works currently. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T13:11:30.347",
"Id": "456017",
"Score": "1",
"body": "You can access parent members from subclass, so there would be no need to reimplement this design in subclasses. That's what `inheritance` is for."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T13:13:13.860",
"Id": "456018",
"Score": "1",
"body": "Additionally, please run some linter, before you post here. It'll make bitches like me much happier. You can also use auto-formatter like [black](https://pypi.org/project/black/)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T13:17:58.263",
"Id": "456019",
"Score": "0",
"body": "I've never heard of either of those but I can see the utility right away!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T13:24:37.333",
"Id": "456020",
"Score": "2",
"body": "Python creators and community are really caring, comparing to other, like .net and c#. Say your [prayer](https://www.python.org/dev/peps/pep-0020/) everyday. Be familiar with style guides [PEP8](https://www.python.org/dev/peps/pep-0008/). Linters are tools which help you ensure compatibility with PEP8. There's plenty of them i.e. [flake8](https://pypi.org/project/flake8/), [pylint](https://pypi.org/project/pylint/). If you're using vscode or pycharm it'll automatically detect those linters in your env and highlight errors."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T10:41:39.250",
"Id": "233322",
"ParentId": "233319",
"Score": "3"
}
},
{
"body": "<p>Some minor comments on the code:</p>\n\n<ol>\n<li>Class definition should be separated from the line with import by <a href=\"https://www.python.org/dev/peps/pep-0008/#blank-lines\" rel=\"nofollow noreferrer\">two spaces</a>.</li>\n<li><p>My personal preference is to have key-value pairs in dictionaries separated with a space after colon as shown in <a href=\"https://www.python.org/dev/peps/pep-0008/#whitespace-in-expressions-and-statements\" rel=\"nofollow noreferrer\">PEP 8</a>: </p>\n\n<pre><code>defaults = {'A': None, 'B': 0, 'C': 0}\n</code></pre></li>\n<li><p><a href=\"https://www.python.org/dev/peps/pep-0008/#programming-recommendations\" rel=\"nofollow noreferrer\">Comparing to <code>None</code></a> should be done by <code>is</code> instead of <code>==</code>:</p>\n\n<pre><code>required = [key for key, value in defaults.items() if value is None]\n</code></pre>\n\n<p>Note that I also removed redundant brackets around <code>key, value</code>. There are several other lines where brackets are not needed around them.</p></li>\n<li><p>PEP 8 also discourages <a href=\"https://www.python.org/dev/peps/pep-0008/#pet-peeves\" rel=\"nofollow noreferrer\">aligning several lines</a> with assignments by <code>=</code>, so instead of, for example:</p>\n\n<blockquote>\n<pre><code>results = None\nkeys, values = zip(*setup.items())\n</code></pre>\n</blockquote>\n\n<p>it should be</p>\n\n<pre><code>results = None\nkeys, values = zip(*setup.items())\n</code></pre></li>\n<li><p>There is <a href=\"https://stackoverflow.com/q/4015417/7851470\">no need to specify <code>object</code></a> in <code>class O(object)</code>, <code>class O</code> will work fine.</p></li>\n<li><p>Here:</p>\n\n<blockquote>\n<pre><code>for key, value in kwargs.items():\n if key in setup:\n setup[key] = kwargs[key] # user specified overrides default\n</code></pre>\n</blockquote>\n\n<p>you don't use <code>value</code>, but you could:</p>\n\n<pre><code>for key, value in kwargs.items():\n if key in setup:\n setup[key] = value\n</code></pre></li>\n<li><p>Here:</p>\n\n<blockquote>\n <p><code>keys, values = zip(*setup.items())</code></p>\n</blockquote>\n\n<p>you don't need <code>values</code> as you overwrite them later. So, I'd just remove this line altogether.</p></li>\n<li><p><code>set((1,))</code> can be replaced with <code>{1}</code>, and <code>set.difference</code> can be replaced with just <code>-</code>. BTW, I like how you combined two conditions from my previous review in one!</p></li>\n<li><p>Don't forget to use <code>np.can_cast</code> instead of checking the dtypes against <code>np.int64</code>. The current version failed for me until I changed it.</p></li>\n<li><p><code>[array.astype(float) for array in arrays]</code> can be written as <code>list(map(np.float64, arrays))</code> but both versions are fine.</p></li>\n<li><p>The overall design looks quite unusual to me. If it would be me, I'd separate validating data from the container that will keep it. In other words, I'd not keep it in one class. BTW, if a class has just two methods and one of them is <code>__init__</code> then <a href=\"https://www.youtube.com/watch?v=o9pEzgHorH0\" rel=\"nofollow noreferrer\">it shouldn't be a class</a>. Another thing you could try is <a href=\"https://pydantic-docs.helpmanual.io/\" rel=\"nofollow noreferrer\">pydantic</a> library. Never had a chance to try it myself though, but with this problem of data validation I'd give it a shot.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T13:28:30.183",
"Id": "456022",
"Score": "0",
"body": "Once again, thank you for the review and tutelage! There's a lot of habits to break here (some badder than others) but I'll work on all of them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-01T11:54:54.353",
"Id": "463544",
"Score": "1",
"body": "I'm now slowly de-classing; this answer keeps on giving!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T13:21:14.467",
"Id": "233331",
"ParentId": "233319",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "233331",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T09:19:11.167",
"Id": "233319",
"Score": "4",
"Tags": [
"python",
"python-3.x"
],
"Title": "Managing user defined and default values for instance attributes"
}
|
233319
|
<p>I have a form built with react, formik and yup, and this form has some async validations. Apparently, some users were able to bypass these validations, and to prevent some errors, I wanted to disable the submit button when there's a pending http request.</p>
<p>Many years ago, I used to handle this very easily with jQuery, but now, this is not the case.</p>
<p>I came up with a solution where I used the useEffect hook to set a state in case there's an http request running, and the way I'm detecting this is what I wanted your opinion.</p>
<p>Basically:</p>
<pre><code>import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { Input } from '../../../../components/Formik';
const Form = props => {
const [disableSubmitBtn, setDisableSubmitBtn] = useState(false);
useEffect(() => {
axios.interceptors.request.use(
configs => {
console.log('http req running');
setDisableSubmitBtn(true);
return configs;
},
error => {
return Promise.reject(error);
},
);
console.log('no http req running');
setDisableSubmitBtn(false);
}, [disableSubmitBtn]);
return (
<form
className="form-horizontal"
onSubmit={e => {
props.handleSubmit(e);
}}
>
{props.settings.bonuscode && (
<fieldset>
<Input
id="marketing.bonus_code"
{...props.user.marketing.bonus_code}
{...props}
classNameLabel="col-md-5"
classNameInput="col-md-7"
/>
</fieldset>
)}
<button
id="wordreg-form-submit"
type="submit"
disabled={props.settings.formSubmited || disableSubmitBtn}
>
Submit
</button>
</form>
);
};
export default Form;
</code></pre>
<p>So what matters is actually the code inside the useEffect hook. Whad do you think about it?
Is it ok to check for pending http requests this way?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T13:26:17.813",
"Id": "456021",
"Score": "0",
"body": "Nothing you can do on frontend to prevent users from bypassing frontend validations. If you want to validate anything in a reliable manner, validate it on backend."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T13:59:04.730",
"Id": "456023",
"Score": "0",
"body": "of course, but that's not the point in here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T16:00:46.770",
"Id": "456052",
"Score": "0",
"body": "I don't really know React Hooks, so take this with a grain of salt. If using useEffect() feels wrong, maybe the right approach is to write your own form. So instead of using the html form, make the React Form component be composed of the parts needed. That way, your button will have an onClick that will send a GET/POST request and at that point you can probably specify what you want to do at the moment you press it and at the moment you receive your response."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T12:21:14.050",
"Id": "456225",
"Score": "0",
"body": "@calvines the useEffect hook is meant for that. I already have my form components... I was just asking for a review as I couldn't find a solution for that after searching for it, and I created this solution on my own, which for me it seems good. as I said, I used to do this in the past with jQuery, and this time I wanted to do it with vanilla, but it felt right to me to use axios interceptors for that."
}
] |
[
{
"body": "<p>Yes, your approach looks correct to me. I also had faced similar issues earlier in my project (before hooks were introduced) and had used setState for a boolean variable to enable and disable the button. </p>\n\n<p>The thing which you need to keep in mind is look out for edge cases related to your business requirements. e.g. suppose a async validation is happening but API gave you 401 or some other status code (i.e. validation didn't happen properly but API gave some response), so should you be enabling the button for user to retry or the button should remain disable.</p>\n\n<p>Hoping that I am able to explain you properly. Please revert if something is not clear to you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T12:12:15.200",
"Id": "456222",
"Score": "0",
"body": "That's a valid point, Sunil! What I did for now is sending a GTM event in case there's an error, so that we can investigate the issue."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T19:40:21.043",
"Id": "233359",
"ParentId": "233325",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "233359",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T11:20:13.393",
"Id": "233325",
"Score": "4",
"Tags": [
"javascript",
"ecmascript-6",
"asynchronous",
"react.js",
"axios"
],
"Title": "Disabling a form button while there's an http request running"
}
|
233325
|
<p>I am learning to write test cases in iOS using Swift. I was stuck at testing <code>static</code> functions from my <code>Utilities</code> class, so I tried to mock that class and then test the cases. Please let me know if its the correct approach or else tell me how to do that. Here is my code:</p>
<pre><code>import XCTest
@testable import ConnectAndSell
class UtilitiesMock{
func getBuildNumber() -> String{
return Utilities.getAppBuildNumber()
}
func getVersionNumber() -> String{
return Utilities.getAppVersion()
}
}
class UtilitiesTests: XCTestCase {
//system under test
var sut:UtilitiesMock!
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
sut = UtilitiesMock()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
sut = nil
}
func testBuildNumber() {
let buildNumber = Bundle.main.infoDictionary?["CFBundleVersion"] as! String
XCTAssertEqual(buildNumber, sut.getBuildNumber())
}
func testVersionNumber() {
let versionNumber = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as! String
XCTAssertEqual(versionNumber, sut.getVersionNumber())
}
}
</code></pre>
<p><strong>EDIT:</strong> Adding <code>Utilities</code> class so that you guys can see what am I trying to test. It's just simple functions to verify the current build number and version number. I have taken these function just for example. My main aim is to know is it the correct approach to test <code>static</code> methods. </p>
<pre><code>import Foundation
class Utilities {
static func getAppVersion() -> String {
if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
log.debug("App verison: \(version)")
return version
}
return ""
}
static func getAppBuildNumber() -> String {
if let number = Bundle.main.infoDictionary?["CFBundleVersion"] as? String {
log.debug("Build number: \(number)")
return number
}
return ""
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T14:00:40.180",
"Id": "456024",
"Score": "3",
"body": "Hey Vishal, without more detail about the code that's being tested we can't really help you out.. You should include your full code :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T05:34:20.060",
"Id": "456185",
"Score": "1",
"body": "@IEatBagels Please check my edit section. My main goal is to know the approach to test static methods, regardless of what I am testing. Hope this will help you to suggest something :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T14:48:48.907",
"Id": "456244",
"Score": "0",
"body": "This is Code Review. Either you put forward the code and we can help you, or you're only interested in the rough outlines and you're on the wrong site. Hypothetical code is not something we handle well, as per our [help/on-topic]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T14:50:31.557",
"Id": "456245",
"Score": "0",
"body": "For an implementation demo, the outer function (invoking the code that *does* matter) doesn't have to be as strictly to the reality, but the rest does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T05:42:50.567",
"Id": "456350",
"Score": "0",
"body": "@Mast I have already added the whole code which I am trying to get reviewed by the community. What else should I add so that it can be reviewed ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-08T16:19:55.380",
"Id": "456756",
"Score": "0",
"body": "Does your `log.debug(\"Build number: \\(number)\")` wrap whatever it's doing in a `#if DEBUG;// do stuff; #endif`? If not, I'd update that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-09T04:41:48.543",
"Id": "456804",
"Score": "1",
"body": "@Adrian Yes it does that. Thanks"
}
] |
[
{
"body": "<ol>\n<li>Unit Tests should not have a dependency on the application bundle at runtime which could not be injected on the init phase or by a method arguments</li>\n</ol>\n\n<p>The given <code>Utility</code> class has a static methods which act like a shortcuts to longer syntax calls. This methods calls directly methods on <code>Bundle</code> class object which is cannot be mocked. The solution is to move <code>Bundle -> infoDictionary</code> outside of a method and set it as a static property. Now, in the app the dictionary can reference a dictionary from the app bundle and in test bundle will reference a mocked dictionary. The main purpose of a unit testing this methods will be to validate usage of given dictionary and keys to access demanded values.</p>\n\n<ol start=\"2\">\n<li>Utility methods aka class methods are not dependency injection friendly and that makes them more complicated to test</li>\n<li>UtilitiesMock is not a mock, it's more a proxy / facade / wrapper class</li>\n</ol>\n\n<p>Solution:</p>\n\n<pre><code>protocol BundleInfoDictionaryShortcuts {\n static var bundleMainInfoDictionary: [String : Any]? { get set }\n}\n\nenum BundleInfoDictionary: String {\n case keyCFBundleShortVersionString = \"CFBundleShortVersionString\"\n case keyCFBundleVersion = \"CFBundleVersion\"\n}\n\nclass Utilities: BundleInfoDictionaryShortcuts {\n\n static var bundleMainInfoDictionary: [String : Any]? = Bundle.main.infoDictionary\n\n static func getAppVersion() -> String {\n\n guard let version = bundleMainInfoDictionary?[BundleInfoDictionary.keyCFBundleShortVersionString.rawValue] as? String else {\n fatalError()\n }\n return version\n }\n\n static func getAppBuildNumber() -> String {\n guard let number = bundleMainInfoDictionary?[BundleInfoDictionary.keyCFBundleVersion.rawValue] as? String else {\n fatalError()\n }\n return number\n }\n}\n</code></pre>\n\n\n\n<pre><code>// File: BundleInfoDictionaryShortcutsTests.swift\n\nclass BundleInfoDictionaryShortcutsTests: XCTestCase {\n static let appVersion = \"1.0.1\"\n static let appBuildNumber = \"120\"\n\n override class func setUp() {\n super.setUp()\n Utilities.bundleMainInfoDictionary = [\n BundleInfoDictionary.keyCFBundleShortVersionString.rawValue: appVersion,\n BundleInfoDictionary.keyCFBundleVersion.rawValue: appBuildNumber\n ]\n }\n\n func testGetAppVersion() {\n XCTAssertEqual(Utilities.getAppVersion(), Self.appVersion)\n }\n func testGetAppBuildNumber() {\n XCTAssertEqual(Utilities.getAppBuildNumber(), Self.appBuildNumber)\n }\n }\n</code></pre>\n\n\n\n<pre><code>// File: BundleInfoDictionaryShortcutsTests.swift\n\n class BundleInfoDictionaryTests: XCTestCase {\n func testKeys() {\n XCTAssertEqual(BundleInfoDictionary.keyCFBundleShortVersionString.rawValue,\"CFBundleShortVersionString\")\n XCTAssertEqual(BundleInfoDictionary.keyCFBundleVersion.rawValue,\"CFBundleVersion\")\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-11T05:51:49.203",
"Id": "457184",
"Score": "0",
"body": "Thanks @Adobels. This a clear and detailed explanation."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-10T13:52:56.720",
"Id": "233787",
"ParentId": "233329",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "233787",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T11:50:32.570",
"Id": "233329",
"Score": "1",
"Tags": [
"unit-testing",
"swift",
"ios"
],
"Title": "Unit Test class from iOS"
}
|
233329
|
<p>I have a Canny Edge Detection Code written in C++. I would like to know how can I make it more robust in terms of detecting all the edges correctly and save it? Is this the best possible edge detection possible? Can the coders find any error in my code? Below is a picture of how the code looks like.</p>
<pre><code>#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <stdlib.h>
#include <stdio.h>
using namespace cv;
/// Global variables
Mat src, src_gray;
Mat dst, detected_edges;
int edgeThresh = 1;
int lowThreshold;
int const max_lowThreshold = 100;
int ratio = 3;
int kernel_size = 3;
char* window_name = "Edge Map";
/**
* @function CannyThreshold
* @brief Trackbar callback - Canny thresholds input with a ratio 1:3
*/
void CannyThreshold(int, void*)
{
/// Reduce noise with a kernel 3x3
blur( src_gray, detected_edges, Size(3,3) );
/// Canny detector
Canny( detected_edges, detected_edges, lowThreshold, lowThreshold*ratio, kernel_size );
/// Using Canny's output as a mask, we display our result
dst = Scalar::all(0);
src.copyTo( dst, detected_edges);
imshow( window_name, dst );
}
/** @function main */
int main( int argc, char** argv )
{
/// Load an image
src = imread( argv[1] );
if( !src.data )
{ return -1; }
/// Create a matrix of the same type and size as src (for dst)
dst.create( src.size(), src.type() );
/// Convert the image to grayscale
cvtColor( src, src_gray, CV_BGR2GRAY );
/// Create a window
namedWindow( window_name, CV_WINDOW_AUTOSIZE );
/// Create a Trackbar for user to enter threshold
createTrackbar( "Min Threshold:", window_name, &lowThreshold, max_lowThreshold, CannyThreshold );
/// Show the image
CannyThreshold(0, 0);
/// Wait until user exit program by pressing a key
waitKey(0);
return 0;
}
</code></pre>
<p><a href="https://i.stack.imgur.com/Xbxw5.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Xbxw5.jpg" alt="enter image description here"></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T14:05:22.140",
"Id": "456028",
"Score": "0",
"body": "Hey mvr950, could you maybe tell us what version of C++ and OpenCV you are using?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T14:28:34.197",
"Id": "456034",
"Score": "0",
"body": "g++ -v gave me gcc version 6.3.0 20170516 (Debian 6.3.0-18+deb9u1) opencv on synaptic is 2.4.9.1 lsb_release -a\nNo LSB modules are available.\nDistributor ID: Debian\nDescription: Debian GNU/Linux 9.3 (stretch)\nRelease: 9.3\nCodename: stretch"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T09:47:48.613",
"Id": "456374",
"Score": "0",
"body": "There are better edge detectors that utilize machine learning but they are slower and harder to manage. Also there are other classic edge detectors. It is hard to say which detectors are better in general because some are suited to certain tasks while others are faster."
}
] |
[
{
"body": "<p>In terms of making more robust, a fairly obvious improvement would be to ensure that <code>argv[1]</code> exists before using it (that's what <code>argc</code> is for). If there's no argument, or the file can't be read, emit a useful error message to <code>std::cerr</code> and return <code>EXIT_FAILURE</code> - negative return values from <code>main()</code> can vary by platform.</p>\n\n<p>Why do we declare <code>CannyThreshold</code> with two arguments, but never use them? Just declare it taking no arguments.</p>\n\n<p>Your description mentions saving the result, but I don't see any code for that - did you perhaps show us the wrong version of the program?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T14:42:18.903",
"Id": "456038",
"Score": "0",
"body": "I wanted to know about the best method to save an image in jpg or png format."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T15:05:54.737",
"Id": "456041",
"Score": "1",
"body": "That's not how Code Review works - you should have implemented to the best of your ability and shown that. We can't review code that's missing!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T15:10:58.517",
"Id": "456042",
"Score": "0",
"body": "Sorry. Thanks for pointing that out."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T14:22:56.370",
"Id": "233338",
"ParentId": "233335",
"Score": "8"
}
},
{
"body": "<p>I'm confused by this line of code:</p>\n\n<pre><code>src.copyTo( dst, detected_edges);\n</code></pre>\n\n<p>What you are doing is writing into <code>dst</code>, at the location of the detected edges, the pixel value of the original input image <code>src</code>.</p>\n\n<p>By definition, the location of the edge is somewhere half-way the transition between two more or less uniformly colored regions. Half-way you should see a color half-way between the colors of those two regions. Why is this color interesting enough to preserve in your output? What if at the location of the transition the pixel value happens to be 0?</p>\n\n<p>The purpose of the Canny edge detector is to <em>detect</em> the location of edges. It returns a binary image where the pixels at edges are set. These locations are found by using hysteresis thresholding (a two-threshold process) of an image where the pixel values were the edge strength. That is, there is an intermediate image where the intensity of the pixel is related to the contrast at the edge. Maybe you want to recover that image? If so, you'd have to copy-paste the code inside the Canny function, and leave out the last step, the thresholding.</p>\n\n<hr>\n\n<p>This line:</p>\n\n<pre><code>blur( src_gray, detected_edges, Size(3,3) );\n</code></pre>\n\n<p>is not necessary. You should be able to get the same effect by increasing the <code>apertureSize</code> parameter to <code>cv::Canny</code>. Also, a box filter is the worst type of blur filter you can apply. <a href=\"https://www.crisluengo.net/archives/22\" rel=\"nofollow noreferrer\">Here I wrote up a bit explaining what is so bad about the box filter.</a> One of the consequences of using a box filter before detecting edges is that you might find false edges.</p>\n\n<p>For best precision you'd use a Gaussian filter, and then set the <code>apertureSize</code> parameter to 1 to avoid further smoothing inside the <code>cv::Canny</code> function.</p>\n\n<hr>\n\n<p>You also get better results if you set the <code>L2gradient</code> input parameter to <code>true</code>. This makes the function use the correct definition of norm, which leads to a more rotationally-invariant filter (this means that you will get more similar results if you rotate your image by 45 degrees, apply the filter, and then rotate the result back).</p>\n\n<p>Combining the previous point and this point, you'd end up doing:</p>\n\n<pre><code>GaussianBlur( src_gray, detected_edges, Size(0,0), 2 )\nCanny( detected_edges, detected_edges, lowThreshold, lowThreshold*ratio, 1, true );\n</code></pre>\n\n<hr>\n\n<p>Regarding style:</p>\n\n<p>Try to be consistent with spacing and so on. It makes it easier to read code. For example these three consecutive lines:</p>\n\n<pre><code>dst = Scalar::all(0);\nsrc.copyTo( dst, detected_edges);\nimshow( window_name, dst );\n</code></pre>\n\n<p>The first line has no spaces inside the parentheses, the second one only after the opening parenthesis, and the third one inside both.</p>\n\n<p>A similar thing happens with the closing brackets: each one in your bit of code is on a different column.</p>\n\n<p>Finally, I would suggest that you don't do</p>\n\n<pre><code>using namespace cv;\n</code></pre>\n\n<p>and instead explicitly write <code>cv::</code> in front of each OpenCV function call. This makes it explicit where the function that you're calling comes from. This is a small program, and you only call one function that is not from OpenCV, but as your program grows, you'll have more self-written functions and maybe also call functions from a second library. Using explicit namespaces will make reading your code a lot easier.</p>\n\n<hr>\n\n<p>Regarding \"detecting all the edges correctly\":</p>\n\n<p>This depends on your definition of edge. The Canny edge detector detects all the edges correctly, using its definition of edge.</p>\n\n<p>If you define \"edges\" as the edges of all objects in the image, then it is not possible to detect them all. You can only detect edges if the contrast between the object and the background is large enough. A black object on a black background will not have any \"edges\" (edges according to Canny's definition) along its \"edges\" (the actual object's edges). If you are interested in detecting these type of edges, I recommend that you closely follow the latest research publications in the field, maybe one day someone will discover how to do this. :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-13T12:31:20.697",
"Id": "233972",
"ParentId": "233335",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "233338",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T14:03:03.993",
"Id": "233335",
"Score": "6",
"Tags": [
"c++",
"image",
"opencv"
],
"Title": "Image edge detection"
}
|
233335
|
<p>I have a live webcam windows which means there are six subdivided windows in a single window live. And show pictures in colored and black and white. Is there anyway I can make the code minimalistically minimized? I believe the code is considerably long. </p>
<pre><code>import cv2
import cv
import numpy as np
import matplotlib.image as mpimg
from matplotlib import pyplot as plt
def threshold_slow(T, image):
# grab the image dimensions
h = image.shape[0]
w = image.shape[1]
d = image.shape[2]
# loop over the image, pixel by pixel
for y in range(0, h):
for x in range(0, w):
for z in range(0, d):
# threshold the pixel
if image[y, x,z] >= T:
image[y, x,z] = 255
else:
image[y, x,z] = 0
# return the thresholded image
return image
def grab_frame(cam):
#cv2.namedWindow("test")
#img_counter = 0
while True:
ret, color1 = cam.read()
#r = 100.0 / color1.shape[1]
r = 640.0 / color1.shape[1]
#r = 0.25
dim = (100, int(color1.shape[0] * r))
dim = (640,480)
# perform the actual resizing of the image and show it
color = cv2.resize(color1, dim, interpolation = cv2.INTER_AREA)
#color = color1.copy()
b = color.copy()
# set green and red channels to 0
b[:, :, 1] = 0
b[:, :, 2] = 0
g = color.copy()
# set blue and red channels to 0
g[:, :, 0] = 0
g[:, :, 2] = 0
r = color.copy()
# set blue and green channels to 0
r[:, :, 0] = 0
r[:, :, 1] = 0
#y= color.copy()
#gray = cv2.cvtColor(l,cv2.COLOR_RGB2GRAY)
#_,y = cv2.threshold(gray, 60, 255, cv2.THRESH_BINARY)
#y = cv2.cvtColor(y, cv2.COLOR_GRAY2RGB)
y = cv2.add(r,g)
d = color.copy()
gray1 = cv2.cvtColor(d,cv2.COLOR_RGB2GRAY)
_,p = cv2.threshold(gray1, 60, 255, cv2.THRESH_BINARY)
p = cv2.cvtColor(p, cv2.COLOR_GRAY2RGB)
#threshold_slow(220,p)
return [color,b,g,r,y,p]
cam = cv2.VideoCapture(0)
#cv2.waitKey(0)
while(1):
ret, color = cam.read()
[color,b,g,r,y,p] = grab_frame(cam)
horiz = np.hstack((color,b,g))
#verti = np.vstack((color,r))
horiz1 = np.hstack((r,y,p))
verti = np.vstack((horiz,horiz1))
cv2.imshow('HORIZONTAL', verti)
if not ret:
break
k = cv2.waitKey(1)
if k%256 == 27:
# ESC pressed
print("Escape hit, closing...")
break
cam.release()
cv2.destroyAllWindows()
</code></pre>
<p><a href="https://i.stack.imgur.com/yhpRt.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/yhpRt.jpg" alt="enter image description here"></a></p>
|
[] |
[
{
"body": "<ul>\n<li><p>First, get rid of all the unneeded whitespace. Use consistent amount between functions (Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a>, recommends two).</p></li>\n<li><p>PEP8 also recommends using spaces in lists, after the commas, and <code>lower_case</code> for all variables and functions (your <code>T</code> in <code>threshold_slow</code> violates this).</p></li>\n<li><p>Don't use magic numbers in your code. Give them readable names and if necessary make them global constants:</p>\n\n<pre><code>WIDTH, HEIGHT = 640, 480\n</code></pre></li>\n<li><p>Next, since your images are already <code>numpy</code> arrays, use that fact. Your (unused) <code>threshold_slow</code> function can be replaced by a single line using <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html\" rel=\"noreferrer\"><code>numpy.where</code></a>:</p>\n\n<pre><code>def threshold_fast(T, image):\n return np.where(image >= T, 255, 0)\n</code></pre>\n\n<p>Note that this does not modify the image inplace. It is a bad practice to do that <em>and</em> return a modified/new object. You should decide, either return a new object <em>or</em> modify in place and return <code>None</code>.</p></li>\n<li><p>The <code>import cv</code> is not used (and I could not even find a way to install it anymore).</p></li>\n<li><p>Tuple assignment works also without a list on the left side, just do <code>color, b, g, r, y, p = grab_frame(cam)</code>. The same is true when returning a tuple (<code>return color, b, g, r, y, p</code>).</p></li>\n<li><p>Arguably, I would split up your <code>grab_frame</code> code into subfunctions like <code>red(image)</code>, <code>green(image)</code>, <code>blue(image)</code>, <code>yellow(image)</code>, <code>black_and_white(image)</code>.</p>\n\n<pre><code>def red(image):\n \"\"\"Copy only the red channel from image\"\"\"\n out = np.zeros_like(image)\n # for some reason red is in the last channel\n out[:, :, 2] = image[:, :, 2]\n return out\n...\n</code></pre>\n\n<p>While this move will not make your code shorter, it will make it more readable.</p></li>\n<li><p>Note that the canonical order is red, green, blue (RGB). If at all possible I would stick to that. I'm not sure why openCV would deviate from that.</p></li>\n<li><p>You should at least add a <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"noreferrer\"><code>docstring</code></a> to each of your functions as a rudimentary documentation. See above for a short example.</p></li>\n<li><p>You can use <code>while True</code> instead of <code>while(1)</code>. No parenthesis needed and <code>True</code> is unambiguous (even for those people who both know C-like languages, where <code>0</code> is <code>False</code> and shell scripting languages like bash, where non-zero is <code>False</code>).</p></li>\n<li><p>I would also add a <code>tile(images, rows)</code> function that puts your images into rows and columns. You could just use the <a href=\"https://docs.python.org/3/library/itertools.html#itertools-recipes\" rel=\"noreferrer\"><code>itertools</code> recipe</a> <code>grouper</code> for this:</p>\n\n<pre><code>from itertools import zip_longest\n\ndef grouper(iterable, n, fillvalue=None):\n \"Collect data into fixed-length chunks or blocks\"\n # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx\"\n args = [iter(iterable)] * n\n return zip_longest(*args, fillvalue=fillvalue)\n</code></pre></li>\n<li><p>Since you <a href=\"https://codereview.stackexchange.com/questions/233347/pyopencv-code-that-displays-color-b-w-and-canny-images-input-from-single-live-w\">seem to want to use different amounts of tiles, and different effects</a>, it might make sense to keep a list of functions to apply to the base image, so that in the end you only need one call:</p>\n\n<pre><code>def identity(x):\n return x\n\ndef tile(images, cols, fillvalue=None):\n return np.vstack(np.hstack(group)\n for group in grouper(images, cols, fillvalue))\n\nfuncs = identity, red, black_and_white, canny\nimages = (func(image) for func in funcs)\n# arrange them in a 2x2 grid\ncv2.imshow('HORIZONTAL', tile(images, cols=2, fillvalue=np.zeros_like(image)))\n</code></pre>\n\n<p>If the number of images is not evenly divisible by the number of columns, the row is filled up with blank images. </p></li>\n<li><p>You should put your main calling code under a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\"</code> guard</a> to allow importing from this script.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T16:32:42.533",
"Id": "233348",
"ParentId": "233340",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "233348",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T14:55:23.623",
"Id": "233340",
"Score": "5",
"Tags": [
"python",
"opencv"
],
"Title": "Display image from live webcam as taken, with four different color filters and in B/W"
}
|
233340
|
<p>The following classes are used for web development. And I was wondering if I'm implementing them correctly specially the Base class.</p>
<p>This is a version 2.0 of the <a href="https://codereview.stackexchange.com/questions/227664/php-classes-with-functions-used-for-building-a-web-application/">question</a> the classes are as follows:</p>
<ul>
<li>MyPDO</li>
<li>Session</li>
<li>Security</li>
<li>Base</li>
</ul>
<p>Examples:</p>
<pre class="lang-php prettyprint-override"><code><?php
//using the autoloader
require "../classes/autoloader.php";
// checking if the user isn't logged in so he can loggin
$session = new Session;
if ($session->is_logged_in()) {
Base::location();
}
// set session variables used by the class "logging" the user in
$session->initialize_user_session($user["admin"], $_POST["username"]);
//Redirect to another webpage and exit
Base::location();
//Encoding output to prevent XSS
$html = "<script>alert('XSS')</script>";
echo "<h1>". Security::clean_html($html) ."</h1>";
</code></pre>
<hr>
<p>My doubts are should I use the constants and is base class any good since it only has two functions and they are not that related?
The code is:</p>
<p>MyPDO class (made from phpdelusions.net) : </p>
<pre class="lang-php prettyprint-override"><code>define("DB_HOST", "localhost");
define("DB_NAME", "root");
define("DB_USER", "root");
define("DB_PASS", "root");
define("DB_CHAR", "utf8mb4");
class MyPDO extends PDO
{
public function __construct($dsn = NULL, $username = DB_USER, $password = DB_PASS, $options = [])
{
$default_options = [
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
];
$options = array_replace($default_options, $options);
$dsn = $dsn ?? "mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHAR;
parent::__construct($dsn, $username, $password, $options);
}
public function run($sql, $args = NULL)
{
if (!$args)
{
return $this->query($sql);
}
$stmt = $this->prepare($sql);
$stmt->execute($args);
return $stmt;
}
}
</code></pre>
<p>Session class:</p>
<pre class="lang-php prettyprint-override"><code>/*
* Session handling class
*/
define("ADMIN_VALUE_KEY", "admin");
define("LOGIN_VALUE_KEY", "logged_in");
define("USER_ID_KEY", "user_id");
define("CSRF_TOKEN_KEY", "csrf_token");
define("LOCATION_DEFAULT_DIR", "index.php");
class Session
{
public function __construct()
{
session_start();
}
public function initialize_user_session($admin, $user_id) {
$_SESSION[ADMIN_VALUE_KEY] = $admin;
$_SESSION[LOGIN_VALUE_KEY] = true;
$_SESSION[USER_ID_KEY] = $user_id;
$_SESSION[CSRF_TOKEN_KEY] = Security::generate_token(64);//bin2hex(random_bytes(32));
}
public function logout(){
session_destroy();
Base::location();
}
public function is_logged_in() {
return (!empty($_SESSION[USER_ID_KEY]));
}
public function is_admin() {
return (!empty($_SESSION[ADMIN_VALUE_KEY]));
}
/*
* Check functions
*/
public function check_token($token, $dir = LOCATION_DEFAULT_DIR)
{
if (!hash_equals($_SESSION[CSRF_TOKEN_KEY], $token)) {
Base::location($dir);
}
}
public function check_login($dir = LOCATION_DEFAULT_DIR)
{
if (empty($_SESSION[USER_ID_KEY])) {
Base::location($dir);
}
}
public function check_admin($dir = LOCATION_DEFAULT_DIR)
{
if (empty($_SESSION[ADMIN_VALUE_KEY])) {
Base::location($dir);
}
}
}
</code></pre>
<p>Security class:</p>
<pre class="lang-php prettyprint-override"><code>class Security
{
public static function generate_token(int $length) : string {
return bin2hex(random_bytes($length/2));
}
public static function clean_html(string $html) : string {
return htmlspecialchars($html, ENT_QUOTES, 'utf-8');
}
public static function clean_json(string $json) : string {
return json_encode($json, JSON_HEX_QUOT|JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS);
}
}
</code></pre>
<p>Base class:</p>
<pre class="lang-php prettyprint-override"><code>define("LOCATION_DEFAULT_DIR", "index.php");
class Base
{
public static function location($dir = LOCATION_DEFAULT_DIR)
{
header("Location: " . $dir);
exit();
}
public static function check_input($required, $error)
{
foreach ($required as $field) {
if (empty($_POST[$field])) {
Base::location($error);
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<h1>Constants - glabal vs. class scope</h1>\n\n<p>Definig global constants should be considered a bad practice. You should move them to the classes above which you are defining them now.</p>\n\n<p>You should also consider defining those constants private unless you need them elsewhere too (in which case they probably belong elsewhere themselves and the class in question should accept them as constructor arguments)</p>\n\n<pre><code>class Session\n{\n private const ADMIN_VALUE_KEY = \"admin\"\n}\n</code></pre>\n\n<h1>Multipurpose methods</h1>\n\n<p>Methods like this one:</p>\n\n<pre><code>public function run($sql, $args = NULL)\n{\n if (!$args)\n {\n return $this->query($sql);\n }\n $stmt = $this->prepare($sql);\n $stmt->execute($args);\n return $stmt;\n}\n</code></pre>\n\n<p>should also be considered a bad practice. Not talking about the fact that <code>run</code> is pretty bad name for this, IMHO anyway. What I mean is the method takes one argument and does something, or it takes two arguments and does something else. PHP does not have the feature of method overloading. And so you should define two separate methods for this (like PDO does). Well I know from certain angle you could say it is the same thing. And if you were forced to use two arguments because you are implementing an interface, then I would not object (except maybe the interface deserved some inspection).</p>\n\n<h1>Extending PDO</h1>\n\n<p>Extending PDO is not a very good idea as well.\nYou are doing it for 2 reasons:</p>\n\n<ol>\n<li><p>you wanted to simplify query with/without args but that is IMO useless. You always know if you want to pass arguments or not and so you can choose the right method to use.</p></li>\n<li><p>you wanted to allow default constructor with all your credentials passed, but that is not IoC, it is not SRP, it is not flexible, it introduces extra dependency...</p></li>\n</ol>\n\n<p>The simplest design pattern of all comes to rescue, the factory!</p>\n\n<pre><code>function createMyPDO(): \\PDO\n{\n return new \\PDO(/* hardcode it, load it from config file, get it from class variables, load it from database (just kidding:)), ... */);\n}\n</code></pre>\n\n<h1>Type Hints</h1>\n\n<p>You should be as specific about the types of arguments as possible. Omitting them is, well yea, it is a minor performance gain, but it is a major readability drop.</p>\n\n<p>As seen on the <code>Security</code> class, you definitely have access to the scalar typehints feature. So why not use it?</p>\n\n<p>Also if you expect array why accepting null? Like in the already mentioned <code>run</code> method.</p>\n\n<h1>Single Exit Point</h1>\n\n<pre><code>public static function location($dir = LOCATION_DEFAULT_DIR)\n{\n header(\"Location: \" . $dir);\n exit();\n}\n</code></pre>\n\n<p>Avoid calling <code>exit</code> on multiple places, there should only be one exit in your application/page. And by exit I mean a call to <code>exit</code> or the natural end of program.\nWell, we all use (or used to use) var_dump (and alike) with <code>exit</code>/<code>die</code> for development purpose (take a look at xdebug and forget var_dump btw) but in production code, only one exit point should exist, because there may be task(s) that need to be done before exit. And even if there is none now, adding it in future is like nothing if you have only one exit point.</p>\n\n<h1>Code Style</h1>\n\n<p>This is definitely a matter of preference, but it looks weird to me to have classes starting with capital letter, then methods with snake case. So I would just recommend to stick with the most common way in PHP world, and that is:</p>\n\n<pre><code>PascalCaseClass::withCamelCaseMethods()\n</code></pre>\n\n<h1>Base</h1>\n\n<p>The <code>Base</code> class looks like you didn't know what to do with those functions. They are what was left after some refactor and class splitting. But just because they are only two doesn't mean they belong together.</p>\n\n<pre><code>Base::location();\n</code></pre>\n\n<p>doesn't mean anything to me.</p>\n\n<pre><code>Response::redirect()\n</code></pre>\n\n<p>on the other hand tells me something about what it does.</p>\n\n<p>Also you dont have to wrap every two lines in a function.</p>\n\n<p>The below is absoutely ok to do and I would actually understand what it does</p>\n\n<pre><code>if (!Form::checkRequiredFields($required, $_POST)) {\n return Response::redirect($error);\n}\n</code></pre>\n\n<p>unlike I would from</p>\n\n<pre><code>Base::check_input($required, $error);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T18:09:16.780",
"Id": "456081",
"Score": "0",
"body": "A very good review with many valid points. Only a little correction: the purpose of the run() function is *to simplify query with args* in the first place which greatly reduces the amount of code to be written. the \"without\" part is indeed useless but that' s not the point"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T18:16:47.883",
"Id": "456082",
"Score": "0",
"body": "@YourCommonSense You can still call `$pdo->query($sql)` without args and `$pdo->prepare($sql)->execute($args)` with args. Not sure if it is worth simplifying to `$mypdo->run($sql, $args)`, especially if that's the only reason to extend PDO class in the first place."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T18:42:08.753",
"Id": "456086",
"Score": "0",
"body": "In most cases you need also fetch, and it's worth"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T13:20:24.983",
"Id": "456227",
"Score": "0",
"body": "I am genuinely curious, would will be your approach, given run() is renamed to query_params() with the empty $args functionality removed?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T15:55:09.437",
"Id": "456253",
"Score": "0",
"body": "@YourCommonSense First for the fetch. It's true you usualy need that as well, but the `run` method is not calling it in either case, so that is irrelevant here. For the query_params, I already said I don't think it is worth it. Anyway I didn't really propose that empty $args functionality is removed, what I wanted to say is that `$pdo->prepare($sql)->execute([])` will also work. I actualy believe that `PDO::query` is just a shorthand for this. Anyway my approach would be to not use PDO directly, I would define interface with methods I care of and wrap PDO in an implementation of that interface"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T15:57:32.627",
"Id": "456254",
"Score": "0",
"body": "@YourCommonSense True is however, that actually I never use PDO directly. That is the job of DBAL. And DBAL is actualy such an interface like I mentioned. I actually also rarely use DBAL directly. Mostly I use ORM which is yet another layer wrapping DBAL...."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T16:00:34.217",
"Id": "456255",
"Score": "0",
"body": "run() returns a PDOStatement instance to which any fetch*() could be chained. $pdo->prepare($sql)->execute() returns a boolean and that's the exact reason for all the mess. There are no useless methods in PDO so you'll end up duplicating all the functionality. I do understand it's the right thing to do but... It feels too WET."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T16:04:00.420",
"Id": "456256",
"Score": "0",
"body": "That's actually why I avoid PDO entirely. I don't mind if it is deep inside objects I really use directly. But 1. PDO is too low level to do anything from application domain with it directly and easily. 2. PDO does not even have an explicit interface which is something I don't like to depend on. I like if my classes depend on interfaces, not other classes..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T16:09:34.583",
"Id": "456257",
"Score": "0",
"body": "@YourCommonSense And as you say, there are no useless methods on PDO. The run method is just a single and simple use case for two of them. It does not bring anything new... If it really has to exist, it should exist separately from the PDO class and just depend on it, not inherit it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T16:22:26.390",
"Id": "456258",
"Score": "0",
"body": "Can you explain what you mean when you say there should be a single exit point?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T16:25:20.713",
"Id": "456259",
"Score": "0",
"body": "I use the `Response::redirect()` function to do error handling that way instead of having multiple levels of if's I check error by error and then if the error exists I forward the user to a page and exit (basically the return early principle but outside of a function)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T16:25:41.103",
"Id": "456260",
"Score": "0",
"body": "@DavidMachado When you redirect, you call exit. That is one exit point. When you don't redirect the exit point is after the last echo of your example. Your code should always end on the same and only exit point."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T16:32:56.113",
"Id": "456261",
"Score": "0",
"body": "@DavidMachado It surely seems ok for very simple use case. But you are asking for code review. If you want to learn how to do things right in general. This is it. Early return being good is also disputable btw..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T16:33:10.520",
"Id": "456262",
"Score": "0",
"body": "I do it that way so that the whole code doesn't get wrapped in an if else for each error"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T16:38:06.923",
"Id": "456263",
"Score": "0",
"body": "@DavidMachado Why each? Why not `$redirect = checkRedirect(); if ($redirect) {addRedirectHeader($redirect);} else {renderPage();} exit;` Simple and you retain one exit point (for the page, should there be one exit point for the whole application)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T16:47:28.113",
"Id": "456264",
"Score": "0",
"body": "Interisting approach, thank you for all the insights and the code review ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T16:59:36.823",
"Id": "456266",
"Score": "0",
"body": "@DavidMachado You are welcome. Btw I just realized one thing I missed in the review and I'm not sure how to say it without offending you :D So I just say it. Your classes (except MyPDO) are not really classes. They are more like \"namespaces\". This is not really OOP. A class should have its data and its related behaviour."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T17:05:58.690",
"Id": "456270",
"Score": "0",
"body": "No offense, I just want to learn keep throwing critics at me. What is data and related behaviour?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T17:08:08.027",
"Id": "456271",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/101799/discussion-between-slepic-and-david-machado)."
}
],
"meta_data": {
"CommentCount": "19",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T17:24:58.350",
"Id": "233351",
"ParentId": "233341",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "233351",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T15:04:31.483",
"Id": "233341",
"Score": "5",
"Tags": [
"php",
"object-oriented",
"comparative-review"
],
"Title": "PHP OOP classes used for building web applications"
}
|
233341
|
<p>I have a C++ program where the input are 2 arrays, each containing <code>a</code> and <code>z</code> number of elements. The program then creates all possible combinations using all elements in both arrays. For example, if one array had <code>2^4</code> elements and the other had <code>2^7</code> elements, the total possible combinations would be <code>(16 - 1) * (128 - 1) = 1,905</code>.</p>
<p>Finding all combinations of the arrays can be done in a relatively quick time either by printing to console or writing the combinations to a file. The problem seems to be when writing the array to vector at the end <code>main.cpp</code> as this significantly slows the program after each iteration. </p>
<p>main.cpp</p>
<pre><code>double ZProfile1Array[MPROFILEVAL];
double AProfile1Array[MPROFILEVAL];
int solver(char *filename){
char zLine[MCOMBIN][300];
FILE *plist;
int i = 0; int stotal = 0;
// Get array of possible combinations into zLine array
char *sdfilename = getDSFileName(1);
plist = fopen(sdfilename,"r");
while(fgets(zLine[i],sizeof(zLine[i]),plist)){
zLine[i][strlen(zLine[i]) - 1] = '\0'; // gets rid of \n that fgets gets
i++;
}
fclose(plist);
stotal = i;
// Get array of possible combinations into aLine array
sdfilename = getDSFileName(2);
char aLine[MCOMBIN][300];
i = 0; int dtotal = 0;
plist = fopen(sdfilename,"r");
while(fgets(aLine[i],sizeof(aLine[i]),plist)){
aLine[i][strlen(aLine[i]) - 1] = '\0'; // gets rid of \n that fgets gets
i++;
}
fclose(plist);
dtotal = i;
std::vector<double> itemA;
std::vector<double> itemZ;
std::string aCombo;
std::string zCombo;
char *token;char *tokend;char tstr[300];
int index = 0;
int j = 0;int id = 0; int jd = 0;int indexd = 0;
// for each value of Sigma nA
for(i = 1; i < zTotal; i++){ // i = 1 because first line is always empty
zCombo = "";
for(j = 0; j < rows; j++)ZProfile1Array[j] = 0;
token = strtok(zLine[i]," ");
index = 0;
while (token){
index = atoi(token) - 1; // because array indicies start from 0
token = strtok(NULL," ");
for(j = 0; j < rows; j++){
ZProfile1Array[j] += zprofile[index][j];
}
zCombo.append(sname[index]);
zCombo.append(" + ");
}
zCombo.resize(zCombo.size() - 3); // remove trailing " + "
// for each value of Sigma nZ
for(id = 1; id < aTotal; id++){ // i = 1 because first line is always empty
aCombo = "";
for(jd = 0; jd < rows; jd++)AProfile1Array[jd] = 0;
strcpy(tstr,aLine[id]); // use strtok on tstr because will be called a number of times and we don't want to modify aLine
tokend = strtok(tstr," ");
indexd = 0;
while (tokend){
indexd = atoi(tokend) - 1; // because array indicies start from 0 and nZ starts from 1
tokend = strtok(NULL," ");
for(jd = 0; jd < rows; jd++){
AProfile1Array[jd] += aprofile[indexd][jd];
}
aCombo.append(dname[indexd]);
aCombo.append(" + ");
}
aCombo.resize(aCombo.size() - 3); // remove trailing " + "
// write array to vector
// *** next several lines slows down script ***
std::fill(itemZ.begin(),itemZ.end(),0.0);
std::fill(itemA.begin(),itemA.end(),0.0);
for(int ii = 0; ii < rows; ii++){
itemZ.push_back(ZProfile1Array[ii]);
itemA.push_back(AProfile1Array[ii]);
}
printf("(%s,%s)\n",zCombo.c_str(),aCombo.c_str());
}
}
}
</code></pre>
<p>Can the slowdown be avoided?</p>
<p>This is the core script of the program and calls on other functions from other files but I do not think they are relevant but can include them if necessary. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T15:35:52.117",
"Id": "456046",
"Score": "0",
"body": "Are those `std::fill`s correct? They zero out most of the data, except whatever was added on the last iteration"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T15:48:34.203",
"Id": "456048",
"Score": "0",
"body": "@harold - Considering it slows the program down, it probably isn't the ideal solution but I have only recently started to use C++ so still getting used to using the language. `itemZ` and `itemA` are used later in the script so an alternative method would be welcome."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T15:48:41.390",
"Id": "456049",
"Score": "0",
"body": "Usually C++ implementations initialize `std::vector` to 0 capacity and they increase as it grows. I would try to do `item<A|Z>.reserve(<amount>)` with both vectors right after you define them and see if that works. If you know `amount` at that point just use it otherwise use a big value, it will grow if it needs to anyway. This is a very competitive programming trick that usually doesn't make an incredibly huge difference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T16:00:42.833",
"Id": "456051",
"Score": "0",
"body": "@calvines - Thanks for the good tip, tried it and it might have helped a little."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T16:04:58.473",
"Id": "456053",
"Score": "0",
"body": "@Joseph Also, why exactly do you need the `std::fill` calls? I don't really follow that part of the logic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T16:24:26.353",
"Id": "456054",
"Score": "1",
"body": "To make your code ready for a humane code review, youshouldletyourIDEaddthemissingspacesaroundoperatorsandseveralotherplaces, because that makes the code more readable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T16:26:33.560",
"Id": "456056",
"Score": "1",
"body": "The code doesn't compile for me since `MPROFILEVAL` is undefined. Please change your code so that it compiles, and provide some example data so that we can experiment and review the code under realistic conditions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T16:51:01.443",
"Id": "456064",
"Score": "1",
"body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T16:52:10.227",
"Id": "456066",
"Score": "1",
"body": "You'll receive better reviews if you show a complete example. For example, I recommend that you [edit] to show the necessary `#include` lines, and a `main()` that shows how to call your function. It can really help reviewers if they are able to compile and run your program."
}
] |
[
{
"body": "<p>That code is so convoluted (Looks like C).</p>\n\n<p>To read a file into a vector of double.</p>\n\n<pre><code>#include <vector>\n#include <iterator>\n#include <fstream>\n\n...\n\nstd::ifstream file(\"filename\");\nstd::vector<double> data(std::istream_iterator<double>{file},\n std::istream_iterator<double>{});\n</code></pre>\n\n<p>Done.</p>\n\n<hr>\n\n<p>Vectors resize and copy there content from the old to new data space if they run out of room. To prevent this you can reserve enought space for all elements so that no reallocation happens.</p>\n\n<pre><code>std::vector<double> itemA;\nstd::vector<double> itemZ;\n\n// You don't specify where rows is defined or set.\n// But we know that these arrays will eventually reach this size.\n\nitemA.reserve(rows);\nitemZ.reserve(rows);\n</code></pre>\n\n<hr>\n\n<p>These lines are doing nothing useful:</p>\n\n<pre><code>std::fill(itemZ.begin(),itemZ.end(),0.0);\nstd::fill(itemA.begin(),itemA.end(),0.0);\n</code></pre>\n\n<p>It this point both vectors have zero elements and thus it does nothing.</p>\n\n<hr>\n\n<p>This is not C++</p>\n\n<pre><code>printf(\"(%s,%s)\\n\",zCombo.c_str(),aCombo.c_str());\n</code></pre>\n\n<p>Stop using features from other languages.\nC++ has much better console output operations.</p>\n\n<pre><code>std::cout << \"(\" << zCombo << \",\" << aCombo << \")\\n\";\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T00:37:08.957",
"Id": "233377",
"ParentId": "233344",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T15:27:06.977",
"Id": "233344",
"Score": "-2",
"Tags": [
"c++",
"array",
"vectors"
],
"Title": "Writing array to vector slows down program after each iteration"
}
|
233344
|
<p>I have functioning code that I wrote what seems like a long time ago in a <code>Worksheet_Change</code> event, and even though this works I'm sure that it can be written better. I'm thinking passing the items like <code>CustName = Split(cell.Offset(0,-1).Value, "-")(0)</code> to a variable in a Sub or Function for generating the Email, might be better and easier to maintain, but for the life of me I cannot wrap my head around how to accomplish this. I am open to all thoughts and suggestions y'all have.</p>
<pre><code>Private Sub Worksheet_Change(ByVal Target As Range)
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim pEmail As String
pEmail = "ZackE@VBAisfun.codingrules"
Dim Recipient As String
Recipient = "Zack"
Dim EmailAddr As String
EmailAddr = pEmail
Dim RgCell As Range
Set RgCell = Range("C3:C100")
Dim RgSel As Range
Set RgSel = Intersect(Target, RgCell)
Dim cell As Range
Dim CustName As String, TitleCo As String, ClsDate As String, ContractPrice As String
Dim lamount As String, Product As String, Msg As String, Notes As String
If Not RgSel Is Nothing Then
Dim OutlookApp As Object
Set OutlookApp = CreateObject("Outlook.Application")
Dim MItem As Object
Set MItem = OutlookApp.CreateItem(0)
For Each cell In RgSel
If LCase(cell.Value) = "zack" Then
CustName = Split(cell.Offset(0, -1).Value, "-")(0)
lamount = Format(cell.Offset(0, 14).Value, "Currency")
ClsDate = cell.Offset(0, 8).Value
ContractPrice = Format(cell.Offset(0, 13).Value, "Currency")
Product = cell.Offset(0, 15).Value
TitleCo = cell.Offset(0, 2).Value
Notes = cell.Offset(0, 17).Value
Dim Subj As String
Subj = "***NEW LOAN ASSIGNED***" & " - " & UCase(CustName)
Dim strBeforeRows As String
strBeforeRows = "<head><style>table, th, td {border: 1px solid gray; border-collapse:" & "collapse;}</style></head><body>" & _
"<p>" & "Hello " & Recipient & "," & "<br><br>" & vbNewLine & vbNewLine & _
"You have been assigned the following loan for " & CustName & "." & "</p>" & vbNewLine & _
"<table style=""width:100%""><tr>" & _
"<th bgcolor=""#bdf0ff"">Product</th>" & _
"<th bgcolor=""#bdf0ff"">Loan Amount</th>" & _
"<th bgcolor=""#bdf0ff"">Closing Date</th>" & _
"<th bgcolor=""#bdf0ff"">Title Company</th>" & _
"<th bgcolor=""#bdf0ff"">Notes</th>" & _
"<th bgcolor=""#bdf0ff"">Contract Price</th></tr>"
Dim strRows As String
strRows = strRows & "<tr>"
strRows = strRows & "<td ""col width=10%"">" & Product & "</td>"
strRows = strRows & "<td ""col width=10%"">" & lamount & "</td>"
strRows = strRows & "<td ""col width=10%"">" & ClsDate & "</td>"
strRows = strRows & "<td ""col width=10%"">" & TitleCo & "</td>"
strRows = strRows & "<td ""col width=10%"">" & Notes & "</td>"
strRows = strRows & "<td ""col width=10%"">" & ContractPrice & "</td>"
strRows = strRows & "</tr>"
Dim strAfterRows As String
strAfterRows = "</table></body>"
Dim strAll As String
strAll = strBeforeRows & strRows & strAfterRows
With MItem
.Display
.To = EmailAddr
.Subject = Subj
.HTMLBody = strAll & "<br>" & .HTMLBody
.Send
End With
End If
Next cell
End If
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
</code></pre>
|
[] |
[
{
"body": "<p>I will assume you have used <code>Option Explicit</code> at the top of every module. </p>\n\n<p>Some kudos up front:</p>\n\n<ul>\n<li>Declaration of variables where you are going to use them</li>\n<li>Reasonable indenting (why the additional indent for <code>For Each cell In RgSel</code>?)</li>\n<li>Reasonable variable names (although <code>lamount</code> could be <code>loanAmount</code>)</li>\n</ul>\n\n<h2>Explicit range calls</h2>\n\n<p>I see one potential 'gotcha' in the code:</p>\n\n<pre><code>Set RgCell = Range(\"C3:C100\")\n</code></pre>\n\n<p>Always fully qualify cells. In your code above, this is the only time you explicitly call a range, which minimises the impact (good design choice!). In this case, you are using the code in a Worksheet module and I am assuming that the range you want to use is also on this worksheet. So the change is simply:</p>\n\n<pre><code>Set RgCell = Me.Range(\"C3:C100\")\n</code></pre>\n\n<p>But then, I ask the question - why C3 to C100? Why not C99 or C1000? In Excel, you can use <strong>named ranges</strong>. Used properly, they will shrink and grow as you add/remove cells - meaing that you can dispense with magic numbers and guessing the count of cells! So in this case, you could call the range of cells 'ApplicantNames'. The resultant code could look like either of the two below:</p>\n\n<pre><code>Set RgCell = Me.Range(\"ApplicantNames\")\nSet RgCell = Me.Names(\"ApplicantNames\").RefersToRange\n</code></pre>\n\n<p>The <code>Worksheet_Change</code> event trigger may sometimes be something other than a user interaction, so the active sheet may not be what you think it is.</p>\n\n<h2>Know when to stop referring to Excel objects</h2>\n\n<p>At some point in the code, you are using Excel as a database. In this case, it is very early. Every time the code makes a reference to a Range or some other Excel-specific action, the code has to switch from the VBA Engine to the Excel Engine. This costs in terms of performance. In your case, it may not be noticeable because you are likely only dealing with a few rows. But if you were to deal with a 1000 rows, you would certainly notice the performance hit!</p>\n\n<p>Seeing as you don't do anything to the excel data itself, you can make a single call to the Excel part, collect all the data and then work exclusively in the VBA engine. This is done by arrays.</p>\n\n<pre><code>Set RgSel = Intersect(Target, RgCell)\nSet RgSel = RgSel.Offset(0,-1)\nSet RgSel = RgSet.Resize(,18) ' based on the offsets you used in the original code\nDim myData as Variant\nmyData = RgSel.Value\n</code></pre>\n\n<p>'myData' is now a 2-D array.</p>\n\n<pre><code>For Each cell In RgSel\n</code></pre>\n\n<p>Now becomes</p>\n\n<pre><code>For someIterator = LBound(myData, 1) to UBound(myData, 1) ' iterate through the rows\n</code></pre>\n\n<p>And, as an example, you can then get your key information like:</p>\n\n<pre><code>TitleCo = myData(someIterator, 3)\n</code></pre>\n\n<h2>Magic Numbers</h2>\n\n<p>Try and avoid magic numbers (and strings) by declaring them as public constants in their own module. This makes them obvious, and you know where to find them if you want to change them.</p>\n\n<p>Examples of magic numbers and the resultant code:</p>\n\n<pre><code>If LCase(cell.Value) = \"zack\" Then ' <-- or did you mean 'recipient' in this case?\n\nPublic Const SUBJECTPREFIX As String = \"***NEW LOAN ASSIGNED***\" & \" - \"\nSubj = SUBJECTPREFIX & UCase(CustName)\n\nPublic Const TDCOLWIDTH As String = \"<td \"\"col width=10%\"\">\"\n\nDim strRows As String\nstrRows = strRows & \"<tr>\"\nstrRows = strRows & TDCOLWIDTH & Product & \"</td>\"\nstrRows = strRows & TDCOLWIDTH & lamount & \"</td>\"\nstrRows = strRows & TDCOLWIDTH & ClsDate & \"</td>\"\nstrRows = strRows & TDCOLWIDTH & TitleCo & \"</td>\"\nstrRows = strRows & TDCOLWIDTH & Notes & \"</td>\"\nstrRows = strRows & TDCOLWIDTH & ContractPrice & \"</td>\"\nstrRows = strRows & \"</tr>\"\n\nPublic Const BODYLEADER as String = \"<head><style>table, th, td {border: 1px solid gray; border-collapse:\" & \"collapse;}</style></head><body>\" & _\n \"<p>\" & \"Hello \"\nPublic Const BODYINTRO As String = \", <br><br>\" & vbNewLine & vbNewLine & _\n \"You have been assigned the following loan for \"\nPublic Const BODYTABLEHEADERS As String = \".\" & \"</p>\" & vbNewLine & _\n \"<table style=\"\"width:100%\"\"><tr>\" & _\n \"<th bgcolor=\"\"#bdf0ff\"\">Product</th>\" & _\n \"<th bgcolor=\"\"#bdf0ff\"\">Loan Amount</th>\" & _\n \"<th bgcolor=\"\"#bdf0ff\"\">Closing Date</th>\" & _\n \"<th bgcolor=\"\"#bdf0ff\"\">Title Company</th>\" & _\n \"<th bgcolor=\"\"#bdf0ff\"\">Notes</th>\" & _\n \"<th bgcolor=\"\"#bdf0ff\"\">Contract Price</th></tr>\"\n\nstrBeforeRows = BODYLEADER & Recipient & BODYINTRO & CustName & BODYTABLEHEADERS\n</code></pre>\n\n<p>As I noted above, the declaration of the magic numbers should be in their own module, not mixed with the code as I have done here. Even if you use the <code>Const</code> only once in the code, this is good code hygiene because it makes magic numbers obvious, it makes the easier to find and thus makes the code easier to maintain. In addition, the actual code now is self commenting - previously there was a wall of string that people had to guess what it actually meant.</p>\n\n<p>In the case of TABLEHEADERS and TDCOLWIDTH, if you add another column, you can now have the two lines of code adjacent to each other, and you are less likely to forget to amend the column widths to suit the new headers!</p>\n\n<h2>Finally</h2>\n\n<pre><code>Application.ScreenUpdating = False\nApplication.DisplayAlerts = False\n\nApplication.DisplayAlerts = True\nApplication.ScreenUpdating = True\n</code></pre>\n\n<p>With the code in the OP, <code>.ScreenUpdate = False</code> does nothing, because no events exist that cause the screen to repaint. I am not sure that any alerts will be generated by Excel either. With a change to using arrays, performance should not be an issue.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T20:30:28.677",
"Id": "456097",
"Score": "0",
"body": "Thank you for the very detailed explanation. Yes, `Option Explicit` is at the top of the module. I keep forgetting about the `Public Const` and need to start to use that more. I will definitely make the adjustments when I am able to get back to this project. I will let you know how it goes and accept the answer once ive tested everything out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T14:08:32.997",
"Id": "456406",
"Score": "0",
"body": "I used a hybrid of your suggestions and TinMan's, but since I used more of TinMan's suggestions and edits I accepted his answer. Thank you again for the very helpful information. Both you and TinMan have taught me a lot in my last few posts."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T15:26:59.400",
"Id": "456425",
"Score": "0",
"body": "The Signature must be apart of the original HTMLBody. Try inserting the new html into the beginning of the `MailItem.HTMLBody ` like you were doing. (e.g. `MailItem.HTMLBody = NewHTML & MailItem.HTMLBody`)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T20:12:42.923",
"Id": "233362",
"ParentId": "233345",
"Score": "4"
}
},
{
"body": "<p>Compact html is very hard to read and edit.</p>\n\n<blockquote>\n<pre><code> strBeforeRows = \"<head><style>table, th, td {border: 1px solid gray; border-collapse:\" & \"collapse;}</style></head><body>\" & _\n \"<p>\" & \"Hello \" & Recipient & \",\" & \"<br><br>\" & vbNewLine & vbNewLine & _\n \"You have been assigned the following loan for \" & CustName & \".\" & \"</p>\" & vbNewLine & _\n \"<table style=\"\"width:100%\"\"><tr>\" & _\n \"<th bgcolor=\"\"#bdf0ff\"\">Product</th>\" & _\n \"<th bgcolor=\"\"#bdf0ff\"\">Loan Amount</th>\" & _\n \"<th bgcolor=\"\"#bdf0ff\"\">Closing Date</th>\" & _\n \"<th bgcolor=\"\"#bdf0ff\"\">Title Company</th>\" & _\n \"<th bgcolor=\"\"#bdf0ff\"\">Notes</th>\" & _\n \"<th bgcolor=\"\"#bdf0ff\"\">Contract Price</th></tr>\"\n<head><style>table, th, td {border: 1px solid gray; border-collapse:collapse;}</style></head><body><p>Hello Zack,<br><br>\n</code></pre>\n</blockquote>\n\n<p>Likewise the output is equally hard to read.</p>\n\n<pre><code>You have been assigned the following loan for Bugs.</p>\n<table style=\"width:100%\"><tr><th bgcolor=\"#bdf0ff\">Product</th><th bgcolor=\"#bdf0ff\">Loan Amount</th><th bgcolor=\"#bdf0ff\">Closing Date</th><th bgcolor=\"#bdf0ff\">Title Company</th><th bgcolor=\"#bdf0ff\">Notes</th><th bgcolor=\"#bdf0ff\">Contract Price</th></tr><tr><td \"col width=10%\">Product</td><td \"col width=10%\">Loan Amt</td><td \"col width=10%\">12/3/2019</td><td \"col width=10%\">Acme Title</td><td \"col width=10%\">Notes</td><td \"col width=10%\">Price</td></tr></table></body>\n</code></pre>\n\n<p>Writing well formatted code that produces well formatted html will make it much easier to read, write and modify procedures.</p>\n\n<p>Although <code>bgcolor</code> is supported by Outlook Mail html editor, it is depreciated. Use <code>background-color</code> instead.</p>\n\n<pre><code>\"<td \"\"col width=10%\"\">\"\n</code></pre>\n\n<p><code>col</code> is not an attribute, it is a html tag. I recommend using any relevant table section tags (Col tags belong in a colgroup, column headers a tr in the thead, standard cells in a tr in the tbody...etc.) </p>\n\n<p>Using single quotes will make your code easier to read.</p>\n\n<pre><code><col width='10%'>\n</code></pre>\n\n<p>Why use inline styles when you have a style tag?</p>\n\n<pre><code>\"<th bgcolor=\"\"#bdf0ff\"\">Product</th>\"\n\n\n.HTMLBody = strAll & \"<br>\" & .HTMLBody\n</code></pre>\n\n<p>Replace the HTMLBody altogether, don't concatenate it to your html. The default HTMLBody could potentially cause your message to display improperly.</p>\n\n<p>Generating the html template, compiling the table rows, and creating the MailItem should be separate functions called by the <code>Worksheet_Change</code> event. This will make it easier to test each part of the code. </p>\n\n<h2>Sample Code</h2>\n\n<p>Notice that I put a Stop after I display the message. This allows me to make changes to the functions that generate the html and update the message htmlbody. This is a massive time saver. </p>\n\n<pre><code>Option Explicit\n\nPublic Const TBodyMarker As String = \"@tbody\"\n\nSub CreateTestEmail()\n\n Dim Outlook As Object\n Set Outlook = CreateObject(\"Outlook.Application\")\n\n Dim MailItem As Object\n Set MailItem = Outlook.CreateItem(0)\n\n With MailItem\n Const olFormatHTML As Long = 2\n .BodyFormat = olFormatHTML\n .HTMLBody = TestMessage\n .Display\n\n Stop\n End With\n\nEnd Sub\n\nFunction TestMessage() As String\n Dim HTMLBody As String\n HTMLBody = getLoanMessageHTML\n\n Dim TBody As String\n TBody = getTR(\"Clothing\", \"$10,000\", #1/1/2020#, \"Acme Title\", \"Blah Blah Blah\", \"$200.00\")\n TBody = TBody & vbNewLine & getTR(\"Purses\", \"$1000\", #12/1/2019#, \"Acme Title\", \"Blah Blah Blah\", \"$50.00\")\n HTMLBody = Replace(HTMLBody, TBodyMarker, TBody)\n TestMessage = HTMLBody\nEnd Function\n\nFunction getLoanMessageHTML()\n Dim list As Object\n Set list = CreateObject(\"System.Collections.Arraylist\")\n list.Add \"<html>\"\n list.Add Space(2) & \"<head>\"\n list.Add Space(4) & \"<style>\"\n Rem Table\n list.Add Space(6) & \"table {\"\n list.Add Space(8) & \"width:100%;\"\n list.Add Space(6) & \"}\"\n Rem Table TH TD\n list.Add Space(6) & \"table, th, td {\"\n list.Add Space(8) & \"border:1px solid gray;\"\n list.Add Space(8) & \"border-collapse:collapse;\"\n list.Add Space(6) & \"}\"\n Rem TH\n list.Add Space(6) & \"th {\"\n list.Add Space(8) & \"background-color:#bdf0ff;\"\n list.Add Space(6) & \"}\"\n list.Add Space(4) & \"</style>\"\n list.Add Space(2) & \"<head>\"\n list.Add Space(2) & \"<body>\"\n Rem Message To Zack\n list.Add Space(4) & \"<p>Hello Zack,<br><br>\"\n Rem Table\n list.Add Space(4) & \"<table>\"\n Rem Column Group\n list.Add Space(6) & \"<colgroup>\"\n list.Add Space(8) & \"<col width='10%'>\"\n list.Add Space(8) & \"<col width='10%'>\"\n list.Add Space(8) & \"<col width='10%'>\"\n list.Add Space(8) & \"<col width='10%'>\"\n list.Add Space(8) & \"<col width='10%'>\"\n list.Add Space(8) & \"<col width='10%'>\"\n list.Add Space(6) & \"</colgroup>\"\n Rem THead\n list.Add Space(6) & \"<thead>\"\n list.Add Space(8) & \"<tr>\"\n list.Add Space(10) & \"<th>Product</th>\"\n list.Add Space(10) & \"<th>Loan Amount</th>\"\n list.Add Space(10) & \"<th>Closing Date</th>\"\n list.Add Space(10) & \"<th>Title Company</th>\"\n list.Add Space(10) & \"<th>Notes</th>\"\n list.Add Space(10) & \"<th>Contract Price</th>\"\n list.Add Space(8) & \"</tr>\"\n list.Add Space(6) & \"</thead>\"\n list.Add Space(6) & \"<tbody>\"\n Rem TBody\n list.Add Space(6) & TBodyMarker\n list.Add Space(6) & \"</tbody>\"\n list.Add Space(4) & \"</table>\"\n list.Add Space(2) & \"</body>\"\n list.Add \"</html>\"\n\n getLoanMessageHTML = Join(list.ToArray, vbNewLine)\nEnd Function\n\nFunction getTR(ParamArray TDValues() As Variant)\n Dim list As Object\n Set list = CreateObject(\"System.Collections.Arraylist\")\n Dim Item As Variant\n list.Add Space(8) & \"<tr>\"\n For Each Item In TDValues\n list.Add Space(10) & \"<td>\" & Item & \"</td>\"\n Next\n list.Add Space(8) & \"</tr>\"\n getTR = Join(list.ToArray, vbNewLine)\nEnd Function\n</code></pre>\n\n<p>Having formatted output will also save you a lot of time and aggravation in the long run.</p>\n\n<pre><code><html>\n <head>\n <style>\n table {\n width:100%;\n }\n table, th, td {\n border:1px solid gray;\n border-collapse:collapse;\n }\n th {\n background-color:#bdf0ff;\n }\n </style>\n <head>\n <body>\n <p>Hello Zack,<br><br>\n <table>\n <colgroup>\n <col width='10%'>\n <col width='10%'>\n <col width='10%'>\n <col width='10%'>\n <col width='10%'>\n <col width='10%'>\n </colgroup>\n <thead>\n <tr>\n <th>Product</th>\n <th>Loan Amount</th>\n <th>Closing Date</th>\n <th>Title Company</th>\n <th>Notes</th>\n <th>Contract Price</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>Clothing</td>\n <td>$10,000</td>\n <td>1/1/2020</td>\n <td>Acme Title</td>\n <td>Blah Blah Blah</td>\n <td>$200.00</td>\n </tr>\n <tr>\n <td>Purses</td>\n <td>$1000</td>\n <td>12/1/2019</td>\n <td>Acme Title</td>\n <td>Blah Blah Blah</td>\n <td>$50.00</td>\n </tr>\n </tbody>\n </table>\n </body>\n</html>\n</code></pre>\n\n<p>The sample code above is just a mockup. In practice I might store the html template in a textbox for easier viewing and modifications. I would also write a message class with settings to save, send or display the email. IMO having it all wrapped up in a class will make it easier to test.</p>\n\n<h2>Sample Class: EmailIyem</h2>\n\n<pre><code>Option Explicit\n\nPrivate MailItem As Object\nPrivate Outlook As Object\n\nPublic Property Get GetMailItem() As Object\n Rem Some Code\nEnd Property\n\nPublic Property Get GetOutlook() As Object\n Rem Some Code\nEnd Property\n\nPublic Function CreateMailItem() As Object\n If Not MailItem Is Nothing Then\n Rem What do you want to do here?\n Rem Do you want to throw an Error?\n Rem Or have a Msgbox() propting to replace the current MailItem?\n End If\n If Outlook Is Nothing Then\n Rem What do you want to do here?\n Set Outlook = CreateObject(\"Outlook.Application\")\n End If\n\n Set MailItem = Outlook.CreateItem(0)\nEnd Function\n\nPublic Function Send() As Boolean\n Rem Raise Error if MailItem is Nothing\n Rem Attempt to Send the MailItem and return the True if sent\nEnd Function\n\nPublic Sub Display()\n Rem Raise Error if MailItem is Nothing\n MailItem.Display\nEnd Sub\n\nPublic Function Save() As Boolean\n Rem Raise Error if MailItem is Nothing\n Rem Attempt to Save the MailItem and return the True if Saved\nEnd Function\n\nPublic Property Get HTMLBody() As String\n Rem Raise Error if MailItem is Nothing\n HTMLBody = Me.GetMailItem.HTMLBody\nEnd Property\n\nPublic Property Let HTMLBody(ByVal newHTMLBody As String)\n Rem Raise Error if MailItem is Nothing\n Me.GetMailItem.HTMLBody = newHTMLBody\nEnd Property\n\nPublic Property Get Subject() As String\n Rem Raise Error if MailItem is Nothing\n Subject = Me.GetMailItem.Subject\nEnd Property\n\nPublic Property Let Subject(ByVal newSubject As String)\n Rem Raise Error if MailItem is Nothing\n Me.GetMailItem.Subject = newSubject\nEnd Property\n\nPublic Property Get BCC() As String\n Rem Raise Error if MailItem is Nothing\n BCC = Me.GetMailItem.BCC\nEnd Property\n\nPublic Property Let BCC(ByVal newBCC As String)\n Rem Raise Error if MailItem is Nothing\n Me.GetMailItem.BCC = newBCC\nEnd Property\n\nPublic Property Get CC() As String\n Rem Raise Error if MailItem is Nothing\n CC = Me.GetMailItem.CC\nEnd Property\n\nPublic Property Let CC(ByVal newCC As String)\n Rem Raise Error if MailItem is Nothing\n Me.GetMailItem.CC = newCC\nEnd Property\n</code></pre>\n\n<p>This is just a rough muck-up. The purpose of the class is to encapsulate the methods, settings and error handling associated for working with MailItems. Avoid adding feature that are specific to the current project. These features can easily be implemented in another class or module. Keeping the logic separate from the implementation will allow you to reuse the class in many other projects.</p>\n\n<p>For example:</p>\n\n<p>Instead of hard coding an html template and having a routine that builds a specific table, you could create a Template property and a InsertHTML method.</p>\n\n<pre><code>Public Property Get HTMLTemplate() As String\n\nEnd Property\n\nPublic Property Let HTMLTemplate(ByVal newHTMLTemplate As String)\n\nEnd Property\n\nPublic Function InsertHTML(ByVal Find As String, ByVal Replacement As String) As Boolean\n If InStr(Me.HTMLTemplate, Find) > 0 Then\n Me.HTMLTemplate = Replace(Me.HTMLTemplate, Find, Replacement)\n InsertHTML = True\n End If\nEnd Function\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T12:19:52.863",
"Id": "456224",
"Score": "0",
"body": "Thank you. I'm just now starting to learn my way around the class modules. Would you be willing to show me a small sample of how you would wrap everything up in a class?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T13:59:29.707",
"Id": "456237",
"Score": "0",
"body": "@ZackE I added a rough outline and explanation of what an email item class might look like."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T14:13:05.103",
"Id": "456239",
"Score": "0",
"body": "Thanks for the sample of a class module. I probably wont utilize it in this project because of the simple fact Class Modules are still above my skill set at this stage; however, the information you have provided is going to be a great resource for the very near future."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T15:37:07.120",
"Id": "456251",
"Score": "1",
"body": "Classes are easier than you think. I wouldn't modify this project unless it was a necessity. Wait till it comes time to add new features. By then you will undoubtedly have learned a lot more and will want to rewrite it anyway."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T15:17:58.103",
"Id": "456415",
"Score": "0",
"body": "only thing that isnt working is the body of the email is not adding the default signatue."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T04:37:31.240",
"Id": "233385",
"ParentId": "233345",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "233385",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T15:36:40.837",
"Id": "233345",
"Score": "3",
"Tags": [
"vba",
"excel"
],
"Title": "Worksheet_Change Event Sends Email"
}
|
233345
|
<p>I have this code to weave the split_input <code>['5,4 4,5 8,7', '6,3 3,2 9,6 4,3', '7,6', '9,8', '5,5 7,8 6,5 6,4']</code> together. However I feel like this can be done more efficient (especially the weave function) but I have no clue how to improve it without importing any modules.</p>
<pre><code>class Class1:
def __init__(self, row):
self.row = row
def append(self, coordinate):
self.row += [coordinate]
def extend(self, row):
for coordinate in row:
self.row += [coordinate]
def weave(self, row2):
result = Class1([])
for i in range(len(self.row)):
if i < len(self.row):
result.append(self.row[i])
if i < len(row2.row):
result.append(row2.row[i])
if len(row2.row) > len(self.row):
result.extend(row2.row[len(self.row):])
return result
def get_route(split_input):
rows = []
for i in range(len(split_input)):
rows += [Class1(split_input[i].split())]
previous_row = rows[0]
for row in rows[1:]:
previous_row = previous_row.weave(row)
return previous_row
woven_rows = get_route(split_input)
print woven_rows
</code></pre>
<p>Do you have any good advice?</p>
<p>The output of the code is one list. First, the first and second list are weaved into one list. Then this list is weaved with the third list etc.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T16:31:49.463",
"Id": "456059",
"Score": "0",
"body": "When I print `print(woven_rows.row)` it shows `['5,4', '5,5', '9,8', '7,8', '7,6', '6,5', '6,3', '6,4', '4,5', '3,2', '8,7', '9,6', '4,3']`. If that's the final result - why it should be namely like that and in that order?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T17:38:51.843",
"Id": "456076",
"Score": "2",
"body": "So, weaving `[1, 2, 3, 4]` with `[\"a\", \"b\", \"c\", \"d\"]` should produce `[1, \"a\", 2, \"b\", 3, \"c\", 4, \"d\"]`, and then you somehow weave that with `[\"!\", \"@\", \"#\", \"$\"]`, although I have no idea how that should look? Can you give some easier example in- and output?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T09:02:03.423",
"Id": "456198",
"Score": "0",
"body": "@Boris Please keep answers inside answers. Answers only have to state one improvement, so yes your comment is fine as an answer. Thank you."
}
] |
[
{
"body": "<p>I'm not sure what Class1 is for, but you can weave 2 lists together using a list comprehension to build the first part of the list. Then add on the rest of the longer list. Like so:</p>\n\n<pre><code>def weave2(seq1, seq2):\n result = [item for pair in zip(seq1, seq2) for item in pair]\n\n if len(seq1) < len(seq2):\n result += seq2[len(seq1):]\n else:\n result += seq1[len(seq2):]\n\n return result\n</code></pre>\n\n<p>To weave more than two lists, weave the first two together, then weave in the third list, and so on. Like so:</p>\n\n<pre><code>def weave(*args):\n args = iter(args)\n result = next(args)\n\n for arg in args:\n result = weave2(result, arg)\n\n return result\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T06:33:04.113",
"Id": "233389",
"ParentId": "233346",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T15:36:51.513",
"Id": "233346",
"Score": "2",
"Tags": [
"python",
"python-2.x"
],
"Title": "Weaving multiple lists into one"
}
|
233346
|
<p>I have e single live webcam camera. I have displayed one color image, black and white image and canny edge image. Do you think I should put a scrollbar for the canny edge detection amount to make it a standard program or current threshold is fine?</p>
<pre><code>import cv2
import cv
import numpy as np
import matplotlib.image as mpimg
from matplotlib import pyplot as plt
cam = cv2.VideoCapture(0)
cv2.namedWindow("test")
img_counter = 0
while True:
ret, color = cam.read()
edges = cv2.Canny(color, 50,500)
gray = cv2.cvtColor(color,cv2.COLOR_RGB2GRAY)
grey_3_channel = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
edges_3_channel = cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR)
#blank_image = np.zeros((color.height*3,color.width*3,3), np.uint8)
horiz = np.hstack((color, grey_3_channel,edges_3_channel))
cv2.imshow('HORIZONTAL', horiz)
if not ret:
break
k = cv2.waitKey(1)
if k%256 == 27:
# ESC pressed
print("Escape hit, closing...")
break
cam.release()
cv2.destroyAllWindows()
</code></pre>
<p><a href="https://i.stack.imgur.com/UwCVQ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UwCVQ.jpg" alt="enter image description here"></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T16:56:24.647",
"Id": "456067",
"Score": "4",
"body": "I see you've posted three questions in under three hours. While it's not really a problem, don't you think it would be better if you waited to have answers for a question in order not to redo the same mistakes in every questions? :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T17:28:50.010",
"Id": "456074",
"Score": "1",
"body": "@IEatBagels: While the [first question](https://codereview.stackexchange.com/questions/233335/image-edge-detection) seems independent enough (it is about the underlying C++ code that performs the edge detection used here), the [second question](https://codereview.stackexchange.com/questions/233340/display-image-from-live-webcam-as-taken-with-four-different-color-filters-and-i) is certainly similar enough to this one that getting (more) feedback on that one first might make sense."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T16:05:37.937",
"Id": "233347",
"Score": "1",
"Tags": [
"python",
"opencv"
],
"Title": "PyOpencv code that displays color, b/w and canny images input from single live webcam camera"
}
|
233347
|
<p>Please bear in mind, I've only started learning c++ this week, and as such, would love topic suggestions for which I should master, to become better at C++.</p>
<p>Below, is my code for a singly linkedlist. It doesn't have complete functionality, just the ability to print, append, and add a node at a specified index. </p>
<p>Currently I'm aware that each node is created on the Heap. I have no idea how to delete the nodes in a LinkedList once the LinkedList itself is deleted. I'm also not sure how to create a linkedlist without pointers.</p>
<pre><code>#include<iostream>
template <typename T>
struct Node {
Node(T value);
T data;
Node<T> *next;
};
template <typename T>
Node<T>::Node(T value){
this->data = value;
this->next = nullptr;
}
template <typename T>
class LinkedList {
public:
Node<T> *head;
LinkedList<T>();
void push_back(T data);
void push_back(int index, T data);
void print();
};
template <typename T>
LinkedList<T>::LinkedList(){
this->head = nullptr;
}
template <typename T>
void LinkedList<T>::push_back(T data){
Node<T> *n = new Node<T>(data);
if (this->head == nullptr){
this->head = n;
} else {
Node<T> *cursor = this->head;
while(cursor->next != nullptr){
cursor = cursor->next;
}
cursor->next = n;
}
}
template <typename T>
void LinkedList<T>::push_back(int index, T data){
Node<T> *cursor = this->head;
unsigned const position = index - 1;
int i = 0;
while (i < position && cursor->next != nullptr){
cursor = cursor->next;
i++;
}
Node<T> *nodeToInsert = new Node<T>(data);
Node<T> *temp = cursor->next;
cursor->next = nodeToInsert;
nodeToInsert->next = temp;
}
template <typename T>
void LinkedList<T>::print(){
Node<T> *cursor = this->head;
while(cursor != nullptr){
std::cout << cursor->data << '\n';
cursor = cursor->next;
}
}
int main(){
LinkedList<int> intL;
intL.push_back(1);
intL.push_back(2);
intL.push_back(3);
intL.print();
LinkedList<std::string> sL;
sL.push_back("one");
sL.push_back("two");
sL.push_back("three");
sL.push_back(2, "two point five");
sL.print();
}
</code></pre>
<p>Also, should I potentially add an abstract class/or a c++ version of an interface for my LinkedList to follow, and then I could use this same abstraction for, say, a stack? </p>
|
[] |
[
{
"body": "<h2>Notes</h2>\n<blockquote>\n<p>Currently I'm aware that each node is created on the Heap.</p>\n</blockquote>\n<p>No such thing as heap in C++ (or stack technically).<br />\nYou mean dynamically allocated memory in the situation.</p>\n<p>Note: Though the language does not specify the need for a stack most implementations will use one. But the concept itself is not useful for thinking about C++ objects. You should look up "Automatic/Static/Dynamic" storage duration.</p>\n<blockquote>\n<p>I have no idea how to delete the nodes in a LinkedList once the LinkedList itself is deleted.</p>\n</blockquote>\n<p>If you create something with <code>new</code> ou delete it with <code>delete</code>. I'll cover that below. When an object is destroyed (either manually or by going out of scope) its destructor will always be called.</p>\n<blockquote>\n<p>I'm also not sure how to create a linkedlist without pointers.</p>\n</blockquote>\n<p>I don't think I could do that either.</p>\n<blockquote>\n<p>Also, should I potentially add an abstract class/or a c++ version of an interface for my LinkedList to follow.</p>\n</blockquote>\n<p>In C++ we use this thing called "Concepts". A linked list is an implementation of the "Concept: Container" there is no interface for a concept but rather a standard set of things that it should implement. <a href=\"https://en.wikipedia.org/wiki/Concepts_(C%2B%2B)\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Concepts_(C%2B%2B)</a></p>\n<p>Thus allows for template to do "Duck" typing.<br />\nIf it quacks like a duck then it can be used as a duck.</p>\n<p>Basically templates allow you to use any type as long as the function you use are available for that type and it compiles it is said to follow the duck typing interface of the template.</p>\n<blockquote>\n<p>and then I could use this same abstraction for, say, a stack?</p>\n</blockquote>\n<p>Now there is already a type <code>std::stack</code> that underneath uses an object that implements the <code>Concept of a SequenceContainer</code>.</p>\n<p>And defines these functions (As defined for a Sequenced Container).</p>\n<ul>\n<li>back()</li>\n<li>push_back()</li>\n<li>pop_back()</li>\n</ul>\n<p>See: <a href=\"https://en.cppreference.com/w/cpp/named_req/SequenceContainer\" rel=\"nofollow noreferrer\">https://en.cppreference.com/w/cpp/named_req/SequenceContainer</a></p>\n<h2>Code Review</h2>\n<p>Don't need to mention the template type inside the templates object.</p>\n<pre><code>template <typename T>\nstruct Node {\n Node(T value);\n T data;\n Node<T> *next; // That <T> is not needed here.\n // The compiler assumes its a T unless you\n // manually specify otherwise.\n};\n</code></pre>\n<hr />\n<p>The <code>*</code> and <code>&</code> and <code>&&</code> are part of the type infomration. So in C++ (unlike C) they are usually placed next to the type information not the member.</p>\n<pre><code> Node* next; // Next has a type Node* (or Node Pointer).\n</code></pre>\n<hr />\n<p>Don't use <code>this-></code></p>\n<pre><code>template <typename T>\nNode<T>::Node(T value){\n this->data = value;\n this->next = nullptr;\n}\n</code></pre>\n<p>The only time you need to use <code>this-></code> is when you have a local variable that shadows a member variable. If you have a shadowing problem them the compiler can not tell when you accidently leave off the <code>this-></code> and thus shadowing leads to hard to detect bugs.</p>\n<p>So it is better to use unique names and get the compiler to warn you when you have a shodowed variable. Then your naming of variables becomes better and you don't accidently use the wrong variable.</p>\n<hr />\n<p>For short function put them in the class definition.</p>\n<pre><code>template <typename T>\nNode<T>::Node(T value){\n this->data = value;\n this->next = nullptr;\n}\n</code></pre>\n<p>Thats short and because you don't need the <code>template <typename T></code> in the class it becomes even shorter.</p>\n<hr />\n<p>Prefer to use the initializer list over constructor code.</p>\n<p>When an object is created all its members are initialized in the order declared in the class. If there are no members initialized in the initializer list they are <code>zero</code> or <code>default</code> initialized depending on the exact declaration.</p>\n<p>But if you are setting the values in the constructor code this means you are re-setting them in the code. For complex objects this means you are calling the <code>operator=</code> to redo work that was done in the initializer list.</p>\n<pre><code>template <typename T>\nNode<T>::Node(T value)\n : data() // You have an implicit initialization here\n , next() // even if you don't do it yourself.\n{\n data = value; // If the above initialization did work\n next = nullptr; // Then these two assignments become extra work.\n}\n</code></pre>\n<hr />\n<p>Your copy constructor passes the data by value:</p>\n<pre><code>Node<T>::Node(T value) // Pass by value causes a copy of value here.\n : data() // Data is default constructed here.\n // See above.\n{ \n this->data = value; // Copy assignment causes another copy to be\n // made here.\n</code></pre>\n<p>If you are keeping the data you need to copy it at some point but you don't need to copy it twice. So pass by const reference to avoid a copy.</p>\n<pre><code>Node<T>::Node(T const & value) // Pass by reference to avoid copy.\n : data(value) // Construct data using the copy constructor.\n{ \n</code></pre>\n<hr />\n<p>In modern C++ we have the concept of move semantics. This allows an object to move expensive parts to another object if it is not going to be used again. Think of passing a huge array into an object. You may not want to copy it (as above). If you are not going to use the data again you want to move the object.</p>\n<pre><code>Node<T>::Node(T&& value) // The double && indicates it will bind\n // To an r-value reference (something that can be moved)\n : data(std::move(value)) // You pass the T object to the move\n // constructor of the type T to allow it to\n // move itself.\n{ \n</code></pre>\n<hr />\n<p>Better declaration for Node:</p>\n<pre><code>template <typename T>\nstruct Node\n{\n Node(T const& value)\n : data(value)\n , next(nullptr)\n {}\n Node(T&& value)\n : data(std::move(value))\n , next(nullptr)\n {}\n T data;\n Node* next;\n};\n</code></pre>\n<hr />\n<p>But even better news. Since the above is such a common pattern (Adding constructors and assignment operators like this). That this is done automatically for all types (unless you start manually defining them). So the above type can be defined simply by doing:</p>\n<pre><code>template <typename T>\nstruct Node\n{\n T data;\n Node* next;\n};\n</code></pre>\n<p>Note: Normally this is a bad thing if your object contains a pointer. <strong>BUT</strong> if we consider the <code>Node</code> as a non owning of the pointer it works. But you have to move the responsibility for owning onto the <code>LinkedList</code> class. So we will cover that below.</p>\n<hr />\n<p>LinkedList is a class that contains an "OWNED" pointer (unlike Node). So this class you do need to specify a couple of methods or things go wrong.</p>\n<p>Look up the rule of three.</p>\n<p>If you don't specify them the compiler will automatically generate:</p>\n<ul>\n<li>CopyConstructor <code>LinkedList(LinkedList const&);</code></li>\n<li>CopyAssignment <code>LinkedList& operator=(LinkedList const&);</code></li>\n<li>Destructor <code>~LinkedList()</code></li>\n</ul>\n<p>The constructors do a shallow copy and the destructor simply makes sure that all members are correctly destroyed. So in this case they do:</p>\n<pre><code> LinkedList(LinkedList const& copy)\n : head(copy.head)\n {}\n LinkedList& operator=(LinkedList const& copy)\n {\n head = copy.head;\n return *this;\n }\n ~LinkedList()\n {\n /* Nothing is done for pointers */\n }\n</code></pre>\n<p>So what you say. This does not affect me. This is true because currently you have not defined the destructor. But if you correctly define the destructor the constructors will cause problems.</p>\n<pre><code> ~LinkedList()\n {\n deleteTheListPointedAtBy(head); // This is what you should do.\n }\n</code></pre>\n<p>This causes problems because the above 2 constructors allow:</p>\n<pre><code> {\n LinkedList<int> a;\n a.push_back(1);\n LinkedList<int> b(a); // We are allowed to copy a like this.\n // But both a and b have a head that points\n // at the same value.\n\n } // At this point both a and b are destroyed.\n // Thus there destructors are called.\n // Thus they both try and delete all the same nodes.\n // which will cause problems.\n</code></pre>\n<hr />\n<p>As above in Node. You should think about move semantics. There are two methods added in C++11 that change the rule of three into the rule of 5.</p>\n<ul>\n<li>MoveConstructor <code>LinkedList(LinkedList&&);</code></li>\n<li>MoveAssignment <code>LinkedList& operator=(LinkedList&&);</code></li>\n</ul>\n<hr />\n<p>As above use the initializer list:</p>\n<pre><code>template <typename T>\nLinkedList<T>::LinkedList(){\n this->head = nullptr;\n}\n</code></pre>\n<hr />\n<p>As above pass by const reference to avoid a copy.</p>\n<pre><code>template <typename T>\nvoid LinkedList<T>::push_back(T data){\n</code></pre>\n<hr />\n<p>Same again pass by const reference:</p>\n<pre><code>template <typename T>\nvoid LinkedList<T>::push_back(int index, T data){\n</code></pre>\n<hr />\n<p>This is good and looks correct.</p>\n<pre><code> Node<T> *cursor = this->head;\n unsigned const position = index - 1;\n int i = 0;\n while (i < position && cursor->next != nullptr){\n cursor = cursor->next;\n i++;\n }\n Node<T> *nodeToInsert = new Node<T>(data);\n Node<T> *temp = cursor->next;\n cursor->next = nodeToInsert;\n nodeToInsert->next = temp;\n</code></pre>\n<p>But we could simplify it a bit:</p>\n<pre><code> Node* cursor = head;\n for(int loop = 0;loop < position && cursor->next !- nullptr;++loop,cursor = cursor->next)\n {}\n\n cursor->next = new Node<T>(data, cursor->next);\n</code></pre>\n<hr />\n<p>This also works well.</p>\n<pre><code>template <typename T>\nvoid LinkedList<T>::print(){\n Node<T> *cursor = this->head;\n while(cursor != nullptr){\n std::cout << cursor->data << '\\n';\n cursor = cursor->next;\n }\n}\n</code></pre>\n<p>But you assume the output is <code>std::cout</code>. I would pass the output stream as a parameter (it can default to std::cout`). This makes the print much more flexable.</p>\n<p>The <code>print()</code> method does not change the state of the object so it should be marked <code>const</code>.</p>\n<p>In C++ we normally use <code>operator<<</code> to output stuff. So you may want to write that function so it looks more natural. It can simply call the print method.</p>\n<pre><code>template <typename T>\nvoid LinkedList<T>::print(std::ostream& str) const\n{\n Node<T> *cursor = this->head;\n while(cursor != nullptr){\n str << cursor->data << '\\n';\n cursor = cursor->next;\n }\n}\ntemplate<typename T>\nstd::ostream& operator<<(std::ostream& str, LinkedList<T> const& list)\n{\n list.print(str);\n return str;\n}\n</code></pre>\n<hr />\n<p>Your missing destructor:</p>\n<pre><code>template<typename T>\n~LinkedList()\n{\n Node<T>* old;\n while (head) {\n old = head;\n head = head->next;\n delete old;\n }\n }\n</code></pre>\n<h1>Alternative Implementation:</h1>\n<pre><code>template <typename T>\nclass LinkedList\n{\n // Make Node a private member of the Linked List.\n struct Node\n {\n T data;\n Node* next;\n };\n Node* head;\n Node* tail;\n\n public:\n ~LinkedList() {deleteList();}\n\n LinkedList()\n : head(nullptr)\n , tail(nullptr)\n {}\n\n LinkedList(LinkedList const& copy)\n : LinkedList()\n {\n for(Node* other = copy->head; head; head = head->next) {\n push_back(other->data);\n }\n }\n LinkedList operator=(LinkedList const& copy)\n {\n LinkedList tmp(copy); // See Copy and Swap Idiom\n swap(tmp);\n return *this;\n }\n\n LinkedList(LinkedList&& move) noexcept\n : LinkedList()\n {\n swap(move);\n }\n LinkedList operator=(LinkedList&& move) noexcept\n {\n swap(move);\n return *this;\n }\n\n void swap(LinkedList& other) noexcept\n {\n using std::swap;\n swap(head, other.head);\n swap(tail, other.tail);\n }\n friend void swap(LinkedList& lhs, LinkedList& rhs) noexcept\n {\n lhs.swap(rhs);\n }\n\n void push_back(T const& data)\n {\n pushbackNode(new Node{data, nullptr});\n }\n void push_back(T&& data)\n {\n pushbackNode(new Node{std::move(data), nullptr});\n }\n\n void push_back(int index, T const& data); \n void push_back(int index, T&& data);\n\n void print() const;\n friend std::ostream& operator<<(std::ostream& str, LinkedList const& data) {\n data.print(str);\n return str;\n }\n private:\n void deleteList()\n {\n Node* old;\n while (head) {\n old = head;\n head = head->next;\n delete old;\n }\n } \n void pushbackNode(Node* node)\n {\n if (tail) {\n tail->next = node;\n tail = tail->next;\n }\n else {\n head = tail = node;\n }\n }\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T21:16:43.817",
"Id": "456137",
"Score": "0",
"body": "Thank you! Very informative :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T20:57:17.753",
"Id": "233368",
"ParentId": "233355",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "233368",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T18:17:20.763",
"Id": "233355",
"Score": "2",
"Tags": [
"c++",
"linked-list",
"pointers",
"heap"
],
"Title": "Basic LinkedList implementation"
}
|
233355
|
<p>I have an array of hashes (<code>price_params['items']</code>) where each item has a key called <code>quantity</code> what I'm trying to do is to clean every duplicate of each item but keeping the count of the times the item was found in the array in the unique one that I'm leaving (using the <code>quantity</code> key to keep that value)</p>
<p>This is my code so far:</p>
<pre><code>def clean_duplicated_offers
price_params['items'].each do |item|
max_count = price_params['items'].count(item)
next unless max_count > 1
price_params['items'].delete(item)
item['quantity'] = max_count
price_params['items'] << item
end
end
</code></pre>
<p>It works well, but it feels weird to delete every occurrence of the item in the array just to add it back to it.</p>
<p>Is there any better way to achieve this?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T02:43:53.203",
"Id": "456164",
"Score": "1",
"body": "create an empty array. Iterate `price_params['items']` (Attempt to) insert each into the empty array. If `item` does not exist there, insert it, otherwise add one to the existing`item['quantity']`. Set `price_params['items']` to this new array."
}
] |
[
{
"body": "<p>I ended up doing something like this:</p>\n\n<pre><code>def clean_duplicated_offers\n price_params['items'] = price_params['items'].each_with_object([]) do |item, items_array|\n if items_array.include? item\n items_array.detect { |i| i == item }['quantity'] += 1\n else\n items_array << item\n end\n end\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T14:20:59.637",
"Id": "233415",
"ParentId": "233357",
"Score": "1"
}
},
{
"body": "<p>Does it have to be an <code>Array</code>? I.e. is the order important?</p>\n\n<p>If not, then there is actually a data structure that does <em>exactly</em> what you want: the <em>multiset</em>. A multiset is just like a <em>set</em>, except that its elements have a <em>multiplicity</em>. In other words, a set can tell you whether or not an element is a member, a multiset in addition can tell you <em>how often</em> it is a member.</p>\n\n<p>Basically, if you use a multiset, you will not have to do <em>anything</em>, since the multiset keeps track of the multiplicity (i.e. your <code>quantity</code>) for you.</p>\n\n<p>There is no multiset in the Ruby core library or standard library, but there are a couple of third-party libraries and gems. <a href=\"https://maraigue.hhiro.net/multiset/\" rel=\"nofollow noreferrer\">I'll just grab one randomly</a>, it doesn't really matter which one; their APIs are fairly similar.</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>require 'multiset'\n\nprice_params_items = %w[item2 item1 item3 item2 item3 item3]\n\nresult = Multiset[*price_params_items]\n#=> #<Multiset:#2 \"item2\", #1 \"item1\", #3 \"item3\">\n</code></pre>\n\n<p>And that's it! You might ask yourself, where is the algorithm gone? That is a general property of programming: if you find the right data structure(s), the algorithm(s) become(s) much simpler, or in this case, even vanishes completely.</p>\n\n<p>Unfortunately, for this specific implementation of multiset, there is no direct way to retrieve the multiplicity of an element, but you can convert it to a hash, and then you get what you need:</p>\n\n<pre class=\"lang-rb prettyprint-override\"><code>result.to_hash\n#=> { \"item2\" => 2, \"item1\" => 1, \"item3\" => 3 }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-09T04:02:26.267",
"Id": "456802",
"Score": "0",
"body": "Very interesting! In this case I'm not able to use third party libraries for this matter, but I will keep an eye on Multisets for future functionalities. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-07T11:12:06.007",
"Id": "233584",
"ParentId": "233357",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "233415",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T18:58:09.580",
"Id": "233357",
"Score": "1",
"Tags": [
"array",
"ruby",
"ruby-on-rails",
"hash-map"
],
"Title": "Removing duplicate hashes in an array while keeping count of the times the hash was present"
}
|
233357
|
<p>I am trying to improve the time running of this code. Some dummies variable is defined and it is just some part of a lot of lines of code, but I tried it with dummies variables. It takes too much in higher size of etas and Nx. I would like to know if there is a better way to calculate dfdeta.</p>
<pre><code>matlab
format long;
%%constant
A=1.0;
B=1.0;
ngrain=70;%grains number
NxNy = 512*512; %domain
etas = rand(NxNy,70));
sum=zeros(NxNy,1);
eta = etas;
for jgrain=1:ngrain
if(jgrain ~= igrain)
sum = sum +etas( :,jgrain).^2;
end%if
end%for
dfdeta = A*(2.0*B* eta .*sum +eta.^3 - eta);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T19:59:46.377",
"Id": "456091",
"Score": "1",
"body": "Could you give more detail regarding your code? Otherwise it's very hard to understand what you're trying to do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T23:34:20.083",
"Id": "456152",
"Score": "0",
"body": "Your code doesn't run. You have an extra `)` in the definition of `etas` and `igrain` is never defined. What should `igrain` be?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T12:13:57.387",
"Id": "456223",
"Score": "0",
"body": "@David I modified the code."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T19:47:04.463",
"Id": "233360",
"Score": "1",
"Tags": [
"performance",
"computational-geometry",
"matlab"
],
"Title": "Calculating the term of dfdeta"
}
|
233360
|
<p>We have to execute a bunch of jobs , each have an ID and they are passed on to the processor . Since the processor can only work on a limited number of jobs (denoted by <code>deleteBatchSizeMax</code> in the code snippet),we are using a paged approach so that only a subset is picked up by the processor.To implement this we have a functionality which calculates the Page Size. It takes in the total number of jobs, and the max page size. The code handles the situation where the page size may not be an exact multiple , example 22 items have a <code>deleteBatchSizeMax</code> of 10. This translates to 22/10 so it gives us a page size of 3 where the jobs are executed in chunks of 10,10,2.
Hence wrote the below described function!</p>
<pre><code> private int CalculatePageSize(int totalNumberOfJobs, int deleteBatchSizeMax)
=> totalNumberOfJobs % deleteBatchSizeMax != 0
? (totalNumberOfJobs / deleteBatchSizeMax) + 1
: totalNumberOfJobs / deleteBatchSizeMax;
</code></pre>
<p>I am hearing complaints that apparently its not readable and I should do the if-else block. I think that the variable names are well defined , code is well commented (omitted here) and self explanatory.</p>
<p>I wanted to know the feedback of the community.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-28T13:31:51.307",
"Id": "483535",
"Score": "1",
"body": "I have rolled back you latest edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] |
[
{
"body": "<p>There are a few ways which this method could be made more readable.</p>\n\n<p>The first if-statement is negated, making the control flow slightly more complicated; the statement can be negated (again) to clarify the flow:</p>\n\n<pre><code>private int CalculatePageSize(int totalNumberOfJobs, int deleteBatchSizeMax) \n => totalNumberOfJobs % deleteBatchSizeMax == 0\n ? totalNumberOfJobs / deleteBatchSizeMax\n : (totalNumberOfJobs / deleteBatchSizeMax) + 1;\n</code></pre>\n\n<p>Secondly, the statement is currently checking if <code>totalNumberOfJobs</code> is an even divisible of <code>deleteBatchSizeMax</code>. The computation <code>totalNumberOfJobs / deleteBatchSizeMax</code> is used three times. When <code>(double)totalNumberOfJobs / (double)deleteBatchSizeMax</code> doesn't contain a decimal place, then it implies <code>totalNumberOfJobs % deleteBatchSizeMax == 0</code>, and vice-versa.</p>\n\n<p>To simplify the pattern, consider the following: when A divides B with no remainder, then divide it, otherwise divide it and add one. Therefore, <code>Math.Ceiling</code> can be used:</p>\n\n<pre><code>private int CalculatePageSize(int totalNumberOfJobs, int deleteBatchSizeMax) \n => (int)Math.Ceiling((double)totalNumberOfJobs / (double)deleteBatchSizeMax);\n</code></pre>\n\n<p>The <code>Math.Ceiling</code> function \"rounds\" up to positive infinity; so 4.5 -> 5, 4.00001 -> 5 and so on. This emulates the original loop condition.</p>\n\n<p>Edit: the second double conversion is not required as it is upcasted to a double.</p>\n\n<pre><code>private int CalculatePageSize(int totalNumberOfJobs, int deleteBatchSizeMax) \n => (int)Math.Ceiling((double)totalNumberOfJobs / deleteBatchSizeMax);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T23:47:12.687",
"Id": "456154",
"Score": "0",
"body": "Do you mean Math.Ceiling?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T23:49:12.003",
"Id": "456155",
"Score": "0",
"body": "@Errorsatz yes; thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T10:12:50.220",
"Id": "456215",
"Score": "0",
"body": "@alexyorke Thanks . this is nice although there are 3 casts . I will have to run tests for the edge cases . Will keep ya updated."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T23:14:04.210",
"Id": "233373",
"ParentId": "233363",
"Score": "4"
}
},
{
"body": "<p>Inspired by <a href=\"https://codereview.stackexchange.com/a/233373\">alexyorke's answer</a>, what about this:</p>\n\n<p>In a MathUtils class, define:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>public static int DivCeiling(int num, int den) => (num + den - 1) / den;\n</code></pre>\n\n<p>And then, in your application class, define:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>private int CalculatePageSize(int totalNumberOfJobs, int deleteBatchSizeMax)\n => MathUtils.DivCeiling(totalNumberOfJobs, deleteBatchSizeMax);\n</code></pre>\n\n<p>That way you can combine the short variable names of an abstract class for mathematical utilities (since the formula can be used in really many contexts) with the readability and simplicity in your application class.</p>\n\n<p>You can also write extensive unit tests for the <code>MathUtils</code> class, focusing on the formula. And in your application code you only have to decide whether it is correct to use the <code>DivCeiling</code> function or not.</p>\n\n<p>As usual for unit tests, pay attention to edge cases:</p>\n\n<ul>\n<li><code>num == 0</code> (always results in 0)</li>\n<li><code>den == 0</code> (exception, that's ok)</li>\n<li><code>num == int.MaxValue</code> (overflow in my code, but converting the numbers to <code>double</code> feels inappropriate to me)</li>\n<li><code>den == int.MaxValue / 2 + 1, num = int.MaxValue / 2 + 2</code> (overflow)</li>\n<li><code>num < 0</code></li>\n<li><code>den < 0</code></li>\n</ul>\n\n<p>To fix this, you could do the intermediate calculation using <code>long</code> instead of <code>int</code>. You just have to ensure that when converting the result back to <code>int</code>, that you don't cut off any significant digits.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T10:15:51.547",
"Id": "456216",
"Score": "0",
"body": "Thanks for taking out your time and write such a detailed and thoughtful answer ."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T00:51:21.180",
"Id": "233378",
"ParentId": "233363",
"Score": "1"
}
},
{
"body": "<p>I would go with following sample</p>\n<ol>\n<li><p>Mare sure total and count are positive numbers</p>\n</li>\n<li><p>On next step we expect the <code>pages</code> result to be always positive > 1.</p>\n<p>Divide the <code>total</code> number of item by the <code>count</code>.\nAll divisions by <code>total < count</code> leads to 0 that is the reason +1 is aded to the result.\nBy having <code>total-1</code> we handle the case <code>total = count</code> and having + 1 will give are wrong result. Well this could be handled with few ifs but in the case you prefer a shorter version ...</p>\n</li>\n</ol>\n<pre><code>private int pages(int total, int count){\n if(total <= 0 || count <=0 ){\n return 0;\n }\n return ((total - 1) / count) + 1;\n}\n</code></pre>\n<p>Tests:</p>\n<pre><code>pages(0,10) -> 0 \npages(1,10) -> 1\npages(10,10)) -> 1\npages(11,10)) -> 2\npages(101,10) -> 11\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-28T14:44:05.067",
"Id": "246128",
"ParentId": "233363",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "233373",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T20:34:20.063",
"Id": "233363",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Calculating a page size to execute a subset of jobs at a time"
}
|
233363
|
<p>This mandelbulb-set generator creates a <code>.xyz</code> file which contains all the points that are in the set which lie on a 3D grid. It does what it is supposed to.</p>
<p>However, the number of calculations done is proportional to the cube of the resolution*, which means that the script takes very long if the resolution is in the order of 500 or 1000.</p>
<p><sup>*</sup> The resolution is the amount of points that each axis is divided into. A resolution of 5 means that the x, y and z axis are each divided by 5. Therefore, there are <span class="math-container">\$5^3 = 125\$</span> points that are calculated.</p>
<p>Here is the entire code:</p>
<pre><code>#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;
/* Mandelbulb: https://en.wikipedia.org/wiki/Mandelbulb
*
* The sequence v(n+1) = v(n)^power + c is iterated several times for every point in 3d space. v(0) and c are equal to that point.
* If the length of v(n) does not exceed 'maxlength' (i.e. it does not diverge) then the point is an element of the mandelbulb set
* and saved to the file.
*/
int main()
{
//settings:
int iter = 5;
int resolution = 50;
double power = 8.0;
double maxlength = 2.0;
double rangemin = -1.75;
double rangemax = 1.75;
//Points:
double xpos, ypos, zpos; //positions to cycle through
double xpoint, ypoint, zpoint; //point to be calculated at that position
double cx, cy, cz; //C-point
double r, phi, theta; //spherical coordinates
//calculated variables:
double div = (rangemax - rangemin) / double(resolution);
//other variables:
double length = 0;
double density = 0; //Named 'density' since the 3d-volume has density=1 if the point is in the set and density=0 if point is not in the set
double progress, progdiv = 100.0 / pow((double(resolution) + 1), 3.0);
//User interface:
cout << endl;
cout << "+--------------------+" << endl;
cout << "|Mandelbulb generator|" << endl;
cout << "+--------------------+" << endl << endl;
cout << "Standard settings:" << endl;
cout << "Iterations: " << iter << endl;
cout << "Power: " << power << endl;
cout << "Maxlength: " << maxlength << endl;
cout << "rangemin: " << rangemin << endl;
cout << "rangemax: " << rangemax << endl;
cout << "Resolution: " << resolution << endl;
cout << endl;
//create output file:
ofstream file ("Mandelbulb.xyz");
file << div << endl; //first line contains distance between points for other scripts to read
//x,y,z-loop:
for(xpos = rangemin; xpos <= rangemax; xpos += div){
for(ypos = rangemin; ypos <= rangemax; ypos += div){
for(zpos = rangemin; zpos <= rangemax; zpos += div){
//Display progress in console:
progress += progdiv;
cout << " \r";
cout << progress << "%\r";
cout.flush();
//reset for next point:
xpoint = xpos;
ypoint = ypos;
zpoint = zpos;
cx = xpos;
cy = ypos;
cz = zpos;
//Sequence loop:
for(int i = 0; i <= iter; i++)
{
r = sqrt(xpoint*xpoint + ypoint*ypoint + zpoint*zpoint);
phi = atan(ypoint/xpoint);
theta = acos(zpoint/r);
xpoint = pow(r, power) * sin(power * theta) * cos(power * phi) + cx;
ypoint = pow(r, power) * sin(power * theta) * sin(power * phi) + cy;
zpoint = pow(r, power) * cos(power * theta) + cz;
length = r;
if(length >= maxlength)
{
density = 0.0;
break;
}
density = 1.0;
}
if(density == 1.0)
{
file << xpos << " " << ypos << " " << zpos << endl;
}
}//zpos loop end
}//ypos loop end
}//xpos loop end
cout << endl << "Done." << endl;
return 0;
}
</code></pre>
<p>I hope that the comments make clear what happens, otherwise please ask. Again, the goal is to make it execute as fast as possible. I am a beginner at C++ and might not see some obvious bottlenecks. I'd like to avoid using external libraries.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T21:22:02.103",
"Id": "456140",
"Score": "2",
"body": "Parallelism is the answer here. Generating a fractal is an embarrassingly parallel problem. Split the space into `k` threads and have each of them calculate the subspace autonomously. If you take this approach to the limit then you would use GPUs, and have a thread calculate a single point. I wrote an article some time ago on fractals on CUDA (Julia set in this case) http://www.davidespataro.it/cuda-julia-set-fractals/."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T21:40:03.203",
"Id": "456145",
"Score": "1",
"body": "You should definitely avoid `flush()` and `endl`. They will slow your program down since they force it to write to the file/stdout right now. For this it has to wait on the system. Without flushing, it can buffer the writing for later (it will certainly do it at some point) and then can write more data in a single write, which minimizes waiting. See also [here](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rio-endl)"
}
] |
[
{
"body": "<p>I probably can't say much about the algorithm but I see many things which can help you improve your use of C++ and programming in general.</p>\n\n<ul>\n<li><h3>Don't use <code>using namespace std</code></h3>\n\nWhy? You pollute the whole <code>std</code> namespace into your program which could lead to name clashes. More about it <a href=\"//stackoverflow.com/q/1452721\">here</a>.</li>\n<li><h3>Use const and constexpr</h3>\n\n<p>Consider these declarations:</p>\n\n<blockquote>\n<pre><code>//settings:\nint iter = 5;\nint resolution = 50;\ndouble power = 8.0;\ndouble maxlength = 2.0;\ndouble rangemin = -1.75;\ndouble rangemax = 1.75;\n</code></pre>\n</blockquote>\n\n<p>In your program you can now happily modify these parameters by\n accident. Since they should be constants say so with the keyword\n <code>const</code>:</p>\n\n<pre><code>const int iter = 5;\nconst int resolution = 50;\nconst double power = 8.0;\nconst double maxlength = 2.0;\nconst double rangemin = -1.75;\nconst double rangemax = 1.75;\n</code></pre>\n\n<p>If C++11 is available, even better: make them <code>constexpr</code>:</p>\n\n<pre><code>constexpr int iter = 5;\nconstexpr int resolution = 50;\nconstexpr double power = 8.0;\nconstexpr double maxlength = 2.0;\nconstexpr double rangemin = -1.75;\nconstexpr double rangemax = 1.75;\n</code></pre>\n\n<p>This makes these variables true constants. That means they eat up no\n memory. They are just aliases for the numbers.</p></li>\n<li><h3>Use <code>auto</code> whenever possible</h3>\n\n<p>You don't have to mention types explicitly. Instead use <code>auto</code>. So we get:</p>\n\n<pre><code>constexpr auto iter = 5;\nconstexpr auto resolution = 50;\nconstexpr auto power = 8.0;\nconstexpr auto maxlength = 2.0;\nconstexpr auto rangemin = -1.75;\nconstexpr auto rangemax = 1.75;\n</code></pre></li>\n<li><h3>omit <code>return 0</code> in <code>main()</code></h3>\n\n<p>In C++, <code>return 0</code> gets automatically inserted into the <code>main</code> function if you don't write it. So for this special case it is not necessary to write the <code>return</code>.</p></li>\n<li><h3>Avoid declaring several variables on one line</h3>\n\n<p>Consider this in your code:</p>\n\n<blockquote>\n<pre><code>double progress, progdiv = 100.0 / pow((double(resolution) + 1), 3.0);\n\n//...\n\n//Display progress in console:\nprogress += progdiv;\n</code></pre>\n</blockquote>\n\n<p>My compiler shows a warning in the last line:</p>\n\n<blockquote>\n <p>variable 'progress' is uninitalized when used here</p>\n</blockquote>\n\n<p>That means <code>progress</code> can have any value here and gets added here.</p>\n\n<p>So better write two lines and initialize:</p>\n\n<pre><code>auto progress = 0.0;\nauto progdiv = 100.0 / pow((double(resolution) + 1), 3.0);\n</code></pre></li>\n<li><h3>Avoid <code>std::endl</code></h3>\n\n<p>This is really a very common beginners' trap. Even some books use <code>std::endl</code> all the time but it is wrong.</p>\n\n<p>First of all, <code>std::endl</code> is nothing but this:</p>\n\n<pre><code>'\\n' + `std::flush`\n</code></pre>\n\n<p>So it gives you a new line (What you want) and the performs a expensive flush of the output sequence which is in 99.9% of the cases not necessary. So stick to <code>\\n</code>.</p></li>\n<li><h3>Declare variables as late as possible:</h3>\n\n<p>This:</p>\n\n<blockquote>\n<pre><code>//reset for next point:\nxpoint = xpos;\nypoint = ypos;\nzpoint = zpos;\ncx = xpos;\ncy = ypos;\ncz = zpos;\n</code></pre>\n</blockquote>\n\n<p>Should be:</p>\n\n<pre><code>//reset for next point:\nauto xpoint = xpos;\nauto ypoint = ypos;\nauto zpoint = zpos;\nauto cx = xpos;\nauto cy = ypos;\nauto cz = zpos;\n</code></pre>\n\n<p>Unlike in old C Standard, you can declare variables as late as possible. They should be declared when they are needed. This avoids mistakes.</p>\n\n<p>Same goes for this:</p>\n\n<pre><code>auto r = sqrt(xpoint*xpoint + ypoint*ypoint + zpoint*zpoint);\nauto phi = atan(ypoint/xpoint);\nauto theta = acos(zpoint/r);\n</code></pre></li>\n<li><h3>Limit your line length</h3>\n\n<p>Consider this nice line:</p>\n\n<blockquote>\n<pre><code>//other variables:\ndouble length = 0.0;\ndouble density = 0.0; //Named 'density' since the 3d-volume has density=1 if the point is in the set and density=0 if point is not in the set\n</code></pre>\n</blockquote>\n\n<p>You should limit your line length to a value (80 or 100 are common) so you can read all the code without scrolling to the right. With this limit you can also open two code pages next to each other. More about it <a href=\"//softwareengineering.stackexchange.com/q/604/\">here</a>.</p>\n\n<p>Most IDEs support a visible line length marker. In mine it looks like this:</p>\n\n<p></p>\n\n<p>So better like this:</p>\n\n<pre><code>double length = 0.0;\n//Named 'density' since the 3d-volume has density=1 if the point is in the \n//set and density=0 if point is not in the set\ndouble density = 0.0; \n</code></pre></li>\n<li><h3>Avoid long functions</h3>\n\n<p>Your <code>main</code> function is very long and it's hard to grasp from looking at it what is going on. Prefer shorter functions which only do one thing. The <code>main</code> does several things (user input, calculation etc). Split that into smaller functions. And the smaller functions into even smaller functions. This way you also have the option to run the algorithm without any user input, maybe for unit tests.</p></li>\n</ul>\n\n<hr>\n\n<p>Refactored, the code looks like this:</p>\n\n<pre><code>#include <iostream>\n#include <cmath>\n#include <fstream>\n\n/* Mandelbulb: https://en.wikipedia.org/wiki/Mandelbulb\n *\n * The sequence v(n+1) = v(n)^power + c is iterated several times for every\n * point in 3d space. v(0) and c are equal to that point.\n * If the length of v(n) does not exceed 'maxlength' (i.e. it does not diverge)\n * then the point is an element of the mandelbulb set\n * and saved to the file.\n*/\n\nstruct Parameters{\n const int iter;\n const int resolution;\n const double power;\n const double maxLength;\n const double rangemin;\n const double rangemax;\n};\n\nvoid printParameters(std::ostream &os, const Parameters &parameters);\n\nvoid calculation(\n std::ostream &calcOutput,\n std::ostream &progressOutput,\n bool progressOutputOn,\n const Parameters &parameters);\n\nbool sequenceLoop(double xpos, double ypos, double zpos, int iter, \n double power, double maxLength);\n\nbool sequence(double &xpoint, double &ypoint, double &zpoint, double power,\n double maxLength, double cx, double cy, double cz);\n\n\nvoid printParameters(std::ostream &os, const Parameters &parameters)\n{\n os << '\\n'\n << \"+--------------------+\" << '\\n'\n << \"|Mandelbulb generator|\" << '\\n'\n << \"+--------------------+\" << '\\n'\n <<'\\n'\n << \"Standard settings:\" << '\\n'\n << \"Iterations: \" << parameters.iter << '\\n'\n << \"Power: \" << parameters.power << '\\n'\n << \"Maxlength: \" << parameters.maxLength << '\\n'\n << \"rangemin: \" << parameters.rangemin << '\\n'\n << \"rangemax: \" << parameters.rangemax << '\\n'\n << \"Resolution: \" << parameters.resolution << '\\n'\n <<'\\n';\n}\n\nvoid calculation(\n std::ostream &calcOutput,\n std::ostream &progressOutput,\n bool progressOutputOn,\n const Parameters &parameters)\n{\n auto div = (parameters.rangemax - parameters.rangemin) \n / double(parameters.resolution);\n //first line contains distance between points for other scripts to read\n calcOutput << div << '\\n';\n\n auto progress = 0.0;\n auto progdiv = 100.0 / pow((double(parameters.resolution) + 1), 3.0);\n\n //x,y,z-loop:\n for(auto xpos = parameters.rangemin; \n xpos <= parameters.rangemax; xpos += div) {\n\n for(auto ypos = parameters.rangemin; \n ypos <= parameters.rangemax; ypos += div) {\n\n for(auto zpos = parameters.rangemin; \n zpos <= parameters.rangemax; zpos += div) {\n\n if(progressOutputOn) {\n //Display progress in console:\n progress += progdiv;\n progressOutput << \" \\r\"\n << progress << \"%\\r\";\n progressOutput.flush();\n }\n\n if(sequenceLoop(xpos, ypos, zpos, parameters.iter, \n parameters.power, parameters.maxLength))\n {\n calcOutput << xpos << \" \" << ypos << \" \" << zpos << '\\n';\n }\n }\n }\n }\n\n if(progressOutputOn) {\n progressOutput << '\\n'\n << \"Done.\" << '\\n';\n }\n}\n\nbool sequenceLoop(\n double xpos,\n double ypos,\n double zpos,\n double power,\n int iter,\n double maxLength)\n{\n auto xpoint = xpos;\n auto ypoint = ypos;\n auto zpoint = zpos;\n\n for(auto i = 0; i <= iter; i++)\n {\n if(!sequence(xpoint, ypoint, zpoint, power, maxLength,\n xpos, ypos, zpos)) {\n return false;\n }\n }\n return true;\n}\n\nbool sequence(\n double &xpoint,\n double &ypoint,\n double &zpoint,\n double power,\n double maxLength,\n double cx,\n double cy,\n double cz)\n{\n auto r = sqrt(xpoint*xpoint + ypoint*ypoint + zpoint*zpoint);\n auto phi = atan(ypoint/xpoint);\n auto theta = acos(zpoint/r);\n\n xpoint = pow(r, power) * sin(power * theta) * cos(power * phi) + cx;\n ypoint = pow(r, power) * sin(power * theta) * sin(power * phi) + cy;\n zpoint = pow(r, power) * cos(power * theta) + cz;\n\n return r < maxLength;\n}\n\nint main()\n{\n constexpr Parameters parameters{ 5, 50, 8.0, 2.0, -1.75, 1.75 };\n\n printParameters(std::cout, parameters);\n\n constexpr auto outputFileName = \"Mandelbulb.xyz\";\n std::ofstream ofs (outputFileName);\n\n calculation(ofs, std::cout, true, parameters);\n}\n</code></pre>\n\n<p>I hope this gives some idea how to make the code more readable. I think it can be still improved further.</p>\n\n<p>For a bit of speedup, I suggest to turn off the progress echoing in the console with <code>progressOutputOn = false</code> for the method <code>calculation</code>.</p>\n\n<p>As mentioned in the comments, maybe you can split up the calculation into several threads. For example:</p>\n\n<pre><code>xpoint = pow(r, power) * sin(power * theta) * cos(power * phi) + cx;\nypoint = pow(r, power) * sin(power * theta) * sin(power * phi) + cy;\nzpoint = pow(r, power) * cos(power * theta) + cz;\n</code></pre>\n\n<p>These 3 points get calculated one after each other. But they are independent of each other, so probably they can be excecuted in parallel. I sould try that out with <code>std::async</code>. </p>\n\n<p>That's my first thought but maybe even the whole algorithm needs to be set up differently to have it ready for parallel computation.</p>\n\n<p>Now that you have the code cleaned up, you can measure the time between the calculations to see how the speed is (also with other parameters).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T09:10:19.623",
"Id": "233525",
"ParentId": "233364",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "233525",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T20:44:34.203",
"Id": "233364",
"Score": "8",
"Tags": [
"c++",
"performance"
],
"Title": "C++ Mandelbulb-set generator"
}
|
233364
|
<p>I was trying to create a simple RAII wrapper with rule of 5 for a TCP POSIX socket. My aim was to try learn how to apply rule of five in different situations, but this one was somehow tricky.</p>
<pre><code>class tcp_socket {
public:
tcp_socket() {
_s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
}
tcp_socket(const tcp_socket& other) = delete;
tcp_socket& operator=(const tcp_socket& other) = delete;
tcp_socket(tcp_socket&& other) noexcept {
_s = other._s;
other._s = -1;
}
tcp_socket& operator=(tcp_socket&& other) noexcept {
if (this != &other) {
_s = other._s;
other._s = -1;
}
return (*this);
}
~tcp_socket() {
close(_s);
}
private:
int _s = -1;
};
</code></pre>
<p>In this class, I like to create socket in constructor and close it in destructor, a logical RAII approach. But I noticed closing socket in destructor creates a lot of side effects for writing other 4 routines of rule of five.</p>
<p><strong>Move constructor/assignment:</strong></p>
<p>As you see, I use <code>other._s = -1;</code> in move constructor/assignment. Because if I don't, when the moved object deletes, it will also close my socket in moved-to object. I think this will solve my problem, because when moved object will be destroyed, it will try to close <code>-1</code> file descriptor which is an error, but will not ruin anything.</p>
<p><strong>Copy constructor/assignment:</strong></p>
<p>As you see, the only method that I could think of for copy constructor/assignment is deleting them. Because at first I thought to use <code>dup()</code> to duplicate file descriptor for copying, but if I do so, operations on one one instance (for example <code>shutdown()</code>) will affect another instance.</p>
<p>What do you think about this class? Do you think if this class does provide a simple RAII with correct rule of five or I need to adjust it somehow? Is it possible to write Copy constructor/assignment somehow or it is not logical to provide them?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T20:05:16.300",
"Id": "456099",
"Score": "0",
"body": "@GuillaumeRacicot I have seen arguments that say sometimes using swap for move is not a good idea. because to does too many assignments which will be not necessary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T20:16:16.900",
"Id": "456100",
"Score": "0",
"body": "Unrelated: after `_s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);`, the code should test `_s` to make sure a socket was acquired. If it wasn't, this would be a fabulous place to throw an exception."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T20:10:30.450",
"Id": "456102",
"Score": "0",
"body": "@GuillaumeRacicot: You're right (and HolyBlackCat said so too) but there is more than one alternative."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T20:09:38.033",
"Id": "456103",
"Score": "0",
"body": "@Afshin in this case, your move assigement leaks a socket. If `other._s` is not `-1`, you **always leak**. Test it yourself and you'll see. The idiomatic fix is swap, and it so happen that it's also the most effecient. Your move constructor is okay though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T20:02:54.750",
"Id": "456104",
"Score": "0",
"body": "@GuillaumeRacicot: While a swap has elegance to it, I think it's somewhat inappropriate for one socket wrapper to infest another socket wrapper with something that requires a potentially failing system call. I say \"clean up your own mess\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T19:38:54.617",
"Id": "456105",
"Score": "0",
"body": "@Afshin it's broken because it leaks the `other`'s socket. It should be a swap."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T19:37:58.540",
"Id": "456106",
"Score": "0",
"body": "@Afshin depends on what you want. Do you want shared ownership or unique ownership?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T19:37:57.760",
"Id": "456107",
"Score": "0",
"body": "@Deduplicator why move assignment is broken?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T20:26:30.230",
"Id": "456108",
"Score": "0",
"body": "@GuillaumeRacicot yea, I got it. I had that memory leak because I forgot to use `close(_s);`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T19:36:09.140",
"Id": "456109",
"Score": "0",
"body": "@GuillaumeRacicot I thought of something like that myself too. So you think we need to do reference counting in this case too?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T19:35:27.157",
"Id": "456110",
"Score": "0",
"body": "@Afshin -- Change the word \"socket\" to \"stream\" in your comment, and you will see yourself in the same boat as C++ streams."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T19:34:59.250",
"Id": "456112",
"Score": "0",
"body": "@Afshin in that case you need something like `tcp_socket_ref` which act as an observer to the socket. Much like you can use raw pointers to observe the value of a `std::unique_ptr`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T19:33:46.943",
"Id": "456113",
"Score": "0",
"body": "@SombreroChicken the main reason I posted it here was copy constructor/assignment and if there is a way to provide them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T19:33:03.117",
"Id": "456114",
"Score": "0",
"body": "@PaulMcKenzie The only situation for copy constructor/assignment that I think of is when you was to use single socket in for example multiple thread. You want to pass socket for example in a visitor approach to other classes and use it in other classes. SO copy constructor/assignment is useful, but I really could not find a proper way to provide them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T19:30:16.513",
"Id": "456116",
"Score": "0",
"body": "I don't see anything wrong with deleting the copy constructor and assignment operator if they don't make sense. The C++ stream classes do the same thing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T19:36:07.883",
"Id": "456118",
"Score": "0",
"body": "As an aside, move-assignment is badly broken. Make it an unconditional straight swap."
}
] |
[
{
"body": "<p>These are good questions!</p>\n\n<h3>1. You should indeed have the copy constructor & assignment operator deleted.</h3>\n\n<p>The \"rule of five\" tells you to specifically define a copy c'tor and assignment operator - but it doesn't tell you that you have to make the available. It is a perfectly valid choice to decide to <em>not</em> allow your object to be copied or non-move-assigned - only moved. An example of this: <a href=\"https://en.cppreference.com/w/cpp/memory/unique_ptr\" rel=\"nofollow noreferrer\"><code>std::unique_ptr</code></a>.</p>\n\n<p>It's also what I would recommend in your case, because:</p>\n\n<ol>\n<li>Like you said, duplicating a file descriptor is weird and unexpected.</li>\n<li>It's not obvious to the user of your class what the copy behavior <em>should</em> be.</li>\n<li>There don't seem to be - AFAICT - common scenarios in which you would <em>copy</em>, rather than move or pass by <em>reference</em>, a TCP socket.</li>\n</ol>\n\n<h3>2. Consider using <code>std::optional</code> to indicate \"no valid value\" or \"missing\" or \"none\"</h3>\n\n<p>In C (and the C system call bindings on Unix-like systems), it is a convention to use the -1 value for an invalid/missing file descriptor is a convention. We know that the <code>int</code> type is actually larger than the actual space of possible file descriptor values, so we use a junk value, which we assume the OS never uses, to indicate \"no valid value\". Now, this works fine; and you could choose to, say, define a static class constant:</p>\n\n<pre><code>static constexpr const int no_file_descriptor { -1 };\n</code></pre>\n\n<p>and then write:</p>\n\n<pre><code>close(_s);\n_s = other._s;\nother._s = no_file_descriptor;\n</code></pre>\n\n<p><sub>As @HolyBlackCat suggests, you must get <code>_s</code> to be closed somehow. You could also just swap the two descriptors, but I find that to contradict the element of least surprise.</sub></p>\n\n<p>but you might want to consider the more general (though less space-efficient) solution, which is the <a href=\"https://en.cppreference.com/w/cpp/utility/optional\" rel=\"nofollow noreferrer\"><code>std::optional<T></code></a> type template. It is intended for exactly your case: Either holding some value of type <code>T</code> (in your case, <code>int</code>), or holding some indication of \"no value\". Using an optional, you could write:</p>\n\n<pre><code>close(_s.get());\n_s = other._s;\nother._s = std::nullopt;\n</code></pre>\n\n<p>You'll still need to write your move assignment and move construction code, unfortunately (thanks @CassioRenan for noticing these are both necessary).</p>\n\n<h3>Other suggestions</h3>\n\n<ol start=\"3\">\n<li>Don't use a plain <code>int</code>; either find a type definition of a file descriptor from some library you're using, or if you have no definition to borrow, have <code>using file_descriptor = int;</code> or <code>using file_descriptor_index = int</code>.</li>\n<li><code>_s</code> is a bad member name. Use something more explicit, e.g. <code>descriptor_index_</code> or <code>posix_descriptor_index_</code>.</li>\n<li>Always check the return value of library/system calls! And handle errors.</li>\n</ol>\n\n<h3>The modified code</h3>\n\n<pre><code>class tcp_socket {\nprotected:\n void close_if_neccessary() {\n constexpr auto socket_close_failed { -1 };\n if (descriptor_index_.has_value()) { \n auto retval = close(descriptor_index_.value()); \n if (retval == socket_close_failed) { \n // throw something here, e.g.:\n // throw std::system_error(errno, std::system_category(), \"close()\");\n }\n };\npublic:\n using file_descriptor_index = int;\n\n tcp_socket() : descriptor_index_() { \n constexpr auto socket_creation_failed { -1 };\n auto retval = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);\n if (retval == socket_creation_failed) { \n // throw std::system_error(errno, std::system_category(), \"socket()\");\n }\n descriptor_index = retval;\n };\n\n tcp_socket(const tcp_socket& other) = delete;\n tcp_socket& operator=(const tcp_socket& other) = delete;\n tcp_socket& operator=(tcp_socket&& other) noexcept {\n if (other.descriptor_index_ != descriptor_index_) {\n close_if_neccessary();\n descriptor_index_ = other.descriptor_index_;\n other.descriptor_index_ = std::nullopt;\n }\n return this;\n };\n tcp_socket(tcp_socket&& other) noexcept :\n descriptor_index_(other.descriptor_index_) \n {\n other.descriptor_index = std::nullopt;\n }\n ~tcp_socket() { \n // You might want to wrap this in a try-catch, since\n // destructors shouldn't throw. Otherwise you're risking\n // a double-exception and immediate program termination.\n close_if_necessary(); \n }\n\nprotected:\n std::optional<file_descriptor_index> descriptor_index_;\n};\n</code></pre>\n\n<p>See <a href=\"https://stackoverflow.com/q/12171377/1593077\">this StackOverflow question</a> about the weird exception code in the comments:</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T20:40:45.543",
"Id": "456119",
"Score": "0",
"body": "I somehow agree with Guillaume more with not using optional in this specific case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T20:26:17.067",
"Id": "456120",
"Score": "2",
"body": "@einpoklum-reinstateMonica because there is a complete subset of a value an int can take to represent a unix socket. `-1` is the value used to contain the *no socket* in case of errors. I would personally not transform the value representation of what an API returns. I may not know someday `-2` could be used for something else. Also, it's a bit like `std::unique_ptr`. It doesn't contain an optional pointer. Rather, the `nullptr` value denotes the *not owner* value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T20:15:07.720",
"Id": "456121",
"Score": "0",
"body": "@GuillaumeRacicot: It's not essential to use it, but - why would you advise against?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T19:54:11.500",
"Id": "456122",
"Score": "0",
"body": "if I use `std::optional`, I need to check and if it has value then close it is destructor,isn't it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T19:55:12.623",
"Id": "456123",
"Score": "0",
"body": "@Afshin: Yes, essentially: `if descriptor_index_.has_value() { close(descriptor_index); }`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T20:10:25.757",
"Id": "456124",
"Score": "0",
"body": "I would advise against `std::optional`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T21:05:04.473",
"Id": "456133",
"Score": "0",
"body": "@GuillaumeRacicot: There is, but why is that an issue? Are you out of bytes? Do you expect there to be a hundreds of thousands of RAII sockets making the space-saving meaningful? As for `std::unique_ptr` - it can get away with it, maybe, because pointers traditionally have `nullptr` as a meaningful value. Having said that - allowing for a \"null socket\" is as simple as adding a default constructor to my code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T21:06:57.657",
"Id": "456134",
"Score": "0",
"body": "@Afshin: You're thinking in C terms. You should not explore these minor hacks unless it really gives you some benefit other than feeling clever. It's much better to have simpler, shorter, code with less information to remember."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T21:34:56.427",
"Id": "456144",
"Score": "1",
"body": "Just noticed something else: If you use the move constructor by doing `tcp_socket a; tcp_socket b(std::move(a))`, you end up closing the same socket twice. This happens because when moving a `std::optional`, the moved-from `optional` will still contain a value (except that it will be a *moved-from* value). My take from this is that `std::optional` is really not a great choice for this specific problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T23:46:46.637",
"Id": "456153",
"Score": "0",
"body": "@CássioRenan: Oh, man! That's so annoying. I somehow had it in my head that moving from an optional actually clears it. Thanks again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T06:51:14.617",
"Id": "456188",
"Score": "1",
"body": "@einpoklum-reinstateMonica \"It's much better to have simpler, shorter, code with less information to remember.\", and that is what you did in this code???"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T07:12:24.350",
"Id": "456190",
"Score": "0",
"body": "@E.Vakili: The lengthening of my code are mostly not due to the use of `std::optional` - it's longer names, error handling avoiding double-close's, comments... but ok, fair point still."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T09:51:56.990",
"Id": "456209",
"Score": "3",
"body": "@einpoklum-reinstateMonica Adding `std::optional` does not add any benefits to the solution except loss of efficiency, readability, and ... It's not a C++ point of view as you claim. C++ aims at bringing strong abstraction alongside the efficiency. Don't pay for what you don't need."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T19:40:00.157",
"Id": "233366",
"ParentId": "233365",
"Score": "7"
}
},
{
"body": "<p>There's one major problem with the code:</p>\n\n<p><strong>Your move assignment is broken.</strong></p>\n\n<p>You forgot to <code>close(_s)</code> before overwriting it with <code>other._s</code>.</p>\n\n<p>To avoid this kind of problems, I suggest using the copy-and-swap idiom. It makes writing a <code>operator=</code> a no-brainer in most cases:</p>\n\n<pre><code>tcp_socket &operator=(tcp_socket other) noexcept // Note the lack of `&&`.\n{\n std::swap(_s, other._s);\n return *this;\n}\n</code></pre>\n\n<p>If you decide to do this, you also need to remove <code>tcp_socket& operator=(const tcp_socket& other) = delete;</code> to prevent it from conflicting with this operator.</p>\n\n<hr>\n\n<p>Additionally...</p>\n\n<p><strong>You shouldn't do <code>close(-1)</code>.</strong></p>\n\n<p>Moving an object sets <code>_s</code> of the original object to <code>-1</code>.</p>\n\n<p><code>close(-1)</code> is not a no-op. (It sets <code>errno</code> to 'bad file descriptor'.) Thus the destructor should do</p>\n\n<pre><code>if (_s != -1)\n close(_s);\n</code></pre>\n\n<p><strong>It would be a good idea to have a way to create a 'null' <code>tcp_socket</code> instance.</strong></p>\n\n<p>Instances of <code>tcp_socket</code> don't necessarily own sockets. By moving from an instance, or make it 'null' (i.e. it no longer owns a socket).</p>\n\n<p>IMO, it would make sense to have a way to directly create 'null' intstances.</p>\n\n<p>I wouldn't open the socket in <code>socket()</code>, and create a separate constructor that does open one.</p>\n\n<p><strong>You don't <em>have</em> to explicitly delete the copy constructor and assignment operator.</strong></p>\n\n<p>Declaring a move constructor or assignment operator causes both the constructor and assignment operator to be implicitly deleted. </p>\n\n<p>Whether or not you <em>should</em> delete them explicitly (for extra clarity) is a different question.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T19:59:54.657",
"Id": "456125",
"Score": "0",
"body": "I would +1 you for the first two suggestions, but -1 you for the third one. It would not be a good idea to be able to create a 'null' TCP socket. That kind of flies in the face of the RAII approach. Now, you could argue that perhaps RAII is not a good approach for sockets, but that's a different discussion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T20:02:47.017",
"Id": "456126",
"Score": "0",
"body": "if you provide move assignment in the way you did, you practically provide copy assignment too.isn't it? so I think it is better to add `&&` to provide move only. and yea, I missed `close(_s);`, I should have not made that mistake."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T20:04:03.270",
"Id": "456127",
"Score": "0",
"body": "@Afshin If you had a non-deleted copy constructor, then yes, this assignment operator would act as a copy assignment too (another reason why copy-and-swap is so good). But since your copy constructor is deleted, it doesn't. If you added `&&` here, you'd need to do `other._s = -1` manually. (Having `operator=` swap objects is not a good idea.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T20:11:36.510",
"Id": "456128",
"Score": "0",
"body": "@einpoklum-reinstateMonica Let's agree to disagree. :) From my experience, it's extremely convenient (and it would be even more convenient if creating a socket required some parameters, preventing `tcp_socket` from being default-constructible otherwise). And, after all, that's what `std::fstream` does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T20:13:24.167",
"Id": "456129",
"Score": "0",
"body": "@HolyBlackCat: It _is_ extremely convenient - but in the same way that having a null pointer is convenient. The inconvenience forces you to not whip these objects into existence until you really need to. Remember you can always use `std::optional<tcp_socket>`, and that's your \"null socket\" right there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T20:37:48.453",
"Id": "456130",
"Score": "0",
"body": "You made a mistake. since I need to provide deleted copy assignment, you **must** add `&&` to your move assignment. I just tested and if we don't we get `use of overloaded operator '=' is ambiguous` error which is logical."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T20:47:59.210",
"Id": "456131",
"Score": "0",
"body": "@Afshin Huh, you're right. But rather than adding `&&`, you can simply remove the deleted copy assignment. It will be implicitly deleted anyway, and an implicitly deleted copy assignment doesn't seem to cause such conflicts."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T20:57:13.080",
"Id": "456132",
"Score": "0",
"body": "But If I remove explicitly deleted copy assignment and `&&`, code will not be efficient because both move constructor and move assignment will be called(not sure why move constructor will be called in this case, but testing so I'm sure). So still adding `&&` is better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T21:12:00.503",
"Id": "456136",
"Score": "1",
"body": "@Afshin More function calls doesn't necessarily mean slower code, the only way to know for sure is to benchmark it. I wouldn't expect any noticeable slowdown, especially in release builds. The reason why I prefer the `&&`-less version is because it's easier to write."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T19:55:32.827",
"Id": "233367",
"ParentId": "233365",
"Score": "6"
}
},
{
"body": "<p>As other answers have said, use swap to get assignment correct, and don't close already-closed descriptors.</p>\n<p>Some minor style nitpicks to add:</p>\n<ul>\n<li>Use initializers in preference to assignment in the constructors.</li>\n<li>There's no need to name the arguments to the deleted copy methods.</li>\n<li>Remove the redundant parens from <code>return *this;</code>.</li>\n<li>Consider a public <code>close()</code> method, for users that care about handling errors.</li>\n</ul>\n<p>In contrast to einpoklum, I like your choice of invalid file descriptor (-1); we don't need the overhead of <code>std::optional</code> when a clear invalid value is available. I do recommend giving it a name, though.</p>\n<h1>My version</h1>\n<pre><code>#include <utility>\n\n#include <unistd.h>\n#include <sys/types.h> /* required on pre-POSIX BSD platforms */\n#include <sys/socket.h>\n#include <netinet/in.h>\n\nclass tcp_socket\n{\npublic:\n tcp_socket()\n : s{::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)}\n {\n }\n\n tcp_socket(const tcp_socket&) = delete;\n void operator=(const tcp_socket&) = delete;\n\n tcp_socket(tcp_socket&& other) noexcept\n : s{other.s}\n {\n other.s = null_socket;\n }\n\n tcp_socket& operator=(tcp_socket&& other) noexcept\n {\n return swap(other);\n }\n\n int close() {\n return ::close(s);\n }\n \n ~tcp_socket()\n {\n if (s != null_socket) {\n // note: errors are ignored!\n close();\n }\n }\n\nprivate:\n static constexpr int null_socket = -1;\n\n int s;\n\n tcp_socket& swap(tcp_socket& other) noexcept\n {\n std::swap(s, other.s);\n return *this;\n }\n};\n</code></pre>\n<h1>Future directions</h1>\n<p>You might need a <code>udp_socket</code> before long. It's probably a good idea to create a <code>socket</code> base class with protected constructor so that the RAII is managed in a single-responsibility class and the protocol-specific part is in relevant subclasses:</p>\n<pre><code>class socket\n{\nprotected:\n socket(int fd)\n : s{fd}\n {\n }\n\npublic:\n // ...\n};\n\nclass tcp_socket : public socket\n{\npublic:\n tcp_socket()\n : socket{::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)}\n {\n }\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T09:00:04.550",
"Id": "233395",
"ParentId": "233365",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "233366",
"CommentCount": "16",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T19:26:02.390",
"Id": "233365",
"Score": "12",
"Tags": [
"c++",
"socket",
"tcp",
"posix",
"raii"
],
"Title": "Correctly applying the \"rule of five\" to a RAII socket wrapper"
}
|
233365
|
<p>I have a tool that displays data in some format. For example, it can display a list of dogs in a CSV or JSON formats.
In the code, I had a lot of places where I had to check the format and display the data in that format. The only difference between the code blocks is the calls to the data.
Some of them call <code>get_name()</code> and <code>get_id()</code> while others call <code>get_type()</code> and so on.</p>
<p>I tried to create an abstract class that has the display method and the derived classes have the <code>get_block</code> (for JSON), <code>get_line</code> (for CSV) and so on.
The code looks like:</p>
<pre><code>class DisplayingFormatEnum(Enum):
OPTION_A = 'user-option-a'
OPTION_B = 'user-option-b'
class DisplayingFormat(ABC):
def get_row(data):
pass
def get_block(data):
pass
def get_line(data):
pass
def display_format_table(self):
table = PrettyTable(self.title)
for d in self.data:
table.add_row(self.get_row(d))
print(table)
def print_json(self):
result = []
for d in self.data:
block = self.get_block(d)
result.append(block)
print(result)
def display_format_dsv(self):
for d in self.data:
print(f"{self.get_line(d)}")
def display_format_list(self):
if self.result_format == 'table':
self.display_format_table()
elif self.result_format == 'json':
self.display_format_json()
else:
self.display_format_dsv()
class DisplayingFormatPeople(DisplayingFormat):
def __init__(self, people, result_format, enum_type):
if not isinstance(enum_type, DisplayingFormatEnum):
raise DisplayingFormatError("Entity must be an instance of DisplayingFormatEnum Enum")
if enum_type.value == DisplayingFormatEnum.OPTION_A.value:
self.title = TITLE_OPTION_A['people']
else:
raise DisplayingFormatError(f"DisplayingFormatPeople can only use {DisplayingFormatEnum.OPTION_A.value} as a valid enum_type. Invalid enum_type: {enum_type.value}")
self.result_format = result_format
self.data = people
self.enum_type = enum_type
def get_row(self, person):
return [person.get_name(), person.get_id()]
def get_block(self, person):
block = {}
block[self.title[0]] = person.get_name()
block[self.title[1]] = person.get_id()
return block
def get_line(self, person):
return ';'.join((person.get_name(), person.id()))
class DisplayingFormatCars(DisplayingFormat):
def __init__(self, cars, result_format, enum_type):
if not isinstance(enum_type, DisplayingFormatEnum):
raise DisplayingFormatError("Entity must be an instance of DisplayingFormatEnum Enum")
if enum_type.value == DisplayingFormatEnum.OPTION_A.value:
self.title = TITLE_OPTION_A['cars']
else:
raise DisplayingFormatError(f"DisplayingFormatProjects can only use {DisplayingFormatEnum.OPTION_A.value} as a valid enum_type. Invalid enum_type: {enum_type.value}")
self.result_format = result_format
self.data = cars
self.enum_type = enum_type
def get_row(self, car):
return [car.get_type()]
def get_block(self, car):
block = {}
block[self.title[0]] = car.get_type()
return block
def get_line(self, car):
return car.get_type()
class DisplayingFormatDogs(DisplayingFormat):
def __init__(self, dogs, result_format, enum_type):
if not isinstance(enum_type, DisplayingFormatEnum):
raise DisplayingFormatError("Entity must be an instance of DisplayingFormatEnum Enum")
if enum_type.value == DisplayingFormatEnum.OPTION_A.value:
self.title = TITLE_OPTION_A['dogs']
elif enum_type.value == DisplayingFormatEnum.OPTION_B.value:
self.title = TITLE_OPTION_B['dogs']
else:
error_line = "DisplayingFormatDogs can only use {DisplayingFormatEnum.OPTION_A.value} and {DisplayingFormatEnum.OPTION_B.value} as valid entities."
error_line += "Invalid enum_type: {enum_type.value}"
raise DisplayingFormatError(f"{error_line}")
self.result_format = result_format
self.data = dogs
self.enum_type = enum_type
def get_row(self, dog):
return [dog.get_nickname(), dog.get_type()]
def get_block(self, dog):
block = {}
block[self.title[0]] = dog.get_nickname()
block[self.title[2]] = dog.get_type()
return block
def get_line(self, dog):
return ';'.join((dog.get_nickname(), dog.get_type()))
class DisplayingFormatError(Exception):
pass
</code></pre>
<p>I believe that this code is a good use of inheritance but I think it does not fit well with the "composition over inheritance" rule.
I'm afraid of unexpexted future changes that will require me to change this code.
How should I change my code to follow this rule?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T15:32:17.410",
"Id": "456250",
"Score": "0",
"body": "Please edit your question so that the title describes the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!"
}
] |
[
{
"body": "<p>I'm not convinced using an abstract base class is really useful here. All of your methods follow exactly the same principles. The only differences are the names and fields and the allowed enumeration values.</p>\n\n<p>So as a first step I would put all the code into the baseclass, and only add the check for the enumeration into the constructor and implement the <code>get_data</code> method in each subclass:</p>\n\n<pre><code>class DisplayingFormat:\n def __init__(self, data, result_format, enum_type):\n if not isinstance(enum_type, DisplayingFormatEnum):\n raise DisplayingFormatError(\"Entity must be an instance of DisplayingFormatEnum Enum\")\n self.result_format = result_format\n self.data = data\n self.enum_type = enum_type\n self.title = None\n\n def get_data(self, obj):\n raise NotImplementedError\n\n def to_table(self):\n table = PrettyTable(self.title)\n for d in self.data:\n table.add_row(self.get_data(d))\n return table\n\n def to_json(self):\n return [dict(zip(self.title, self.get_data(d))) for d in self.data]\n\n def to_dsv(self):\n return [';'.join(map(str, self.get_data(d))) for d in self.data]\n\n def display_format_list(self):\n if self.result_format == 'table':\n print(self.to_table())\n elif self.result_format == 'json':\n print(self.to_json())\n else:\n print(self.to_dsv())\n\n\nclass DisplayingFormatPeople(DisplayingFormat):\n def __init__(self, people, result_format, enum_type):\n super().__init__(people, result_format, enum_type)\n\n if enum_type.value == DisplayingFormatEnum.OPTION_A.value:\n self.title = TITLE_OPTION_A['people']\n else:\n raise DisplayingFormatError(f\"DisplayingFormatPeople can only use {DisplayingFormatEnum.OPTION_A.value} as a valid enum_type. Invalid enum_type: {enum_type.value}\")\n\n def get_data(self, person):\n return person.get_name(), person.get_id()\n\n\nclass DisplayingFormatCars(DisplayingFormat):\n def __init__(self, cars, result_format, enum_type):\n super().__init__(cars, result_format, enum_type)\n\n if enum_type.value == DisplayingFormatEnum.OPTION_A.value:\n self.title = TITLE_OPTION_A['cars']\n else:\n raise DisplayingFormatError(f\"DisplayingFormatProjects can only use {DisplayingFormatEnum.OPTION_A.value} as a valid enum_type. Invalid enum_type: {enum_type.value}\")\n\n def get_data(self, car):\n return car.get_type()\n\nclass DisplayingFormatDogs(DisplayingFormat):\n def __init__(self, dogs, result_format, enum_type):\n super().__init__(cars, result_format, enum_type)\n\n if enum_type.value == DisplayingFormatEnum.OPTION_A.value:\n self.title = TITLE_OPTION_A['dogs']\n elif enum_type.value == DisplayingFormatEnum.OPTION_B.value:\n self.title = TITLE_OPTION_B['dogs']\n else:\n error_line = f\"DisplayingFormatDogs can only use {DisplayingFormatEnum.OPTION_A.value} and {DisplayingFormatEnum.OPTION_B.value} as valid entities.\"\n error_line += f\"Invalid enum_type: {enum_type.value}\"\n raise DisplayingFormatError(error_line)\n\n def get_data(self, dog):\n return dog.get_nickname(), dog.get_type()\n</code></pre>\n\n<p>Note that I also fixed some un-/needed <code>f-string</code>s and used list comprehensions where applicable. I also modified and renamed your format methods so they return the formatted object and are only printed in <code>display_format_list</code>, which might need a better name as well.</p>\n\n<p>This could be simplified further. The easiest way is if you can modify the objects in <code>data</code> to have an implemented <code>__getitem__</code> method, but you can also hack it together using <code>getattr</code>. What you really only need for each subclass are the field names and the association between the option and the title:</p>\n\n<pre><code>class DisplayingFormat:\n fields = []\n titles = {}\n def __init__(self, data, result_format, enum_type):\n if not isinstance(enum_type, DisplayingFormatEnum):\n raise DisplayingFormatError(\"Entity must be an instance of DisplayingFormatEnum Enum\")\n if enum_type not in self.titles:\n raise DisplayingFormatError(f\"enumy_type must be in {[opt.value for opt in self.titles]}. Invalid enum_type: {enum_type.value}\")\n self.result_format = result_format\n self.data = data\n self.title = self.titles[enum_type]\n\n def get_data(self, obj):\n # if you implement __getitem__\n return [obj[f] for f in self.fields]\n # or this, if you cannot modify your objects interface\n return [getattr(obj, f\"get_{f}\")() for f in self.fields]\n\n ...\n\nclass DisplayingFormatPeople(DisplayingFormat):\n fields = [\"name\", \"id\"]\n titles = {DisplayingFormatEnum.OPTION_A: TITLE_OPTION_A['people']}\n\nclass DisplayingFormatCars(DisplayingFormat):\n fields = [\"type\"]\n titles = {DisplayingFormatEnum.OPTION_A: TITLE_OPTION_A['dogs']}\n\nclass DisplayingFormatDogs(DisplayingFormat):\n fields = [\"nickname\", \"type\"],\n titles = {DisplayingFormatEnum.OPTION_A: TITLE_OPTION_A['dogs']\n DisplayingFormatEnum.OPTION_B: TITLE_OPTION_B['dogs']}\n</code></pre>\n\n<p>If you really want to go the route of composition, you would probably want to make the formatter an argument, so that you have only one class with this interface:</p>\n\n<pre><code>class Display:\n def __init__(self, data, title, formatter):\n ...\n</code></pre>\n\n<p>where taking care of selecting the proper columns to go to <code>data</code> as well as selecting the proper title is all external to the class. The formatter then takes the role of the <code>to_json</code>, ... methods. And at that point it doesn't even need to be a class anymore, a function would suffice.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-10T23:55:48.827",
"Id": "457168",
"Score": "0",
"body": "I don't get how `to_json` and `to_dsv` work. What if `get_data` returns only one string and not tuple? it prints something like `p;e;r;s;o;n`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T15:23:26.647",
"Id": "233417",
"ParentId": "233369",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T21:07:03.750",
"Id": "233369",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"formatting",
"inheritance"
],
"Title": "Using composition instead of inheritance and abstract classes"
}
|
233369
|
<h1>Problem</h1>
<p>Developers in my team are new to Docker. I wanted to provide a way to accomplish general Docker housekeeping tasks (like pruning unused images and compacting the Hyper-V volume) largely automatically.</p>
<h1>Solution</h1>
<p>The PowerShell script below is designed to be run either interactively or as a service. When run non-interactively, progress is logged to the Windows Event Log, otherwise progress is logged to the console.</p>
<p>Additionally, we provide a number of pre-built base images in our internal registry <code>HQ-DOCKER-</code>. These provide server software whose details the developers don't need to know. So, point releases and upstream base OS patches are built into images <em>of the same tag name</em>. These also need to be pulled at semi-regular intervals (for those who ignore automated build announcements we already have in place).</p>
<h1>Review Goals</h1>
<ol>
<li>Is this process adequately <em>fault-tolerant</em>?</li>
<li>Is it <em>overly complicated</em>? (Would it be better broken out into two scripts: one that's always non-interactive and one that can be run interactively?)</li>
<li>Is it adequately <em>portable</em> (specifically regarding the .NET libraries I use, or something I may have overlooked)?</li>
<li>Are there any glaring non-idiomatic-PowerShell issues?</li>
</ol>
<p>As always, further comments beyond the scope of the 4 above points are more than welcome. Similarly, commentary about this post are welcome.</p>
<h1>Code</h1>
<pre><code>#Requires -RunAsAdministrator
#Requires -Modules Hyper-V
param(
[Switch]$FullSystem,
[Switch]$Pull,
[String]$VHDX
)
if ([System.Diagnostics.EventLog]::SourceExists("DockerMaintenance") -eq $False) {
New-EventLog -LogName Application -Source DockerMaintenance
}
function Write-ErrorLog($Message) {
if (!$MyInvocation.scriptname) {
Write-EventLog -LogName Application `
-Source DockerMaintenance `
-EventID 3001 `
-Category 1 `
-EntryType Error `
-Message $Message
} else {
Write-Host -ForegroundColor Red $Message
}
}
function Write-InfoLog($Message) {
if (!$MyInvocation.scriptname) {
Write-EventLog -LogName Application `
-Source DockerMaintenance `
-EventID 3001 `
-Category 1 `
-EntryType Information `
-Message $Message
} else {
Write-Host $Message
}
}
if ($null -eq $VHDX) {
$err = "The -VHDX parameter is missing! Please add it."
Write-ErrorLog $err
Exit -1
} elseif ((![System.IO.File]::Exists("${VHDX}")) -or ($VHDX -notlike "*\DockerDesktop.vhdx")){
$err = "The path provided for -VHDX ""${VHDX}"" does not point to a 'DockerDesktop.vhdx'!"
Write-ErrorLog $err
Exit -2
}
function Invoke-Toast($Message, $Cancel) {
$AppId = '{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\WindowsPowerShell\v1.0\powershell.exe'
$XmlString = @"
<toast>
<visual>
<binding template="ToastGeneric">
<text hint-maxLines="1">Docker Maintenance</text>
<text>$Message</text>
</binding>
</visual>
<audio src="ms-winsoundevent:Notification.Default" />
</toast>
"@
$ToastXml = [Windows.Data.Xml.Dom.XmlDocument]::new()
$ToastXml.LoadXml($XmlString)
$Toast = [Windows.UI.Notifications.ToastNotification]::new($ToastXml)
[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($AppId).Show($Toast)
}
function Invoke-ImagePrune() {
Write-InfoLog "Pruning unused and dangling images"
docker image prune -f
}
function Invoke-SystemPrune() {
Write-InfoLog "Fully pruning docker system"
docker system prune -f
}
function Invoke-DockerPull() {
Write-InfoLog "Pulling HQ docker images"
docker images --format "{{.Repository}}:{{.Tag}}" | Where-Object { $_ -like "hq-docker-*" } | ForEach-Object { docker pull $_ }
}
function Invoke-CompactDocker() {
Write-InfoLog "Compacting ${VHDX}"
Mount-VHD $VHDX -ReadOnly
Optimize-VHD $VHDX -Mode Full
Dismount-VHD $VHDX
}
function Stop-Docker() {
$docker = Get-VM | Where-Object { $_.Name -eq 'DockerDesktopVM' }
if ($docker.State -ne "Off") {
Write-InfoLog "Docker is still running. Stopping..."
Get-VM | Where-Object { $_.Name -eq 'DockerDesktopVM' } | Stop-VM
Get-Process -Name "*Docker*" | Stop-Process -Force
}
}
function Start-Docker() {
Write-InfoLog "Restarting docker"
Net Start "com.docker.service"
& "C:\Program Files\Docker\Docker\Docker Desktop.exe"
if ($MyInvocation.scriptname) {
Write-Host "Docker for Windows is now starting up. Watch for the usual Toast notification."
}
}
if ($MyInvocation.scriptname) {
Invoke-Toast "Your Docker for Windows will be temporarily shut down for maintenance in 5 MINUTES. `
This process should take about 3 minutes."
Start-Sleep -Seconds (60*5)
} else {
Write-Host -ForegroundColor Green "Beginning maintenance in 5 seconds. Abort with [CTRL-C]."
Start-Sleep -Seconds 5
}
if ($True -eq $Pull) {
Invoke-DockerPull
}
if ($True -eq $FullSystem) {
Invoke-SystemPrune
} else {
Invoke-ImagePrune
}
Stop-Docker
Invoke-CompactDocker
Write-InfoLog "Maintenance Complete, restarting Docker..."
Start-Docker
</code></pre>
<h1>Doc Comment</h1>
<p>At the very top of the file, I extracted it to make the code more concise but include it here for completeness.</p>
<pre><code><#
.Synopsis
Runs periodic maintenance on Docker for Windows.
It must be run as an Administrator!
.Description
Intended to be run interactively or as a periodoc service, this will execute configurable docker prune
within the VM and then stop and compact the virtual machine hard disk before restarting Docker.
When run as a service, logs are sent to the Windows Event Log. Otherwise, progress is logged to the console.
.Parameter VHDX
Required. The complete path to your DockerDesktop virtual hard disk file, i.e., 'F:\Docker\DockerDesktop.vhdx'
.Parameter FullSystem
Optional. By default docker will prune unused images with 'docker image prune'.
Add this flag to execute 'docker system prune -f'.
.Parameter Pull
Optional (but recommended). Pull rebuilt base images from the internal HQ-DOCKER registry.
.Example
periodic-maintenance.ps1 -VHDX "F:\Docker\DockerDesktop.vhdx" -FullSystem -Pull
# Interactively run a full system prune, pull the latest internal base images, compact the VHDX.
.Example
periodic-maintenance.ps1 -VHDX "F:\Docker\DockerDesktop.vhdx"
# Run a minimal image prune and compact the VHDX.
#>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T21:42:42.967",
"Id": "233370",
"Score": "3",
"Tags": [
".net",
"powershell",
"virtual-machine",
"docker"
],
"Title": "PowerShell script to execute Docker maintenance, optionally non-interactively"
}
|
233370
|
<p><strong>Requirements (<em>Installed using <a href="https://scoop.sh/" rel="nofollow noreferrer">Scoop</a></em>)</strong></p>
<pre><code>scoop install nasm dosbox
</code></pre>
<p><strong>Build <em>(Using <a href="https://nasm.us/" rel="nofollow noreferrer">NASM</a></em>)</strong></p>
<pre class="lang-bsh prettyprint-override"><code>nasm -g tasks.asm -o tasks.com
</code></pre>
<blockquote>
<p><code>-g</code> enables debugging capabilities</p>
</blockquote>
<p><strong>Execute <em>(Using <a href="https://www.dosbox.com/" rel="nofollow noreferrer">DOSBox</a></em>)</strong></p>
<pre class="lang-bsh prettyprint-override"><code>mount H: C:\com\parent\path
H:
tasks.com
</code></pre>
<p><strong><em>tasks.asm</em></strong></p>
<p>Sections are added for clarity.</p>
<pre><code>[org 100h]
section .text
main:
lea si, [task_a]
call spawn_new_task
lea si, [task_b]
call spawn_new_task
.loop_forever:
lea si, [main_str]
call putstring
call yield
jmp .loop_forever
task_a:
.loop_forever:
lea si, [main_a]
call putstring
call yield
jmp .loop_forever
task_b:
.loop_forever:
lea si, [main_b]
call putstring
call yield
jmp .loop_forever
spawn_new_task:
; find a free task, start pointers off at -1
xor cx, cx
lea bx, [stack_status]
.loop:
cmp cx, 3 ; change this to add more tasks
jl .continue
ret ; no free task, return immediately
.continue:
cmp byte [bx], 0
je .done ; if equal, tasks is free
inc cx
inc bx
jmp .loop
.done:
mov byte [bx], 1 ; task was free, reserve it
lea bx, [stack_pointers]
mov [bx], sp ; save main's stack pointer
; switch to free stack
add bx, cx
add bx, cx ; free stack is list of words (not bytes) and add is cheaper than mul
mov sp, [bx] ; change to free stack
push si ; push stuff
pusha
pushf
mov [bx], sp ; save new stack's new pointer
mov sp, [stack_pointers] ; change back to main
ret
yield:
; ret already saved by call
pusha
pushf
movzx cx, byte [current_task]
; save current stack pointer
lea bx, [stack_pointers]
add bx, cx
add bx, cx
mov [bx], sp
; loop through stack status looking for a 1
lea bx, [stack_status]
add bx, cx ; make sure we start looking at next task
.loop:
inc bx
inc cx
cmp cx, 3 ; increment this for more tasks
jl .continue
xor cx, cx ; clear cx
lea bx, [stack_status] ; reset bx back to start
.continue:
cmp byte [bx], 1 ; is this stack active
je .found_one
jmp .loop
.found_one:
mov [current_task], cl
; switch to new stack
lea bx, [stack_pointers]
add bx, cx
add bx, cx
mov sp, [bx]
popf
popa
ret
; takes an address to write to in si
; writes to address until a null term is encountered
; returns nothing
putstring:
mov ah, 0Eh
.continue:
lodsb ; put char to write in al
test al, al ; simulate and
je .done ; was al 0?
int 10h ; call interrupt
jmp putstring
.done:
ret
section .rdata
main_str: db "I am task main", 13, 10, 0
main_a: db "I am task a", 13, 10, 0
main_b: db "I am task b", 13, 10, 0
section .data
current_task: db 0
stack_status:
status_1: db 1 ; this is for Main
status_2: db 0
status_3: db 0
stacks: times 256 * 2 db 0
stack_pointers:
dw 0 ; this is for Main
dw stacks + 256
dw stacks + 512
</code></pre>
|
[] |
[
{
"body": " \n\n<p>This is a nice example of <a href=\"https://en.wikipedia.org/wiki/Cooperative_multitasking\" rel=\"nofollow noreferrer\">Cooperative Multitasking</a>. Each task has to decide if and when it yields. However based on the fact that the individual tasks are placed in a single program, this could sooner be called Cooperative <a href=\"https://en.wikipedia.org/wiki/Multithreading_(computer_architecture)\" rel=\"nofollow noreferrer\">Multithreading</a>.</p>\n\n<p>In the <em>putstring</em> procedure you erroneously wrote <code>jmp putstring</code> where you clearly wanted to write <code>jmp .continue</code>. That's an honest mistake.\nWhat you do keep neglecting though is the <em>DisplayPage</em> parameter that BIOS expects in the <code>BH</code> register.</p>\n\n<p>If you've programmed in MASM before, it can be hard to adopt the shorter way to load an address via the <code>mov</code> instruction. <code>mov si, task_a</code> does the same as your <code>lea si, [task_a]</code> but it is 1 byte shorter. You used this many times (11x).</p>\n\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code> cmp cx, 3 ; change this to add more tasks\n jl .continue\n ret ; no free task, return immediately\n.continue:\n</code></pre>\n</blockquote>\n\n<p>This ressembles a beginner's code, yet I'm sure you are not a beginner!\nThe <em>spawn_new_task</em> procedure has a nice <code>ret</code> near its end, so why not jump there based on the opposite condition?</p>\n\n<pre class=\"lang-none prettyprint-override\"><code> cmp cx, 3 ; change this to add more tasks\n jnl .ret ; no free task, return immediately\n\n ...\n\n.ret:\n ret\n</code></pre>\n\n<p>Same thing happens here:</p>\n\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code> cmp byte [bx], 1 ; is this stack active\n je .found_one\n jmp .loop\n.found_one:\n</code></pre>\n</blockquote>\n\n<p>Why not write (no need for the label this time):</p>\n\n<pre class=\"lang-none prettyprint-override\"><code> cmp byte [bx], 1 ; is this stack active\n jne .loop\n</code></pre>\n\n<p>Because your <em>main</em> task will always be active, there's no reason to consider it in the search for a free task slot. This saves one iteration forever.<br>\nAlso there's no need to test the <code>CX</code> counter up front. Better have the test near the bottom and avoid the extraneous unconditional jump back. So changing from a <strong>Do While</strong> loop into a <strong>Loop While</strong> loop.<br>\nStarting from a byte that is known to be 0, <code>inc byte [bx]</code> will produce shorter code than <code>mov byte [bx], 1</code>.</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>spawn_new_task: ; find a free task, start pointers off at -1\n xor cx, cx\n mov bx, stack_status\n.loop:\n inc bx\n inc cx\n cmp [bx], ch ; CH=0\n je .done ; if equal, tasks is free\n cmp cx, 2 ; change this to add more 'spawnable' tasks\n jb .loop\n ret ; no free task, return immediately\n.done:\n inc byte [bx] ; task was free, reserve it\n</code></pre>\n\n<p>What's the comment \"start pointers off at -1\" about? Your code nowhere has any -1.</p>\n\n<p>The bulk of this program contains empty space. You can easily move the free space for the additional stacks outside of the program file.</p>\n\n<hr>\n\n<p>The following rewrite (FASM) reveals a <strong>code size</strong> reduction of 9% (171 → 156) and a <strong>file size</strong> reduction of 72% (735 → 208).</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>org 100h\n\nmain:\n mov si, task_a\n call spawn_new_task\n mov si, task_b\n call spawn_new_task\n\n.loop_forever:\n mov si, main_str\n call putstring\n call yield\n jmp .loop_forever\n\ntask_a:\n mov si, main_a\n call putstring\n call yield\n jmp task_a\n\ntask_b:\n mov si, main_b\n call putstring\n call yield\n jmp task_b\n\nspawn_new_task: ; find a free task slot\n xor cx, cx\n mov bx, stack_status\n.loop:\n inc bx\n inc cx\n cmp [bx], ch ; CH=0\n je .done ; if equal, task slot is free\n cmp cx, 2 ; change this to add more 'spawnable' tasks\n jb .loop\n ret ; no free task, return immediately\n.done:\n inc byte [bx] ; task was free, reserve it\n mov bx, stack_pointers\n mov [bx], sp ; save main's stack pointer\n add bx, cx ; switch to free stack\n add bx, cx ; free stack is list of words (not bytes) and add is cheaper than mul\n mov sp, [bx] ; change to free stack\n push si ; push stuff\n pusha\n pushf\n mov [bx], sp ; save new stack's new pointer\n mov sp, [stack_pointers] ; change back to main\n ret\n\nyield:\n ; ret already saved by call\n pusha\n pushf\n movzx cx, byte [current_task]\n ; save current stack pointer\n mov bx, stack_pointers\n add bx, cx\n add bx, cx\n mov [bx], sp\n ; loop through stack status looking for a 1\n mov bx, stack_status\n add bx, cx ; make sure we start looking at next task\n.loop:\n inc bx\n inc cx\n cmp cx, 3 ; increment this for more tasks\n jb .continue\n xor cx, cx ; clear cx\n mov bx, stack_status ; reset bx back to start\n.continue:\n cmp byte [bx], 1 ; is this stack active\n jne .loop\n mov [current_task], cl\n ; switch to new stack\n mov bx, stack_pointers\n add bx, cx\n add bx, cx\n mov sp, [bx]\n popf\n popa\n ret\n\n ; takes an address to write to in si\n ; writes to address until a null term is encountered\n ; returns nothing\nputstring:\n mov bh, 0\n mov ah, 0Eh\n jmp .first\n.next:\n int 10h ; call interrupt\n.first:\n lodsb ; put char to write in al\n test al, al ; simulate and\n jnz .next ; was al 0?\n ret\n\n main_str: db \"I am task main\", 13, 10, 0\n main_a: db \"I am task a\", 13, 10, 0\n main_b: db \"I am task b\", 13, 10, 0\n\n current_task: db 0\n\n stack_status:\n status_1: db 1 ; this is for Main\n status_2: db 0\n status_3: db 0\n\n stack_pointers:\n dw 0 ; this is for Main\n dw stacks + 256\n dw stacks + 512\n\n stacks:\n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-07T15:36:20.127",
"Id": "456685",
"Score": "0",
"body": "The Intel 8088, which is DOSBox's default processor, would only have a single core. How can it be multithreading if there's only one core? Would the \"tasks\" be able to technically qualify as \"threads?\" (Ty for the rest; I'm still learning a lot about NASM)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-13T15:15:07.197",
"Id": "457541",
"Score": "0",
"body": "@T145 Multithreading is not associated with the number of cores. See its definition : \"...multithreading is the ability of a central processing unit (CPU) (or **a single core** in a multi-core processor) to provide multiple threads of execution concurrently...\" Multithreading is also not associated with any hardware. It's the software that makes it work. Of course if the hardware offers supporting features they are very welcome."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-07T11:03:05.170",
"Id": "233582",
"ParentId": "233371",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "233582",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-03T21:53:27.347",
"Id": "233371",
"Score": "6",
"Tags": [
"windows",
"assembly",
"nasm"
],
"Title": "Multitasking in NASM Win16 Assembly"
}
|
233371
|
<p>I am trying to create a very basic class: <code>Line</code> as follows:</p>
<pre class="lang-py prettyprint-override"><code>class Line:
def __init__(self, x1, y1, x2=None, y2=None, dx=None, dy=None):
self._x1 = x1
self._y1 = y1
if dx is None:
if x2 is None:
raise ValueError("You must specify either x2 or dx. both argument are not passed")
else:
self._x2 = x2
self._dx = dx
else:
if x2 is None:
self._x2 = self._x1 + dx
self._dx = dx
else:
raise ValueError("Both x2 and dx are passed. You must supply only one of them")
if dy is None:
if y2 is None:
raise ValueError("You must specify either y2 or dy. both argument are not passed")
else:
self._y2 = y2
self._dy = dy
else:
if y2 is None:
self._y2 = self._y1 + dy
self._dy = dy
else:
raise ValueError("Both y2 and dy are passed. You must supply only one of them")
def x1(self):
return self._x1
def x2(self):
return self._x2
def y1(self):
return self._y1
def y2(self):
return self._y2
def dx(self):
return self._dx
def dy(self):
return self._dy
</code></pre>
<p><code>x1</code> and <code>y1</code> arguments are mandatory. But I want:</p>
<ul>
<li>Only <code>x2</code> or <code>dx</code> is passed not both.</li>
<li>Only <code>y2</code> or <code>dy</code> is passed not both.</li>
</ul>
<p>In the code above I feel that I am repeating my self. How can I achieve that with minimum conditons?</p>
<p>I appreciate your help </p>
|
[] |
[
{
"body": "<p>I noticed with <code>dx</code> and <code>dy</code>, you're assigning them to <code>self.dx</code> and <code>self.dy</code> regardless of what they are. Those assignments can be moved up with <code>x1</code> and <code>x2</code> which thins out the checks a bit.</p>\n\n<p>Unless you really want all four combinations to happen using the same function though, I'd probably break this down into some \"pseudo-constructors\" that defer to the main constructor. Instead of allowing all possible combinations of data then error checking after, I'd just try to limit up front what options are available. There are four possible input combinations: <code>dx, dy</code>, <code>dx, y2</code>, <code>x2, y2</code>, and <code>x2, dy</code>. You could have four static methods that explicitly request a certain combination, and construct a line accordingly.</p>\n\n<p>In the below code, I also decided to use a <a href=\"https://docs.python.org/3/library/collections.html#collections.namedtuple\" rel=\"nofollow noreferrer\"><code>NamedTuple</code></a> here. They're basically a shortcut way of creating an immutable class, complete with a generated constructor, a <code>__repr__</code> implementation and some other nice features. See the comments doc page and the comments.</p>\n\n<p>Now, I'll admit that this code that I ended up with isn't quite as nice as what I originally saw in my head. I think it is still quite an improvement though in terms of readability:</p>\n\n<pre><code>from typing import NamedTuple, Optional\n\n# NamedTuple automatically creates a constructor that handles all the annoying self._x2 = x2 lines\n# It also makes Line immutable. This gets rid of the need for the getters you have\nclass Line(NamedTuple):\n x1: int # \"Declare\" the fields that the tuple will have\n y1: int\n\n x2: int \n y2: int\n\n dx: Optional[int] = None # With defaults of None for some\n dy: Optional[int] = None\n\n # staticmethod essentially gets rid of the `self` parameter and makes the method \n # intended to be called on the class itself instead of on an instance.\n @staticmethod\n def from_dx_dy(x1, y1, dx, dy):\n return Line(x1, y1, dx=dx, dy=dy, x2=x1 + dx, y2=y1 + dy)\n\n @staticmethod\n def from_dx_y2(x1, y1, dx, y2):\n return Line(x1, y1, dx=dx, y2=y2, x2=x1 + dx)\n\n @staticmethod\n def from_x2_dy(x1, y1, x2, dy):\n return Line(x1, y1, x2=x2, dy=dy, y2=y1 + dy)\n\n @staticmethod\n def from_x2_y2(x1, y1, x2, y2):\n return Line(x1, y1, x2=x2, y2=y2)\n</code></pre>\n\n<p>Then, as an example:</p>\n\n<pre><code>>>> Line.from_dx_dy(1, 2, 3, 4)\nLine(x1=1, y1=2, x2=4, y2=6, dx=3, dy=4)\n\n>>> Line.from_x2_dy(1, 2, 3, 4)\nLine(x1=1, y1=2, x2=3, y2=6, dx=None, dy=4)\n</code></pre>\n\n<p>It still has an unfortunate amount of duplication, but I think it's easier to make sense of.</p>\n\n<hr>\n\n<hr>\n\n<p>As mentioned in the comments, since I'm referring to the class itself in the static methods, they should arguably be <code>classmethod</code>s instead:</p>\n\n<pre><code>@classmethod\ndef from_dx_dy(cls, x1, y1, dx, dy):\n return cls(x1, y1, dx=dx, dy=dy, x2=x1 + dx, y2=y1 + dy)\n\n@classmethod\ndef from_dx_y2(cls, x1, y1, dx, y2):\n return cls(x1, y1, dx=dx, y2=y2, x2=x1 + dx)\n\n@classmethod\ndef from_x2_dy(cls, x1, y1, x2, dy):\n return cls(x1, y1, x2=x2, dy=dy, y2=y1 + dy)\n\n@classmethod\ndef from_x2_y2(cls, x1, y1, x2, y2):\n return cls(x1, y1, x2=x2, y2=y2)\n</code></pre>\n\n<p>Where <code>cls</code> is referring to the current class (<code>Line</code>). I don't like the look of this as much, but it is the intent of class methods.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T01:18:35.030",
"Id": "233380",
"ParentId": "233375",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "233380",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T00:06:33.667",
"Id": "233375",
"Score": "5",
"Tags": [
"python",
"object-oriented",
"overloading"
],
"Title": "Overloading python class constructor"
}
|
233375
|
<p><a href="https://repl.it/repls/PlushFluidRecursio" rel="nofollow noreferrer">Code</a></p>
<p><a href="https://leetcode.com/problems/search-a-2d-matrix-ii/" rel="nofollow noreferrer">Problem</a></p>
<pre><code>class Solution:
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if len(matrix) == 0 or len(matrix[0]) == 0:
return False
height = len(matrix)
width = len(matrix[0])
row = height - 1
col = 0
while col < width and row >= 0:
if matrix[row][col] > target:
row -= 1
elif matrix[row][col] < target:
col += 1
else:
return True
return False
</code></pre>
<p>Any improvements you could make to this? Runtime is O(Len(row) + len(col)), space is constant.</p>
<p>I looked at other solutions and a lot of them used binary search, but that is O(len(col) * log(len(row)) so I don't think that's an improvement.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T01:59:24.270",
"Id": "456162",
"Score": "0",
"body": "`O(n) > O(log(n))`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T02:49:17.773",
"Id": "456165",
"Score": "0",
"body": "@alexyorke but `O(n + k) < O(n log k)` for the most part."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T03:12:43.043",
"Id": "456167",
"Score": "0",
"body": "@Quintec ah, that is correct"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T07:31:59.413",
"Id": "456192",
"Score": "2",
"body": "You could use a binary search for both the rows and columns. I guess it would be `O(log(n) + log(m))` or `log(n + m)`"
}
] |
[
{
"body": "<p>Unfortunately, using binary search both for rows and columns is not possible here. It fails if the last element of the first row is too small, i.e. for this input:</p>\n\n<pre><code>matrix = [[ 0, 1, 2, 3, 4, 5],\n [ 6, 7, 8, 9, 10, 11],\n [12, 13, 14, 15, 16, 17],\n [18, 19, 20, 21, 22, 23],\n [24, 25, 26, 27, 28, 29]]\ntarget = 10\n</code></pre>\n\n<p>However, you could use binary search within each row for <span class=\"math-container\">\\$\\mathcal{O}(n\\log m)\\$</span> runtime, compared to your <span class=\"math-container\">\\$\\mathcal{O}(n + m)\\$</span> runtime, as you noted in the question. While this is nominally worse, for the actual testcases being tested by Leetcode it performs better.</p>\n\n<pre><code>from bisect import bisect_left\n\nclass Solution:\n def searchMatrix(self, matrix, target):\n \"\"\"\n :type matrix: List[List[int]]\n :type target: int\n :rtype: bool\n \"\"\"\n if not matrix or not matrix[0]:\n return False\n for row in matrix:\n i = bisect_left(row, target)\n if i < len(row) and row[i] == target:\n return True\n return False\n</code></pre>\n\n<p>Your code: 36ms, faster than 85.35%</p>\n\n<p>Binary search: 28 ms, faster than 98.39%</p>\n\n<p>This is probably due to the testcases being small enough (and if <span class=\"math-container\">\\$m = n\\$</span>, <span class=\"math-container\">\\$2n > n\\log_b n\\$</span> for <span class=\"math-container\">\\$n < b^2\\$</span>).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T13:33:09.267",
"Id": "233411",
"ParentId": "233381",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T01:50:39.043",
"Id": "233381",
"Score": "3",
"Tags": [
"python",
"programming-challenge",
"matrix",
"complexity"
],
"Title": "Using Python to search a sorted 2D Matrix"
}
|
233381
|
<p><a href="https://adventofcode.com/2019/day/3" rel="nofollow noreferrer">Advent of Code, Day 3 Problem Definitions</a></p>
<pre><code>input1 = 'R995,U982,R941,U681,L40,D390,R223,U84,L549,U568,R693,D410,R779,U33,L54,D18,L201,U616,R583,D502,R307,U46,L726,D355,L62,D973,R134,U619,L952,U669,L28,U729,L622,D821,R814,D149,L713,U380,R720,U438,L112,U587,R161,U789,R959,U254,R51,U648,R259,U555,R863,U610,L33,D97,L825,D489,R836,D626,L849,D262,L380,U831,R650,U832,R339,D538,L49,D808,L873,D33,L405,D655,R884,D630,R589,D291,L675,D210,L211,D325,L934,D515,R896,U97,L639,U654,L301,U507,L642,D416,L325,U696,L3,U999,R88,D376,L187,U107,R394,U273,R117,D872,R162,D496,L599,D855,L961,U830,L156,U999,L896,D380,L476,U100,R848,U547,L266,D490,L87,D376,L428,U265,R645,U584,L623,D658,L103,U946,R162,U678,R532,D761,L141,D48,L487,D246,L85,D680,R859,D345,L499,D194,L815,D742,R700,D141,L482,D442,L943,D110,L892,D486,L581,U733,L109,D807,L474,U866,R537,U217,R237,U915,R523,D394,L509,U333,R734,U511,R482,D921,R658,U860,R112,U527,L175,D619,R140,D402,L254,D956,L556,U447,L518,U60,L306,U88,R311,U654,L551,D38,R750,U835,L784,U648,L374,U211,L635,U429,R129,U849,R411,D135,L980,U40,R480,D91,R881,D292,R474,D956,L89,D640,L997,D397,L145,D126,R936,U135,L167,U289,R560,D745,L699,U978,L459,D947,L782,U427,L784,D561,R985,D395,L358,D928,R697,U561,L432,U790,R112,D474,R852,U862,R721,D337,L355,U598,L94,D951,L903,D175,R981,D444,L690,D729,L537,D458,R883,U152,R125,D363,L90,U260,R410,D858,L825,U185,R502,D648,R793,D600,L589,U931,L772,D498,L871,U326,L587,D789,L934,D889,R621,U689,R454,U475,L166,U85,R749,D253,R234,D96,R367,D33,R831,D783,R577,U402,R482,D741,R737,D474,L666'
input2 = 'L996,D167,R633,D49,L319,D985,L504,U273,L330,U904,R741,U886,L719,D73,L570,U982,R121,U878,R36,U1,R459,D368,R229,D219,R191,U731,R493,U529,R53,D613,R690,U856,L470,D722,R464,D378,L187,U540,R990,U942,R574,D991,R29,D973,R905,D63,R745,D444,L546,U939,L848,U860,R877,D181,L392,D798,R564,D189,R14,U120,R118,D350,R798,U462,R335,D497,R916,D722,R398,U91,L284,U660,R759,U676,L270,U69,L774,D850,R440,D669,L994,U187,R698,U864,R362,U523,L128,U89,R272,D40,L134,U571,L594,D737,L830,D956,L213,D97,R833,U454,R319,U809,L506,D792,R746,U283,R858,D743,R107,U499,R102,D71,R822,U9,L547,D915,L717,D783,L53,U871,R920,U284,R378,U312,R970,D316,R243,D512,R439,U530,R246,D824,R294,D726,R541,D250,R859,D134,R893,U631,L288,D151,L796,D759,R17,D656,L562,U136,R861,U42,L66,U552,R240,D121,L966,U288,L810,D104,R332,U667,L63,D463,R527,D27,R238,D401,L397,D888,R168,U808,L976,D462,R299,U385,L183,U303,L121,U385,R260,U80,R420,D532,R725,U500,L376,U852,R98,D597,L10,D441,L510,D592,L652,D230,L290,U41,R521,U726,R444,U440,L192,D255,R690,U141,R21,U942,L31,U894,L994,U472,L460,D357,R150,D721,R125,D929,R473,U707,R670,D118,R255,U287,R290,D374,R223,U489,R533,U49,L833,D805,L549,D291,R288,D664,R639,U866,R205,D746,L832,U864,L774,U610,R186,D56,R517,U294,L935,D304,L581,U899,R749,U741,R569,U282,R460,D925,L431,D168,R506,D949,L39,D472,R379,D125,R243,U335,L310,D762,R412,U426,L584,D981,L971,U575,L129,U885,L946,D221,L779,U902,R251,U75,L729,D956,L211,D130,R7,U664,L915,D928,L613,U740,R572,U733,R277,U7,R953,D962,L635,U641,L199'
# Toggle part1/part2 (we'll pretend this is a good approach...)
part_one = False
def move_steps(points, move, x, y, direction, steps):
for _ in range(move):
x += direction[0]
y += direction[1]
steps +=1
# Store the number of steps to this point only if we haven't
# been here - we want the smallest number of steps stored
# for comparison purposes
if not (x,y) in points:
points[(x,y)] = steps
return x, y, steps
def get_points(raw_points):
# Build list of all points the command traverses
input_points = raw_points.split(',')
points = {}
x = 0
y = 0
steps = 0
for p in input_points:
move = int(p[1:])
if p[0] == 'R':
x, y, steps = move_steps(points, move, x, y, (1,0), steps)
if p[0] == 'L':
x, y, steps = move_steps(points, move, x, y, (-1,0), steps)
if p[0] == 'U':
x, y, steps = move_steps(points, move, x, y, (0,1), steps)
if p[0] == 'D':
x, y, steps = move_steps(points, move, x, y, (0,-1), steps)
return points
points_one = get_points(input1)
points_two = get_points(input2)
shortest_length = 9999999999999
# Check which points match and keep track of the shortest length between them
points = points_one.keys()
for p in points:
if p in points_two.keys():
if part_one:
length = abs(p[0]) + abs(p[1])
else:
length = points_one[p] + points_two[p]
if length < shortest_length:
shortest_length = length
print(shortest_length)
</code></pre>
<p>I'm not a huge fan of how this turned out. </p>
<p>I have a few ideas for ways to make it better but I am curious what sticks out first.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T06:56:42.980",
"Id": "456189",
"Score": "1",
"body": "In the future could you tag all Python questions with the [tag:python] tag as well as the sub-version. This allows better visibility to your question as some people only watch the [tag:python] tag. Further more, since links can rot. [Please include a description of the challenge here in your question.](//codereview.meta.stackexchange.com/q/1993) Thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T08:17:41.683",
"Id": "456195",
"Score": "1",
"body": "The current question title isn't useful without the external resource. Please [edit] to summarize the requirement in your own words. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T09:14:38.867",
"Id": "456199",
"Score": "0",
"body": "@TobySpeight Your comment is confusing. Do you think there's a problem with the title or not?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T09:17:52.710",
"Id": "456200",
"Score": "0",
"body": "@Peilonrayz Yes, of course there's a problem with the title. It's absolutely meaningless to anyone not familiar with the Advent of Code resource."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T09:20:41.863",
"Id": "456202",
"Score": "2",
"body": "@TobySpeight The status quo of the site is that [titles](https://codereview.stackexchange.com/search?q=Project+Euler) [like](https://codereview.stackexchange.com/search?q=Hackerrank) [this](https://codereview.stackexchange.com/search?q=Advent+of+code) are fine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-08T22:37:24.310",
"Id": "456783",
"Score": "0",
"body": "What do you mean by \"Part 3\"? Advent of Code problems are divided into two parts, not three. Do you have posted previous questions that are related?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-08T22:56:37.400",
"Id": "456786",
"Score": "0",
"body": "Please add some description of the problem to the question itself, so that we're not dependent on the third party site to know *what the question is about*. (This makes the question put on-hold, not the title)"
}
] |
[
{
"body": "<h3><em>Towards better manageability and flexibility</em></h3>\n\n<ul>\n<li><p><strong><code>get_points</code></strong> function</p>\n\n<p>Name of side <code>p[0]</code> and move range <code>int(p[1:])</code> are better unpacked and named once:</p>\n\n<pre><code>side_name, move_range = p[0], int(p[1:])\n</code></pre>\n\n<p>All those <code>if</code> conditions should be mutually exclusive <code>if .. elif .. elif ...</code>.<br>But instead, a better and more flexible way would be to declare <em>\"directions\"</em> map at once:</p>\n\n<pre><code>DIRECTIONS_MAP = {'R': (1, 0), 'L': (-1, 0), 'U': (0, 1), 'D': (0, -1)}\n</code></pre>\n\n<p>then, there would only one condition for containment check.</p>\n\n<p>The final optimized function:</p>\n\n<pre><code>def get_points(raw_points):\n # Build list of all points the command traverses\n input_points = raw_points.split(',')\n points = {}\n x = y = steps = 0\n for p in input_points:\n side_name, move_range = p[0], int(p[1:])\n if side_name in DIRECTIONS_MAP:\n x, y, steps = move_steps(points, move_range, x, y, DIRECTIONS_MAP[side_name], steps)\n\n return points\n</code></pre></li>\n<li><p><em>finding shortest distance between points</em></p>\n\n<p>Instead of constant check for matched points with:</p>\n\n<pre><code>points = points_one.keys()\nfor p in points:\n if p in points_two.keys():\n ...\n</code></pre>\n\n<p>a more flexible way is to get <em>intersection</em> between dictionaries key views at once:</p>\n\n<pre><code>for p in points_one.keys() & points_two.keys():\n</code></pre>\n\n<p>The whole block of statements is extracted into separate function <strong><code>find_shortest_distance</code></strong> with explicit responsibility and default arguments:</p>\n\n<pre><code>def find_shortest_distance(input1, input2, shortest_length=9999999999999, part_one=False):\n points_one = get_points(input1)\n points_two = get_points(input2)\n\n # Check which points match and keep track of the shortest length between them\n for p in points_one.keys() & points_two.keys():\n if part_one:\n length = abs(p[0]) + abs(p[1])\n else:\n length = points_one[p] + points_two[p]\n if length < shortest_length:\n shortest_length = length\n return shortest_length\n</code></pre></li>\n</ul>\n\n<hr>\n\n<p>Sample usage:</p>\n\n<pre><code>input1 = 'R995,U982,R941,U681,L40,D390,R223,U84,L549,U568,R693,D410,R779,U33,L54,D18,L201,U616,R583,D502,R307,U46,L726,D355,L62,D973,R134,U619,L952,U669,L28,U729,L622,D821,R814,D149,L713,U380,R720,U438,L112,U587,R161,U789,R959,U254,R51,U648,R259,U555,R863,U610,L33,D97,L825,D489,R836,D626,L849,D262,L380,U831,R650,U832,R339,D538,L49,D808,L873,D33,L405,D655,R884,D630,R589,D291,L675,D210,L211,D325,L934,D515,R896,U97,L639,U654,L301,U507,L642,D416,L325,U696,L3,U999,R88,D376,L187,U107,R394,U273,R117,D872,R162,D496,L599,D855,L961,U830,L156,U999,L896,D380,L476,U100,R848,U547,L266,D490,L87,D376,L428,U265,R645,U584,L623,D658,L103,U946,R162,U678,R532,D761,L141,D48,L487,D246,L85,D680,R859,D345,L499,D194,L815,D742,R700,D141,L482,D442,L943,D110,L892,D486,L581,U733,L109,D807,L474,U866,R537,U217,R237,U915,R523,D394,L509,U333,R734,U511,R482,D921,R658,U860,R112,U527,L175,D619,R140,D402,L254,D956,L556,U447,L518,U60,L306,U88,R311,U654,L551,D38,R750,U835,L784,U648,L374,U211,L635,U429,R129,U849,R411,D135,L980,U40,R480,D91,R881,D292,R474,D956,L89,D640,L997,D397,L145,D126,R936,U135,L167,U289,R560,D745,L699,U978,L459,D947,L782,U427,L784,D561,R985,D395,L358,D928,R697,U561,L432,U790,R112,D474,R852,U862,R721,D337,L355,U598,L94,D951,L903,D175,R981,D444,L690,D729,L537,D458,R883,U152,R125,D363,L90,U260,R410,D858,L825,U185,R502,D648,R793,D600,L589,U931,L772,D498,L871,U326,L587,D789,L934,D889,R621,U689,R454,U475,L166,U85,R749,D253,R234,D96,R367,D33,R831,D783,R577,U402,R482,D741,R737,D474,L666'\ninput2 = 'L996,D167,R633,D49,L319,D985,L504,U273,L330,U904,R741,U886,L719,D73,L570,U982,R121,U878,R36,U1,R459,D368,R229,D219,R191,U731,R493,U529,R53,D613,R690,U856,L470,D722,R464,D378,L187,U540,R990,U942,R574,D991,R29,D973,R905,D63,R745,D444,L546,U939,L848,U860,R877,D181,L392,D798,R564,D189,R14,U120,R118,D350,R798,U462,R335,D497,R916,D722,R398,U91,L284,U660,R759,U676,L270,U69,L774,D850,R440,D669,L994,U187,R698,U864,R362,U523,L128,U89,R272,D40,L134,U571,L594,D737,L830,D956,L213,D97,R833,U454,R319,U809,L506,D792,R746,U283,R858,D743,R107,U499,R102,D71,R822,U9,L547,D915,L717,D783,L53,U871,R920,U284,R378,U312,R970,D316,R243,D512,R439,U530,R246,D824,R294,D726,R541,D250,R859,D134,R893,U631,L288,D151,L796,D759,R17,D656,L562,U136,R861,U42,L66,U552,R240,D121,L966,U288,L810,D104,R332,U667,L63,D463,R527,D27,R238,D401,L397,D888,R168,U808,L976,D462,R299,U385,L183,U303,L121,U385,R260,U80,R420,D532,R725,U500,L376,U852,R98,D597,L10,D441,L510,D592,L652,D230,L290,U41,R521,U726,R444,U440,L192,D255,R690,U141,R21,U942,L31,U894,L994,U472,L460,D357,R150,D721,R125,D929,R473,U707,R670,D118,R255,U287,R290,D374,R223,U489,R533,U49,L833,D805,L549,D291,R288,D664,R639,U866,R205,D746,L832,U864,L774,U610,R186,D56,R517,U294,L935,D304,L581,U899,R749,U741,R569,U282,R460,D925,L431,D168,R506,D949,L39,D472,R379,D125,R243,U335,L310,D762,R412,U426,L584,D981,L971,U575,L129,U885,L946,D221,L779,U902,R251,U75,L729,D956,L211,D130,R7,U664,L915,D928,L613,U740,R572,U733,R277,U7,R953,D962,L635,U641,L199'\n\nprint(find_shortest_distance(input1, input2)) # 32132\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T06:36:32.890",
"Id": "233390",
"ParentId": "233383",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T03:57:02.720",
"Id": "233383",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"programming-challenge"
],
"Title": "Advent of Code 2019 Day 3, Part 3"
}
|
233383
|
<p>The goal of the function is to find out how to get from one angle to another angle. Two things are involved: the amount to move by and the direction (+ means turn right, - means turn left). The most the angle will have to move by is 180deg. The function is rather short. I wanted to avoid using and trig functions or pi. I want this as fast as I can while maintaining readability.</p>
<pre><code>import pandas as pd
import numpy as np
def get_wind_dir_difd(dir_1, dir_2):
"""
Figures out the shortest way to get from dir_1 to dir_2. Positive nunber go clockwise, negative numbers go counter clockwise.
NOTE: The direction 0 and 360 are the same.
:param dir_1: int. The direction of the first wind.
:param dir_2: The direction of the second wind.
:return: int. The what to add (can be a negative number too) to the first wind dir to get to the second wind dir.
"""
diff = dir_2 - dir_1
if diff > 180: # the highest diff can be is 180
diff = 360 - diff
elif diff < -180: # the lowest diff can be is -180
diff = 360 + diff
if dir_2 > dir_1 and (dir_2 - dir_1 > 180): # ensures the correct sign is used when dir_2 is larger and the difference betwene the two is more than 180, EX 10, 310 or 40, 360
diff = -diff
return diff
# IGNORE WHAT IS BELOW, THAT IS JUST TO TEST
get_wind_dir_dif_vec = np.vectorize(get_wind_dir_difd)
df = pd.read_csv('test.csv')
df['diff'] = get_wind_dir_dif_vec(df['val1'], df['val2'])
for i in range(len(df)):
row = df.iloc[i]
correct_or_not = row['diff'] == row['what_diff_should_be']
if correct_or_not:
correct_or_not = ''
else:
correct_or_not = 'X'
df.set_value(i, ' bad_answer ', correct_or_not)
print(df)
</code></pre>
<hr>
<p>To give you a better idea of the program</p>
<pre><code> val1 val2 diff what_diff_should_be bad_answer
0 120 30 -90 -90
1 340 20 40 40
2 20 340 -40 -40
3 310 10 60 60
4 10 310 -60 -60
5 0 300 -60 -60
6 300 0 60 60
7 190 180 -10 -10
8 180 190 10 10
9 200 220 20 20
10 220 200 -20 -20
11 10 190 180 180
12 360 0 0 0
13 0 360 0 0
14 340 20 40 40
15 350 0 10 10
16 350 360 10 10
17 40 360 -40 -40
18 180 0 -180 -180
19 0 180 180 180
</code></pre>
<hr>
<p>This is the csv I tested it on.</p>
<pre><code>val1,val2,diff,what_diff_should_be
120,30,,-90
340,20,,40
20,340,,-40
310,10,,60
10,310,,-60
0,300,,-60
300,0,,60
190,180,,-10
180,190,,10
200,220,,20
220,200,,-20
10,190,,180
360,0,,0
0,360,,0
340,20,,40
350,0,,10
350,360,,10
40,360,,-40
180,0,,-180
0,180,,180
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T04:20:33.643",
"Id": "456168",
"Score": "0",
"body": "What about `abs(dir_1 - dir_2) * ((dir_2 > dir_1) - (dir_1 > dir_2))`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T04:23:44.113",
"Id": "456169",
"Score": "0",
"body": "@alexyorke won't that always return a positive value? Some of the output will be negative."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T04:26:13.897",
"Id": "456170",
"Score": "0",
"body": "it returns negative values (I tried it with a few examples in your answer.) The `((dir_2 > dir_1) - (dir_1 > dir_2))` is a convoluted way to get the sign of the number; if it's positive it will be 1, negative it will be -1 (and thus multiply the answer by that.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T04:39:16.413",
"Id": "456172",
"Score": "3",
"body": "`return (dir_2 - dir_1 + 180) % 360 - 180` That works in all example cases except the last, where it returns -180 instead of 180, which is arguably equivalent."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T04:43:05.013",
"Id": "456173",
"Score": "0",
"body": "@AJNeufeld While it is arguably equivalent, it is not the answer I want. I will use this function to later interpolate and for that the sign matter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T04:43:39.123",
"Id": "456174",
"Score": "0",
"body": "@alexyorke I get a numpy error with your function `TypeError: numpy boolean subtract, the `-` operator, is deprecated, use the bitwise_xor, the `^` operator, or the logical_xor function instead.`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T04:45:58.113",
"Id": "456175",
"Score": "0",
"body": "@Vader my answer doesn't require numpy! https://repl.it/repls/WiseDisloyalSearch"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T04:48:07.217",
"Id": "456176",
"Score": "0",
"body": "How are you subtracting booleans from each other? I knwo you said earlier it is used to get the sign of a number. But is there way to rewrite where it will work in my example?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T04:51:24.383",
"Id": "456177",
"Score": "0",
"body": "@Vader I just noticed that it doesn't work for `340` and `20`; I will have to try another solution"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T09:35:28.513",
"Id": "456204",
"Score": "0",
"body": "What determines whether +180 or -180 should be output? The test cases have both results, but no indication of when to choose each."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T13:09:46.700",
"Id": "456226",
"Score": "0",
"body": "Are both directions guaranteed to be in the range 0 to 360?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T14:41:01.887",
"Id": "456241",
"Score": "0",
"body": "@Edward yes, lowest input can eb is 0, highest is 360."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T14:43:08.827",
"Id": "456242",
"Score": "0",
"body": "@TobySpeight Later I will use this function to interpolate missing data. So, if dir_1 is lower than dir_2 like it is with `(0, 180)` then the answer should be positive because 90 (90 b/c +180/2) would be the middle value and not -90. Hope that helps."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T15:39:38.707",
"Id": "456252",
"Score": "1",
"body": "I'm not sure how that helps with interpolation; regardless, you should [edit] that requirement so it's part of the question (comments can be easily lost)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T18:22:37.043",
"Id": "456276",
"Score": "0",
"body": "@AJNeufeld `return 180 - (dir1 - dir2 + 180) % 360` would fix the one corner case, while also working for all the other cases."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T08:53:56.523",
"Id": "456370",
"Score": "0",
"body": "@AJNeufeld: That's the only needed formula. Everything else is wrong or needlessly complex."
}
] |
[
{
"body": "<h3><em>Consolidation and unified conditionals</em></h3>\n\n<ul>\n<li><p>the primary difference <code>dir_2 - dir_1</code> occurs twice in the initial approach: once at the 1st assignment and another time - in the last <code>if</code> condition. <br>Thus, <em>Extract variable</em> technique can be applied to avoid repetition:</p>\n\n<pre><code>prime_diff = final_diff = dir_2 - dir_1\n</code></pre>\n\n<p>where <code>prime_diff</code> is the primary/initial difference and the <code>final_diff</code> is <em>derivative</em> final difference that may or may not be modified due to further conditions</p></li>\n<li><p>the 1st condition <code>if diff > 180</code> and last sub-check <code>(dir_2 - dir_1 > 180)</code> are essentially the same expression, thus, can beforehand be extracted into a variable to avoid repetition:</p>\n\n<pre><code>gt180 = prime_diff > 180 # greater than 180 (gt)\n</code></pre></li>\n<li><p>the crucial <code>if ... elif</code> conditional containing 2 statements can be unified to a single <code>or</code> conditional with 1 consolidated statement:</p>\n\n<pre><code>if gt180 or prime_diff < -180: \n</code></pre></li>\n<li><p>the 1st sub-check <code>dir_2 > dir_1</code> in the last conditional <code>if dir_2 > dir_1 and (dir_2 - dir_1 > 180):</code> is redundant because <code>dir_2 - dir_1 > 180</code> will be <strong><code>True</code></strong> only when <code>dir_2</code> is greater than <code>dir_1</code> in any way.</p></li>\n</ul>\n\n<hr>\n\n<p>The final <strong><code>get_wind_dir_difd</code></strong> function is simplified to the following:</p>\n\n<pre><code>def get_wind_dir_difd(dir_1, dir_2):\n \"\"\"\n Figures out the shortest way to get from dir_1 to dir_2. Positive nunber go clockwise, negative numbers go counter clockwise.\n NOTE: The direction 0 and 360 are the same.\n :param dir_1: int. The direction of the first wind.\n :param dir_2: The direction of the second wind.\n :return: int. The what to add (can be a negative number too) to the first wind dir to get to the second wind dir.\n \"\"\"\n prime_diff = final_diff = dir_2 - dir_1\n gt180 = prime_diff > 180 # greater than 180 (gt)\n\n if gt180 or prime_diff < -180:\n final_diff = 360 - abs(prime_diff)\n if gt180:\n final_diff = -final_diff\n\n return final_diff\n</code></pre>\n\n<hr>\n\n<p>Test results:</p>\n\n<pre><code> val1 val2 diff what_diff_should_be bad_answer \n0 120 30 -90 -90 \n1 340 20 40 40 \n2 20 340 -40 -40 \n3 310 10 60 60 \n4 10 310 -60 -60 \n5 0 300 -60 -60 \n6 300 0 60 60 \n7 190 180 -10 -10 \n8 180 190 10 10 \n9 200 220 20 20 \n10 220 200 -20 -20 \n11 10 190 180 180 \n12 360 0 0 0 \n13 0 360 0 0 \n14 340 20 40 40 \n15 350 0 10 10 \n16 350 360 10 10 \n17 40 360 -40 -40 \n18 180 0 -180 -180 \n19 0 180 180 180 \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T08:52:23.470",
"Id": "456196",
"Score": "3",
"body": "To me this isn't simplified, it's _more_ confusing. Also to some this may read as just an alternate solution. Could you explain what have you changed?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T09:45:45.420",
"Id": "456206",
"Score": "0",
"body": "Thank you for the update. The [curse of knowlege](https://en.wikipedia.org/wiki/Curse_of_knowledge) is that changes that are fairly obvious to you, may not be obvious to others."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T09:47:54.417",
"Id": "456207",
"Score": "0",
"body": "@Peilonrayz, Ok, I've added a detailed explanation, for now that should be easy to understand and follow"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T09:49:41.250",
"Id": "456208",
"Score": "0",
"body": "Yes, it should be. Sorry I think my second remark has caused some confusion here."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T07:37:13.380",
"Id": "233392",
"ParentId": "233384",
"Score": "5"
}
},
{
"body": "<ul>\n<li><p>Since you seem to be targeting Sphinx for your documentation you should either:</p>\n\n<ol>\n<li><p>Specify your parameter types correctly in the docstring.</p>\n\n<blockquote>\n <pre class=\"lang-none prettyprint-override\"><code>:param int dir_1: The direction of the first wind.\n</code></pre>\n</blockquote>\n\n<p>Or</p>\n\n<blockquote>\n <pre class=\"lang-none prettyprint-override\"><code>:param dir_1: The direction of the first wind.\n:type dir_1: int\n</code></pre>\n</blockquote></li>\n<li><p><a href=\"https://stackoverflow.com/a/51312475\">Get Sphinx to do this for you from PEP 484 type hints.</a> (Python 3.5+ notation)</p>\n\n<blockquote>\n<pre><code>def get_wind_dir_difd(dir_1: int, dir_2: int) -> int:\n \"\"\"\n :param dir_1: The direction of the first wind.\n \"\"\"\n</code></pre>\n</blockquote></li>\n</ol></li>\n<li><p>Your docstring is rather hard to read as they just go off forever. Limit the length of them so it's easier to read them when developing.</p></li>\n<li>Take advantage of Sphinx <code>NOTE:</code> should use <code>.. note::</code>.</li>\n<li>Your first two comments are pretty meh. The third should really be before the if so it's easier to read.</li>\n<li>Check your spelling - number, between.</li>\n</ul>\n\n<pre><code>def get_wind_dir_difd(dir_1: int, dir_2: int) -> int:\n \"\"\"\n Figures out the shortest way to get from :code:`dir_1` to :code:`dir_2`.\n Positive number go clockwise, negative numbers go counter clockwise.\n\n .. note::\n\n The direction 0 and 360 are the same.\n\n :param dir_1: Direction of the first wind.\n :param dir_2: Direction of the second wind.\n :return: What to add to :code:`dir_1` to get :code:`dir_2`.\n \"\"\"\n diff = dir_2 - dir_1\n if diff > 180:\n diff = 360 - diff\n elif diff < -180:\n diff = 360 + diff\n\n # Ensures the correct sign is used when dir_2 is larger\n # and the difference between the two is more than 180.\n # EX 10, 310 or 40, 360\n if dir_2 > dir_1 and (dir_2 - dir_1 > 180):\n diff = -diff\n\n return diff\n</code></pre>\n\n<hr>\n\n<ul>\n<li><code>dir_2 > dir_1</code> is always true when <code>dir_2 > dir_1 + 180</code>.</li>\n<li><code>dir_2 > dir_1 and (dir_2 - dir_1 > 180)</code> is the same as <code>diff > 180</code>. So you can easily merge the ifs together.</li>\n</ul>\n\n<pre><code>def get_wind_dir_difd(dir_1: int, dir_2: int) -> int:\n diff = dir_2 - dir_1\n if diff > 180:\n diff -= 360\n elif diff < -180:\n diff += 360\n return diff\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T15:14:06.033",
"Id": "456248",
"Score": "0",
"body": "Looks like my biggest mistake was doing `diff = 360 - diff` instead of `diff -= 360`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T08:28:12.587",
"Id": "233393",
"ParentId": "233384",
"Score": "6"
}
},
{
"body": "<p>The other reviews give some good formatting advice so I'll concentrate solely on the function itself. I would probably write this instead:</p>\n\n<pre><code>def dir_diff(dir1, dir2):\n diff = (dir2 - dir1) % 360\n return diff if diff <= 180 else diff - 360\n</code></pre>\n\n<p>The way Python's <code>%</code> operator works, it assures that we always have a positive number from 0 to 360 for <code>diff</code> in the first line. Then we only need to adjust if the value is greater than 180. Note also that unlike all of the other versions (including the original), this version will also continue to work properly even if we pass in values such as 900, -92 or 725, 9900.</p>\n\n<p>Better yet, use AJNeufeld's comment or twalberg's equivalent:</p>\n\n<pre><code>return 180 - (dir1 - dir2 + 180) % 360\n</code></pre>\n\n<p>In another comment, the OP said:</p>\n\n<blockquote>\n <p>Later I will use this function to interpolate missing data. So, if dir_1 is lower than dir_2 like it is with (0, 180) then the answer should be positive because 90 (90 b/c +180/2) would be the middle value and not -90. Hope that helps.</p>\n</blockquote>\n\n<p>This requirement doesn't make sense to me because interpolation between two diametrically opposite points on a circle can legitimately be interpreted as either midpoint. However, if it's really a requirement, we can combine like so:</p>\n\n<pre><code>def Edward2(dir1, dir2):\n diff = (dir2 - dir1 + 180) % 360 - 180\n return -diff if diff == -180 and dir1 < dir2 else diff\n</code></pre>\n\n<p>If anyone cares, here is the test code I used:</p>\n\n<pre><code>import csv\n\ndef orig(dir_1, dir_2):\n diff = dir_2 - dir_1\n\n if diff > 180:\n diff = 360 - diff\n\n elif diff < -180:\n diff = 360 + diff\n\n if dir_2 > dir_1 and (dir_2 - dir_1 > 180):\n diff = -diff\n\n return diff\n\ndef Edward1(dir1, dir2):\n diff = (dir2 - dir1) % 360\n return diff if diff <= 180 else diff - 360\n\ndef twalberg(dir1, dir2):\n return 180 - (dir1 - dir2 + 180) % 360\n\ndef AJneufeld(dir1, dir2):\n return (dir2 - dir1 + 180) % 360 - 180\n\ndef Edward2(dir1, dir2):\n diff = (dir2 - dir1 + 180) % 360 - 180\n return -diff if diff == -180 and dir1 < dir2 else diff\n\nif __name__==\"__main__\":\n green = \"\\x1b[32m\"\n red = \"\\x1b[91m\"\n white = \"\\x1b[37m\"\n algo = [orig, Edward1, twalberg, AJneufeld, Edward2]\n\n\n def testAll(d1, d2, desired):\n print('{:-6} {:-6} {:-6}'.format(d1, d2, desired), end='')\n for fn in algo:\n calc = fn(int(d1),int(d2))\n color = [green, red][calc != desired]\n print('{}{:>10}{}'.format(color, calc, white), end='')\n print()\n\n print(' dir1 dir2 desired', end='')\n for fn in algo:\n print(f'{fn.__name__:>10}', end='')\n print()\n with open('input.csv') as csvfile:\n rowreader = csv.reader(csvfile)\n for row in rowreader:\n testAll(int(row[0]), int(row[1]), int(row[2]))\n</code></pre>\n\n<p>Here is the test data I used, with the format <code>dir1</code>,<code>dir2</code>,<code>desired</code>.</p>\n\n<h2>input.csv</h2>\n\n<pre><code>120,30,-90\n340,20,40\n20,340,-40\n310,10,60\n10,310,-60\n0,300,-60\n300,0,60\n190,180,-10\n180,190,10\n200,220,20\n220,200,-20\n10,190,180\n360,0,0\n0,360,0\n340,20,40\n350,0,10\n350,360,10\n40,360,-40\n180,0,-180\n0,180,180\n1,181,180\n359,179,-180\n180,0,-180\n181,1,-180\n179,359,180\n90,270,180\n270,90,-180\n-90,-270,-180\n-270,-90,180\n0,360,0\n360,0,0\n180,-180,0\n-180,-180,0\n-180,180,0\n180,180,0\n900,-92,88\n725,9900,175\n725,9905,180\n9905,725,-180\n</code></pre>\n\n<h2>Results</h2>\n\n<p>With the test cases shown, only the <code>Edward2</code> function gets all results correct. I'm using Python 3.7.5.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T18:16:39.770",
"Id": "456273",
"Score": "1",
"body": "or even `return 180 - (dir1 - dir2 + 180) % 360` and skip the extra variable...."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T18:20:35.713",
"Id": "456274",
"Score": "0",
"body": "Yes, and that’s also equivalent to AJNeufeld’s comment which I had overlooked until a moment ago."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T18:45:29.107",
"Id": "456278",
"Score": "0",
"body": "Well, it's _nearly_ equivalent, but it gets the one corner case right that his didn't..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T19:24:11.123",
"Id": "456281",
"Score": "0",
"body": "@twalberg They just get different ones \"wrong\": try 0,180 and 180,0 for instance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T19:53:45.267",
"Id": "456285",
"Score": "0",
"body": "Valid point, but it does at least get all the test cases listed by the OP... When the two directions are 180 apart, either +180 or -180 are valid, I guess..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T21:24:18.633",
"Id": "456300",
"Score": "0",
"body": "@twalberg: I agree on all points. Also, I should specifically note that either your solution or AJNeufeld's is superior to the one I first proposed. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T01:40:38.087",
"Id": "456326",
"Score": "0",
"body": "seems more complicated that @peilonrayz 's answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T01:46:04.683",
"Id": "456327",
"Score": "0",
"body": "@Vader: While it's often useful to see other approaches, ultimately, you should use what makes sense to you as long as you understand the trade-offs and limitations of the various approaches."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T03:05:25.137",
"Id": "456336",
"Score": "0",
"body": "@Edward I agree. I appreciate you include all the other approaches takes, It makes it easy to compare and contrast.I think your `Edwars2` method is good, but it sacrifices readability for brevity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T03:12:48.293",
"Id": "456337",
"Score": "0",
"body": "@Vader I don’t think it sacrifices readability at all, but like beauty, it’s in the eye of the beholder. Use what you like but remain open to alternative approaches and you will write code you can be proud of."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T15:25:57.627",
"Id": "233418",
"ParentId": "233384",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "233393",
"CommentCount": "16",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T04:07:04.333",
"Id": "233384",
"Score": "6",
"Tags": [
"python",
"mathematics"
],
"Title": "Calculate the movement required to get from one angle to another angle on a compass"
}
|
233384
|
<p>I'm trying to "build" a few "spaceships" in my code. I'm feeling it's a good idea to enumerate all the spaceships and use that as a subscript to build and use an array that holds the spaceships' properties. After researching Stack Overflow and other places, I found a solution that works, but I'm feeling it's not very elegant and I'm probably not making good use of the Swift language. I'm also unhappy with having to define the name (string) of the spaceship again (and not using the enum case for that).</p>
<p>Do I miss the obvious cleaner solution? Any suggestions for a better solution?</p>
<pre><code>enum SpaceshipName: Int, CaseIterable {
case Orion
case Vega
case Gemini
}
struct SpaceshipProperties {
var name: String = "TBD"
var fuel: Int = 0
var speed: Int = 0
}
// Initialize the spaceships:
var spaceShips = [SpaceshipProperties]()
for s in SpaceshipName.allCases {
spaceShips.append(SpaceshipProperties())
}
// Now start using the spaceships:
spaceShips[SpaceshipName.Orion.rawValue].name = "Orion"
spaceShips[SpaceshipName.Orion.rawValue].fuel = 100
spaceShips[SpaceshipName.Gemini.rawValue].speed = 2200
// ... and so forth
// Ultimately, I want to iterate through the spaceships in the following manner:
for s in SpaceshipName.allCases {
// Perform calculations with all the spaceships here, for example:
let newSpeed = spaceShips[s.rawValue].speed + 10
spaceShips[s.rawValue].speed = newSpeed
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>Maybe you should create <code>enum</code> with property? Something like this, I don't know if it is what you want but hope it will be helpful.</p>\n\n<pre class=\"lang-swift prettyprint-override\"><code>enum Ship {\n\n case first(ShipPropperties), second(ShipPropperties), third(ShipPropperties)\n\n static let allValues: [Ship] = [first(ShipPropperties()), second(ShipPropperties()), third(ShipPropperties())]\n\n var properties: ShipPropperties {\n switch self {\n case .first(let properties): return properties\n case .second(let properties): return properties\n case .third(let properties): return properties\n }\n }\n\n func changeProperties(to: ShipPropperties) {\n properties.changeProperties(name: to.name, fuel: to.fuel, speed: to.speed)\n }\n\n}\n\nclass ShipPropperties {\n\n var name: String = \"TBD\"\n var fuel: Int = 0\n var speed: Int = 0\n\n func changeProperties(name: String, fuel: Int, speed: Int) {\n self.name = name\n self.fuel = fuel\n self.speed = speed\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-30T13:18:36.973",
"Id": "456178",
"Score": "0",
"body": "thank you. That's a promising idea to print the properties into the enum. With my limited Swift knowledge, however, I fail to see how I would access (read or write) the actual properties. Do I understand correctly that, with the above code, I would be limited to writing all the properties per ship at once?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-02T07:15:44.657",
"Id": "456179",
"Score": "0",
"body": "no, you can set properties using for loop in Ship.allValues"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-29T10:31:43.063",
"Id": "233387",
"ParentId": "233386",
"Score": "1"
}
},
{
"body": "<p>SpaceShipName enum will keep your ships. In swift, enums can have a function in that case that is matchspaces. With using this function you can pass your struct data which is consist of spaceShipProperties like a fuel,speed. I demonstrate to you how to use it, after that, you just need to create an array, then inside of for loop print each of spaceShip's members easily</p>\n\n<pre class=\"lang-swift prettyprint-override\"><code>// for use \n\nSpaceShipName.Orion.matchSpaces() // return spaceShip struct object \n\n\nstruct SpaceshipProperties {\n var name: String = \"TBD\"\n var fuel: Int = 0\n var speed: Int = 0\n}\n\nenum SpaceShipName: String {\n\n case Orion = \"Orion\"\n case Vega = \"Vega\"\n case Gemini = \"Gemini\"\n\n func matchSpaces() -> SpaceShip {\n\n var spaceShip: SpaceShip\n\n switch self {\n\n case .Orion:\n spaceShip = SpaceShipProporties('name', 'yourFuel','200')\n\n case .Vega:\n spaceShip = SpaceShipProporties('name2', 'yourFuel','150')\n\n case .Gemini:\n spaceShip = SpaceShipProporties('names', 'yourFuel','175')\n }\n\n\n return spaceShip\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-29T14:16:28.847",
"Id": "456180",
"Score": "0",
"body": "thank you. If I understand your code correctly, it wouldn't allow me to write the spaceship properties (in the SpaceshipProperties struct), just read them, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-29T17:20:05.533",
"Id": "456181",
"Score": "0",
"body": "yeah just read them. İnside of matchSpaces() function you create SpaceShipProporties struct . After than call it, just you have to add spaceShip object in to array . And Lastly you can print each of spaceShip objects with for loop effectively."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-29T12:27:13.007",
"Id": "233388",
"ParentId": "233386",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-29T10:02:14.537",
"Id": "233386",
"Score": "3",
"Tags": [
"swift"
],
"Title": "Using enum to create, subscript and loop an array of structs in Swift 5.0"
}
|
233386
|
<p>I have recently tried to get a better grip on machine learning from a point of implementation - not statistics. I've read several explanations of an implementation of a Neural Network via pseudocode and this is the result - a Toy Neural Network.
I have used several sources from medium.com and towardsdatascience.com (if all sources need to be listed, I will make an edit.)</p>
<p>I originally created a naive Matrix custom class with O(N^3) matrix multiplication, but removed to instead use ujmp.
I used ujmp.org Matrix class for faster matrix multiplication, but due to my lacking understanding of how to utilise the speed ups, I believe that </p>
<p>This is the final code. Please comment and suggest improvements! Thank you. I will include SGD, backpropagation, feed forward, and mini batch calculation. Backprop is private due to a wrapping method called train.</p>
<p>The class NetworkInput is a wrapper for an attributes and a label DenseMatrix.</p>
<p>All functions here are interfaces for activationfunctions, functions to evaluate the test data and to calculate loss and error.</p>
<p>This is the SGD.</p>
<pre><code>/**
* Provides an implementation of SGD for this neural network.
*
* @param training a Collections object with {@link NetworkInput }objects,
* NetworkInput.getData() is the data, NetworkInput.getLabel()is the label.
* @param test a Collections object with {@link NetworkInput} objects,
* NetworkInput.getData() is the data, NetworkInput.getLabel is the label.
* @param epochs how many iterations are we doing SGD for
* @param batchSize how big is the batch size, typically 32. See https://stats.stackexchange.com/q/326663
*/
public void stochasticGradientDescent(@NotNull List<NetworkInput> training,
@NotNull List<NetworkInput> test,
int epochs,
int batchSize) {
int trDataSize = training.size();
int teDataSize = test.size();
for (int i = 0; i < epochs; i++) {
// Randomize training sample.
Collections.shuffle(training);
System.out.println("Calculating epoch: " + (i + 1) + ".");
// Do backpropagation.
for (int j = 0; j < trDataSize - batchSize; j += batchSize) {
calculateMiniBatch(training.subList(j, j + batchSize));
}
// Feed forward the test data
List<NetworkInput> feedForwardData = this.feedForwardData(test);
// Evaluate prediction with the interface EvaluationFunction.
int correct = this.evaluationFunction.evaluatePrediction(feedForwardData).intValue();
// Calculate loss with the interface ErrorFunction
double loss = errorFunction.calculateCostFunction(feedForwardData);
// Add the plotting data, x, y_1, y_2 to the global
// lists of xValues, correctValues, lossValues.
addPlotData(i, correct, loss);
System.out.println("Loss: " + loss);
System.out.println("Epoch " + (i + 1) + ": " + correct + "/" + teDataSize);
// Lower learning rate each iteration?. Might implement? Don't know how to.
// ADAM? Is that here? Are they different algorithms all together?
// TODO: Implement Adam, RMSProp, Momentum?
// this.learningRate = i % 10 == 0 ? this.learningRate / 4 : this.learningRate;
}
}
</code></pre>
<p>Here we calculate the mini batches and update our weights with an average.</p>
<pre><code>private void calculateMiniBatch(List<NetworkInput> subList) {
int size = subList.size();
double scaleFactor = this.learningRate / size;
DenseMatrix[] dB = new DenseMatrix[this.totalLayers - 1];
DenseMatrix[] dW = new DenseMatrix[this.totalLayers - 1];
for (int i = 0; i < this.totalLayers - 1; i++) {
DenseMatrix bias = getBias(i);
DenseMatrix weight = getWeight(i);
dB[i] = Matrix.Factory.zeros(bias.getRowCount(), bias.getColumnCount());
dW[i] = Matrix.Factory
.zeros(weight.getRowCount(), weight.getColumnCount());
}
for (NetworkInput data : subList) {
DenseMatrix dataIn = data.getData();
DenseMatrix label = data.getLabel();
List<DenseMatrix[]> deltas = backPropagate(dataIn, label);
DenseMatrix[] deltaB = deltas.get(0);
DenseMatrix[] deltaW = deltas.get(1);
for (int j = 0; j < this.totalLayers - 1; j++) {
dB[j] = (DenseMatrix) dB[j].plus(deltaB[j]);
dW[j] = (DenseMatrix) dW[j].plus(deltaW[j]);
}
}
for (int i = 0; i < this.totalLayers - 1; i++) {
DenseMatrix cW = getWeight(i);
DenseMatrix cB = getBias(i);
DenseMatrix scaledDeltaB = (DenseMatrix) dB[i].times(scaleFactor);
DenseMatrix scaledDeltaW = (DenseMatrix) dW[i].times(scaleFactor);
DenseMatrix nW = (DenseMatrix) cW.minus(scaledDeltaW);
DenseMatrix nB = (DenseMatrix) cB.minus(scaledDeltaB);
setWeight(i, nW);
setLayerBias(i, nB);
}
}
</code></pre>
<p>This is the back propagation algorithm.</p>
<pre><code>private List<DenseMatrix[]> backPropagate(DenseMatrix toPredict, DenseMatrix correct) {
List<DenseMatrix[]> totalDeltas = new ArrayList<>();
DenseMatrix[] weights = getWeights();
DenseMatrix[] biases = getBiasesAsMatrices();
DenseMatrix[] deltaBiases = this.initializeDeltas(biases);
DenseMatrix[] deltaWeights = this.initializeDeltas(weights);
// Perform Feed Forward here...
List<DenseMatrix> activations = new ArrayList<>();
List<DenseMatrix> xVector = new ArrayList<>();
// Alters all arrays and lists.
this.backPropFeedForward(toPredict, activations, xVector, weights, biases);
// End feedforward
// Calculate error signal for last layer
DenseMatrix deltaError;
// Applies the error function to the last layer, create
deltaError = errorFunction
.applyErrorFunctionGradient(activations.get(activations.size() - 1), correct);
// Set the deltas to the error signals of bias and weight.
deltaBiases[deltaBiases.length - 1] = deltaError;
deltaWeights[deltaWeights.length - 1] = (DenseMatrix) deltaError
.mtimes(activations.get(activations.size() - 2).transpose());
// Now iteratively apply the rule
for (int k = deltaBiases.length - 2; k >= 0; k--) {
DenseMatrix z = xVector.get(k);
DenseMatrix differentiate = functions[k + 1].applyDerivative(z);
deltaError = (DenseMatrix) weights[k + 1].transpose().mtimes(deltaError)
.times(differentiate);
deltaBiases[k] = deltaError;
deltaWeights[k] = (DenseMatrix) deltaError.mtimes(activations.get(k).transpose());
}
totalDeltas.add(deltaBiases);
totalDeltas.add(deltaWeights);
return totalDeltas;
}
</code></pre>
<p><strong>EDIT</strong>
I forgot to include the feed forward algorithm.</p>
<pre><code>private void backPropFeedForward(DenseMatrix starter, List<DenseMatrix> actives,
List<DenseMatrix> vectors,
DenseMatrix[] weights, DenseMatrix[] biases) {
DenseMatrix toPredict = starter;
//actives.add(toPredict);
actives.add(Matrix.Factory.zeros(starter.getRowCount(), starter.getColumnCount()));
for (int i = 0; i < getTotalLayers() - 1; i++) {
DenseMatrix x = (DenseMatrix) weights[i].mtimes(toPredict).plus(biases[i]);
vectors.add(x);
toPredict = this.functions[i + 1].applyFunction(x);
actives.add(toPredict);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Ooh, hard to make any comments about this without knowing neural networks.</p>\n\n<p>However, I do see a lot of repetition especially when it comes to bias and weight. It may be a good idea to create generic methods for those. I see you use specific methods such as <code>getBias(i)</code> and <code>getWeight(i)</code> but those can be inserted using lambda functions.</p>\n\n<p>The <code>size</code> and <code>scaleFactor</code> variables are not used in the first two <code>for</code> loops, so I don't understand why they are declared & initialized so early. If you only declare variables where you need them it becomes easier to extract methods out of large swaths of code, and your code becomes easier to read (because you don't have to keep track of so many variables as a reader).</p>\n\n<p>There are a lot of unexplained calculations such as <code>- 1</code> and <code>- 2</code> going on. For you they may be clear, but generally you should comment on <strong>what</strong> you're trying to achieve with them.</p>\n\n<p>In general the functions are too large. Try to minimize the amount of code. If you have three <code>for</code> loops in a row in one function, try and see if you can extract (<code>private</code>) methods for them instead.</p>\n\n<p><code>stochasticGradientDescent</code> clearly prints out the result instead of returning it. That's not nice; at least indicate somewhere that it produces output. Instead of using <code>System.out</code>, simply use a <code>PrintStream out</code> as argument if you create such a method. Then you can always stream the output to file or to a <code>String</code> (for testing purposes) - and for console output you just pass <code>System.out</code> as parameter.</p>\n\n<p>Similarly, <code>calculateMiniBatch</code> doesn't return a value, it calls two setters instead. That's generally not done, as you can directly assign such things to fields. Calling public methods from private methods can be dangerous if they get overwritten. For this kind of purpose I might also consider returning a private <code>WeightAndBias</code> class instance with just two fields (a record in Java).</p>\n\n<p>I'm really wondering why <code>DenseMatrix</code> is not parameterized properly, I keep seeing class casts back to <code>DenseMatrix</code> while the methods are clearly defined on <code>DenseMatrix</code> itself. That probably means that an interface does not have a generic type parameter included that is set not by <code>DenseMatrix</code>, e.g.</p>\n\n<pre><code>interface Matrix<T extends Matrix> {\n T operation();\n}\n\nclass DenseMatrix<DenseMatrix> {\n DenseMatrix operation();\n}\n</code></pre>\n\n<p>Otherwise, I'll be glad to let you know that I don't understand the first thing about the code, so I'll stop while I'm behind :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-27T23:11:25.560",
"Id": "238071",
"ParentId": "233391",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T07:02:12.830",
"Id": "233391",
"Score": "2",
"Tags": [
"java",
"machine-learning",
"neural-network"
],
"Title": "Java Neural Network Implementation"
}
|
233391
|
<h1>Advent of Code 2019: Day 3</h1>
<p>I'm doing <a href="https://adventofcode.com/" rel="nofollow noreferrer">Advent of Code</a> this year. Below is my attempt at <a href="https://adventofcode.com/2019/day/3" rel="nofollow noreferrer">day 3</a>: </p>
<h2>Problem</h2>
<h3>Part One</h3>
<blockquote>
<p>--- Day 3: Crossed Wires ---</p>
<p>The gravity assist was successful, and you're well on your way to the Venus refuelling station. During the rush back on Earth, the fuel management system wasn't completely installed, so that's next on the priority list.</p>
<p>Opening the front panel reveals a jumble of wires. Specifically, two wires are connected to a central port and extend outward on a grid. You trace the path each wire takes as it leaves the central port, one wire per line of text (your puzzle input).</p>
<p>The wires twist and turn, but the two wires occasionally cross paths. To fix the circuit, you need to <em>find the intersection point closest to the central port</em>. Because the wires are on a grid, use the <a href="https://en.wikipedia.org/wiki/Taxicab_geometry" rel="nofollow noreferrer">Manhattan distance</a> for this measurement. While the wires do technically cross right at the central port where they both start, this point does not count, nor does a wire count as crossing with itself.</p>
<p>For example, if the first wire's path is <code>R8,U5,L5,D3</code>, then starting from the central port (<code>o</code>), it goes right <code>8</code>, up <code>5</code>, left <code>5</code>, and finally down <code>3</code>:</p>
</blockquote>
<pre><code>...........
...........
...........
....+----+.
....|....|.
....|....|.
....|....|.
.........|.
.o-------+.
...........
</code></pre>
<blockquote>
<p>Then, if the second wire's path is <code>U7,R6,D4,L4</code>, it goes up <code>7</code>, right <code>6</code>, down <code>4</code>, and left <code>4</code>:</p>
</blockquote>
<pre><code>...........
.+-----+...
.|.....|...
.|..+--X-+.
.|..|..|.|.
.|.-X--+.|.
.|..|....|.
.|.......|.
.o-------+.
...........
</code></pre>
<blockquote>
<p>These wires cross at two locations (marked <code>X</code>), but the lower-left one is closer to the central port: its distance is <code>3 + 3 = 6</code>.</p>
<p>Here are a few more examples:</p>
<ul>
<li><p><code>R75,D30,R83,U83,L12,D49,R71,U7,L72</code><br>
<code>U62,R66,U55,R34,D71,R55,D58,R83</code> = distance <code>159</code></p></li>
<li><p><code>R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51</code><br>
<code>U98,R91,D20,R16,D67,R40,U7,R15,U6,R7</code> = distance <code>135</code></p></li>
</ul>
<p><em>What is the Manhattan distance</em> from the central port to the closest intersection?</p>
</blockquote>
<p> </p>
<h3>Part Two</h3>
<blockquote>
<p>--- Part Two ---</p>
<p>It turns out that this circuit is very timing-sensitive; you actually need to <em>minimize the signal delay</em>.</p>
<p>To do this, calculate the <em>number of steps</em> each wire takes to reach each intersection; choose the intersection where the <em>sum of both wires' steps</em> is lowest. If a wire visits a position on the grid multiple times, use the steps value from the <em>first</em> time it visits that position when calculating the total value of a specific intersection.</p>
<p>The number of steps a wire takes is the total number of grid squares the wire has entered to get to that location, including the intersection being considered. Again consider the example from above:</p>
</blockquote>
<pre><code>...........
.+-----+...
.|.....|...
.|..+--X-+.
.|..|..|.|.
.|.-X--+.|.
.|..|....|.
.|.......|.
.o-------+.
...........
</code></pre>
<blockquote>
<p>In the above example, the intersection closest to the central port is reached after <code>8+5+5+2 = 20</code> steps by the first wire and <code>7+6+4+3 = 20</code> steps by the second wire for a total of <code>20+20 = 40</code> steps.</p>
<p>However, the top-right intersection is better: the first wire takes only <code>8+5+2 = 15</code> and the second wire takes only <code>7+6+2 = 15</code>, a total of <code>15+15 = 30</code> steps.</p>
<p>Here are the best steps for the extra examples from above:</p>
<ul>
<li><code>R75,D30,R83,U83,L12,D49,R71,U7,L72</code><br>
<code>U62,R66,U55,R34,D71,R55,D58,R83</code> = <code>610</code> steps</li>
<li><code>R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51</code><br>
<code>U98,R91,D20,R16,D67,R40,U7,R15,U6,R7</code> = <code>410</code> steps</li>
</ul>
<p><em>What is the fewest combined steps the wires must take to reach an intersection?</em></p>
</blockquote>
<hr>
<h2>Solution</h2>
<pre class="lang-py prettyprint-override"><code>with open(r"..\Inputs\day_3.txt") as file:
wires = [line.rstrip().split(",") for line in file.readlines()]
def dist(p1: tuple, p2=(0, 0): tuple) -> int:
"""Calculates the Manhattan distance between two points"""
return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])
def trace(step: str, pos: tuple) -> list:
"""Draws the line formed by applying a step (`step`) to a given coordinate (`pos`).
Args:
`step`: The step to be taken.
`pos`: The position to which the step should be applied.
Returns:
(list): A list of coordinates that define the line.
"""
shift = int(step[1:])
direction = step[0]
x = pos[0]
y = pos[1]
if direction == "D":
line = [(x, y-j) for j in range(1, shift+1)]
elif direction == "U":
line = [(x, y+j) for j in range(1, shift+1)]
elif direction == "L":
line = [(x-i, y) for i in range(1, shift+1)]
elif direction == "R":
line = [(x+i, y) for i in range(1, shift+1)]
return line
def draw(pos: tuple, path: list) -> list:
"""Draws the graph formed by following a sequence of steps (`path`) from a given starting position (`pos`)."""
graph = []
for step in path:
line = trace(step, pos)
pos = line[-1] # Update `pos`.
graph += line
return graph
def intersect(paths: list) -> tuple:
"""Draws the graphs formed by following the two provided paths and finds their intersection.
Args:
`paths`: A list of two elements, corresponding to the paths for the two wires.
Returns:
(tuple): A 3-tuple representing the graphs of the three wires and their intersections.
`graph_1 (list)`: Graph of the first wire.
`graph_2 (list)`: Graph of the second wire.
`crosses`: Set of points where the two wires cross each other.
"""
graph_1, graph_2 = draw((0, 0), paths[0]), draw((0, 0), paths[1])
crosses = set(graph_1) & set(graph_2)
return crosses, graph_1, graph_2
def reaches(paths: list) -> dict:
"""Finds the distance travelled by each wire to their various points of intersection.
Args:
`paths`: A list of two elements, corresponding to the paths for the two wires.
Returns:
(dict): A dictionary mapping each point of intersection to the distances the two wires take to reach it.
"""
crosses, graph_1, graph_2 = intersect(paths)
dct = {point: [None, None] for point in crosses}
for idx, pair in enumerate(graph_1):
if pair in crosses:
dct[pair][0] = dct[pair][0] or idx+1
for idx, pair in enumerate(graph_2):
if pair in crosses:
dct[pair][1] = dct[pair][1] or idx+1
return dct
def part_one() -> int:
"""Finds minimum Manhattan distance from origin of the intersection points."""
return min(dist(cross) for cross in intersect(wires)[0])
def part_two() -> int:
"""Finds minimum distance travelled by the two wires to reach an intersection point."""
return min(sum(pair) for pair in reaches(wires).values())
</code></pre>
<hr>
<h2>Notes</h2>
<p>I don't consider myself a beginner in Python, however I am not proficient in it either. I guess I would be at the lower ends of intermediate. I am familiar with PEP 8 and have read it in its entirety, thus, any stylistic deviations I make are probably deliberate. Nevertheless, feel free to point them out if you feel a particular choice of mine was sufficiently erroneous. I am concerned with best practices and readability, but also the performance of my code. I am not sure what tradeoff is appropriate, and would appreciate feedback on the tradeoffs I did make. </p>
<p>For example, <code>reaches()</code> could have been rewritten as:</p>
<pre class="lang-py prettyprint-override"><code>def reaches(paths: list) -> dict:
"""Finds the distance travelled by each wire to their various points of intersection.
Args:
`paths`: A list of two elements, corresponding to the paths for the two wires.
Returns:
(dict): A dictionary mapping each point of intersection to the distances the two wires take to reach it.
"""
crosses, graph_1, graph_2 = intersect(paths)
dct = {point: [None, None] for point in crosses}
ln_1, ln_2 = len(graph_1), len(graph_2)
if ln_1 < ln_2:
graph_1 += [None] * (ln_2 - ln_1)
else:
graph_2 += [None] * (ln_1 - ln_2)
for idx, pair in enumerate(zip(graph_1, graph_2)):
if pair[0] in crosses:
dct[pair[0]][0] = dct[pair[0]][0] or idx+1
if pair[1] in crosses:
dct[pair[1]][1] = dct[pair[1]][1] or idx+1
return dct
</code></pre>
<p>Which eliminates one iteration and could be more performant (actual testing in my Jupyter notebook with <code>%timeit</code> did show a slight performance improvement (mean of 616 ms vs 592 ms), but I'm not sure it was significant), but might make the code less readable? I wasn't sure which tradeoff to make here.</p>
<p>My style tends to over utilise functions. This is partly because I genuinely think separating functionality into functions is a good thing, but is also an artifiact of my development practices. I tend to write the program in a Jupyter notebook (the ability to execute arbitrary code excerpts in semi isolated cells is a very helpful development aid and lends itself naturally to one function per cell (with the added benefit of being able to easily test functions independently)). I would welcome thoughts on this, but unless it is particularly egregious, I am unlikely to change it.</p>
<p>I am aware that the approach I took to solving this problem is not necessarily the most efficient (especially space wise), as each line could be represented by its start and end coordinates (and not as a list of all its coordinates), but I haven't worked out a satisfactory solution using that approach, so this is all I have for now.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T07:32:27.673",
"Id": "456362",
"Score": "0",
"body": "@Peilonrayz I removed the performance tag and stated that I didn't think I was a beginner?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T07:39:34.993",
"Id": "456365",
"Score": "0",
"body": "Oops, I misread that :("
}
] |
[
{
"body": "<p>I couldn't find any drawbacks in your code. Maybe one nitpicking:</p>\n\n<p>instead of</p>\n\n<pre><code>for idx, pair in enumerate(graph_1):\n if pair in crosses:\n dct[pair][0] = dct[pair][0] or idx+1\n</code></pre>\n\n<p>you can do</p>\n\n<pre><code>for idx, coords in enumerate(graph_1, 1): \n if coords in crosses:\n dct[coords][0] = dct[coords][0] or idx\n</code></pre>\n\n<p>But I can suggest another approach - storing the length of wire while tracing, instead of calculating it afterward. It allows to eliminate the <code>reaches</code> function at all. I tried to add this functionality into your solution, but too much changes are required - it is easier to write from the beginning.</p>\n\n<p>I have my own solution, which uses this approach. It is different from your in many aspects:</p>\n\n<ul>\n<li>finding intersections happens at once for both part of the task. They are stored inside the <code>Grid</code> object.</li>\n<li>every point of wire has the <strong>length</strong> and <strong>x, y</strong> coordinates, so why not to store this information together? I store these values into wire's dictionary in form of <code>(y, x) : length</code>.</li>\n<li>using a dictionary instead of switch like <strong>if-else</strong> construction for <code>R, L, U, D</code> commands execution.</li>\n</ul>\n\n<p><strong>crossed_wires.py</strong></p>\n\n<pre><code>class Grid:\n def __init__(self):\n self.commands = {\n 'R' : {\"axis\" : 'x', \"step\" : +1},\n 'L' : {\"axis\" : 'x', \"step\" : -1},\n 'U' : {\"axis\" : 'y', \"step\" : +1},\n 'D' : {\"axis\" : 'y', \"step\" : -1}\n }\n def trace_wires(self, wire_1, wire_2):\n self.wire_1_coords = self.wire_coords_with_length(wire_1)\n self.wire_2_coords = self.wire_coords_with_length(wire_2)\n self.cross_coords = self.wires_intersections()\n\n def wire_coords_with_length(self, path):\n coords = {'x' : 0, 'y' : 0}\n wire_coords = {}\n wire_length = 0\n for move in path.split(','):\n direction = move[0] \n magnitude = int(move[1:])\n\n axis = self.commands[direction][\"axis\"]\n step = self.commands[direction][\"step\"]\n\n start_axis_value = coords[axis]\n end_axis_value = start_axis_value + magnitude * step\n for new_axis_value in range(start_axis_value, end_axis_value + step, step):\n coords[axis] = new_axis_value\n new_coords = (coords['y'], coords['x'])\n\n if new_coords not in wire_coords:\n wire_coords[new_coords] = wire_length\n wire_length += 1\n\n return wire_coords\n\n def wires_intersections(self):\n intersections = self.wire_1_coords.keys() & self.wire_2_coords.keys()\n intersections.remove((0, 0))\n return intersections\n\n def min_manhattan_dst(self):\n return min(abs(coords[0]) + abs(coords[1]) for coords in self.cross_coords)\n\n def min_wire_lens(self):\n return min(self.wire_1_coords[coords] + self.wire_2_coords[coords] for coords in self.cross_coords)\n\nwire_1 = input()\nwire_2 = input()\n\ngrid = Grid()\ngrid.trace_wires(wire_1, wire_2)\n\nprint(grid.min_wire_lens())\nprint(grid.min_manhattan_dst())\n</code></pre>\n\n<p>It gets data from the standard input, so in the Linux the usage will be:</p>\n\n<pre><code>crossed_wires.py < input.txt\n</code></pre>\n\n<p>My solution is a little slower than your (for each part separately), the difference is about <code>50 ms</code>. Probable it is caused by building a class.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-08T07:04:34.373",
"Id": "456712",
"Score": "1",
"body": "In `wire_coords_with_length()`, shouldn't `wire_length` be updated even if `new_coords` are already in `wire_coords`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-08T10:24:16.770",
"Id": "456719",
"Score": "0",
"body": "@RootTwo From the point of wire - should, because wire length have increased. It turns out this is not wire length, but the shortest length to the specific coordinates. Thus, `wire_length` should be renamed to something like `min_wire_len_to_coords`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-07T12:00:53.047",
"Id": "233585",
"ParentId": "233396",
"Score": "2"
}
},
{
"body": "<p>I would suggest coding <code>trace</code> as a generator that takes a path and yields the sequence of coordinates on the path.</p>\n\n<pre><code>def trace(path):\n step = {'U':(0,1), 'D':(0,-1),\n 'R':(1,0), 'L':(-1,0)}\n\n x = y = 0\n\n for segment in path:\n dx,dy = step[segment[0]]\n length = int(segment[1:])\n\n for n in range(length):\n x += dx\n y += dy\n yield x, y\n</code></pre>\n\n<p>Then code <code>draw</code> to build a dict mapping coords to the wire length to reach that coord.</p>\n\n<pre><code>def draw(path):\n coords = {}\n\n for path_length, coord in enumerate(trace(path), 1):\n if coord not in coords:\n coords[coord] = path_length\n\n return coords\n</code></pre>\n\n<p>Using dicts, let's you use the keys like sets, making it easy to find the intersecting points.</p>\n\n<pre><code>coords1 = draw(path1.split(','))\ncoords2 = draw(path2.split(','))\n\nintersections = coords1.keys() & coords2.keys()\n</code></pre>\n\n<p>And the answers:</p>\n\n<pre><code>min_manhattan = min(abs(x)+abs(y) for x,y in intersections)\n\nmin_wire = min(coords1[coord] + coords2[coord] for coord in intersections)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-09T01:55:58.983",
"Id": "233652",
"ParentId": "233396",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T09:08:10.487",
"Id": "233396",
"Score": "5",
"Tags": [
"python",
"algorithm",
"programming-challenge"
],
"Title": "Advent of Code 2019 Day 3"
}
|
233396
|
<h1>Advent of Code 2019: Day 1</h1>
<p>I'm doing <a href="https://adventofcode.com/" rel="nofollow noreferrer">Advent of Code</a> this year. Below is my attempt at <a href="https://adventofcode.com/2019/day/1" rel="nofollow noreferrer">day 1</a>: </p>
<h2>Problem</h2>
<h3>Part One</h3>
<blockquote>
<p>--- Day 1: The Tyranny of the Rocket Equation ---</p>
<p>Santa has become stranded at the edge of the Solar System while delivering presents to other planets! To accurately calculate his position in space, safely align his warp drive, and return to Earth in time to save Christmas, he needs you to bring him measurements from fifty stars.</p>
<p>Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck!</p>
<p>The Elves quickly load you into a spacecraft and prepare to launch.</p>
<p>At the first Go / No Go poll, every Elf is Go until the Fuel Counter-Upper. They haven't determined the amount of fuel required yet.</p>
<p>Fuel required to launch a given module is based on its mass. Specifically, to find the fuel required for a module, take its mass, divide by three, round down, and subtract 2.</p>
<p>For example:</p>
<ul>
<li>For a mass of 12, divide by 3 and round down to get 4, then subtract 2 to get 2.</li>
<li>For a mass of 14, dividing by 3 and rounding down still yields 4, so the fuel required is also 2.</li>
<li>For a mass of 1969, the fuel required is 654.</li>
<li>For a mass of 100756, the fuel required is 33583.</li>
</ul>
<p>The Fuel Counter-Upper needs to know the total fuel requirement. To find it, individually calculate the fuel needed for the mass of each module (your puzzle input), then add together all the fuel values.</p>
<p>What is the sum of the fuel requirements for all of the modules on your spacecraft?</p>
</blockquote>
<p> </p>
<h3>Part Two</h3>
<blockquote>
<p>--- Part Two ---</p>
<p>During the second Go / No Go poll, the Elf in charge of the Rocket Equation Double-Checker stops the launch sequence. Apparently, you forgot to include additional fuel for the fuel you just added.</p>
<p>Fuel itself requires fuel just like a module - take its mass, divide by three, round down, and subtract 2. However, that fuel also requires fuel, and that fuel requires fuel, and so on. Any mass that would require negative fuel should instead be treated as if it requires zero fuel; the remaining mass, if any, is instead handled by wishing really hard, which has no mass and is outside the scope of this calculation.</p>
<p>So, for each module mass, calculate its fuel and add it to the total. Then, treat the fuel amount you just calculated as the input mass and repeat the process, continuing until a fuel requirement is zero or negative. For example:</p>
<ul>
<li>A module of mass 14 requires 2 fuel. This fuel requires no further fuel (2 divided by 3 and rounded down is 0, which would call for a negative fuel), so the total fuel required is still just 2.</li>
<li>At first, a module of mass 1969 requires 654 fuel. Then, this fuel requires 216 more fuel (654 / 3 - 2). 216 then requires 70 more fuel, which requires 21 fuel, which requires 5 fuel, which requires no further fuel. So, the total fuel required for a module of mass 1969 is 654 + 216 + 70 + 21 + 5 = 966.</li>
<li>The fuel required by a module of mass 100756 and its fuel is: 33583 + 11192 + 3728 + 1240 + 411 + 135 + 43 + 12 + 2 = 50346.</li>
</ul>
<p>What is the sum of the fuel requirements for all of the modules on your spacecraft when also taking into account the mass of the added fuel? (Calculate the fuel requirements for each module separately, then add them all up at the end.)</p>
</blockquote>
<hr>
<h2>Solution</h2>
<pre class="lang-py prettyprint-override"><code>f = lambda mass: mass // 3 - 2
def partial_sum(mass):
return 0 if f(mass) <= 0 else f(mass) + partial_sum(f(mass))
def part_one():
with open(r"../Inputs/day_1.txt") as file:
return sum(f(int(i)) for i in file.readlines())
def part_two():
with open(r"../Inputs/day_1.txt") as file:
return sum(partial_sum(int(mass)) for mass in file.readlines())
</code></pre>
<hr>
<h2>Notes</h2>
<p>I don't consider myself a beginner in Python, however I am not proficient in it either. I guess I would be at the lower ends of intermediate. I am familiar with PEP 8 and have read it in its entirety, thus, any stylistic deviations I make are probably deliberate. Nevertheless, feel free to point them out if you feel a particular choice of mine was sufficiently erroneous. I am concerned with best practices and readability, but also the performance of my code. I am not sure what tradeoff is appropriate, and would appreciate feedback on the tradeoffs I did make. </p>
<p>My style tends to over utilise functions. This is partly because I genuinely think separating functionality into functions is a good thing, but is also an artifiact of my development practices. I tend to write the program in a Jupyter notebook (the ability to execute arbitrary code excerpts in semi isolated cells is a very helpful development aid and lends itself naturally to one function per cell (with the added benefit of being able to easily test functions independently)). I would welcome thoughts on this, but unless it is particularly egregious, I am unlikely to change it.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T19:56:59.120",
"Id": "456288",
"Score": "0",
"body": "Shouldn't `partial_sum` directly include `mass` in the sum? So `return mass + (0 if f(mass) <=0 else f(mass) + partial_sum(f(mass)))`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T20:01:24.443",
"Id": "456291",
"Score": "0",
"body": "Can you do the math ahead of time and derive a closed-form equation for the total fuel required for a module based on a recurrence relation? I haven't tried it, so not sure it's possible. Otherwise I personally think the recursive approach makes more sense here than an iterative one (in general I prefer functional prog over imperative)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T06:56:34.880",
"Id": "456356",
"Score": "0",
"body": "\"Shouldn't partial_sum directly include mass in the sum? So return mass + (0 if f(mass) <=0 else f(mass) + partial_sum(f(mass)))?\"\n\n@bob no. That I posted it here means the solution works. Changing it as you described wouldn't work. The reason it starts with 0 is because the partial sum eventually drops below 0, so 0 forms the base case of the recursive algorithm."
}
] |
[
{
"body": "<blockquote>\n<pre><code>f = lambda mass: mass // 3 - 2\n</code></pre>\n</blockquote>\n\n<p>I would question the spec and consider making this <code>max(0, mass // 3 - 2)</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>def partial_sum(mass):\n return 0 if f(mass) <= 0 else f(mass) + partial_sum(f(mass))\n</code></pre>\n</blockquote>\n\n<p>DRY: calculate <code>f(mass)</code> once and store it in a local variable.</p>\n\n<p><code>partial_sum</code> isn't the most descriptive name.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>def part_one():\n with open(r\"../Inputs/day_1.txt\") as file:\n return sum(f(int(i)) for i in file.readlines())\n\ndef part_two():\n with open(r\"../Inputs/day_1.txt\") as file:\n return sum(partial_sum(int(mass)) for mass in file.readlines())\n</code></pre>\n</blockquote>\n\n<p>Again, DRY. This isn't as clear cut, but I think it's worth pulling out a function which takes a module mass and returns a total fuel mass, and then <code>part_one</code> calls it with <code>f</code> and <code>part_two</code> calls it with <code>partial_sum</code>.</p>\n\n<p>Well done for using <code>with</code> for the file I/O.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T07:10:09.940",
"Id": "456358",
"Score": "0",
"body": "Thanks for the pointers re: my grouping into functions. I'll implement those."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T10:55:48.140",
"Id": "233401",
"ParentId": "233398",
"Score": "5"
}
},
{
"body": "<p>Your function <code>f</code> should probably be a proper function, like all the others. There is no reason for it to be a <code>lambda</code>.</p>\n\n<pre><code>def fuel(mass):\n return mass // 3 - 2\n</code></pre>\n\n<p>Instead of using recursion, you could use iteration in <code>partial_sum</code>:</p>\n\n<pre><code>def total_fuel(mass):\n total_mass = 0\n while True:\n mass = fuel(mass)\n if mass <= 0:\n break\n total_mass += mass\n return total_mass\n</code></pre>\n\n<p>The difference between the iterative and recursive approach is not really relevant here. The required fuel quickly vanishes even for really large masses (like <code>1e308</code>), so you never run into the stack size limit. However, timing wise the iterative approach is faster by up to about a factor three, probably due to the overhead of the additional function calls of the recursive solution:</p>\n\n<pre><code>In [31]: %timeit partial_sum(1e308)\n1.04 ms ± 9.28 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n\nIn [32]: %timeit total_fuel(1e308)\n372 µs ± 6.47 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n</code></pre>\n\n<p>In Python 3.8+ this function can be shortened a bit more, as mentioned <a href=\"https://codereview.stackexchange.com/questions/233398/advent-of-code-2019-day-1/233405?noredirect=1#comment456229_233405\">in the comments</a> by <a href=\"https://codereview.stackexchange.com/users/84718/409-conflict\">@409_Conflict</a>:</p>\n\n<pre><code>def total_fuel(mass):\n total_mass = 0\n while (mass := fuel(mass)) > 0:\n total_mass += mass\n return total_mass\n</code></pre>\n\n<p>Files are directly iterable, there is no need to first read the whole file content into memory:</p>\n\n<pre><code>def part_two():\n with open(\"../Inputs/day_1.txt\") as file:\n return sum(total_fuel(int(mass)) for mass in file)\n</code></pre>\n\n<p>Note that usually you don't need the string to be a raw string, a simple <code>\"\"</code> string suffices here.</p>\n\n<p>You don't show in this case how you are calling it. but you should make sure to put it under a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a> to allow importing from this script without running the code.</p>\n\n<p>It might also be worthwhile to add a <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\"><code>docstring</code></a> to each of your functions, or at least add a module docstring with the challenge description.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T13:34:40.113",
"Id": "456229",
"Score": "2",
"body": "Python 3.8 FTW: `while (mass := fuel(mass)) > 0: total_mass += mass`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T13:35:49.810",
"Id": "456231",
"Score": "0",
"body": "@409_Conflict: Ah yes, I was trying to find a way to do that, but I always forget about the new walrus operator..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T13:41:20.377",
"Id": "456233",
"Score": "0",
"body": "Yeah, the new patterns to recognize are `data = do_work(); if condition(data):...` and its corollary using `while True ... break`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T19:55:08.053",
"Id": "456286",
"Score": "0",
"body": "In your `rocket_equation` function, did you include the module's mass anywhere in the calculation of `total_mass`? I'm not seeing it but may have missed it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T19:56:54.787",
"Id": "456287",
"Score": "0",
"body": "@bob No I do not, as per the problem statement. When I came up with the name, I did, though, so maybe the name is not the best anymore."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T19:58:42.730",
"Id": "456289",
"Score": "0",
"body": "That makes sense; so this is giving the total fuel required for a module."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T20:00:25.277",
"Id": "456290",
"Score": "1",
"body": "@bob Yeah. That is probably a better name for the function, edited."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T07:09:42.190",
"Id": "456357",
"Score": "0",
"body": "Aah, thanks for the comment. I no iterative is faster (my solution was initially iterative), I just went with the recursive solution cause I felt it was more elegant. I do appreciate the pointers though. I can't use Python 3.8 because Jupyter doesn't seem to support it well (or if it does, i am unable to get it to work)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T07:12:46.993",
"Id": "456359",
"Score": "0",
"body": "As for the import guard, this is part of a repo for Advent of Code solutions, so it's unlikely to be imported into any other code (more likely to copy and paste if I need a function I wrote here). Same also for the module docstring. The file name indicates which day it's a solution to, so there's no real need for an extra docstring on top of that?"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T12:56:28.880",
"Id": "233405",
"ParentId": "233398",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "233401",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T09:56:14.870",
"Id": "233398",
"Score": "4",
"Tags": [
"python",
"algorithm",
"programming-challenge"
],
"Title": "Advent of Code 2019: Day 1"
}
|
233398
|
<p>I have created one generic <code>Page</code> class for store paging information with its data.</p>
<p>The class look like:</p>
<pre><code>public class Page<T>
where T : new()
{
private List<T> _list = new List<T>();
[JsonProperty(PropertyName = "total_count")]
public long TotalCount { get; set; }
[JsonProperty(PropertyName = "page_start")]
public long PageStart { get; set; }
[JsonProperty(PropertyName = "page_size")]
public long PageSize { get; set; }
[JsonProperty(PropertyName = "list")]
public List<T> List
{
get { return _list; }
set { _list = value; }
}
}
</code></pre>
<p>For every table model of my application uses generic <code>Page</code> class in repository for return <code>PageSize</code> and its total records with its <code>List</code>.</p>
<p>My repository use like below:</p>
<pre><code>public class StudentRepository
{
private readonly CountingCloud_DevContext _dbContext;
public StudentRepository(CountingCloud_DevContext dbContext)
{
_dbContext = dbContext;
}
public Page<StudentResponse> Get(Dictionary<string, object> filterParameters)
{
var resultfinal = new Page<StudentResponse>();
int from = 0, size = 10;
resultfinal = Paging(resultfinal, filterParameters, ref from, ref size);
var query = _dbContext.Students.ToList();
var result = query.Select(x => new StudentResponse
{
Id = x.Id,
Name = x.Name
});
resultfinal.TotalCount = result.Count();
query = result.Skip(from).Take(size);
return resultfinal;
}
private static Page<StudentResponse> Paging(Page<StudentResponse> pagingResponse, Dictionary<string, object> parameters, ref int from, ref int size)
{
if (parameters != null)
{
if (parameters.ContainsKey("PageSize") && parameters.ContainsKey("PageStart"))
{
if (Convert.ToInt32(parameters["PageSize"]) != 0)
{
size = Convert.ToInt32(parameters["PageSize"]);
from = (Convert.ToInt32(parameters["PageStart"]) - 1) * size;
pagingResponse.PageSize = size;
pagingResponse.PageStart = Convert.ToInt32(parameters["PageStart"]);
}
}
else
{
pagingResponse.PageSize = size;
pagingResponse.PageStart = from + 1;
}
}
else
{
pagingResponse.PageSize = size;
pagingResponse.PageStart = from + 1;
}
return pagingResponse;
}
}
</code></pre>
<p>Currently <code>Paging()</code> method I have use for all table like my other Repository is for Employee then for that paging method is look like below:</p>
<pre><code>private static Page<EmployeeResponse> Paging(Page<StudentResponse> pagingResponse, Dictionary<string, object> parameters, ref int from, ref int size)
{
if (parameters != null)
{
if (parameters.ContainsKey("PageSize") && parameters.ContainsKey("PageStart"))
{
if (Convert.ToInt32(parameters["PageSize"]) != 0)
{
size = Convert.ToInt32(parameters["PageSize"]);
from = (Convert.ToInt32(parameters["PageStart"]) - 1) * size;
pagingResponse.PageSize = size;
pagingResponse.PageStart = Convert.ToInt32(parameters["PageStart"]);
}
}
else
{
pagingResponse.PageSize = size;
pagingResponse.PageStart = from + 1;
}
}
else
{
pagingResponse.PageSize = size;
pagingResponse.PageStart = from + 1;
}
return pagingResponse;
}
</code></pre>
<p>I would like make this private method is generic so all repository use same,
please suggest me what I am implemented is correct or any better improvement for code any changes.</p>
|
[] |
[
{
"body": "<p>Some quick remarks:</p>\n\n<ul>\n<li><p><a href=\"https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/general-naming-conventions\" rel=\"nofollow noreferrer\">Names shouldn't contain underscores etc</a>: <code>CountingCloud_DevContext</code>. (The exception is the underscore at the start of a private member (e.g. <code>_dbContext</code>.)</p></li>\n<li><p>If you have a Dictionary, do not use <code>ContainsKey</code> if you need to retrieve the value associated with that key. This is why the much more efficient <code>TryGetValue</code> exists.</p></li>\n<li><p>Do not copy-paste magic strings (e.g. \"PageSize\") all over the place. Store them as <code>const</code> in a relevant class and use that.</p></li>\n<li><p>But most importantly: what's the point of <code>Dictionary<string, object></code> when all it contains is two specific key-value pairs? Why not make a <code>PagingParameters</code> class with <code>PageSize</code> and <code>PageStart</code> as nullable <code>int</code>s? Don't make things too generic, because all you end up is making things harder for yourself.</p></li>\n<li><p>Also avoid making a generic Repository class. It likely will create more work and solve nothing.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T12:37:49.607",
"Id": "233403",
"ParentId": "233399",
"Score": "3"
}
},
{
"body": "<p>The Page class does not need to have this T:new constraint, and the List can be an automatic property, just as the other Properties are.</p>\n\n<p>The Dictionary parameter can be changed to an IReadOnlyDictionary, to indicate, your methods only read the dictionary,\nthey don't modify anything.</p>\n\n<p>The Paging method takes a Page, and returns the same Page ?\nIf there is no code, that eventually changes the Page to something else, the return value is not necessary.</p>\n\n<p>You can consider making your Paging-method a part of the Page class itself. </p>\n\n<pre><code>pagingResponse.Paging(filterParameters, ref from, ref size) \n</code></pre>\n\n<p>may look simpler.</p>\n\n<p>If you only Count something from a Query in result.Count(); why do you do a complicated select before ?\nThe result of this</p>\n\n<pre><code> var query = _dbContext.Students.ToList();\n var result = query.Select(x => new StudentResponse\n {\n Id = x.Id,\n Name = x.Name\n });\n resultfinal.TotalCount = result.Count();\n</code></pre>\n\n<p>Is exactly the same as from </p>\n\n<pre><code> _dbContext.Students.Count();\n</code></pre>\n\n<p>Your last query is kind of useless.</p>\n\n<pre><code> query = result.Skip(from).Take(size);\n</code></pre>\n\n<p>It's created but not executed, and thrown away at the end of the routine.\nAnd this makes the from and size parameters useless itself, they aren't good for anything.</p>\n\n<p>You have the information of \"size\" and \"from\" already availabel in PageSize and PageStart.\nWhy passing it out of the Paging method a second time as a ref parameter ?</p>\n\n<p>There might be some iteration missing, you seem to create one page only - and List is unassigned.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T18:37:24.673",
"Id": "233423",
"ParentId": "233399",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T09:57:41.383",
"Id": "233399",
"Score": "1",
"Tags": [
"c#",
"beginner",
"object-oriented",
"design-patterns"
],
"Title": "Generic Implementation for Paging Class in c#"
}
|
233399
|
<p>Suppose I have a list that holds a list of column names:</p>
<pre><code>columns = [
'Village Trustee V Belleville', 'Unnamed: 74', 'Unnamed: 75',
'Village President V Black Earth', 'Village Trustee V Black Earth',
'Unnamed: 78', 'Unnamed: 79', 'Village President V Blue Mounds',
'Village Trustee V Blue Mounds', 'Unnamed: 82',
'Village Trustee V Cottage Grove', 'Unnamed: 94', 'Unnamed: 95',
'Village President V Cross Plains', 'Village Trustee V Cross Plains',
'Unnamed: 98', 'Unnamed: 99'
]
</code></pre>
<p>And I want to find all <code>Unnamed: XX</code> values and replace them consecutively with the first valid string. For example:</p>
<p>Input:
<code>'Village Trustee V Belleville', 'Unnamed: 74', 'Unnamed: 75'</code></p>
<p>Output:
<code>'Village Trustee V Belleville', 'Village Trustee V Belleville', 'Village Trustee V Belleville'</code></p>
<p>For this I have a function:</p>
<pre><code>def rename_unnamed(columns):
current_value = None
pattern = re.compile(r'^Unnamed:\s\d+$')
for column_index, column in enumerate(columns):
if re.match(pattern, column):
columns[column_index] = current_value
else:
current_value = column
return columns
</code></pre>
<p>Which does the job pretty fine, however, I was wondering if this could be improved and/or simplified, as this looks like a mouthful for rather a simple task.</p>
|
[] |
[
{
"body": "<ul>\n<li><p>Don't mutate input and return.</p>\n\n<p>If I need to pass <code>columns</code> unedited to two different functions, than your function will seem like it's not mutating <code>columns</code> and I wouldn't have to perform a copy of the data. But this isn't the case.</p></li>\n<li><p>You may want to potentially error if there are no values before the first \"Unnamed\" value.</p></li>\n<li>You may want to make <code>pattern</code> an argument, to allow reusability of the function. And instead use change it to a callback to allow even more reusability.</li>\n</ul>\n\n<p>Overall your function's pretty good. I don't think it can be made much shorter.</p>\n\n<pre><code>def value_or_previous(iterator, undefined, default=None):\n prev_item = default\n for item in iterator:\n if not undefined(item):\n prev_item = item\n yield prev_item\n\n\ndef rename_unnamed(columns):\n return list(value_or_previous(columns, re.compile(r'^Unnamed:\\s\\d+$').match))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T13:18:27.143",
"Id": "233409",
"ParentId": "233404",
"Score": "3"
}
},
{
"body": "<p>In case you need to modify the initial <code>columns</code> list (mutable data structure) you don't need to <code>return</code> it.<br></p>\n\n<p>The crucial pattern can be moved out to the <em>top</em> making it reusable and accessible for other potential routines or <em>inline</em> conditions:</p>\n\n<pre><code>UNNAMED_PAT = re.compile(r'^Unnamed:\\s\\d+$')\n</code></pre>\n\n<p>As the function's responsibility is to <strong><em>back fill</em></strong> (backward filling) items matched by specific regex pattern I'd rename it appropriately like say <strong><code>backfill_by_pattern</code></strong>. The <em>search</em> pattern is passed as an argument.</p>\n\n<p>I'll suggest even more concise solution based on replacement of <em>search</em> items by the item at the <em>previous</em> index:</p>\n\n<pre><code>def backfill_by_pattern(columns, pat):\n fill_value = None\n for i, column in enumerate(columns):\n if pat.match(column):\n columns[i] = columns[i - 1] if i else fill_value\n</code></pre>\n\n<p>Sample usage:</p>\n\n<pre><code>backfill_by_pattern(columns, pat=UNNAMED_PAT)\nprint(columns)\n</code></pre>\n\n<p>The output:</p>\n\n<pre><code>['Village Trustee V Belleville',\n 'Village Trustee V Belleville',\n 'Village Trustee V Belleville',\n 'Village President V Black Earth',\n 'Village Trustee V Black Earth',\n 'Village Trustee V Black Earth',\n 'Village Trustee V Black Earth',\n 'Village President V Blue Mounds',\n 'Village Trustee V Blue Mounds',\n 'Village Trustee V Blue Mounds',\n 'Village Trustee V Cottage Grove',\n 'Village Trustee V Cottage Grove',\n 'Village Trustee V Cottage Grove',\n 'Village President V Cross Plains',\n 'Village Trustee V Cross Plains',\n 'Village Trustee V Cross Plains',\n 'Village Trustee V Cross Plains']\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T00:59:51.320",
"Id": "456319",
"Score": "0",
"body": "I get `None` when running this script; am I running it correctly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T07:35:55.983",
"Id": "456363",
"Score": "1",
"body": "@alexyorke, the very 1st sentence about *(mutable data structure)* should have given you a hint"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T14:10:37.120",
"Id": "233414",
"ParentId": "233404",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "233409",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T12:53:45.650",
"Id": "233404",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"regex"
],
"Title": "Find and replace consecutive string values in a list"
}
|
233404
|
<p>This program is yet to become user-friendly and is still in development, but I wanted to improve the current code.</p>
<pre><code>from random import choice
from os import system
clear = lambda: system('cls') # FOR WINDOWS ONLY
words = [i.strip() for i in open('words.txt').readlines()]
# Possible stages
STAGES = [
"""
-------
""",
"""
_______
| |
|
|
|
|
-------
""",
"""
_______
| |
| O
|
|
|
-------
""",
"""
_______
| |
| O
| |
|
|
-------
""",
"""
_______
| |
| O
| /|
|
|
-------
""",
"""
_______
| |
| O
| /|\\
|
|
-------
""",
"""
_______
| |
| O
| /|\\
| /
|
-------
""",
"""
_______
| |
| O
| /|\\
| / \\
|
-------
"""]
class HangMan:
def __init__(self):
self.current_stage = 0 # The stage in which the hangman is
self.letters = [chr(i) for i in range(97, 97 + 26)] # Possible characters
self.word = choice(words) # Random word
self.current_word = ['_'] * len(self.word) # The letters which the player has unlocked till now
def get_input(self) -> int:
""" Takes the player's input and processes it """
print(*self.letters)
print()
char = input('Please enter a letter from the above set: ')
while char.lower() not in self.letters:
print(f'Invalid letter: {char}\n')
char = input('Please enter another letter: ')
print()
return self.process_char(char)
def process_char(self, given_char: str) -> int:
"""
Processes the input and returns 0, 1, or 2
0 -> Win
1 -> Neither a win nor a loss
2 -> Lose
"""
self.letters.remove(given_char.lower())
unlocked = 0
for index, char in enumerate(self.word):
if char.lower() == given_char.lower():
self.current_word[index] = char
unlocked += 1
if '_' not in self.current_word:
print('You\'ve won!')
return 0
if not unlocked:
print('Whoops! Wrong letter!')
if not self.next_stage():
clear()
print(STAGES[self.current_stage])
print('You\'ve lost!')
return 2
else:
print(f'Yay! You\'ve unlocked {unlocked} letter{"" if unlocked == 1 else "s"}!')
return 1
def next_stage(self) -> bool:
""" Returns if this stage is the last """
self.current_stage += 1
if self.current_stage < len(STAGES) - 1:
return True
return False
def game(self) -> None:
""" Starts the game """
while True:
clear() # Comment if you are not using a command console
print('Currently unlocked letters:', ''.join(self.current_word))
print()
print(STAGES[self.current_stage])
x = self.get_input()
if x == 0 or x == 2:
print(f'The word was {self.word}!')
print()
input('Press enter to continue...')
if x == 0 or x == 2:
return
man = HangMan()
man.game()
</code></pre>
<p>How do I improve this? (Make this look better, make it faster, etc.)</p>
|
[] |
[
{
"body": "<pre><code>STAGES = [\n\"\"\"\n\n\n\n\n\n\n -------\n\"\"\",\n\n\"\"\"\n _______\n | |\n |\n |\n |\n |\n -------\n\"\"\",\n\n...\n</code></pre>\n\n<p>I would remove the first line break at the top of each stage to condense it, then re-add it when printing out.</p>\n\n<pre><code>clear()\n</code></pre>\n\n<p>I would remove this as users' usually don't like having their terminal cleared unexpectedly. </p>\n\n<pre><code> def next_stage(self) -> bool:\n \"\"\" Returns if this stage is the last \"\"\"\n\n self.current_stage += 1\n\n if self.current_stage < len(STAGES) - 1:\n return True\n\n return False\n</code></pre>\n\n<p>This can be simplified to <code>self.current_stage += 1</code> then <code>return self.current_stage < len(STAGES) - 1</code>.</p>\n\n<p><code>.lower()</code> is called four times; the user's input should be lower-cased before processing so that <code>.lower()</code> doesn't have to be called again. This would require <code>self.letters = [chr(i) for i in range(97, 97 + 26)]</code> to just have lowercase letters so that <code>.lower()</code> can be removed in the loop that checks if the characters are in the list containing capitals.</p>\n\n<pre><code> print()\n input('Press enter to continue...')\n\n if x == 0 or x == 2:\n return\n</code></pre>\n\n<p>This can be removed and replaced with \"Do you want to play again?\" If the user enters yes, then they can otherwise not. If the functionality is that the user keeps playing until they either win or lose, then it could be different.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T04:59:57.060",
"Id": "456347",
"Score": "0",
"body": "I agree with your last point, but as I said, the code is still in development. Great answer though!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T01:18:21.040",
"Id": "233447",
"ParentId": "233407",
"Score": "1"
}
},
{
"body": "<p>Your code is good but it may be overly complex. The more concise the code the easier it is to read (for me anyway). In this example below I have just used some example words, this code of course is just a quick example for demonstration. There is not anything in place if you get the word or want to guess the word etc. I couldn't really find a reason to use a class for simpler games because although the functions are 'closely related' in your functions, comprehension can save a lot of time and code. </p>\n\n<p>The while loop is useful because it gives a consistent input option which can be as user friendly as you make it. I think its essential for the users experience when making something like a text RPG. </p>\n\n<pre><code>import random\n\nwords = ['cheese', 'biscuits', 'hammer', 'evidence'] \nword_choice = [i.lower() for i in random.choice(words)]\nlives = 3\ncor_guess = []\nwhile True:\n print('Letters found: {}\\nWord length: {}'.format(cor_guess, len(word_choice)))\n if lives == 0:\n print('Your dead homie!\\nThe word was: ', word_choice)\n break\n guess = str(input('Guess a letter: '))\n if guess in word_choice:\n print(guess, 'is in the word!\\n')\n cor_guess.append(guess)\n else:\n print('Your dying slowly!\\n')\n lives -= 1\n</code></pre>\n\n<p>Example of the output:</p>\n\n<pre><code>Letters found: []\nWord length: 8\nGuess a letter: v\nv is in the word!\n\nLetters found: ['v']\nWord length: 8\nGuess a letter: i\ni is in the word!\n\nLetters found: ['v', 'i']\nWord length: 8\nGuess a letter: r\nYour dying slowly!\n\nLetters found: ['v', 'i']\nWord length: 8\nGuess a letter: b\nYour dying slowly!\n\nLetters found: ['v', 'i']\nWord length: 8\nGuess a letter: o\nYour dying slowly!\n\nLetters found: ['v', 'i']\nWord length: 8\nYour dead homie!\nThe word was: ['e', 'v', 'i', 'd', 'e', 'n', 'c', 'e']\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T13:49:00.333",
"Id": "235067",
"ParentId": "233407",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T13:06:31.697",
"Id": "233407",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"hangman"
],
"Title": "Single player Hangman in Python"
}
|
233407
|
<p>I made a <strong>Tic Tac Toe</strong> game using C. Here two players, <strong>player1</strong> and <strong>player2</strong>, can participate and play. Please rate my code and suggest improvements.</p>
<pre><code>#include<stdio.h>
#include<conio.h>
void board(char t[]);
int cheak(char T[]);
void main()
{
int i=0,n,r=100,p=1;
char TOT[9]={'1','2','3','4','5','6','7','8','9'};
char a='X';
for(;i<9;i++)
{
clrscr();
board(TOT);
printf("\n\n\n Player1=X\nPlayer2=O");
printf(" \n player %d tern:-",p);
printf("\nEnter number");
scanf("%d",&n);
TOT[n-1]=a;
if(a=='X')
{
a='O';
}
else
{
a='X';
}
r=cheak(TOT);
if(r==1)
{
clrscr();
board(TOT);
printf("\nPlayer 1 win");
break;
}
if(r==2)
{
clrscr();
board(TOT);
printf("\nPlayer 2 win");
break;
}
if(p==1)
{
p=2;
}
else
{
p=1;
}
if(i==8)
{
clrscr();
board(TOT);
printf("\n\nMatch Draw");
break;
}
}
getch();
}
void board(char t[])
{
printf("_________________");
printf("\n|| %c || %c || %c ||",t[0],t[1],t[2]);
printf("\n|---------------|");
printf("\n|| %c || %c || %c ||",t[3],t[4],t[5]);
printf("\n|---------------|");
printf("\n|| %c || %c || %c ||",t[6],t[7],t[8]);
printf("\n|---------------|");
}
int cheak(char T[])
{
int i=0,n=0;
for(;n<3;n++)
{
if(T[i]=='X'&&T[i+1]=='X'&&T[i+2]=='X')
{
return 1;
}
i=i+3;
}
i=0;
for(n=0;n<3;n++)
{
if(T[i]=='X'&&T[i+3]=='X'&&T[i+6]=='X')
{
return 1;
}
i++;
}
if(T[0]=='X'&&T[4]=='X'&&T[8]=='X')
{
return 1;
}
if(T[2]=='X'&&T[4]=='X'&&T[6]=='X')
{
return 1;
}
i=0;
for(n=0;n<3;n++)
{
if(T[i]=='O'&&T[i+1]=='O'&&T[i+2]=='O')
{
return 2;
}
i=i+3;
}
i=0;
n=0;
for(;n<3;n++)
{
if(T[i]=='O'&&T[i+3]=='O'&&T[i+6]=='O')
{
return 2;
}
i++;
}
if(T[0]=='O'&&T[4]=='0'&&T[8]=='O')
{
return 2;
}
if(T[2]=='O'&&T[4]=='O'&&T[6]=='O')
{
return 2;
}
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<h2><code>void main()</code> is not portable</h2>\n\n<p>Although it \"works\" in a lot of cases, the only two portable definitions of <code>main</code> are:</p>\n\n<pre><code>int main(void)\n</code></pre>\n\n<p>and</p>\n\n<pre><code>int main(int argc, char **argv)\n</code></pre>\n\n<h2>Error checking</h2>\n\n<p>You don't check the return value of <code>scanf</code>.</p>\n\n<p>This would be better:</p>\n\n<pre><code>if(scanf(\"%d\", &n) != 1)\n{\n fputs(\"Error; enter a number.\", stderr);\n return EXIT_FAILURE; /* entering a letter will cause infinite loop so error out here */\n}\n</code></pre>\n\n<p>Note that <code>EXIT_FAILURE</code> requires <code>stdlib.h</code> to be included.</p>\n\n<h2>Out-of-bounds write</h2>\n\n<p>If a user enters a <code>0</code> or a number greater than <code>9</code> in the <code>scanf</code> mentioned above, this line will write outside of the array bounds:</p>\n\n<pre><code> TOT[n-1]=a;\n</code></pre>\n\n<p>This can cause a segmentation fault.</p>\n\n<h2>Spelling</h2>\n\n<p>There are a couple spelling errors in this code:</p>\n\n<blockquote>\n <p>cheak -> check<br>\n tern -> turn</p>\n</blockquote>\n\n<h2>Formatting</h2>\n\n<p>There are a few issues with formatting here; first of all, each line in a function should be indented by at least 4 spaces. In addition, you should put spaces after commas in function calls, and around most (if not all) operators.</p>\n\n<h2>Portability</h2>\n\n<p>Although <code>clrscr</code> and <code>getch</code> work with Windows and DOS, I would suggest simply removing <code>clrscr</code> and replacing <code>getch</code> with <code>getchar</code>. This makes your code portable to the point where it can run on most other systems.</p>\n\n<h2>Non-descriptive variable names</h2>\n\n<p>At first glance, I don't know what <code>t</code>, <code>T</code>, <code>TOT</code>, <code>a</code>, <code>i</code>, <code>n</code>, <code>r</code>, or <code>p</code> are for. The variable names should describe what they contain.</p>\n\n<h2>Spacing</h2>\n\n<p>Although the board is nice, the prompt to the user isn't. I would suggest something like this:</p>\n\n<pre><code> printf(\"\\n\\n\\nPlayer 1 = X\\nPlayer 2 = O\");\n printf(\"\\nPlayer %d's turn.\",p);\n printf(\"\\n\\nEnter a number: \");\n</code></pre>\n\n<p>...</p>\n\n<pre><code> if(r == 1 || r == 2)\n {\n board(TOT);\n printf(\"\\nPlayer %d wins!\", r);\n break;\n }\n</code></pre>\n\n<h2>Misc.</h2>\n\n<p><code>p</code> is already 1 here. You don't need to set it again:</p>\n\n<pre><code> else\n {\n p=1;\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T20:04:01.060",
"Id": "233428",
"ParentId": "233412",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "233428",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T13:39:06.717",
"Id": "233412",
"Score": "3",
"Tags": [
"c",
"game",
"tic-tac-toe"
],
"Title": "Simulate Tic Tac Toe game using C language"
}
|
233412
|
<p>I am very new to Kotlin and I am trying to achieve this:</p>
<ul>
<li>I get a batch of <code>PersonDetails</code> to save or update</li>
<li>In the batch, the same <code>PersonDetails</code> with name is different locale can be present.</li>
<li>The end goal of this method is to merge the batch itself and also merge the existing entries in Database then return the updated data structure for saving into DB. </li>
</ul>
<p>I am not very happy with the way I have coded, can you please review this code and give your review comments.</p>
<pre><code>fun doProcess(batchToProcess: List<PersonDetail>) : Map<Long, PersonDetail> {
val idsInBatch = batchToProcess.map { it.lcmId }.toList()
val personDetailsFromDb = personDetailsRepository.getBatch(idsInBatch)
.map { it.lcmId to it }
.toMap()
val batchesOfPersonDetails = mutableMapOf<Long, PersonDetail>()
batchToProcess.map { aPerson ->
var personDetail = batchesOfPersonDetails[aPerson.lcmId]
if (personDetail == null) {
personDetail = personDetailsFromDb[aPerson.lcmId]
}
val updatedPersonDetail = when {
personDetail == null -> aPerson.toPersonDetail()
personDetail.isActive != aPerson.isActive -> {
personDetail.isActive = personDetail.isActive
personDetail
}
personDetail.localeDetails[aPerson.localeCode] != aPerson.localeName -> {
personDetail.localeDetails[aPerson.localeCode] = aPerson.localeName
personDetail
}
else -> {
logger.info { "Duplicate_Event for id ${aPerson.lcmId}" }
personDetail
}
}
batchesOfPersonDetails[updatedPersonDetail.lcmId] = updatedPersonDetail
}
return batchesOfPersonDetails
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T12:16:35.943",
"Id": "458690",
"Score": "0",
"body": "Did you mean to do only one update inside when at a time or all the updates at the same time?"
}
] |
[
{
"body": "<p>It's hard to follow exactly your logic. Pretty sure this line is wrong:</p>\n\n<pre><code>personDetail.isActive = personDetail.isActive\n</code></pre>\n\n<p>You probably meant to assign to something else as you are assigning same value (maybe <code>personDetail.isActive = aPerson.isActive</code>)</p>\n\n<p>Another fishy thing is, that you have those 2 conditions in \"when\" for assigning 'active' and 'locale' stuff. Maybe it's correct, but maybe both can happen at same time. In that case when is bad as it executes only first matching.</p>\n\n<p>Overall I would rewrite mapping function to form, that makes more sense to me. I think you can first setup return instance in one place rather than in different places and then at once modify it however you want. One question is logging and if it is necessary. Without logging it is even simpler, but otherwise I'd go with 1 <code>if</code> with <code>or</code> conditions and put logging in else or use else if + else in case, there is no <code>or</code> condition. Remove comments to have same functionality as in <code>when</code>.</p>\n\n<pre><code>batchToProcess.map { aPerson ->\n val personDetail = batchesOfPersonDetails.getOrDefault(\n aPerson.lcmId,\n personDetailsFromDb.getOrDefault(aPerson.lcmId, aPerson.toPersonDetail())\n )\n\n if (personDetail.isActive != aPerson.isActive) { //or both conditions with OR and then all changed content in one branch\n personDetail.isActive = aPerson.isActive // correct\n } /* else */\n if (personDetail.localeDetails[aPerson.localeCode] != aPerson.localeName) {\n personDetail.localeDetails[aPerson.localeCode] = aPerson.localeName\n } /* else { do logging } */\n\n batchesOfPersonDetails[personDetail.lcmId] = personDetail\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-09T09:01:40.420",
"Id": "233666",
"ParentId": "233413",
"Score": "2"
}
},
{
"body": "<p>To make your code understandable, you should extract the code for merging a single <code>PersonDetail</code> into a separate function:</p>\n\n<pre><code>fun merge(fresh: PersonDetail, fromDb: PersonDetail): PersonDetail {\n}\n</code></pre>\n\n<p>This function is where the main complexity happens, and it should be easy to write unit tests for this part of the code. And you should definitely write unit tests, after all you're dealing with details of actual people here, so you better get it correct from the beginning.</p>\n\n<p>In this <code>merge</code> function you can have much shorter variable names. Since you are dealing with persons only, you can remove the word <code>person</code> from the variable names, like I already did in the function declaration above. You can remove the word <code>detail</code> as well.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T09:08:30.497",
"Id": "460546",
"Score": "0",
"body": "Thanks, removing `person` and `detail` makes sense."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-09T04:30:49.000",
"Id": "235336",
"ParentId": "233413",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T13:42:27.953",
"Id": "233413",
"Score": "0",
"Tags": [
"kotlin"
],
"Title": "Merge objects in Kotlin if they are updated"
}
|
233413
|
<p>I've been trying to create a <code>shared example</code> to quickly and efficiently test controllers with CRUD operations that might also be nested.</p>
<p>I came up with this solution that works, but I feel that can be improved.</p>
<pre><code> module ApiHelper
RSpec.shared_examples "a CRUD controller" do |model:|
def self.controller_has_action?(action)
described_class.action_methods.include?(action.to_s)
end
def self.model_belongs_to_associations(model)
model.reflect_on_all_associations(:belongs_to).map(&:name).nil?
end
resource_singular = model.name.underscore.to_sym
parent_resource = model.reflect_on_all_associations(:belongs_to).map(&:name).first
#let(:parent_resource) { model.reflect_on_all_associations(:belongs_to).map(&:name) }
let(:records) { FactoryBot.create_list(resource_singular, 10) }
let(:parent_record) { FactoryBot.create(parent_resource.to_sym) }
before(:each) { request.env["HTTP_ACCEPT_LANGUAGE"] = "en" }
describe "#show", if: controller_has_action?(:show) do
context "when requested record exists" do
let(:record) { records[rand 10] }
before(:each) do
get :show, params: {id: record.id}
end
it "succeeds" do
expect(response).to have_http_status(:success)
end
it "returns the requested record" do
expect(json["id"]).to eq(record.id)
end
end
end
describe "#index", if: controller_has_action?(:index) do
let(:params) {
params = {}
unless parent_resource.nil?
params.merge!((parent_resource.to_s << "_id").to_sym => parent_record.id)
end
}
before(:each) do
get :index, params: params
end
it "succeeds" do
expect(response).to have_http_status(:success)
end
it "returns the factory names" do
record_names = json.map { |c| c["name"] }
expect(record_names).to all(be_a(String).and(include(resource_singular.capitalize.to_s)))
end
end
# noinspection RubyDuplicatedKeysInHashInspection
describe "#create", if: controller_has_action?(:create) do
let(:request_params) {
params = {}
unless parent_resource.nil?
params.merge!((parent_resource.to_s << "_id").to_sym => parent_record.id)
end
params.merge!(resource_singular => record_attrs)
}
before(:each) do
post :create, params: request_params
end
context "when valid" do
let(:record_attrs) { attributes_for(resource_singular) }
it "succeeds" do
expect(response).to have_http_status(:created)
expect(response.headers["Content-Type"]).to eql("application/json; charset=utf-8")
end
it "saves the new record" do
expect { post :create, params: request_params }.to change(model, :count).by(1)
end
end
context "when invalid" do
let(:record_attrs) { attributes_for(resource_singular, :invalid) }
it "fails" do
expect(response).to have_http_status(:unprocessable_entity)
end
end
end
describe "#update" do
let(:record) { records[rand 10] }
before(:each) do
patch :update, params: {resource_singular => new_attrs, :id => record.id}
end
context "when valid" do
let(:new_attrs) { attributes_for(resource_singular) }
it "succeeds" do
expect(response).to have_http_status(:success)
end
it "saves update" do
record.reload
expect(record).to have_attributes(new_attrs)
end
end
context "when invalid" do
let(:new_attrs) { attributes_for(resource_singular, :invalid) }
it "fails" do
expect(response).to have_http_status(:unprocessable_entity)
end
end
end
describe "#destory", if: controller_has_action?(:destroy) do
context "when record exists" do
let(:record) { records[rand 10] }
before(:each) do
delete :destroy, params: {id: record.id}
end
it "success" do
expect(response).to have_http_status(:no_content)
end
it "remove record" do
expect(model.all).not_to include(record)
end
end
context "when requested record doesn't exist" do
it "throws exception" do
bypass_rescue
expect { delete :destroy, params: {id: -1} }.to raise_exception(ActiveRecord::RecordNotFound)
end
end
end
describe "#translations" do
context "#show DE" do
before(:each) { request.env["HTTP_ACCEPT_LANGUAGE"] = "de" }
let(:record) { records[rand(10)] }
it "returns the title in DE" do
get :show, params: {id: record.id}
puts(record.attributes)
expect(json["name"]).to eq(record.name)
end
end
end
end
end
</code></pre>
<p>This can be called like this:</p>
<pre><code>it_behaves_like "a CRUD controller", model: Island
</code></pre>
|
[] |
[
{
"body": "<p>A couple notes.</p>\n\n<p>1) You don't have to pass <code>:each</code> to <code>before</code> calls, it's <a href=\"https://github.com/rspec/rspec-core/blob/8a287bd893889dba60e7bfce530727e7b009651e/lib/rspec/core/hooks.rb#L14-L18\" rel=\"nofollow noreferrer\">the default</a>:</p>\n\n<pre><code># Before\nbefore(:each) do\n get :index, params: params\nend\n\n# After\nbefore { get :index, params: params }\n</code></pre>\n\n<p>2) The code may benefit from the use of <a href=\"https://relishapp.com/rspec/rspec-expectations/v/3-9/docs/built-in-matchers/be-matchers\" rel=\"nofollow noreferrer\"><code>be</code> matchers</a>:</p>\n\n<pre><code># Before\nit \"success\" do\n expect(response).to have_http_status(:no_content)\nend\n\nit \"succeeds\" do\n expect(response).to have_http_status(:success)\nend\n\n# After\nit { is_expected.to be_no_content }\nit { is_expected.to be_successful }\n</code></pre>\n\n<p>3) In some cases the content of <code>params</code> object is ambiguous, because <code>unless</code> returns <code>nil</code> when the condition is falsy. Here is an example of different <code>params</code> initialization:</p>\n\n<pre><code># Before\nlet(:params) {\n params = {}\n unless parent_resource.nil?\n params.merge!((parent_resource.to_s << \"_id\").to_sym => parent_record.id)\n end\n}\n\n# After\nlet(:params) { parent_resource.nil? ? {} : { \"#{parent_resource}_id\".to_sym => parent_record.id } }\n</code></pre>\n\n<p>5) You're likely setting the language header in multiple places throughout the code, so a helper would come handy:</p>\n\n<pre><code>def set_language_header(lang)\n request.env[\"HTTP_ACCEPT_LANGUAGE\"] = lang\nend\n\nbefore { set_language_header(:en) }\nbefore { set_language_header(:de) }\n</code></pre>\n\n<p>Hope it helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-15T12:36:42.240",
"Id": "457720",
"Score": "0",
"body": "Thank you, what do you think of this part `parent_resource = model.reflect_on_all_associations(:belongs_to).map(&:name).first`? With multiple `belongs_to` associations obviously it will be problematic."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-15T12:18:35.133",
"Id": "234066",
"ParentId": "233420",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T18:18:57.980",
"Id": "233420",
"Score": "3",
"Tags": [
"ruby",
"ruby-on-rails",
"rspec"
],
"Title": "RSpec shared example for CRUD Controllers that might be nested or not"
}
|
233420
|
<p>I'm writing extension methods to shorten the code required to get custom <code>Claim</code>s from an <code>IPrincipal</code>. I have two general forms for the bodies of these methods.</p>
<h3>Form 1</h3>
<pre><code>public static long? GetFirmId(this IPrincipal principal)
{
return ((ClaimsPrincipal) principal)?.FindFirst(nameof(User.FirmId)) == null
? default(long?)
: long.TryParse(((ClaimsPrincipal) principal).FindFirst(nameof(User.FirmId)).Value, out var firmId)
? firmId
: default(long?);
}
</code></pre>
<h3>Form 2</h3>
<pre><code>public static long? GetFirmId(this IPrincipal principal)
{
if (principal == null)
{
return default(long?);
}
var claim = ((ClaimsPrincipal) principal).FindFirst(nameof(User.FirmId));
if (claim == null)
{
return default(long?);
}
if (long.TryParse(claim.Value, out var firmId))
{
return firmId;
}
return default(long?);
}
</code></pre>
<p>Please note that safely casting <code>IPrincipal</code> to <code>ClaimsPrincipal</code> is not necessary as <code>IPrincipal</code> in an ASP.NET Identity application is guaranteed to be a <code>ClaimsPrincipal</code>. I personally like form 1 better due to the brevity. The only thing I'm not super fond of is having to repeat <code>((ClaimsPrincipal) principal).FindFirst(nameof(User.FirmId))</code>. However, I would say that form 2 is easier to understand for anyone not familiar with modern C# features (or ternary operators, which I have found to be surprisingly unheard of).</p>
<p>ReSharper suggests a middle ground (probably because it isn't sophisticated enough to transcribe form 2 to form 1):</p>
<pre><code>public static long? GetFirmId(this IPrincipal principal)
{
var claim = ((ClaimsPrincipal) principal)?.FindFirst(nameof(User.FirmId));
if (claim == null)
{
return default(long?);
}
return long.TryParse(claim.Value, out var firmId) ? firmId : default(long?);
}
</code></pre>
<p>I'm looking for recommendations as to which form is "best," or an alternative suggestion. The project this is from has about ten of these methods for various custom claims of bool, bool?, char, char?, int, int?, long, long? and string. We are using custom claims to prevent needing a database trip (and additional code to make said database trip) to fetch commonly-used user-specific data.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T02:20:03.570",
"Id": "456329",
"Score": "0",
"body": "The `(claim == null)` block might be able to be removed by adding in `?` in as `long.TryParse(claim?.Value, out var firmId)`; I'm not familiar with `ClaimsPrincipal`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T12:13:03.703",
"Id": "456384",
"Score": "1",
"body": "If you have multiple of these, why then not move `((ClaimsPrincipal) principal)?.FindFirst(claimName)` to a method of its own?"
}
] |
[
{
"body": "<p>Sometimes breaking things up into smaller manageable chunks makes them easier to swallow</p>\n\n<p>Break the responsibilities up into more focused concerns.</p>\n\n<pre><code>public static class PrincipalExtension {\n /// <summary>\n /// Retrieves the Firm Id claim if it exists\n /// </summary>\n public static long? GetFirmId(this IPrincipal principal) {\n return long.TryParse(principal.FindFirstOrEmpty(nameof(User.FirmId)), out var firmId)\n ? firmId\n : default(long?);\n }\n /// <summary>\n /// Retrieves the first claim that is matched by the \n /// specified type if it exists, String.Empty otherwise.\n /// </summary>\n public static string FindFirstOrEmpty(this IPrincipal principal, string type) {\n return principal is ClaimsPrincipal p\n ? p.FindFirst(type)?.Value ?? string.Empty\n : string.Empty;\n }\n}\n</code></pre>\n\n<p><code>FindFirstOrEmpty</code> handles the finding of the claim value if it exists.</p>\n\n<p>This allows the main function to perform its designed role.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-07T03:06:16.577",
"Id": "233573",
"ParentId": "233422",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "233573",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T18:33:17.400",
"Id": "233422",
"Score": "2",
"Tags": [
"c#",
"asp.net",
"extension-methods",
"asp.net-identity"
],
"Title": "Extension method for getting custom Principal Claim"
}
|
233422
|
<p>Using <code>systemd</code>'s <code>.path</code> unit to run a Python script whenever a httpd config file is changed. The Python script creates a backup of the config and logs the differences of the newly modified and backup file. After that it checks the syntax of the httpd config and gracefully reloads the web server service.</p>
<p>The Python script:</p>
<pre><code>#!/path/to/python
import difflib
import logging
import shutil
import subprocess
import sys
from pathlib import Path
import yaml
logging.basicConfig(format='%(levelname)s - %(message)s', level=logging.INFO)
class HttpdMonitor:
def __init__(self, config_file):
self.config_file = config_file
self.config = self.load_config()
self.httpd_conf = self.config['httpd-conf']
self.backup_file = self.config['httpd-conf'] + '.bak'
self.syntax_check_cmd = self.config['syntax-check-cmd'].split()
self.reload_cmd = self.config['reload-cmd'].split()
def load_config(self):
with open(self.config_file, 'r') as stream:
return yaml.safe_load(stream)
def make_backup(self):
try:
shutil.copy2(self.httpd_conf, self.backup_file)
except IOError as e:
logging.exception("Making backup failed: %s", e)
def find_diff(self):
with open(self.httpd_conf, 'r') as f, open(self.backup_file, 'r') as bak:
diffs = list(
difflib.unified_diff(f.readlines(), bak.readlines(), fromfile=self.httpd_conf, tofile=self.backup_file))
return diffs
def log_diff(self):
try:
diffs = self.find_diff()
logging.info('Differences found: \n%s', ''.join(diffs))
except IOError as e:
logging.exception('Finding diff failed: %s', e)
def call_httpd_commands(self):
subprocess.run(self.syntax_check_cmd, check=True)
subprocess.run(self.reload_cmd, check=True)
def reload_httpd(self):
try:
self.call_httpd_commands()
except subprocess.CalledProcessError as e:
logging.exception("Reloading failed: %s", e)
def run(self):
if not Path(self.backup_file).is_file():
self.make_backup()
return
self.log_diff()
self.make_backup()
self.reload_httpd()
if __name__ == '__main__':
httpd_monitor = HttpdMonitor(sys.argv[1])
httpd_monitor.run()
</code></pre>
<p>This uses a YAML file to specify the httpd config file and also the commands to run, sort of like this:</p>
<pre><code>---
httpd-conf: /path/to/file
syntax-check-cmd: httpd -t
reload-cmd: httpd -k graceful
</code></pre>
<p>Using <code>systemd</code>'s <code>.path</code> unit the script get fired whenever there's something changed in the httpd config file. For example <code>httpd-monitor.path</code>:</p>
<pre><code>[Unit]
Description=Monitor the httpd conf for changes
[Path]
PathChanged=/path/to/file
Unit=httpd-monitor.service
[Install]
WantedBy=multi-user.target
</code></pre>
<p>And <code>httpd-monitor.service</code>:</p>
<pre><code>[Unit]
Description=Do backup, diff changes and reload httpd
[Service]
Restart=no
Type=simple
ExecStart=/path/to/httpd_monitor.py /path/to/httpd-monitor.yaml
[Install]
WantedBy=multi-user.target
</code></pre>
<p>So I'd first run <code>systemd start httpd-monitor.service</code> just to create the initial backup (the if condition within the <code>run()</code> method should take care of it) and then just <code>systemd enable --now httpd-monitor.path</code> to enable the <code>.path</code> unit.
Probably not the simplest of solutions so I'm very open to any feedback!</p>
|
[] |
[
{
"body": "<p>As a whole your approach looks good, except for a couple of issues I'd suggest to fix:</p>\n\n<ul>\n<li><p><strong><code>__init__</code></strong> method<br>\nAvoid repetitive indexing of nested structures like <code>self.config['httpd-conf']</code>.<br>Instead use assigned instance variable with <code>f-string</code> formatting:</p>\n\n<pre><code>def __init__(self, config_file):\n self.config_file = config_file\n self.config = self.load_config()\n self.httpd_conf = self.config['httpd-conf']\n self.backup_file = f'{self.httpd_conf}.bak'\n self.syntax_check_cmd = self.config['syntax-check-cmd'].split()\n self.reload_cmd = self.config['reload-cmd'].split()\n</code></pre></li>\n<li><p><strong><code>find_diff</code></strong> method<br>\nNo need to convert a <em>generator</em> returned by <code>difflib.unified_diff</code> function into <code>list</code> with <code>diffs = list(...)</code> - the subsequent <strong><code>''.join(diffs)</code></strong> itself will take care of consuming generator.</p></li>\n<li><p><code>call_httpd_commands</code> method<br>\nThis method is redundant as its main effect is reloading <code>httpd</code> server, but you already have the appropriate method for that purpose - <strong><code>reload_httpd</code></strong>. <br>Thus <code>call_httpd_commands</code> method's statements are just moved there and the old method is eliminated:</p>\n\n<pre><code>def reload_httpd(self):\n try:\n subprocess.run(self.syntax_check_cmd, check=True)\n subprocess.run(self.reload_cmd, check=True)\n except subprocess.CalledProcessError as e:\n logging.exception(\"Reloading failed: %s\", e)\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T07:50:44.213",
"Id": "456366",
"Score": "0",
"body": "Thank you! I wasn't too sure how to write the `reload_httpd()` method. So I made a separate `call_httpd_commands` because I remembered from Robert C. Martin's 'Clean Code' book (which seems to be more Java specific tho) that it's 'nicer' to extract functions from error handling. \n\nIt does look redundant now that I look at it and in this case I have to agree that I should break that 'rule'."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T21:13:34.280",
"Id": "233433",
"ParentId": "233424",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T18:59:18.913",
"Id": "233424",
"Score": "2",
"Tags": [
"python",
"beginner",
"python-3.x",
"linux"
],
"Title": "Log the diff of a Apache httpd config file and reload the service with Python and systemd"
}
|
233424
|
<ul>
<li>What can make this code better?</li>
<li>And how could I improve this code?</li>
<li>Oh and what I would love is if someone has a project that is not that
challenging but I could learn a lot from it :)</li>
</ul>
<p> </p>
<pre><code>import java.util.Scanner;
public class RockPaperScissors {
final static int ROCK = 1;
final static int PAPER = 2;
final static int SCISSORS = 3;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Start By Entering A number");
int human = input.nextInt();
System.out.println("ROCK IS 1 :: PAPER IS 2 :: SCISSORS 3");
int computerScore = 0, humanScore = 0, computer;
while (human != -1) {
human = input.nextInt();
computer = (int) (Math.random() * 3 + 1);
String h = human == 1 ? "ROCK" : human == 2 ? "PAPER" : "SCISSORS";
String c = computer == 1 ? "ROCK" : computer == 2 ? "PAPER" : "SCISSORS";
if ((human == ROCK && computer == SCISSORS) || (human == PAPER && computer == ROCK) || (human == SCISSORS && computer == PAPER)) {
humanScore++;
System.out.println("Human Won : " + humanScore);
System.out.println("Human Chose " + h + " and Computer Chose " + c);
} else if ((computer == ROCK && human == SCISSORS) || (computer == PAPER && human == ROCK) || (computer == SCISSORS && human == PAPER)) {
computerScore++;
System.out.println("Computer Won : " + computerScore);
System.out.println("Human Chose " + h + " and Computer Chose " + c);
} else if (human == computer) {
System.out.println("HAH YOU BOTH THINK THE SAME! ");
System.out.println("DRAW!");
} else {
System.out.println("Something Went Wrong Try Again:( ");
}
}
System.out.println("\n\nThe Scores Are *DRUM NOISES* ");
for (int i = 0; i < 4; i++) {
System.out.println("------------------------------");
}
System.out.println("Human score : " + humanScore);
System.out.println("Computer score : " + computerScore);
if (humanScore > computerScore) {
System.out.println("Human Race Is saved! We Won!");
} else if (computerScore > humanScore) {
System.out.println("Sadly We Lost. Better Luck Next Time:)");
} else {
System.out.println("Scores are Tied");
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-10T20:31:42.603",
"Id": "457155",
"Score": "0",
"body": "Make your code less [procedural](https://en.wikipedia.org/wiki/Procedural_programming) , and more [OOP](https://en.wikipedia.org/wiki/Object-oriented_programming) . [Short functions](https://medium.com/@efexen/keeping-it-short-8d1cdeca076a) are the key for [clear code](https://introcs.cs.princeton.edu/java/11style/)."
}
] |
[
{
"body": "<p>You should split your code up into methods. Methods generally improve code readability, increase robustness, and allow for faster development time.</p>\n\n<p>Try to split the code into methods based on behaviour. So for example, you may have a method to handle user input, a method to generate the computer's response (rock, paper or scissors), a method to display the scores, and a method to find the winner.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T23:42:54.013",
"Id": "456315",
"Score": "2",
"body": "The advice you give is good, but it may not be the right level of concreteness for a beginner. Imagine you were in the state of having written Rock Paper Scissors and being proud of your first program. What could you possibly get out of this code review?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T18:38:40.563",
"Id": "456453",
"Score": "2",
"body": "Thank You bro I will try to apply methods to my code ASAP!:D"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T22:07:46.553",
"Id": "233437",
"ParentId": "233426",
"Score": "3"
}
},
{
"body": "<p>This is a reasonable first attempt but there are many ways to make it better:</p>\n\n<pre><code>public class RockPaperScissors {\n final static int ROCK = 1;\n final static int PAPER = 2;\n final static int SCISSORS = 3;\n</code></pre>\n\n<ul>\n<li><p>Consider using an enumerated type to hold related constants.</p>\n\n<pre><code>System.out.println(\"Start By Entering A number\");\n</code></pre></li>\n<li><p>Your capitalization is not standard English.</p></li>\n<li><p>Tell the user how to quit.</p>\n\n<pre><code>int human = input.nextInt();\nSystem.out.println(\"ROCK IS 1 :: PAPER IS 2 :: SCISSORS 3\");\n</code></pre></li>\n<li><p>Put the explanation <em>before</em> fetching input!</p></li>\n<li><p>Why is there no \"is\" for the scissors case?</p>\n\n<pre><code>int computerScore = 0, humanScore = 0, computer;\nwhile (human != -1) {\n</code></pre></li>\n<li><p>Consider refactoring the main method so that it more clearly reflects what is happening, and extracting state to an object. I'd prefer to see your main look like this:</p></li>\n</ul>\n\n<hr>\n\n<pre><code>public static void main(String[] args) {\n initialize();\n Game g = new Game();\n g.printStartingText();\n while(!g.finished())\n g.playRound();\n g.printEndText();\n}\n</code></pre>\n\n<hr>\n\n<p>Can you structure your program like that? It will be more clear if you do.</p>\n\n<pre><code> String h = human == 1 ? \"ROCK\" : human == 2 ? \"PAPER\" : \"SCISSORS\";\n String c = computer == 1 ? \"ROCK\" : computer == 2 ? \"PAPER\" : \"SCISSORS\";\n</code></pre>\n\n<ul>\n<li><p>You've replicated some code here; it would be better to make a map from integer to the enumerated value and do two lookups in the map here.</p>\n\n<pre><code> if ((human == ROCK && computer == SCISSORS) || (human == PAPER && computer == ROCK) || (human == SCISSORS && computer == PAPER)) {\n</code></pre></li>\n<li><p>Instead of doing this work twice, write a method that returns PLAYER_1, PLAYER_2 or TIE:</p>\n\n<pre><code> Winner w = getWinner(human, computer);\n</code></pre></li>\n</ul>\n\n<p>That will let you simplify the logic that follows, and it will be easier to read.</p>\n\n<pre><code> System.out.println(\"Something Went Wrong Try Again:( \");\n</code></pre>\n\n<ul>\n<li><p>This should never happen. A better choice would be to assert that the condition is impossible.</p>\n\n<pre><code> System.out.println(\"Human Race Is saved! We Won!\");\n</code></pre></li>\n</ul>\n\n<p>Why are the humans \"we\"? The message is being produced by a computer! It should be \"The human race is saved; you won and we computers lost.\" :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T23:39:20.877",
"Id": "456314",
"Score": "2",
"body": "Nice review, except for the `snake_case`. Have you been away from Java and C# for a while? Or maybe there is a new trend that I missed … ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T23:48:05.560",
"Id": "456316",
"Score": "3",
"body": "@RolandIllig: I have spent the last couple years programming in C#, Java, Scala, Python and OCAML and I am now thoroughly confused as to what the right conventions are. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T18:37:53.120",
"Id": "456451",
"Score": "2",
"body": "Awesome!!!I should apply objects to my game as you said.I know basic so far,arrays,loops,methods,String and chars.I should as you said start Implementing more OOP into my Programming.PS Sorry for my English its not my native language"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T18:40:16.863",
"Id": "456454",
"Score": "2",
"body": "@IslamŠakrak: Your English is very good! But you might want to find a native speaker to do a quick check for oddities in punctuation or spelling. English is a bizarre language with crazy rules."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T23:10:45.363",
"Id": "233441",
"ParentId": "233426",
"Score": "5"
}
},
{
"body": "<pre><code>String h = human == 1 ? \"ROCK\" : human == 2 ? \"PAPER\" : \"SCISSORS\";\nString c = computer == 1 ? \"ROCK\" : computer == 2 ? \"PAPER\" : \"SCISSORS\";\n</code></pre>\n\n<p>This line is duplicated and can be converted into a method.</p>\n\n<pre><code>System.out.println(\"Computer Won : \" + computerScore);\nSystem.out.println(\"Human Chose \" + h + \" and Computer Chose \" + c);\n</code></pre>\n\n<p>and </p>\n\n<pre><code>System.out.println(\"Human Won : \" + humanScore);\nSystem.out.println(\"Human Chose \" + h + \" and Computer Chose \" + c);\n</code></pre>\n\n<p>have very similar logic, and can be refactored into another method where the differing strings can be substituted.</p>\n\n<pre><code>((computer == ROCK && human == SCISSORS) || (computer == PAPER && human == ROCK) || (computer == SCISSORS && human == PAPER))\n</code></pre>\n\n<p>This comparison check is duplicated twice, and could be refactored into another method.</p>\n\n<p>Each player has three properties: a name, score, and current move and needs to know if another move beats theirs. This can be converted into a <code>Player</code> class and the <code>beats(x, y)</code> comparison can be done there so that <code>human.beats(computer)</code> can be run. This makes it easier to read as there is more English.</p>\n\n<pre><code>for (int i = 0; i < 4; i++) {\n System.out.println(\"------------------------------\");\n}\n</code></pre>\n\n<p>This loop can be replaced with a <code>.repeat(n)</code> invocation, which duplicates the string four times.</p>\n\n<pre><code>while (human != -1) {\n</code></pre>\n\n<p>This could be converted into a <code>while true</code> loop and then this condition can be specified as <code>if (human == -1) break</code> which simplifies the control flow.</p>\n\n<pre><code>ROCK IS 1 :: PAPER IS 2 :: SCISSORS 3\n</code></pre>\n\n<p>It is unclear that the user has to enter in -1 to end the program. Perhaps the message could be added here.</p>\n\n<p>Applying these suggestions, I get the following code:</p>\n\n<pre><code>package com.company;\n\nimport java.util.Scanner;\n\npublic class RockPaperScissors {\n public static void main(String[] args) {\n Scanner input = new Scanner(System.in);\n System.out.println(\"Start By Entering A number\");\n Player human = new Player(\"Human\");\n Player computer = new Player(\"Computer\");\n human.move = input.nextInt();\n System.out.println(\"ROCK IS 1 :: PAPER IS 2 :: SCISSORS 3\");\n\n while (true) {\n if (human.move == -1) break;\n human.move = input.nextInt();\n makeComputerMove(computer);\n if (human.beats(computer)) {\n processWinner(human, computer);\n } else if (computer.beats(human)) {\n processWinner(computer, human);\n } else {\n System.out.println(\"HAH YOU BOTH THINK THE SAME! \");\n System.out.println(\"DRAW!\");\n }\n }\n printFinalWinner(human, computer);\n }\n\n private static void makeComputerMove(Player computer) {\n computer.move = (int) (Math.random() * 3 + 1);\n }\n\n /**\n * Prints the final winner to the console with the scores\n * @param human The human player\n * @param computer The computer player\n */\n private static void printFinalWinner(Player human, Player computer) {\n System.out.println(\"\\n\\nThe Scores Are *DRUM NOISES* \");\n System.out.println(\"------------------------------\\n\".repeat(4));\n System.out.println(\"Human score : \" + human.getScore());\n System.out.println(\"Computer score : \" + computer.getScore());\n if (human.getScore() > computer.getScore()) {\n System.out.println(\"Human Race Is saved! We Won!\");\n } else if (computer.getScore() > human.getScore()) {\n System.out.println(\"Sadly We Lost. Better Luck Next Time:)\");\n } else {\n System.out.println(\"Scores are Tied\");\n }\n }\n\n /**\n * Increments the score of the winner and prints the summary\n * @param winner The winning player\n * @param loser The player who lost\n */\n private static void processWinner(Player winner, Player loser) {\n winner.incrementScore();\n System.out.printf(\"%s Chose %s and %s Chose %s%n\", winner.name, winner.moveString(), loser.name, loser.moveString());\n }\n}\n\n/**\n * Holds information about the player such as score, name, and move\n */\nclass Player {\n final static int ROCK = 1;\n final static int PAPER = 2;\n final static int SCISSORS = 3;\n String name;\n int move;\n private int score;\n\n public int getScore() {\n return this.score;\n }\n\n public void incrementScore() {\n this.score++;\n }\n\n public Player(String name) {\n this.name = name;\n }\n\n /**\n * Checks if the move of another player beats the current player\n * @param another The other player\n * @return Whether the other player's move beats this player's\n */\n public boolean beats(Player another) {\n return (this.move == ROCK && another.move == SCISSORS\n || (this.move == PAPER && another.move == ROCK)\n || (this.move == SCISSORS && another.move == PAPER));\n }\n\n /**\n * The move integer into a string such as \"ROCK\", \"PAPER\", or \"SCISSORS\"\n * @return The string interpretation of the move\n */\n public String moveString() {\n return this.move == 1 ? \"ROCK\" : this.move == 2 ? \"PAPER\" : \"SCISSORS\";\n }\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T18:41:15.607",
"Id": "456455",
"Score": "0",
"body": "Thank you bro,this looks great appreciate it!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T00:19:10.470",
"Id": "233442",
"ParentId": "233426",
"Score": "3"
}
},
{
"body": "<p>I like putting those moves into enums. This is quite common so I've found nice solution already. This will make your checking for who won a lot nicer and readable:\n<a href=\"https://codereview.stackexchange.com/a/90552/214636\">https://codereview.stackexchange.com/a/90552/214636</a></p>\n\n<p>Also I feel like there definitely should be some thread sleeps after drumroll to add some more tension! Ex:</p>\n\n<pre><code> for (int i = 0; i < 4; i++) {\n System.out.println(\"------------------------------\");\n Thread.sleep(500);\n }\n</code></pre>\n\n<p>This will also require to add <code>throws Exception</code> (or <code>InterruptedException</code>) to main method signature.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-10T16:48:25.440",
"Id": "233800",
"ParentId": "233426",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T19:23:48.737",
"Id": "233426",
"Score": "2",
"Tags": [
"java",
"beginner",
"game",
"rock-paper-scissors"
],
"Title": "\"Rock Paper Scissors Game\" Java"
}
|
233426
|
<p>I was reminded by an achievement notification yesterday of <a href="https://codereview.stackexchange.com/questions/97318/string-replacement-using-dictionaries">this question</a> of mine, posted nearly four and a half years ago. After reading through my own code and the review posted, I decided to re-implement it. </p>
<p>Thus far, I have implemented a few changes:</p>
<ul>
<li>The function has been renamed to <code>mapping_replace</code>, perhaps more clear than <code>keymap_replace</code>.</li>
<li>The scope-creep features of <code>lower_keys=False</code>, <code>lower_values=False</code>, <code>lower_string=False</code> have been removed; as pointed out by <a href="https://codereview.stackexchange.com/users/36525/alexwlchan">alexwlchan</a>, behaviors like these should be left to the end-user.</li>
<li>The function will now, by default, throw an error if a key-value conflict is detected; if the end-user so desires, however, this behavior can be suppressed (e.g.: <code>{ "A": "B", "B": "C" }</code> - the second key <code>"B"</code> conflicts with the value of <code>"A"</code>).</li>
<li>The function now supports replacement with regular expressions, using <code>re.sub</code>. I am concerned in particular about this portion of the code, as it would seem that compiling a (potentially) significant number of regular expressions on the fly over-and-over again is an expensive operation; I tried to implement some form of memoization, but to no avail.</li>
<li>Finally, this function has been re-implemented in Python 3.8, under which dictionaries now retain their order of insertion.</li>
</ul>
<p><strong>dict_replace.py</strong></p>
<pre><code>import re
_DUPLICATE_KEY_EXCEPTION_MSG = "Key '{0}' already provided."
_KEY_VALUE_CONFLICT_EXCEPTION_MSG = "The key of '{0}' -> '{1}' conflicts with a separate mapping containing the value '{0}'."
class _KeyValueConflictException(Exception):
pass
def _validate_mappings(mappings: dict) -> None:
"""Validate a set of mappings provided to mapping_replace function.
This function takes a dictionary provided to the mapping_replace function by the end-
-user and determines whether or not the dictionary contains key-value conflicts.
Keyword arguments:
mappings -- The set of mappings to validate.
"""
keys = []
values = []
for key, value in mappings.items():
if key in values:
raise _KeyValueConflictException(_KEY_VALUE_CONFLICT_EXCEPTION_MSG.format(key, value))
keys.append(key)
values.append(value)
def mapping_replace(string: str, mappings: dict, use_regex=False, *, validate_mappings=True) -> str:
"""Replace portions of a string with a replacement.
This function takes a dictionary either of the format 'string -> replacement string'
or of the format 'regular expression -> replacement string'; in the case of the
former, it will replace all instances of 'string' with the provided replacement string,
and in the the case of the latter it will replace all expression matches with the
provided replacement string.
It should be noted that this function, by default, will raise an error if key-value
conflicts are found (e.g.: { 'A': 'B', 'B': 'C' } -- value 'B' and key 'B' conflict),
but this behavior can be suppressed by calling the function with validate_mappings=False.
Keyword arguments:
string -- The string to perform replacement operations on.
mappings -- The mapping of strings -> replacements or patterns -> replacements.
use_regex -- Whether or not the function uses regular expressions. False by default.
validate_mappings -- Whether or not to validate the provided mappings for conflicts.
"""
if validate_mappings:
_validate_mappings(mappings)
replaced_string = string
if use_regex:
for key, value in mappings.items():
replaced_string = re.sub(key, value, replaced_string)
else:
for key, value in mappings.items():
replaced_string = replaced_string.replace(key, value)
return replaced_string
</code></pre>
<p>Some example usage:</p>
<blockquote>
<pre><code>print(mapping_replace("simple test", { "simple": "complex", "test": "haha" }))
print(mapping_replace("124233 test", { r"\d+": "letters" }, True))
print(mapping_replace("Hello world", { "H": "J", "J": "Y"}, False, validate_mappings=False)) # No exception!
print(mapping_replace("Hello world", { "H": "J", "J": "Y" })) # Raises exception!
</code></pre>
</blockquote>
|
[] |
[
{
"body": "<p><strong>Naming</strong></p>\n\n<p>In many places, functions are described as operating on \"mappings\" or \"set of mappings\". As far as I can tell, the dictionary passed as a parameter is <em>a</em> mapping.\nThus, the plural form can be removed in various places.</p>\n\n<p>(As a disclaimer, English is not my native language - let me know if I am wrong.)</p>\n\n<hr>\n\n<p><strong>Unused value</strong></p>\n\n<p>In <code>_validate_mapping</code>, the list <code>keys</code> is populated but never used.</p>\n\n<hr>\n\n<p><strong>Limitation of the validation</strong></p>\n\n<p>The validation logic seems to be here to ensure that a substitution will not bring a pattern that will be replaced (or would have been replaced) by a different substitution.</p>\n\n<p>This somehow ensure that the order of the dictionary is not important.</p>\n\n<p>An example would be:</p>\n\n<pre><code>print(\"Yello world\" == mapping_replace(\"Hello world\", { \"H\": \"J\", \"J\": \"Y\"}, False, validate_mapping=False)) # No exception!\nprint(\"Jello world\" == mapping_replace(\"Hello world\", { \"J\": \"H\", \"H\": \"J\"}, False, validate_mapping=False)) # No exception!\n</code></pre>\n\n<p>However, there are various things that may be misleading with the corresponding logic <em>under the assumption that my understanding is valid</em> .</p>\n\n<p><strong>Handling of regexp</strong></p>\n\n<p>Regexp are not properly handled. For instance, this call:</p>\n\n<pre><code>print(\"\\d+ test\" == mapping_replace(\"124233 test\", { r\"\\d+\": r\"\\d+\" }, True, validate_mapping=False))\n</code></pre>\n\n<p>should have the same behaviour with <code>validate_mapping</code> set to <code>True</code> or <code>False</code>. At the moment, it either works or throws the exception.</p>\n\n<p><strong>Opposite situation</strong></p>\n\n<p>There are situations (like above) where the exception is thrown but but probably shouldn't but there are also situations where no exception is thrown but one would be expected.\nThis may give a feeling of \"safety\" which is not really valid.</p>\n\n<p>An example would be:</p>\n\n<pre><code>print(\"YYello world\" == mapping_replace(\"Hello world\", { \"H\": \"JJ\", \"J\": \"Y\" }))\nprint(\"JJello world\" == mapping_replace(\"Hello world\", { \"J\": \"Y\", \"H\": \"JJ\" }))\n</code></pre>\n\n<p>Should this throw ?</p>\n\n<p><strong>My expectations</strong></p>\n\n<p>Here is the behavior I'd have expected at least for the regexp case: check that no value from the dict would be matched by any of the keys (using <code>re.search</code>). In reality I do not see any correct way to check for any mapping that could lead to conflicts.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T22:08:34.927",
"Id": "233438",
"ParentId": "233429",
"Score": "4"
}
},
{
"body": "<h3>Ways of optimizing</h3>\n\n<ul>\n<li><p><strong><code>_validate_mappings</code></strong> function<br>Two lists <code>keys = []</code> and <code>values = []</code> are just used for accumulation and membership check, though inefficiently.<br>Instead, the more optimized way is to rely on <code>dict.values()</code> <em>view</em> object converted to <code>set</code> for fast containment check.<br>The optimized function would look as (<em>docstrings</em> are skipped for demo):</p>\n\n<pre><code>def _validate_mappings(mappings: dict) -> None:\n values = set(mappings.values())\n for key, value in mappings.items():\n if key in values:\n raise _KeyValueConflictException(_KEY_VALUE_CONFLICT_EXCEPTION_MSG.format(key, value))\n</code></pre></li>\n<li><p><code>mapping_replace</code> function in <strong><code>use_regex=True</code></strong> mode and dealing with multiple regex replacements.<br>To replace a loop of numerous subsequent regex compilations and substitutions I would suggest a \"single-pass\" substitution powered by the following features:</p>\n\n<ul>\n<li><em>regex alternation group</em> <code>(...)|(...)|(...)</code> to combine all raw patterns into one</li>\n<li>Python <code>dict</code> preserves its insertion order since 3.7</li>\n<li>the respective <em>replacement</em> string is found using <a href=\"https://docs.python.org/3/library/re.html#re.Match.lastindex\" rel=\"noreferrer\"><code>Match.lastindex</code></a> feature (the integer index of the last matched capturing group)</li>\n</ul>\n\n<p>Although, this trick may require non-overlapping patterns provided in <code>mappings</code> dict.<br>The crucial <strong><code>if use_regex:</code></strong> block:</p>\n\n<pre><code>...\nif use_regex:\n keys_list = list(mappings.keys())\n replacer = lambda m: mappings[keys_list[m.lastindex - 1]]\n pat = fr\"{'|'.join(f'({k})' for k in mappings.keys())}\" # composing regex alternation group\n replaced_string = re.sub(pat, replacer, replaced_string)\n</code></pre></li>\n</ul>\n\n<hr>\n\n<p>I've added some extended test case (3rd one) to show how's the regex trick goes:</p>\n\n<pre><code>print(mapping_replace(\"simple test\", {\"simple\": \"complex\", \"test\": \"haha\"}))\nprint(mapping_replace(\"124233 test\", {r\"\\d+\": \"letters\"}, True))\nprint(mapping_replace(\"011 test ABCbb11www\", {\"\\d+\": \"symbols\", \"[A-Z]+\": \"@\", \"w+\": \"W3W\"}, True))\nprint(mapping_replace(\"Hello world\", {\"H\": \"J\", \"J\": \"Y\"}, False, validate_mappings=False)) # No exception!\nprint(mapping_replace(\"Hello world\", {\"H\": \"J\", \"J\": \"Y\"}))\n</code></pre>\n\n<p>The output:</p>\n\n<pre><code>complex haha\nletters test\nsymbols test @bbsymbolsW3W\nYello world\nraise _KeyValueConflictException(_KEY_VALUE_CONFLICT_EXCEPTION_MSG.format(key, value))\n__main__._KeyValueConflictException: The key of 'J' -> 'Y' conflicts with a separate mapping containing the value 'J'.\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T11:16:54.893",
"Id": "456377",
"Score": "1",
"body": "The validation could be simplified further to `if mappings.keys() & mapping.values()`, because both are set-like objects."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T11:38:46.067",
"Id": "456378",
"Score": "1",
"body": "@Graipher, technically - yes, it could be. But the initial idea was to **raise** on the **1**st conflicting key found. Thus, the exact condition `if mappings.keys() & mapping.values()` won't be self-sufficient, as on the 1st step - the intersection is checked --> then check if it's not empty (if found - it will hold **all** keys) --> convert `set` to iterator and consume the 1st key. `conflicts = mappings.keys() & mappings.values();\n if conflicts:\n key = next(iter(conflicts))\n raise _KeyValueConflictException(_KEY_VALUE_CONFLICT_EXCEPTION_MSG.format(key, mappings[key]))`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T11:39:46.910",
"Id": "456379",
"Score": "1",
"body": "True, the intersection needs to compare all values and keys."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T17:46:10.507",
"Id": "456611",
"Score": "0",
"body": "@RomanPerekhrest But the happy path will compare all values and keys anyway, so you lose nothing doing it for the error path. It might even be beneficial to inform the user of all the conflicts at once so they are not frustrated by several rounds of trial and errors."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T22:41:17.840",
"Id": "233439",
"ParentId": "233429",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "233439",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T20:19:54.217",
"Id": "233429",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"strings"
],
"Title": "String replacement with dictionaries -- follow up"
}
|
233429
|
<p>I wrote this snippet to allocate blocks of memory, whose sizes and number are available during initialisation. I choose to equally divide the statically allocated memory. There are some error checks before allocating a block to a pool of memory and I maintain a free list in the memory blocks. It is not thread safe at the moment. Can I get some feedback?</p>
<pre><code>#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#define MAX_POOLS 4 // ceiling for num of pools
#define HEAP_SIZE 65536 // input heap size
// simple linked list
typedef struct {
void* next;
} node_t;
typedef struct {
uint16_t max_blocks; // max allowed blocks
uint16_t blocks_alloced; // contiguous blocks allocated
uint8_t* pool_start; //starting address of the pool
node_t* head; // free list pointer
size_t block_size; // block size
} pool_allocator_t;
static uint8_t pool_heap[HEAP_SIZE];
pool_allocator_t g_pools[MAX_POOLS];
static inline bool is_power_of_two(size_t in);
// added for tests
void pool_deinit(void)
{
memset(pool_heap, 0, HEAP_SIZE);
memset(g_pools, 0, MAX_POOLS);
}
bool pool_init(size_t* block_sizes, size_t block_size_count)
{
// not supported
if (block_size_count > MAX_POOLS) {
return false;
}
// non positive inputs are invalid
for (int i = 0; i < block_size_count; ++i) if ((int64_t)(block_sizes[i]) <= 0) return false;
size_t unalloc_space = sizeof(pool_heap);
uint8_t* boundary_start = pool_heap;
uint8_t* boundary_end = pool_heap + sizeof(pool_heap);
memset(g_pools, 0, MAX_POOLS * sizeof(pool_allocator_t));
uint8_t* base_address = boundary_start;
// equally sized partitions
uint16_t partition_size = unalloc_space / block_size_count;
for (int i = 0; i < block_size_count; ++i) {
if (!is_power_of_two(block_sizes[i]) // enforce power of two numbers only, doesn't exactly take care of alignment issues
|| block_sizes[i] > partition_size // bigger than partition?
|| base_address > boundary_end // did we overstep?
|| base_address + block_sizes[i] > boundary_end) { // is expected size not going to be fulfilled?
// clean up
memset(g_pools, 0, MAX_POOLS * sizeof(pool_allocator_t));
// init failed. fails even if first few blocks have been allocated successfully
return false;
}
g_pools[i].pool_start = base_address;
g_pools[i].head = NULL;
g_pools[i].block_size = block_sizes[i];
g_pools[i].max_blocks = partition_size / block_sizes[i];
unalloc_space -= partition_size;
base_address += (g_pools[i].max_blocks * g_pools[i].block_size);
// print stats for this partition
}
return true;
}
void* pool_malloc(size_t n)
{
// non-positive numbers are invalid inputs
if ((int64_t)n <= 0) return NULL;
pool_allocator_t* pool = NULL;
// decide which partition will it go to
uint8_t valid_partition = UINT8_MAX;
size_t valid_block = UINT32_MAX;
for (int i = 0; i < MAX_POOLS; ++i) {
// get smallest block size out of all pools that can fit this input
if (g_pools[i].pool_start != NULL
&& n <= g_pools[i].block_size
&& g_pools[i].block_size <= valid_block) {
valid_block = g_pools[i].block_size;
valid_partition = i;
}
}
// valid partition was found
if (valid_partition != UINT8_MAX) {
pool = &g_pools[valid_partition];
}
// no relevant partition found for this size
if (pool == NULL) {
return NULL;
}
if (n <= pool->block_size) {
} else {
return NULL;
}
// result block pointer, start with NULL
node_t* ret_block = NULL;
// see if memory is already available before getting new block?
if (pool->head != NULL) {
// head is non-null, so we have a previously freed block for use
// get this block's address and update head
ret_block = pool->head;
pool->head = pool->head->next;
} else {
// head is null, all previously allocated blocks are still under use. get a new block
// check if space is available
if (pool->blocks_alloced < pool->max_blocks) {
// get address of new block, increment blocks under use
ret_block = (void *)(pool->pool_start + pool->blocks_alloced * pool->block_size);
pool->blocks_alloced++;
} else {
// cannot satisfy requirement, fail
}
}
return ret_block;
}
void pool_free(void* ptr)
{
// base case
if (ptr == NULL) {
return;
}
// check if it is beyond the boundaries of heap
if (ptr < (void*)pool_heap || ptr >= (void*)&pool_heap[HEAP_SIZE]) {
}
pool_allocator_t* pool = NULL;
uint8_t allocated_pools = 0;
for(int i = 0; i < MAX_POOLS; ++i) if (g_pools[i].pool_start != NULL) allocated_pools++;
// find which partition the memory exists in
for (int i = 0; i < allocated_pools; ++i) {
void* curr_pool_boundary = (void*)( g_pools[i].pool_start + g_pools[i].max_blocks * g_pools[i].block_size);
if (ptr >= (void*)g_pools[i].pool_start // within boundary of this pool
&& ptr < curr_pool_boundary // within boundary of this pool
&& ((uint8_t*)ptr - g_pools[i].pool_start) % g_pools[i].block_size == 0) { //check if it is pointing to a valid block
// found in this bin, check if it is pointing to a valid block
pool = &g_pools[i];
}
}
// memory block wasn't found, exit
if (pool == NULL) {
return;
}
// set to 0, may not be necessary
memset(ptr, 0, pool->block_size);
// now that it's de-allocated, we can make it a node
node_t* freed_mem = (node_t*)ptr;
// point next to previous free location
freed_mem->next = pool->head;
// last freed node should become head
pool->head = freed_mem;
}
static inline bool is_power_of_two(size_t in)
{
return (in & (in - 1)) == 0;
}
int main()
{
size_t block[4] = {32, 64, 256, 1024};
bool ret = pool_init(block, sizeof(block)/sizeof(block[0]));
void* data1 = pool_malloc(16);
void* data2 = pool_malloc(65);
void* data3 = pool_malloc(1024);
return 0;
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T20:48:24.627",
"Id": "456294",
"Score": "1",
"body": "Looks like you're missing some code early in `my_pool_init`, right before the indented `unalloc_space,` line. That and the next two lines look like parameters to a function call but there is no function call and it won't currently compile."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T20:48:53.823",
"Id": "456295",
"Score": "1",
"body": "`is_power_of_two` will return `true` when `in` is 0."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T20:58:51.757",
"Id": "456296",
"Score": "0",
"body": "The declarations/definitions of `pool_heap` and `g_pools` are missing. The header files included are also missing (`stdint.h`, `stdbool.h`, and `string.h`), At the moment there is too much missing for us to review the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T21:03:59.610",
"Id": "456299",
"Score": "1",
"body": "Edited code to produce a compile-worthy snippet. I check for non-positive integers before initializing, so is_power_of_two returning true for 0 should not happen? But that is a correct callout."
}
] |
[
{
"body": "<h2>Algorithm</h2>\n<p>This looks like it was primarily developed as a library, it is possible on code review to provide separate files for review. Most of the code belongs possibly in a file called <code>memoryblockallocator.c</code>, there should also be a <code>memoryblockallocator.h</code> that provides the public function prototypes for <code>memoryblockallocator.c</code>. The <code>main()</code> function can be in a separate file called <code>main.c</code> which includes the header file <code>memoryblockallocator.h</code>. Within <code>memoryblockallocator.c</code> both <code>pool_heap</code> and <code>g_pools</code> should be declared as <code>static</code> so that they are not accessible to the rest of the program, currently only <code>pool_heap</code> is declared as <code>static</code>.</p>\n<p>Due to the logic in <code>is_power_of_two()</code> there is no benefit in declaring this an <code>inline</code> function, also modern <code>C</code> compilers that optimize the generated code may ignore <code>inline</code> since it is only a recommendation in the C99 standard.</p>\n<p>There is no need to put a size into the declaration <code>size_t block[4] = {32, 64, 256, 1024};</code> in <code>main()</code>, C will give it the proper size, and the code already contains the proper way to calculate the size in the call to <code>pool_init()</code>.</p>\n<p>In the function <code>void pool_free(void* ptr)</code> it might be good if the code merged adjacent blocks so that if the memory needs to be allocated again it isn't too fragmented. When allocating memory it might be good to use either a best fit or first fit algorithm for the allocation also to reduce the possibility of fragmentation. To do this the <code>node</code> struct may need to be augmented with more information.</p>\n<h2>Lack of Error Checking or Checking of Return Values</h2>\n<p>The function <code>pool_init(size_t* block_sizes, size_t block_size_count)</code> returns a bool value indicating the success or failure of the initialization, but this is ignored in <code>main()</code>. If <code>pool_intit()</code> fails <code>main()</code> should probably report an error and exit.</p>\n<h2>Unused and Untested Functions</h2>\n<p>Niether the function <code>void pool_deinit(void)</code> or the function <code>void pool_free(void* ptr)</code> are called in the program. In the case of <code>void pool_free(void* ptr)</code> this means that an important and complex part of the code is not being tested. It would not be good to trust that <code>void pool_free(void* ptr)</code> is working properly without testing it.</p>\n<h2>If Statements That Don't Do Anything</h2>\n<p>In the function <code>void pool_free(void* ptr)</code> there is this if statement that doesn't change anything:</p>\n<pre><code> // check if it is beyond the boundaries of heap\n if (ptr < (void*)pool_heap || ptr >= (void*)&pool_heap[HEAP_SIZE]) {\n }\n</code></pre>\n<p>If there is no action then this <code>if</code> statement isn't necessary</p>\n<p>In the function <code>void* pool_malloc(size_t n)</code> there is this <code>if</code> statement.</p>\n<pre><code> if (n <= pool->block_size) {\n } else {\n return NULL;\n }\n \n</code></pre>\n<p>The logic can be changed so that the code is simplified so there are no empty code blocks.</p>\n<pre><code> if (n > pool->block_size) {\n return NULL;\n }\n</code></pre>\n<h2>Inconsistent Use of Code Blocks in Flow Control</h2>\n<p>Withing the function <code>void pool_free(void* ptr)</code> there are these statements that control the flow of the function:</p>\n<pre><code> if (ptr == NULL) {\n return;\n }\n\n\n for(int i = 0; i < MAX_POOLS; ++i) if (g_pools[i].pool_start != NULL) allocated_pools++;\n\n\n if (pool == NULL) {\n return;\n }\n</code></pre>\n<p>The first thing to notice is that two of the three <code>if</code> statements wrap braces around a single statement, this is a good practice, this code can be expanded easily in maintenance. The inconsistency is the for loop does not wrap the <code>if</code> statement in braces and the <code>if</code> statement does not wrap the action in braces either. This code will be very difficult to maintain by you or anyone that inherits the code. A second problem with the for loop is that there are 3 statements all on one line which is even harder to maintain. Based on the other statements in this function I would expect to see:</p>\n<pre><code> for(int i = 0; i < MAX_POOLS; ++i)\n {\n if (g_pools[i].pool_start != NULL) \n {\n allocated_pools++;\n }\n }\n</code></pre>\n<p>This could easily be turned into a function to reduce the amount of code in <code>void pool_free(void* ptr)</code></p>\n<pre><code>static uint8_t count_allocated_pools()\n{\n uint8_t allocated_pools = 0;\n\n for(int i = 0; i < MAX_POOLS; ++i)\n {\n if (g_pools[i].pool_start != NULL)\n {\n allocated_pools++;\n }\n }\n\n return allocated_pools;\n}\n</code></pre>\n<p>Breaking the code up in this manner makes it easier to write, read, debug and maintain.</p>\n<p>The suggestions in this section apply to the other functions as well.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T07:23:13.170",
"Id": "456360",
"Score": "0",
"body": "Thank you for the detailed feedback! Is it good practice to not explicitly specify size of an array when it is initialized, like int a[] = {3,4}? Secondly, since allocation is only of individual blocks and a free list is maintained, are there chances of fragmentation? Thirdly, is casting size_t to int64_t a valid way to check for negative numbers passed to a function accepting size_t?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T13:20:17.943",
"Id": "456391",
"Score": "1",
"body": "The size_t type is unsigned, it can't ever be negative, it might wrap overflow where you go from a very large number back to zero so no. a[] = {3,4} is the most common way of initializing variables. Because your free list never merges adjacent free blocks back together you by default are fragmenting the memory."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T22:16:45.603",
"Id": "456483",
"Score": "0",
"body": "C will not complain if a negative number is passed as an argument to a function accepting size_t. So it is upto the library to handle this case. I thought casting to int64_t would help in this case(to identify negative input). I'm not sure how to handle this case."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T00:27:20.720",
"Id": "233443",
"ParentId": "233430",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "233443",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T20:42:30.647",
"Id": "233430",
"Score": "4",
"Tags": [
"c",
"c99"
],
"Title": "static memory block allocator in c99"
}
|
233430
|
<p>Follow-up to <a href="https://codereview.stackexchange.com/questions/232962/partial-zilog-z80-emulator-written-in-c">Partial Zilog Z80 emulator written in C++</a></p>
<p>I would say that I'm still new to the language, so I'm going to keep the <a href="/questions/tagged/beginner" class="post-tag" title="show questions tagged 'beginner'" rel="tag">beginner</a> tag this time.</p>
<p>Changes:</p>
<p>I've implemented the suggestions from @1201ProgramAlarm and have implemented about ¼ of the instructions in the main set.</p>
<p>I have in general reduced code duplication. I don't think that at this point I can do anything further in that direction.</p>
<p>I've refrained from creating variables until they are needed, and added some extra checks.</p>
<p>I've moved most of the code from <code>tools.cpp</code> back to <code>z80emu.hpp</code>.</p>
<p>I've started implementing the flag changes, though some are still incomplete.</p>
<p><code>emulate.cpp</code>:</p>
<pre><code>#include <stdexcept>
#include "z80emu.hpp"
#include "opcodes.h"
#ifndef NDEBUG
# include <iostream>
using std::cout;
using std::endl;
#endif
namespace z80emu
{
// return value: number of instructions executed
uint16_t z80::emulate(size_t file_size)
{
reg *rp[] =
{
&regs.bc,
&regs.de,
&regs.hl,
&regs.sp
};
/*
reg *rp2[] =
{
&regs.bc,
&regs.de,
&regs.hl,
&regs.af
};
*/
uint16_t inst = 0;
uint8_t op;
(void)file_size;
for(;;)
{
switch((op = mem[regs.pc]))
{
case NOP:
break;
case LD_BC_IMM:
case LD_DE_IMM:
case LD_HL_IMM:
case LD_SP_IMM:
ld16imm(op >> 4, rp);
break;
case LD_DBC_A:
case LD_DDE_A:
deref16_u8(op >> 4, rp) = regs.af.geth();
break;
case INC_BC:
case INC_DE:
case INC_HL:
case INC_SP:
case DEC_BC:
case DEC_DE:
case DEC_HL:
case DEC_SP:
incdec16(op >> 4, op & 8, rp);
break;
case INC_B:
case INC_C:
case INC_D:
case INC_E:
case INC_H:
case INC_L:
case INC_DHL:
case INC_A:
case DEC_B:
case DEC_C:
case DEC_D:
case DEC_E:
case DEC_H:
case DEC_L:
case DEC_DHL:
case DEC_A:
incdec8(op >> 4, op & 8, op & 1, rp);
break;
case LD_B_IMM:
case LD_C_IMM:
case LD_D_IMM:
case LD_E_IMM:
case LD_H_IMM:
case LD_L_IMM:
case LD_DHL_IMM:
case LD_A_IMM:
ld8imm(op, rp);
break;
case RLCA:
case RRCA:
case RLA:
case RRA:
bitshifta(op);
break;
case EX_AF_AF:
regs.af.exchange();
break;
case ADD_HL_BC:
case ADD_HL_DE:
case ADD_HL_HL:
case ADD_HL_SP:
{
uint8_t f = regs.af.getl();
rp[RP_HL]->add16(rp[op>>4]->get16());
f &= ~(1 << F_N);
/* TODO: set C on carry */
}
break;
case LD_A_DBC:
case LD_A_DDE:
regs.af.seth(deref16_u8(op >> 4, rp));
break;
case DJNZ_IMM:
{
uint8_t off = mem[++regs.pc];
uint8_t b_adj = regs.bc.geth() - 1;
regs.bc.seth(b_adj);
if(b_adj)
reljmp(off);
}
break;
case JR_IMM:
reljmp(mem[++regs.pc]);
break;
case JR_NZ_IMM:
case JR_Z_IMM:
case JR_NC_IMM:
case JR_C_IMM:
ccreljmp(mem[++regs.pc]);
break;
case DAA:
{
uint8_t f = regs.af.getl(),
a = regs.af.geth();
if((a & 0x0f) > 0x09 || (f & (1 << F_H)))
a += 0x06;
if(a & 0x10 && !(regs.af.geth() & 0x10))
f |= 1 << F_H;
if((a & 0xf0) > 0x90 || (f & (1 << F_C)))
{
a += 0x60;
f |= 1 << F_C;
}
f |= parity(a) << F_PV;
}
break;
case CPL:
{
uint8_t f = regs.af.getl(),
a = regs.af.geth();
a = ~a;
f |= 1 << F_H;
f |= 1 << F_N;
regs.af.seth(a);
regs.af.setl(f);
}
break;
default:
#ifndef NDEBUG
cout << std::hex << std::showbase
<< "af: " << regs.af.get16() << endl
<< "af': " << regs.af.getexx() << endl
<< "bc: " << regs.bc.get16() << endl
<< "bc': " << regs.bc.getexx() << endl
<< "de: " << regs.de.get16() << endl
<< "de': " << regs.de.getexx() << endl
<< "hl: " << regs.hl.get16() << endl
<< "hl': " << regs.hl.getexx() << endl
<< "sp: " << regs.sp.get16() << endl
<< "a: " << +regs.af.geth() << endl
<< "f: " << +regs.af.getl() << endl
<< "b: " << +regs.bc.geth() << endl
<< "c: " << +regs.bc.getl() << endl
<< "d: " << +regs.de.geth() << endl
<< "e: " << +regs.de.getl() << endl
<< "h: " << +regs.hl.geth() << endl
<< "l: " << +regs.hl.getl() << endl;
#endif
throw std::logic_error("Unimplemented opcode!");
}
regs.pc++;
inst++;
}
} // z80::emulate
} // namespace z80emu
</code></pre>
<p><code>main.cpp</code>:</p>
<pre><code>#include <cerrno>
#include <limits>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <exception>
#include "z80emu.hpp"
void usage(const char *progname);
int main(int argc, char **argv)
{
if((unsigned)argc - 2 > 0)
{
usage(argv[0]);
return EXIT_FAILURE;
}
std::ifstream infile;
infile.open(argv[1], std::ifstream::in | std::ifstream::binary);
if(!infile.good())
{
std::cerr << "Opening " << argv[1] << " failed: "
<< std::strerror(errno) << std::endl;
return EXIT_FAILURE;
}
size_t file_size;
file_size = infile.seekg(0, infile.end).tellg();
infile.seekg(0, infile.beg);
if(file_size > UINT16_MAX)
{
std::cerr << "Error: File too large." << std::endl;
return EXIT_FAILURE;
}
z80emu::z80 z80;
infile.read((char *)z80.mem, file_size);
try
{
z80.emulate(file_size);
}
catch(std::exception &e)
{
std::cerr << "Emulation failed: " << e.what() << std::endl;
return EXIT_FAILURE;
}
return 0;
}
void usage(const char *progname)
{
std::cout << " Usage: " << progname << " z80-prog" << std::endl;
}
</code></pre>
<p><code>opcodes.hpp</code>:</p>
<pre><code>#ifndef Z80EMU_OPCODES_HPP
#define Z80EMU_OPCODES_HPP 1
namespace z80emu
{
enum opcodes
{
NOP = 0x00,
LD_BC_IMM = 0x01,
LD_DBC_A = 0x02,
INC_BC = 0x03,
INC_B = 0x04,
DEC_B = 0x05,
LD_B_IMM = 0x06,
RLCA = 0x07,
EX_AF_AF = 0x08,
ADD_HL_BC = 0x09,
LD_A_DBC = 0x0a,
DEC_BC = 0x0b,
INC_C = 0x0c,
DEC_C = 0x0d,
LD_C_IMM = 0x0e,
RRCA = 0x0f,
DJNZ_IMM = 0x10,
LD_DE_IMM = 0x11,
LD_DDE_A = 0x12,
INC_DE = 0x13,
INC_D = 0x14,
DEC_D = 0x15,
LD_D_IMM = 0x16,
RLA = 0x17,
JR_IMM = 0x18,
ADD_HL_DE = 0x19,
LD_A_DDE = 0x1a,
DEC_DE = 0x1b,
INC_E = 0x1c,
DEC_E = 0x1d,
LD_E_IMM = 0x1e,
RRA = 0x1f,
JR_NZ_IMM = 0x20,
LD_HL_IMM = 0x21,
LD_DIMM_HL = 0x22,
INC_HL = 0x23,
INC_H = 0x24,
DEC_H = 0x25,
LD_H_IMM = 0x26,
DAA = 0x27,
JR_Z_IMM = 0x28,
ADD_HL_HL = 0x29,
LD_HL_DIMM = 0x2a,
DEC_HL = 0x2b,
INC_L = 0x2c,
DEC_L = 0x2d,
LD_L_IMM = 0x2e,
CPL = 0x2f,
JR_NC_IMM = 0x30,
LD_SP_IMM = 0x31,
LD_DIMM_A = 0x32,
INC_SP = 0x33,
INC_DHL = 0x34,
DEC_DHL = 0x35,
LD_DHL_IMM = 0x36,
SCF = 0x37,
JR_C_IMM = 0x38,
ADD_HL_SP = 0x39,
LD_A_DIMM = 0x3a,
DEC_SP = 0x3b,
INC_A = 0x3c,
DEC_A = 0x3d,
LD_A_IMM = 0x3e,
CCF = 0x3f
}; // enum opcodes
} // namespace z80emu
#endif
</code></pre>
<p><code>z80emu.hpp</code>:</p>
<pre><code>#ifndef Z80EMU_HPP
#define Z80EMU_HPP 1
#if __cplusplus >= 201103L
# include <cstdint>
# include <utility>
using std::uint16_t;
using std::uint8_t;
#else
# include <algorithm>
# include <stdint.h>
#endif
#include <cassert>
#include <cstring>
#include <vector>
namespace z80emu
{
enum cc
{
CC_NZ = 0,
CC_Z = 1,
CC_NC = 2,
CC_C = 3,
CC_PO = 4,
CC_PE = 5,
CC_P = 6,
CC_M = 7
};
enum flags
{
F_C = 0,
F_N = 1,
F_PV = 2,
F_F3 = 3,
F_H = 4,
F_F5 = 5,
F_Z = 6,
F_S = 7
};
enum regpair
{
RP_BC = 0,
RP_DE = 1,
RP_HL = 2,
RP_SP = 3
};
enum bytemask
{
HIGH_BYTE = 0xff00,
LOW_BYTE = 0x00ff
};
enum bitmask
{
BIT0 = 0x01,
BIT1 = 0x02,
BIT2 = 0x04,
BIT3 = 0x08,
BIT4 = 0x10,
BIT5 = 0x20,
BIT6 = 0x40,
BIT7 = 0x80,
BIT0MASK = 0x00,
BIT1MASK = 0x01,
BIT2MASK = 0x03,
BIT3MASK = 0x07,
BIT4MASK = 0x0f,
BIT5MASK = 0x1f,
BIT6MASK = 0x3f,
BIT7MASK = 0x7f,
FULLMASK = 0xff
};
inline bool parity(uint16_t n)
{
uint8_t ctr, bits = sizeof(n) << 3;
for( ctr = 0; bits; ctr++ )
{
bits >>= 1;
n = (n >> bits) ^ (n & ((1u << bits) - 1));
}
return n;
}
// calculate the two's complement of an 8-bit integer
template<typename T>
inline T twoscomp(T val)
{
return ~val + 1;
}
struct reg
{
inline uint16_t get16() const
{
return val;
}
// Allow to get shadow register for debugging purposes
inline uint16_t getexx() const
{
return exx;
}
inline uint8_t get8(bool low) const
{
return low ? getl() : geth();
}
inline uint8_t geth() const
{
return val >> 8;
}
inline uint8_t getl() const
{
return val;
}
inline void set16(uint16_t v)
{
val = v;
}
inline void set8(bool low, uint8_t v)
{
if(low)
setl(v);
else
seth(v);
}
inline void seth(uint8_t h)
{
val = (val & LOW_BYTE) | h << 8;
}
inline void setl(uint8_t l)
{
val = (val & HIGH_BYTE) | l;
}
inline void add16(uint16_t a)
{
val += a;
}
inline void exchange()
{
std::swap(val, exx);
}
reg()
{
val = exx = 0;
}
private:
uint16_t val, exx;
}; // struct reg
#if __cplusplus >= 201103L
static_assert(sizeof(reg) == 4, "sizeof(reg) != 4");
#endif
struct registers
{
reg af;
reg bc;
reg de;
reg hl;
reg ix;
reg iy;
reg sp;
reg wz;
uint16_t pc;
registers()
{
pc = 0;
}
};
struct z80
{
uint8_t *mem;
registers regs;
uint16_t emulate(size_t file_size);
/* return reference to a byte in memory
specified by a 16-bit pointer */
inline uint8_t &deref16_u8(uint8_t idx, reg **tab)
{
return mem[tab[idx]->get16()];
}
// set 8-bit register or memory location
inline void set8(uint8_t idx, uint8_t val, bool low, reg **tab)
{
/* idx is the index for the 16-bit register
if low is true, return the low part of the register,
otherwise return the high part */
switch(idx & 3)
{
case 3:
if(low)
regs.af.seth(val);
else
mem[regs.hl.get16()] = val;
break;
default:
tab[idx]->set8(low, val);
break;
}
}
// get 8-bit register or memory location
inline uint8_t get8(uint8_t idx, bool low, reg **tab)
{
// relatively the same usage as above
switch(idx & 3)
{
case 3:
if(low)
{
return regs.af.geth();
}
else
{
return mem[regs.hl.get16()];
}
default:
return tab[idx]->get8(low);
}
}
// load 16-bit register with immediate
inline void ld16imm(uint8_t idx, reg **tab)
{
/* Do these individually because
of endianness and memory wrapping */
tab[idx]->setl(mem[++regs.pc]);
tab[idx]->seth(mem[++regs.pc]);
}
// load 8-bit register with immediate
inline void ld8imm(uint8_t op, reg **tab)
{
set8(op >> 4, mem[++regs.pc], op & 8, tab);
}
// increment or decrement 16-bit register
inline void incdec16(uint8_t idx, bool dec, reg **tab)
{
tab[idx]->add16(dec ? -1 : 1);
}
// increment or decrement 8-bit register
inline void incdec8(uint8_t idx, bool low, bool dec, reg **tab)
{
uint8_t val = get8(idx, low, tab);
uint8_t f = regs.af.getl() & ~(1 << F_N | 1 << F_PV | 1 << F_Z | 1 << F_H);
dec ? val-- : val++;
f |= dec << F_N;
f |= (val == (0x80 - dec) || !(val + dec)) << F_PV;
f |= !(val + dec) << F_Z;
f |= ((val & (0x10 - dec)) == (0x10 - dec)) << F_H;
set8(idx, val, low, tab);
regs.af.setl(f);
}
// main bitshift operations on a
inline void bitshifta(uint8_t op)
{
uint8_t val = regs.af.geth();
uint8_t f = regs.af.getl();
f &= ~(1 << F_H | 1 << F_N | 1 << F_C);
if(op >> 3 & 1) // rlca, rla
f |= (val & 1) << F_C;
else // rrca, rra
f |= (val >> 7) << F_C;
switch(op >> 3)
{
case 0: // rlca
val = val << 1 | val >> 7;
break;
case 1: // rrca
val = val >> 1 | val << 7;
break;
case 2: // rla
val = val << 1 | !!(f & (1 << F_C));
break;
case 3: // rra
val = val >> 1 | !!(f & (1 << F_C)) << 7;
break;
}
f |= parity(val) << F_PV;
regs.af.seth(val);
regs.af.setl(f);
}
inline bool cond(cc condition_code)
{
uint8_t f = regs.af.getl();
bool z = f & 1 << F_Z,
c = f & 1 << F_C,
pv = f & 1 << F_PV,
s = f & 1 << F_S;
switch(condition_code)
{
case CC_NZ:
return !z;
case CC_Z:
return z;
case CC_NC:
return !c;
case CC_C:
return c;
case CC_PO:
return !pv;
case CC_PE:
return pv;
case CC_P:
return !s;
case CC_M:
return s;
}
assert(!"This should never happen!");
}
inline void reljmp(uint8_t off)
{
if(off & BIT7)
regs.pc -= twoscomp(off);
else
regs.pc += off;
}
inline void ccreljmp(uint8_t off)
{
if(cond(static_cast<cc>((off - 0x20) >> 3)))
reljmp(off);
}
const z80 &operator=(const z80 &rhs)
{
memcpy(mem, rhs.mem, 1 << 16);
regs = rhs.regs;
return *this;
}
z80()
{
mem = new uint8_t[1 << 16]();
}
z80(const z80 &old)
{
mem = new uint8_t[1 << 16];
memcpy(mem, old.mem, 1 << 16);
regs = old.regs;
}
~z80()
{
delete[] mem;
}
}; // struct z80
} // namespace z80emu
#endif
</code></pre>
<p>I'm still looking for some of the same things as last time, but I'll go ahead and go over them again:</p>
<ul>
<li><p>Are there any "more C++" things (that work from C++03 to C++2a) that I can do? Have I started using the language's features adequately?</p></li>
<li><p>Are there any C++ "best practices" that I'm missing here?</p></li>
<li><p>If there are any other miscellaneous things that could be improved, please let me know.</p></li>
</ul>
|
[] |
[
{
"body": "<p>Here are some things that may help you improve your program.</p>\n\n<h2>Decide on a header naming scheme</h2>\n\n<p>The <code>emulate.cpp</code> file has these two lines:</p>\n\n<pre><code>#include \"z80emu.hpp\"\n#include \"opcodes.h\"\n</code></pre>\n\n<p>However the files are labeled in the question as both having <code>.hpp</code> extensions. It's better to pick one or the other and stick with it rather than mixing both. I use <code>.h</code> always.</p>\n\n<h2>Don't use <code>std::endl</code> if you don't really need it</h2>\n\n<p>The difference betweeen <code>std::endl</code> and <code>'\\n'</code> is that <code>'\\n'</code> just emits a newline character, while <code>std::endl</code> actually flushes the stream. This can be time-consuming in a program with a lot of I/O and is rarely actually needed. It's best to <em>only</em> use <code>std::endl</code> when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one. Avoiding the habit of using <code>std::endl</code> when <code>'\\n'</code> will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized.</p>\n\n<h2>Prefer <code>class</code> to <code>struct</code></h2>\n\n<p>The only real difference, of course, is that by default, the members of a <code>struct</code> are public, while the members of a class are private. Still, it's best to keep the internals of a class private to reduce linkage among objects to only what they need. This simplifies the interface and therefore the maintenance. In this case, the <code>z80</code> <code>struct</code> has a great many things, including registers and memory, that would likely be better hidden as internal <code>private</code> data structures.</p>\n\n<h2>Only use <code>inline</code> for small, timing-critical functions</h2>\n\n<p>The overuse of <code>inline</code> is a problem in two respects. First, it makes it harder for readers to read and understand the interface to your class. Second, it has the potential to ruin portability if you intend to maintain a stable ABI. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rf-inline\" rel=\"nofollow noreferrer\">F.5</a> for details.</p>\n\n<h2>Prefer in-class initializers to member initializers</h2>\n\n<p>The code currently includes this:</p>\n\n<pre><code>struct registers\n{\n reg af;\n reg bc;\n reg de;\n reg hl;\n reg ix;\n reg iy;\n reg sp;\n reg wz;\n uint16_t pc;\n registers()\n {\n pc = 0;\n }\n};\n</code></pre>\n\n<p>This would be better written with no explicit constructor at all:</p>\n\n<pre><code>struct registers\n{\n reg af;\n reg bc;\n reg de;\n reg hl;\n reg ix;\n reg iy;\n reg sp;\n reg wz;\n uint16_t pc = 0;\n};\n</code></pre>\n\n<p>The same applies to the underlying <code>reg</code>. See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-in-class-initializer\" rel=\"nofollow noreferrer\">C.48</a> for details.</p>\n\n<h2>Separate interface from implementation</h2>\n\n<p>The interface is the part in the <code>.h</code> file and the implementation is in the <code>.cpp</code> file. Users of this code should be able to read and understand everything they need from the interface file. That means, among other things, that only <code>#include</code>s essential to being able to understand the interface should be in the <code>.h</code> file. In this case, much of what is currently in the <code>z80emu.h</code> file should actually be moved into a <code>z80emu.cpp</code> file and the implementation of <code>z80::emulate</code> should be moved from <code>emulate.cpp</code> to <code>z80emu.cpp</code>.</p>\n\n<h2>Strive for a minimal sufficient interface</h2>\n\n<p>The code currently contains these lines:</p>\n\n<pre><code>// calculate the two's complement of an 8-bit integer\ntemplate<typename T>\ninline T twoscomp(T val)\n{\n return ~val + 1;\n}\n</code></pre>\n\n<p>There are a couple of problems with this. First, it's only used internally in a single location. Second, there's not really a need for it to be a template, since both the comment and the usage indicate that it's only intended for use with a <code>uint8_t</code> type.</p>\n\n<h2>Use only necessary <code>#include</code>s</h2>\n\n<p>The <code>#include <vector></code> line in <code>z80emu.h</code> is not necessary and can be safely removed. It would be good to review all includes to make sure that only the required ones are present.</p>\n\n<h2>Initialize variables with declaration</h2>\n\n<p>The code currently has these lines:</p>\n\n<pre><code>std::ifstream infile;\n\ninfile.open(argv[1], std::ifstream::in | std::ifstream::binary);\nif(!infile.good())\n{\n std::cerr << \"Opening \" << argv[1] << \" failed: \"\n << std::strerror(errno) << std::endl;\n return EXIT_FAILURE;\n}\n</code></pre>\n\n<p>That's not wrong, per se, but there are more idiomatic ways to write that. First, in C++, it's generally good practice to initialize variables as they are declared so that they're immediately useful. In this case, that means combining lines:</p>\n\n<pre><code>std::ifstream infile{argv[1], std::ifstream::in | std::ifstream::binary};\n</code></pre>\n\n<p>Here I am using the C++11 style of initialization, which I highly recommend, but the same can be done with older C++ compilers with slightly different syntax. </p>\n\n<p>The second thing is that instead of this:</p>\n\n<pre><code>if(!infile.good())\n</code></pre>\n\n<p>We can use the more idiomatic:</p>\n\n<pre><code>if (!infile) \n</code></pre>\n\n<p>The result is the same, but the latter style is less verbose and more typical of modern style.</p>\n\n<h2>Avoid C-style casts</h2>\n\n<p>The code has these two lines:</p>\n\n<pre><code>z80emu::z80 z80;\ninfile.read((char *)z80.mem, file_size);\n</code></pre>\n\n<p>One problem with this is the C-style cast of <code>z80.mem</code> to a <code>char *</code> but the the more fundamental problem is that we're reaching into the innards of the <code>z80</code> object. Better would be to create a constructor that accepts a memory chunk and size.</p>\n\n<h2>Check return values for errors</h2>\n\n<p>In the lines quoted above, <code>infile.read()</code> simply throws away the return value. That's not a good idea because that function returns the number of bytes actually read. It's better to always check that you're actually getting what you expected from I/O functions or memory allocation functions and take the appropriate error handling actions otherwise.</p>\n\n<h2>Rethink the class design</h2>\n\n<p>The <code>opcodes</code> <code>enum</code> is currently just a list of numbers with associated names. Better, in my view, would be to have an <code>instruction</code> class that would encapsulate both the opcode and the behavior. This is the very definition of object-oriented programming, and would help a lot here. To give you some ideas about how this might look consider <a href=\"https://codereview.stackexchange.com/questions/115118/mac1-simulator-debugger\">MAC1 simulator/debugger</a> and <a href=\"https://codereview.stackexchange.com/questions/122385/toyvm-a-small-and-simple-virtual-machine-in-c-fizzbuzz-demonstration/122399#122399\">ToyVM - a small and simple virtual machine in C + FizzBuzz demonstration</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T12:03:55.243",
"Id": "456380",
"Score": "0",
"body": "Ah, shoot. Renaming `opcodes.h` to `opcodes.hpp` was a last-minute change before posting. I forgot to change the `#include`. It was originally only a `.h` because it only had `#define` in it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T12:06:48.010",
"Id": "456381",
"Score": "0",
"body": "I knew I should've tagged c++98. In-structure initializers are new in C++11."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T12:08:52.490",
"Id": "456382",
"Score": "0",
"body": "That comment on `twoscomp` is outdated. It'll need to be used on the 16-bit registers, too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T12:26:28.740",
"Id": "456386",
"Score": "0",
"body": "You will be denying yourself many language improvements if you use only C++98. A lot has happened in C++ in the last two decades!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T12:27:34.050",
"Id": "456387",
"Score": "0",
"body": "What's the last compiler (for say, Linux) that required C++98?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T13:52:12.133",
"Id": "456400",
"Score": "1",
"body": "By gcc 4.8.1 there was a [full c++11 implementation](https://gcc.gnu.org/projects/cxx-status.html#cxx11) and that was released on [May 31, 2013](https://gcc.gnu.org/releases.html). Many of the individual C++11 features were implemented in versions earlier than that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T17:46:03.850",
"Id": "456448",
"Score": "1",
"body": "That's enough for me. `std::array`, here I come!"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T02:39:34.943",
"Id": "233455",
"ParentId": "233431",
"Score": "3"
}
},
{
"body": "<p>This is a supplement to the excellent <a href=\"/a/233455/75307\">answer by Edward</a>.</p>\n<h1>Care with namespaces</h1>\n<p>Currently, the header has</p>\n<blockquote>\n<pre><code>using std::uint16_t;\nusing std::uint8_t;\n</code></pre>\n</blockquote>\n<p>I recommend not bringing these into the global namespace in a header - that affects every translation unit that uses the header, which can be a nuisance in larger programs (particularly when not all written by the same author). Instead, if you really feel that <code>std::</code> is too much to type and to read, bring them into a smaller scope (e.g. within a function, or at worst into global scope in individual, non-header, files).</p>\n<p>There are a few uses of unqualified names from the <code>std</code> namespace - these should be portably written <code>std::size_t</code>, <code>std::memcpy</code>, etc. You've probably only compiled on systems that use their freedom to put copies of Standard Library identifiers into the global namespace, but that's not required, and you can't depend on it.</p>\n<h1>Includes</h1>\n<p>I recommend re-ordering these includes:</p>\n<blockquote>\n<pre><code>#include <cerrno>\n#include <limits>\n#include <cstdlib>\n#include <cstring>\n#include <fstream>\n#include <iostream>\n#include <exception>\n#include "z80emu.hpp"\n</code></pre>\n</blockquote>\n<p>If we put our own includes before the standard library headers, we stand a better chance of identifying accidental dependencies:</p>\n<pre><code>#include "z80emu.hpp"\n\n#include <cerrno>\n#include <cstdlib>\n#include <cstring>\n#include <exception>\n#include <fstream>\n#include <iostream>\n#include <limits>\n</code></pre>\n<p>I'm pretty sure we don't use <code><limits></code>, and really ought to have <code><cstdint></code> instead (for <code>UINT16_MAX</code> and the like).</p>\n<h1>Error reporting</h1>\n<p>Most error messages are correctly sent to <code>std::cerr</code>. But when we call <code>usage()</code> to indicate invocation errors, that's sent to <code>std::cout</code>. We should pass the stream to this function, too, so we can make it print to the error stream when it's shown as an error (rather than specifically requested, when we add support for <code>--help</code> argument).</p>\n<pre><code>static void usage(std::ostream& os, const char *progname)\n{\n os << " Usage: " << progname << " z80-prog\\n";\n}\n</code></pre>\n<p>I also recommend static linkage here, as this function shouldn't need to be accessible from other translation units.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T08:32:08.307",
"Id": "233461",
"ParentId": "233431",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "233455",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T20:58:27.653",
"Id": "233431",
"Score": "3",
"Tags": [
"c++",
"beginner",
"emulator"
],
"Title": "Less incomplete Z80 emulator written in C++"
}
|
233431
|
<p>I'm writing a Rust library to facilitate implementing the following C API in Rust. That is, it should be possible to create a Rust-idiomatic implementation by depending on my wrapper library.</p>
<pre><code>// Called first. Implementer may allocate memory here.
void init();
// For each input: start is called, then run is called repeatedly, finally stop
// is called. The input pointer is valid until the end of stop.
void start(const char* input, size_t size);
void run();
void stop();
// Called last. Implementer should free all allocated memory.
void deinit();
</code></pre>
<p>To clarify the required order of calls, the following example code calls the API as specified:</p>
<pre><code>#include <stdlib.h>
#include <string.h>
#include "api.h"
void run_input(const char* s) {
size_t size = strlen(s);
char* data = malloc(size);
memcpy(data, s, size);
start(data, size);
run();
run();
stop();
free(data);
}
int main(int argc, char** argv) {
init();
run_input("abcde");
run_input("xyz");
deinit();
}
</code></pre>
<p><em>Note</em>: neither the API nor the code calling it are mine. Only the Rust wrapper code (below) is mine. The API is well established with multiple existing implementations and callers; I cannot change it.</p>
<p>Because the lifetime of each <code>input</code> spans multiple calls into Rust, it's difficult to ensure the implementation has access to it for right lifetime. I also want to support implementations which persist mutable data between different inputs. Here is my current solution:</p>
<pre class="lang-rust prettyprint-override"><code>//! A helper library for implementing the C API. The implementer should
//! implement the Runner and Factory traits:
//! struct RunnerImpl;
//! impl Runner for RunnerImpl {
//! // ...
//! }
//! struct FactoryImpl;
//! impl Factory for FactoryImpl {
//! // ...
//! }
//! and call the macro:
//! factory!(FactoryImpl);
use std::borrow::BorrowMut;
use std::mem::transmute;
use std::slice;
pub trait Runner {
fn run(&mut self);
fn stop(&mut self);
}
pub trait Factory {
fn default() -> Self
where
Self: Sized;
fn start_runner<'a>(&'a mut self, input: &'a [u8]) -> Box<dyn Runner + 'a>;
}
struct Wrapper {
factory: Box<dyn Factory>,
runner: Option<Box<dyn Runner>>,
}
impl Wrapper {
fn new<F: Factory + 'static>() -> Self {
Wrapper {
factory: Box::new(F::default()),
runner: None,
}
}
fn runner(&mut self) -> &mut (dyn Runner + 'static) {
self.runner.as_mut().unwrap().borrow_mut()
}
}
static mut INSTANCE: *mut Wrapper = 0 as *mut _;
unsafe fn instance() -> &'static mut Wrapper {
assert_ne!(INSTANCE, 0 as *mut _);
&mut *INSTANCE
}
#[doc(hidden)]
pub unsafe fn init_impl<F: Factory + 'static>() {
INSTANCE = Box::into_raw(Box::new(Wrapper::new::<F>()));
}
#[doc(hidden)]
#[no_mangle]
pub unsafe extern "C" fn start(input: *const libc::c_char, size: libc::size_t) {
// The actual lifetime of input is until the stop() call. Because this spans multiple FFI calls
// into rust code, the lifetime can't be expressed in rust. Therefore pretend it is 'static. In
// stop() we drop Runner, preventing the reference from leaking (?).
// The Factory reference should have the same lifetime, and again we pretend it is 'static.
// The wrapper doesn't access factory while running, so it's safe to pretend that runner has
// exclusive access to it.
let input = slice::from_raw_parts(input as *const u8, size);
let f: &mut dyn Factory = instance().factory.borrow_mut();
let fs: &'static mut dyn Factory = transmute(f);
instance().runner = Some(fs.start_runner(input));
}
#[doc(hidden)]
#[no_mangle]
pub unsafe extern "C" fn run() {
instance().runner().run()
}
#[doc(hidden)]
#[no_mangle]
pub unsafe extern "C" fn stop() {
instance().runner().stop();
instance().runner = None;
}
#[doc(hidden)]
#[no_mangle]
pub unsafe extern "C" fn deinit() {
std::mem::drop(Box::from_raw(INSTANCE));
INSTANCE = 0 as *mut _;
}
#[macro_export]
macro_rules! factory {
($factory: path) => {
#[doc(hidden)]
#[no_mangle]
pub unsafe extern "C" fn init() {
$crate::init_impl::<$factory>()
}
};
}
</code></pre>
<p>My intention is that each <code>Runner</code> can hold a reference to the <code>Factory</code> to persist data between inputs, and also hold a reference to <code>input</code> for use in <code>run()</code> and <code>stop()</code>, but can't leak <code>input</code> beyond its lifetime.</p>
<p>I mainly want to know whether the lifetime munging is safe. <strong>Assuming the API is called as specified, can an implementation of <code>Runner</code> and <code>Factory</code> cause use-after-free access to <code>input</code>? Can the transmute cause any trouble?</strong></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T21:00:30.697",
"Id": "456468",
"Score": "0",
"body": "Can you provide an example of usage of this API?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T21:08:23.210",
"Id": "456470",
"Score": "0",
"body": "Can there only be a single instance? Regardless, you should return a pointer from `init` and require your user to pass that pointer to `start`, `run`, `stop`, and `deinit`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T02:25:07.890",
"Id": "456503",
"Score": "0",
"body": "@PitaJ IIUC you are suggesting changes to the C API. I can't change that part, it's given. Only the Rust code is mine. Are you asking for example code calling the C API, or example code implementing the Runner and Factory traits?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T18:42:56.977",
"Id": "456620",
"Score": "0",
"body": "Just to confirm: you absolutely can't modify the C API, is that correct? I was asking for an example of C API usage."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-08T20:28:33.367",
"Id": "456768",
"Score": "0",
"body": "@PitaJ I added to the question example calling code and an explicit note that I can't change the API. btw I put the \"api\" tag on the question because I view the Runner and Factory traits as an API also; they specify the interface that the user of my wrapper must implement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-09T05:54:52.753",
"Id": "456806",
"Score": "0",
"body": "Here's my poke at it, but I didn't use the overcomplicated Trait stuff you did, as I can't see a good reason to do so. If that isn't a problem, I will expand on the reasoning behind my choices in an answer. https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=607bb21ae8b4261c0b5e5ded0e6fdfc9"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-10T00:08:35.430",
"Id": "456958",
"Score": "0",
"body": "@PitaJ thanks for having a look. I used traits because the wrapper library should be re-usable by multiple implementations (which I guess would need to be in separate libraries). This is what I meant by \"a Rust library to facilitate implementing...\"; I'll try to make it a bit more explicit in my question."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T20:59:40.020",
"Id": "233432",
"Score": "3",
"Tags": [
"api",
"rust"
],
"Title": "Wrapping a C API to be implemented in rust"
}
|
233432
|
<p>I am working on a very simple 3D vector class, which I can use to set up and access three-dimensional vectors using a wrapper around std::vector. It's not intended to be foolproof, just good enough to get by.</p>
<p>The main goal is to make it simple to use, explicit and easy to debug. I have often accidentally put in out-of-bounds coordinates or given invalid dimensions, so this at least can catch those cases and report back in an understandable way.</p>
<p>Hence all the debug prints, should it be used improperly for any reason. </p>
<p>The only thing I am unhappy with is <code>resize</code>. I would not have included it (too dangerous), but found some cases in my code where I could not set up its dimensions in advance, like if it was a member of another class. In those cases, it needed a default and resize option. </p>
<p>Since resize does all the checking, I just reused it for the constructor rather than copy-paste all that. </p>
<p>I'm still somewhat new to C++ and was taught from a C background, so I'm always looking to improve my style. </p>
<pre><code>template <typename T>
class Vector3D
{
private:
std::vector<T> data;
public:
// Dimensions in each direction
unsigned long xDim;
unsigned long yDim;
unsigned long zDim;
// Constructor
Vector3D(unsigned long _xDim, unsigned long _yDim, unsigned long _zDim)
{
resize(_xDim, _yDim, _zDim);
}
T& at(unsigned long _x, unsigned long _y, unsigned long _z)
{
if (_x >= xDim || _y >= yDim || _z >= zDim)
{
std::cerr << "Position: " << x << ", " << y << ", " << z << std::endl;
std::cerr << "Vector width: " << xDim << ", " << yDim << ", " << zDim
<< std::endl;
std::cerr << "Invalid indices into 3D vector" << std::endl;
// Throw an exception here..
}
unsigned position = _x + (_y * xDim) + (_z * xDim * yDim);
return data[position];
}
/**
* @brief Default constructor. Dangerous to use, should use the explicit one
* if at all possible.
*/
Vector3D()
{
xDim = 0;
yDim = 0;
zDim = 0;
}
/**
* @brief Re-sizes a 3D vector with new dimensions.
* @details This is a nuclear option. You're re-sizing the dimensions of a
* three-dimensional vector. Do not expect results to be good. Only use this
* explicitly when initialization is impossible up-front.
* @param _xDim, _yDim, _zDim - The new dimensions of the vector
*/
void resize(unsigned _xDim, unsigned _yDim, unsigned _zDim)
{
if (_xDim == 0 || _yDim == 0 || _zDim == 0)
{
// Throw an exception here...
}
xDim = _xDim;
yDim = _yDim;
zDim = _zDim;
// Resize could fail, especially if the dimensions are too large. Just print
// out the dimensions in x,y,z, number of elements and total bytes just in
// case
try
{
data.resize(xDim * yDim * zDim);
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
std::cerr << "Error allocating 3D Vector. Dimensions: ";
std::cerr << "X: " << xDim << " Y: " << yDim << " Z: " << zDim
<< std::endl;
std::cerr << "Number of elements: " << (xDim * yDim * zDim)
<< std::endl;
std::cerr << "Size in bytes: " << (xDim * yDim * zDim) * sizeof(T)
<< std::endl;
// Throw an exception here...
}
}
unsigned long getSize() { return data.size(); }
// Should only be used if the vector is storing pointers to some data
void freeData()
{
for (unsigned long i = 0; i < data.size(); i++)
{
free(data[i]);
}
}
// A couple methods to get the real vector, if they want it.
std::vector<T>& getData() { return data; }
const std::vector<T>& getData() const { return data; }
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T21:52:20.327",
"Id": "456302",
"Score": "0",
"body": "throw an exception here :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T22:05:44.157",
"Id": "456305",
"Score": "0",
"body": "In my own code there's a macro that calls some home-made assertion class, I didn't want to fiddle with all that but I also wasn't sure what it was doing under the hood, so I left it out."
}
] |
[
{
"body": "<p>Quick comments:</p>\n\n<ol>\n<li>unsigned long => size_t everywhere ... it's the same, but that's the alias for this job</li>\n<li>check for _xDim, _yDim, _xDim < 0 ... underflow is also undefined behvaiour ;-)</li>\n<li>implement operator[] for those who are confident about their bounds, or for faster release builds. It's not trivial for multiple dims, <a href=\"https://stackoverflow.com/a/6969904/1087626\">check here</a>. </li>\n<li>free data is flawed. You need to look into unique_pointer or shared pointer which will do this stuff for you. </li>\n<li>Resize? It is actually required? Can you not auto-resize during at()? unless you want that as a code check during development. </li>\n<li>Consider <a href=\"http://eigen.tuxfamily.org/index.php?title=Main_Page\" rel=\"nofollow noreferrer\">a library</a></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T17:25:31.600",
"Id": "456444",
"Score": "0",
"body": "Since the dimensions are passed as unsigned values, checking if they are < 0 will always return false, right? Also, I'm confused on what you meant be resize(). I ran into cases where (for like if I had a Vector3D as a member of another class) it could not be initialized with its dimensions. So I needed to leave a default constructor for it as size zero, then a resize for those cases. I've heard of Eigen, but it's way too large and complex for my needs. I'd prefer to hand-roll if possible. What did you mean by unique or shared pointers, how would that help in this case?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T17:26:05.187",
"Id": "456445",
"Score": "0",
"body": "Also how does operator[] allow \"faster release builds\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T21:23:35.753",
"Id": "456472",
"Score": "0",
"body": "@TylerShellberg Hmm, yes. Re unsigned > 0; You're right, sort of. But ... well I guess that's why they say don't do arithmetic with (which you no doubt will be in the calling code) and then force the result into an unsigned type to \"eliminate negatives\". This is a complex problem. Be careful. It's quite possible that your calling code will accidentally produce a negative which then gets cast into goodness know what in the unsigned _x, _y, _z..etc"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T21:27:36.437",
"Id": "456474",
"Score": "0",
"body": "@TylerShellberg Re `operator[]`: On `std::vector` this is faster than `::at()` because it is not bounds checked. You might want to model it the same way... or used checks with a `#define NDEBUG` type flag for Debug builds only."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T21:34:27.910",
"Id": "456476",
"Score": "0",
"body": "@TylerShellberg Re resize: My point was: \"Do you really want to resize manually\"? It seems weird to me. Either the vector3D has a fixed size which is know on construction or it doesn't. \n\nIf you don't know the size at time of Default Construction as member of another class, then don't default construct it in that other class. It's hard to say what the right solution to that is without seeing the application, but the time, purpose and scope of use will come into it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T09:25:51.200",
"Id": "456564",
"Score": "0",
"body": "For your resize problem, you could declare a `std::optional<Vector3D> maybeVector = std::nullopt;` \n in your other class and then construct the Vector3D later when the size is known. -> full sizing will happen at construction?! see here: https://www.bfilipek.com/2018/05/using-optional.html : \"To perform lazy-loading of resources.\n\n For example, a resource type has no default constructor, and the construction is substantial. So you can define it as std::optional<Resource> (and you can pass it around the system), and then load only if needed later.\""
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T00:34:44.810",
"Id": "233444",
"ParentId": "233435",
"Score": "1"
}
},
{
"body": "<p><code>getSize</code> seems a bit redundant (since you provide a way to get to the underlying vector, and that can be used to get the size). Since <code>Vector3D</code> doesn't have one size, what would that number mean?</p>\n\n<p>Add a way to get all 3 dimensions.</p>\n\n<p>The <code>getData</code> methods are dangerous, since they give access to the underlying vector that would allow the user to change the size of it.</p>\n\n<p>If you are concerned about the dangers of having a resize function, you could have <code>resize</code> throw an exception if the <code>Vector3D</code> already has a size (<code>data</code> is not empty). Then possibly rename it to <code>setsize</code> or <code>init</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-04T01:25:32.387",
"Id": "235051",
"ParentId": "233435",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-04T21:43:20.197",
"Id": "233435",
"Score": "2",
"Tags": [
"c++",
"vectors"
],
"Title": "A simple 3D Wrapper class around std::vector"
}
|
233435
|
<p>I found it useful to execute multiple reads in parallel using a set of my extension methods for <code>TaskFactory</code>, which could be used as:</p>
<pre><code>static async Task Main(string[] args)
{
var (r1, r2, r3, r4) = await Task.Factory.StartNew(
Read1Async, Read2Async, Read3Async, Read4Async);
async Task<int> Read1Async() => /* cut as not relevant */;
async Task<string> Read2Async() => /* cut as not relevant */;
async Task<long> Read3Async() => /* cut as not relevant */;
async Task<double[]> Read4Async() => /* cut as not relevant */;
}
</code></pre>
<p>The actual helper code is:</p>
<pre><code>public static class TaskFactoryExtensions
{
public async static Task<(T1, T2)> StartNew<T1, T2>(
this TaskFactory taskFactory,
Func<Task<T1>> action1,
Func<Task<T2>> action2)
{
var task1 = Task.Run(action1);
var task2 = Task.Run(action2);
return (await task1, await task2);
}
public async static Task<(T1, T2, T3)> StartNew<T1, T2, T3>(
this TaskFactory taskFactory,
Func<Task<T1>> action1,
Func<Task<T2>> action2,
Func<Task<T3>> action3)
{
var task1 = Task.Run(action1);
var task2 = Task.Run(action2);
var task3 = Task.Run(action3);
return (await task1, await task2, await task3);
}
public async static Task<(T1, T2, T3, T4)> StartNew<T1, T2, T3, T4>(
this TaskFactory taskFactory,
Func<Task<T1>> action1,
Func<Task<T2>> action2,
Func<Task<T3>> action3,
Func<Task<T4>> action4)
{
var task1 = Task.Run(action1);
var task2 = Task.Run(action2);
var task3 = Task.Run(action3);
var task4 = Task.Run(action4);
return (await task1, await task2, await task3, await task4);
}
}
</code></pre>
<p>It just saves on typing...</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T00:59:37.610",
"Id": "456318",
"Score": "0",
"body": "I just came across in the VTC queue, LCC."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T01:02:57.480",
"Id": "456321",
"Score": "0",
"body": "Would `Task.WaitAll` work here? https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.waitall?view=netframework-4.8"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T01:07:38.430",
"Id": "456322",
"Score": "0",
"body": "@alexyorke Nope, you will not get the results. And only `Task` or `Task<T[]>` could be returned from `Task.WhenAll()`. Here we could work with multiple datatypes being returned as a tuple in a single line of code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T01:15:51.780",
"Id": "456324",
"Score": "0",
"body": "@alexyorke We could use it in the extension method implementation, but it adds one extra line without helping anyhow and could be dangerous (a blocking call). TPL was never been updated after tuple introduction, so we are alone in making helpers like that :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T01:19:20.130",
"Id": "456325",
"Score": "0",
"body": "@DmitryNogin thank you for the clarification; I will have to read up on the documentation"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T16:33:05.750",
"Id": "456606",
"Score": "1",
"body": "that is strange to use separate thread for async read operation ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T16:54:11.900",
"Id": "456608",
"Score": "0",
"body": "@Disappointed It is a very generic mechanism. `Task.Run` usage allows to keep a preexisting `Task.Factory.StartNew` semantics. Throwing an exception from a synchronous part of `Read2Async` (before the very first `await`) will otherwise prevent `Read3Async` and `Read4Async` invocation and unwind the stack in a situation with no `await` like `var task = Task.Factory.StartNew(Read1Async, Read2Async)` - not what one would expect from `StartNew`."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T00:36:30.053",
"Id": "233445",
"Score": "2",
"Tags": [
"c#",
"task-parallel-library"
],
"Title": "Execute asynchronous read in parallel"
}
|
233445
|
<p>I wrote a simple Python 3 program that takes data from either a file or standard input and xor encrypts or decrypts the data. By default, the output is encoded in base64, however there is a flag for disabling that <code>--raw</code>. It works as intended except when I am using the raw mode, in which case an extra line and some random data is appended to the output when decrypting xor data.</p>
<pre><code>#!/usr/bin/env python3
from itertools import cycle
import argparse
import base64
import re
def xor(data, key):
return ''.join(chr(ord(str(a)) ^ ord(str(b))) for (a, b) in zip(data, cycle(key)))
# check if a string is base64 encoded.
def is_base64(s):
pattern = re.compile("^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$")
if not s or len(s) < 1:
return False
else:
return pattern.match(s)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--infile', type=argparse.FileType('r'), default='-', dest='data', help='Data to encrypt'
'or decrypt')
parser.add_argument('-r', '--raw', dest='raw', default=False, action='store_true', help='Do not use base64 encoding')
parser.add_argument('-k', '--key', dest='key', help='Key to encrypt with', required=True)
args = parser.parse_args()
data = args.data.read()
key = args.key
raw = args.raw
if raw:
ret = xor(data, key)
print(str(ret))
else:
if is_base64(data):
# print('is base64')
decoded = base64.b64decode(data).decode()
ret = xor(decoded, key)
print(ret)
else:
# print('is not base64')
ret = xor(data, key)
encoded = base64.b64encode(bytes(ret, "utf-8"))
print(encoded.decode())
</code></pre>
<p>When running without the <code>--raw</code> flag, everything performs as intended:</p>
<pre><code>$ echo lol|./xor.py -k 123
XV1fOw==
echo lol|./xor.py -k 123 |./xor.py -k 123
lol
</code></pre>
<p>However, if I disable base64, something rather odd happens. It's easier to demonstrate then it is to explain:</p>
<pre><code>$ echo lol|./xor.py -k 123 -r |./xor.py -k 123 -r
lol
8
</code></pre>
<p>Does anyone know why I am seeing the character <code>8</code> appended to the output of xor decrypted data? I have a c program called <a href="https://gist.github.com/darkerego/f7880ee8878b64a9f6ce945d7cf98aa4" rel="nofollow noreferrer">xorpipe</a> that I use for this exact use case, and it does not suffer this bug. I wanted to rewrite it in Python.</p>
<p>I am looking for other constructive criticism, suggestions, or reviews as well. Particular, I would like argparse to be able to determine whether the supplied input is either a file, string, or data piped from standard input. This is easy to accomplish bash or C, but I am not sure how best to do this in Python.</p>
|
[] |
[
{
"body": "<blockquote>\n <p>Does anyone know why I am seeing the character 8 appended to the output of xor decrypted data?</p>\n</blockquote>\n\n<p>The statement <code>echo lol</code> pipes <code>lol\\n\\r</code> to Python, which encodes the line breaks as <code>;_</code> which is decoded into an <code>8</code>. Unfortunately <code>echo -n</code> doesn't work here but adding <code>.strip()</code> to the input data in the Python script fixes this issue.</p>\n\n<p>PEP8 is Python's internal coding standards which specify how line breaks and code should be structured: <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">https://www.python.org/dev/peps/pep-0008/</a> . The guide is very long; you can use <code>autopep8</code> to auto-format the code.</p>\n\n<pre><code> if raw:\n ret = xor(data, key)\n print(str(ret))\n else:\n if is_base64(data):\n # print('is base64')\n decoded = base64.b64decode(data).decode()\n ret = xor(decoded, key)\n print(ret)\n else:\n # print('is not base64')\n ret = xor(data, key)\n encoded = base64.b64encode(bytes(ret, \"utf-8\"))\n print(encoded.decode())\n</code></pre>\n\n<p>I would simplify the nested if-statements and add a <code>return</code> to <code>print(str(ret))</code> then the <code>is_base64</code> could be unindented, or I would set a variable called <code>decoded</code> to the final string to print, then print it out at the end of the <code>if/elif</code> loop.</p>\n\n<p><code>is_base64(s)</code> could just run <code>base64.b64decode(data).decode()</code> and return <code>False</code> if any exceptions were thrown during decoding instead of the regex.</p>\n\n<p>I would remove the commented out code such as <code># print('is base64')</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T02:57:06.450",
"Id": "456334",
"Score": "0",
"body": "Ah, that is really obvious now that you have pointed it out. </facepalm> Thanks, that solves the issue!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T03:02:33.603",
"Id": "456335",
"Score": "0",
"body": "The reason why I am using a regex to check whether or not the data is base64 or not is because I was having issues with the method of decoding and then re-encoding the input, and the regex seemed to work better, so out of all the solutions I found in this thread that method seemed to work best for this case. https://stackoverflow.com/questions/12315398/check-if-a-string-is-encoded-in-base64-using-python - i don't remember exactly what the issue was, I will double check that though. Thank you very much."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T01:44:01.127",
"Id": "233450",
"ParentId": "233448",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "233450",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T01:27:56.083",
"Id": "233448",
"Score": "0",
"Tags": [
"python",
"algorithm",
"python-3.x",
"console"
],
"Title": "Python 3 Simple Xor Pipe/CLI Program"
}
|
233448
|
<p>I don't like this function. Looks too imperative.</p>
<p>It takes two sorted lists and returns a sorted intersection of the two lists. There is an implicit assumption that there are no duplicate elements in either list.</p>
<p>Please don't suggest converting (even one of) the arguments to <code>set</code>, or using some sort of library function. This is a single-pass O(n+m) time, O(1) auxiliary space algorithm, and I want to keep it that way.</p>
<pre><code>def sorted_lists_intersection(lst1, lst2):
i1 = 0
i2 = 0
len1 = len(lst1)
len2 = len(lst2)
intersection = []
while i1 < len1 and i2 < len2:
while lst1[i1] < lst2[i2]:
i1 += 1
if i1 == len1:
return intersection
while lst2[i2] < lst1[i1]:
i2 += 1
if i2 == len2:
return intersection
if lst1[i1] == lst2[i2]:
intersection.append(lst1[i1])
i1 += 1
i2 += 1
return intersection
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-17T20:32:04.450",
"Id": "458087",
"Score": "0",
"body": "You can still use a `set` or `dict` and maintain runtime of O(n+m). So what's the reason behind not using them? Is it to not use extra space?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-17T23:13:29.727",
"Id": "458104",
"Score": "0",
"body": "Basically yes. There may be other implications of using a `set` or `dict`, such as maintaining sortedness (although this one could be solved easily by something like `filter(x, set(y))`). Besides, I wanted to see a more elegant way to write this specific function (without sets), since I found the original code too much like C/C++/etc.; too unpythonic."
}
] |
[
{
"body": "<p>The code seems to be too complicated. There are a few ways it can be optimized:</p>\n\n<pre><code>if i1 == len1:\n return intersection\n</code></pre>\n\n<p>and</p>\n\n<pre><code>if i2 == len2:\n return intersection\n</code></pre>\n\n<p>return statements can be expressed as <code>yield</code> so that the return for the entire array is not required; it returns constantly. However, this condition needs to be there otherwise it won't work; it can be refactored into incrementing both pointers step-wise instead, which eliminates boundary checks and <code>intersection.append(lst1[i1])</code>.</p>\n\n<p>With these rules applied, the following is the refactored version:</p>\n\n<pre><code>def intersect(a, b):\n i = 0\n j = 0\n while i < len(a) and j < len(b):\n if a[i] > b[j]:\n j += 1\n elif a[i] < b[j]:\n i += 1\n else:\n yield a[i]\n j += 1\n i += 1\n</code></pre>\n\n<p>Depending on readability, it can be expressed more tersely as:</p>\n\n<pre><code>def intersect(a, b):\n i = 0\n j = 0\n while i < len(a) and j < len(b):\n if a[i] == b[j]:\n yield a[i]\n i, j = i + (a[i] <= b[j]), j + (a[i] >= b[j])\n</code></pre>\n\n<p>This works because boolean operators return <code>0</code> if false and <code>1</code> if true. Since the failure conditions will add <code>0</code>, it won't affect the result. The variables have to be assigned together on one line as it has to use <code>i</code> and <code>j</code> copies for array indexing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T02:28:44.530",
"Id": "456331",
"Score": "0",
"body": "@kyrill thank you for your suggestions; I have updated my answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T02:30:00.933",
"Id": "456332",
"Score": "0",
"body": "Note my first suggestion"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T02:33:43.283",
"Id": "456333",
"Score": "0",
"body": "And what do you mean by \"return statements can be expressed as yield\" ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T03:14:30.747",
"Id": "456338",
"Score": "0",
"body": "@kyrill The `yield` operator \"returns\" a value when called; the function can then be wrapped in a `list()` to get the same \"behavior| as returning/appending a list in a loop"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T03:17:37.470",
"Id": "456339",
"Score": "0",
"body": "I must say I find your new `while` condition quite confusing..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T03:18:25.793",
"Id": "456340",
"Score": "0",
"body": "@kyrill I removed it a few minutes ago; it was not working for some inputs"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-07T00:07:59.430",
"Id": "456644",
"Score": "2",
"body": "While the terse function works I don't think it's worth the extra programmer overhead in understanding it to save 5 lines of code."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T02:06:46.477",
"Id": "233453",
"ParentId": "233449",
"Score": "9"
}
},
{
"body": "<p>While you don't want alternative solutions, you should take a look at the data in your specific usecase. As an example, for some randomly generated input (both lists of length ~600) on my machine (Python 3.6.9, GCC 8.3.0), your function takes</p>\n\n<pre><code>In [18]: %timeit sorted_lists_intersection(a, b)\n179 µs ± 1.19 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n</code></pre>\n\n<p>The function defined in the <a href=\"https://codereview.stackexchange.com/a/233453/98493\">answer</a> by <a href=\"https://codereview.stackexchange.com/users/8149/alexyorke\">@alexyorke</a>, while more readable IMO, takes a bit longer:</p>\n\n<pre><code>In [16]: %timeit list(intersect(a, b))\n249 µs ± 4.67 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n</code></pre>\n\n<p>In contrast, this highly readable and short implementation using <code>set</code> and <code>sorted</code>, that completely disregards the fact that the lists are already sorted (which means that it also works with unsorted lists):</p>\n\n<pre><code>def intersect_set(a, b):\n return sorted(set(a) & set(b))\n</code></pre>\n\n<p>is about twice as fast:</p>\n\n<pre><code>In [29]: %timeit intersect_set(a, b)\n77 µs ± 1.44 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n</code></pre>\n\n<p>Of course, in order to properly compare them, here are more data points:</p>\n\n<pre><code>import numpy as np\n\nnp.random.seed(42)\n\nns = np.logspace(1, 6, dtype=int)\ninputs = [[sorted(set(np.random.randint(1, n * 10, n))) for _ in range(2)] for n in ns]\n</code></pre>\n\n<p>The <code>set</code> based function wins in all of these test cases:</p>\n\n<p><a href=\"https://i.stack.imgur.com/yFNhQ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/yFNhQ.png\" alt=\"enter image description here\"></a></p>\n\n<p>It looks like for lists with lengths of the order of more than 10M your function might eventually win, due to the <span class=\"math-container\">\\$\\mathcal{O}(n\\log n)\\$</span> nature of <code>sorted</code>.</p>\n\n<p>I think the greater speed (for a wide range of list sizes), coupled with the higher readability, maintainability and versatility makes this approach superior. Of course it requires objects to be hashable, not just orderable.</p>\n\n<p>Whether or not this data is similar enough to yours, or whether or not you get the same timings, performing them to see which one is the best solution in your particular usecase is my actual recommendation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T13:47:31.803",
"Id": "456397",
"Score": "0",
"body": "Interesting; I ran your inputs with `timeit.Timer.autorange` and got [these results](https://i.imgur.com/IURmjaA.png). Also, keep in mind that my method as well as alexyorke's is implemented in pure Python, whereas `set` and `sorted` are implemented in C, that's why it's so fast."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T13:53:15.690",
"Id": "456402",
"Score": "0",
"body": "@kyrill: Interesting results. Which Python version did you use? The one I used is 3.6.9."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T14:04:44.517",
"Id": "456405",
"Score": "0",
"body": "`3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD64)]`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T02:42:22.383",
"Id": "456507",
"Score": "1",
"body": "@kyrill: Using functions implemented in C instead of doing everything in Python *is* the best practice because removes the interpreter overhead; `more-itertools` recipes do this for all the functions inside. Why are you trying to avoid best practice?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T02:51:35.910",
"Id": "456508",
"Score": "0",
"body": "@Voile I think you got me wrong. I don't want to avoid C; I want to avoid creating a `set` if I already have a `list` which may be large. Furthermore, using my original approach as opposed to a set-based one, I can consume elements on the fly, so I can even process infinite iterables (assuming they are sorted)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T02:57:49.510",
"Id": "456509",
"Score": "2",
"body": "@kyrill Then you *definitely* should modify your function to take iterables and `yield` values instead while utilizing the `itertools` functions; they're mostly written in C and this is the kind of situation they're used for. It's much cleaner and prevents all the clumsy store-keeping revolving around lists."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T03:35:33.700",
"Id": "456513",
"Score": "0",
"body": "I said I *can* consume elements on the fly if I wanted to, not that I do. This is easy to see and I don't feel the need to modify my original function to make it any more obvious. Anyhow, which `itertools` functions are you talking about?"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T11:38:28.357",
"Id": "233468",
"ParentId": "233449",
"Score": "15"
}
},
{
"body": "<p>If you treated your 2 inputs as iterables instead of simply lists, you could think in terms of <code>for</code> loops with direct access to elements instead of using <code>__getitem__</code> all around. The second advantage being, obviously, that you can call the function using any iterable instead of only lists; so data that is in a file, for instance, can be processed with, <em>e.g.</em>:</p>\n\n<pre><code>target = [4, 8, 15, 16, 23, 42]\nwith open(my_file) as f:\n common = sorted_lists_intersection(target, map(int, f))\n</code></pre>\n\n<p>without having to store the whole file in memory at once.</p>\n\n<p>If you also make sure to turn your function into a generator, you can directly iterate over the results without having to store all of them at once in memory either; and you can still call <code>list</code> on the function if you truly need a list.</p>\n\n<p>I propose the following implementation that have the same precondition than yours: the inputs must be sorted and should not contain duplicates:</p>\n\n<pre><code>from contextlib import suppress\n\n\ndef intersect_sorted_iterables(iterable1, iterable2):\n iterator = iter(iterable2)\n\n with suppress(StopIteration):\n other = next(iterator)\n\n for element in iterable1:\n if element > other:\n other = next(x for x in iterator if x >= element)\n if element == other:\n yield element\n</code></pre>\n\n<p>This version will take advantage of <code>next</code> raising <code>StopIteration</code> to exit the loop when any of the iterable is exhausted, making it par with your <code>len</code> checks.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T16:14:47.480",
"Id": "456439",
"Score": "0",
"body": "I played with the idea of using iterators with `next` but found it less elegant than the original code. Your idea is interesting as well, but TBH the code is a bit convoluted, especially the `for` loop with conditional `continue` and unconditional `break`. I think it would be neater if you did something like `other = next(x for x in iterator if x >= element)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T21:45:27.643",
"Id": "456477",
"Score": "0",
"body": "@kyrill Yes, that's a neat rewrite of the inner for loop that get rid of the \"must iterate over the whole first iterator\" constraint."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T08:13:19.133",
"Id": "456556",
"Score": "2",
"body": "You can exit the first loop with a return statement in an `else` block of the second loop, which triggers when the second iterator is exhausted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T17:11:11.340",
"Id": "456609",
"Score": "0",
"body": "@moooeeep Updated the code with the suggestion from kyrill, so this is not needed anymore."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T15:56:16.167",
"Id": "233479",
"ParentId": "233449",
"Score": "8"
}
},
{
"body": "<p>My own contribution.</p>\n\n<p>I took inspiration from 409_Conflict and made a lazy generator which takes sorted iterables.</p>\n\n<p>I further generalized it to accept an arbitrary (but non-zero) number of iterables and return their mutual intersection.</p>\n\n<p>The time complexity of this algorithm is <span class=\"math-container\">\\$O(n^2*\\min\\{\\text{len}(it) \\ \\vert\\ it \\in \\texttt{iterables}\\})\\$</span> where <span class=\"math-container\">\\$n = \\text{len}(\\texttt{iterables})\\$</span>. Using some smart datastructure such as Fibonacci heap, the asymptotic complexity could be improved at the cost of actual performance (and also readability and such).</p>\n\n<pre><code>import contextlib\n\ndef all_equal(items):\n \"\"\"\n Returns `False` if and only if there is an element e2 in `items[1:]`,\n such that `items[0] == e2` is false.\n \"\"\"\n items_it = iter(items)\n try:\n first_item = next(items_it)\n except StopIteration:\n return True\n\n return all(first_item == next_item for next_item in items_it)\n\n\ndef sorted_iterables_intersection(*iterables):\n\n iterators = [iter(iterable) for iterable in iterables]\n\n with contextlib.suppress(StopIteration):\n while True:\n elems = [next(it) for it in iterators]\n\n while not all_equal(elems):\n # Find the iterator with the lowest value and advance it.\n min_idx = min(range(len(iterables)), key=elems.__getitem__)\n min_it = iterators[min_idx]\n elems[min_idx] = next(min_it)\n\n yield elems[0]\n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T21:59:35.683",
"Id": "456481",
"Score": "0",
"body": "Lastly, allowing for 0 iterables (if desired) is trivial by changing the `while True:` into `while iterators:`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T22:59:59.940",
"Id": "456487",
"Score": "0",
"body": "Regarding the `all_equal`: there's indeed no need for `zip`; I removed it and also replaced `try` with `contextlib.suppress`. As per allowing zero iterables: `while iterators` is the exact thing that came to my mind, and I swiftly dismissed the idea because there's really no need to keep repeatedly checking whether there are any iterators; you only need to check once. And adding a check before the while loop just didn't seem worth it ‒ why would you call the function with no arguments? Anyways, thanks for the suggestions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T04:48:13.437",
"Id": "456530",
"Score": "0",
"body": "The definition of `all_euqal()` is missing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T07:22:05.823",
"Id": "456547",
"Score": "0",
"body": "@kyrill Yes, also one can wonder where iterators is beeing modified in the first place. So I agree with your points, hence the \"if desired\"."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T17:34:20.490",
"Id": "233481",
"ParentId": "233449",
"Score": "6"
}
},
{
"body": "<p>If you truly don't want to convert to sets, perhaps use the underlying idea that they implement. Note that <code>get_hash</code> is pretty arbitrary and definitely could be improved. <a href=\"https://en.wikipedia.org/wiki/Hash_table\" rel=\"nofollow noreferrer\">Here's a resource on improving the hashing and choice of <code>hash_map</code> size</a></p>\n\n<pre><code>def get_hash(thing, hash_map):\n hashed = ((hash(thing) * 140683) ^ 9011) % len(hash_map)\n incr_amount = 1\n while hash_map[hashed] is not None and hash_map[hashed] != thing:\n hashed += incr_amount ** 2\n incr_amount += 1\n if hashed >= len(hash_map):\n hashed = hashed % len(hash_map)\n return hashed\n\ndef sorted_lists_intersection(a, b):\n hash_map = [None for _ in range(len(a) * 7 + 3)]\n\n for x in a:\n hash_map[get_hash(x, hash_map)] = x\n\n return filter(lambda x: x == hash_map[get_hash(x, hash_map)], b)\n</code></pre>\n\n<p><strong>Edit based on comments:</strong></p>\n\n<p>Here is a O(m*n) <a href=\"https://en.wikipedia.org/wiki/In-place_algorithm\" rel=\"nofollow noreferrer\">in-place</a> answer</p>\n\n<pre><code>def intersection_sorted_list(a, b):\n return filter(lambda x: x in a, b)\n</code></pre>\n\n<p>Now, if the lists are sorted we can speed this up a bit by shrinking the range we check against after each successive match. I believe this makes it O(m+n) time. </p>\n\n<pre><code>def intersection_sorted_list(a, b):\n start_indx = 0\n for x in b:\n for i in range(start_indx, len(a)):\n if a[i] == x:\n yield a[i]\n if a[i] >= x:\n start_indx = i + 1\n break\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T01:39:54.903",
"Id": "456497",
"Score": "0",
"body": "Pardon my French, but this is awful. Firstly, Python has a built-in `hash` function; secondly, Python has a built-in `dict` class which is a \"hash map\" and thirdly, what you try to accomplish using a hash map, can be accomplished using a `set`. Your answer can be summed up in one line: `return filter(lambda x: x in set(a), b)`. Which I explicitly stated I am not interested in."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T01:46:37.300",
"Id": "456499",
"Score": "0",
"body": "@kyrill, the inbuilt function is not directly applicable for hashmaps, you need to find the modulo of it and perform probing at the very least. \"what you try to accomplish using a hash map, can be accomplished using a set\" I explicitly stated that was the purpose of my answer. You haven't stated what you are interested in, only \"I don't like this function. Looks too imperative.\". This a less imperative function. I don't understand what you are looking for since you are explicitly avoiding the best solution to your problem. I thought you were trying to avoid under the hood bloat of `set`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T01:48:46.183",
"Id": "456500",
"Score": "0",
"body": "@kyrill the answer you contributed is essentially a more abstract and less efficient implementation (due to doing O(n) lookups instead of hashes) of the above."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T01:50:58.700",
"Id": "456501",
"Score": "0",
"body": "What I was interested in, is to avoid creating a `set` if I already have a (possibly huge) `list`. I have no comment on your second comment..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T02:23:55.380",
"Id": "456502",
"Score": "0",
"body": "@kyrill This answer does not create a set, it creates a list of the same space complexity, which you can modify to be O(n) or O(m). Are you looking for an in-place algorithm https://en.wikipedia.org/wiki/In-place_algorithm ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T02:36:55.523",
"Id": "456504",
"Score": "0",
"body": "Yes Budd, you understood that correctly. I am indeed looking for an in-place algorithm."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T03:21:10.600",
"Id": "456510",
"Score": "0",
"body": "Can you find the mistake in your new version? Hint: the results it produces are correct (at least I think so; I haven't checked)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T03:30:17.000",
"Id": "456512",
"Score": "0",
"body": "Welcome to CodeReview@SE. I quite like your \"sorted list variant\" - can't decide whether adding a break after the yield would be an improvement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T03:40:57.563",
"Id": "456515",
"Score": "0",
"body": "@kyrill results might not be intended if the values in a and b are non-unique, I'm not sure if you want unique values in the output."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T03:41:01.650",
"Id": "456516",
"Score": "0",
"body": "@greybeard thanks, the second if condition is inclusive of the first and thus covers that ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T03:57:17.280",
"Id": "456520",
"Score": "0",
"body": "It has nothing to do with duplicates. As I said, the results it produces are correct, and besides, I have stated that the inputs contain no duplicate values. Your new version simply doesn't work quite correctly – namely the \"range shrinking\" part."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T04:05:10.640",
"Id": "456524",
"Score": "0",
"body": "@kyrill if you are aware of an error please point it out"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T04:16:10.463",
"Id": "456525",
"Score": "0",
"body": "You don't update `start_indx` if you skip over an element. Eg. `x` is 1 and `a` starts with [0, 2]; then you would advance `a[i]` from 0 to 2 without saving it, and break the loop because 2 > 1 (again without saving `i`). Then you would consume the next element from `b` and start comparing it again from the beginning of `a` (from 0), but you should start from the last consumed element of `a` (from 2)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T05:39:40.403",
"Id": "456536",
"Score": "1",
"body": "I misremembered revisions up to 3."
}
],
"meta_data": {
"CommentCount": "14",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T01:13:31.313",
"Id": "233497",
"ParentId": "233449",
"Score": "2"
}
},
{
"body": "<h1>using iterators</h1>\n\n<p>This is basically the same as your solution, but uses iterators instead of explicit indexing. I find it easy to understand.</p>\n\n<pre><code>def sorted_list_intersection(list1, list2):\n iter1 = iter(list1)\n iter2 = iter(list2)\n\n intersection = []\n\n try:\n item1 = next(iter1)\n item2 = next(iter2)\n\n while True:\n if item1 == item2:\n intersection.append(item1)\n item1 = next(iter1)\n item2 = next(iter2)\n\n elif item1 < item2:\n item1 = next(iter1)\n\n else:\n item2 = next(iter2)\n\n except StopIteration:\n return intersection\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T11:24:16.510",
"Id": "456577",
"Score": "1",
"body": "I was going to post something very similar, but instead of the `intersection` intermediate list, and appending to it, `yield` each match"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T13:27:38.963",
"Id": "456588",
"Score": "1",
"body": "I'd suggest incorporating the `yield` as mentioned above. It would make sense to make your function a generator, since you're already using iterators (and hence possibly accepting generators as arguments)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T18:57:05.690",
"Id": "456623",
"Score": "1",
"body": "I agree `yield item1` may be better than `intersection.append(item1)`, depending on the use case, I was just mirroring what the OP code did."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T02:17:48.160",
"Id": "233505",
"ParentId": "233449",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T01:33:05.943",
"Id": "233449",
"Score": "10",
"Tags": [
"python",
"algorithm",
"reinventing-the-wheel"
],
"Title": "Intersection of sorted lists"
}
|
233449
|
<p>Because I often have to deal with two <code>Variant</code>s that may or may not be <code>Null</code>, we need a null-safe equality test, so I came up with <code>IsDistinct</code> which works but I have some issues with the code:</p>
<ol>
<li>When I tried to keep it terse, the readability was harmed.</li>
<li>When I tried to expand the logic for readability, it still makes for some thinking. </li>
<li>I looked for potentials to short-circuit or otherwise result the number of steps to arrive at a result. In this case, it all takes 2 evaluations, unless both sides are non-null, in which case we have 3 evaluations.<sup>1</sup> </li>
</ol>
<p>Can we do better? </p>
<pre><code>Public Function IsDistinct(LeftValue As Variant, RightValue As Variant) As Boolean
If IsNull(LeftValue) Then
If IsNull(RightValue) Then
IsDistinct = False
Else
IsDistinct = True
End If
Else
If IsNull(RightValue) Then
IsDistinct = True
Else
IsDistinct = Not (LeftValue = RightValue)
End If
End If
End Function
</code></pre>
<h2>Inputs & Expected Outputs</h2>
<pre><code>LeftValue RightValue Result
1 1 False
1 0 True
Null 1 True
0 Null True
Null Null False
"" "" False
"" Null True
</code></pre>
<p>Note that it doesn't have to be just <code>0</code> and <code>1</code>; it could be text, dates, or numbers. It's more important that when either inputs are <code>Null</code>, it should automatically be <code>True</code> since <code>Null</code> will always be "distinct" from any non-<code>Null</code> values. However, when both inputs are <code>Null</code>, then it's always <code>False</code> because we are considering them "equal" in this situation.<sup>2</sup></p>
<p>The special case of an empty string and a <code>Null</code> is arguably problematic. I've swung both ways; sometimes I want empty string to be considered "equal" to a <code>Null</code>, sometimes I don't. In the <code>IsDistinct</code> as defined, they are not considered equal.<sup>3</sup></p>
<hr>
<p>1) In one of iterations, I considered starting with <code>Result = (LeftValue = RightValue)</code> and doing additional evaluation if the <code>Result</code> was <code>Null</code>, signaling that either or both inputs were <code>Null</code>. But IIRC, I found that it made for more steps since I had to evaluate each inputs with <code>IsNull</code> to determine whether both were <code>Null</code> and thus not distinct. </p>
<p>2) As a matter of fact, when I look at the first 3 lines:</p>
<pre><code>If IsNull(LeftValue) Then
If IsNull(RightValue) Then
IsDistinct = False
</code></pre>
<p>My instinct is to go "wait, that's not right.", thinking about it and realize it IS correct. The fact that I stumble on that even more than once tells me that it's quite hard to read. Boo. </p>
<p>3) Thanks to <a href="https://codereview.stackexchange.com/a/233478/149207">@Ryan Wildry</a> for pointing this blind spot out!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T02:14:56.987",
"Id": "456328",
"Score": "3",
"body": "`If IsNull(RightValue) Then\n IsDistinct = False\n Else\n IsDistinct = True\n End If` can be simplified to `IsDistinct = Not IsNull(RightValue)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T07:36:05.283",
"Id": "456364",
"Score": "0",
"body": "For some reason I thought that I had test two nulls as true. Nice work!"
}
] |
[
{
"body": "<p>Nested ifs are something I've come to knee-jerk refactor into similar below. Writing functions that state what they're doing reduces the burden to understand. When future-Iven comes along and evaluates the logic I won't be asking myself 'What's this doing?' as I'll already know.</p>\n\n<pre><code>Public Function IsDistinct(leftValue As Variant, rightValue As Variant) As Boolean\n If AreBothValuesNull(leftValue, rightValue) Then\n IsDistinct = False\n Exit Function\n End If\n\n If IsOnlyOneValueNull(leftValue, rightValue) Then\n IsDistinct = True\n Exit Function\n End If\n\n IsDistinct = Not (leftValue = rightValue)\nEnd Function\n\nPrivate Function AreBothValuesNull(ByVal leftValue As Variant, ByVal rightValue As Variant) As Boolean\n AreBothValuesNull = IsNull(leftValue) And IsNull(rightValue)\nEnd Function\n\nPrivate Function IsOnlyOneValueNull(ByVal leftValue As Variant, ByVal rightValue As Variant) As Boolean\n IsOnlyOneValueNull = (IsNull(leftValue) And Not IsNull(rightValue) _\n Or Not IsNull(leftValue) And IsNull(rightValue))\nEnd Function\n</code></pre>\n\n<p>What about the same value but with different types? <code>IsDistinct(1, \"1\")</code> comes to mind as a test case.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T14:44:31.093",
"Id": "456411",
"Score": "0",
"body": "Regarding the question about different types -- I would consider that out of the function's scope. All the weird implicit conversion rules applies in this case and if the user doesn't like it, then user shouldn't be putting in garbage. Your code is definitely much more readable and I don't have to think as hard as with my original version. The only bad thing is that in the worst case, we have 7 evaluations, on the account that the `And`s and `Or`s aren't lazy."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T18:36:47.313",
"Id": "456450",
"Score": "0",
"body": "Is there a reason you've used `ByVal` in your helper functions and not in the main function signature?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T18:38:34.967",
"Id": "456452",
"Score": "0",
"body": "Copy-pasta oversight."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T08:30:25.127",
"Id": "233460",
"ParentId": "233451",
"Score": "3"
}
},
{
"body": "<p>Personally, when iterating possibilities, I always use <code>SELECT CASE True</code> instead of nested <code>If</code> and <code>Else</code> statements to just have a list of possibilities for readability purposes.</p>\n\n<p>Performance might not be 100% optimal, since this can lead to slightly more comparisons, but I will gladly take that to have more readable code.</p>\n\n<pre><code>Public Function IsDistinct(LeftValue As Variant, RightValue As Variant) As Boolean\n Select Case True\n Case IsNull(LeftValue) And IsNull(RightValue)\n IsDistinct = False\n Case IsNull(LeftValue) Or IsNull(RightValue)\n IsDistinct = True\n Case LeftValue = RightValue\n IsDistinct = False\n Case Else\n IsDistinct = True\n End Select\nEnd Function\n</code></pre>\n\n<p>Note that because I'm iterating possibilities, I prefer not to do <code>IsDistinct = Not (LeftValue = RightValue)</code> but only assign literals for readability (I'll just have <code>Case Condition Then Literal</code>), but if you don't care, you can of course save two lines.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T14:50:40.670",
"Id": "456412",
"Score": "0",
"body": "Definitely readable. Unfortunately, the worst case has 5 evaluations, though the best case is still only 2 evaluations (the first case with the `And`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T15:01:57.210",
"Id": "456413",
"Score": "0",
"body": "Yup, this could definitely be optimized to not call `IsNull` up to 4 times and require less assignments and comparisons (stripping away all `IsDistinct = False` statements is also a trivial optimization, for example). However, the cost of this function is so little that I'd be surprised if you have a case where that isn't premature."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T15:03:59.593",
"Id": "456414",
"Score": "0",
"body": "One case where it can matter is when the function is used as a part of the conditional formatting for an Access continuous form where it will be repeatedly evaluated as the user moves around in the form. That can matter."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T09:45:48.283",
"Id": "233462",
"ParentId": "233451",
"Score": "2"
}
},
{
"body": "<p>You have no idea how excited I am about this. Years after learning about the <code>Xor</code> operator and I finally get to use it!! </p>\n\n<p><a href=\"https://bettersolutions.com/vba/data-types/variant-null.htm\" rel=\"nofollow noreferrer\">VBA - Logical Operators</a>: Xor Operator</p>\n\n<blockquote>\n <p>Called Logical Exclusion. It is the combination of NOT and OR Operator. If one, and only one, of the expressions evaluates to be True, the result is True.</p>\n</blockquote>\n\n<p>The <code>Xor</code> seems like a great fit because both the parameters need to be tested for nulls and the values can not equal one another.</p>\n\n<h2>My Version</h2>\n\n<pre><code>Public Function NotEquals(LeftValue As Variant, RightValue As Variant) As Boolean\n If IsNull(LeftValue) Xor IsNull(RightValue) Then\n NotEquals = True\n ElseIf LeftValue <> RightValue Then\n NotEquals = True\n End If\nEnd Function\n</code></pre>\n\n<h2>Results</h2>\n\n<p><a href=\"https://i.stack.imgur.com/mJKY8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mJKY8.png\" alt=\"Immediate Window Results\"></a></p>\n\n<h2>Crude Tests</h2>\n\n<pre><code>Option Explicit\nPublic Const Repetitions = 10000000\n\nPublic Function IsDistinct(LeftValue As Variant, RightValue As Variant) As Boolean\n If IsNull(LeftValue) Then\n If IsNull(RightValue) Then\n IsDistinct = False\n Else\n IsDistinct = True\n End If\n Else\n If IsNull(RightValue) Then\n IsDistinct = True\n Else\n IsDistinct = Not (LeftValue = RightValue)\n End If\n End If\nEnd Function\n\nPublic Function NotEquals(LeftValue As Variant, RightValue As Variant) As Boolean\n If IsNull(LeftValue) Xor IsNull(RightValue) Then\n NotEquals = True\n ElseIf LeftValue <> RightValue Then\n NotEquals = True\n End If\nEnd Function\n\nSub CompareResults()\n Dim SumOfTime As Double\n Debug.Print \"Number of Repetitions: \"; FormatNumber(Repetitions, 0)\n\n Debug.Print\n Debug.Print \"IsDistinct Test\"\n Debug.Print \"Left\"; Tab(8); \"Right\"; Tab(16); \"Time\"; Tab(24); \"Result\"\n SumOfTime = TestIsDistinct(1, 1)\n SumOfTime = SumOfTime + TestIsDistinct(1, 0)\n SumOfTime = SumOfTime + TestIsDistinct(Null, 1)\n SumOfTime = SumOfTime + TestIsDistinct(0, Null)\n SumOfTime = SumOfTime + TestIsDistinct(Null, Null)\n Debug.Print \"Total Time for All IsDistinct Test: \"; SumOfTime\n\n Debug.Print\n Debug.Print \"NotEquals Test\"\n Debug.Print \"Left\"; Tab(8); \"Right\"; Tab(16); \"Time\"; Tab(24); \"Result\"\n SumOfTime = TestNotEquals(1, 1)\n SumOfTime = SumOfTime + TestNotEquals(1, 0)\n SumOfTime = SumOfTime + TestNotEquals(Null, 1)\n SumOfTime = SumOfTime + TestNotEquals(0, Null)\n SumOfTime = SumOfTime + TestNotEquals(Null, Null)\n Debug.Print \"Total Time for All NotEquals Test: \"; SumOfTime\n\nEnd Sub\n\nFunction TestIsDistinct(LeftValue As Variant, RightValue As Variant) As Double\n Dim t As Double\n t = Timer\n Dim Result As Boolean\n Dim n As Long\n For n = 1 To Repetitions\n Result = IsDistinct(LeftValue, RightValue)\n Next\n\n Dim SumOfTime As Double\n SumOfTime = Round(Timer - t, 4)\n\n Debug.Print LeftValue; Tab(8); RightValue; Tab(16); SumOfTime; Tab(24); Result\n\n TestIsDistinct = SumOfTime\nEnd Function\n\nFunction TestNotEquals(LeftValue As Variant, RightValue As Variant) As Double\n Dim t As Double\n t = Timer\n Dim Result As Boolean\n Dim n As Long\n For n = 1 To Repetitions\n Result = NotEquals(LeftValue, RightValue)\n Next\n\n Dim SumOfTime As Double\n SumOfTime = Round(Timer - t, 4)\n\n Debug.Print LeftValue; Tab(8); RightValue; Tab(16); SumOfTime; Tab(24); Result\n\n TestNotEquals = SumOfTime\nEnd Function\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T14:40:48.253",
"Id": "456409",
"Score": "0",
"body": "Nice! One of my early iterations did indeed use `Xor` but I abandoned it for the sake of readability. I see that the key is how you set up the `ElseIf` condition, so even for both `Null `inputs, we still get `False`. We still have 2 evaluations in the best case and 3 in the worse case. Well done!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T21:02:56.730",
"Id": "458729",
"Score": "0",
"body": "I don't know much about VBA, but shouldn't you initialize `NotEquals` to `False` at the start of the method?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-23T22:34:52.473",
"Id": "458737",
"Score": "0",
"body": "@SimonForsberg Boolean variable are False by default."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T11:27:04.200",
"Id": "233467",
"ParentId": "233451",
"Score": "8"
}
},
{
"body": "<p>Yet another approach, this time with string coercion. Knowing the type certainly helps simplify the tests, however it does come at a cost of speed. However thought I'd share for those who may be unfamiliar with the approach.</p>\n\n<pre><code>Option Explicit\n\nPublic Function IsDistinct(LeftValue As Variant, RightValue As Variant) As Boolean\n IsDistinct = Not ((LeftValue & vbNullString) = (RightValue & vbNullString))\nEnd Function\n\nPublic Sub Tests()\n Debug.Print IsDistinct(1, 1)\n Debug.Print IsDistinct(1, 0)\n Debug.Print IsDistinct(Null, 1)\n Debug.Print IsDistinct(0, Null)\n Debug.Print IsDistinct(Null, Null)\n\n Dim i As Long\n Dim t As Double\n Dim result As Boolean\n t = Timer\n 'How long does it take?\n For i = 1 To 100000\n result = IsDistinct(1, 1)\n result = IsDistinct(1, 0)\n result = IsDistinct(Null, 1)\n result = IsDistinct(0, Null)\n result = IsDistinct(Null, Null)\n Next\n\n Debug.Print \"This took \" & Timer - t & \" seconds\"\nEnd Sub\n</code></pre>\n\n<p>Here are the results of the tests:</p>\n\n<pre><code>False\nTrue\nTrue\nTrue\nFalse\nThis took 0.2421875 seconds\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T15:20:08.703",
"Id": "456417",
"Score": "1",
"body": "String coercion goes wrong if you want to handle Null and zero-length strings separately, though"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T15:24:32.493",
"Id": "456421",
"Score": "0",
"body": "@ErikA Yes, in this scheme it's helpful to point out vbNullString and Null would return `False`. Depends if you care about type too. I think there is some practical applications where that doesn't matter very much (or you might want this behavior), but good to point out. +1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T15:26:04.397",
"Id": "456423",
"Score": "0",
"body": "That highlights a blind spot in my original tests. I would have considered an empty string \"distinct\" from a `Null`. But I agree there will be cases where for the purpose, they are \"same\". I will clarify the question accordingly."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T15:18:08.383",
"Id": "233478",
"ParentId": "233451",
"Score": "3"
}
},
{
"body": "<p>Developing further based on <a href=\"https://codereview.stackexchange.com/a/233467/149207\">TinMan's excellent answer</a> and other posters' contributions, I came up with this:</p>\n\n<pre><code>Public Function IsDistinct(LeftValue As Variant, RightValue As Variant) As Boolean\n If LeftValue <> RightValue Then\n IsDistinct = True\n ElseIf IsNull(LeftValue) Xor IsNull(RightValue) Then\n IsDistinct = True\n End If\nEnd Function\n</code></pre>\n\n<p>Both this version and TinMan's version reduces the number of evaluations to only 1 in the best case and 2 for the worst case. However, this version exploits the fact that the <code>If</code> conditions will treat <code>Null</code> result as a falsy result.<sup>1</sup> </p>\n\n<p>Therefore, only equal values and <code>Null</code> result will proceed to the <code>ElseIf</code> condition, which we use the <code>Xor</code> to verify that they aren't both <code>Null</code>. If that doesn't match, then we know that they are considered the same value. </p>\n\n<p>This is more terse but I think the readability hurts a bit because of the <code>LeftValue <> RightValue</code> potentially returning a <code>Null</code> result which does not make for most intuitive thinking through the logical procession. But I would say that it's more common to compare one value against another value than it is to have <code>Null</code> against any other value or having both <code>Null</code> so that is also a good optimization, I think. Need to test whether this is in fact an improvement in speed, though.</p>\n\n<hr>\n\n<p>1) Aside: I found out that <code>Select Case True</code> does not like <code>Null</code> results; we get an <code>Invalid Use of Null</code> error with that structure. Thus, it must be a <code>If/ElseIf</code> which tolerates <code>Null</code> result. However, It's very important to remember that with a <code>Null</code> result, it will never ever enter any <code>If</code> or <code>ElseIf</code> branch, and therefore always fall into the <code>Else</code> or through.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T20:39:25.540",
"Id": "233486",
"ParentId": "233451",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T01:47:52.590",
"Id": "233451",
"Score": "6",
"Tags": [
"vba",
"null",
"variant-type"
],
"Title": "Simplify & Reduce steps in the IsDistinct function"
}
|
233451
|
<p><strong>Objective</strong> </p>
<p>To create a unique id with few characters as possible. </p>
<ul>
<li>Language: C# </li>
<li>Engine Unity3D</li>
<li>Target : iOS && iPadOS</li>
</ul>
<p><strong>Scenario</strong></p>
<p>I found quite a few solutions from Stack Exchange but would like to know if someone could just look at my code to review it. It is a very important module IMO</p>
<p><strong>Code</strong></p>
<pre><code> /// <summary>
/// Identifiers the generation.
/// </summary>
/// <returns>A Unique ID</returns>
private string generateUniqueID(int _characterLength = 11)
{
StringBuilder _builder = new StringBuilder();
Enumerable
.Range(65, 26)
.Select(e => ((char)e).ToString())
.Concat(Enumerable.Range(97, 26).Select(e => ((char)e).ToString()))
.Concat(Enumerable.Range(0, 10).Select(e => e.ToString()))
.OrderBy(e => Guid.NewGuid())
.Take(_characterLength)
.ToList().ForEach(e => _builder.Append(e));
return _builder.ToString();
}
</code></pre>
<p>In the above code, I always pass <code>_characterLength</code> to be always <code>11</code>.</p>
<p><strong>Request</strong></p>
<ol>
<li>Would you recommend the above method? If not, could you please specify why? </li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T04:04:50.877",
"Id": "456343",
"Score": "0",
"body": "I would probably just use `System.Guid.NewGuid().ToString().Substring(0, _characterLength);` Is there some reason you're specifically using uppercase strings instead of just a Guid directly? This is what they're for after all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T05:49:43.553",
"Id": "456351",
"Score": "0",
"body": "How often would you create an ID, and what is the scope (i.e. how broadly are they going to be used)? If you are going to make one every hour, then using a dated timestamp would guarantee uniqueness! After all, unique does not have to be random."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T08:27:31.187",
"Id": "456367",
"Score": "3",
"body": "This does not generate a unique ID, it generates a random ID"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T08:39:08.460",
"Id": "456368",
"Score": "0",
"body": "Thank you for the comments. \nBased on the response from @Turksarama && @Anders | if I just use\n\n`return Guid.NewGuid().ToString().Substring(0, 9);` \n\n\n1. Would that be good. \n2. What are the chances of not getting a unique string?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T09:10:26.517",
"Id": "456372",
"Score": "1",
"body": "@karsnen Guids are significantly _more_ unique than your algorithm. You are limiting uniqueness both by length and by not allowing repeating characters.\nNote that I wouldn't even use substring ideally (I don't know why you're limiting length). Just use `Guid.NewGuid()` and be done with it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T09:20:08.873",
"Id": "456373",
"Score": "0",
"body": "@karsnen to put it in perspective, `2^128=340,282,366,920,938,463,463,374,607,431,768,211,456` unique GUIDs, while your algorithm generates `62!-(62-n)!` strings, which for `n=9` gives `7,361,598,240,057,600` unique combinations. i.e. guids are 46 sextillion times more unique than your algorithm for length 9."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T20:47:09.010",
"Id": "456467",
"Score": "0",
"body": "@Turksarama | Thank you very much for taking the time to respond. The only reason for shortening the string is to have a short URL like a YoutTube URL which only has 11 characters. When you say _You are limiting uniqueness both by length and by not allowing repeating characters_ => I am not sure where exactly I am doing it. I am fine in allowing repeating characters in `System.Guid.NewGuid().ToString().Substring(0, _characterLength);`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T21:15:35.463",
"Id": "456471",
"Score": "0",
"body": "Your algorithm in your question generates a sequence of unique characters (no character is repeated) then you shuffle them and take `n`. By not having a character repeat there are fewer possible sequences. The most basic example is if you have only characters `1` and `0`. If they can repeat, there are four sequences: `00, 01, 10, 11`. If they can't repeat there are only two: `10, 01`.\n\nI think it should be obvious that a shorter string has fewer possible values."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-08T21:14:18.360",
"Id": "456773",
"Score": "0",
"body": "I thank everybody who have contributed here. Jeff has written a good answer."
}
] |
[
{
"body": "<pre><code> /// <summary>\n /// Identifiers the generation.\n /// </summary>\n /// <returns>A Unique ID</returns>\n private string generateUniqueID(int _characterLength = 11)\n</code></pre>\n\n<p>A good summary should describe what the method does. This summary doesn't really tell me anything. Keep it simple: the method generates IDs, so write the summary as such.</p>\n\n<p><code>generateUniqueID</code> does not follow C# method naming conventions. Call it <code>GenerateUniqueID</code>. Note the <code>PascalCase</code>.</p>\n\n<p>A character always has a length of 1, so <code>_characterLength</code> is a bit of a confusing name for me. What it describes is actually the length of the ID, so call it <code>idLength</code>, or just <code>length</code> since the thing it's describing is obvious from the method name anyway.</p>\n\n<p>You got the <code>camelCasing</code> right for parameter and local identifiers, but it's not conventional to use underscores. Get rid of those.</p>\n\n<p>It's not clear why you'd give such a method a default value, but in any case that <code>11</code> should be defined as a constant somewhere. Avoid magic numbers. By giving that number a name, you give it a meaning that's obvious to the next person who reads your code.</p>\n\n<pre><code>private const int DefaultIDLength = 11;\n\nprivate string GenerateUniqueID(int length = DefaultIDLength)\n...\n</code></pre>\n\n<hr>\n\n<pre><code>StringBuilder _builder = new StringBuilder();\n</code></pre>\n\n<p>It's common to use <code>var</code> when the expression type is obvious.</p>\n\n<p>Your ID will always be <code>length</code> characters long, so use the <code>StringBuilder</code> constructor that takes an initial capacity:</p>\n\n<pre><code>var builder = new StringBuilder(length);\n</code></pre>\n\n<hr>\n\n<pre><code>Enumerable\n .Range(65, 26)\n .Select(e => ((char)e).ToString())\n .Concat(Enumerable.Range(97, 26).Select(e => ((char)e).ToString()))\n .Concat(Enumerable.Range(0, 10).Select(e => e.ToString()))\n .OrderBy(e => Guid.NewGuid())\n .Take(_characterLength)\n .ToList().ForEach(e => _builder.Append(e));\n</code></pre>\n\n<p>This is the crux of your implementation, and there's a lot to unpack here, so let's go step by step.</p>\n\n<pre><code>Enumerable\n .Range(65, 26)\n .Select(e => ((char)e).ToString())\n .Concat(Enumerable.Range(97, 26).Select(e => ((char)e).ToString()))\n .Concat(Enumerable.Range(0, 10).Select(e => e.ToString()))\n</code></pre>\n\n<p>This produces the same sequence every time you run it. It's painful to read. Why not just specify it as a constant? This gets the point across far easier:</p>\n\n<pre><code>private const string AllowableIDCharacters = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n</code></pre>\n\n<p>But we'll see later that none of this is necessary.</p>\n\n<p>You don't need all those <code>ToString</code>s everywhere. You gain nothing by using <code>string</code> as an intermediate representation instead of <code>char</code>. Keep them as <code>char</code>s during the shuffle: <code>StringBuilder.Append()</code> has an overload that accepts <code>char</code>.</p>\n\n<p>I try to avoid writing lambdas with side effects. This would be more conventionally written as a <code>foreach</code> loop, which also avoids the need to convert the thing to a list:</p>\n\n<pre><code>foreach (char c in AllowableIDCharacters\n .OrderBy(e => Guid.NewGuid())\n .Take(length))\n{\n builder.Append(c);\n}\n</code></pre>\n\n<p>But by far the biggest problem here is your source of entropy, as Turksarama pointed out in the comments. By shuffling the alphabet, you are not allowing any repeated characters! This cuts down the number of unique IDs you can generate by more than half. Drop the shuffling idea entirely, it's not the best tool for this job.</p>\n\n<hr>\n\n<p>You cannot generate unique IDs without keeping some kind of state. GUIDs work by generating sequences that, while not unique in a pure sense, are so astronomically unlikely to be repeated that they are \"unique\" for all practical intents and purposes.</p>\n\n<p>If you embrace the non-determinism approach of generating unique IDs that GUID takes, then the question is no longer \"how to generate a unique ID with as few characters as possible\". It is now \"what is an acceptable trade-off between ID length and probability of collision\".</p>\n\n<p>Because your method is just a mechanism for generating IDs <em>given a length</em>, then half of your problem reduces to something much simpler:</p>\n\n<ol>\n<li>Given an ID length <code>n</code>, how do I minimize the probability of a collision?</li>\n<li>How do I maximize the amount of information contained within a string of length <code>n</code>?</li>\n</ol>\n\n<p>Both of these are straightforward problems. To minimize collisions you need a source of entropy that is both uniformly distributed and unpredictable. There are a lot of ways to do this, with varying degrees of uniformity and unpredictability, but do note that GUIDs are <em>not</em> uniformly distributed, are <em>somewhat</em> predictable, and are therefore not a great choice here. There is plenty of literature on how to generate such entropy so I won't go into detail for now. A common choice in .NET is to use <code>RNGCryptoServiceProvider</code>.</p>\n\n<p>Maximizing the information contained in the ID means trying to squeeze as many bits of data as possible into that string. You chose an encoding that can represent 62 different things per character, or about 5.95 bits of data per character -- but because of the shuffling issue we talked about earlier, the actual number will be much smaller. For IDs of length 11 it's less than half.</p>\n\n<p>I assume you're limited to ID strings of 8-bit ASCII-ish characters. But the alphabet you came up with is <em>really</em> close to Base 64, so why not just use Base 64? That'll give you an even 6 bits of information per character. By selecting a standard encoding as such, you'll avail to yourself a suite of standard tools for converting to and from that encoding.</p>\n\n<hr>\n\n<p>Here's an example of how you could do it:</p>\n\n<pre><code>private static readonly RNGCryptoServiceProvider random = new RNGCryptoServiceProvider();\n\nprivate string GenerateUniqueID(int length)\n{\n // We chose an encoding that fits 6 bits into every character,\n // so we can fit length*6 bits in total.\n // Each byte is 8 bits, so...\n int sufficientBufferSizeInBytes = (length * 6 + 7) / 8;\n\n var buffer = new byte[sufficientBufferSizeInBytes];\n random.GetBytes(buffer);\n return Convert.ToBase64String(buffer).Substring(0, length);\n}\n</code></pre>\n\n<p>This gives you 6 bits of entropy per character. It's up to you and the constraints of your business domain to pick an appropriate length. By the \"birthday problem\" rule of thumb, the probability of two random IDs of <code>n</code> bits to conflict with each other is about one in <code>2^(n/2)</code>; so an ID length of 11 gives you 66 bits, with a one in <code>2^33</code> chance of two IDs conflicting.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-08T21:13:30.533",
"Id": "456772",
"Score": "0",
"body": "Thank you for the answer. Besides the solution and how to approach the problem - I also learned about naming conventions & how to document. Have a great day."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T17:53:19.783",
"Id": "233553",
"ParentId": "233452",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "233553",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T02:04:05.840",
"Id": "233452",
"Score": "3",
"Tags": [
"c#",
"strings",
".net",
"unity3d"
],
"Title": "Generate Unique ID in C#"
}
|
233452
|
<p><strong>Problem Statement:</strong> Users can chat while the replies of the chatbot are based on past messages.</p>
<p>So the chatbot needs to have the context of the previous messages and reply accordingly. Here is pseudocode of chatbot for more understanding</p>
<pre><code>hi_flag = False
message = await websocket.receive_bytes()
if message == "Hey":
hi_flag = True
reply = f'hey, there {user_id}'
await websocket.send_bytes(reply)
if message == "hey":
reply = f'Hey you already said Hi ! WTH !'
await websocket.send_bytes(reply)
if message == "Goodbye":
if not hi_flag:
reply = 'Hey You did not say HI !'
await websocket.send_bytes(reply)
</code></pre>
<p>So the problem sums to be pretty much that the user should be able to send a get/post request but the context should be there (like a session)</p>
<p>I am a beginner in this field and this approach won't necessarily be the best.
Here is a solution that I built using fastapi</p>
<hr>
<p><code>invoker.py</code> <em>(uvicorn invoker:app)</em></p>
<pre><code>from fastapi import FastAPI
import aioredis
import subprocess
REDIS_URL = 'redis://localhost:6379'
app = FastAPI()
client_list = []
async def snoopers_a(client_id):
client_id += "_replies"
result = await app.state.r.blpop(client_id)
return result[1]
# return str(r.blpop(client_id)[1])[2:-1]
async def pushers_a(client_id, message):
await app.state.r.lpush(client_id,message)
@app.on_event("startup")
async def on_startup():
r = await aioredis.create_redis(REDIS_URL)
app.state.r = r
@app.post("/request")
async def request_startpoint(client_id: str, client_message: str):
if client_id in client_list:
print("Waiting at Existing Client")
await pushers_a(client_id, client_message)
return await snoopers_a(client_id)
else:
client_list.append(client_id)
print("Creating new Subprocess !")
subprocess.Popen(['python', 'arbiter.py', client_id])
print("Subprocess Created !")
await pushers_a(client_id, client_message)
print(f"Waiting for {client_id}")
return await snoopers_a(client_id)
</code></pre>
<p>The above invokes a new python process for each client. ( The invoked process from here on arbiter). It also pushes the messages in a Redis list. The task of the arbiter is to get the message from the list and then send it to the connected WebSocket to push the reply back in a reply list of that client. The invoker after pushing the message would just wait at the reply list and the rest work is done by the invoker.</p>
<hr>
<p><code>arbiter.py</code></p>
<pre><code>import asyncio
import aioredis
import websockets
import sys
client_id = sys.argv[1]
print(sys.argv[1])
async def snoopers_b(client_id,r):
result = await r.blpop(client_id)
return result
async def pushers_b(client_id, message,r):
client_id += "_replies"
await r.lpush(client_id, message)
async def websockets_thing(client_id):
REDIS_URL = 'redis://localhost:6379'
r = await aioredis.create_redis(REDIS_URL)
uri = "ws://localhost:1111/ws"
async with websockets.connect(uri) as babble_socket:
while True:
client_message = await snoopers_b(client_id, r)
print(f"Got Message of Client : {client_message}")
await babble_socket.send(client_message)
bot_message = await babble_socket.recv()
print(f"Got Message of Babble : {bot_message}")
if bot_message == "BYE":
await r.delete(client_id)
break
await pushers_b(client_id, bot_message, r)
loop = asyncio.get_event_loop()
loop.run_until_complete(websockets_thing(client_id))
loop.close()
</code></pre>
<p>The task of the arbiter is client-specific. It invokes a new connection so that it gets the message from the client_queue and then pushes it to connected WebSocket, gets a reply back and pushes reply back to middleware/invoker.</p>
<hr>
<p><code>dummychatbot.py</code> runs at port 1111 <em>(uvicorn dummychatbot:app --port 1111)</em></p>
<pre><code>from fastapi import FastAPI
from starlette.websockets import WebSocket
import random
app = FastAPI()
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
id = random.randint(10, 10000)
while True:
data = await websocket.receive_bytes()
if data == "Hey":
print(f"Hey User {id} : {data} Acknowledged :P")
await websocket.send_bytes(f"Hey User {id} : {data} Acknowledged :P")
data = await websocket.receive_bytes()
if data == "Hello" :
print(f"Hey User {id} : you already said Hey :P")
await websocket.send_bytes(f"Hey User {id} : {data} Acknowledged :P")
else:
print(f"Hey User {id} : Start with Hey instead of {data} :P")
await websocket.send_bytes(f"Hey User {id} : {data} Acknowledged :P")
</code></pre>
<p>A chatbot is the main hurdle. The above two programs are created so that context can be maintained using get and post requests. So if the user has previously said Hey and now says Hello it gets reply accordingly.</p>
<blockquote>
<p>I tried getting rid of WebSockets here but it faces deadlock problem
does not work for more than one clients concurrently
Middleware API : <a href="https://paste.pythondiscord.com/abopimehik.py" rel="nofollow noreferrer">https://paste.pythondiscord.com/abopimehik.py</a>
Chatbot Independent: <a href="https://paste.pythondiscord.com/odakitoteg.py" rel="nofollow noreferrer">https://paste.pythondiscord.com/odakitoteg.py</a></p>
</blockquote>
<hr>
<p><strong><em>Benchmarks</em></strong></p>
<p>The above code works for 900 concurrent users after that either there is Redis garbage collector error or server gets forced disconnected. Tested using this code: <a href="https://paste.pythondiscord.com/exomobelaz.py" rel="nofollow noreferrer">https://paste.pythondiscord.com/exomobelaz.py</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T13:51:10.407",
"Id": "456399",
"Score": "0",
"body": "In your `dummychatbot.py` script --> 2 `if` statements: how do you imagine `data` be simultaneously `data == \"Hey\"` AND `data == \"Hello\"` ???"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T06:44:33.933",
"Id": "456539",
"Score": "0",
"body": "@RomanPerekhrest I have edited the code it was a minor error while copy-pasting. I have added one more recieve_bytes(). So that It can act as a dummy of keeping the context."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T09:49:03.010",
"Id": "233463",
"Score": "3",
"Tags": [
"python",
"asynchronous",
"api",
"websocket"
],
"Title": "Middleware which lets developer maintain dynamic context"
}
|
233463
|
<p>Given an <em>N</em> x <em>N</em> matrix of positive integers, I need to find the shortest path from the first cell of matrix to the last cell of matrix. I can move exactly <em>x</em> steps from any cell, where <em>x</em> is the value of the cell. The possible movements are right or down, i.e from any cell <code>M[i][j]</code> I can move to locations <code>M[i + M[i][j]][j]</code> or <code>M[i][j +M[i][j]]</code>.</p>
<p>For example:</p>
<pre><code>int[][] matrix =
{
{1, 2, 1},
{1, 1, 1},
{1, 1, 1}
};
</code></pre>
<p>Returning it as a list of strings, the output would be: [(0, 0), (0, 1), (2, 1), (2, 2)]</p>
<p>I have implemented a working solution, but I am wondering if I can improve anything in terms of time complexity?</p>
<p>Here is the code:</p>
<pre><code>class Node {
// queue node used in BFS
// (x, y) represents coordinates of a cell in matrix
int x, y;
// maintain a parent node for printing final path
Node parent;
Node(int x, int y, Node parent) {
this.x = x;
this.y = y;
this.parent = parent;
}
@Override
public String toString() {
return "(" + x + ", " + y + ')';
}
}
class Solution {
LinkedList<String> shortestPathList = new LinkedList<>();
public List<String> getShortestPath(int[][] matrix) {
if (matrix == null) {
return Collections.emptyList();
}
Node node = findPath(matrix, 0, 0);
AddToPath(node);
return shortestPathList;
}
// possible movements
private static int[] row = {0, 1};
private static int[] col = {1, 0};
// The function returns false if is not a valid position
private static boolean isValid(int x, int y, int matrixLength) {
return (x >= 0 && x < matrixLength) && (y >= 0 && y < matrixLength);
}
// Find shortest route in the matrix from source cell (x, y) to
// destination cell (N - 1, N - 1)
public static Node findPath(int matrix[][], int x, int y) {
int matrixLength = matrix.length;
// create a queue and enqueue first node
Queue<Node> q = new ArrayDeque<>();
Node src = new Node(x, y, null);
q.add(src);
// set to check if matrix cell is visited before or not
Set<String> visited = new HashSet<>();
String key = src.x + "," + src.y;
visited.add(key);
// run till queue is not empty
while (!q.isEmpty()) {
// pop front node from queue and process it
Node curr = q.poll();
int i = curr.x, j = curr.y;
// return if destination is found
if (i == matrixLength - 1 && j == matrixLength - 1) {
return curr;
}
// value of current cell
int n = matrix[i][j];
// check both 2 possible movements from current cell
// and recur for each valid movement
for (int k = 0; k < 2; k++) {
// get next position coordinates using value of current cell
x = i + row[k] * n;
y = j + col[k] * n;
// check if it is possible to go to next position
// from current position
if (isValid(x, y, matrixLength)) {
// construct next cell node
Node next = new Node(x, y, curr);
key = next.x + "," + next.y;
// if it not visited yet
if (!visited.contains(key)) {
// push it into the queue and mark it as visited
q.add(next);
visited.add(key);
}
}
}
}
// return null if path is not possible
return null;
}
//function to get path from start to end
private void AddToPath(Node node) {
if (node == null) {
return;
}
shortestPathList.addFirst(node.toString());
printPath(node.parent);
}
}
</code></pre>
|
[] |
[
{
"body": "<h2>Access Modifiers & Variables</h2>\n\n<p>Firstly, I would recommend you only declare one variable per line. This improves readability and also encourages & facilitates commenting the declarations. It can however have the disadvantage of having an ugly wall of declarations at the start of your classes, though ordering your variables properly can help alleviate this problem.</p>\n\n<p>I personnally like to order class & instance variables like so : </p>\n\n<pre><code>- first, `static final` variables, with a name written in capitals snake_case, e.g. THIS_IS_A_CONSTANT\n\n- then, other `static` variables\n\n- `final` instance variables\n\n- within those, I like placing objects & composite types first, followed by variables of primitive types (`int`, `boolean`, `char` and so on)\n\n- finally, I like having all `public` variables first, then `protected` and finally `private` variables, although I like to put constants at the top whether they are `public` or `private`\n</code></pre>\n\n<p>Of course, this is only one way of doing it, and some people may think mine is strange or doesn't suit their personal style. I'd recommend you find or come up with one that you like and stick to it in the future.</p>\n\n<p>In practice, it would look something like this : </p>\n\n<pre><code>public class MyClass {\n private static final int SOME_CONSTANT = 25;\n public static final int SOME_OTHER_CONSTANT = 25; \n public static int aaa;\n public final int A;\n public List<Integer> integers;\n public Object object;\n public int x; \n\n ...\n\n public void someMethod() { ... }\n\n private void aPrivateMethod() { ... }\n\n public static void someOtherMethod() { ... }\n\n ...\n\n public int getX() {\n return x;\n }\n}\n</code></pre>\n\n<p>Obviously, the names given to the variables in my example are terrible and I only chose them because I couldn't be bothered to come up with a unique name for each one.</p>\n\n<p>You should also keep all you variable declarations together, and not mix them with method declarations. <code>public</code> variables should be avoided as they can be modified by anyone or anything; instead, you can declare them as <code>private</code> and add getters and/or setters to access them. This can also allow you to add logic inside the getter or setter methods, to check or validate the value provided for example.</p>\n\n<p>For methods, I again like placing all <code>public</code> methods first, followed by <code>protected</code> and then <code>private</code> ones; I generally put <code>static</code> methods at the bottom if there are any. And finally, I like to keep all getters & setters together, somewhere I can easily forget about them after they've been implemented.</p>\n\n<h2>Naming and Comments</h2>\n\n<p>Your code has a lot of comments, although most of them are superfluous and sometimes even wrong (e.g. <em>run till queue is not empty</em> followed by <code>while (!q.isEmpty())</code>). I personnally don't like comments very much and try to avoid them as much as I can, as they can require a lot of effort to maintain and are often not necessary in well-written code (which I can't claim to write yet, as much as I may want to); I also find that they make the code harder to read when too abundant, and my first instinct when looking at heavily-commented code is often to get rid of all the redundant comments -but that's just me.</p>\n\n<p>But that doesn't mean you shouldn't write comments! However, rather than explaining what the code is doing (which the code itself already does), comments should be used to explain things that cannot be inferred or understood simply by reading the code; for example, telling why one method or technique was used in this particular case rather than another.</p>\n\n<p>As an example, in the snippet below, the comment is only really useful because of how the variable <code>n</code> is named. If it were named <code>nbSteps</code>, or maybe <code>currentValue</code> (I'm not very good with names either, but I'm trying to improve), the comment would then be completely unnecessary. But if you see a reference to <code>n</code> somewhere else is the code, you might think <em>\"mmmh, what was n again? was it the size of the matrix? the number of steps I can take? or maybe the number of elements in the queue? who knows!\"</em>. </p>\n\n<pre><code>// value of current cell\nint n = matrix[i][j];\n</code></pre>\n\n<p>Similarly, the comment <code>// The function returns false if is not a valid position</code> doesn't tell us anything that we don't already know from simply reading the method's name.</p>\n\n<p>This takes us to variable names, and naming in general. Giving your variables, classes and methods meaningful names (that actually tell you what they are or what they do) is probably the most essential thing to making code easy to read. Again, most of your comments simply tell the reader what one things or another is or does, which accomplish very little.</p>\n\n<p>Shortened or abbreviated names like <code>curr</code> or <code>q</code> don't really have any benefit over longer, clearer ones, other than making the very first time you type the name a tiny bit shorter. Renaming them to <code>current</code> and <code>queue</code> for example will make the code easier to read later, and you shouldn't be worried about typing a few more characters each time; let you IDE help you and do its job!</p>\n\n<p>There is probably a lot more to say about comments and maybe JavaDoc, but I think the above outlines enough of the basics to improve your code commenting habits.</p>\n\n<p>I've rewritten your <code>Node</code> class using the above guidelines while keeping its functionality, structure and meaning as close to the original as possible :</p>\n\n<p>Node.java</p>\n\n<pre><code>// queue node used in BFS\npublic class Node {\n private final int x; // x-coordinate of a cell in matrix\n private final int y; // y-coordinate of a cell in matrix \n private final Node parent; // maintain a parent node for printing final path\n\n public Node(final int x, final int y, final Node parent) {\n this.x = x;\n this.y = y;\n this.parent = parent;\n }\n\n public int getX() {\n return x;\n }\n\n public int getY() {\n return y;\n }\n\n public Node getParent() {\n return parent;\n }\n\n @Override\n public String toString() {\n return '(' + x + \", \" + y + ')';\n }\n}\n</code></pre>\n\n<p>I've made all the fields in Node.java <code>private final</code> and added getters, as you don't ever change them after setting them in the constructor. You also used both single and double quotes for characters in your <code>toString()</code> method, which I've corrected.</p>\n\n<p>While trying to refactor and make improvements to your <code>Solution</code> class, I found I was having a hard time understanding how it's meant to be used; at first, I thought it was a static class, from which you call <code>findPath()</code>, which would return... a <code>Node</code>? But you have a mix of <code>static</code> and non-<code>static</code> methods and variables, and use them within one another, but have no constructur... </p>\n\n<p>Also, <code>getShortestPath()</code> returns a list that will only ever contain the node added to it by <code>findPath()</code>, which is simply the lower-right node (or destination, as you call it), so you only ever get the destination and never the actual full path. </p>\n\n<p>I would maybe suggest you refactor this portion of your code and submit it for another review, as -unless I'm mistaken- I do not believe it is actually functional right now.</p>\n\n<h2>Some additional things...</h2>\n\n<p>I strongly recommend you use the <code>final</code> keyword <em>everywhere</em> you can; method arguments, local variables... it indicates that the value you're assigning to the variable should not and will not change after it's been assigned. In other words, a <code>final</code> variable can only be assigned once, e.g. you can't do <code>final int x = 45; x = 25;</code>. </p>\n\n<p>Again, there's more to say about the use of <code>final</code>, but if you'd like to know more I recommend you take a look at this answer : <a href=\"https://softwareengineering.stackexchange.com/questions/98691/excessive-use-final-keyword-in-java\">https://softwareengineering.stackexchange.com/questions/98691/excessive-use-final-keyword-in-java</a>.</p>\n\n<p>I also notice that you didn't include imports in your questions; you should add those next time you ask a question on CodeReview.</p>\n\n<p>You declared an overload for <code>toString()</code> in your Node class, why not use it for the value provided to <code>key</code>? That way, if you ever want to change that key, you can simply change the <code>toString()</code> method instead of having to change it in two places. Or you could create another method just for this purpose, to keep the <code>toString()</code> for displaying a nicely formatted string, while the other one would be a simplified version of your <code>toString()</code>, used solely for generating the 'keys'.</p>\n\n<p>Another thing; you declare <code>shortestPathList</code> as a <code>LinkedList<String></code>, and <code>getShortestPath()</code> returns a <code>List<String></code>. I'd suggest you either change <code>shortestPathList</code>'s type to a <code>List<String></code>, or change the method's return type, as it will only ever return <code>shortestPathList</code>. You can find more information about this topic here : <a href=\"https://stackoverflow.com/questions/12321177/arraylist-or-list-declaration-in-java\">https://stackoverflow.com/questions/12321177/arraylist-or-list-declaration-in-java</a>.</p>\n\n<p>If I've made any mistakes or if you disagree with anything I've said, please refrain from throwing your keyboard at me but do point them out to me so that I can improve my own skills and knowledge!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T03:55:07.123",
"Id": "233509",
"ParentId": "233464",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T09:57:44.687",
"Id": "233464",
"Score": "3",
"Tags": [
"java",
"matrix",
"breadth-first-search"
],
"Title": "Finding shortest path in matrix"
}
|
233464
|
<p>I'm trying to write a script to delete event invites from my personal google calendar. I get invited to multiple events everyday such as "Click here to win an iPhone" etc.</p>
<p>I have written a google script to run each hour and delete any events where I am not the owner. However this is getting all events and then iterating through them to see if I am the owner in a for loop. This seems quite inefficient and takes a long time to run.</p>
<p>Is there a better way to achieve this.</p>
<p>Current code below:</p>
<pre><code>function deleteScamCalendarInvites() {
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear() + 5, date.getMonth(), 1);
var myCalendar = CalendarApp.getDefaultCalendar();
var myEvents = myCalendar.getEvents(firstDay, lastDay);
for(var i in myEvents){
if(myEvents[i].isOwnedByMe() == false){
var eventId = myEvents[i];
eventId.deleteEvent();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T10:35:16.017",
"Id": "456375",
"Score": "0",
"body": "you can try and play around with the q search paramater for events.list it says its full text search on all fields i tried creator.self=false not sure if it works or not. Its the only thing i can think of"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T19:08:00.417",
"Id": "456462",
"Score": "0",
"body": "Does Google Apps support filter functions by chance?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T10:15:13.817",
"Id": "233465",
"Score": "2",
"Tags": [
"google-apps-script"
],
"Title": "Google Script - Calendar events not owned by me"
}
|
233465
|
<p>I need to round numbers in a Word document, as I couldn't find a built-in way, here is my approach, it rounds all numbers in selection. </p>
<p>As I use VBA mainly in Excel I'm not sure whether I've done it the best way possible: </p>
<pre><code>Sub RoundNumbers()
Dim OrigRng As Range
Dim WorkRng As Range
Dim FindPattern As String
Dim FoundVal As String
Set OrigRng = Selection.Range
Set WorkRng = Selection.Range
FindPattern = "([0-9]){1,}.[0-9]{1,}"
Do
With WorkRng
.SetRange OrigRng.Start, OrigRng.End ' using "set WorkRng = OrigRng" would cause them to point to the same object (OrigRng is also changed when WorkRng is changed)
If .Find.Execute(findtext:=FindPattern, Forward:=True, _
MatchWildcards:=True) Then
.Expand wdWord ' I couldn't find a reliable way for greedy matching with Word regex, so I expand found range to word
.Text = round(CDbl(.Text) + 0.000001) ' VBA's round() perform bankers' rounding, adding a small number is a quick fix which works for my data
End If
End With
Loop While WorkRng.Find.Found
End Sub
</code></pre>
<p>Input example: </p>
<pre><code>Lorem ipsum dolor sit amet, consectetur adipiscing elit 15.12. Duis vestibulum gravida elit 3.1415, ac pretium neque suscipit ut. Pellentesque eu ipsum quam.
| 94.3 | 1.5 | 39 | 6.5 |
| 62.4 | 56.6 | 96.4 | 46.4 |
| 92 | 1.2 | 62.1 | 77.6 |
| 55.4 | 83.3 | 44.3 | 49.5 |
| 13.9 | 8.5 | 95.2 | 14.4 |
| 62.5 | 37.4 | 24 | 23.4 |
| 71.9 | 81.6 | 10.3 | 21.6 |
Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Suspendisse nec elementum massa. Donec sit amet volutpat ligula.
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T15:43:38.490",
"Id": "456433",
"Score": "0",
"body": "Could you add some mock-data?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T07:57:16.377",
"Id": "456555",
"Score": "0",
"body": "@TinMan: added sample input"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T09:53:07.110",
"Id": "456566",
"Score": "0",
"body": "Nice work! I read the article but that recommended adding `+0.000001` but did not think that it applied to whole numbers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T09:59:50.407",
"Id": "456568",
"Score": "0",
"body": "@TinMan: adding `0.000001` is needed to avoid performing bankers' rounding"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T10:36:58.880",
"Id": "233466",
"Score": "1",
"Tags": [
"vba",
"ms-word"
],
"Title": "Round numbers in MS Word"
}
|
233466
|
<p>My program (which eventually will be containerised) should be able to do the following:</p>
<ul>
<li>continuously listening for deployment and daemonsets in kubernetes (2 threads)</li>
<li>collect info needed (like annotations)</li>
<li>use the info collected in order to create objects in a remote database</li>
</ul>
<p>I could use some peer review for the thread part, which looks like this currently:</p>
<pre><code>#first thread to watch for deployments
def watch_deployments():
v1 = client.AppsV1Api()
w = watch.Watch()
last_seen_version = v1.list_deployment_for_all_namespaces().metadata.resource_version
while True:
for item in w.stream(v1.list_deployment_for_all_namespaces, pretty="pretty", resource_version=last_seen_version):
_ = {item["object"].metadata.name:[item["object"].kind, item["object"].metadata.namespace, item["object"].metadata.resource_version, item["object"].metadata.annotations]}
depl_lst.put(_)
def watch_daemonsets():
v1 = client.AppsV1Api()
w = watch.Watch()
last_seen_version = v1.list_daemon_set_for_all_namespaces().metadata.resource_version
while True:
for item in w.stream(v1.list_daemon_set_for_all_namespaces, pretty="pretty", resource_version=last_seen_version):
_ = {item["object"].metadata.name:[item["object"].kind, item["object"].metadata.namespace, item["object"].metadata.resource_version, item["object"].metadata.annotations]}
depl_lst.put(_)
if __name__ == '__main__':
current_obj = {}
depl_lst = Queue()
thread.start_new_thread(watch_deployments, ())
thread.start_new_thread(watch_daemonsets, ())
while True:
for i in range(depl_lst.qsize()):
current_obj = depl_lst.get()
#add object is the function in order to create the item in the remote database, not listed here
add_object()
depl_lst.task_done()
</code></pre>
<p>Its the same thing with what is being done here but in this case, the asyncio was being used:
<a href="https://medium.com/@sebgoa/kubernets-async-watches-b8fa8a7ebfd4" rel="nofollow noreferrer">https://medium.com/@sebgoa/kubernets-async-watches-b8fa8a7ebfd4</a></p>
|
[] |
[
{
"body": "<h3>Restructuring and consolidation</h3>\n\n<p><em>Dealing with API client instance</em><br>Instead of generating a new <code>client.AppsV1Api</code> instance in each separate thread - create the instance in the main thread and pass <em>shared</em> API client to your threads constructors:</p>\n\n<pre><code>if __name__ == '__main__':\n ...\n v1 = client.AppsV1Api()\n thread.start_new_thread(watch_deployments, (v1,))\n thread.start_new_thread(watch_daemonsets, (v1))\n ...\n</code></pre>\n\n<hr>\n\n<p>Both target functions <code>watch_deployments</code> and <code>watch_daemonsets</code> perform essentially the same set of actions and differ only in specific <strong><code>v1.list_...</code></strong> routine.<br>To eliminate duplication the common behavior is extracted into a separate function say <strong><code>_gather_watched_metadata</code></strong> that will accept a particular <code>v1.list_...</code> function object as <em>callable</em>:</p>\n\n<pre><code>def _gather_watched_metadata(list_func):\n w = watch.Watch()\n last_seen_version = list_func().metadata.resource_version\n while True:\n for item in w.stream(list_func, pretty=\"pretty\", resource_version=last_seen_version):\n metadata = item[\"object\"].metadata\n _ = {metadata.name: [item[\"object\"].kind, metadata.namespace,\n metadata.resource_version,\n metadata.annotations]}\n depl_lst.put(_)\n</code></pre>\n\n<p>As can be seen in the above function, to avoid repetitive indexing of nested attributes like <code>item[\"object\"].metadata</code> it is worth to extract it into a variable at once.</p>\n\n<p>Now, both target functions become just as below:</p>\n\n<pre><code>def watch_deployments(v1):\n _gather_watched_metadata(v1.list_deployment_for_all_namespaces)\n\n\ndef watch_daemonsets(v1):\n _gather_watched_metadata(v1.list_daemon_set_for_all_namespaces)\n</code></pre>\n\n<p>That can be shortened even further: both <code>watch_...</code> functions can be eliminated and you may run just with <code>_gather_watched_metadata</code> function and specific API routines passed as an argument :</p>\n\n<pre><code>...\nv1 = client.AppsV1Api()\nthread.start_new_thread(_gather_watched_metadata, (v1.list_deployment_for_all_namespaces,))\nthread.start_new_thread(_gather_watched_metadata, (v1.list_daemon_set_for_all_namespaces,))\n</code></pre>\n\n<p>But to apply the last <em>\"shortening\"</em> - is up to you ...</p>\n\n<hr>\n\n<p><em>Consuming <code>depl_lst</code> queue</em><br>Initiating <code>for</code> loop with <code>range</code> in this context:</p>\n\n<pre><code>while True:\n for i in range(depl_lst.qsize()):\n ...\n</code></pre>\n\n<p>is redundant as it's enough to check if queue is <strong>not</strong> <a href=\"https://docs.python.org/3/library/queue.html#queue.Queue.empty\" rel=\"nofollow noreferrer\">empty</a>:</p>\n\n<pre><code>while True:\n if not depl_lst.empty():\n current_obj = depl_lst.get()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T13:40:56.037",
"Id": "233474",
"ParentId": "233469",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T12:16:04.627",
"Id": "233469",
"Score": "2",
"Tags": [
"python",
"multithreading"
],
"Title": "Python multi-threaded kubernetes watcher"
}
|
233469
|
<p>How could I refactor this code to get it more cleaner:</p>
<pre><code>public List<TestDTO> Map(product product)
{
if (product == null || product.Tests == null || !product.productTests.Any()) return null;
return product.productTests.Select(x => _productService.Map(x)).ToList();
}
</code></pre>
<p>Is it possible to write this more cleaner?</p>
<p>Thanks</p>
<p>Cheers</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T13:13:51.493",
"Id": "456389",
"Score": "0",
"body": "Is this your real code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T13:20:06.453",
"Id": "456390",
"Score": "0",
"body": "@Heslacher Nop, just playing around"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T13:31:07.740",
"Id": "456393",
"Score": "0",
"body": "If the code is not real, then the question is **off-topic**. See https://codereview.meta.stackexchange.com/questions/3649/my-question-was-closed-as-being-off-topic-what-are-my-options/3652#3652"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T15:44:59.067",
"Id": "456434",
"Score": "0",
"body": "It might be better to ask questions like this on stackoverflow.com, but search stackoverflow.com first to see if it has already been answered."
}
] |
[
{
"body": "<p>One solution would be to stop passing <code>null</code> values around everywhere. That would require changes much wider than the scope of this method though.</p>\n\n<p>The biggest thing that can be won here is the <code>?.</code> operator. If the left hand side is <code>null</code>, the result will be <code>null</code> as well:</p>\n\n<pre><code>product?.productTests?.Select(x => _productService.Map(x))?.ToList();\n</code></pre>\n\n<p>will remove the need for the first two null checks.</p>\n\n<p>Returning a <code>null</code> instead of an empty list is... questionable, but if you must return <code>null</code> you can check afterwards:</p>\n\n<pre><code>public List<TestDTO> Map(product product)\n{\n var list = product?.productTests?.Select(x => _productService.Map(x))?.ToList();\n if (list?.Count == 0) return null;\n return list;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T13:24:57.177",
"Id": "456392",
"Score": "0",
"body": "isn't this enought ? `return product?.productTests?.Select(x => _productService.Map(x)).ToList();` if any of this is `null`, `null` will be returned, otherwise data.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T13:42:39.830",
"Id": "456394",
"Score": "0",
"body": "@Roxy'Pro I made a mistake, it should be `?.ToList` as well. Note that this is functionally different from your code, which also returns `null` when `product.productTests` is empty."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T17:09:28.363",
"Id": "456443",
"Score": "0",
"body": "If `list` is null, an exception is thrown on `if (list.Count == 0) return null;`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T07:07:18.947",
"Id": "456542",
"Score": "0",
"body": "@RickDavin good point. `list?.Count` it is :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T13:14:06.497",
"Id": "233471",
"ParentId": "233470",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "233471",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T13:05:47.147",
"Id": "233470",
"Score": "-2",
"Tags": [
"c#",
"null"
],
"Title": "How to get rid of many if null checks - c#"
}
|
233470
|
<p>I reworked the Game I did in FLTK some while ago: <a href="https://codereview.stackexchange.com/questions/201833/hunt-the-wumpus-gui-fltk">Hunt the Wumpus GUI (FLTK)</a></p>
<p>This time I used C++ with the Qt Framework. The result looks like this:</p>
<p><img src="https://i.stack.imgur.com/KJchC.jpg" width="325">
<img src="https://i.stack.imgur.com/t8QQF.jpg" width="325"></p>
<p>If you want to try out the game. The full code can be found in my Git Hub:
<a href="https://github.com/sandro4912/hunt-the-wumpus" rel="noreferrer">https://github.com/sandro4912/hunt-the-wumpus</a></p>
<p>One more hint not find in the Instructions. If the main game is started you can type "show" to show all the hazards in the neighbour rooms. Or "hide" to hide them. I have a basic keylogger looking for these words to be typed to debug/cheat.</p>
<p>Since the codebase is to big to post it here, I want to focus on some important parts of the code.</p>
<ul>
<li><strong>Room</strong>: represents a single Room in the Dungeon.</li>
<li><strong>DungeonView</strong>: The view which displays the dungeon. It manages dragging the player to annother room and shooting the arrows.</li>
<li><strong>Dungeon:</strong> Manages the Scene and the DungeonView and the rooms</li>
<li><strong>roomutility</strong>: helper functions to create the dungeon / connect the
rooms.</li>
</ul>
<p>Let me know what you think of the code.
Is it easy to read / understand?
Are there any bad practices?</p>
<p>Feel free to also check the other classes in the repo. If there's anything strange, let me know.</p>
<p><b> room.h </b></p>
<pre><code>#ifndef ROOM_H
#define ROOM_H
#include <QGraphicsWidget>
#include <array>
class QAction;
class Room : public QGraphicsWidget
{
Q_OBJECT
public:
explicit Room(QGraphicsItem *parent = nullptr);
void emitNeigbourHazards();
[[nodiscard]] bool isEmpty() const;
void setWumpus(bool value);
[[nodiscard]] bool hasWumpus() const;
void setPit(bool value);
[[nodiscard]] bool hasPit() const;
void setBat(bool value);
[[nodiscard]] bool hasBat() const;
void setPlayer(bool value);
[[nodiscard]] bool hasPlayer() const;
void setPlayerWasHere(bool value);
[[nodiscard]] bool playerWasHere() const;
void setTarget(bool value);
[[nodiscard]] bool isTarget() const;
void addNeighbour(Room *neighbour);
[[nodiscard]] QVector<Room *> neighbours() const;
void showContent(bool value);
void clear();
[[nodiscard]] QRectF boundingRect() const override;
void paint(QPainter *painter,
const QStyleOptionGraphicsItem *option,
QWidget *widget) override;
enum { Type = UserType + 1 };
[[nodiscard]] int type() const override;
signals:
void wumpusNear();
void batNear();
void pitNear();
void playerDiedFromWumpus();
void playerDiedFromPit();
void playerDraggedByBat();
void entered();
public slots:
void enter();
protected:
void contextMenuEvent(QGraphicsSceneContextMenuEvent *event) override;
void mousePressEvent(QGraphicsSceneMouseEvent *event) override;
void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override;
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override;
void dragEnterEvent(QGraphicsSceneDragDropEvent *event) override;
void dragLeaveEvent(QGraphicsSceneDragDropEvent *event) override;
void dropEvent(QGraphicsSceneDragDropEvent *event) override;
private slots:
void toggleGuessWumpus();
void toggleGuessPit();
void toggleGuessBat();
private:
bool isNeighbour(Room *room) const;
bool minDistanceReached(QGraphicsSceneMouseEvent *event,
Qt::MouseButton button);
void executePlayerDrag(QGraphicsSceneMouseEvent *event);
bool isPlayerDrag(QGraphicsSceneDragDropEvent *event);
void drawRoom(QPainter *painter, const QImage &roomImage);
void drawWumpus(QPainter *painter, const QImage &wumpusImage);
void drawBat(QPainter *painter, const QImage &batImage);
void drawPit(QPainter *painter, const QImage &pitImage);
void drawPlayer(QPainter *painter);
[[nodiscard]] QImage roomImage() const;
[[nodiscard]] QImage roomVisitedImage() const;
[[nodiscard]] QImage roomTargetImage() const;
[[nodiscard]] QImage batImage() const;
[[nodiscard]] QImage batConfirmedImage() const;
[[nodiscard]] QImage pitImage() const;
[[nodiscard]] QImage pitConfirmedImage() const;
[[nodiscard]] QImage wumpusImage() const;
[[nodiscard]] QImage wumpusConfirmedImage() const;
[[nodiscard]] QImage playerImage() const;
[[nodiscard]] QImage playerDraggedImage() const;
bool mBatConfirmed{ false };
bool mHasWumpus{ false };
bool mHasPit{ false };
bool mHasBat{ false };
bool mHasPlayer{ false };
bool mPlayerWasHere{ false };
bool mGuessWumpus{ false };
bool mGuessBat{ false };
bool mGuessPit{ false };
bool mShowContent{ false };
bool mIsTarget{ false };
QAction *mGuessWumpusAction;
QAction *mGuessBatAction;
QAction *mGuessPitAction;
QVector<Room *> mNeighbours;
};
#endif // ROOM_H
</code></pre>
<p><b> room.cpp </b></p>
<pre><code>#include "room.h"
#include "dragplayermimedata.h"
#include <QApplication>
#include <QAction>
#include <QCursor>
#include <QDrag>
#include <QMimeData>
#include <QGraphicsWidget>
#include <QGraphicsSceneMouseEvent>
#include <QGraphicsSceneContextMenuEvent>
#include <QMenu>
#include <QMenuBar>
#include <QMouseEvent>
#include <QPainter>
Room::Room(QGraphicsItem *parent)
: QGraphicsWidget(parent)
{
Q_ASSERT(roomImage().size() == roomVisitedImage().size());
Q_ASSERT(roomVisitedImage().size() == roomTargetImage().size());
Q_ASSERT(roomImage().height() ==
pitImage().height() + batImage().height());
Q_ASSERT(roomImage().height() ==
pitImage().height() + playerImage().height());
Q_ASSERT(roomImage().height() ==
pitImage().height() + wumpusImage().height());
Q_ASSERT(roomImage().width() ==
batImage().width() + playerImage().width() +
wumpusImage().width());
Q_ASSERT(batImage().size() == batConfirmedImage().size());
Q_ASSERT(pitImage().size() == pitConfirmedImage().size());
Q_ASSERT(wumpusImage().size() == wumpusConfirmedImage().size());
setAcceptDrops(true);
mGuessWumpusAction = new QAction{tr("Has &Wumpus")};
mGuessWumpusAction->setCheckable(true);
connect(mGuessWumpusAction, &QAction::triggered,
this, &Room::toggleGuessWumpus);
mGuessBatAction = new QAction{tr("Has &Bat")};
mGuessBatAction->setCheckable(true);
connect(mGuessBatAction, &QAction::triggered, this, &Room::toggleGuessBat);
mGuessPitAction = new QAction{tr("Has &Pit")};
mGuessPitAction->setCheckable(true);
connect(mGuessPitAction, &QAction::triggered, this, &Room::toggleGuessPit);
addAction(mGuessWumpusAction);
addAction(mGuessBatAction);
addAction(mGuessPitAction);
resize(boundingRect().size());
setVisible(false);
}
void Room::emitNeigbourHazards()
{
auto batEmitted = false;
auto wumpusEmitted = false;
auto pitEmitted = false;
for(const auto& neigbour : mNeighbours) {
if(neigbour == nullptr) {
continue;
}
if (!batEmitted && neigbour->hasBat()) {
emit batNear();
batEmitted = true;
}
if (!wumpusEmitted && neigbour->hasWumpus()) {
emit wumpusNear();
wumpusEmitted = true;
}
if (!pitEmitted && neigbour->hasPit()) {
emit pitNear();
pitEmitted = true;
}
}
}
bool Room::isEmpty() const
{
return !hasPlayer() && !hasBat()&& !hasPit() && !hasWumpus();
}
void Room::setWumpus(bool value)
{
if(value && hasPlayer()) {
emit playerDiedFromWumpus();
}
mHasWumpus = value;
update();
}
bool Room::hasWumpus() const
{
return mHasWumpus;
}
void Room::setPit(bool value)
{
mHasPit = value;
update();
}
bool Room::hasPit() const
{
return mHasPit;
}
void Room::setBat(bool value)
{
mHasBat = value;
update();
}
bool Room::hasBat() const
{
return mHasBat;
}
void Room::setPlayer(bool value)
{
mHasPlayer = value;
if (value) {
mPlayerWasHere = true;
}
update();
}
bool Room::hasPlayer() const
{
return mHasPlayer;
}
void Room::setPlayerWasHere(bool value)
{
mPlayerWasHere = value;
update();
}
bool Room::playerWasHere() const
{
return mPlayerWasHere;
}
void Room::setTarget(bool value)
{
mIsTarget = value;
update();
}
bool Room::isTarget() const
{
return mIsTarget;
}
void Room::addNeighbour(Room *neighbour)
{
mNeighbours.push_back(neighbour);
}
QVector<Room *> Room::neighbours() const
{
return mNeighbours;
}
void Room::showContent(bool value)
{
mShowContent = value;
update();
}
void Room::clear()
{
mBatConfirmed = false;
mHasWumpus = false;
mHasPit = false;
mHasBat = false;
mHasPlayer = false;
mPlayerWasHere = false;
mGuessWumpus = false;
mGuessBat = false;
mGuessPit = false;
mShowContent = false;
mIsTarget = false;
}
QRectF Room::boundingRect() const
{
return QRectF{ 0, 0,
static_cast<qreal>(roomImage().width()),
static_cast<qreal>(roomImage().height())};
}
void Room::paint(
QPainter *painter,
const QStyleOptionGraphicsItem *option,
QWidget *widget)
{
Q_UNUSED(option)
Q_UNUSED(widget)
if (isTarget()) {
drawRoom(painter, roomTargetImage());
}
else if (playerWasHere()) {
drawRoom(painter, roomVisitedImage());
}
else {
drawRoom(painter, roomImage());
}
if (hasPlayer()) {
drawPlayer(painter);
}
if (mShowContent) {
if (hasWumpus()) {
drawWumpus(painter, wumpusConfirmedImage());
}
if (hasBat()) {
drawBat(painter, batConfirmedImage());
}
if (hasPit()) {
drawPit(painter, pitConfirmedImage());
}
}
else {
if (mGuessWumpus) {
drawWumpus(painter, wumpusImage());
}
if (mBatConfirmed) {
drawBat(painter, batConfirmedImage());
}
else if (mGuessBat) {
drawBat(painter, batImage());
}
if (mGuessPit) {
drawPit(painter, pitImage());
}
}
}
int Room::type() const
{
return Type;
}
void Room::enter()
{
if (mHasWumpus) {
emit playerDiedFromWumpus();
return;
}
if (mHasPit) {
emit playerDiedFromPit();
return;
}
if (mHasBat) {
emit playerDraggedByBat();
mBatConfirmed = true;
mGuessBatAction->setChecked(true);
mGuessBatAction->setEnabled(false);
return;
}
setVisible(true);
for(auto &neighbour : mNeighbours) {
neighbour->setVisible(true);
neighbour->update();
}
emitNeigbourHazards();
emit entered();
setPlayer(true);
}
void Room::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
{
if (hasPlayer()) {
return;
}
QMenu menu;
menu.addAction(mGuessWumpusAction);
menu.addAction(mGuessBatAction);
menu.addAction(mGuessPitAction);
menu.exec(event->screenPos());
}
void Room::mousePressEvent(QGraphicsSceneMouseEvent *event)
// needs to be overriden to toggle mouseMoveEvent
{
Q_UNUSED(event)
}
void Room::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
if(!hasPlayer()) {
return;
}
if (minDistanceReached(event, Qt::LeftButton)) {
executePlayerDrag(event);
}
}
void Room::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
// needs to be overriden to toggle mouseMoveEvent
{
Q_UNUSED(event)
}
void Room::dragEnterEvent(QGraphicsSceneDragDropEvent *event)
{
const auto dragPlayerData =
qobject_cast<const DragPlayerMimeData *>(event->mimeData());
if(dragPlayerData && isNeighbour(dragPlayerData->room()) &&
dragPlayerData->imageData() == playerDraggedImage()) {
event->setAccepted(true);
}
else {
event->setAccepted(false);
}
}
void Room::dragLeaveEvent(QGraphicsSceneDragDropEvent *event)
{
if (isPlayerDrag(event)) {
setPlayer(false);
update();
}
}
void Room::dropEvent(QGraphicsSceneDragDropEvent *event)
{
const auto roomData =
qobject_cast<const DragPlayerMimeData *>(event->mimeData());
if(roomData && isNeighbour(roomData->room()) &&
roomData->imageData() == playerDraggedImage()) {
enter();
update();
event->setAccepted(true);
}
else {
event->setAccepted(false);
}
}
void Room::toggleGuessWumpus()
{
if(mGuessWumpus) {
mGuessWumpus = false;
mGuessWumpusAction->setChecked(false);
}
else {
mGuessWumpus = true;
mGuessWumpusAction->setChecked(true);
}
update();
}
void Room::toggleGuessPit()
{
if(mGuessPit) {
mGuessPit = false;
mGuessPitAction->setChecked(false);
}
else {
mGuessPit = true;
mGuessPitAction->setChecked(true);
}
update();
}
void Room::toggleGuessBat()
{
if(mGuessBat) {
mGuessBat = false;
mGuessBatAction->setChecked(false);
}
else {
mGuessBat = true;
mGuessBatAction->setChecked(true);
}
update();
}
bool Room::isNeighbour(Room *room) const
{
if (room == nullptr) {
return false;
}
for(const auto &neighbour : mNeighbours) {
if (room == neighbour) {
return true;
}
}
return false;
}
bool Room::minDistanceReached(QGraphicsSceneMouseEvent *event,
Qt::MouseButton button)
{
return QLineF(event->screenPos(),
event->buttonDownScreenPos(button))
.length() >= QApplication::startDragDistance();
}
void Room::executePlayerDrag(QGraphicsSceneMouseEvent *event)
{
setPlayer(false);
auto drag = new QDrag(event->widget());
auto mime = new DragPlayerMimeData;
mime->setRoom(this);
drag->setMimeData(mime);
mime->setImageData(playerDraggedImage());
drag->setPixmap(QPixmap::fromImage(playerDraggedImage()));
drag->setHotSpot(QPoint(0, 0));
auto result = drag->exec();
if (result == Qt::IgnoreAction) {
setPlayer(true);
}
}
bool Room::isPlayerDrag(QGraphicsSceneDragDropEvent *event)
{
return qobject_cast<const DragPlayerMimeData *>(event->mimeData()) &&
event->mimeData()->imageData() == playerDraggedImage();
}
void Room::drawRoom(QPainter *painter, const QImage &roomImage)
{
painter->drawImage(boundingRect(), roomImage);
}
void Room::drawWumpus(QPainter *painter, const QImage &wumpusImage)
{
auto xOffset = roomImage().width() - wumpusImage.width();
painter->drawImage(
QPointF{boundingRect().x() + xOffset, boundingRect().y()},
wumpusImage);
}
void Room::drawBat(QPainter *painter, const QImage &batImage)
{
painter->drawImage(
QPointF{boundingRect().x(), boundingRect().y()}, batImage);
}
void Room::drawPit(QPainter *painter, const QImage &pitImage)
{
auto yOffset = roomImage().height() - pitImage.height();
painter->drawImage(
QPointF{boundingRect().x(), boundingRect().y() + yOffset},
pitImage);
}
void Room::drawPlayer(QPainter *painter)
{
auto xOffset = roomImage().width() - wumpusImage().width() -
playerImage().width();
painter->drawImage(
QPointF{boundingRect().x() + xOffset, boundingRect().y()},
playerImage());
}
QImage Room::roomImage() const
{
return QImage{":/ressources/room.png"};
}
QImage Room::roomVisitedImage() const
{
return QImage{":/ressources/room_visited.png"};
}
QImage Room::roomTargetImage() const
{
return QImage{":/ressources/room_target.png"};
}
QImage Room::batImage() const
{
return QImage{":/ressources/bat.png"};
}
QImage Room::batConfirmedImage() const
{
return QImage{":/ressources/bat_confirmed.png"};
}
QImage Room::pitImage() const
{
return QImage{":/ressources/pit.png"};
}
QImage Room::pitConfirmedImage() const
{
return QImage{":/ressources/pit_confirmed.png"};
}
QImage Room::wumpusImage() const
{
return QImage{":/ressources/wumpus.png"};
}
QImage Room::wumpusConfirmedImage() const
{
return QImage{":/ressources/wumpus_confirmed.png"};
}
QImage Room::playerImage() const
{
return QImage{":/ressources/player.png"};
}
QImage Room::playerDraggedImage() const
{
return QImage{":/ressources/player_dragged.png"};
}
</code></pre>
<p><b>dungeonview.h</b></p>
<pre><code>#ifndef DUNGEONVIEW_H
#define DUNGEONVIEW_H
#include <QGraphicsView>
class Room;
class DungeonView : public QGraphicsView
{
Q_OBJECT
public:
explicit DungeonView(QWidget *parent = nullptr);
signals:
void shootHitWumpus();
void shootMissedWumpus();
protected:
void mousePressEvent(QMouseEvent *event) override;
void mouseReleaseEvent(QMouseEvent *event) override;
void mouseMoveEvent(QMouseEvent *event) override;
private:
void startShootArrowMode(Room *room);
void stopShootArrowMode(QMouseEvent *event);
void shootArrow(QMouseEvent *event);
void startDragPlayerMode(QMouseEvent *event);
void stopDragPlayerMode(QMouseEvent *event);
[[nodiscard]] bool maxArrowRangeReached() const;
bool isMarked(Room *room) const;
bool isNeigbourOfLastMarkedRoom(Room *room) const;
bool leftRoom(Room *current, Room* last);
bool enteredRoom(Room *current, Room* last);
static constexpr auto mArrowRoomRange{ 3 };
bool mShootArrowSelectOn{ false };
Room *mlastRoom{ nullptr };
QVector<Room *> mMarkedRooms;
};
#endif // DUNGEONVIEW_H
</code></pre>
<p><b>dungeonview.cpp</b></p>
<pre><code>#include "dungeonview.h"
#include "room.h"
#include <QDebug>
#include <QMouseEvent>
#include <algorithm>
DungeonView::DungeonView(QWidget *parent)
:QGraphicsView{ parent }
{
setMouseTracking(true);
}
void DungeonView::mousePressEvent(QMouseEvent *event)
{
if (auto room = qgraphicsitem_cast<Room *>(itemAt(event->pos()));
room && room->hasPlayer()) {
if (event->button() == Qt::RightButton) {
startShootArrowMode(room);
}
else if (event->button() == Qt::LeftButton) {
startDragPlayerMode(event);
}
}
}
void DungeonView::mouseReleaseEvent(QMouseEvent *event)
{
if (mShootArrowSelectOn && event->button() == Qt::RightButton) {
stopShootArrowMode(event);
}
else if (auto room = qgraphicsitem_cast<Room *>(itemAt(event->pos())) ;
room && room->hasPlayer() &&
event->button() == Qt::LeftButton) {
stopDragPlayerMode(event);
}
}
void DungeonView::mouseMoveEvent(QMouseEvent *event)
{
auto room = qgraphicsitem_cast<Room *>(itemAt(event->pos()));
if(room && !mShootArrowSelectOn) {
QGraphicsView::mouseMoveEvent(event);
}
if(room == mlastRoom) {
return;
}
if(!mShootArrowSelectOn && leftRoom(room, mlastRoom)) {
setCursor(Qt::ArrowCursor);
}
else if (mShootArrowSelectOn && !maxArrowRangeReached() &&
!isMarked(room) && isNeigbourOfLastMarkedRoom(room)) {
room->setTarget(true);
mMarkedRooms.push_back(room);
}
else if (enteredRoom(room, mlastRoom) && room->hasPlayer()) {
setCursor(Qt::OpenHandCursor);
}
mlastRoom = room;
}
void DungeonView::startShootArrowMode(Room *room)
{
mShootArrowSelectOn = true;
room->setTarget(true);
mlastRoom = room;
mMarkedRooms.push_back(room);
setCursor(Qt::CrossCursor);
}
void DungeonView::stopShootArrowMode(QMouseEvent *event)
{
for (auto &room : mMarkedRooms) {
room->setTarget(false);
}
if (mMarkedRooms.size() > 1) {
shootArrow(event);
}
mMarkedRooms.clear();
mlastRoom = nullptr;
mShootArrowSelectOn = false;
setCursor(Qt::ArrowCursor);
}
void DungeonView::shootArrow(QMouseEvent *event)
{
auto room = qgraphicsitem_cast<Room *>(itemAt(event->pos()));
if(room && room == mMarkedRooms.back()) {
auto hitWumpus = false;
for (auto i = 1; i < mMarkedRooms.size(); ++i) {
if(room->hasWumpus()) {
emit shootHitWumpus();
hitWumpus = true;
break;
}
}
if (!hitWumpus) {
emit shootMissedWumpus();
}
}
}
void DungeonView::startDragPlayerMode(QMouseEvent *event)
{
setCursor(Qt::ClosedHandCursor);
QGraphicsView::mousePressEvent(event);
}
void DungeonView::stopDragPlayerMode(QMouseEvent *event)
{
setCursor(Qt::OpenHandCursor);
QGraphicsView::mousePressEvent(event);
}
bool DungeonView::maxArrowRangeReached() const
{
return mMarkedRooms.size() > mArrowRoomRange;
}
bool DungeonView::isMarked(Room *room) const
{
if(mMarkedRooms.empty()) {
return false;
}
return std::find(mMarkedRooms.begin(),
mMarkedRooms.end(), room) != mMarkedRooms.end();
}
bool DungeonView::isNeigbourOfLastMarkedRoom(Room *room) const
{
if(mMarkedRooms.empty()) {
return false;
}
auto lastRoomNeigbours = mMarkedRooms.back()->neighbours();
return std::find(lastRoomNeigbours.begin(),
lastRoomNeigbours.end(), room) != lastRoomNeigbours.end();
}
bool DungeonView::leftRoom(Room *current, Room *last)
{
return (current == nullptr && last != nullptr);
}
bool DungeonView::enteredRoom(Room *current, Room *last)
{
return (current != nullptr && last == nullptr);
}
</code></pre>
<p><b>dungeon.h</b></p>
<pre><code>#ifndef DUNGEON_H
#define DUNGEON_H
#include <QWidget>
class Room;
class QGraphicsScene;
class QGraphicsLineItem;
class DungeonView;
class Dungeon : public QWidget
{
Q_OBJECT
public:
explicit Dungeon(QWidget *parent = nullptr);
void showHazards(bool value);
void enter();
void reset();
[[nodiscard]] int remainingArrows() const;
signals:
void wumpusNear();
void batNear();
void pitNear();
void playerDraggedByBat();
void playerDiedFromWumpus();
void playerDiedFromPit();
void playerIsOutOfArrows();
void playerKilledWumpus();
void enteredRoom();
void arrowShot();
private slots:
void moveWumpusIfWakeUp();
void showLinesToNeigboursOfRoom();
void decreaseArrows();
private:
void scaleViewToSize();
void emptyRooms();
void hideDungeon();
void createRooms();
void connectToRooms();
void addRoomsToScene();
void addLinesToScene();
void addLineToNeigbours(const Room *room);
bool lineExistsInScene(const QLineF &line);
QGraphicsLineItem *findLineInScene(const QLineF &line);
static constexpr auto mCountOfRooms = 20;
static constexpr auto mCountOfPits = 2;
static constexpr auto mCountOfBats = 2;
static constexpr auto mCountOfArrows = 5;
int mRemainingArrows{ mCountOfArrows };
QGraphicsScene *mGraphicsScene;
DungeonView *mDungeonView;
QVector<Room *> mRooms;
};
#endif // DUNGEON_H
</code></pre>
<p><b>dungeon.cpp</b></p>
<pre><code>#include "dungeon.h"
#include "dungeonview.h"
#include "room.h"
#include "roomutility.h"
#include <QGuiApplication>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QRandomGenerator>
#include <QScreen>
#include <QVBoxLayout>
#include <QDebug>
#include <algorithm>
Dungeon::Dungeon(QWidget *parent)
: QWidget(parent),
mGraphicsScene{ new QGraphicsScene },
mDungeonView{ new DungeonView }
{
createRooms();
connectRoomsAsDodekaeder(mRooms);
setPositionOfRooms(mRooms);
addRoomsToScene();
addLinesToScene();
connectToRooms();
populateRoomsRandom(mRooms, mCountOfPits, mCountOfBats);
mDungeonView->setScene(mGraphicsScene);
mDungeonView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
mDungeonView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
connect(mDungeonView, &DungeonView::shootHitWumpus,
this, &Dungeon::playerKilledWumpus);
connect(mDungeonView, &DungeonView::shootMissedWumpus,
this, &Dungeon::moveWumpusIfWakeUp);
connect(mDungeonView, &DungeonView::shootHitWumpus,
this, &Dungeon::decreaseArrows);
connect(mDungeonView, &DungeonView::shootMissedWumpus,
this, &Dungeon::decreaseArrows);
connect(mDungeonView, &DungeonView::shootHitWumpus,
this, &Dungeon::arrowShot);
connect(mDungeonView, &DungeonView::shootMissedWumpus,
this, &Dungeon::arrowShot);
auto layout = new QVBoxLayout;
layout->addWidget(mDungeonView);
layout->setSpacing(0);
layout->setContentsMargins(0,0,0,0);
setLayout(layout);
scaleViewToSize();
setFixedSize(size());
}
void Dungeon::showHazards(bool value)
{
for(auto &room : mRooms) {
room->showContent(value);
}
}
void Dungeon::enter()
{
for (;;) {
auto idx = QRandomGenerator::global()->bounded(0, mRooms.size() - 1);
if(mRooms[idx]->isEmpty()) {
mRooms[idx]->enter();
break;
}
}
}
void Dungeon::reset()
{
emptyRooms();
hideDungeon();
mRemainingArrows = mCountOfArrows;
populateRoomsRandom(mRooms, mCountOfPits, mCountOfBats);
}
int Dungeon::remainingArrows() const
{
return mRemainingArrows;
}
void Dungeon::moveWumpusIfWakeUp()
{
auto direction = QRandomGenerator::global()->bounded(0, 3);
if (direction == 3) { // 25% chance that wumpus won't move
return;
}
auto wumpusRoomIt{ std::find_if(mRooms.begin(), mRooms.end(),
[](Room *room) { return room->hasWumpus(); }) };
(*wumpusRoomIt)->setWumpus(false);
auto newRoom = (*wumpusRoomIt)->neighbours()[direction];
newRoom->setWumpus(true);
auto playerRoomIt{ std::find_if(mRooms.begin(), mRooms.end(),
[](Room *room) { return room->hasPlayer(); }) };
(*playerRoomIt)->emitNeigbourHazards();
}
void Dungeon::showLinesToNeigboursOfRoom()
{
auto room = qobject_cast<Room *>(sender());
auto startPoint = room->mapToScene(room->rect().center());
auto neighbours = room->neighbours();
for (const auto &neighbour : neighbours) {
auto endPoint = neighbour->mapToScene(neighbour->rect().center());
QLineF line{ startPoint, endPoint };
auto lineItem = findLineInScene(line);
if (lineItem) {
lineItem->show();
}
}
}
void Dungeon::decreaseArrows()
{
--mRemainingArrows;
if (mRemainingArrows == 0) {
emit playerIsOutOfArrows();
}
}
void Dungeon::scaleViewToSize()
{
mDungeonView->fitInView(mDungeonView->scene()->sceneRect(),
Qt::KeepAspectRatio);
}
void Dungeon::emptyRooms()
{
for(auto room : mRooms) {
room->clear();
}
}
void Dungeon::hideDungeon()
{
auto items = mGraphicsScene->items();
for (auto &item : items) {
item->hide();
}
}
void Dungeon::createRooms()
{
mRooms.reserve(mCountOfRooms);
for(int i = 0; i< mCountOfRooms; ++i) {
mRooms.push_back(new Room);
}
}
void Dungeon::connectToRooms()
{
for(const auto &room : mRooms) {
connect(room, &Room::entered,
this, &Dungeon::showLinesToNeigboursOfRoom);
connect(room, &Room::entered,
this, &Dungeon::enteredRoom);
connect(room, &Room::wumpusNear,
this, &Dungeon::wumpusNear);
connect(room, &Room::batNear,
this, &Dungeon::batNear);
connect(room, &Room::pitNear,
this, &Dungeon::pitNear);
connect(room, &Room::playerDiedFromWumpus,
this, &Dungeon::playerDiedFromWumpus);
connect(room, &Room::playerDiedFromPit,
this, &Dungeon::playerDiedFromPit);
connect(room, &Room::playerDraggedByBat,
this, &Dungeon::playerDraggedByBat);
connect(room, &Room::playerDraggedByBat,
this, &Dungeon::enter);
}
}
void Dungeon::addRoomsToScene()
{
for(const auto &room : mRooms) {
mGraphicsScene->addItem(room);
}
}
void Dungeon::addLinesToScene()
{
for (const auto& room : mRooms) {
addLineToNeigbours(room);
}
}
void Dungeon::addLineToNeigbours(const Room *room)
{
auto startPoint = room->mapToScene(room->rect().center());
constexpr auto lineWidth = 10;
QPen pen;
pen.setBrush(Qt::black);
pen.setWidth(lineWidth);
auto neighbours = room->neighbours();
for (const auto &neighbour : neighbours) {
auto endPoint = neighbour->mapToScene(neighbour->rect().center());
QLineF line{ startPoint, endPoint };
if (lineExistsInScene(line)) {
continue;
}
auto lineItem = mGraphicsScene->addLine(line, pen);
lineItem->setZValue(-1);
lineItem->hide();
}
mGraphicsScene->update();
}
bool Dungeon::lineExistsInScene(const QLineF &line)
{
return findLineInScene(line) != nullptr;
}
QGraphicsLineItem *Dungeon::findLineInScene(const QLineF &line)
{
auto items = mGraphicsScene->items();
for(const auto &item : items) {
auto existingLineItem = qgraphicsitem_cast<QGraphicsLineItem *>(item);
if(existingLineItem) {
auto p1 = existingLineItem->line().p1();
auto p2 = existingLineItem->line().p2();
auto newP1 = line.p1();
auto newP2 = line.p2();
if((p1 == newP1 && p2 == newP2) || (p1 == newP2 && p2 == newP1)) {
return existingLineItem;
}
}
}
return nullptr;
}
</code></pre>
<p><b>roomutility.h</b></p>
<pre><code>#ifndef ROOMUTILITY_H
#define ROOMUTILITY_H
#include <QVector>
class Room;
void connectRoomsAsDodekaeder(QVector<Room *> &rooms);
void setNeigbours(QVector<Room *> &rooms,
int roomNo,
int roomNoNeigbourOne,
int roomNoNeigbourTwo,
int roomNoNeigbourThree);
void populateRoomsRandom(
QVector<Room *> &rooms, int countOfPits, int countOfBats);
void setPositionOfRooms(QVector<Room *> &rooms);
Room *randomRoom(const QVector<Room *> &rooms);
#endif // ROOMUTILITY_H
</code></pre>
<p><b>roomutility.cpp</b></p>
<pre><code>#include "roomutility.h"
#include "room.h"
#include <QRandomGenerator>
static constexpr auto countOfRooms = 20;
void connectRoomsAsDodekaeder(QVector<Room *> &rooms)
{
Q_ASSERT(rooms.size() == countOfRooms);
setNeigbours(rooms, 0, 1, 4, 19);
setNeigbours(rooms, 1, 0 , 2, 17);
setNeigbours(rooms, 2, 1 , 3, 15);
setNeigbours(rooms, 3, 2 , 4, 13);
setNeigbours(rooms, 4, 0 , 3, 5);
setNeigbours(rooms, 5, 4 , 6, 12);
setNeigbours(rooms, 6, 5 , 7, 19);
setNeigbours(rooms, 7, 6 , 8, 11);
setNeigbours(rooms, 8, 7 , 9, 18);
setNeigbours(rooms, 9, 8 , 10, 16);
setNeigbours(rooms, 10, 9 , 11, 14);
setNeigbours(rooms, 11, 7 , 10, 12);
setNeigbours(rooms, 12, 5 , 11, 13);
setNeigbours(rooms, 13, 3 , 12, 14);
setNeigbours(rooms, 14, 10 , 13, 15);
setNeigbours(rooms, 15, 2 , 14, 16);
setNeigbours(rooms, 16, 9 , 15, 17);
setNeigbours(rooms, 17, 1 , 16, 18);
setNeigbours(rooms, 18, 8 , 17, 19);
setNeigbours(rooms, 19, 0 , 6, 18);
}
void setNeigbours(QVector<Room *> &rooms,
int roomNo,
int roomNoNeigbourOne,
int roomNoNeigbourTwo,
int roomNoNeigbourThree)
{
Q_ASSERT(roomNo >= 0 && roomNo < rooms.size());
Q_ASSERT(roomNoNeigbourOne >= 0 && roomNoNeigbourOne < rooms.size());
Q_ASSERT(roomNoNeigbourTwo >= 0 && roomNoNeigbourTwo < rooms.size());
Q_ASSERT(roomNoNeigbourThree >= 0 && roomNoNeigbourThree < rooms.size());
Q_ASSERT(roomNo != roomNoNeigbourOne);
Q_ASSERT(roomNoNeigbourOne != roomNoNeigbourTwo);
Q_ASSERT(roomNoNeigbourTwo != roomNoNeigbourThree);
Q_ASSERT(roomNoNeigbourThree != roomNo);
rooms[roomNo]->addNeighbour(rooms[roomNoNeigbourOne]);
rooms[roomNo]->addNeighbour(rooms[roomNoNeigbourTwo]);
rooms[roomNo]->addNeighbour(rooms[roomNoNeigbourThree]);
}
void populateRoomsRandom(
QVector<Room *> &rooms, int countOfPits, int countOfBats)
{
constexpr auto countOfWumpus = 1;
Q_ASSERT(countOfPits >= 0);
Q_ASSERT(countOfBats >= 0);
Q_ASSERT(countOfPits + countOfBats + countOfWumpus < rooms.size());
auto room = randomRoom(rooms);
room->setWumpus(true);
for (auto i = 0; i < countOfPits; ++i) {
for (;;) {
auto room = randomRoom(rooms);
if (room->isEmpty()) {
room->setPit(true);
break;
}
}
}
for (auto i = 0; i < countOfBats; ++i) {
for (;;) {
auto room = randomRoom(rooms);
if (room->isEmpty()) {
room->setBat(true);
break;
}
}
}
}
void setPositionOfRooms(QVector<Room *> &rooms)
{
const auto roomWidth = static_cast<int>(rooms[0]->size().width());
const auto roomHeight = static_cast<int>(rooms[0]->size().height());
QVector<QPoint> points
{
QPoint{ 400 - roomWidth / 2, 450 - roomHeight / 2},
QPoint{ 600 - roomWidth / 2, 450 - roomHeight / 2},
QPoint{ 600 - roomWidth / 2, 550 - roomHeight / 2},
QPoint{ 500 - roomWidth / 2, 600 - roomHeight / 2},
QPoint{ 400 - roomWidth / 2, 550 - roomHeight / 2},
QPoint{ 250 - roomWidth / 2, 600 - roomHeight / 2},
QPoint{ 250 - roomWidth / 2, 450 - roomHeight / 2},
QPoint{ 100 - roomWidth / 2, 300 - roomHeight / 2},
QPoint{ 500 - roomWidth / 2, 75 - roomHeight / 2},
QPoint{ 900 - roomWidth / 2, 300 - roomHeight / 2},
QPoint{ 900 - roomWidth / 2, 900 - roomHeight / 2},
QPoint{ 100 - roomWidth / 2, 900 - roomHeight / 2},
QPoint{ 300 - roomWidth / 2, 750 - roomHeight / 2},
QPoint{ 500 - roomWidth / 2, 750 - roomHeight / 2},
QPoint{ 750 - roomWidth / 2, 750 - roomHeight / 2},
QPoint{ 750 - roomWidth / 2, 600 - roomHeight / 2},
QPoint{ 800 - roomWidth / 2, 450 - roomHeight / 2},
QPoint{ 700 - roomWidth / 2, 300 - roomHeight / 2},
QPoint{ 500 - roomWidth / 2, 200 - roomHeight / 2},
QPoint{ 350 - roomWidth / 2, 300 - roomHeight / 2},
};
Q_ASSERT(points.size() == rooms.size());
for(auto i = 0; i<rooms.size(); ++i) {
rooms[i]->setPos(points[i]);
}
}
Room *randomRoom(const QVector<Room *> &rooms)
{
auto idx = QRandomGenerator::global()->bounded(0, rooms.size() - 1);
return rooms[idx];
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T18:58:07.267",
"Id": "456457",
"Score": "0",
"body": "Interesting question -- does drag and drop work for you? It's failing here on Qt version 5.12 on a 64-bit Fedora platform but I don't see a problem in the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T19:04:43.107",
"Id": "456458",
"Score": "0",
"body": "yes drag and drop works just fine on my system. I only tryed it on KDE Neon 64Bit. I can try it out on windows 10 aswell. What means it fails you can even drag the player to ann other room?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T19:05:33.813",
"Id": "456459",
"Score": "0",
"body": "Which version of Qt are you using?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T19:07:16.813",
"Id": "456461",
"Score": "0",
"body": "I used Qt 5.13.2"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T19:13:13.887",
"Id": "456463",
"Score": "0",
"body": "Also tryed it on a Windows 10 64 Bit VM. Drag and drop works aswell. The VM has still Qt 5.12.4"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T19:33:36.063",
"Id": "456465",
"Score": "1",
"body": "Maybe the issue is even a bug in the fedora. One time i found a bug in Qt with a project which only happened in neon."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T18:40:03.897",
"Id": "456619",
"Score": "0",
"body": "The drag-and-drop problem is apparently a bug in [`mutter`](https://developer.gnome.org/meta/3.16/index.html). I'll put in a bug report over the weekend."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T20:08:59.423",
"Id": "456629",
"Score": "2",
"body": "nice that you could find it. so my programm helped to make the linux better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-09T16:59:07.913",
"Id": "456905",
"Score": "0",
"body": "@Sandro4912 marking `slots` is not more necessary"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-09T18:12:07.717",
"Id": "456912",
"Score": "0",
"body": "what do you mean with marking slots?"
}
] |
[
{
"body": "<p>In all this is a good effort and helped me discover and report a <a href=\"https://gitlab.gnome.org/GNOME/mutter/issues/965\" rel=\"nofollow noreferrer\">bug in mutter</a>, so I learned some things, too. There are still some things that I think can help you improve your program.</p>\n\n<h2>Fix the bug</h2>\n\n<p>It's a minor bug, but if the player decides to play again, the <code>Room::clear()</code> method doesn't completely reset each room. Specifically, if the user has made a guess about the presence of a hazard, those guesses remain in the subsequent game. Also, if the player actually encountered a bat, that box remains disabled. One way to fix that is to add these lines to <code>Room::clear()</code>:</p>\n\n<pre><code>// also send signals\nmGuessPitAction->setChecked(false);\nmGuessWumpusAction->setChecked(false);\nmGuessBatAction->setChecked(false);\nmGuessBatAction->setEnabled(true);\n</code></pre>\n\n<p>However I think I would instead create and use functions as shown in the next two suggestions.</p>\n\n<h2>Prefer using boolean values directly over <code>if</code></h2>\n\n<p>The <code>Room</code> code currently has this code:</p>\n\n<pre><code>void Room::toggleGuessBat()\n{\n if(mGuessBat) {\n mGuessBat = false;\n mGuessBatAction->setChecked(false);\n }\n else {\n mGuessBat = true;\n mGuessBatAction->setChecked(true);\n }\n update();\n}\n</code></pre>\n\n<p>That seems a bit verbose to me. We could shorten it by using the boolean value directly:</p>\n\n<pre><code>void Room::toggleGuessBat()\n{\n mGuessBat = !mGuessBat;\n mGuessBatAction->setChecked(mGuessBat);\n update();\n}\n</code></pre>\n\n<p>However, we could also get rid of the variable entirely as in the next suggestion.</p>\n\n<h2>Eliminate redundant variables</h2>\n\n<p>The bug I mentioned above was caused by the fact that a stored boolean value and the display value were out of synchronization. One certain way to eliminate all such bugs is to not have two separate things. That is, the variable could be eliminated and only the value of the <code>QAction</code> used instead. This makes it very simple to keep synchronization but also means that we no longer have a separate variable and so, of course, the program is more tightly coupled to the interface. This may or may not be a good idea, depending on your tastes and goals, but I believe that in this case it has more advantages than disadvantages. For instance, we can replace the three slots with a single very simple one:</p>\n\n<pre><code>void Room::selfUpdate()\n{\n update();\n}\n</code></pre>\n\n<p>And now all three <code>connect</code> calls can use the same slot:</p>\n\n<pre><code>connect(mGuessWumpusAction, &QAction::triggered, this, &Room::selfUpdate);\n</code></pre>\n\n<p>The <code>QAction</code> will take care of the appearance and the boolean variable and all that is left is to change from checking the eliminated boolean variables to the states of the checkboxes like this: </p>\n\n<pre><code>if (mGuessWumpusAction->isChecked()) {\n drawWumpus(painter, wumpusImage());\n}\n</code></pre>\n\n<h2>Simplify your code</h2>\n\n<p>The existing <code>Room::boundingRect()</code> is this:</p>\n\n<pre><code>QRectF Room::boundingRect() const\n{\n return QRectF{ 0, 0,\n static_cast<qreal>(roomImage().width()),\n static_cast<qreal>(roomImage().height())};\n}\n</code></pre>\n\n<p>I would use an alternative constructor that takes a <code>QRect</code> to simplify the code and eliminate casts:</p>\n\n<pre><code>QRectF Room::boundingRect() const\n{\n return roomImage().rect();\n}\n</code></pre>\n\n<h2>Use a <code>std::array</code> for fixed-size collections</h2>\n\n<p>The <code>mRooms</code> is currently a <code>QArray</code>, but it could just as easily be a fixed-size <code>std::array</code>. The advantage is that many of the checks that are currently in the code are no longer needed. For example, we could change the <code>Dungeon</code> class so that in now includes an <code>array</code> of actual <code>Room</code> objects rather than uninitialized pointers.</p>\n\n<pre><code>std::array<Room, mCountOfRooms> mRooms;\n</code></pre>\n\n<p>That now eliminates the need for <code>createRooms</code>. Then we could change the helper function <code>connectRoomsAsDodekaeder()</code> to a private member function of <code>Dungeon</code> and use a lambda instead of a separate additional helper function.</p>\n\n<pre><code>void Dungeon::connectRoomsAsDodekaeder()\n{\n auto makeNeighbours = [this](std::size_t src, std::array<std::size_t, 3>n){\n for (const auto i: n) {\n this->mRooms[src].addNeighbour(&(this->mRooms[i]));\n }\n };\n\n makeNeighbours(0, {1, 4, 19});\n makeNeighbours(1, {0 , 2, 17});\n makeNeighbours(2, {1 , 3, 15});\n makeNeighbours(3, {2 , 4, 13});\n makeNeighbours(4, {0 , 3, 5});\n makeNeighbours(5, {4 , 6, 12});\n makeNeighbours(6, {5 , 7, 19});\n makeNeighbours(7, {6 , 8, 11});\n makeNeighbours(8, {7 , 9, 18});\n makeNeighbours(9, {8 , 10, 16});\n makeNeighbours(10, {9 , 11, 14});\n makeNeighbours(11, {7 , 10, 12});\n makeNeighbours(12, {5 , 11, 13});\n makeNeighbours(13, {3 , 12, 14});\n makeNeighbours(14, {10 , 13, 15});\n makeNeighbours(15, {2 , 14, 16});\n makeNeighbours(16, {9 , 15, 17});\n makeNeighbours(17, {1 , 16, 18});\n makeNeighbours(18, {8 , 17, 19});\n makeNeighbours(19, {0 , 6, 18});\n}\n</code></pre>\n\n<h2>Consider simplifying randomization</h2>\n\n<p>Right now the code to randomize the locations of hazards selects random numbers until it finds an empty room and then places each hazard. There is a simpler way to do this:</p>\n\n<pre><code>void Dungeon::populateRooms()\n{\n // create a temporary array of room pointers\n std::array<Room *, mCountOfRooms> mixer;\n std::size_t i{0};\n for (auto &r : mRooms) {\n mixer[i++] = &r;\n }\n // shuffle the pointers to simplify initialization\n std::random_shuffle(mixer.begin(), mixer.end());\n auto it{mixer.begin()};\n // place the wumpus\n (*it++)->setWumpus(true);\n // now the bats\n for (int bats{mCountOfBats}; bats; --bats) {\n (*it++)->setBat(true);\n }\n // now the pits\n for (int pits{mCountOfPits}; pits; --pits) {\n (*it++)->setPit(true);\n }\n}\n</code></pre>\n\n<p>Using <code>random_shuffle</code>, we essentially do the randomization just once and then simply sequentially add the hazards.</p>\n\n<h2>Don't leak memory</h2>\n\n<p>Most of the memory is automatically freed by Qt because the objects are all linked together. However, the three <code>QAction</code> items allocated in the <code>Room</code> constructor are not freed. Adding the appropriate destructor to <code>Room</code> could fix that memory leak.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-09T09:04:43.630",
"Id": "456822",
"Score": "0",
"body": "Can it really work with `std::array<Room, mCountOfRooms> mRooms;` ? If I do that I cannot do `auto room = qobject_cast<Room *>(sender());` in `showLinesToNeigboursOfRoom`. I modified it to use `std::array<Room *, mCountOfRooms> mRooms` It looks like it works but in the constructor of the array I have to type 20 times `new Room`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-09T09:19:26.890",
"Id": "456826",
"Score": "0",
"body": "for the memory leak. I think it would be more QT like to assign the `QActions` `Room` as a parent in the constructor. like `mGuessWumpusAction = new QAction{tr(\"Has &Wumpus\"), this};`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-09T09:23:38.733",
"Id": "456827",
"Score": "0",
"body": "and good idea with the temporary array. I thought i could not use `random_shuffle` because the rooms are already connected. I updated the repo with the suggested changes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-10T11:46:53.623",
"Id": "457024",
"Score": "1",
"body": "I've sent you a pull request to show how to turn `Room *` into `Room` as per my suggestion above. As for the memory leak, I prefer your solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-10T16:51:36.103",
"Id": "457102",
"Score": "0",
"body": "I merged the commit. thanks for many good advice's."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-07T22:49:10.977",
"Id": "233610",
"ParentId": "233472",
"Score": "4"
}
},
{
"body": "<p>Piggy-backing off of Edward's answer around leaking memory, I would advocate the use of <em>smart pointers</em> here (if you're using C++11 or higher). You then wouldn't have to write the deconstructor and memory would be deallocated when the object loses scope.</p>\n\n<p>For instance, your code</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>QAction* mGuessWumpusAction = new QAction{tr(\"Has &Wumpus\")};\n</code></pre>\n\n<p>would become</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <memory>\n\nstd::shared_ptr<QAction> mGuessWumpusAction = std::shared_ptr<QAction>(\n new QAction{tr(\"Has &Wumpus\")}\n);\n</code></pre>\n\n<p>and <code>shared_ptr</code> is super nice because it overloads <code>-></code> so that <code>mGuessWumpusAction->doStuff()</code> still \"dereferences\" in the way you'd think.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-09T07:27:05.943",
"Id": "456808",
"Score": "0",
"body": "Since it's a `QAction` is better to assign the `parent` pointer instead of using a smart pointer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-09T08:45:20.083",
"Id": "456816",
"Score": "1",
"body": "In plain c++ I would agree it would be good to use smart pointers instead of plain pointers. However the QT way of manage memory is in most cases to assign the Object a parent which then automatically deletes the child. See https://doc.qt.io/qt-5/objecttrees.html."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-10T05:28:55.173",
"Id": "456985",
"Score": "0",
"body": "Okay, very interesting! I actually didn't know that. I'm guessing that comes from pre-C++11 times when people forgot to delete pointers all the time and so QT added some built-in functionality to support that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-11T10:40:36.170",
"Id": "457230",
"Score": "0",
"body": "yes QT is alot older than C++11 so they stayed with there way of manage memory."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-08T00:45:53.920",
"Id": "233613",
"ParentId": "233472",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "233610",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T13:33:15.347",
"Id": "233472",
"Score": "7",
"Tags": [
"c++",
"game",
"c++17",
"qt"
],
"Title": "Hunt the Wumpus Game (C++ with QT)"
}
|
233472
|
<p>I want to count the occurrences of a multi line ASCII pattern within a file.</p>
<p>The pattern looks like this:</p>
<pre><code>a1
b2
c3
</code></pre>
<p>The file I want to search looks like this:
(The _ represent whitespaces but I thought it's easier to understand with this notation)</p>
<pre><code>_ _ _ a1
_ _ _ b2
_ _ _ c3 _ _ _ _ a1
a1_ _ _ _ _ _ _ _ b2 _ _ _ _ a1
_ _ _ _ _ _ _ _ _ c3 _ _ _ _ b2
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ c3
</code></pre>
<p>The desired output should be 3 in this case. I solved this with a bunch of loops and counting symbols till finding the first part of the pattern. Then checking if the second part hast the same count of numbers before to ensure the second part is underneath the first one and so on.</p>
<pre><code>_ _ _ _ a1 _ _ _ a1
_ _ _ _ b2 _ _ b2 _
_ _ _ _ c3 _ _ _ c3
</code></pre>
<p>In this example there is only one valid pattern found since the parts of the second aren't exactly under each other.</p>
<p>The regarding code is as following:</p>
<pre><code>import sys
def load_data(path):
data = []
try:
fp = open(path, 'r')
for f_line in fp:
data.append(f_line.rstrip())
finally:
fp.close()
return data
bug_path = 'data/bug.txt'
landscape_path = 'data/landscape.txt'
bug = load_data(bug_path)
landscape = load_data(landscape_path)
findings = [[] for x in landscape]
min_len_bug = min([len(x) for x in bug])
for cnt, l_line in enumerate(landscape):
if len(l_line) < min_len_bug:
continue
for bCnt, bLine in enumerate(bug):
findings[cnt] = [(bCnt, ind) for ind in range(len(l_line)) if l_line.startswith(bLine, ind)] + findings[cnt]
def bugInLine(line, bug_part, whitespace):
for entry in line:
if entry[0] == bug_part and entry[1] == whitespace:
return True
complete_bugs_cnt = 0
for cnt, l_line in enumerate(findings):
for found in l_line:
if found[0] == 0 and len(findings) > (cnt + len(bug) - 1):
check = 1
for i in range(1, len(bug)):
if bugInLine(findings[cnt + i], i, found[1]):
check = check + 1
if check == len(bug):
complete_bugs_cnt = complete_bugs_cnt + 1
print complete_bugs_cnt
</code></pre>
<p>Since this isn't the most elegant solution I'm wondering if there is a possibility to solve this problem by using some regex code and combine this with the <code>re.findall()</code>-method.</p>
<p>I'd highly appreciate any help.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T15:24:23.763",
"Id": "456420",
"Score": "1",
"body": "What are the edge cases? If the 2nd file does not contain the first **2** lines (as you posted) `_ _ _ a1\\n\n_ _ _ b2`. What should be the result then?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T15:28:57.140",
"Id": "456426",
"Score": "0",
"body": "If the first 2 lines are missing in the 2nd file the output should be __2__ since there are only 2 occurrences of the full pattern. I the last two lines are missing the output should be __1__ since there is only one full pattern there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T15:30:55.627",
"Id": "456427",
"Score": "1",
"body": "The idea formulated as \"*Then checking if the second part hast the same count of numbers before to ensure the second part is underneath the first one and so on*\" is unclear to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T15:34:47.860",
"Id": "456429",
"Score": "0",
"body": "I wanted to describe that it's important for this problem that the pattern is there with each of it's parts underneath each other. I'll try to edit my question to make it more clear."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T15:37:43.313",
"Id": "456430",
"Score": "0",
"body": "@RomanPerekhrest I added another example to make my description more clear."
}
] |
[
{
"body": "<pre><code> data = []\n try:\n fp = open(path, 'r')\n for f_line in fp:\n data.append(f_line.rstrip())\n\n finally:\n fp.close()\n return data\n</code></pre>\n\n<p>This can be simplified to:</p>\n\n<pre><code>data = []\nwith open(path) as fp:\n f_line = fp.readline()\n data.append(f_line.rstrip())\nreturn data\n</code></pre>\n\n<p>The <code>with</code> statement in Python will automatically close the file after the code is done with it. It also handles the <code>finally</code> exception by closing it.</p>\n\n<pre><code>findings = [[] for x in landscape]\n</code></pre>\n\n<p>This initialization can be skipped if the algorithm is transformed.</p>\n\n<pre><code>for cnt, l_line in enumerate(findings):\n for found in l_line:\n if found[0] == 0 and len(findings) > (cnt + len(bug) - 1):\n check = 1\n for i in range(1, len(bug)):\n if bugInLine(findings[cnt + i], i, found[1]):\n check = check + 1\n\n if check == len(bug):\n complete_bugs_cnt = complete_bugs_cnt + 1\n</code></pre>\n\n<p>This is close to <code>text = [''.join(arr) for arr in zip(*text[::1])]</code> (rotate the text by -90 degrees and search) and <code>sum([word.count(pattern_to_find) for word in text])</code>. </p>\n\n<p>The current algorithm is too complicated. Consider an algorithm which checks if a word is present in a single line. Given the line <code>abc c d e a abc</code> the word <code>abc</code> occurs twice, and <code>.count()</code> can be used to find how many times that pattern occurs, or, a while loop with the string split on whitespace (then check if the item is equal to that item.)</p>\n\n<p>However, the text is in columns instead of rows. The text can be rotated -90 degrees which turns it into the easy-to-parse row format. From there it becomes very easy to parse.</p>\n\n<p>After applying these transformations, the code becomes the following (without file reading):</p>\n\n<pre><code>def find_text_column(haystack, pattern_to_find):\n text = haystack.splitlines()\n maxlen = len(max(text, key=len))\n # make every line the same length so that zip() works, as it does not work with irregular arrays\n text = [line.ljust(maxlen, ' ') for line in text]\n\n # rotate string by -90 degrees\n text = [''.join(arr) for arr in zip(*text[::1])]\n return sum([word.count(pattern_to_find) for word in text])\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T23:32:02.610",
"Id": "233489",
"ParentId": "233476",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "233489",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T14:37:26.113",
"Id": "233476",
"Score": "1",
"Tags": [
"python",
"regex"
],
"Title": "Match a multi line text block"
}
|
233476
|
<p>I'm looking for feedback on this Personal Finance tool. I want to know what I've done well and what I haven't done so well. Please don't criticise the fact I've used Hungarian notation, it's required in my university assignment and I know I probably should be using classes but at the moment I'm just sticking to the procedural approach.</p>
<blockquote>
<h2>Scenario</h2>
<p>A reputable bank has asked you to create a personal finance management
program. The program will need to be able to take the user's monthly
wage, their monthly bills, and any weekly bills that they may occur.
This will then be broken down to find out how much of their wages they
will then have left to save.</p>
<p>The user should be able to enter any amount of monthly bills and
weekly bills. The user should also have the option to add other users
from their household to be handled within the calculations.</p>
<p>Once all of the relevant information has been included, an overview of
the bills against a weekly, monthly and yearly cost should be output.</p>
<h2>Inputs</h2>
<ul>
<li>User's Name (Must be more than 1)</li>
<li>Monthly Wage (Must be more than 1)</li>
<li>The different bills the user has to pay (Per Person)</li>
</ul>
<h2>Outputs</h2>
<ul>
<li>User's Name</li>
<li>Weekly, Monthly, Yearly Wage Total</li>
<li>Weekly, Monthly, Yearly Bills Total</li>
<li>Total Spent on Bills</li>
<li>Total left to Save</li>
<li>10% over and under the total that can be saved</li>
<li>How much can be saved per month</li>
<li>10% over and under the total that can be saved per month</li>
</ul>
</blockquote>
<hr />
<h1>The code</h1>
<h3><code>Personal Finance Management.cpp</code></h3>
<p>This file contains the <code>main</code> function. Program execution begins and ends there.</p>
<pre><code>#include <iostream>
#include <string>
#include <vector>
#include <cctype>
using namespace std;
void Addusers(vector<string>&sUserName)
{
string sUserNameInput = "";
cout << "\nEnter the name of household member: ";
cin >> sUserNameInput;
sUserName.push_back(sUserNameInput);
}
void AddMonthlyWage(vector<string>&sUserName,vector<double> &dMonthlyWage)
{
double dInputMonthlyWage = 0;
cout << "\n" << *sUserName.rbegin() << "'s monthly income: ";
cin >> dInputMonthlyWage;
dMonthlyWage.push_back(dInputMonthlyWage);
}
void YearlyAmount(vector<double>&dYearlySalary,vector<double>&dMonthlyWage, vector<string>&sUserName)
{
double dYearlySalaryProcess = 0;
dYearlySalaryProcess = *dMonthlyWage.rbegin() * 12;
dYearlySalary.push_back(dYearlySalaryProcess);
}
void WeeklyAmount(vector<double>&dYearlySalary, vector<double>&dWeeklySalary, vector<string>&sUserName)
{
double dWeeklySalaryProcess = 0;
for (int iCount = 0; iCount != sUserName.size(); iCount++)
{
dWeeklySalaryProcess = (*dYearlySalary.rbegin() / 12) / 4;
dWeeklySalary.push_back(dWeeklySalaryProcess);
}
}
double dCalculateBillAmounts(double dYearlySalary,const double dIncomeTax, double dWaterBill, double dElectricityBill)
{
double dTotalBillProcess = 0;
dTotalBillProcess = (dYearlySalary * dIncomeTax) + dWaterBill + dElectricityBill;
return dTotalBillProcess;
}
void BillAmounts(vector<double> &dYearlySalary, vector<string>&sUserName, vector<double>&dTotalBill)
{
const double dIncomeTax = 0.1;
vector<double> dWaterBill;
vector<double> dElectricityBill;
double dTotalBillProcess = 0;
double dInputBill = 0;
cout << "\nPlease enter " << *sUserName.rbegin() << "'s water bill: ";
cin >> dInputBill;
dWaterBill.push_back(dInputBill);
cout << "\nPlease enter " << *sUserName.rbegin() << "'s electricity bill: ";
cin >> dInputBill;
dElectricityBill.push_back(dInputBill);
dTotalBillProcess = dCalculateBillAmounts(*dYearlySalary.rbegin(), dIncomeTax, *dWaterBill.rbegin(), *dElectricityBill.rbegin());
dTotalBill.push_back(dTotalBillProcess);
}
double CalculateMonthly(double dAmount)
{
double dCalculateMonthlyProcess = dAmount / 12;
return dCalculateMonthlyProcess;
}
double CalculateWeekly(double dAmount)
{
double dCalculateWeeklyProcess = dAmount / 54;
return dCalculateWeeklyProcess;
}
double TotalOver(double dAmount, double dPercentage)
{
double dPercentageUnder = dAmount + (dAmount * dPercentage);
return dPercentageUnder;
}
double TotalUnder(double dAmount, double dPercentage)
{
double dPercentageOver = dAmount - (dAmount * dPercentage);
return dPercentageOver;
}
void DisplayResults(vector<string> &sUserName, vector<double> &dMonthlyWage, vector<double> &dTotalBill, vector<double> &dYearlySalary,vector<double> &dWeeklySalary)
{
vector<double> dTotalSavings;
double dTotalSavingsProcess = 0;
double dSavingsOverProcess = 0;
double dSavingsUnderProcess = 0;
vector<double> dSavingsOverPercentage;
vector<double> dSavingsUnderPercentage;
const double dPercentage = 0.1;
vector<double> dBillsOverPercentage;
vector<double> dBillsUnderPercentage;
double dBillsOverProcess = 0;
double dBillsUnderProcess = 0;
for (int iCount = 0; iCount != sUserName.size(); iCount++)
{
cout << "\nResults for - " << sUserName.at(iCount) << ".";
cout << "\n--Salary--";
cout << "\nYearly salary is: £" << dYearlySalary.at(iCount) << ".";
cout << "\nMonthly salary: £" << dMonthlyWage.at(iCount) << ".";
cout << "\nWeekly salary is: £" << dWeeklySalary.at(iCount) << ".";
cout << "\n--Bills--";
cout << "\nTotal spent on bills: £" << dTotalBill.at(iCount) << ".";
cout << "\nMonthly bill cost: £" << CalculateMonthly(dTotalBill.at(iCount)) << ".";
cout << "\nWeekly bill cost: £" << CalculateWeekly(dTotalBill.at(iCount)) << ".";
cout << "\n--Savings over and under 10%--";
dTotalSavingsProcess = dYearlySalary.at(iCount) - dTotalBill.at(iCount);
dTotalSavings.push_back(dTotalSavingsProcess);
cout << "\nTotal savings: £" << dTotalSavings.at(iCount);
dSavingsOverProcess = TotalOver(dTotalSavings.at(iCount), dPercentage);
dSavingsOverPercentage.push_back(dSavingsOverProcess);
cout << "\n" << dPercentage * 100 << "% over their total savings: £" << dSavingsOverPercentage.at(iCount);
dSavingsUnderProcess = TotalUnder(dTotalSavings.at(iCount),dPercentage);
dSavingsUnderPercentage.push_back(dSavingsUnderProcess);
cout << "\n" << dPercentage * 100 << "% under their total savings: £" << dSavingsUnderPercentage.at(iCount);
cout << "\n--Bills over and under 10%--";
dBillsOverProcess = TotalOver(dTotalBill.at(iCount), dPercentage);
dBillsOverPercentage.push_back(dBillsOverProcess);
cout << "\n" << dPercentage * 100 << "% over their total bills: £" << dBillsOverPercentage.at(iCount);
dBillsUnderProcess = TotalUnder(dTotalBill.at(iCount),dPercentage);
dBillsUnderPercentage.push_back(dBillsUnderProcess);
cout << "\n" << dPercentage * 100 << "% under their total bills: £" << dBillsUnderPercentage.at(iCount);
cout << "\n";
}
}
void ContinueOptions(bool &bExit)
{
char cSelection = 0;
cout << "Do you wish to add another family member? (Y/N) ";
cin >> cSelection;
cSelection = toupper(cSelection);
if(cSelection == 'Y')
{
cout << "\nAdd a new family member";
}
else
{
cout << "\nGoodbye!";
bExit = true;
}
}
int main()
{
vector<string>sUserName;
vector<double>dMonthlyWage;
vector<double>dYearlySalary;
vector<double>dWeeklySalary;
vector<double>dTotalBills;
bool bExit = false;
do
{
//Procedure 1
Addusers(sUserName);
//Procedure 2
AddMonthlyWage(sUserName,dMonthlyWage);
//Procedure 3
YearlyAmount(dYearlySalary,dMonthlyWage, sUserName);
//Procedure 4
WeeklyAmount(dYearlySalary,dWeeklySalary, sUserName);
//Procedure 5
BillAmounts(dYearlySalary,sUserName,dTotalBills);
//Procedure 6
DisplayResults(sUserName, dMonthlyWage,dTotalBills,dYearlySalary,dWeeklySalary);
//Procedure 7
ContinueOptions(bExit);
}while(bExit == false);
cout << "\n";
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T17:29:59.607",
"Id": "456446",
"Score": "1",
"body": "Is it explicitly required to not to use classes?"
}
] |
[
{
"body": "<h1>Avoid <code>using namespace std</code></h1>\n<p>That's not one of the namespaces designed for wholesale import into the global namespace. Such a <code>using</code> directive denies you the advantages that namespaces bring.</p>\n<h1>Always check your inputs</h1>\n<p>See the problem here?</p>\n<blockquote>\n<pre><code>cin >> sUserNameInput;\nsUserName.push_back(sUserNameInput);\n</code></pre>\n</blockquote>\n<p>If the <code>>></code> operator fails, <code>sUserNameInput</code> will still be empty. But the requirement says it must be greater than 1 (presumably meaning the name length), so we fail.</p>\n<p>Always check that <code>>></code> was successful, either by testing the stream (it has a conversion to <code>bool</code>) or by setting it to throw exceptions (and then handle the exceptions appropriately).</p>\n<h1>Use <code>const</code> on reference parameters that we're not changing.</h1>\n<p>For example, <code>YearlyAmount()</code> only needs to read <code>dMonthlyWage</code>, not modify it, and doesn't use <code>sUserName</code> at all:</p>\n<pre><code>void YearlyAmount(std::vector<double>& dYearlySalary,\n std::vector<double> const& dMonthlyWage,\n std::vector<string>&)\n</code></pre>\n<p>We should probably just remove the unused paramater.</p>\n<h1>Accessing last element</h1>\n<p><code>std::vector()</code> provides <code>back()</code> as a more convenient way to write <code>*v.rbegin()</code>.</p>\n<h1>Lines end in <code>\\n</code></h1>\n<p>We need to print <code>\\n</code> at the <em>end</em> of each line, not at its beginning.</p>\n<h1><code>std::toupper()</code> takes an <code>int</code> value</h1>\n<p>Arguments to character conversion functions take the <em>unsigned</em> value of a character, represented as <code>int</code>. We need to cast to <code>unsigned char</code> before the promotion to <code>int</code> happens, to avoid passing negative values.</p>\n<h1>Prefer returning a value than writing to a reference.</h1>\n<p><code>ContinueOptions</code> has a single return value, so return it. Look how much clearer that is:</p>\n<blockquote>\n<pre><code>bool bExit = false;\ndo\n{\n ...\n ContinueOptions(bExit);\n}while(bExit == false);\n</code></pre>\n</blockquote>\n<p>That becomes:</p>\n<pre><code>do\n{\n ...\n} while(ContinueOptions());\n</code></pre>\n<p>That's with a function like this:</p>\n<pre><code>bool ContinueOptions()\n{\n std::cout << "Do you wish to add another family member? (y/N) ";\n char cSelection;\n std::cin >> cSelection;\n if (!std::cin) {\n // input failed - assume "no"\n return false;\n }\n bool go_again = std::toupper(static_cast<unsigned char>(cSelection)) == 'Y';\n std::cout << (go_again ? "Add a new family member\\n" : "Goodbye!\\n");\n return go_again;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T21:24:52.850",
"Id": "456473",
"Score": "0",
"body": "Hi there, thank you for reviewing my program. You’ve mentioned a lot of interesting points which I have taken on board. I’m a little lost on your second point about inputs. I can’t see anything wrong? I’d appreciate if you elaborate on that. I’m very glad you told me about the last point because I was thinking to myself there must be a better way. Thanks for that!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T22:10:53.990",
"Id": "456482",
"Score": "0",
"body": "Input can go wrong for all sorts of reasons - end of file (or broken connection), input that fails to convert (e.g. entering letters when a number was required), etc. If we always assume input is successful, and never check for errors, we'll get strange results. Look at my version of `ContinueOptions` for a very simple error check - `if (!std::cin)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T22:59:35.143",
"Id": "456486",
"Score": "0",
"body": "Oh I see what you mean! Thanks very much! I greatly appreciate your help!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T18:31:15.937",
"Id": "233483",
"ParentId": "233480",
"Score": "5"
}
},
{
"body": "<h2>Complexity</h2>\n<p>The code does a pretty good job of following the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow 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 exception to this is the function <code>DisplayResults()</code> which is too complex (does too much in one function). Based on the name of the function it should do exactly one thing, which is display the results.</p>\n<p>The <code>Addusers()</code> function function should be responsible for calling all the functions to add user information, there should be a new function call <code>AddUserName()</code>.</p>\n<p>Many of the functions would require less parameters if user was a class and that would greatly simplify the implementation.</p>\n<p>In the <code>calculate</code> functions the code can simply return the calculation rather than assigning it to a variable and then returning the variable. It might be possible to write these functions as <a href=\"https://en.cppreference.com/w/cpp/language/lambda\" rel=\"nofollow noreferrer\">lambda expressions</a> rather than functions.</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<h2>Useless Comments</h2>\n<p>The comments in <code>main()</code> of the form <code>//Procedure N</code> really don't help explain anything. Comments should be used to explain why the code may be doing something that a programmer can't infer by reading self documenting code. Given the function and variable names in the program this code is self documenting code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T21:31:20.727",
"Id": "456475",
"Score": "0",
"body": "Thanks so much for reviewing my program. Can you elaborate about the return user function? I’d appreciate that greatly. I will definitely take on board about the display procedure I will fix that! Many thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T15:37:49.887",
"Id": "456604",
"Score": "1",
"body": "To return `user` there should be a `user` class or struct. What I was describing above is that all necessary vectors should be passed into the `AddUser` function (note, not plural) and that the `AddUser` function should call each of the functions that get input. I would put off all calculations until all user information has been added. While looking into an answer for your comment I noticed that the function `BillAmounts` has to vectors that aren't used as vectors, this looks like a bug waiting to happen."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T18:38:47.003",
"Id": "233484",
"ParentId": "233480",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "233483",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T16:29:09.847",
"Id": "233480",
"Score": "5",
"Tags": [
"c++",
"beginner"
],
"Title": "Personal Finance Management Tool"
}
|
233480
|
<p>I built a scanner generator like flex or jflex in Scala for a class last year. Part of this project is a small library for handling and manipulating finite automata. It works completely as intended, except for maybe some bugs in the conversion to dot-code, which is of little concern.</p>
<p>I would like to have some aspects of this library reviewed, including but not limited to:</p>
<ol>
<li>Quality and usefulness of the documentation of classes and methods</li>
<li>Application of functional concepts (tail recursion) </li>
<li>Naming of classes, methods, and variables</li>
<li>Simplicity and - more subjectively - elegance of solutions. Especially in my implementation of the subset construction to make the automaton deterministic.</li>
<li>... and any other comment you may have</li>
</ol>
<p><strong>References to code other than the supplied code</strong></p>
<p>The library uses a custom class for sets called <code>MySet</code>, which is outside of the scope of this question. I may ask for reviews for this class in another question. <code>MySet</code> supports using ranges as sets, complementary and difference sets without listing all values. It also provides the mathematical operators for unions, intersections, and differences.</p>
<p><strong>Code</strong></p>
<p>The library mainly consists of the class <code>AutomatonSpecification</code>, which encapsulates the list of transitions as well as start and accepting states.
It provides various methods to manipulate (create a manipulated copy) an automaton, most notably to remove epsilon transitions, make it deterministic via subset construction, and calculating a minimal automaton.</p>
<p>AutomatonSpecification.scala:</p>
<pre class="lang-scala prettyprint-override"><code>package automata.finiteautomata
/**
* Encapsulates all aspects of a finite automaton.
* This includes the transitions as well as the start and accepting states of the automaton
*
* @param transitions The transitions in this automaton
* @param accepting A list of accepting states along with their result value
* @param start The set of possible start states
* @tparam InputElement The type of the input elements of the automaton
* @tparam StateType The type of the states in this automaton
* @tparam Result The result type of this automaton
*/
case class AutomatonSpecification[InputElement, StateType <: State[StateType], Result]
(transitions: List[Transition[InputElement, StateType]], accepting: List[Acceptance[StateType, Result]], start: Set[StateType]) {
/**
* Finds the epsilon closure of a given state.
* Calculates the epsilon closures of all epsilon reachable states as a byproduct.
*
* @param state The state to find the epsilon closure of
* @param knownClosures A map containing known epsilon closures. Acts as a cache.
* @return A tuple consisting of 1. The set of epsilon reachable states and 2. A map of all known epsilon closures
*/
def epsilonClosureOf(state: StateType, knownClosures: Map[StateType, Set[StateType]] = Map()): (Set[StateType], Map[StateType, Set[StateType]]) = {
def helper(currentState: StateType, known: Map[StateType, Set[StateType]], visitedStates: Set[StateType]): (Set[StateType], Map[StateType, Set[StateType]]) = {
if (visitedStates.contains(currentState)) return (visitedStates, known)
val visited = visitedStates + currentState
known.get(currentState) match {
case Some(closure) => (closure, known)
case None =>
val (c, k) =
transitions
.filter(t => t.oldState == currentState && t.condition == EpsilonCondition)
.map(_.newState).toSet
.foldLeft((visited, known)) {
case ((newVisited, newKnown), reachablestate) =>
//Get the transitive closure of the epsilon-reachable state
//All known closures (f._2) are passed on
//Already visited states (f._1) are also passed on.
//The last part is needed to correctly handle cycles of epsilon-reachable states
val (closure, newknown) = helper(reachablestate, newKnown, newVisited)
(newVisited ++ closure, newknown)
}
(c, k + (currentState -> c))
}
}
helper(state, knownClosures, Set())
}
/**
* Finds the epsilon closure of all states of this automaton
*
* @return A map containing the epsilon closures of all states.
*/
def allEpsilonClosures: Map[StateType, Set[StateType]] = this.states.foldLeft(Map[StateType, Set[StateType]]())(
(k, state) => this.epsilonClosureOf(state, k)._2)
/**
* Tail recursive function to remove all epsilon transitions in a specification of a finite automaton in an iterative manner
*
* @return The specification of an equivalent automaton without any epsilon transitions
*/
@scala.annotation.tailrec
final def withoutEpsilonIterative: AutomatonSpecification[InputElement, StateType, Result] = {
//If there are no epsilon transitions left, return the argument
if (this.transitions.forall(_.condition != EpsilonCondition)) return this
val transformed: List[(List[Transition[InputElement, StateType]], Option[Acceptance[StateType, Result]])] =
this.transitions.map {
case Transition(a, EpsilonCondition, b) if a == b =>
(Nil, None) //Reflective epsilon transitions are meaningless and result in infinite loops.
case Transition(oldState, EpsilonCondition, newState) =>
//1. Replace epsilon transition with all possible transitive transitions (potentially including new epsilon-transitions)
//2. If the target state was accepting, add the initial state to the set of accepting states
(this.transitions.filter(_.oldState == newState).map(x => Transition(oldState, x.condition, x.newState)),
this.accepting.find(_.state == newState).map(_.copy(state = oldState)))
case t => (List(t), None) //All non-epsilon transitions are kept
}
//tailrecursive call to eliminate the next set of epsilon transitions
AutomatonSpecification(transformed.flatMap(_._1), transformed.flatMap(_._2) ++ this.accepting,
this.start).withoutEpsilonIterative
}
/**
* Removes all epsilon transitions in the specification.
* Curiously around 4x slower than 'withoutEpsilonIterative' for small automata.
* The resulting specification may contain unreachable states
*
* @return The specification of an equivalent automaton without any epsilon transitions.
*/
def withoutEpsilon: AutomatonSpecification[InputElement, StateType, Result] = {
val closures = this.allEpsilonClosures
val transitions = for (state <- this.states.toList;
closing <- closures(state);
transition <- this.transitions.filter(
_.oldState == closing) if transition.condition != EpsilonCondition)
yield transition.copy(oldState = state)
val accepting = this.accepting.flatMap({
case Acceptance(state, result) => closures.filter({
case (_, value) => value.contains(state)
}).keys.map(s => Acceptance(s, result)).toList
})
AutomatonSpecification(transitions, accepting, this.start.flatMap(closures)).cullAcceptingStates
}
/**
* Makes the automaton deterministic by constructing all reachable state-subsets.
* Requires the specification to not contain any epsilon transition.
* Removes unreachable states as a byproduct.
*
* @return A new specification containing aggregate states and no sources of non-deterministic behaviour
*/
def toDeterministic: AutomatonSpecification[InputElement, AggregateState[StateType], Result] =
this.toDeterministic(AggregateState(this.start))
/**
* Makes the automaton deterministic by constructing all reachable state-subsets.
* Requires the specification to not contain any epsilon transition.
* Removes unreachable states as a byproduct.
*
* @param aggregateStartState An aggregate start state
* @return A new specification containing aggregate states and no sources of non-deterministic behaviour
*/
private def toDeterministic(aggregateStartState: AggregateState[StateType]): AutomatonSpecification[InputElement, AggregateState[StateType], Result] = {
case class StateTransition(condition: TransitionCondition[InputElement], target: AggregateState[StateType])
/**
* Transforms a list of non-deterministic transitions for a given state into a list of usable deterministic transitions
*
* @param current The current aggregate state
* @param transitions A list of all transitions that can be taken from the current state
* @return A usable list of AggregateTransitions with no remaining sources of non-determinism
*/
def solveAll(current: AggregateState[StateType], transitions: List[StateTransition]): List[Transition[InputElement, AggregateState[StateType]]] = {
val resolved = resolveAllCollisions(transitions)
resolved.map(t => Transition[InputElement, AggregateState[StateType]](current, t.condition, t.target))
}
/**
* Transforms a list of non-deterministic transitions into a list of deterministic transitions
*
* @param transitions A list of possible transitions
* @return A list of deterministic transitions without the origin state
*/
def resolveAllCollisions(transitions: List[StateTransition]): List[StateTransition] = {
transitions match {
case Nil => Nil
case head :: Nil => head :: Nil
case head :: tail =>
resolveCollisionsForSingleHead(head, tail) match {
case Some(replacement) => resolveAllCollisions(replacement)
case None => head :: resolveAllCollisions(tail)
}
}
}
/**
* Resolves the first collision between a given transition and any of a list of transitions
*
* @param head The transition to resolve collisions with
* @param tail List of all potential collision candidates
* @return None if there was no collision, some list of transitions if there was a collision that was replaced.
* The list is functionally equivalent to all transitions head :: tail
*/
def resolveCollisionsForSingleHead(head: StateTransition, tail: List[StateTransition]): Option[List[StateTransition]] = {
@scala.annotation.tailrec
def helper(tail: List[StateTransition], safe: List[StateTransition]): Option[List[StateTransition]] = {
tail match {
case Nil => None
case next :: ts => resolveOptionalCollision(head, next) match {
case None => helper(ts, next :: safe)
case Some(replacement) => Some(replacement.filterNot(_.condition.isEmpty) ::: ts ::: safe)
}
}
}
helper(tail, Nil)
}
/**
* Resolves the collision between to transitions
*
* @param a The first transition
* @param b The second transition
* @return None if there was no collision, some list of transitions if the transitions collide and need to be replaced.
* The list may contain "empty" transitions, i.e. SetConditions that with empty character sets.
* While not harmful, they should be filtered for efficiency.
*/
def resolveOptionalCollision(a: StateTransition, b: StateTransition): Option[List[StateTransition]] = {
(a, b) match {
case (StateTransition(SetCondition(t1), aNew), StateTransition(SetCondition(t2), bNew)) =>
val intersect = t1 ∩ t2
if (intersect.isEmpty) None
else Some(List(
StateTransition(SetCondition(t1 \ t2), aNew),
StateTransition(SetCondition(t2 \ t1), bNew),
StateTransition(SetCondition(intersect), aNew ++ bNew)
))
case _ => None
}
}
@scala.annotation.tailrec
def constructAggregateStatesAndTransitions(queue: List[AggregateState[StateType]], known: Set[AggregateState[StateType]], transes: List[Transition[InputElement, AggregateState[StateType]]]): (Set[AggregateState[StateType]], List[Transition[InputElement, AggregateState[StateType]]]) = {
queue match {
case Nil => (known, transes)
case head :: tail if known.contains(head) => constructAggregateStatesAndTransitions(tail, known, transes)
case head :: tail =>
val resolved: List[Transition[InputElement, AggregateState[StateType]]] = {
//Filter transitions on the old state, and map to an instance of C
val cs = this.transitions.filter(t => head.states.contains(t.oldState)).map(
t => StateTransition(t.condition, AggregateState(Set(t.newState))))
solveAll(head, cs) //Solve the collisions in those transitions
}
val newStates = resolved.map(
_.newState) //Get all aggregate states, are can be reached by the resolved transitions
//Recursive call to get transitions of all remaining aggregate states, adding the newly found states to the queue
constructAggregateStatesAndTransitions(newStates ++ tail, known + head, resolved.map(
t => Transition[InputElement, AggregateState[StateType]](head, t.condition, t.newState)) ::: transes)
}
}
//Compound expression to hide variables from nested functions
{
//Construct all reachable aggregate states and the corresponding transitions
val (states, ts) = constructAggregateStatesAndTransitions(aggregateStartState :: Nil, Set(), Nil)
val accepting = this.accepting.flatMap({
case Acceptance(state, result) => states.filter(value => value.states.contains(state)).map(
s => Acceptance(s, result)).toList
})
AutomatonSpecification(ts, accepting, Set(aggregateStartState)).cullAcceptingStates
}
}
/**
* Maps all states to a numbered state, to make it more convenient to use.
*
* @return An updated specification containing numbered states.
*/
def withNumberedStates: AutomatonSpecification[InputElement, NumberedState, Result] =
this.mapStates(this.getIntegralStateMap)
/**
* Maps all states in this specification.
* Guaranteed to preserve determinism if 'f' is injective.
*
* @param f The function, that maps old states to new states.
* @tparam NewState The type of the new states
* @return An updated specification.
*/
def mapStates[NewState <: State[NewState]](f: StateType => NewState): AutomatonSpecification[InputElement, NewState, Result] = AutomatonSpecification(
this.transitions.map(_.mapStates(f)), this.accepting.map(a => a.copy(state = f(a.state))), this.start.map(f))
/**
* @return A Set of all States in this Automaton
*/
def states: Set[StateType] = this.transitions.flatMap(t => List(t.oldState, t.newState)).toSet ++ this.start
/**
* Removes all redundant and therefore ineffective accepting states
*
* @return A new automaton specification without the redundant acceptances
*/
private def cullAcceptingStates: AutomatonSpecification[InputElement, StateType, Result] = {
def filter(ac: List[Acceptance[StateType, Result]]): List[Acceptance[StateType, Result]] = {
ac match {
case Nil => Nil
case head :: tail => head :: filter(tail.filterNot(_.state == head.state))
}
}
this.copy(accepting = filter(this.accepting))
}
/**
* Minimizes the automaton using Brzozowski’s algorithm.
* Limitation: Only works correctly when all results of accepting states are equal.
*
* @return A minimized automaton with aggregate states
*/
def minimized: AutomatonSpecification[InputElement, AggregateState[AggregateState[StateType]], Result] =
this.reversed.toDeterministic.reversed.toDeterministic
/**
* Reverses the automaton.
* The result automaton accepts the reversed language of this automaton.
* Only works when all semantics of accepting states are equal.
*
* @return A potentially non-deterministic finite automaton specification, that accepts the reversed language.
*/
def reversed: AutomatonSpecification[InputElement, StateType, Result] =
AutomatonSpecification(
this.transitions.map(_.reverse),
this.start.map(s => Acceptance(s, this.accepting.head.result)).toList,
this.accepting.map(_.state).toSet
)
/**
* Groups transistion edges by their start- and end-node.
* Merges the transitions that can be merged
*
* @return A new AutomatonSpecification with the combined transitions
*/
def mergeTransitions: AutomatonSpecification[InputElement, StateType, Result] = {
def union(a: TransitionCondition[InputElement], b: TransitionCondition[InputElement]): TransitionCondition[InputElement] = (a, b) match {
case (EpsilonCondition, EpsilonCondition) => EpsilonCondition
case (EpsilonCondition, other) => other
case (other, EpsilonCondition) => other
case (SetCondition(lhs), SetCondition(rhs)) => SetCondition(lhs ∪ rhs)
}
val mergedTransitions = this.transitions.groupBy(t => (t.oldState, t.newState)).map({
case ((old, target), trans) =>
Transition(old, trans.map(_.condition).reduce(union), target)
}).toList
this.copy(transitions = mergedTransitions)
}
/**
* Creates a dot graph-representation of this automaton.
*
* @return A string in valid dot-syntax for graphical representation
*/
def toDot(f: InputElement => String = _.toString): String = {
val regularstates = this.states &~ this.accepting.map(_.state).toSet &~ this.start
val statemap = this.getIntegralStateMap.mapValues(_.state.toString)
s"""digraph G{
| {
| node[shape=circle style=filled fillcolor=white]
| ${
this.accepting.map(
a => s"""${statemap(a.state)} [shape=doublecircle, label="${a.state.toDot}(${a.result})"]""").mkString("\n ")
}
| ${this.start.map(a => s"""${statemap(a)} [fillcolor=yellow label="${a.toDot}"]""").mkString("\n ")}
| ${regularstates.map(a => s"""${statemap(a)} [label="${a.toDot}"]""").mkString("\n ")}
| }
| ${this.transitions.map(t => s"${t.toDot(statemap, f)};").mkString("\n ")}
|}
""".stripMargin
}
/**
* Creates a human-readable representation of this automaton
*
* @return A string describing the automaton
*/
override def toString: String = s"Automaton Specification: Start with $start, End with $accepting:\n${
this.transitions.mkString("\n")
}"
/**
* Maps all states of this automaton to a numbered state
*
* @return A map containing a numbered state for every state this automaton contains
*/
private def getIntegralStateMap: Map[StateType, NumberedState] =
this.states.zipWithIndex.toMap.mapValues(NumberedState)
/**
* Merges this automaton with another automaton.
* The merge is done by mapping the states of the second automaton to remove all clashes and keeping the starting states of both automatons.
* The resulting automaton is by nature non-deterministic.
*
* @param other The second automaton.
* @return A new automaton specification whose accepted language is the union of both automatons.
*/
def mergeWith(other: AutomatonSpecification[InputElement, StateType, Result]): AutomatonSpecification[InputElement, StateType, Result] = {
val highest = this.getHighestStateIndex + 1
val transformed = other.mapStates(_ + highest)
AutomatonSpecification(this.transitions ::: transformed.transitions, this.accepting ::: transformed.accepting,
this.start ++ transformed.start)
}
private def getHighestStateIndex: Int = this.states.map(_.max).max
}
</code></pre>
<p>Accompanying this class are some small classes representing states and transitions located in the package object.</p>
<p>package.scale:</p>
<pre class="lang-scala prettyprint-override"><code>package automata
package object finiteautomata {
/**
* A state for a finite automaton
*
* @tparam ConcreteState The concrete State class
*/
sealed trait State[ConcreteState] {
/**
* Adds an offset to all relevant statenumbers of this state
*
* @param offset The offset to add
* @return A new ConcreteState including the offset
*/
def +(offset: Int): ConcreteState
/**
* @return A dot-representation of this state
*/
def toDot: String
/**
* @return The maximum state number that is used in this state
*/
def max: Int
}
/**
* A simple numbered state for finite automata
*
* @param state The state number
*/
case class NumberedState(state: Int) extends State[NumberedState] {
override def +(offset: Int): NumberedState = NumberedState(state + offset)
override def toDot: String = state.toString
override def max: Int = this.state
}
/**
* An aggregate state for finite automata. Represents the union of multiple base states.
*
* @param states The base states included in this aggregate state
* @tparam BaseState The type of the base states
*/
case class AggregateState[BaseState <: State[BaseState]](states: Set[BaseState]) extends State[AggregateState[BaseState]] {
def ++(other: AggregateState[BaseState]): AggregateState[BaseState] = AggregateState(this.states ++ other.states)
override def +(offset: Int): AggregateState[BaseState] = AggregateState(this.states.map(_ + offset))
override def toDot: String = s"{${this.states.map(_.toDot).mkString(",")}}"
override def max: Int = states.map(_.max).max
}
/**
* Represents an accepting state by associating a result with it
*
* @param state The accepting state
* @param result The result of the automaton if it halts in the accepting state
* @tparam State The state type of the automaton
* @tparam Result The result type of the automaton
*/
case class Acceptance[State, Result](state: State, result: Result)
/**
* Abstract base for transition conditions of a finite automaton
*
* @tparam InputElement The type of input elements for the automaton
*/
sealed trait TransitionCondition[+InputElement] {
/**
* @return True if the transition can never be triggered, false otherwise
*/
def isEmpty: Boolean
/**
* Creates a dot-representation for this transition
*
* @param f A mapping function to map InputElements to a dot-representation
* @return The completed dot-representation
*/
def toDot(f: InputElement => String = _.toString): String
}
/**
* A transition condition described by a set of all input elements that can trigger the transition
*
* @param set A set containing all elements that trigger the associated transition
* @tparam InputElement The type of input elements for the automaton
*/
case class SetCondition[InputElement](set: automata.util.sets.MySet[InputElement]) extends TransitionCondition[InputElement] {
override def isEmpty: Boolean = set.isEmpty
override def toDot(f: InputElement => String = _.toString): String = set.toFormattedString(f)
}
/**
* The epsilon transition condition. Always triggers and consumes no input
*/
case object EpsilonCondition extends TransitionCondition[Nothing] {
override def isEmpty: Boolean = false
override def toDot(f: Nothing => String = _.toString): String = "ϵ"
}
/**
* Represents a complete transition of an automaton
*
* @param oldState The origin state for this transition
* @param condition The condition on which the transition is triggered
* @param newState The target state of this transition.
* @tparam InputElement The type of input elements for the automaton
* @tparam StateType The type of states in the automaton
*/
case class Transition[+InputElement, StateType <: State[StateType]](oldState: StateType,
condition: TransitionCondition[InputElement],
newState: StateType) {
/**
* Applies a function on the origin and target states of this transition
*
* @param f The mapping function
* @tparam NewState The type of the new states
* @return A new Transition describing the reverse direction of this transition
*/
def mapStates[NewState <: State[NewState]](f: StateType => NewState): Transition[InputElement, NewState] =
Transition[InputElement, NewState](f(this.oldState), condition, f(this.newState))
/**
* Reverses the transition by flipping origin and target states.
*
* @return The new, reversed transition
*/
def reverse: Transition[InputElement, StateType] = Transition(newState, condition, oldState)
/**
* @return A simple string representation of the transistion
*/
override def toString: String = {
s"$oldState with $condition to $newState"
}
/**
* @param statemap A function that maps states to their dot-representation
* @param f A function that maps input elements to their dot-representation
* @return A dot representation for this transition
*/
def toDot(statemap: StateType => String, f: InputElement => String = _.toString): String = {
s"""${statemap(oldState)} -> ${statemap(newState)} [label="${condition.toDot(f)}"]"""
}
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T18:48:03.917",
"Id": "233485",
"Score": "2",
"Tags": [
"functional-programming",
"scala"
],
"Title": "Finite automaton library in Scala including subset construction and minimization"
}
|
233485
|
<p>I have created a very simple Class Module and a Dictionary to store original values when the workbook is opened as part of this project ive been working on. When the workbook opens I call a test to see if its open in read only mode because multiple people will be in the workbook, but only one person will have it open for editing. <br>Currently the project sends an email when a file is assigned to an individual, but now i need to track any changes to cells in certain columns and send out an email based on that. The email part i have figured out already with help from <a href="https://codereview.stackexchange.com/questions/233345/worksheet-change-event-sends-email">This Post</a>.<br><br>
I also need to be able to add an item to the existing dictionary, which is the part I am struggling on, when a number is added to a cell in a named range. Unfortunately, the research I have done isnt really explained well or not a close enough example to what I am looking to do. Thanks for you help.</p>
<p><strong>Class Module</strong></p>
<pre><code>'clsLoanData
Public LoanAmount As String
Public TitleCompany As String
Public Notes As String
Public CloseDate As String
Public PurchasePrice As String
Public Product As String
Public LoanNumber As String
Public CustomerName As String
</code></pre>
<p><strong>Worksheet_Change Event</strong></p>
<pre><code>Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim Recipient As String
Recipient = "zack"
Dim CustName As String, TitleCo As String, clsDate As String, ContractPrice As String
Dim lAmount As String, Product As String, Msg As String, Notes As String
Dim rgCells As Range
Set rgCells = Me.Range("pNames")
Dim rgSel As Range
Set rgSel = Intersect(Target, rgCells)
Dim cell As Range
If Not rgSel Is Nothing Then
For Each cell In rgSel
If LCase(cell.Value) = Recipient Then
Dim oLoan As New clsLoanData
With oLoan
.LoanAmount = Format(Trim(cell.Offset(0, 14).Value), "Currency")
.CloseDate = Trim(cell.Offset(0, 8).Value)
.Notes = Trim(cell.Offset(0, 17).Value)
.LoanNumber = Trim(cell.Offset(0, -2).Value)
.Product = Trim(cell.Offset(0, 15).Value)
.PurchasePrice = Format(Trim(cell.Offset(0, 13).Value), "Currency")
.TitleCompany = Trim(cell.Offset(0, 2).Value)
.CustomerName = Trim(Split(cell.Offset(0, -1).Value, " - ")(0))
CreateEmail oLoan.CustomerName, oLoan.TitleCompany, oLoan.CloseDate, _
oLoan.PurchasePrice, oLoan.LoanAmount, oLoan.Product, oLoan.Notes
End With
'Dim LoanInfoDict As Object
'Set LoanInfoDict = CreateObject("Scripting.Dictionary")
'Set LoanInfoDict = StoreOriginalLoanInfo("zacke")
'THIS IS WHERE I AM STUCK SINCE I DONT KNOW HOW TO ADD TO
'AN EXISTING DICTIONARY.
Next cell
End If
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Dim lNum As Range
Set lNum = Me.Range("LoanNums")
'Dim c As Range
'Set c = Sheet1.Range("pNames")
If Not Intersect(Target, lNum) Is Nothing Then
Dim cAddress As String
cAddress = Target.Address
StoreNewLoanNumberInfo cAddress
End If
End Sub
</code></pre>
<p><strong>Functions</strong></p>
<pre><code>Option Explicit
Function StoreOriginalLoanInfo(ByVal pName As String, Optional ByVal lNum) As Dictionary
Dim OriginalLoanInfo As Object
Set OriginalLoanInfo = CreateObject("Scripting.Dictionary")
'OriginalLoanInfo.RemoveAll
Dim c As Range
Dim cCell As Range
Set c = Sheet1.Range("pNames")
For Each cCell In c.Cells
If LCase(cCell.Value) = pName Then
Dim oLoan As New clsLoanData
With oLoan
.LoanAmount = Trim(cCell.Offset(0, 14).Value)
.CloseDate = Trim(cCell.Offset(0, 8).Value)
.Notes = Trim(cCell.Offset(0, 17).Value)
.LoanNumber = Trim(cCell.Offset(0, -2).Value)
.Product = Trim(cCell.Offset(0, 15).Value)
.PurchasePrice = Trim(cCell.Offset(0, 13).Value)
.TitleCompany = Trim(cCell.Offset(0, 2).Value)
.CustomerName = Trim(Split(cCell.Offset(0, -1).Value, " - ")(0))
End With
If Not OriginalLoanInfo.Exists(oLoan.LoanNumber) And oLoan.LoanNumber <> vbNullString Then
OriginalLoanInfo.Add oLoan.LoanNumber, oLoan
With oLoan
Debug.Print .LoanNumber, .CustomerName, .CloseDate, .LoanAmount, .Notes, .Product, .PurchasePrice, .TitleCompany
End With
End If
End If
Next cCell
Set StoreOriginalLoanInfo = OriginalLoanInfo
End Function
'The end goal is to have this added to the StoreOriginalLoanInfo Dictionary
'when a number is added to column A
Function StoreNewLoanNumberInfo(ByVal cell As String) As Dictionary
Dim NewLoanInfo As Object
Set NewLoanInfo = CreateObject("Scripting.Dictionary")
Dim ln As Range
Set ln = Sheet1.Range("LoanNums")
Dim c As Range
Set c = Sheet1.Range(cell)
Dim oLoan As New clsLoanData
With oLoan
.LoanAmount = Trim(c.Offset(0, 16).Value)
.CloseDate = Trim(c.Offset(0, 10).Value)
.Notes = Trim(c.Offset(0, 19).Value)
.LoanNumber = Trim(c.Value)
.Product = Trim(c.Offset(0, 17).Value)
.PurchasePrice = Trim(c.Offset(0, 15).Value)
.TitleCompany = Trim(c.Offset(0, 4).Value)
.CustomerName = Trim(Split(c.Offset(0, 1).Value, " - ")(0))
End With
If Not NewLoanInfo.Exists(oLoan.LoanNumber) Then
NewLoanInfo.Add oLoan.LoanNumber, oLoan
With oLoan
Debug.Print .LoanNumber, .CustomerName, .CloseDate, .LoanAmount, .Notes, .Product, .PurchasePrice, .TitleCompany
End With
End If
Set StoreNewLoanNumberInfo = NewLoanInfo
End Function
</code></pre>
<p><strong>EDIT</strong>
Below is the procedure and function to test if the file is in read only mode per TinMan's request. The reason I have these is because I only want the dictionary with the loan information to populate when the workbook is first opened by the user who will be editing the worksheet. This data will be used to compare against new data entered for an additional email that something has been updated.</p>
<pre><code>Option Explicit
Sub testReadOnly()
Dim uName As String, pName As String
pName = "zack"
uName = LCase(Environ("username"))
Dim pLastRow As Long
pLastRow = Sheet1.Cells(Sheet1.Rows.Count, "C").End(xlUp).Row
If uName = "zacke" Then
If Not isReadOnly(PIPELINEFILE) Then
StoreOriginalLoanInfo pName, pLastRow
Else
MsgBox "File Is Read-Only"
End If
End If
End Sub
Function isReadOnly(ByVal fName As String) As Boolean
'vbNormal = 0, vbReadOnly = 1, vbHidden = 2, vbDirectory = 16
If Len(fName) > 0 Then
isReadOnly = GetAttr(fName) And vbReadOnly
End If
End Function
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T23:00:59.090",
"Id": "456488",
"Score": "0",
"body": "How are you storing the dictionary? Is it a global variable? How is it initiated?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T00:13:30.987",
"Id": "456489",
"Score": "0",
"body": "@TinMan the data is passed from the variables set in the class module and the initiating even comes from a sub routine that tests if the workbook is in read only mode. I can post that procedure tomorrow when I'm back in the office if that helps."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T03:27:03.790",
"Id": "456511",
"Score": "0",
"body": "You should post it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T13:45:44.397",
"Id": "456590",
"Score": "0",
"body": "@TinMan I added the information you requested."
}
] |
[
{
"body": "<p>Hopefully this example will help you to organize and simplify your project design. Overall, your code is fairly clean but it can be simplified mostly by focused on what parts of your code are repeated and redundant. In particular, you have several code sections that collect the loan details using <code>Offset</code> on the worksheet. All of the offsets are the same, plus you have encapsulated all of the loan details into it's own class. So make the class do the work:</p>\n\n<p><strong>Class Module: LoanData</strong></p>\n\n<pre><code>Option Explicit\n\n'--- Class: LoanData\nPublic LoanAmount As String\nPublic TitleCompany As String\nPublic Notes As String\nPublic CloseDate As String\nPublic PurchasePrice As String\nPublic Product As String\nPublic LoanNumber As String\nPublic CustomerName As String\n\nPublic Sub Populate(ByRef loanDetails As Range)\n With loanDetails\n LoanAmount = Format(Trim(.Offset(0, 14).Value), \"Currency\")\n CloseDate = Trim(.Offset(0, 8).Value)\n Notes = Trim(.Offset(0, 17).Value)\n LoanNumber = Trim(.Offset(0, -2).Value)\n Product = Trim(.Offset(0, 15).Value)\n PurchasePrice = Format(Trim(.Offset(0, 13).Value), \"Currency\")\n TitleCompany = Trim(.Offset(0, 2).Value)\n CustomerName = Trim(Split(.Offset(0, -1).Value, \" - \")(0))\n End With\nEnd Sub\n</code></pre>\n\n<p>And by the way, my personal preference is to NOT prefix custom classes with <code>cls</code>. There's no reason for it and you can distinguish your own classes from the VBA built-ins anyway. Trust me, no one will be confused thinking that <code>LoanData</code> is built in to the language. Notice how the class supplies a method to populate itself, given a cell <code>Range</code> as a reference for your <code>Offset</code>.</p>\n\n<blockquote>\n <p><strong>SIDE NOTE 1</strong>: I would likely have declared the <code>LoanAmount</code> and <code>PurchasePrice</code> variables as <code>Double</code>, then deferred to the calling routine to decide how to format those values for output. By forcing those values as <code>String</code> here, you've prevented possible future operations if you wanted to, for example, sum all the loan values for a given zip code or something.</p>\n \n <p><strong>SIDE NOTE 2</strong>: the dictionary code is implemented as you presented it, but I am concerned that your \"Key\" value for the <code>Dictionary</code> is not guaranteed to be unique for all possibilities. Your key looks like it is the CustomerName (recipient?). You might consider what field or fields you'd need to consider for a truly unique identifier. I would think the <code>LoanNumber</code> would be unique enough. Or a combination of <code>LoanNumber</code> and <code>CustomerName</code> perhaps.</p>\n</blockquote>\n\n<p>It's easiest to describe the general methods that deal with the <code>Dictionary</code> directly before considering the worksheet change events.</p>\n\n<p>First, I recommend using early binding for the <code>Microsoft Scripting Runtime</code>, at least to start your coding and debugging. It will make the <code>Dictionary</code> easier to work with.</p>\n\n<p>Next, when you need to reference a (semi-)persistent (global) variable, you declare this at the top of a regular VBA code module. In my example, the variable <code>allLoans</code> is declared as <code>Private</code>. All interactions with this dictionary are performed from publicly available routines (which is desirable), so keep the dictionary private here. The basic workhorse of the project is <code>UpdateLoanDictionary</code>. This is the routine that will create a new entry or modify an existing entry:</p>\n\n<pre><code>Private allLoans As Dictionary\n\nPublic Sub UpdateLoanDictionary(ByRef thisCustomer As Range)\n '--- just in case this Sub is called before the dictionary is created\n If allLoans Is Nothing Then CreateLoanDictionary\n If IsEmpty(thisCustomer.Value) Then Exit Sub\n\n Dim thisLoan As LoanData\n Set thisLoan = New LoanData\n thisLoan.Populate thisCustomer\n\n If Not allLoans.Exists(thisLoan.CustomerName) Then\n '--- create a new loan entry\n allLoans.Add thisLoan.CustomerName, thisLoan\n Else\n '--- update the existing loan entry\n allLoans(thisLoan.CustomerName) = thisLoan\n End If\nEnd Sub\n</code></pre>\n\n<p><em>(the whole module is given in a single block below)</em></p>\n\n<p>Notice that is takes a single-cell range as the input parameter. This will be used to check the data and to create an object with the <code>LoanData</code> we need. (More about how to create the whole dictionary below.)</p>\n\n<blockquote>\n <p><strong>SIDE NOTE 3 - VERY IMPORTANT</strong>: create your new <code>LoanData</code> object with a separate <code>New</code> statement as shown above. Your method is <code>Dim oLoan As New clsLoanData</code> in a single statement. This declares a \"static\" class, i.e. an object that is created ONCE and only once. You want to create many of these <code>LoanData</code> objects, so you want a dynamic declaration that will create a new object each time.</p>\n</blockquote>\n\n<p>Now, there are two conditions in which you want to create your dictionary: when the workbook opens for the first time and also when the worksheet containing the data is activated. So these methods are simple.</p>\n\n<p><strong>Workbook Module: ThisWorkbook</strong></p>\n\n<pre><code>Option Explicit\n\nPrivate Sub Workbook_Open()\n CreateLoanDictionary\nEnd Sub\n</code></pre>\n\n<p><strong>Worksheet Module: Sheet1</strong></p>\n\n<pre><code>Option Explicit\n\nPrivate Sub Worksheet_Activate()\n CreateLoanDictionary\nEnd Sub\n</code></pre>\n\n<p>So back in the VBA Code Module, there is an additional routine to support these conditions:</p>\n\n<pre><code>Public Sub CreateLoanDictionary(Optional ByVal forceNewDictionary As Boolean = False)\n '--- if the dictionary already exists, we don't have to recreate it\n ' unless it's forced\n If forceNewDictionary Or (allLoans Is Nothing) Then\n Set allLoans = New Dictionary\n Dim customerNames As Range\n Set customerNames = ActiveSheet.Range(\"pNames\")\n Dim customer As Range\n For Each customer In customerNames\n UpdateLoanDictionary customer\n Next customer\n End If\nEnd Sub\n</code></pre>\n\n<p>This is where the code will loop through all the data on your worksheet and create all the entries in your dictionary using the <code>UpdateLoanDictionary</code> method we defined earlier. (functional isolation FTW!)</p>\n\n<p>The last bit is back in the worksheet module code, to respond to changes on the worksheet. Since we have the <code>LoanData</code> object doing all the work of setting up the loan details and the <code>UpdateLoanDictionary</code> method taking care of interacting with the dictionary, the <code>Worksheet_Change</code> event code is greatly simplified:</p>\n\n<pre><code>Private Sub Worksheet_Change(ByVal Target As Range)\n Dim customerNames As Range\n Set customerNames = ActiveSheet.Range(\"pNames\")\n\n Dim allChangedCells As Range\n Set allChangedCells = Intersect(Target, customerNames)\n If Not allChangedCells Is Nothing Then\n Dim changedCell As Range\n For Each changedCell In allChangedCells\n AddLoanToDictionary changedCell\n Next changedCell\n End If\nEnd Sub\n</code></pre>\n\n<blockquote>\n <p><strong>SIDE NOTE 4</strong>: it's best in event code to make it as short and efficient as possible. That includes making your range <code>Intersect</code> check the very first thing in the Sub. Any other logic you need can work after you determine that you really need to do that work.</p>\n</blockquote>\n\n<p>So here are the code modules in whole:</p>\n\n<p><strong>Class Module: LoanData</strong></p>\n\n<pre><code>Option Explicit\n\n'--- Class: LoanData\nPublic LoanAmount As String\nPublic TitleCompany As String\nPublic Notes As String\nPublic CloseDate As String\nPublic PurchasePrice As String\nPublic Product As String\nPublic LoanNumber As String\nPublic CustomerName As String\n\nPublic Sub Populate(ByRef loanDetails As Range)\n With loanDetails\n LoanAmount = Format(Trim(.Offset(0, 14).Value), \"Currency\")\n CloseDate = Trim(.Offset(0, 8).Value)\n Notes = Trim(.Offset(0, 17).Value)\n LoanNumber = Trim(.Offset(0, -2).Value)\n Product = Trim(.Offset(0, 15).Value)\n PurchasePrice = Format(Trim(.Offset(0, 13).Value), \"Currency\")\n TitleCompany = Trim(.Offset(0, 2).Value)\n CustomerName = Trim(Split(.Offset(0, -1).Value, \" - \")(0))\n End With\nEnd Sub\n</code></pre>\n\n<p><strong>Workbook Module: ThisWorkbook</strong></p>\n\n<pre><code>Option Explicit\n\nPrivate Sub Workbook_Open()\n CreateLoanDictionary\nEnd Sub\n</code></pre>\n\n<p><strong>Worksheet Module: Sheet1</strong></p>\n\n<pre><code>Option Explicit\n\nPrivate Sub Worksheet_Activate()\n CreateLoanDictionary\nEnd Sub\n\nPrivate Sub Worksheet_Change(ByVal Target As Range)\n Dim customerNames As Range\n Set customerNames = ActiveSheet.Range(\"pNames\")\n\n Dim allChangedCells As Range\n Set allChangedCells = Intersect(Target, customerNames)\n If Not allChangedCells Is Nothing Then\n Dim changedCell As Range\n For Each changedCell In allChangedCells\n AddLoanToDictionary changedCell\n Next changedCell\n End If\nEnd Sub\n</code></pre>\n\n<p>(There's a bonus method below to <code>ShowLoans</code> that gave me a quick test of the dictionary. You can expand/modify it as needed.)</p>\n\n<p><strong>Code Module: LoanDataSupport</strong></p>\n\n<pre><code>Option Explicit\n\nPrivate allLoans As Dictionary\n\nPublic Sub CreateLoanDictionary(Optional ByVal forceNewDictionary As Boolean = False)\n '--- if the dictionary already exists, we don't have to recreate it\n ' unless it's forced\n If forceNewDictionary Or (allLoans Is Nothing) Then\n Set allLoans = New Dictionary\n Dim customerNames As Range\n Set customerNames = ActiveSheet.Range(\"pNames\")\n Dim customer As Range\n For Each customer In customerNames\n UpdateLoanDictionary customer\n Next customer\n End If\nEnd Sub\n\nPublic Sub UpdateLoanDictionary(ByRef thisCustomer As Range)\n '--- just in case this Sub is called before the dictionary is created\n If allLoans Is Nothing Then CreateLoanDictionary\n If IsEmpty(thisCustomer.Value) Then Exit Sub\n\n Dim thisLoan As LoanData\n Set thisLoan = New LoanData\n thisLoan.Populate thisCustomer\n\n If Not allLoans.Exists(thisLoan.CustomerName) Then\n '--- create a new loan entry\n allLoans.Add thisLoan.CustomerName, thisLoan\n Else\n '--- update the existing loan entry\n allLoans(thisLoan.CustomerName) = thisLoan\n End If\nEnd Sub\n\nSub ShowLoans()\n If allLoans Is Nothing Then\n Debug.Print \"This is no loan dictionary!\"\n Else\n If allLoans.Count = 0 Then\n Debug.Print \"There is a loan dictionary, but it's empty!\"\n Else\n Debug.Print \"There are \" & allLoans.Count & \" loans in the dictionary:\"\n Dim loan As Variant\n For Each loan In allLoans.Items\n Debug.Print \"Loan Number: \" & loan.LoanNumber\n Next loan\n End If\n End If\nEnd Sub\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T15:03:49.150",
"Id": "456598",
"Score": "0",
"body": "Thank you for this. It really helped give me more understanding in how to use a Class Module and also how to use a dictionary. I did make some tweaks to it because the LoanNumber is going to be the key for the dictionary. Thanks again!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T05:59:33.727",
"Id": "233514",
"ParentId": "233488",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "233514",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T21:33:07.520",
"Id": "233488",
"Score": "2",
"Tags": [
"vba",
"excel",
"hash-map"
],
"Title": "Add items to Dictionary from another dictionary on cell value change"
}
|
233488
|
<p>I wrote this code that makes a fairly long function call multiple times using some of the same parameters</p>
<pre><code>match key {
Key { code: KeyCode::Left, .. } => self.map.move_object_by(PLAYER, -1, 0),
Key { code: KeyCode::Right, .. } => self.map.move_object_by(PLAYER, 1, 0),
Key { code: KeyCode::Up, .. } => self.map.move_object_by(PLAYER, 0, -1),
Key { code: KeyCode::Down, .. } => self.map.move_object_by(PLAYER, 0, 1),
}
</code></pre>
<p>I was looking for a way to shortened this function call with something simlar to C/C++ macros. I looked into Rust Macros but they are clearly very different. The solution I came up with is creating a function pointer to a closure that calls the function <code>self.map.move_object_by</code></p>
<pre><code>let mut move_player = |x, y| self.map.move_object_by(PLAYER, x, y);
match key {
Key { code: KeyCode::Left, .. } => move_player(-1, 0),
Key { code: KeyCode::Right, .. } => move_player(1, 0),
Key { code: KeyCode::Up, .. } => move_player(0, -1),
Key { code: KeyCode::Down, .. } => move_player(0, 1),
}
</code></pre>
<p>Is this bad? Will this cause any real slow downs or bugs? Are there other/better ways of doing this?</p>
|
[] |
[
{
"body": "<p>The Rust compiler will probably inline the code, and generate the exact same code in both situations. So there isn't a performance issue.</p>\n\n<p>However, I think there is a better way to write it:</p>\n\n<pre><code>if let Some((x,y)) = match key.code {\n KeyCode::Left => Some((-1, 0)),\n KeyCode::Right => Some((1, 0)),\n KeyCode::Up => Some((0, -1)),\n KeyCode::Down => Some((0, 1)),\n _ => None\n} {\n self.map.move_object_by(PLAYER, x, y);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T06:09:11.587",
"Id": "233516",
"ParentId": "233490",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "233516",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T23:36:41.603",
"Id": "233490",
"Score": "2",
"Tags": [
"beginner",
"rust"
],
"Title": "Shortening function calls with closures"
}
|
233490
|
<h1>Motivation</h1>
<p>In my web app (React, Redux, TypeScript) we have a common need to write paginated API calls, with various UI interactions (infinite scroll, prefetch pages in the background, or manual page navigation controls). Rather than re-write pagination handling in every case, I wanted to create a re-usable method to use pagination anywhere, as well as make it easy to update non-paginated data into paginated data.</p>
<p>Pagination is repeatedly <a href="https://github.com/reduxjs/redux/issues/176" rel="nofollow noreferrer">cited as a specific example</a> where the features of Redux, like reducer composition, are meant to shine. So I gave it a shot!</p>
<p>Because I'm using TypeScript a parallel goal is to make this type-safe and self-documenting.</p>
<h1>Paginated Server API</h1>
<p>All paginated API endpoints take requests like this:</p>
<pre><code>{
offset: 0,
limit: 100
}
</code></pre>
<p>And return like this:</p>
<pre><code>{
items: [ ...100 items ],
size: 300
}
</code></pre>
<p>In this example we are asking for the first page (<code>offset=0</code>) with 100 per page, and receiving the first page items along with the info that there are 300 total items (ie 3 pages). The next page would be <code>{ offset: 100, limit: 100 }</code>.</p>
<h1>Approach</h1>
<ul>
<li><code>paginate(config, reducer)</code> is a a "<a href="https://github.com/reduxjs/redux/issues/176" rel="nofollow noreferrer">transducer</a>" (aka "enhancer" or "higher-order reducer") that takes a reducer meant for items (array) and wraps it in handling of page request, success, and error action cases to update a paginated state object.</li>
<li><code>paginated(actions, onFetch, getPaginatedState)</code> is an action creator that will dispatch actions which compliments <code>paginate()</code> with page request, success, and error actions. It only requires implementing how a specific page fetch request is made via <code>onFetch(offset, limit)</code>, and what slice of the store to pull pagination state from via <code>getPaginatedState(state)</code>.</li>
<li><code><InfinateScroller></code>, <code><PaginationControls></code> and <code><InfinitePreloader></code> are components that deal with user interactivity and when to request pages from the API.</li>
<li>Connected components pass the relevant pagination store state slice and page fetch action to one of the above components.</li>
</ul>
<h1>Code</h1>
<h2><code>Paginated<T></code> type that represents a store state slice of paginated data:</h2>
<pre><code>export interface Paginated<T> {
/**
* True if a request for a page is in progress.
*/
fetching: boolean;
/**
* True if a request for a page resulted in an error, which could be an API error or UI processing error.
*/
error: boolean;
/**
* The configured page size to use in requests.
*/
pageSize: number;
/**
* The current requested page index (0 = first page), or null if no request has been made yet.
*/
currentPage: number | null;
/**
* The loaded items, or null if no request has been completed yet.
*/
items: T[] | null;
/**
* The total number of items available from the server, or null if no request has been completed yet.
*/
totalItems: number | null;
}
</code></pre>
<p>Example usage of <code>Paginated<T></code> the store state type:</p>
<pre><code>interface StoreState {
paginatedProjects: Paginated<Project>;
}
interface Project {
id: string;
name: string;
// ...
}
</code></pre>
<p><code>PaginatedActionTypes</code> type used for both <code>paginate()</code> transducer and <code>paginated()</code> action creator to describe the actions during a pagination API call:</p>
<pre><code>interface PaginatedActionTypes {
requestType: string;
successType: string;
errorType: string;
}
</code></pre>
<h2>The <code>paginate()</code> transducer implementation:</h2>
<pre><code>import { Action, Reducer } from "redux";
interface PaginateConfig extends PaginatedActionTypes {
/**
* The number of items requested with each page.
*/
pageSize: number;
/**
* Optional list of action types that should reset the state to default.
* For example, use this to have certain UI actions like filtering and sorting
* clear the existing data and down-stream UIs will re-fetch the first page.
*/
invalidateTypes?: string[];
}
export interface PaginatedRequestAction extends Action {
requestedPage: number;
}
export interface PaginatedSuccessAction<T> extends Action {
items: T[];
size: number;
fetchedPage: number;
}
export interface PaginatedErrorAction extends Action {
failedPage: number;
}
type PaginatedAction<T> =
PaginatedRequestAction
| PaginatedSuccessAction<T>
| PaginatedErrorAction;
/**
* This function can enhance a reducer to handle a paginated API collection.
*
* The wrapped reducer can be written without knowledge of pagination.
*
* The correlated state will be a Paginated wrapper that holds the pagination state and the loaded items.
*/
export function paginate<T>(config: PaginateConfig, reducer: Reducer<T[]>) {
const { requestType, successType, errorType, invalidateTypes, pageSize } = config;
const defaultState: Paginated<T> = {
fetching: false,
error: false,
pageSize,
// Use `null` to indicate "never loaded" vs "loaded empty collection", used by down-stream components to show loading state.
totalItems: null,
items: null,
currentPage: null
};
const paginatedReducer = (state: Paginated<T> = defaultState, action: PaginatedAction<T>): Paginated<T> => {
switch (action.type) {
case requestType:
const request = action as PaginatedRequestAction;
return {
...state,
fetching: true,
currentPage: request.requestedPage
};
case successType:
const success = action as PaginatedSuccessAction<T>;
if (state.currentPage !== success.fetchedPage)
throw new Error(`Received page ${ success.fetchedPage } but expecting page ${ state.currentPage }`);
const existingItems = state.items || [];
return {
...state,
fetching: false,
error: false,
items: [...existingItems, ...success.items],
totalItems: success.size
};
case errorType:
const error = action as PaginatedErrorAction;
return {
...state,
fetching: false,
error: true
};
default:
// Actions that invalidate the loaded data, resets to initial state
if (invalidateTypes && invalidateTypes.includes(action.type)) {
return defaultState;
}
// Pass unhandled actions through to inner reducer
if (state.items) {
const nextItems = reducer(state.items, action);
// Update items if the inner reducer returned a new state
if (nextItems !== state.items) {
// Update the size by delta if it changed by the inner reducer
const nextTotalItems = state.totalItems != null && state.items
? state.totalItems + (nextItems.length - state.items.length)
: state.totalItems;
return {
...state,
items: nextItems,
totalItems: nextTotalItems
};
}
}
return state;
}
};
return paginatedReducer;
}
</code></pre>
<h2>The <code>paginated()</code> action creator implementation, which uses <a href="https://github.com/reduxjs/redux-thunk" rel="nofollow noreferrer">thunk</a>:</h2>
<pre><code>import { StoreState, ThunkDispatch } from "../../store/configureStore";
export interface Collection<T> {
items: T[];
size: number;
}
/**
* This is a helper function to create action creators for the paginate() enhancer.
*
* You give it the same action types for { request, success, fail } and callbacks to call
* the actual API and extract the paginated state, and it handles the fetching of
* the next page of data and dispatching the actions during the life-cycle of a call.
*/
export function paginated<T>(
{ requestType, successType, errorType }: PaginatedActionTypes,
onFetch: (offset: number, limit: number, getState: () => StoreState) => Promise<Collection<T>>,
getPaginatedState: (state: StoreState) => Paginated<T>
) {
return async (dispatch: ThunkDispatch, getState: () => StoreState) => {
const { pageSize, currentPage, fetching } = getPaginatedState(getState());
if (fetching) {
console.error(`Already fetching ${ requestType } page -- ignoring duplicate call. Components should not try to fetch another page while fetching a page is in progress.`);
return;
}
const nextPage = currentPage == null ? 0 : currentPage + 1;
const request: PaginatedRequestAction = {
type: requestType,
requestedPage: nextPage
};
dispatch(request);
try {
const nextPageOffset = nextPage * pageSize;
const response = await onFetch(nextPageOffset, pageSize, getState);
if (response.size == null)
throw new Error(`Unexpected paginated response: "size" is missing`);
const action: PaginatedSuccessAction<T> = {
type: successType,
items: response.items || [],
size: response.size,
fetchedPage: nextPage
};
dispatch(action);
} catch (e) {
console.error(`Error in paginated.onFetch call:`, e);
const error: PaginatedErrorAction = {
type: errorType,
failedPage: nextPage
};
dispatch(error);
}
};
}
</code></pre>
<h2><code><InfiniteScroller></code> component, which uses <a href="https://www.npmjs.com/package/react-waypoint" rel="nofollow noreferrer">react-waypoint</a> to request the next page when the user scrolls to the bottom of the loaded data.</h2>
<pre><code>import * as React from "react";
import { PureComponent } from "react";
import Waypoint from "react-waypoint";
import WaypointEvent = ReactWaypoint.WaypointEvent;
import { Loader } from "./Loader";
import { LoadingError } from "./LoadingError";
interface InfiniteScrollerProps {
/**
* Whether the initial page has been loaded. If false an initial onLoadMore() will be called when first rendered.
*/
initialLoaded: boolean;
/**
* Whether a page is currently being loaded. Prevents onLoadMore() from being called until false.
*/
isLoading: boolean;
/**
* Whether the requested page resulted in an error.
*/
hasError: boolean;
/**
* Called when the next (or initial) page needs to be loaded due to scrolling (or initial render).
*/
onLoadMore(): void;
/**
* How many items are currently loaded.
*/
itemsLoaded: number;
/**
* Total items that can be loaded.
*/
totalItems: number;
}
export class InfiniteScroller extends PureComponent<InfiniteScrollerProps, {}> {
handleEnterBottomWaypoint = (e: WaypointEvent): void =>
this.props.onLoadMore();
componentDidUpdate(prevProps: Readonly<InfiniteScrollerProps>, prevState: Readonly<{}>, snapshot?: any): void {
if (!this.props.initialLoaded && prevProps.initialLoaded !== this.props.initialLoaded) {
this.props.onLoadMore();
}
}
render() {
const { initialLoaded, itemsLoaded, totalItems, className, isLoading, hasError, children } = this.props;
const hasMoreItems = itemsLoaded < totalItems;
const needsToLoadMore = (!initialLoaded || hasMoreItems) && !hasError;
return (
<div className={ className }>
{ children }
{ isLoading ? <Loader/> : needsToLoadMore && <Waypoint onEnter={ this.handleEnterBottomWaypoint }/> }
{ hasError && <LoadingError/> }
</div>
);
}
}
</code></pre>
<p><code><InfinitePreloader></code> and <code><PaginationControls></code> work similarly.</p>
<h1>Example</h1>
<p>(Some irrelevant details trimmed.)</p>
<h2><code>paginatedProjectsReducer</code> which wraps a <code>projectsReducer</code> using the <code>paginate()</code> transducer:</h2>
<pre><code>// This is an example of a reducer that deals with an array and has no knowledge of pagination:
export type ProjectsAction =
UpdateProjectSuccessAction
| UpdateProjectsSuccessAction
| CreateProjectSuccessAction
| DeleteProjectSuccessAction
// etc..
export const projectsReducer = (state: Project[], action: ProjectsAction): Project[] => {
switch (action.type) {
case UPDATE_PROJECT_SUCCESS: // ...
case UPDATE_PROJECTS_SUCCESS: // ...
case CREATE_PROJECT_SUCCESS: // ...
case DELETE_PROJECT_SUCCESS: // ...
default:
const _exhaustiveCheck: never = action;
return state;
}
};
// This is an example of a reducer wrapped with pagination:
export const paginatedProjectsReducer = paginate<Project>(
{
requestType: FETCH_PROJECTS_REQUEST,
successType: FETCH_PROJECTS_SUCCESS,
errorType: FETCH_PROJECTS_ERROR,
invalidateTypes: [
RELOAD_PROJECTS,
LEAVE_PROJECTS_CONTEXT,
FILTER_PROJECTS,
SORT_PROJECTS
],
pageSize: 100
},
projectsReducer
);
</code></pre>
<p><code>paginatedProjectsReducer</code> is used in the store's root reducer:</p>
<pre><code>import { paginatedProjectsReducer as paginatedProjects } from "./projectsReducer";
export const rootReducer = combineReducers({
paginatedProjects
});
</code></pre>
<h2><code>fetchProjects</code> action creator using the <code>paginated()</code> action creator to fetch the next page of projects:</h2>
<pre><code>import { api } from "../api";
export const FETCH_PROJECTS_REQUEST = "FETCH_PROJECTS_REQUEST";
export const FETCH_PROJECTS_SUCCESS = "FETCH_PROJECTS_SUCCESS";
export const FETCH_PROJECTS_ERROR = "FETCH_PROJECTS_ERROR";
export const fetchProjects = (planId: string) => (
paginated<Project>(
{
requestType: FETCH_PROJECTS_REQUEST,
successType: FETCH_PROJECTS_SUCCESS,
errorType: FETCH_PROJECTS_ERROR
},
async (offset, limit, getState) => (
// Simple API call, but can be more complicated as needed
await api.getProjectsForPlan({ id: planId, limit, offset })
),
state => state.paginatedProjects
)
);
</code></pre>
<h2>Usage of <code><InfiniteScroller></code> from a connected component:</h2>
<pre><code> render() {
const { paginatedProjects, fetchProjects, planId } = this.props;
return (
<InfiniteScroller initialLoaded={ !!paginatedProjects.items }
isLoading={ paginatedProjects.fetching }
hasError={ paginatedProjects.error }
onLoadMore={ () => fetchProjects(planId) }
itemsLoaded={ paginatedProjects.items?.length ?? 0 }
totalItems={ paginatedProjects.totalItems ?? 0 }>
{ items && items.map(project => <ProjectRow key={ project.id } {...project} />) }
</InfiniteScroller>
)
</code></pre>
<h1>Summary</h1>
<p>That's a lot of code, thanks to anyone who takes the time to look at it!</p>
<p>This ended up fairly similar to <a href="https://www.npmjs.com/package/redux-pagination" rel="nofollow noreferrer">redux-pagination</a> and probably other implementations, one notable difference being I opted to keep the fetching delegated outside the pagination implementation, so that pagination is not opinionated about how to fetch pages. I also opted not to use middleware <a href="https://codesandbox.io/s/github/reduxjs/redux/tree/master/examples/real-world" rel="nofollow noreferrer">like the Redux example</a>, because frankly I find the indirection hard to follow, and didn't see a benefit to it. Tell me how I'm wrong!</p>
<p>I've been using this for a little while now, so it's <em>somewhat</em> battle-tested, but I'd love to get any feedback. It seems that pagination is a common use-case in Redux but I found it surprisingly hard to find an unopinionated implementation I could fit into my existing app, so I built this one. Cheers!</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-05T23:56:58.323",
"Id": "233491",
"Score": "2",
"Tags": [
"react.js",
"typescript",
"pagination",
"redux"
],
"Title": "Redux pagination transducer"
}
|
233491
|
<p>I have a function that creates a rectangle from two rectangles that overlap, I was wondering if there is a smarter way to do it purely mathematically rather than lots of <code>if</code> statements to check <code>min</code> and <code>max</code> the way I currently have setup.</p>
<p>This is my function</p>
<pre><code> public static bool Overlaps(this Bounds a, Bounds bounds, out Bounds result)
{
result = new Bounds();
//they don't overlap
if (!a.Intersects(bounds)) return false;
float minX;
float maxX;
float minZ;
float maxZ;
if (a.min.x > bounds.min.x)
minX = a.min.x;
else
minX = bounds.min.x;
if (a.max.x < bounds.max.x)
maxX = a.max.x;
else
maxX = bounds.max.x;
if (a.min.z > bounds.min.z)
minZ = a.min.z;
else
minZ = bounds.min.z;
if (a.max.z < bounds.max.z)
maxZ = a.max.z;
else
maxZ = bounds.max.z;
// using XZ plane for debug
Vector3 min = new Vector3(minX,0,minZ);
Vector3 max = new Vector3(maxX,0,maxZ);
result.SetMinMax(min,max);
return true;
}
</code></pre>
<p>Here it is in action</p>
<p><a href="https://i.stack.imgur.com/wtH1D.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wtH1D.gif" alt="enter image description here"></a></p>
|
[] |
[
{
"body": "<pre><code>float minX;\nfloat maxX;\nfloat minZ;\nfloat maxZ;\n</code></pre>\n\n<p>The declarations can be inlined so that it is clearer when they are being set. However, in geometry and other applications it may be preferable to declare them like this.</p>\n\n<pre><code>if (a.max.x < bounds.max.x)\n maxX = a.max.x;\n else\n maxX = bounds.max.x;\n</code></pre>\n\n<p>These conditions can be replaced with calls to <code>Math.max</code> and <code>Math.min</code>.</p>\n\n<p>The variable names such as <code>minX</code> and <code>maxX</code> seem to be reversed; <code>minX</code> seems to be referring to <code>maxX</code> and vice-versa. I am not very familiar with geometry so I don't know if my suggestion is correct to swap the names.</p>\n\n<p>After applying these suggestions, the method becomes the following:</p>\n\n<pre><code> public static bool Overlaps(this Bounds a, Bounds bounds, out Bounds result)\n {\n result = new Bounds();\n //they don't overlap\n if (!a.Intersects(bounds)) return false;\n\n float minX = Math.Max(a.min.x, bounds.min.x);\n float maxX = Math.Min(a.max.x, bounds.max.x);\n\n float minZ = Math.Max(a.min.z, bounds.min.z);\n float maxZ = Math.Min(a.max.z, bounds.max.z);\n\n // using XZ plane for debug\n Vector3 min = new Vector3(minX, 0, minZ);\n Vector3 max = new Vector3(maxX, 0, maxZ);\n result.SetMinMax(min, max);\n return true;\n }\n</code></pre>\n\n<p>Edit: to respond to the comment (minimizing if statements), it could be expressed as:</p>\n\n<pre><code> public static bool Overlaps(this Bounds a, Bounds bounds, out Bounds result)\n {\n result = new Bounds();\n\n float minX = Math.Max(a.min.x, bounds.min.x);\n float maxX = Math.Min(a.max.x, bounds.max.x);\n\n float minZ = Math.Max(a.min.z, bounds.min.z);\n float maxZ = Math.Min(a.max.z, bounds.max.z);\n\n // using XZ plane for debug\n Vector3 min = new Vector3(minX, 0, minZ);\n Vector3 max = new Vector3(maxX, 0, maxZ);\n result.SetMinMax(min, max);\n return !a.Intersects(bounds);\n }\n</code></pre>\n\n<p>This would be slightly less efficient; I don't know if this is valid as if the <code>Vector3</code> class will accept input which did not pass <code>.Intersects</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T00:38:56.703",
"Id": "456492",
"Score": "0",
"body": "But that function call is doing the same thing surely? Other than cleaning up the code its not reduced the if statements and turning it into a purely mathematical approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T00:48:01.493",
"Id": "456493",
"Score": "0",
"body": "@WDUK I have updated my answer with an alternative approach with no `if` statements."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T01:18:32.450",
"Id": "456496",
"Score": "0",
"body": "Thanks for the help :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T09:56:42.190",
"Id": "456567",
"Score": "0",
"body": "It's much cleaner with the early exist code. Plus porbalby more effecient too."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T00:32:48.447",
"Id": "233495",
"ParentId": "233493",
"Score": "2"
}
},
{
"body": "<p>I don't think it is correct to write to the output parameter <code>result</code> when you return false. Maybe you should return the result or null instead.</p>\n\n<p>Apart from that I would yet make @alexyorke 's solution more compact (assuming <code>Bounds</code> have constructor from min/max) by getting rid of all the intermediate variables:</p>\n\n<pre><code>public static Bounds GetOverlap(this Bounds a, Bounds bounds)\n{\n if (!a.Intersects(bounds)) return null;\n\n return new Bounds(\n new Vector3(\n Math.Max(a.min.x, bounds.min.x),\n 0,\n Math.Max(a.min.z, bounds.min.z)\n ),\n new Vector3(\n Math.Min(a.max.x, bounds.max.x),\n 0,\n Math.Min(a.max.z, bounds.max.z)\n )\n );\n}\n</code></pre>\n\n<p>You may still define the shorthand, but I would suggest omitting the output parameter in which case it becomes alias of <code>Intersects</code> anyway, so maybe it is useless:</p>\n\n<pre><code>public static bool Overlaps(this Bounds a, Bounds bounds)\n{\n return a.Intersects(bounds);\n}\n</code></pre>\n\n<p>And btw if you want to speed it up a little bit, you may look into the <code>Intersects</code> function and you are likely to see that some things that you do in the <code>Overlaps</code> function are done there too. Reimplementing <code>Overlaps</code> without calling <code>Intersects</code> may then be faster, but since you haven't provided the <code>Intersects</code> function, I cannot help here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T11:09:46.083",
"Id": "456570",
"Score": "0",
"body": "Structs can't be null and a bounds of zero returned will still require me to check if the result has a valid bounds to draw. So I opted for the bool / out option."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T09:07:41.100",
"Id": "233524",
"ParentId": "233493",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "233495",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T00:17:30.683",
"Id": "233493",
"Score": "3",
"Tags": [
"c#",
"algorithm",
"mathematics"
],
"Title": "Get resulting rectangle from two overlapping rectangles"
}
|
233493
|
<p>In order to plot a squircle using its parametric equations:</p>
<p><a href="https://i.stack.imgur.com/VZmBW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VZmBW.png" alt="enter image description here" /></a></p>
<p>The equations can be found in page 9 of this
<a href="https://arxiv.org/pdf/1604.02174.pdf" rel="nofollow noreferrer">this article</a>:</p>
<blockquote>
<p>Fong, Chamberlain. "Squircular Calculations." arXiv preprint arXiv:1604.02174 (2016).</p>
</blockquote>
<p>Unfortunately the following singularities are not handled by those equations:</p>
<ul>
<li>For <code>t = 0</code>, <code>t = pi/2</code>, <code>t = pi</code>, <code>t = 3pi/2</code>, and <code>t=2*pi</code></li>
</ul>
<p>Here is the code to plot these equations in Python</p>
<pre class="lang-py prettyprint-override"><code>"""Plot squircle shape using its parametric equations"""
import numpy as np
from numpy import pi, sqrt, cos, sin, sign
import matplotlib.pyplot as plt
# FG stands for Fernandez-Guasti who introduced the algebric equations.
def FG_param(r, s, t):
x = np.ones_like(t)
y = np.ones_like(t)
for i, _t in enumerate(t):
if np.isclose(_t, 0.0):
x[i] = r
y[i] = 0.0
elif np.isclose(_t, pi/2.0):
x[i] = 0.0
y[i] = r
elif np.isclose(_t, pi):
x[i] = -r
y[i] = 0.0
elif np.isclose(_t, 3*pi/2.0):
x[i] = 0.0
y[i] = -r
elif np.isclose(_t, 2*pi):
x[i] = r
y[i] = 0.0
else:
x[i] = r*sign(cos(t[i]))/(s*sqrt(2)*np.abs(sin(t[i])))*sqrt(1 - sqrt(1-s**2*sin(2*t[i])**2))
y[i] = r*sign(sin(t[i]))/(s*sqrt(2)*np.abs(cos(t[i])))*sqrt(1 - sqrt(1-s**2*sin(2*t[i])**2))
return x, y
s = 0.7
r = 1.0
NTHETA = 90
t = np.linspace(0, 2*pi, NTHETA)
x, y = FG_param(r, s, t)
plt.gca().set_aspect('equal')
plt.scatter(x, y, s=5)
plt.show()
</code></pre>
<p>The function <code>FG_param</code> looks very clumsy. I appreciate any help to make it more compact and neat.</p>
<p>Thank you</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T04:39:04.513",
"Id": "456527",
"Score": "0",
"body": "It is possible to simplify via knowing that boolean statements return `0` or `1` if they are coerced to; for example, `np.isclose(_t, pi/2.0)` returns `1` if true, so that can be inverted (display zero if matched) and then multiplied by the RHS to remove it; the equation can be restructured to be `r + xsin(...)`, where `x` is the condition. This can be repeated for all remaining conditions and structured accordingly. I may provide a code sample"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T04:40:44.070",
"Id": "456528",
"Score": "0",
"body": "Something *sort* of like this, but this is not 100% correct: `x[i] = r * \\\n (np.isclose(_t, 0.0) or np.isclose(_t, 2*pi)) * \\\n (not np.isclose(_t, 0.0) or np.isclose(_t, 2*pi)) * \\\n (1 - (not np.isclose(_t, pi))) * \\\n (not np.isclose(_t, 3*pi/2.0))`"
}
] |
[
{
"body": "<p>Off the top of my head, and untested, how about:</p>\n\n<pre><code>def FG_param(r, s, t):\n x = np.ones_like(t)\n y = np.ones_like(t)\n\n for i, _t in enumerate(t):\n radical = sqrt(1 - sqrt(1 - s**2 * sin(2*_t)**2))\n\n try:\n x[i] = r*sign(cos(_t)) / (s*sqrt(2)*np.abs(sin(_t))) * radical\n\n except ZeroDivisionError:\n x[i] = -r if np.isclose(_t, pi) else r\n\n try:\n y[i] = r*sign(sin(_t)) / (s*sqrt(2)*np.abs(cos(_t))) * radical\n\n except ZeroDivisionError:\n y[i] = r if _t < pi/2.0 else -r\n\n return x, y\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T05:02:43.733",
"Id": "233511",
"ParentId": "233496",
"Score": "1"
}
},
{
"body": "<p>Here's a different solution. The singularities occur when sin(_t) or cos(_t) is zero. So check for those conditions.</p>\n\n<pre><code>def FG_param(r, s, t):\n x = np.ones_like(t)\n y = np.ones_like(t)\n\n for i, _t in enumerate(t):\n sin_t = sin(_t)\n cos_t = cos(_t)\n\n if np.isclose(sin_t, 0.0):\n x[i] = -r if np.isclose(_t, pi) else r\n y[i] = 0.0\n\n elif np.isclose(cos_t, 0.0):\n x[i] = 0.0\n y[i] = r if _t < pi else -r\n\n else:\n radical = sqrt(1 - sqrt(1 - s**2 * sin(2*_t)**2))\n\n x[i] = r*sign(cos_t) / (s*sqrt(2)*np.abs(sin_t)) * radical\n y[i] = r*sign(sin_t) / (s*sqrt(2)*np.abs(cos_t)) * radical\n\n return x, y\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T12:13:20.007",
"Id": "456581",
"Score": "1",
"body": "The singularities occur also when `s=0`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-07T00:31:58.493",
"Id": "456645",
"Score": "0",
"body": "@Navaro: Exactly. In that case (i.e: `s=0`) the map will be a circle with radius `r`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-07T01:08:15.687",
"Id": "456647",
"Score": "0",
"body": "@Navaro s==0 wasn't handled in the original code, so I didn't handle it either. It would be an easy case to handle."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-07T01:12:35.710",
"Id": "456648",
"Score": "0",
"body": "@RootTwo: Yes, you could just add something like this at the top of the function: `if s == 0: return r*cos(t), r*sin(t)`"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T06:02:56.230",
"Id": "233515",
"ParentId": "233496",
"Score": "3"
}
},
{
"body": "<p>This solution is an order of magnitude faster than the other ones. It uses numpy functions, so there aren't any explicit loops. <code>np.where</code> chooses values that keep the equations from blowing up where the denominator would go to zero. Case for <code>s == 0</code> is handled separately.</p>\n\n<pre><code>def FG_param1(r, s, t):\n\n if s == 0:\n return r*cos(t), r*sin(t)\n\n\n sin_t = sin(t)\n cos_t = cos(t)\n\n radical = sqrt(1 - sqrt(1 - s**2 * sin(2*t)**2))\n\n x_denom = np.where(np.isclose(sin_t, 0.0), 1.0, s*sqrt(2)*np.abs(sin_t))\n x = r * sign(cos_t) * np.where(np.isclose(sin_t, 0.0, 1e-12), 1.0, radical / x_denom)\n\n y_denom = np.where(np.isclose(cos_t, 0.0), 1.0, s*sqrt(2)*np.abs(cos_t))\n y = r * sign(sin_t) * np.where(np.isclose(cos_t, 0.0, 1e-12), 1.0, radical / y_denom)\n\n return x, y\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-07T03:58:00.317",
"Id": "233577",
"ParentId": "233496",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T01:08:12.333",
"Id": "233496",
"Score": "2",
"Tags": [
"python",
"mathematics"
],
"Title": "Handling singularities in squircle parametric equations"
}
|
233496
|
<p>Exercise 1-17 from the book The C Programming Language: 2nd Edition, K&R</p>
<p>Full description: Write a program to print all input lines that are longer than 80 characters.</p>
<pre><code>#include <stdio.h>
#define MAX_ARRAYCHARACTERS 1000
#define MIN_CHARACTERS 80
int main(void){
int currchar, // current character being read
currlinelen = 0; // how many characters in a line
char characters[MAX_ARRAYCHARACTERS]; // holds all the characters
while( ( currchar = getchar() ) != EOF ){
characters[currlinelen] = currchar;
++currlinelen;
if(currchar == '\n'){ // if there is a new line
if(currlinelen >= MIN_CHARACTERS){ // if the total length of characters of this line is higher than 80
puts("LINE WITH 80+ CHARACTERS: ");
for(int thischar = 0; thischar < currlinelen; ++thischar) // print all the characters that were in that line
putchar(characters[thischar]);
}
currlinelen = 0;
}
}
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<pre><code>while( ( currchar = getchar() ) != EOF ){\n characters[currlinelen] = currchar;\n ++currlinelen;\n</code></pre>\n\n<p>This causes a buffer overflow (and undefined behavior) when the entered string is more than <code>MAX_ARRAYCHARACTERS</code>. A buffer overflow could crash your program, and can cause weird behavior. It is also considered a security vulnerability.</p>\n\n<p>To fix this, I would suggest looking at <code>getline()</code> which is a safer method. Additionally, it doesn't have the <code>1000</code> character limit as defined in <code>MAX_ARRAYCHARACTERS</code>. Using this method would greatly simply this code.</p>\n\n<pre><code>++currlinelen;\n</code></pre>\n\n<p>I would use <code>currlinelen++</code> instead as this is not being used in an assign operation and doesn't depend on the alternative behavior. It is a bit more readable this way too.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T08:47:47.323",
"Id": "456561",
"Score": "3",
"body": "Actually preincrement is the faster one and should be preferred (IMHO). Postincrement inherently has to create a copy before incrementing the original (https://en.cppreference.com/w/cpp/language/operator_incdec). Sure this can be optmized by compiler for integers, but it's a good habit in general, because you don't have to change style when it comes to classes with overloaded operators."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-08T04:17:01.830",
"Id": "456709",
"Score": "0",
"body": "@slepic C (as this post is tagged) does not have overloaded operators/classes. What is good and idiomatic for one language differs with other languages. [The suggestion](https://codereview.stackexchange.com/questions/233498/print-input-lines-longer-than-80-characters-in-c#comment456561_233501) is a micro optimization and does not improve the order of complexity. Better to focus on the big stuff and let the compiler do it job with the small stuff. It is more productive. In C. ++x vs. x++ is nearly a style issues, as with such, follow your group's style guide."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-08T14:53:57.227",
"Id": "456749",
"Score": "0",
"body": "@chux-ReinstateMonica, I know it's trivial and it makes no difference after compiling and optimization, but I still cringe a little every time I see an unnecessary post-increment. Conceptually, my mind sees `++x` as \"*increment the value of x*\", while it sees `x++` as \"*save the value of x; increment the value of x; discard the saved value*\" (which is what ancient compilers actually did)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-08T21:05:34.257",
"Id": "456770",
"Score": "0",
"body": "@RayButterworth Fair enough. I cringe when I see folks trying to out compile a compiler rather than focus on larger issues like buffer overflow protection (as alex did well here) that OP's code lacked. In C, `++currlinelen;` and `++currlinelen++;` can be expected to emit the same efficient code. It a group felt pre/post was efficient to police, their coding guidelines would address it. I see the issue does not merit the initial comment (hence my comment) and would have not cared had OP/alex coded either way."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T01:59:01.873",
"Id": "233501",
"ParentId": "233498",
"Score": "3"
}
},
{
"body": "<p>That's too complicated a solution.</p>\n\n<p>It also not only imposes an arbitrary limit on the maximum possible input line length, it fails to check that the input doesn't exceed this limit.</p>\n\n<p>80 is the only significant number in this program.\nThere's no need to worry about anything more than that.</p>\n\n<p>Simply get characters into an 80 character buffer.</p>\n\n<p>If you get '\\n' before it fills, empty the buffer.</p>\n\n<p>Otherwise, print the full buffer and get and print characters until the next '\\n'.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-08T04:31:14.577",
"Id": "456710",
"Score": "0",
"body": "awesome! really liked this new approach. I tried it and I came up with this: https://pastebin.com/XmfQRkxx seems to be working just fine, but I feel that the code is too clunky. if there's any noticeable mistakes, please let me know!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T02:04:43.560",
"Id": "233503",
"ParentId": "233498",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T01:27:35.880",
"Id": "233498",
"Score": "4",
"Tags": [
"c"
],
"Title": "Print input lines longer than 80 characters in C"
}
|
233498
|
<p>I wanted to create a short little piece of code so that I could see the biases in the random function.</p>
<pre class="lang-py prettyprint-override"><code>import random
import statistics
import time
num = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
average = []
while True:
randomNum = random.randint(0, 9)
num[randomNum] += 1
average.append(randomNum)
print(f"\nThe average for all the numbers is {round(statistics.mean(average), round(sum(num) / 20))}") # The second part of the round function is to keep as few digits on screen while still showing changes with every number. 20 is the arbitrary number I found worked best.
print(f"The most common number is {num.index(max(num))}\n")
time.sleep(0.5)
</code></pre>
<p>Since I am new-ish to python I wanted to know if, even though its only 15 lines, that I am following good coding practices. That way when my code gets more complicated, I don't have to worry about that as much</p>
|
[] |
[
{
"body": "<pre><code>num = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]\n</code></pre>\n\n<p>The shorthand to initialize this is <code>[0] * 10</code>; it can be used for strings too (bonus fact.)</p>\n\n<pre><code>round(sum(num) / 20))\n</code></pre>\n\n<p>This should be written as <code>round(sum(num), 20)</code> as the division operator adds in error, and is present through many iterations. Changing it to the latter reduced the bias.</p>\n\n<pre><code>time.sleep(0.5)\n</code></pre>\n\n<p>Usually the user doesn't want to wait if they don't have to; if this is run as a console program and if the user wants to inspect the output (before it disappears), it can be managed in the IDE. If the user must press a key, calling <code>input()</code> waits.</p>\n\n<p>I would also avoid hardcoding the start and end values for random, and the array size and instead use variables.</p>\n\n<p>The program will eventually run out of memory because the <code>average</code> list is being appended to every iteration and not being cleared. This can be prevented by instead summing the numbers (keeping a single numeric counter) and dividing by the total number of iterations. This has been an exercise left for the author.</p>\n\n<p>The final code becomes:</p>\n\n<pre><code>import random\nimport statistics\n\nstart = 0\nend = 9\n\nnum = [0] * abs(end - start + 1)\naverage = []\n\nwhile True:\n randomNum = random.randint(start, end)\n num[randomNum] += 1\n average.append(randomNum)\n print(\n f\"\\nThe average for all the numbers is {round(statistics.mean(average), round(sum(num), 20))}\"\n )\n print(f\"The most common number is {num.index(max(num))}\\n\")\n\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T01:45:42.047",
"Id": "233500",
"ParentId": "233499",
"Score": "2"
}
},
{
"body": "<p>Hard coding your data can be lengthy and it can restrict flexibility when carrying out further analysis. You can shorten your code with list comprehension. </p>\n\n<pre><code>import random\n\nn = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n\ndef main(val):\n ls = [i for i in random.choices(n, k=val)]\n ns = sum(ls)/len(ls)\n print('Length of Data : {}\\nSum of Data : {}\\nAverage of Data: {}\\nRandom Gen Data: {}'.format(len(ls), sum(ls), ns, ls))\n\nmain(100) #Enter amount of data you want to pass through the function\n</code></pre>\n\n<p>This returns:</p>\n\n<pre><code>Length of Data : 100\nSum of Data : 399\nAverage of Data: 3.99\nRandom Gen Data: [7, 4, 0, 8, 8, 0, 6, 7, 6, 4, 7, 0, 0, 0, 9, 4, 3, 0, 0, 7, 0, 4, 6, 5, 3, 0, 6, 0, 7, 0, 0, 4, 3, 7, 7, 9, 5, 3, 5, 2, 0, 4, 1, 1, 5, 8, 9, 0, 3, 2, 7, 5, 3, 3, 3, 3, 7, 5, 7, 5, 7, 1, 6, 2, 7, 7, 5, 1,6, 6, 4, 7, 8, 2, 0, 1, 5, 3, 5, 4, 9, 7, 7, 2, 0, 3, 4, 6, 3, 4, 3, 5, 6, 3, 0, 1, 3, 8, 0, 1]\n</code></pre>\n\n<p>It isn't necessary to use a <code>while</code> loop in this instance because you will still need to break your loop which is the same as giving a start and end value to a random range reference. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T08:09:56.717",
"Id": "233522",
"ParentId": "233499",
"Score": "3"
}
},
{
"body": "<p>As noted in the <a href=\"https://codereview.stackexchange.com/a/233500/98493\">answer</a> by <a href=\"https://codereview.stackexchange.com/users/8149/alexyorke\">@alexyorke</a>, you keep on adding to the data list. This means that your program can run out of memory. One way to reduce this risk greatly is to not save every data point, but use the data of how often each number appears.</p>\n\n<p>Here are two different ways to do it, one uses a <code>list</code> as an array, like your code:</p>\n\n<pre><code>def mean(numbers):\n return sum(i * n for i, n in enumerate(numbers)) / sum(numbers)\n\ndef most_common(numbers):\n return max((n, i) for i, n in enumerate(numbers))[1]\n\nif __name__ == \"__main__\":\n high = 10\n counter = [0] * high\n for _ in range(1000):\n counter[random.randrange(high)] += 1\n average = round(mean(counter), round(sum(counter) / 20))\n print(f\"\\nThe average for all the numbers is {average}\")\n print(f\"The most common number is {most_common(counter)}\\n\")\n</code></pre>\n\n<p>This has the disadvantage that it only works for integers (because only integers can be indices for a <code>list</code>). Instead you could use a <code>collections.Counter</code> to keep the counts:</p>\n\n<pre><code>from collections import Counter\n\ndef mean(counts):\n return sum(i * n for n, i in counts.items()) / sum(counts.values())\n\ndef most_common(counts):\n return counts.most_common(1)[0][0]\n\nif __name__ == \"__main__\":\n high = 10\n counter = Counter()\n for _ in range(1000):\n counter[random.randrange(high)] += 1\n average = round(mean(counter), round(sum(counter.values()) / 20))\n print(f\"\\nThe average for all the numbers is {average}\")\n print(f\"The most common number is {most_common(counter)}\\n\")\n</code></pre>\n\n<p>Note that in both cases I added a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a> to allow importing from this script from other scripts, which is a good practice to use.</p>\n\n<hr>\n\n<p>As a bonus, making a rudimentary histogram is also quite easy with the counter and some format string magic:</p>\n\n<pre><code>width = 60\nnorm = sum(counter.values())\nfor i, n in sorted(counter.items()):\n print(f\"{i:<2} | {'#' * int((n * width / norm)):<{width}}| {n / norm:>7.2%}\")\n\n0 | ##### | 9.80%\n1 | ###### | 10.40%\n2 | ###### | 10.20%\n3 | ##### | 8.40%\n4 | ###### | 10.70%\n5 | ##### | 9.30%\n6 | ###### | 11.00%\n7 | ##### | 9.40%\n8 | ###### | 10.80%\n9 | ###### | 10.00%\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T11:38:31.277",
"Id": "233534",
"ParentId": "233499",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "233500",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T01:34:17.187",
"Id": "233499",
"Score": "3",
"Tags": [
"python",
"beginner",
"python-3.x",
"random"
],
"Title": "Random Function Bias Tester"
}
|
233499
|
<p>This problem is from <a href="https://adventofcode.com/2019/day/4" rel="nofollow noreferrer">Advent of Code day 4</a> (part 1). The problem is to find the number of ints in the given range satisfying:</p>
<ul>
<li>all digits are non decreasing</li>
<li>there is at least one group of at least two equal digits in a row</li>
</ul>
<p><code>combinations</code> only generates non-decreasing sequences; for example:</p>
<pre><code>λ> combinations 2 ['1'..'3']
["11","12","13","22","23","33"]
</code></pre>
<p>The algorithm generates all non-decreasing combinations from <code>['0'..'9']</code>, then checks that there's at least one repeating character, that there are no leading zeros, and that the number is in range. Running it with the input <code>125730-579381</code> correctly prints <code>2081</code>.</p>
<p>The main things I want to know about are whether there's a way to improve the algorithm, and whether the readability is good. </p>
<pre class="lang-hs prettyprint-override"><code>import Data.List (tails, group)
import Control.Arrow
import Control.Monad
-- all non-decreasing combinations of k from xs
combinations :: Int -> [a] -> [[a]]
combinations 0 _ = [[]]
combinations k xs = do
xs'@(x:_) <- tails xs
map (x:) $ combinations (pred k) xs'
-- return True iff all predicates are satisfied
allF :: [a -> Bool] -> a -> Bool
allF fs x = and $ map ($ x) fs
-- all ints within the range satisfying:
-- strictly increasing digits
-- at least one sequence of exactly 2 of the same digit
solve :: Int -> Int -> Int
solve low hi = length . takeWhile (<= hi) . dropWhile (< low) . map read .
filter (allF [hasDouble, noLeadingZeros]) $ combinations 6 ['0'..'9']
where hasDouble = any ((> 1) . length) . group
noLeadingZeros = (/= '0') . head
main :: IO ()
main = do
(low, high) <- join (***) read <$> second tail <$> span (/= '-') <$> getLine
print $ solve low high
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T14:29:51.583",
"Id": "456597",
"Score": "1",
"body": "Your getLine arrow is impressive! You apparently forgot to check isSorted with allF? Where in the codeadvent spec did you read the exactly ==2 and noLeadingZeroes part? Contrary to your spec as well as your formula, it explicity says that 111111 is feasible, and implicitly that 000000 also is: non-decreasing and repetetive!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T15:11:18.733",
"Id": "456601",
"Score": "0",
"body": "`combinations` generates only non-decreasing sequences so there's no need to check that condition a second time in my algorithm. I think that this is faster than generating all numbers in the range and checking that they're ascending. In part two of the question (not shown on the link until you solve part 1), the requirement changes to be exactly == 2 instead of at least 2. I will update my question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T15:29:37.477",
"Id": "456603",
"Score": "0",
"body": "@RomanCzyborra also the `noLeadingZeroes` part is because this question deals with numbers instead of strings of digits. If I didn't include that part, my algorithm would deem `000000` as good when in reality that would just be `0` which has no repeating digits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T15:53:14.197",
"Id": "456605",
"Score": "1",
"body": "I finished that codeadvent now too and you are right that the count requirement reduces to (==2) after you have correctly calculated the nubby (>=2) and also that you had already specified the nondecreasing in the combinations comment. As to zero leads: apparently codeadvent hands everybody a randomized individual [min..max] puzzle range to count thru that does seem to start above 111110 or at least it did for me nulling any ambiguity."
}
] |
[
{
"body": "<p>Disclaimer: I don't know Haskell and I have never used it before.</p>\n\n<pre><code>solve low hi = length . takeWhile (<= hi) . dropWhile (< low) . map read .\n filter (allF [hasDouble, noLeadingZeros]) $ combinations 6 ['0'..'9']\n where hasDouble = any ((== 2) . length) . group\n noLeadingZeros = (/= '0') . head\n</code></pre>\n\n<p>Instead of running <code>combinations 6 ['0'..'9']</code> and then chopping off everything which has a zero at the start, generate numbers from <code>100000..999999</code> and then convert it to a string. This would eliminate the <code>combinations</code> method.</p>\n\n<p>I was able to make the following conclusions about the algorithm:</p>\n\n<ul>\n<li><p>if the numbers are sorted from smallest to largest, then it should equal the original number (i.e. they are already sorted from smallest to greatest)</p></li>\n<li><p>if the numbers with no duplicates does not equal the original number, then it means that there is at least two which were \"de-duped\", therefore it has two duplicates</p></li>\n</ul>\n\n<p>I was able to produce the following code:</p>\n\n<pre><code>import Data.List\n\ncheckNum num = do return ((sort(show num) == (show num) && (nub (show num)) /= (show num)))\nmain = do checkNum 4222211\n</code></pre>\n\n<p>This checks if the sorted number (as a string) is equal to itself (which means that it is increasing correctly), and <code>nub</code> removes all duplicate digits.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T12:57:26.807",
"Id": "456583",
"Score": "0",
"body": "a sorted number with a triplicate and no duplicate is also unequal to its nub and hence a false positive"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T13:00:28.930",
"Id": "456584",
"Score": "0",
"body": "@RomanCzyborra what would be an example of that number?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T13:11:31.607",
"Id": "456585",
"Score": "0",
"body": "nub \"111\" == \"1‘' /= \"111\" but (all(/=2).map length.group) \"111\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T13:13:32.457",
"Id": "456586",
"Score": "0",
"body": "@RomanCzyborra wouldn't that be allowed? `111111 meets these criteria (double 11, never decreases).` and `Two adjacent digits are the same`. Let me know if I'm misunderstanding something"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T13:23:01.033",
"Id": "456587",
"Score": "0",
"body": "I would word your requirement as a group of at least two equal digits in a row unlike ours of at least one group of *exactly* two equal digits in a row. In my understanding, exactly means no less than and no more than."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T13:37:02.833",
"Id": "456589",
"Score": "0",
"body": "i think @alexyorke you also need to enhance your main with something like print to get the IO() return type, and may omit do, return, and all but your innermost parentheses, but better confer http://tio.run/ or your local runhaskell"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T03:50:01.327",
"Id": "233507",
"ParentId": "233504",
"Score": "1"
}
},
{
"body": "<p>I would take the show(Int->[Char]) shortcut instead of going the zero-prefixing read([Char]->Int) roundabout:</p>\n\n<pre><code>count[from,to]=\n sum[1|\n i<-[from..to],\n let s=show i,\n any(==2)[length g|g<-group s],\n s==sort s]\n</code></pre>\n\n<p>Or a little more efficiently assembled:</p>\n\n<pre><code>sorted [a, b] = a <= b\nsorted (a:b:c) = sorted [a, b] && sorted (b: c)\nsorted _ = True\nduplicate s = [ ] < [2 | [_,_] <- group s]\ngood s = sorted s && duplicate s\ncount [min, max] = sum [1 | i <- [min..max], good(show i)]\n</code></pre>\n\n<p>Or single-scanned:</p>\n\n<pre><code>good (pair, span, max, rest) = \n if rest == 0 then pair || span == 2 else\n let (q, r) = quotRem rest 10\n in case compare r max of\n GT -> False\n EQ -> good (pair, span + 1, r, q)\n LT -> good (pair || span == 2, 1, r, q)\ncount min max =\n sum [1 | i <- [min..max], good(False, 0, 9, i)]\n</code></pre>\n\n<p>When referencing the original codeadvent instead of the codereview specification, this diverts to a calculation of 4795 feasible passwords in one million combinations:</p>\n\n\n\n<pre class=\"lang-hs prettyprint-override\"><code>import Data.List\nmain=print$sum[1|i<-[1000000..1999999],s<-[tail.show$i],s/=nub s,s==sort s]\n</code></pre>\n\n<p><a href=\"https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRzyezuIQrNzEzz7agKDOvRKW4NDfasCbTRjfa0AAM9PQMLcEgVqcYKFqSmJmjV5yRX66SCRTQt80rTVIo1im2tS0GGVkc@/8/AA\" rel=\"nofollow noreferrer\" title=\"Haskell – Try It Online\">Try it online!</a></p>\n\n<p>If 000000 and its likes are no legal six-digit numbers the password space reduces to 2919 in 900000:</p>\n\n\n\n<pre class=\"lang-hs prettyprint-override\"><code>import Data.List\nmain=print$sum[1|\n i<-[100000..999999],\n s<-[show$i],s/=nub s,s==sort s]\n</code></pre>\n\n<p><a href=\"https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRzyezuIQrNzEzz7agKDOvRKW4NDfasIZLIdNGN9rQAAT09CzBIFaHS6EYKFqckV@ukhmrU6xvm1eapFCsU2xrWwwyrzj2/38A\" rel=\"nofollow noreferrer\" title=\"Haskell – Try It Online\">Try it online!</a></p>\n\n<p>But the codeadvent challenge asks to count (>=2) group occurrences upfront and then upon success to count the exactly (==2) group occurrences in an unambiguous range:</p>\n\n\n\n<pre class=\"lang-hs prettyprint-override\"><code>puzzle=[156218..652527]\nv(0,_)2_=[1,1];v(0,_)1x=x;v(0,_)_[_,z]=[1,z]\nv(n,m)s x=let(q,r)=quotRem n 10 in case compare r m of\n GT->[0,0];EQ->v(q,r)(s+1)x;LT->v(q,r)1$v(0,0)s x\ninstance Num a=>Num[a]where\n (+)=zipWith(+); (*)=zipWith(*); (-)=zipWith(-);\n abs=map abs; signum=map signum; fromInteger=repeat.fromInteger;\nmain=print$sum[v(i,9)0[0,0]|i<-puzzle]\n</code></pre>\n\n<p><a href=\"https://tio.run/##TZDfS8MwEMff@1fcwx6aLR1NoVOJ2ZuIIIIy8KGUEsttCzZpl6S1FP/32m7KfLrv537fHaX7xKoax6YdhgpFxtJNwm7X602apMlNHnRhTAuSFFOEspxfkPWi/5VFVtAhn6PDnGyoJg56UaEPT9QScWpr/4YaDLAYlIFSOoSy1o20CBY01PsAHnfRNotpnPOH12jbnStDt2Kk58@7PwdbzBPjuX2gjPPSlAgvrQYptpPJZP51RIsBhCsiBtW8K3@cJIdweeXlzNGVI8IDkB9OaNnMloNTB9PqM18kh72t9ZPxeEArLDYo/fqfiwdaKiMaq4xfuGmRLlT0jsTng77VfXR5bT6OPw\" rel=\"nofollow noreferrer\" title=\"Haskell – Try It Online\">Try it online!</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T10:55:02.903",
"Id": "233530",
"ParentId": "233504",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T02:13:20.507",
"Id": "233504",
"Score": "1",
"Tags": [
"haskell"
],
"Title": "Advent of Code #4 in Haskell - Ascending digits with double digit"
}
|
233504
|
<p>Can anyone advise on how to use the <em>SymPy</em> <a href="https://docs.sympy.org/latest/modules/physics/quantum/tensorproduct.html" rel="nofollow noreferrer">TensorProduct</a> function without having to explicitly indicate the full sequence of objects to take the product of. Below (for the simple case N=3) you can see one of my attempts. But the tensor products are still not coinciding, hence I am still having to write out the full sequence to get the correct answer. </p>
<pre><code>import scipy
from numpy import*
import math
from sympy import I, Matrix, symbols
from sympy.physics.quantum import TensorProduct
N = 3
x = array([1/(math.sqrt(2)),1/(math.sqrt(2))])
V =[]
for i in range(1,N+1):
V.append(x)
V = array(V)
TP1 = TensorProduct(V[0],V[1],V[2])
TP2 = TensorProduct(V[:])
print TP1
print TP2
</code></pre>
<p>Thanks for any assistance.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T03:37:12.263",
"Id": "456514",
"Score": "1",
"body": "Code not working as intended is [not ready for review on CodeReview@SE](https://codereview.stackexchange.com/help/on-topic). That said, try printing `V`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T03:44:20.557",
"Id": "456518",
"Score": "0",
"body": "@greybeard The code runs as is above and it prints $V$. The problem is that is does not give the correct tensor product unless I explicitly write out each element of the sequence."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T03:56:49.767",
"Id": "456519",
"Score": "2",
"body": "@JohnDoe try `TP2 = TensorProduct(*V)`; let me know if that works or if I'm misunderstanding something"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T04:00:42.580",
"Id": "456521",
"Score": "0",
"body": "@alexyorke That seems to works thanks! I'm not familiar with the '*v' syntax, I'm relatively new to Python. Where can I read up on this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T04:01:46.147",
"Id": "456522",
"Score": "0",
"body": "@JohnDoe Here is an article: https://stackoverflow.com/questions/36620025/pass-array-as-argument-in-python . I will post my comment as the answer which you can accept to let others know how you solved the problem"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T07:40:03.990",
"Id": "456552",
"Score": "0",
"body": "@greybeard It *does* work as intended, it's asking for a specific maintenance optimization. However, this is not the code as OP wrote it. It's an example. Which means this is a specific problem with MCVE, Stack Overflow territory. VTC as example code, will flag for migration."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T08:21:30.423",
"Id": "456558",
"Score": "0",
"body": "I see your point: emphasise it *in the question*."
}
] |
[
{
"body": "<p>To pass a list of array arguments as individual parameters to a Python function, use the <code>*</code> operator:</p>\n\n<pre><code>TP1 = TensorProduct(*V)\n</code></pre>\n\n<p>This is equivalent to <code>TensorProduct(V[0], V[1], V[2],...,V[n])</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T04:03:09.327",
"Id": "233510",
"ParentId": "233506",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "233510",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T03:12:31.110",
"Id": "233506",
"Score": "1",
"Tags": [
"python",
"python-2.x",
"sympy"
],
"Title": "Executing Scipy Tensor Product"
}
|
233506
|
<p>My code consists of <code>Split</code>, <code>Mid</code>, <code>Left</code>, <code>Right</code> and <code>Replace</code> functions which are used to trim my data into a more neat manner. However, it's too long and inefficient, it takes too much time to go through all this because I have up to thousands of files that will go through this.</p>
<p>My main code goes through a folder and goes through all the files inside the folder to find and search for strings and then copy it out into a new worksheet.</p>
<pre><code>'Test RowA(1)
wks.Cells(BlankRow, 1).Replace What:="testtest : ", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
</code></pre>
<hr>
<pre><code>'Start RowB(2)
wks.Cells(BlankRow, 2).Replace What:=" Started at: ", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
</code></pre>
<hr>
<pre><code>'Temp RowC(3)
Dim strSearchC As String
Dim cCell As Range
Dim s3 As String
strSearchC = "testflyy"
Set cCell = wks.Cells(BlankRow, 3).Find(What:=strSearchC, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not cCell Is Nothing Then
s3 = Split(cCell.Value, ":")(1)
s3 = Mid(s3, 1, 3)
cCell.Value = s3
End If
</code></pre>
<hr>
<pre><code>'Type RowD(4)
Dim strSearchD As String
Dim dCell As Range
Dim s4 As String
strSearchD = "testflyy"
Set dCell = wks.Cells(BlankRow, 4).Find(What:=strSearchD, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not dCell Is Nothing Then
s4 = Split(dCell.Value, "_", 3)(2)
s4 = Mid(s4, 1, 3)
dCell.Value = s4
End If
</code></pre>
<hr>
<pre><code>'No RowF(6)
Dim strSearchF As String
Dim fCell As Range
Dim s6 As String
strSearchF = "homebeestrash_archivetestts"
Set fCell = wks.Cells(BlankRow, 6).Find(What:=strSearchF, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not fCell Is Nothing Then
s6 = Split(fCell.Value, "testts")(1)
s6 = Mid(s6, 1, 2)
fCell.Value = s6
End If
</code></pre>
<hr>
<pre><code>'End RowG(7)
Dim strSearchG As String
Dim gCell As Range
Dim s7 As String
strSearchG = "homebeestrash_archivetestts"
Set gCell = wks.Cells(BlankRow, 7).Find(What:=strSearchG, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not gCell Is Nothing Then
s7 = Split(gCell.Value, "reports")(1)
s7 = Split(s7, "Report")(0)
s7 = Left(s7, 8) & " " & Right(s7, 6)
</code></pre>
<hr>
<pre><code>'Month RowH(8)
wks.Cells(BlankRow, 8).Value = WorksheetFunction.Transpose(Left(s7, 4) & "-" & Mid(s7, 5, 2) & "-" & Mid(s7, 7, 2)) '<~~ get 2019-03-02
gCell.Value = s7
End If
</code></pre>
<p>Basically these are to trim the already extracted data in each respective rows worksheet, Row A and B is just simply replacing the data with nothing, for Row C onwards to Row H,, i will search if the string exists on the particular row and then use <code>Split</code> or <code>Right</code>, <code>Left</code>, <code>Mid</code> functions.</p>
<p>Question: Is there any other way to write it more efficiently because there are too many codings with formats like this and I feel like its slowing my program down a lot.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T07:48:30.387",
"Id": "456553",
"Score": "0",
"body": "Welcome to Code Review. Can you please clarify what the code is supposed to do? It looks more like a proof-of-concep than like something that actually accomplishes something, but a proper description might just fix that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T08:27:37.340",
"Id": "456559",
"Score": "0",
"body": "Hi, i have edited my post, please have a look."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T11:09:50.973",
"Id": "456571",
"Score": "0",
"body": "Much better, can you also provide a better title? 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": "2019-12-06T20:16:53.430",
"Id": "456633",
"Score": "0",
"body": "What kind of files are being searched? There are much better ways to process the files but no way to advise on it without mock data."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-07T06:29:07.633",
"Id": "456660",
"Score": "0",
"body": "The coding that i have provided above is just trimming of the data that has already been copied into the worksheet, basically i find whether or not the string exists in the worksheet, if yes then trim it down using split, Right,Left,Mid functions, sometimes replace."
}
] |
[
{
"body": "<p>So I had a look at your code and I got confused to what you were trying to do with find. So I had to test it out for myself. If I understand it correctly you are using it to figure out if a string contains the value you are looking for. If it does you continue processing if not you skip it. </p>\n\n<p>However, this can be done by fetching the cell value and performing <code>InStr <> 0</code> to do the same thing. </p>\n\n<p>I wrote a quick VBA to see the performance of find in relation to InStr. The results of this was (as you can test yourself now) that the <code>.Find</code> method took aproximately 5 seconds to compute, whereas the <code>InStr</code> one finishes instantly. When running on 100000 lines it takes almost a minute to complete, whereas the <code>InStr</code> one finishes instantly. So since you perform the <code>Cells(x,y).Find</code> for 4 separate columns in thousand of files I would say that this is your main culprit for timeloss. </p>\n\n<pre><code>Sheet1.Cells(1, 2).Value = TimeValue(Now)\n\nFor i = 0 To 10000\nDim x\nSet x = Sheet1.Cells(1, 1).Find(What:=\"12\", LookIn:=xlFormulas, _\n LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _\n MatchCase:=False, SearchFormat:=False)\n If Not x Is Nothing Then\n Sheet1.Cells(1, 4) = \"Yup\"\n End If\nNext i\nSheet1.Cells(1, 3).Value = TimeValue(Now)\nSheet1.Cells(2, 2).Value = TimeValue(Now)\nFor i = 0 To 10000\nSet x = Sheet1.Cells(2, 1)\n If InStr(x, \"12\") <> 0 Then\n Sheet1.Cells(2, 4) = \"Yup\"\n End If\nNext i\nSheet1.Cells(2, 3).Value = TimeValue(Now)\n</code></pre>\n\n<p>On top of that you are running <code>Cells(x,y).Replace</code> which is about twice as slow as just setting the value of the Replace as seen below. </p>\n\n<pre><code>wks.Cells(BlankRow, 1) = Replace(wks.Cells(BlankRow, 1),\"string to remove\",\"\")\n</code></pre>\n\n<p>The methods you are running for Find and Replace are supposed to be executed on Ranges for the maximum efficiency. Say if you instead running replace on each cell one by one you execute it on the entire column straight away like this: </p>\n\n<pre><code>wks.Columns(1).Replace What:=\"testtest : \", Replacement:=\"\", LookAt:=xlPart, _\n SearchOrder:=xlByColumns, MatchCase:=False, SearchFormat:=False, _\n ReplaceFormat:=False\n</code></pre>\n\n<p>Then you will notice that the Replace is performed in less than a second for all rows. Making it a lot faster if you have massive files. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T08:36:35.987",
"Id": "456560",
"Score": "0",
"body": "Hi, thanks for trying it out yourself! i'm trying it out now and sorry for asking this, could you please explain to me your coding? like how it works? because i'm still very new to vba i'm not able to understand complicated codings"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T11:16:53.780",
"Id": "456574",
"Score": "0",
"body": "Sure, Top code does the same thing in two different ways. It's a benchmark where I perform the task the way you do it in the first loop 10000 times. Before I do that I print the time it started into a cell (Unnecessary for your code) and after it I print the end time into another cell. So Now I have Start and End time of the execution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T11:21:05.127",
"Id": "456575",
"Score": "0",
"body": "For the second loop I perform the task in another way where I just fetch the value of the cell and use string methods instead to perform the search for \"12\" in your case this would be \"testflyy\". If the result of InStr is 0 then no match was found. So If InStr(x,\"12\") <> 0 means that as long as the result is not 0 the string \"12\" was found. This gives the same result as your Find method since it searches for a string and if it is not found it is not processed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T11:23:31.450",
"Id": "456576",
"Score": "0",
"body": "The second set where we target the Replace method we would want to execute the Replace on all rows before we start processing them. So before you start iterating on BlankRow you would Call the new replace method from my code block so that all fields are properly formatted from the beginning."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-07T06:33:20.043",
"Id": "456663",
"Score": "0",
"body": "Thanks for explaining! for the first part of the coding, do you search for \"12\" and then write in \"Yup\" if it exists? what if i want to write in whatever comes after 12? basically the whole string?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-07T07:01:20.277",
"Id": "456664",
"Score": "0",
"body": "Ah sorry, yes exactly. As long as you get a match it will be Not 0. So if you search for 1234 on a string with value 1234 InStr will returen 1 for the start position of 1234. If you search for 12345 on string 1234 you get no match and it returns 0."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T06:45:54.297",
"Id": "233518",
"ParentId": "233512",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T05:38:55.420",
"Id": "233512",
"Score": "2",
"Tags": [
"vba",
"excel"
],
"Title": "VBA More effective way of data trimming"
}
|
233512
|
<p>I ended up using 2x 2D arrays with a one element border around everything to simplify the kernel logic.</p>
<pre><code>import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import java.util.Random;
public class WorldSimulation {
long generation = 0;
int[][] next = null;
int[][] current = null;
float cellWidth;
float cellHeight;
int width;
int height;
public WorldSimulation(int width, int height, float w, float h)
{
this.width = width;
this.height = height;
next = new int[width+2][height+2];
current = new int[width+2][height+2];
cellWidth = (w / this.width);
cellHeight = (h / this.height);
}
public void timeStep(Canvas canvas, Paint paint)
{
generation ++;
for (int i = 0; i < next.length; i++) {
System.arraycopy(next[i], 0, current[i], 0, next[0].length);
}
for(int i = 1; i < this.width+1; i++)
{
for(int j = 1; j < this.height+1; j++)
{
float left = (i * cellWidth);
float top = (j * cellHeight);
float right = (left + cellWidth);
float bottom = (top + cellHeight);
int status = current[i][j];
int neighbours = livingNeighbours(i, j);
if(status == 255) {
paint.setColor(Color.rgb(0, 255, 0));
canvas.drawRect(left-cellWidth,top-cellHeight,right,bottom,paint);
if (neighbours < 2) {
next[i][j]=0;
}
else if(neighbours >3)
{
next[i][j]=0;
}
}
else if(status!=255)
{
paint.setColor(Color.rgb(0, status--, 0));
canvas.drawRect(left-cellWidth,top-cellHeight,right,bottom,paint);
if(neighbours == 3)
{
next[i][j] = 255;
}
}
}
}
}
public int livingNeighbours(int i, int j) {
int alive = 0 ;
for(int kernelRow = i -1; kernelRow <= i+1; kernelRow ++)
{
for(int kernelCol = j -1; kernelCol <= j+1; kernelCol ++)
{
if(current[kernelRow][kernelCol]== 255 && !(kernelRow == i && kernelCol == j))
{
alive ++;
}
}
}
return alive;
}
public void setCell(int i, int j, boolean alive)
{
next[i][j] = 255;
}
}
</code></pre>
<p>The full implementation can be found here: <a href="https://github.com/jacasey/life/" rel="nofollow noreferrer">https://github.com/jacasey/life/</a> and I've put a version up on the Google Play Store as well.</p>
<p>The whole thing clocks in at around 12 KB which I think is pretty cool when you compare it to the monters apps on the playstore today.</p>
<p>I was thinking of re-implementing this with a 1D array and indexing calculations but I don't think this would really add to much re: size or performance wise.</p>
<p><a href="https://play.google.com/store/apps/details?id=com.jcasey.life" rel="nofollow noreferrer">https://play.google.com/store/apps/details?id=com.jcasey.life</a></p>
|
[] |
[
{
"body": "<p><strong>General isues</strong></p>\n\n<p>Your code doesn't follow the single responsibility principle. The class <code>WorldSimulation</code> is responsible for updating the game and creating the graphical representation. If you followed a naming convention where the name of a class describes it's functionality it would have to be <code>WorldSimulationAndPaint</code>.</p>\n\n<p>Instead of passing the canvas and paint to the game engine, you should try to follow the MVC pattern. I have once implemented a Conway's game of life too. I had a timer that was responsible for controlling the updates. The timer sent an event to the game engine telling it \"please advance the game state by one frame\". When the game engine had done that, the game engine sent an event to the user interface telling it \"here's the lates game state, please update the user interface.\"</p>\n\n<p>Once you have removed the responsibility of drawing from WorldSimulation you can remove the cellWidth and cellHeight fields.</p>\n\n<p>The events can be transmitted by setting up each component as a listener to the relevant source or with an event bus (such as Google Guava).</p>\n\n<p><strong>Field visibility</strong></p>\n\n<p>All the fields in WorldSimulation are visible to other classes in the package. The fields of a class should be as closely guarded as possible so they should be <code>private</code> unless a there is a very good reason to do otherwise. That way you guarantee that the state of the object can only be changed by the object itself. It also forces you to concentrate on the interface your class provides to others.</p>\n\n<p>The <code>livingNeighbours</code> method is not supposed to be accessed from outside the class, so it should be private too.</p>\n\n<p><strong>Magic numbers</strong></p>\n\n<p>What does 255 mean? Instead of using a literal integer every time you should define it as a constant whose name describes the meaning of the value and use the constant instead of the literal 255.</p>\n\n<pre><code>private static final int STATUS_ALIVE = 255;\nprivate static final int STATUS_DEAD = 0;\n</code></pre>\n\n<p><strong>Duplicated code</strong></p>\n\n<p>The drawRect call is identical in both branches of the if statement. You can take them both out and replace them with a single call after the if statement.</p>\n\n<pre><code>canvas.drawRect(left-cellWidth,top-cellHeight,right,bottom,paint);\n</code></pre>\n\n<p><strong>Misleading naming</strong></p>\n\n<p>In <code>livingNeighbours</code> you count number of cells, but the value is collected in a variable named <code>alive</code>. In spoken language \"alive\" has only two values (alive or dead). Thus it sugests that the field would be a boolean (as you have done in the setCell method), while it is in fact an integer. It should be named <code>livingNeighbourCount</code>.</p>\n\n<p><strong>Misleading method signature</strong></p>\n\n<p>The <code>alive</code> parameter suggest that one could set a cell to be either living or dead. The implementation however only sets it to a living state. Either fix the code to handle the parameter or remove it and rename the method to <code>setCellAlive</code>.</p>\n\n<pre><code>public void setCell(int i, int j, boolean alive)\n{\n next[i][j] = 255;\n}\n</code></pre>\n\n<p><strong>Rules</strong></p>\n\n<p>You're not really implementing <a href=\"https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life#Rules\" rel=\"nofollow noreferrer\">Conway's Game of Life</a>. :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T17:32:43.167",
"Id": "233552",
"ParentId": "233520",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T07:33:54.347",
"Id": "233520",
"Score": "0",
"Tags": [
"java",
"android"
],
"Title": "Implementation of Conway's Game Of Life on Android"
}
|
233520
|
<p>I have the requirement to return the result of my ViewModel as a Dictionary of KeyValue pairs. My view model comprises of multiple classes and can have null values in properties. I need to return only values which are not null and non-zero in case of <code>double/string</code> types. Following is the class I created:</p>
<pre><code>public static class ObjectExtensions
{
public static IDictionary<string, dynamic> ConvertToDictionary(this object source, BindingFlags bindingAttribute = BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public)
{
IDictionary<string, dynamic> dictionary = new Dictionary<string, dynamic>();
PropertyInfo[] properties = source.GetType().GetProperties(bindingAttribute);
foreach (PropertyInfo propertyInfo in properties)
{
if (propertyInfo.PropertyType == typeof(System.String) ||
propertyInfo.PropertyType == typeof(System.Int16) ||
propertyInfo.PropertyType == typeof(System.Int32) ||
propertyInfo.PropertyType == typeof(System.Int64) ||
propertyInfo.PropertyType == typeof(System.Double) ||
propertyInfo.PropertyType == typeof(System.Decimal) ||
propertyInfo.PropertyType == typeof(System.Guid)
)
{
dynamic propertyValue = propertyInfo.GetValue(source, null);
if (propertyValue != null)
{
if (propertyValue.GetType() == typeof(double))
{
propertyValue = Math.Round(propertyValue, 4);
}
dictionary.Add(propertyInfo.Name, propertyValue);
}
}
else if (propertyInfo.PropertyType.IsGenericType)
{
dynamic propertyValue = propertyInfo.GetValue(source, null);
if (propertyValue != null)
{
if (propertyValue.GetType() == typeof(double))
{
propertyValue = Math.Round(propertyValue, 4);
}
dictionary.Add(propertyInfo.Name, propertyValue);
}
}
else
{
dynamic complexPropertyValue = propertyInfo.GetValue(source, null);
if (complexPropertyValue != null)
{
PropertyInfo[] complexProperties = complexPropertyValue.GetType().GetProperties();
foreach (PropertyInfo complexPropertyInfo in complexProperties)
{
dynamic propertyValue = complexPropertyInfo.GetValue(complexPropertyValue, null);
if (propertyValue != null)
{
if (propertyValue.GetType() == typeof(double))
{
propertyValue = Math.Round(propertyValue, 4);
}
dictionary.Add(complexPropertyInfo.Name, propertyValue);
}
}
}
}
}
FormatDictionary(dictionary);
return dictionary;
}
private static IDictionary<string, dynamic> FormatDictionary(IDictionary<string, dynamic> source)
{
foreach (var item in source)
{
if (item.Value.GetType() == typeof(int) || item.Value.GetType() == typeof(double))
{
if (item.Value == 0)
{
source.Remove(item);
}
}
if (item.Value.GetType() == typeof(string))
{
if (string.IsNullOrWhiteSpace(item.Value))
{
source.Remove(item);
}
}
}
return source;
}
}
</code></pre>
<p>Is it the right approach. Any feedback will be appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T07:36:51.220",
"Id": "456550",
"Score": "0",
"body": "Right approach compared to ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T07:38:12.330",
"Id": "456551",
"Score": "0",
"body": "For using two `foreach loops` to check for nested properties."
}
] |
[
{
"body": "<p>Here is my feedback</p>\n\n<ol>\n<li><p>Why do you use full types name, like <code>System.Double</code> ? I prefer shorter version , just <code>double</code>.</p></li>\n<li><p>Also I prefer to use <code>var</code> as it makes code shorter and more readable. So instead of <code>IDictionary<string, dynamic> dictionary = new Dictionary<string, dynamic>();</code> I would use <code>var dictionary = new Dictionary<string, dynamic>();</code> which looks neater for me.</p></li>\n<li><p>For some reason you do not handle <code>float</code> datatype ... Probaly you just missed it. The same for <code>char</code> and <code>boolean</code> datatypes. So your code will fail for class with these properties types.</p></li>\n<li><p>That is also strange that you <code>Round</code> only <code>double</code> values. What about <code>float</code> and <code>decimal</code> types ? probably you should be consistent.</p></li>\n<li><p>Looks like in first <code>if</code> statement you wanted to check if type is built-in primitive type. I would recommend extract separate method for it - <code>IsPrimitiveType(Type type)</code></p></li>\n<li><p>Function name <code>FormatDictionary</code> is misleading as for me. Because it does not format a dictionary, but filter it. So, I think <code>FilterDictionary</code> is a better name</p></li>\n<li><p>It is considered as bad practice to modify input parameter inside function, but <code>FormatDictionary</code> does it. I would recommend to create new collection and return it, instead of modifying existed one</p></li>\n</ol>\n\n<p>That is what I see on the first glance. Probably there is something else if look closer :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T16:33:35.880",
"Id": "456607",
"Score": "0",
"body": "BTW: [\"As a matter of style, use of the keyword is favoured over use of the complete system type name.\"](https://www.ecma-international.org/publications/standards/Ecma-334.htm). So use `int` instead of `Int32` etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-08T13:01:22.563",
"Id": "456726",
"Score": "1",
"body": "Thanks for the feedback. Appreciated."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T13:20:04.143",
"Id": "233541",
"ParentId": "233521",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "233541",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T07:34:04.957",
"Id": "233521",
"Score": "0",
"Tags": [
"c#",
"hash-map",
"reflection"
],
"Title": "To convert all the class properties to IDictionary<string, dynamic>"
}
|
233521
|
<p>I would like feedback on this <code>DistinctUntilChangedBy</code> operator for <code>System.Reactive</code> that only emits when the current value is different than the last by a specified amount. Is there a better implementation?</p>
<p>I want to avoid multiple emits when the stream looks like this: 0.80, 0.81, 0.80, 0.81, etc.</p>
<p>Using the operator like this:</p>
<pre><code>stream.DistinctUntilChangedBy(0.01).Subscribe(x => Console.WriteLine(x));
</code></pre>
<p>Should output this:</p>
<pre><code>0.80
</code></pre>
<p>The operator looks like this and it is also on GitHub as a <a href="https://gist.github.com/mgnslndh/a8ec564faf19c1c4ade44be1a32c3679" rel="nofollow noreferrer">gist</a>:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Reactive.Linq;
namespace Gists.Reactive.Linq
{
public static partial class ObservableExtensions
{
///<summary>
///Only emit when the current value is different than the last by the specified amount.
///</summary>
public static IObservable<decimal> DistinctUntilChangedBy(this IObservable<decimal> source, decimal amount)
{
return source.DistinctUntilChanged(new DistinctUntilChangedByEqualityComparer(amount));
}
private class DistinctUntilChangedByEqualityComparer : IEqualityComparer<decimal>
{
private readonly decimal amount;
public DistinctUntilChangedByEqualityComparer(decimal amount)
{
this.amount = amount;
}
public bool Equals(decimal x, decimal y)
{
var diff = Math.Abs(x - y);
return diff <= Math.Abs(amount);
}
public int GetHashCode(decimal obj)
{
throw new NotSupportedException();
}
}
}
}
</code></pre>
|
[] |
[
{
"body": "<h2><code>DistinctUntilChangedBy()</code></h2>\n<p>This method is <code>public</code> and therefore should do proper argument validation. Since this method is an extension-method, it could be called like:</p>\n<pre><code>ObservableExtensions.DistinctUntilChangedBy(someObservable, someDecimal);\n</code></pre>\n<p>If <code>someObservable</code>is <code>null</code>, your method would throw a <code>NullReferenceException</code> where an <code>ArgumentNullException</code> would be a better fit.</p>\n<h2><code>Equals(decimal, decimal)</code></h2>\n<p>Instead of returning <code>diff <= Math.Abs(amount)</code> you could set the class variable <code>amount</code> in the constructor directly to the <code>Abs(amount)</code> of the passed argument:</p>\n<pre><code>this.amount = Math.Abs(amount)\n</code></pre>\n<p>That could speed it up if the <code>Equals()</code> method is called often.</p>\n<h2><code>GetHashCode(decimal)</code></h2>\n<p>Only if you are 100% sure that this method won't ever be called should you throw a <code>NotSupportedException</code>. See <a href=\"//stackoverflow.com/q/4095395/\"><em>What's the role of <code>GetHashCode</code> in the <code>IEqualityComparer<T></code> in .NET?</em></a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-09T14:44:18.390",
"Id": "233693",
"ParentId": "233526",
"Score": "2"
}
},
{
"body": "<p>You can do it without the IEqualityComparer but does get a tad bit more complex. Taking the gist of <a href=\"http://www.zerobugbuild.com/?p=213\" rel=\"nofollow noreferrer\">PairWithPrevious</a></p>\n\n<p>You can create an extension that keeps track of the previous value. The code that makes this look complex is the nullable decimal from the seed data. We do this so that we know it came from seed data and we can skip it. </p>\n\n<pre><code>public static IObservable<decimal> DistinctVariance(this IObservable<decimal> source, decimal offSet)\n{\n return source.Scan(Tuple.Create<decimal?, decimal?>(null, null), (tuple, item) => Tuple.Create<decimal?, decimal?>(tuple.Item2, item))\n .Where(tuple => tuple.Item2 != null && (tuple.Item1 == null || Math.Abs(tuple.Item1.Value - tuple.Item2.Value) > offSet))\n .Select(tuple => tuple.Item2.Value);\n\n}\n</code></pre>\n\n<p>This should act like your original function </p>\n\n<p>if we have data like .80m, .81m, .82m, .83m, .80m it would emit .80m, .80m</p>\n\n<p>Now if we wanted to emit once the last publish value has changed more than the variance we could write the function </p>\n\n<pre><code>public static IObservable<decimal> DistinctVariance2(this IObservable<decimal> source, decimal offSet)\n{\n return source.Scan((prior, current) => Math.Abs(prior - current) > offSet ? current : prior)\n .DistinctUntilChanged();\n\n}\n</code></pre>\n\n<p>Since we don't care about the previous value we can just keep storing the last value. \nInput of .80m, .81m, .82m, .83m, .80m would emit .80, .82, .80</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-21T19:58:13.153",
"Id": "235979",
"ParentId": "233526",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T09:36:26.410",
"Id": "233526",
"Score": "4",
"Tags": [
"c#",
"system.reactive"
],
"Title": "Reactive operator for distinct values that must change by amount"
}
|
233526
|
<p>I am doing <a href="https://adventofcode.com" rel="noreferrer">Advent of Code 2019</a> in order to learn Rust (it's been fun, but challenging!). </p>
<p>I am looking for help and feedback from more experiences Rustaceans on my solution to <a href="https://adventofcode.com/2019/day/6" rel="noreferrer">Day 6: Universal Orbit Map</a> in Rust. </p>
<p>Specifically I am looking to see where I am <strong>not</strong> doing it the idiomatic Rust way, where my Java background shines through or anything that doesn't look or feel right or Rust-ish.</p>
<pre><code>use std::collections::HashMap;
use std::io;
use std::io::Read;
fn main() {
let mut input = String::new();
match io::stdin().read_to_string(&mut input) {
Ok(v) => v,
Err(_) => panic!("Unable to read input"),
};
let mut orbits = HashMap::new();
input
.lines()
.map(|l| l.split(")").collect::<Vec<&str>>())
.for_each(|o| {
orbits.insert(o[1].to_string(), o[0].to_string());
});
let num_orbits = orbits
.iter()
.map(|k| path(k.0, &orbits))
.map(|p| p.len())
.sum::<usize>();
let mut you_path = path("YOU", &orbits);
let mut san_path = path("SAN", &orbits);
while you_path.get(you_path.len() - 1) == san_path.get(san_path.len() - 1) {
you_path.pop();
san_path.pop();
}
println!(
"Number of orbits: {}, Number of jumps: {}",
num_orbits,
(you_path.len() + san_path.len())
);
}
fn path(from: &str, orbits: &HashMap<String, String>) -> Vec<String> {
let mut p = Vec::new();
let mut inner = from;
loop {
match orbits.get(inner) {
Some(v) => {
p.push(v.to_string());
inner = v;
}
None => break,
};
}
p
}
</code></pre>
|
[] |
[
{
"body": "<p>Disclaimer: I don't know Rust.</p>\n\n<p>I only have comments on performance.</p>\n\n<p>To compute the number of orbits, it's unnecessary to compute paths, you could compute just the length of paths. That would reduce the space complexity to constant.</p>\n\n<p>When computing the number of orbits, instead of going from each planet until the root, you could go from the root, traversing paths to every planet exactly once. That would reduce the time complexity to linear.</p>\n\n<p>When computing the common ancestor from SAN and YOU, you only need to track part of the path segments, until a common point. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-07T11:04:56.320",
"Id": "233583",
"ParentId": "233527",
"Score": "4"
}
},
{
"body": "<pre><code>fn main() {\n let mut input = String::new();\n match io::stdin().read_to_string(&mut input) {\n Ok(v) => v,\n Err(_) => panic!(\"Unable to read input\"),\n };\n</code></pre>\n\n<p>If you are just going to panic, use <code>unwrap</code> or <code>expect</code> method on Result. </p>\n\n<pre><code> let mut orbits = HashMap::new();\n input\n .lines()\n .map(|l| l.split(\")\").collect::<Vec<&str>>())\n .for_each(|o| {\n orbits.insert(o[1].to_string(), o[0].to_string());\n });\n</code></pre>\n\n<p>I'd do:</p>\n\n<pre><code> let mut orbits : HashMap<_,_> = input\n .lines()\n .map(|l| l.split(\")\").collect::<Vec<&str>>())\n .map(|o| {\n (o[1].to_string(), o[0].to_string())\n })\n .collect();\n</code></pre>\n\n<p>You can <code>collect()</code> into many things including hashmaps.</p>\n\n<pre><code> let num_orbits = orbits\n .iter()\n .map(|k| path(k.0, &orbits))\n .map(|p| p.len())\n .sum::<usize>();\n</code></pre>\n\n<p>I generally prefer to put the variable on the let: <code>let num_orbits: usize</code>, instead of in the <code>::<></code></p>\n\n<pre><code> let mut you_path = path(\"YOU\", &orbits);\n let mut san_path = path(\"SAN\", &orbits);\n\n while you_path.get(you_path.len() - 1) == san_path.get(san_path.len() - 1) {\n you_path.pop();\n san_path.pop();\n }\n</code></pre>\n\n<p>There is a <code>last()</code> method that you can use here insetad of the <code>.get()</code></p>\n\n<pre><code> println!(\n \"Number of orbits: {}, Number of jumps: {}\",\n num_orbits,\n (you_path.len() + san_path.len())\n );\n}\n\nfn path(from: &str, orbits: &HashMap<String, String>) -> Vec<String> {\n</code></pre>\n\n<p>You could have all of this operate on <code>&str</code> if you use lifetimes, but thats a little more advanced.</p>\n\n<pre><code> let mut p = Vec::new();\n let mut inner = from;\n loop {\n match orbits.get(inner) {\n Some(v) => {\n</code></pre>\n\n<p>Use <code>while let Some(v) = orbits.get(inner) {</code>.\nThis will loop until orbits.get returns <code>None</code>.</p>\n\n<pre><code> p.push(v.to_string());\n inner = v;\n }\n None => break,\n };\n }\n p\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-11T04:22:36.480",
"Id": "457178",
"Score": "0",
"body": "Thanks! That’s very helpful and generous!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-10T01:22:00.173",
"Id": "233738",
"ParentId": "233527",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "233738",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T10:44:19.067",
"Id": "233527",
"Score": "5",
"Tags": [
"programming-challenge",
"rust"
],
"Title": "Advent of Code 2019 Day 6 - Beginner Rust solution"
}
|
233527
|
<p>I encountered a use case where it was needed to store each element of a tuple into a list of their respective type of the tuple element. To streamline this feature I wrote a method extension that I overloaded for different sized tuples. The code is quite basic and does not do a lot but I thought you could give me some feedback on how to improve it and/or how to do it in a more elegant way </p>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Collections.Generic;
public static class UserSpecificTupleExtension
{
/// <summary>
/// Deconstructs a tuple and stores each indivdual value into a provided non-null List
/// </summary>
/// <typeparam name="T1">type of tuple element</typeparam>
/// <param name="value">Instance which calls this method</param>
/// <param name="List1">instance of a List which holds type T1 </param>
public static void Deconstruct<T1>(this Tuple<T1> value, ref List<T1> List1)
{
var a = value.Item1;
List1.Add(a);
}
/// <summary>
/// Deconstructs a tuple and stores each indivdual value into a provided non-null List
/// </summary>
/// <typeparam name="T1">type of tuple element</typeparam>
/// <param name="value">Instance which calls this method</param>
/// <param name="List1">instance of a List which holds type T1</param>
public static void Deconstruct<T1>(this ValueTuple<T1> value, ref List<T1> List1)
{
var a = value.Item1;
List1.Add(a);
}
/// <summary>
/// Deconstructs a tuple and stores each indivdual value into a provided non-null List
/// </summary>
/// <typeparam name="T1">type of tuple element</typeparam>
/// <typeparam name="T2">type of tuple element</typeparam>
/// <param name="value">Instance which calls this method</param>
/// <param name="List1">instance of a List which holds type T1</param>
/// <param name="List2">instance of a List which holds type T2</param>
public static void Deconstruct<T1, T2>(this Tuple<T1, T2> value, ref List<T1> List1, ref List<T2> List2)
{
var (a, b) = value;
List1.Add(a);
List2.Add(b);
}
/// <summary>
/// Deconstructs a tuple and stores each indivdual value into a provided non-null List
/// </summary>
/// <typeparam name="T1">type of tuple element</typeparam>
/// <typeparam name="T2">type of tuple element</typeparam>
/// <param name="value">Instance which calls this method</param>
/// <param name="List1">instance of a List which holds type T1</param>
/// <param name="List2">instance of a List which holds type T2</param>
public static void Deconstruct<T1, T2>(this ValueTuple<T1, T2> value, ref List<T1> List1, ref List<T2> List2)
{
var (a, b) = value;
List1.Add(a);
List2.Add(b);
}
/// <summary>
/// Deconstructs a tuple and stores each indivdual value into a provided non-null List
/// </summary>
/// <typeparam name="T1">type of tuple element</typeparam>
/// <typeparam name="T2">type of tuple element</typeparam>
/// <typeparam name="T3">type of tuple element</typeparam>
/// <param name="value">Instance which calls this method</param>
/// <param name="List1">instance of a List which holds type T1</param>
/// <param name="List2">instance of a List which holds type T2</param>
/// <param name="List3">instance of a List which holds type T3</param>
public static void Deconstruct<T1, T2, T3>(this Tuple<T1, T2, T3> value, ref List<T1> List1, ref List<T2> List2, ref List<T3> List3)
{
var (a, b, c) = value;
List1.Add(a);
List2.Add(b);
List3.Add(c);
}
/// <summary>
/// Deconstructs a tuple and stores each indivdual value into a provided non-null List
/// </summary>
/// <typeparam name="T1">type of tuple element</typeparam>
/// <typeparam name="T2">type of tuple element</typeparam>
/// <typeparam name="T3">type of tuple element</typeparam>
/// <param name="value">Instance which calls this method</param>
/// <param name="List1">instance of a List which holds type T1</param>
/// <param name="List2">instance of a List which holds type T2</param>
/// <param name="List3">instance of a List which holds type T3</param>
public static void Deconstruct<T1, T2, T3>(this ValueTuple<T1, T2, T3> value, ref List<T1> List1, ref List<T2> List2, ref List<T3> List3)
{
var (a, b, c) = value;
List1.Add(a);
List2.Add(b);
List3.Add(c);
}
}
</code></pre>
<p>And here a small sample program:</p>
<pre><code>public class Program
{
public static void Main()
{
var listA = new List<int>();
var listB = new List<string>();
var listC = new List<char>();
(1, "4", '_').Deconstruct(ref listA, ref listB, ref listC);
listA.ForEach(Console.WriteLine);
listB.ForEach(Console.WriteLine);
Console.ReadKey();
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T22:27:29.800",
"Id": "456641",
"Score": "1",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. Feel free to post a follow-up question if the code has changed significantly enough."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T22:31:18.700",
"Id": "456642",
"Score": "0",
"body": "@Mast i will keep that in mind for the future"
}
] |
[
{
"body": "<h1><code>ref</code> parameters</h1>\n\n<p>Make sure you fully understand what <code>ref</code> does and when it's appropriate to use it.</p>\n\n<p><code>ref</code> gives you an <em>alias to the variable passed into the method</em>, so only use <code>ref</code> when you need to modify <em>the original variable passed by the caller</em>.</p>\n\n<p><code>List<T></code> is already a reference type: anything passed to a <code>List<T></code> parameter will already be a reference to an object of that type. You can happily modify the object via that reference without needing <code>ref</code>.</p>\n\n<h1>Parameter types</h1>\n\n<p>It's a good rule of thumb to accept the least specific type possible as a parameter.</p>\n\n<p>Because you are only calling <code>Add</code> on the given lists, you don't actually require a concrete <code>List<T></code> type to be passed. All lists that you'll ever be interested in implement <code>IList<T></code> which has an <code>Add</code> method, so you should accept <code>IList<T></code> instead.</p>\n\n<p>You could go even further: <code>IList<T>.Add</code> is inherited from <code>ICollection<T></code> so if you don't care about order then go ahead and loosen those parameter types to <code>ICollection<T></code>.</p>\n\n<h1>Method header</h1>\n\n<p>Good on you for documenting your public methods! It's a great practice to get into; keep on doing it.</p>\n\n<p>I do a have a few suggestions:</p>\n\n<pre><code>/// <summary>\n/// Deconstructs a tuple and stores each indivdual value into a provided non-null List\n/// </summary>\n/// <typeparam name=\"T1\">type of tuple element</typeparam>\n/// <param name=\"value\">Instance which calls this method</param>\n/// <param name=\"List1\">instance of a List which holds type T1 </param>\n</code></pre>\n\n<p>You (rightly) specify in the summary that the list must be non-null, but you don't actually check for <code>null</code> anywhere: your code will crash if <code>null</code> is passed.</p>\n\n<p>Common convention in C# is to perform argument validation at the start of the method and throw an appropriate <code>ArgumentException</code> (or one of its child types):</p>\n\n<pre><code>public static void Deconstruct<T1>(this Tuple<T1> value, List<T1> List1)\n{\n if (List1 is null) throw new ArgumentNullException(nameof(List1));\n // ...\n}\n</code></pre>\n\n<p>You could claim, \"What's the difference? It'll just crash anyway with an ArgumentNullException instead!\"</p>\n\n<p>The difference is:</p>\n\n<ol>\n<li>The exception is more clear to the user that <em>they</em> got the argument wrong, and</li>\n<li>By performing validation at the start you fail <em>fast</em>, rather than at some point in the middle. Imagine what happens in your <code>Deconstruct<T1, T2></code> if the first list is non-null but the second one is null -- you'll have modified only one of the given lists! Who gets to clean up the state of your now half-modified input arguments?</li>\n</ol>\n\n<p>While we're at it, change that parameter name from <code>List1</code> to <code>list</code>. C# convention dictates <code>camelCase</code> for parameter names, and the <code>1</code> is redundant for this overload.</p>\n\n<h1>Deconstruction</h1>\n\n<pre><code>public static void Deconstruct<T1, T2>(this ValueTuple<T1, T2> value, ref List<T1> List1, ref List<T2> List2)\n{\n var (a, b) = value;\n List1.Add(a);\n List2.Add(b);\n}\n</code></pre>\n\n<p>You gain nothing by doing <code>var (a, b) = value;</code>. It just adds an unnecessary deconstruction of <code>value</code>. You can already access the individual elements using the <code>ItemN</code> fields:</p>\n\n<pre><code>public static void Deconstruct<T1, T2>(this ValueTuple<T1, T2> value, IList<T1> list1, IList<T2> list2)\n{\n list1.Add(value.Item1);\n list2.Add(value.Item2);\n}\n</code></pre>\n\n<p>I might also suggest using a slightly different name from <code>Deconstruct</code>, since the compiler <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/deconstruct#deconstructing-user-defined-types\" rel=\"noreferrer\">sometimes gives special meaning to methods called <code>Deconstruct</code></a>. It wouldn't <em>actually</em> do anything special in this case because it doesn't meet all the requirements, but it might still mislead or confuse someone who's familiar with that feature. Maybe name them <code>DeconstructToLists</code> or something -- it avoids that ambiguity while making it more clear what it does and what its side effect is.</p>\n\n<hr>\n\n<p>Aside from that, I don't mind the repeatedness of the code. C# does not have first-class support for iterating over generic type arguments so any attempt to generalize your code will certainly result in a mess of reflection and boxing. There is such a small, finite set of generic flavours of <code>Tuple</code> and <code>ValueTuple</code> that I wouldn't invest the time in generalizing it further.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T22:07:36.253",
"Id": "456639",
"Score": "0",
"body": "Thanks for this great answer. The reason for using ref ... well, I just had in mind I must change obj and the change must be visible outside of the method. I think rust starts to creep into my thought patterns XD\n\nI totally forgot about ICollection in c#. currently, I just use IEnumerable for almost everything. regarding the naming that is certainly a good point didn't know about the special meaning of that method name thanks for that information.\n\nRegarding the null check... forgot to write them down but it was intended^^ as you have seen in my comments. Again thanks for taking a look :D"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T21:28:07.200",
"Id": "233560",
"ParentId": "233528",
"Score": "7"
}
},
{
"body": "<p>In addition to @Jeff's comments, you could also change your approach a bit. The reason you use <code>List<T1></code> is you want to do this with multiple <code>Tuple<T1></code> don't you? You might have lists of tuples in your code here and there e.g. <code>List<Tuple<T1, T2>></code>. Instead of creating methods which need to accept other objects as parameters and change their state - construct and return right in your extension method.</p>\n\n<pre><code>/// <summary>\n/// Takes a list of tuples and returns a tuple of lists.\n/// </summary>\npublic static Tuple<List<T1>, List<T2>> ToListTuple<T1, T2>( this IEnumerable<Tuple<T1, T2>> tupleList )\n{\n return new Tuple<List<T1>, List<T2>>(\n tupleList.Select( inputObj => inputObj.Item1 ).ToList(),\n tupleList.Select( inputObj => inputObj.Item2 ).ToList()\n );\n}\n</code></pre>\n\n<p>It might seem an overkill at first. Writing methods as pure functions is however something I would highly recommend. Pure functions are functions which do not modify state of any object, they just return things and their results are <em>repeatable</em>. Also if you take this approach the operation can be easily reversed:</p>\n\n<pre><code>/// <summary>\n/// Takes a tuple of lists and returns a list of tuples.\n/// </summary>\npublic static List<Tuple<T1, T2>> ToTupleList<T1, T2>(this Tuple<IEnumerable<T1>, IEnumerable<T2>> listTuple)\n{\n return listTuple.Item1.Zip(listTuple.Item2, MakeNewTuple).ToList();\n}\n\n/// <summary>\n/// Returns a tuple containing two objects.\n/// </summary>\nprivate static Tuple<T1, T2> MakeNewTuple<T1, T2>(T1 t1Item, T2 t2Item)\n{\n return new Tuple<T1, T2>(t1Item, t2Item);\n}\n</code></pre>\n\n<p>To support other sizes of <code>Tuple<...></code> objects you will need to write additional overloads.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-10T10:55:41.243",
"Id": "457019",
"Score": "1",
"body": "Very interesting. If the given use case would contain tuples containing list this is certainly a way to go. Unfortunately in my case I need to take reference from pre-existing lists and insert the the elements accordingly because we cannot change the given api. Nonetheless I really like your approach. Thanks a lot."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-10T10:31:43.043",
"Id": "233771",
"ParentId": "233528",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "233560",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T10:52:08.887",
"Id": "233528",
"Score": "5",
"Tags": [
"c#"
],
"Title": "Deconstruct tuple and store each element into a List of their respective element type"
}
|
233528
|
<p>Asked in interview today:</p>
<p>You want to paint a skyline on your wall using only horizontal brush strokes. You are given an array of numbers, each representing the size of the column/building in that position. E.g. [1,2,1] - you can use two (horizontal) brush strokes. The first will paint the entire first row, and the second will paint the middle of the 2nd column.</p>
<p>Write an efficient algorithm to do so.</p>
<p>Here's my solution - idea being you count each end of strokes, and wipe out a row (or go up a row) for every iteration:</p>
<pre><code>def solution(A):
strokes = 0
copy = [a for a in A]
while sum(copy) > 0:
for i in range(len(copy)):
if (copy[i] > 0) and ((i+1 == len(copy)) or (copy[i+1] == 0)):
strokes += 1
if copy[i] > 0:
copy[i] -= 1
return strokes
</code></pre>
<p>solution([1,0,5,8,0]) will output 9</p>
|
[] |
[
{
"body": "<p>With every height drop by 1 point, a line ends. So you just need to calculate the sum of height drops. Don't forget to account for the last height. You could also do the same thing from the other end (every height increase starts a line).</p>\n\n<pre><code>def skyline(heights):\n diffs = [e1 - e2 for e1, e2 in zip(heights, heights[1:])]\n return sum(diff for diff in diffs if diff > 0) + heights[-1]\n</code></pre>\n\n<hr>\n\n<p>Some remarks on your code:</p>\n\n<ul>\n<li><p><code>copy = [a for a in A]</code> can be rewritten as <code>copy = A.copy()</code></p></li>\n<li><p>some parentheses in <code>(copy[i] > 0) and ((i+1 == len(copy)) or (copy[i+1] == 0))</code> can be omitted:</p>\n\n<pre>if copy[i] > 0 and (i+1 == len(copy) or copy[i+1] == 0):</pre></li>\n<li><p>you can use <code>enumerate</code> in the for loop:</p>\n\n<pre>\nfor i, elem in enumerate(copy):\n if elem > 0 and (i+1 == len(copy) or copy[i+1] == 0):\n strokes += 1\n if elem > 0:\n copy[i] -= 1\n</pre></li>\n<li><p>the <code>if</code>s can be merged:</p>\n\n<pre>\nfor i, elem in enumerate(copy):\n if elem > 0:\n copy[i] -= 1\n if i+1 == len(copy) or copy[i+1] == 0:\n strokes += 1\n</pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-07T12:16:37.473",
"Id": "456675",
"Score": "0",
"body": "clever, simple and elegant... wish I would have thought of it :-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T15:01:45.483",
"Id": "233546",
"ParentId": "233531",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "233546",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T11:29:14.117",
"Id": "233531",
"Score": "3",
"Tags": [
"python",
"array",
"interview-questions"
],
"Title": "Find number of horizontal brush strokes to paint a skyline"
}
|
233531
|
<p>Was asked in an interview today - </p>
<p>You are given an integer (in finite range [-N, N]) and you wish to maximize the number by inserting somewhere the digit '5'. </p>
<p>My solution - the idea here is going from left to right and checking if the digit is bigger than 5 or not. The first time you reach one that isn't you insert the 5 there. With the exception of negative numbers where you check and do the opposite.</p>
<p>I did it by converting ints to strings and vice versa.</p>
<pre><code>def solution(N):
array = str(N)
result = []
mod = 1
for i in range(len(array) + 1):
if i == len(array):
result.append('5')
break
if array[i] == '-':
mod = -1
result.append(array[i])
continue
if int(array[i]) * mod > 5 * mod:
result.append(array[i])
else:
result.append('5')
result.append(array[i:])
break
return int("".join(result))
</code></pre>
<p>So - <code>solution(128)</code> will output <code>5128</code>; <code>solution(0)</code> will output <code>50</code>, <code>solution(-74)</code> will output <code>-574</code> etc.</p>
|
[] |
[
{
"body": "<p>Presumably, <code>if array[i] == '-'</code> is meant to check if the number is negative. Having it like you have though doesn't make a lot of sense. If it's in the loop, that suggests that a <code>-</code> could be expected at any point within the number. In reality though, it will only ever occur as the first character in the string. I'd just check <code>N</code> the number with <code>if N < 0</code> to see if it's negative. You can streamline this check right in the definition of <code>mod</code>:</p>\n\n<pre><code>mod = 1 if N >= 0 else -1\n</code></pre>\n\n<p>Unfortunately, that slightly complicates adding <code>-</code> to <code>result</code>. The simplest way to deal with it I think is just to change the definition of <code>result</code> to be similar to that of <code>mod</code>:</p>\n\n<pre><code>result = [] if n >= 0 else ['-']\n</code></pre>\n\n<p>Since the checks are the same though, you could combine then into returning a tuple instead then unpacking it:</p>\n\n<pre><code>mod, result = (1, []) if n >= 0 else (-1, ['-'])\n</code></pre>\n\n<p>And, <code>array</code> will need to have the <code>-</code> cleaved off if we're doing it before the loop:</p>\n\n<pre><code>mod, result, checked_digits = (1, [], digits) if n >= 0 else (-1, ['-'], digits[1:])\n</code></pre>\n\n<p>Normally, I don't think a triple variable definition like this should be encouraged, but there's nothing too fancy or complicated going on here to make the line confusing. I think it's fine.</p>\n\n<hr>\n\n<p>I'd rename <code>array</code> and <code>N</code>:</p>\n\n<ul>\n<li><p><code>array</code> isn't really a correct or useful description. I think <code>digits</code> would be better.</p></li>\n<li><p><code>N</code> should be <code>n</code>.</p></li>\n</ul>\n\n<hr>\n\n<p>You're iterating over the indices of <code>digits</code> and using <code>digits[i]</code> all over the place even though you don't even need the index in most cases. I'd iterate over the digits themselves, and use <code>enumerate</code> to get the index in the couple cases that you actually need it for:</p>\n\n<pre><code>for i, digit in enumerate(digits):\n . . .\n\n if int(digit) * mod > 5 * mod:\n result.append(digit)\n</code></pre>\n\n<hr>\n\n<p>I'd move the <code>if i == len(array):</code> check out of the loop as well. Really, it's just checking if at no point a <code>break</code> was encountered. That's exactly the use case for <code>for</code>'s <code>else</code> clause <a href=\"https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops\" rel=\"nofollow noreferrer\">(yes, <code>for</code> can have an <code>else</code>)</a>:</p>\n\n<pre><code>for i, digit in enumerate(checked_digits):\n . . .\n\nelse:\n result.append(5)\n</code></pre>\n\n<p>The <code>else</code> will only execute if no <code>break</code> was encountered. In the case of this code, that means that no digit greater than <code>5</code> was found.</p>\n\n<p>Honestly, this is the first time I've ever found a useful case for <code>for...else</code>. It worked out nice here though.</p>\n\n<hr>\n\n<p>I'd add <code>5</code> and <code>'5'</code> as constants at the top. Having the magic strings and numbers floating your code makes your code harder to change latter, and doesn't indicate what the <code>5</code> and <code>'5'</code> actually are for:</p>\n\n<pre><code>TARGET_NUM = 5\nTARGET_DIGIT = str(TARGET_NUM)\n\n\ndef solution(n):\n</code></pre>\n\n<p>Or, just make that number a parameter with a default to make it easy to use different target numbers:</p>\n\n<pre><code>def solution(n: int, target_num: int = 5) -> int:\n target_digit = str(target_num)\n</code></pre>\n\n<p>I also added some type hints in there, because why not?</p>\n\n<hr>\n\n<hr>\n\n<p>In the end, this is what I ended up with:</p>\n\n<pre><code>def solution(n: int, target_num: int = 5):\n target_digit = str(target_num)\n digits = str(n)\n\n mod, result, checked_digits = (1, [], digits) if n >= 0 else (-1, ['-'], digits[1:])\n\n for i, digit in enumerate(checked_digits):\n if int(digit) * mod > TARGET_NUM * mod:\n result.append(digit)\n\n else:\n result.append(TARGET_DIGIT)\n result.append(checked_digits[i:])\n break\n\n else:\n result.append(TARGET_DIGIT)\n\n return int(\"\".join(result))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-07T12:22:09.207",
"Id": "456677",
"Score": "0",
"body": "thanks for the input. Never knew about the for-else thingy"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T16:51:04.377",
"Id": "233549",
"ParentId": "233532",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-06T11:34:33.523",
"Id": "233532",
"Score": "1",
"Tags": [
"python",
"interview-questions"
],
"Title": "Insert a digit to maximize the given number"
}
|
233532
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.