body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>This is a component for a lexer which operates on a byte input stream that handles reading and decoding the contents of a string contained within double-quotes. The validity of the encoding is handled by <code>CharsetDecoder#decode()</code> which will throw an exception on an invalid buffer.</p>
<p>The <code>charset</code> argument defines the encoding of the string contents not the encoding of the quotation marks themselves (which is defined by the lexer). This allows the contents of the string to be defined as a character set other than the parent document. However, it must be a valid subset of Unicode such that its contents do not erroneously contain a byte value to match code point 34. Some form of <code>readHeredoc()</code> could provide an alternative for this specific use case.</p>
<pre><code>String readString(
Reader r,
Charset charset)
throws IOException
{
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
int cp;
while ((cp = r.read()) > 0) {
if (cp == '"')
break;
ostream.write(cp);
}
return charset.newDecoder().decode(ByteBuffer.wrap(ostream.toByteArray()))
.toString();
}
</code></pre>
<hr>
<p><em>Reaching the end the buffer before a matching quotation is not handled; I haven't decided on the defined behavior for this and its absence is known.</em></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-18T02:14:35.967",
"Id": "468925",
"Score": "1",
"body": "*Reaching the end the buffer before a matching quotation is not handled but will likely end up throwing an exception* - and that's desired? If so, feel free to [edit] to clarify; note that asking for help fixing code that doesn't work as intended is out-of-scope on this site."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-18T02:39:33.743",
"Id": "468929",
"Score": "2",
"body": "*It's not handled*, as in I haven't decided on the defined behavior and its absence is known. I made note of it as it would otherwise be something to point out in a code review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-18T02:43:33.553",
"Id": "468930",
"Score": "3",
"body": "Fair enough, and that is correct - just pointing out, since we *require* that the code you put up for review works as intended to the best of your knowledge, that some readers might mistake the statement for a request to help with debugging it, which would be off-topic here. Hence, and since one person already put in what appears to be an erroneous vote to close, my *suggestion* to edit to clarify. Feel free to ignore, as far as I can tell there's nothing wrong with your post, although more context wouldn't hurt (it never does)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T17:36:11.850",
"Id": "469107",
"Score": "2",
"body": "This question seems to lack context of the whole class, it would be better if we could see the code that calls it as well."
}
] | [
{
"body": "<p>the only advice, that I can give you, is to separate the logic in multiple methods. This will make your method shorter and allow the code to be reused.</p>\n\n<p>Personally, I see two other methods.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> String readString(Reader r, Charset charset) throws IOException {\n ByteArrayOutputStream ostream = copyInputToStream(r);\n\n final ByteBuffer byteBuffer = ByteBuffer.wrap(ostream.toByteArray());\n\n return decodeBufferAsString(charset, byteBuffer);\n }\n\n private String decodeBufferAsString(Charset charset, ByteBuffer byteBuffer) throws CharacterCodingException {\n return charset.newDecoder().decode(byteBuffer).toString();\n }\n\n private ByteArrayOutputStream copyInputToStream(Reader reader) throws IOException {\n ByteArrayOutputStream ostream = new ByteArrayOutputStream();\n\n int cp;\n\n while ((cp = reader.read()) > 0) {\n\n if (cp == '\"') {\n break;\n }\n\n ostream.write(cp);\n }\n\n return ostream;\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-18T11:37:30.253",
"Id": "239096",
"ParentId": "239084",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-18T01:49:22.620",
"Id": "239084",
"Score": "2",
"Tags": [
"java",
"strings",
"parsing",
"stream"
],
"Title": "Reading bytes between two quotes from a stream and decoding it to its appropriate character set"
} | 239084 |
<p>I have some side projects by using a private module I have. My main goals are to match the list if they started with the pre-defined prefix, then put them into a list. From that filtered list, I extract two elements each time and modify their label name. I am trying to clean up my code to make it more concise and user-friendly, also to make sure asking some questions before actually modify the file label. Ideally, I want to have a way to list down the file's label that is going to edit before actually editing them, if that is possible.</p>
<pre><code>for k, v in sessList.items():
# get the acquisitions in one session
acqList = module.get_session_acqs(session_id = k, sort = {'timestamp': 'asc'} )
conversion(acqList)
</code></pre>
<pre><code>import itertools
import numpy as np
from pytz import utc
from datetime import *
from dateutil import *
from datetime import timedelta
from itertools import *
from math import *
def conversion(acqList):
prefix = ['MCS','FT', 'FS', 'GNo', 'Rs', 'WHw', 'Cy']
newList = []
#to check if there is any of the items contains the prefix
for e in acqList:
for pf in prefix:
if(e.label.startswith(pf)):
newList.append(e)
data = np.arange(len(newList))
def pairwise(iterable):
return zip(*[iter(iterable)]*2)
for v, w in pairwise(data):
labelA = newList[v].label
labelB = newList[w].label
#checking when the labelA or labelB has MCS then change the name
if 'MCS' in labelA:
newLabel = labelB + '_mc'
acqID = newList[v].id
#here is when the modify happens from my module
module.modify_acq(acquisition_id = acqID, label = newLabel )
elif 'MCS' in labelB:
newLabel = labelA + '_mc'
acqID = newList[w].id
#here is when the modify happens from my module
module.modify_acq(acquisition_id = acqID, label = newLabel )
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-18T09:41:15.620",
"Id": "468953",
"Score": "1",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-18T14:03:37.390",
"Id": "468972",
"Score": "0",
"body": "@TobySpeight thanks for pointing it out. I will try to edit my title."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T16:39:09.590",
"Id": "469100",
"Score": "0",
"body": "_Ideally, I want to have a way to list down the file's label_ - If your code does not do this now, CR is not the place to help you; you're better off with Stack Overflow. Code Review can only help you with current, implemented, working code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T16:39:49.203",
"Id": "469101",
"Score": "0",
"body": "Your code, as it stands, will not run; the indentation on your comments is incorrect."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T00:55:13.267",
"Id": "469148",
"Score": "0",
"body": "@Reinderien, do you mind explaining more on *the indentation on your comments is incorrect* this? It does run, but I would like to know if I can write my code in a more user-friendly way and easy to be understood by others."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T15:40:26.027",
"Id": "469264",
"Score": "0",
"body": "Literally copy-and-paste this code. It will not run. The comment level of indentation must be the same as the level of indentation of the previous line."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T00:16:24.533",
"Id": "469312",
"Score": "1",
"body": "Bizarre. I'm downgrading from 'it's not syntactically valid' - because, bizarrely, it is - to \"no one should ever do that\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T20:24:36.533",
"Id": "469367",
"Score": "0",
"body": "Well it is because there is a package that needed to be installed and I did not share that in this post."
}
] | [
{
"body": "<h2>Indentation</h2>\n\n<p>This:</p>\n\n<pre><code>def conversion(acqList):\n\n\n prefix = ['MCS','FT', 'FS', 'GNo', 'Rs', 'WHw', 'Cy']\n newList = []\n\n#to check if there is any of the items contains the prefix\n for e in acqList:\n</code></pre>\n\n<p>is (as a surprise to me) valid syntax, but that doesn't mean it's a good idea. The beginning of a comment, when that comment is the only thing on the line, should match the level of indentation of the block it's in. To do otherwise is pretty confusing.</p>\n\n<p>You also seem to be using two-space indentation, when the standard is four.</p>\n\n<h2>If-parens</h2>\n\n<p>This:</p>\n\n<pre><code> if(e.label.startswith(pf)):\n</code></pre>\n\n<p>should become</p>\n\n<pre><code>if e.label.startswith(pf):\n</code></pre>\n\n<h2>Nested functions</h2>\n\n<p>There are sometimes good reasons for nested functions, but so far as I can see, this:</p>\n\n<pre><code> def pairwise(iterable):\n return zip(*[iter(iterable)]*2)\n</code></pre>\n\n<p>doesn't have any of them. You're better off moving this function to global scope.</p>\n\n<h2>PEP8 spacing</h2>\n\n<p>By the PEP8 formatting standard, this:</p>\n\n<pre><code> module.modify_acq(acquisition_id = acqID, label = newLabel )\n</code></pre>\n\n<p>would become</p>\n\n<pre><code>module.modify_acq(acquisition_id=acq_id, label=new_label)\n</code></pre>\n\n<h2>Mutability</h2>\n\n<p>This:</p>\n\n<pre><code> prefix = ['MCS','FT', 'FS', 'GNo', 'Rs', 'WHw', 'Cy']\n</code></pre>\n\n<p>never changes, so it should be made an immutable tuple:</p>\n\n<pre><code> prefix = ('MCS','FT', 'FS', 'GNo', 'Rs', 'WHw', 'Cy')\n</code></pre>\n\n<h2>Namespace pollution</h2>\n\n<p>These:</p>\n\n<pre><code>from datetime import *\nfrom dateutil import *\nfrom datetime import timedelta\nfrom itertools import *\nfrom math import *\n</code></pre>\n\n<p>have a few problems. First, your <code>timedelta</code> import is redundant, because you already <code>import *</code>.</p>\n\n<p>Also, it's not a great idea to import everything from these modules. You're better off either</p>\n\n<ol>\n<li>importing specific symbols from these modules as necessary, or</li>\n<li>importing only the module itself (i.e. <code>import math</code>) and then using fully-qualified references.</li>\n</ol>\n\n<p>Either of those will significantly clean up your namespace.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T00:47:45.487",
"Id": "239255",
"ParentId": "239087",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-18T04:20:24.933",
"Id": "239087",
"Score": "3",
"Tags": [
"python",
"performance"
],
"Title": "Scripts to get label name from ACQ container and modify ACQ label name"
} | 239087 |
<p>I've created an integer index based union find implementation in C#, and am looking for some feedback. Unit tests have been written with NUnit. Some questions I am considering:</p>
<ol>
<li>Can the implementation be made more performant?</li>
<li>Can the (C#) language be used more elegantly?</li>
<li>Are there any general style guidelines being violated?</li>
<li>Could the design of the classes in the implementation or unit tests be done better?</li>
<li>Are there any bugs that have been missed?</li>
<li>Is there a better way to leverage the NUnit framework for clearer code?</li>
</ol>
<pre><code>using System;
namespace DataStructures
{
/// <summary>
/// An integer based implementation of the union find data structure
/// </summary>
/// <remarks>
/// It is expected that the integer indices stored internally in this <see cref="UnionFind"/> class are correlated to actual objects via a bijection of integer indices
/// to objects
/// </remarks>
public class UnionFind
{
private int[] elements;
private int[] componentSizes;
/// <summary>
/// The number of components that elements have been grouped into
/// </summary>
public int ComponentCount { get; private set; }
/// <summary>
/// Creates an instance of an integer based <see cref="UnionFind"/> data structure
/// </summary>
/// <param name="size">The number of elements to initialize the <see cref="UnionFind"/> instance with</param>
/// <exception cref="ArgumentOutOfRangeException">Thrown if the inputted <paramref name="size"/> is less than 0 or above <see cref="int.MaxValue"/></exception>
public UnionFind(int size)
{
if (size < 0 || size > int.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(size), Resource.SizeMustBeWithinValidRange);
}
this.elements = new int[size];
this.componentSizes = new int[size];
for (var i = 0; i < size; i++)
{
this.elements[i] = i;
this.componentSizes[i] = 1;
}
this.ComponentCount = size;
}
/// <summary>
/// Checks by index whether two elements are in the same group
/// </summary>
/// <param name="firstIndex">The index of the first element to check</param>
/// <param name="secondIndex">The index of the second element to check</param>
/// <returns>True if the elements are in the same group, otherwise false</returns>
public bool Connected(int firstIndex, int secondIndex)
{
return this.Find(firstIndex) == this.Find(secondIndex);
}
/// <summary>
/// Finds the index of the root parent to an element
/// </summary>
/// <param name="index">The index of the child element</param>
/// <returns>The index of the root parent element, or the inputted index if the element has no parents</returns>
/// <exception cref="ArgumentOutOfRangeException">Thrown if the inputted <paramref name="index"/> is less than 0 or above <see cref="int.MaxValue"/></exception>
/// <remarks>
/// This method has the side-effect of compressing the path from child to root parent such that all elements between, including the child, directly
/// point to the root parent after <see cref="Find(int)"/> has executed. As a result of path compression, <see cref="Find(int)"/> runs in amortized
/// constant time.
/// </remarks>
public int Find(int index)
{
if (index < 0 || index > this.elements.Length - 1)
{
throw new ArgumentOutOfRangeException(nameof(index), Resource.IndexMustBeWithinValidRange);
}
int nextIndex = index;
while (this.HasParent(nextIndex))
{
nextIndex = this.elements[nextIndex];
}
new PathCompressor(this.elements).Compress(index, nextIndex);
return nextIndex;
}
/// <summary>
/// Gets the size of the component an element belongs to
/// </summary>
/// <param name="index">The index of the element</param>
/// <returns>The size of the component the element belongs to</returns>
public int GetComponentSize(int index)
{
return this.componentSizes[this.Find(index)];
}
/// <summary>
/// Merges two elements' groups together
/// </summary>
/// <param name="firstIndex">The index of the first element to merge</param>
/// <param name="secondIndex">The index of the second element to merge</param>
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown if either the inputted <paramref name="firstIndex"/> or <paramref name="secondIndex"/> is less than 0 or above <see cref="int.MaxValue"/>
/// </exception>
public void Unify(int firstIndex, int secondIndex)
{
if (firstIndex < 0 || firstIndex > this.elements.Length - 1)
{
throw new ArgumentOutOfRangeException(nameof(firstIndex), Resource.IndexMustBeWithinValidRange);
}
if (secondIndex < 0 || secondIndex > this.elements.Length - 1)
{
throw new ArgumentOutOfRangeException(nameof(secondIndex), Resource.IndexMustBeWithinValidRange);
}
if (firstIndex == secondIndex)
{
return;
}
var firstParentIndex = this.Find(firstIndex);
var secondParentIndex = this.Find(secondIndex);
if (firstParentIndex == secondParentIndex)
{
return;
}
this.UpdateComponentState(firstParentIndex, secondParentIndex);
}
private void UpdateComponentState(int firstParentIndex, int secondParentIndex)
{
if (this.componentSizes[firstParentIndex] >= this.componentSizes[secondParentIndex])
{
this.elements[secondParentIndex] = firstParentIndex;
this.componentSizes[firstParentIndex] += this.componentSizes[secondParentIndex];
}
else
{
this.elements[firstParentIndex] = secondParentIndex;
this.componentSizes[secondParentIndex] += this.componentSizes[firstParentIndex];
}
this.ComponentCount--;
}
private bool HasParent(int nextIndex)
{
return this.elements[nextIndex] != nextIndex;
}
}
}
</code></pre>
<pre><code>namespace DataStructures
{
/// <summary>
/// A path compression strategy class for the <see cref="UnionFind"/> data structure.
/// </summary>
internal class PathCompressor
{
private readonly int[] elements;
/// <summary>
/// Creates an instance of a <see cref="PathCompressor"/>
/// </summary>
/// <param name="elements">An array of all elements that could undergo path compression</param>
public PathCompressor(int[] elements)
{
this.elements = elements;
}
/// <summary>
/// Compresses the path from a child element to its root parent element.
/// </summary>
/// <param name="fromIndex">The index of the child element from which path compression will start. Path compression includes the child element.</param>
/// <param name="toIndex">The index of the root parent element where path compression will end.</param>
public void Compress(int fromIndex, int toIndex)
{
var next = fromIndex;
while (this.elements[next] != toIndex)
{
var temp = this.elements[next];
this.elements[next] = toIndex;
next = temp;
}
}
}
}
</code></pre>
<p>Unit Tests:</p>
<pre><code>using DataStructures;
using NUnit.Framework;
using System.Collections.Generic;
namespace UnitTests
{
/// <summary>
/// Unit tests for the <see cref="UnionFind"/> class
/// </summary>
public class UnionFindTests
{
/// <summary>
/// Tests that <see cref="UnionFind.Connected(int, int)"/> successfully identifies elements which are in the same group
/// </summary>
/// <param name="parameters">An instance encapsulating the inputs and expected outputs from this test</param>
[TestCaseSource(nameof(UnionFindTests.ConnectedTestCaseSource))]
public void TestConnected(Parameters<IndexPair, bool> parameters)
{
var unionFind = new UnionFind(parameters.InitialSize);
foreach (var pair in parameters.PairsToMerge)
{
unionFind.Unify(pair.FirstIndex, pair.SecondIndex);
}
foreach (var inputOutput in parameters.InputOutput)
{
Assert.That(unionFind.Connected(inputOutput.Input.FirstIndex, inputOutput.Input.SecondIndex), Is.EqualTo(inputOutput.ExpectedOutput));
}
}
/// <summary>
/// Tests that <see cref="UnionFind.Find(int)"/> finds an elements root parent as expected
/// </summary>
/// <param name="initialSize">The size of the <see cref="UnionFind"/> to initialize</param>
/// <param name="indexToFind">The element index to input into the <see cref="UnionFind.Find(int)"/> method</param>
/// <param name="expectedRootIndex">The expected output index from <see cref="UnionFind.Find(int)"/></param>
[TestCase(1, 0, 0)]
[TestCase(2, 1, 1)]
[TestCase(4, 3, 3)]
[TestCase(10, 9, 9)]
public void TestFind(int initialSize, int indexToFind, int expectedRootIndex)
{
var unionFind = new UnionFind(initialSize);
Assert.That(unionFind.Find(indexToFind), Is.EqualTo(expectedRootIndex));
}
/// <summary>
/// Tests that <see cref="UnionFind.Unify(int, int)"/> merges elements/groups as expected
/// </summary>
/// <param name="parameters">An instance encapsulating the inputs and expected outputs from this test</param>
[TestCaseSource(nameof(UnionFindTests.UnifyTestCaseSource))]
public void TestUnify(Parameters<int, int> parameters)
{
var unionFind = new UnionFind(parameters.InitialSize);
foreach (var pair in parameters.PairsToMerge)
{
unionFind.Unify(pair.FirstIndex, pair.SecondIndex);
}
foreach (var inputOutput in parameters.InputOutput)
{
Assert.That(unionFind.Find(inputOutput.Input), Is.EqualTo(inputOutput.ExpectedOutput));
}
}
/// <summary>
/// Tests that the <see cref="UnionFind.GetComponentSize(int)"/> returns the queried component size as expected
/// </summary>
/// <param name="parameters"></param>
[TestCaseSource(nameof(UnionFindTests.GetComponentSizeTestCaseSource))]
public void TestGetComponentSize(Parameters<int, int> parameters)
{
var unionFind = new UnionFind(parameters.InitialSize);
foreach (var pair in parameters.PairsToMerge)
{
unionFind.Unify(pair.FirstIndex, pair.SecondIndex);
}
foreach (var inputOutput in parameters.InputOutput)
{
Assert.That(unionFind.GetComponentSize(inputOutput.Input), Is.EqualTo(inputOutput.ExpectedOutput));
}
}
private static IEnumerable<TestCaseData> ConnectedTestCaseSource()
{
yield return new TestCaseData(new Parameters<IndexPair, bool>
{
InitialSize = 4,
PairsToMerge = new[] { new IndexPair(1, 1), new IndexPair(2, 2), new IndexPair(3, 3) },
InputOutput = new[]
{
new InputOutput<IndexPair, bool>(new IndexPair(1, 2), false),
new InputOutput<IndexPair, bool>(new IndexPair(1, 3), false),
new InputOutput<IndexPair, bool>(new IndexPair(2, 3), false),
new InputOutput<IndexPair, bool>(new IndexPair(1, 1), true),
new InputOutput<IndexPair, bool>(new IndexPair(2, 2), true),
new InputOutput<IndexPair, bool>(new IndexPair(3, 3), true),
}
}).SetName("Unify each element to itself, then ensure no elements are in the same group");
yield return new TestCaseData(new Parameters<IndexPair, bool>
{
InitialSize = 11,
PairsToMerge = new[] { new IndexPair(1, 5), new IndexPair(6, 3), new IndexPair(3, 1), new IndexPair(7, 3) },
InputOutput = new[]
{
new InputOutput<IndexPair, bool>(new IndexPair(1, 2), false),
new InputOutput<IndexPair, bool>(new IndexPair(1, 3), true),
new InputOutput<IndexPair, bool>(new IndexPair(1, 4), false),
new InputOutput<IndexPair, bool>(new IndexPair(1, 5), true),
new InputOutput<IndexPair, bool>(new IndexPair(1, 6), true),
new InputOutput<IndexPair, bool>(new IndexPair(1, 7), true),
new InputOutput<IndexPair, bool>(new IndexPair(6, 7), true),
new InputOutput<IndexPair, bool>(new IndexPair(6, 10), false)
}
}).SetName("Unify some elements, then ensure only these elements are in the same group");
}
private static IEnumerable<TestCaseData> UnifyTestCaseSource()
{
yield return new TestCaseData(new Parameters<int, int>
{
InitialSize = 4,
PairsToMerge = new[] { new IndexPair(1, 1), new IndexPair(2, 2), new IndexPair(3, 3) },
InputOutput = new[] { new InputOutput<int, int>(1, 1), new InputOutput<int, int>(2, 2), new InputOutput<int, int>(3, 3) }
}).SetName("Unify each element to itself, then ensure each element points to itself");
yield return new TestCaseData(new Parameters<int, int>
{
InitialSize = 6,
PairsToMerge = new[] { new IndexPair(1, 2), new IndexPair(2, 3), new IndexPair(3, 4), new IndexPair(4, 5) },
InputOutput = new[]
{
new InputOutput<int, int>(1, 1),
new InputOutput<int, int>(2, 1),
new InputOutput<int, int>(3, 1),
new InputOutput<int, int>(4, 1),
new InputOutput<int, int>(5, 1)
}
}).SetName("Unify all elements into the same component, then ensure all elements have the same parent");
yield return new TestCaseData(new Parameters<int, int>
{
InitialSize = 101,
PairsToMerge = new[] { new IndexPair(5, 100), new IndexPair(3, 50), new IndexPair(2, 50), new IndexPair(50, 6), new IndexPair(100, 6) },
InputOutput = new[]
{
new InputOutput<int, int>(5, 3),
new InputOutput<int, int>(100, 3),
new InputOutput<int, int>(3, 3),
new InputOutput<int, int>(50, 3),
new InputOutput<int, int>(2, 3),
new InputOutput<int, int>(6, 3)
}
}).SetName("Unify two components together, then ensure all elements have the same parent");
yield return new TestCaseData(new Parameters<int, int>
{
InitialSize = 501,
PairsToMerge = new[] { new IndexPair(500, 400), new IndexPair(20, 60), new IndexPair(33, 67), new IndexPair(33, 6), new IndexPair(500, 20), new IndexPair(500, 6) },
InputOutput = new[]
{
new InputOutput<int, int>(500, 500),
new InputOutput<int, int>(400, 500),
new InputOutput<int, int>(20, 500),
new InputOutput<int, int>(60, 500),
new InputOutput<int, int>(33, 500),
new InputOutput<int, int>(6, 500)
}
}).SetName("Unify three components together, then ensure all elements have the same parent");
yield return new TestCaseData(new Parameters<int, int>
{
InitialSize = 11,
PairsToMerge = new[]
{
new IndexPair(10, 0),
new IndexPair(1, 9),
new IndexPair(2, 8),
new IndexPair(3, 7),
new IndexPair(4, 6),
new IndexPair(5, 10),
new IndexPair(5, 1),
new IndexPair(8, 5),
new IndexPair(3, 4)
},
InputOutput = new[]
{
new InputOutput<int, int>(0, 10),
new InputOutput<int, int>(1, 10),
new InputOutput<int, int>(2, 10),
new InputOutput<int, int>(3, 3),
new InputOutput<int, int>(4, 3),
new InputOutput<int, int>(5, 10),
new InputOutput<int, int>(6, 3),
new InputOutput<int, int>(7, 3),
new InputOutput<int, int>(8, 10),
new InputOutput<int, int>(9, 10),
new InputOutput<int, int>(10, 10)
}
}).SetName("Unify elements into two different compoents, then ensure that they each have the correct parent");
}
private static IEnumerable<TestCaseData> GetComponentSizeTestCaseSource()
{
yield return new TestCaseData(new Parameters<int, int>
{
InitialSize = 4,
PairsToMerge = new[] { new IndexPair(1, 1), new IndexPair(2, 2), new IndexPair(3, 3) },
InputOutput = new[] { new InputOutput<int, int>(1, 1), new InputOutput<int, int>(2, 1), new InputOutput<int, int>(3, 1) }
}).SetName("Get the component size of elements that have not yet been grouped");
yield return new TestCaseData(new Parameters<int, int>
{
InitialSize = 6,
PairsToMerge = new[] { new IndexPair(1, 2), new IndexPair(2, 3), new IndexPair(3, 4), new IndexPair(4, 5) },
InputOutput = new[]
{
new InputOutput<int, int>(1, 5),
new InputOutput<int, int>(2, 5),
new InputOutput<int, int>(3, 5),
new InputOutput<int, int>(4, 5),
new InputOutput<int, int>(5, 5)
}
}).SetName("Get the component size of elements that are all in the same component");
yield return new TestCaseData(new Parameters<int, int>
{
InitialSize = 11,
PairsToMerge = new[]
{
new IndexPair(10, 0),
new IndexPair(1, 9),
new IndexPair(2, 8),
new IndexPair(3, 7),
new IndexPair(4, 6),
new IndexPair(5, 10),
new IndexPair(5, 1),
new IndexPair(8, 5),
new IndexPair(3, 4)
},
InputOutput = new[]
{
new InputOutput<int, int>(0, 7),
new InputOutput<int, int>(1, 7),
new InputOutput<int, int>(2, 7),
new InputOutput<int, int>(3, 4),
new InputOutput<int, int>(4, 4),
new InputOutput<int, int>(5, 7),
new InputOutput<int, int>(6, 4),
new InputOutput<int, int>(7, 4),
new InputOutput<int, int>(8, 7),
new InputOutput<int, int>(9, 7),
new InputOutput<int, int>(10, 7)
}
}).SetName("Get the component size of elements that are in different components");
}
/// <summary>
/// Parameters for testing the <see cref="UnionFind"/> data structure
/// </summary>
public class Parameters<T, U>
{
/// <summary>
/// The initial size of the <see cref="UnionFind"/> instance under test
/// </summary>
public int InitialSize { get; set; }
/// <summary>
/// The index pairs to merge before the target method is tested
/// </summary>
public IndexPair[] PairsToMerge { get; set; }
public InputOutput<T,U>[] InputOutput { get; set; }
}
/// <summary>
/// A pair of indices that should be processed together, such as for merging
/// </summary>
public class IndexPair
{
/// <summary>
/// The index of the first element to process
/// </summary>
public int FirstIndex { get; }
/// <summary>
/// The index of the second element to process
/// </summary>
public int SecondIndex { get; }
/// <summary>
/// Creates an instance of an <see cref="IndexPair"/> for grouping pairs of indices together
/// </summary>
/// <param name="firstIndex">The index of the first element to process</param>
/// <param name="secondIndex">The index of the second element to process</param>
public IndexPair(int firstIndex, int secondIndex)
{
this.FirstIndex = firstIndex;
this.SecondIndex = secondIndex;
}
}
/// <summary>
/// Encapsulated input and expected output for the method under test
/// </summary>
/// <typeparam name="T">The type of <see cref="Input"/></typeparam>
/// <typeparam name="U">The type of <see cref="ExpectedOutput"/></typeparam>
public class InputOutput<T, U>
{
/// <summary>
/// The value to input into the method under test
/// </summary>
public T Input { get; }
/// <summary>
/// The expected output value of the method under test
/// </summary>
public U ExpectedOutput { get; }
/// <summary>
/// Creates an instance for encapsulating input into a method under test, and the expected output
/// </summary>
/// <param name="input">The value that will be inputted into the method under test</param>
/// <param name="expectedOutput">The expected output value from the method under test</param>
public InputOutput(T input, U expectedOutput)
{
this.Input = input;
this.ExpectedOutput = expectedOutput;
}
}
}
}
</code></pre>
<pre><code>using DataStructures;
using NUnit.Framework;
using System.Collections.Generic;
using System.Linq;
namespace UnitTests
{
/// <summary>
/// Unit tests for the <see cref="PathCompressor"/> class
/// </summary>
internal class PathCompressorTests
{
/// <summary>
/// Tests that the <see cref="PathCompressor.Compress(int, int)"/> method behaves as expected
/// </summary>
/// <param name="parameters">An instance encapsulating the inputs and expected outputs from this test</param>
[TestCaseSource(nameof(PathCompressorTestCaseSource))]
public void TestPathCompressor(CompressParameters parameters)
{
var elements = parameters.InitialIndices;
var compressor = new PathCompressor(elements);
compressor.Compress(parameters.StartIndex, parameters.RootIndex);
Assert.That(elements, Is.EqualTo(parameters.ExpectedIndices));
}
private static IEnumerable<TestCaseData> PathCompressorTestCaseSource()
{
yield return new TestCaseData(new CompressParameters
{
InitialIndices = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10 },
StartIndex = 0,
RootIndex = 10,
ExpectedIndices = Enumerable.Repeat(10, 11).ToArray()
}).SetName("Compress elements in series");
yield return new TestCaseData(new CompressParameters
{
InitialIndices = new[] { 1, 10, 3, 6, 5, 2, 8, 9, 7, 9, 4 },
StartIndex = 0,
RootIndex = 9,
ExpectedIndices = Enumerable.Repeat(9, 11).ToArray()
}).SetName("Compress elements in mixed array order");
}
/// <summary>
/// Parameters for testing the <see cref="PathCompressor.Compress(int, int)"/> method
/// </summary>
public class CompressParameters
{
/// <summary>
/// An array of element indices to initialize the <see cref="PathCompressor"/> instance under test with
/// </summary>
public int[] InitialIndices { get; set; }
/// <summary>
/// The index of the child element where path compression will begin
/// </summary>
public int StartIndex { get; set; }
/// <summary>
/// The index of the root parent element where path compression will end
/// </summary>
public int RootIndex { get; set; }
/// <summary>
/// The expected element indices after path compression
/// </summary>
public int[] ExpectedIndices { get; set; }
}
}
}
<span class="math-container">```</span>
</code></pre>
| [] | [
{
"body": "<h1>Using two arrays of <code>int</code></h1>\n<p>That's nice. There is a tendency to use <code>Node</code> objects that refer to each other by address, which still requires an array to initially find a node by index anyway, and then the nodes become a pointless extra step. Trap avoided.</p>\n<h1>PathCompressor</h1>\n<p>This class is a bit dubious, it works by "stealing" (temporarily, so maybe "borrowing") the private data of the main data structure and modifying it (resulting in a kind of action-at-a-distance type of modification). Strangely, it holds state at all, its main job is encapsulating the path compression function as an object. It could have been a private method of <code>UnionFind</code> as well, or even just inlined directly into its call-site. There are no other places where it would be used .. well, except in the tests.</p>\n<p>Describing it as a path compression <em>strategy</em> class suggests that it's part of a strategy pattern, where different strategies might be supplied, but there is no facility to supply them. The other major strategies, path splitting, and path halving are specifically meant to be performed <em>during</em> the initial pass - their point is sacrificing some amount of path-shortening to avoid a second pass. If they were implemented as a drop-in replacement strategy, the way it is now, their point would be missed.</p>\n<p>So in total, in my opinion, there should not be a <code>PathCompressor</code> class.</p>\n<h1>Naming of <code>elements</code></h1>\n<p><code>elements</code> is very generic. That's no big deal, but you could emphasize their nature more, for example, <code>parents</code> or <code>links</code>.</p>\n<h1>Performance?</h1>\n<p>You could try path splitting/halving, they were invented to be faster in practice than full path compression. I've never benchmarked them though.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T20:57:10.597",
"Id": "469369",
"Score": "0",
"body": "Thanks for the awesome feedback! Did not know about path splitting or halving. \n\nBased on your comments, if a set of strategy classes were to be implemented, it seems it would be better to implement them as Find strategy classes instead of Path Compression/Splitting/Halving strategy classes. For example, classes could be something like FindWithPathCompression, FindWithPathSplitting, FindWithPathHalving. These could then be injected into the UnionFind via constructor or property. \n\nAnyone have a better design pattern for doing this?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-18T06:04:05.210",
"Id": "239090",
"ParentId": "239088",
"Score": "3"
}
},
{
"body": "<p>As for the primary code I think it's very well written, with good documentation, naming and general structure.</p>\n\n<p>Some minor comments:</p>\n\n<p>Avoid the use of <code>this.</code>-prefix - it is rather un-C#-ish, unless it's absolutely necessary:</p>\n\n<blockquote>\n<pre><code>public PathCompressor(int[] elements)\n{\n this.elements = elements;\n}\n</code></pre>\n</blockquote>\n\n<hr>\n\n<blockquote>\n <p><code>if (size < 0 || size > int.MaxValue)</code></p>\n</blockquote>\n\n<p>An <code>int</code> can never be larger than <code>int.MaxValue</code> - if so <code>int.MaxValue</code> wouldn't be <code>int.MaxValue</code>.</p>\n\n<hr>\n\n<blockquote>\n <p><code>if (index < 0 || index > elements.Length - 1)</code></p>\n</blockquote>\n\n<p>I would prefer <code>index >= elements.Length</code> for the second condition.</p>\n\n<hr>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-18T14:00:36.653",
"Id": "239102",
"ParentId": "239088",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "239090",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-18T04:33:33.490",
"Id": "239088",
"Score": "3",
"Tags": [
"c#",
"unit-testing",
"nunit",
"union-find"
],
"Title": "Integer index based Union Find with path compression strategy"
} | 239088 |
<p>This function takes two lists of same length and a target number: the number which is to be summed. The function then returns a list of pairs whose sum is closest to the target number than any other pairs. It also finds the pair whose sum is equal to the target number.</p>
<pre class="lang-py prettyprint-override"><code>def pair_finder(list1, list2, t):
list1.sort()
list2.sort()
list1.reverse()
t_low = list1[-1] + list2[0]
t_high = list1[0] + list2[-1]
pairs_low = []
pairs_high = []
pairs_equal = []
for i in list1:
k = 0
for j in list2:
if i + j < t:
if i + j > t_low:
pairs_low.clear()
t_low = i + j
pairs_low.append([i, j])
elif (i + j == t_low):
pairs_low.append([i, j])
if i + j > t:
if i + j < t_high:
pairs_high.clear()
t_high = i + j
pairs_high.append([i, j])
list2 = list2[k:]
break
elif i + j == t_high:
pairs_high.append([i, j])
if i + j == t:
pairs_equal.append([i, j])
k += 1
pairs = []
for q in pairs_low:
pairs.append(q)
for w in pairs_high:
pairs.append(w)
for r in pairs_equal:
pairs.append(r)
return pairs
while True:
try:
l1 = []
l2 = []
li = input("enter the first sequence of numbers by giving exactly one space between numbers:")
for i in li.split(" "):
l1.append(int(i))
lj = input("enter the second sequence of numbers by giving exactly one space between numbers:")
for j in lj.split(" "):
l2.append(int(j))
if len(l1) == len(l2):
target = int(input("enter the target number: "))
break
else:
print("the length of both sequences should be same!")
l1 = []
l2 = []
except ValueError:
print("only integer type values are allowed!")
for pair in pair_finder(l1, l2, target):
print(pair)
</code></pre>
<p>Example:<br>
Let list 1 be <code>2 98 63 41 25 27 -51 48 18 54 31 28 55 11</code> <br> and list 2 be <code>21 56 87 65 21 12 75 41 33 91 32 15 8 -35</code> <br>and target number be 43 hence the <br>pairs <code>(15, 27),(33, 11),(41, 2),(32, 11),(15, 28),(12, 31)</code></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-18T10:28:24.430",
"Id": "468956",
"Score": "0",
"body": "Your code is broken (regarding the correct indentation), also you missed to provide a description what it is purposed to do. Your question is _off-topic_ here, fix these things first before asking for a review please."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-18T10:42:10.557",
"Id": "468958",
"Score": "1",
"body": "@πάνταῥεῖ The code is a C&P error, and can be fixed by anyone - including you. The title includes the description, what more explanation do you need to understand this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-18T10:49:24.750",
"Id": "468960",
"Score": "2",
"body": "Yeah you've broke the code again, after I fixed it..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-18T10:52:37.993",
"Id": "468961",
"Score": "1",
"body": "@Peilonrayz Isn't it the duty of the author to post working code here?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-18T10:55:49.283",
"Id": "468962",
"Score": "0",
"body": "@πάνταῥεῖ The reason the code is not working is because SE has a non-standard method of displaying code blocks. Causing 'code problems' for people that are new to the system. Please perform a quick browse of meta and you'll see more information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-18T12:02:56.310",
"Id": "468965",
"Score": "0",
"body": "@Peilonrayz I think I've manually rolled-back the code to your version."
}
] | [
{
"body": "<h1>Human Computer Interaction</h1>\n\n<h2>Prompts</h2>\n\n<pre><code> li = input(\"enter the first sequence of numbers by giving exactly one space between numbers:\")\n lj = input(\"enter the second sequence of numbers by giving exactly one space between numbers:\")\n</code></pre>\n\n<p>These are awfully long prompts for the user to enter in a list of values after. Maybe instructions, and then two short input prompts?</p>\n\n<pre><code> print(\"Enter two space separated integer number sequences, of the same length.\")\n li = input(\"First sequence: \")\n lj = input(\"Second sequence: \")\n</code></pre>\n\n<h2>White-space separators</h2>\n\n<p><code>li.split(\" \")</code> will separate a string into a number of items separated by exactly one space. If the user wants to enter a single digit number on one line, and a two digit number on the next, and keep the columns of numbers lined up, they can't use extra spaces.</p>\n\n<p><code>.split()</code>, with no arguments, will split a string into a number of items separated by one or more white-space characters.</p>\n\n<pre><code>>>> \" 2 3 \\t \\n 4 \\r 5 \".split()\n['2', '3', '4', '5']\n</code></pre>\n\n<p>No hard requirements to use exactly one space. And leading and trailing spaces are trimmed, too!</p>\n\n<h1>Unexpected Behaviour</h1>\n\n<pre><code>def pair_finder(list1, list2, t):\n list1.sort()\n list2.sort()\n ...\n</code></pre>\n\n<p>After calling <code>pair_finder(l1, l2, target)</code>, you'll find that <code>l1</code> and <code>l2</code> have been sorted! The caller probably did not expect that.</p>\n\n<p>Use:</p>\n\n<pre><code>def pair_finder(list1, list2, t):\n list1 = sorted(list1)\n list2 = sorted(list2)\n ...\n</code></pre>\n\n<p>The <code>sorted(...)</code> function doesn't modify the input list, and it returns a new list. By assigning those to the original variables, <code>list1</code> & <code>list2</code> will be sorted, but the caller's <code>l1</code> & <code>l2</code> lists won't be touched.</p>\n\n<h1>Pythonic Constructs</h1>\n\n<h2>Loop like a native</h2>\n\n<h3>List comprehension</h3>\n\n<pre><code>l1 = []\nfor i in li.split(\" \"):\n l1.append(int(i))\n</code></pre>\n\n<p>This is an inefficient construct. You are creating a list, and then expanding the list one item at a time.</p>\n\n<p>You could create the list all at once, using list comprehension:</p>\n\n<pre><code>l1 = [int(i) for i in li.split(\" \")]\n</code></pre>\n\n<p>And applying the same operation to every item in a sequence is called a mapping operation, and Python has a built-in <code>map(func, sequence)</code> function:</p>\n\n<pre><code>l1 = list(map(int, li.split(\" \")))\n</code></pre>\n\n<p>Or, combining with the input and using the better space handling:</p>\n\n<pre><code>print(\"Enter two space separated integer number sequences, of the same length.\")\nl1 = list(map(int, input(\"First sequence: \").split()))\nl2 = list(map(int, input(\"Second sequence: \").split()))\n</code></pre>\n\n<h3>Enumerate</h3>\n\n<pre><code> k = 0\n for j in list2:\n ...\n k += 1\n</code></pre>\n\n<p>This should be replaced with:</p>\n\n<pre><code> for k, j in enumerate(list2):\n ...\n</code></pre>\n\n<p>to allow Python to maintain the <code>k</code> index while walking through the <code>list2</code> items.</p>\n\n<h2>Extending Lists</h2>\n\n<p>Adding a list to another list is a <code>list.extend(...)</code> operation:</p>\n\n<pre><code>pairs = []\nfor q in pairs_low:\n pairs.append(q)\nfor w in pairs_high:\n pairs.append(w)\nfor r in pairs_equal:\n pairs.append(r)\n</code></pre>\n\n<p>Could become simply:</p>\n\n<pre><code>pairs = []\npairs.extend(pairs_low)\npairs.extend(pairs_high)\npairs.extend(pairs_equal)\n</code></pre>\n\n<h2>if ... elif</h2>\n\n<pre><code> if i + j < t:\n ...\n if i + j > t:\n ...\n if i + j == t:\n ...\n</code></pre>\n\n<p>If the sum is less than <code>t</code>, it won't be greater than <code>t</code>, or equal to <code>t</code>. And if it is greater than <code>t</code>, it won't be equal to <code>t</code>. And if it is not less than or greater than <code>t</code>, it can only be equal to <code>t</code>. Why do the extra comparisons?</p>\n\n<pre><code> if i + j < t:\n ...\n elif i + j > t:\n ...\n else:\n ...\n</code></pre>\n\n<h2>PEP-8</h2>\n\n<h3>Unnecessary parenthesis:</h3>\n\n<pre><code> elif (i + j == t_low):\n</code></pre>\n\n<h3>Variable names too short to be meaningful</h3>\n\n<p><code>li</code>, <code>lj</code>, <code>l1</code>, <code>l1</code>, <code>q</code>, <code>w</code>, <code>r</code>, <code>t</code></p>\n\n<h3>Main guard</h3>\n\n<p>Mainline code should be protected with</p>\n\n<pre><code>if __name__ == '__main__':\n ...\n</code></pre>\n\n<p>to allow the file to be imported into another file, for unit tests, etc.</p>\n\n<h1>Algorithmic Improvements</h1>\n\n<p><code>pair_finder()</code> starts off by sorting both input lists. That is an <span class=\"math-container\">\\$O(N \\log N)\\$</span> operation. Then it reverses one of the lists, which is an <span class=\"math-container\">\\$O(N)\\$</span> operation. And then ...</p>\n\n<pre><code>for i in list1:\n ...\n for j in list2:\n ...\n</code></pre>\n\n<p>... which is <span class=\"math-container\">\\$O(N^2)\\$</span>! Right now, this is the time consuming part of the algorithm. But what are we doing? We are looking for two numbers which sum to <code>target</code>. Let’s turn that around:</p>\n\n<pre><code>for i in list1:\n desired = target - i\n # find “desired” in list2\n</code></pre>\n\n<p>Well, <code>list2</code> is sorted, so we can do a binary search to find the <code>desired</code> value.</p>\n\n<pre><code>for i in list1:\n desired = target - i\n pos = bisect.bisect_left(list2, desired)\n ...\n</code></pre>\n\n<p>The binary search is <span class=\"math-container\">\\$O(\\log N)\\$</span>, so with the outer loop, the time complexity has dropped to <span class=\"math-container\">\\$O(N \\log N)\\$</span>, the same as the sorting.</p>\n\n<p>The <code>desired</code> value may or may not be in <code>list2</code>. If it is, it is at <code>list2[pos]</code>. Assuming we don’t fall off the start of <code>list2</code>, then for the current <code>i</code> value, <code>i+list2[pos-1]</code> would be the largest sum less than <code>target</code>.</p>\n\n<p>Assuming we don’t fall off the end of <code>list2</code>, if <code>list2[pos] == desired</code>, then the sum <code>i+list2[pos+1]</code> will be the smallest sum greater than <code>target</code> for the current value of <code>i</code>.</p>\n\n<pre><code>for i in list1:\n desired = target - i\n pos = bisect.bisect_left(list2, desired)\n if pos < len(list2):\n if list2[pos] == desired:\n # add (i, desired) to pairs_equal\n low, high = pos - 1, pos + 1\n else:\n low, high = pos - 1, pos\n if low >= 0:\n # add (i, list2[low]) to pairs_low, if >= t_low\n if high < len(list2):\n # add (i, list2[high]) to pairs_high, if <= t_high\n</code></pre>\n\n<p>But ... what about duplicates? If <code>list2</code> contains duplicate values, <code>pos + 1</code> may not be sufficient to advanced to a value larger than <code>desired</code>. You could use both <code>bisect_left</code> and <code>bisect_right</code> to find either end of a sequence of multiple <code>desired</code> values. The difference in <code>right</code> and <code>left</code> would be the count of those values, and you could add <code>[(i, desired)] * count</code> to <code>pairs_equal</code>. But you’d also need to do the same for the <code>pairs_low</code> and <code>pairs_high</code>, which means more binary searching to find those ends. Or, you could use two <code>collections.Counter</code> objects to count occurrences of each value in <code>list1</code> and <code>list2</code>, and then remove duplicates values from <code>list1</code> and <code>list2</code>. Any pairs added would need to be replicated by the product of the respective counts to occur the correct number of times in the result.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T08:32:37.837",
"Id": "469039",
"Score": "0",
"body": "Excellent review. I would stick to the list comprehensions, instead of using `map` for clarity,"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-18T23:05:31.963",
"Id": "239124",
"ParentId": "239095",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-18T10:25:51.597",
"Id": "239095",
"Score": "2",
"Tags": [
"python",
"complexity"
],
"Title": "Finding the closest pair of numbers which add to a target number"
} | 239095 |
<p>After sticking with the same handful of languages for years, I decided to learn C.</p>
<p>I've written a guess the number game, where it generates a random number based on the difficulty level, and then you have 5 attempts of guessing the number. </p>
<p>If you guess incorrect, it will give you a clue by telling you if the answer is higher or lower than your last guess. I find the game to be pretty interactive, and wanted to get a code review to see how I could improve on it.</p>
<p>This is my first ever C program and I'm just looking to improve.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int generate_random_number(int min, int max) {
srand ( time(NULL) );
return min + (rand() % (max - min));
}
void play() {
int difficulty = 1; // 1 = easy, 2 = medium, 3 = hard, 4 = insane
printf("1 = EASY, 2 = MEDIUM, 3 = HARD, & 4 = INSANE\n");
printf("What level would you like to play: ");
scanf("%i", &difficulty);
int min = 0;
int max = 0;
int random = 0;
if (difficulty == 1) {
min = 0;
max = 25;
printf("You have selected to play easy\n\n");
}
else if (difficulty == 2) {
min = 0;
max = 50;
printf("You have selected to play medium\n\n");
}
else if (difficulty == 3) {
min = 0;
max = 75;
printf("You have selected to play hard\n\n");
}
else if (difficulty == 4) {
min = 0;
max = 100;
printf("You have selected to play insane\n\n");
}
random = generate_random_number(min, max);
int tries = 5;
int won = 0;
while (tries > 0)
{
int guess = 1000000; // just so it doesn't accidentally equal to random
printf("Guess a number %i to %i: ", min, max);
scanf("%i", &guess);
if (guess == random) {
won = 1;
break;
}
else {
if (guess > random) {
printf("Incorrect guess, the answer is lower than your guess!\n\n");
}
else {
printf("Incorrect guess, the answer is higher than your guess!\n\n");
}
}
tries -= 1;
}
if (won) {
printf("Congratulations, you have won the game!");
}
else {
printf("Sorry, you are out of tries.\n\n");
}
}
int main() {
while (1) {
play();
}
return 0;
}
</code></pre>
| [] | [
{
"body": "<p>Good:</p>\n\n<p>no warnings with <code>-Wall -Wextra -pedantic</code> with both gcc and clang, no\nmemory leaks found with valgrind.</p>\n\n<p>Bad:</p>\n\n<p>use prototypes instead of declarations to give compiler a chance\nto issue warnings when an incorrect number of parameters is passed or incorrect types are passed:</p>\n\n<pre><code>void play(void)\nint main(void)\n</code></pre>\n\n<p>You don't check if user passes correct acceptable difficulty level:</p>\n\n<pre><code>$ ./main\n1 = EASY, 2 = MEDIUM, 3 = HARD, & 4 = INSANE\nWhat level would you like to play: 6\nFloating point exception\n$ ./main\n1 = EASY, 2 = MEDIUM, 3 = HARD, & 4 = INSANE\nWhat level would you like to play: 0\nFloating point exception\n</code></pre>\n\n<p>You don't check if user passes an integer in the first place:</p>\n\n<pre><code>$ ./main\n1 = EASY, 2 = MEDIUM, 3 = HARD, & 4 = INSANE\nWhat level would you like to play: a\n</code></pre>\n\n<p>will make your program go into an endless loop.</p>\n\n<p>Suggested:</p>\n\n<p>convert <code>int difficulty = 1</code> into an en enum with additional <code>DIFFICULTY_MAX</code> and <code>DIFFICULTY_MIN</code> values, and check if value passed from the user is lower than <code>DIFFICULTY_MAX</code> and larger or equal to <code>DIFFICULTY_MIN</code>.</p>\n\n<p>Use <code>EXIT_SUCCESS</code> to denote success at the end of <code>main()</code>:</p>\n\n<pre><code>return EXIT_SUCCESS;\n</code></pre>\n\n<p>or just omit the return from <code>main()</code> - compiler will automatically return a success value if we run off the end. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T14:03:44.793",
"Id": "469174",
"Score": "0",
"body": "Thank you, I have marked this the correct answer as it was the one which helped me most."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-18T15:53:28.197",
"Id": "239105",
"ParentId": "239103",
"Score": "5"
}
},
{
"body": "<blockquote>\n<pre><code>if (difficulty == 1) {\nelse if (difficulty == 2) {\nelse if (difficulty == 3) {\n</code></pre>\n</blockquote>\n\n<p>This looks like <code>switch (difficulty)</code> might be more appropriate - perhaps with a <code>default</code> branch to catch out-of-range values.</p>\n\n<p>Or, more simply, since we're just picking values, and <code>min</code> is always 0, just select from an array values (after verifying that the user's choice is in range):</p>\n\n<pre><code>int max[] = { 25, 50, 75, 100 };\n</code></pre>\n\n<p>In fact, with these values, we could simply multiply:</p>\n\n<pre><code>int max = 25 * difficulty;\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>scanf(\"%i\", &difficulty);\n</code></pre>\n</blockquote>\n\n<p>Don't just discard the result from <code>scanf()</code> - always test that it converted as many values as you wanted. In this case,</p>\n\n<pre><code>if (scanf(\"%i\", &difficulty) != 1) {\n fputs(\"Enter a number!\\n\", stderr);\n exit(EXIT_FAILURE); /* or some better handling */\n}\n</code></pre>\n\n<p>Similarly here:</p>\n\n<blockquote>\n<pre><code> scanf(\"%i\", &guess);\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>Finally, it would be polite to allow users to exit the game when they get bored of it (I know, I can't quite believe that might happen, either!).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T00:55:55.967",
"Id": "469016",
"Score": "2",
"body": "Rather than a case statement, I'd have an array of structures with min, max and description then index to that (having first validated the choice)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T10:25:20.433",
"Id": "469049",
"Score": "0",
"body": "Yes, that makes more sense"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-18T16:04:44.527",
"Id": "239106",
"ParentId": "239103",
"Score": "3"
}
},
{
"body": "<blockquote>\n <pre class=\"lang-c prettyprint-override\"><code>int generate_random_number(int min, int max) {\n srand ( time(NULL) );\n return min + (rand() % (max - min));\n}\n</code></pre>\n</blockquote>\n\n<p>You should only seed the random number generator once, at the start of <code>main</code>. In this case, if (for some reason) somebody played more than one round in a single second, both games would have the same number. Probably not a huge issue for this particular program, but something to be aware of.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T12:40:39.673",
"Id": "469071",
"Score": "0",
"body": "*\"(for some reason)\"* could be an automated test, for example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T18:58:48.100",
"Id": "469112",
"Score": "0",
"body": "@TobySpeight Not with `time(NULL)` as a seed - presumably that would change between one test and the next. If you wanted to do automated tests, you'd pick some constant as the seed and leave this line in here. But most likely N. Shead is correct that you would only want to do this once."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T14:03:14.143",
"Id": "469173",
"Score": "0",
"body": "Thanks for the response, when seeding random is the call to srand expensive, is this why I should only call it once?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-11-04T16:04:27.720",
"Id": "495394",
"Score": "0",
"body": "@Ash - it's not that it's expensive, but because reseeding from time at (possibly) predictable intervals may perturb the randomness of the distribution. That's a minor concern in a game or simulation, but becomes very important when you're creating random secrets for cryptography."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T01:27:15.910",
"Id": "239127",
"ParentId": "239103",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "239105",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-18T15:28:08.157",
"Id": "239103",
"Score": "6",
"Tags": [
"c",
"number-guessing-game"
],
"Title": "Simple text based game in C"
} | 239103 |
<h1>Introduction</h1>
<p>At this moment in time, I'm in the process of creating some fluent interface, as a result, I've created a DSL <em>style</em> solution for authentication & authorisation. </p>
<p>As a result, the consuming code-base may look something along the lines of this: </p>
<pre><code>public class Demo {
public String login() throws IllegalStateException {
JWTState jwt = beginAuth()
.authentication()
.username("JoeBloggs")
.password("Secure_Pa$$w0rD!-#0962")
.authenticate()
.whenAuthenticationFails(e -> log.error("Authentication failure", e))
.then()
.authorisation()
.adGroup("Basic")
.authorise()
.whenAuthorisationFails(e -> log.error("Authorisation failure", e))
.then()
.jwt()
.generateJwt()
.whenJwtFails(e -> log.error("Unable to generate JWT", e))
.getJwt();
// Safety net, rather than return null or an empty string, throw this exception
return Optional.of(jwt.isValid())
.filter(Boolean::valueOf)
.map(x -> jwt.token())
.orElseThrow(() -> new IllegalStateException("Unable to generate JWT"));
}
}
</code></pre>
<hr>
<h1>Defensive Example</h1>
<p>Since I've gone with a defensive approach, the consuming code-base does not need to worry about exceptions that are thrown, since they're handled internally. Although, these exceptions can be visible to the consuming code upon request, as you can see with the <code>'whenXFails'</code> methods. Internally, there's a lot of logic going on, an example being one of the guard clauses, an example being this snippet from the password guard clause:</p>
<pre><code>// Start of class....
@Override
public void validate(String password) throws IllegalArgumentException {
argument(password).
regex(VALID_PASSWORD_REGEX).
message("Supplied password is null").whenNull().
message("Supplied password is empty").whenEmpty().
message("Supplied password is too short").whenLessThan(MINIMUM_PASSWORD_LENGTH).
message("Supplied password is too long").whenGreaterThan(MAXIMUM_PASSWORD_LENGTH).
message("Supplied password does not match the valid password regex").whenNoRegexMatch();
}
// End of class....
</code></pre>
<p>To ensure that there's a good ability to log errors & debug this code-base, I've tried to handle nearly every scenario I can think of, expected & unexpected. In which case, you can see above that there are many specific cases where the password validation will fail, but from the consumer's perspective this isn't necessarily visible.</p>
<p>In the event that the consuming code-base wishes to proceed through this unit of work, it will merely alter the current state. Referring back to the <code>Demo</code> class, in the event of some failure, the <code>getJwt()</code> method will return some <code>JWTState</code> such as <code>InvalidJWTState</code>, this is to ensure that something is always returned to the consumer, meaning that the consumer need not check for null values. I've also taken the time to apply the null object design pattern to improve the defensiveness of this code. </p>
<hr>
<h1>Conclusion</h1>
<p>Before I ramble on & on, I'd just like to cut to the chase, first off, in this instance, am I applying good practices? If not can anyone make any recommendations on how I could improve the overall quality of this code-base? Secondly, are there better methods that I'm merely not aware of?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T17:02:14.260",
"Id": "469103",
"Score": "2",
"body": "This statement `As a result, the consuming code-base may look something along the lines of this: ` indicates that the code is not concrete from a working project. That makes this question off-topic for code review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T07:43:06.430",
"Id": "469153",
"Score": "0",
"body": "@pacmaninbw This code is in a prototype phase, I just wanted to get an idea of what other developers thought about the approach, etc. It will however be used in **several** working projects as a part of a very large & on-going migration project."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T08:58:46.890",
"Id": "469157",
"Score": "0",
"body": "Well, I understand your sentiment, but Code Review is for specific code from a specific project. So it sounds like you're simply at the wrong place until you have one of those projects close-to-finished (to the point where you can say whether that piece of the code works or not)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T09:00:22.943",
"Id": "469158",
"Score": "0",
"body": "this is no valid piece of code to review, just some snippets and ideas - it's not possible to review this question (-1)"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-18T15:37:37.970",
"Id": "239104",
"Score": "1",
"Tags": [
"java",
"fluent-interface"
],
"Title": "Defensive Fluent Interface Implementation"
} | 239104 |
<p>I have the following classes. I wonder if this structure makes sense in any terms especially the usage of the <code>UserDetails</code> class from Spring. Should I use <code>loadbyusername</code> method to create and remove methods in account service or is it okay? Then where should we use <code>loadbyusername</code> method?</p>
<p>Base class to cover fundamental properties like <code>id</code>, <code>createdAt</code>, etc.</p>
<pre><code>@Accessors(chain = true)
@Data
@MappedSuperclass
public class Base {
@Id
private String id = UUID.randomUUID().toString();
@CreatedDate
private Date createdAt;
@LastModifiedDate
private Date updatedAt;
}
</code></pre>
<p>Account class</p>
<pre><code>@Entity
@JsonIgnoreProperties(value = {"createdAt", "updatedAt"})
@Data
public class Account extends Base {
@NotNull
private String username;
@NotNull
private String password;
@NotNull
@Email
private String email;
@NotNull
private Role role;
}
</code></pre>
<p>Account details class implementing userdetails</p>
<pre><code>public class AccountDetails implements UserDetails {
private Account account;
public AccountDetails(Account account) {
this.account = account;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}
@Override
public String getPassword() {
return account.getPassword();
}
@Override
public String getUsername() {
return account.getUsername();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
</code></pre>
<p>Account service</p>
<pre><code>@Service
public class AccountService {
@Autowired
AccountRepository accountRepository;
@Autowired
BCryptPasswordEncoder bCryptPasswordEncoder;
@Autowired
ModelMapper modelMapper;
public boolean create(AccountDTO accountDTO) {
if (usernameExists(accountDTO.getUsername())) {
throw new UsernameExistsException();
}
Account account = modelMapper.map(accountDTO, Account.class);
account.setPassword(bCryptPasswordEncoder.encode(account.getPassword()));
account.setId(UUID.randomUUID().toString());
account.setRole(Role.USER);
if (accountRepository.save(account) != null) {
return true;
} else {
throw new RuntimeException();
}
}
public boolean remove(AccountDTO accountDTO) {
if (!usernameExists(accountDTO.getUsername())) {
throw new UsernameNotFoundException("Account named " + accountDTO.getUsername() + " not found");
}
Optional<Account> account = accountRepository.findByUsername(accountDTO.getUsername());
accountRepository.delete(account.get());
if (!usernameExists(accountDTO.getUsername())) {
return true;
}
return false;
}
public boolean usernameExists(String username) {
return accountRepository.findByUsername(username).isPresent();
}
}
</code></pre>
<p>AccountDetailsService implementing userdetailsservice</p>
<pre><code>@Service
public class AccountDetailsService implements UserDetailsService {
@Autowired
AccountRepository accountRepository;
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
Optional<Account> optionalAccount = accountRepository.findByUsername(s);
if (!optionalAccount.isPresent()) {
throw new UsernameNotFoundException("Account named " + s + " not found");
}
return new AccountDetails(optionalAccount.get());
}
}
</code></pre>
| [] | [
{
"body": "<p>Some tips:</p>\n\n<p><strong>Tip 1</strong></p>\n\n<pre><code>@Autowired\nAccountRepository accountRepository;\n\n@Autowired\nBCryptPasswordEncoder bCryptPasswordEncoder;\n...\n</code></pre>\n\n<p>Setter injection is considered as bad practice prefer constructor injection to gain more control and to avoid NullPointerExceptions.\n<a href=\"http://olivergierke.de/2013/11/why-field-injection-is-evil/\" rel=\"nofollow noreferrer\">Why field injection is evil</a></p>\n\n<p><strong>Tip 2</strong></p>\n\n<pre><code>@Id\nprivate String id = UUID.randomUUID().toString();\n</code></pre>\n\n<p>Encapsulate id generation into some component class eg. IDGenerator.nextId() where IDGenerator is an interface and you would provide some implementation class for that. You'll have more control in testing.</p>\n\n<p><strong>Tip 3</strong></p>\n\n<pre><code>Optional<Account> optionalAccount = accountRepository.findByUsername(s);\n\nif (!optionalAccount.isPresent()) {\n throw new UsernameNotFoundException(\"Account named \" + s + \" not found\");\n}\n\nreturn new AccountDetails(optionalAccount.get());\n</code></pre>\n\n<p>Using Optional like that is considered as bad practice. Something like that would be a lot better:</p>\n\n<pre><code>Account account = accountRepository.findByUsername(s).orElseThrow(UsernameNotFoundException::new)\nreturn new AccountDetails(account)\n</code></pre>\n\n<p><strong>Tip 4</strong></p>\n\n<pre><code>throw new RuntimeException();\n</code></pre>\n\n<p>You should throw more specific exceptions.</p>\n\n<p><strong>Tip 5 UPDATE</strong></p>\n\n<p>I think that <code>AccountService.remove(AccountDTO accountDTO)</code> is too complex.\nI believe in that case would be better to just write own deletion method in repository:</p>\n\n<pre><code>public void remove(AccountDTO accountDTO) {\n Objects.requireNonNull(accountDTO);\n accountRepository.deleteByUsername(accountDTO.getUsername());\n}\n</code></pre>\n\n<p><strong>Tip 6</strong></p>\n\n<p><code>AccountService</code> and <code>AccountDetailsService</code> could be as one class, these classes have similar responsibilities.</p>\n\n<p><strong>Tip 7</strong></p>\n\n<blockquote>\n <p>Then where should we use loadbyusername method?</p>\n</blockquote>\n\n<p>Spring security needs class which implements this interface when we use some other user data store than in memory.\nWhen some client app try to login / generate token this method \nwould be invoked by spring and whether if user exists or not spring\nwould respond with 400 Bad Request or 200 OK.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T08:34:48.563",
"Id": "469042",
"Score": "0",
"body": "Thanks for great tips. How can I reduce complexity of remove method in service?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T08:57:34.263",
"Id": "469044",
"Score": "0",
"body": "@JohnSpring I updated Tip 5."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T11:06:44.643",
"Id": "469052",
"Score": "0",
"body": "is it problematic if we dont check if the username is in db or not before deleting?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T11:29:48.903",
"Id": "469053",
"Score": "0",
"body": "I think it depends on the business case but In general it is not a problem. Notice that we expect that after this `remove` method ends we should not see particular user account on the database and that is true, if account exists it would be deleted if not nothing happens and thats ok because that is expected behaviour (particular user account should not exists on db)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T11:33:02.133",
"Id": "469054",
"Score": "0",
"body": "also do I still need accountdetails class after I merged accountservice and accountdetailsservice"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T11:38:29.103",
"Id": "469055",
"Score": "0",
"body": "No, that merged class can implement the UserDetailsService."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T11:51:17.540",
"Id": "469056",
"Score": "0",
"body": "I mean accountdetails model"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T11:57:42.237",
"Id": "469057",
"Score": "0",
"body": "Yes, you should have some impl of UserDetails either so AccountDetails is ok."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-18T21:43:57.980",
"Id": "239119",
"ParentId": "239107",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "239119",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-18T16:15:50.293",
"Id": "239107",
"Score": "2",
"Tags": [
"java",
"spring"
],
"Title": "Spring boot loadbyusername"
} | 239107 |
<p>I have created a simple Activity Planner that allows adding tasks and associated sub-tasks. It is mainly based on the <code>Treeview</code> widget. This being my first GUI-based project, I would like to know:</p>
<ul>
<li>If this is a good design pattern</li>
<li>If this could have been better broken down</li>
<li>About any typical features to be added </li>
<li>How it can be optimized in terms of performance and storage</li>
<li>About the pros and cons in general</li>
<li>About better practices</li>
</ul>
<p>I plan to remove the "Change Theme" feature. It's just there to assist in picking the right theme from the <code>ttkthemes</code> module. This is exactly why I had to wrap all my content in a Frame that fills up the entire outer root container that doesn't inherit the theme.</p>
<p>Any thoughts and help would be highly appreciated!</p>
<pre><code>import tkinter as tk
import tkinter.ttk as ttk
import tkinter.messagebox as tkmb
import tkinter.font as tkfont
import tkinter.filedialog
import ttkthemes as ttkt
import sys
import pickle
class Activity:
"""
Represents a single activity.
Attributes:
name(str): Activity Name
iid(str): Activity ID, uniquely identifies the activity
start(str): Start Time
end(str): End Time
parent()
"""
def __init__(self, name, start, end, priority, parent=None):
self.name = name
self.iid = id(name)
self.start = start
self.end = end
self.parent = parent #parent iid
self.checked = False
self.priority = priority
def has_parent(self):
return True if self.parent is not None else False
#TODO:
def has_completed(self):
self.checked = True
#TODO:
def notify(self):
pass
def __str__(self):
return str((self.name, self.iid, self.start, self.end, self.parent, self.priority))
def __repr__(self):
return self.__str__()
class ActivityTreeviewHandler:
"""
Handles the treeview to which the activity objects are added
"""
def __init__(self, tree_label_frame, on_item_select_callback=None, *cols):
self.activity_tree = ttk.Treeview(tree_label_frame, columns=list(cols))
self.activity_tree.heading('#0', text="Name")
self.activities = [] #Activity maintainer list for serialization and deserialization
for col in cols:
self.activity_tree.heading(col, text=col)
self.activity_tree.bind('<<TreeviewSelect>>', on_item_select_callback)
self.activity_tree.pack(padx=50, pady=50)
def add_activity(self, activity):
""" If activity has a parent, adds it a sub activity else adds at the top level.
The iid attribute of activity is used as the item id in the tree."""
self.activities.append(activity)
if activity.has_parent():
self.activity_tree.insert(activity.parent, 'end', activity.iid, text=activity.name, values=(activity.start, activity.end, activity.priority))
else:
self.activity_tree.insert('', 'end', activity.iid, text=activity.name, values=(activity.start, activity.end, activity.priority))
def remove_activity(self, activity_iid):
""" Removes an activity from the list and not from the treeview"""
#Prepare list of activities to be removed
removed_activites = [activity for activity in self.activities if activity.iid in activity_iid]
#Remove them 1 by 1
for activity in removed_activites:
self.activities.remove(activity)
def remove_selected_activity(self):
""" Removes the currently selected activity from the treeview and then calls remove_activity()"""
sel = self.activity_tree.selection()
self.activity_tree.delete(sel)
self.remove_activity(sel)
def save_state(self):
""" Serializer; writes all activites in the current treeview to a file using pickle
and returns the destination file name. Returns an empty string if fails.
Return:
str (Returns the destination file name)
"""
try:
with open(tkinter.filedialog.asksaveasfilename( title="Enter File Name"), 'wb') as dest_file:
#Serialize
pickle.dump(self.activities, dest_file, pickle.HIGHEST_PROTOCOL)
return dest_file.name
except Exception as e:
tkmb.showerror("Failed", "Couldn't save list")
return
def clear_treeview(self):
""" Empties the treeview """
self.activity_tree.delete(*self.activity_tree.get_children())
#Loads a list state from file after clearing the tree
def load_state(self):
""" Deserializer: Clears the tree, asks the user to open a saved file, and adds the activities to the tree
and returns the file name. Returns an empty string if fails.
Return:
str (Returns the destination file name)
"""
try:
self.clear_treeview()
with open(tkinter.filedialog.askopenfilename( title="Select File"), 'rb') as dest_file:
#Deserialize
self.activities = pickle.load(dest_file)
for activity in self.activities:
if activity.has_parent():
self.activity_tree.insert(activity.parent, 'end', activity.iid, text=activity.name, values=(activity.start, activity.end, activity.priority))
else:
self.activity_tree.insert('', 'end', activity.iid, text=activity.name, values=(activity.start, activity.end, activity.priority))
return dest_file.name
except Exception as e:
tkmb.showerror("Failed", "Couldn't load list")
return ""
class InputWindow:
""" Represents the input window that
* Takes in the details of a new activity
* Constructs an activity object from the details
* Passes the constructed object to the ActivityTreeviewHandler object's add_activity()
"""
def __init__(self, w_title, treeview_handler: ActivityTreeviewHandler, has_parent=False):
#Create Toplevel
self.container = tk.Toplevel()
self.container.title(w_title)
self.has_parent = has_parent
self.adder_pane = ttk.Frame(self.container)
self.adder_pane.pack(expand=True, fill=tk.BOTH, ipadx=50, ipady=100)
self.treeview_handler = treeview_handler
#Create input fields
self.activity_input = {}
self.activity_input['name'] = ttk.Entry(self.adder_pane), ttk.Label(self.adder_pane, text="Activity name:")
self.activity_input['start'] = ttk.Entry(self.adder_pane), ttk.Label(self.adder_pane, text="From :")
self.activity_input['end'] = ttk.Entry(self.adder_pane), ttk.Label(self.adder_pane, text="To :")
self.activity_input['priority'] = ttk.Entry(self.adder_pane), ttk.Label(self.adder_pane, text="Priority:")
#Add to parent container
self.activity_input['name'][1].grid(row=0, column=0, pady=5)
self.activity_input['name'][0].grid(row=0, column=1, pady=5)
self.activity_input['start'][1].grid(row=1, column=0, pady=5)
self.activity_input['start'][0].grid(row=1, column=1, pady=5)
self.activity_input['end'][1].grid(row=2, column=0, pady=5)
self.activity_input['end'][0].grid(row=2, column=1, pady=5)
self.activity_input['priority'][1].grid(row=3, column=0, pady=5)
self.activity_input['priority'][0].grid(row=3, column=1, pady=5)
ttk.Button(self.adder_pane, text="Add", command=self.construct_activity_from_input).grid(row=4,column=1)
self.container.mainloop()
def construct_activity_from_input(self):
for field in self.activity_input:
if self.activity_input[field][0].get() == "":
tkmb.showerror("Empty field "+field, "Please enter a valid "+field)
return
activity = Activity(
self.activity_input['name'][0].get(),
self.activity_input['start'][0].get(),
self.activity_input['end'][0].get(),
self.activity_input['priority'][0].get(),
self.treeview_handler.activity_tree.selection()[0] if self.has_parent else None
)
self.treeview_handler.add_activity(activity)
self.container.destroy()
class App:
""" The main Activity Planner App
Attributes
themes(list) - helps implementing change_theme()
saved(bool) - monitors save state
"""
def __init__(self):
self.container = ttkt.ThemedTk()
self.master = ttk.Frame(self.container)
self.master.pack(fill=tk.BOTH, expand=True)
self.themes = self.container.get_themes()
self.tree_label_frame = ttk.LabelFrame(self.master, text="Your Activities")
self.button_label_frame = ttk.LabelFrame(self.master, text="Modify")
self.treeview_handler = ActivityTreeviewHandler(self.tree_label_frame, self.on_select, 'From', 'To', 'Priority')
self.add_button = ttk.Button(self.button_label_frame, text="Add Activity...", command=self.on_add_activity)
self.add_button.pack(anchor=tk.CENTER, pady=10)
self.remove_button = ttk.Button(self.button_label_frame, text="Delete Activity", state='disabled', command=self.on_delete_activity)
self.remove_button.pack(anchor=tk.CENTER, pady=10)
self.add_sub_button = ttk.Button(self.button_label_frame, text="Add Sub Activity...", state='disabled', command=self.on_add_sub_activity)
self.add_sub_button.pack(anchor=tk.CENTER, pady=10)
self.theme_changer = self.change_theme()
ttk.Button(self.button_label_frame, text="Change Theme", command= lambda: next(self.theme_changer)).pack(pady=10, anchor=tk.CENTER)
self.tree_label_frame.pack(padx=50, pady=25)
self.button_label_frame.pack(padx=50, pady=25, fill=tk.X, expand=True)
self.container.wm_state('zoomed')
self.saved = True
#Menu
self.menubar = tk.Menu(self.container)
self.menus = {}
self.menus['file'] = tk.Menu(self.menubar, tearoff=0)
self.menus['file'].add_command(label="New", command=self.new_instance)
self.menus['file'].add_command(label="New Child Window", command=self.new_child_instance)
self.menus['file'].add_separator()
self.menus['file'].add_command(label="Save...", command=self.on_save)
self.menus['file'].add_command(label="Load...", command=self.on_load)
self.menus['file'].add_separator()
self.menus['file'].add_command(label="Quit", command=self.quit)
self.menus['edit'] = tk.Menu(self.menubar)
self.menus['edit'].add_command(label="Add Activity", command=self.on_add_activity)
self.menus['edit'].add_command(label="Add Sub Activity", command=self.on_add_sub_activity)
self.menus['edit'].add_command(label="Delete Activity", command=self.on_delete_activity )
self.menubar.add_cascade(label="File", menu=self.menus['file'])
self.menubar.add_cascade(label="Edit", menu=self.menus['edit'])
self.container.config(menu=self.menubar)
self.container.title("Activity Planner")
self.container.mainloop()
def change_theme(self):
""" Cycles through the available themes provided by ttkthemes"""
while True:
for thm in self.themes:
self.container.set_theme(thm)
yield
def on_add_activity(self):
InputWindow("Add a New Activity", self.treeview_handler)
self.saved = False
def on_add_sub_activity(self):
InputWindow("Add a New Sub Activity", self.treeview_handler, has_parent=True)
self.saved = False
def on_delete_activity(self):
self.treeview_handler.remove_selected_activity()
self.saved = False
self.add_sub_button['state'] = 'disabled'
self.remove_button['state'] = 'disabled'
def on_select(self, event):
self.add_sub_button['state'] = 'normal'
self.remove_button['state'] = 'normal'
def quit(self):
self.ask_save_state()
self.container.destroy()
sys.exit(0)
def new_instance(self):
self.ask_save_state()
self.container.destroy()
App()
def new_child_instance(self):
App()
def ask_save_state(self):
if not self.saved:
if(tkmb.askyesno("Save List", "Do you want to save the list?")):
self.on_save()
def on_save(self):
name = self.treeview_handler.save_state()
self.container.title(name+ " - Activity Planner")
self.saved = True
def on_load(self):
self.ask_save_state()
name = self.treeview_handler.load_state()
self.container.title(name+ " - Activity Planner")
App()
</code></pre>
| [] | [
{
"body": "<h2>Type hints</h2>\n\n<pre><code>\"\"\"\n Attributes:\n name(str): Activity Name\n iid(str): Activity ID, uniquely identifies the activity\n start(str): Start Time\n end(str): End Time\n parent()\n\"\"\"\n</code></pre>\n\n<p>It's nice that you've documented these types, but it would be better to tell Python (or at least your IDE) about them:</p>\n\n<pre><code>def __init__(self, name: str, start: datetime, end: datetime, ...):\n self.name: str = name\n self.start: datetime = start\n ...\n</code></pre>\n\n<p>Note that if a variable is a time, it should actually be represented with a time type and not a string.</p>\n\n<h2>Boolean expressions</h2>\n\n<pre><code>return True if self.parent is not None else False\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>return self.parent is not None\n</code></pre>\n\n<h2>Todo methods</h2>\n\n<p>Rather than <code>pass</code>, you should <code>raise NotImplementedError()</code>.</p>\n\n<h2><code>__str__</code></h2>\n\n<p>Rather than string-izing a tuple like this:</p>\n\n<pre><code> return str((self.name, self.iid, self.start, self.end, self.parent, self.priority))\n</code></pre>\n\n<p>you should probably be more deliberate and format a string, such as</p>\n\n<pre><code>return f'{self.name}: iid={self.iid} time={self.start}-{self.end}'\n</code></pre>\n\n<h2>Dynamic args</h2>\n\n<pre><code> if activity.has_parent():\n self.activity_tree.insert(activity.parent, 'end', activity.iid, text=activity.name, values=(activity.start, activity.end, activity.priority))\n else: \n self.activity_tree.insert('', 'end', activity.iid, text=activity.name, values=(activity.start, activity.end, activity.priority))\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>parent = activity.parent if activity.has_parent() else ''\nself.activity_tree.insert(parent, 'end', activity.iid, text=activity.name, values=(activity.start, activity.end, activity.priority))\n</code></pre>\n\n<h2>Dictionary literals</h2>\n\n<pre><code> self.activity_input = {}\n self.activity_input['name'] = ttk.Entry(self.adder_pane), ttk.Label(self.adder_pane, text=\"Activity name:\")\n self.activity_input['start'] = ttk.Entry(self.adder_pane), ttk.Label(self.adder_pane, text=\"From :\")\n self.activity_input['end'] = ttk.Entry(self.adder_pane), ttk.Label(self.adder_pane, text=\"To :\")\n self.activity_input['priority'] = ttk.Entry(self.adder_pane), ttk.Label(self.adder_pane, text=\"Priority:\")\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>self.activity_input = {\n 'name': (ttk.Entry(self.adder_pane), ttk.Label(self.adder_pane, text=\"Activity name:\")),\n 'start': (ttk.Entry(self.adder_pane), ttk.Label(self.adder_pane, text=\"From :\")),\n ...\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T16:35:38.580",
"Id": "239149",
"ParentId": "239112",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "239149",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-18T18:21:26.573",
"Id": "239112",
"Score": "4",
"Tags": [
"python",
"performance",
"design-patterns",
"tkinter",
"to-do-list"
],
"Title": "A Python tkinter Activity Planner (To-do List)"
} | 239112 |
<p>I've some Metal buffers which I populate with geometry data. Most data consists of <code>Float</code>s, but the buffer also contains custom structs for the tessellation stage.
I get the <code>UnsafeMutableRawPointer</code> for the Metal buffer in this way:</p>
<p><code>let origin=geometryBuffer.contents()</code></p>
<p>Which I then supply to the following function:</p>
<pre><code>
func populate(bufferPointer: UnsafeMutableRawPointer, useTessellation: Bool) -> UnsafeMutableRawPointer {
var bufferPointer = bufferPointer
if let vertexData = vertexData {
var floatPointer = bufferPointer.assumingMemoryBound(to: Float.self)
for index in vertexData.indexes {
floatPointer[0]=vertexData.vertices[Int(3*index+0)]
floatPointer[1]=vertexData.vertices[Int(3*index+1)]
floatPointer[2]=vertexData.vertices[Int(3*index+2)]
floatPointer=floatPointer.advanced(by: 3)
}
bufferPointer = floatPointer.deinitialize(count: 0)
} else if useTessellation, let patchData=patchData {
memcpy(bufferPointer, patchData, patchData.count*MemoryLayout<PatchIn>.stride)
bufferPointer=bufferPointer.advanced(by: patchData.count*MemoryLayout<PatchIn>.stride)
}
if let lineData = lineVertexData {
var floatPointer = bufferPointer.assumingMemoryBound(to: Float.self)
floatPointer[0]=lineData[0].x
floatPointer[1]=lineData[0].y
floatPointer[2]=0
floatPointer[3]=lineData[1].x
floatPointer[4]=lineData[1].y
floatPointer[5]=0
floatPointer=floatPointer.advanced(by: 6)
bufferPointer = floatPointer.deinitialize(count: 0)
}
return bufferPointer
}
</code></pre>
<p>I'm very uncertain here about my usage of <code>assumingMemoryBound(to:)</code>, <code>deinitialize(count:)</code> and the <code>memcpy()</code>.</p>
<p>The code seems to run fine, but according to the documentation it's quite easy to get into undefined behaviour. So I wonder whether I'm using the pointers correctly.</p>
<p>Thanks in advance.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-18T19:11:19.897",
"Id": "239114",
"Score": "4",
"Tags": [
"swift",
"pointers"
],
"Title": "Using UnsafeMutableRawPointers with Metal buffers in Swift"
} | 239114 |
<p>I was looking into SOA to better utilize SIMD instructions. I implemented a generic wrapper object that lets you chose the amount of individual vectors each structure consists of. I am using xsimd and boost libraries if you're interested in testing it out.</p>
<p>Next step would be to make initializing the buffer easier, like an emplace method that allows forwarding arguments to the nested vectors or smth., here your feedback would come into play :)</p>
<p>I implemented the stl-style transform algorithm on the buffer that lets you transform a buffer of size N into a buffer of size M. Here I took the pre-implemented transform algorithm from xsimd as reference.
As an example, I calculate the cross-product and dot-product of some vectors. First I transform a buffer of size 3 into a buffer of size 3, second from 3 to 1.</p>
<p>Also added structured binding support by adding specializations for tuple_size and tuple_element, see here <a href="https://stackoverflow.com/questions/55585723/boostcombine-range-based-for-and-structured-bindings">boost:: combine, range-based for and structured bindings</a></p>
<pre><code>#include <chrono>
#include <iostream>
#include <vector>
#include <xsimd/xsimd.hpp>
#include <xsimd/stl/algorithms.hpp>
#include <boost/iterator/zip_iterator.hpp>
namespace voxel
{
template <typename T, size_t N>
struct Buffer final
{
std::array<std::vector<T, XSIMD_DEFAULT_ALLOCATOR(T)>, N> values;
[[nodiscard]]
auto begin() noexcept
{
return std::apply([](auto&&... xs) noexcept
{
return boost::make_zip_iterator(boost::make_tuple(std::begin(std::forward<decltype(xs)>(xs))...));
}, values);
}
[[nodiscard]]
auto cbegin() const noexcept
{
return std::apply([](auto&&... xs) noexcept
{
return boost::make_zip_iterator(boost::make_tuple(std::cbegin(std::forward<decltype(xs)>(xs))...));
}, values);
}
[[nodiscard]]
auto end() noexcept
{
return std::apply([](auto&&... xs) noexcept
{
return boost::make_zip_iterator(boost::make_tuple(std::end(std::forward<decltype(xs)>(xs))...));
}, values);
}
[[nodiscard]]
auto cend() const noexcept
{
return std::apply([](auto&&... xs) noexcept
{
return boost::make_zip_iterator(boost::make_tuple(std::cend(std::forward<decltype(xs)>(xs))...));
}, values);
}
};
}
namespace std
{
template <typename T, typename U>
struct tuple_size<boost::tuples::cons<T, U>>
: boost::tuples::length<boost::tuples::cons<T, U>>
{
};
template <size_t I, typename T, typename U>
struct tuple_element<I, boost::tuples::cons<T, U>>
: boost::tuples::element<I, boost::tuples::cons<T, U>>
{
};
}
namespace voxel
{
namespace detail
{
template <typename T, std::size_t I>
struct RepeatHelper final
{
using Type = T;
};
}
template <typename T, typename I>
struct Repeat;
template <typename T, size_t... Is>
struct Repeat<T, std::index_sequence<Is...>> final
{
using Type = std::tuple<typename detail::RepeatHelper<T, Is>::Type...>;
};
namespace detail
{
template <typename Input, typename Output, typename Function, size_t... Is, size_t... Js>
void transform(Input begin, Input end, Output out, Function&& function, std::index_sequence<Is...>,
std::index_sequence<Js...>)
{
using InputValueType = std::decay_t<decltype(begin->template get<0>())>;
using OutputValueType = std::decay_t<decltype(out->template get<0>())>;
static_assert(std::is_same_v<InputValueType, OutputValueType>,
"Input and Output have to be of the same type!");
using InputTraits = xsimd::simd_traits<InputValueType>;
using OutputTraits = xsimd::simd_traits<OutputValueType>;
const auto distance = static_cast<std::size_t>(std::distance(begin, end));
const auto inputSize = InputTraits::size;
const auto outputSize = OutputTraits::size;
const auto alignInput =
xsimd::get_alignment_offset(&(begin->template get<0>()), distance, inputSize);
const auto alignOutput =
xsimd::get_alignment_offset(&(out->template get<0>()), distance, outputSize);
const auto alignEnd = alignInput + ((distance - alignInput) & ~(inputSize - 1));
for (auto i = 0u; i < alignInput; ++i)
{
*(out + i) = function((begin + i)->template get<Is>()...);
}
typename Repeat<typename InputTraits::type, std::index_sequence<Is...>>::Type batches;
if (alignInput == alignOutput)
{
for (auto i = alignInput; i < alignEnd; i += inputSize)
{
(xsimd::load_aligned(&(begin + i)->template get<Is>(), std::get<Is>(batches)), ...);
const auto result = function(std::get<Is>(batches)...);
(xsimd::store_aligned(&(out + i)->template get<Js>(), result.template get<Js>()), ...);
}
}
else
{
for (auto i = alignInput; i < alignEnd; i += inputSize)
{
(xsimd::load_aligned(&(begin + i)->template get<Is>(), std::get<Is>(batches)), ...);
const auto result = function(std::get<Is>(batches)...);
(xsimd::store_unaligned(&(out + i)->template get<Js>(), result.template get<Js>()), ...);
}
}
for (auto i = alignEnd; i < distance; ++i)
{
*(out + i) = function((begin + i)->template get<Is>()...);
}
}
}
template <typename Input, typename Output, typename Function>
void transform(Input begin, Input end, Output out, Function&& function)
{
using InputSize = boost::tuples::length<std::decay_t<decltype(*begin)>>;
using OutputSize = boost::tuples::length<std::decay_t<decltype(*out)>>;
return detail::transform(begin, end, out, std::forward<Function>(function),
std::make_index_sequence<InputSize::value>{},
std::make_index_sequence<OutputSize::value>{});
}
}
int main()
{
voxel::Buffer<float, 3u> values;
values.values[0].reserve(100U);
values.values[1].reserve(100U);
values.values[2].reserve(100U);
for (auto y = 0; y < 10; ++y)
{
for (auto x = 0; x < 10; ++x)
{
values.values[0].emplace_back(x);
values.values[1].emplace_back(y);
values.values[2].emplace_back(x + y);
}
}
std::cout << "cross products:\n";
voxel::Buffer<float, 3u> crossProducts;
crossProducts.values[0].resize(100U);
crossProducts.values[1].resize(100U);
crossProducts.values[2].resize(100U);
const auto runs = 10U;
const auto xx = 29.0F;
const auto yy = 34.0F;
const auto zz = 23.0F;
auto accumulated = 0.0;
for (auto i = 0u; i < runs; ++i)
{
const auto t0 = std::chrono::high_resolution_clock::now();
voxel::transform(values.cbegin(), values.cend(), crossProducts.begin(),
[=](const auto& x, const auto& y, const auto& z) noexcept
{
return boost::make_tuple(yy * z - zz * y, zz * x - xx * z, xx * y - yy * x);
});
const auto elapsed = std::chrono::duration_cast<std::chrono::duration<double>>(
std::chrono::high_resolution_clock::now() - t0).count();
accumulated += elapsed;
std::cout << i << '.' << ' ' << elapsed << 's' << '\n';
}
std::cout << "average. " << accumulated / static_cast<double>(runs) << 's' << '\n' << '\n';
for (const auto [x, y, z] : crossProducts)
{
std::cout << '(' << x << ',' << y << ',' << z << ')' << '\n';
}
std::cout << "\ndot products:\n";
voxel::Buffer<float, 1u> dotProducts;
dotProducts.values[0].resize(100U);
accumulated = 0.0;
for (auto i = 0u; i < runs; ++i)
{
const auto t0 = std::chrono::high_resolution_clock::now();
voxel::transform(values.cbegin(), values.cend(), dotProducts.begin(),
[=](const auto& x, const auto& y, const auto& z) noexcept
{
return boost::make_tuple(xx * x + yy * y + zz * z);
});
const auto elapsed = std::chrono::duration_cast<std::chrono::duration<double>>(
std::chrono::high_resolution_clock::now() - t0).count();
accumulated += elapsed;
std::cout << i << '.' << ' ' << elapsed << 's' << '\n';
}
std::cout << "average. " << accumulated / static_cast<double>(runs) << 's' << '\n' << '\n';
for (const auto [x] : dotProducts)
{
std::cout << '(' << x << ')' << '\n';
}
}
</code></pre>
<p>EDIT:
In the meantime I worked on implementing a join function, that lets you join 2 buffers into a new one, although it seems to work, I haven't fully tested it yet.
As there is no answer at this time, I am going to add it to this post, instead of making a new one:</p>
<pre><code>namespace detail
{
template <typename Input1, typename Input2, typename Output, typename Function, size_t... Is, size_t... Js,
size_t... Ks>
void join(Input1 begin1, Input1 end1, Input2 begin2, Input2 end2, Output out, Function&& function,
std::index_sequence<Is...>, std::index_sequence<Js...>, std::index_sequence<Ks...>)
{
using Input1ValueType = std::decay_t<decltype(begin1->template get<0>())>;
using Input2ValueType = std::decay_t<decltype(begin2->template get<0>())>;
using OutputValueType = std::decay_t<decltype(out->template get<0>())>;
static_assert(std::conjunction_v<std::is_same<Input1ValueType, Input2ValueType>, std::is_same<
Input1ValueType, OutputValueType>>,
"Input1, Input2 and Output have to be the same type!");
using Input1Traits = xsimd::simd_traits<Input1ValueType>;
using Input2Traits = xsimd::simd_traits<Input2ValueType>;
using OutputTraits = xsimd::simd_traits<OutputValueType>;
const auto distance = static_cast<std::size_t>(std::min(std::distance(begin1, end1),
std::distance(begin2, end2)));
const auto input1Size = Input1Traits::size;
const auto input2Size = Input2Traits::size;
const auto outputSize = OutputTraits::size;
const auto alignBegin1 =
xsimd::get_alignment_offset(&(begin1->template get<0>()), distance, input1Size);
const auto alignBegin2 =
xsimd::get_alignment_offset(&(begin2->template get<0>()), distance, input2Size);
const auto alignOutput =
xsimd::get_alignment_offset(&(out->template get<0>()), distance, outputSize);
const auto alignEnd =
alignBegin1 + ((distance - alignBegin1) & ~(input1Size - 1));
for (auto i = 0U; i < alignBegin1; ++i)
{
*(out + i) = function((begin1 + i)->template get<Is>()..., (begin2 + i)->template get<Js>()...);
}
typename Repeat<typename Input1Traits::type, std::index_sequence<Is...>>::Type input1Batches;
typename Repeat<typename Input2Traits::type, std::index_sequence<Js...>>::Type input2Batches;
if (alignBegin1 == alignOutput && alignBegin1 == alignBegin2)
{
for (auto i = alignBegin1; i < alignEnd; i += input1Size)
{
(xsimd::load_aligned(&(begin1 + i)->template get<Is>(), std::get<Is>(input1Batches)), ...);
(xsimd::load_aligned(&(begin2 + i)->template get<Js>(), std::get<Js>(input2Batches)), ...);
const auto result = function(std::get<Is>(input1Batches)..., std::get<Js>(input2Batches)...);
(xsimd::store_aligned(&(out + i)->template get<Ks>(), result.template get<Ks>()), ...);
}
}
else if (alignBegin1 == alignOutput && alignBegin1 != alignBegin2)
{
for (auto i = alignBegin1; i < alignEnd; i += input1Size)
{
(xsimd::load_aligned(&(begin1 + i)->template get<Is>(), std::get<Is>(input1Batches)), ...);
(xsimd::load_unaligned(&(begin2 + i)->template get<Js>(), std::get<Js>(input2Batches)), ...);
const auto result = function(std::get<Is>(input1Batches)..., std::get<Js>(input2Batches)...);
(xsimd::store_aligned(&(out + i)->template get<Ks>(), result.template get<Ks>()), ...);
}
}
else if (alignBegin1 != alignOutput && alignBegin1 == alignBegin2)
{
for (auto i = alignBegin1; i < alignEnd; i += input1Size)
{
(xsimd::load_aligned(&(begin1 + i)->template get<Is>(), std::get<Is>(input1Batches)), ...);
(xsimd::load_aligned(&(begin2 + i)->template get<Js>(), std::get<Js>(input2Batches)), ...);
const auto result = function(std::get<Is>(input1Batches)..., std::get<Js>(input2Batches)...);
(xsimd::store_unaligned(&(out + i)->template get<Ks>(), result.template get<Ks>()), ...);
}
}
else
{
for (auto i = alignBegin1; i < alignEnd; i += input1Size)
{
(xsimd::load_aligned(&(begin1 + i)->template get<Is>(), std::get<Is>(input1Batches)), ...);
(xsimd::load_unaligned(&(begin2 + i)->template get<Js>(), std::get<Js>(input2Batches)), ...);
const auto result = function(std::get<Is>(input1Batches)..., std::get<Js>(input2Batches)...);
(xsimd::store_unaligned(&(out + i)->template get<Ks>(), result.template get<Ks>()), ...);
}
}
for (auto i = alignEnd; i < distance; ++i)
{
*(out + i) = function((begin1 + i)->template get<Is>()..., (begin2 + i)->template get<Js>()...);
}
}
}
template <typename Input1, typename Input2, typename Output, typename Function>
void join(Input1 begin1, Input1 end1, Input2 begin2, Input2 end2, Output out, Function&& function)
{
using Input1Size = boost::tuples::length<std::decay_t<decltype(*begin1)>>;
using Input2Size = boost::tuples::length<std::decay_t<decltype(*begin2)>>;
using OutputSize = boost::tuples::length<std::decay_t<decltype(*out)>>;
detail::join(begin1, end1, begin2, end2, out, std::forward<Function>(function),
std::make_index_sequence<Input1Size::value>{},
std::make_index_sequence<Input2Size::value>{},
std::make_index_sequence<OutputSize::value>{});
}
</code></pre>
| [] | [
{
"body": "<p>The code is clear and conforms to modern C++ programming guidelines.</p>\n\n<p>Here are some small points to consider:</p>\n\n<h1><code>final</code></h1>\n\n<p>The point of <code>final</code> is to help the compiler devirtualize function calls. Since your classes (<code>Buffer</code>, <code>RepeatHelper</code>, etc.) has no virtual member functions, <code>final</code> does not help the compiler optimize. It is hence unreasonable to prevent inheriting from these classes (which is handy in many situations). Therefore, remove the <code>final</code>.</p>\n\n<h1>Template metaprogramming</h1>\n\n<p><code>index_sequence</code> + <code>get</code> is handy, but <code>std::apply</code> is usually more readable. For example, compare</p>\n\n<pre><code>for (auto i = 0u; i < alignInput; ++i)\n{\n *(out + i) = function((begin + i)->template get<Is>()...);\n}\n</code></pre>\n\n<p>with</p>\n\n<pre><code>std::transform(begin, begin + i, out, [](auto&& element) {\n return std::apply(function, std::forward<decltype(element)>(element));\n});\n</code></pre>\n\n<p>(assuming that the tuple from boost implements the standard tuple protocol).</p>\n\n<p>Since you are already using boost, you can use Boost.Mp11 <a href=\"https://www.boost.org/doc/libs/1_72_0/libs/mp11/doc/html/mp11.html#mp_repeat_cl_n\" rel=\"nofollow noreferrer\"><code>mp_repeat_c</code></a> to produce a tuple of <code>N</code> copies of the same type:</p>\n\n<pre><code>boost::mp11::mp_repeat_c<std::tuple<T>, N> // produces std::tuple</* N copies of T */>\n</code></pre>\n\n<p>Also, this one from <code>join</code>:</p>\n\n<pre><code>std::conjunction_v<std::is_same<Input1ValueType, Input2ValueType>,\n std::is_same<Input1ValueType, OutputValueType>>\n</code></pre>\n\n<p>can be replaced by:</p>\n\n<pre><code>boost::mp11::mp_same<Input1ValueType, Input2ValueType, OutputValueType>::value\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T11:44:43.400",
"Id": "239182",
"ParentId": "239117",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "239182",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-18T20:41:38.873",
"Id": "239117",
"Score": "2",
"Tags": [
"c++",
"c++17",
"boost"
],
"Title": "\"Structure of arrays\" wrapper"
} | 239117 |
<p>I have a dictionary that looks like this:</p>
<pre class="lang-py prettyprint-override"><code>Counter({(1, 9): 3, (4, 2): 2, (3, 0): 1, (5, 4): 1})
</code></pre>
<p>I would like to convert it to an array that would look like this:</p>
<pre class="lang-py prettyprint-override"><code>[[1, 9, 3], [4, 2, 2], [3, 0, 1], [5, 4, 1]]
</code></pre>
<p>Help appreciated!</p>
<pre><code>import itertools
import collections
import numpy as np
a = [1,5,1,1,3,4,4] # First column
b = [9,4,9,9,0,2,2] # Second column
ind = np.lexsort((b,a)) # Sort by a, then by b
print (ind)
c= [(a[i],b[i]) for i in ind]
d =np.array(c)
counts = collections.Counter()
list_of_items = d
for sublist in list_of_items:
counts.update(itertools.combinations(sublist, 2))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-18T22:42:23.010",
"Id": "469012",
"Score": "0",
"body": "Welcome to Code Review"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T01:06:01.200",
"Id": "469017",
"Score": "1",
"body": "Welcome to Code Review! The code you posted doesn't appear to implement the functionality that you discuss in your title and post. Are you asking how to perform this conversion? If so, this question is off-topic on Code Review and should be directed to [StackOverflow](https://stackoverflow.com/) instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T02:53:31.363",
"Id": "469024",
"Score": "0",
"body": "You can implement this in one line: `[[*key, value] for key, value in counts.items()]`. But as others have mentioned, Code Review is meant for reviewing *working* code, not asking for solutions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T05:59:47.793",
"Id": "469030",
"Score": "0",
"body": "Thanks for solution! I am new to this so apologize for posting in wrong forum."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-18T22:11:35.273",
"Id": "239120",
"Score": "1",
"Tags": [
"python",
"array",
"hash-map",
"converting"
],
"Title": "Convert dict to array in Python"
} | 239120 |
<p>As I'm learning c++, I decided to implement my own sorting algorithm. As I'm a beginner I didn't use any template to be able to use them for different types of variable and they can only sort item in a vector. I implemented bubble sort, selection sort, insertion sort, merge sort and quick sort. I'm not asking you to review all my code but you can if you want to, any advice on something that strike you are welcome.
Here is my code :</p>
<pre><code>#include <iostream>
#include <vector>
void display_vector(const std::vector<int>& to_display);
void bubble_sort(std::vector<int>& to_sort);
void bubble_sort_optimized(std::vector<int>& to_sort);
void selection_sort(std::vector<int>& to_sort);
void insertion_sort(std::vector<int>& to_sort);
std::vector<int> merge_sort(std::vector<int>& to_sort);
void quick_sort_rec(std::vector<int>& to_sort, int start, int end);
inline void quick_sort(std::vector<int>& to_sort);
int ind_min(const std::vector<int>& v, const int& i);
int partition(std::vector<int>& v, int start, int end);
std::vector<int> merge(std::vector<int>& v1, std::vector<int>& v2);
std::vector<int> get_from_to(std::vector<int>& v, unsigned int start, unsigned int end);
int main()
{
std::vector<int> vector_to_sort = { -5,2,4,1,8,3,8,9,1,10 };
std::vector<int> sorted_vector;
quick_sort(vector_to_sort);
display_vector(vector_to_sort);
}
void bubble_sort(std::vector<int>& to_sort)
{
//For the i-iteration we loop the n-(i+1) value and swap if two following value are not sorted
for (unsigned int i = 1; i < to_sort.size(); ++i)
{
for (unsigned int k = 0; k < to_sort.size() - i; ++k)
{
if (to_sort[k] > to_sort[k + 1])
{
int value = to_sort[k];
to_sort[k] = to_sort[k + 1];
to_sort[k + 1] = value;
}
}
}
//Time complexity : O(n^2) where n is the size of the vector in any case
}
void bubble_sort_optimized(std::vector<int>& to_sort)
{
unsigned int i = 1;
bool sorted = false;
while (i < to_sort.size() && !sorted)
{
sorted = true;
for (unsigned int k = 0; k < to_sort.size() - i; ++k)
{
if (to_sort[k] > to_sort[k + 1])
{
int value = to_sort[k];
to_sort[k] = to_sort[k + 1];
to_sort[k + 1] = value;
sorted = false;
}
}
}
//Time complexity : O(n^2) where n is the size of the vector in the worse case, in the best case O(n)
}
void selection_sort(std::vector<int>& to_sort)
{
//For the i-iteration we find the index superior or egal to i of the minimal value in the vector and we put it in at the i-place
for (unsigned int i = 0; i < to_sort.size(); ++i)
{
int ind_swap = ind_min(to_sort, i);
int temp = to_sort[i];
to_sort[i] = to_sort[ind_swap];
to_sort[ind_swap] = temp;
}
//Time complexity : O(n^2) where n is the size of the vector in the worst case, in the best case O(n)
}
void insertion_sort(std::vector<int>& to_sort)
{
//For the i-iteration we suppose the vector to be sort for the i-1 first value we insert the i-value into the i-1 value to keep it sort
for (unsigned int i = 1; i < to_sort.size(); ++i)
{
int value = to_sort[i];
int k = i;
while (k > 0 && to_sort[k - 1] > value)
{
to_sort[k] = to_sort[k - 1];
k--;
}
to_sort[k] = value;
}
//Time complexity : O(n^2) where n is the size of the vector in the worst case, in the best case O(n)
}
int ind_min(const std::vector<int>& v, const int& i)
{
int min = v[i];
int ind_min = i;
for (unsigned int k = i + 1; k < v.size(); ++k)
{
if (v[k] < min)
{
min = v[k];
ind_min = k;
}
}
return ind_min;
}
std::vector<int> merge_sort(std::vector<int>& to_sort)
{
if (to_sort.size() <= 1)
{
return to_sort;
}
else
{
unsigned int mid = to_sort.size() / 2;
std::vector<int> left;
std::vector<int> right;
left.reserve(mid);
right.reserve(to_sort.size() - mid);
left = get_from_to(to_sort, 0, mid);
right = get_from_to(to_sort, mid, (unsigned int) to_sort.size());
left = merge_sort(left);
right = merge_sort(right);
return merge(left, right);
}
//Time complexity : O(n*ln(n)) where n is the size of the vector
}
std::vector<int> merge(std::vector<int>& v1, std::vector<int>& v2)
{
unsigned int n1 = v1.size();
unsigned int n2 = v2.size();
unsigned int i1 = 0;
unsigned int i2 = 0;
std::vector<int> merged;
while (i1 < n1 and i2 < n2)
{
if (v1[i1] < v2[i2])
{
merged.push_back(v1[i1]);
++i1;
}
else
{
merged.push_back(v2[i2]);
++i2;
}
}
while (i1 < n1)
{
merged.push_back(v1[i1]);
++i1;
}
while (i2 < n2)
{
merged.push_back(v2[i2]);
++i2;
}
return merged;
}
std::vector<int> get_from_to(std::vector<int>& v, unsigned int start, unsigned int end)
{
if (start == end)
{
std::cout << "get_from_to ERROR start index = end index";
return std::vector<int>();
}
std::vector<int> extrated;
extrated.reserve(end - start - 1);
for (unsigned int k = start; k < end; ++k)
{
extrated.push_back(v[k]);
}
return extrated;
}
void quick_sort_rec(std::vector<int>& to_sort, int start, int end)
{
if (start == end)
{
return;
}
else
{
int p = partition(to_sort, start, end);
quick_sort_rec(to_sort, start, p);
quick_sort_rec(to_sort, p + 1, end);
}
}
inline void quick_sort(std::vector<int>& to_sort)
{
quick_sort_rec(to_sort, 0, to_sort.size());
}
int partition(std::vector<int>& v, int start, int end)
{
int value = v[start];
int p = start;
for (int k = start + 1; k < end; ++k)
{
if (v[k] < value)
{
v[p] = v[k];
v[k] = v[p + 1];
v[p + 1] = value;
}
}
return p;
}
void display_vector(const std::vector<int>& to_display)
{
for (unsigned int i = 0; i < to_display.size() -1 ; ++i)
{
std::cout << to_display[i] << ", ";
}
std::cout << to_display[to_display.size() - 1] << '\n';
}
</code></pre>
<p>PS : Forgive my English, I'm French but I will try my best to be able to respond to your advice.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T00:39:37.363",
"Id": "469015",
"Score": "0",
"body": "In English, the letter \"I\" is capital when used as a first-person pronoun, and \"English\" and \"French\" start with a capital letter too, but otherwise I think your English is good enough."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T08:00:53.220",
"Id": "469035",
"Score": "0",
"body": "Just a little correction. Complexity of merge sort is actually `n*ln(n)/ln(2)`. I know you could say that ln(2) Is a constant, thus omitable but log base 2 really conveys the nature of the algorithm much better than natural log."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T08:11:11.867",
"Id": "469036",
"Score": "1",
"body": "@slepic Yes you are right but from a purely mathematical point of view O(n * ln(n)) is equal to O(n * ln(n) / ln(2))"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T08:55:10.860",
"Id": "469043",
"Score": "0",
"body": "Yes, im not saying it is wrong. Log with any base could be there actually. But thats exactly why in O notation we usualy write just `log(n)` without specifying the base. `ln(n)` seems to contain explicit base `e` making it seem that `e` is somehow fundamental to the algorithm. Not in mathematical sense, but it may lead to unnecesary confusion for the reader who is not a mathematical machine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T09:02:24.523",
"Id": "469045",
"Score": "0",
"body": "@slepic Ok ok I will change it. I just more use to ln than log as a mathematic student."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T12:47:42.010",
"Id": "469073",
"Score": "2",
"body": "Incorporating advice from an answer into the question violates the question-and-answer nature of this site. You could post improved code as a new question, as an answer, or as a link to an external site - as described in [I improved my code based on the reviews. What next?](/help/someone-answers#help-post-body). I have rolled back the edit, so the answers make sense again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T13:10:13.683",
"Id": "469079",
"Score": "0",
"body": "O(ln _n_) == O(log₂ _n_); I think most of us are used to seeing ln there, but it makes no sense to introduce constant multipliers in big-O notation. I think that changing to do so makes it less clear."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T17:33:05.080",
"Id": "469106",
"Score": "0",
"body": "@TobySpeight I agree for the O notation it's what i said and thank i did not know if i should create a new question or edit the existing one."
}
] | [
{
"body": "<p>Thank you for not using <code>using namespace std;</code>.</p>\n<p>Enclosing all blocks of code in <code>{}</code> is a good practice that I promote, so thank you for that good practice as well.</p>\n<p>In C and C++ you don't really need that large block of function declarations at the top if all the functions are in the proper order, but in some cases this is a matter of style, in other cases if 2 functions call each other function prototypes are necessary.</p>\n<h2>Missing Header File</h2>\n<p>To use <code>and</code> as the logical AND operator the header file <code>iso646.h</code> should be included, otherwise it might be better to use <code>&&</code> as the logical AND operator. Not all C++ compilers include this by default.</p>\n<h2>Proper Testing of Sort Functions</h2>\n<p>If you really want to properly test the functions you should have a vector that has the properly sorted values to compare the returned values of the a sort function.</p>\n<h2>Not All Functions are Used</h2>\n<p>This is sometimes a sign that the code is not ready for review or Ready for Use by Others (RFUBO). In this case I believe it is because the testing hasn't really been thought out and only one test will work at a time.</p>\n<p>One way to correct this is to not use the input vector as the output. Instead each sort function can return a sorted vector rather than each function being void.</p>\n<pre><code>std::vector<int> bubble_sort(std::vector<int> to_sort);\nstd::vector<int> insertion_sort(std::vector<int> to_sort);\n\nbool vectors_are_equal(std::vector<int> sorted, std::vector<int> control)\n{\n if (sorted.size() != control.size())\n {\n return false;\n }\n\n for (int i = 0; i < control.size(); i++)\n {\n if (sorted[i] != control[i])\n {\n return false;\n }\n }\n\n return true;\n}\n\nint main()\n{\n std::vector<int> vector_to_sort = { 10, 8, 4, 1, 8, 3, 2, 9, 1, -5 };\n std::vector<int> control = { -5, 1, 1, 2, 3, 4, 8, 8, 9, 10};\n\n std::vector<int> sorted_vector = bubble_sort(vector_to_sort);\n std::cout << "Bubble Sort Test " << ((vectors_are_equal(sorted_vector, control)) ? "Passed" : "Failed") << "\\n";\n display_vector("Bubble Sort", sorted_vector);\n std::cout << "\\n";\n\n sorted_vector.clear();\n sorted_vector = insertion_sort(vector_to_sort);\n std::cout << "Insertion Sort Test " << ((vectors_are_equal(sorted_vector, control)) ? "Passed" : "Failed") << "\\n";\n display_vector("Insertion Sort", sorted_vector);\n\n}\n</code></pre>\n<p>It might be interesting to add timing to the tests to see what's faster. It might also be interesting to use a random number generator to populate the <code>vector_to_sort</code>, and larger ranges of numbers would also be interesting.</p>\n<p>Note I've changed the order of some of the values in the <code>vector_to_sort</code> so that there are a couple of worst case scenarios.</p>\n<p>Much code duplication of testing could be corrected by a function that takes the name and a function pointer of the sort to be tested.</p>\n<h2>Inline Functions</h2>\n<p>The C++ keyword <code>inline</code> is obsolete, current optimizing compilers do a much better job of inlining functions as necessary.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T08:33:43.353",
"Id": "469040",
"Score": "0",
"body": "Yes my bad for « and » I’m not yet use to && as I learn python first."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T12:51:07.730",
"Id": "469074",
"Score": "0",
"body": "`<iso646.h>` (or `<ciso646>`) is empty on a conforming implementation - it's only necessary if you want to provide a sop to old/broken compilers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T13:31:16.527",
"Id": "469084",
"Score": "0",
"body": "@TobySpeight so VS2019 C++ is broken?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T18:25:21.853",
"Id": "469109",
"Score": "0",
"body": "If it doesn't have `and` and `or` keywords, then yes it is, in that respect. It might be worth mentioning that compiler as a motivation for your recommendation to use the header as a workaround (it wasn't obvious to me why you suggested it, for example)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T00:55:42.517",
"Id": "469149",
"Score": "2",
"body": "@pacmaninbw VS2019 is broken if you don't specify `/permissive-`, yes. With `/permissive-` (enabling standards conformance, set by default for new projects since VS2017 I believe) then `and` and `or` are proper keywords."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T00:46:24.867",
"Id": "239125",
"ParentId": "239122",
"Score": "3"
}
},
{
"body": "<p>Let's go through the functions and see what can be improved.</p>\n\n<h1><code>main</code></h1>\n\n<p>The <code>sorted_vector</code> variable is not used. Remember to enable compiler\nwarnings.</p>\n\n<p>You only test the <code>quick_sort</code> function. Consider testing other\nfunctions as well.</p>\n\n<h1><code>bubble_sort</code></h1>\n\n<p>The correct type to index a <code>std::vector<int></code> is\n<code>std::vector<int>::size_type</code>. <code>std::size_t</code> (defined in header\n<code><cstddef></code>) is also fine, but <code>unsigned int</code> is not appropriate.</p>\n\n<p>Instead of looping to <code>to_sort.size() - i</code>, why not simply set <code>i</code> to\nthe correct bound?</p>\n\n<p>Use <code>std::swap</code> (defined in header <code><utility></code>) to swap two values\ninstead of manually introducing a third variable.</p>\n\n<p>In <code>bubble_sort_optimized</code>, <code>i</code> doesn't increase, so the function does\nunnecessary work.</p>\n\n<h1><code>selection_sort</code></h1>\n\n<p>This function can be simplified with <code>std::iter_swap</code> (defined in\nheader <code><utility></code>) and <code>std::min_element</code> (defined in header\n<code><algorithm></code>):</p>\n\n<pre><code>void selection_sort(std::vector<int>& to_sort)\n{\n for (auto it = to_sort.begin(); it != to_sort.end(); ++it) {\n std::iter_swap(it, std::min_element(it, to_sort.end()));\n }\n}\n</code></pre>\n\n<p>The <code>ind_min</code> function can be removed.</p>\n\n<h1><code>merge_sort</code></h1>\n\n<p>The function has a strange interface — it mutates the input\nvector and returns a new vector.</p>\n\n<p>The <code>get_from_to</code> function is also not useful, because <code>std::vector</code>\nalready has the functionality:</p>\n\n<pre><code>void merge_sort(std::vector<int>& to_sort)\n{\n if (to_sort.size() <= 1) {\n return;\n }\n auto mid = to_sort.begin() + to_sort.size() / 2;\n std::vector left(to_sort.begin(), mid);\n std::vector right(mid, to_sort.end());\n merge_sort(left);\n merge_sort(right);\n std::merge(left.begin(), left.end(), right.begin(), right.end(), to_sort.begin());\n}\n</code></pre>\n\n<p>Note that <code>std::merge</code> (defined in header <code><algorithm></code>) does the job\nof <code>merge</code>.</p>\n\n<h1><code>quick_sort</code></h1>\n\n<p>You are using <code>int</code> to index the vector — that's even worse than\n<code>unsigned int</code>.</p>\n\n<p>You don't have to mark <code>quick_sort</code> inline — unless you are\nimplementing the function in a header, in which case all non-template\nfunctions need to be inline in order to prevent ODR violations.</p>\n\n<h1><code>display_vector</code></h1>\n\n<p>This function has a bug: the function accesses invalid memory if\n<code>to_display</code> is empty, in which case <code>to_display.size() - 1</code> returns\n<code>SIZE_MAX</code> (which is typically <code>4294967295</code> or <code>18446744073709551615</code>)\ninstead of <code>-1</code>, since <code>to_display.size()</code> is an unsigned value! The\nempty case needs to be handled specially anyway. For other cases, use\n<code>std::ostream_iterator</code> (defined in header <code><iterator></code>):</p>\n\n<pre><code>void display_vector(const std::vector<int>& to_display)\n{\n if (to_display.empty()) {\n return;\n }\n std::copy(to_display.begin(), to_display().end() - 1,\n std::ostream_iterator<int>{std::cout, \", \"});\n std::cout << to_display.back() << '\\n';\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T08:22:56.960",
"Id": "469037",
"Score": "0",
"body": "What do you mean when you say set i to the correct bound in the bubble sort ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T08:25:46.193",
"Id": "469038",
"Score": "0",
"body": "@Kiyosuke `for (auto i = to_sort.size(); i--;)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T09:05:16.033",
"Id": "469046",
"Score": "0",
"body": "Yes why not I don't usually use reverse loop so it will be a good start"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T03:57:07.460",
"Id": "239131",
"ParentId": "239122",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "239131",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-18T22:30:41.820",
"Id": "239122",
"Score": "3",
"Tags": [
"c++",
"sorting"
],
"Title": "My C++ sorting algorithm for vector"
} | 239122 |
<p>LINQ <code>Select</code> usually works like this:</p>
<pre><code>IEnumerable<Task<int>> res = new[] {1,2,3}.Select(async i => i);
</code></pre>
<p>I would like to have the following though:</p>
<pre><code>IEnumerable<int> res = new[] {1,2,3}.Select(async i => i);
</code></pre>
<p>This extension method helps to get it:</p>
<pre><code>static class SelectAsync
{
public static IEnumerable<TResult> Select<T, TResult>(
this IEnumerable<T> source, Func<T, Task<TResult>> selector)
{
return source
.ToObservable()
.Select(value => Observable.FromAsync(() => selector(value)))
.Concat()
.ToEnumerable();
}
}
</code></pre>
<p>So the following is true:</p>
<pre><code>public class AsyncSelect_Should
{
[Test]
public void Not_Block()
{
var src = new[] { 1, 2, 3 };
var res = src.Select(async i => i);
CollectionAssert.AreEqual(src, res);
}
}
</code></pre>
<p>There should be something bad, really bad about it. Does it? :)</p>
| [] | [
{
"body": "<p>The bad part is that <code>ToEnumerable</code> returns an <code>IEnumerable</code> that blocks for each element until it is produced by the <code>IObservable</code> it is called on. This means that you might as well be doing:</p>\n\n<pre><code>public static IEnumerable<R> SelectAsync<T, R>(this IEnumerable<T> source, Func<T, Task<R>> selector)\n{\n foreach (var item in source)\n yield return selector(item).Result;\n}\n</code></pre>\n\n<p>and depending on what kind of app you're writing, this might deadlock, though I think your version of going through Rx might avoid that and be more functionality close to:</p>\n\n<pre><code>public static IEnumerable<R> SelectAsync<T, R>(this IEnumerable<T> source, Func<T, Task<R>> selector)\n{\n foreach (var item in source)\n yield return Task.Run(() => selector(item)).Result;\n}\n</code></pre>\n\n<p>Either way, you're blocking a <code>Thread</code> which is seen as a bad thing to do in the age of async/await and the TPL. It would be as bad as using <code>Thread.Sleep</code> with <code>Task.Run</code>. It is not likely to lock up your app, especially if your app is multi-threaded, but it most certainly will block a <code>Thread</code> on the thread pool.</p>\n\n<p>I've certainly seen people get away with using <code>Thread.Sleep</code> with <code>Task.Run</code> with no real consequences, but keep in mind that it can cause issues when you scale.</p>\n\n<p>As for how you might know this without being intimately familiar with Rx and the details of how its operators work? That's easy. Just know that you can never go from having an asynchronous value (<code>Task<T></code>) to having a synchronous value (<code>T</code>) without awaiting (which requires that you stay in an async context) or blocking. Even Rx doesn't have enough magic to change that :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T17:20:17.780",
"Id": "239150",
"ParentId": "239123",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "239150",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-18T22:45:09.460",
"Id": "239123",
"Score": "6",
"Tags": [
"c#",
"linq",
"system.reactive"
],
"Title": "Async selector in LINQ"
} | 239123 |
<p>So my question is the cleanest way to do <code>#product_panels_for</code> below:</p>
<pre><code>class ProductPanel < Struct.new(:product)
end
class ProductPresenter
def product_panels_for(selected_products)
selected_products.map do |product|
product_panels.find { |panel| panel.product.to_s == product }
end.
compact
end
def product_panels
[ProductPanel.new(:iphone), ProductPanel.new(:ipad), ProductPanel.new(:ibidet)]
end
end
ProductPresenter.new.product_panels_for(['ipad', 'iphone']) # => [<ProductPanel product=:ipad>, <ProductPanel product=:iphone>]
</code></pre>
<p>This is obviously simplified, but the point is <code>#product_panels_for</code> should return values from <code>product_panels</code> but in the order given in <code>selected_panels</code>. Maybe this is fine is just feels a bit gangly for something that seems conceptually simpler than that.</p>
<p>To be clear the order is defined by the business, it won't be alphabetical or anything nice.</p>
<p>In case anyone's thinking it, yes, I know in Ruby 2.7 I could replace <code>.map...compact</code> with <code>.filter_map</code>, but I'm not on 2.7 yet.</p>
<p>My previous implementation was:</p>
<pre><code>def product_panels_for(selected_products)
product_panels.select { |pp| selected_products.include?(pp) }
end
</code></pre>
<p>which was nice and clean but didn't preserve the order of selected_products. </p>
<p>If the implementation at the top can't be improved on, is there a nice way to use this previous implementation but chain something after the select that sorts the result so the order matches <code>selected_products</code>? I'm just generally curious about a good way to cleanly sort A so its order matches B where B is a list of values for an attributes of A.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-03T01:29:18.467",
"Id": "470475",
"Score": "0",
"body": "Did you notice that if you have duplicate products you only get one product panel? If you are assuming a 1-to-` relationship then that's probably fine..."
}
] | [
{
"body": "<p>Your solution looks good to me, I tried some alternatives but they end up being a little more verbose and not adding value that makes it worth.</p>\n\n<p>Also, I don't think it is worth adding one more step to order it just to use <code>select</code>.</p>\n\n<p>I would go with your first solution.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-15T20:08:03.270",
"Id": "240588",
"ParentId": "239126",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T01:16:59.200",
"Id": "239126",
"Score": "1",
"Tags": [
"ruby"
],
"Title": "Return values from array A in the order they are in array B"
} | 239126 |
<p><strong>My Solution</strong></p>
<p>What I am looking for:</p>
<ol>
<li>DRY Code - in my handleDeleteBook and handleToggleStatus methods I felt that I couldn't find a way to share the id between the methods. Furthermore, what other sections of the code need to be DRY?</li>
<li>MVC Pattern - this was my first time using the MVC pattern so I don't know if I did it correctly and also I used OOJS for this but I don't know if I should've used factories and modules.</li>
<li>Better code - what code could be better? For example, II think I could've used a closure for my generateBookComponent but instead, I wipe the book components from the DOM and render them again so I don't have duplicates in the DOM.</li>
</ol>
<p><strong>Disclaimer</strong></p>
<p>I did get my library project reviewed before but I wanted to see how much I improved.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const Model = function() {
this.books = [];
};
Model.prototype.addBook = function(
bookTitle,
bookAuthor,
bookPage,
bookStatus
) {
const book = {
id:
this.books.length > 0
? this.books[this.books.length - 1].id + 1
: 0,
title: bookTitle,
author: bookAuthor,
page: bookPage,
status: bookStatus,
};
this.books.push(book);
};
Model.prototype.deleteBook = function(id) {
return (this.books = this.books.filter(bookId => bookId.id !== id));
};
Model.prototype.toggleStatus = function(id, updatedText) {
return (this.books[id].status = updatedText);
};
const View = function() {
this.modal = document.querySelector('.modal');
this.statusText = {
read: 'Read',
unread: 'Unread',
};
};
View.prototype.InputValues = function() {
return {
titleInput: document.getElementById('title').value,
authorInput: document.getElementById('author').value,
currentPage: Number(document.getElementById('pages').value),
statusOption: document.getElementById('status').value,
};
};
View.prototype.resetInput = function() {
document
.querySelectorAll('.modal__input')
.forEach(input =>
input.value !== '' ? (input.value = '') : input.value
);
};
View.prototype.setModal = function(stateModal) {
if (stateModal) {
this.modal.style.display = 'flex';
} else {
this.modal.style.display = 'none';
}
};
View.prototype.toggleStatus = function() {
if (event.target.textContent === this.statusText.read) {
event.target.classList.remove('status__btn--change');
event.target.textContent = this.statusText.unread;
} else {
event.target.classList.toggle('status__btn--change');
event.target.textContent = this.statusText.read;
}
return event.target.textContent;
};
View.prototype.deleteBook = function() {
event.target.parentNode.parentNode.remove();
};
View.prototype.getId = function() {
return Number(event.target.parentNode.parentNode.dataset.id);
};
View.prototype.generateBookComponent = function(library) {
let htmlTemplate = library.map(library => {
return `
<tr class="bookshelf__book" data-id="${library.id}">
<td class="title">${library.title}</td><td class="author">${
library.author
}</td><td class="pages">${
library.page
}</td><td class="status"><button class="${
library.status === 'Read'
? 'status__btn status__btn--change'
: 'status__btn'
}" >${
library.status === this.statusText.read
? this.statusText.read
: this.statusText.unread
}</button></td><td class="delete"><button class="btn btn--primary">x</button></td>
</tr>`;
});
return htmlTemplate.join('');
};
View.prototype.clearBooksDom = function() {
const bookshelf = document.querySelectorAll('.bookshelf__book');
bookshelf.forEach(bookHTML => bookHTML.remove());
};
View.prototype.render = function(component) {
const bookshelf = document.querySelector('.bookshelf__creation');
bookshelf.insertAdjacentHTML('beforeend', component);
};
const Controller = function(Model, View) {
this.Model = Model;
this.View = View;
};
const app = new Controller(new Model(), new View());
Controller.prototype.handleAddBook = function() {
const {
titleInput,
authorInput,
currentPage,
statusOption,
} = this.View.InputValues();
this.Model.addBook(titleInput, authorInput, currentPage, statusOption);
};
Controller.prototype.handleDeleteBook = function() {
let id = this.View.getId();
this.View.deleteBook();
this.Model.deleteBook(id);
};
Controller.prototype.handleToggleStatus = function() {
let id = this.View.getId();
let status = this.View.toggleStatus();
this.Model.toggleStatus(id, status);
};
Controller.prototype.handleModal = function(state) {
this.View.setModal(state);
this.View.resetInput();
};
Controller.prototype.startRender = function() {
const bookComponent = this.View.generateBookComponent(this.Model.books);
this.View.clearBooksDom();
this.View.render(bookComponent);
};
document
.querySelector('.bookshelf__open-modal')
.addEventListener('click', () => {
// - invoke handleModal()
app.handleModal(true);
});
document.querySelector('.modal__add').addEventListener('click', event => {
// - grab input values from array and store in book array
app.handleAddBook();
// - modal is gone
app.handleModal(false);
// - render books from book array
app.startRender();
});
document.querySelector('.modal__cancel').addEventListener('click', () => {
app.handleModal(false);
});
window.addEventListener('click', event => {
if (event.target.classList.contains('btn--primary')) app.handleDeleteBook();
if (event.target.classList.contains('status__btn')) app.handleToggleStatus();
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
margin: 0;
padding: 0;
-webkit-box-sizing: border-box;
box-sizing: border-box;
font-family: 'Roboto', sans-serif;
}
.background {
padding: 2% 4%;
margin-bottom: 2em;
height: 12rem;
width: 100%;
color: #fff;
background: linear-gradient(304deg, #020024 0%, #3a3d3d 0%, #282828 94%);
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-direction: column;
flex-direction: column;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
}
.background__heading {
margin-bottom: 0.2em;
font-size: 2.5rem;
}
.bookshelf {
max-width: 90%;
margin: 0 auto;
position: relative;
}
.bookshelf__heading {
font-size: 2rem;
font-weight: 700;
}
.bookshelf__creation {
text-align: left;
}
.bookshelf table {
border-collapse: collapse;
margin: 2em 0;
}
.bookshelf table th {
padding: 0.6em 1em;
}
.bookshelf__book {
border-top: 2px solid #ececec;
}
.bookshelf__book td {
padding: 1em;
text-align: left;
}
.bookshelf__open-modal {
padding: 0.7rem;
border: none;
background-color: #383838;
color: white;
cursor: pointer;
position: absolute;
right: 0;
top: 0;
}
.status__btn {
padding: 0.4rem 2rem;
border: none;
background-color: #ececec;
cursor: pointer;
}
.status__btn--change {
background-color: #383838;
color: white;
}
.delete .btn {
cursor: pointer;
width: 1.5rem;
height: 1.5rem;
color: white;
border-radius: 50%;
text-align: center;
border: none;
font-weight: 700;
-webkit-transition: background-color 0.5s ease-in-out;
transition: background-color 0.5s ease-in-out;
}
.delete .btn:hover {
background-color: #383838;
}
.modal {
padding: 1.25rem;
width: 100%;
position: absolute;
top: 0;
background: white;
max-width: 50%;
margin: 0 auto;
-webkit-transform: translate(50%, 20%);
transform: translate(50%, 20%);
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-align: center;
-ms-flex-align: center;
align-items: center;
-webkit-box-pack: center;
-ms-flex-pack: center;
justify-content: center;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-ms-flex-direction: column;
flex-direction: column;
border-radius: 6px;
-webkit-box-shadow: 0 0.5em 1em -0.125em rgba(10, 10, 10, 0.1), 0 0 0 1px rgba(10, 10, 10, 0.02);
box-shadow: 0 0.5em 1em -0.125em rgba(10, 10, 10, 0.1), 0 0 0 1px rgba(10, 10, 10, 0.02);
color: #4a4a4a;
display: none;
}
.modal .modal__add {
padding: 0.7rem;
border: none;
background-color: #383838;
color: white;
cursor: pointer;
}
.modal .modal__cancel {
padding: 0.7rem;
border: 1.5px solid lightgray;
border-radius: 5px;
background-color: #fff;
cursor: pointer;
}
.modal h2 {
margin-bottom: 1em;
}
.modal * {
-ms-flex-item-align: self-start;
-ms-grid-row-align: self-start;
align-self: self-start;
}
.modal label {
font-size: 1rem;
font-weight: 600;
margin-bottom: 0.4em;
}
.modal input {
width: 100%;
margin-bottom: 1em;
height: 3em;
border: 1.5px solid lightgray;
border-radius: 5px;
}
.modal select {
width: 6rem;
height: 2rem;
border: 1.5px solid lightgray;
border-radius: 5px;
background-color: #fff;
margin-bottom: 1em;
cursor: pointer;
}
tbody:nth-child(even) {
background-color: whitesmoke;
border-top: 1px solid #a0a0a0;
}
/*# sourceMappingURL=index.css.map */</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Librario</title>
<!-- links -->
<link href="https://fonts.googleapis.com/css?family=Roboto:400,700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="./index.css">
</head>
<body>
<div class="container">
<header class="background">
<h1 class="background__heading">Librario</h1>
<p class="background__intro-text">Your Pocket Bookshelf</p>
</header>
<div class="bookshelf">
<h2 class="bookshelf__heading">Books</h2>
<table class="bookshelf__creation">
<tr class="table">
<th class="table__heading">Title</th>
<th class="table__heading">Author</th>
<th class="table__heading">Pages</th>
<th class="table__heading">Status</th>
</tr>
<!-- <!-- <tr class="bookshelf__book" data-newBook="">
<td class="title">Harry Potter and the Sorceror Stone</td>
<td class="author">J.K Rowling</td>
<td class="pages">890</td>
<td class="status"><button class="status__btn">Read</button></td>
<td class="delete"><button class="btn btn--primary">x</button></td>
</tr> -->
</table>
<button class="bookshelf__open-modal">Add New Book</button>
</div>
<div class="modal">
<h2>Add New Book</h2>
<label for="title">Title</label>
<input class="modal__input" id="title" type="text">
<label for="author">Author</label>
<input class="modal__input" id="author" type="text">
<label for="pages">Number of Pages</label>
<input class="modal__input" id="pages" type="text">
<label for="status">Read Status</label>
<select id="status">
<option value="Read">Read</option>
<option value="Unread">Unread</option>
</select>
<div class="modal__btn-container">
<button class="modal__add">Add Book</button>
<button class="modal__cancel">Cancel</button>
</div>
</div>
</div>
<!-- Scripts -->
<script src="./index.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T02:54:27.680",
"Id": "239129",
"Score": "1",
"Tags": [
"javascript",
"object-oriented",
"mvc"
],
"Title": "**Refactored** Library project"
} | 239129 |
<p>I'm trying to optimize my code or see if there's a better way to do it. Given values for <code>acctData</code> and balances below, I need to return an array of accounts filtered by the user name.</p>
<pre><code>const acctData = [
{
acctNum: "AAA - 1234",
user: "Alice"
},
{
acctNum: "AAA - 5231",
user: "Bob"
},
{
acctNum: "AAA - 9921",
user: "Alice"
},
{
acctNum: "AAA - 8191",
user: "Alice"
}
];
const balance = {
"AAA - 1234": 4593.22,
"AAA - 9921": 0,
"AAA - 5231": 232142.5,
"AAA - 8191": 4344
};
const combinedAccBalance = JSON.parse(JSON.stringify(acctData));
const getAccountNumbers = (filterByUser) => {
return combinedAccBalance
.filter(acc => {
acc.balance = balance[acc.acctNum];
return acc.user === filterByUser;
}).sort((a, b) => {
return a.balance - b.balance;
})
.map(fa => {
return fa.acctNum;
});
};
getAccountNumbers("Alice");
//Returns
["AAA - 9921", "AAA - 8191", "AAA - 1234"]
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T06:17:23.470",
"Id": "239132",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Filtering and sorting for account data"
} | 239132 |
<p><a href="https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/" rel="nofollow noreferrer">https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/</a></p>
<blockquote>
<p>Given a non-negative integer num, return the number of steps to reduce
it to zero. If the current number is even, you have to divide it by 2,
otherwise, you have to subtract 1 from it.</p>
<p>Example 1:</p>
<p>Input: num = 14 Output: 6 Explanation: Step 1) 14 is even; divide by
2 and obtain 7. Step 2) 7 is odd; subtract 1 and obtain 6. Step 3) 6
is even; divide by 2 and obtain 3. Step 4) 3 is odd; subtract 1 and
obtain 2. Step 5) 2 is even; divide by 2 and obtain 1. Step 6) 1 is
odd; subtract 1 and obtain 0. Example 2:</p>
<p>Input: num = 8 Output: 4 Explanation: Step 1) 8 is even; divide by 2
and obtain 4. Step 2) 4 is even; divide by 2 and obtain 2. Step 3) 2
is even; divide by 2 and obtain 1. Step 4) 1 is odd; subtract 1 and
obtain 0. Example 3:</p>
<p>Input: num = 123 Output: 12 </p>
<p>Constraints:</p>
<p>0 <= num <= 10^6</p>
</blockquote>
<pre><code> public int NumberOfSteps (int num) {
int count = 0;
while( num !=0)
{
if(num %2==0)
{
num = num/2;
count++;
}
else
{
if( num == 1)
{
return count+1;
}
num = num-1;
count++;
}
}
return count;
}
</code></pre>
<p>Please review for performance</p>
| [] | [
{
"body": "<p>Not much to say for such a simple algorithm. However there is an optimization that you could employ. Check for odd instead of even, then convert to even. Then divide by 2. At most this cuts your iterations by half.</p>\n\n<p>It would look like this:</p>\n\n<pre><code>public int NumberOfSteps(int num)\n{\n int count = 0;\n while (num != 0)\n {\n if(num % 2 == 1)\n {\n num -= 1;\n ++count;\n }\n if(num > 0)\n {\n num /= 2;\n ++count;\n }\n }\n return count;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T00:55:02.167",
"Id": "239162",
"ParentId": "239134",
"Score": "4"
}
},
{
"body": "<p>You need to guard against a negative <code>num</code>, or else your algorithm will run infinitely (<code>num = num - 1)</code>.</p>\n\n<hr>\n\n<p>Dividing <code>36</code> and <code>37</code> with <code>2</code> are both <code>18</code> with reminders of <code>0</code> and <code>1</code>. So it should be possible to keep dividing by <code>2</code> and adding the reminder, in order to add <code>1</code> for odd and <code>0</code> for even numbers:</p>\n\n<pre><code>public int Review(int num)\n{\n if (num == 0) return 0;\n\n int result = 0;\n\n while (num != 0)\n {\n result += 1 + (num & 1);\n num /= 2;\n }\n\n // The last iteration will always be 1 / 2 which shouldn't be counted.\n result--;\n\n return result;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T12:55:19.283",
"Id": "469168",
"Score": "0",
"body": "I reviewed your review :) see my answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T12:58:33.860",
"Id": "469170",
"Score": "0",
"body": "@potato: I've seen it - elegant - I have upvoted :-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T08:37:10.347",
"Id": "239174",
"ParentId": "239134",
"Score": "3"
}
},
{
"body": "<p>My answer is an upgrade of Henrik's answer. (so it's a review of a review lol)</p>\n\n<p>Dividing an <code>int</code> by 2 is the same as shifting the bits 1 to the right. I'd expect a good compiler to make such optimizations automatically, but I think it's still worth mentioning.</p>\n\n<p>I got rid of the if statement at the start, which in most cases (non 0 input) is a waste of time. The <code>do...while</code> removes the need for handling the 0 case differently.</p>\n\n<p>I start the count from -1 to not have to do a subtraction in the end.</p>\n\n<p>Having a <code>do...while</code> loop means one less execution of the while conditional statement, and I also put the bit shift there to not run it more times than necessary.</p>\n\n<pre><code>public int countSteps(int num)\n{\n int count = -1;\n do\n {\n count += 1 + (num & 1);\n } while ( (num >>= 1) != 0);\n return count;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T11:40:05.557",
"Id": "239181",
"ParentId": "239134",
"Score": "2"
}
},
{
"body": "<p>I went a bit crazy about it just for fun, and found a solution that is much more efficient than a loop :)</p>\n\n<p>If you look at the bits as the game progresses, you can reframe the problem. Subtracting 1 from an odd number is flipping the right-most bit from 1 to 0. Dividing by 2 is shifting the bits 1 place to the right.</p>\n\n<p>Example in binary:</p>\n\n<pre><code>1001101\n</code></pre>\n\n<p>There are four 1-bits, which means 4 subtractions of 1. The left most 1 bit is in the 7th position, which means 6 divisions by 2. There is an exception to this rule when the input is 0, so this is the (almost) final formula:</p>\n\n<pre><code>if (num == 0) return 0;\nreturn (number of 1-bits) + (number of bits to the right of the left-most 1-bit);\n</code></pre>\n\n<p>A <a href=\"https://www.playingwithpointers.com/blog/swar.html\" rel=\"nofollow noreferrer\">genius SWAR algorithm</a> can be used to count the 1-bits:</p>\n\n<pre><code>public int BitCount(int x)\n{\n x -= (x >> 1) & 0x55555555;\n x = ((x >> 2) & 0x33333333) + (x & 0x33333333);\n return (((x >> 4) + x) & 0x0f0f0f0f) * 0x01010101 >> 24;\n}\n</code></pre>\n\n<p>To count the bits on the right of the left-most 1-bit, we can turn them all into 1s by overlapping the number (<code>|</code> operator) with bit shifts of itself:</p>\n\n<pre><code>public int FillGaps(x)\n{\n x |= x >> 1;\n x |= x >> 2;\n x |= x >> 4;\n x |= x >> 8;\n return x | x >> 16;\n}\n</code></pre>\n\n<p>The final function is:</p>\n\n<pre><code>public int CountSteps_NoLoop(int num)\n{\n if(num == 0) return 0;\n return BitCount(num) + BitCount(FillGaps(num)) - 1;\n}\n</code></pre>\n\n<p>There is one more thing that can be done to make the function even faster: because this function is so complicated with lots of bitwise operations, it is slower than a loop for small numbers, so you can do something like this:</p>\n\n<pre><code>public int CountSteps(int num)\n{\n const int TIPPING_POINT = 32; // or 16 with Roslyn 3.4 compiler (according to my benchmarks)\n if(num < TIPPING_POINT)\n {\n return CountSteps_Loop(num); // method from my other answer\n }\n else\n {\n return CountSteps_NoLoop(num);\n }\n}\n</code></pre>\n\n<p>Since I already went this far, why not go all the way and avoid function calls and variable declarations (who needs meaningful names):</p>\n\n<pre><code>public int CountSteps(int x)\n{\n if(x < 32)\n {\n int c = -1;\n do\n {\n c += 1 + (x & 1);\n } while ( (x >>= 1) != 0);\n\n return c;\n }\n else\n {\n int s = x - ((x >> 1) & 0x55555555);\n s = ((s >> 2) & 0x33333333) + (s & 0x33333333);\n\n x |= x >> 1; \n x |= x >> 2;\n x |= x >> 4;\n x |= x >> 8;\n x |= x >> 16;\n\n x -= (x >> 1) & 0x55555555;\n x = ((x >> 2) & 0x33333333) + (x & 0x33333333);\n\n return ((((s >> 4) + s) & 0x0f0f0f0f) * 0x01010101 >> 24)\n + ((((x >> 4) + x) & 0x0f0f0f0f) * 0x01010101 >> 24) - 1;\n }\n}\n</code></pre>\n\n<h2>Update: more optimizations!</h2>\n\n<p>The main reason I kept the if statement until now is not to speed up the case of 16 smallest numbers, that was just an opportunity to make better use of an if statement that I needed anyway to take care of the case of 0 input. Now I got rid of this if statement and instead of subtracting 1 from the bit count at the end (which created the exception for 0), I shift one bit off of the number before counting the bits (2nd line inside the function). Also according to my benchmarks this shift is faster than subtracting 1 in the end.</p>\n\n<p>I also optimized the return statement by adding both bit counts as early as possible before finishing the count (see the 2nd last line).</p>\n\n<pre><code>public int CountSteps(int x)\n{\n int s = x - ((x >> 1) & 0x55555555);\n x = (x >> 1) | (x >> 2);\n x |= x >> 2;\n x |= x >> 4;\n x |= x >> 8;\n x |= x >> 16;\n x -= (x >> 1) & 0x55555555;\n x = ((x >> 2) & 0x33333333) + (x & 0x33333333)\n + ((s >> 2) & 0x33333333) + (s & 0x33333333);\n return (((x >> 4) & 0x0f0f0f0f) + (x & 0x0f0f0f0f)) * 0x01010101 >> 24;\n}\n</code></pre>\n\n<p>Benchmarking: (with the highest 40 million values of <code>int</code> as function input)</p>\n\n<ul>\n<li>code with loop: 3.89s</li>\n<li>my fancy code: 0.48s</li>\n<li>with processor instructions: 0.38s</li>\n</ul>\n\n<p>The performance gap will grow if the functions are extended to handle <code>long</code>s, because it's O(1) vs O(n).</p>\n\n<hr>\n\n<p>Using hardware instructions is the fastest, and makes much clearer code:</p>\n\n<pre><code>public int CountSteps(int x)\n{\n return 32 - BitOperations.LeadingZeroCount((uint)x >> 1)\n + BitOperations.PopCount((uint)x);\n}\n</code></pre>\n\n<p>But implementing it without these instructions makes a much more enjoyable challenge.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T16:34:36.520",
"Id": "239197",
"ParentId": "239134",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "239197",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T08:18:22.773",
"Id": "239134",
"Score": "3",
"Tags": [
"c#",
"programming-challenge"
],
"Title": "LeetCode: Number of steps to reduce a number to zero C#"
} | 239134 |
<p>I am trying to find <code>missing positive integer in an. array</code>.I don't know where my function not working ?</p>
<p>question given </p>
<p><strong>Given an unsorted integer array, find the first missing positive integer.</strong></p>
<pre><code>Given [1,2,0] return 3,
[3,4,-1,1] return 2,
[-8, -7, -6] returns 1
</code></pre>
<p>my function works on following above cases works fine..</p>
<pre><code>let firstMissingPositive = function(A){
if(A.length === 1 && A[0] < 0){
return 1
}
let j=0;
for (let i = 0; i < A.length; i++) {
if(A[i] < 0){
let temp = A[j]
A[j] = A[i]
A[i] = temp;
j++;
}
}
let arr =A.slice(j);
for (let i = 0; i < arr.length; i++) {
if (arr[(arr[i]) - 1] > 0) {
arr[(arr[i]) - 1] = -arr[(arr[i]) - 1]
}
}
let k=0;
while (true){
if(arr[k]>0 || k >= arr.length){
break;
}
k++
}
return ++k
}
</code></pre>
<p>**but fails in this case **
when input is this. </p>
<pre><code>[ 463, 127, 436, 72, 79, 301, 613, 898, 675, 960, 832, 486, 453, 274, 133, 721, 750, 538, 545, 112, 414, 817, 885, 812, 906, 577, 544, 101, 165, 45, 489, 503, 479, 293, 234, 427, 347, 851, 316, 827, 209, 578, 255, 56, 608, 914, 156, 537, 870, 567, 284, 240, 292, 111, 590, 713, 110, 768, 598, 879, 980, 660, 46, 320, 410, 869, 154, 970, 836, 423, 413, 501, 782, 403, 561, 117, 624, 638, 67, 646, 917, 379, 344, 543, 978, 506, 936, 947, 645, 633, 375, 706, 531, 470, 551, 632, 536, 642, 573, 705, 823, 897, 26, 476, 139, 496, 628, 91, 725, 570, 701, 244, 935, 126, 2, 560, 726, 20, 680, 7, 888, 183, 80, 804, 729, 583, 728, 515, 644, 774, 856, 192, 386, 25, 57, 471, 482, 174, 627, 757, 714, 203, 206, 847, 245, 336, 989, 326, 607, 95, 69, 71, 54, 975, 366, 591, 185, 964, 848, 84, 819, 737, 687, 215, 904, 651, 289, 134, 232, 341, 932, 64, 483, 128, 901, 808, 896, 941, 530, 195, 865, 903, 472, 508, 42, 971, 53, 86, 689, 925, 685, 934, 549, 841, 169, 317, 826, 600, 950, 90, 495, 219, 674, 814, 359, 556, 269, 187, 517, 541, 558, 8, 744, 958, 332, 163, 862, 218, 376, 23, 321, 346, 534, 864, 157, 285, 318, 200, 595, 810, 43, 32, 368, 753, 670, 887, 238, 1000, 513, 979, 499, 708, 473, 584, 981, 106, 695, 868, 881, 610, 273, 239, 190, 281, 373, 247, 364, 396, 837, 521, 871, 528, 617, 123, 894, 965, 108, 976, 451, 454, 673, 910, 681, 300, 702, 703, 307, 196, 535, 407, 763, 966, 945, 944, 65, 752, 776, 973, 554, 3, 998, 559, 35, -3, 147, 395, 761, 442, 586, 899, 191, 990, 606, 771, 393, 649, 987, 593, 877, 527, 201, 259, 150, 683, 263, 330, 21, 105, 406, 233, 303, 254, 33, 417, 497, 622, 286, 9, 967, 603, 78, 118, 304, 235, 985, 657, 741, 425, 995, 592, 844, 933, 99, 524, 418, 623, 529, 797, 342, 217, 580, 691, 772, 13, 390, 666, 87, 448, 505, 907, 765, 802, 484, 419, 669, 780, 96, 585, 796, 686, 302, 858, 388, 438, 893, 735, 360, 913, 902, 279, 720, 408, 287, 996, 507, 28, 416, 731, 928, 977, 547, 739, 788, 168, 331, 146, 664, 619, 723, 732, 102, 14, 424, 216, 575, 568, 93, 992, 272, 160, 389, 47, 647, 189, 988, 343, 991, 940, 358, 181, 611, 229, 265, 892, 422, 211, 443, 747, 736, 266, 652, 351, 612, 514, 876, 637, 329, 474, 68, 730, 825, 676, 778, 208, 956, 270, 398, 968, 268, 594, 288, 385, 866, 197, 428, 441, 672, 158, 618, 811, 363, 905, 462, 241, 226, 450, 309, 170, 822, 727, 333, 335, 92, 540, 202, 205, 115, 153, 569, 142, 290, 943, 394, 248, 228, 643, 415, 784, 579, 571, 291, 177, 711, 149, 130, 921, 922, 439, 951, 338, 769, 283, 308, 857, 253, 833, 490, 824, 518, 525, 131, 924, 27, 830, 915, 237, 694, 581, 609, 19, 152, 566, 465, 140, 81, 313, 969, 327, 6, 526, 135, 186, 656, 662, 155, 874, 648, 488, 199, 677, 952, 614, 722, 369, 682, 129, 478, 433, 809, 891, 717, 550, 748, 0, 323, 469, 151, 41, 299, 193, 487, 931, 634, 400, 799, 884, 405, 480, 76, 805, 926, 426, 312, 821, 178, 789, 449, 697, 853, 295, 48, 224, 397, 447, 946, 49, 382, 236, 867, 485, 349, 231, 227, 39, 38, 882, 210, 457, 222, 852, 665, 138, 455, 114, 204, 498, 511, 230, 509, 278, 365, 831, 412, 5, 816, 1, 324, 194, 464, 141, 420, 795, 839, 641, 10, 777, 15, 519, 829, 961, 109, 31, -5, 63, 421, 77, 430, 542, 452, 256, 355, 357, 704, 434, 459, 262, 132, 863, 468, 929, 716, 564, 890, 616, 855, 845, 548, 143, 145, 707, 787, 948, 11, 872, 61, 909, 762, 639, 786, 350, 136, 972, 75, 605, 354, 339, 305, 754, 755, 658, 40, 319, 620, 679, 984, 252, 477, 432, 684, 766, 280, 912, 949, 328, 834, 522, 310, 920, 546, 770, 214, 962, 678, 760, 916, -4, 401, 12, 957, 806, 791, 261, 277, 372, 17, 85, 982, 97, 125, 698, 399, 381, 655, 315, 182, 923, 886, 440, 223, 387, 173, 663, 588, 122, 113, 98, 803, 353, 668, 311, 587, 444, 636, 939, 429, 790, 718, 938, 738, 50, 362, 435, 813, 908, 650, 843, 959, 460, 849, 167, 384, 348, 467, 337, 356, 724, 516, 121, 880, 667, 779, 709, 986, 751, 51, 781, 659, 794, 653, 635, 553, 60, 322, 352, 696, 392, 250, 119, 431, 746, 164, 107, 563, 461, 532, 712, 391, 840, 380, 801, 574, 900, 576, 640, 378, 963, 601, 267, 207, 370, 225, 260, 500, 883, 159, 58, 166, 745, 179, 251, 271, 294, 257, 631, 895, 604, 828, 953, 520, 16, 818, 539, 491, 120, 875, 89, 692, 458, 552, 599, 861, 492, 74, 699, 55, 475, 345, 24, 700, 889, 937, 785, 758, 983 ]
</code></pre>
<p>expected output is <code>4</code></p>
<p>and my output is <code>1</code></p>
<p>here is my code
<a href="https://jsbin.com/poduqayime/2/edit?html,js,console,output" rel="nofollow noreferrer">https://jsbin.com/poduqayime/2/edit?html,js,console,output</a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T09:07:19.560",
"Id": "469047",
"Score": "0",
"body": "Your *question*, cross-posted from [stackoverflow](https://stackoverflow.com/questions/60753448/first-missing-positive-integer-in-an-array-using-javascript), isn't going to work here, as [only working code is on-topic](https://codereview.stackexchange.com/help/on-topic)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T09:26:55.543",
"Id": "469048",
"Score": "0",
"body": "@greybeard but it is working for few inputs ..not for all"
}
] | [
{
"body": "<p>I didn't analyse your code but this code returns expected values:</p>\n\n<pre><code>const firstMissingPositive = (arr) => {\n const arrSorted = arr.filter( val => val > 0 ).sort( (a,b) => a - b );\n const length = arrSorted.length;\n if (length === 0) return 1;\n\n for ( let i=0; i < length; i++ ){\n if ( arrSorted[i] + 1 !== arrSorted[i + 1] ) {\n return arrSorted[i] + 1\n }\n }\n}\n</code></pre>\n\n<p>Initially you can <code>.filter</code> positive values and <code>.sort</code> the array by the use of:</p>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\" rel=\"nofollow noreferrer\">Array.filter</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort\" rel=\"nofollow noreferrer\">Array.sort</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T18:34:59.333",
"Id": "239202",
"ParentId": "239135",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T09:01:56.010",
"Id": "239135",
"Score": "-1",
"Tags": [
"javascript",
"algorithm"
],
"Title": "first missing positive integer in an array using javascript?"
} | 239135 |
<p><a href="https://leetcode.com/problems/sum-of-two-integers/" rel="nofollow noreferrer">https://leetcode.com/problems/sum-of-two-integers/</a></p>
<blockquote>
<p>Calculate the sum of two integers a and b, but you are not allowed to
use the operator + and -.</p>
<p>Example 1:</p>
<p>Input: a = 1, b = 2 Output: 3 Example 2:</p>
<p>Input: a = -2, b = 3 Output: 1</p>
</blockquote>
<pre><code>using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace MathQuestions
{
/// <summary>
/// https://leetcode.com/problems/sum-of-two-integers/
/// </summary>
[TestClass]
public class SumOfTwoIntegersTest
{
[TestMethod]
public void ExampleTest()
{
int a = 1;
int b = 2;
int expected = 3;
Assert.AreEqual(expected, GetSum(a,b));
}
[TestMethod]
public void ExampleTest2()
{
int a = 5;
int b = 7;
int expected = 12;
Assert.AreEqual(expected, GetSum(a, b));
}
public int GetSum(int a, int b)
{
if (a == 0) return b;
if (b == 0) return a;
while (b != 0)
{
int carry = a & b;
a = a ^ b;
b = carry << 1;
}
return a;
}
}
}
</code></pre>
<p>Please review for performance</p>
| [] | [
{
"body": "<p>Your code is pretty much perfect, the only problem is that you chose to sacrifice some performance in most cases (non 0 operands) for the sake of making the rare case faster. Here's a slight improvement based on the assumption that most of the times none of the operands will be 0.</p>\n\n<p>The trick is to keep it efficient in the case of 0 without wasting time on special checks that don't help the actual calculation. If the carry is 0 then you know you're done. Storing the output (<code>a ^ b</code>) in the same variable removes the need for an if statement for returning <code>b</code> instead of <code>a</code>.</p>\n\n<p>Also 1 bitwise operation and assignment is saved by shifting the carry at the start of the loop, so there is no extra unused shift at the end. (note: it would slow the function down in case of overflow, but that's a rare case and it's expected that the programmer will avoid overflow anyway)</p>\n\n<pre><code>public int GetSum(int a, int b)\n{\n int carry = a & b;\n a = a ^ b;\n\n while (carry != 0)\n {\n b = carry << 1;\n carry = a & b;\n a = a ^ b;\n }\n\n return a;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T07:56:36.860",
"Id": "239172",
"ParentId": "239136",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "239172",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T09:21:38.793",
"Id": "239136",
"Score": "1",
"Tags": [
"c#",
"programming-challenge",
"bitwise"
],
"Title": "LeetCode: Sum of Two Integers C#"
} | 239136 |
<p>In rust fp-core crate there is a compose function, but it is very limited for my liking.<br>
So I made a macro which uses the function composition syntax of Haskell.<br>
I would like to know why fp-core didn't do something like this in the first place? </p>
<p>What advice would you give me since this is the first macro I ever wrote in rust.</p>
<p>Here is my code:</p>
<pre><code>#[macro_export]
macro_rules! compose {
// end
(@inner . $g:ident $e:expr) =>
{
$g($e)
};
(@inner . ( $g:ident $($param:expr),+ ) $e:expr) =>
{
$g ( $( $param ),+ , $e )
};
// middle
(@inner . ( $f:ident $($param:expr),+ ) $( $gs:tt )* ) =>
{
$f( $( $param ),+ , compose!{ @inner $( $gs )* } )
};
(@inner . $f:ident $( $gs:tt )* ) =>
{
$f( compose!{ @inner $( $gs )* } )
};
//start
( $f:ident $( $tokens:tt )* ) =>
{
$f(compose!{ @inner $( $tokens )* } )
};
( ( $f:ident $( $param:expr ),+ ) $( $tokens:tt )* ) =>
{
$f( $( $param ),+ , compose!{ @inner $( $tokens )* } )
};
}
#[cfg(test)]
mod compose_tests {
fn add_3(x:u32) -> u32 {
x + 3
}
fn double(x:u32) -> u32 {
x * 2
}
fn my_add(x :u32, y :u32) -> u32
{
x + y
}
#[test]
fn simple_test() {
assert_eq!(compose!{double . add_3 2}, 10);
}
#[test]
fn double_a_lot() {
assert_eq!(compose!{double . double . double . double . double . double . double 1}, 128);
}
#[test]
fn simple_partial_app() {
let mut x = compose!{double . (my_add 2) 1};
assert_eq!(x, 6);
x = compose!{(my_add 2) . double 1};
assert_eq!(x, 4);
x = compose!{double . (my_add 2) . double 1};
assert_eq!(x, 8);
x = compose!{(my_add 2) . double . double 1};
assert_eq!(x, 6);
x = compose!{double . double . (my_add 1) 1};
assert_eq!(x, 8);
x = compose!{(my_add 2) . (my_add 2) . double 1};
assert_eq!(x, 6);
x = compose!{(my_add 2) . (my_add 2) . (my_add 1) 1};
assert_eq!(x, 6);
}
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T09:47:38.577",
"Id": "239137",
"Score": "3",
"Tags": [
"rust"
],
"Title": "Function composition in rust"
} | 239137 |
<p>I'm looking for some fresh ideas on how to optimize a couple of functions in my C++ code. I run the code through a profiler and it shows that they take 20% and 40% of the time respectively. The functions are called many times as they live inside a triple nested loop (cannot be avoided).</p>
<p>The <code>blip3_inner(args...)</code> (20% of the time) is a follows:</p>
<pre><code> void PairBlip::blip3_inner(int &i, int &j, int &k, int &e,double g[][2][3],
double gp[][2][3] ,double &blip_ijk, double coef[2])
{
double f[3][2][3];
for (int d=0; d<3; ++d)
for (int a=0; a<2; ++a)
for (int b=0; b<3; ++b)
f[d][a][b] = gp[d][a][b] * blip_ijk - g[d][a][b] * coef[a];
blip3_dump(i,j,k,e,f);
}
</code></pre>
<p>and <code>blip3_dump(args...)</code> (40% of time) is:</p>
<pre><code> void PairBlip::blip3_dump(int &i, int &j, int &k, int &e, double f[][2][3])
{
for (int d=0; d<3; ++d)
{
for (int b=0; b<3; ++b)
{
force_fp[i][d][e+size2b+b*size_grid_3b] += f[d][0][b] + f[d][1][b];
force_fp[j][d][e+size2b+b*size_grid_3b] -= f[d][0][b];
force_fp[k][d][e+size2b+b*size_grid_3b] -= f[d][1][b];
}
}
}
</code></pre>
<p>The code is compiled with the following flags:</p>
<pre><code>-g -std=c++11 -O3 -ffast-math -march=native
</code></pre>
<p>The code will be used on range of architectures and the choice of compiler flags is really down to the end user.</p>
<p>The entire code is parallelized with MPI so above functions are computed by the single core.</p>
<p>For the second function, I tried to replace <code>force_fp</code> which is declared on the heap with an intermediate variable declared on the stack. While it improves things when compiling with <code>-O</code> any benefit disappears soon as <code>-O3</code> is used.</p>
<p>I would appreciate any ideas.</p>
<p><strong>Background</strong></p>
<p>I'm developing machine learning interatomic pair potential to work with <a href="https://lammps.sandia.gov/" rel="nofollow noreferrer">https://lammps.sandia.gov/</a>. The structure of the code is very similar to the classical three-body potentials such as Tersoff or Stillinger-Weber. The aforementioned code is called inside nested <code>i</code>, <code>j</code>, <code>k</code> loop where <code>i</code> goes over all atoms in a box, <code>j</code> and <code>k</code> overall nearest neighbors of <code>i</code>. It is what it is and there is no room for improvement here.</p>
<p><strong>Update</strong></p>
<p>I tried reducing a number of nested loops and improve caching in <code>blip3_inner()</code> by flattening <code>f[18]</code>,<code>g[18]</code>,<code>gp[18]</code> but it does not improve speed.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T12:10:13.433",
"Id": "469060",
"Score": "0",
"body": "Welcome to CodeReview@SE! I much like seeing a quantified motivation to try and reduce execution time in pieces of code presented upfront."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T12:13:29.103",
"Id": "469063",
"Score": "0",
"body": "(It *may* improve readability to enclose identifiers in `\\``\"*backticks*\" like *where `i` goes*.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T12:38:11.553",
"Id": "469070",
"Score": "1",
"body": "I have a nagging feeling that the performance problem may be in *upper level algorithm design* or *(\"bulk\")memory access pattern*: can you disclose more about the enclosing `triple nested loop`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T16:24:09.673",
"Id": "469099",
"Score": "0",
"body": "In my book, `compute g, gp, coeff (all depend on i, j, k)` didn't cut it, anyway: `blip_ijk` and `coef` don't change in `blip3_whatever()` - why aren't they already incorporated into `gp[][][]` and `g[][][]`? I could take educated guesses seeing the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T18:40:33.850",
"Id": "469110",
"Score": "0",
"body": "(One search I'd check for ideas: [Intel's take on n bodies](https://www.google.com/search?q=site:intel.com+\"n-body\").)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T21:32:03.660",
"Id": "469140",
"Score": "0",
"body": "@greybeard `blip_ijk` depends on `i` `j` `k` and `e` so cannot be incorporated into `g` and `gp`. `coef` depends on `blip_ijk` Tried to add code to my question but this is apparently against rules. For each `i` `j` `k` there is a vector calculated hence loop over `e`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T21:40:22.690",
"Id": "469143",
"Score": "0",
"body": "(Not to worry: guess [where I got](https://codereview.stackexchange.com/revisions/239139/6) above quote. As said before: not enough, anyway.)"
}
] | [
{
"body": "<p>Introduce a variable for <code>blip3_dump()</code>'s offset expression:</p>\n\n<pre><code> for (int b=0, e_size2b = e + size2b; b<3; ++b) {\n int offset = e_size2b + b * size_grid_3b;\n for (int d=0; d<3; ++d) {\n force_fp[i][d][offset] += f[d][0][b] + f[d][1][b];\n force_fp[j][d][offset] -= f[d][0][b];\n force_fp[k][d][offset] -= f[d][1][b];\n }\n }\n</code></pre>\n\n<p>Note how this has \"the <code>a</code>-loop\" unrolled - more obvious with separate <code>force_fp[i]</code> updates.<br>\nIn <code>PairBlip::blip3_inner()</code>, unroll the <code>a</code>-loop and swap iterating first&last index:</p>\n\n<pre><code> for (int b=0; b<3; ++b)\n for (int d=0; d<3; ++d) {\n f[d][0][b] = gp[d][0][b] * blip_ijk - g[d][0][b] * coef[0];\n f[d][1][b] = gp[d][1][b] * blip_ijk - g[d][1][b] * coef[1];\n }\n</code></pre>\n\n<p>This seems to suggest to replace <code>f[][][]</code> and associated indexing with <code>f0</code> and <code>f1</code>:</p>\n\n<pre><code>void blip3_inner(int i, int j, int k, int e_size2b,\n double g[][2][3], double gp[][2][3],\n double &blip_ijk, double coef[2])\n{\n for (int b=0; b<3; ++b) {\n int offset = e_size2b + b * size_grid_3b;\n for (int d=0; d<3; ++d) {\n double f0 = gp[d][0][b] * blip_ijk - g[d][0][b] * coef[0],\n f1 = gp[d][1][b] * blip_ijk - g[d][1][b] * coef[1];\n force_fp[i][d][offset] += f0 + f1;\n force_fp[j][d][offset] -= f0;\n force_fp[k][d][offset] -= f1;\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T22:02:42.440",
"Id": "469144",
"Score": "0",
"body": "@greybeard In fact couldn't wait till tomorrow. There is 6.5% gain in speed plus cleaner code. Thanks for that."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T12:31:53.960",
"Id": "239143",
"ParentId": "239139",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "239143",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T10:25:11.593",
"Id": "239139",
"Score": "3",
"Tags": [
"c++",
"performance",
"simulation",
"physics"
],
"Title": "Molecular dynamics simulation"
} | 239139 |
<p>This is my first static web project made from scratch without any external js libraries.</p>
<p>please review and let me know the improvement areas.</p>
<p>1, are my js functions upto mark? any performance issues are there?
2, are css styles properly refactored?
3, are html tags used fine? etc..</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/* dark mode code */
const darkModeButtonId = 'dark-mode-button';
function darkMode() {
let button = document.getElementById(darkModeButtonId);
document.body.className = 'body-dark';
button.innerHTML = '';
button.title = 'lights on';
}
function lightMode() {
let button = document.getElementById(darkModeButtonId);
document.body.className = 'body-light';
button.innerHTML = '';
button.title = 'dark mode';
}
function toggleDarkMode() {
if (document.body.className == 'body-light') {
darkMode()
//setModeInSession('dark');
} else {
lightMode()
//setModeInSession('light');
}
}
// to save the state of the mode to appear across pages in current browser session
function setModeInSession(value) {
if (sessionStorage.getItem('mode') != value) {
sessionStorage.setItem('mode', value);
}
}
function getModeFromSession() {
return sessionStorage.getItem('mode');
}
window.onload = function switchMode() {
//if (!(getModeFromSession() === null)) { //get the mode and apply for current page
//if (getModeFromSession() == 'dark') {
//darkMode()
//} else {
// lightMode()
// }
// } else { //if no mode in session apply dark mode based on current time
let today = new Date()
let time = today.getHours()
if (time < 6 || time > 20) {
darkMode()
//}
}
}
/* dark mode code - ends */
/* scroll to anchor */
let anchorlinks = document.querySelectorAll('a[href^="#"]')
for (let item of anchorlinks) {
item.addEventListener('click', (e) => {
let hashval = item.getAttribute('href')
let target = document.querySelector(hashval)
target.scrollIntoView({
behavior: 'smooth'
//block: 'start',
//inline:'nearest'
})
history.pushState(null, null, hashval) // for url updation
e.preventDefault() //needed for scroll
})
}
/* scroll to anchor - ends */
/* go to top button */
var prevScrollpos = window.pageYOffset;
const navigationBarId = 'navigation';
const footerId = 'footer';
window.onscroll = function () {
let currentScrollPos = window.pageYOffset;
if (currentScrollPos > 0) {
if (prevScrollpos > currentScrollPos) {
document.getElementById(navigationBarId).style.top = "0";
document.getElementById(footerId).style.bottom = "0";
document.getElementById("shareBtn").style.top = "85px"
document.getElementById("sharelinks").style.top = "115px"
} else {
document.getElementById(navigationBarId).style.top = "-70px";
document.getElementById(footerId).style.bottom = "-70px";
document.getElementById("shareBtn").style.top = "10px"
document.getElementById("sharelinks").style.top = "40px"
}
prevScrollpos = currentScrollPos;
}
scrollFunction();
}
// When the user scrolls down 20px from the top of the document, show the button
//window.onscroll = function() {scrollFunction()};
function scrollFunction() {
let goToTopButton = document.getElementById("goToTopBtn");
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
goToTopButton.style.display = "block";
} else {
goToTopButton.style.display = "none"; // to disappear once scroll ends
}
}
// When the user clicks on the button, scroll to the top of the document
function goToTopFunction() {
scrollToTop();
//document.body.scrollTop = 0; // For Safari
// document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
}
const scrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) { // check if page reached top or not
window.requestAnimationFrame(scrollToTop); // for smooth animation
window.scrollTo(0, c - c / 8);
}
};
/* go to top button - ends*/
/* share button - starts*/
// var shareBtn = document.getElementById('shareBtn');
// if (window.matchMedia('(min-width: 1000px)')) {
// shareBtn.addEventListener('mouseover', (e) => {
// let sharelinks = document.getElementById("sharelinks");
// if (sharelinks.style.display == 'none' || sharelinks.style.display == '') {
// sharelinks.style.display = 'flex';
// } else {
// sharelinks.style.display = 'none';
// }
// });
// }
function share() {
let sharelinks = document.getElementById("sharelinks");
if (sharelinks.style.display == 'none' || sharelinks.style.display == '') {
sharelinks.style.display = 'flex';
} else {
sharelinks.style.display = 'none';
}
}
function buildURI(item) {
if (item.href == 'mailto:?') {
subject = 'subject=' + document.getElementById('header').innerText;
body = "&body=Check out at this url : " + window.location.href;
item.setAttribute('href', item.href + subject + body);
} else {
item.setAttribute('href', item.href + window.location.href);
}
}
/* share button - ends*/</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
max-width: 850px;
text-align: left;
margin: auto;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
}
body,
a,
#navigation,
#footer {
transition: 0.4s;
}
.body-dark {
--dark-background-color: #202020;
--dark-text-color: #b3b9c5;
background-color: var(--dark-background-color);
color: var(--dark-text-color);
}
.body-dark h3 {
background-color: var(--dark-background-color);
color: var(--dark-text-color);
}
.body-dark a {
color: var(--dark-text-color);
}
.body-dark #navigation {
background-color: var(--dark-background-color);
}
.body-dark #footer {
background-color: var(--dark-background-color);
}
.body-light {
--light-background-color: #f8f9fa;
--light-text-color: black;
background-color: var(--light-background-color);
color: var(--light-text-color);
}
.body-light h3 {
background-color: var(--light-background-color);
color: var(--light-text-color);
}
.body-light a {
color: var(--light-text-color);
}
.body-light #navigation {
background-color: var(--light-background-color);
}
.body-light #footer {
background-color: var(--light-background-color);
}
/* navigation - start */
#navigation {
position: fixed;
margin: auto;
width: 100%;
max-width: 850px;
padding: 20px;
top: 0;
opacity: 0.9;
z-index: 1;
display: flex;
align-items: center;
flex-direction: row;
justify-content: space-between;
}
#navigation:hover{
opacity: 1;
}
#brand {
display: flex;
align-items: center;
flex-direction: row;
}
#navbrand {
text-decoration: none;
}
#name {
font-size: 23px;
padding-left: 20px;
display: inline;
text-decoration: none;
}
@media only screen and (max-width: 620px) {
#name {
display: none;
}
}
.navItems {
padding-right: 30px;
list-style: none;
}
.navItems a {
text-decoration: none;
padding: 5px;
}
.navItems a:hover {
color: steelblue;
text-decoration: none;
}
/* dark/light mode button */
#dark-mode-button {
background-color: transparent;
border: none;
outline: 0;
cursor: pointer;
}
/* navigation - end */
/* navigator start */
#navigator a {
text-decoration: none;
}
#navigator a:hover {
text-decoration: none;
color: steelblue;
}
/* navigator end */
#header {
margin-top: 70px;
}
h2 {
padding: 10px 20px 0px;
}
.text {
text-indent: 50px;
padding: 0 20px;
}
h3 {
margin: auto;
padding: 10px 20px;
position: -webkit-sticky;
position: sticky;
top: 0px;
opacity: 0.9;
transition: 0.4s;
}
#footer {
position: fixed;
padding: 10px 0;
z-index: 1;
opacity: 0.8;
bottom: 0;
width: 100%;
max-width: 850px;
position: -webkit-sticky;
position: sticky;
display: flex;
align-items: center;
justify-content: center;
}
.icon {
text-decoration: none;
padding: 0 10px;
cursor: pointer;
}
#footer:hover{
opacity: 1;
}
.body-dark .icon {
filter: invert(100%);
}
/* new code add below*/
/* scroll to top button */
#goToTopBtn {
display: none; /* Hidden by default */
position: fixed; /* Fixed/sticky position */
bottom: 50px; /* Place the button at the bottom of the page */
right: 15px; /* Place the button 30px from the right */
z-index: 99; /* Make sure it does not overlap */
border: none; /* Remove borders */
outline: none; /* Remove outline */
background-color: steelblue; /* Set a background color */
color: white; /* Text color */
cursor: pointer; /* Add a mouse pointer on hover */
padding: 15px; /* Some padding */
border-radius: 25px; /* Rounded corners */
font-size: 18px; /* Increase font size */
opacity: 0.7;
}
@media (min-width: 1100px) {
#goToTopBtn {
bottom: 50px; /* Place the button at the bottom of the page */
right: 250px;
}
}
#goToTopBtn:hover {
background-color: #555; /* Add a dark-grey background on hover */
}
/* scroll to top button ends */
/* share button code starts*/
#shareBtn{
position: fixed;
top: 85px; /* Place the button at the bottom of the page */
right: 22.5px; /* Place the button 30px from the right */
z-index: 99;
opacity: 0.7;
background-color: transparent;
border: none;
padding: 0;
outline: 0;
}
.body-dark #shareBtn {
filter: invert(100%);
}
@media (min-width: 1100px) {
#shareBtn {
right: 250px;
}
}
#shareBtn:hover{
cursor: pointer;
opacity: 1;
}
#sharelinks{
position: fixed;
display:none;
top: 115px; /* Place the button at the bottom of the page */
right: 22.5px; /* Place the button 30px from the right */
z-index: 99;
flex-direction: column;
align-items: center;
justify-content: space-between;
opacity: 0.7;
/* animate down */
}
#sharelinks:hover{
opacity: 1;
}
.body-dark #sharelinks {
filter: invert(100%);
}
.sharelink{
padding: 5px 0;
}
@media (min-width: 1100px) {
#sharelinks {
right: 250px;
}
}
/* share button code ends*/</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Author</title>
<link rel="stylesheet" href="style.css">
<script src="darkMode.js" defer></script>
</head>
<body id="body" class="body-light">
<div id="navigation">
<div id="brand">
<a id="navbrand" href="index.html"></a>
<a id="name" href="index.html"><strong>Author</strong></a>
</div>
<div class="navItems">
<a href="index.html">Home</a>
<a href="index.html">About</a>
<a href="mailto:blabla@bla.com">Contact Me</a>
<button onclick="toggleDarkMode()" title="dark mode" id="dark-mode-button"></button>
</div>
</div>
<div id="header">
<h2>HTML Tutorial
</h2>
</div>
<nav id="navigator">
<ol>
<li>
<a href="#what">What is html?</a>
</li>
<li>
<a href="#how">How is css?</a>
</li>
<li>
<a href="#when">What is css?</a>
</li>
</ol>
</nav>
<button onclick="goToTopFunction()" id="goToTopBtn" title="Go to top">Top</button>
<button onclick="share()" id="shareBtn" title="Share to"><img src="share.png"></button>
<div id="sharelinks">
<a onclick="buildURI(this)" href="https://www.facebook.com/sharer/sharer.php?u=" class="sharelink"
target="_blank" title="Facebook"><img src="facebook32.png" /></a>
<a onclick="buildURI(this)" href="https://wa.me/whatsappphonenumber/?text=" class="sharelink" target="_blank"
title="WhatsApp"><img src="whatsapp24.png"></a>
<a onclick="buildURI(this)" href="mailto:?" class="sharelink" target="_blank"
title="Mail"><img src="envelope.png"></a>
</div>
<div class="content">
<h3 id="what">What is html?</h3>
<article class="text"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quasi dolores doloribus et
illum
necessitatibus aliquid fugit dignissimos similique? Enim consequatur iste eius eveniet sint adipisci
deserunt
eaque? Adipisci, veniam veritatis! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quasi
dolores
doloribus et illum
necessitatibus aliquid fugit dignissimos similique? Enim consequatur iste eius eveniet sint adipisci
deserunt
eaque? Adipisci, veniam veritatis! </article>
</div>
<div class="content">
<h3 id="how">how is css?</h3>
<article class="text"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quasi dolores doloribus et
illum
necessitatibus aliquid fugit dignissimos similique? Enim consequatur iste eius eveniet sint adipisci
deserunt
eaque? Adipisci, veniam veritatis! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quasi
dolores
doloribus et illum
necessitatibus aliquid fugit dignissimos similique? Enim consequatur iste eius eveniet sint adipisci
deserunt
eaque? Adipisci, veniam veritatis! </article>
<article class="text">Lorem ipsum dolor sit amet consectetur adipisicing elit. Laudantium veniam sed esse ipsa,
est quas, suscipit
itaque quae tempore eaque delectus ullam ea sit doloremque numquam dolores totam, blanditiis corporis
consequuntur! Esse, doloribus incidunt at odio sequi neque totam nisi, soluta animi magnam optio nihil
perspiciatis. Quod consequuntur rerum ipsam aspernatur. Ipsam quia eius minima nemo. Aliquam nihil
commodi,
dolor necessitatibus cupiditate recusandae sunt animi autem nam officiis perferendis itaque esse debitis
amet, fuga accusamus dolorem minima veniam, pariatur cumque! Rerum possimus eveniet exercitationem
commodi
libero labore aut, facilis voluptatem quam? Facere, eos, harum nemo dolorem nulla minima quas ipsum amet
sed
deserunt cupiditate quisquam pariatur ratione inventore, perspiciatis totam laborum excepturi modi?
Dignissimos veniam, similique sunt debitis quibusdam nesciunt quo dolorum fuga velit. Dolores eum vero
sed,
officiis, earum possimus consequatur voluptas enim illo nisi reprehenderit cupiditate. Optio repellat
voluptatem consequatur corporis eveniet quam quos cupiditate dolorem, libero provident, rerum qui
assumenda
velit repudiandae temporibus? Asperiores eum dolorem distinctio reprehenderit? Voluptatum eaque eius
ducimus
quam distinctio! Deserunt doloremque sint commodi ipsam at atque, pariatur vel totam, quas aliquam
voluptatibus nobis corrupti, repellat cumque aut quaerat libero quisquam repellendus quo dignissimos
consectetur. Quia hic inventore, nesciunt iusto rem beatae esse!</article>
</div>
<div class="content">
<h3 id="when">what is css?</h3>
<article class="text"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quasi dolores doloribus et
illum
necessitatibus aliquid fugit dignissimos similique? Enim consequatur iste eius eveniet sint adipisci
deserunt
eaque? Adipisci, veniam veritatis! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quasi
dolores
doloribus et illum
necessitatibus aliquid fugit dignissimos similique? Enim consequatur iste eius eveniet sint adipisci
deserunt
eaque? Adipisci, veniam veritatis! </article>
<article class="text">Lorem ipsum dolor sit amet consectetur adipisicing elit. Laudantium veniam sed esse ipsa,
est quas, suscipit
itaque quae tempore eaque delectus ullam ea sit doloremque numquam dolores totam, blanditiis corporis
consequuntur! Esse, doloribus incidunt at odio sequi neque totam nisi, soluta animi magnam optio nihil
perspiciatis. Quod consequuntur rerum ipsam aspernatur. Ipsam quia eius minima nemo. Aliquam nihil
commodi,
dolor necessitatibus cupiditate recusandae sunt animi autem nam officiis perferendis itaque esse debitis
amet, fuga accusamus dolorem minima veniam, pariatur cumque! Rerum possimus eveniet exercitationem
commodi
libero labore aut, facilis voluptatem quam? Facere, eos, harum nemo dolorem nulla minima quas ipsum amet
sed
deserunt cupiditate quisquam pariatur ratione inventore, perspiciatis totam laborum excepturi modi?
Dignissimos veniam, similique sunt debitis quibusdam nesciunt quo dolorum fuga velit. Dolores eum vero
sed,
officiis, earum possimus consequatur voluptas enim illo nisi reprehenderit cupiditate. Optio repellat
voluptatem consequatur corporis eveniet quam quos cupiditate dolorem, libero provident, rerum qui
assumenda
velit repudiandae temporibus? Asperiores eum dolorem distinctio reprehenderit? Voluptatum eaque eius
ducimus
quam distinctio! Deserunt doloremque sint commodi ipsam at atque, pariatur vel totam, quas aliquam
voluptatibus nobis corrupti, repellat cumque aut quaerat libero quisquam repellendus quo dignissimos
consectetur. Quia hic inventore, nesciunt iusto rem beatae esse!</article>
</div>
<div id="footer" class="footer">
<a href="https://www.facebook.com/" class="icon" target="_blank" title="facebook"><img src="facebook32.png"/></a>
<a href="https://www.instagram.com/" class="icon" target="_blank" title="instagram"><img src="instagram32.png"/></a>
<a href="https://www.twitter.com/" class="icon" target="_blank" title="twitter"><img src="twitter32.png"/></a>
<a href="https://www.github.com/" class="icon" target="_blank" title="github"><img src="github32.png"/></a>
<a href="https://www.linkedin.com/" class="icon" target="_blank" title="linkedin"><img src="linkedin32.png"/></a>
<a href="mailto:blabla@gmail.com" class="icon" target="_blank" title="Mail"><img src="envelope.png"/></a>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<p>One of the things you should consider is user experience. You are saving the light or dark mode to Session Storage. Everytime the user visits your page he will have to select the mode again and again. If you save it in local storage instead, that will persist even if the user comes back another day. Consider that change. You want the user to do as less work as possible to enjoy the experience you provide.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T12:09:54.637",
"Id": "469542",
"Score": "1",
"body": "Thanks. But after all the thought, I have decided to come up with the current time based switch approach as well for dark mode. So user will get the mode during his entire session and if he comes the same day during night, he will get dark mode as well, else if day it will be day mode. After all the thoughts and feedback from my wife, I used session storage and time based default mode..anyways thanks for your time. And yes, user experience IS my top priority."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T12:10:43.353",
"Id": "469543",
"Score": "0",
"body": "that's even cooler, but the concept applies anyway to other stuff"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T10:53:37.273",
"Id": "239351",
"ParentId": "239140",
"Score": "2"
}
},
{
"body": "<p>It's good web project for first time, but in your HTML use <a href=\"https://developer.mozilla.org/en-US/docs/Glossary/Semantics\" rel=\"nofollow noreferrer\">semantic HTML</a>.</p>\n\n<p>Also use section tags, header tags, nav tags and main tags.</p>\n\n<p>This image can help you for layout:</p>\n\n<p><img src=\"https://www.w3schools.com/html/img_sem_elements.gif\" alt=\"layout\"></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-01T09:43:42.393",
"Id": "243214",
"ParentId": "239140",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T10:58:33.213",
"Id": "239140",
"Score": "4",
"Tags": [
"javascript",
"html",
"css"
],
"Title": "My first static web project without any external js"
} | 239140 |
<h1>Current OBJLoader:</h1>
<p>Using pygame's obj loader as a base, I created a new obj loader for Python OpenGL. The loader includes the following functionality:</p>
<ol>
<li>Collect vertices, normals, and texture to draw</li>
<li>Divide objects based on materials</li>
<li>Store each material's vertices, normals, colours and textures in
separate VAO's</li>
<li>Have an instance vbo ready for each material</li>
<li>Call an appropriate shader for each material</li>
<li>Draw the whole Object as if it is one object</li>
</ol>
<p>This means that you can call a single object to be drawn once, i.e:</p>
<pre><code> obj_m = ObjLoader()
obj_m.load_model("C:/Projects/PythonScripts/GIS/obj_pins/KFC.obj")
obj_KFC = obj_m.load_obj()
</code></pre>
<p>Or you can draw the object in multiple places using instancing, i.e:</p>
<pre><code> instance_list = [[0,0,0], [-10,0,0], [10,0,0]]
obj_m = ObjLoader()
obj_m.load_model("C:/Projects/PythonScripts/GIS/obj_pins/KFC.obj", *instance_list)
obj_KFC = obj_m.load_obj()
</code></pre>
<p>Then you can call the object in your drawing loop with or without transformation, i.e:</p>
<pre><code> obj_m.draw_call(obj_KFC, view, projection, model)
</code></pre>
<p>or</p>
<pre><code> transform = glm.mat4(1.0)
transform = glm.rotate(transform, glfw.get_time(), glm.vec3(0.0, 1.0, 1.0))
transform = glm.scale(transform, glm.vec3(1.0, 1.0, 1.0))
obj_m.draw_call(obj_KFC, view, projection, model, transform)
</code></pre>
<p><strong>Output:</strong>
<a href="https://i.stack.imgur.com/MQGnG.png" rel="noreferrer"><img src="https://i.stack.imgur.com/MQGnG.png" alt="Instanced Object" /></a></p>
<h1>Current Drawbacks</h1>
<p>I only recently started with OpenGL for fun and I'm not a programmer per se. Therefore I implemented the object loader's functionality as I went along. The code is therefore not "pretty", nor tested extensively and mostly without added error checking code. These are the known drawbacks:</p>
<ol>
<li><p>The .obj file should be triangulated i.e using Blender:</p>
<p><a href="https://i.stack.imgur.com/MkjR4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/MkjR4.png" alt="Triangulate object" /></a></p>
</li>
<li><p>The .obj, .mtl, and image (if a material contains a texture) needs to
be in the same folder</p>
</li>
<li><p>The link to the texture in the .mtl folder should be relative, therefore containing only the name of the image i.e: <em>map_Kd 3D_kfc.png</em></p>
</li>
</ol>
<h1>Improvements</h1>
<p>I thought to share the code because as I stated, I'm not a programmer per se, but I think others can benefit from this especially when the code is "cleaner". So the questions:</p>
<ol>
<li>Are there obvious structure improvements?</li>
<li>Are there obvious improvements to the code?</li>
<li>Are there any wanted improvements i.e lighting?</li>
</ol>
<h1>OBJLOADER CODE</h1>
<pre><code>import numpy as np
from OpenGL.GL import *
from OpenGL.GL.shaders import compileProgram, compileShader
import os
import glm
from PIL import Image
class ObjLoader:
def __init__(self):
self.vert_coords = []
self.text_coords = []
self.norm_coords = []
self.object_parts = {}
self.setup_index()
self.obj_shaders()
def setup_index(self):
self.material_index = []
self.vertex_index = []
self.texture_index = []
self.normal_index = []
self.model = []
self.material_index = []
self.vertex_index = []
self.texture_index = []
self.normal_index = []
def load_model(self, file, *args):
for line in open(file, 'r'):
if line.startswith('#'): continue
values = line.split()
if not values: continue
if values[0] == 'v':
self.vert_coords.append(values[1:4])
if values[0] == 'vt':
self.text_coords.append(values[1:3])
if values[0] == 'vn':
self.norm_coords.append(values[1:4])
if values[0] == 'mtllib':
self.mtl = values[1]
matarials = self.mat_in_file(file)
m_counter = 0
for line in open(file, 'r'): # open(file, 'r'):
if line.startswith('#'): continue
values = line.split()
if not values: continue
if values[0] == 'usemtl':
if values[1] != matarials[m_counter][0]:
self.define_i_t_u(file, matarials[m_counter], args)
m_counter += 1
self.setup_index()
if values[0] == 'f':
face_i = []
text_i = []
norm_i = []
for v in values[1:4]:
w = v.split('/')
face_i.append(int(w[0]) - 1)
text_i.append(int(w[1]) - 1)
norm_i.append(int(w[2]) - 1)
self.vertex_index.append(face_i)
self.texture_index.append(text_i)
self.normal_index.append(norm_i)
self.define_i_t_u(file, matarials[m_counter], args)
def define_i_t_u(self, file, mat, args):
self.vertex_index = [y for x in self.vertex_index for y in x]
self.texture_index = [y for x in self.texture_index for y in x]
self.normal_index = [y for x in self.normal_index for y in x]
for i in self.vertex_index:
self.model.extend(self.vert_coords[i])
for i in self.texture_index:
self.model.extend(self.text_coords[i])
for i in self.normal_index:
self.model.extend(self.norm_coords[i])
self.model = np.array(self.model, dtype='float32')
glUseProgram(mat[1])
texid = self.MTL(file)
l_vao = self.vao_creator(self.vertex_index, self.model, mat[1], mat[2], texid, args)
self.object_parts["{0}".format(mat[0])] = l_vao
def MTL(self, filename):
filename = os.path.splitext(filename)[0] + '.mtl'
filepath = os.path.dirname(filename)
base = os.path.basename(filename)
file_only_name = os.path.splitext(base)[0]
contents = {}
mtl = None
image = None
texid = None
surf = None
values = []
for line in open(filename, "r"):
if line.startswith('#'): continue
values = line.split()
if not values: continue
if values[0] == 'newmtl':
mtl = contents[values[1]] = {}
elif mtl is None:
raise ValueError("mtl file doesn't start with newmtl stmt")
elif values[0] == 'map_Kd':
self.object_shader = self.shader_obj_text
# load the texture referred to by this declaration
mtl[values[0]] = values[1]
texid = mtl['texture_Kd'] = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, texid)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,
GL_LINEAR)
image = Image.open(os.path.join(filepath, mtl['map_Kd']))
flipped_image = image.transpose(Image.FLIP_TOP_BOTTOM)
img_data = flipped_image.convert("RGBA").tobytes()
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.width, image.height, 0, GL_RGBA, GL_UNSIGNED_BYTE,
img_data)
return texid
def vao_creator(self, vertex_index, model, shader, defuse_col, texid, args):
texture_offset = len(vertex_index) * 12
VAO = glGenVertexArrays(1)
glBindVertexArray(VAO)
VBO = glGenBuffers(1)
glBindBuffer(GL_ARRAY_BUFFER, VBO)
glBufferData(GL_ARRAY_BUFFER, model.itemsize * len(model), model, GL_STATIC_DRAW)
# position
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, model.itemsize * 3, ctypes.c_void_p(0))
glEnableVertexAttribArray(0)
# texture
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, model.itemsize * 2, ctypes.c_void_p(texture_offset))
glEnableVertexAttribArray(1)
# Normals
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, model.itemsize * 3, ctypes.c_void_p(12))
glEnableVertexAttribArray(2)
# Instancing
if len(args) == 0:
amount = 1
vert_instance = np.array([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]])
else:
amount = len(args)
vert_instance = np.array(args)
modelMatrices = []
# Storring the objects in a list
for i in range(0, amount):
mod_list = []
model_o = glm.mat4(1.0)
model_o = glm.translate(model_o, glm.vec3(vert_instance[i][0], vert_instance[i][1], vert_instance[i][2]))
# model_o = glm.scale(model_o, glm.vec3(0.00005, 0.00005, 0.00005))
for i in range(4):
for j in range(4):
mod_list.append(model_o[i][j])
modelMatrices.append(mod_list)
modelMatrices = np.array(modelMatrices, dtype="f")
instanceVBO = glGenBuffers(1)
glBindBuffer(GL_ARRAY_BUFFER, instanceVBO)
glBufferData(GL_ARRAY_BUFFER, amount * glm.sizeof(glm.mat4), modelMatrices, GL_STATIC_DRAW)
# Bind each vertex attrib array of matrices (4 vectors in Matrix)
glEnableVertexAttribArray(3)
glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, glm.sizeof(glm.mat4), ctypes.c_void_p(0))
glEnableVertexAttribArray(4)
glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, glm.sizeof(glm.mat4), ctypes.c_void_p(glm.sizeof(glm.vec4)))
glEnableVertexAttribArray(5)
glVertexAttribPointer(5, 4, GL_FLOAT, GL_FALSE, glm.sizeof(glm.mat4),
ctypes.c_void_p((2 * glm.sizeof(glm.vec4))))
glEnableVertexAttribArray(6)
glVertexAttribPointer(6, 4, GL_FLOAT, GL_FALSE, glm.sizeof(glm.mat4),
ctypes.c_void_p((3 * glm.sizeof(glm.vec4))))
# Set instancing
glVertexAttribDivisor(3, 1)
glVertexAttribDivisor(4, 1)
glVertexAttribDivisor(5, 1)
glVertexAttribDivisor(6, 1)
glBindVertexArray(0)
return ([VAO, len(vertex_index), shader, defuse_col, texid, len(vert_instance)])
def mat_in_file(self, filename):
filename = os.path.splitext(filename)[0] + '.mtl'
mtl = None
contents = {}
mat_list = []
for line in open(filename, "r"):
if line.startswith('#'): continue
values = line.split()
if not values: continue
if values[0] == 'newmtl':
object_shader = self.shader_obj
mtl = contents[values[1]] = {}
matname = values[1]
elif mtl is None:
raise ValueError("mtl file doesn't start with newmtl stmt")
elif values[0] == 'Kd':
defuse_col = [float(values[1]), float(values[2]), float(values[3])]
elif values[0] == 'd':
defuse_col = defuse_col + [float(values[1])]
mat_list.append([matname, object_shader, defuse_col])
elif values[0] == 'map_Kd':
object_shader = self.shader_obj_text
mat_list.pop()
mat_list.append([matname, object_shader, defuse_col])
return mat_list
def load_obj(self):
obj_list = [self.object_parts[ind] for ind in self.object_parts]
return obj_list
def draw_call(self, vao_list, view, projection, model, *transf):
if len(transf) == 0:
transform = glm.mat4(1.0)
else:
transform = transf[0]
for key in vao_list:
VAO = key[0]
vertex_len = key[1]
shader = key[2]
d_colour = key[3]
texid = key[4]
len_instanced = key[5]
glUseProgram(shader)
glBindTexture(GL_TEXTURE_2D, texid)
view_loc = glGetUniformLocation(shader, "view")
proj_loc = glGetUniformLocation(shader, "projection")
model_loc = glGetUniformLocation(shader, "model")
col_loc = glGetUniformLocation(shader, "mycolor")
glUniformMatrix4fv(view_loc, 1, GL_FALSE, view)
glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection)
glUniformMatrix4fv(model_loc, 1, GL_FALSE, model)
glUniform4fv(col_loc, 1, glm.value_ptr(glm.vec4(d_colour)))
transformLoc = glGetUniformLocation(shader, "transform")
glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm.value_ptr(transform))
glBindVertexArray(VAO)
glDrawArraysInstanced(GL_TRIANGLES, 0, vertex_len, len_instanced)
glBindVertexArray(0)
def obj_shaders(self):
vertex_obj = """
# version 330
in layout(location = 0) vec3 position;
in layout(location = 1) vec2 textureCoords;
in layout(location = 2) vec3 normalCoords;
in layout (location = 3) mat4 instanceMatrix;
uniform mat4 transform;
uniform mat4 view;
uniform mat4 model;
uniform mat4 projection;
out vec2 newTexture;
out vec3 newNorm;
void main()
{
gl_Position = projection * view *instanceMatrix *model * transform *vec4(position, 1.0f);
newTexture = textureCoords;
newNorm = normalCoords;
}
"""
fragment_obj = """
#version 330
in vec2 newTexture;
in vec3 newNorm;
uniform vec4 mycolor;
out vec4 outColor;
uniform sampler2D samplerTexture;
void main()
{
outColor = mycolor;
}
"""
fragment_obj_text = """
#version 330
in vec2 newTexture;
in vec3 newNorm;
in vec3 out_colours;
uniform vec4 mycolor;
out vec4 outColor;
uniform sampler2D samplerTexture;
void main()
{
outColor = texture(samplerTexture, newTexture);
}
"""
self.shader_obj = compileProgram(compileShader(vertex_obj, GL_VERTEX_SHADER),
compileShader(fragment_obj, GL_FRAGMENT_SHADER))
self.shader_obj_text = compileProgram(compileShader(vertex_obj, GL_VERTEX_SHADER),
compileShader(fragment_obj_text, GL_FRAGMENT_SHADER))
</code></pre>
<h1>Example code</h1>
<pre><code>import glfw
import pyrr
from ObjLoader import *
def window_resize(window, width, height):
glViewport(0, 0, width, height)
def main():
# initialize glfw
if not glfw.init():
return
w_width, w_height = 800, 600
window = glfw.create_window(w_width, w_height, "My OpenGL window", None, None)
if not window:
glfw.terminate()
return
glfw.make_context_current(window)
glfw.set_window_size_callback(window, window_resize)
instance_list = [[0,0,0], [-10,0,0], [10,0,0]]
obj_m = ObjLoader()
obj_m.load_model("C:/Projects/PythonScripts/GIS/obj_pins/KFC.obj", *instance_list)
obj_KFC = obj_m.load_obj()
glClearColor(0.2, 0.3, 0.2, 1.0)
glEnable(GL_DEPTH_TEST)
view = pyrr.matrix44.create_from_translation(pyrr.Vector3([0.0, 0.0, -20.0]))
projection = pyrr.matrix44.create_perspective_projection_matrix(65.0, w_width / w_height, 0.1, 100.0)
model = pyrr.matrix44.create_from_translation(pyrr.Vector3([0.0, 0.0, 0.0]))
while not glfw.window_should_close(window):
glfw.poll_events()
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
#obj_m.draw_call(obj_KFC, view, projection, model)
transform = glm.mat4(1.0)
transform = glm.rotate(transform, glfw.get_time(), glm.vec3(0.0, 1.0, 1.0))
transform = glm.scale(transform, glm.vec3(1.0, 1.0, 1.0))
obj_m.draw_call(obj_KFC, view, projection, model, transform)
glfw.swap_buffers(window)
glfw.terminate()
if __name__ == "__main__":
main()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T19:02:52.387",
"Id": "469113",
"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 new question instead (after waiting for a day, perhaps more answers are coming in), with a link to this question for additional context. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T19:11:36.123",
"Id": "469117",
"Score": "0",
"body": "O.k thanks. Will catch up with the rules then."
}
] | [
{
"body": "<p>Hello and welcome to CodeReview!</p>\n\n<p>A random list of observations:</p>\n\n<h2>Type hints</h2>\n\n<p>For your members, </p>\n\n<pre><code> self.vert_coords = []\n</code></pre>\n\n<p>can be (assuming it's a list of floats)</p>\n\n<pre><code>self.vert_coords: List[float] = []\n</code></pre>\n\n<p>and so on. This helps for a few reasons - smart IDEs will notice if you're using the member with an unexpected type and can warn you; autocomplete is better; and this is clearer to other programmers (including you in six months).</p>\n\n<h2>Typo</h2>\n\n<p><code>matarials</code> = <code>materials</code></p>\n\n<h2>Generation/comprehension</h2>\n\n<p>This:</p>\n\n<pre><code> face_i = []\n text_i = []\n norm_i = []\n for v in values[1:4]:\n w = v.split('/')\n face_i.append(int(w[0]) - 1)\n text_i.append(int(w[1]) - 1)\n norm_i.append(int(w[2]) - 1)\n</code></pre>\n\n<p>can be expressed a number of different ways; one example:</p>\n\n<pre><code>parts = [\n [\n int(w) - 1 for w in v.split('/')\n for w in v.split('/')\n ]\n for v in values[1:4]\n]\n\nself.vertex_index.append([part[0] for part in parts])\nself.texture_index.append([part[1] for part in parts])\nself.normal_index.append([part[2] for part in parts])\n</code></pre>\n\n<p>Or you could also make a function that yields:</p>\n\n<pre><code>def get_vertices(values):\n for v in values[1:4]:\n yield int(v.split('/')[0]) - 1\n\n...\n\nself.vertex_index = list(get_vertices(values))\n</code></pre>\n\n<h2>Nomenclature</h2>\n\n<p>Re. <code>def MTL</code> - usually methods in Python are lower-case.</p>\n\n<p>Also, this:</p>\n\n<p><code>modelMatrices</code></p>\n\n<p>is typically in snake_case, i.e. <code>model_matrices</code></p>\n\n<h2>Array definition</h2>\n\n<p>This:</p>\n\n<pre><code> vert_instance = np.array([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]])\n</code></pre>\n\n<p>is more legible as</p>\n\n<pre><code>vert_instance = np.array([\n [0.0, 0.0, 0.0],\n [1.0, 1.0, 1.0],\n])\n</code></pre>\n\n<h2>Computers are good at loops</h2>\n\n<pre><code> glVertexAttribDivisor(3, 1)\n glVertexAttribDivisor(4, 1)\n glVertexAttribDivisor(5, 1)\n glVertexAttribDivisor(6, 1)\n</code></pre>\n\n<p>can become</p>\n\n<pre><code>for i in range(3, 7):\n glVertexAttribDivisor(i, 1)\n</code></pre>\n\n<h2>Indentation</h2>\n\n<p>Your <code>vertex_obj</code> string has a large amount of indentation. I'm not sure why this is, but either way, that string is better off living in a file that you read in when you need it. It's more maintainable that way.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T19:13:00.877",
"Id": "469118",
"Score": "0",
"body": "Thanks. I edit my code with your suggestions. It even pointed out an error where I tested 2 instances for vert_instance and never changed the code back to a single instance. Also had duplicate variable declarations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T19:16:15.297",
"Id": "469119",
"Score": "2",
"body": "Please do not edit existing code based on suggestions. Policy is to open a new question."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T15:51:54.857",
"Id": "239148",
"ParentId": "239145",
"Score": "4"
}
},
{
"body": "<p>Two things that I can see that I think would improve your structure a lot:</p>\n\n<ul>\n<li><p>Keep the shader sources in separate files (I like to have them in /res/shaders with a .glsl extension) and load them in. You could have a class called <code>ShaderProgram</code> with methods <code>load_shader</code> and that also links up the shader program and removes the compiled shaders when linked.</p></li>\n<li><p>Having a class also for the VAO would allow you to access members, which means that you could transform this:</p>\n\n<pre><code> for key in vao_list:\n ...\n shader = key[2]\n ...\n\n glUseProgram(shader)\n</code></pre>\n\n<p>to something like this:</p>\n\n<pre><code> for VAO in vao_list:\n glUseProgram(VAO.shader)\n</code></pre></li>\n</ul>\n\n<h3>Smaller improvements</h3>\n\n<p>You're currently dealing with a lot of lists and manual indexes where you could use classes and list comprehensions. This:</p>\n\n<pre><code> mod_list = []\n for i in range(4):\n for j in range(4):\n mod_list.append(model_o[i][j])\n</code></pre>\n\n<p>could be written as <code>mod_list = [model_o[i][j] for j in range(4) for i in range(4)]</code>. List comprehensions are faster and easier to read. And speaking of lists, you may want to have a look at <code>Collections.deque</code> (a bit faster), and you may want to rethink some of your lists since you probably are using a lot of performance there.</p>\n\n<hr>\n\n<p>Use context managers. You're opening files without making sure that they're closed, e.g. here: <code>for line in open(file, 'r'):</code>.</p>\n\n<h3>\"Bugs\"</h3>\n\n<p>You're overwriting a lot of your variables here:</p>\n\n<pre><code> def setup_index(self):\n self.material_index = []\n self.vertex_index = []\n self.texture_index = []\n self.normal_index = []\n self.model = []\n self.material_index = [] # duplicate\n self.vertex_index = [] # duplicate\n self.texture_index = [] # duplicate\n self.normal_index = [] # duplicate\n</code></pre>\n\n<p>I also think I found a \"bug\", where you do:</p>\n\n<pre><code> mtl = None\n ...\n if values[0] == 'newmtl':\n ...\n mtl = contents[values[1]] = {}\n ...\n elif mtl is None:\n raise ValueError(\"mtl file doesn't start with newmtl stmt\")\n</code></pre>\n\n<p>It would only evaluate that <code>else-if</code> if the first <code>if</code> is False, and the <code>else-if</code> will only be <code>True</code> if the first <code>if</code> is <code>False</code>. Based on your message in the raised error, I would think that you just want <code>if values[0] == \"newmtl\": <do-this> else: raise <error></code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T11:06:43.487",
"Id": "239501",
"ParentId": "239145",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T13:03:48.880",
"Id": "239145",
"Score": "7",
"Tags": [
"python",
"opengl"
],
"Title": "pyopenGL OBJ loader improvements"
} | 239145 |
<p>I stumbled across the 100 prisoners problem on <a href="http://rosettacode.org/wiki/100_prisoners" rel="nofollow noreferrer">Rosetta Code</a>. I thought it would be fun to add a Common Lisp solution, see below.</p>
<p>Before I publish my solution I would like to have some feedback on my code. I have used lists for the task because I think it is most natural in CL and performance isn't an issue here.</p>
<p>Thanks for your comments!</p>
<pre><code>(defparameter *samples* 10000)
(defparameter *prisoners* 100)
(defparameter *max-guesses* 50)
(defun range (n)
"Returns a list from 0 to N."
(loop
for i below n
collect i))
(defun nshuffle (list)
"Returns a shuffled LIST."
(loop
for i from (length list) downto 2
do (rotatef (nth (random i) list)
(nth (1- i) list)))
list)
(defun build-drawers ()
"Returns a list of shuffled drawers."
(nshuffle (range *prisoners*)))
(defun strategy-1 (drawers p)
"Returns T if P is found in DRAWERS under *MAX-GUESSES* using a random strategy."
(loop
for i below *max-guesses*
thereis (= p (nth (random *prisoners*) drawers))))
(defun strategy-2 (drawers p)
"Returns T if P is found in DRAWERS under *MAX-GUESSES* using an optimal strategy."
(loop
for i below *max-guesses*
for j = p then (nth j drawers)
thereis (= p (nth j drawers))))
(defun 100-prisoners-problem (strategy &aux (drawers (build-drawers)))
"Returns T if all prisoners find their number using the given STRATEGY."
(every (lambda (e) (eql T e))
(mapcar (lambda (p) (funcall strategy drawers p)) (range *prisoners*))))
(defun sampling (strategy)
(loop
repeat *samples*
for result = (100-prisoners-problem strategy)
count result))
(defun compare-strategies ()
(format t "Using a random strategy in ~4,2F % of the cases the prisoners are free.~%" (* (/ (sampling #'strategy-1) *samples*) 100))
(format t "Using an optimal strategy in ~4,2F % of the cases the prisoners are free.~%" (* (/ (sampling #'strategy-2) *samples*) 100)))
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T13:23:11.303",
"Id": "239146",
"Score": "3",
"Tags": [
"common-lisp"
],
"Title": "My solution to the 100 prisoners challenge"
} | 239146 |
<p>I have three methods that I need to call multiple times only varying the date parameter of each. The natural solution to avoid code duplication is to put the three methods in a loop and iterate over the varying dates. </p>
<p>The problem with that approach is that I need to keep track of the results of each method call along with the dates that produced the result so that I can build the DTOs. So, I'm not sure how to employ a loop without resulting in redundant & verbose code or if a loop is even the right solution to avoid code duplication.</p>
<p>Here's my code:</p>
<pre><code> LocalDate sevenDaysAgo = endDate.minusDays(7);
Map<String, BigDecimal> sevenDayValues = client.getValues(productIds, sevenDaysAgo, endDate);
Map<String, BigDecimal> sevenDayGrossValues = client.getBaselineValues(grossProductIds, sevenDaysAgo, endDate, "gross");
Map<String, BigDecimal> sevenDayNetValues = client.getBaselineValues(netProductIds, sevenDaysAgo, endDate, "net");
//calling same methods again varying start date
LocalDate thirtyDaysAgo = endDate.minusDays(30);
Map<String, BigDecimal> thirtyDayValues = client.getValues(productIds, thirtyDaysAgo, endDate);
Map<String, BigDecimal> thirtyDayGrossValues = client.getBaselineValues(grossProductIds, thirtyDaysAgo, endDate, "gross");
Map<String, BigDecimal> thirtyDayNetValues = client.getBaselineValues(netProductIds, thirtyDaysAgo, endDate, "net");
//and again
LocalDate sixtyDaysAgo = endDate.minusDays(60);
Map<String, BigDecimal> sixtyDayValues = client.getValues(productIds, sixtyDaysAgo, endDate);
Map<String, BigDecimal> sixtyDayGrossValues = client.getBaselineValues(grossProductIds, sixtyDaysAgo, endDate, "gross");
Map<String, BigDecimal> sixtyDayNetValues = client.getBaselineValues(netProductIds, sixtyDaysAgo, endDate, "net");
//and yet again
LocalDate ninetyDaysAgo = endDate.minusDays(90);
Map<String, BigDecimal> ninetyDayValues = client.getValues(productIds, ninetyDaysAgo, endDate);
Map<String, BigDecimal> ninetyDayGrossValues = client.getBaselineValues(grossProductIds, ninetyDaysAgo, endDate, "gross");
Map<String, BigDecimal> ninetyDayNetValues = client.getBaselineValues(netProductIds, ninetyDaysAgo, endDate, "net");
List<ProductValuesDto> dtos = new ArrayList<>();
//now build the dtos. Need to know the date range
//that the values correspond to (see buildDtos method)
buildDtos(dtos,
productId,
sevenDayValues,
thirtyDayValues,
ninetyDayValues,
threeHundredSixtyFiveDayValues);
buildDtos(dtos,
grossProductIds,
sevenDayGrossValues,
thirtyDayGrossValues,
ninetyDayGrossValues,
threeHundredSixtyFiveDayGrossValues);
buildDtos(dtos,
netProductIds,
sevenDayNetValues,
thirtyDayNetValues,
ninetyDayNetValues,
threeHundredSixtyFiveDayNetValues);
return dtos;
}
public void buildDtos(List<ProductValuesDto> dtos,
List<String> productIds,
Map<String, BigDecimal> sevenDayValues,
Map<String, BigDecimal> thirtyDayValues,
Map<String, BigDecimal> ninetyDayValues,
Map<String, BigDecimal> threeHundredSixtyFiveDayValues) {
for(String productId : productIds) {
ProductValuesDto dto = ProductValuesDto
.builder(productId)
.sevenDayValue(sevenDayValues.get(productId))
.thirtyDayValue(thirtyDayValues.get(productId))
.ninetyDayValue(ninetyDayValues.get(productId))
.threeHundredSixtyFiveDayValue(threeHundredSixtyFiveDayValues.get(productId))
.build();
dtos.add(dto);
}
}
</code></pre>
<p>The <code>client</code> methods all return <code>Map<String, BigDecimal></code> where the key is the <code>productId</code> and the value is assessed value of the product over the start to end date.</p>
<p>A few notes:</p>
<ol>
<li><code>client</code> methods are defined in a third party library that I cannot change</li>
<li>The DTO will be handed back to a client of my application. It needs to have fields as noted in the builder.</li>
<li>The offset days (7, 30, 60, 90) are static requirements. But it's possible (although unlikely) that a 120 day offset may be added in the future.</li>
<li>I'm using Java 8 and open to using functional programming techniques.</li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T19:09:02.460",
"Id": "469115",
"Score": "0",
"body": "_\"1. client methods are defined in a third party library that I cannot change\"_ You can always put a wrapper on top."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T13:14:58.187",
"Id": "469345",
"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](https://codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T01:57:41.260",
"Id": "470180",
"Score": "0",
"body": "Thanks for the guidance, Sᴀᴍ Onᴇᴌᴀ. I've changed the title."
}
] | [
{
"body": "<p>Thanks for sharing your code.</p>\n\n<p>As you already found out, the only difference in the \"map generation blocks\" is the names \nof the variables holding the maps. \nSo it is quite obvious, that you could move this 3 lines into the method <code>buildDtos</code>.</p>\n\n<p>On the other hand the first line in each \"map generation blocks\" calls a separate \nmethod on the <code>client</code> object. This is an <em>odd ball solution</em> and the proper way to deal with that would be to enable <code>clinet.client.getBaselineValues()</code> to deal with \na special String <em>(<strong>Attention!</strong> resist the temptation to use <code>null</code>!)</em> to return the \nsame result as <code>clinet.client.getValues()</code>.</p>\n\n<p>until then we could introduce a <em>FunctionalInterface</em> to mimik that on this side. This could look like this:</p>\n\n<pre><code>@FunctionalInterface\ninterface ValueSelector {\n Map<String, BigDecimal> selectFrom(\n Client client, \n List<String> ids, \n LocalDate startDate, \n LocalDate endDate);\n}\n\npublic List<ProductValuesDto> main() {\n\n buildDtos(//\n dtos,\n productIds,\n (client, ids, start, end) -> client.getValues(ids, start, end));\n buildDtos(\n dtos,\n grossProductIds,\n (client, ids, start, end) -> client.getBaselineValues(ids, start, end, \"gross\"));\n buildDtos(//\n dtos,\n netProductIds,\n (client, ids, start, end) -> client.getBaselineValues(ids, start, end, \"net\"));\n return dtos;\n\n}\n\npublic void buildDtos(List<ProductValuesDto> dtos, List<String> productIds, ValueSelector valueSelector) {\n\n Map<String, BigDecimal> sevenDayValues = valueSelector\n .selectFrom(client, productIds, endDate.minusDays(7), endDate);\n Map<String, BigDecimal> thirtyDayValues = valueSelector\n .selectFrom(client, productIds, endDate.minusDays(30), endDate);\n Map<String, BigDecimal> threeHundredSixtyFiveDayValues = valueSelector\n .selectFrom(client, productIds, endDate.minusDays(365), endDate);\n Map<String, BigDecimal> ninetyDayNetValues = valueSelector\n .selectFrom(client, productIds, endDate.minusDays(90), endDate);\n\n for (String productId : productIds) {\n ProductValuesDto dto = ProductValuesDto.builder(productId)//\n .sevenDayValue(sevenDayValues.get(productId))//\n .thirtyDayValue(thirtyDayValues.get(productId))//\n .ninetyDayValue(ninetyDayNetValues.get(productId))//\n .threeHundredSixtyFiveDayValue(threeHundredSixtyFiveDayValues.get(productId))//\n .build();\n dtos.add(dto);\n }\n\n}\n</code></pre>\n\n<hr>\n\n<h1>Update</h1>\n\n<p>Based on that approach we could improve this even further.</p>\n\n<h2>Improvement 1</h2>\n\n<p>Create an <code>enum</code> that provides implementations of the new interface:</p>\n\n<pre><code>enum ClientValues {\n PLAIN {\n\n @Override\n ValueSelector getSelectorForType(String reportType) {\n return (client, ids, start, end)\n -> client.getValues(ids, start, end);\n }\n },\n BASELINE {\n\n @Override\n ValueSelector getSelectorForType(String reportType) {\n return (client, ids, start, end)\n -> client.getBaselineValues(ids, start, end, reportType);\n }\n };\n abstract ValueSelector getSelectorForType(//\n String reportType);\n}\n</code></pre>\n\n<p>create a <code>Map</code> that assigns this <code>enum</code> constants to the strings used:</p>\n\n<pre><code> Map<String, ClientValues> valuesByType = new HashMap<>();\n valuesByType.put(\"plain\", ClientValues.PLAIN);\n</code></pre>\n\n<p>We intentionally leave out the constant that is used most often. </p>\n\n<p>Next we create another map that assignes the Strings used with the respective ID lists:</p>\n\n<pre><code> Map<String, List<String>> idsByType = new HashMap<>();\n idsByType.put(\"plain\", productIds);\n idsByType.put(\"gross\", grossProductIds);\n idsByType.put(\"net\", netProductIds);\n</code></pre>\n\n<p>Complete mapping this time.</p>\n\n<p>Both maps could even be <em>class members</em> (with <code>static</code> initializers) or <em>object members</em> constructed \nsomewhere else and injected into this class.</p>\n\n<p>Now we can iterate over the entries of the second map using the first one like this:</p>\n\n<pre><code> for (String idType : idsByType.keySet()) {\n List<String> ids = idsByType.get(idType);\n ClientValues clientValues = \n valuesByType.getOrDefault(idType, ClientValues.BASELINE);\n buildDtos(//\n dtos,\n ids,\n clientValues.getSelectorForType(idType));\n }\n return dtos;\n</code></pre>\n\n<p><strong>Advantage:</strong> an new \"report type\" would only require a new entry in <code>idsByType</code> and \nmaybe a new entry in <code>valuesByType</code> if the client has another special method for fetching \nthan values.</p>\n\n<h2>Improvement 2</h2>\n\n<p>The same approach can simplify <code>buildDtos</code> too.</p>\n\n<p>Again we start by creating an <code>enum</code>:</p>\n\n<pre><code>enum ProductValuesBuilderFacade {\n SEVEN_DAY_VALUES(7) {\n ProductValuesDto setValueTo(\n ProductValuesDto builder, BigDecimal value) {\n return builder.sevenDayValue(value);\n }\n },\n THIRTY_DAY_VALUES(30) {\n ProductValuesDto setValueTo(\n ProductValuesDto builder, BigDecimal value) {\n return builder.thirtyDayValue(value);\n }\n },\n NINETY_DAY_VALUES(90) {\n ProductValuesDto setValueTo(\n ProductValuesDto builder, BigDecimal value) {\n return builder.ninetyDayValue(value);\n }\n },\n THREE_HUNDRED_SIXTY_FIVE_DAY_VALUES_DAY_VALUES(365) {\n ProductValuesDto setValueTo(\n ProductValuesDto builder, BigDecimal value) {\n return builder.threeHundredSixtyFiveDayValue(value);\n }\n };\n\n private final long timeOffsetInDays;\n\n ProductValuesBuilderFacade(long timeOffsetInDays) {\n this.timeOffsetInDays = timeOffsetInDays;\n }\n\n abstract ProductValuesDto setValueTo(\n ProductValuesDto builder, BigDecimal bigDecimal);\n\n public LocalDate getStartDate(LocalDate endDate) {\n return endDate.minusDays(timeOffsetInDays);\n }\n}\n</code></pre>\n\n<p>This gives us the opportunity to iterate over its constants inside the method:</p>\n\n<pre><code>public void buildDtos(\n List<ProductValuesDto> dtos,\n List<String> productIds,\n ValueSelector valueSelector) {\n for (String productId : productIds) {\n ProductValuesDto dto = ProductValuesDto.builder(productId);\n ProductValuesBuilderFacade[] productValuesBuilderFacades =\n ProductValuesBuilderFacade.values();\n for (ProductValuesBuilderFacade productValuesBuilderFacade \n : productValuesBuilderFacades) {\n Map<String, BigDecimal> allValuesForDate \n = valueSelector.selectFrom(\n client,\n productIds,\n productValuesBuilderFacade\n .getStartDate(endDate),\n endDate);\n dto = productValuesBuilderFacade.setValueTo(\n dto,\n allValuesForDate.getOrDefault(productId, BigDecimal.ZERO));\n }\n dtos.add(dto.build());\n }\n}\n</code></pre>\n\n<p><strong>Advantages</strong>: </p>\n\n<ul>\n<li>again the <code>enum</code> can live in its own file.</li>\n<li>a new setter method in the DTO requires only a new constant in the <code>enum</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T21:22:53.617",
"Id": "469139",
"Score": "0",
"body": "Thank you for providing a solution. The `FunctionalInterface` seems like a great way to refactor the code. `client.getBaselineValues` and `client.getValues` do very different things although they return the same type of data. I think that may explain why the 3rd party developer chose different methods. As you noted though, that knowledge could be hidden from its clients by allowing a special value for the `String` param to return the same result as `client.getValues`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T09:40:13.173",
"Id": "469160",
"Score": "0",
"body": "@James *\"seems like a great way to refactor the code.\"* It is just a technical detail. The \"way\" to refactor code is: convert *similar looking code* into *equal looking code* so that the duplication becomes obvious and your IDE can support you resolving the duplication."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-03T20:45:17.390",
"Id": "470581",
"Score": "0",
"body": "Thanks for the comment. By the way, I believe the `buildDtos` method in Improvement 2 has an issue. The outer loop iterates over `productIds` while inner loop calls `selectFrom` for all `productIds`. So, `selectFrom` is called once for every product id & `ProductValuesBuilderFacade` but it only needs to be called once per `ProductValuesBuilderFacade`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-04T08:46:07.347",
"Id": "470597",
"Score": "0",
"body": "@James *\"I believe the `buildDtos` method in Improvement 2 has an issue.\"* **---** maybe. But on one hand this site is not focused on correctness, My aim was to provide a \"recipe\" for the improvement, not a working solution. And for second you did not provide a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) including UnitTests to support stable behavior while refactoring..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-06T15:36:55.963",
"Id": "470814",
"Score": "0",
"body": "@ Timothy Truckle, I'm very grateful for your solution & I hope that my comment did not come off as unappreciative. When I went to incorporate your improvements into my code, I simply noticed the unwanted `client` calls (which are slow). To eliminate that, it resulted in `builDtos` being a bit more involved. Besides getting thoughts about if I was maybe missing something, I was trying to provide general acknowledgement of the issue for anyone else reading this post. Your point is taken though & once again, I very much appreciate all your time & work to provide a thoughtful solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-06T21:44:55.457",
"Id": "470873",
"Score": "0",
"body": "@James All is good. I'm self confident enough to not taking your reply personal. I just wanted you to know why correctness was not so much in my mind. No offense intended on my side too."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T20:05:37.643",
"Id": "239157",
"ParentId": "239151",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "239157",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T18:20:07.413",
"Id": "239151",
"Score": "5",
"Tags": [
"java"
],
"Title": "Getting key-values for set of date ranges by calling different lib methods and using results to create DTOs"
} | 239151 |
<p>The question is from <em>Automate the Boring Stuff with Python</em> and asks us to find the number of streaks of six heads or six tails that come up when a coin is tossed 100 times.</p>
<blockquote>
<h2>Coin Flip Streaks:<br><br></h2>
<p>For this exercise, we’ll try doing an experiment. If you flip a coin 100 times and write down an “H” for each heads and “T” for each tails, you’ll create a list that looks like “T T T T H H H H T T.” If you ask a human to make up 100 random coin flips, you’ll probably end up with alternating head-tail results like “H T H T H H T H T T,” which looks random (to humans), but isn’t mathematically random. A human will almost never write down a streak of six heads or six tails in a row, even though it is highly likely to happen in truly random coin flips. Humans are predictably bad at being random.</p>
<p>Write a program to find out how often a streak of six heads or a streak of six tails comes up in a randomly generated list of heads and tails. Your program breaks up the experiment into two parts: the first part generates a list of randomly selected 'heads' and 'tails' values, and the second part checks if there is a streak in it. Put all of this code in a loop that repeats the experiment 10,000 times so we can find out what percentage of the coin flips contains a streak of six heads or tails in a row. As a hint, the function call random.randint(0, 1) will return a 0 value 50% of the time and a 1 value the other 50% of the time.</p>
</blockquote>
<p><strong>My Solution:</strong></p>
<pre><code>def streakFinder(inputList):
import copy
count=0
delList=copy.copy(inputList) # The list is copied to another reference so that it can be safely modified without affecting the original list
try: # When the last element remains, there is no element left that can calculate the difference-->['H','H']
while len(delList)!=0:
i=0
if delList[i]=='H':
j=delList.index('T')
else:
j=delList.index('H')
if j-i>=6:
count+=1
del delList[i:j]
except: # The error generated is dealt here.
if len(delList)>=6:
count+=1
return count
</code></pre>
<p><br>
The inputList is the randomly generated list of H and T resulting from 100 coin tosses.<br><br>
My solution gives me the correct answer. However, I would like to know if there is a better way to approach or solve this problem. If there are any errors, please point them out as I'm a beginner.</p>
| [] | [
{
"body": "<h2>List copying</h2>\n\n<p>Are you sure you need a deep copy? Probably you can get away with a shallow copy, in which case</p>\n\n<p><code>del_list = list(input_list)</code></p>\n\n<h2>Type hints</h2>\n\n<p><code>def streakFinder(inputList):</code></p>\n\n<p>can probably be</p>\n\n<p><code>def streak_finder(input_list: Iterable[int]) -> int</code></p>\n\n<p>Note that even if you always pass in a <code>list</code>, you don't strictly <em>need</em> to pass in a list; you can pass in any iterable. So indicate the broadest useful type to your callers.</p>\n\n<p>Also note the use of snake_case in those names.</p>\n\n<h2>Too-broad <code>except</code></h2>\n\n<p>(Nearly) never just <code>except</code>. If you have an infinite loop, for instance, this will prevent Ctrl+C break from working. Instead, catch the specific exception type that you're anticipating.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T06:59:13.460",
"Id": "469235",
"Score": "0",
"body": "How to catch a specific exception type?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T13:54:40.607",
"Id": "469250",
"Score": "2",
"body": "`except ValueError:` for example"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T14:51:27.053",
"Id": "469255",
"Score": "1",
"body": "`del_list = input_list[:]` is a shorter way to copy the list."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T14:55:24.090",
"Id": "469257",
"Score": "2",
"body": "It's shorter but it always strikes me as less legible and more of a hack. You have to understand implicit array slicing to understand why that works."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T15:19:26.740",
"Id": "469354",
"Score": "0",
"body": "@AJNeufeld But that would means that del_list and input_list both have the same reference and thus changing one would change the other, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T15:19:49.230",
"Id": "469355",
"Score": "1",
"body": "Nope - that actually does copy the list."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T15:24:32.777",
"Id": "469356",
"Score": "1",
"body": "@Reinderien What is the difference between del_list = input_list and del_list = input_list[:]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T15:25:30.693",
"Id": "469357",
"Score": "2",
"body": "The former is a direct assignment. The latter is a slice, and slices always copy to a new list."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T15:27:24.807",
"Id": "469358",
"Score": "1",
"body": "@Harshil `input_list[:]`, on the right side of an assignment statement or as an argument in a function call, takes elements of `input_list`, from the first to the last, and returns it as a new list. When used on the left side of an assignment statement, it will modify `input_list`."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T02:42:45.463",
"Id": "239164",
"ParentId": "239154",
"Score": "5"
}
},
{
"body": "<p>Python has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a>, which recommends using <code>lower_case</code> for both functions and variables. Since this is a programming challenge, you can probably not change the function name, but the variable names are fully under your control. PEP 8 also recommends surrounding <code>=</code> with spaces when used for assignment and the same for binary operators (like <code>!=</code>, but also augmented assignment like <code>+=</code>).</p>\n\n<p>Imports should usually go into the global scope, at the top of your code. One exception are functions that are used only for testing and would pollute the global namespace unnecessarily, but this is not the case here. </p>\n\n<p>In general, empty collections are falsey in Python, and non-empty collections are truthy. This means that instead of <code>while len(delList)!=0</code> you can just do <code>while delList</code>.</p>\n\n<p>You have a potential bug / the problem description is not explicit enough / their tests don't have enough coverage. You count all streaks of at least length six, the text reads such that only streaks of exactly length six count. But apparently their tests don't throw longer streaks at your code, or implement something different from the problem description as well.</p>\n\n<p>Don't be afraid to use Python's standard library, it has many tools that can make your life a lot easier. In this case I would use <a href=\"https://docs.python.org/3/library/itertools.html#itertools.groupby\" rel=\"noreferrer\"><code>itertools.groupby</code></a> to group the tosses by their result. After this it becomes very easy to get the length of each streak and count all instances of that length being at least six using a <a href=\"https://wiki.python.org/moin/Generators\" rel=\"noreferrer\">generator expression</a> with the built-in function <code>sum</code>:</p>\n\n<pre><code>from itertools import groupby\n\ndef streakFinder(tosses):\n return sum(1 for _, streak in groupby(tosses) if len(list(streak)) >= 6)\n</code></pre>\n\n<p>This should be significantly faster than your solution as well, because it only goes through the list exactly once. Your code has repeated calls to <code>list.index</code>, which starts iterating at the front every time.</p>\n\n<p>Note that the random toss generation, which in the problem description is recommended to use <code>random.randint</code> and which you do not show, could be very short using <a href=\"https://docs.python.org/3/library/random.html#random.choices\" rel=\"noreferrer\"><code>random.choices</code></a>:</p>\n\n<pre><code>import random\n\ntosses = random.choices([\"H\", \"T\"], k=100)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T07:39:55.330",
"Id": "239171",
"ParentId": "239154",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "239171",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T19:13:16.167",
"Id": "239154",
"Score": "6",
"Tags": [
"python"
],
"Title": "Coin Flip Streaks"
} | 239154 |
<h2>Background</h2>
<p>Traversing the file hierarchy, going through files and sub-directories from a directory, is a quite common task when doing file system search operations of some sorts. I have already encountered multiple applications where I need to do this as a part of my solution, so I figured I should put this code in a separate library.</p>
<h2>Goal</h2>
<p>I am trying to write a very small library for file and directory traversal, where simplicity and performance is favored over feature richness. My intention is however that the design of this library should not limit any programmer using it for their own application, which why I have made the <code>FileWalker</code> implement the <code>Iterator</code> trait.</p>
<p>With <em>file and directory traversal</em> I mean, that I should for a directory with a given path, be able to iterate through all files and sub-directories in that directory, and recursively content of sub-directories. This should be repeated until all files and directories have been "consumed", or until a maximum recursion depth has been reached.</p>
<h2>Code</h2>
<p>The full project can be found at <a href="https://github.com/mantono/walker" rel="nofollow noreferrer">GitHub</a>, current commit at time of writing is <a href="https://github.com/mantono/walker/tree/a7c84e2762f66a476cb26d14b16a26c664d9420f" rel="nofollow noreferrer">a7c84e27</a>. All Rust source code is however included in this post.</p>
<pre class="lang-rust prettyprint-override"><code>use std::collections::VecDeque;
use std::fs;
use std::fs::{Metadata, ReadDir};
use std::path::PathBuf;
#[derive(Default)]
pub struct FileWalker {
files: VecDeque<PathBuf>,
dirs: VecDeque<PathBuf>,
origin: PathBuf,
max_depth: u32,
follow_symlinks: bool,
}
impl FileWalker {
/// Create a new FileWalker starting from the current directoty (path `.`).
/// This FileWalker will not follow symlinks and will not have any limitation
/// in recursion depth for directories.
pub fn new() -> FileWalker {
FileWalker::for_path(&PathBuf::from("."), std::u32::MAX, false)
}
/// Create a new FileWalker for the given path, while also specifying the
/// max recursion depth and if symlinks should be followed or not.
///
/// With a directory structure of
///
/// ```yaml
/// test_dirs:
/// - file0
/// sub_dir:
/// - file1
/// - file2
/// ```
///
/// the FileWalker should return the files as following
/// ```
/// use std::path::PathBuf;
///
/// let path = PathBuf::from("test_dirs");
/// let max_depth: u32 = 100;
/// let follow_symlinks: bool = false;
/// let mut walker = walker::FileWalker::for_path(&path, max_depth, follow_symlinks);
///
/// assert_eq!(Some(PathBuf::from("test_dirs/file0").canonicalize().unwrap()), walker.next());
/// assert_eq!(Some(PathBuf::from("test_dirs/sub_dir/file2").canonicalize().unwrap()), walker.next());
/// assert_eq!(Some(PathBuf::from("test_dirs/sub_dir/file1").canonicalize().unwrap()), walker.next());
/// assert_eq!(None, walker.next());
/// ```
pub fn for_path(path: &PathBuf, max_depth: u32, follow_symlinks: bool) -> FileWalker {
if !path.is_dir() {
panic!("Path is not a directory: {:?}", path);
}
let mut dirs = VecDeque::with_capacity(1);
dirs.push_back(path.clone());
let files = VecDeque::with_capacity(0);
FileWalker {
files,
dirs,
origin: path.clone(),
max_depth,
follow_symlinks,
}
}
fn load(&self, path: &PathBuf) -> Result<(Vec<PathBuf>, Vec<PathBuf>), std::io::Error> {
let path: ReadDir = read_dirs(&path)?;
let (files, dirs) = path
.filter_map(|p| p.ok())
.map(|p| p.path())
.filter(|p: &PathBuf| self.follow_symlinks || !is_symlink(p))
.filter(is_valid_target)
.partition(|p| p.is_file());
Ok((files, dirs))
}
fn push(&mut self, path: &PathBuf) {
match self.load(path) {
Ok((files, dirs)) => {
self.files.extend(files);
let current_depth: u32 = self.depth(path) as u32;
if current_depth < self.max_depth {
self.dirs.extend(dirs);
}
}
Err(e) => log::warn!("{}: {:?}", e, path),
}
}
fn depth(&self, dir: &PathBuf) -> usize {
let comps0 = self.origin.canonicalize().unwrap().components().count();
let comps1 = dir.canonicalize().unwrap().components().count();
comps1 - comps0
}
}
impl Iterator for FileWalker {
type Item = PathBuf;
fn next(&mut self) -> Option<Self::Item> {
match self.files.pop_front() {
Some(f) => Some(f),
None => match self.dirs.pop_front() {
Some(d) => {
self.push(&d);
self.next()
}
None => None,
},
}
}
}
fn read_dirs(path: &PathBuf) -> Result<ReadDir, std::io::Error> {
let full_path: PathBuf = path.canonicalize()?;
Ok(fs::read_dir(full_path)?)
}
fn is_valid_target(path: &PathBuf) -> bool {
let metadata: Metadata = path.metadata().expect("Unable to retrieve metadata:");
metadata.is_file() || metadata.is_dir()
}
fn is_symlink(path: &PathBuf) -> bool {
match path.symlink_metadata() {
Ok(sym) => sym.file_type().is_symlink(),
Err(err) => {
log::warn!("{}: {:?}", err, path);
false
}
}
}
#[cfg(test)]
mod tests {
use crate::FileWalker;
use std::path::PathBuf;
const TEST_DIR: &str = "test_dirs";
#[test]
fn test_depth_only_root_dir() {
let dir = PathBuf::from(TEST_DIR);
let found = FileWalker::for_path(&dir, 0, false).count();
assert_eq!(1, found);
}
#[test]
fn test_depth_one() {
let dir = PathBuf::from(TEST_DIR);
let found = FileWalker::for_path(&dir, 1, false).count();
assert_eq!(3, found);
}
}
</code></pre>
<h2>Concerns & Priorities</h2>
<ul>
<li>Performance - I do not have a lot of experience or know-how when it comes to performance and performance optimization in Rust. Any feedback on how I improve performance is most welcome.</li>
<li>Testing - I have written two test cases, and included some doctest in the documentation for <code>FileWalker::for_path</code>, but I am not sure if I should consider this enough. I would have preferred a setup where I could run these test cases without actual files being present on the hard drive or a part of the project when running tests, I don't know how realistic that is. Maybe it is more job than it is worth. The files used for testing can be found in the GitHub repo.</li>
<li>Documentation - Is something unclear? I have only documented public methods, should make some further documentation?</li>
</ul>
<p>Other feedback and input is of course most welcome as well!</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T22:19:47.603",
"Id": "239159",
"Score": "2",
"Tags": [
"file-system",
"rust"
],
"Title": "Implementing A File and Directory Traversal Iterator in Rust"
} | 239159 |
<p>I've written a function which should generate an ISO 8601 duration string, given two Dates as input.</p>
<pre class="lang-js prettyprint-override"><code>import {
differenceInYears,
differenceInMonths,
differenceInWeeks,
differenceInDays,
getDaysInYear,
eachYearOfInterval,
} from 'date-fns/esm'; // v2.11.0
/**
* Given a start Date and an end Date, returns an ISO 8601 duration string
* Only supports Year, Month, Week, and Day. Does not support Hour or smaller.
* @param {Date} start
* @param {Date} end
* @return {string} ISO 8601 Duration
* @example
* ```js
* toISODurationString(new Date('2020'), new Date('2021'));
* // => PY1
* ```
*/
export function toISODurationString(start, end) {
const differenceInDaysOverYears =
eachYearOfInterval({ start, end })
.map(getDaysInYear)
.map(days => days % 365)
.reduce(add) - 365;
const Y = differenceInYears(end, start);
const M = differenceInMonths(end, start) - 12;
const W = differenceInWeeks(end, start) - 52;
const D = differenceInDays(end, start) - (365 + differenceInDaysOverYears);
return Object.entries({ Y, M, W, D })
.reduce((s, [c, v]) => `${s}${v !== 0 ? c + v : ''}`, 'P');
}
</code></pre>
<p>I'm concerned about the <code>differenceInDaysOverYears</code> part. Is this code reliable? Specifically, will it robustly handle any Date you give it?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T06:11:33.450",
"Id": "469231",
"Score": "0",
"body": "What will happen in `days % 365` if a year has `366` days?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T16:43:48.810",
"Id": "469270",
"Score": "0",
"body": "`differenceInDaysOverYears` will increment by 1 for each such year in the interval. `const add = (x, y) => x + y`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T16:49:36.290",
"Id": "469271",
"Score": "0",
"body": "Will it be (366 % 365) - 365 == -364 ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T17:11:40.743",
"Id": "469272",
"Score": "0",
"body": "`const D = differenceInDays(end, start) - (365 + differenceInDaysOverYears);` so we have the total difference in days, say for a 1 year interval of 366 days === 366, minus the typical year, minus the delta, equals 0"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T23:05:51.087",
"Id": "239160",
"Score": "2",
"Tags": [
"javascript",
"datetime"
],
"Title": "Generate ISO 8601 Duration String from Two Date Objects"
} | 239160 |
<p>When I was not sure about how to do this, I asked <a href="https://stackoverflow.com/q/60731020/5825294">this question</a> on StackOverflow, the body of which is the following:</p>
<blockquote>
<p>As regards line numbers, when doing normal file editing, I prefer to
have the following setting</p>
<pre><code>set number
set relativenumber
</code></pre>
<p>because the former tells me where I am, the latter helps me using
<kbd>j</kbd> and <kbd>k</kbd> effectively.</p>
<p>However, when <a href="https://www.dannyadam.com/blog/2019/05/debugging-in-vim/" rel="nofollow noreferrer">debugging with
<code>gdb</code></a>,
using the <code>termdebug</code> package and the <code>:Termdebug</code> command, I often
want to set breakpoints; hence, I'd like to turn the latter option
off, executing the <code>set norelativenumber</code> command on a global scope,
so that all files I'm editing show the actual line numbers.</p>
</blockquote>
<p>Reading the answer, and Vim help pages a bit more, I ended up with the following solution, which is now part of my <code>~/.vimrc</code> file:</p>
<pre><code>" Source the termdebug plugin
packadd termdebug
" Add mapping to load termdebug
noremap <silent> <Leader>td :call MyTermdebug()<CR>
" turn off relativenumber,
" start Termdebug,
" and create autocmd to turn relativenumber back on
function! MyTermdebug()
call SetRelNumInAllWin(v:false)
augroup ClosingDebugger
au!
autocmd BufUnload !gdb call SetRelNumInAllWin(v:true)
augroup END
Termdebug
endfunction
" set/unset relativenumber in all windows if flag is v:true/v:false
function! SetRelNumInAllWin(flag)
let current_win_id = win_getid()
tabdo windo call SetRelNum(a:flag)
call win_gotoid(current_win_id)
endfunction
" set/unset relativenumber in current window if flag is v:true/v:false
function! SetRelNum(flag)
if &number
if a:flag
set relativenumber
else
set norelativenumber
end
end
endfunction
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T19:41:52.477",
"Id": "469205",
"Score": "2",
"body": "[What you may and may not do after receiving answers](https://codereview.meta.stackexchange.com/a/1765). I've rolled back Rev 2 → 1."
}
] | [
{
"body": "<p>Two things off the top of my head:</p>\n\n<p>Use mode-specific mappings, so <code>nnoremap</code> limits the mapping to normal mode. (Great job on the use of non-recursive mappings.)</p>\n\n<p>You can access options as vimscript variables with <code>&relativenumber</code>. <code>SetRelNum</code> is sort of unecessary: I would have written</p>\n\n<pre><code>tabdo windo let &relativenumber = a:flag\n</code></pre>\n\n<p>(And if that doesn’t work because of some odd scope rule, you can <code>exec</code> it with everything but <code>a:flag</code> in quotes. You may have to pass <code>0</code>/<code>1</code> instead of <code>v:false</code>/<code>v:true</code> etc.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T15:00:27.397",
"Id": "469184",
"Score": "1",
"body": "Concerning `nore`* I have just absorbed the lesson \"use non-recursive mappings by default, unless you need recursion **and** you really know what you are doing\". That oneliner you suggested is great! I'll check and adjust if needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T17:16:14.530",
"Id": "469196",
"Score": "0",
"body": "Yes, I had to use 0/1 instead of `v:false`/`v:true`. However I am thinking about a usability contraddiction in my solution. Since I want to take advantage of `rnu` when navigating the files, and I want to deactivate it just when I'm in the `!gdb` window where I run the `break` command, it would make sense to set and unset `rnu` in all windows everytime move from/to the `!gdb` window."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T17:17:51.927",
"Id": "469197",
"Score": "1",
"body": "There are some BufWinEnter style events you can look into for that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T17:25:08.413",
"Id": "469198",
"Score": "0",
"body": "Yes, but I kinda remember that the termdebug buffer has something special, as regards the events. If I have issues, I'll post a question on stack overflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T17:25:34.527",
"Id": "469199",
"Score": "0",
"body": "Ok! Remember [vi.se] exists as well!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T19:24:53.483",
"Id": "469203",
"Score": "1",
"body": "I was wrong, using those events with the gdb window seems perfectly fine."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T14:52:29.627",
"Id": "239192",
"ParentId": "239161",
"Score": "2"
}
},
{
"body": "<p>I realized that deactivating <code>rnu</code> when I start <code>:Termdebug</code> is unproductive, as the option remains inactive even when I'm navigating the scripts while the <code>!gdb</code> window is open.</p>\n<p>So I ended up with this solution, where <code>rnu</code> is off only if the cursor is in the <code>!gdb</code> window; as soon as the cursor moves away from it, <code>rnu</code> is turned on.</p>\n<pre><code>" mapping and function to start gdb and activate "smart" relativenumber\nnnoremap <silent> <Leader>td :call TermdebugAndRelNumOff()<CR>\nfunction! TermdebugAndRelNumOff()\n augroup ClosingDebugger\n au!\n " set/unset rnu when leaving/entering gdb window\n autocmd BufLeave !gdb call SetRelNumInAllWin(1)\n autocmd BufEnter !gdb call SetRelNumInAllWin(0)\n " delete the augroup (and its autocmd-s) when closing gdb\n autocmd BufUnload !gdb au! | augroup! ClosingDebugger\n augroup END\n " start Termdebug\n Termdebug\nendfunction\n</code></pre>\n<p><strong>NOTE</strong></p>\n<p>The use of <code>windo</code> has the undesirable behavior of altering the window which <kbd>Ctrl</kbd>+<kbd>p</kbd> will jump to: once I move <em>to</em> the <code>!gdb</code> window from <code>ThisWindow</code>, those keys will jump to the bottom-right window instead of to <code>ThisWindow</code>. I'm trying to address this annoying thing <a href=\"https://vi.stackexchange.com/questions/26852/how-can-i-alter-the-window-to-which-ctrlp-will-jump-to\">here</a>.</p>\n<p><strong>NOTE2</strong></p>\n<p>Since moving away from the <code>!gdb</code> window makes no sense if that window is not in the current tab, and since moving to it from a tab which does not contain it is unlikely (or is it non-sense too?), I suspect that <code>tabdo</code> can be avoided entirely in the definition of <code>SetRelNumInAllWin</code> given in the question.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T19:59:26.247",
"Id": "239205",
"ParentId": "239161",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "239192",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-19T23:31:56.033",
"Id": "239161",
"Score": "2",
"Tags": [
"vimscript"
],
"Title": "Turning relativenumber option off/on when opening/closing the gdb terminal window"
} | 239161 |
<p>I have the following working code</p>
<pre><code>import numpy as np
r = np.loadtxt('CoordUnwrapped/ParticleCoordU.5000',skiprows=9,usecols = (4,5,6))
rcom = np.loadtxt('hexaCOM/COMA/COMA.5000',skiprows=10,usecols = (4,5,6))
N = 50
Sx1= []
Sx2 = []
Sx3 = []
for i in range(0,N):
S_data_1 = (r[i,0]-rcom[0,0])**2)
S_data_2 = (r[i+N,0]-rcom[1,0])**2)
S_data_3 = (r[i+2*N,0]-rcom[2,0])**2)
Sx1.append(S_data_1)
Sx2.append(S_data_2)
Sx3.append(S_data_3)
data = np.array([Sx1,Sx2,Sx3])
x = np.average(data, axis=0)
</code></pre>
<p>The problem that I'm facing is that I am looking to obtain 400 Sx vectors and with this format it is not really feasible. Just to be clear this is a snapshot of what I am looking to get at the end:</p>
<pre><code>N = 50
Sx1= []
Sx2 = []
Sx3 = []
.
.
.
Sx400 = []
for i in range(0,N):
S_data_1 = (r[i,0]-rcom[0,0])**2)
S_data_2 = (r[i+N,0]-rcom[1,0])**2)
S_data_3 = (r[i+2*N,0]-rcom[2,0])**2)
.
.
.
S_data_400 = (r[i+399*N,0]-rcom[399,0]**2)
Sx1.append(S_data_1)
Sx2.append(S_data_2)
Sx3.append(S_data_3)
data = np.array([Sx1,Sx2,Sx3,...,Sx400])
x = np.average(data, axis=0)
</code></pre>
<p>As you can see this approach is too time consuming and not efficient at all. Any suggestions would be great. Thank you!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T13:17:38.987",
"Id": "469171",
"Score": "0",
"body": "You may want to read some Python books or tutorials. Solving this issue was taught to my class in the first couple of lessons of formal (high school) education."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T15:56:23.297",
"Id": "469189",
"Score": "0",
"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](https://codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
}
] | [
{
"body": "<p>There isn't any need to name all your Sx variables and copy+paste the code to build each one; just build them in another loop. You can do both loops as list comprehensions very concisely:</p>\n\n<pre><code>data = np.array([\n [(r[i+s*N, 0] - rcom[s, 0])**2 for i in range(N)] \n for s in range(400)\n])\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T04:51:00.010",
"Id": "239168",
"ParentId": "239165",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "239168",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T03:39:39.577",
"Id": "239165",
"Score": "0",
"Tags": [
"python",
"performance",
"python-3.x"
],
"Title": "Current python for loop not efficent"
} | 239165 |
<p>My problem is I'm having a table and 7 child table. I'm fetching details using querying the main table first then querying the child tables one by one sequentially. To improve performance I decided to execute all the seven queries parallely using completable future.</p>
<pre><code> StoryDetail storyDetail = new StoryDetail();
CompletableFuture<IStoryDetail> iStoryDetailCompletableFuture = CompletableFuture
.supplyAsync(() -> storyRepository.getStoryDetails(id), executorService);
CompletableFuture<List<Comment>> iCommentFuture = CompletableFuture
.supplyAsync(() -> commentRepository.getComments(id), executorService);
CompletableFuture<List<Images>> iImageFuture = CompletableFuture
.supplyAsync(() -> imageRepository.getImagesByStoryId(id), executorService);
</code></pre>
<p>Here we are executing all the queries sequentially:</p>
<pre><code>CompletableFuture.allOf(iCommentFuture, iStoryDetailCompletableFuture, iImageFuture)
;
</code></pre>
<p>And waits for all of them to finish then sets the value in the <code>StoryDetail</code> object:</p>
<pre><code> storyDetail.setComments(iCommentFuture.get());
storyDetail.setImages(iImageFuture.get());
mapStoryDetail(iStoryDetailCompletableFuture.get(), storyDetail);
</code></pre>
<p>Is the approach correct?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T09:59:25.723",
"Id": "469161",
"Score": "1",
"body": "\"is the approach correct\" Did you test it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T22:58:28.387",
"Id": "469220",
"Score": "0",
"body": "it seems to be working fine"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T23:06:08.220",
"Id": "469440",
"Score": "0",
"body": "So that you see this (and to make it a little more clear) - @mtj's answer contains a very large \"But...\"; **generally**, the database server is already going to execute (some or all) of your query in parallel. There are further weird tricks it can do, as well. Except in some extreme circumstances, a database query with multiple `JOIN`s is going to beat manually executing multiple per-table statements. That's actually the whole point of SQL - to abstract access patterns, in favor of declaring the connections required of the data."
}
] | [
{
"body": "<p>Yes, your approach is correct.</p>\n\n<p>However, you parallelize various queries, which probably go to a remote backing database. As you told us nothing about the runtime of these queries, the nature of the database, the complexity of the underlying statements, I can only ask you to <strong><em>measure</em></strong>.</p>\n\n<p>Parallelism induces overhead - in the runtime AND in program complexity. Check, whether it is worth it, and where your bottlenecks lie.</p>\n\n<p>In my experience from enterprise applications, real big data transfers are normally not made better by parallelism, as the bottleneck is often the network between application server and database.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T06:12:28.130",
"Id": "239304",
"ParentId": "239166",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T04:11:50.370",
"Id": "239166",
"Score": "2",
"Tags": [
"java",
"multithreading"
],
"Title": "Parallel SQL queries using completable future"
} | 239166 |
<blockquote>
<p>Design a class called Post. This class models a StackOverflow post. It should have properties
for title, description and the date/time it was created. We should be able to up-vote or down-vote
a post. We should also be able to see the current vote value. In the main method, create a post,
up-vote and down-vote it a few times and then display the the current vote value.</p>
<p>In this exercise, you will learn that a StackOverflow post should provide methods for up-voting
and down-voting. You should not give the ability to set the Vote property from the outside,
because otherwise, you may accidentally change the votes of a class to 0 or to a random
number. And this is how we create bugs in our programs. The class should always protect its
state and hide its implementation detail.</p>
<p>Educational tip: The aim of this exercise is to help you understand that classes should
encapsulate data AND behaviour around that data. Many developers (even those with years of
experience) tend to create classes that are purely data containers, and other classes that are
purely behaviour (methods) providers. This is not object-oriented programming. This is
procedural programming. Such programs are very fragile. Making a change breaks many parts
of the code.</p>
</blockquote>
<p>That is the information given to me for this exercise in my C# tutorial. The following is my working code. Still trying to grasp Object Oriented Programming. I believe I did set the properties so that you can get the information but <em>not give the ability to set the Vote property from the outside</em> by setting the property to Private. I also tried to protect the state of voting so that you could not up-vote or down-vote consecutively, yet allow it to change your vote and show the vote count along with protecting the state of the vote count.</p>
<p>Anyhow if anyone can see how to improve on this, point out a better way, or teach me something new I would greatly appreciate it.</p>
<pre><code>using System;
namespace ExerciseTwo
{
class Post
{
public string Title { get; set; }
public string Description { get; set; }
public DateTime TimeDateCreated { get; private set; }
public int VoteCount { get; private set; }
private bool HasVotedUp;
private bool HasVotedDown;
public Post(string title, string description)
{
Title = title;
Description = description;
TimeDateCreated = DateTime.UtcNow;
VoteCount = 0;
}
public void VoteUp()
{
if (HasVotedUp)
{
throw new Exception("You have already up-voted.");
}
else
{
VoteCount++;
HasVotedUp = true;
HasVotedDown = false;
}
}
public void VoteDown()
{
if (HasVotedDown)
{
throw new Exception("You have already down-voted.");
}
else
{
VoteCount--;
HasVotedDown = true;
HasVotedUp = false;
}
}
}
}
</code></pre>
<p>Script to demo how it could work.</p>
<pre><code>namespace ExerciseTwo
{
class Program
{
static void Main()
{
Post post = new Post("Does my post work?", "Test to see if my post works.");
System.Console.WriteLine($"Title: {post.Title}");
System.Console.WriteLine($"Description: {post.Description}");
System.Console.WriteLine($"Date Created: {post.TimeDateCreated}");
System.Console.WriteLine($"Post Count: {post.VoteCount}");
post.VoteDown();
System.Console.WriteLine($"Post Count: {post.VoteCount}");
post.VoteUp();
System.Console.WriteLine($"Post Count: {post.VoteCount}");
}
}
}
</code></pre>
<p>Thank you for your help!</p>
| [] | [
{
"body": "<p>I don't know which version of C# you use, but as of C# 6 it's possible to set initial values on property definition, which has 2 advantages:</p>\n\n<ul>\n<li>Can eyeball the initial values quickly by looking at the property definitions.</li>\n<li>Doesn't require you to copy the same initial value assignment code into additional constructors you may create.</li>\n</ul>\n\n<p>Example initial value definition:</p>\n\n<pre><code>public int VoteCount { get; private set; } = 0;\n</code></pre>\n\n<p>Also in the case of <code>int</code> with initial value <code>0</code> you don't have to explicitly set it because when an instance of the class is initialized all the <code>int</code>s are initialized with the default value <code>0</code> unless you specified otherwise. Just like the <code>bool</code>s are <code>false</code> by default (you didn't set them in the constructor).</p>\n\n<hr>\n\n<p>You could add another layer of protection to the creation date:</p>\n\n<pre><code>public DateTime TimeDateCreated { get; } = DateTime.UtcNow;\n</code></pre>\n\n<p>Without defining a setter, <code>TimeDateCreated</code> is set when you create an instance of <code>Post</code> and can never be changed again for that instance. It makes sense here because the only date you'd ever want to change on a post is the date it was edited.</p>\n\n<hr>\n\n<p>Not a big deal for now, but it's better to develop early the habit of giving good variable names, this means being descriptive, concise and consistent with the naming of things around the code base. Most of your names are good, but <code>TimeDateCreated</code> is a bit counter-intuitive because once you'll get used to the name <code>DateTime</code> you'll expect this property to be named <code>DateTimeCreated</code>.</p>\n\n<hr>\n\n<p>It's good that you protected <code>VoteCount</code>, but your vote function does something unwanted: if you first downvote and then upvote, you will be back to 0 votes but without the ability to upvote. I suggest you rethink this part of the code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T14:26:10.773",
"Id": "469177",
"Score": "0",
"body": "```public int VoteCount { get; private set; } = 0;``` I saw this recently but was not sure if this was ideal for this case. Now I know that it would be. Thanks for showing me this. \n```public DateTime TimeDateCreated { get; } = DateTime.UtcNow;```\nClasses and constructors are still new to me. I wasn't sure if this had to be set in the constructor. Another good point I need to learn. ```DateTimeCreated``` was the original name, but I thought to change it to what you see now thinking that might be confusing or too similar to the DateTime class. Guess I was wrong."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T14:31:37.927",
"Id": "469178",
"Score": "0",
"body": "```It's good that you protected VoteCount, but your vote function does something unwanted: if you first downvote and then upvote, you will be back to 0 votes but without the ability to upvote. I suggest you rethink this part of the code.```I didn't account for that. I'll have to think of a way to refactor that. Good catch and thank you for your help!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T14:32:22.830",
"Id": "469179",
"Score": "0",
"body": "You're welcome :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T14:41:48.090",
"Id": "469181",
"Score": "0",
"body": "```if (VoteCount == 0) VoteCount++;``` I added this to .VoteUp() and something similar to VoteDown(). Either this, or put one method inside of these and route this out there. I thought this was the easiest way to go about it at least."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T06:50:48.800",
"Id": "239170",
"ParentId": "239169",
"Score": "6"
}
},
{
"body": "<p>There is nothing to add more than @potato's answer. However, I just want to re-enforced the answer. </p>\n\n<p>The naming convention for <code>TimeDateCreated</code> can be changed to <code>CreatedOn</code> or <code>CreatedDate</code> or any related naming for creation date. The keynote here is that you don't need to specify the datatype name in the properties as the property is public and I clearly can see its datatype. Then, why should I need to include it in the its name ? since I know the datatype, I need to know what value should this property store. So, here comes the good naming convention. Doesn't matter short or long names, as long as it's describing the role of the property clearly. </p>\n\n<p>The other note is the <code>VoteUp()</code> and <code>VoteDown()</code>, there is no need for exceptions, just skip voting if user already voted. </p>\n\n<pre><code>// default : VoteCount == 0 (user did not up or down voted).\n// When upvote, VoteCount == 1\n// when downvote, VoteCount == VoteCount - 1\npublic void VoteUp()\n{\n if(VoteCount == -1 || VoteCount == 0)\n {\n VoteCount += 1;\n }\n}\n\npublic void VoteDown()\n{\n if(VoteCount == 0 || VoteCount == 1)\n {\n VoteCount -= 1;\n }\n}\n</code></pre>\n\n<p>Now, you can get rid of <code>HasVotedUp</code> and <code>HasVotedDown</code>. You only need to throw an exception if there is an actual process breaking. This means, exceptions used to throw an error if it's breaking one of your logic's core requirements. For instance, <code>Post</code> requires a title. So, every post must have a title. in this case we can do : </p>\n\n<pre><code> public Post(string title, string description)\n{\n if(string.IsNullOrEmpty(title)) { throw new ArgumentNullException(nameof(title)); }\n\n Title = title;\n Description = description;\n TimeDateCreated = DateTime.UtcNow;\n VoteCount = 0;\n}\n</code></pre>\n\n<p>so, you're enforcing the requirement here. This class won't be initiated unless there is a title with at least one character. </p>\n\n<p>While Voting, is an optional requirement, user can upvote, downvote, or nothing. User only can upvote or downvote once. If you throw an exception in this part, you'll break the whole process (which might store valid arguments). So, just skipping it with an <code>if</code> statement without any exceptions would be our best approach to not break the application. </p>\n\n<p>You have to use your reasoning judgement on your code, try always to link it to a real world application or use case, this would give you a really good judgement on what you will do next. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T01:23:53.570",
"Id": "469222",
"Score": "0",
"body": "How does your suggestion prevent the user from casting more than one up or down vote?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T01:30:17.583",
"Id": "469223",
"Score": "0",
"body": "@Milliorn I'm assign `1` and `0` and not incrementing. So, user can upvote, and down-vote whenever needed. if user up or dow voted more than once, it will just take the first one, and skip the rest."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T01:40:46.453",
"Id": "469224",
"Score": "1",
"body": "@Milliorn correction, I've totally missed one senario, where if the user is down-voted (so `VoteCount` would store one value of `-1`,`0`,`1`. I've updated the code as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T20:11:34.900",
"Id": "469280",
"Score": "0",
"body": "I went with your suggestion on using ```CreatedOn ```. It describes exactly what it is. It took me a few times of reading what you said and what the lesson said to understand why you suggested ```VoteUp()``` and ```VoteDown()```. Although I have some disagreements with this approach I went ahead and changed it to your suggestion since it functions the same way with less code. The instructor of the lesson doesn't make anymore details on what to expect and it still complies with the demands of the lesson."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T20:13:12.660",
"Id": "469281",
"Score": "0",
"body": "```if(string.IsNullOrEmpty(title)) { throw new ArgumentNullException(nameof(title)); }``` I did not think about this case. Good catch and suggestion!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T23:01:58.217",
"Id": "469301",
"Score": "0",
"body": "@Milliorn don't expect much detailed explanations in a real job task. You have to use your reasoning, and connect the dots together, because you will be expected to know what you are doing, and you expect the other end does not know a thing. I assume this is what your instructor tries to teach you. So, your instructor would give you some tips that would be enough to give you an idea that would help you to build your questions to get the full requirements of this task in order to deliver it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T23:08:48.470",
"Id": "469303",
"Score": "0",
"body": "@Milliorn I would encourage you to let the instructor review your current work, ask some questions, and get your answers, then go back and do the required adjustments, then review ..etc. until you cover all requirements."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T01:01:11.267",
"Id": "239214",
"ParentId": "239169",
"Score": "3"
}
},
{
"body": "<p>You have a couple of good answers. Since you are an experienced developer who is new to C#, I will address some other things.</p>\n\n<p><strong>Things you do quite well</strong></p>\n\n<ul>\n<li>Braces and indentation</li>\n<li>Naming (most of the time)</li>\n</ul>\n\n<p>For the last item, most of your naming is good. As @iSR5 mentions, <code>TimeDateCreated</code> could have a better name. I have been programming since the 1980's, and I went through those years of the variable name including the data type and scope. With .NET, this is no longer needed, but more so with .NET and C# usage, <strong><em>it is frowned upon</em></strong>.</p>\n\n<p><strong>Helpful links</strong></p>\n\n<p><a href=\"https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/naming-guidelines\" rel=\"nofollow noreferrer\">Naming Guidelines</a></p>\n\n<p><a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/inside-a-program/coding-conventions\" rel=\"nofollow noreferrer\">C# Coding Conventions</a></p>\n\n<p><strong>Spots for improvement</strong></p>\n\n<p>I would like to see an access modifier on class <code>Post</code>. Either <code>public</code> or <code>internal</code>. </p>\n\n<p>As @potato says, the creation date should be read-only. Likewise, you may want to add a <code>ModifiedDate</code>. This would be updated anytime the title and description are altered. Thinking ahead, there likely would be a <code>Content</code> to the post, and changing it would also affect <code>ModifiedDate</code>.</p>\n\n<p><strong>Voting By User (Version 2?)</strong></p>\n\n<p>Beyond that, your code looks decent. My remaining issue is the class design. A <code>Post</code> should have a 1-to-many relationship with users (voters). Just like here, you have created a post. I can vote on it, potato can vote on it, iSR5 votes, etc. I would think tracking the votes in your class should be redesigned to account for this. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T20:28:58.940",
"Id": "469283",
"Score": "0",
"body": "I went ahead with the suggestion ```CreatedOn```. I think it describes the property for what it is(or is it a field). I bookmarked those links. They will be useful later on. I changed the ```Post``` class to ```internal class Post```. I am still learning all the access modifiers. I changed ```CreateOn``` to ```public DateTime CreatedOn { get; } = DateTime.UtcNow;```. However, I am unsure if that makes it ```readonly```. If not, I believe then it would be if I set ```DateTime.UtcNow``` in the constructor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T20:32:09.203",
"Id": "469285",
"Score": "0",
"body": "As for ModifiedDate I like that suggestion and it be necessary if this was to be built on. Since the instructor did not request that I am leaving it now. Same goes with with the ```Voting By User (Version 2?)```. Both are required to make this work if it was to be taken further. However, I am leaving it out since it was not requested and the scope of this I believe was to just try to teach how to keep this in a valid state. Thank you for your continued help @Rick Davin."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T21:56:01.903",
"Id": "469292",
"Score": "1",
"body": "Yes @Milliorn, this is both read-only and auto-initialized: `public DateTime CreatedOn { get; } = DateTime.UtcNow;`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T12:51:45.713",
"Id": "239227",
"ParentId": "239169",
"Score": "2"
}
},
{
"body": "<p>Thank you to everyone that helped me out on this. This is what it has refactored into based on everyone's suggestions. Looks more concise and easy to read. Appreciate the advice so I can continue to learn C#.</p>\n\n<pre><code>using System;\n\nnamespace ExerciseTwo\n{\n internal class Post\n {\n public string Title { get; set; }\n public string Description { get; set; }\n public DateTime CreatedOn { get; } = DateTime.UtcNow;\n public int VoteCount { get; private set; } = 0;\n\n public Post(string title, string description)\n {\n if (string.IsNullOrEmpty(title)) { throw new ArgumentNullException(nameof(title)); }\n\n Title = title;\n Description = description;\n }\n\n public void VoteUp()\n {\n switch (VoteCount)\n {\n case -1:\n case 0:\n VoteCount += 1;\n break;\n }\n }\n\n public void VoteDown()\n {\n switch (VoteCount)\n {\n case 0:\n case 1:\n VoteCount -= 1;\n break;\n }\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T18:52:32.370",
"Id": "239281",
"ParentId": "239169",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T05:21:20.613",
"Id": "239169",
"Score": "6",
"Tags": [
"c#",
"object-oriented",
"properties",
"state"
],
"Title": "Section 2: Classes - Design a StackOverflow Post"
} | 239169 |
<p>I'm relatively new to Python and learned, that <a href="https://stackoverflow.com/questions/32594073/let-a-function-return-nothing-not-even-none-in-python-2-7-10-possible">function cannot return nothing, not even <code>None</code></a>. In my application I want to iterate over a list and keep all non-<code>None</code> results of a complicated function:</p>
<pre><code>def complicated_function(x):
if x < 0:
return "a"
elif x == 3.6:
return "b"
elif x == 4:
return None # Idealy here nothing should be returned
elif x > 10:
return "c"
else:
return "d"
</code></pre>
<p>I have three soltuions and my question is which would you recommend me to use and are there better ones?</p>
<h3>First solution</h3>
<pre><code>tmp = [complicated_function(x) for x in [-1, 2, 3.6, 4, 5, 20]]
ret = [x for x in tmp if x]
</code></pre>
<h3>Second solution</h3>
<pre><code>ret = [complicated_function(x) for x in [-1, 2, 3.6, 4, 5, 20] if complicated_function(x)]
</code></pre>
<h3>Third solution</h3>
<pre><code>ret = []
for x in [-1, 2, 3.6, 4, 5, 20]:
tmp = complicated_function(x)
if tmp:
ret.append(tmp)
</code></pre>
<p>I think the first solution is slow, if the list to iterate over is very large. The second solution seems to be bad if the complated_function is really expensive (in rumtime). The third solution seems to be ok, but <a href="https://stackoverflow.com/questions/30245397/why-is-a-list-comprehension-so-much-faster-than-appending-to-a-list">append is said to be significantly slower than list comprehension</a>.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T11:13:41.133",
"Id": "469163",
"Score": "3",
"body": "Which Python version are you using? In Python 3.8+ you can make your list comprehension less expensive by calling the function only once using the walrus operator."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T14:36:25.657",
"Id": "469180",
"Score": "0",
"body": "@Graipher How would the walrus operator work?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T14:45:04.597",
"Id": "469183",
"Score": "5",
"body": "`ret = [y for x in [-1, 2, 3.6, 4, 5, 20] if (y := complicated_function(x))]`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T15:00:56.320",
"Id": "469185",
"Score": "0",
"body": "@Graipher Thanks for your explanaition of the walrus operator. I'm using Python 3.7, but definitely will keep this in mind as an option when switching to 3.8."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T15:26:25.643",
"Id": "469187",
"Score": "2",
"body": "https://stackoverflow.com/a/48609910/7311767"
}
] | [
{
"body": "<p>You can use an intermediate generator function:</p>\n\n<pre><code>[y for y in (complicated_function(x) for x in <my_iterable>) if y is not None]\n</code></pre>\n\n<p>An alternative is changing <code>complicated_function</code> to become a generator that accepts an iterable, instead of a pure function:</p>\n\n<pre><code>def complicated_function(iterable):\n for x in iterable:\n if x < 0:\n yield \"a\"\n elif x == 3.6:\n yield \"b\"\n elif x == 4:\n continue\n elif x > 10:\n yield \"c\"\n else:\n yield \"d\"\n</code></pre>\n\n<p>and then: <code>list(complicated_function(<my_iterable>))</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T16:41:46.307",
"Id": "239198",
"ParentId": "239175",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "239198",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T08:52:49.743",
"Id": "239175",
"Score": "1",
"Tags": [
"python",
"iteration"
],
"Title": "Which solution is good to generate a list without None results from a function?"
} | 239175 |
<p>I made a <a href="https://codereview.stackexchange.com/questions/238937/string-calculator">calculator</a> a few days ago and posted the code here. I got some very helpful feedback. So I remade the calculator and learned a lot in the process. Here's my new code:</p>
<p><strong>In the header file:</strong></p>
<pre><code>#include <string>
template <typename NUMTYPE>
std::string calculate(const std::string&);
template <typename NUMTYPE>
std::string calculateRPN(const std::string&);
std::string toRPN(const std::string&);
</code></pre>
<p><strong>In the source file:</strong></p>
<pre><code>#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <vector>
#include <stdexcept>
#include <cmath>
// forward declarations:
template std::string calculate<long double>(const std::string&);
template std::string calculateRPN<long double>(const std::string&);
template std::string calculate<long long>(const std::string&);
template std::string calculateRPN<long long>(const std::string&);
template std::string calculate<double>(const std::string&);
template std::string calculateRPN<double>(const std::string&);
template std::string calculate<long>(const std::string&);
template std::string calculateRPN<long>(const std::string&);
template std::string calculate<int>(const std::string&);
template std::string calculateRPN<int>(const std::string&);
template std::string calculate<float>(const std::string&);
template std::string calculateRPN<float>(const std::string&);
template std::string calculate<short>(const std::string&);
template std::string calculateRPN<short>(const std::string&);
template <typename NUMTYPE>
std::string calculate(const std::string &expression)
{
if (expression.empty())
return "";
return calculateRPN<NUMTYPE>(toRPN(expression));
}
inline bool isNumber(const char);
inline bool isLetter(const char);
inline bool isOperator(const char);
template <typename NUMTYPE>
NUMTYPE applyOperator(const char operation, NUMTYPE&, NUMTYPE&);
template <typename NUMTYPE>
void applyFunction(std::string &function, NUMTYPE &argument);
template <typename NUMTYPE>
NUMTYPE factorial(NUMTYPE);
// pi and e aren't defined in the c++ standard until c++20 so I define them here
static const long double pi_num = 3.1415926535897932;
static const long double e_num = 2.7182818284590452;
template <typename NUMTYPE>
std::string calculateRPN(const std::string &expression)
{
// https://en.wikipedia.org/wiki/Reverse_Polish_notation#Postfix_evaluation_algorithm
if (expression.empty())
return "";
std::vector<NUMTYPE> number_stack;
std::stringstream in(expression);
std::string word;
NUMTYPE num1, num2;
try
{
while (in >> word)
{
if (word == "(" || word == ")")
throw std::runtime_error("Syntax Error");
else if (isNumber(word.front()))
{
std::stringstream numstream(word);
numstream >> num1;
}
else if (isOperator(word.front()))
{
if (word.size() > 1) // negative number
{
if (word.front() != '-' || !isNumber(word[1]))
throw std::runtime_error("Operators must be space-seperated");
std::stringstream numstream(word);
numstream >> num1;
number_stack.push_back(num1);
continue;
}
if (number_stack.empty())
throw std::runtime_error("Too Many Operators");
num1 = number_stack.back();
number_stack.pop_back();
num2 = number_stack.back();
number_stack.pop_back();
num1 = applyOperator(word.front(), num1, num2);
}
else if (isLetter(word.front()))
{
// dealing with mathematical constants
if (word == "pi")
{
number_stack.push_back(pi_num);
continue;
}
if (word == "e")
{
number_stack.push_back(e_num);
continue;
}
// dealing with functions
num1 = number_stack.back();
number_stack.pop_back();
if (word == "min")
{
num2 = number_stack.back();
number_stack.pop_back();
num1 = num1 < num2 ? num1 : num2;
}
else if (word == "max")
{
num2 = number_stack.back();
number_stack.pop_back();
num1 = num1 > num2 ? num1 : num2;
}
else
applyFunction(word, num1);
}
else
throw std::runtime_error("Unknown Symbol");
number_stack.push_back(num1);
}
if (number_stack.size() > 1)
throw std::runtime_error("Too Many Numbers");
std::stringstream answer;
answer << std::setprecision(16) << number_stack.back();
answer >> word;
return word;
}
catch(const std::exception& error)
{
return error.what();
}
}
inline bool isNumber(const char character)
{
if ((character >= '0' && character <= '9') || character == '.')
return true;
else
return false;
}
inline bool isLetter(const char character)
{
if ((character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z'))
return true;
else
return false;
}
inline bool isOperator(const char character)
{
if (character == '+' || character == '-' || character == '*' || character == '/' ||
character == '%' || character == '^' || character == '(' || character == ')')
return true;
else
return false;
}
template <typename NUMTYPE>
NUMTYPE applyOperator(const char operation, NUMTYPE& num1, NUMTYPE& num2)
{
if (operation == '+')
return num1 + num2;
else if (operation == '-')
return num1 - num2;
else if (operation == '*')
return num1 * num2;
else if (operation == '/')
{
if (num1 == 0)
throw std::runtime_error("Math Error");
return num2 / num1;
}
else if (operation == '%')
{
if (num1 == 0)
throw std::runtime_error("Math Error");
return (long long) num2 % (long long) num1;
}
else if (operation == '^')
{
if (num1 == 0 && num2 == 0)
throw std::runtime_error("Math Error");
return pow(num2, num1);
}
else
throw std::runtime_error("Unknown Symbol");
}
template <typename NUMTYPE>
void applyFunction(std::string &function, NUMTYPE &argument)
{
if (function == "abs")
argument = fabs(argument);
else if (function == "sqrt")
argument = sqrt(argument);
else if (function == "cbrt")
argument = cbrt(argument);
else if (function == "sin")
argument = sin(argument);
else if (function == "cos")
argument = cos(argument);
else if (function == "tan")
argument = tan(argument);
else if (function == "cot")
argument = 1 / tan(argument);
else if (function == "sec")
argument = 1 / cos(argument);
else if (function == "csc")
argument = 1 / sin(argument);
else if (function == "arctan")
argument = atan(argument);
else if (function == "arcsin")
argument = asin(argument);
else if (function == "arccos")
argument = acos(argument);
else if (function == "arccot")
argument = atan(1 / argument);
else if (function == "arcsec")
argument = acos(1 / argument);
else if (function == "arccsc")
argument = asin(1 / argument);
else if (function == "sinh")
argument = sinh(argument);
else if (function == "cosh")
argument = cosh(argument);
else if (function == "tanh")
argument = tanh(argument);
else if (function == "coth")
argument = 1 / tanh(argument);
else if (function == "sech")
argument = 1 / cosh(argument);
else if (function == "csch")
argument = 1 / sinh(argument);
else if (function == "arctanh")
argument = atanh(argument);
else if (function == "arcsinh")
argument = asinh(argument);
else if (function == "arccosh")
argument = acosh(argument);
else if (function == "arccoth")
argument = atanh(1 / argument);
else if (function == "arcsech")
argument = acosh(1 / argument);
else if (function == "arccsch")
argument = asinh(1 / argument);
else if (function == "log")
argument = log10(argument);
else if (function == "ln")
argument = log(argument);
else if (function == "exp")
argument = exp(argument);
else if (function == "gamma")
argument = tgamma(argument);
else if (function == "erf")
argument = erf(argument);
else
throw std::runtime_error("Unknown Function");
}
template <typename NUMTYPE>
NUMTYPE factorial(NUMTYPE number)
{
if (number < 0)
throw std::runtime_error("Math Error");
NUMTYPE res = 1;
while (number > 1)
{
res *= number;
--number;
}
return res;
}
// functions for "toRPN"
inline char precedence(const char operation);
void parseNumber(const std::string &in, std::string &out, std::string::size_type &index);
void parseFunction(const std::string &in, std::string::size_type &index, std::vector<std::string> &operation_stack);
void parseOperator(const char operation, std::string &out, std::vector<std::string> &operation_stack);
void pushOut(std::vector<std::string> &operation_stack, std::string &out);
bool pushOut_cond(const char operation, std::vector<std::string> &operation_stack);
bool pi_cond(const std::string &expression, std::string::size_type &index);
bool e_cond(const std::string &expression, std::string::size_type &index);
// converts a mathematical expression into Reverse Polish Notation using shunting-yard algorithm
std::string toRPN(const std::string &expression)
{
// https://en.m.wikipedia.org/wiki/Shunting-yard_algorithm
std::string expression_RPN;
expression_RPN.reserve(expression.length());
std::vector<std::string> operation_stack;
// for dealing with omitted multiplication signs like "2sin(x)cos(x)" or "5(4+3(2+1))"
bool number_flag = false, rightParen_flag = false;
try
{
for (std::string::size_type i = 0; i < expression.length(); ++i)
{
if (isNumber(expression[i]))
{
parseNumber(expression, expression_RPN, i);
if (rightParen_flag) // omitted multiplication sign
parseOperator('*', expression_RPN, operation_stack);
if (number_flag) // consecutive numbers
throw std::runtime_error("Syntax Error");
number_flag = true;
rightParen_flag = false;
}
else if (isLetter(expression[i]))
{
if (number_flag || rightParen_flag) // omitted multiplication sign
parseOperator('*', expression_RPN, operation_stack);
// dealing with mathematical constants
if (pi_cond(expression, i))
{
expression_RPN.append("pi ");
// treat as righ parenthesis (for omitted multiplication signs)
number_flag = false;
rightParen_flag = true;
++i;
continue;
}
if (e_cond(expression, i))
{
expression_RPN.append("e ");
// treat as righ parenthesis (for omitted multiplication signs)
number_flag = false;
rightParen_flag = true;
continue;
}
// dealing with functions
parseFunction(expression, i, operation_stack);
number_flag = false;
rightParen_flag = false;
}
else if (isOperator(expression[i]))
{
// consecutive operators
if (!number_flag && !rightParen_flag && expression[i] != '(')
{
if (expression[i] == '-') // negative sign (instead of minus operation)
{
expression_RPN.append("-1 ");
parseOperator('*', expression_RPN, operation_stack);
continue;
}
else
throw std::runtime_error("Syntax Error");
}
if ((number_flag || rightParen_flag) && expression[i] == '(') // omitted multiplication sign
parseOperator('*', expression_RPN, operation_stack);
parseOperator(expression[i], expression_RPN, operation_stack);
if (expression[i] == ')')
rightParen_flag = true;
else
rightParen_flag = false;
number_flag = false;
}
else if (expression[i] == '!')
{
if (number_flag || rightParen_flag)
expression_RPN.append("! ");
else
throw std::runtime_error("Syntax Error");
// treat as righ parenthesis (for omitted multiplication signs)
number_flag = false;
rightParen_flag = true;
}
else if (expression[i] == ',')
{
number_flag = false;
rightParen_flag = false;
}
else if (expression[i] == ' ')
continue;
else
throw std::runtime_error("Unknown Symbol");
}
while (!operation_stack.empty())
{
if (operation_stack.back() == "(")
throw std::runtime_error("Mismatched Parentheses");
pushOut(operation_stack, expression_RPN);
}
}
catch (const std::exception &error)
{
std::cerr << error.what() << '\n';
return "";
}
expression_RPN.pop_back(); // removing the extra space
return expression_RPN;
}
inline char precedence(const char operation)
{
if (operation == '+' || operation == '-')
return 0;
else if (operation == '*' || operation == '/' || operation == '%')
return 1;
else if (operation == '^')
return 2;
else
return 3;
}
void parseNumber(const std::string &in, std::string &out, std::string::size_type &index)
{
out.push_back(in[index]);
while (index + 1 < in.length() && isNumber(in[index + 1]))
{
++index;
out.push_back(in[index]);
}
// handling decimals (only allowing one decimal point per number)
if (index + 1 < in.length() && in[index + 1] == '.')
{
while (index + 1 < in.length() && isNumber(in[index + 1]))
{
++index;
out.push_back(in[index]);
}
}
out.push_back(' ');
}
void parseFunction(const std::string &in, std::string::size_type &index, std::vector<std::string> &operation_stack)
{
std::string buffer;
buffer.push_back(in[index]);
while (index + 1 < in.length() && isLetter(in[index + 1]))
{
++index;
buffer.push_back(in[index]);
}
operation_stack.push_back(buffer);
}
void parseOperator(const char operation, std::string &out, std::vector<std::string> &operation_stack)
{
if (operation == '(')
{
operation_stack.push_back(std::string(1, operation));
return;
}
if (operation == ')')
{
while (!operation_stack.empty() && operation_stack.back() != "(")
pushOut(operation_stack, out);
if (operation_stack.empty()) // no left paranthesis '(' found
throw std::runtime_error("Mismatched Parentheses");
else // left paranthesis '(' found
operation_stack.pop_back();
return;
}
while (pushOut_cond(operation, operation_stack))
pushOut(operation_stack, out);
operation_stack.push_back(std::string(1, operation));
}
void pushOut(std::vector<std::string> &operation_stack, std::string &out)
{
out.append(operation_stack.back());
out.push_back(' ');
operation_stack.pop_back();
}
bool pushOut_cond(const char operation, std::vector<std::string> &operation_stack)
{
if (!operation_stack.empty() && operation_stack.back() != "(")
{
// a function is at the top of the stack
if (isLetter(operation_stack.back().front()))
return true;
// an operation with greater precedence is at the top of the stack
else if (precedence(operation_stack.back().front()) > precedence(operation))
return true;
else if (precedence(operation_stack.back().front()) == precedence(operation))
{
// the operation isn't right-to-left associative
if (operation != '^')
return true;
else
return false;
}
else
return false;
}
else
return false;
}
bool pi_cond(const std::string &expression, std::string::size_type &index)
{
if (expression.substr(index, 2) == "pi")
{
if (index + 2 == expression.size() || !isLetter(expression[index + 2]))
return true;
else
return false;
}
else
return false;
}
bool e_cond(const std::string &expression, std::string::size_type &index)
{
if (expression[index] == 'e')
{
if (index + 1 == expression.size() || !isLetter(expression[index + 1]))
return true;
else
return false;
}
else
return false;
}
</code></pre>
<p><strong>Possible use:</strong></p>
<pre><code>int main()
{
std::string expression;
std::getline(std::cin, expression);
while (expression != "end")
{
std::cout << "= " << calculate<long double>(expression) << "\n\n";
std::getline(std::cin, expression);
}
}
</code></pre>
<p>Two questions:</p>
<ul>
<li>I'm fairly new to exception handling; Did do it correctly in my code?</li>
<li>There were some functions that weren't part of the "calculator". So I didn't define them in the header file. Is this bad practice or good practice?</li>
</ul>
<p>Suggestions and ideas are always welcome :)</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T09:03:00.073",
"Id": "469241",
"Score": "0",
"body": "After going through my code, I realized most of the code bloat is coming from handling omitted multiplication signs. Does anyone know a clean way to deal with this (input like 2(4+7(5+8)))? I can't think of a way other than using flags, which is messy, hard to track and inconvenient."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T12:48:49.797",
"Id": "469247",
"Score": "0",
"body": "Please do not modify the question after it has been answered. https://codereview.stackexchange.com/help/someone-answers"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T11:12:25.927",
"Id": "469342",
"Score": "0",
"body": "Ok, thanks again"
}
] | [
{
"body": "<p>I am not a pro coder but to my eye your try/catch block seems very correct. You did covered all types of error that may occur during the execution of the code if given an incorrect input. \nI would say that the exception handling is implemented correctly.<br>\nFor the second question, most coders would agree that it is a good practice to drop everything that is not required in the code and removing stuff that would not effect the functionality a tiny bit. These pieces of code may increase the execution and compile time which is a judging factor in many coding competitions. \nIn your case, removing the header files that are not required in the code is a good practice.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T12:17:54.173",
"Id": "469167",
"Score": "0",
"body": "Thank you for your answer! I think you misunderstood my second question: the functions were needed but they weren't intended to be used separately by someone who's using the header"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T11:29:37.200",
"Id": "239180",
"ParentId": "239177",
"Score": "1"
}
},
{
"body": "<h2>Answers to Specific Questions</h2>\n<blockquote>\n<p>There were some functions that weren't part of the "calculator". So I didn't define them in the header file. Is this bad practice or good practice?</p>\n</blockquote>\n<p>It is sometimes necessary to keep some things private, these functions don't need a prototype in the header file.</p>\n<blockquote>\n<p>I'm fairly new to exception handling; Did do it correctly in my code?</p>\n</blockquote>\n<p>The problem with your exception handling is that you are returning the <code>error,what()</code> value as a successful <code>word</code> in at least one case. How does the outer program know that this is an error and stops the processing. It is possible that they try{} catch{} implementation is at a too low level and may need to be at a higher level in the programming so that the program resets and doesn't try to process the string.</p>\n<h2>General Observations</h2>\n<p>One thing to always keep in mind when designing and writing software is maintainability. Functionality always grows as a program matures and this means that there are changes that must be made. You may win the lottery or inherit a lot of money so you may not be the one maintaining the code. This code will not be easy to modify by other people.</p>\n<p>It also seems that you may have missed some of the suggestions that EmilyL made (make sure your code is working properly).</p>\n<h2>Separate Functionality</h2>\n<p>There are 2 sets of functionality here, parsing the expressions and performing the calculations, split the functionality so that first the input is entirely parsed, and then calculate the value if the expression is legal, don't try to do everything at once. This will simplify writing and debugging the code. Build a parse tree of operators and operands and then process the parse tree separately. There is really no need to convert to Reverse Polish Notation internally.</p>\n<p>Quite possibly there should be 2 classes used by the program, a parser and then a calculator. The parsing algorithm and the calculating algorithm should be in separate source files with separate header files.</p>\n<h2>Complexity</h2>\n<p>The function <code>std::string toRPN(const std::string &expression)</code> is far too complex (does too much in one function) and should have blocks of code broken out into more functions. In the dinosaur age of computing, functions that were more than one page long (about 60 lines) were considered too long to be understandable. In the modern age, any function that does not fit on a screen is too long.</p>\n<p>There is also a programming principle called the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> that applies here. The Single Responsibility Principle 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<h1>Let the Compiler do the Optimization</h1>\n<p>In the C++ language the keyword <code>inline</code> is obsolete. Optimizing compilers do a much better job of deciding what functions should be inlined. There isn't any other use for the keyword <code>inline</code> other than optimization.</p>\n<h1>Prefer Data Structures Over Long If Then Else If Statements</h1>\n<p>In the function <code>void applyFunction(std::string &function, NUMTYPE &argument)</code> the very long <code>if then else if</code> statement might be better implemented using <code>std::map</code>. This would make adding or deleting operations much easier because the map is easier to add to. It would also greatly reduce the amount of code in this function.</p>\n<h2>Use the Conditional (or Ternary) Operator</h2>\n<p>The functions <code>inline bool isNumber(const char character)</code> <code>inline bool isLetter(const char character)</code> and <code>inline bool isOperator(const char character)</code> could all be much shorter, in the case of <code>isNumber()</code> and <code>isLeter()</code> they are one liners if you use the <a href=\"http://www.cplusplus.com/articles/1AUq5Di1/\" rel=\"nofollow noreferrer\">ternary operator</a>.</p>\n<pre><code>inline bool isNumber(const char character)\n{\n return ((character >= '0' && character <= '9') || character == '.');\n}\n\ninline bool isLetter(const char character)\n{\n return ((character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z'));\n}\n</code></pre>\n<p>If you include <code><cctype></code> this becomes even simpler, <code>isLetter()</code> can simply be replaced by <code>isalpha()</code> and <code>isNumber()</code> can be simplified with</p>\n<pre><code>inline bool isNumber(const char character)\n{\n return (isdigit(character) || character == '.');\n}\n</code></pre>\n<p>The function <code>inline bool isOperator(const char character)</code> is easier to maintain if it written in the following manner.</p>\n<pre><code>bool isOperator(const char character)\n{\n std::vector<char>operators = {'+', '-', '*', '/', '&', '^', '(', ')'};\n for (char m_operator: operators)\n {\n if (m_operator == character)\n {\n return true;\n }\n return false;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T06:38:55.637",
"Id": "469233",
"Score": "0",
"body": "Thank you for your very in-depth review! The quality of the answers here never ceases to impress me. I did write unit tests this time around but I didn't include them here (should I?)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T12:41:22.303",
"Id": "469246",
"Score": "0",
"body": "You should have included the unit tests, but since you have 2 answers, it's too late to update the question."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T22:48:17.920",
"Id": "239210",
"ParentId": "239177",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "239210",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T11:09:39.023",
"Id": "239177",
"Score": "2",
"Tags": [
"c++",
"calculator"
],
"Title": "String Calculator 2"
} | 239177 |
<p>I have written a very basic algorithm, that counts the amount of times sub-string appears in a string.</p>
<p>The algorithm is given:</p>
<ul>
<li><strong>seq</strong> - a string sequence</li>
<li><strong>k</strong> - length of a sub-string</li>
<li><strong>L</strong> - a window of a string to search in</li>
<li><strong>t</strong> - times that sub-string, length <strong>k</strong> has to be present to be added to results</li>
</ul>
<hr>
<pre><code>from collections import defaultdict
import concurrent.futures
def kmer_clumps(seq, k, L, t):
"""Returns a set of L-t kmers that form a clump. If a kmer of length [k] apperas [t] times in window [L], it is added to a set"""
print("Starting a job")
clump_dict = defaultdict(list)
clumps = set()
for pos in range(len(seq) - k + 1):
current_pos = seq[pos:pos + k]
clump_dict[current_pos].append(pos)
if len(clump_dict[current_pos]) >= t:
if ((clump_dict[current_pos][-1] + (k - 1)) - clump_dict[current_pos][-t]) < L:
clumps.add(current_pos)
if clumps:
return clumps
else:
return None
</code></pre>
<hr>
<p><a href="https://i.stack.imgur.com/RooQO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RooQO.png" alt="enter image description here"></a></p>
<hr>
<p>Running this algorithm in one thread/core is easy, just pass all of the parameters and it scans the string and returns a list.</p>
<p>Now, this is a perfect candidate for running on multiple cores as sometimes I need to provide a large amount of data to this algorithm (text file 20mb+ in size or even more).</p>
<p>Below, I have used Python's <code>import multiprocessing</code> and/or <code>import concurrent.futures</code>, but this does not really matter as the question is: what is the best way of splitting the data to be passed to multiple threads/cores to avoid duplicate data, large amounts of memory usage, etc... I am hoping that people can share their experience in preparing data in this manner and best practices for this.</p>
<pre><code>seq = "CGGACTCGACAGATGTGAAGAACGACAATGTGAAGACTCGACACGACAGAGTGAAGAGAAGAGGAAACATTGTAA"
k = 5
L = 50
t = 4
cores = 2
def sub_seq_clumps_multicore_job(seq, k, L, t, cores=1):
seqLength = len(seq)
if cores == 1:
print("Using only 1 core as specified or data is to small.")
return kmer_clumps(seq, k, L, t)
else:
print("Preparing data...")
# Basic logic to split the data to provide to multiple jobs/threads
jobSegments = seqLength // cores
extraSegments = seqLength % cores
overlapSize = (L // cores)
# Creating multiple parts from a single string and adding same arguments to all
# Amount of parts is based on core/thread count
parts = []
for part in range(0, seqLength, jobSegments + extraSegments):
tmpList = [seq[part:part + jobSegments +
extraSegments + overlapSize + 1], k, L, t]
parts.append(tmpList)
print(f"Processing data on {cores} cores...")
resultSet = set()
# Starting jobs/threads by passing all parts to a thread pool
with concurrent.futures.ProcessPoolExecutor() as executer:
jobs = [
executer.submit(kmer_clumps, *sec) for sec in parts
]
# Just collecting results
for f in concurrent.futures.as_completed(jobs):
resultSet.update(f.result())
# Returning collected results, which are sub-strings of length k,
# that were found in all windows length L
return resultSet
print(sub_seq_clumps_multicore_job(seq, k, L, t, cores))
</code></pre>
<p>Some sample output:</p>
<p><strong>Data, segmented and passed to <code>kmer_clumps(seq, k, L, t)</code> to run on 1 core/thread:</strong></p>
<pre><code>"CGGACTCGACAGATGTGAAGAACGACAATGTGAAGACTCGACACGACAGAGTGAAGAGAAGAGGAAACATTGTAA", 5, 50, 4
</code></pre>
<p><strong>Data, segmented and passed to <code>kmer_clumps(seq, k, L, t)</code> to run on 2 core/thread:</strong></p>
<pre><code>Thread 1:
['CGGACTCGACAGATGTGAAGAACGACAATGTGAAGACTCGACACGACAGAGTGAAGAGAAGAGG', 5, 50, 4]
Thread 2:
['CGACACGACAGAGTGAAGAGAAGAGGAAACATTGTAA', 5, 50, 4]
</code></pre>
<p><strong>Data, segmented and passed to <code>kmer_clumps(seq, k, L, t)</code> to run on 4 core/thread:</strong></p>
<pre><code>Thread 1:
['CGGACTCGACAGATGTGAAGAACGACAATGTGAA', 5, 50, 4]
Thread 2:
['ACGACAATGTGAAGACTCGACACGACAGAGTGAA', 5, 50, 4]
Thread 3:
['ACGACAGAGTGAAGAGAAGAGGAAACATTGTAA', 5, 50, 4]
Thread 4:
['GAAACATTGTAA', 5, 50, 4]]
</code></pre>
<hr>
<hr>
<p><strong>Results in running time, when reading a huge data file (4.5 MB):</strong></p>
<pre><code>File reading complete!
Using only 1 core as specified or data is to small.
Starting a job
real 0m4.536s
</code></pre>
<hr>
<pre><code>File reading complete!
Preparing data...
Processing data on 2 cores...
Starting a job
Starting a job
real 0m2.438s
</code></pre>
<hr>
<pre><code>File reading complete!
Preparing data...
Processing data on 4 cores...
Starting a job
Starting a job
Starting a job
Starting a job
real 0m1.413s
</code></pre>
<hr>
<pre><code>File reading complete!
Preparing data...
Processing data on 6 cores...
Starting a job
Starting a job
Starting a job
Starting a job
Starting a job
Starting a job
real 0m1.268s
</code></pre>
<p>Because of the nature of the algorithm, when running on multiple threads/cores there is more data generated as we need to make sure we cover the whole data string and take a window L into the account. So there are data overlaps happening:</p>
<p>Let's take two examples:</p>
<p><strong>Running on 2 cores:</strong>
<a href="https://i.stack.imgur.com/1ckyF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1ckyF.png" alt="enter image description here"></a></p>
<p><strong>Running on 4 cores:</strong>
<a href="https://i.stack.imgur.com/aFbNd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aFbNd.png" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/SGDFa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SGDFa.png" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/fXjcx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fXjcx.png" alt="enter image description here"></a></p>
<p>With this post I have two goals:</p>
<p>1) To have experienced people look at it and suggest any improvements to how to segment the data for threading like that, to avoid data duplicates, memory overload, etc... any suggestions would be very helpful.</p>
<p>2) To learn from amazing people and so others can learn from this example.</p>
<p>Thank you all very much!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T19:57:38.997",
"Id": "469208",
"Score": "0",
"body": "_I am not including this algorithm to avoid confusion. It has been tested and it works as expected._ - Fine; but what if a reviewer wants to execute your code (potentially with different segmentation)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T20:12:57.637",
"Id": "469211",
"Score": "0",
"body": "@Reinderien you are right."
}
] | [
{
"body": "<h2>Type hints</h2>\n\n<p>At a guess, this:</p>\n\n<pre><code>def kmer_clumps(seq, k, L, t):\n</code></pre>\n\n<p>can become</p>\n\n<pre><code>def kmer_clumps(seq: Sequence[str], k: int, l: int, t: int) -> Set[str]:\n</code></pre>\n\n<p>It's somewhat more self-documenting, and helps your IDE with static analysis and autocompletion.</p>\n\n<p>p.s. There's nothing wrong with returning an empty set. That's much more preferable than returning <code>None</code>. People iterating over the returned set often won't need to change their code for an empty set, but <em>would</em> need to change their code for a <code>None</code>.</p>\n\n<h2>Logging</h2>\n\n<pre><code>print(\"Starting a job\")\n</code></pre>\n\n<p>can benefit from the (even simple) use of <a href=\"https://docs.python.org/3.8/library/logging.html#module-email\" rel=\"nofollow noreferrer\">https://docs.python.org/3.8/library/logging.html#module-email</a></p>\n\n<h2>Global constants</h2>\n\n<p>...such as</p>\n\n<pre><code>k = 5\nL = 50\nt = 4\ncores = 2\n</code></pre>\n\n<p>should be ALL_CAPS.</p>\n\n<h2>Variable names</h2>\n\n<p><code>seqLength</code> should be snake_case, i.e. <code>set_length</code>; and so on for your other variables.</p>\n\n<h2>Generators</h2>\n\n<pre><code> parts = []\n for part in range(0, seqLength, jobSegments + extraSegments):\n tmpList = [seq[part:part + jobSegments +\n extraSegments + overlapSize + 1], k, L, t]\n parts.append(tmpList)\n</code></pre>\n\n<p>can be cleaned up by factoring it out into a generator function:</p>\n\n<pre><code>def make_part_list(...):\n for part in range(0, seqLength, jobSegments + extraSegments):\n tmpList = [seq[part:part + jobSegments +\n extraSegments + overlapSize + 1], k, L, t]\n yield tmpList\n # or if you don't want nested lists...\n yield from tmpList\n\n# ...\nparts = tuple(make_part_list(...))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T09:20:51.860",
"Id": "469337",
"Score": "0",
"body": "Thanks a lot for your input! This code is mostly draft, so 'Global constants', for example, were just for testing porpoise so people can try running the code. While you provided very interesting suggestions, I was more interested in discussing how we can optimize segmentation of the data, a string of text in this case, before we split it into multiple threads/cores. this code works just fine and does what I need it to do. I could not find any good information about how to segment/split data for multiprocessing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T09:20:58.150",
"Id": "469338",
"Score": "0",
"body": "In some cases you just need to do multiple things, which are not really connected ore semi-connected in parallel. This is easier. But in this case we have one single peace of data that we need to process and the result is a combination of all the 'findings' from all threads. I was wondering if there was a better way to approach data segmentation/splitting."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T15:36:30.797",
"Id": "239233",
"ParentId": "239178",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T11:12:21.047",
"Id": "239178",
"Score": "4",
"Tags": [
"python",
"multithreading",
"multiprocessing"
],
"Title": "Data segmentation and optimization for Multi-threaded/Multi-core use (In Python)"
} | 239178 |
<p>I've created a function that generates an <code><ul></code> of my wordpress custom taxonomy terms, displaying <code>parent > child > second child</code> heirachy. Functionally it is working perfectly and replaces my old hard-coded menu. </p>
<p>The problem is I'm inexperienced and recognise it as an ugly, inefficient function but could not figure out how to make it better. I tried use 'While()' loops to simplify things but came unstuck. Could someone help me understand how to improve this. The final output (including CSS and jQuery to collapse deactivated menu items) is included below. </p>
<pre><code>//Display Navigation Menu
function taxonomy_nav(){
//Get Parent Terms
$getParents = [
'taxonomy' => 'kernal_category',
'parent' => 0,
'number' => 0,
'hide_empty' => false
];
//Assign parent terms to variable
$parent_terms = get_terms( $getParents );
//Loop through parent terms
foreach ( $parent_terms as $parent_term ) {
//Store children terms
$childrenCheck = get_term_children( $parent_term->term_id, $parent_term->taxonomy );
//If parent term has children...
if ( ! is_wp_error( $childrenCheck ) && ! empty ( $childrenCheck ) ) {
//Output parent term and start new children list
echo '<li><a href="'. get_term_link( $parent_term ) .'">'. $parent_term->name.'</a>';
echo '<ul>';
//Loop through child items and output name
foreach ( get_terms( 'kernal_category', array( 'hide_empty' => false, 'parent' => $parent_term->term_id ) ) as $child_term) {
//Check if children have children
$secondChildrenCheck = get_term_children( $child_term->term_id, $child_term->taxonomy );
//Generate list for second children
if ( ! is_wp_error( $secondChildrenCheck ) && ! empty( $secondChildrenCheck ) ) {
echo '<li><a href="' . get_term_link( $child_term ) . '">' . $child_term->name.'</a>';
echo '<ul>';
//If child has child, look through child
foreach ( get_terms( 'kernal_category', array( 'hide_empty' => false, 'parent' => $child_term->term_id ) ) as $second_child_term) {
echo '<li><a href="'. get_term_link( $second_child_term ) . '">'.$second_child_term->name . '</a></li>';
}
echo '</ul>';
echo '</li>';
} else {
echo '<li><a href="'. get_term_link( $child_term ) .'">'. $child_term->name.'</a></li>';
}
}
echo '</ul>';
echo '</li>';
} else {
echo '<li><a href="'. get_term_link( $parent_term ) .'">'. $parent_term->name.'</a></li>';
}
}
</code></pre>
<p><a href="https://i.stack.imgur.com/XvNjd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XvNjd.png" alt="Final List ="></a></p>
| [] | [
{
"body": "<p>The first thing I noticed was your indentation. On some lines the indentation is not consistent. Try to keep your indentation consistent as it helps others read your code.</p>\n\n<p>You also write a lot of comments in your code but comments are usually not necessary. I only write comments to explain certain design choices which are not clear from the code (for example doing some low-level code because it improves performance rather than readability) or I write comments to explain a difficult algorithm or procedure of steps. A lot of your comments distract from the actual code or are confusing. For example</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>//Store children terms \n$childrenCheck = get_term_children( $parent_term->term_id, $parent_term->taxonomy );\n</code></pre>\n\n<p>The comment says something about storing children terms but the method called is called <code>get_term_children</code> implying there is something fetched, not stored. I assume you mean storing the children terms in the variable, but in that case a comment stating <code>//fetching children term</code> would be better as most developers understand that the children terms are stored in the variable. No comment would even be better as most experienced developers read the code and immediately see that the children terms are fetched.</p>\n\n<p>If comments help you understand your code better and you are the only one reading your code, by all means. But you should also try to read and understand code without comments.</p>\n\n<p>A general rule of thumb is that a lot of nested structures is not a good sign. You now have a foreach inside an if inside a foreach inside an if inside a foreach. What you can do for example for each foreach statement is take all the code inside the foreach statement and extract it into a separate function. Try to give each of these functions descriptive names what they are doing.</p>\n\n<p>You also have a lot of repetition when it comes to echoing. The following</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>echo '<li><a href=\"'. get_term_link( $parent_term ) .'\">'. $parent_term->name.'</a></li>';\n</code></pre>\n\n<p>is used quite a lot throughout your code. You can extract this to a method, something like</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function printListItem($term) {\n echo '<li><a href=\"'. get_term_link( $term ) .'\">'. $term->name.'</a></li>';\n}\n</code></pre>\n\n<p>In this way when you have to change something to each list item at the same time (for example, adding a html class to the <code>li</code>s) you only have to do it in one place.</p>\n\n<p>The check for children can also be extracted into a separate function, say</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function hasChildren($term) {\n $children = get_term_children( $term->term_id, $term->taxonomy );\n return !is_wp_error($children) && !empty($children);\n}\n</code></pre>\n\n<p>Than you can use it like this:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>foreach ( $parent_terms as $parent_term ) { \n if (hasChildren($parent_term) {\n ...\n }\n}\n</code></pre>\n\n<p>I think this is a good set of improvements for you to start with to improve the readability of your code. Just keep practicing and eventually you will write clearer code and understand how to improve your own code :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T14:49:15.557",
"Id": "239191",
"ParentId": "239184",
"Score": "2"
}
},
{
"body": "<p>As pointed out, there is a lot of code repetition and this is a big problem when any changes get made. It's so easy to quickly make a change to one piece of code and miss the 3 other versions of it which do the same thing.</p>\n\n<p>Rather than factor out these parts of code into functions though, you can re-factor the code into a recursive function. The idea being that you just use the same code to do each layer of the process rather than loops within loops calling helper functions to do the more common tasks.</p>\n\n<p>One other thing I have changed is to build the output into a string rather than <code>echo</code> it out directly. I would normally then return this string to the calling code and let that do whatever it wants with it. This allows more control over the output generated, also allows the output to be re-used (although not sure how that would be necessary in this case) rather than having to re-generate the output each time. But as I'm not sure how this is called, I just <code>echo</code> the combined string at the end.</p>\n\n<pre><code>function taxonomy_nav( string $category = null, array $settings = null ) : string {\n if ( $category == null ) {\n $settings = [\n 'taxonomy' => 'kernal_category',\n 'parent' => 0,\n 'number' => 0,\n 'hide_empty' => false\n ];\n $parent_terms = get_terms( $settings );\n }\n else {\n $parent_terms = get_terms( $category, $settings );\n }\n\n foreach ( $parent_terms as $parent_term ) {\n $list = '<li><a href=\"'. get_term_link( $parent_term ) .'\">'. $parent_term->name.'</a>';\n\n $childrenCheck = get_term_children( $parent_term->term_id, $parent_term->taxonomy );\n\n if ( ! is_wp_error( $childrenCheck ) && ! empty ( $childrenCheck ) ) {\n $list .= '<ul>'\n . taxonomy_nav ( 'kernal_category', array( 'hide_empty' => false, 'parent' => $parent_term->term_id ) ) \n . '</ul>';\n }\n\n $list .= '</li>';\n }\n\n echo $list;\n}\n</code></pre>\n\n<p>As you can see, in the <code>if ( ! is_wp_error( $childrenCheck )</code> block, it just starts the sub list and then calls itself to do the processing for any child nodes. </p>\n\n<p>This also shows how the list item itself is only ever generated by the one line of code, not repetition and any changes are easily identified.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T14:29:46.790",
"Id": "469252",
"Score": "0",
"body": "Grrr, I was going to suggest recursion, but you beat me to it; plus one. I was also going to recommend that `<ul>` elements only be written if there are `<li>` tags for it -- you addressed that too! It may not be a concern for this OP, but I was thinking of declaring a hard limit to the recursion levels. I don't think `!empty()` is necessary -- if `!is_wp_error()` then there will be an array declared as `$childrenCheck`. To check if it is truthy (IOW, has a count), just check `if ($childrenCheck)` and spare the function call ...unless you prefer the explicit nature of `!empty()`. Good review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T20:50:15.593",
"Id": "469287",
"Score": "0",
"body": "@nigel ren Thanks for your input and comments. I've not had a chance to put these into practice but I can clearly see how they would improve my code, much appreciated. I will come back if any questions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T22:15:16.500",
"Id": "469294",
"Score": "0",
"body": "I would also like to endorse the consistent use of square-braced array syntax (`[...]`). It is more concise than `array(...)` and provides a visual differentiation from language constructs and function calls which I'll argue improves readability. Either way, only one syntactic style should be used throughout the project -- consistency is important. I personally don't separate `}` and ` else {` on different lines and I am fundamentally opposed to WP's coding standard which endorses excessive whitespaces around everything."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T07:41:04.207",
"Id": "239221",
"ParentId": "239184",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "239191",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T11:56:34.893",
"Id": "239184",
"Score": "2",
"Tags": [
"php",
"recursion",
"wordpress"
],
"Title": "Function for iterating out an unordered list of custom taxonomy terms"
} | 239184 |
<p>For work, we have to use Atlassian Jira, which is depressing. To make my life a bit easier, I decided to write a cli application to get ticket summaries, and I thought it would make a good first project in rust. The code below works, but I would be grateful for any tips/improvements. I'm a python programmer, so it's almost certainly not idiomatic rust...</p>
<pre><code>extern crate reqwest;
extern crate tokio;
use serde_json;
use reqwest::header::{AUTHORIZATION,ACCEPT,CONTENT_TYPE,HeaderValue,HeaderMap};
const BASE_URL: &str = "https://subdomain.atlassian.net/rest/api/latest/issue";
fn parse_config() -> String {
let config_file = std::fs::read_to_string("/home/username/.config/jiracli").expect("No config file found");
String::from(config_file.trim())
}
async fn summarise(client: reqwest::Client, ticket_number:String) -> Result<String, Box<dyn std::error::Error>> {
let compiled_url = format!("{}/{}", &BASE_URL, ticket_number);
let json_response: serde_json::Value = client.get(&compiled_url).send().await?.json().await?;
let ticket_fields = json_response["fields"].as_object().unwrap();
let ticket_summary = ticket_fields.get("summary").unwrap().as_str().unwrap();
let ticket_status = ticket_fields["status"].as_object().unwrap().get("name").unwrap().as_str().unwrap();
let ticket_creator = ticket_fields["creator"].as_object().unwrap().get("displayName").unwrap().as_str().unwrap();
let response=format!("Creator: {}\nStatus: {}\nSummary: {}", ticket_creator,ticket_status,ticket_summary);
Ok(String::from(response))
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let verb = std::env::args().nth(1).expect("No verb provided");
let ticket_number = std::env::args().nth(2).expect("No ticket provided");
let formatted_auth = format!("Basic {}", parse_config());
let auth_header_value = HeaderValue::from_str(&formatted_auth).unwrap();
let mut headers = HeaderMap::new();
headers.insert(AUTHORIZATION, auth_header_value);
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
headers.insert(ACCEPT, HeaderValue::from_static("application/json"));
let client = reqwest::Client::builder()
.default_headers(headers)
.build()?;
let result = match &verb[..] {
"summary" => Ok(summarise(client, ticket_number).await),
_ => Err("Not implemented")
};
println!("{}", result.unwrap()?);
Ok(())
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T13:06:42.747",
"Id": "239185",
"Score": "1",
"Tags": [
"rust"
],
"Title": "Basic Rust HTTP request as a learning exercise"
} | 239185 |
<p>In my web API, the client wants me to implement logic in order to control/block concurrent requests in a specific time period. I added RequestInterval which is 10 seconds in the appsettings of web config. I added the Authorization filter into my project. I tested, it looks working but I wonder if you can check and give me some feedback. </p>
<pre><code>public class ValidIntervalFilter : AuthorizationFilterAttribute
{
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
double sec = Double.Parse(WebConfigurationManager.AppSettings["RequestInterval"].ToString());
DateTime lastDateTime = DateTime.Now;
DateTime requestDateTime = DateTime.Now;
var terminal_number = HttpContext.Current.Request.Params["shopNo"];
using (GameContext ctx = new GameContext())
{
//this will throw an exception
var lastRequestTime = ctx.Database.SqlQuery<DateTime>(
"SELECT MAX([RequestDateTime]) FROM GameRequests WHERE[ShopNo] = @shopNo and RequestDateTime >= CONVERT(DATE, GETDATE())",
new SqlParameter("shopNo", terminal_number)).ToList();
foreach (var time in lastRequestTime)
{
lastDateTime = Convert.ToDateTime(time);
}
DateTime timeAfterInterval = lastDateTime.AddSeconds(sec);
if (requestDateTime <= timeAfterInterval)
{
var response = new HttpResponseMessage
{
StatusCode = (HttpStatusCode)429,
ReasonPhrase = "Too Many Requests",
Content = new StringContent("Concurrent requests are NOT permitted in " + sec + " seconds.")
};
actionContext.Response = response;
}
}
}
}
</code></pre>
<p><strong>I changed the query and here is the updated code:</strong> </p>
<pre><code>public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
double sec = Double.Parse(WebConfigurationManager.AppSettings["RequestInterval"].ToString());
var terminal_number = HttpContext.Current.Request.Params["shopNo"];
using (GameContext ctx = new GameContext())
{
var lastRequestTime = ctx.Database.SqlQuery<Int32>(
"SELECT DATEDIFF(SECOND, [RequestDateTime], GETDATE()) As [SecondsSinceLastRequest] FROM [dbo].[GameRequests] WHERE [ShopNo] = @shopNo AND DATEDIFF(SECOND, [RequestDateTime], GETDATE() ) < @delay",
new SqlParameter("shopNo", terminal_number), new SqlParameter("delay", sec)).ToList();
if (lastRequestTime.Count > 0)
{
var response = new HttpResponseMessage
{
StatusCode = (HttpStatusCode)429,
ReasonPhrase = "Too Many Requests",
Content = new StringContent("Concurrent requests are NOT permitted in " + sec + " seconds.")
};
actionContext.Response = response;
}
}
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T13:58:09.397",
"Id": "239186",
"Score": "1",
"Tags": [
"c#",
"entity-framework",
"asp.net-web-api"
],
"Title": "Concurrent requests are not permitted in specific time period"
} | 239186 |
<p>I have had an attempt at the Mars Rover Kata and would very much appreciate a review and any suggestions to improve.</p>
<p>MessageParser to parse incoming messages and create the domain models:</p>
<pre><code>public class MessageParser
{
private static readonly Regex GridDetailsRegex = new Regex(@"\d\s\d");
private static readonly Regex RoverDetailsRegex = new Regex(@"\d\s\d\s(N|E|S|W)");
private static readonly Regex MovementDetailsRegex = new Regex(@"(L|R|M)");
private static readonly string[] LineSeparators = new[] { "\r\n", "\r", "\n" };
private static readonly Dictionary<char, Movement> MovementsMap =
new Dictionary<char, Movement>()
{
{'L', Movement.TurnLeft},
{'R', Movement.TurnRight},
{'M', Movement.Move},
};
public string HandleMessage(string message)
{
var result = ParseMessage(message);
return result;
}
private Result<string[]> SplitLines(string message)
{
if (string.IsNullOrWhiteSpace(message))
{
return Result<string[]>.Failure(Error.MessageIsEmpty);
}
var lines = message.Split(
LineSeparators,
StringSplitOptions.None
);
if (lines.Length < 5)
{
return Result<string[]>.Failure(Error.MessageIsInvalid);
}
var gridDetailsIsValid = GridDetailsRegex.IsMatch(lines[0].Trim());
var roverParts = lines.Skip(1).ToArray();
var roverDetailsAreValid = roverParts.Where((rp, index) => index % 2 == 0).All(rd => RoverDetailsRegex.IsMatch(rd));
var roverMovementsAreValid = roverParts.Where((rp, index) => index % 2 > 0).All(rm=>MovementDetailsRegex.IsMatch(rm));
return gridDetailsIsValid && roverDetailsAreValid && roverMovementsAreValid ? Result<string[]>.Success(lines) : Result<string[]>.Failure(Error.MessageIsInvalid);
}
private string ParseMessage(string message)
{
var partsResult = SplitLines(message);
if (partsResult.IsSuccess == false)
{
return Lines(partsResult.Errors);
}
var lineParts = partsResult.Value;
var gridDetails = lineParts.First();
var grid = Grid.Create(gridDetails);
if (grid.IsSuccess == false)
{
return Lines(grid.Errors);
}
var roverDetails = lineParts.Skip(1).ToArray();
var result = AddRovers(grid.Value, roverDetails);
return result.IsSuccess ? Lines(grid.Value.GetRoverStatuses()) : Lines(result.Errors);
}
private Result AddRovers(Grid grid, string[] roverParts)
{
for (int i = 0; i < roverParts.Length - 1; i += 2)
{
var rover = Rover.Create(roverParts[i]);
var movements = roverParts[i + 1].ToArray().Select(m => MovementsMap[m]).ToArray();
var addResult = grid.AddRover(rover, movements);
if (addResult.IsSuccess == false)
{
return addResult;
}
}
return Result.Success();
}
private static string Lines(IEnumerable<Error> errors)
{
return Lines(errors.Select(e => e.Code));
}
private static string Lines(IEnumerable<string> lines)
{
return string.Join(Environment.NewLine, lines);
}
}
</code></pre>
<p>Coordinate:</p>
<pre><code>public struct Coordinate
{
public int X { get; }
public int Y { get; }
public Coordinate(int x, int y)
{
X = x;
Y = y;
}
public bool IsWithin(Coordinate minimum, Coordinate maximum)
{
return maximum.X >= X && maximum.Y >= Y && minimum.X <= X && minimum.Y <= Y;
}
public Coordinate Move(Direction direction)
{
if (direction.Equals(Direction.North))
{
return new Coordinate(X, Y + 1);
}
if (direction.Equals(Direction.East))
{
return new Coordinate(X + 1, Y);
}
if (direction.Equals(Direction.South))
{
return new Coordinate(X, Y - 1);
}
return new Coordinate(X - 1, Y);
}
}
</code></pre>
<p>Direction:</p>
<pre><code>public struct Direction
{
public static readonly Direction North = new Direction("N", "E", "W");
public static readonly Direction East = new Direction("E", "S", "N");
public static readonly Direction South = new Direction("S", "W", "E");
public static readonly Direction West = new Direction("W", "N", "S");
private static readonly List<Direction> ValidDirections = new List<Direction>()
{
North,East,South,West
};
public string Current { get; }
public string Right { get; }
public string Left { get; }
private Direction(string current, string right, string left)
{
Current = current;
Right = right;
Left = left;
}
public static Direction Create(string direction)
{
switch (direction)
{
case "N":
return North;
case "E":
return East;
case "S":
return South;
case "W":
return West;
default:
throw new ArgumentException($"Invalid direction {direction}", nameof(direction));
}
}
public Direction TurnLeft()
{
var left = Left;
return ValidDirections.Single(d => d.Current == left);
}
public Direction TurnRight()
{
var right = Right;
return ValidDirections.Single(d => d.Current == right);
}
public override string ToString() => Current;
}
</code></pre>
<p>Movement:</p>
<pre><code>public enum Movement
{
TurnLeft,
TurnRight,
Move
}
</code></pre>
<p>Rover:</p>
<pre><code>public class Rover
{
public string Id { get; }
public Coordinate Coordinate { get; }
public Direction Direction { get; }
private Rover(Coordinate coordinate, Direction direction)
{
Coordinate = coordinate;
Direction = direction;
Id = $"{coordinate.X}-{coordinate.Y}-{direction}";
}
public override string ToString() => $"{Coordinate.X} {Coordinate.Y} {Direction}";
public Result<Rover> Move(Movement[] movements, Coordinate[] obstacles, Coordinate minimum, Coordinate maximum)
{
var newCoordinate = new Coordinate(Coordinate.X, Coordinate.Y);
Direction newDirection = Direction;
foreach (var movement in movements)
{
if (movement == Movement.Move)
{
newCoordinate = newCoordinate.Move(newDirection);
if (newCoordinate.IsWithin(minimum, maximum) == false)
{
return Result<Rover>.Failure(Error.OutOfBoundRover(Id));
}
if (obstacles.Any(o => o.Equals(newCoordinate)))
{
return Result<Rover>.Failure(Error.Obstacle(Id, newCoordinate));
}
}
else
{
newDirection = movement == Movement.TurnLeft ? newDirection.TurnLeft() : newDirection.TurnRight();
}
}
return Result<Rover>.Success(new Rover(newCoordinate, newDirection));
}
public static Rover Create(string roverDetails)
{
var parts = roverDetails.Split(" ");
return new Rover(new Coordinate(int.Parse(parts[0]), int.Parse(parts[1])), Direction.Create(parts[2]));
}
}
</code></pre>
<p>Grid:</p>
<pre><code>public class Grid
{
private readonly Coordinate _maximumBoundaries;
private readonly Coordinate _minimumBoundaries;
private readonly List<Rover> _rovers;
private Grid(Coordinate minimumBoundaries, Coordinate maximumBoundaries)
{
_maximumBoundaries = maximumBoundaries;
_minimumBoundaries = minimumBoundaries;
_rovers = new List<Rover>();
}
public static Result<Grid> Create(string gridDetails)
{
var parts = gridDetails.Split(" ");
var hasX = int.TryParse(parts.FirstOrDefault(), out var gridX);
var hasY = int.TryParse(parts.LastOrDefault(), out var gridY);
if (!hasX || !hasY || gridX == 0 && gridY == 0)
{
return Result<Grid>.Failure(Error.InvalidGridSize);
}
var minimumBoundaries = new Coordinate(0, 0);
var maximumBoundaries = new Coordinate(gridX, gridY);
return Result<Grid>.Success(new Grid(minimumBoundaries, maximumBoundaries));
}
public Result AddRover(Rover rover, Movement[] movements)
{
if (_rovers.Any(r => r.Coordinate.Equals(rover.Coordinate)))
{
return Result.Failure(Error.RoverExists(rover.Id));
}
if (rover.Coordinate.IsWithin(_minimumBoundaries, _maximumBoundaries) == false)
{
return Result.Failure(Error.OutOfBoundRover(rover.Id));
}
var obstacles = _rovers
.Where(r => r.Id != rover.Id)
.Select(r => r.Coordinate).ToArray();
var moveResult = rover.Move(movements, obstacles, _minimumBoundaries, _maximumBoundaries);
if (moveResult.IsSuccess == false)
{
return moveResult;
}
_rovers.Add(moveResult.Value);
return Result.Success();
}
public string[] GetRoverStatuses()
{
return _rovers.Select(r => r.ToString()).ToArray();
}
}
</code></pre>
<p>Tests:</p>
<pre><code>public class MessageParserTests
{
private readonly MessageParser _sut;
public MessageParserTests()
{
_sut = new MessageParser();
}
[Fact]
public void WhenMessageIsValid_InitializesGrid()
{
var input = Lines(
"5 5",
"1 2 N",
"LMLMLMLMM",
"3 3 E",
"MMRMMRMRRM");
var output = _sut.HandleMessage(input);
output.Should().Be(Lines(
"1 3 N",
"5 1 E"));
}
[Theory]
[InlineData("")]
[InlineData(" ")]
[InlineData(null)]
public void WhenMessageIsNullOrEmpty_ReturnsErrorCode(string input)
{
var output = _sut.HandleMessage(input);
output.Should().Be("error.message.missing");
}
[Fact]
public void WhenMessageHasMissingGridSize_ReturnsErrorCode()
{
var input = Lines(
"1 2 N",
"LMLMLMLMM",
"3 3 E",
"MMRMMRMRRM");
var output = _sut.HandleMessage(input);
output.Should().Be("error.message.invalid");
}
[Fact]
public void WhenMessageGridSizeTooSmall_ReturnsErrorCode()
{
var input = Lines(
"0 0",
"1 2 N",
"LMLMLMLMM",
"3 3 E",
"MMRMMRMRRM");
var output = _sut.HandleMessage(input);
output.Should().Be("error.grid.size.invalid");
}
[Fact]
public void WhenMessageHasInvalidXForGridSize_ReturnsErrorCode()
{
var input = Lines(
"x 5",
"1 2 N",
"LMLMLMLMM",
"3 3 E",
"MMRMMRMRRM");
var output = _sut.HandleMessage(input);
output.Should().Be("error.message.invalid");
}
[Fact]
public void WhenMessageHasInvalidYForGridSize_ReturnsErrorCode()
{
var input = Lines(
"x 5",
"1 2 N",
"LMLMLMLMM",
"3 3 E",
"MMRMMRMRRM");
var output = _sut.HandleMessage(input);
output.Should().Be("error.message.invalid");
}
[Fact]
public void WhenMessageHasNegativeGridSize_ReturnsErrorCode()
{
var input = Lines(
"5 -5",
"1 2 N",
"LMLMLMLMM",
"3 3 E",
"MMRMMRMRRM");
var output = _sut.HandleMessage(input);
output.Should().Be("error.message.invalid");
}
[Fact]
public void WhenMessageHasMissingFirstRoverCoordinates_ReturnsErrorCode()
{
var input = Lines(
"5 5",
"LMLMLMLMM",
"3 3 E",
"MMRMMRMRRM");
var output = _sut.HandleMessage(input);
output.Should().Be("error.message.invalid");
}
[Fact]
public void WhenMessageHasOutOfBoundFirstRoverCoordinates_ReturnsErrorCode()
{
var input = Lines(
"5 5",
"6 2 N",
"LMLMLMLMM",
"3 3 E",
"MMRMMRMRRM");
var output = _sut.HandleMessage(input);
output.Should().Be("error.rover.[6-2-N].out.of.bound");
}
[Fact]
public void WhenMessageHasMissingFirstRoverMovements_ReturnsErrorCode()
{
var input = Lines(
"5 5",
"1 2 N",
"3 3 E",
"MMRMMRMRRM");
var output = _sut.HandleMessage(input);
output.Should().Be("error.message.invalid");
}
[Fact]
public void WhenMessageHasInvalidXForFirstRoverCoordinates_ReturnsErrorCode()
{
var input = Lines(
"5 5",
"X 2 N",
"LMLMLMLMM",
"3 3 E",
"MMRMMRMRRM");
var output = _sut.HandleMessage(input);
output.Should().Be("error.message.invalid");
}
[Fact]
public void WhenMessageHasInvalidYForFirstRoverCoordinates_ReturnsErrorCode()
{
var input = Lines(
"5 5",
"1 Y N",
"LMLMLMLMM",
"3 3 E",
"MMRMMRMRRM");
var output = _sut.HandleMessage(input);
output.Should().Be("error.message.invalid");
}
[Fact]
public void WhenMessageHasInvalidDirectionForFirstRoverCoordinates_ReturnsErrorCode()
{
var input = Lines(
"5 5",
"1 2 9",
"LMLMLMLMM",
"3 3 E",
"MMRMMRMRRM");
var output = _sut.HandleMessage(input);
output.Should().Be("error.message.invalid");
}
[Fact]
public void WhenMessageHasMissingSecondRoverCoordinates_ReturnsErrorCode()
{
var input = Lines(
"5 5",
"1 2 N",
"LMLMLMLMM",
"MMRMMRMRRM");
var output = _sut.HandleMessage(input);
output.Should().Be("error.message.invalid");
}
[Fact]
public void WhenMessageHasOutOfBoundSecondRoverCoordinates_ReturnsErrorCode()
{
var input = Lines(
"5 5",
"1 2 N",
"LMLMLMLMM",
"3 6 E",
"MMRMMRMRRM");
var output = _sut.HandleMessage(input);
output.Should().Be("error.rover.[3-6-E].out.of.bound");
}
[Fact]
public void WhenMessageHasInvalidXForSecondRoverCoordinates_ReturnsErrorCode()
{
var input = Lines(
"5 5",
"1 2 N",
"LMLMLMLMM",
"X 3 E",
"MMRMMRMRRM");
var output = _sut.HandleMessage(input);
output.Should().Be("error.message.invalid");
}
[Fact]
public void WhenMessageHasInvalidYForSecondRoverCoordinates_ReturnsErrorCode()
{
var input = Lines(
"5 5",
"1 2 N",
"LMLMLMLMM",
"3 Y E",
"MMRMMRMRRM");
var output = _sut.HandleMessage(input);
output.Should().Be("error.message.invalid");
}
[Fact]
public void WhenMessageHasInvalidDirectionForSecondRoverCoordinates_ReturnsErrorCode()
{
var input = Lines(
"5 5",
"1 2 N",
"LMLMLMLMM",
"3 3 2",
"MMRMMRMRRM");
var output = _sut.HandleMessage(input);
output.Should().Be("error.message.invalid");
}
[Fact]
public void WhenMessageHasMissingSecondRoverMovements_ReturnsErrorCode()
{
var input = Lines(
"5 5",
"1 2 N",
"LMLMLMLMM",
"3 3 E");
var output = _sut.HandleMessage(input);
output.Should().Be("error.message.invalid");
}
[Fact]
public void WhenMessageHasOverlappingRovers_ReturnsErrorCode()
{
var input = Lines(
"5 5",
"1 2 N",
"L",
"1 2 N",
"R");
var output = _sut.HandleMessage(input);
output.Should().Be("error.rover.[1-2-N].exists");
}
[Fact]
public void WhenMessageCausesRoversToCrash_ReturnsErrorCode()
{
var input = Lines(
"5 5",
"1 2 N",
"L",
"1 1 N",
"M");
var output = _sut.HandleMessage(input);
output.Should().Be("error.rover.[1-1-N].met.obstacle.[1,2]");
}
[Fact]
public void WhenMessageCausesRoverToGoOffGrid_ReturnsErrorCode()
{
var input = Lines(
"5 5",
"1 2 N",
"MMMM",
"1 1 N",
"M");
var output = _sut.HandleMessage(input);
output.Should().Be("error.rover.[1-2-N].out.of.bound");
}
private static string Lines(params string[] parts)
{
return string.Join(Environment.NewLine, parts);
}
}
</code></pre>
| [] | [
{
"body": "<p>On the whole, I quite like the approach. There's a few things to consider.</p>\n<h1>Test Size</h1>\n<p>Your first happy path test seems like it's testing quite a lot more than if the grid is initialized...</p>\n<blockquote>\n<pre><code>[Fact]\npublic void WhenMessageIsValid_InitializesGrid()\n{\n var input = Lines(\n "5 5",\n "1 2 N",\n "LMLMLMLMM",\n "3 3 E",\n "MMRMMRMRRM");\n var output = _sut.HandleMessage(input);\n\n output.Should().Be(Lines(\n "1 3 N",\n "5 1 E"));\n}\n</code></pre>\n</blockquote>\n<p>It's actually testing if two different rovers can be put on the grid and moved around it, covering all possible direction changes. I'd expect this to be more focussed.</p>\n<h1>Naming</h1>\n<p>Naming's always hard, however it's quite important. I'm not sure <code>MessageParser</code> is the right name for your high level class. I'd expect a message parser to take in a message and then return some kind of decoded model to represent the message, for example a list of commands (CreateGrid(5,5), AddRover(1,2,N), MoveRover(id), TurnRover(id, direction) etc). You parser is actually responsible for both decoding the message and executing each of the commands. This feels a bit misleading.</p>\n<h1>Direction</h1>\n<p>Your direction class has public three properties <code>Left</code>,<code>Right</code>,<code>Current</code>, which identify the direction string. This is really an implementation detail of the class, I'd consider if these really need to be public, or could they be private. Clients all use the <code>TurnLeft</code>/<code>TurnRight</code> methods.</p>\n<p>There's an overlap between the behaviour of <code>TurnLeft</code>, <code>TurnRight</code> and <code>Create</code>. All three methods convert from a string representation (N) to a Direction instance North. Whilst the <code>Turn</code> methods do it via a lookup, <code>Create</code> uses a switch. It seems like this could be consolidated to take one approach (Turn could rely on create, or create could perform a lookup and throw an error if it doesn't exist).</p>\n<p>Whilst the list is small, so iterating through it should be fast, I'd still tend to represent this type of lookup as a Map / Dictionary. Using a dictionary, the implementation might look like this:</p>\n<pre><code>private static Dictionary<String, Direction> validDirections = new Dictionary<string, Direction>\n{\n {"N", North },\n {"E", East },\n {"S", South },\n {"W", West }\n};\n\nprivate static Direction LookupDirection(string encodedDirection)\n{\n if (validDirections.TryGetValue(encodedDirection, out Direction direction))\n {\n return direction;\n }\n throw new ArgumentException($"Invalid direction {encodedDirection}", nameof(encodedDirection));\n}\n\npublic static Direction create(String encodedDirection)\n{\n return LookupDirection(encodedDirection);\n}\n\npublic Direction TurnLeft()\n{\n return LookupDirection(Left);\n}\n\npublic Direction TurnRight()\n{\n return LookupDirection(Right);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T12:58:00.623",
"Id": "239361",
"ParentId": "239187",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "239361",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T14:01:01.490",
"Id": "239187",
"Score": "2",
"Tags": [
"c#",
"unit-testing"
],
"Title": "First attempt at Mars Rover Kata done in TDD"
} | 239187 |
<p>I've made a simple brainfuck compiler, I feel like my code is unreadable and messy, how can I improve it?</p>
<p>src/core.clj</p>
<pre><code>(ns brainfuck-asm.core
(:require [brainfuck-asm.parse :as parse]
[brainfuck-asm.optimize :as optimize]
[brainfuck-asm.generate :as generate]
[clojure.java.io :as io]
[clojure.string :as str])
(:gen-class))
(defn- ^:const remove-initial-comment-loop
([sequence] (case (first sequence)
\[ (remove-initial-comment-loop (drop 1 sequence) 1)
sequence))
([[character & chars] matching-bracket-count]
(cond
(nil? character) (throw (IllegalArgumentException. "Unbalanced braces"))
(zero? matching-bracket-count) (str character (str/join chars))
(not= 0 matching-bracket-count) (recur chars (case character
\[ (inc matching-bracket-count)
\] (dec matching-bracket-count)
matching-bracket-count)))))
(defn- ^:const optimize-ast [ast]
(map #(update % :statements optimize/optimize-sentence) ast))
(defn- ^:const remove-illegal-characters [input]
(let [legal-characters #{\+ \- \< \> \. \, \[ \]}]
(filter #(contains? legal-characters %) input)))
(defn -main [& args]
(let [input-file-name (first args)]
(cond
(nil? input-file-name) (println "Please specify a brainfuck source file to compile")
(.exists (io/file input-file-name))
(let [brainfuck-code (slurp input-file-name)]
(if (parse/balanced? brainfuck-code)
(-> brainfuck-code
remove-illegal-characters
remove-initial-comment-loop
parse/generate-ast
optimize-ast
generate/generate-assembly
println)
(println "Your code's braces are unbalanced (missing [ or ]).")))
:else (println (str "Cannot find: " input-file-name "\nExiting...")))))
</code></pre>
<p>src/generate.clj</p>
<pre><code>(ns brainfuck-asm.generate
(:require [clojure.string :as str]))
(defn- ^:const prepare-statements [statements]
(->> statements flatten (map #(str " " %)) (str/join \newline)))
(defn- ^:const generate-segment [name & statements]
(str "segment ." name \newline (prepare-statements statements) \newline))
(defn- ^:const generate-label [name & statements]
(str \newline name \: \newline (prepare-statements statements) \newline))
(defn- ^:const generate-loop-condition [statement]
["cmp byte [eax], 0" (str "jne " (:argument statement)) "ret"])
(def ^:private ^:const print-cell
(generate-label "print_cell" "push eax" "mov ecx, eax" "mov eax, 0x04"
"mov ebx, 0x01" "mov edx, 0x01" "int 0x80" "pop eax" "ret"))
(def ^:private ^:const read-definition
(generate-label "read" "mov ecx, eax" "push eax" "mov eax, 0x03" "mov ebx, 0x00"
"mov edx, 0x01" "int 0x80" "pop eax" "ret"))
(def ^:private ^:const exit ["mov eax, 1" "xor ebx, ebx" "int 0x80"])
(defn- ^:const statement->asm
"Translates an statement to assembly code"
[statement]
(case (:type statement)
:inc "inc byte [eax]"
:dec "dec byte [eax]"
:inc-pointer "inc eax"
:dec-pointer "dec eax"
:add (str "add byte [eax], " (:argument statement))
:sub (str "sub byte [eax], " (:argument statement))
:add-pointer (str "add eax, " (:argument statement))
:sub-pointer (str "sub eax, " (:argument statement))
:call-print "call print_cell"
:call-read "call read"
:call-loop (str "call loop" (:argument statement))
:call-exit exit
:loop-end (generate-loop-condition statement)
:load-array "mov eax, array"
(throw (IllegalArgumentException. (str (:type statement) " is not a proper statement type")))))
(defn ^:const generate-assembly [ast]
(str
(generate-segment "bss" "array: resb 30000")
\newline
(generate-segment "text" "global _start")
(str/join (map #(apply generate-label (:name % "_start") (map statement->asm (:statements %))) ast))
print-cell
read-definition))
</code></pre>
<p>src/optimize.clj</p>
<pre><code>(ns brainfuck-asm.optimize
(:require [brainfuck-asm.parse :as parse]
[clojure.zip :as zip]))
(defn- ^:const optimize-two-statements
"Defines the rules for optimzing statements.
Returns nil if statements cannot be optimized, else the combination of statements"
[statement statement1]
(cond
(= (statement :type) (statement1 :type) :inc) (parse/create-statement :add 2)
(= (statement :type) (statement1 :type) :dec) (parse/create-statement :sub 2)
(= (statement :type) (statement1 :type) :inc-pointer) (parse/create-statement :add-pointer 2)
(= (statement :type) (statement1 :type) :dec-pointer) (parse/create-statement :sub-pointer 2)
(and (= (statement :type) :add) (= (statement1 :type) :inc)) (update statement :argument inc)
(and (= (statement :type) :sub) (= (statement1 :type) :dec)) (update statement :argument inc)
(and (= (statement :type) :add-pointer) (= (statement1 :type) :inc-pointer)) (update statement :argument inc)
(and (= (statement :type) :sub-pointer) (= (statement1 :type) :dec-pointer)) (update statement :argument inc)
:else nil))
(defn- ^:const optimize-sentence-zipper
"Takes a zipped sentence and optimizes it"
([sentence-zipper]
(if (-> sentence-zipper zip/next zip/end?)
(zip/root sentence-zipper)
(let [replacement (optimize-two-statements (zip/node sentence-zipper) (-> sentence-zipper zip/next zip/node))]
(case replacement
nil (recur (zip/next sentence-zipper))
(recur (-> sentence-zipper
(zip/replace replacement)
zip/next
zip/remove)))))))
(defn ^:const optimize-sentence
"Turns a vector of statements (sentence) into an optimized sentence.
Returns a vector"
[sentence]
(optimize-sentence-zipper (-> sentence zip/vector-zip zip/next)))
</code></pre>
<p>src/parse.clj</p>
<pre><code>(ns brainfuck-asm.parse)
(defn ^:const balanced?
"Returns whether brackets contained in expr are balanced"
([expr] (balanced? expr 0))
([[x & xs] count]
(cond (neg? count) false
(nil? x) (zero? count)
(= x \[) (recur xs (inc count))
(= x \]) (recur xs (dec count))
:else (recur xs count))))
(defn ^:const create-statement
([type]
{:type type})
([type argument]
{:type type
:argument argument}))
(defn- ^:const craete-loop [name]
{:name name
:type :loop
:statements []})
(defn- ^:const brainfuck->ast-node [character]
(case character
\+ (create-statement :inc)
\- (create-statement :dec)
\> (create-statement :inc-pointer)
\< (create-statement :dec-pointer)
\. (create-statement :call-print)
\, (create-statement :call-read)
(throw (IllegalArgumentException. (format "%s is not a valid brainfuck symbol" character)))))
(defn ^:const generate-ast
([brainfuck-symbols]
{:pre [(balanced? brainfuck-symbols)]}
(generate-ast '() {:type :entrypoint :statements [{:type :load-array}]} '() brainfuck-symbols 0))
([ast current-label stack [character & characters] loop-count]
(case character
nil (apply conj ast (update current-label :statements conj (create-statement :call-exit)) stack)
\[ (recur ast
(craete-loop (str "loop" loop-count))
(conj stack (update current-label :statements conj (create-statement :call-loop loop-count)))
characters
(inc loop-count))
\] (recur (conj ast (update current-label :statements conj (create-statement :loop-end (:name current-label))))
(peek stack)
(pop stack)
characters
loop-count)
(recur ast
(update current-label :statements conj (brainfuck->ast-node character))
stack
characters
loop-count))))
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T16:31:11.013",
"Id": "239196",
"Score": "3",
"Tags": [
"clojure",
"compiler"
],
"Title": "Brainfuck NASM compiler in Clojure"
} | 239196 |
<h1><code>sudoedit_enhanced</code> written POSIX-ly challenge</h1>
<hr>
<p>While creating <code>sudoedit_enhanced</code> POSIX (apart from <code>readlink</code> I have been pointed out) shell script snippet, I face two challenges:</p>
<ol>
<li><p>check if all the files exist, it does not make sense to create a new file this way</p></li>
<li><p><code>sudoedit</code> does not work with symlinks, so translate symlinks to normal file paths</p></li>
</ol>
<p>The core part (<em>carved out</em>) checking the existence of files and translates symlinks to normal files follows:</p>
<hr>
<pre class="lang-sh prettyprint-override"><code>for file in "$@"; do
if ! [ -f "$file" ]; then
printf '%s\n' >&2 "sudoedit_enhanced_run(): This file ('$file') does not exist or it is not a regular file."
return 1
fi
[ -L "$file" ] && file=$(readlink -f "$file")
set -- "$@" "$file"
shift
done
</code></pre>
<hr>
<p>It should work, though not much testing has been done so far, I am quite positive there is space to improve.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T17:05:36.320",
"Id": "239199",
"Score": "1",
"Tags": [
"file",
"posix",
"sh"
],
"Title": "sudoedit_enhanced written POSIX-ly (readlink possible problem?)"
} | 239199 |
<p>I have some code that is slow because it loops over every row in an input matrix <code>Y</code>. Obviously, this code does not scale with the number of rows. I don't think it's critical to understand what the code does, but for the curious, it is a <a href="https://en.wikipedia.org/wiki/Gibbs_sampling" rel="nofollow noreferrer">Gibbs sampling</a> step for sampling the dispersion parameter <code>r</code> for the <a href="https://en.wikipedia.org/wiki/Negative_binomial_distribution" rel="nofollow noreferrer">negative binomial distribution</a>.</p>
<p>Is there anything I can do to make this faster? I've tried <code>for y in Y_j[Y_j > 0]</code> in the <code>crt_sum</code> function, but that's not actually faster according to a simple speed test. I suspect because in many cases, the code loops over every row in the <code>Y_j</code>th column of <code>Y</code> in C and then does it again in Python.</p>
<pre class="lang-py prettyprint-override"><code>import numpy as np
def sample_r(Y, P, R, e0=1e-2, f0=1e-2):
"""Sample negative binomial dispersion parameter `r` based on
(Zhou 2020). See:
- http://people.ee.duke.edu/~mz1/Papers/Mingyuan_NBP_NIPS2012.pdf
- https://mingyuanzhou.github.io/Softwares/LGNB_Regression_v0.zip
"""
J = Y.shape[1]
for j in range(J):
L = crt_sum(Y, R, j)
A = e0 + L
# `maximum` is element-wise, while `max` is not.
maxes = np.maximum(1 - P[:, j], -np.inf)
B = 1. / (f0 - np.sum(np.log(maxes)))
R[j] = np.random.gamma(A, B)
# `R` cannot be zero.
inds = np.isclose(R, 0)
R[inds] = 0.0000001
return R
def crt_sum(Y, R, j):
"""Sum independent Chinese restaurant table random variables.
"""
Y_j = Y[:, j]
r = R[j]
L = 0
tbl = r / (r + np.arange(Y_j.max()))
for y in Y_j:
if y > 0:
u = np.random.uniform(0, 1, size=y)
inds = np.arange(y)
L += (u <= tbl[inds]).sum()
return L
</code></pre>
<p>Synthetic data should be sufficient. Basically, <code>Y</code> is a matrix of count data (non-negative integers), <code>P</code> is a matrix of numbers in the range [0, 1], and <code>R</code> is a matrix of positive (nonzero) real numbers. This should be sufficient to generate realistic data:</p>
<pre class="lang-py prettyprint-override"><code>def sigmoid(x):
return 1 / (1 + np.exp(-x))
N = 100
J = 10
Y = np.arange(N*J).reshape(N, J)
P = sigmoid(np.random.random((N, J)))
R = np.arange(J, dtype=float)+1
sample_r(Y, P, R)
</code></pre>
<p>I currently don't have any tests (sorry, lonely researcher code), but assuming my implementation is correct, this should pass</p>
<pre class="lang-py prettyprint-override"><code>assert(sample_r(Y, P, R) == sample_r_fast(Y, P, R))
</code></pre>
<p>where <code>sample_r_fast</code> a faster implementation. Thanks in advance.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T19:54:08.733",
"Id": "469206",
"Score": "0",
"body": "Do you have any unit tests or sample data for us?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T19:57:24.740",
"Id": "469207",
"Score": "0",
"body": "I don't have any tests. Assuming my current implementation is correct, is `assert(sample_r(Y, P, R) == sample_r_fast(Y, P, R))` sufficient? I also initialized some sample data at the bottom. Do you want real data?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T19:58:29.563",
"Id": "469209",
"Score": "0",
"body": "I guess synthetic data are sufficient, but a unit test would really help - you should edit the question to include that assert."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T20:06:42.093",
"Id": "469210",
"Score": "1",
"body": "Okay, I've edited the question to contain details about synthetic data and that assert."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T15:00:51.690",
"Id": "469259",
"Score": "0",
"body": "The negative binomial distribution is implemented in [`scipy.stats.nbinom`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.nbinom.html). It allows getting the PMF, CMF, moments and random variables according to it and is vectorized. I don't quite see which one of them you need, but you should probably check it out if you haven't already."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T20:54:11.440",
"Id": "469288",
"Score": "0",
"body": "Thanks. My code is for performing statistical inference, meaning given data you believe is negative binomial distributed, compute a best guess of the NB parameters `r` and `p`. There are many libraries for doing standard inference on standard distributions, but I'm performing a particular kind of inference (Gibbs sampling). My Gibbs sampler for NB is relatively new and is not supported by current statistical software packages."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T13:48:06.713",
"Id": "469984",
"Score": "1",
"body": "there is likely a bug in your code. the example returns integers `np.int32` because you replace values in R which has been generated using arange; yet, gamma is a real valued function. Is this intended?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T20:55:23.163",
"Id": "470159",
"Score": "0",
"body": "Good catch, thanks. I've edited the post so that `R` is `np.float64`."
}
] | [
{
"body": "<p>Yes, it is possible to vectorize the code. Does that make it faster? That depends on the spread of values in your data Y. </p>\n\n<p>Computing the <code>scale</code> parameter can be vectorized without issues and should be faster.</p>\n\n<p>For the <code>shape</code> parameter - I haven't read the papers - you seem to use something that looks quite similar to rejection sampling. You compute a probability distribution <code>tbl</code> over NxJ, then draw Y[n, j] many samples from a uniform distribution and check how often you land within <code>tbl[n,j]</code>. <code>shape</code> is then the sum of \"hits\" along N.</p>\n\n<p>The naive approach to vectorizing this would be to draw the same amount of samples for each Y[n, j]. In this case at least <code>max(Y)</code> many. This can create a lot of overhead if your data has a few really large values but otherwise small ones. If the values are fairly close together, this will make things faster. If you have a way to quickly (pre-)generate large quantities of uniform numbers this limitation doesn't matter.</p>\n\n<p>Here is the code:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def sample_r_vec(Y, P, R, e0=1e-2, f0=1e-2, random_numbers=None):\n \"\"\"Sample negative binomial dispersion parameter `r` based on\n (Zhou 2020). See:\n\n - http://people.ee.duke.edu/~mz1/Papers/Mingyuan_NBP_NIPS2012.pdf\n - https://mingyuanzhou.github.io/Softwares/LGNB_Regression_v0.zip\n \"\"\"\n\n if random_numbers is None:\n random_numbers = np.random.uniform(0, 1, size=(*Y.shape, np.max(Y) + 1))\n\n # compute shape\n Y_max_vec = np.arange(np.max(Y) + 1).reshape((-1, 1))\n R_vec = R.reshape((1, -1))\n tbl = (R_vec / (R_vec + Y_max_vec))\n tbl = tbl.reshape((*tbl.shape, 1))\n N_vec = np.arange(Y.shape[0]).reshape(-1, 1)\n J_vec = np.arange(Y.shape[1]).reshape(1, -1)\n sum_hits = np.cumsum(random_numbers <= tbl.T, axis=2)[N_vec, J_vec, Y - 1]\n sum_hits[Y == 0] = 0\n shape = e0 + np.sum(sum_hits, axis=0)\n\n # compute scale\n maxes = np.maximum(1 - P, -np.inf)\n scale = 1. / (f0 - np.sum(np.log(maxes), axis=0))\n\n # sample\n R = np.random.gamma(shape, scale)\n R[R < 1e-7] = 1e-7\n return R\n</code></pre>\n\n<p><strong>Edit:</strong> Based on the comment, I did find a different bug that is now fixed.</p>\n\n<hr>\n\n<p><strong>Edit:</strong> Demonstration that both versions perform equally.</p>\n\n<p>Firstly, we need a different test to assert equality of the code; try <code>assert(sample_r(Y, P, R) == sample_r(Y, P, R))</code> and you will quickly see the problem. There are many reasons why a different test is needed: (1) <code>sample_r</code> and <code>sample_r_fast</code> return vectors and not scalars. The truth value of a vector is undefined (numpy also warns for that). (2) your code (<code>sample_r</code>) modifies <code>R</code> in place, which means that the input to <code>sample_r_fast</code> will be different to the input of <code>sample_r</code>. Logically, the outputs will differ due to the unwanted side effect. (3) Both functions are expected to create random samples and compute results based on that. <code>assert</code> tests for <em>exact</em> equality and will hence fail even if both versions are correct. Providing the same random seed won't be enough either, because the order in which the samples are used may differ, which will change the results. (4) This is a numerics problem; even in the deterministic part of the code it is only accurate up to a tolerance. (5) The code estimates parameters for a distribution and then samples once from the estimated distribution; these samples are then compared. If we want to know whether or not the two versions estimate the same distributions it seems much more efficient to directly compare the parameters.</p>\n\n<p>To fix all of this, I modified the code in the following way:</p>\n\n<ol>\n<li>Added an optional parameter to the function that can be used as random numbers; generate them if <code>none</code>.</li>\n<li>Made sure the same random numbers are used for comparisons each time.</li>\n<li>Removed the sampling of R at the end and instead return the estimated shape and scale directly.</li>\n<li>It is also nice to test if the new code is actually faster, so I added a speed test (excluding RNG).</li>\n</ol>\n\n<p>My full script looks like this:</p>\n\n<pre><code>import numpy as np\n\n\ndef sample_r(Y, P, R, e0=1e-2, f0=1e-2, random_numbers=None):\n \"\"\"Sample negative binomial dispersion parameter `r` based on\n (Zhou 2020). See:\n\n - http://people.ee.duke.edu/~mz1/Papers/Mingyuan_NBP_NIPS2012.pdf\n - https://mingyuanzhou.github.io/Softwares/LGNB_Regression_v0.zip\n \"\"\"\n\n if random_numbers is None:\n random_numbers = np.random.uniform(0, 1, size=(*Y.shape, np.max(Y) + 1))\n\n A_vec = np.zeros_like(R)\n B_vec = np.zeros_like(R)\n J = Y.shape[1]\n for j in range(J):\n L = crt_sum(Y, R, j, random_numbers)\n A = e0 + L\n A_vec[j] = A\n\n # `maximum` is element-wise, while `max` is not.\n maxes = np.maximum(1 - P[:, j], -np.inf)\n B = 1. / (f0 - np.sum(np.log(maxes)))\n B_vec[j] = B\n\n # R[j] = np.random.gamma(A, B)\n # `R` cannot be zero.\n # inds = np.isclose(R, 0)\n # R[inds] = 0.0000001\n return A_vec, B_vec\n\n\ndef crt_sum(Y, R, j, random_numbers):\n \"\"\"Sum independent Chinese restaurant table random variables.\n \"\"\"\n\n Y_j = Y[:, j]\n r = R[j]\n L = 0\n tbl = r / (r + np.arange(Y_j.max()))\n for n_idx, y in enumerate(Y_j):\n if y > 0:\n relevant_numbers = random_numbers[n_idx, j, :y]\n inds = np.arange(y)\n L += (relevant_numbers <= tbl[inds]).sum()\n return L\n\n\ndef sample_r_vec(Y, P, R, e0=1e-2, f0=1e-2, random_numbers=None):\n \"\"\"Sample negative binomial dispersion parameter `r` based on\n (Zhou 2020). See:\n\n - http://people.ee.duke.edu/~mz1/Papers/Mingyuan_NBP_NIPS2012.pdf\n - https://mingyuanzhou.github.io/Softwares/LGNB_Regression_v0.zip\n \"\"\"\n\n if random_numbers is None:\n random_numbers = np.random.uniform(0, 1, size=(*Y.shape, np.max(Y) + 1))\n\n # compute shape\n Y_max_vec = np.arange(np.max(Y) + 1).reshape((-1, 1))\n R_vec = R.reshape((1, -1))\n tbl = (R_vec / (R_vec + Y_max_vec))\n tbl = tbl.reshape((*tbl.shape, 1))\n N_vec = np.arange(Y.shape[0]).reshape(-1, 1)\n J_vec = np.arange(Y.shape[1]).reshape(1, -1)\n sum_hits = np.cumsum(random_numbers <= tbl.T, axis=2)[N_vec, J_vec, Y - 1]\n sum_hits[Y == 0] = 0\n shape = e0 + np.sum(sum_hits, axis=0)\n\n # compute scale\n maxes = np.maximum(1 - P, -np.inf)\n scale = 1. / (f0 - np.sum(np.log(maxes), axis=0))\n\n return shape, scale\n\nif __name__ == \"__main__\":\n def sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\n np.random.seed(1337)\n\n N = 100\n J = 10\n Y = np.arange(N*J, dtype=np.int32).reshape(N, J)\n P = sigmoid(np.random.random((N, J)))\n # use test case from comments\n R = np.ones(J, dtype=np.float32); R[J-1] = 5000\n random_numbers = np.random.uniform(0, 1, size=(*Y.shape, np.max(Y) + 1))\n\n shape_normal, scale_normal = sample_r(Y.copy(), P.copy(), R.copy(), random_numbers=random_numbers)\n shape_vec, scale_vec = sample_r_vec(Y.copy(), P.copy(), R.copy(), random_numbers=random_numbers)\n\n assert np.all(np.isclose(scale_normal, scale_vec))\n assert np.all(np.isclose(shape_normal, shape_vec))\n\n #speed test\n import timeit\n t1 = timeit.timeit(lambda: sample_r(Y.copy(), P.copy(), R.copy(), random_numbers=random_numbers), number=100)\n t2 = timeit.timeit(lambda: sample_r_vec(Y.copy(), P.copy(), R.copy(), random_numbers=random_numbers), number=100)\n print(f\"Original version total time {t1:.2f}. Vector Version total time {t2:.2f}.\")\n\n N = 1000\n J = 10\n Y = 100*np.ones(N*J, dtype=np.int32).reshape(N, J)\n P = sigmoid(np.random.random((N, J)))\n R = np.arange(J)+1\n random_numbers = np.random.uniform(0, 1, size=(*Y.shape, np.max(Y) + 1))\n t1 = timeit.timeit(lambda: sample_r(Y.copy(), P.copy(), R.copy(), random_numbers=random_numbers), number=100)\n t2 = timeit.timeit(lambda: sample_r_vec(Y.copy(), P.copy(), R.copy(), random_numbers=random_numbers), number=100)\n print(f\"Original version total time {t1:.2f}. Vector Version total time {t2:.2f}.\")\n</code></pre>\n\n<p><em>Note that this now has a python 3.7+ dependency due to format strings in the functional test, the relevant code does not have that dependency.</em></p>\n\n<p>Output:</p>\n\n<pre><code>Original version total time 1.29. Vector Version total time 1.05.\nOriginal version total time 8.55. Vector Version total time 0.98.\n</code></pre>\n\n<p>I did the following modifications to your code: To return the estimated parameters, I am stacking them up in a vector as they are being computed. To deal with the random sampling, I generate a whole bunch of random numbers (<code>Y.max()</code> many) for each <code>Y[n, j]</code>, and then select the first <code>y=Y[n,j]</code> of them. This is the same idea I used to vectorize the code; it 'wastes' <code>Y.max() - Y[n, j]</code> many random samples at each step, because the code generates them but then doesn't use them; it's a trick to match the shapes for vectorization. This is the main reason why the vectorized version will only be faster if you either (1) pre-generate the random numbers, or (2) have a situation where the different <code>Y[n, j]</code> don't differ too much, so that generating the 'waste' doesn't take more time than is saved by hardware acceleration.</p>\n\n<p>I hope this explains what is going on.</p>\n\n<p>PS: Please, please use informative variable names for code in the future. <code>L,n,j,A,B</code>, ect. are not wise choices if others are to read your code or if you try to understand it 3 years from now.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T21:00:25.613",
"Id": "470160",
"Score": "0",
"body": "+1 because this is close; however the code has a bug. Note that we do not compute `Y.max()` but rather `Y[:, j].max()`. Hence, `random_numbers` is wrong, `tbl` is wrong, etc. This is actually the main thing I don't know how to vectorize, since it would result in arrays with inconsistently sized rows. The reason your code approximates mine is that in the toy data, all the largest values are in the last row. This means that each column has approximately the same value for `Y[:, j].max()`. Try this pathological case to see the approximation error grow: `R = np.ones(J); R[J-1] = 5000`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T03:59:37.500",
"Id": "470189",
"Score": "0",
"body": "@gwg I probably didn't explain my idea well. I can start by computing `tbl = r / (r + np.arange(Y[:, j].max()))` which is an array of length `Y[:, j]`. Note that `np.arange(Y.max())[:Y[:,j]] == np.arange(Y[:,j])` (note the leading `:`). The values after `Y[:,j]` are unused padding to make the shapes match across `j`. As long as I don't access the padding, that is okay. Same idea for `random_numbers`. If the comment is not clear, I will elaborate in the answer. I will also check for other bugs to see why the results differ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-07T14:48:41.407",
"Id": "470953",
"Score": "0",
"body": "I didn't get a notification for your edit, but it looks great. Thank you. I haven't had time to verify it yet—this is an active research project with a lot of moving parts—but I'll accept it so I don't forget. You're correct that the `assert(...)` was conceptual, not a real test. I'll test using `np.isclose` and by verifying that model learns the `R` parameter in a controlled setting."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-07T15:36:50.337",
"Id": "470957",
"Score": "0",
"body": "@gwg for such a controlled setting, you can check the second half of my answer :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T14:47:20.600",
"Id": "239611",
"ParentId": "239204",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "239611",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T19:42:15.123",
"Id": "239204",
"Score": "4",
"Tags": [
"python",
"numpy"
],
"Title": "Can this sampling code be vectorized or optimized?"
} | 239204 |
<p>I designed a game with trying to use solid principles. What changes should I do for making program more extensible, readable. Thanks in advance.</p>
<p><strong>Cell class</strong></p>
<pre><code>public class Squares
{
public int NumberOfAdjacentMines { get; set; }
public bool IsMine { get; set; }
public bool IsFlagged { get; set; }
// show if square is left-clicked and opened
public bool IsUncovered { get; set; }
public Point Location { get ; set ; }
}
</code></pre>
<p><strong>ElapsedTime Class</strong></p>
<pre><code>public class ElapsedTime
{
Stopwatch stopwatch;
long elapsedTime;
public ElapsedTime()
{
elapsedTime = 0;
stopwatch = new Stopwatch();
stopwatch.Start();
}
// getting elapsed time in watch format like 01 : 57
public string TimeInHourFormat()
{
elapsedTime = stopwatch.ElapsedMilliseconds / 1000;
int second = (int) elapsedTime % 60;
int minute = (int) elapsedTime / 60;
string result = string.Empty;
if (second < 10)
{
result = $": 0{second}";
}
else
{
result = $": {second}";
}
if (minute < 10)
{
result = $"0{minute} {result}";
}
else
{
result = $"{minute} {result}";
}
if (elapsedTime > 3600)
{
int hour = (int)elapsedTime / 3600;
result = $"{hour} : {result}";
}
return result;
}
public void StopTimer()
{
stopwatch.Stop();
}
}
</code></pre>
<p><strong>Map Class</strong></p>
<pre><code>public class Map
{
public List<Squares> SquaresWithMine { get; private set; }
public Squares[,] AllSquares { get; set; }
public int MineNumber { get; set; }
public Map(int squaresHorizontal, int squaresVertical, int mineNumber)
{
MineNumber = mineNumber;
AllSquares = new Squares[squaresVertical, squaresHorizontal];
SquaresWithMine = new List<Squares>(mineNumber);
for (int i = 0; i < AllSquares.GetLength(0); i++)
{
for (int j = 0; j < AllSquares.GetLength(1); j++)
{
AllSquares[i, j] = new Squares()
{
Location = new Point(j, i),
IsFlagged = false,
IsMine = false,
IsUncovered = false,
NumberOfAdjacentMines = 0
};
}
}
}
public Squares Square(int x, int y)
{
return AllSquares[y, x];
}
// list of non-clicked and no mine squares For showing left squares
// after all mines are opened
public IEnumerable<Squares> NotOpenedSquares()
{
IEnumerable<Squares> notOpenedSquares;
notOpenedSquares = AllSquares
.Cast<Squares>()
.Where(item => !item.IsMine & !item.IsUncovered);
return notOpenedSquares;
}
// create a mine-free region 3X3 or 2X2 at corners for first click event
IEnumerable<Squares> MineFreeRegion(Point firstClickedSquare)
{
int x = firstClickedSquare.X;
int y = firstClickedSquare.Y;
List<Squares> neighborhoods = NeighborhoodCells(firstClickedSquare).ToList();
neighborhoods.Add(AllSquares[y, x]);
return neighborhoods;
}
// getting list of adjacent neighborhood squares
IEnumerable<Squares> NeighborhoodCells(Point square)
{
var adjacentCells = new List<Squares>();
int currentTop;
int currentLeft;
for (int i = -1; i < 2; i++)
{
for (int j = -1; j < 2; j++)
{
if (i != 0 | j != 0)
{
currentLeft = square.X + j;
currentTop = square.Y + i;
if (currentLeft > -1 & currentLeft < AllSquares.GetLength(1))
{
if (currentTop > -1 & currentTop < AllSquares.GetLength(0))
{
Squares neighborhood = AllSquares[currentTop, currentLeft];
adjacentCells.Add(neighborhood);
}
}
}
}
}
return adjacentCells;
}
// getting mine list in the order on being close to first clicked mine
public IEnumerable<Squares> MinesFromCloseToAway(Point clicked)
{
IEnumerable<Squares> orderedMines;
orderedMines = SquaresWithMine
.OrderBy(item => MineDistanceToExplosion(item.Location, clicked));
return orderedMines;
}
// calculate mines distance to first clicked mine
int MineDistanceToExplosion(Point mine, Point explosion)
{
int x = mine.X - explosion.X;
int y = mine.Y - explosion.Y;
int distance = x * x + y * y;
return distance;
}
// if a square that has no mine neighborhood is clicked, then it and its adjacent cells
// will be added to list for opening all once
public void OpenSquaresRecursively(IList<Squares> squares, Squares clicked)
{
clicked.IsUncovered = true;
squares.Add(clicked);
IEnumerable<Squares> nghbrhds = NeighborhoodCells(clicked.Location);
foreach (Squares neighborhoodSquare in nghbrhds)
{
if (neighborhoodSquare.IsUncovered | neighborhoodSquare.IsFlagged)
{
continue;
}
if (neighborhoodSquare.NumberOfAdjacentMines == 0)
{
OpenSquaresRecursively(squares, neighborhoodSquare);
}
else
{
neighborhoodSquare.IsUncovered = true;
squares.Add(neighborhoodSquare);
}
}
}
public void OpenSquare(Squares square)
{
square.IsUncovered = true;
}
public void ChangeFlagState(Squares clicked)
{
clicked.IsFlagged = !clicked.IsFlagged;
}
// when first click is made, a mine free region that include first clicked square
// in the middle is created and those cells is removed from the all cell list
// for placing mines in squares those left. after that this in line list is shuffled
// with creating random numbers
public void LocateMinesRandomly(Point firstClickedSquare)
{
Random random = new Random();
IEnumerable<Squares> mineFreeRegion = MineFreeRegion(firstClickedSquare);
AllSquares
.Cast<Squares>()
.Where(point => !mineFreeRegion.Any(square => square.Location == point.Location))
.OrderBy(item => random.Next())
.Take(MineNumber)
.ToList()
.ForEach(item =>
{
Squares mine = AllSquares[item.Location.Y, item.Location.X];
mine.IsMine = true;
SquaresWithMine.Add(mine);
});
}
// calculate number of adjacent mines that a no-mine square has
public void FindMinesAdjacent()
{
SquaresWithMine
.SelectMany(item
=> NeighborhoodCells(item.Location))
.ToList()
.ForEach(item => item.NumberOfAdjacentMines++);
}
}
</code></pre>
<p><strong>Game class</strong></p>
<pre><code>public enum Clicks
{
DefaultClick = 0,
LeftClick = 1,
RightClick = 2
}
public enum Actions
{
DoNothing = 0,
PutFlag,
RemoveFlag,
ExplodeAllMines,
OpenSquare,
OpenSquaresRecursively
}
public enum GameStatus
{
Default = 0,
NotFinished,
Won,
Lost
}
public class Game
{
bool firstClick;
bool clickedToMine;
public int WinningScore { get; private set; }
public int CurrentScore { get; private set; }
public Squares[,] Squares { get; private set; }
Map map;
public Game(int squaresHorizontal, int squaresVertical, int mineNumber)
{
CurrentScore = 0;
WinningScore = squaresHorizontal * squaresVertical - mineNumber;
firstClick = false;
clickedToMine = false;
map = new Map(squaresHorizontal, squaresVertical, mineNumber);
Squares = map.AllSquares;
}
public int NumberOfNotOpenedSafetySquare()
{
return WinningScore - CurrentScore;
}
public Squares Square(int x, int y)
{
return map.AllSquares[y, x];
}
public GameStatus GameSituation()
{
if (CurrentScore == WinningScore)
{
return GameStatus.Won;
}
else if (clickedToMine)
{
return GameStatus.Lost;
}
else
{
return GameStatus.NotFinished;
}
}
public Actions ClickSquare(Clicks mouseClick, Squares clicked)
{
// running once when map is first time clicked by left click during game
if (!firstClick & mouseClick == Clicks.LeftClick)
{
StartGame(clicked.Location);
firstClick = !firstClick;
}
if (mouseClick == Clicks.RightClick)
{
Actions result;
// if a square ic left-clicked before then right click has no effect
if (clicked.IsUncovered)
{
return Actions.DoNothing;
}
// if square has flag on it then it will be removed
// else flag will be placed on it
if (clicked.IsFlagged)
{
result = Actions.RemoveFlag;
}
else
{
result = Actions.PutFlag;
}
ChangeFlagState( clicked);
return result;
}
if (mouseClick == Clicks.LeftClick)
{
// if a square that has flag on it received left-click
// there will be no effect
if (clicked.IsFlagged)
{
return Actions.DoNothing;
}
if (clicked.IsMine)
{
clickedToMine = true;
return Actions.ExplodeAllMines;
}
// if a square that has mine neighborhood is clicked,
// a number of mines will be wrote on it
if (clicked.NumberOfAdjacentMines > 0)
{
OpenSquare(clicked);
return Actions.OpenSquare;
}
// if a square that has no mine neighborhood is clicked,
// then its neighborhodo and itself will be opened at once
else
{
return Actions.OpenSquaresRecursively;
}
}
return Actions.DoNothing;
}
public IEnumerable<Squares> NotOpenedSquare()
{
IEnumerable<Squares> notOpenedSquares = map.NotOpenedSquares();
return notOpenedSquares;
}
// getting list of mines for showing where each all of them
// if a mine is clicked by the user
public IEnumerable<Squares> MinesToShow()
{
IEnumerable<Squares> minesToShow = map.SquaresWithMine;
return minesToShow;
}
// getting list of in line mines for exploding all if a mine is clicked by the user
public IEnumerable<Squares> MinesToExplode(Squares clicked)
{
IEnumerable<Squares> minesToExplode = map.MinesFromCloseToAway(clicked.Location);
return minesToExplode;
}
// if a square that has no mine neighborhood is clicked then
// its all neighborhoods and itself is added a list for opening all in once
// and number of those added to score
public IEnumerable<Squares> SquaresWillBeOpened(Squares clicked)
{
var squaresWillBeOpened = new List<Squares>();
map.OpenSquaresRecursively(squaresWillBeOpened, clicked);
CurrentScore += squaresWillBeOpened.Count;
return squaresWillBeOpened;
}
public void StartGame(Point firstClickedSquare)
{
map.LocateMinesRandomly(firstClickedSquare);
map.FindMinesAdjacent();
}
public void OpenSquare(Squares square)
{
map.OpenSquare(square);
CurrentScore++;
}
void ChangeFlagState(Squares clicked)
{
map.ChangeFlagState(clicked);
}
}
</code></pre>
<p><strong>Form Class</strong></p>
<pre><code>public partial class Form1 : Form
{
Color buttonBackColor;
int buttonSize;
int buttonNumberX;
int buttonNumberY;
int mineNumber;
Game game;
Timer timer;
ElapsedTime elapsedTime;
Button[,] allButtons;
Dictionary<Button, Squares> squaresInButtons;
Dictionary<GameStatus, string> gameResultText;
Dictionary<GameStatus, Color> gameResultColor;
public Form1()
{
buttonSize = 35;
buttonNumberX = 38;
buttonNumberY = 17;
mineNumber = (buttonNumberX * buttonNumberY) / 9 ;
buttonBackColor = Color.FromArgb(160, 90, 250);
gameResultText = new Dictionary<GameStatus, string>
{
{ GameStatus.Won, "- - - - - WON - - - - - -" },
{ GameStatus.Lost, "- - - - - LOST - - - - - -" }
};
gameResultColor = new Dictionary<GameStatus, Color>
{
{ GameStatus.Won, Color.Green },
{ GameStatus.Lost, Color.Red }
};
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
int panelWidth = buttonNumberX * buttonSize;
int panelHeight = buttonNumberY * buttonSize;
this.Width = panelWidth + 50;
this.Height = panelHeight + 100;
pnlMayınlar.Size = new Size(panelWidth, panelHeight);
pnlMayınlar.Left = 20;
pnlMayınlar.Top = 85;
pnlMayınlar.BackColor = Color.Black;
InitializeGame();
int lblTop = 40;
label2.Top = lblTop;
lblTimeShower.Top = lblTop;
label1.Text = "Remaining Square : " + game.NumberOfNotOpenedSafetySquare().ToString();
label1.Location = new Point(panelWidth - label1.Width, lblTop);
pnlMayınlar.Show();
}
void InitializeGame()
{
squaresInButtons = new Dictionary<Button, Squares>();
game = new Game(buttonNumberX, buttonNumberY, mineNumber);
allButtons = new Button[buttonNumberY, buttonNumberX];
pnlMayınlar.Enabled = true;
for (int i = 0; i < game.Squares.GetLength(0); i++)
{
for (int j = 0; j < game.Squares.GetLength(1); j++)
{
Button button = CreateButton(j, i);
squaresInButtons.Add(button, game.Square(j, i));
pnlMayınlar.Controls.Add(button);
}
}
label2.Hide();
label1.Show();
SetLabelText(game.NumberOfNotOpenedSafetySquare());
elapsedTime = new ElapsedTime();
timer = new Timer
{
Interval = 1000,
};
timer.Tick += DrawElapsedTime;
timer.Start();
}
Button CreateButton(int x, int y)
{
Button button = new Button()
{
Size = new Size(buttonSize, buttonSize),
Top = y * buttonSize,
Left = x * buttonSize,
BackColor = buttonBackColor,
BackgroundImageLayout = ImageLayout.Stretch
};
button.MouseDown += ClickingOnSquares;
allButtons[y, x] = button;
return button;
}
private void yeniOyunToolStripMenuItem_Click(object sender, EventArgs e)
{
pnlMayınlar.Controls.Clear();
InitializeGame();
}
void ClickingOnSquares(object sender, MouseEventArgs e)
{
Button clicked = sender as Button;
Squares square = squaresInButtons[clicked];
if (e.Button == MouseButtons.Right)
{
Actions actions = game.ClickSquare(Clicks.RightClick, square);
if (actions == Actions.DoNothing)
{
return;
}
if (actions == Actions.PutFlag)
{
clicked.BackgroundImage = Properties.Resources.flagIcon;
}
else if(actions == Actions.RemoveFlag)
{
clicked.BackgroundImage = null;
clicked.BackColor = buttonBackColor;
}
}
if (e.Button == MouseButtons.Left)
{
Actions actions = game.ClickSquare(Clicks.LeftClick, square);
if (actions == Actions.DoNothing)
{
return;
}
// open left clicked square that has at least one neighborhood mine
else if (actions == Actions.OpenSquare)
{
OpenMineFreeSquare(square);
}
// open square that has no mine neighborhood and its neighborhoods at once
else if (actions == Actions.OpenSquaresRecursively)
{
IEnumerable<Squares> squareList = game.SquaresWillBeOpened(square);
foreach (Squares item in squareList)
{
OpenMineFreeSquare(item);
}
}
else if (actions == Actions.ExplodeAllMines)
{
// show where all mines are after any mine is clicked
IEnumerable<Squares> allMines = game.MinesToShow();
ShowMines(allMines);
Thread.Sleep(1000);
// put exploded mine image on every mine
//in order to their distance first clicked mine
IEnumerable<Squares> inLineMines = game.MinesToExplode(square);
ExplodeAllMines(inLineMines);
}
SetLabelText(game.NumberOfNotOpenedSafetySquare());
// getting game situation for checking if there is a win or lose
GameStatus gameState = game.GameSituation();
// if game should be continue then leave method
// else check there is a win or lose and do necessary things
if (gameState == GameStatus.NotFinished | gameState == GameStatus.Default)
{
return;
}
else
{
// stop counting time and write resulting text above map
timer.Stop();
label1.Hide();
label2.Show();
label2.ForeColor = gameResultColor[gameState];
label2.Text = gameResultText[gameState];
label2.Left = (this.Width - label2.Width) / 2;
if (gameState == GameStatus.Won)
{
IEnumerable<Squares> notDetonetedMines = game.MinesToShow();
ShowMines(notDetonetedMines);
}
else
{
// opening all not opened non-mine squares after all mines exploded
IEnumerable<Squares> NotOpenedSquares = game.NotOpenedSquare();
foreach (Squares item in NotOpenedSquares)
{
OpenMineFreeSquare(item);
Thread.Sleep(10);
}
}
pnlMayınlar.Enabled = false;
}
}
}
// when a no-mine square is clicked, number of neighborhood mine is wrote
// on it and colored depending on that number
void OpenMineFreeSquare(Squares square)
{
Button clicked = allButtons[square.Location.Y, square.Location.X];
if (square.NumberOfAdjacentMines > 0)
{
clicked.Text = square.NumberOfAdjacentMines.ToString();
}
clicked.BackColor = SquareTextColor(square.NumberOfAdjacentMines);
clicked.Enabled = false;
}
// put a detoneted mine image on squares after any mine is clicked
void ExplodeAllMines(IEnumerable<Squares> inLineMines)
{
foreach (Squares item in inLineMines)
{
Button willBeDetoneted = allButtons[item.Location.Y, item.Location.X];
willBeDetoneted.BackgroundImage = Properties.Resources.detonetedmine;
willBeDetoneted.Enabled = false;
willBeDetoneted.Update();
Thread.Sleep(50);
}
}
// put a not-detoneted mine image on squares before detoneted mine image is put
// for making exploding animation
void ShowMines(IEnumerable<Squares> inLineMines)
{
foreach (Squares item in inLineMines)
{
Button willBeDetoneted = allButtons[item.Location.Y, item.Location.X];
willBeDetoneted.BackgroundImage = Properties.Resources.notDetonetedMine;
willBeDetoneted.Enabled = false;
}
}
// start when map is loaded and showing elapsed time at the left upper corner
void DrawElapsedTime(object source, EventArgs e)
{
lblTimeShower.Text = elapsedTime.TimeInHourFormat();
}
// write number of how many more square must be clicked for to win
void SetLabelText(int score)
{
label1.Text = "Remaining Square : " + score.ToString();
}
// color list for squares those have neighborhood mine at least one
Color SquareTextColor(int mineNumber)
{
Color[] colors = {
Color.FromArgb(180, 180, 180) ,
Color.FromArgb(20, 110, 250) ,
Color.FromArgb(10, 220, 20),
Color.FromArgb(250, 20, 20),
Color.FromArgb(150, 20, 60),
Color.FromArgb(180, 40, 170),
Color.FromArgb(90, 20, 20),
Color.FromArgb(80, 30, 60),
Color.FromArgb(50, 10, 40)
};
return colors[mineNumber];
}
}
</code></pre>
| [] | [
{
"body": "<p>That's a lot of code to review. I've given it a cursory review and have a few comments, but by no means is it an exhaustive review.</p>\n\n<p>Overall, I like your style. Nice indentation, uses of braces, class access modifiers, IEnumerable(s), and variable names not being abbreviated. Most of the times, but not all, your names are clear.</p>\n\n<p>Other things stand out. Unless an enum uses flags, naming should be singular, not plural. See <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/enum\" rel=\"nofollow noreferrer\">Enum Design</a> for more. Doing so could cause some confusion with an enum now renamed to Click or Action. Perhaps you may rename them to CellClick and CellAction.</p>\n\n<p>I'm not a fan of the class name <code>Squares</code>. I personally would have chosen <code>Cell</code>. This is a matter of taste. However, if you keep it as square, then that class name should also be singular <code>Square</code> since the class describes a single square and not a collection.</p>\n\n<p>I can't help but wonder if the Square properties IsMine, IsFlagged, and IsUncovered could not be condensed into a State. Maybe not all 3 could be used, but 2 perhaps could determine a State.</p>\n\n<p>I see no reason for the <code>ElapsedTime</code> class. The <code>TimeInHourFormat</code> could become an extension method or just a method placed inside the UI form. If it were an extension method, there could be 2 overloads. One that accepts <code>(this Stopwatch stopwatch)</code> and the other that has <code>(this TimeSpan elapsedTime)</code>. The main logic would be to the <code>TimeSpan</code>.</p>\n\n<p>That's about all I can cover before getting to work. Overall it looks very good, but there is definitely room for improvement.</p>\n\n<p><strong>UPDATE WITH EXTENSIONS</strong></p>\n\n<p>I had some free time to whip out sample extensions. Note that <code>ToString(\"00\")</code> takes care of the nit-picky details in a lot less code.</p>\n\n<pre><code>public static class StopwatchExtensions\n{\n public static string ToHoursMinutesSeconds(this Stopwatch stopwatch) => ToHoursMinutesSeconds(stopwatch.Elapsed);\n\n public static string ToHoursMinutesSeconds(this TimeSpan elapsed) \n {\n // You really do not need secondsText and minutesText. \n // You could use each respective right-hand expression in the return statement below.\n var secondsText = elapsed.Seconds.ToString(\"00\");\n var minutesText = elapsed.Minutes.ToString(\"00\");\n var hours = (long)Math.Truncate(elapsed.TotalHours);\n var hoursText = (hours > 0) ? hours.ToString(\"00\") + \":\" : \"\";\n return $\"{hoursText}{minutesText}:{secondsText}\";\n }\n}\n</code></pre>\n\n<p>Don't be thrown off by \"00\" for hours. It will display a minimum of 2 digits, but if hours is > 99, it will display all the digits. You are liberated from worrying about having your custom stopwatch class take care of all the mechanics of operating a stopwatch. All you care about is formatting the elapsed time, not just for a <code>Diagnostics.Stopwatch</code> but for any <code>TimeSpan</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-03T12:27:20.337",
"Id": "470528",
"Score": "0",
"body": "@yuga Answer updated with sample code"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T12:41:28.707",
"Id": "239439",
"ParentId": "239207",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T21:44:10.797",
"Id": "239207",
"Score": "4",
"Tags": [
"c#",
"game",
"winforms",
"minesweeper"
],
"Title": "C# MineSweeper Game using winform"
} | 239207 |
<p>New to coding/Javascript. Writing a basic Tic Tac Toe game.</p>
<p>I'm writing the game to be dynamic, so it won't always be a three-by-three grid, but rather any size grid larger than 1. I have a completely functioning game and win checker function, but the win checker is very, very wet. I've tried several way to dry it up, but can't really find a good pattern that doesn't cause bugs or issues. </p>
<p>The winChecker function below receives a 2D array that could resemble something like (for a 3x3 grid):</p>
<pre><code>const squares = [
[null, null, null],
[null, null, null],
[null, null, null]
];
</code></pre>
<p>The winChecker function looks like: </p>
<pre><code>const winChecker = squares => {
for (let column = 0; column < squares.length; column++) {
const horizontalCase = squares[column][0];
const verticalCase = squares[0][column];
const negativeCase = squares[0][0];
const positiveCase = squares[0][squares.length - 1];
if (horizontalCase !== null) {
for (let row = 0; row < squares.length; row++) {
if (horizontalCase !== squares[column][row]) {
break;
} else {
if (row === squares.length - 1) {
return true;
}
}
}
}
if (verticalCase !== null) {
for (let row = 0; row < squares.length; row++) {
if (verticalCase !== squares[row][column]) {
break;
} else {
if (row === squares.length - 1) {
return true;
}
}
}
}
if (negativeCase !== null) {
for (let row = 0; row < squares.length; row++) {
if (negativeCase !== squares[row][row]) {
break;
} else {
if (row === squares.length - 1) {
return true;
}
}
}
}
if (positiveCase !== null) {
for (let row = 0; row < squares.length; row++) {
if (positiveCase !== squares[row][squares.length - 1 - row]) {
break;
} else {
if (row === squares.length - 1) {
return true;
}
}
}
}
}
return false;
</code></pre>
<p>The function above actually works, it's just real wet. Any help in drying it up would be lovely.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T04:39:36.387",
"Id": "469229",
"Score": "0",
"body": "Welcome to CodeReview@SE. Site standard is to title questions for what the code is to accomplish, not your issues with it. Repeating the language tag in the title is frowned upon."
}
] | [
{
"body": "<p>I think the nicest thing to do is to split your task into three bits, essentially you want to see if a row, column or diagonal has all the entries the same.</p>\n\n<p>A row, column or diagonal can all be thought of just as a (1D) array.</p>\n\n<p>In fact, these things are all the 'lines' (pictorially) that you can find in a 2D array (which span the whole array).</p>\n\n<p>Now given a 2D array A, there's several ways to define a line, for instance the line which corresponds to the second row we can say is the pairs <code>(i, j)</code> such that <code>i === 1</code> (and j can be anything). Similarly the left diagonal is the pairs <code>(i, j)</code> such that <code>i === j</code>.</p>\n\n<p>Ok so I want to think of a line as a function, for instance I will think of the second row as the function</p>\n\n<p><code>(i, j) => i === 1</code></p>\n\n<p>OK, now given a line (which we represent as a function), I want to extract the elements of A which lie on that line, so I should traverse A, and for each element (i, j) I check if that element is in my line (i.e. if my function returns true for it) and if so include it in my result.</p>\n\n<p>How to do this? Well I /want/ to be able to loop through a 2D array gracefully, sadly we can't do that in JS, so I'll just look at each row in turn, determine which elements of that row are in my line and keep them, something like.</p>\n\n<pre><code>function getSectionOf2DArray(arr, lineFunc) {\n return arr.map((row, i) => row.filter((_, j) => lineFunc(i, j)));\n}\n</code></pre>\n\n<p>So now I have a 2D array still, the element at position i of the array is an array consisting of the things in row i which are in my line. If I flatten it I'll have the array of things in my line. I'm not sure if you're using node or are in the browser, so I'll write a flatten to be safe.</p>\n\n<pre><code>function getSectionOf2DArray(arr, sectionFunc) {\n return Array.prototype.concat.apply(\n [],\n arr.map((row, i) => row.filter((_, j) => sectionFunc(i, j)))\n );\n}\n</code></pre>\n\n<p>Nearly there now, let me define the lines of a 2D array.</p>\n\n<p>First the rows, well given a 2D array A, these are just the things <code>(i, j) => i === k</code> for k up to the length of the array.</p>\n\n<pre><code>const rowLines = array =>\n Array(array.length)\n .fill(0)\n .map((_, k) => (i, j) => i === k);\n</code></pre>\n\n<p>Now the columns, similar story just with a slight reversal, now it's <code>(i, j) => j === k</code></p>\n\n<pre><code>const colLines = array =>\n Array(array.length)\n .fill(0)\n .map((_, k) => (i, j) => j === k);\n</code></pre>\n\n<p>Finally the diagonals, the left diagonal (i.e. starting in the top left) is <code>(i, j) => i === j</code>, while the right diagonal is <code>(i, j) => i + j === A.length - 1</code></p>\n\n<pre><code>const leftDiag = array => (i, j) => i === j;\nconst rightDiag = array => (i, j) => i + j === array.length - 1;\n</code></pre>\n\n<p>(I have made leftDiag continue to be a function defined in terms of array just for consistency, it will make our life nicer later).</p>\n\n<p>Great, so now if we do</p>\n\n<pre><code>const ourLines = array =>\n rowLines(array)\n .concat(colLines(array))\n .concat(leftDiag(array))\n .concat(rightDiag(array));\n</code></pre>\n\n<p>Then ourLines is a function which takes an array and returns an array of lines (aka functions).</p>\n\n<p>Now we just need to define a function which says whether an 'evaluated' (as in I have the actual elements rather than the function) line corresponds to a win, this is easy, it's just if all the elements are the same and not equal to undefined. If all the elements are the same then when we turn the array into a set it will have just one element</p>\n\n<pre><code>const win = evalLine => new Set(evalLine).size === 1 && evalLine [0] !== undefined;\n</code></pre>\n\n<p>OK, now we should just go through our lines, get the actual array of elements in A they correspond to, and check if any is a win.</p>\n\n<pre><code>const winResults = array =>\n ourLines(array).map(line => win(getSectionOf2DArray(array, line)));\n\nconst isThereAWin = array => winResults(array).includes(true);\n</code></pre>\n\n<p>In summary, </p>\n\n<pre><code>const winChecker = squares => {\n const getSectionOf2DArray = (arr, sectionFunc) =>\n Array.prototype.concat.apply(\n [],\n arr.map((row, i) => row.filter((_, j) => sectionFunc(i, j)))\n );\n\n const rowLines = array => Array(array.length).fill(0).map((_, k) => (i, j) => i === k);\n\n const colLines = array => Array(array.length).fill(0).map((_, k) => (i, j) => j === k);\n\n const leftDiag = array => (i, j) => i === j;\n const rightDiag = array => (i, j) => i + j === array.length - 1;\n\n const ourLines = array =>\n rowLines(array)\n .concat(colLines(array))\n .concat(leftDiag(array))\n .concat(rightDiag(array));\n\n const win = evalLine => new Set(evalLine).size === 1 && evalLine[0] !== undefined;\n\n const winResults = array => ourLines(array).map(line => win(getSectionOf2DArray(array, line)));\n\n const isThereAWin = array => winResults(array).includes(true);\n\n return isThereAWin(squares);\n};\n</code></pre>\n\n<p>I hope you agree this pattern is nice. There are ways to write more concise things for your specific use case but this is simple and extendable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T02:40:45.910",
"Id": "239216",
"ParentId": "239211",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-20T23:37:44.633",
"Id": "239211",
"Score": "1",
"Tags": [
"javascript",
"array",
"tic-tac-toe"
],
"Title": "JavaScript Tic Tac Toe Win Checker is Wet"
} | 239211 |
<p>If I have a list that contains <code>True</code> and <code>False</code> values, how can I find the start and stop indices of where there are blocks of <code>True</code> values?</p>
<p><code>x = [True, False, False, True, True, True, False, True, False, False, False, True, True, False, True]</code></p>
<p>The output that I am looking for is:</p>
<pre><code>[[0, 0],
[3, 5],
[7, 7],
[11, 12],
[14, 14]
]
</code></pre>
<p>Here, the value in the first column is the start index and the value in the second column is the stop index.</p>
<p>One solution that I have is:</p>
<pre><code>start = []
stop = []
if y[0]:
start.append(0)
for i in range(len(y)):
if y[i] and not y[i-1]:
start.append(i)
if i > 0 and (not y[i] and y[i-1]):
stop.append(i-1)
if y[len(y)-1]:
stop.append(len(y)-1)
print(list(map(list, zip(start, stop))))
</code></pre>
| [] | [
{
"body": "<h1>Enumerate</h1>\n\n<p><code>for i in range(len(y)):</code> is an antipattern. If you want indices (<code>i</code>) and the values at those indices (<code>y[i]</code>) the Pythonic way is using <code>enumerate</code>:</p>\n\n<pre><code>for i, yi in enumerate(y):\n</code></pre>\n\n<h1>Start indices</h1>\n\n<p>Let's take a moment and split this task into two parts: the start indices and the stop indices. First, the start indices:</p>\n\n<pre><code>start = []\nif y[0]:\n start.append(0)\nfor i in range(len(y)):\n if y[i] and not y[i-1]:\n start.append(i)\n</code></pre>\n\n<p>That almost looks like it could be replaced by list comprehension ...</p>\n\n<pre><code>start = [i for i, yi in enumerate(y) if yi and not y[i-1]]\n</code></pre>\n\n<p>... except for that <code>y[i-1]</code> part, which may wrap around and grab a value from the end of the array. What you really want to do is <code>zip</code> the <code>y[i]</code> and <code>y[i-1]</code> sequences together. We just need to start the <code>y[i-1]</code> sequence off with a leading <code>False</code> value:</p>\n\n<pre><code>start = [i for i, (y1, y2) in enumerate(zip([False] + y[:-1], y)) if y2 > y1]\n</code></pre>\n\n<h1>Stop indices</h1>\n\n<p>The stop indices are similar, zipping <code>y[i]</code> with <code>y[i+1]</code> with a trailing <code>False</code>:</p>\n\n<pre><code>stop = [i for i, (y1, y2) in enumerate(zip(y, y[1:] + [False])) if y2 < y1]\n</code></pre>\n\n<h1>Groupby</h1>\n\n<p>And now for something completely different.</p>\n\n<p><code>itertools.groupby()</code> takes sequential items with matching keys, groups them together, and emits them together with their key. We just need the <code>True</code> and <code>False</code> values to be the key, and attach the index numbers to the <code>True</code>/<code>False</code> values.</p>\n\n<pre><code>>>> [list(group) for key, group in groupby(enumerate(x), key=lambda ix: ix[1])]\n[[(0, True)],\n [(1, False), (2, False)],\n [(3, True), (4, True), (5, True)],\n [(6, False)],\n [(7, True)],\n [(8, False), (9, False), (10, False)],\n [(11, True), (12, True)],\n [(13, False)],\n [(14, True)]]\n</code></pre>\n\n<p>(output reformatted to show one inner list per line, for clarity)</p>\n\n<p>But we only want the groups where the <code>key</code> is <code>True</code>:</p>\n\n<pre><code>>>> [list(group)\n... for key, group in groupby(enumerate(x), key=lambda ix: ix[1])\n... if key]\n[[(0, True)],\n [(3, True), (4, True), (5, True)],\n [(7, True)],\n [(11, True), (12, True)],\n [(14, True)]]\n</code></pre>\n\n<p>For each group, we want the first and the last items in the group:</p>\n\n<pre><code>>>> [[group[0], group[-1]]\n... for group in (list(group)\n... for key, group in groupby(enumerate(x),\n... key=lambda ix: ix[1])\n... if key)]\n[[(0, True), (0, True)],\n [(3, True), (5, True)],\n [(7, True), (7, True)],\n [(11, True), (12, True)],\n [(14, True), (14, True)]]\n</code></pre>\n\n<p>Actually, we only want the indices stored in those items:</p>\n\n<pre><code>start_stop = [[group[0][0], group[-1][0]]\n for group in (list(group)\n for key, group in groupby(enumerate(x),\n key=lambda ix: ix[1])\n if key)]\n</code></pre>\n\n<p>Which gives:</p>\n\n<pre><code>>>> start_stop\n[[0, 0], [3, 5], [7, 7], [11, 12], [14, 14]]\n</code></pre>\n\n<hr>\n\n<p>In the comments, <a href=\"https://codereview.stackexchange.com/users/98493/graipher\">Graipher</a> suggests:</p>\n\n<blockquote>\n <p>Personally, I would make getting the groups a generator expression assigned to a variable and then iterator over that in a list comprehension ... </p>\n</blockquote>\n\n<pre><code>from itertools import groupby\nfrom operator import itemgetter\n\ngroups = (list(group) for key, group in groupby(enumerate(x), key=itemgetter(1))\n if key)\nstart_stop = [[group[0][0], group[-1][0]] for group in groups]\n</code></pre>\n\n<blockquote>\n <p>... using <code>operator.itemgetter</code> (instead of the <code>lambda ix: ix[1]</code>) for some more readability.</p>\n</blockquote>\n\n<hr>\n\n<p>In the comments, <a href=\"https://codereview.stackexchange.com/users/98633/roottwo\">RootTwo</a> suggests:</p>\n\n<blockquote>\n <p>This could be simplified by grouping the indices directly instead of using <code>enumerate</code>:</p>\n</blockquote>\n\n<pre><code>[(group[0], group[-1]) for group in (\n list(group) for key, group in groupby(range(len(x)), key=x.__getitem__) if key)]\n</code></pre>\n\n<hr>\n\n<p>Timings, for a list of 15,000,000 entries (the original <code>x</code> list, replicated one million times):</p>\n\n<pre><code>Original: 7.3 seconds\nAJNeufeld: 6.4 seconds\nGraipher: 5.5 seconds\nRootTwo: 3.1 seconds\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T16:19:15.060",
"Id": "469266",
"Score": "1",
"body": "`itertools.groupby` is also what I would have recommended. Although the list comprehensions are really hard to grasp starting from the second to last. Personally, I would make getting the groups a generator expression assigned to a variable and then iterator over that in a list comprehension: `groups = (list(group) for key, group in groupby(enumerate(x), key=itemgetter(1)) if key); start_stop = [[group[0][0], group[-1][0]] for group in groups]`. And use `operator.itemgetter` for some more readability."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T16:35:34.740",
"Id": "469267",
"Score": "0",
"body": "@Graipher I did make the groups a generator expression in the last & second last. :-) I left it as list comprehension for the first two, so if the OP tried them out in a REPL or printed them, they'd see an actual result instead of seeing `<generator_expression(#14)>`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T16:36:34.467",
"Id": "469268",
"Score": "0",
"body": "I know, I would pull it out of the list comprehension and assign it to a variable, though. That nestedness took me a minute to read."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T21:47:25.473",
"Id": "469291",
"Score": "1",
"body": "This could be simplified by grouping the indices directly instead of using enumerate: `[(group[0], group[-1]) for group in (list(group) for key, group in groupby(range(len(x)), key=x.__getitem__) if key)`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T03:27:24.190",
"Id": "239218",
"ParentId": "239213",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "239218",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T00:48:55.553",
"Id": "239213",
"Score": "6",
"Tags": [
"python"
],
"Title": "Find Start/Stop Indices Where Array Is True"
} | 239213 |
<p>I recently wrote the following code:</p>
<pre><code>def freq_progress
user_flashcards = input_flashcards.includes(:term)
terms_unicos = user_flashcards.map(&:term).compact.uniq
freq_1, freq_2, freq_3, freq_4, freq_5 = 0, 0, 0, 0, 0
terms_unicos.each do |term|
case term.ranking
when nil
next
when 1..100
freq_1 += 1
when 101..300
freq_2 += 1
when 301..1000
freq_3 += 1
when 1001..2000
freq_4 += 1
when 2001..5000
freq_5 += 1
else
next
end
end
{
f1: freq_1,
f2: freq_2,
f3: freq_3,
f4: freq_4,
f5: freq_5
}
end
</code></pre>
<p>In the code review, our technical manager told me that parallel assignment is considered bad practice.</p>
<p>In the Ruby style guide, it says:</p>
<blockquote>
<p>Avoid the use of parallel assignment for defining variables. Parallel assignment is allowed when it is the return of a method call, used with the splat operator, or when used to swap variable assignment. Parallel assignment is less readable than separate assignment.</p>
</blockquote>
<p>However, I figure that this would apply mostly to situations where each variable is set to a different value, and that my particular use case (setting all values to 0, the same "boring" value) would potentially be an exception to the readability rule.</p>
<p>In other words, it seems that this would emphasize the "equal" nature of the 5 variables.</p>
<p>This may be a matter of opinion, but since the Ruby style guide recommends against it, I’d love to hear what Rubyists more experienced than I have to say about this.</p>
<p>As well as any opportunities for refactoring!</p>
<p>Thanks, Michael</p>
<p>p.s. this question was originally posted on StackOverflow, but I was told to close the question and move it to Code Review.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T04:28:42.090",
"Id": "469228",
"Score": "0",
"body": "(One of not too many cases where such a \"migration\" suggestion seems helpful: Questions bound to get opinions are explicitly deprecated on SO and on-topic at CR.)"
}
] | [
{
"body": "<p>Yes, it is generally considered a bad practice because it is considered confusing. Though as you point out it is fairly unlikely to confuse because everything is being set to zeros and the alternative is five lines of repeated code.</p>\n\n<p>However I find myself asking why you don't use an array. i.e.</p>\n\n<p><code>freqs = [0, 0, 0, 0, 0]</code>\nor\n<code>freqs = Array.new(5, 0)</code></p>\n\n<p>or else just define define the final hash:</p>\n\n<pre><code>def freq_progress\n user_flashcards = input_flashcards.includes(:term)\n terms_unicos = user_flashcards.map(&:term).compact.uniq\n\n result = { f1: 0, f2: 0, f3: 0, f4: 0, f5: 0}\n terms_unicos.each do |term|\n case term.ranking\n when 1..100\n result[:f1] += 1\n when 101..300\n result[:f2]+= 1\n when 301..1000\n result[:f3] += 1\n when 1001..2000\n result[:f4] += 1\n when 2001..5000\n result[:f5] += 1\n end\n end\n\n result\n end\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T20:07:44.097",
"Id": "469279",
"Score": "0",
"body": "Good point on the hash. On the normal SO, somebody commented about the array solution as well. How would this be returned to the frontend? Simply as a 5-positioned array?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T00:02:31.670",
"Id": "469506",
"Score": "0",
"body": "Understood - the hash is \"required\" just because that's how the React client receives it in json. Otherwise, an array would be great. Thanks again."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T20:03:38.027",
"Id": "239246",
"ParentId": "239215",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "239246",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T01:25:22.210",
"Id": "239215",
"Score": "1",
"Tags": [
"ruby"
],
"Title": "Ruby parallel assignment"
} | 239215 |
<p>I (a junior back-end Java dev) decided I wanted to learn some front-end development skills; in particular, I wanted experience with React and websockets. I decided to write an app that would allow for remote play of a 9X9 variant of tic tac toe one of my college friends made up. The rules are:</p>
<ol>
<li>The board is divided into 9 smaller games of tic tac toe, arranged in a tic tac toe grid.</li>
<li>Winning 3 boards in a row on the larger grid wins you the game.</li>
<li>Wherever you play in a smaller grid determines where your opponent must play in the larger grid; i.e. if I play in the bottom right corner of any smaller grid, then my opponent is limited to the bottom right corner of the larger grid on their next turn. I'll post screenshots to clarify.<a href="https://i.stack.imgur.com/D4ug8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/D4ug8.png" alt="X has played in the bottom-right of their sub-square, so O is limited to the bottom right of the larger square"></a></li>
<li>If the square on the larger grid you would be forced to play in is full, then you can play in any of the larger grid squares instead. </li>
</ol>
<p>I decided on socket.io to handle websockets for me, and picked flask_socketio to handle things in python. With that done, I wrote a react app to display the game and a python server to handle the logic. Then I added chat capability, just for fun. </p>
<p>Here's the react code. </p>
<pre><code>import SuperBoard from './superboard.js'
import openSocket from 'socket.io-client'
import SocketContext from './socket-context'
import ChatBox from './chatbox.js'
const port = '1337';
//For remote games, change this to the ip of the host machine
const ip = '0.0.0.0';
const socket = openSocket('http://' + ip + ':' + port);
class Game extends React.Component {
constructor(props) {
super(props)
this.state = {
boards: initBoards(),
wonBoards: Array(9).fill(''),
lastPlayed: -1,
yourTurn: false,
status: 'Waiting for another player...',
}
socket.on('boards', boards => {
this.setState({boards: boards})
});
socket.on('wonboards', wonBoards => {
this.setState({wonBoards: wonBoards})
});
socket.on('lastPlayed', lastPlayed => {
this.setState({lastPlayed: lastPlayed})
});
socket.on('x_or_o', x_or_o => {
this.setState({x_or_o: x_or_o})
});
socket.on('turn', player => {
if (player === this.state.x_or_o) {
this.setState({status: "You're up.", yourTurn: true})
} else {
this.setState({status: player + ' is thinking.', yourTurn: false})
}
});
socket.on('victory', player => {
if (player === this.state.color) {
this.setState({status: 'You win!', yourTurn: false})
} else {
this.setState({status: 'You lose!', yourTurn: false})
}
});
}
handleClick(i,j) {
console.log("Sending click: " + i + " " + j);
socket.emit('click', {i:i, j:j});
}
render() {
const boards = this.state.boards;
const wonBoards = this.state.wonBoards;
const lastPlayed = this.state.lastPlayed;
const status = this.state.status;
const username = this.state.x_or_o;
return (
<div className="game">
<div className="game-board">
<SuperBoard
boards={boards}
onClick={(i,j) => this.handleClick(i,j)}
wonBoards={wonBoards}
lastPlayed={lastPlayed}
/>
</div>
<div className="game-info">
<div className="status">{status}</div>
<div>
<SocketContext.Provider value={socket}>
<ChatBox username={username}/>
</SocketContext.Provider>
</div>
</div>
</div>
);
}
}
function initBoards() {
var boards = new Array(9);
for(var i = 0; i < boards.length ;i++){
boards[i] = new Array(9);
boards[i].fill('');
}
return boards;
}
export default Game
</code></pre>
<p>Some specific notes:</p>
<ol>
<li>I've never written react or socket.io code before. If you see anything that violates the best practices of either framework, let me know. </li>
<li>I'm also looking for any security holes something like this could leave open. I'd like to try deploying this on an AWS EC2 server eventually, and I'd rather not have any script kiddies messing with my account. </li>
<li><p>I won't include the message code because </p>
<ol>
<li>it's partially taken from <a href="https://github.com/WigoHunter/react-chatapp" rel="nofollow noreferrer">another</a> developer who seems to have pretty solid react skills and </li>
<li>I don't consider it particularly interesting. If you want to look at it, it's in the github repo under message.js and Chatbox.js. </li>
</ol></li>
<li>I'm aware of some minor bugs in the code (like the chat has a bug that causes it to only render on the left side, when your messages should render on the right) but let me know if you find any others. (It's not production-ready code without a few minor bugs, right?)</li>
</ol>
<p>Here's the python code:</p>
<pre><code>from flask_socketio import SocketIO, emit
from flask_cors import CORS
app = Flask(__name__)
#change this in prod
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, cors_allowed_origins="*")
CORS(app)
boards = [['' for i in range(9)] for i in range(9)]
wonBoards = ['' for i in range(9)]
lastPlayed = -1
players = {'X': None, 'O': None}
turn = 'X'
def reset():
boards = [['' for i in range(9)] for i in range(9)]
players = {'X': None, 'O': None}
turn = 'X'
@socketio.on('connect')
def connect():
print("Someone connected to websocket!")
if (players['X'] == None):
print("It was player X!")
players['X'] = request.sid
socketio.emit('x_or_o', 'X', room=players['X'])
socketio.emit('message', {"username":"System", "content":"You're playing as X"}, room=players['X'])
elif (players['O'] == None) :
print("It was player O!")
players['O'] = request.sid
socketio.emit('x_or_o', 'O', room=players['O'])
socketio.emit('message', {"username":"System", "content":"You're playing as O"}, room=players['O'])
socketio.emit('turn', 'X')
@socketio.on('disconnect')
def disconnect():
print("Player disconnected!")
if (players['X'] == request.sid):
players['X'] = None
print("It was x!")
elif (players['O'] == request.sid):
players['O'] = None
print('It was o!')
@socketio.on('post_submit')
def message(object):
[username, content] = object.values()
socketio.emit('message',{"username":username, "content":content})
@socketio.on('click')
def click(object):
[i,j] = object.values()
if (players[turn] != request.sid):
print("Wrong player clicked!")
return
if players['X'] == None or players['O'] == None:
print("Not enough players connected!")
return
#check if space is empty, the correct board is selected, the selected board is not won and the game is not over
rightBoard = (i != lastPlayed and lastPlayed != -1)
if (boards[i][j] != '' or rightBoard or wonBoards[i] or boardWin(wonBoards)):
return
#set the space to X or O
boards[i][j] = turn
#check if the board is won
updateWonBoards(i)
#check if the next board to play on is won
updateLastPlayed(j)
socketio.emit('boards', boards)
socketio.emit('wonboards', wonBoards)
socketio.emit('lastPlayed', lastPlayed)
if (boardWin(wonBoards) != ""):
socketio.emit('victory',boardWin(wonBoards))
reset()
#Toggle the player
togglePlayer()
socketio.emit('turn', turn)
def togglePlayer():
global turn
turn = 'O' if turn == 'X' else 'X'
def updateWonBoards(i):
global wonBoards
global boards
wonBoards[i] = boardWin(boards[i])
def updateLastPlayed(j):
global lastPlayed
global wonBoards
lastPlayed = -1 if wonBoards[j] != '' else j
def boardWin(board):
lines = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
]
for i in range(0, len(lines)):
[a, b, c] = lines[i]
if (board[a] != '' and board[a] == board[b] and board[a] == board[c]):
return board[a]
#"~" is used to indicate a draw
if "" in board:
return ""
else:
return "~"
if __name__ == '__main__':
reset()
socketio.run(app, port=1337, debug=True, host='0.0.0.0')
</code></pre>
<p>Some more notes:</p>
<ol>
<li>Again, let me know if any glaring security holes exist in my code. </li>
<li>If flask_socketio isn't the best library for this, let me know.</li>
</ol>
<p><a href="https://github.com/NoahWhite1115/9tactoe-frontend" rel="nofollow noreferrer">Here's</a> the github link for everything. I'm really excited to get some feedback on this. Also, if you have any tips on how to improve this answer or my writing skills, I'd love to hear those as well.</p>
<p>To anyone who tried installing the front-end from github before this post: I forgot to push up the package.json, so it wouldn't install. Everything works now. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T05:53:55.273",
"Id": "469230",
"Score": "0",
"body": "To anyone who tried installing the front-end from github before this post: I forgot to push up the package.json, so it wouldn't install. Everything works now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T13:27:24.460",
"Id": "469249",
"Score": "0",
"body": "Welcome to Code Review! When adding additional information you should [edit] your question instead of adding a comment. I have added that information to your post. Learn more about comments including when to comment and when not to in [the Help Center page about Comments](https://codereview.stackexchange.com/help/privileges/comment)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T14:47:57.043",
"Id": "469254",
"Score": "1",
"body": "I would suggest thinking about what you would do if you were to nest this idea again, i.e. what if I wanted a 3 x 3 board of superboards, say these are megaboards, what if I wanted a 3 x 3 board of megaboards? If you do this you could remove some duplication."
}
] | [
{
"body": "<p>I'm not fantastic with Typescript; so let's take a look at your Python:</p>\n\n<h2>Credentials</h2>\n\n<pre><code>app.config['SECRET_KEY'] = 'secret!'\n</code></pre>\n\n<p>This shouldn't be baked into your code. It should be in a secure wallet of some kind. Resources on the internet abound about how to accomplish this, either in Python or at the operating system level.</p>\n\n<h2>Business logic vs. presentation</h2>\n\n<pre><code>boards = [['' for i in range(9)] for i in range(9)]\n</code></pre>\n\n<p>This is a classic example of conflating presentation (a string to be shown to the user) with business logic (is a cell filled in?)</p>\n\n<p>Consider using <code>Enum</code> instances, or maybe <code>Optional[bool]</code>.</p>\n\n<h2>Logging</h2>\n\n<p>Rather than</p>\n\n<pre><code>print(\"Someone connected to websocket!\")\n</code></pre>\n\n<p>use the actual <a href=\"https://docs.python.org/3.8/library/logging.html#module-email\" rel=\"nofollow noreferrer\">logging</a> facilities of Python. They don't need to have a complex configuration; using them will better-structure the output and allow for complex configurations in the future if you want.</p>\n\n<h2><code>None</code> comparison</h2>\n\n<pre><code>if (players['X'] == None):\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>if players['X'] is None:\n</code></pre>\n\n<p>also, parens are not necessary.</p>\n\n<h2>Unpacking</h2>\n\n<pre><code>[i,j] = object.values()\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>i, j = object.values()\n</code></pre>\n\n<p>That said: is <code>object</code> a <code>dict</code>? The order of values, after Python 2, is no longer non-deterministic, but (if I remember correctly) in insertion order. Generally it's a bad idea to rely on this order. You should rethink the way that these are stored and looked up. Can you rely on the key instead?</p>\n\n<h2>Globals</h2>\n\n<pre><code>\ndef togglePlayer():\n global turn\n turn = 'O' if turn == 'X' else 'X'\n\ndef updateWonBoards(i):\n global wonBoards\n global boards\n wonBoards[i] = boardWin(boards[i])\n\ndef updateLastPlayed(j):\n global lastPlayed\n global wonBoards\n lastPlayed = -1 if wonBoards[j] != '' else j\n</code></pre>\n\n<p>These globals should be in some kind of game state singleton class instead.</p>\n\n<h2>Mutability</h2>\n\n<pre><code> lines = [\n [0, 1, 2],\n [3, 4, 5],\n [6, 7, 8],\n [0, 3, 6],\n [1, 4, 7],\n [2, 5, 8],\n [0, 4, 8],\n [2, 4, 6]\n ]\n</code></pre>\n\n<p>This should be a tuple of tuples, not a list of lists.</p>\n\n<h2>Iteration</h2>\n\n<pre><code>for i in range(0, len(lines)):\n</code></pre>\n\n<p>should just be</p>\n\n<pre><code>for line in lines:\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T14:53:19.077",
"Id": "239232",
"ParentId": "239217",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "239232",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T02:47:28.653",
"Id": "239217",
"Score": "4",
"Tags": [
"python",
"react.js",
"jsx",
"flask",
"socket.io"
],
"Title": "9X9 Tic Tac Toe variant with frontend in react and backend in python flask_socketio"
} | 239217 |
<p>I've written the following function in C which shall take as input a character array (decayed to a char * of course), and mutate the string into a title-cased string in the form "this is a string" -> "This Is A String".</p>
<pre><code>void title_case(char str[])
{
assert(str);
size_t i;
str[0] = toupper((int) str[0]);
if(strlen(str) == 1) return;
for(i = 1; i < strlen(str); ++i)
{
str[i] = tolower((int)str[i]);
if(str[i -1] == ' ')
{
str[i] = toupper((int)str[i]);
}
}
return;
}
</code></pre>
<p>Please provide any feedback you see fit. Is there a more concise way to do this? Is array bracket notation the most clear way?</p>
<p>Driver:</p>
<pre><code>#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
void title_case(char str[]);
int main(void)
{
char sentence[] = "this is a SeNTeNce.";
title_case(sentence);
printf("%s\n", sentence);
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T22:19:07.643",
"Id": "469295",
"Score": "1",
"body": "What is the expected output for \"this.is.a.string\"?"
}
] | [
{
"body": "<ol>\n<li><p>In the context of function parameter passing, char* and char[] are equivalent (because char[] decays to char*).</p>\n\n<p>Anyway, I would rather use <code>title_case(char* s)</code> because it more clearly expresses the truth: what you really get within the function is a pointer to the first character of the array.</p></li>\n<li><p>Accepting char* as string parameter implicitly suggests that the passed string will be '\\0'-terminated. As you probably know, there are many known security issues with this.\nIf that's not the case, that means if you cannot guarantee the '\\0'-ending always, consider passing the string length also, for ex.: \n<code>title_case(char* s, size_t len)</code> </p></li>\n<li><p>The cast from char to int <code>(int)s[0]</code> should not be needed, because conversion from smaller to the bigger integral type is always done implicitly and should trigger no warning on any compiler I know.</p></li>\n</ol>\n\n<p>4.The strlen() in this loop <code>for(i = 1; i < strlen(str); ++i)</code> is called on every iteration, so the overall complexity will be quadratic. The common practice to avoid this is to store length into a variable and then use it, like:</p>\n\n<pre><code>size_t len = strlen(str);\nfor (i = 1; i < len; ++i) ...\n</code></pre>\n\n<ol start=\"5\">\n<li>The more concise way with linear complexity would be something like this</li>\n</ol>\n\n<p>></p>\n\n<pre><code>#include <stdio.h>\n#include <string.h>\n#include <ctype.h>\n\nvoid title_case(char *s)\n{\n if (s == NULL) return;\n\n for (char *p = s; *p != '\\0'; ++p)\n *p = (p == s || *(p-1) == ' ') ? toupper(*p) : tolower(*p);\n}\n\nint main()\n{\n char s[] = \"this is some title\";\n title_case(s);\n printf(\"%s\\n\", s);\n}\n</code></pre>\n\n<p>Note: In the boolean expression <code>p == s || *(p-1) == ' '</code> short-circuit evaluation capability of C/C++ is used: if p==s is true, then *(p-1) is not evaluated. Otherwise we would dereference invalid pointer -> which would lead to undefined behaviour.</p>\n\n<p><strong>Edited:</strong> Emphasize quadratic complexity issue, as proposed in comments by @sudo</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T10:37:49.047",
"Id": "469243",
"Score": "0",
"body": "Looks like you forgot, that OP's code also lowercased all the non-first letters of words"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T10:54:46.780",
"Id": "469244",
"Score": "0",
"body": "@Yuri, yes thanks. Have made an update."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T21:22:01.383",
"Id": "469289",
"Score": "0",
"body": "Note that OP's code calls strlen on each iteration which makes the complexity quadratic while the proposed version in this answer has linear complexity. (GCC optimizes the calls to strlen, Clang does not.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T06:02:38.230",
"Id": "469332",
"Score": "0",
"body": "@sudo: yeah, thanks. Updated."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T18:44:25.377",
"Id": "469425",
"Score": "1",
"body": "@chux: it's correct. updated. The emphasize was on more concise solution, not the most efficient. But good point anyway."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T09:20:49.000",
"Id": "239223",
"ParentId": "239219",
"Score": "2"
}
},
{
"body": "<p><strong>O(n*n)</strong></p>\n\n<p>With a changing <code>str</code> and <code>strlen(str)</code> in the <code>for(i = 1; i < strlen(str); ++i)</code> loop, code repeatedly calculates the string length. Once is enough.</p>\n\n<p>Even easier, test for the <em>null character</em>.</p>\n\n<p><strong><code>is...(int ch)</code> called with <code>char</code></strong></p>\n\n<p><code>is...(int)</code> and <code>to...er(int)</code> functions expect an <code>unsigned char</code> <em>value</em> or <code>EOF</code>. When called with a <code>char</code> less than zero (and not <code>EOF</code>), the result in undefined behavior. The C standard library here treats <code>char</code> as if it was <code>unsigned char</code>. Best to do like-wise.</p>\n\n<p>OP's <code>(int)</code> cast as in <code>toupper((int) str[0])</code> serves scant purpose.</p>\n\n<p><strong>Simplify start of word logic</strong></p>\n\n<p>Suggest using a flag that is set whenever the processed <code>char</code> was a white-space.</p>\n\n<p><strong>Array brackets?</strong></p>\n\n<p>This is a style issue. As such, best to follow your group's coding standard. The standard C library use the 2nd style.</p>\n\n<pre><code>void title_case(char str[])\n// or\nvoid title_case(char *str) // I find this more commmon\n</code></pre>\n\n<p><strong>Sample code</strong></p>\n\n<pre><code>#include <assert.h>\n#include <ctype.h>\n#include <stdbool.h>\n\nvoid title_case(char str[]) {\n assert(str);\n bool StartOfWord = true;\n while (*str) {\n if (StartOfWord) {\n *str = toupper((unsigned char) *str);\n } else {\n *str = tolower((unsigned char) *str);\n }\n StartOfWord = isspace((unsigned char) *str);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T14:37:26.640",
"Id": "239320",
"ParentId": "239219",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T06:41:32.607",
"Id": "239219",
"Score": "1",
"Tags": [
"c",
"strings"
],
"Title": "Title Case function in C"
} | 239219 |
<p>I am trying to write a sql storeprocedure that basically returns a derived value from an outcome of a function call. The derived field returns the difference in days and if the difference is less than 24 hours then returns hours. It is working as desired but just need to ensure if the approach is right.</p>
<p>Storeprocedure query</p>
<pre><code>SELECT ua.ID AS UserAgreementID
, A.ID AS AgreementID
, A.Code
, A.ComplianceCode
, A.Name
, A.Description
, A.Version
, ua.UserAgreementStateID
, uas.Name AS UserAgreementStateName
, ua.AcceptanceWindowExpiry
, declaration.GetDifferenceInDaysOrHours(ua.AcceptanceWindowExpiry) AS NoOfDays
, A.Data
, pa.ID AS AuthoredByID
, pa.FirstName + ' ' + pa.LastName AS AuthoredByName
, A.Authored
, ia.ID AS IssuedByID
, ia.FirstName + ' ' + pa.LastName AS IssuedByName
, A.Issued
FROM declaration.Agreement AS A
INNER JOIN declaration.UserAgreement AS ua
ON A.ID = ua.AgreementID
INNER JOIN declaration.UserAgreementState AS uas
ON ua.UserAgreementStateID = uas.ID
LEFT JOIN common.Person AS pa
ON A.AuthoredBy = pa.ID
LEFT JOIN common.Person AS ia
ON A.IssuedBy = ia.ID
WHERE ua.UserID = 607
AND uas.Code IN ('ISS', 'DEF') -- Issued, Deferred
AND A.Draft = CONVERT(BIT, 0) -- Not a draft.
AND A.Deleted = CONVERT(BIT, 0) -- Not deleted.
AND ISNULL(A.Issued, '9999-12-31') <= GETUTCDATE() -- Issued date less than equal to today's date (Issued date).
AND ISNULL(A.Expires, '9999-12-31') > GETUTCDATE()
</code></pre>
<p>I am not sure if writing a function and calling it within the storeprocedure has any implications and is the right way to do it. The results that I am getting are correct though. Could somebody throw some light.</p>
<pre><code>CREATE FUNCTION declaration.GetDifferenceInDaysOrHours(@AcceptanceWindowExpiry datetime)
RETURNS int
AS
BEGIN
DECLARE @timeDifferenceInDays INT;
DECLARE @timeDifferenceInHours INT;
DECLARE @timeDifference INT;
SELECT @timeDifferenceInDays = DATEDIFF(d, GETUTCDATE(), @AcceptanceWindowExpiry)
IF @timeDifferenceInDays > 1
BEGIN
SELECT @timeDifference = @timeDifferenceInDays
END
ELSE
BEGIN
SELECT @timeDifferenceInHours = DATEDIFF(HOUR, GETUTCDATE(), @AcceptanceWindowExpiry)
IF @timeDifferenceInHours >= 0 AND @timeDifferenceInHours <= 24
BEGIN
SELECT @timeDifference = @timeDifferenceInHours
END
ELSE
BEGIN
SELECT @timeDifference = -1
END
END
RETURN @timeDifference;
END;
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T23:10:19.910",
"Id": "469304",
"Score": "0",
"body": "This statement `How do I call this function from within the query.` makes the question off-topic since the code isn't working."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T08:01:19.430",
"Id": "469334",
"Score": "0",
"body": "I have re framed the question. Update the post. Just to let you code is working. I am looking at the approach ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T11:24:30.050",
"Id": "469343",
"Score": "1",
"body": "I'm not reviewing the code, but there is nothing wrong with calling a function from a stored procedure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T09:09:23.540",
"Id": "469465",
"Score": "0",
"body": "Stored procedures are usually the preferred way of doing things."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T09:09:53.183",
"Id": "469466",
"Score": "0",
"body": "Is there anything that makes you doubt about the approach?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T10:04:12.120",
"Id": "469467",
"Score": "0",
"body": "I just wanted an expert opinion . Thats it"
}
] | [
{
"body": "<p>Calling a function from a stored procedure is absolutely fine.</p>\n\n<p>As far as the code goes, you could reduce the number of statements.</p>\n\n<p>e.g. instead of</p>\n\n<pre><code> IF @timeDifferenceInHours >= 0 AND @timeDifferenceInHours <= 24\n BEGIN \n SELECT @timeDifference = @timeDifferenceInHours\n END\n ELSE\n BEGIN\n SELECT @timeDifference = -1\n END\n</code></pre>\n\n<p>I would suggest</p>\n\n<pre><code> select @timedifference = \n case when @timeDifferenceInHours >= 0 AND @timeDifferenceInHours <= 24\n then @timeDifferenceInHours\n else -1 \n end\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-02T20:44:31.727",
"Id": "239827",
"ParentId": "239224",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T09:20:51.060",
"Id": "239224",
"Score": "1",
"Tags": [
"sql",
"sql-server"
],
"Title": "Calling a function within stored procedure to derive a value"
} | 239224 |
<p>I want to remove the mail contact from all Groups in the "Member Of" tab. I am able to remove all MemberOf for mail contact. How can I improve the speed of the script?</p>
<pre><code>Get-MailContact <name> | ForEach-Object { Get-ADObject $_.distinguishedname -Properties memberof } | Remove-ADPrincipalGroupMembership -Identity $_ -MemberOf $_.memberof
</code></pre>
| [] | [
{
"body": "<p>This seems pretty optimal to me given how simple it is, only a question, why the <code>foreach</code>? Do you expect <code>Get-MailContact</code> to return multiple contacts ?</p>\n<p>I don't have an AD I can test it against, but I'd be curious to know if "reversing" the operation by removing the member from the groups instead of removing the membership from the user could make it faster:</p>\n<pre><code>$ADContact = Get-MailContact <name> | Get-ADObject -Properties memberof \n# Loop through all the groups and remove the user from them.\nforeach ($group in $ADContact.MemberOf) {Remove-ADGroupMember -Identity $group -Member $ADContact}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-22T16:26:14.047",
"Id": "244335",
"ParentId": "239225",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T09:39:56.043",
"Id": "239225",
"Score": "2",
"Tags": [
"powershell"
],
"Title": "Removing contact from all mail groups"
} | 239225 |
<p>I am trying to solve ProjectEuler.net problem #50, Consecutive Prime Sum. Here is the problem:</p>
<blockquote>
<p>The prime 41, can be written as the sum of six consecutive primes:</p>
<pre><code>41 = 2 + 3 + 5 + 7 + 11 + 13
</code></pre>
<p>This is the longest sum of consecutive primes that adds to a prime below one-hundred.</p>
<p>The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.</p>
<p>Which prime, below one-million, can be written as the sum of the most consecutive primes?</p>
</blockquote>
<p>I have written some code which solve the problem just fine when the limit is 10, 100, 1000 or 10000 but when the limit is 1000000 as the problem requires, the program takes too much time to finish running!!</p>
<p>What can be done to my code to make the program faster?</p>
<pre><code>package com.company;
import java.util.ArrayList;
class ConsecutivePrimeSum {
public static int limit=1000000;
int lengthOfTheLongest =0;
int sumOfTheLongest =0;
void solution(){
ArrayList<Integer> arrayOfPrimes=generatePrimes();
scanSequences(arrayOfPrimes);
System.out.println("The longest sum is "+ sumOfTheLongest +" and contains "+lengthOfTheLongest+" terms");
}
private ArrayList<Integer> generatePrimes(){
ArrayList<Integer> arrayOfPrimes=new ArrayList<Integer>();
for(int i=limit;i>=2;i--){
if(isPrime(i)){
arrayOfPrimes.add(i);
}
}
return arrayOfPrimes;
}
/**
* @param s
* this scans ArrayList s, to get sequence of prime numbers and calculate
* their sum and corresponding length
* then assign the longest length to the variable lengthOfTheLongest, and its sum to variable sumOfTheLongest
*/
private void scanSequences(ArrayList<Integer> s){
ArrayList<Integer> cumulativeSums=generateCumulativeSums(s);
for(int start=1;start<=s.size();start++){
for (int end=s.size()-1;end>=start;end--){
if(!isPrime(sumFromTo(cumulativeSums,start,end))) continue;
if(sumFromTo(cumulativeSums,start,end)>limit) break;
if ((end-start+1)> lengthOfTheLongest){
sumOfTheLongest =sumFromTo(cumulativeSums,start,end);
lengthOfTheLongest =(end-start+1);
}
}
}
}
/**
* @param s
* @return arraylist of cumulative sums of the elements in s
*/
private ArrayList<Integer> generateCumulativeSums(ArrayList<Integer> s){
int sum=0;
ArrayList<Integer> cumulativeSums=new ArrayList<Integer>();
for (int i=0;i<s.size();i++){
cumulativeSums.add(sum=sum+s.get(i));
}
return cumulativeSums;
}
/**
* @param a is an ArrayList whose elements are to be summed
* @param start is the index of where summing should start
* @param end is the index of where summing should end
* @return the obtained sum
*/
private int sumFromTo( ArrayList<Integer> a,int start, int end){
int sum;
sum=a.get(end)-a.get(start-1);
return sum;
}
private static boolean isPrime(int number){
boolean isPrime=false;
int divider=2;
int count=0;
while(divider<=number){
if(number%divider==0)
count=count+1;
divider=divider+1;
}
if(count==1)
isPrime=true;
return isPrime;
}
}
class Test{
public static void main(String [] args){
ConsecutivePrimeSum consecutivePrimeSum=new ConsecutivePrimeSum();
consecutivePrimeSum.solution();
}
}
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T14:18:24.710",
"Id": "469251",
"Score": "0",
"body": "Hello, this question is off-topic, since the code is not working as intended; I suggest that you read the [What topics can I ask about here?](https://codereview.stackexchange.com/help/on-topic) `Code Review aims to help improve working code. If you are trying to figure out why your program crashes or produces a wrong result, ask on Stack Overflow instead. Code Review is also not the place to ask for implementing new features.`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T22:02:13.173",
"Id": "469293",
"Score": "2",
"body": "@Doi9t Improving performance questions are on topic here. The code apparently works as intended for smaller limits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T00:22:54.800",
"Id": "469315",
"Score": "0",
"body": "What are your ideas for a better *algorithm*?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T01:27:38.573",
"Id": "469322",
"Score": "1",
"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) for examples, and revise the title accordingly."
}
] | [
{
"body": "<ul>\n<li><p>Generation of prime numbers is suboptimal. Use a <a href=\"https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"noreferrer\">sieve of Erathosthenes</a>.</p></li>\n<li><p><code>isPrime</code> is highly suboptimal. You already generated an array of all necessary primes, so just binary search it.</p></li>\n<li><p>Breaking the loop in</p>\n\n<pre><code> if(sumFromTo(cumulativeSums,start,end)>limit)\n break;\n</code></pre>\n\n<p>looks like a bug. The intention is to loop by decreasing <code>end</code>, yet since the loop starts with the very long sequence, its sum is likely to exceed the limit right away. Shorter sequences with the same <code>start</code> are never tested.</p>\n\n<p>Consider finding the proper <code>end</code> as an upper limit of a <code>sumFromTo(cumulativeSums, start, end) <= limit</code> predicate (hint: another binary search).</p></li>\n<li><p>You are not interested in <em>all</em> sequences of the primes. Most of the primes execs <code>2</code> are odd. Notice that if the sequence has an even number of odd primes, its sum is even, that is not a prime. Once the correct <code>end</code> is established, you may safely decrease it by <code>2</code>.</p></li>\n<li><p>Style wise, give your operators some breathing space.</p>\n\n<pre><code> for (int end = s.size() - 1; end >= start; end--) {\n</code></pre>\n\n<p>is much more readable than</p>\n\n<pre><code> for (int end=s.size()-1;end>=start;end--){\n</code></pre></li>\n</ul>\n\n<p>PS: I am not aware of any math regarding sums of consecutive primes. It is very much possible that such math exists, and the goal of this problem is to discover it. That would be a true optimization.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T00:17:46.970",
"Id": "469313",
"Score": "1",
"body": "`That would be a true optimization`[Wouldn't](http://oeis.org/A216000) [it](http://oeis.org/A216001)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T02:03:16.057",
"Id": "469323",
"Score": "0",
"body": "@greybeard Perhaps, if only they'd spell some math."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T22:00:48.343",
"Id": "239249",
"ParentId": "239226",
"Score": "7"
}
},
{
"body": "<h1>Prime Generation</h1>\n\n<p>As mentioned by <a href=\"https://codereview.stackexchange.com/users/40480/vnp\">vnp</a>, use the <a href=\"https://en.wikipedia.org/wiki/Sieve_of_Eratosthenese\" rel=\"nofollow noreferrer\">Sieve of Eratosthenese</a>. In that implementation, use a <a href=\"https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/BitSet.html#%3Cinit%3E(int)\" rel=\"nofollow noreferrer\"><code>BitSet(1_000_000)</code></a> for efficient memory usage during your sieve; a sieve for primes up to one million will only take 125 KB of memory.</p>\n\n<p>Keep the sieve around after you've generated your prime numbers, because it makes a very efficient <span class=\"math-container\">\\$O(1)\\$</span> time complexity <code>isPrime(number)</code> checker:</p>\n\n<pre><code>bool isPrime(int number) {\n return sieve.get(number);\n}\n</code></pre>\n\n<h1>Prime Generation, Part 2</h1>\n\n<p>How many primes numbers are there (less than one million)? You don't know, so you've used an <code>ArrayList<Integer></code> to store them.</p>\n\n<p>But you could know. It will be <a href=\"https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/BitSet.html#cardinality()\" rel=\"nofollow noreferrer\"><code>sieve.cardinality()</code></a>. So instead of using a memory wasting, slow-to-access indirect container, you could use:</p>\n\n<pre><code>int[] arrayOfPrimes = new int[sieve.cardinality()];\n</code></pre>\n\n<p>which gives you a much smaller memory footprint, and faster access speeds.</p>\n\n<p>Ditto for your <code>cumulativeSums</code>. You could even make these a <code>long[]</code>, to avoid possible overflows, and still use less memory than <code>ArrayList<Integer></code> will!</p>\n\n<h1>Longest Sequence</h1>\n\n<p>What is the longest sequence of primes that sum to any value (prime or not) less that one million? This will be your absolute limit for the length of the sequence. Any sequence longer than this is pointless to check.</p>\n\n<p>The longest sequence that sums to a value less than one million will, of course, contain the smallest values. So, it will be:</p>\n\n<pre><code>2 + 3 + 5 + 7 + 11 + 13 + 17 + 19 + 23 + ... + prime[n-1]\n</code></pre>\n\n<p>So just start adding the prime numbers until it exceeds one million; that number of terms is the limit. Your search space is only sequences between 21 terms and this limit in length. And if you search backwards, you can stop when you find the first working value.</p>\n\n<h1>Even & Odd length sequences</h1>\n\n<p>The sum of an even number of odd numbers is even, so cannot be prime. The only way to make an odd number, using an even number of primes is if one of those primes is even (2), so the remaining primes compose an odd number of odd numbers.</p>\n\n<p>Ergo:</p>\n\n<ul>\n<li>Even length sequences must start at 2 (2 + 3, 2 + 3 + 5 + 7, ...)</li>\n<li>Odd length sequences must not start at 2.</li>\n</ul>\n\n<p>So an even length sequence check could be a quick check of <code>isPrime(cumulativeSum[n])</code>. No loop required.</p>\n\n<p>Odd length sequences still need to check <code>isPrime(cumulativeSum[i+n] - cumulativeSum[i])</code> for all <code>i</code>, (for differences less than one million, of course).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T04:34:05.420",
"Id": "239263",
"ParentId": "239226",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "239249",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T09:44:16.813",
"Id": "239226",
"Score": "0",
"Tags": [
"java",
"performance",
"programming-challenge"
],
"Title": "ProjectEuler.net problem #50, Consecutive Prime Sum"
} | 239226 |
<p>This is one of my first projects in C++, and I would call it a program for storing, displaying data and prognosing numbers.</p>
<p>I use following compiler: g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0</p>
<p>I will try to explain my code starting with the main method which is located at the bottom of the code. The main method in my program is like the main menu. You have four options when you start the program: Displaying data, inputting data, prognosing numbers and quit. The source code is at the bottom of this post.</p>
<h2>1. Displaying Data</h2>
<p>When you choose this option, your ouput is following (if the data file is not empty):</p>
<pre><code>Do you want to make a prognose (P), input new data (I), show current data (D) or quit (Q)?: d
___________________
|Day|Infected|Dead|
|1 |2 |0 |
|2 |2 |0 |
|3 |3 |0 |
|4 |3 |0 |
|5 |9 |0 |
|6 |14 |0 |
|7 |18 |0 |
|8 |21 |0 |
|9 |29 |0 |
|10 |41 |0 |
|11 |55 |0 |
|12 |79 |0 |
|13 |104 |0 |
|14 |131 |0 |
|15 |182 |0 |
|16 |246 |0 |
|17 |302 |1 |
|18 |504 |1 |
|19 |655 |1 |
|20 |860 |1 |
|21 |1016 |3 |
|22 |1332 |3 |
|23 |1646 |4 |
|24 |2053 |6 |
|25 |2388 |6 |
Do you want to make a prognose (P), input new data (I), show current data (D) or quit (Q)?:
</code></pre>
<p>When choosing this option, the function <code>displayData()</code> with the parameter <code>file_name</code> is called. The function has two parameters, but the second one, <code>prognose_days</code> is defaultly set to -1. This is because this function has two ways of executing. The first way is only displaying the current data (<code>prognose_days = -1</code>), and the second way is displaying the current data + prognosed numbers (<code>prognose_days = n</code>).</p>
<p>After setting some variables, the function first checks, if the data file contains data. Then it takes every line from the data file and splits it at the delimeter <code>:</code>. The splitting is done with the method <code>splitString()</code>. The splitted lines get saved in a vector called <code>vector_list</code>.</p>
<p>The next condition checks if only the current data should get displayed, or also prognosed numbers. When prognosed numbers also should get displayed, it adds those to the end of the <code>vector_list</code>.</p>
<p>The rest of the function is pretty complicated for others to read, I think. The point of the rest is to display the table with the data correctly and in a good looking way. Firstly the longest length of each column (day, infected, dead) gets stored into a variable with the function <code>getLongestLength()</code>. Then the table gets outputted with help of ternary operator, with the correct width etc.</p>
<h2>2. Inputting Data</h2>
<p>When you choose this option, your output is the following:</p>
<pre><code>Do you want to make a prognose (P), input new data (I), show current data (D) or quit (Q)?: i
Day 26: Enter new data or quit (Q): 2500:7
Day 27: Enter new data or quit (Q): q
Do you want to make a prognose (P), input new data (I), show current data (D) or quit (Q)?:
</code></pre>
<p>This option gets the numbers you type in (e.g 2500:7 -> 2500 infections and 7 deaths) and writes them with the help of the function <code>writeFile()</code> into the data file.</p>
<h2>3. Prognosing Numbers</h2>
<p>When you choose this option your output is the following:</p>
<pre><code>Do you want to make a prognose (P), input new data (I), show current data (D) or quit (Q)?: p
How many days to you want to prognose?: 3
______________________
|Day |Infected|Dead|
|1 |2 |0 |
|2 |2 |0 |
|3 |3 |0 |
|4 |3 |0 |
|5 |9 |0 |
|6 |14 |0 |
|7 |18 |0 |
|8 |21 |0 |
|9 |29 |0 |
|10 |41 |0 |
|11 |55 |0 |
|12 |79 |0 |
|13 |104 |0 |
|14 |131 |0 |
|15 |182 |0 |
|16 |246 |0 |
|17 |302 |1 |
|18 |504 |1 |
|19 |655 |1 |
|20 |860 |1 |
|21 |1016 |3 |
|22 |1332 |3 |
|23 |1646 |4 |
|24 |2053 |6 |
|25 |2388 |6 |
|26 |2500 |7 |
|27 (P)|3409 |9 |
|28 (P)|4649 |12 |
|29 (P)|6339 |16 |
Infections: 6339
Deaths: 16
Do you want to make a prognose (P), input new data (I), show current data (D) or quit (Q)?:
</code></pre>
<p>This option calculates a prognose, by calculating the average factor for the numbers. Ex.</p>
<pre><code>1 Infected
3 Infected (x3)
8 Infected (x2.66)
9 Infected (x1.125)
Average Factor: (3+2.66+1.125) / 3 = 2,26
Prognose for two days:
9*2,26 = 20,34
20,34*2,26 = 45,96
</code></pre>
<p>I know mathematically, this is not the best approach, but that is not important now.
The function does exactly what I calculated above and returns an array with the prognosed infections and deaths.</p>
<h2>4. Quit</h2>
<p>Quits the program.</p>
<p>My questions are:</p>
<ul>
<li>Does my code have any major flaws or no-gos in programming or programming in C++?</li>
<li>Should have I used pointers and/or addresses in my code?</li>
<li>How is the general style of my programming?</li>
<li>Did you notice anything else?</li>
</ul>
<h2>coronavirus.cpp</h2>
<pre><code>#include <stdio.h>
#include <math.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
// DECLARES METHODS
vector<string> splitString(string s, char delim);
// DEFAULTLY PROGNOSE DAYS IS -1 WHICH MEANS IT ONLY DISPLAYS CURRENT DATA AND NOT PROGNOSE DATA
void displayData(string file_name, int prognose_days = -1);
// PUBLIC VARIABLE FOR FILENAME
string file_name = "corona_numbers.dat";
// CALCULATES PROGNOSE WITH FILE AND PROGNOSE DAYS
vector<int> calculatePrognose(double days, string file_name) {
int zero_dead = 0, zero_infected = 0;
// DECLARES INPUT FILESTREAM TO READ FILE
ifstream file(file_name);
// DECLARS VECTOR WHICH CONTAINS VECTORS OF SPLITTED FILE-LINES
vector<vector<string>> vector_list;
string line;
// DECLARES VARIABLES
double avg_infected_factor, avg_dead_factor, last_infected_count, last_dead_count, infected = 0, dead = 0;
vector<int> empty_file = { -1, -1};
// CHECKS IF FILE EXISTS/IS EMPTY
if (file.peek() == ifstream::traits_type::eof()) {
cout << "\033[1;31m[ERROR]\033[0m File is empty. Please input data!" << endl;
return empty_file;
}
// GETS LINES OF FILE, SPLITS THEM AND PUTS THEM IN A VECTOR
while(getline(file, line)) {
vector<string> splitted_string = splitString(line, ':');
vector_list.push_back(splitted_string);
}
//TODO: CHANGE CALCULATION OF AVGFACTOR WITH SORTING OUT EXTREMES
// SETS FIRST NUMBER OF DATA TO LASTCOUNT
last_infected_count = stoi(vector_list[0][1]);
last_dead_count = stoi(vector_list[0][2]);
avg_dead_factor, avg_infected_factor = 0;
// SUMS AVEREAGES OF COUNTS
for(int i = 1; i < vector_list.size(); i++) {
// CHECK IF LAST NUMBER IS ZERO TO PREVENT A DIVISION THROUGH ZERO
if (last_dead_count != 0) {
avg_dead_factor += stoi(vector_list[i][2]) / last_dead_count;
last_dead_count = stoi(vector_list[i][2]);
} else {
// INCREMENT COUNTER FOR TIMES ZERO PEOPLE WERE DEAD
zero_dead++;
}
// CHECK IF LAST NUMBER IS ZERO TO PREVENT A DIVISION THROUGH ZERO
if (last_infected_count != 0) {
avg_infected_factor += stoi(vector_list[i][1]) / last_infected_count;
last_infected_count = stoi(vector_list[i][1]);
} else {
// INCREMENT COUNTER FOR TIMES ZERO PEOPLE WERE INFECTED
zero_infected++;
}
// SET LAST INFECTED COUNT TO CURRENT COUNT
last_infected_count = stoi(vector_list[i][1]);
last_dead_count = stoi(vector_list[i][2]);
}
// CALCULATES AVERAGES
avg_infected_factor = avg_infected_factor / (vector_list.size() - 1 - zero_infected);
avg_dead_factor = avg_dead_factor / (vector_list.size() - 1 - zero_dead);
// CALCULATES PROGNOSES
infected = stoi(vector_list[vector_list.size() - 1][1]) * pow(avg_infected_factor, days);
dead = stoi(vector_list[vector_list.size() - 1][2]) * pow(avg_dead_factor, days);
vector<int> prognose = { (int) infected, (int) dead };
// DISPLAYS PROGNOSEDATA IN TABLE
return prognose;
}
// SPLITS STRING AT DELIMETER AND RETURNS A VECTOR
vector<string> splitString(string s, char delim) {
string string_token;
vector<string> string_vector;
for (int i = 0; i < s.length(); i++) {
if (s[i] == delim) {
string_vector.push_back(string_token);
string_token = "";
} else {
string_token += s[i];
}
}
return string_vector;
}
// WRITES TO FILE
void writeFile(string content, string file_name) {
ofstream file;
file.open(file_name, ios_base::out | ios_base::app);
file << content;
file.close();
}
// GET LONGEST NUMBER IN DATA TO DISPLAY TABLE CORRECTLY
int getLongestLength(vector<vector<string>> vector_list, int index) {
int result;
result = vector_list[0][index].length();
for(vector<string> splitted_string: vector_list) {
if (splitted_string[index].length() > result) {
result = splitted_string[index].length();
}
}
return result;
}
// DISPLAY PROGNOSE FOR EACH DAY IN TABLE
// DISPLAYS CURRENT DATA AS TABLE
void displayData(string file_name, int prognose_days) {
int width_day, width_infected, width_dead, current_day;
string day = "Day";
string infected = "Infected";
string dead = "Dead";
ifstream file(file_name);
string line;
vector<vector<string>> vector_list;
// CHECKS IF FILE EXISTS/IS EMPTY
if (file.peek() == ifstream::traits_type::eof()) {
cout << "\033[1;31m[ERROR]\033[0m File is empty. Please input data!" << endl;
return;
}
// GETS LINES OF FILE, SPLITS THEM AND PUTS THEM IN A VECTOR
while(getline(file, line)) {
vector<string> splitted_string = splitString(line, ':');
vector_list.push_back(splitted_string);
}
if (prognose_days != -1) {
vector<string> prognose_vector;
ifstream file(file_name);
string line;
int current_day;
while(getline(file, line)) {
vector<string> splitted_string = splitString(line, ':');
// GETS LAST DAY AND CONTINUES WITH THE NEXT
current_day = stoi(splitted_string[0]) + 1;
}
for(int i = 1; i <= prognose_days; i++) {
// CREATE EXTRA STRING TO ADD COLOR
prognose_vector.push_back(to_string(current_day) + " (P)");
prognose_vector.push_back(to_string(calculatePrognose(i, file_name)[0]));
prognose_vector.push_back(to_string(calculatePrognose(i, file_name)[1]));
vector_list.push_back(prognose_vector);
current_day++;
prognose_vector.clear();
}
}
file.close();
// GET LONGEST LENGTH OF EACH COLUMN
width_day = getLongestLength(vector_list, 0);
width_infected = getLongestLength(vector_list, 1);
width_dead = getLongestLength(vector_list, 2);
// DISPLAYS SEPERATORS IN CORRECT COUNT WITH TERNARY OPERATORS
cout << string(((width_day < day.length()) ? 0 : width_day - day.length())
+ ((width_infected < infected.length()) ? 0 : width_infected - infected.length())
+ ((width_dead < dead.length()) ? 0 : width_dead - dead.length())
+ day.length() + infected.length() + dead.length() + 4, '_') << endl;
// DISPLAYS DESCRIPTION IN CORRECT COUNT WITH TERNARY OPERATORS
cout <<
"|" << "\033[1;32m" << day << "\033[0m" << string((width_day < day.length()) ? 0 : width_day - day.length(), ' ') <<
"|" << "\033[1;33m" << infected << "\033[0m" << string((width_infected < infected.length()) ? 0 : width_infected - infected.length(), ' ') <<
"|" << "\033[1;31m" << dead << "\033[0m" << string((width_dead < dead.length()) ? 0 : width_dead - dead.length(), ' ') <<
"|" << endl;
// DISPLAYS DATA IN CORRECT COUNT WITH TERNARY OPERATORS
for(vector<string> splitted_string: vector_list) {
cout <<
"|" << splitted_string[0] << string((splitted_string[0].length() < day.length())
? ((width_day < day.length()) ? day.length() - splitted_string[0].length()
: width_day - splitted_string[0].length()) : width_day - splitted_string[0].length(), ' ') <<
"|" << splitted_string[1] << string((splitted_string[1].length() < infected.length())
? ((width_infected < infected.length()) ? infected.length() - splitted_string[1].length()
: width_infected - splitted_string[1].length()) : width_infected - splitted_string[1].length(), ' ') <<
"|" << splitted_string[2] << string((splitted_string[2].length() < dead.length())
? ((width_dead < dead.length()) ? dead.length() - splitted_string[2].length()
: width_dead - splitted_string[2].length()) : width_dead - splitted_string[2].length(), ' ') <<
"|" << endl;
}
}
int main(int argc, char **argv) {
string use_choice, infected_and_dead;
double prognose_days;
// LOOP TO GET TO MAIN MENU WHEN LEAVING A SUB MENU
while (true) {
// GETS CHOICE
cout << "Do you want to make a prognose (P), input new data (I), show current data (D) or quit (Q)?: ";
cin >> use_choice;
// TRANSFORMS CHOICE TO LOWERCASE TO IGNORE CASE
transform(use_choice.begin(), use_choice.end(), use_choice.begin(), ::tolower);
// PROGNOSE
if (use_choice == "p") {
cout << "How many days to you want to prognose?: ";
cin >> prognose_days;
// CALCULATES PROGNOSE OUT OF SUBMITTED DAYS
vector<int> prognose = calculatePrognose(prognose_days, file_name);
if (prognose[0] && prognose[1] == -1) {
continue;
} else {
displayData(file_name, prognose_days);
cout << "\033[1;33mInfections:\033[0m " << prognose[0] << endl
<< "\033[1;31mDeaths: \033[0m" << prognose[1] << endl;
}
// INPUT NEW DATA
} else if (use_choice == "i") {
ifstream file(file_name);
string line;
int current_day;
// CHECKS IF FILE EXISTS/IS EMPTY AND START WITH DAY 1
if (file.peek() == ifstream::traits_type::eof()) {
current_day = 1;
} else {
while(getline(file, line)) {
vector<string> splitted_string = splitString(line, ':');
// GETS LAST DAY AND CONTINUES WITH THE NEXT
current_day = stoi(splitted_string[0]) + 1;
}
}
file.close();
while (true) {
cout << "Day " << current_day << ": Enter new data or quit (Q): ";
cin >> infected_and_dead;
// TRANSFORMS CHOICE TO LOWERCASE TO IGNORE CASE
transform(infected_and_dead.begin(), infected_and_dead.end(), infected_and_dead.begin(), ::tolower);
if (infected_and_dead == "q") {
current_day++;
break;
}
// CONVERTS NUMBERS TO STRINGS
infected_and_dead = to_string(current_day) + ":" + infected_and_dead + ":" + "\n";
// CHECKS IF DATA IS CORRECTLY INPUTTED
if (splitString(infected_and_dead, ':').size() < 3) {
cout << "\033[1;31m[ERROR]\033[0m Invalid Input! Please enter data in this form: 'infected:dead' " << endl;
continue;
}
// WRITES DATA TO FILE
writeFile(infected_and_dead, file_name);
current_day++;
}
// DISPLAY DATA
} else if (use_choice == "d") {
displayData(file_name);
// QUIT
} else if (use_choice == "q") {
break;
} else {
// DISPLAYS ERROR MESSAGE WHEN WRONG CHOICE IS SUBMITTED
cout << "\033[1;31m[ERROR]\033[0m Invalid Input" << endl;
}
}
return 0;
}
</code></pre>
<h2>corona_numbers.dat (example)</h2>
<pre><code>1:10:0:
2:25:2:
3:50:3:
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T00:37:28.643",
"Id": "469318",
"Score": "0",
"body": "Welcome to Code Review! Can you [edit] the question to also indicate the revision of the standard and the compiler options you are using? Thanks. By the way, you can take the [tour] and browse our [FAQs](https://codereview.meta.stackexchange.com/questions/tagged/faq?tab=Votes) to further familiarize yourself with our community."
}
] | [
{
"body": "<p>It would have been nice to have the data file so that we could test the code to provide an even better review.</p>\n<h2>Complexity</h2>\n<p>Almost All of the functions are too complex (do too much) and should be broken up into multiple functions. Multiple functions are easier to read, write, debug and maintain. A single function that performs a single operation is much easier to debug and write. Specifically these functions are too complex, <code>vector<int> calculatePrognose(double days, string file_name)</code>, <code>void displayData(string file_name, int prognose_days = -1)</code> and <code>int main(int argc, char **argv)</code>.</p>\n<p>There is also a programming principle called the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> that applies here. The Single Responsibility Principle 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>As programs grow in size the use of <code>main()</code> should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.</p>\n<p>The entire <code>while(true)</code> loop in <code>main()</code> should be a function. The entire block of code within</p>\n<pre><code> } else if (use_choice == "i") {\n ...\n }\n</code></pre>\n<p>Would be a sub-function of the <code>while(true)</code> loop function.</p>\n<p>Another example, this snippet from vector calculatePrognose(double days, string file_name) would make a good function:</p>\n<pre><code> for(int i = 1; i < vector_list.size(); i++) {\n\n // CHECK IF LAST NUMBER IS ZERO TO PREVENT A DIVISION THROUGH ZERO\n if (last_dead_count != 0) {\n avg_dead_factor += stoi(vector_list[i][2]) / last_dead_count;\n last_dead_count = stoi(vector_list[i][2]);\n\n } else {\n // INCREMENT COUNTER FOR TIMES ZERO PEOPLE WERE DEAD\n zero_dead++;\n }\n\n // CHECK IF LAST NUMBER IS ZERO TO PREVENT A DIVISION THROUGH ZERO\n if (last_infected_count != 0) {\n avg_infected_factor += stoi(vector_list[i][1]) / last_infected_count;\n last_infected_count = stoi(vector_list[i][1]);\n\n } else {\n // INCREMENT COUNTER FOR TIMES ZERO PEOPLE WERE INFECTED\n zero_infected++;\n }\n\n // SET LAST INFECTED COUNT TO CURRENT COUNT\n last_infected_count = stoi(vector_list[i][1]);\n last_dead_count = stoi(vector_list[i][2]);\n }\n</code></pre>\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 [stack overflow question][3] discusses this in more detail.</p>\n<h2>Initialize The Local Variables When They are Declared</h2>\n<p>In C++ local variables do not have a default value, they should all be initialized. My complier reports one warning where a variable is used before it is initialized, <code>avg_dead_factor</code> in <code>vector<int> calculatePrognose(double days, string file_name)</code>.</p>\n<pre><code>uninitialized local variable 'avg_dead_factor' used\n</code></pre>\n<p>The code contains this line:</p>\n<pre><code>avg_dead_factor, avg_infected_factor = 0;\n</code></pre>\n<p>Only <code>avg_infected_factor</code> will be initialized in the above code.</p>\n<p>To make it easier to maintain the code, each variable should be delcared and initialized on a single line:</p>\n<pre><code>vector<int> calculatePrognose(double days, string file_name) {\n // DECLARES VARIABLES\n int zero_dead = 0;\n int zero_infected = 0;\n double avg_infected_factor = 0;\n double avg_dead_factor = 0;\n double last_infected_count = 0;\n double last_dead_count = 0;\n double infected = 0;\n double dead = 0;\n</code></pre>\n<p>It is important to note that variables should be declared as they are needed and only within the scope that they are needed. The above snippet is only an example.</p>\n<p>Code should be as self documenting as possible and comments like <code>// DECLARES VARIABLES</code> are not necessary.</p>\n<h2>Global Variables</h2>\n<p>Generally you've done a pretty good job of avoiding global variables, with one glaring exception:</p>\n<blockquote>\n<pre><code>string file_name = "corona_numbers.dat";\n</code></pre>\n</blockquote>\n<p>It might be better if this was declared in <code>main()</code> and passed to the functions that need it. This value could be an argument that is passed into the program from the command line to make the program easier to use without modifying it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T23:02:48.420",
"Id": "239253",
"ParentId": "239229",
"Score": "3"
}
},
{
"body": "<p>Welcome to Code Review! Let's go through your code and try to improve it.</p>\n\n<h1>Comments</h1>\n\n<p>The first thing I notice about your code is that all comments are written in ALL CAPS. This not only makes the comments harder to read, but also distracts the reader of the code. I suggest changing them to lower case.</p>\n\n<p>Some comments talk about aspects of the C++ language rather than the purpose of the code:</p>\n\n<pre><code>// DECLARES METHODS\n// PUBLIC VARIABLE FOR FILENAME\n</code></pre>\n\n<p>etc. These comments are unnecessary to readers familiar with C++, so you can remove them once you feel comfortable with basic C++ constructs.</p>\n\n<h1><code>using namespace std;</code></h1>\n\n<p>Putting a <code>using namespace std;</code> at global level is considered bad practice. It pulls in all names from the <code>std</code> namespace, potentially introducing name clashes. See <a href=\"https://stackoverflow.com/q/1452721\">Why is <code>using namespace std;</code> considered bad practice?</a> for more information. For relatively small projects like yours, this is not a big problem, but I recommend that you remove this line and get used to qualifying names from the standard library with <code>std::</code> as soon as possible.</p>\n\n<h1>Declarations and definitions of functions</h1>\n\n<p>Instead of declaring functions first and put the definitions after, you can simply define functions after their dependencies. That is, you can define <code>splitString</code> before <code>calculatePrognose</code> to eliminate the declaration.</p>\n\n<h1>Pass-by-value vs pass-by-reference</h1>\n\n<p>When you are reading data, passing by value requires copying the content of the argument. This is very expensive for large types like <code>vector<vector<string>></code>. Pass by const reference (<code>const vector<vector<string>>&</code>) instead. See <a href=\"https://stackoverflow.com/a/2139254\">How to pass objects to functions in C++?</a> for more information.</p>\n\n<h1>Data</h1>\n\n<p>Right now, the way you keep track of data is to maintain a <code>vector<vector<string>></code> in each function and pass it around. First, each record (the <code>vector<string></code>) can be made a simple class:</p>\n\n<pre><code>using data_t = long;\n\nstruct Record {\n data_t day;\n data_t infected;\n data_t dead;\n};\n</code></pre>\n\n<p>We can overload <code>>></code> to support input:</p>\n\n<pre><code>// simple manipulator\n// is >> eat_delim{':'} eats ':' delimiter\nstruct eat_delim {\n char delim;\n};\n\nstd::istream& operator>>(std::istream& is, eat_delim manip)\n{\n if (is.peek() == manip.delim) {\n is.get();\n } else {\n is.setstate(is.failbit);\n }\n return is;\n}\n\nstd::istream& operator>>(std::istream& is, Record& rec)\n{\n return is >> rec.day >> eat_delim{':'}\n >> rec.infected >> eat_delim{':'}\n >> rec.dead >> eat_delim{':'};\n}\n</code></pre>\n\n<p>Then, we can make a dedicated class to perform operations on the data:</p>\n\n<pre><code>class DataProcessor {\n std::vector<Record> data;\n std::string filename;\npublic:\n DataProcessor(std::string file)\n : filename{std::move(file)}\n {\n std::ifstream in{filename};\n for (Record rec; in >> rec;) {\n data.push_back(rec);\n }\n }\n // ...\n};\n</code></pre>\n\n<h1><code>splitString</code></h1>\n\n<p>Here's roughly how I would write the <code>splitString</code> method with string methods:</p>\n\n<pre><code>// a:b:c: => [a, b, c]\nauto split_string(std::string_view string, char delim)\n{\n std::vector<std::string> result;\n for (std::size_t index; (index = string.find(delim)) != string.npos) {\n result.emplace_back(string, 0, index);\n string.remove_prefix(index + 1);\n }\n return result;\n}\n</code></pre>\n\n<p>This <code>split_string</code> discards content after the last delimiter, just like your version does. Note that <code>string_view</code> is used to <a href=\"https://stackoverflow.com/q/40127965\">avoid copying</a> and <code>size_t</code> is used to index the string instead of <code>int</code>.</p>\n\n<h1><code>writeFile</code></h1>\n\n<p>This function can be simplified if you make use of RAII — automatic opening/closing:</p>\n\n<pre><code>std::ofstream file{file_name, std::ios_base::app};\nfile << content;\n</code></pre>\n\n<p>Note that <code>out</code> is always set for <code>ofstream</code>.</p>\n\n<p>Under our new design, this operation will be carried out when new data is added, so that the file syncs with our data.</p>\n\n<h1><code>getLongestLength</code></h1>\n\n<p>This function becomes much simpler with C++20 projections:</p>\n\n<pre><code>std::ranges::max(\n vector_list | std::views::transform([&](const auto& record) {\n return record[index].size();\n })\n)\n</code></pre>\n\n<h1><code>calculatePrognose</code></h1>\n\n<p>The size of this function makes it hard to understand, so let's try to break it down. We calculate the average factor first and determine the prognosis later:</p>\n\n<pre><code>// pointer to member of Record\nusing column_t = data_t Record::*;\n\nclass DataProcessor {\n // ...\npublic:\n // ...\n double average_factor(column_t column)\n {\n if (data.size() <= 1) {\n throw std::invalid_argument{\"Insufficient samples\"};\n }\n std::vector<data_t> past_data(data.size());\n std::transform(data.begin(), data.end(), past_data, column);\n std::adjacent_difference(past_data.begin(), past_data.end(),\n past_data.begin(), std::divides{});\n return std::accumulate(past_data.begin() + 1, past_data.end(), 0.0) / (past_data.size() - 1);\n }\n std::vector<Record> prognosis(data_t days)\n {\n auto infected_factor = average_factor(&Record::infected);\n auto dead_factor = average_factor(&Record::dead);\n\n std::vector<Record> result;\n for (Record rec = data.back(); days--;) {\n ++rec.day;\n rec.infected *= infected_factor;\n rec.dead *= dead_factor;\n result.push_back(rec);\n }\n return result;\n }\n // ...\n};\n</code></pre>\n\n<h1><code>displayData</code></h1>\n\n<p>Again, the sheer length of the function makes it virtually incomprehensible (the last part is especially unreadable), so I'm just trying to rewrite it. The printing of the data rows (as opposed to prognosis rows) can be extracted into a separate function:</p>\n\n<pre><code>class DataProcessor {\n // ...\npublic:\n // ...\n void print_data(std::ostream& os) const\n {\n std::array<int, 3> widths {\n // calculate widths\n };\n\n auto total_width = widths[0] + widths[1] + widths[2] + 4;\n os << std::string(total_width, '_');\n print_data_rows(os, widths);\n print_stats(os);\n }\n // print_prognosis is similar\n // ...\nprivate:\n void print_data_rows(std::ostream& os, const std::array<int, 3>& widths) const\n {\n for (const auto& record : data) {\n os << '|'\n << std::setw(widths[0]) << record.day\n << '|'\n << std::setw(widths[1]) << record.infected\n << '|'\n << std::setw(widths[2]) << record.dead\n << '|';\n }\n }\n void print_prognosis_rows(std::ostream& os, const std::array<int, 3>& widths, data_t days) const\n {\n auto prog = prognosis(days);\n for (const auto& record : prog) {\n os << '|'\n << std::setw(widths[0]) << (std::to_string(record.day) + \" (P)\")\n << '|'\n << std::setw(widths[1]) << (std::to_string(record.day) + \" (P)\")\n << '|'\n << std::setw(widths[2]) << (std::to_string(record.day) + \" (P)\")\n << '|';\n }\n }\n void print_stats(std::ostream& os)\n {\n // print Infections: 6339 etc.\n }\n // ...\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T03:52:44.230",
"Id": "239262",
"ParentId": "239229",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T13:38:28.290",
"Id": "239229",
"Score": "6",
"Tags": [
"c++"
],
"Title": "Program for prognosing, storing and displaying data about a virus"
} | 239229 |
<p>In <a href="https://github.com/bstarynk/helpcovid" rel="nofollow noreferrer">helpcovid</a> git <a href="https://github.com/bstarynk/helpcovid/commit/e27dd3b123c183006654f81dca3b4a19cb9de95e" rel="nofollow noreferrer">commit <code>e27dd3b123c18300665</code></a> we have a stupid bug related to Linux GNU <a href="https://www.gnu.org/software/libc/manual/html_node/Argp.html" rel="nofollow noreferrer">glibc <code>argp</code></a> program argument parsing.</p>
<pre><code>void
hcv_parse_program_arguments(int &argc, char**argv)
{
struct argp_state argstate;
memset (&argstate, 0, sizeof(argstate));
argstate.input = &hcv_progargs;
hcv_progargs.hcv_progmagic = HCV_PROGARG_MAGIC;
static struct argp argparser;
argparser.options = hcv_progoptions;
argparser.parser = hcv_parse1opt;
argparser.args_doc = "*no-positional-arguments*";
argparser.doc = "github.com/bstarynk/helpcovid"
" - a GPLv3+ free software to help organizing"
" against Covid19 - NO WARRANTY";
argparser.children = nullptr;
argparser.help_filter = nullptr;
argparser.argp_domain = nullptr;
if (argp_parse(&argparser, argc, argv, 0, nullptr, nullptr))
HCV_FATALOUT("failed to parse program arguments to " << argv[0]);
#warning TODO: complete hcv_parse_program_arguments
} // end hcv_parse_program_arguments
</code></pre>
<p>The bug is obvious, but I cannot find it.</p>
<p>At runtime, with the <code>main</code> function being:</p>
<pre><code>int
main(int argc, char**argv)
{
hcv_early_initialize(argv[0]);
hcv_parse_program_arguments(argc, argv);
HCV_SYSLOGOUT(LOG_NOTICE, "start of " << argv[0] << std::endl
<< " version:" << hcv_versionmsg);
HCV_SYSLOGOUT(LOG_INFO, "normal end of " << argv[0]);
return 0;
} // end of main
</code></pre>
<p>we observe immediately:</p>
<pre><code>rimski.x86_64 ~/helpcovid 19:12 .0 % ./helpcovid
** HELPCOVID FATAL! hcv_main.cc:84:: corrupted program arguments
**** FATAL ERROR hcv_main.cc:84
./helpcovid[3684197]: FATAL STOP hcv_main.cc:84 (Success)
zsh: abort (core dumped) ./helpcovid
</code></pre>
<p>happening in</p>
<pre><code>// parse a single program option
static error_t
hcv_parse1opt (int key, char *arg, struct argp_state *state)
{
/* Get the input argument from argp_parse, which we
know is a pointer to our arguments structure. */
struct hcv_progarguments *progargs
= reinterpret_cast<hcv_progarguments *>(state->input);
if (!progargs || progargs->hcv_progmagic != HCV_PROGARG_MAGIC)
// this should never happen
HCV_FATALOUT("corrupted program arguments"); //@@@@@@@@@@@@@@@@@@@
switch (key)
{
default:
return ARGP_ERR_UNKNOWN;
}
} // end hcv_parse1opt
</code></pre>
<p>The error being at line with <code>//@@@@@@@@@@@@@@@@@@@</code>, <a href="https://github.com/bstarynk/helpcovid/blob/master/hcv_main.cc#L84" rel="nofollow noreferrer">file <code>hcv_main.cc</code> line 84</a>. The <code>gdb</code> debugger tells that <code>progargs</code> is a null pointer (and should not be).</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T18:08:31.533",
"Id": "469273",
"Score": "0",
"body": "Can you please edit the post to share some more details about the bug? Such as the expected behavior vs the observed behavior."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T02:34:24.840",
"Id": "469324",
"Score": "0",
"body": "Isn't code on this site supposed to be bug free? From a meta question tagged as an FAQ, *\"[A guide to Code Review for Stack Overflow users](https://codereview.meta.stackexchange.com/questions/5777)\"* (my emphasis): *\"Please, we **don't want** the following kinds of questions ... questions where the code **does not work as intended**\"*"
}
] | [
{
"body": "<p>I think that the call to <code>argp_parse()</code> in <code>hcv_parse_program_arguments()</code> is missing a pointer to the arguments struct. Looking at the <code>main()</code> function in the canonical <a href=\"https://www.gnu.org/software/libc/manual/html_node/Argp-Example-3.html\" rel=\"nofollow noreferrer\">Argp Example 3</a>, we see that the <code>argp_parse()</code> function is passed a pointer to <code>struct arguments arguments</code>.</p>\n\n<pre><code>int\nmain (int argc, char **argv)\n{\n struct arguments arguments;\n\n /* Default values. */\n arguments.silent = 0;\n arguments.verbose = 0;\n arguments.output_file = \"-\";\n\n /* Parse our arguments; every option seen by parse_opt will\n be reflected in arguments. */\n argp_parse (&argp, argc, argv, 0, 0, &arguments);\n\n printf (\"ARG1 = %s\\nARG2 = %s\\nOUTPUT_FILE = %s\\n\"\n \"VERBOSE = %s\\nSILENT = %s\\n\",\n arguments.args[0], arguments.args[1],\n arguments.output_file,\n arguments.verbose ? \"yes\" : \"no\",\n arguments.silent ? \"yes\" : \"no\");\n\n exit (0);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T05:47:33.387",
"Id": "469331",
"Score": "2",
"body": "Welcome to Code Review! Please note, questions involving code that's not working as intended, are off-topic on this site. If OP edits their post to address the problem and make their post on-topic, they make your answer moot. [It is advised not to answer such questions](https://codereview.meta.stackexchange.com/a/6389/120114). Protip: There are tons of on-topic questions to answer; you'll make more reputation faster if you review code in questions that will get higher view counts for being on-topic."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T19:35:45.583",
"Id": "239244",
"ParentId": "239238",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "239244",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T17:40:09.647",
"Id": "239238",
"Score": "0",
"Tags": [
"parsing",
"linux",
"c++17"
],
"Title": "bad GNU libc argp code"
} | 239238 |
<p>I recently implemented a Bloom Filter in Haskell and, although I am not new to functional programming, I am a beginner when it comes to Haskell itself.</p>
<p>I'll gladly take any feedback regarding the implementation or the code style. I tried to stick to the Haskell conventions regarding function and variable naming, but I may have gotten some stuff wrong.</p>
<p>You will notice that I'm using my own implementation of a Bitset, you can assume it behaves like a normal one (I sure hope so).</p>
<pre><code>module DataStructures.BloomFilter (empty, insert, member, DataStructures.BloomFilter.null) where
import System.Random (random, StdGen)
import qualified DataStructures.Bitset as Bitset
import Data.Hashable (hashWithSalt)
-- n: expected number of items in the Bloom Filter
-- p: acceptable probability of a false positive
-- m: max number of bits the Bloom Filter will use
-- k: number of hashing functions
data BloomFilter = BloomFilter {
n :: Int, p :: Float, bitset :: Bitset.Bitset, m :: Int, k :: Int, hashSeed :: Int
} deriving (Eq, Show)
getMaxSize :: Int -> Float -> Int
getMaxSize n p = abs $ ceiling $ fromIntegral n * (log p) / (log (1 / (log 2 ^ 2)))
getNumberOfHashFunctions :: Int -> Int -> Int
getNumberOfHashFunctions n m = round $ fromIntegral (m `div` n) * log 2
empty :: Int -> Float -> StdGen -> BloomFilter
empty n p randGen =
let m = getMaxSize n p
k = getNumberOfHashFunctions n m
hashSeed = fst $ random randGen
in BloomFilter n p Bitset.empty m k hashSeed
null :: BloomFilter -> Bool
null = Bitset.null . bitset
getHashes :: Show a => BloomFilter -> a -> [Int]
getHashes bloomFilter elem =
let str = show elem
seed = hashSeed bloomFilter
maxSize = m bloomFilter
in (`mod` maxSize) . abs . (`hashWithSalt` str) . (seed +) <$> [1..(k bloomFilter)]
insert :: Show a => BloomFilter -> a -> BloomFilter
insert bloomFilter elem =
let hashes = getHashes bloomFilter elem
newBitset = Bitset.insertMany (bitset bloomFilter) hashes
in bloomFilter { bitset = newBitset }
-- Returns whether an element *may be* present in the bloom filter.
-- This function can yield false positives, but not false negatives.
member :: Show a => BloomFilter -> a -> Bool
member bloomFilter elem =
let hashes = getHashes bloomFilter elem
bs = bitset bloomFilter
in all (Bitset.member bs) hashes
</code></pre>
<p>I would have liked to use a murmur3 hashing function but all Haskell implementations use types that I'm not yet familiar with (Word32, ByteString).</p>
| [] | [
{
"body": "<p>I only have one minor nitpick: the definition of <code>getMaxSize</code> becomes clearer if we use <code>logBase</code>:</p>\n\n<pre><code>abs $ ceiling $ fromIntegral n * (log p) / (log (1 / (log 2 ^ 2)))\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>abs $ ceiling $ fromIntegral n * (- 0.5) * logBase (log 2) p\n</code></pre>\n\n<p>We can use the identity <code>ceiling (-x) == - floor(x)</code> to get</p>\n\n<pre><code>abs . floor $ fromIntegral n * 0.5 * logBase (log 2) p\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-01T12:08:46.777",
"Id": "241550",
"ParentId": "239241",
"Score": "2"
}
},
{
"body": "<p>Instead of transforming everything to <code>String</code> using <code>Show</code> just for the purpose of hashing it, you should constraint element types to be <a href=\"https://hackage.haskell.org/package/hashable-1.3.0.0/docs/Data-Hashable.html#t:Hashable\" rel=\"nofollow noreferrer\"><code>Hashable</code></a> instead:</p>\n\n<pre><code>getHashes :: Hashable a => BloomFilter -> a -> [Int]\ngetHashes bloomFilter elem =\n let seed = hashSeed bloomFilter\n maxSize = m bloomFilter\n in (`mod` maxSize) . abs . (`hashWithSalt` elem) . (seed +) <$> [1..(k bloomFilter)]\n</code></pre>\n\n<p>I'd also use <code>maxSize</code> and <code>numFuns</code> as the field names in <code>BloomFilter</code> and then use <code>RecordWildCards</code>:</p>\n\n<pre><code>getHashes :: Hashable a => BloomFilter -> a -> [Int]\ngetHashes BloomFilter{..} elem = map nthHash [1..numFuns]\n where\n nthHash n = abs (hashWithSalt (n + hashSeed) elem) `mod` maxSize \n</code></pre>\n\n<p>Or maybe even nicer:</p>\n\n<pre><code>getHashes :: Hashable a => BloomFilter -> a -> [Int]\ngetHashes BloomFilter{..} elem = \n [ abs (hashWithSalt (i + hashSeed) elem) `mod` maxSize | i <- [1..numFuns] ]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T14:53:43.973",
"Id": "476813",
"Score": "0",
"body": "Oh I did not know about the RecordWildCards thing. Very cool, thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-25T11:40:00.730",
"Id": "242895",
"ParentId": "239241",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T18:52:18.910",
"Id": "239241",
"Score": "5",
"Tags": [
"haskell",
"functional-programming",
"set",
"bitset",
"bloom-filter"
],
"Title": "Bloom Filter in Haskell"
} | 239241 |
<p>The code starts with 128 bits of 0 (size of <code>md5sum</code> checksum) then brute forces to find checksum matching regex (all characters of checksum in hex are digits). I know that there may be collisions and that not all 2^128 possible checksums will come out.</p>
<p>I know that if the code is run, that it will not finish any time soon. I will try to read up on how I can change the <code>for</code> loop into a parallel <code>for</code> loop that uses all CPU cores.</p>
<p>This is one of my first (not very useful) programs in Golang. All constructive feedback welcome.</p>
<p>Output:</p>
<pre><code>0000000000000000000000000092FE92 14275262221639818016075488414463
000000000000000000000000009FF5EA 56052719788687373369347657641554
00000000000000000000000000BA7A1D 25521851964074241922881283516897
00000000000000000000000000E13807 19356247379454983142782955697777
00000000000000000000000000E8C976 64115693827254722796959498140064
00000000000000000000000001037BAD 68461226587668825351060559236884
0000000000000000000000000109658F 87596081213274701373126754303410
...
</code></pre>
<pre><code>package main
import (
"crypto/md5"
"encoding/hex"
"fmt"
"regexp"
"strings"
)
func main() {
data := []byte("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00")
r, _ := regexp.Compile("^[0-9]{32}$")
for {
hash := md5.Sum(data)
hash_hex_string := hex.EncodeToString(hash[:])
if (r.MatchString(hash_hex_string)) {
fmt.Printf("%X %s\n", data, strings.ToUpper(hash_hex_string))
}
if (!increment(data, 15)) {
break
}
}
}
func increment(data []byte, start_pos int) (bool) {
if (start_pos < 0) {
return false
}
data[start_pos]++
if (data[start_pos] == 0) {
return increment(data, start_pos - 1)
}
return true
}
<span class="math-container">```</span>
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T19:20:25.247",
"Id": "239243",
"Score": "1",
"Tags": [
"performance",
"beginner",
"go"
],
"Title": "Brute force md5 checksum matching regex"
} | 239243 |
<p>PHP coder here. Learning JavaScript this week. I made a sudoku game for practice. Features:</p>
<ul>
<li>Import puzzles by pasting a text string.</li>
<li>Imported squares are gray. Your squares are white.</li>
<li>Program doesn't let you make a clearly illegal move. It will blank your number and color the square red for 2 seconds.</li>
<li>The sudoku puzzle/game is a class. Easy to add methods and features to it later.</li>
<li>Room for growth. I may add a "solve" button and a "give hints" check box later. I may add a "you won" message when you win.</li>
</ul>
<p>Things I'm hoping to gain from this Code Review.</p>
<ul>
<li>Let's focus on the JavaScript. Improvements to the JavaScript code's organization, style, choice of functions, variable and function names, etc.</li>
<li>Feel free to refactor completely if you want.</li>
<li>Looking for that professional coder perspective so I can build good habits.</li>
<li>Feel free to suggest next steps/next features.</li>
</ul>
<p>Fiddle - <a href="https://jsfiddle.net/AdmiralAkbar2/z6rv70h4/37/" rel="nofollow noreferrer">https://jsfiddle.net/AdmiralAkbar2/z6rv70h4/37/</a></p>
<h1>Screenshot</h1>
<p><a href="https://i.stack.imgur.com/06jfR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/06jfR.png" alt="enter image description here" /></a></p>
<h1>JavaScript</h1>
<pre><code>// TODO: solve button
// TODO: show hints
// if 8 squares in a 3x3 are known, highlight 9th square
// if 8 squares in a row are known, highlight 9th square
// if 8 squares in a column are known, highlight 9th square
"use strict";
class Sudoku {
constructor() {
this.board = this.blank_board_array();
}
blank_board_array() {
return [
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0]
];
}
// I can't figure out how to get this working with the "set" keyword, so making a method for now
set_board(board_string) {
if ( ! board_string.match(/^\d{81}$/m) ) {
this.board = this.blank_board_array();
return;
}
for ( let row = 0; row <= 8; row++ ) {
for ( let column = 0; column <= 8; column++ ) {
this.board[row][column] = board_string.charAt(row*9+column);
}
}
/*
if ( ! this.puzzle_is_valid() ) {
this.board = this.blank_board_array();
return;
}
*/
}
get_board_array() {
return this.board;
}
make_move(row, col, value) {
this.board[row][col] = value;
}
is_legal_move(row, col, value) {
// check for non numbers
// weird that JS match function doesn't put quotes around regex
if ( ! value.match(/^[1-9]$/m) ) {
return false;
}
// check row
for ( let i = 0; i <= 8; i++ ) {
if ( value == this.board[row][i] ) {
return false;
}
}
// check column
for ( let i = 0; i <= 8; i++ ) {
if ( value == this.board[i][col] ) {
return false;
}
}
// check 3x3 grid
let row_offset = Math.floor(row/3)*3;
let col_offset = Math.floor(col/3)*3;
for ( let i = 0 + row_offset; i <= 2 + row_offset; i++ ) {
for ( let j = 0 + col_offset; j <= 2 + col_offset; j++ ) {
if ( value == this.board[i][j] ) {
return false;
}
}
}
return true;
}
};
let game1 = new Sudoku();
let import_string;
let import_button = document.getElementById('import');
let sudoku_squares = createArray(9,9);
for ( let row = 0; row <= 8; row++ ) {
for ( let col = 0; col <= 8; col++ ) {
sudoku_squares[row][col] = document.getElementsByClassName('sudoku')[0].getElementsByTagName('tbody')[0].getElementsByTagName('tr')[row].getElementsByTagName('td')[col].getElementsByTagName('input')[0];
}
}
import_button.addEventListener("mouseup", function() {
import_string = document.getElementsByName("import_string")[0].value;
game1.set_board(import_string);
print_sudoku_to_webpage(game1);
});
for ( let row = 0; row <= 8; row++ ) {
for ( let col = 0; col <= 8; col++ ) {
sudoku_squares[row][col].addEventListener('input', function(e) {
e.target.classList.remove("invalid");
if ( ! game1.is_legal_move(row, col, e.target.value) && e.target.value != "" ) {
e.target.value = "";
highlight_temporarily(e.target, 2000);
} else {
game1.make_move(row, col, e.target.value);
}
});
}
}
function print_sudoku_to_webpage(sudoku_object) {
let board = sudoku_object.get_board_array();
clear_webpage_board();
for ( let row = 0; row <= 8; row++ ) {
for ( let col = 0; col <= 8; col++ ) {
if ( board[row][col] != 0 ) {
let input = sudoku_squares[row][col];
input.value = board[row][col];
input.classList.add('imported_square');
}
}
}
}
function clear_webpage_board() {
for ( let row = 0; row <= 8; row++ ) {
for ( let col = 0; col <= 8; col++ ) {
sudoku_squares[row][col].value = "";
sudoku_squares[row][col].classList.remove('imported_square');
}
}
}
// This code is borrowed from another website. Thanks google.
function createArray(length) {
var arr = new Array(length || 0),
i = length;
if (arguments.length > 1) {
var args = Array.prototype.slice.call(arguments, 1);
while(i--) arr[length-1 - i] = createArray.apply(this, args);
}
return arr;
}
function highlight_temporarily(obj, timeout_in_ms){
obj.classList.add('invalid');
setTimeout(function(){
obj.classList.remove('invalid');
}, timeout_in_ms);
}
</code></pre>
<h1>HTML</h1>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<title>Sudoku</title>
</head>
<body>
<div class="import">
<input type="text" name="import_string" value="080100007000070960026900130000290304960000082502047000013009840097020000600003070" />
<br />
<button id="import">Import</button>
<!--
<button id="solve">Solve</button>
<input type="checkbox" value="1" name="hints" /> Show Hints
-->
</div>
<table class="sudoku">
<tbody>
<tr class="1">
<td class="1"><input type="text" maxlength="1" /></td>
<td class="2"><input type="text" maxlength="1" /></td>
<td class="3 thick_right"><input type="text" maxlength="1" /></td>
<td class="4"><input type="text" maxlength="1" /></td>
<td class="5"><input type="text" maxlength="1" /></td>
<td class="6 thick_right"><input type="text" maxlength="1" /></td>
<td class="7"><input type="text" maxlength="1" /></td>
<td class="8"><input type="text" maxlength="1" /></td>
<td class="9"><input type="text" maxlength="1" /></td>
</tr>
<tr class="2">
<td class="1"><input type="text" maxlength="1" /></td>
<td class="2"><input type="text" maxlength="1" /></td>
<td class="3 thick_right"><input type="text" maxlength="1" /></td>
<td class="4"><input type="text" maxlength="1" /></td>
<td class="5"><input type="text" maxlength="1" /></td>
<td class="6 thick_right"><input type="text" maxlength="1" /></td>
<td class="7"><input type="text" maxlength="1" /></td>
<td class="8"><input type="text" maxlength="1" /></td>
<td class="9"><input type="text" maxlength="1" /></td>
</tr>
<tr class="3 thick_bottom">
<td class="1"><input type="text" maxlength="1" /></td>
<td class="2"><input type="text" maxlength="1" /></td>
<td class="3 thick_right"><input type="text" maxlength="1" /></td>
<td class="4"><input type="text" maxlength="1" /></td>
<td class="5"><input type="text" maxlength="1" /></td>
<td class="6 thick_right"><input type="text" maxlength="1" /></td>
<td class="7"><input type="text" maxlength="1" /></td>
<td class="8"><input type="text" maxlength="1" /></td>
<td class="9"><input type="text" maxlength="1" /></td>
</tr>
<tr class="4">
<td class="1"><input type="text" maxlength="1" /></td>
<td class="2"><input type="text" maxlength="1" /></td>
<td class="3 thick_right"><input type="text" maxlength="1" /></td>
<td class="4"><input type="text" maxlength="1" /></td>
<td class="5"><input type="text" maxlength="1" /></td>
<td class="6 thick_right"><input type="text" maxlength="1" /></td>
<td class="7"><input type="text" maxlength="1" /></td>
<td class="8"><input type="text" maxlength="1" /></td>
<td class="9"><input type="text" maxlength="1" /></td>
</tr>
<tr class="5">
<td class="1"><input type="text" maxlength="1" /></td>
<td class="2"><input type="text" maxlength="1" /></td>
<td class="3 thick_right"><input type="text" maxlength="1" /></td>
<td class="4"><input type="text" maxlength="1" /></td>
<td class="5"><input type="text" maxlength="1" /></td>
<td class="6 thick_right"><input type="text" maxlength="1" /></td>
<td class="7"><input type="text" maxlength="1" /></td>
<td class="8"><input type="text" maxlength="1" /></td>
<td class="9"><input type="text" maxlength="1" /></td>
</tr>
<tr class="6 thick_bottom">
<td class="1"><input type="text" maxlength="1" /></td>
<td class="2"><input type="text" maxlength="1" /></td>
<td class="3 thick_right"><input type="text" maxlength="1" /></td>
<td class="4"><input type="text" maxlength="1" /></td>
<td class="5"><input type="text" maxlength="1" /></td>
<td class="6 thick_right"><input type="text" maxlength="1" /></td>
<td class="7"><input type="text" maxlength="1" /></td>
<td class="8"><input type="text" maxlength="1" /></td>
<td class="9"><input type="text" maxlength="1" /></td>
</tr>
<tr class="7">
<td class="1"><input type="text" maxlength="1" /></td>
<td class="2"><input type="text" maxlength="1" /></td>
<td class="3 thick_right"><input type="text" maxlength="1" /></td>
<td class="4"><input type="text" maxlength="1" /></td>
<td class="5"><input type="text" maxlength="1" /></td>
<td class="6 thick_right"><input type="text" maxlength="1" /></td>
<td class="7"><input type="text" maxlength="1" /></td>
<td class="8"><input type="text" maxlength="1" /></td>
<td class="9"><input type="text" maxlength="1" /></td>
</tr>
<tr class="8">
<td class="1"><input type="text" maxlength="1" /></td>
<td class="2"><input type="text" maxlength="1" /></td>
<td class="3 thick_right"><input type="text" maxlength="1" /></td>
<td class="4"><input type="text" maxlength="1" /></td>
<td class="5"><input type="text" maxlength="1" /></td>
<td class="6 thick_right"><input type="text" maxlength="1" /></td>
<td class="7"><input type="text" maxlength="1" /></td>
<td class="8"><input type="text" maxlength="1" /></td>
<td class="9"><input type="text" maxlength="1" /></td>
</tr>
<tr class="9">
<td class="1"><input type="text" maxlength="1" /></td>
<td class="2"><input type="text" maxlength="1" /></td>
<td class="3 thick_right"><input type="text" maxlength="1" /></td>
<td class="4"><input type="text" maxlength="1" /></td>
<td class="5"><input type="text" maxlength="1" /></td>
<td class="6 thick_right"><input type="text" maxlength="1" /></td>
<td class="7"><input type="text" maxlength="1" /></td>
<td class="8"><input type="text" maxlength="1" /></td>
<td class="9"><input type="text" maxlength="1" /></td>
</tr>
</tbody>
</table>
</body>
</html>
</code></pre>
<h1>CSS</h1>
<pre><code>body {font-family:sans-serif;}
.import {padding-bottom:0.2em;}
.import input[type=text] {width:630px;}
.valid {background-color:limegreen;}
.invalid {background-color:red;}
.imported_square {background-color:lightgray;}
.sudoku {border:4px solid black; border-collapse: collapse;}
.sudoku tr {padding:0;}
.sudoku td {padding:0; border:1px solid black; width:1em;}
.sudoku input {width:1em; border:0; font-size:25pt; text-align:center;}
.sudoku .thick_right {border-right:4px solid black !important;}
.sudoku .thick_bottom {border-bottom:4px solid black;}
</code></pre>
| [] | [
{
"body": "<p>The code is mostly easy to read- indentation seems consistent, though the CSS rules are not separated by new lines - a common convention among many style guides. There are a few comments and many functions/methods are self-documenting but it would be good to comment each function/method to be thorough, especially if you intend to have others utilize the code. </p>\n\n<p>It looks like some <a href=\"/questions/tagged/ecmascript-6\" class=\"post-tag\" title=\"show questions tagged 'ecmascript-6'\" rel=\"tag\">ecmascript-6</a> features are used - e.g. Classes, but more could be used- e.g. <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"nofollow noreferrer\">the spread syntax</a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters\" rel=\"nofollow noreferrer\">default parameters</a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment\" rel=\"nofollow noreferrer\">destructuring assignment</a> and perhaps <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions\" rel=\"nofollow noreferrer\">arrow functions</a>, etc. </p>\n\n<p>Some variables are actually declared as global - e.g. <code>game1</code>, <code>import_string</code>, etc. - since they are not contained inside a function. That is likely not an issue for a small application like this but in a larger application it would be wise to limit the scopes (e.g. inside an IIFE, DOM-loaded callback, etc. to avoid namespace collisions.</p>\n\n<hr>\n\n<p>The biggest thing I notice that is sub-optimal is this block:</p>\n\n<blockquote>\n<pre><code> for ( let row = 0; row <= 8; row++ ) {\n for ( let col = 0; col <= 8; col++ ) {\n sudoku_squares[row][col] = document.getElementsByClassName('sudoku')[0].getElementsByTagName('tbody')[0].getElementsByTagName('tr')[row].getElementsByTagName('td')[col].getElementsByTagName('input')[0];\n }\n}\n</code></pre>\n</blockquote>\n\n<p>Not only is that line inside the nested loop excessively long, but it means there are 81 DOM lookups just for the first element with class <em>sudoku</em>, plus DOM lookups for each of the child elements. </p>\n\n<p><a href=\"https://i.stack.imgur.com/ybMID.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ybMID.jpg\" alt=\"bridge toll\"></a></p>\n\n<blockquote>\n <p><em>”...DOM access is actually pretty costly - I think of it like if I have a bridge - like two pieces of land with a toll bridge, and the JavaScript engine is on one side, and the DOM is on the other, and every time I want to access the DOM from the JavaScript engine, I have to pay that toll”</em><br>\n - John Hrvatin, Microsoft, MIX09, in <a href=\"https://channel9.msdn.com/Events/MIX/MIX09/T53F\" rel=\"nofollow noreferrer\">this talk <em>Building High Performance Web Applications and Sites</em></a> at 29:38, also cited in the <a href=\"https://books.google.com/books?id=ED6ph4WEIoQC&pg=PA36&lpg=PA36&dq=John+Hrvatin+%22DOM%22&source=bl&ots=2Wrd5G2ceJ&sig=pjK9cf9LGjlqw1Z6Hm6w8YrWOio&hl=en&sa=X&ved=2ahUKEwjcmZ7U_eDeAhVMGDQIHSfUAdoQ6AEwAnoECAgQAQ#v=onepage&q=John%20Hrvatin%20%22DOM%22&f=false\" rel=\"nofollow noreferrer\">O'Reilly <em>Javascript</em> book by Nicholas C Zakas Pg 36</a>, as well as mentioned in <a href=\"https://www.learnsteps.com/javascript-increase-performance-by-handling-dom-with-care/\" rel=\"nofollow noreferrer\">this post</a></p>\n</blockquote>\n\n<p>One could simply add an <em>id</em> attribute to the table element and then access the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement/rows\" rel=\"nofollow noreferrer\"><code>rows</code></a> property instead of querying for the rows, and access the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableRowElement#Properties\" rel=\"nofollow noreferrer\"><code>cells</code></a> property of each row instead of querying for them. Another simplification would be to use <code>document.querySelectorAll()</code> with a selector like <code>.sudoku input</code> to get a collection of the inputs. </p>\n\n<hr>\n\n<p>Similar to PHP’s <code>foreach</code> loops, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\"><code>for..of</code> loops</a> could be used instead of the <code>for</code> loops to avoid having to manually increment the counter variables. </p>\n\n<p>Instead of blocks like this:</p>\n\n<pre><code>for ( let i = 0; i <= 8; i++ ) {\n if ( value == this.board[row][i] ) {\n return false;\n }\n}\n</code></pre>\n\n<p>simplify it like this:</p>\n\n<pre><code>for ( const cell of this.board[row]) {\n if ( value == cell ) {\n return false;\n }\n }\n</code></pre>\n\n<hr>\n\n<p>The method <code>blank_board_array</code> could be a static method since it doesn’t need to reference any state of the instance. The same could apply to some of the other helper functions. Additionally, <code>createArray()</code> could be used instead of <code>blank_board_array()</code>. And that could perhaps be simplified by utilizing <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill\" rel=\"nofollow noreferrer\"><code>Array.fill()</code></a>.</p>\n\n<hr>\n\n<p>Instead of using <code>let</code> for all block-scope variables, it is wise to default to using <code>const</code> to avoid accidental re-assignment. Then when you determine re-assignment is necessary use <code>let</code> (e.g. for counters, etc.).</p>\n\n<hr>\n\n<p>The mouse up event handler for the import button starts with this line:</p>\n\n<blockquote>\n<pre><code> import_string = document.getElementsByName(\"import_string\")[0].value\n</code></pre>\n</blockquote>\n\n<p>It would be simpler to add an <em>id</em> attribute to that element and then use <code>document.getElementById()</code> to reference it- that way there is no need to fetch a collection of elements just to get the first one.</p>\n\n<p>If all elements were wrapped in a <code><form></code> tag then that element could be referenced by <code>document.forms[0].import_string</code> but then you would have to ensure the form didn’t get submitted.</p>\n\n<p>Also it would likely be wise to use the <code>click</code> event instead of <code>mouseup</code> - that way if the user preferred using the keyboard to tab through elements it would allow pressing the <kbd>Enter</kbd> key to also trigger the event handler.</p>\n\n<hr>\n\n<p>The e.g. <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"nofollow noreferrer\">the spread syntax</a> could be used to transform this:</p>\n\n<blockquote>\n<pre><code>var args = Array.prototype.slice.call(arguments, 1);\n</code></pre>\n</blockquote>\n\n<p>To this:</p>\n\n<pre><code>const args = [...arguments].slice(1);\n</code></pre>\n\n<p>Or <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift\" rel=\"nofollow noreferrer\"><code>Array.shift()</code></a> could be used to take the first argument off the array, eliminating the need to call <code>slice()</code>.</p>\n\n<p>Or use destructuring assignment to assign those variables.</p>\n\n<pre><code>function createArray() {\n const [length = 0, ...remainingArgs] = arguments;\n var arr = new Array(length),\n i = length;\n if (remainingArgs.length) {\n while(i--) arr[length-1 - i] = createArray(...remainingArgs);\n }\n</code></pre>\n\n<hr>\n\n<p>There is one CSS rule containing <code>!important</code>:</p>\n\n<blockquote>\n<pre><code>.sudoku .thick_right {border-right:4px solid black !important;}\n</code></pre>\n</blockquote>\n\n<p>It is best to create a rule that is more specific than any others instead of using <code>!important</code>. </p>\n\n<blockquote>\n <p>When an important rule is used on a style declaration, this declaration overrides any other declarations. Although technically <code>!important</code> has nothing to do with specificity, it interacts directly with it. Using !important, however, is <strong>bad practice</strong> and should be avoided because it makes debugging more difficult by breaking the natural <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/Cascade\" rel=\"nofollow noreferrer\">cascading</a> in your stylesheets. When two conflicting declarations with the <code>!important</code> rule are applied to the same element, the declaration with a greater specificity will be applied.<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity#The_!important_exception\" rel=\"nofollow noreferrer\">1</a></sup></p>\n</blockquote>\n\n<p>There happen to be no other <code>border-right</code> rules that need to be overridden so that keyword can be removed here.</p>\n\n<hr>\n\n<p>The table rows and cells have class names like “1”, “2”. I don't see any CSS or JavaScript that utilizes those class names. While \"CSS2.1 it is a recommendation, even in CSS3\"<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS\" rel=\"nofollow noreferrer\">2</a></sup> class names should not start with a number:</p>\n\n<blockquote>\n <p>Property names and <a href=\"https://www.w3.org/TR/css-syntax-3/#at-rule\" rel=\"nofollow noreferrer\">at-rule</a> names are always <a href=\"https://www.w3.org/TR/css-syntax-3/#identifier\" rel=\"nofollow noreferrer\">identifiers</a>, which have to start with a letter or a hyphen followed by a letter, and then can contain letters, numbers, hyphens, or underscores. You can include any <a href=\"https://www.w3.org/TR/css-syntax-3/#code-point\" rel=\"nofollow noreferrer\">code point</a> at all, even ones that CSS uses in its syntax, by <a href=\"https://www.w3.org/TR/css-syntax-3/#escape-codepoint\" rel=\"nofollow noreferrer\">escaping</a> it.<sup><a href=\"https://www.w3.org/TR/css-syntax-3/#syntax-description\" rel=\"nofollow noreferrer\">3</a></sup></p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T19:55:27.127",
"Id": "469500",
"Score": "3",
"body": "Thank you so much for the detailed feedback. I will spend today refactoring my code to incorporate these suggestions. I love Code Review - people are nicer than on Stack Overflow, and the answers are incredibly helpful : )"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T04:41:05.833",
"Id": "469509",
"Score": "0",
"body": "What other ES6 features could I potentially use? You mention this in line 1 of your answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T17:37:21.233",
"Id": "469641",
"Score": "1",
"body": "I updated the answer to mention more examples"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T21:33:22.110",
"Id": "469667",
"Score": "0",
"body": "You're a legend. Thank you for adding that. I've incorporated a lot of your suggestions into the latest fiddle - https://jsfiddle.net/AdmiralAkbar2/z6rv70h4/226/ . I will continue incorporating suggestions from this code review, and perhaps post a part 2 in a week or two."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T14:07:19.583",
"Id": "469769",
"Score": "1",
"body": "Nice - I added some notes about CSS as well"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T17:12:41.223",
"Id": "239371",
"ParentId": "239248",
"Score": "2"
}
},
{
"body": "<p>To add to existing review a few points I noticed:</p>\n\n<ul>\n<li>You are mixing up under_score (<code>clear_webpage_board</code>) and camelCase naming (<code>createArray</code>). Typically functions in javascript use camelCase (you can see that in all built-in methods that you use, including the borrowed <code>createArray</code>).</li>\n<li>Css on the other hand typically uses naming, where dash is used, so <code>thick-right</code>, not <code>thick_right</code>. Ye it's a bit annoying that every technology has different convention naming.</li>\n<li>I don't like your namings very much. <code>print_sudoku_to_webpage</code>. That method sychronizes your data with html elements, that represent it. I would call it maybe <code>displayBoard</code> or something (since you call it \"board\" in another function. <code>print</code> feels off, you don't print anything. <code>webpage</code> also (duh, you are on a webpage, we know that). <code>clear_webpage_board</code> again drop <code>webpage</code>, no point.</li>\n<li>How to use your code if I wanted more sudoku boards on one page? It wouldn't work, because you are always looking for first element with class \"sudoku\". It feels like there should be one class representing <code>Sudoku</code>, independent from HTML (you have that) and then there should be another class, that can display it in UI, handle events and pass those events to game itself. That class can know this \"root element\" with class \"sudoku\" and look for rest of pieces inside of it using <code>querySelector</code> as our colleague in other answer mentioned. That would also clean all your cycles and code, that doesn't have function anywhere. </li>\n<li>Consider extracting repeating strings to constants - that will help avoiding bugs. If you make typo mistake in one place but not another, sometimes it's hard to debug. Same goes for numbers - that would also make it easier to generate sudoku with different dimensions.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T23:07:51.487",
"Id": "470166",
"Score": "0",
"body": "Thanks for the feedback. I'll change my variable names and shorten the verbose method names. I probably won't refactor the code to print multiple sudoku boards on the same page, it would increase complexity and is not a feature I am likely to use. YAGNI. I'll probably post a part 2 in a week or two."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T08:03:51.663",
"Id": "470205",
"Score": "0",
"body": "Up to you, depends what do you want from the project. I don't see it as YAGNI. I see it as practice of SRP and separating of concerns. Either way keep up the good work, good luck!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T10:46:46.913",
"Id": "470213",
"Score": "0",
"body": "Maybe you're right. What's the best way to implement this? I'd have to replace all my HTML ID's with classes right? Then have the user put something like <div class=\"sudoku\"></div> in their HTML, and my code would insert the Sudoku there, correct? How would I keep track of each unique div/sudoku since it doesn't have an ID? Feel free to edit your answer if you need more space. Thanks for your help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T10:48:16.347",
"Id": "470215",
"Score": "0",
"body": "By the way, more up to date fiddle here. https://jsfiddle.net/AdmiralAkbar2/z6rv70h4/229/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-01T07:17:40.953",
"Id": "470275",
"Score": "0",
"body": "Pass \"root\" element (ex your `.sudoku` div) to HTML rendering class. If you wanna keep track of it all root elements, you do it outside of your sudoku classes. HTML rendering class doesn't need to care about IDs, other roots etc. Try to separate concerns and make classes as simple as possible :-)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T23:06:00.243",
"Id": "239383",
"ParentId": "239248",
"Score": "5"
}
},
{
"body": "<p>Let's start with some convention things, in JS we (everyone) write function and variable names as camel case.</p>\n\n<p>I see you have a comment that you tried to use a setter, the issue is that you would then want to use it in two ways. You would want to write this.board = import_string to call the setter, but in the constructor you do </p>\n\n<p><code>this.board = this.blank_board_array();</code></p>\n\n<p>You could use a setter with some rewriting, but I think it's fine as is.</p>\n\n<p>The double equals in JS <code>==</code> coerces the types, so that for example <code>0==[]</code> is true, while this can be useful, in my experience it fits squarely in the realm of being too clever, or of things working coincidentally. I would advise you always use <code>===</code> which does not coerce types (but controversially to my colleagues I write lines like <code>if (x === false)</code>, some say this is a step too far).</p>\n\n<p>I would suggest that it would be nicer to have functions which create an html Sudoku board, i.e. rather than target elements that happen to be there, you can make the elements with JS and then add a single element (with many children) at the end, if you do this you can also tidy up the logic of setting up the event listeners a lot too.</p>\n\n<p>In general there's been a trend (at least in my experience working) towards writing quite functional code in JS. Your stuff is far removed from that, not really a problem, just something to be aware of. </p>\n\n<p>It's a bit hard to give an example without just rewriting everything, but for instance (though the example I will give is still not very functional) several times you loop over a 2D array, you could write a function loopOverMatrix(matrix, f) which takes a 2D array and a function f (i, j) => {...}, and loops over all the elements [i][j] and calls f(i)(j). </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T23:27:25.650",
"Id": "470167",
"Score": "0",
"body": "\"if you do this you can also tidy up the logic of setting up the event listeners a lot too.\" I'd be willing to try this. What's your idea? Can you give an example?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T00:11:33.743",
"Id": "470171",
"Score": "0",
"body": "By the way, here's the current code. I moved all the listeners into a DOMContentLoaded listener. https://jsfiddle.net/AdmiralAkbar2/z6rv70h4/229/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T23:04:55.597",
"Id": "470249",
"Score": "1",
"body": "Sure, here I wrote an example of what I mean https://jsfiddle.net/y5j92eno/3/. Now you could just use the sudoku variable to do manipulations, better yet, you could add more properties to the object you pass into makeSudokuGrid to better initialise it. Regarding your code now, I write OOP code (in other languages) so know something of it, and from that perspective it's great, and what you're doing is just generally well done. But I would strongly advise that if learning JS is for more than just fun that you try doing things in the more functional way."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T23:11:09.777",
"Id": "239384",
"ParentId": "239248",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "239371",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T20:47:48.950",
"Id": "239248",
"Score": "5",
"Tags": [
"javascript",
"html",
"css",
"ecmascript-6",
"sudoku"
],
"Title": "Sudoku game in JavaScript"
} | 239248 |
<p><a href="https://leetcode.com/problems/sliding-window-median/" rel="nofollow noreferrer">https://leetcode.com/problems/sliding-window-median/</a></p>
<blockquote>
<p>Median is the middle value in an ordered integer list. If the size of
the list is even, there is no middle value. So the median is the mean
of the two middle value.</p>
<p>Examples: [2,3,4] , the median is 3</p>
<p>[2,3], the median is (2 + 3) / 2 = 2.5</p>
<p>Given an array nums, there is a sliding window of size k which is
moving from the very left of the array to the very right. You can only
see the k numbers in the window. Each time the sliding window moves
right by one position. Your job is to output the median array for each
window in the original array.</p>
<p>For example, Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.</p>
</blockquote>
<p><a href="https://i.stack.imgur.com/97ecy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/97ecy.png" alt="enter image description here"></a></p>
<blockquote>
<p>Therefore, return the median sliding window as [1,-1,-1,3,5,6].</p>
<p>Note: You may assume k is always valid, ie: k is always smaller than
input array's size for non-empty array. Answers within 10^-5 of the
actual value will be accepted as correct.</p>
</blockquote>
<p>Please review for performance. also I am not sure about GetID function is there a smarter way to get the same result of unique number and sorting for median? </p>
<pre><code>using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace TreeQuestions
{
/// <summary>
/// https://leetcode.com/problems/sliding-window-median/
/// </summary>
[TestClass]
public class SlidingWindowMedianTest
{
[TestMethod]
public void ExampleTest()
{
int[] nums = { 1, 3, -1, -3, 5, 3, 6, 7 };
int k = 3;
double[] expected = { 1, -1, -1, 3, 5, 6 };
double[] res = SlidingWindowMedian.MedianSlidingWindow(nums, k);
CollectionAssert.AreEqual(expected, res);
}
[TestMethod]
public void ExampleTestFailed()
{
int[] nums = { 1, 4, 2, 3 };
int k = 4;
double[] expected = { 2.5 };
double[] res = SlidingWindowMedian.MedianSlidingWindow(nums, k);
CollectionAssert.AreEqual(expected, res);
}
[TestMethod]
public void ExampleTestOverFlow()
{
int[] nums = { 2147483647, 2147483647 };
int k = 2;
double[] expected = { 2147483647.0 };
double[] res = SlidingWindowMedian.MedianSlidingWindow(nums, k);
CollectionAssert.AreEqual(expected, res);
}
[TestMethod]
public void ExampleFailed2()
{
int[] nums = { 5, 2, 2, 7, 3, 7, 9, 0, 2, 3 };
int k = 9;
double[] expected = { 3.0, 3.0 };
double[] res = SlidingWindowMedian.MedianSlidingWindow(nums, k);
CollectionAssert.AreEqual(expected, res);
}
}
public class SlidingWindowMedian
{
public static double[] MedianSlidingWindow(int[] nums, int k)
{
var res = new List<double>();
var med = new SortedList<long, int>();
for (int i = 0; i < nums.Length; i++)
{
med.Add(GetId(i, nums), nums[i]);
if (med.Count > k)
{
med.Remove(GetId(i - k, nums));
}
if (med.Count == k)
{
if (k % 2 == 0)
{
res.Add( ((long)med[med.Keys[k / 2 - 1]] + med[med.Keys[k / 2]])/2.0 );
}
else
{
res.Add(med[med.Keys[k / 2]]);
}
}
}
return res.ToArray();
}
private static long GetId(int i, int[] nums)
{
return Convert.ToInt64(nums[i]) * nums.Length + i;
}
}
}
</code></pre>
| [] | [
{
"body": "<p>Your ID is a <code>long</code> created from 2 <code>int</code>s, so you can fit both <code>int</code>s inside this one <code>long</code> side by side:</p>\n\n<pre><code>long key = (long)nums[i] << 32 | i;\n</code></pre>\n\n<hr>\n\n<p>You have a lot of unnecessary <code>if</code> statement evaluations. You could get rid of them by adding the first <code>k</code> elements from the array into the list in a separate loop, and then starting a second loop from <code>i = k</code> that can safely do <code>med.Remove</code> and <code>med.Add</code> without <code>if</code>s.</p>\n\n<p><code>k</code> never changes, so instead of evaluating <code>k % 2 == 0</code> and <code>k / 2</code> and <code>k / 2 - 1</code> in every iteration, you can store the final value in a variable before the loop begins. Then in the loop you only need to call</p>\n\n<pre><code>res.Add(med[med.Keys[medianIndex]]);\n</code></pre>\n\n<p>or</p>\n\n<pre><code>res.Add( ((long)med[med.Keys[medianIndex]] + med[med.Keys[medianIndex2]])/2.0 );\n</code></pre>\n\n<hr>\n\n<p>Making <code>res</code> a list and in the end converting it into an array slows your code down a lot. You can make it an array (of size <code>nums.Length - k + 1</code>). Lists come with the overhead of their extra functionality, so you waste time not only on the conversion to an array but also on every time you add a number to the list.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T10:18:10.443",
"Id": "239266",
"ParentId": "239252",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "239266",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T22:43:38.000",
"Id": "239252",
"Score": "3",
"Tags": [
"c#",
"programming-challenge"
],
"Title": "LeetCode: Sliding Window Median C#"
} | 239252 |
<p>I've taken up <a href="https://twitch.tv/aaronchall" rel="noreferrer">code streaming</a> and I'm concerned that as I do so, I'll leak an API token somewhere.</p>
<p>It was suggested that I use something like "a secrets.toml or secrets.yaml or secrets.json file." But I don't want it all in one file. If I did have a leak, I'd likely lose all my tokens at once.</p>
<p>So I considered a secrets directory, where each file holds each API's token. But what if I accidentally cat the file to the screen?</p>
<p>So I wanted to encrypt the tokens. Because I'm a bit obsessive about these kinds of things. I wouldn't call this encryption, but it is obfuscation, and I think it improves my op-sec quite a bit and it makes me feel a bit better about not leaking api tokens.</p>
<p>I'm using Python, and specifically the following functions and the Path object from the standard library. <code>randbits</code> will give me as close to cryptographically strong random 0s and 1s as one can get from the Python standard library. <code>getpass</code> will hide the token if I happen to paste it there. And <code>Path</code> objects are amazing for dealing with file paths.</p>
<pre class="lang-py prettyprint-override"><code>from sys import argv
from secrets import randbits
from pathlib import Path
from getpass import getpass
from tempfile import mkdtemp
_USAGE = """usage:
python -m py.token "api name"
python -m py.token --test
"""
def main():
if len(argv) == 2:
if argv[1] == '--test':
test()
else:
try:
print(Manager().get_token(argv[1]))
except:
print(_USAGE)
raise
else:
print(_USAGE)
</code></pre>
<p>As the <code>main()</code> foreshadows, to manage it all I have a <code>Manager</code> class that can save the tokens and update them, update all of them with a new mask, and for regular usage, to get api tokens:</p>
<pre class="lang-py prettyprint-override"><code>class Manager:
def __init__(self, root=Path.home()):
self.passtoken_dir = root / 'pass'
self.secrets_dir = self.passtoken_dir / 'secrets'
self.ptfile = self.passtoken_dir / 'token'
self.create_dirs_and_mask()
def create_dirs_and_mask(self):
self.passtoken_dir.mkdir(exist_ok=True)
self.secrets_dir.mkdir(exist_ok=True)
if not self.ptfile.is_file():
self.ptfile.write_bytes(new_passtoken())
else:
# just realized this print() won't work for command line usage.
print('we have a mask file already.')
def save_token(self, api_name='', token=b''):
if not api_name:
api_name = input('api name: ')
if not token:
token = bytes(getpass('input token (hidden): '), 'utf8')
file = self.secrets_dir / api_name
file.write_bytes(mask(token, self.ptfile.read_bytes()))
def update_mask_and_masked_tokens(self):
old_pt = self.ptfile.read_bytes()
new_pt = new_passtoken()
for file in self.secrets_dir.iterdir():
token = unmask(file.read_bytes(), old_pt)
file.write_bytes(mask(token, new_pt))
self.ptfile.write_bytes(new_pt)
def get_token(self, api_name) -> bytes:
return unmask((self.secrets_dir/api_name).read_bytes(),
self.ptfile.read_bytes())
</code></pre>
<p>I like having the <code>create_dirs_and_mask</code> method separate for the possibility of overriding for test purposes, but I didn't go in that direction for testing.</p>
<p>The above Manager object relies heavily on these utility functions to obfuscate and convert from bytes to ints and back.</p>
<pre class="lang-py prettyprint-override"><code>def new_passtoken() -> bytes:
return int_to_bytes(randbits(8*256))
def bytes_to_int(token) -> int:
return int.from_bytes(token, 'big')
def int_to_bytes(integer) -> bytes:
# wish we didn't have to implement ourselves...
result = []
while integer:
result.append(integer & 255)
integer >>= 8
return bytes(reversed(result))
def mask(token: bytes, passtoken: bytes) -> bytes:
return int_to_bytes(bytes_to_int(token)
^ bytes_to_int(passtoken))
def unmask(masked_token: bytes, passtoken: bytes) -> bytes:
return int_to_bytes(bytes_to_int(masked_token)
^ bytes_to_int(passtoken))
</code></pre>
<p>I first implemented mask and unmask with multiply and integer division instead of xor, but it seemed to me that if a leak happened there would be a greater chance of inferring the components of the calculation.</p>
<p>This is all one module, and I haven't yet put the tests in
a test module. Tests do pass:</p>
<pre class="lang-py prettyprint-override"><code>def test(): # TODO put tests in a test package
"""test that functions round-trip
and manager can save, get, update, and still get.
"""
from shutil import rmtree
token = b'abc123}|{'
assert token == int_to_bytes(bytes_to_int(token))
passtoken = b'passtoken'
assert token == unmask(mask(token, passtoken), passtoken)
root = Path(mkdtemp())
try:
manager = Manager(root=root)
api = 'any api'
manager.save_token(api, token)
assert manager.get_token(api) == token
manager.update_mask_and_masked_tokens()
assert manager.get_token(api) == token
globals().update(locals())
finally:
rmtree(root)
</code></pre>
<p>For the command line usage, we call the main when we're the entry point for the program:</p>
<pre class="lang-py prettyprint-override"><code>if __name__ == '__main__':
main()
</code></pre>
<p>Please review! I'm especially looking for suggestions that upgrade my attempts at "encryption" without putting a reliance on a third-party library, unless it is quite stable, seasoned, and expected to continue to be in service for the foreseeable future.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T21:07:32.440",
"Id": "469370",
"Score": "0",
"body": "How about you store it in the cloud? I'm currently using [Azure App Configuration](https://docs.microsoft.com/en-us/azure/azure-app-configuration/) for this sort of thing and it has radically improved virtually every aspect of my development process. Data is encrypted by default, values that need to be kept even more secure can be put into an associated key vault, one can use the same exact configuration for local development, continuous integration, and production... I just love it! Anything that speaks REST is compatible but some frameworks (such as DotNet and Java) have first class support."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T23:54:37.210",
"Id": "469376",
"Score": "0",
"body": "You can cat-proof your files using terminal escape codes (plus a lot of leading newlines in case you accidentally open them in an editor).\n\nOr just store them all in a DB."
}
] | [
{
"body": "<pre><code>def int_to_bytes(integer) -> bytes:\n # wish we didn't have to implement ourselves...\n result = []\n while integer:\n result.append(integer & 255)\n integer >>= 8\n return bytes(reversed(result))\n</code></pre>\n\n<p>Your wish has been granted; you don't have to implement it yourself:</p>\n\n<pre><code>def int_to_bytes(integer) -> bytes:\n return integer.to_bytes((integer.bit_length() + 7) // 8, 'big')\n</code></pre>\n\n<p>Note: <a href=\"https://docs.python.org/3/library/stdtypes.html?highlight=bit_length#int.bit_length\" rel=\"noreferrer\"><code>int.bit_length()</code></a> is the length of the value in bits. We must divide this by 8 to yield the required number of bytes, but we must not lose any fractions of a byte, so we add 7 to the number of bits first. For example: If a number requires 81 bits, (10.125 bytes, or 1 bit more than 10 bytes), adding 7 will increase this to 88 bits, which integer-divided by 8 gives 11, as required. <a href=\"https://docs.python.org/3/library/stdtypes.html?highlight=bit_length#int.to_bytes\" rel=\"noreferrer\"><code>int.to_bytes(num_bytes, 'big')</code></a> will then result in the correct <code>bytes</code> result.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T00:57:22.890",
"Id": "239257",
"ParentId": "239254",
"Score": "10"
}
},
{
"body": "<ol>\n<li>Your <code>main</code> is a classic arrow anti-pattern. You can use guard clauses to make the code flat and easier to understand.</li>\n<li>Bare excepts are normally not a good idea. Why would you want to print the usage if the code works fine but the user passes a keyboard interrupt? You may want to use <code>except Exception:</code>.</li>\n<li><p>I would prefer if <code>mask</code> and <code>unmask</code> were wrapped up in a class. I personally would leave them as static methods.</p>\n\n<p>This has the benefit that your <code>Manager</code> can be later changed to use any encryption. As long as there's an object that defines an <code>encrypt</code> and a <code>decrypt</code> method.</p></li>\n<li><p>Functions like <code>create_dirs_and_mask</code> are normally a really large red flag, to me, signalling that your constructor is doing too much.</p>\n\n<p>Your constructor is doing quite a lot, building three paths from root, building two directories, building a file if it doesn't exist, printing to the end user if a file already exists.</p>\n\n<p>Not only does this clearly break <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"noreferrer\">SRP</a>, it's needlessly locking down customizability of the class and making it more annoying to test.</p>\n\n<p>Just move the fancy bits into a class method and leave the constructor to be as dumb as possible.</p></li>\n<li><p>The name <code>update_mask_and_masked_tokens</code> is a mouthful and a half. I would just change this to be the setter of the token property.</p>\n\n<p>Since the function currently doesn't take an argument I would move the <code>new_passtoken()</code> call out of the method and as an argument.</p></li>\n<li><p>You have a confusing and useless line <code>masked = mask</code>.</p></li>\n<li><p>I would change <code>Manager</code> to act like a dict - changing <code>save_token</code> to <code>__setitem__</code>.</p>\n\n<p>Changing it to have the same interface as a dict allows for you to easily swap this out for a plain old dictionary to easily test code that uses this. It also ensures that you don't break SRP by adding bells or whistles that don't belong on Manager. For example <code>save_token</code> is currently merging business logic with its user interface, a generally pretty poor design choice.</p></li>\n<li>The special bells and whistles added to <code>Manager.save_token</code> are currently not used, you may want to follow YAGNI and just scrap that part of your code. Alternately you can expose the functionality as an external function.</li>\n<li>I'm not a fan of <code>python -m py.token --test</code>. I personally would just drop it as an option and use pytest.</li>\n<li>Rather than <code>mkdtemp</code> I would use <code>TemporaryDirectory</code> and use it as a context manager. This would remove the need to import <code>shutil.rmtree</code>.</li>\n</ol>\n\n<pre class=\"lang-py prettyprint-override\"><code>from sys import argv\nfrom secrets import randbits\nfrom pathlib import Path\nfrom getpass import getpass\nfrom tempfile import TemporaryDirectory\n\n_USAGE = \"\"\"usage:\n python -m py.token \"api name\"\n python -m py.token --test\n\"\"\"\n\n\ndef main():\n if len(argv) != 2:\n print(_USAGE)\n return\n\n if argv[1] == '--test':\n test()\n return\n\n try:\n manager = TokenManager.load(new_passtoken)\n print(manager[argv[1]])\n except Exception:\n print(_USAGE)\n raise\n\n\nclass Mask:\n @staticmethod\n def encrypt(token: bytes, passtoken: bytes) -> bytes:\n return int_to_bytes(bytes_to_int(token)\n ^ bytes_to_int(passtoken))\n\n @staticmethod\n def decrypt(masked_token: bytes, passtoken: bytes) -> bytes:\n return int_to_bytes(bytes_to_int(masked_token)\n ^ bytes_to_int(passtoken))\n\n\nclass TokenManager:\n def __init__(self, token_file, secrets_dir, crypto):\n secrets_dir.mkdir(exist_ok=True)\n self._secrets_dir = secrets_dir\n self._token_file = token_file\n self._token = token_file.read_bytes()\n self._crypto = crypto\n\n @classmethod\n def load(cls, new_token=None, crypto=Mask, root=Path.home()):\n base = root / 'pass'\n base.mkdir(exist_ok=True)\n secrets = base / 'secrets'\n token = base / 'token'\n if not token.exists():\n if new_token is None:\n raise ValueError('No existing token exists')\n token.write_bytes(new_token())\n return cls(token, secrets, crypto)\n\n def __getitem__(self, api) -> bytes:\n encrypted = (self._secrets_dir / api).read_bytes()\n return self._crypto.decrypt(encrypted, self.token)\n\n def __setitem__(self, api, token) -> None:\n encrypted = self._crypto.encrypt(token, self.token)\n (self._secrets_dir / api).write_bytes(encrypted)\n\n @property\n def token(self) -> bytes:\n return self._token\n\n @token.setter\n def token(self, token) -> None:\n for file in self._secrets_dir.iterdir():\n token_ = self._crypto.decrypt(file.read_bytes(), self.token)\n encrypted = self._crypto.encrypt(token_, token)\n file.write_bytes(encrypted)\n self._token = token\n self._token_file.write_bytes(token)\n\n\ndef new_passtoken() -> bytes:\n return int_to_bytes(randbits(8*256))\n\n\ndef bytes_to_int(token) -> int:\n return int.from_bytes(token, 'big')\n\n\ndef int_to_bytes(integer) -> bytes:\n # wish we didn't have to implement ourselves...\n result = []\n while integer:\n result.append(integer & 255)\n integer >>= 8\n return bytes(reversed(result))\n\n\ndef save_token(manager, api_name='', token=b''):\n if not api_name:\n api_name = input('api name: ')\n if not token:\n token = bytes(getpass('input token (hidden): '), 'utf8')\n manager[api_name] = token\n\n\ndef test():\n token = b'abc123}|{'\n assert token == int_to_bytes(bytes_to_int(token))\n passtoken = b'passtoken'\n assert token == Mask.decrypt(Mask.encrypt(token, passtoken), passtoken)\n with TemporaryDirectory() as tmp_dir:\n manager = TokenManager.load(new_passtoken, crypto=Mask, root=Path(tmp_dir))\n api = 'any api'\n manager[api] = token\n assert manager[api] == token\n manager.token = new_passtoken()\n assert manager[api] == token\n globals().update(locals())\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T04:49:56.917",
"Id": "469329",
"Score": "0",
"body": "Unequivocally agree with 1, 6, 9, and 10. 2, mostly agree, but I immediately reraise. 3 makes sense on further thought. 4, IDK about SRP, but the rest makes sense. 5, token's setter is doing a lot - I'm reticent to have something that looks like an attribute write to the disk on setting. 7, I expected to use save_token on a Python shell (though at this point, I'm so close, I may as well implement command line option to set and to update all.) 8. similar objection to property - don't want it to look like a dict because writing to disk. You put a lot of effort into this, and I appreciate it. +1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T05:36:33.697",
"Id": "469330",
"Score": "0",
"body": "@AaronHall 4 I find SRP, and other principles, to act as a signals for other problems. 5 & 8 I have come across those arguments before; I think this comes down to taste. I prefer sugar, you prefer purity. 7 Sounds reasonable, I can't really comment on this any more than I have. You may, or may not, be interested in [`cmd`](https://docs.python.org/3/library/cmd.html)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T03:05:31.413",
"Id": "239261",
"ParentId": "239254",
"Score": "14"
}
},
{
"body": "<p>You also have an operational problem as much as a code problem. Any tokens you use for a public demonstration should - </p>\n\n<ol>\n<li>Be as least-privileged as possible (eg grant READ access instead of CRUD or full admin)</li>\n<li>Be tied to demo/test/dev environments where possible (I pray you are not doing code streaming in PROD)</li>\n<li>Expired/rotated/destroyed frequently and aggressively (Terminate the token when your stream is done, set shorter timeouts so it expires for you)</li>\n<li>Audited for improper use (check your logs and set alerts for unexpected use)</li>\n<li>Access controlled in addition to the token where possible (whitelist IP, mutual TLS, etc). </li>\n</ol>\n\n<p>The code is an interesting exercise and the reviews will help. However what prevents some other debugging operation from exposing a token in a header or log or step-wise debugging operation? You can expose a token in a log or <code>tcpdump</code> just as easily as with <code>cat</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T17:33:27.293",
"Id": "239327",
"ParentId": "239254",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-21T23:47:08.230",
"Id": "239254",
"Score": "10",
"Tags": [
"python",
"object-oriented",
"unit-testing",
"cryptography"
],
"Title": "Secrets management, operational security, keeping API tokens hidden while streaming"
} | 239254 |
<p>I'm learning python and for educational purposes I implemented <a href="https://github.com/lukascode/tar-parser" rel="nofollow noreferrer">tar archive parser</a>. I'm not beginner programmer. I would like to receive some feedback and tips about code, what can I improve, what could be done better and so on. </p>
<p>Implementation:</p>
<p><strong>tar.py</strong></p>
<pre><code>#!/usr/bin/env python3
import io
import os
import sys
import math
import json
class Tar:
BLOCK_SIZE = 512
def __init__(self, file_path):
if not file_path or len(file_path) == 0:
raise ValueError("Bad file path")
self.file_path = file_path
def __enter__(self):
self.input_stream = open(self.file_path, "rb")
self.headers = []
return self
def __exit__(self, type, value, traceback):
self.close()
def close(self):
if self.input_stream:
self.input_stream.close()
def get_all_files(self):
self.__scan()
return list(map(
lambda f: FileSnapshot(f.file_name, f.file_size, f.file_mode, f.flag),
self.headers
))
def extract_file(self, file_name, target_folder=os.getcwd()):
if not file_name or len(file_name) == 0:
raise ValueError("Bad file name")
if not target_folder or len(target_folder) == 0:
raise ValueError("Bad target folder")
self.__scan()
result = list(filter(
lambda fh: fh.flag == 0 and fh.file_name == file_name,
self.headers
))
if len(result) == 0:
raise RuntimeError("File '{}' not found".format(file_name))
fh = result[0]
leaf = os.path.basename(fh.file_name)
f_path = os.path.join(target_folder, leaf)
self.__extract(fh, f_path)
def extract_all(self, target_folder=os.getcwd()):
if not target_folder or len(target_folder) == 0:
raise ValueError("Bad target folder")
self.__scan()
for fh in self.headers:
f_path = os.path.join(target_folder, fh.file_name)
if fh.flag == 5: # if directory
os.makedirs(f_path, exist_ok=True)
elif fh.flag == 0: # if regular file
parent = os.path.dirname(os.path.abspath(f_path))
os.makedirs(parent, exist_ok=True)
self.__extract(fh, f_path)
def __extract(self, fh, file_name):
with open(file_name, "wb") as f:
if fh.file_size > 0:
total = 0
bytes_left = fh.file_size
self.input_stream.seek(fh.offset, 0)
while bytes_left > 0:
data = self.input_stream.read(Tar.BLOCK_SIZE)
data = data[:bytes_left]
f.write(data)
bytes_left -= len(data)
def __scan(self): # iterate over headers
if len(self.headers) == 0:
while True:
block = self.input_stream.read(Tar.BLOCK_SIZE)
if len(block) < Tar.BLOCK_SIZE:
break
h = self.__get_file_header(block)
if not len(h.magic) > 0:
break
# ommit regular file bytes
if h.flag == 0:
h.set_offset(self.input_stream.tell())
if h.file_size > 0:
if h.file_size % Tar.BLOCK_SIZE != 0:
bytes_to_skeep = math.ceil(h.file_size / Tar.BLOCK_SIZE) * Tar.BLOCK_SIZE
else:
bytes_to_skeep = h.file_size
self.input_stream.seek(bytes_to_skeep, 1)
self.headers.append(h)
def __get_file_header(self, block):
try:
file_name = self.__get_file_name(block)
file_mode = self.__get_file_mode(block)
uid = self.__get_uid(block)
gid = self.__get_gid(block)
file_size = self.__get_file_size(block)
mtime = self.__get_mtime(block)
chksum = self.__get_chksum(block)
type_flag = self.__get_type_flag(block)
linkname = self.__get_linkname(block)
magic = self.__get_magic(block)
version = self.__get_version(block)
uname = self.__get_uname(block)
gname = self.__get_gname(block)
devmajor = self.__get_devmajor(block)
devminor = self.__get_devminor(block)
prefix = self.__get_prefix(block)
except Exception as e:
raise RuntimeError("Broken file") from e
header = FileHeader(file_name, file_size, file_mode, uid, gid,
mtime, chksum, type_flag, linkname, magic, version,
uname, gname, devmajor, devminor, prefix)
return header
def __get_file_name(self, block): # string
offset, size = 0, 100
fname = self.__get_block_data(block, offset, size)
fname = fname[0:fname.find(b'\x00')].decode().strip()
return fname
def __get_file_mode(self, block): # string
offset, size = 100, 8
mode = self.__get_block_data(block, offset, size)
mode = mode[:mode.find(b'\x00')].decode().strip()
return mode
def __get_uid(self, block): # string
offset, size = 108, 8
uid = self.__get_block_data(block, offset, size)
uid = uid[:uid.find(b'\x00')].decode().strip()
return uid
def __get_gid(self, block): # string
offset, size = 116, 8
gid = self.__get_block_data(block, offset, size)
gid = gid[:gid.find(b'\x00')].decode().strip()
return gid
def __get_file_size(self, block): # int
offset, size = 124, 12
size = self.__get_block_data(block, offset, size)
size = size[:size.find(b'\x00')].decode().strip()
if len(size) > 0:
size = int(size, 8)
else:
size = 0
return size
def __get_mtime(self, block): # int
offset, size = 136, 12
mtime = self.__get_block_data(block, offset, size)
mtime = mtime[:len(mtime)-1]
mtime = mtime[:mtime.find(b'\x00')].decode().strip()
if len(mtime) > 0:
mtime = int(mtime, 8)
else:
mtime = 0
return mtime
def __get_chksum(self, block): # int
offset, size = 148, 8
chksum = self.__get_block_data(block, offset, size)
chksum = chksum[:chksum.find(b'\x00')].decode().strip()
if len(chksum) > 0:
chksum = int(chksum)
else:
chksum = 0
return chksum
def __get_type_flag(self, block): # int
offset, size = 156, 1
flag = self.__get_block_data(block, offset, size)
if flag == b'\x00':
flag = 0
elif flag == b'x':
flag = 11
else:
flag = int(flag)
return flag
def __get_linkname(self, block): # string (applicable if type_flag = 1 or 2)
offset, size = 157, 100
linkname = self.__get_block_data(block, offset, size)
return linkname[:linkname.find(b'\x00')].decode().strip()
def __get_magic(self, block): # string
offset, size = 257, 6
magic = self.__get_block_data(block, offset, size)
magic = magic[:magic.find(b'\x00')].decode().strip()
return magic
def __get_version(self, block): # string
offset, size = 263, 2
version = self.__get_block_data(block, offset, size)
version = version[:len(version)-1].decode().strip()
return version
def __get_uname(self, block): # string
offset, size = 265, 32
uname = self.__get_block_data(block, offset, size)
uname = uname[:uname.find(b'\x00')].decode().strip()
return uname
def __get_gname(self, block): # string
offset, size = 297, 32
gname = self.__get_block_data(block, offset, size)
gname = gname[:gname.find(b'\x00')].decode().strip()
return gname
def __get_devmajor(self, block): # string
offset, size = 329, 8
devmajor = self.__get_block_data(block, offset, size)
devmajor = devmajor[:devmajor.find(b'\x00')].decode().strip()
return devmajor
def __get_devminor(self, block): # string
offset, size = 337, 8
devminor = self.__get_block_data(block, offset, size)
devminor = devminor[:devminor.find(b'\x00')].decode().strip()
return devminor
def __get_prefix(self, block): # string
offset, size = 345, 155
prefix = self.__get_block_data(block, offset, size)
prefix = prefix[:prefix.find(b'\x00')].decode().strip()
return prefix
def __get_block_data(self, block, offset, size):
return block[offset:offset+size]
class FileSnapshot:
def __init__(self, file_name, file_size, file_mode, flag):
self.file_name = file_name
self.file_size = file_size
self.file_mode = file_mode
self.flag = flag
def __repr__(self):
return self.file_name
class FileHeader:
def __init__(self, file_name, file_size, file_mode, uid, gid, mtime,
chksum, flag, linkname, magic, version, uname, gname, devmajor, devminor, prefix):
self.file_name = file_name
self.file_size = file_size
self.file_mode = file_mode
self.uid = uid
self.gid = gid
self.mtime = mtime
self.chksum = chksum
self.flag = flag
self.linkname = linkname
self.magic = magic
self.version = version
self.uname = uname
self.gname = gname
self.devmajor = devmajor
self.devminor = devminor
self.prefix = prefix
def set_offset(self, offset):
self.offset = offset
def usage():
u = """
Usage:
tar.py <archive.tar> --list List all files in the archive
tar.py <archive.tar> --extract-all Extract all files from the archive
tar.py <archive.tar> --extract <file> Extract single file from the archive
"""
print(u)
sys.exit(1)
if __name__ == "__main__":
try:
if len(sys.argv) > 2:
archive = sys.argv[1]
operation = sys.argv[2]
with Tar(archive) as t:
if operation == "--list":
files = t.get_all_files()
for f in files:
print(f)
elif operation == "--extract-all":
t.extract_all()
elif operation == "--extract":
if len(sys.argv) > 3:
file_name = sys.argv[3]
t.extract_file(file_name)
else:
usage()
else:
usage()
except Exception as e:
print("Error: {}".format(str(e)))
sys.exit(1)
</code></pre>
<p><strong>tartest.py</strong></p>
<pre><code>#!/usr/bin/env python3
import unittest
import tar
import os
class TarTest(unittest.TestCase):
def test_get_all_files(self):
# given
with tar.Tar("tartest.tar") as t:
# when
files = t.get_all_files()
# then
self.assertTrue(len(files) == 5)
self.assertTrue(self.containsFile(files, "tartest/a.txt"))
self.assertTrue(self.containsFile(files, "tartest/b.txt"))
self.assertTrue(self.containsFile(files, "tartest/foo/c.txt"))
def test_extract_file(self):
# given
with tar.Tar("tartest.tar") as t:
# when
t.extract_file("tartest/a.txt")
t.extract_file("tartest/foo/c.txt")
# then
self.assertTrue(os.path.isfile("a.txt"))
self.assertTrue(self.fileContains("a.txt", "This is file a"))
self.assertTrue(os.path.isfile("c.txt"))
self.assertTrue(self.fileContains("c.txt", "This is file c"))
os.remove("a.txt")
os.remove("c.txt")
def test_extract_all(self):
# given
with tar.Tar("tartest.tar") as t:
# when
t.extract_all()
# then
self.assertTrue(os.path.isdir("tartest"))
self.assertTrue(os.path.isdir("tartest/foo"))
self.assertTrue(os.path.isfile("tartest/a.txt"))
self.assertTrue(os.path.isfile("tartest/b.txt"))
self.assertTrue(os.path.isfile("tartest/foo/c.txt"))
os.system("rm -rf tartest")
def containsFile(self, files, file_name):
for f in files:
if f.file_name == file_name:
return True
return False
def fileContains(self, file_name, content):
with open(file_name) as f:
return content == f.read().splitlines()[0]
if __name__ == '__main__':
unittest.main()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T19:44:18.140",
"Id": "469658",
"Score": "0",
"body": "Oh, one last thing: I tried using your code to unzip a file tar'ed with 7zip, and it failed trying to convert the flag (b'L', which is a vendor flag) to an int; you might want your code to fail more gracefully in the case of an unrecognized flag (and use a str flag instead of an int one)"
}
] | [
{
"body": "<p>I can offer some tips for making your code more pythonic.</p>\n\n<h3>General</h3>\n\n<ul>\n<li>It's good practice to add a docstring for each module, class, and documented function.</li>\n<li>Imports <code>io</code> and <code>json</code> are unused.</li>\n<li>In the <code>Tar.__extract</code> method, the variable <code>total</code> is unused.</li>\n</ul>\n\n<h3><code>class Tar</code></h3>\n\n<ul>\n<li><p><code>not file_path or len(file_path) == 0</code>: If the user inputs an empty string, <code>not file_path</code> is sufficient (and <code>None</code> is not a possible value unless input manually). More to the point, you are not exactly detecting a \"bad file path\". You could use <a href=\"https://docs.python.org/3.8/library/os.path.html#os.path.exists\" rel=\"nofollow noreferrer\"><code>os.path.exists</code></a> for a more robust check. Alternatively, don't validate the path at all, and consider a <code>try... except OSError</code> block in your <code>__enter__</code> method; this will <a href=\"https://stackoverflow.com/a/14575508/10601881\">avoid race conditions</a>. (You perform similar checks in <code>extract_file</code> and <code>extract_all</code> that can also be changed.)</p></li>\n<li><p>You have an <code>__enter__</code> method and an <code>__exit__</code> method, which allows your class to be used with a context-manager, excellent! However, you also provide a <code>close</code> function, without providing a corresponding <code>open</code> function, which means that <code>close</code> could never be reasonably called by the user. Eliminate <code>close</code> or add <code>open</code>.</p></li>\n<li><p>You invoke name-mangling by using double-underscores on methods like <code>__extract</code>; this is fine to prevent truly \"private\" data members from clashing with those from a superclass or subclass, but on methods it makes inheriting from your class (say, to extend it with logging features) unnecessarily difficult. To mark a member as \"private\", <a href=\"https://stackoverflow.com/a/7456865/10601881\">a single leading underscore is enough</a>.</p></li>\n<li><p>Similarly, in the interest of being able to subclass your class, you should consider <code>self.BLOCK_SIZE</code> instead of <code>Tar.BLOCK_SIZE</code> (though maybe this is a constant of the tar format?).</p></li>\n<li><p><code>list(map(...))</code>: It's generally more clear to replace this with a list comprehension (and as opposed to <code>lambda</code>, sometimes <a href=\"https://stackoverflow.com/a/40948713/10601881\">more performant</a>):</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def get_all_files(self):\n self._scan()\n return [FileSnapshot(f.file_name, f.file_size, f.file_mode, f.flag) for f in self.headers]\n</code></pre></li>\n<li><p><code>list(filter(...))</code>: To get the first match, it's generally better to use a generator comprehension:</p>\n\n<pre><code>def extract_file(...):\n ...\n try:\n result = next(fh for fh in self.headers if fh.flag == 0 and fh.file_name == file_name)\n except StopIteration:\n raise RuntimeError(\"File '{}' not found\".format(file_name))\n ...\n</code></pre></li>\n</ul>\n\n<h3><code>class FileSnapshot</code>, <code>class FileHeader</code></h3>\n\n<ul>\n<li><p>There is a lot of boilerplate code here, that could be eliminated with <em>e.g.</em> the <a href=\"https://docs.python.org/3/library/dataclasses.html\" rel=\"nofollow noreferrer\"><code>@dataclass</code> decorator</a>.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from dataclasses import dataclass\n...\n@dataclass\nclass FileSnapshot:\n file_name : str\n file_size : int\n ...\n</code></pre></li>\n<li><p><code>__repr__</code> methods are generally supposed to <a href=\"https://stackoverflow.com/a/2626364/10601881\">return code that will reproduce the object</a>; consider renaming this method to <code>__str__</code> instead.</p></li>\n</ul>\n\n<h3><code>__main__</code></h3>\n\n<ul>\n<li><p>Take advantage of the standard library <a href=\"https://docs.python.org/3/library/argparse.html\" rel=\"nofollow noreferrer\"><code>argparse</code></a> module. For example, it makes extending your <code>--extract</code> switch to extract multiple files easier, provides error checking and usage strings, and can be used to initialize <code>archive</code> as a <code>Tar</code> automatically.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from argparse import ArgumentParser\n...\nif __name__ == '__main__':\n parser = ArgumentParser(description='.tar archive extractor')\n parser.add_argument('archive', type=Tar, help='...')\n group = parser.add_mutually_exclusive_group(required=True)\n group.add_argument('--list', action='store_true', help='List files')\n group.add_argument('--extract-all', action='store_true', help='Extract all')\n group.add_argument('--extract', nargs='+', help='Extract some')\n args = parser.parse_args()\n with args.archive as t:\n ...\n</code></pre></li>\n</ul>\n\n<h3>Code</h3>\n\n<p>Here's my take on your code</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>#!/usr/bin/env python3\n'''TODO: docstring'''\n\nimport os\nimport math\nfrom dataclasses import dataclass\n\nclass Tar:\n '''TODO docstring'''\n BLOCK_SIZE = 512\n\n def __init__(self, file_path):\n self.file_path = file_path\n self.input_stream = None\n self.headers = []\n\n def __enter__(self):\n self.input_stream = open(self.file_path, \"rb\")\n self.headers = []\n return self\n\n def __exit__(self, exc_type, exc_value, exc_traceback):\n if self.input_stream is not None:\n self.input_stream.close()\n\n def get_all_files(self):\n '''TODO docstring'''\n self._scan()\n return [FileSnapshot(f.file_name, f.file_size, f.file_mode, f.flag) \n for f in self.headers]\n\n def extract_file(self, file_name, target_folder=os.getcwd()):\n '''TODO docstring'''\n self._scan()\n try:\n fh = next(fh for fh in self.headers if fh.flag == 0 and fh.file_name == file_name)\n except StopIteration:\n raise RuntimeError(\"File '{}' not found\".format(file_name))\n leaf = os.path.basename(fh.file_name)\n f_path = os.path.join(target_folder, leaf)\n self._extract(fh, f_path)\n\n def extract_all(self, target_folder=os.getcwd()):\n '''TODO docstring'''\n self._scan()\n for fh in self.headers:\n f_path = os.path.join(target_folder, fh.file_name)\n if fh.flag == 5: # if directory\n os.makedirs(f_path, exist_ok=True)\n elif fh.flag == 0: # if regular file\n parent = os.path.dirname(os.path.abspath(f_path))\n os.makedirs(parent, exist_ok=True)\n self._extract(fh, f_path)\n\n\n def _extract(self, fh, file_name):\n with open(file_name, \"wb\") as f:\n if fh.file_size > 0:\n bytes_left = fh.file_size\n self.input_stream.seek(fh.offset, 0)\n while bytes_left > 0:\n data = self.input_stream.read(Tar.BLOCK_SIZE)\n data = data[:bytes_left]\n f.write(data)\n bytes_left -= len(data)\n\n def _scan(self): # iterate over headers\n if len(self.headers) == 0:\n while True:\n block = self.input_stream.read(Tar.BLOCK_SIZE)\n if len(block) < Tar.BLOCK_SIZE:\n break\n h = self._get_file_header(block)\n if not len(h.magic) > 0:\n break\n # omit regular file bytes\n if h.flag == 0:\n h.offset = self.input_stream.tell()\n if h.file_size > 0:\n if h.file_size % Tar.BLOCK_SIZE != 0:\n bytes_to_skeep = math.ceil(h.file_size / Tar.BLOCK_SIZE) * Tar.BLOCK_SIZE\n else:\n bytes_to_skeep = h.file_size\n self.input_stream.seek(bytes_to_skeep, 1)\n self.headers.append(h)\n\n\n def _get_file_header(self, block):\n try:\n return FileHeader(\n self._get_file_name(block),\n self._get_file_size(block),\n self._get_file_mode(block),\n self._get_uid(block),\n self._get_gid(block),\n self._get_mtime(block),\n self._get_chksum(block),\n self._get_type_flag(block),\n self._get_linkname(block),\n self._get_magic(block),\n self._get_version(block),\n self._get_uname(block),\n self._get_gname(block),\n self._get_devmajor(block),\n self._get_devminor(block),\n self._get_prefix(block)\n )\n except Exception as e:\n raise RuntimeError(\"Broken file\") from e\n\n\n def _get_file_name(self, block): # string\n offset, size = 0, 100\n fname = self._get_block_data(block, offset, size)\n fname = fname[0:fname.find(b'\\x00')].decode().strip()\n return fname\n\n def _get_file_mode(self, block): # string\n offset, size = 100, 8\n mode = self._get_block_data(block, offset, size)\n mode = mode[:mode.find(b'\\x00')].decode().strip()\n return mode\n\n def _get_uid(self, block): # string\n offset, size = 108, 8\n uid = self._get_block_data(block, offset, size)\n uid = uid[:uid.find(b'\\x00')].decode().strip()\n return uid\n\n def _get_gid(self, block): # string\n offset, size = 116, 8\n gid = self._get_block_data(block, offset, size)\n gid = gid[:gid.find(b'\\x00')].decode().strip()\n return gid\n\n def _get_file_size(self, block): # int\n offset, size = 124, 12\n size = self._get_block_data(block, offset, size)\n size = size[:size.find(b'\\x00')].decode().strip()\n if len(size) > 0:\n size = int(size, 8)\n else:\n size = 0\n return size\n\n def _get_mtime(self, block): # int\n offset, size = 136, 12\n mtime = self._get_block_data(block, offset, size)\n mtime = mtime[:len(mtime)-1]\n mtime = mtime[:mtime.find(b'\\x00')].decode().strip()\n if len(mtime) > 0:\n mtime = int(mtime, 8)\n else:\n mtime = 0\n return mtime\n\n def _get_chksum(self, block): # int\n offset, size = 148, 8\n chksum = self._get_block_data(block, offset, size)\n chksum = chksum[:chksum.find(b'\\x00')].decode().strip()\n if len(chksum) > 0:\n chksum = int(chksum)\n else:\n chksum = 0\n return chksum\n\n def _get_type_flag(self, block): # int\n offset, size = 156, 1\n flag = self._get_block_data(block, offset, size)\n if flag == b'\\x00':\n flag = 0\n elif flag == b'x':\n flag = 11\n else:\n flag = int(flag)\n return flag\n\n def _get_linkname(self, block): # string (applicable if type_flag = 1 or 2)\n offset, size = 157, 100\n linkname = self._get_block_data(block, offset, size)\n return linkname[:linkname.find(b'\\x00')].decode().strip()\n\n def _get_magic(self, block): # string\n offset, size = 257, 6\n magic = self._get_block_data(block, offset, size)\n magic = magic[:magic.find(b'\\x00')].decode().strip()\n return magic\n\n def _get_version(self, block): # string\n offset, size = 263, 2\n version = self._get_block_data(block, offset, size)\n version = version[:len(version)-1].decode().strip()\n return version\n\n def _get_uname(self, block): # string\n offset, size = 265, 32\n uname = self._get_block_data(block, offset, size)\n uname = uname[:uname.find(b'\\x00')].decode().strip()\n return uname\n\n def _get_gname(self, block): # string\n offset, size = 297, 32\n gname = self._get_block_data(block, offset, size)\n gname = gname[:gname.find(b'\\x00')].decode().strip()\n return gname\n\n def _get_devmajor(self, block): # string\n offset, size = 329, 8\n devmajor = self._get_block_data(block, offset, size)\n devmajor = devmajor[:devmajor.find(b'\\x00')].decode().strip()\n return devmajor\n\n def _get_devminor(self, block): # string\n offset, size = 337, 8\n devminor = self._get_block_data(block, offset, size)\n devminor = devminor[:devminor.find(b'\\x00')].decode().strip()\n return devminor\n\n def _get_prefix(self, block): # string\n offset, size = 345, 155\n prefix = self._get_block_data(block, offset, size)\n prefix = prefix[:prefix.find(b'\\x00')].decode().strip()\n return prefix\n\n def _get_block_data(self, block, offset, size):\n return block[offset:offset+size]\n\n@dataclass\nclass FileSnapshot:\n '''TODO: docstring'''\n file_name: str\n file_size: int\n file_mode: str\n flag: int\n\n def __str__(self):\n return self.file_name\n\n@dataclass\nclass FileHeader:\n '''TODO: docstring'''\n file_name: str\n file_size: int\n file_mode: str\n uid: str\n gid: str\n mtime: int\n chksum: int\n flag: int\n linkname: str \n magic: str\n version: str\n uname: str\n gname: str\n devmajor: str\n devminor: str\n prefix: str\n offset: int = 0\n\nif __name__ == \"__main__\":\n def main():\n from argparse import ArgumentParser\n parser = ArgumentParser(description='.tar archive extractor')\n parser.add_argument('archive', type=Tar,\n help='The tar archive file')\n group = parser.add_mutually_exclusive_group(required=True)\n group.add_argument('--list', action='store_true', \n help='List all files in the archive')\n group.add_argument('--extract-all', action='store_true', \n help='Extract all files from the archive')\n group.add_argument('--extract', nargs='+', dest='files',\n help='Extract specified files from the archive')\n args = parser.parse_args()\n with args.archive as t:\n if args.list:\n files = t.get_all_files()\n for file in files:\n print(file)\n elif args.extract_all:\n t.extract_all()\n else:\n for file in args.files:\n t.extract_file(file)\n\n main()\n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T11:27:38.997",
"Id": "469737",
"Score": "1",
"body": "All the `_get_*` could be probably done easier by having a `_get_block_data` that truncates to the null byte and decodes and strips the value and then you can have e.g. `_get_linkname = functools.partialmethod(_get_block_data, offset=157, size=100)`. This way you only need to spell out the two where you need to do additional checking. Or maybe even better, save the sizes in a class variable and iterate over the `block` in chunks of varying sizes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T12:18:10.683",
"Id": "469748",
"Score": "1",
"body": "It's true, the get methods are not very DRY; even just adding the find/slice/decode/strip portion to `_get_block_data` would save on boilerplate, or maybe factoring it into a `_get_block_str` since `_get_type_flag` exceptionally doesn't use it"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T10:29:28.973",
"Id": "239397",
"ParentId": "239259",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T02:45:39.977",
"Id": "239259",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"parsing"
],
"Title": "Tar archive parser - custom implementation"
} | 239259 |
<p>I have made a 2 player Tic Tac Toe game in C++. I have put in some error checking also (like if the players enters an invalid position). The code is working absolutely fine.
This is what my program output looks like.</p>
<pre class="lang-none prettyprint-override"><code> | | |
| | |
| | |
Where you want to make move: 1
cross | |
| | |
| | |
Where you want to make move: 2
cross zero |
| | |
| | |
Where you want to make move: 4
cross zero |
cross | |
| | |
Where you want to make move: 3
cross zero zero
cross | |
| | |
Where you want to make move: 7
cross zero zero
cross | |
cross | |
Player 1 is WINNNER!
</code></pre>
<p>Here is my code.</p>
<pre><code>#include <iostream>
using namespace std;
#define Player1 1
#define Player2 2
int whoseTurn;
string moves[3] = {"empty", "cross", "zero"};
string board[9] = {"empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty"};
//An array to avoid duplicate input
int playedPos[9] = {0};
void printBoard()
{
cout << endl;
for (int i = 0; i < 9; i++)
{
if (i == 3 || i == 6)
{
cout << endl;
cout << endl;
}
if (board[i] == "empty")
{
cout << "\t"
<< " | ";
}
else
{
cout << "\t" << board[i] << " ";
}
}
cout << endl;
}
//Checking if any paper has won
bool check_for_victory(string board[])
{
if ((board[0] != "empty") && (board[0] == board[1]) && (board[1] == board[2]))
return true;
if ((board[3] != "empty") && (board[3] == board[4]) && (board[4] == board[5]))
return true;
if ((board[6] != "empty") && (board[6] == board[7]) && (board[7] == board[8]))
return true;
if ((board[0] != "empty") && (board[0] == board[3]) && (board[3] == board[6]))
return true;
if ((board[1] != "empty") && (board[1] == board[4]) && (board[4] == board[7]))
return true;
if ((board[2] != "empty") && (board[2] == board[5]) && (board[5] == board[8]))
return true;
if ((board[0] != "empty") && (board[0] == board[4]) && (board[4] == board[8]))
return true;
if ((board[6] != "empty") && (board[6] == board[4]) && (board[4] == board[2]))
return true;
return false;
}
void makeMove(int whoseTurn)
{
//Variable for counting how many times the game is played
int gameCount = 0;
int pos, move;
while ((check_for_victory(board) == false) && (gameCount != 9))
{
cout << "Where you want to make move: ";
cin >> pos;
if (pos < 10 && pos > 0) //Checking if the user entered a valid move
{
pos--;
//incrementing the position at the pos index to 1
playedPos[pos]++;
if (playedPos[pos] <= 1)
{
if (whoseTurn == Player1)
{
move = Player1;
board[pos] = moves[move];
printBoard();
whoseTurn = Player2;
gameCount++;
}
else if (whoseTurn == Player2)
{
move = Player2;
board[pos] = moves[move];
printBoard();
whoseTurn = Player1;
gameCount++;
}
}
else
{
cout << "You have played this move" << endl;
}
}
else
{
cout << "Enter a valid position" << endl;
}
}
if ((check_for_victory(board) == false) && gameCount != 9)
{
cout << "Math is draw" << endl;
}
else
{
if (whoseTurn == Player1)
{
cout << "Player 2 is WINNER!" << endl;
}
else
{
cout << "Player 1 is WINNNER!" << endl;
}
}
}
int main()
{
whoseTurn = Player1;
printBoard();
makeMove(Player1);
}
</code></pre>
<p>I want to know that have I done it right as it is my first time.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T10:32:20.747",
"Id": "469341",
"Score": "0",
"body": "Your code is far from working as intended what it's supposed to do. Please make your code woking first before asking fo a review here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T00:58:27.350",
"Id": "469379",
"Score": "2",
"body": "For those considering VTC: the code [works fine](https://wandbox.org/permlink/SjrjqrbZidMKNQ4c) now."
}
] | [
{
"body": "<h2>Player identification</h2>\n\n<pre><code>#define Player1 1\n#define Player2 2\n\nint whoseTurn;\n</code></pre>\n\n<p>Do you ever plan to support more than two players? If not, consider representing this as <code>enum</code> or a <code>bool</code>.</p>\n\n<p>The same is true of your <code>moves</code> and <code>board</code>. Those should not be strings; they should be enums. Making them strings is not strongly-typed, and gives you fewer guarantees about the correctness of the code. So avoid \"stringly-typed\" code.</p>\n\n<h2>Don't repeat yourself</h2>\n\n<p>In <code>check_for_victory</code>, note that those statements all look virtually identical except for the indexes. So factor out the indexes into an array of integers and loop over them.</p>\n\n<h2>Boolean expressions</h2>\n\n<pre><code>(check_for_victory(board) == false) && (gameCount != 9)\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>!check_for_victory(board) && gameCount < 9\n</code></pre>\n\n<h2>Consolidation of logic</h2>\n\n<p>This doesn't need an if:</p>\n\n<pre><code> if (whoseTurn == Player1)\n {\n move = Player1;\n board[pos] = moves[move];\n printBoard();\n whoseTurn = Player2;\n gameCount++;\n }\n</code></pre>\n\n<p>As your code stands currently, you can just do</p>\n\n<pre><code>move = whoseTurn;\nboard[pos] = moves[move];\nprintBoard();\nwhoseTurn = N_PLAYERS - whoseTurn + 1;\ngameCount++;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T14:11:50.110",
"Id": "239365",
"ParentId": "239260",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "239365",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T02:56:19.170",
"Id": "239260",
"Score": "3",
"Tags": [
"c++",
"game",
"tic-tac-toe"
],
"Title": "Tic Tac Toe in C++ (console version)"
} | 239260 |
<p>i'm trying to create a url router system, for educational purposes, that has a similar usage like Laravel has, but i'm curious about how i can register the routes like laravel does (with single calls to static methods), here's my "conceptual" code that i made using a TDD approach:</p>
<pre><code> $Route = new Route;
$Route
->setUri('users/[i:id]')
->setMethod('GET')
->setCallback(function () {
return 'get user';
})
->setMiddleware([
App\Http\Middlewares\Auth::class,
App\Http\Middlewares\Permission::class
])
->setName('users.show');
$Route2 = new Route;
$Route2
->setUri('orders')
->setMethod('POST')
->setCallback('OrdersController@create')
->setMiddleware([
App\Http\Middlewares\Auth::class
])
->setName('orders.post');
$Router = new Router;
$Router->addRoute($Route);
$Router->addRoute($Route2);
// if the route is matched this methods are called
// $Router->handleMiddlewares();
// $Router->handleCallback();
$Router->run();
</code></pre>
<p>1 - there's a better approach about how to encapsulate the route object creation to a simple/shorter way?
eg:
in Laravel we can map routes like this:</p>
<pre><code>Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback)->name('foo');
</code></pre>
<p>2 - should the router class be responsible for filtering routes (regex rules etc), handling callbacks and middlewares?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T06:52:30.323",
"Id": "239264",
"Score": "2",
"Tags": [
"php",
"object-oriented",
"design-patterns"
],
"Title": "router system like laravel, how to manage routes creation and router handler?"
} | 239264 |
<p>The goal of my code is to implement a web scraping routine to obtain the name and the price of a product. I want to put this routine separated from the main program file. Sample url to scrape: <a href="https://www.amazon.co.uk/Samsung-MZ-76E1T0B-EU-Solid-State/dp/B078WST5RK/ref=sr_1_1?dchild=1&keywords=samsung+860+evo+1tb&qid=1584446290&sr=8-1" rel="noreferrer">https://www.amazon.co.uk/Samsung-MZ-76E1T0B-EU-Solid-State/dp/B078WST5RK/ref=sr_1_1?dchild=1&keywords=samsung+860+evo+1tb&qid=1584446290&sr=8-1</a>. I'm doing this to learn python (I'm quite new).</p>
<p>I didn't know if it was better to use a class or function, so I tried both. I would like to know if any of the 2 implementations could be made more clear, readable or efficient, or if one of the two implementations is better than the other and why.</p>
<h2>Implementation with a function:</h2>
<pre class="lang-py prettyprint-override"><code>import json
from collections import namedtuple
import requests
from bs4 import BeautifulSoup
parser = "lxml"
headers = {
"User-Agent": "I don't put my user-agent in case it contains sensible info."
}
# This dictionary contains multiple entries. They are the supported domains by the program.
# This is just a sample.
HTML_search_attributes = {
"amazon.co.uk": {
"price": ("span", {"id": "priceblock_ourprice"}),
"name": ("span", {"id": "productTitle"}),
"JavaScript": False,
},
"newegg.com": {
"price": ("script", {"type": "application/ld+json"}),
"name": ("div", {"class": "mini-features-desc"}),
"JavaScript": True,
},
}
def product(url):
d = url.replace("https://", "").replace("www.", "")
domain = d.split("/", maxsplit=1)[0]
r = requests.get(url, headers=headers)
soup = BeautifulSoup(r.text, parser)
# Collect scraping attributes from HTML_search_attributes dictionary.
try:
p = HTML_search_attributes[domain]["price"]
n = HTML_search_attributes[domain]["name"]
js = HTML_search_attributes[domain]["JavaScript"]
except KeyError as err:
raise type(err)(
f"The domain {domain} is not supported by this app."
) from None
# Find price of the product
if js is False:
try:
price = soup.find(p[0], attrs=p[1]).get_text()
price= float(price.strip("\r\n\xa0£€EUR* ").replace(",", "."))
except AttributeError:
price = "No availability"
else:
price = soup.find_all(p[0], attrs=p[1])[-1].get_text()
price = float(json.loads(price)["offers"]["price"])
# Find name of the product
name = soup.find(n[0], attrs=n[1]).get_text()
name = name.strip("\r\n\xa0 ")
Product = namedtuple('Product', ['domain', 'name', 'price'])
return Product(domain, name, price)
</code></pre>
<h2>Implementation with a Class:</h2>
<pre class="lang-py prettyprint-override"><code>import json
import requests
from bs4 import BeautifulSoup
parser = "lxml"
headers = {
"User-Agent": "I don't put my user-agent in case it contains sensible info."
}
# This dictionary contains multiple entries. They are the supported domains by the program.
# This is just a sample.
HTML_search_attributes = {
"amazon.co.uk": {
"price": ("span", {"id": "priceblock_ourprice"}),
"name": ("span", {"id": "productTitle"}),
"JavaScript": False,
},
"newegg.com": {
"price": ("script", {"type": "application/ld+json"}),
"name": ("div", {"class": "mini-features-desc"}),
"JavaScript": True,
},
}
class Product:
def __init__(self, url):
self.url = url
@property
def url(self):
return self._url
@property
def domain(self):
return self._domain
@property
def soup(self):
return self._soup
@property
def price(self):
return self._price
@property
def name(self):
return self._name
@url.setter
def url(self, url):
d = url.replace("https://", "").replace("www.", "")
r = requests.get(url, headers=headers)
self._domain = d.split("/", maxsplit=1)[0]
self._soup = BeautifulSoup(r.text, parser)
self._url = url
# Collect scraping attributes from HTML_search_attributes dictionary.
try:
price = HTML_search_attributes[self._domain]["price"]
name = HTML_search_attributes[self._domain]["name"]
js = HTML_search_attributes[self._domain]["JavaScript"]
except KeyError as err:
raise type(err)(
f"The domain {self._domain} is not supported by this app."
) from None
# Find price of the product
if js is False:
try:
self._price = self._soup.find(price[0], attrs=price[1]).get_text()
self._price = float(self._price.strip("\r\n\xa0£€EUR* ").replace(",", "."))
except AttributeError:
self._price = "No availability"
else:
self._price = self._soup.find_all(price[0], attrs=price[1])[-1].get_text()
self._price = float(json.loads(self._price)["offers"]["price"])
# Find name of the product
self._name = self._soup.find(name[0], attrs=name[1]).get_text()
self._name = self._name.strip("\r\n\xa0 ")
</code></pre>
<h2>Functionality details</h2>
<p>In both cases, changing the url changes all related properties. In both cases, I can access the results with result.price, result.name and result.domain. In the class implementation, all properties are read-only except the url. The price extraction routine is different whether or not the webpage uses JavaScript (I've only encountered one case at the moment).</p>
<p>I've measured the computation time of both methods and I've found that the fastest method is the class method if I iterate as follows:</p>
<pre class="lang-py prettyprint-override"><code>from timeit import default_timer as timer
start = timer()
# urls2bscraped is a list containing multiple urls.
prod = Product(urls2bscraped[0])
print(prod.domain, prod.name, prod.price)
for url in urls2bscraped[1:]:
prod.url = url
print(prod.domain, prod.name, prod.price)
end = timer()
print(end - start)
</code></pre>
<p>Using the function implementation, the mean computation time (10 samples) is 4.47% slower, and creating a new instance of the class for every iteration is 5.05% slower.</p>
<h2>Consulted references:</h2>
<p><a href="https://www.youtube.com/watch?v=wf-BqAjZb8M" rel="noreferrer">Raymond Hettinger - Beyond PEP 8 -- Best practices for beautiful intelligible code</a></p>
<p><a href="https://www.youtube.com/watch?v=o9pEzgHorH0" rel="noreferrer">Jack Diederich - Stop Writing Classes</a></p>
<p><a href="https://docs.microsoft.com/en-us/previous-versions/dotnet/netframework-4.0/ms229054(v=vs.100)?redirectedfrom=MSDN" rel="noreferrer">Choosing Between Properties and Methods</a></p>
| [] | [
{
"body": "<p>You are unfairly doing more work in the function approach!</p>\n\n<pre><code>Product = namedtuple('Product', ['domain', 'name', 'price'])\n</code></pre>\n\n<p>creates a new type every time the statement is executed. Consider:</p>\n\n<pre><code>result1.__class__ == result2.__class__\n</code></pre>\n\n<p>That will evaluate as <code>False</code>, for different result objects, even when returning results from the same site!</p>\n\n<p>You should move the <code>Product</code> type creation outside of the function, and then rerun your timings.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T15:45:33.137",
"Id": "239276",
"ParentId": "239267",
"Score": "3"
}
},
{
"body": "<h2>Data safety</h2>\n\n<p>Your current <code>HTML_search_attributes</code> is type-unsafe - it's closer to a serialized format than an in-memory format.</p>\n\n<p>Consider moving those data to a <code>.json</code> file. Deserializing it will give you exactly what you have now, though I recommend going one step further. Make a class or at least a named tuple to represent a scraped domain, with attributes of <code>price</code>, <code>name</code>, and <code>has_javascript</code>. This will go farther to validate your data and increase the confidence in correctness of your code.</p>\n\n<h2>URL parsing</h2>\n\n<p>Don't do it by hand. This:</p>\n\n<pre><code> d = url.replace(\"https://\", \"\").replace(\"www.\", \"\")\n</code></pre>\n\n<p>will explode for sites such as</p>\n\n<pre><code>https://foo.com/www.section/\n</code></pre>\n\n<p>At the least, you should regex-match to <code>^</code>, the beginning of the string. More likely, you should use <a href=\"https://docs.python.org/3/library/urllib.parse.html\" rel=\"nofollow noreferrer\">https://docs.python.org/3/library/urllib.parse.html</a> .</p>\n\n<p>The next problem is your class representation of these URL parts. After a class is initialized, one should be able to assume within reason that its properties are accessible, but yours are not until <code>url</code> is run. The solution to this is to move this block:</p>\n\n<pre><code> d = url.replace(\"https://\", \"\").replace(\"www.\", \"\")\n r = requests.get(url, headers=headers)\n self._domain = d.split(\"/\", maxsplit=1)[0]\n self._soup = BeautifulSoup(r.text, parser)\n self._url = url\n</code></pre>\n\n<p>into the constructor.</p>\n\n<p>There probably shouldn't even be a public <code>url</code> setter. It only makes sense for it to be initialized once, in the constructor.</p>\n\n<p>The real problem is that the scraping occurs immediately when the class is instantiated. Don't do lengthier operations such as soup calls in <code>__init__</code>; do them in a separate method.</p>\n\n<h2>Invert your logic</h2>\n\n<p>Rather than</p>\n\n<pre><code> if js is False:\n # ...\n else:\n # ...\n</code></pre>\n\n<p>do</p>\n\n<pre><code>if js:\n # ...\nelse:\n # ...\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T16:00:09.707",
"Id": "239277",
"ParentId": "239267",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T10:22:46.910",
"Id": "239267",
"Score": "6",
"Tags": [
"python",
"beginner",
"python-3.x",
"design-patterns",
"comparative-review"
],
"Title": "Implementing web scraping in a function and in a class"
} | 239267 |
<p>I am building an ad-hoc text-editor. I have two functions which use a cache, <code>provideHover</code> and <code>provideCompletionItems</code>.</p>
<pre><code>"use strict";
import * as monaco from "monaco-editor/esm/vs/editor/editor.api";
const $ = require("jquery");
const urlResolve = require("url-resolve");
const AUTOCOMPLETE_ENDPOINT = "http://localhost:7000/";
const LRU = require("lru-cache");
const options = {
max: 500,
length: (suggestions, key) => { return suggestions.length }
};
const cache = new LRU(options);
const definition_cache = new LRU(options);
(function () {
// create div to avoid needing a HtmlWebpackPlugin template
const div = document.createElement('div');
div.id = 'root';
div.style = 'width:800px; height:600px; border:1px solid #ccc;';
document.body.appendChild(div);
})();
monaco.editor.create(
document.getElementById('root'),
{
value: ``,
language: 'python',
theme: 'vs-dark'
}
);
const getCompletions = (text) => {
return $.ajax({
url: urlResolve(AUTOCOMPLETE_ENDPOINT, "suggestion"),
type: 'GET',
"data": {
"text": text
}
});
};
const getDocumentation = (cursorInfo) => {
const line = cursorInfo.line;
const column = cursorInfo.column;
const text = cursorInfo.text;
return $.ajax({
url: urlResolve(AUTOCOMPLETE_ENDPOINT, "documentation"),
type: 'GET',
"data": {
"line": line,
"column": column,
"text": text,
"highlighted": cursorInfo.highlighted
}
});
}
monaco.languages.registerHoverProvider("python", {
provideHover: async (model, position) => {
const lineNumber = position.lineNumber;
const snippet = model.getWordAtPosition(position);
const text = model.getValueInRange({ startLineNumber: 1, startColumn: 1, endLineNumber: position.lineNumber, endColumn: snippet.endColumn });
if (definition_cache.has(text)) {
console.log("hit");
return {
contents: [{ value: definition_cache.get(text) }]
}
}
const response = await getDocumentation({ "line": lineNumber, "column": snippet.endColumn, "text": text, "highlighted": snippet.word });
definition_cache.set(text, response.documentation);
return {
contents: [{ value: response.documentation }]
}
}
});
monaco.languages.registerCompletionItemProvider('python', {
provideCompletionItems: async (model, position) => {
const text = model.getValueInRange({ startLineNumber: 1, startColumn: 1, endLineNumber: position.lineNumber, endColumn: position.column });
if (cache.has(text)) {
const suggestions = cache.get(text);
return {
"suggestions": suggestions
};
}
const completions = await getCompletions(text)
const suggestions = completions.map(c => ({
label: c.name,
insertText: c.name
}));
cache.set(text, suggestions)
return {
"suggestions": suggestions
};
}
});
</code></pre>
<p>As it stands, the introduction of the cache makes the code quite ugly (in my opinion). I'd like to refactor it so that I have only one cache usage that applies in both situations -- something like a Python decorator.</p>
<p>How do I make the code cleaner?</p>
| [] | [
{
"body": "<p>I'd look at python decorators as something, that accepts function and returns function, which is usually original function wrapped in another function and some added behaviour.</p>\n\n<p>Change signature of your \"decorator\" functions to match that and you got something like decorators. Don't have much time at the moment to write examples, but you get the idea :-)</p>\n\n<p>Edit:\nI took a closer look at your code, but it seems very specific to your framework and I can't make complete sense of it to dare refactoring (doesn't mean it's bad code). At least here are some examples of wrapper functions to help you started:\n<a href=\"https://gist.github.com/harrylove/1230566/d064e5c216384d3846f73ed555e9899be02e8f98\" rel=\"nofollow noreferrer\">https://gist.github.com/harrylove/1230566/d064e5c216384d3846f73ed555e9899be02e8f98</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T20:33:14.217",
"Id": "239287",
"ParentId": "239268",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T12:30:10.927",
"Id": "239268",
"Score": "1",
"Tags": [
"javascript",
"node.js",
"cache"
],
"Title": "Python-like decorators for caching"
} | 239268 |
<p>I have created a Snake console game using object-orientated programming methods. This is the first time I have ever used OOP so I just wanted to know if I was using the method correctly as well as hear any other advise I could possibly receive as this is my first time doing this. There are 4 header files and 4 .cpp files used.</p>
<p>Direction.h:</p>
<pre><code>#pragma once
enum class Direction {
STOP = 0, UP, DOWN, LEFT, RIGHT
};
</code></pre>
<p>Food.h:</p>
<pre><code>#pragma once
class Food{
private:
int foodX;
int foodY;
public:
Food(int x, int y);
Food();
int posX() { return foodX; };
int posY() { return foodY; };
void Refresh(int x, int y);
};
</code></pre>
<p>Food.cpp</p>
<pre><code>#include "Food.h"
Food::Food(int x, int y)
{
foodX = x;
foodY = y;
}
Food::Food()
:foodX{ 2 }, foodY{ 2 }
{
}
void Food::Refresh(int x, int y)
{
foodX = x;
foodY = y;
}
</code></pre>
<p>Snake.h</p>
<pre><code>#pragma once
#include "Direction.h"
class Snake{
private:
int headX;
int headY;
int length;
Direction dir;
public:
Snake(int x, int y);
Snake();
int posX() { return headX; };
int posY() { return headY; };
int len() { return length; };
void Update();
void Eat();
void Change_Dir(Direction direction);
};
</code></pre>
<p>Snake.cpp</p>
<pre><code>#include "Snake.h"
Snake::Snake()
: headX{ 1 }, headY{ 1 }, length{ 1 }, dir{ Direction::STOP }
{
}
Snake::Snake(int x, int y)
: length{ 1 }, dir{ Direction::STOP }
{
headX = x;
headY = y;
}
void Snake::Update()
{
switch (dir) {
case(Direction::LEFT):
headX--;
break;
case(Direction::RIGHT):
headX++;
break;
case(Direction::UP):
headY--;
break;
case(Direction::DOWN):
headY++;
break;
case(Direction::STOP):
break;
}
}
void Snake::Eat()
{
length++;
}
void Snake::Change_Dir(Direction direction)
{
dir = direction;
}
</code></pre>
<p>Game.h</p>
<pre><code>#pragma once
#include "Snake.h"
#include "Food.h"
#include <vector>
class Game {
private:
Snake snake;
Food food;
int board_height;
int board_width;
std::vector<int> Snake_Tail_X;
std::vector<int> Snake_Tail_Y;
void Snake_Tail_Update();
void Board_Colission();
void Snake_Colission();
void Eaten();
void Input_Check();
void Draw();
void Logic();
bool Game_Over;
public:
Game();
bool Game_State() { return Game_Over; };
void Play();
};
</code></pre>
<p>Game.cpp</p>
<pre><code>#include "Game.h"
#include <iostream>
#include <conio.h>
Game::Game()
:snake{ 2, 5 }, food{ 5, 5 }, board_height{ 20 }, board_width{ 20 }, Game_Over{ false }, Snake_Tail_X{}, Snake_Tail_Y{}
{
}
void Game::Play()
{
Draw();
Logic();
}
void Game::Draw()
{
int i{ 0 }, j{ 0 }, k{ 0 };
system("cls");
for (i = 0; i < board_height; i++) {
for (j = 0; j < board_width; j++) {
if (j == snake.posX() && i == snake.posY())
std::cout << "O";
else if (j == food.posX() && i == food.posY())
std::cout << "F";
else if (i == 0 || j == 0 || i == board_height - 1 || j == board_width - 1)
std::cout << "#";
else{
bool tail = false;
for (k = 0; k < snake.len() - 1; k++) {
if (Snake_Tail_X[k] == j && Snake_Tail_Y[k] == i) {
std::cout << "o";
tail = true;
}
}
if(tail == false)
std::cout << " ";
}
}
std::cout << std::endl;
}
std::cout << "Score: " << snake.len()-1;
}
void Game::Logic()
{
Input_Check();
Snake_Tail_Update();
snake.Update();
Board_Colission();
Snake_Colission();
Eaten();
}
void Game::Snake_Tail_Update()
{
if (!Snake_Tail_X.empty()) {
int i{ 0 }, tempX{ 0 }, tempY{ 0 }, temp2X{ 0 }, temp2Y{ 0 };
tempX = Snake_Tail_X[0];
tempY = Snake_Tail_Y[0];
Snake_Tail_X[0] = snake.posX();
Snake_Tail_Y[0] = snake.posY();
for (i = 1; i < snake.len()-1; i++) {
temp2X = Snake_Tail_X[i];
temp2Y = Snake_Tail_Y[i];
Snake_Tail_X[i] = tempX;
Snake_Tail_Y[i] = tempY;
tempX = temp2X;
tempY = temp2Y;
}
}
}
void Game::Board_Colission(){
if (snake.posX() == 0 || snake.posX() == board_width-1 || snake.posY() == 0 || snake.posY() == board_height-1) {
Game_Over = true;
}
}
void Game::Snake_Colission()
{
int i{ 0 };
for (i = 0; i < snake.len() - 1; i++) {
if (snake.posX() == Snake_Tail_X[i] && snake.posY() == Snake_Tail_Y[i])
Game_Over = true;
}
}
void Game::Eaten()
{
if (snake.posX() == food.posX() && snake.posY() == food.posY()) {
food.Refresh(rand() % (board_width - 2) + 1, rand() % (board_height - 2) + 1);
snake.Eat();
Snake_Tail_X.push_back(1);
Snake_Tail_Y.push_back(1);
}
}
void Game::Input_Check(){
if (_kbhit()) {
switch(_getch()){
case('a'):
snake.Change_Dir(Direction::LEFT);
break;
case('d'):
snake.Change_Dir(Direction::RIGHT);
break;
case('w'):
snake.Change_Dir(Direction::UP);
break;
case('s'):
snake.Change_Dir(Direction::DOWN);
break;
default:
break;
}
}
}
</code></pre>
<p>Main.cpp</p>
<pre><code>#include <iostream>
#include "Game.h"
int main()
{
Game game;
while (!game.Game_State()) {
game.Play();
}
return 0;
}
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T14:07:36.813",
"Id": "469348",
"Score": "1",
"body": "Just wondering, did you write this on Linux?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T14:21:04.047",
"Id": "469349",
"Score": "0",
"body": "Hi pacmaninbw, I wrote this on Windows in Visual Studio 2019"
}
] | [
{
"body": "<h2>Const methods</h2>\n\n<p>These:</p>\n\n<pre><code> int posX() { return foodX; };\n int posY() { return foodY; };\n// ...\n int posX() { return headX; };\n int posY() { return headY; };\n int len() { return length; };\n</code></pre>\n\n<p>don't modify anything in <code>this</code>, so make them <code>const</code>:</p>\n\n<pre><code> int posX() const { return foodX; };\n int posY() const { return foodY; };\n</code></pre>\n\n<h2>Setters</h2>\n\n<p>This:</p>\n\n<pre><code>void Refresh(int x, int y);\n</code></pre>\n\n<p>is unusual. You're forcing the user to update both <code>x</code> and <code>y</code> at the same time. In a different universe where you care about atomic interactions in a multithreaded application, this might matter, but here it doesn't. Effectively since you have unlimited read/write ability to this class, it's not even worth making individual setter methods - just boil this down to a <code>struct</code> with two public member variables and be done with it.</p>\n\n<h2>Nomenclature</h2>\n\n<pre><code> bool Game_Over;\n</code></pre>\n\n<p>is styled to look like a method but it should actually match the capitalization of your other member variables (i.e. lowercase).</p>\n\n<p><code>Game_State</code> would make sense as a name if you were returning an <code>enum</code>, but since you aren't: it should probably be called something like <code>isGameOver()</code>.</p>\n\n<h2>Characters instead of strings</h2>\n\n<p>This</p>\n\n<pre><code>std::cout << \"O\";\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>std::cout << 'O';\n</code></pre>\n\n<h2>Unused includes</h2>\n\n<p>Remove</p>\n\n<pre><code>#include <iostream>\n</code></pre>\n\n<p>from your <code>main.cpp</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T19:14:02.673",
"Id": "469363",
"Score": "0",
"body": "Hi, thank you for the feedback, I really appreciate it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T15:18:30.090",
"Id": "239275",
"ParentId": "239269",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T12:38:07.210",
"Id": "239269",
"Score": "4",
"Tags": [
"c++",
"object-oriented",
"snake-game"
],
"Title": "Simple Console Snake Game"
} | 239269 |
<p>This was one of my friends' Java OOP class assignments. They were tasked with writing a polynomial class in Java with multiplication functionality. I did it in C++ as a challenge and for improving my programming skills. I also added a little bit of extra functionality.</p>
<h1>Header File</h1>
<p><strong><em>polynomial.hpp</em></strong></p>
<pre><code>#include <vector>
#include <string>
#include <iostream>
class polynomial
{
public:
char var = 'x';
polynomial();
polynomial(const std::string&, const char variable);
polynomial(const std::string&);
// construction by coefficients
polynomial(const std::vector<long double>&);
const std::size_t order() const;
long double &operator[](const std::size_t&);
const long double &operator[](const std::size_t&) const;
long double &coefficient(const std::size_t&);
const long double &coefficient(const std::size_t&) const;
polynomial &operator=(const std::string&);
// adds the argument to this polynomial
void add(const polynomial&);
// returns this polynomial + the argument
polynomial plus(const polynomial&) const;
polynomial operator+(const polynomial&) const;
polynomial &operator+=(const polynomial&);
// subtract the argument from this polynomial
void subtract(const polynomial&);
// returns this polynomial - the argument
polynomial minus(const polynomial&) const;
polynomial operator-(const polynomial&) const;
polynomial &operator-=(const polynomial&);
// multiplies this polynomial by the argument
void multiply(const polynomial&);
// returns this polynomial * the argument
polynomial times(const polynomial&) const;
polynomial operator*(const polynomial&) const;
polynomial &operator*=(const polynomial&);
bool operator==(const polynomial&) const;
void print(std::ostream&) const;
void print(std::ostream&, const char variable) const;
private:
std::vector<long double> coefficients;
};
polynomial add(const polynomial&, const polynomial&);
polynomial subtract(const polynomial&, const polynomial&);
polynomial multiply(const polynomial&, const polynomial&);
std::ostream &operator<<(std::ostream&, const polynomial&);
std::istream &operator>>(std::istream&, polynomial&);
</code></pre>
<h1>Source File</h1>
<p><strong><em>polynomial.cpp</em></strong></p>
<pre><code>#include "polynomial.hpp"
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
#include <iomanip>
polynomial::polynomial()
{
coefficients.push_back(0);
}
bool isNumber(const char);
long double parseNumber(const std::string &in, std::size_t &index, const bool negative_flag);
void setExponent(unsigned &exponent, const char variable,
const std::string &poly, std::size_t &index);
void addCoefficient(long double &num, unsigned &exponent, std::vector<long double>& coefficients);
polynomial::polynomial(const std::string &poly, const char variable)
: var{variable}
{
long double num;
unsigned exponent;
bool negative_flag = false;
coefficients.push_back(0);
for (std::size_t i = 0; i < poly.length(); ++i)
{
if (isNumber(poly[i]))
{
num = parseNumber(poly, i, negative_flag);
setExponent(exponent, var, poly, i);
addCoefficient(num, exponent, coefficients);
}
else if (poly[i] == var)
{
num = 1;
if (negative_flag)
num *= -1;
--i;
setExponent(exponent, var, poly, i);
addCoefficient(num, exponent, coefficients);
}
else if (poly[i] == '-')
negative_flag = true;
else if (poly[i] == '+')
negative_flag = false;
}
}
polynomial::polynomial(const std::string &poly)
: polynomial(poly, 'x') {}
bool isNumber(const char character)
{
return (character >= '0' && character <= '9') || character == '.';
}
long double parseNumber(const std::string &poly, std::size_t &index, const bool negative_flag)
{
long double number;
std::string num_string;
num_string.push_back(poly[index]);
while (index + 1 < poly.length() && isNumber(poly[index + 1]))
{
++index;
num_string.push_back(poly[index]);
}
std::stringstream numstream;
numstream << num_string;
numstream >> number;
if (negative_flag)
number *= -1;
return number;
}
void setExponent(unsigned &exponent, const char variable,
const std::string &poly, std::size_t &index)
{
if (index + 1 < poly.size() && poly[index + 1] == variable)
{
++index;
if (index + 1 < poly.size() && poly[index + 1] == '^')
{
index += 2;
exponent = parseNumber(poly, index, false);
}
else
exponent = 1;
}
else
exponent = 0;
}
void addCoefficient(long double &num, unsigned &exponent, std::vector<long double>& coefficients)
{
if (exponent + 1 > coefficients.size())
coefficients.resize(exponent + 1, 0);
coefficients[exponent] += num;
}
polynomial::polynomial(const std::vector<long double>& poly)
: coefficients{poly} {}
const std::size_t polynomial::order() const
{
return coefficients.size() - 1;
}
long double &polynomial::operator[](const std::size_t &index)
{
return coefficients[index];
}
const long double &polynomial::operator[](const std::size_t &index) const
{
return coefficients[index];
}
long double &polynomial::coefficient(const std::size_t &index)
{
return coefficients[index];
}
const long double &polynomial::coefficient(const std::size_t &index) const
{
return coefficients[index];
}
polynomial &polynomial::operator=(const std::string &poly)
{
*this = polynomial(poly);
return *this;
}
void polynomial::add(const polynomial &poly)
{
if (poly.order() > this->order())
coefficients.resize(poly.order() + 1, 0);
for (std::size_t i = 0; i <= poly.order(); ++i)
coefficients[i] += poly[i];
// removing extra zeros
for (size_t i = coefficients.size() - 1; i > 0; --i)
{
if (coefficients[i] != 0)
break;
else
coefficients.pop_back();
}
}
polynomial polynomial::plus(const polynomial &poly) const
{
std::vector<long double> res = coefficients;
if (poly.order() > this->order())
res.resize(poly.order() + 1, 0);
for (size_t i = 0; i <= poly.order(); ++i)
res[i] += poly[i];
// removing extra zeros
for (size_t i = res.size() - 1; i > 0; --i)
{
if (res[i] != 0)
break;
else
res.pop_back();
}
return polynomial(res);
}
polynomial polynomial::operator+(const polynomial &poly) const
{
return this->plus(poly);
}
polynomial &polynomial::operator+=(const polynomial &poly)
{
this->add(poly);
return *this;
}
void polynomial::subtract(const polynomial &poly)
{
if (poly.order() > this->order())
coefficients.resize(poly.order() + 1, 0);
for (std::size_t i = 0; i <= poly.order(); ++i)
coefficients[i] -= poly[i];
// removing extra zeros
for (size_t i = coefficients.size() - 1; i > 0; --i)
{
if (coefficients[i] != 0)
break;
else
coefficients.pop_back();
}
}
polynomial polynomial::minus(const polynomial &poly) const
{
std::vector<long double> res = coefficients;
if (poly.order() > this->order())
res.resize(poly.order() + 1, 0);
for (size_t i = 0; i <= poly.order(); ++i)
res[i] -= poly[i];
// removing extra zeros
for (size_t i = res.size() - 1; i > 0; --i)
{
if (res[i] != 0)
break;
else
res.pop_back();
}
return polynomial(res);
}
polynomial polynomial::operator-(const polynomial &poly) const
{
return this->minus(poly);
}
polynomial &polynomial::operator-=(const polynomial &poly)
{
this->subtract(poly);
return *this;
}
void polynomial::multiply(const polynomial &poly)
{
std::vector<long double> res(this->order() + poly.order() + 1, 0);
for (std::size_t i = 0; i <= this->order(); ++i)
for (std::size_t j = 0; j <= poly.order(); ++j)
res[i + j] += coefficients[i] * poly[j];
coefficients = res;
}
polynomial polynomial::times(const polynomial &poly) const
{
std::vector<long double> res(this->order() + poly.order() + 1, 0);
for (std::size_t i = 0; i <= this->order(); ++i)
for (std::size_t j = 0; j <= poly.order(); ++j)
res[i + j] += coefficients[i] * poly[j];
return polynomial(res);
}
polynomial polynomial::operator*(const polynomial &poly) const
{
return this->times(poly);
}
polynomial &polynomial::operator*=(const polynomial &poly)
{
this->multiply(poly);
return *this;
}
polynomial add(const polynomial &poly1, const polynomial &poly2)
{
return poly1.plus(poly2);
}
polynomial subtract(const polynomial &poly1, const polynomial &poly2)
{
return poly1.minus(poly2);
}
polynomial multiply(const polynomial &poly1, const polynomial &poly2)
{
return poly1.times(poly2);
}
bool polynomial::operator==(const polynomial& poly) const
{
if (this->order() != poly.order())
return false;
for (std::size_t i = 0; i <= this->order(); ++i)
if (coefficients[i] != poly[i])
return false;
return true;
}
void polynomial::print(std::ostream &out) const
{
print(out, var);
}
void polynomial::print(std::ostream &out, const char variable) const
{
std::size_t exponent = this->order() + 1;
while (exponent > 0)
{
--exponent;
long double num = coefficients[exponent];
if (num != 0)
{
if (num < 0)
{
num *= -1;
out << "- ";
}
else if (exponent != this->order())
out << "+ ";
out << num;
if (exponent > 0)
{
out << variable;
if (exponent > 1)
out << '^' << exponent;
}
out << ' ';
}
}
}
std::ostream &operator<<(std::ostream &out, const polynomial &poly)
{
poly.print(out);
return out;
}
std::istream &operator>>(std::istream &in, polynomial &poly)
{
std::string input;
std::getline(in >> std::ws, input);
poly = input;
return in;
}
</code></pre>
<h1>Unit tests</h1>
<pre><code>void TestPolynomialConstructor()
{
assert(polynomial("3x + 1 - x + 4x^2") == polynomial("4x^2 + 2x + 1"));
}
void TestPolynomialConstructor_void()
{
polynomial poly("0"), poly_void;
assert(poly == poly_void);
}
void TestPolynomialConstructor_var()
{
polynomial poly1("3t + 1 - t + 4t^2", 't'), poly2("3x + 1 - x + 4x^2");
poly2.var = 't';
assert(poly1 == poly2);
}
void TestPolynomialOrder()
{
polynomial poly("6x^3 + 5 + 10x^2");
assert(poly.order() == 3);
}
void TestPolynomialCoefficient()
{
polynomial poly("3x + 1 - x + 4x^2");
assert(poly.coefficient(1) == 2);
}
void TestPolynomialCoefficient_operator()
{
polynomial poly("3x + 1 - x + 4x^2");
assert(poly[1] == 2);
}
void TestPolynomialAddition_plus()
{
polynomial poly1("6x^3 + 5 + 10x^2"), poly2("3x + 1 - x + 4x^2");
assert(poly1.plus(poly2) == polynomial("6x^3 + 14x^2 + 2x + 6"));
}
void TestPolynomialAddition_operator()
{
polynomial poly1("6x^3 + 5 + 10x^2"), poly2("3x + 1 - x + 4x^2");
assert(poly1 + poly2 == polynomial("6x^3 + 14x^2 + 2x + 6"));
}
void TestPolynomialAddition_addtothis()
{
polynomial poly1("6x^3 + 5 + 10x^2"), poly2("3x + 1 - x + 4x^2");
poly1.add(poly2);
assert(poly1 == polynomial("6x^3 + 14x^2 + 2x + 6"));
}
void TestPolynomialAddition_addtothis_operator()
{
polynomial poly1("6x^3 + 5 + 10x^2"), poly2("3x + 1 - x + 4x^2");
poly1 += poly2;
assert(poly1 == polynomial("6x^3 + 14x^2 + 2x + 6"));
}
void TestPolynomialAddition_function()
{
polynomial poly1("6x^3 + 5 + 10x^2"), poly2("3x + 1 - x + 4x^2");
assert(add(poly1, poly2) == polynomial("6x^3 + 14x^2 + 2x + 6"));
}
void TestPolynomialSubtraction_minus()
{
polynomial poly1("6x^3 + 5 + 10x^2"), poly2("6x^3 + 3x + 1 - x + 4x^2");
assert(poly1.minus(poly2) == polynomial("6x^2 - 2x + 4"));
}
void TestPolynomialSubtraction_operator()
{
polynomial poly1("6x^3 + 5 + 10x^2"), poly2("6x^3 + 3x + 1 - x + 4x^2");
assert(poly1 - poly2 == polynomial("6x^2 - 2x + 4"));
}
void TestPolynomialSubtraction_subtractfromthis()
{
polynomial poly1("6x^3 + 5 + 10x^2"), poly2("6x^3 + 3x + 1 - x + 4x^2");
poly1.subtract(poly2);
assert(poly1 == polynomial("6x^2 - 2x + 4"));
}
void TestPolynomialSubtraction_subtractfromthis_operator()
{
polynomial poly1("6x^3 + 5 + 10x^2"), poly2("6x^3 + 3x + 1 - x + 4x^2");
poly1 -= poly2;
assert(poly1 == polynomial("6x^2 - 2x + 4"));
}
void TestPolynomialSubtraction_function()
{
polynomial poly1("6x^3 + 5 + 10x^2"), poly2("6x^3 + 3x + 1 - x + 4x^2");
assert(subtract(poly1, poly2) == polynomial("6x^2 - 2x + 4"));
}
void TestPolynomialMultiplication_times()
{
polynomial poly1("6x^3 + 5 + 10x^2"), poly2("3x + 1 - x + 4x^2");
assert(poly1.times(poly2) == polynomial("24x^5 + 52x^4 + 26x^3 + 30x^2 + 10x + 5"));
}
void TestPolynomialMultiplication_operator()
{
polynomial poly1("6x^3 + 5 + 10x^2"), poly2("3x + 1 - x + 4x^2");
assert(poly1 * poly2 == polynomial("24x^5 + 52x^4 + 26x^3 + 30x^2 + 10x + 5"));
}
void TestPolynomialMultiplication_multiplybythis()
{
polynomial poly1("6x^3 + 5 + 10x^2"), poly2("3x + 1 - x + 4x^2");
poly1.multiply(poly2);
assert(poly1 == polynomial("24x^5 + 52x^4 + 26x^3 + 30x^2 + 10x + 5"));
}
void TestPolynomialMultiplication_multiplybythis_operator()
{
polynomial poly1("6x^3 + 5 + 10x^2"), poly2("3x + 1 - x + 4x^2");
poly1 *= poly2;
assert(poly1 == polynomial("24x^5 + 52x^4 + 26x^3 + 30x^2 + 10x + 5"));
}
void TestPolynomialMultiplication_function()
{
polynomial poly1("6x^3 + 5 + 10x^2"), poly2("3x + 1 - x + 4x^2");
assert(multiply(poly1, poly2) == polynomial("24x^5 + 52x^4 + 26x^3 + 30x^2 + 10x + 5"));
}
</code></pre>
<h1>Test Program</h1>
<p><strong><em>main.cpp</em></strong></p>
<pre><code>#include <iostream>
#include <string>
#include <vector>
#include "polynomial.hpp"
int main()
{
std::string choice;
std::cout << "Select functionality (Enter 'add' for addition, 'sub' for subtraction,"
"'mul' for multiplication, and 'equ' to check equality between polynomials): ";
std::cin >> choice;
std::cout << "Enter two polynomials:\n";
polynomial poly1, poly2;
std::cin >> poly1 >> poly2;
if (choice == "add")
std::cout << poly1 + poly2;
else if (choice == "sub")
std::cout << poly1 - poly2;
else if (choice == "mul")
std::cout << poly1 * poly2;
else if (choice == "equ")
{
if (poly1 == poly2)
std::cout << "Polynomials are equal";
else
std::cout << "Polynomials are not equal";
}
else
std::cout << "Invalid functionality";
std::cin.get();
}
</code></pre>
<p>The <code>main()</code> function is just intended as a test, so it isn't optimal.<br><br>
Let me know what you think!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T13:23:57.793",
"Id": "469346",
"Score": "0",
"body": "How are these unit tests executed?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T13:37:35.287",
"Id": "469347",
"Score": "0",
"body": "@πάνταῥεῖ I call the test functions in a \"unittests.cpp\" file which is compiled separately."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T00:41:01.020",
"Id": "469377",
"Score": "0",
"body": "How do you define a polynomial? Is the `x` an indeterminate (so `3x` != `3t`) or a variable (so `3x` and `3t` are the same function)?"
}
] | [
{
"body": "<h1>Interface</h1>\n\n<p>The first thing I notice is that there is a lot of duplicated functions, because you provide a named function for each overloaded operator: <code>coefficient</code>, <code>add</code>, <code>plus</code>, <code>subtract</code>, <code>minus</code>, <code>multiply</code>, <code>times</code>, and <code>print</code>. Some of them even have non-member versions. This is not common practice in C++ as far as I can tell, so just eliminate them.</p>\n\n<p>Returning a top-level <code>const</code> type is not helpful, because the cv-qualifications of non-class type prvalues are automatically stripped, and it is occasionally useful to perform a non-<code>const</code> operation on a class prvalue. Marking a parameter as top-level <code>const</code> is also not helpful (especially in declarations), because they are stripped as part of the function signature and the point of passing by value is often just to get a modifiable object.</p>\n\n<p>For small types like <code>std::size_t</code>, passing by value is more efficient than passing by const reference.</p>\n\n<p>Binary operators are often overloaded as non-member functions, to minimize the burden of the class.</p>\n\n<p>Some constructors should be marked as <code>explicit</code>, to prevent unwanted implicit conversion:</p>\n\n<pre><code>explicit polynomial(const std::string&);\nexplicit polynomial(const std::vector<long double>&);\n</code></pre>\n\n<p>Also, consider taking <code>std::string_view</code>s instead of <code>const std::string&</code>s. The coefficient constructor should take the argument by value and move in, to enable move semantics:</p>\n\n<pre><code>explicit polynomial(std::vector<long double> coeff)\n : coefficients{std::move(coeff)}\n{\n remove_trailing_zeros();\n}\n</code></pre>\n\n<p>This function:</p>\n\n<pre><code>polynomial &operator=(const std::string&);\n</code></pre>\n\n<p>is unnecessary if the constructors are not explicit. If they are, then this function probably shouldn't exist either because it's basically implicit conversion.</p>\n\n<h1>Design</h1>\n\n<p>Right now, you represent zero polynomials as <code>[0]</code>, and treat their order as zero. This is wrong, because the order of zero polynomials are usually left undefined or defined as negative infinity. Rules like</p>\n\n<p><span class=\"math-container\">$$\n\\deg(AB) = \\deg(A) + \\deg(B)\n$$</span></p>\n\n<p>will cease to work zero polynomials have order zero. Consider representing zero polynomials as <code>[]</code> and throw an exception (or return a special type) in the <code>order</code> function.</p>\n\n<p>Allowing write access to coefficients is not a good option, because this may break the no-trailing-zero class invariant. The process of stripping trailing zeros can be extracted into a function:</p>\n\n<pre><code>private:\n void remove_trailing_zeros()\n {\n // ...\n }\n</code></pre>\n\n<p>As I mentioned in a comment, I'm not sure if the name of the variable should be considered part of the polynomial. Conceptually, the variable should probably be specified as an output manipulator, like this:</p>\n\n<pre><code>std::cout << set_variable(\"x\") << polynomial;\n</code></pre>\n\n<p>This can be implemented by adding facets to the locale of the stream (or by using the <code>std::ios_base::xalloc</code> mechanism if you want to be immune to locale changes).</p>\n\n<p>Also consider making the class a template on the value type.</p>\n\n<h1>Implementation</h1>\n\n<p><code>(character >= '0' && character <= '9')</code> can be replaced by <code>std::isdigit(character)</code> (or <code>std::isdigit(character, std::locale::classic())</code> if someone called <code>std::setlocale</code>).</p>\n\n<p>In my opinion, it is more convenient to implement modifying operations (<code>+=</code>, etc.) based on non-modifying operations (<code>+</code>, etc.) in this case, because we need to copy anyway:</p>\n\n<pre><code>friend polynomial operator+(const polynomial& lhs, const polynomial& rhs)\n{\n const auto& [small, large] = std::minmax(lhs, rhs,\n [](const auto& a, const auto& b) {\n return a.size() < b.size();\n }\n );\n\n auto result = large;\n std::transform(small.begin(), small.end(), result.begin(), result.begin(), std::plus{});\n return polynomial{std::move(result)}; // trailing zeros removed in constructor\n}\n\npolynomial& operator+=(const polynomial& other)\n{\n return *this = *this + other;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T06:25:13.703",
"Id": "469384",
"Score": "0",
"body": "I learned a lot from your review. Thank you for being thorough and concise. I do agree that there are too many functions for the same thing; I wanted to provide functions for every style. but come to think of it, it's unnecessary. Should I keep at least one alternative to operator overloads? (like add(poly1, poly2) for + operator overload)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T06:28:18.747",
"Id": "469385",
"Score": "1",
"body": "@SalehShamloo If the function is identical to the operator, I'd say no, the operator is sufficient, so it isn't necessary to duplicate the same functionality. If there is no operator that naturally fits the operation, then go ahead and provide a named function - `order` is a good example."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T05:17:22.897",
"Id": "239301",
"ParentId": "239271",
"Score": "2"
}
},
{
"body": "<h1><code>long double</code></h1>\n<p><code>long double</code> is a niche type with an inconsistent interpretation: sometimes it's a plain old 64bit <code>double</code>, sometimes 80bits extended-precision, sometimes (rarely) 128bit aka "quad". In the 80bit case, the actual storage requirement may be 10, 12 or 16 bytes. What you get depends on the targeted processor as well as the compiler and perhaps any special options given to the compiler. Such variations are not merely theoretical. For example, MSVC and GCC treat <code>long double</code> differently, even when they both target x86.</p>\n<p>You can use it, but expect inconsistent results, even more than usual for floating point.</p>\n<h1>Leading zeroes?</h1>\n<p>The "no leading zeroes" invariant is easy to break:</p>\n<pre><code>polynomial p = { "0x+1" };\n</code></pre>\n<p>Which gets printed back as <code>+ 1</code> instead of <code>1</code>.</p>\n<p>You could argue that it's my fault for giving strange input intentionally, but it could be neater. Also, multiplication exacerbates the issue:</p>\n<pre><code>polynomial q = p * p;\n</code></pre>\n<p>Now <code>q</code> has two leading zeroes.</p>\n<p>Leading zeroes can also be created from scratch, for example:</p>\n<pre><code>polynomial p = { "0.00000000000000001x+1" };\np = p * p;\np = p * p;\np = p * p;\np = p * p;\np = p * p;\np = p * p;\n</code></pre>\n<p>Due to the limited exponent range of whatever a <code>long double</code> turn out to be, eventually zeroes appear. I tried this with MSVC so <code>long double == double</code>, out of the 65 coefficients only the first 20 are non-zero. Of course, I'm using this strange example intentionally to cause the issue, it may not be a concern for your assignment.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T11:26:33.077",
"Id": "239313",
"ParentId": "239271",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "239301",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T13:21:18.933",
"Id": "239271",
"Score": "4",
"Tags": [
"c++",
"object-oriented"
],
"Title": "Polynomial Class in C++"
} | 239271 |
<p>I implemented the following Tron cycle game so that it can be run on GameCube / Wii devices (quarantine...). Indeed, there exist many tools (I rely on <a href="https://wiibrew.org/wiki/DevkitPPC" rel="noreferrer">devkitPPC</a>) and I thought a Tron game would be an easy starting point for this kind of development.</p>
<p>I have no experience in C, neither in enforcing "classes" in C, or in game development (the naming might be horrible), therefore, any help would be welcomed!</p>
<p>The directory structure is as follows:</p>
<pre><code>├── Makefile
├── source
│ └── tron.c
└── textures
├── ballsprites.png
└── textures.scf
</code></pre>
<p>And the different files are presented below (the only ones I wrote are tron.c and the sprites, all the credit for the rest goes to the team behind the devkit!).</p>
<p><code>Wall walls[NUM_PLAYERS][NUM_WALLS];</code> is a global variable, and not an attribute of the <code>VersusEngineManager</code> class, because the emulator kept firing weird memory errors. Any help on this point would be great!</p>
<p><strong>textures.scf</strong></p>
<pre><code><filepath="ballsprites.png" id="ballsprites" colfmt=6 />
</code></pre>
<p><strong>tron.c</strong></p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#include <math.h>
#include <gccore.h>
#include <ogc/tpl.h>
#include "textures_tpl.h"
#include "textures.h"
#define DEFAULT_FIFO_SIZE (256*1024)
static void *frameBuffer[2] = { NULL, NULL};
static GXRModeObj *rmode;
#define NUM_PLAYERS 2
#define NUM_WALLS 20000
#define SPEED 0x200
#define SPRITE_SIZE 4
#define WIDTH 640
#define HEIGHT 480
#define UPPER_MARGIN 20
#define TV_MARGIN 50
typedef struct
{
int x, y;
} Point;
bool Point_CheckInRectangle(Point *self, int xmin, int xmax, int ymin, int ymax);
bool Point_CheckCollision(Point *self, Point *other);
typedef struct
{
int x, y;
int dx, dy;
int image;
} Player;
int Player_init(Player *self, int x, int y, int dx, int dy, int image);
void Player_UpdatePosition(Player *self);
typedef struct
{
int x, y;
int image;
} Wall;
int playerLossesCount[NUM_PLAYERS];
Wall walls[NUM_PLAYERS][NUM_WALLS];
typedef struct
{
int speed;
int nPlayers;
int wallIndex;
Player players[NUM_PLAYERS];
} VersusEngineManager;
int VersusEngineManager_init(VersusEngineManager *self, int speed, int nPlayers);
bool VersusEngineManager_CheckPlayersCollision(VersusEngineManager *self);
bool VersusEngineManager_CheckWallCollision(VersusEngineManager *self, int playerId);
int VersusEngineManager_UpdateGameState(VersusEngineManager *self);
void VersusEngineManager_UpdatePlayerDirectionFromPAD(VersusEngineManager *self, int pad, int playerId);
void VersusEngineManager_UpdatePlayersDirectionFromPADs(VersusEngineManager *self);
void VersusEngineManager_UpdatePlayersDirectionFromPADs(VersusEngineManager *self)
{
VersusEngineManager_UpdatePlayerDirectionFromPAD(self, 0, 0);
VersusEngineManager_UpdatePlayerDirectionFromPAD(self, 1, 1);
}
typedef struct
{
int spriteSize;
} SpriteDrawer;
int SpriteDrawer_init(SpriteDrawer *self, int spriteSize);
void SpriteDrawer_Rectangle(SpriteDrawer *self, int x, int y, int width, int height, int image);
void SpriteDrawer_SpriteTex(SpriteDrawer *self, int x, int y, int width, int height, int image);
void SpriteDrawer_AllSprites(SpriteDrawer *self);
void SpriteDrawer_Sprites(SpriteDrawer *self, VersusEngineManager *versusEngineManager);
void SpriteDrawer_Scores(SpriteDrawer *self, VersusEngineManager *versusEngineManager);
void SpriteDrawer_ArenaSprites(SpriteDrawer *self);
GXTexObj texObj;
int main( int argc, char **argv ){
u32 fb; // initial framebuffer index
u32 first_frame;
f32 yscale;
u32 xfbHeight;
Mtx44 perspective;
Mtx GXmodelView2D;
void *gp_fifo = NULL;
GXColor background = {0, 0, 0, 0xff};
VIDEO_Init();
rmode = VIDEO_GetPreferredMode(NULL);
fb = 0;
first_frame = 1;
// allocate 2 framebuffers for double buffering
frameBuffer[0] = MEM_K0_TO_K1(SYS_AllocateFramebuffer(rmode));
frameBuffer[1] = MEM_K0_TO_K1(SYS_AllocateFramebuffer(rmode));
VIDEO_Configure(rmode);
VIDEO_SetNextFramebuffer(frameBuffer[fb]);
VIDEO_SetBlack(FALSE);
VIDEO_Flush();
VIDEO_WaitVSync();
if(rmode->viTVMode&VI_NON_INTERLACE) VIDEO_WaitVSync();
fb ^= 1;
// setup the fifo and then init the flipper
gp_fifo = memalign(32,DEFAULT_FIFO_SIZE);
memset(gp_fifo,0,DEFAULT_FIFO_SIZE);
GX_Init(gp_fifo,DEFAULT_FIFO_SIZE);
// clears the bg to color and clears the z buffer
GX_SetCopyClear(background, 0x00ffffff);
// other gx setup
GX_SetViewport(0,0,rmode->fbWidth,rmode->efbHeight,0,1);
yscale = GX_GetYScaleFactor(rmode->efbHeight,rmode->xfbHeight);
xfbHeight = GX_SetDispCopyYScale(yscale);
GX_SetScissor(0,0,rmode->fbWidth,rmode->efbHeight);
GX_SetDispCopySrc(0,0,rmode->fbWidth,rmode->efbHeight);
GX_SetDispCopyDst(rmode->fbWidth,xfbHeight);
GX_SetCopyFilter(rmode->aa,rmode->sample_pattern,GX_TRUE,rmode->vfilter);
GX_SetFieldMode(rmode->field_rendering,((rmode->viHeight==2*rmode->xfbHeight)?GX_ENABLE:GX_DISABLE));
if (rmode->aa)
GX_SetPixelFmt(GX_PF_RGB565_Z16, GX_ZC_LINEAR);
else
GX_SetPixelFmt(GX_PF_RGB8_Z24, GX_ZC_LINEAR);
GX_SetCullMode(GX_CULL_NONE);
GX_CopyDisp(frameBuffer[fb],GX_TRUE);
GX_SetDispCopyGamma(GX_GM_1_0);
// setup the vertex descriptor
// tells the flipper to expect direct data
GX_SetVtxAttrFmt(GX_VTXFMT0, GX_VA_POS, GX_POS_XY, GX_F32, 0);
GX_SetVtxAttrFmt(GX_VTXFMT0, GX_VA_TEX0, GX_TEX_ST, GX_F32, 0);
GX_SetNumChans(1);
GX_SetNumTexGens(1);
GX_SetTevOp(GX_TEVSTAGE0, GX_REPLACE);
GX_SetTevOrder(GX_TEVSTAGE0, GX_TEXCOORD0, GX_TEXMAP0, GX_COLOR0A0);
GX_SetTexCoordGen(GX_TEXCOORD0, GX_TG_MTX2x4, GX_TG_TEX0, GX_IDENTITY);
GX_InvalidateTexAll();
TPLFile spriteTPL;
TPL_OpenTPLFromMemory(&spriteTPL, (void *)textures_tpl,textures_tpl_size);
TPL_GetTexture(&spriteTPL,ballsprites,&texObj);
GX_LoadTexObj(&texObj, GX_TEXMAP0);
guOrtho(perspective,0,479,0,639,0,300);
GX_LoadProjectionMtx(perspective, GX_ORTHOGRAPHIC);
PAD_Init();
srand(time(NULL));
GX_SetViewport(0,0,rmode->fbWidth,rmode->efbHeight,0,1);
guMtxIdentity(GXmodelView2D);
guMtxTransApply (GXmodelView2D, GXmodelView2D, 0.0F, 0.0F, -5.0F);
GX_LoadPosMtxImm(GXmodelView2D,GX_PNMTX0);
GX_SetZMode(GX_TRUE, GX_LEQUAL, GX_TRUE);
GX_SetBlendMode(GX_BM_BLEND, GX_BL_SRCALPHA, GX_BL_INVSRCALPHA, GX_LO_CLEAR);
GX_SetAlphaUpdate(GX_TRUE);
GX_SetColorUpdate(GX_TRUE);
VersusEngineManager versusEngineManager;
VersusEngineManager_init(&versusEngineManager, SPEED, NUM_PLAYERS);
SpriteDrawer spriteDrawer;
SpriteDrawer_init(&spriteDrawer, SPRITE_SIZE);
while(1) {
GX_InvVtxCache();
GX_InvalidateTexAll();
GX_ClearVtxDesc();
GX_SetVtxDesc(GX_VA_POS, GX_DIRECT);
GX_SetVtxDesc(GX_VA_TEX0, GX_DIRECT);
VersusEngineManager_UpdatePlayersDirectionFromPADs(&versusEngineManager);
int gameState = VersusEngineManager_UpdateGameState(&versusEngineManager);
if(gameState==1) { VersusEngineManager_init(&versusEngineManager, SPEED, NUM_PLAYERS); }
SpriteDrawer_Sprites(&spriteDrawer, &versusEngineManager);
GX_DrawDone();
GX_CopyDisp(frameBuffer[fb],GX_TRUE);
VIDEO_SetNextFramebuffer(frameBuffer[fb]);
if(first_frame) {
VIDEO_SetBlack(FALSE);
first_frame = 0;
}
VIDEO_Flush();
VIDEO_WaitVSync();
fb ^= 1; // flip framebuffer
}
return 0;
}
float texCoords[] = {
0.0 ,0.0 , 0.5, 0.0, 0.5, 0.5, 0.0, 0.5,
0.5 ,0.0 , 1.0, 0.0, 1.0, 0.5, 0.5, 0.5,
0.0 ,0.5 , 0.5, 0.5, 0.5, 1.0, 0.0, 1.0,
0.5 ,0.5 , 1.0, 0.5, 1.0, 1.0, 0.5, 1.0
};
int SpriteDrawer_init(SpriteDrawer *self, int spriteSize)
{
self->spriteSize = spriteSize;
return 0;
}
void SpriteDrawer_Sprites(SpriteDrawer *self, VersusEngineManager *versusEngineManager) {
int spriteSize = self->spriteSize;
for(int playerId=0;playerId<NUM_PLAYERS;playerId++){
SpriteDrawer_SpriteTex(self,
versusEngineManager->players[playerId].x >> 8,
versusEngineManager->players[playerId].y >> 8,
spriteSize,
spriteSize,
versusEngineManager->players[playerId].image);
for(int wallId=0; wallId < NUM_WALLS; wallId++) {
SpriteDrawer_SpriteTex(self,
walls[playerId][wallId].x >> 8,
walls[playerId][wallId].y >> 8,
spriteSize,
spriteSize,
walls[playerId][wallId].image);
}
}
SpriteDrawer_ArenaSprites(self);
SpriteDrawer_Scores(self, versusEngineManager);
};
void SpriteDrawer_ArenaSprites(SpriteDrawer *self) {
int spriteSize = self->spriteSize;
SpriteDrawer_Rectangle(self, TV_MARGIN,UPPER_MARGIN+TV_MARGIN, WIDTH-2*TV_MARGIN-spriteSize, HEIGHT - 2*TV_MARGIN - spriteSize,3);
};
void SpriteDrawer_Rectangle(SpriteDrawer *self, int x,int y,int width,int height,int sprite) {
int spriteSize = self->spriteSize;
for(int i=x; i < x+width;i+=spriteSize){
SpriteDrawer_SpriteTex(self, i,y,spriteSize, spriteSize, sprite);
}
for(int i=x; i < x+width+spriteSize;i+=spriteSize){
SpriteDrawer_SpriteTex(self, i,y+height,spriteSize, spriteSize, sprite);
}
for(int i=y; i < y+height;i+=spriteSize){
SpriteDrawer_SpriteTex(self, x,i,spriteSize, spriteSize, sprite);
}
for(int i=y; i < y+height;i+=spriteSize){
SpriteDrawer_SpriteTex(self, x+width,i,spriteSize, spriteSize, sprite);
}
};
void SpriteDrawer_Scores(SpriteDrawer *self, VersusEngineManager *versusEngineManager) {
int spriteSize = self->spriteSize;
for(int playerId=0;playerId<NUM_PLAYERS;playerId++){
for(int score=0;score < playerLossesCount[playerId]; score++){
SpriteDrawer_SpriteTex(self, TV_MARGIN + ( (score * SPEED) >> 8), TV_MARGIN + 2* SPEED * (1 + playerId) >> 8, spriteSize, spriteSize, versusEngineManager->players[playerId].image);
}
}
};
void SpriteDrawer_SpriteTex(SpriteDrawer *self, int x, int y, int width, int height, int image ) {
int texIndex = image * 8;
GX_Begin(GX_QUADS, GX_VTXFMT0, 4); // Draw A Quad
GX_Position2f32(x, y); // Top Left
GX_TexCoord2f32(texCoords[texIndex],texCoords[texIndex+1]);
texIndex+=2;
GX_Position2f32(x+width-1, y); // Top Right
GX_TexCoord2f32(texCoords[texIndex],texCoords[texIndex+1]);
texIndex+=2;
GX_Position2f32(x+width-1,y+height-1); // Bottom Right
GX_TexCoord2f32(texCoords[texIndex],texCoords[texIndex+1]);
texIndex+=2;
GX_Position2f32(x,y+height-1); // Bottom Left
GX_TexCoord2f32(texCoords[texIndex],texCoords[texIndex+1]);
GX_End(); // Done Drawing The Quad
}
int Player_init(Player *self, int x, int y, int dx, int dy, int image)
{
self->x = x;
self->y = y;
self->dx = dx;
self->dy = dy;
self->image = image;
return 0;
}
void Player_UpdatePosition(Player *self)
{
self->x += self->dx;
self->y += self->dy;
}
bool Point_CheckInRectangle(Point *self, int xmin, int xmax, int ymin, int ymax)
{
return self->x < xmin || self->x > xmax || self->y < ymin || self->y > ymax;
}
bool Point_CheckCollision(Point *self, Point *other)
{
return self->x == other->x && self->y==other->y;
}
int VersusEngineManager_init(VersusEngineManager *self, int speed, int nPlayers)
{
self->speed = speed;
self->nPlayers = nPlayers;
self->wallIndex = 0;
Player player0, player1;
Player_init(&player0, ((WIDTH - SPRITE_SIZE ) / 2 ) << 8,100 << 8,0, SPEED, 0);
Player_init(&player1, ((WIDTH - SPRITE_SIZE ) / 2 ) << 8,400 << 8,0, -SPEED, 1);
self->players[0] = player0;
self->players[1] = player1;
for(int playerId=0;playerId<self->nPlayers;playerId++){
for(int wallId=0; wallId < NUM_WALLS; wallId++) {
walls[playerId][wallId].x = 0;
walls[playerId][wallId].y = 0;
walls[playerId][wallId].image = 2;
}
}
return 0;
}
bool VersusEngineManager_CheckPlayersCollision(VersusEngineManager *self)
{
for(int i=0; i < self->nPlayers; i++)
{
for(int j=i+1; j < self->nPlayers; j++)
{
if(Point_CheckCollision(&self->players[i], &self->players[j]) ) {
return true; }
}
}
return false;
};
bool VersusEngineManager_CheckWallCollision(VersusEngineManager *self, int playerId)
{
if(Point_CheckInRectangle(&self->players[playerId],
TV_MARGIN<<8,
WIDTH-SPRITE_SIZE-TV_MARGIN << 8,
(UPPER_MARGIN + TV_MARGIN) <<8 ,
(HEIGHT+UPPER_MARGIN-SPRITE_SIZE-TV_MARGIN) << 8))
{return true;}
for(int i=0;i<NUM_PLAYERS;i++){
for(int wallId=0; wallId < self->wallIndex; wallId++) {
if(self->players[playerId].x == walls[i][wallId].x && self->players[playerId].y == walls[i][wallId].y) {
return true;
}
}
}
return false;
}
int VersusEngineManager_UpdateGameState(VersusEngineManager *self)
{
for(int playerId=0;playerId<self->nPlayers;playerId++){
Player_UpdatePosition(&self->players[playerId]);
bool collision = false;
if (VersusEngineManager_CheckPlayersCollision(self)) {
collision = true;
}
else if(VersusEngineManager_CheckWallCollision(self, playerId)) {
playerLossesCount[playerId] += 1;
collision = true;
}
walls[playerId][self->wallIndex].x = self->players[playerId].x;
walls[playerId][self->wallIndex].y = self->players[playerId].y;
walls[playerId][self->wallIndex].image = playerId;
if(collision) {return 1;} ;
}
self->wallIndex += 1;
return 0;
};
void VersusEngineManager_UpdatePlayerDirectionFromPAD(VersusEngineManager *self, int pad, int playerId)
{
PAD_ScanPads();
if (PAD_ButtonsDown(pad) & PAD_BUTTON_LEFT) {
if (self->players[playerId].dx ==0) {
self->players[playerId].dx = -self->speed;
self->players[playerId].dy = 0;
return;
}
}
if (PAD_ButtonsDown(pad) & PAD_BUTTON_RIGHT) {
if (self->players[playerId].dx ==0) {
self->players[playerId].dx = self->speed;
self->players[playerId].dy = 0;
return;
}
}
if (PAD_ButtonsDown(pad) & PAD_BUTTON_UP) {
if (self->players[playerId].dy ==0) {
self->players[playerId].dx = 0;
self->players[playerId].dy = -self->speed;
return;
}
}
if (PAD_ButtonsDown(pad) & PAD_BUTTON_DOWN) {
if (self->players[playerId].dy ==0) {
self->players[playerId].dx = 0;
self->players[playerId].dy = self->speed;
return;
}
}
}
</code></pre>
<p><strong>Makefile</strong></p>
<pre><code>#---------------------------------------------------------------------------------
# Clear the implicit built in rules
#---------------------------------------------------------------------------------
.SUFFIXES:
.SECONDARY:
#---------------------------------------------------------------------------------
ifeq ($(strip $(DEVKITPPC)),)
$(error "Please set DEVKITPPC in your environment. export DEVKITPPC=<path to>devkitPPC")
endif
include $(DEVKITPPC)/wii_rules
#---------------------------------------------------------------------------------
# TARGET is the name of the output
# BUILD is the directory where object files & intermediate files will be placed
# SOURCES is a list of directories containing source code
# INCLUDES is a list of directories containing extra header files
#---------------------------------------------------------------------------------
TARGET := $(notdir $(CURDIR))
BUILD := build
SOURCES := source
DATA :=
TEXTURES := textures
INCLUDES :=
#---------------------------------------------------------------------------------
# options for code generation
#---------------------------------------------------------------------------------
CFLAGS = -g -O2 -Wall $(MACHDEP) $(INCLUDE)
CXXFLAGS = $(CFLAGS)
LDFLAGS = -g $(MACHDEP) -Wl,-Map,$(notdir $@).map
#---------------------------------------------------------------------------------
# any extra libraries we wish to link with the project
#---------------------------------------------------------------------------------
LIBS := -logc -lm
#---------------------------------------------------------------------------------
# list of directories containing libraries, this must be the top level containing
# include and lib
#---------------------------------------------------------------------------------
LIBDIRS :=
#---------------------------------------------------------------------------------
# no real need to edit anything past this point unless you need to add additional
# rules for different file extensions
#---------------------------------------------------------------------------------
ifneq ($(BUILD),$(notdir $(CURDIR)))
#---------------------------------------------------------------------------------
export OUTPUT := $(CURDIR)/$(TARGET)
export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \
$(foreach dir,$(DATA),$(CURDIR)/$(dir)) \
$(foreach dir,$(TEXTURES),$(CURDIR)/$(dir))
export DEPSDIR := $(CURDIR)/$(BUILD)
#---------------------------------------------------------------------------------
# automatically build a list of object files for our project
#---------------------------------------------------------------------------------
CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c)))
CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp)))
sFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s)))
SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.S)))
BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*)))
SCFFILES := $(foreach dir,$(TEXTURES),$(notdir $(wildcard $(dir)/*.scf)))
TPLFILES := $(SCFFILES:.scf=.tpl)
#---------------------------------------------------------------------------------
# use CXX for linking C++ projects, CC for standard C
#---------------------------------------------------------------------------------
ifeq ($(strip $(CPPFILES)),)
export LD := $(CC)
else
export LD := $(CXX)
endif
export OFILES_BIN := $(addsuffix .o,$(BINFILES)) $(addsuffix .o,$(TPLFILES))
export OFILES_SOURCES := $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(sFILES:.s=.o) $(SFILES:.S=.o)
export OFILES := $(OFILES_BIN) $(OFILES_SOURCES)
export HFILES := $(addsuffix .h,$(subst .,_,$(BINFILES))) $(addsuffix .h,$(subst .,_,$(TPLFILES)))
#---------------------------------------------------------------------------------
# build a list of include paths
#---------------------------------------------------------------------------------
export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \
$(foreach dir,$(LIBDIRS),-I$(dir)/include) \
-I$(CURDIR)/$(BUILD) \
-I$(LIBOGC_INC)
#---------------------------------------------------------------------------------
# build a list of library paths
#---------------------------------------------------------------------------------
export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib) \
-L$(LIBOGC_LIB)
export OUTPUT := $(CURDIR)/$(TARGET)
.PHONY: $(BUILD) clean
#---------------------------------------------------------------------------------
$(BUILD):
@[ -d $@ ] || mkdir -p $@
@$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile
#---------------------------------------------------------------------------------
clean:
@echo clean ...
@rm -fr $(BUILD) $(OUTPUT).elf $(OUTPUT).dol
#---------------------------------------------------------------------------------
else
#---------------------------------------------------------------------------------
# main targets
#---------------------------------------------------------------------------------
$(OUTPUT).dol: $(OUTPUT).elf
$(OUTPUT).elf: $(OFILES)
$(OFILES_SOURCES) : $(HFILES)
#---------------------------------------------------------------------------------
# This rule links in binary data with the .bin extension
#---------------------------------------------------------------------------------
%.bin.o %_bin.h : %.bin
#---------------------------------------------------------------------------------
@echo $(notdir $<)
@$(bin2o)
#---------------------------------------------------------------------------------
%.tpl.o %_tpl.h : %.tpl
#---------------------------------------------------------------------------------
@echo $(notdir $<)
@$(bin2o)
-include $(DEPSDIR)/*.d
#---------------------------------------------------------------------------------
endif
#---------------------------------------------------------------------------------
</code></pre>
<p><strong>ballsprites.png</strong></p>
<p><a href="https://i.stack.imgur.com/Gt7Wj.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Gt7Wj.png" alt="The ball sprite image"></a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T14:28:57.410",
"Id": "469350",
"Score": "0",
"body": "`textures.scf` smells like XML but doesn't have an enclosing XML tag. Is this expected?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T14:29:53.007",
"Id": "469351",
"Score": "1",
"body": "_firing weird memory errors. Any help on this point would be great!_ That isn't what CodeReview is for; for that you'll need to go on StackOverflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T14:30:44.663",
"Id": "469352",
"Score": "0",
"body": "textures.scf smells like XML but doesn't have an enclosing XML tag. Is this expected? Yes"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T16:00:54.727",
"Id": "469359",
"Score": "1",
"body": "To the contrary, your function names and variable names are lovely. I couldn't do any better. But you need to add some spaces. I won't put this in a review because it's not enough, though."
}
] | [
{
"body": "<h2>Statics</h2>\n\n<p>You have a one-file program, so more of your methods and globals, including these:</p>\n\n<pre><code>int playerLossesCount[NUM_PLAYERS];\nWall walls[NUM_PLAYERS][NUM_WALLS];\n\nGXTexObj texObj;\n</code></pre>\n\n<p>should be made <code>static</code>.</p>\n\n<h2>Declarations for variables</h2>\n\n<pre><code>int main( int argc, char **argv ){\n u32 fb; // initial framebuffer index\n u32 first_frame;\n f32 yscale;\n u32 xfbHeight;\n Mtx44 perspective;\n Mtx GXmodelView2D;\n void *gp_fifo = NULL;\n</code></pre>\n\n<p>This style is typical for pre-C99 code, but generally it's more difficult to follow the code this way. It's more legible if the variables are declared and initialized closer to where they're actually used.</p>\n\n<h2>Spaces</h2>\n\n<p>C is generally more free-form than (say) Python when it comes to whitespace, but this:</p>\n\n<pre><code>GX_SetScissor(0,0,rmode->fbWidth,rmode->efbHeight);\n</code></pre>\n\n<p>still needs more. Probably one space after each comma for this to be legible. Also, your brace style varies wildly; compare</p>\n\n<pre><code> if(Point_CheckCollision(&self->players[i], &self->players[j]) ) {\n return true; }\n</code></pre>\n\n<p>with</p>\n\n<pre><code>if(Point_CheckInRectangle(&self->players[playerId], \n TV_MARGIN<<8,\n WIDTH-SPRITE_SIZE-TV_MARGIN << 8,\n (UPPER_MARGIN + TV_MARGIN) <<8 ,\n (HEIGHT+UPPER_MARGIN-SPRITE_SIZE-TV_MARGIN) << 8)) \n{return true;}\n</code></pre>\n\n<p>with</p>\n\n<pre><code> if(self->players[playerId].x == walls[i][wallId].x && self->players[playerId].y == walls[i][wallId].y) {\n return true;\n } \n</code></pre>\n\n<p>The last one seems the sanest, but whatever you do, pick a style and stick with it.</p>\n\n<h2>Coordinates</h2>\n\n<p>Based on a reading of this:</p>\n\n<pre><code>float texCoords[] = {\n 0.0 ,0.0 , 0.5, 0.0, 0.5, 0.5, 0.0, 0.5,\n// ...\nGX_TexCoord2f32(texCoords[texIndex],texCoords[texIndex+1]);\n</code></pre>\n\n<p>it seems that you're flattening an array of coordinates to be represented as x, y, x, y... Your code would be more legible if you were to use an array of <code>Point</code> structures (you've even declared one yourself; you might as well use it). </p>\n\n<h2>Loop combination</h2>\n\n<p>This:</p>\n\n<pre><code>for(int i=y; i < y+height;i+=spriteSize){ \n SpriteDrawer_SpriteTex(self, x,i,spriteSize, spriteSize, sprite); \n}\nfor(int i=y; i < y+height;i+=spriteSize){ \n SpriteDrawer_SpriteTex(self, x+width,i,spriteSize, spriteSize, sprite);\n}\n</code></pre>\n\n<p>should become the equivalent</p>\n\n<pre><code>for(int i=y; i < y+height;i+=spriteSize){ \n SpriteDrawer_SpriteTex(self, x,i,spriteSize, spriteSize, sprite); \n SpriteDrawer_SpriteTex(self, x+width,i,spriteSize, spriteSize, sprite);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T14:46:27.407",
"Id": "239273",
"ParentId": "239272",
"Score": "6"
}
},
{
"body": "<p>There are no classes in C. However, there are functions.</p>\n\n<p>Regarding: </p>\n\n<pre><code>CFLAGS = -g -O2 -Wall $(MACHDEP) $(INCLUDE) \n</code></pre>\n\n<p>When compiling, always enable the warnings, then fix those warnings. ( for <code>gcc</code>, at a minimum use: <code>-Wall -Wextra -Wconversion -pedantic -std=gnu11</code> ) </p>\n\n<p>the <code>=</code> will cause this macro to be re-evaluated every time it is referenced. Suggest:</p>\n\n<pre><code>CFLAGS := -g -O2 -Wall $(MACHDEP) $(INCLUDE) \n</code></pre>\n\n<p>Notice the <code>:=</code> rather than <code>=</code></p>\n\n<p>The declared structs are not given a <code>tag</code> name. This becomes a problem when using a debugger as most debuggers require a tag name to be able to display the individual fields within the struct.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T16:36:23.680",
"Id": "239325",
"ParentId": "239272",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T13:43:01.800",
"Id": "239272",
"Score": "8",
"Tags": [
"object-oriented",
"c",
"game"
],
"Title": "Tron game on Wii / GameCube"
} | 239272 |
<p>I'm implementing Sieve of Eratosthenes by working with multiples of 30 and comparing it to <a href="https://codereview.stackexchange.com/a/112912/220639">multiples of 3 from a previous answer</a></p>
<p>code for multiples of 30:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
const unsigned int res[8] = {1,7,11,13,17,19,23,29};
const unsigned int N = 1000000000;
unsigned int i,j,k,th,tl;
u_int8_t *primes = calloc(N/30+1,sizeof(char));
// 0 is taken to be prime while 1 composite(opposite from the code for multiples of 3)
//jth bit of primes[i]: 30*i+res[j]
primes[0] = '\x01'; // initialize with 1 is not prime and the others are prime
unsigned int ub = sqrt(N)/30+1;
unsigned int t = N/30+1;
for(i=0;i<ub;++i){
for(j=0;j<8;++j){
//current number is i*30+res[j]
if(primes[i]>>j&1){// jth bit is set to 1
continue;
}
th=i; // high
tl=res[j]; // low
// 30*th+res[tl] is composite
while(1){
th+=i;
tl+=res[j];
if(tl>=30){
tl-=30;
th+=1;
} // adding prime to self
if(th>=t){
break;
} // exceeds bound
for(k=0;k<8;++k){
if(tl==res[k]){
primes[th]|=1<<k; // not a prime
break;
}
}
}
}
}
// counting primes
k=3; // 2,3,5
for(i=0;i<t-1;++i){
for(j=0;j<8;++j){
if(primes[i]>>j&1){
continue;
}
++k;
}
}
for(j=0;j<8;++j){
if(primes[i]>>j&1){
continue;
}
if(i*30+res[j]>N){
break;
}
++k;
}
printf("Number of primes equal or less than %d: %d\n",N,k);
free(primes);
return 0;
}
</code></pre>
<p>Timing both variants locally(with -O3 and without compiler optimization), this variant seems to perform worse than the one using multiples of 3:</p>
<pre><code>Multiples of 3 without optimization: 7.69
Multiples of 30 without optimization: 28.42
Multiples of 3 with optimization: 4.00
Multiples of 30 with optimization: 7.32
</code></pre>
<p>looking at the output of -O3 for both programs, the compiler only unrolls the loop and hardcodes some computation(i.e. sqrt(N)) and that's basically it, so either taking multiples of 30 is slower theoretically or the implementation is slower, which is more likely to be the case.</p>
<p><strong>Is there any way that this code can be optimized or is some better way to go about writing the sieve for multiples of 30?</strong></p>
<p>--code for multiples of 3 used as comparison--</p>
<pre><code>#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main(void){
unsigned int N = 1000000000;
unsigned int arraySize = (N/24 + 1);
uint32_t *primes = malloc(arraySize);
// The bits in primes follow this pattern:
//
// Bit 0 = 5, bit 1 = 7, bit 2 = 11, bit 3 = 13, bit 4 = 17, etc.
//
// For even bits, bit n represents 5 + 6*n
// For odd bits, bit n represents 1 + 6*n
memset(primes , 0xff, arraySize);
int sqrt_N = sqrt(N);
for(int i = 5; i <= sqrt_N; i += 4) {
int iBitNumber = i / 3 - 1;
int iIndex = iBitNumber >> 5;
int iBit = 1 << (iBitNumber & 31);
if ((primes[iIndex] & iBit) != 0) {
int increment = i+i;
for (int j = i * i; j < N; j += increment) {
int jBitNumber = j / 3 - 1;
int jIndex = jBitNumber >> 5;
int jBit = 1 << (jBitNumber & 31);
primes[jIndex] &= ~jBit;
j += increment;
if (j >= N)
break;
jBitNumber = j / 3 - 1;
jIndex = jBitNumber >> 5;
jBit = 1 << (jBitNumber & 31);
primes[jIndex] &= ~jBit;
// Skip multiple of 3.
j += increment;
}
}
i += 2;
iBit <<= 1;
if ((primes[iIndex] & iBit) != 0) {
int increment = i+i;
for (int j = i * i; j < N; j += increment) {
int jBitNumber = j / 3 - 1;
int jIndex = jBitNumber >> 5;
int jBit = 1 << (jBitNumber & 31);
primes[jIndex] &= ~jBit;
// Skip multiple of 3.
j += increment;
j += increment;
if (j >= N)
break;
jBitNumber = j / 3 - 1;
jIndex = jBitNumber >> 5;
jBit = 1 << (jBitNumber & 31);
primes[jIndex] &= ~jBit;
}
}
}
// Initial count includes 2, 3.
int count=2;
for (int i=5;i<N;i+=6) {
int iBitNumber = i / 3 - 1;
int iIndex = iBitNumber >> 5;
int iBit = 1 << (iBitNumber & 31);
if (primes[iIndex] & iBit) {
count++;
}
iBit <<= 1;
if (primes[iIndex] & iBit) {
count++;
}
}
printf("%d\n", count);
free(primes);
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T22:00:34.323",
"Id": "469373",
"Score": "0",
"body": "(I don't see *multiples of 3* - should that be 6?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T23:31:17.540",
"Id": "469374",
"Score": "0",
"body": "@greybeard yea it kinda is in multiples of 6 (6n-1 or 6n+1) but was written as multiples of 3 in the prev ans so kinda carried it here"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T08:00:25.697",
"Id": "469392",
"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)*."
}
] | [
{
"body": "<p>When the original multiples-of-3 code finds a prime, it starts setting bits with the square of that value (<code>for (int j = i * i</code>). Your multiples-of-30 code does not do this, and can waste a lot of time marking numbers \"not prime\" that have already been so marked. As the new prime gets larger, this will consume a growing amount of time.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T20:22:44.223",
"Id": "239286",
"ParentId": "239278",
"Score": "3"
}
},
{
"body": "<p>Using 1201ProgramAlarm's comment, the code ran slightly faster but was still slower than taking multiples of 3(effectively 6). However finding if the current composite number is in the multplicative group mod 30 seemed to be the one that took up a long time and could have been memoisation. This is done by precomputing how many times one adds the prime to reach the next composite that needs to be marked and also precomputing the squares(since the counting starts from i*i).</p>\n\n<p>Improved code:</p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nint main(){\n const unsigned int res[8] = {1,7,11,13,17,19,23,29};\n const unsigned int N = 1000000000;\n unsigned int nextelem[8][8][2]={}; //res[i]+nextelem[i][j][0]*res[j]=nextelem[i][j][1]\n unsigned int startk[8]={}; //res[i]*2=res[startk[j]]\n unsigned int i,j,k,ii,jj,kk;\n u_int8_t *primes = calloc(N/30+1,sizeof(char));\n //jth bit of primes[i]: 30*i+res[j]\n primes[0] = '\\x01';\n unsigned int ub = sqrt(N)/30+1;\n unsigned int t = N/30+1;\n for(i=0;i<8;++i){// genning nextelem\n for(j=0;j<8;++j){\n for(k=2;k<30;k+=2){\n for(ii=0;ii<8;++ii){\n if(res[ii]==(res[i]+k*res[j])%30){\n break;\n }\n }\n if(ii!=8){\n nextelem[i][j][0]=k;\n nextelem[i][j][1]=ii;\n break;\n }\n }\n }\n }\n for(i=0;i<8;++i){// genning startk\n for(j=0,k=(res[i]*res[i])%30;j<8;++j){\n if(res[j]==k){\n startk[i]=j;\n break;\n }\n }\n }\n for(i=0;i<ub;++i){\n for(j=0;j<8;++j){\n //current number is i*30+res[j]\n if(primes[i]>>j&1){// jth bit is set to 1\n continue;\n }\n // we start from the square and go up, have a lookup table to figure how much to increment\n ii=i*30+res[j];\n jj=ii*ii;\n k=startk[j];\n while(jj<N){\n primes[jj/30]|=1<<k; // jj not a prime\n jj+=nextelem[k][j][0]*ii;\n k=nextelem[k][j][1];\n }\n }\n }\n // counting primes\n k=3; // 2,3,5\n for(i=0;i<t-1;++i){\n for(j=0;j<8;++j){\n if(primes[i]>>j&1){\n continue;\n }\n ++k;\n }\n }\n for(j=0;j<8;++j){\n if(primes[i]>>j&1){\n continue;\n }\n if(i*30+res[j]>N){\n break;\n }\n ++k;\n }\n printf(\"Number of primes equal or less than %d: %d\\n\",N,k);\n free(primes);\n return 0;\n}\n</code></pre>\n\n<p>Just a nice property the multiplicative group is actually isomorphic to Z2xZ4=(11)x(7) so startk only consists of either res[0]=1 or res[5]=7^2=19</p>\n\n<p>Timings with -O3:</p>\n\n<pre><code>Multiples of 30: 2.70\nMultiples of 3: 3.57\n</code></pre>\n\n<p>which is a nice improvement.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T18:57:36.057",
"Id": "239415",
"ParentId": "239278",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "239286",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T16:15:21.970",
"Id": "239278",
"Score": "2",
"Tags": [
"performance",
"c",
"sieve-of-eratosthenes"
],
"Title": "Sieve of Eratosthenes optimisation"
} | 239278 |
<p>I've been experimenting with Hooks lately and looking more into how can I replace Redux with <code>useContext</code> and <code>useReduer</code>. For me, <a href="https://vuex.vuejs.org/" rel="nofollow noreferrer">Vuex</a> was more intuitive when I first got into stores and I prefer their state management pattern, so I tried to build something close to that using the React Context. </p>
<p>I aim to have one store/context for each page in my app or to have the ability to pull the store/context up, so it's available globally if needed. The final custom <code>useStore()</code> hook should return a store with the following parts:</p>
<p><code>{ state, mutations, actions, getters }</code></p>
<p><a href="https://i.stack.imgur.com/bx5qe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bx5qe.png" alt="enter image description here"></a></p>
<p>Components can then dispatch actions with <code>actions.dispatch({type: 'my-action', payload})</code> (actions commit mutations) or directly commit mutations with <code>mutations.commit({ type: 'my-mutation', payload})</code>. Mutations then mutate the state (using <code>useReducer</code>), which finally causes a rerender. </p>
<p>For my example, I have two entities inside <em>./models</em>. <code>User</code> (context/store provided globally) and <code>Post</code>(context/store provided on it's page):</p>
<pre><code>// User.ts
export interface User {
id: number
username: string
website: string
}
// Post.ts
export interface Post {
id: number
userId: number
title: string
}
</code></pre>
<p>I then create the reducers <em>./store/{entity}/structure/reducer.ts</em>:</p>
<pre><code>import { UserState } from './types'
import { UserMutations } from './types';
export function userReducer(state: UserState, mutation: UserMutations): UserState {
switch (mutation.type) {
// ...
case 'set-users':
return { ...state, users: [...state.users, ...mutation.users] }
// ...
}
}
</code></pre>
<p>Switch through mutations from <em>./store/{entity}/structure/mutations.ts</em></p>
<pre><code>import { User } from '../../../models/User';
import { AxiosError } from 'axios';
export const setUsers = (users: User[]) => ({
type: 'set-users',
users
} as const);
</code></pre>
<p>To get the state <em>./store/{entity}/structure/types/index.ts</em>: </p>
<pre><code>export interface UserState {
isLoading: boolean
error: AxiosError
users: User[]
}
</code></pre>
<p>Any heavier work (fetching data, etc.) before committing a mutation is located inside actions <em>./store/{entity}/structure/actions.ts</em>: </p>
<pre><code>import { UserMutations, UserActions } from "./types";
import axios, { AxiosResponse } from 'axios';
import { GET_USERS_URL, User } from "../../../models/User";
import { API_BASE_URL } from "../../../util/utils";
export const loadUsers = () => ({
type: 'load-users'
} as const);
export const initActions = (commit: React.Dispatch<UserMutations>) => {
const dispatch: React.Dispatch<UserActions> = async (action) => {
switch (action.type) {
case 'load-users':
try {
commit({ type: 'set-loading', isLoading: true })
const res: AxiosResponse<User[]> = await axios.get(`${API_BASE_URL}${GET_USERS_URL}`)
if (res.status === 200) {
const users: User[] = res.data.map((apiUser) => ({
id: apiUser.id,
username: apiUser.username,
website: apiUser.website
}))
commit({ type: 'set-users', users })
}
} catch (error) {
commit({ type: 'set-error', error })
} finally {
commit({ type: 'set-loading', isLoading: false })
}
break;
default:
break;
}
}
return dispatch
}
</code></pre>
<p>Additionally, a new derived state can be computed based on store state using getters <em>./store/{entity}/structure/getters.ts</em>: </p>
<pre><code>import { UserState, UserGetters } from "./types"
export const getters = (state: Readonly<UserState>): UserGetters => {
return {
usersReversed: [...state.users].reverse()
}
}
</code></pre>
<p>Finally, everything is initialized and glued together inside <em>./store/{entity}/Context.tsx</em>:</p>
<pre><code>import React, { createContext, useReducer } from 'react'
import { UserStore, UserState } from './structure/types'
import { userReducer } from './structure/reducer'
import { getters } from './structure/getters'
import { initActions } from './structure/actions'
import { AxiosError } from 'axios'
const initialStore: UserStore = {
state: {
isLoading: false,
error: {} as AxiosError,
users: []
} as UserState,
getters: {
usersReversed: []
},
mutations: {
commit: () => {}
},
actions: {
dispatch: () => {}
}
}
export const UserContext = createContext<UserStore>(initialStore)
export const UserContextProvider: React.FC = (props) => {
const [state, commit] = useReducer(userReducer, initialStore.state)
const store: UserStore = {
state,
getters: getters(state),
actions: {
dispatch: initActions(commit)
},
mutations: {
commit
}
}
return (
<UserContext.Provider value={store}>
{props.children}
</UserContext.Provider>
)
}
</code></pre>
<p>For a syntactic sugar, I wrap the <code>useContext()</code> hook with a custom one:</p>
<pre><code>import { useContext } from 'react'
import { UserContext } from './UserContext'
const useUserStore = () => {
return useContext(UserContext)
}
export default useUserStore
</code></pre>
<p>After providing the context, the store can be used as such: </p>
<pre><code>const { actions, getters, mutations, state } = useUserStore()
useEffect(() => {
actions.dispatch({ type: 'load-users' })
}, [])
</code></pre>
<p>Are there any optimizations I can do? What are the biggest cons when comparing to redux? Here is the <a href="https://github.com/htmnk/ion-react-vuex-like-starter" rel="nofollow noreferrer">repo</a>, any feedback is appreciated. </p>
<p><a href="https://codesandbox.io/s/ion-react-vuex-like-starter-wg0pt" rel="nofollow noreferrer"><img src="https://codesandbox.io/static/img/play-codesandbox.svg" alt="Edit new"></a></p>
<p><strong>Edit 1:</strong></p>
<p>I've wrapped the <code>useContext()</code> with a custom <code>useUserStore()</code> hook, so it can be used as </p>
<pre><code>const { actions, getters, mutations, state } = useUserStore()
</code></pre>
<p>and so the store/context terms are unified when using the store. </p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T19:06:49.907",
"Id": "239282",
"Score": "5",
"Tags": [
"javascript",
"react.js",
"typescript",
"redux"
],
"Title": "React Context & Hooks custom Vuex like store"
} | 239282 |
<p><em>Disclaimer</em>: This is my first post here, so I'm not completely sure if this is on-topic.</p>
<p>I recently added a decorator that wraps a context manager in <a href="https://github.com/jmcgeheeiv/pyfakefs" rel="nofollow noreferrer">pyfakefs</a> (I'm a contributor), which has some optional arguments. In order to make the usage more convenient, I allowed both the usage with and without parentheses (mostly arguments are not needed, so the call without parentheses is the default). The code works but is not nice, and also probably not good if performance matters. I will show the full code here, and the question is just - can this be written nicer, and without the need to call another decorator function in the default case.</p>
<p>This is the complete code including comments:</p>
<pre><code>def _patchfs(f):
"""Internally used to be able to use patchfs without parentheses."""
@functools.wraps(f)
def decorated(*args, **kwargs):
with Patcher() as p:
kwargs['fs'] = p.fs
return f(*args, **kwargs)
return decorated
def patchfs(additional_skip_names=None,
modules_to_reload=None,
modules_to_patch=None,
allow_root_user=True):
"""Convenience decorator to use patcher with additional parameters in a
test function.
Usage::
@patchfs
test_my_function(fs):
fs.create_file('foo')
@patchfs(allow_root_user=False)
test_with_patcher_args(fs):
os.makedirs('foo/bar')
"""
def wrap_patchfs(f):
@functools.wraps(f)
def wrapped(*args, **kwargs):
with Patcher(
additional_skip_names=additional_skip_names,
modules_to_reload=modules_to_reload,
modules_to_patch=modules_to_patch,
allow_root_user=allow_root_user) as p:
kwargs['fs'] = p.fs
return f(*args, **kwargs)
return wrapped
# workaround to be able to use the decorator without using calling syntax
# (the default usage without parameters)
# if using the decorator without parentheses, the first argument here
# will be the wrapped function, so we pass it to the decorator function
# that doesn't use arguments
if inspect.isfunction(additional_skip_names):
return _patchfs(additional_skip_names)
return wrap_patchfs
</code></pre>
<p>Some more usage context:<br>
The decorator can be used in unittest methods to execute the test in a fake filesystem. The actual work is done by the patcher, which is instantiated by the decorator. The fake filesystem is represented by the argument <code>fs</code>,which is taken from the patcher instance, and can be used for some convenience functions like file creation or copying of files from the real file system.
In most cases, this will work out of the box (the decorator without parentheses can be used), but in some cases additional configuration is needed, which can be done by adding some optional arguments to the decorator, which are passed to the patcher. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T20:04:32.120",
"Id": "469366",
"Score": "1",
"body": "This got downvoted a few seconds after posted - can you please comment on what is wrong with the question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T20:50:31.303",
"Id": "469368",
"Score": "3",
"body": "Welcome to CR! Nothing inherently wrong here, but reviewers arguably would like more context around what the code does, why it does it, and how it's used. If you have unit tests covering that code you're encouraged to include them, too! Feel free to [edit] it in any time, keeping in mind that a good peer review takes a little while to craft into a post - do wander around and see what kind of feedback others have received =)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T21:18:49.683",
"Id": "469371",
"Score": "3",
"body": "Thanks a lot! I added some more info, and may add a related unittest later (when I'm back on the PC)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T21:57:09.933",
"Id": "469372",
"Score": "1",
"body": "While being left to guess about down-votes, there's [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask) to consider."
}
] | [
{
"body": "<p>Your <code>_patchfs</code> and <code>wrap_patchfs</code> functions are virtually identical. You don’t need the <code>_patchfs</code> version, just the internal one. One function instead of two is easier to maintain:</p>\n\n<pre><code>def patchfs(_func=None, *, \n additional_skip_names=None,\n modules_to_reload=None,\n modules_to_patch=None,\n allow_root_user=True):\n \"\"\"Your docstring here ...\"\"\"\n\n def wrap_patchfs(f):\n @functools.wraps(f)\n def wrapped(*args, **kwargs):\n with Patcher(\n additional_skip_names=additional_skip_names,\n modules_to_reload=modules_to_reload,\n modules_to_patch=modules_to_patch,\n allow_root_user=allow_root_user) as p:\n kwargs['fs'] = p.fs\n return f(*args, **kwargs)\n\n return wrapped\n\n if _func:\n if not callable(_func):\n raise TypeError(\"Decorator argument not a function.\\n\"\n \"Did you mean `@patchfs(additional_skip_names=...)`?\")\n return wrap_patchfs(_func)\n\n return wrap_patchfs\n</code></pre>\n\n<p>The <code>if not callable: ...</code> ensures you don’t accidentally try to use <code>@patchfs(names_to_skip)</code>. Using <code>*</code> forces the remaining arguments to keyword only arguments; you cannot just list the four arguments, which makes the decorator a little less error-prone. </p>\n\n<hr>\n\n<p>Your docstring's <code>Usage::</code> examples lack the required <code>def</code> keywords for defining functions. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T05:50:35.863",
"Id": "469383",
"Score": "0",
"body": "Thanks - that was exactly what I was looking for! I completely missed that I could use that `_func=None` part. Also kudos for spotting the error in the docstring!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T18:53:17.200",
"Id": "469426",
"Score": "1",
"body": "Hey, that's what Code Review is all about. \"_[Given enough eyeballs, all bugs are shallow](https://en.wikipedia.org/wiki/Linus%27s_law)_\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T18:59:20.290",
"Id": "469427",
"Score": "0",
"body": "Already [used the code](https://github.com/jmcgeheeiv/pyfakefs/commit/312f0f474139a9258bd65ac6223a39a91b8c41ae) :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T05:23:48.330",
"Id": "239302",
"ParentId": "239284",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "239302",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T19:59:55.657",
"Id": "239284",
"Score": "5",
"Tags": [
"python"
],
"Title": "Decorators with and without arguments"
} | 239284 |
<p>This is the solution for a simple challenge from Hackerrank.I am just trying to solve <a href="https://www.hackerrank.com/challenges/ctci-bubble-sort?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=sorting" rel="nofollow noreferrer">Sorting: Bubble Sort Problem</a> on HackerRank.</p>
<p>We are asked to count the number of swaps performed during a bubble sort and to print the first and last item of the ordered vector.</p>
<h3>Sample input</h3>
<pre><code>3
3 2 1
</code></pre>
<p>First line is the number of elements in the vector, the second line is the vector</p>
<h3>Expected output</h3>
<pre><code>Array is sorted in 3 swaps.
First Element: 1
Last Element: 3
</code></pre>
<h2>Code</h2>
<p>I've implemented my solution in C++ and would love to hear what your feedback and what could I have done cleaner</p>
<pre><code>#include <iostream>
#include <vector>
#include <algorithm>
using big_int = long long;
struct answer {
std::size_t count;
big_int first_element;
big_int last_element;
};
template<class T>
answer bubble_sort(std::vector<T> &v) {
std::size_t swap_count = 0;
for (int i = 0; i < v.size(); i++) {
for (int j = 0; j < v.size() - 1; j++) {
if (v[j] > v[j + 1]) {
std::swap(v[j], v[j + 1]);
swap_count++;
}
}
}
return answer{swap_count, v[0], v[v.size()-1]};
}
int main(int argc, char** argv) {
int n;
std::cin >> n;
std::vector<big_int> v(n);
for (int i=0; i<n; i++) {
std::cin >> v[i];
}
auto answer = bubble_sort(v);
std::cout << "Array is sorted in " << answer.count << " swaps.\n"
<< "First Element: " << answer.first_element << "\n"
<< "Last Element: " << answer.last_element;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-13T16:54:17.217",
"Id": "471662",
"Score": "0",
"body": "Can you please Add link of this problem to your Question ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-13T16:57:07.873",
"Id": "471663",
"Score": "0",
"body": "@AhmedEmad I've updated it with the link"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-13T17:33:11.797",
"Id": "471670",
"Score": "0",
"body": "I saw and i have edited some changes and will support your question to find solution for it,Good Luck! @Blasco"
}
] | [
{
"body": "<p>Overall, your code looks great. It's nicely structured, and having a well-defined <code>answer</code> type makes immediately clear what the question is about.</p>\n\n<p>At the bottom of the code, <code>i=0</code> is missing some spaces.</p>\n\n<p>You can improve the speed of the bubble sort by 50% by not counting <code>j</code> from 0 to size but only from 0 to <code>size - 1 - i</code>, since the last few elements are already bubbled up and therefore don't change anymore.</p>\n\n<p>For testing, you should add another counter for the number of comparisons.</p>\n\n<p>To test that your code is indeed correct, you should add an automatic test that takes a large array, fills it with 0 to size and shuffles the array. After sorting it should be the same as before.</p>\n\n<p>I'm not sure whether the C++ compiler is smart enough to know that the vector's size doesn't change during the bubble sort. To get a simple performance boost, compute <code>v.size()</code> once and store it in a local variable. Measure the performance difference using a large array that is already sorted.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T00:42:25.677",
"Id": "469378",
"Score": "0",
"body": "[Is it faster to cache the size of std::vector?](https://stackoverflow.com/q/14566363) The answers seem to suggest no."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T11:54:24.720",
"Id": "469400",
"Score": "1",
"body": "From my understanding the compiler should optimize that, right? I've just checked, and with the default O0 it is true that one can see the `size()` calls. With O3 there isn't even a call to the function that I've defined `bubble_sort()`, I also see no calls to `size()` everything is optimized away"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T20:58:43.350",
"Id": "469435",
"Score": "0",
"body": "As I said, \"I'm not sure\". It's good that everything is optimized away, I wouldn't have expected this though since the compiler needs quite a lot of information to decide all this."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T22:03:34.977",
"Id": "239290",
"ParentId": "239289",
"Score": "2"
}
},
{
"body": "<p>Your <code>answer</code> should also be a template struct. It contains first and last element of type <code>big_int</code> but in the <code>bubble _sort</code> function it is constructed with template argument type <code>T</code>.</p>\n\n<pre><code>template<class T>\nstruct answer {\n std::size_t count;\n T first_element;\n T last_element;\n};\n</code></pre>\n\n<p>But actually maybe the structure Is redundant because first And last element can Always easily be accessed inside the sorted container. Or it could at least contain just references to those elements instead of their copies in case the template argument <code>T</code> is something more complex then <code>long long</code>.</p>\n\n<pre><code>auto count = bubble_sort(v);\nauto & first = v[0];\nauto & last = v[v.size - 1];\n</code></pre>\n\n<p>Further instead of accepting <code>vector<T></code>, you could accept two iterators of template argument type as Is common with many standard functions and allows to work not only for any type of container but also for just a range within a container.</p>\n\n<pre><code>template<class Iterator>\nstd::size_t bubble_sort(Iterator from, Iterator to);\n\n// ...\n\nauto count = bubble_sort(v.begin(), v.end());\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T01:25:01.473",
"Id": "469444",
"Score": "0",
"body": "Nitpick: s/iterator/random access iterator; also s/container/container with random-access iterator"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T08:29:06.210",
"Id": "469461",
"Score": "0",
"body": "@L.F. good point, but I don't think we need to restrict to random access containers. I think any forward Iterator Is enough for the sorting itself. Random access Iterator Is only needed for constant time access to the first and last element. But actually some containers have constant access to first and last elements but not the other elements (like doubly linked list)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T08:30:40.830",
"Id": "469462",
"Score": "0",
"body": "Oops, didn't realize bubble sort doesn't need random access. Sorry! I think forward iterator is enough then - since we are copying iterators and visiting the elements multiple times."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T23:06:01.337",
"Id": "239336",
"ParentId": "239289",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "239336",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-22T21:34:37.857",
"Id": "239289",
"Score": "5",
"Tags": [
"c++",
"programming-challenge"
],
"Title": "Simple Bubble Sort swap counter C++"
} | 239289 |
<p>I wrote a simple antivirus in Python and would love feedback for additional ideas to implement, as well as general code review.</p>
<p>So far it has a <code>FileScanner</code> that checks against a database of known virus hashes and a network scanner that checks against a database of potentially malicious IP addresses.</p>
<p>I'm very curious about what I can do to move forward with this project.</p>
<pre><code>#!/usr/bin/env python
import os
import re
import time
import psutil
import hashlib
import sqlite3
import requests
import threading
from bs4 import BeautifulSoup
from argparse import ArgumentParser
WINDOWS = os.name == 'nt'
if WINDOWS:
from win10toast import ToastNotifier
class DB(object):
# TODO: Log the URLS it's grabbed hashes from
# And check the logged urls and skip over logged urls
# when calling the self.update() function
def __init__(self, db_fp='data.db'):
self.db_fp = db_fp
self.connect()
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
self.close()
def __repr__(self):
return "<SQLite3 Database: {}>".format(self.db_fp)
def connect(self):
self.conn = sqlite3.connect(self.db_fp)
self.cur = self.conn.cursor()
def close(self):
self.conn.commit()
self.cur.close()
self.conn.close()
def create_tables(self):
self.cur.execute('CREATE TABLE IF NOT EXISTS virus_md5_hashes(md5_hash TEXT NOT NULL UNIQUE)')
self.cur.execute('CREATE TABLE IF NOT EXISTS processed_virusshare_urls(url TEXT NOT NULL UNIQUE)')
self.cur.execute('CREATE TABLE IF NOT EXISTS high_risk_ips(ip TEXT NOT NULL UNIQUE)')
self.conn.commit()
def drop_tables(self):
self.cur.execute('DROP TABLE IF EXISTS virus_md5_hashes')
self.cur.execute('DROP TABLE IF EXISTS processed_virusshare_urls')
self.cur.execute('DROP TABLE IF EXISTS high_risk_ips')
self.conn.commit()
def add(self, table, value):
try:
sql = f"INSERT INTO {table} VALUES (?)"
self.cur.execute(sql, (value,))
except sqlite3.IntegrityError as e:
if 'UNIQUE' in str(e):
pass # Do nothing if trying to add a duplicate value
else:
raise e
def exists(self, vname, table, value):
sql = f"SELECT {vname} FROM {table} WHERE {vname} = (?)"
self.cur.execute(sql, (value,))
return self.cur.fetchone() is not None
def reset(self):
'''
reformats the database, think of it as a fresh-install
'''
# self.drop_tables() # This is soooo slow
self.close()
os.remove(self.db_fp)
self.connect()
self.update()
def update(self):
self.create_tables()
self.update_md5_hashes()
self.update_high_risk_ips()
def update_md5_hashes(self):
'''
updates the sqlite database of known virus md5 hashes
'''
urls = self.get_virusshare_urls()
for n, url in enumerate(urls):
reprint(f"Downloading known virus hashes {n+1}/{len(urls)}")
if not self.exists('url', 'processed_virusshare_urls', url):
for md5_hash in self.get_virusshare_hashes(url):
self.add('virus_md5_hashes', md5_hash)
self.add('processed_virusshare_urls', url)
self.conn.commit()
print()
def get_virusshare_urls(self) -> list:
'''
returns a list of virusshare.com urls containing md5 hashes
'''
r = requests.get('https://virusshare.com/hashes.4n6')
soup = BeautifulSoup(r.content, 'html.parser')
return ["https://virusshare.com/{}".format(a['href']) for a in soup.find_all('a')][6:-2]
def get_virusshare_hashes(self, url) -> str:
'''
parses all the md5 hashes from a valid virusshare.com url
'''
r = requests.get(url)
return r.text.splitlines()[6:]
def update_high_risk_ips(self):
sources = [
'https://blocklist.greensnow.co/greensnow.txt',
'https://cinsscore.com/list/ci-badguys.txt',
'http://danger.rulez.sk/projects/bruteforceblocker/blist.php',
'https://malc0de.com/bl/IP_Blacklist.txt',
'https://rules.emergingthreats.net/blockrules/compromised-ips.txt',
'https://rules.emergingthreats.net/fwrules/emerging-Block-IPs.txt',
'https://check.torproject.org/cgi-bin/TorBulkExitList.py?ip=1.1.1.1',
'https://feodotracker.abuse.ch/blocklist/?download=ipblocklist',
'https://hosts.ubuntu101.co.za/ips.list',
'https://lists.blocklist.de/lists/all.txt',
'https://myip.ms/files/blacklist/general/latest_blacklist.txt',
'https://pgl.yoyo.org/adservers/iplist.php?format=&showintro=0',
'https://ransomwaretracker.abuse.ch/downloads/RW_IPBL.txt',
'https://raw.githubusercontent.com/firehol/blocklist-ipsets/master/stopforumspam_7d.ipset',
'https://www.dan.me.uk/torlist/?exit',
'https://www.malwaredomainlist.com/hostslist/ip.txt',
'https://www.maxmind.com/es/proxy-detection-sample-list',
'https://www.projecthoneypot.org/list_of_ips.php?t=d&rss=1',
'http://www.unsubscore.com/blacklist.txt',
]
for n, source in enumerate(sources):
reprint(f"Downloading ips list: {n+1}/{len(sources)}")
try:
r = requests.get(source)
for ip in re.findall(r'[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}', r.text):
self.add('high_risk_ips', ip)
except requests.exceptions.RequestException:
print(f"Exception at {source}")
print()
class FileScanner(object):
def __init__(self):
self._bad_files = []
def get_files_recursively(self, folder) -> str:
'''
:param folder: directory to resursively check for binary files
:return: generator of all binary files (str == full path)
'''
for folder_name, sub_folder, filenames in os.walk(folder):
for f in filenames:
f = f"{folder_name}/{f}"
yield f
def get_md5(self, fp) -> str:
'''
:param fp: full path to a file
:return: the md5 hash of a file
'''
md5_hash = hashlib.md5()
with open(fp, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
md5_hash.update(chunk)
return md5_hash.hexdigest()
def compare_against_database(self, fp):
if is_binary(fp):
with DB() as db: # db connection has to be called within the same thread accessing the db uhg.jpg
md5_hash = self.get_md5(fp)
if db.exists('md5_hash', 'virus_md5_hashes', md5_hash):
self._bad_files.append(fp)
def scan(self, folder, max_threads=10):
start_time = time.time()
fp_gen = self.get_files_recursively(folder)
count = 0
try:
while True:
if threading.active_count() < max_threads:
fp = next(fp_gen)
t = threading.Thread(target=self.compare_against_database, args=(fp, ))
t.start()
count += 1
s = f'Scanning Files - Threads: {threading.active_count()} Files Scanned: {count} '
reprint(s)
else:
time.sleep(0.01)
except OSError:
print(f"OSError: Bad file descriptor: {fp} {' ' * len(fp)}")
except StopIteration:
end_time = time.time()
reprint(' ' * len(s))
print(f"scanned {count} files in {round(end_time - start_time, 2)} seconds")
for f in self._bad_files:
print(f"INFECTED - {f}")
class NetworkScanner(threading.Thread):
def __init__(self, timer=1):
self._timer = timer
self._running = True
self.update_current_connections()
self._displayed_notifications = []
threading.Thread.__init__(self)
def update_current_connections(self):
self._current_connections = psutil.net_connections()
def scan(self):
with DB() as db:
for conn in self._current_connections:
if conn.status != "NONE" or conn.status != "CLOSE_WAIT":
if db.exists('ip', 'high_risk_ips', conn.laddr.ip):
self.notify(conn.laddr.ip, conn.laddr.port, conn.pid)
if conn.raddr:
if db.exists('ip', 'high_risk_ips', conn.raddr.ip):
self.notify(conn.raddr.ip, conn.raddr.port, conn.pid)
def notify(self, ip, port, pid, duration=10):
title, body = "High Risk Connection", f"{psutil.Process(pid).name()}\n{ip}:{port} - {pid}"
if body not in self._displayed_notifications:
if WINDOWS:
ToastNotifier().show_toast(title, body, duration=duration, threaded=True)
self._displayed_notifications.append(body)
else:
print("{} {}".format(title, body))
self._displayed_notifications.append(body)
def run(self):
print('[+] Network Scanner Initialized')
while self._running:
self.update_current_connections()
self.scan()
time.sleep(self._timer)
def stop(self):
print('[-] Network Scanner Stopping')
self._running = False
def is_binary(fp, chunksize=1024) -> bool:
"""Return true if the given filename is binary.
@raise EnvironmentError: if the file does not exist or cannot be accessed.
@attention: found @ http://bytes.com/topic/python/answers/21222-determine-file-type-binary-text on 6/08/2010
@author: Trent Mick <TrentM@ActiveState.com>
@author: Jorge Orpinel <jorge@orpinel.com>"""
try:
with open(fp, 'rb') as f:
while True:
chunk = f.read(chunksize)
if b'\0' in chunk: # found null byte
return True
if len(chunk) < chunksize:
break
except PermissionError:
print(f"Permission Error: {fp} {' ' * len(fp)}")
return False
def reprint(s):
print(s, end='')
print('\r' * len(s), end='')
def parse_args():
parser = ArgumentParser()
parser.add_argument('path', default=os.getcwd(), type=str, help="path to scan")
parser.add_argument('-u', '--update', action="store_true", default=False, help="updates database of virus definitions & high risk IP's")
parser.add_argument('-t', '--threads', default=20, type=int, help="max threads for file scanner")
return parser.parse_args()
def Main():
# Testing for now
args = parse_args()
if args.update:
with DB() as db:
print('[+] Updating database')
db.update()
nsc = NetworkScanner()
nsc.start()
FileScanner().scan(args.path, args.threads)
nsc.stop()
if __name__ == '__main__':
Main()
</code></pre>
| [] | [
{
"body": "<p>One quick performance boost for your database is to use the fact that you can insert multiple rows at the same time. Which you can use in your code both for the IPs and for the hashes, so this can be quite useful:</p>\n\n<pre><code>def add_multiple(self, table, values):\n sql = f\"INSERT OR IGNORE INTO {table} VALUES (?)\"\n self.cur.executemany(sql, [(value,) for value in values])\n</code></pre>\n\n<p>Note that I used <code>INSERT OR IGNORE</code> to ignore already existing rows. <strong>Beware that this command is susceptible to SQL-injection</strong>, because a malicious value for <code>table</code> can do anything in this command (same as in yours). In this case it should be fairly easy to avoid this, since you know all legal table names, so just whitelist them explicitly.</p>\n\n<pre><code>def __init__(self, ...):\n ...\n self.tables = {\"virus_md5_hashes\",\n \"processed_virusshare_urls\",\n \"high_risk_ips\"}\n\ndef add(self, table, value):\n if table not in self.tables:\n raise ValueError(\"This table does not exist\")\n sql = f\"INSERT OR IGNORE INTO {table} VALUES (?)\"\n self.cur.execute(sql, (value,))\n\ndef add_multiple(self, table, values):\n if table not in self.tables:\n raise ValueError(\"This table does not exist\")\n sql = f\"INSERT OR IGNORE INTO {table} VALUES (?)\"\n self.cur.executemany(sql, [(value,) for value in values])\n</code></pre>\n\n<p>Your update functions need to be only slightly modified for the multiple insert to work:</p>\n\n<pre><code>def update_md5_hashes(self):\n '''\n updates the sqlite database of known virus md5 hashes\n '''\n for n, url in enumerate(self.virusshare_urls):\n reprint(f\"Downloading known virus hashes {n+1}/{len(urls)}\")\n if not self.exists('url', 'processed_virusshare_urls', url):\n self.add_multiple('virus_md5_hashes', self.get_virusshare_hashes(url))\n self.add('processed_virusshare_urls', url)\n self.conn.commit()\n print()\n\nIP_ADDRESS = re.compile(r'[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}')\n\ndef update_high_risk_ips(self):\n for n, source in enumerate(self.ip_blacklists):\n reprint(f\"Downloading ips list: {n+1}/{len(sources)}\")\n try: \n r = requests.get(source)\n self.add_many('high_risk_ips', IP_ADDRESS.findall(r.text))\n except requests.exceptions.RequestException:\n print(f\"Exception at {source}\")\n print()\n</code></pre>\n\n<p>I would also put your virusshare URLs and blacklisted IP sources as an attribute of the class so you can change it at runtime, if needed. You can also make them properties if you don't like them being changed, but want to have them accessible nevertheless.</p>\n\n<p>Note that in the first function you do have a <code>self.conn.commit</code> (which I moved under the <code>if</code>, no need for a commit if you didn't do anything), but not in the latter. This could be a bug.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T07:37:55.113",
"Id": "239305",
"ParentId": "239297",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "239305",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T01:33:14.107",
"Id": "239297",
"Score": "6",
"Tags": [
"python",
"python-3.x"
],
"Title": "Simple antivirus"
} | 239297 |
<p>The following is a c++ source code to get a matrix (<code>std::vector<std::vector<T>></code>) transpose in parallel.</p>
<p>The span is <span class="math-container">\$\Theta(\lg^2(n))\$</span> while the work is <span class="math-container">\$\Theta(n^2)\$</span></p>
<p>Any suggestion to improve will be appreciated.</p>
<pre><code>#include<vector>
#include<iostream>
#include<future>
#include<iomanip>
template <typename T>
void parallelForColsTrans(std::vector<std::vector<T>>& A, size_t fCol, size_t lCol, size_t i, size_t n)
{
if (fCol == lCol)
{
T temp = A[i][fCol+n];
A[i][fCol+n] = A[i+n][fCol];
A[i+n][fCol] = temp;
return;
}
std::async(parallelForColsTrans<T>, std::ref(A), fCol, (fCol + lCol) / 2, i, n);
std::async(parallelForColsTrans<T>, std::ref(A), (fCol + lCol) / 2 + 1, lCol, i, n);
}
template <typename T>
void parallelForRowsTrans(std::vector<std::vector<T>>& A, size_t fRow, size_t lRow, size_t fCol, size_t lCol, size_t n)
{
if (fRow == lRow) {
parallelForColsTrans(A, fCol, lCol, fRow, n);
return;
}
std::async(parallelForRowsTrans<T>, std::ref(A), fRow, (fRow+lRow) / 2, fCol, lCol, n);
std::async(parallelForRowsTrans<T>, std::ref(A), (fRow + lRow) / 2 + 1, lRow, fCol, lCol, n);
}
template <typename T>
void pMatTransposeRecursive(std::vector<std::vector<T>>& A, size_t firstRow, size_t lastRow, size_t firstColumn, size_t lastColumn)
{
if (firstRow == lastRow) return;
auto t1 =std::async(pMatTransposeRecursive<T>, std::ref(A), firstRow, (firstRow +lastRow)/2, firstColumn, (firstColumn+lastColumn)/2);
auto t2 =std::async(pMatTransposeRecursive<T>, std::ref(A), (firstRow +lastRow)/2+1, lastRow, firstColumn, (firstColumn+lastColumn)/2);
auto t3 =std::async(pMatTransposeRecursive<T>, std::ref(A), firstRow, (firstRow +lastRow)/2, (firstColumn+lastColumn)/2+1, lastColumn);
pMatTransposeRecursive<T>(std::ref(A), (firstRow +lastRow)/2+1, lastRow, (firstColumn+lastColumn)/2+1, lastColumn);
t1.get();
t2.get();
t3.get();
size_t n = (lastColumn-firstColumn+1)/2;
parallelForRowsTrans<T>(std::ref(A), firstRow, firstRow+n-1, firstColumn, firstColumn+n-1, n);
}
template <typename T>
void transpose(std::vector<std::vector<T>>& A){
pMatTransposeRecursive( A, 0, A.size()-1, 0, A[0].size()-1);
}
int main(){
std::vector<std::vector<int>> A = {{1,2,3,4,7,7,7,8}, {5,6,7,8,4,5,1,1}, {9,10,5,5,11,12,4,79}, {7,8,13,14,15,16,44,6}, {13,-14,7,-7,15,-16,-44,6}, {13,-14,105,106,404,6,9,9}, {13,-14,7,-7,15,-16,-44,6}, {13,-14,105,106,404,6,9,9}};
transpose(A);
for(auto & el:A){
for(auto& ele:el) std::cout << ele << std::setw(4) ;
std::cout << "\n";
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T06:45:06.127",
"Id": "469386",
"Score": "0",
"body": "I think recursion is realy not required for calculating the transpose of a matrix. I don't think it's worth to use multithreading for that either. If you are just doing it for learning and want to keep the recursion and multithreading, please clarify that in the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T06:47:22.887",
"Id": "469387",
"Score": "0",
"body": "@akuzminykh the multithreading saves the time doesn't it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T06:54:42.280",
"Id": "469388",
"Score": "0",
"body": "Calculating the transpose of a matrix is rather simple. So it can be calculated by a single thread pretty fast. Now you have to know that a thread has to be created before it can execute, which takes time. It could happen that your current code is actually slower because of the multithreading, just because of the overhead of creating additional threads. Recursion has a similar problem, but this is more dependent on the compiler. I'd like to write a whole answer in detail but I don't know C++ well .."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T06:57:06.530",
"Id": "469389",
"Score": "0",
"body": "@akuzminykh this is a general code. It's not specified for this small matrix but for huge 2d vectors"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T13:24:15.010",
"Id": "469478",
"Score": "1",
"body": "If your only constraint is to save time, don't roll this yourself; use a BLAS library."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T22:41:38.420",
"Id": "469505",
"Score": "0",
"body": "\"the multithreading saves the time doesn't it\". Nope. If used inproperly it will require both more time and much much more resources ftom CPU slowing down whatever else you happen to do in parallel. This is definitely such a case."
}
] | [
{
"body": "<h1>Is it worth parallelising?</h1>\n\n<p>When you are parallelizing code you have to ask yourself if it's worth doing that. Parallel code doesn't magically give a speedup, because there are various things that can actually slow you down when using parallelism, for example:</p>\n\n<ul>\n<li>Spawning and waiting for threads itself costs some time.</li>\n<li>Threads might be fighting for resources, like locks, but even just memory access might cause contention.</li>\n<li>Code that is not <a href=\"https://en.wikipedia.org/wiki/Embarrassingly_parallel\" rel=\"nofollow noreferrer\">trivially parallelizable</a> might require more computations when parallelized than when running single-threaded.</li>\n</ul>\n\n<p>In the case of transposing matrices, there are almost no computations involved, the work is completely dominated by reading and writing to memory. A good single-threaded implementation, which reads sequentially as much as possible, will likely be able to saturate the memory bus on typical desktop machines.</p>\n\n<p>In your implementation, you have a huge overhead just from starting all the async work items: you call <code>async()</code> more often than there are elements in the matrix. So that alone will make this horribly slow. Most good parallel algorithms try to limit the number of threads to the number of CPU cores or hardware threads that are available.</p>\n\n<p>Even if you didn't parallelize, but kept the structure of the code the same (just not use <code>async()</code>), then the recursive divide-and-conquer approach will cause a non-sequential memory access pattern.</p>\n\n<h1>Code review</h1>\n\n<h2>Nested <code>std::vector<></code>s are not efficient containers for matrices</h2>\n\n<p>While it's convenient to declare a 2D matrix using <code>std::vector<std::vector<T>></code>, it is not very efficient, since there is a lot of indirection. It is more efficient to declare a single <code>std::vector<T></code> of size <code>n * n</code>, and index the vector using <code>[row * n + col]</code>, or use a C++ library that provides proper matrix classes.</p>\n\n<h2>Use <code>std::swap()</code></h2>\n\n<p>The standard library provides <a href=\"https://en.cppreference.com/w/cpp/algorithm/swap\" rel=\"nofollow noreferrer\"><code>std::swap()</code></a>, which swaps two variables for you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T22:34:14.030",
"Id": "469504",
"Score": "1",
"body": "\"A good single-threaded implementation, which reads sequentially as much as possible, will likely be able to saturate the memory bus.\" Only got to address this passage. It depends on the hardware. It is indeed true for typical computers - but it is not the case high peformance CPUs with tons of cores designed for work stations; e.g., Xeon or some AMD processors. They tend to have memory bus way wider than a single thread can populate. Aside from that - parallelizing transpose - definitely not worth parellezation regardless."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T08:14:55.863",
"Id": "469518",
"Score": "0",
"body": "Many normal desktop CPUs can't get full memory bandwidth from a single core either (for example a 4770K with 2400MHz memory gets about 35GB/s multi-threaded but 20GB/s single-threaded), but the problem is less bad than on server parts"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T21:10:18.253",
"Id": "239378",
"ParentId": "239300",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "239378",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T04:28:55.127",
"Id": "239300",
"Score": "5",
"Tags": [
"c++",
"performance",
"multithreading",
"reinventing-the-wheel",
"matrix"
],
"Title": "Getting a transpose of a matrix of size of n*n where n=2^m using multithreading"
} | 239300 |
<p>I'm trying to play around with Godot to learn C# and I was trying to creating pure functions to do the velocity, but I found I was repeating myself.</p>
<pre><code> public override void _PhysicsProcess(float delta)
{
base._PhysicsProcess(delta);
Vector2 moveVelocity = velocity;
moveVelocity = Run(moveVelocity);
moveVelocity = Jump(moveVelocity);
moveVelocity = Dash(moveVelocity);
moveVelocity = Friction(moveVelocity);
moveVelocity = Gravity(moveVelocity);
Animate();
velocity = MoveAndSlide(moveVelocity, Vector2.Up);
}
</code></pre>
<p>Is there a nicer way of doing the above method so I don't copy moveVelocity over and over but not change <code>velocity</code> or create a new class property?</p>
<p>Something like</p>
<pre><code>velocity = Apply(velocity,
Run,
Jump,
Dash,
Friction,
Gravity);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T08:17:24.293",
"Id": "469393",
"Score": "0",
"body": "I think you are looking for fluent interface pattern: https://dotnettutorials.net/lesson/fluent-interface-design-pattern/ With it you can write something like: `velocity.Run().Jump().Dash()`... but of course this will require refactor in your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T15:13:39.983",
"Id": "469407",
"Score": "0",
"body": "Velocity is a Vector2 class can C# just add extra functions to an existing class?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T16:23:50.227",
"Id": "469417",
"Score": "0",
"body": "You can use Extension Methods: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods"
}
] | [
{
"body": "<p>Not sure about your full implementation, but from what I see, you could do a fluent API\nsomething like : </p>\n\n<pre><code>public class PhysicsProcess\n{\n private readonly float _delta; \n private readonly Vector2 _velocity;\n\n public PhysicsProcess(Vector2 velocity)\n {\n _velocity = velocity;\n }\n\n public PhysicsProcess Run()\n {\n // Run logic which would be saved on the global variable \n return this;\n }\n\n public PhysicsProcess Jump() { ... }\n\n public PhysicsProcess Dash() { ... }\n\n public PhysicsProcess Friction() { ... }\n\n public PhysicsProcess Gravity() { ... }\n\n public void Apply()\n {\n // Your final logic which would take all arguments, and do the process you need. \n }\n\n}\n</code></pre>\n\n<p>then your usage would be something like : </p>\n\n<pre><code>var process = new PhysicsProcess(velocity)\n.Run()\n.Jump()\n.Dash()\n.Friction()\n.Gravity()\n.Apply();\n</code></pre>\n\n<p>You can then extend or customize each process as fits your needs. You can also make <code>PhysicsProcess</code> as nested class and call it from a method from the parent class. There are many approaches and customization can be done with fluent APIs, just choose the approach that you see it would be more reasonable to the existing logic (technically, and business-wise).</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>As I mentioned, fluent API is an easy interface to use and customize. For that, you can also make it an extension like this : </p>\n\n<pre><code>public static class Vector2Extensions\n{\n public static PhysicsProcess Apply(this Vector2 velocity)\n {\n return new PhysicsProcess(velocity);\n }\n}\n</code></pre>\n\n<p>now you can for instance add new method to your fluent API class say <code>Save()</code> for instance, which would return <code>Vector2</code>, then you could do something like this : </p>\n\n<pre><code>moveVelocity.Apply()\n .Run()\n .Jump()\n .Dash()\n .Friction()\n .Gravity()\n .Save();\n</code></pre>\n\n<p>When you use this approach, it would make it more maintainable and easy to extend. </p>\n\n<p>I hope this would make it more useful answer. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T12:14:37.880",
"Id": "469471",
"Score": "0",
"body": "Looks acceptable at least until an extension methods answer is provided."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T18:58:47.043",
"Id": "469498",
"Score": "0",
"body": "@ArchimedesTrajano I have updated the answer, showing how you could use the current approach and extend it with an extension method."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T22:32:28.210",
"Id": "239335",
"ParentId": "239303",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "239335",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T05:37:50.133",
"Id": "239303",
"Score": "3",
"Tags": [
"c#",
"functional-programming"
],
"Title": "Writing pure functions but have a chain"
} | 239303 |
<p>I have the below code that helps me do some formatting. But I want to increase the efficiency of the code by making it faster. Below are the formatting steps of the macro.</p>
<ol>
<li>Convert "Q" and "S" column to number format.</li>
<li>Replicate the "I" column to new column by inserting a column next to it.</li>
<li>Cut the column "AD" and paste to column "O".</li>
<li>Remove columns ("A:A,AD:AG").</li>
<li>Replace "#" with null and "OUT" with P input value in "AC" column.</li>
<li>Round the "Q" and "S" column numbers to 2 decimal.</li>
<li>Change the sign of values in column Q by multiplying -1(i.e. <code>*-1</code>).</li>
<li>Filter on "Q" column with "0" and filter on "S" column with "0". Then remove those rows with "Q" and "S" is Zero.</li>
<li>Filter 0 on Q column, Clear only visible cells of "Q" and "R" Columns.</li>
<li>Filter 0 on "S" column, Clear only visible cells of "S" and "T" Columns.</li>
<li>Copy the headers (ThisWorkbook.Sheets("Tool").Range("A20:AC20").Copy) and paste to the A1 of file formatted.</li>
<li>Remove all columns and rows which doesn’t have data apart from used range.</li>
</ol>
<p>Currently macro working fine but taking some time. As I'm new to VBA, I'm not sure how to optimize the code. Hence I'm here looking for help from experts.</p>
<p>Below is the code:</p>
<pre><code>Sub A_to_B()
Dim LastRow As Long Dim Lastcol As Long Dim P As String
'Display a Dialog Box that allows to select a single file. 'The path
for the file picked will be stored in fullpath variable With
Application.FileDialog(msoFileDialogFilePicker)
'Makes sure the user can select only one file
.AllowMultiSelect = True
'Filter to just the following types of files to narrow down selection options
'.Filters.Add "All Files", "*.xlsx; *.xlsm; *.xls; *.xlsb; *.csv"
'Show the dialog box
.Show
'Store in fullpath variable
fullpath = .SelectedItems.Item(1)
End With
'It's a good idea to still check if the file type selected is accurate.
'Quit the procedure if the user didn't select the type of file we need.
If InStr(fullpath, ".xls") = 0 Then
If InStr(fullpath, ".csv") = 0 Then
Exit Sub
End If
End If
'Open the file selected by the user
Workbooks.Open fullpath
P = InputBox("Please Enter the Version")
Application.ScreenUpdating = False
With ActiveWorkbook
Columns(17).NumberFormat = "0"
Columns(19).NumberFormat = "0"
LastRow = Cells(Rows.Count, 2).End(xlUp).Row
Lastcol = Cells(1, Columns.Count).End(xlToLeft).Column
Columns("I").Copy
Columns("I").Insert Shift:=xlToRight
'Range("AE2").Value = P
'Range("AE2", "AE" & Cells(Rows.Count, "B").End(xlUp).Row).FillDown
Columns("AE").Copy
Columns("P").PasteSpecial xlPasteValues
ActiveSheet.Range("A:A,AE:AG").EntireColumn.Delete
Columns("AC").Replace What:="#", Replacement:="", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False,
ReplaceFormat:=False
Columns("AC").Replace What:="OUT", Replacement:=P, LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False,
SearchFormat:=False, ReplaceFormat:=False
Range("AD2").Formula = "=Round(Q2,2)"
Range("AD2", "AD" & Cells(Rows.Count, "B").End(xlUp).Row).FillDown
Range("AD2", "AD" & Cells(Rows.Count, "B").End(xlUp).Row).Copy
Range("Q2").PasteSpecial xlPasteValues
Range("AD2").Formula = "=Round(S2,2)"
Range("AD2", "AD" & Cells(Rows.Count, "B").End(xlUp).Row).FillDown
Range("AD2", "AD" & Cells(Rows.Count, "B").End(xlUp).Row).Copy
Range("S2").PasteSpecial xlPasteValues
Range("AD2").Formula = "=(Q2*-1)"
Range("AD2", "AD" & Cells(Rows.Count, "B").End(xlUp).Row).FillDown
Range("AD2", "AD" & Cells(Rows.Count, "B").End(xlUp).Row).Copy
Range("Q2").PasteSpecial xlPasteValues
Columns("AD:AD").EntireColumn.Delete With ActiveSheet.Range("A:AC")
.AutoFilter Field:=17, Criteria1:="0"
.AutoFilter Field:=19, Criteria1:="0"
.Range("A2:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Delete
.AutoFilter
.AutoFilter Field:=17, Criteria1:="0"
.Range("Q2:R" & LastRow).SpecialCells(xlCellTypeVisible).Clear
.AutoFilter
.AutoFilter Field:=19, Criteria1:="0"
.Range("S2:T" & LastRow).SpecialCells(xlCellTypeVisible).Clear
.AutoFilter
'.Range("C2").AutoFill .Range("C2:C" & .Cells(.Rows.Count, "B").End(xlUp).Row)
End With End With ThisWorkbook.Sheets("Tool").Range("A20:AC20").Copy
ActiveSheet.Range("A1").PasteSpecial Paste:=xlPasteValues
Columns("A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
Rows("1").SpecialCells(xlCellTypeBlanks).EntireColumn.Delete
'ActiveWorkbook.Save
'ActiveWorkbook.Close
MsgBox "Done With Farmatting"
End Sub
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T12:34:06.927",
"Id": "469401",
"Score": "2",
"body": "Ahoy! I [changed the title]() so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate."
}
] | [
{
"body": "<p>Unfortunately it's difficult to provide actionable advice here, because the <strong>purpose</strong> you are trying to achieve is not explained. What would help is sample data, and a clear description of what your script does.</p>\n\n<p>I cannot guess what you are doing, I have no idea if all that even makes sense, surely there must be a better way but we need more insight. Besides, your code is not properly formatted and seems to be missing a few line breaks.</p>\n\n<p>Anyway, and since I am not a mind reader I will just make some suggestions:</p>\n\n<ul>\n<li>use <strong>meaningful names</strong> for your variables and procedures: <code>Sub A_to_B()</code> is meaningless, the procedure should have a more descriptive name</li>\n<li>you should add more <strong>comments</strong>, describe every action and why you do it unless it is very obvious</li>\n<li>add some <strong>spacing</strong> between lines and logical blocks to make reading easier </li>\n<li>proper tabulation too</li>\n<li>you have multiple references to <code>ActiveWorkbook</code> or <code>ActiveSheet</code>, but the user could switch to another sheet while the macro is running, thus your code could be running out of scope and likely crash. There are some <a href=\"https://docs.microsoft.com/en-us/office/vba/api/excel.workbook.activesheet\" rel=\"nofollow noreferrer\">caveats</a> with these methods too. <code>ActiveWorkbook</code> is not the workbook where your code resides. It is the last one that had the focus. Better make an explicit reference to a named sheet.</li>\n<li>use <strong><a href=\"https://helpdeskgeek.com/office-tips/why-you-should-be-using-named-ranges-in-excel/\" rel=\"nofollow noreferrer\">named ranges</a></strong> rather than static ranges like AD2:BC500: they all look the same and you are never quite sure what they represent, so it's easy to confuse them. You can create named ranges on the fly too, and then use them in your code. This is more flexible than repeating stuff like <code>Range(\"AD2\", \"AD\" & Cells(Rows.Count, \"B\")</code>. The first benefit is that the named range is defined only once, and then reused as many times as you want. The other benefit is that the named range is more <strong>descriptive</strong> than a range made up of a number and letters.</li>\n<li>rather than hardcoding numbers like: <code>.AutoFilter Field:=17</code>, use <strong>constant variables</strong>. Surely 17 or 19 have a special meaning.</li>\n<li>you have <code>Application.ScreenUpdating = False</code> but where is <code>Application.ScreenUpdating</code> = True ?</li>\n</ul>\n\n<p>The code doesn't seem to be difficult, and could be so much more readable than it currently is.</p>\n\n<p>Regarding <strong>speed</strong> of execution, you need to figure out yourself, because I am not able to reproduce your environment. If you have 5 million rows, then this is likely going to take time and it's normal. What I would do is add a timestamp trace between each operation to find out which parts are slower. It could be the Replace statements but I have no way to tell.</p>\n\n<p>Here is one trick that could help but you have to try it: in the beginning of your code add this to suspend automatic recalculation:</p>\n\n<pre><code>Application.Calculation = xlManual\n</code></pre>\n\n<p>Then turn it back on when done:</p>\n\n<pre><code>Application.Calculation = xlAutomatic\n</code></pre>\n\n<p>Using <code>Application.ScreenUpdating</code> is a good thing but there is more than can be done.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T18:16:53.497",
"Id": "239330",
"ParentId": "239307",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T08:06:38.787",
"Id": "239307",
"Score": "1",
"Tags": [
"vba",
"excel",
"formatting"
],
"Title": "Altering spreadsheet data"
} | 239307 |
<p>This is regarding code quality and coding standards with respect to Spring Ecosystem. Here there are two methods:</p>
<ul>
<li><code>isRecordExists</code> is using a class level static constant <code>String</code> query. (Definitely suggestable for old way where we use prepared statements)</li>
<li><code>isRecordExists2</code> is using method level <code>String</code> query</li>
</ul>
<p>Which method is better (<code>isRecordExists</code> or <code>isRecordExists2</code>) in context with Spring Boot?</p>
<pre><code>@Repository
public class SpringRepository {
@Autowired
private NamedParameterJdbcTemplate namedParamJdbcTemplate;
private static final String QUERY = " select * from Dual where created_date=:date";
public void isRecordExists(Date date){
/**
* using constant for sql Query String at class level
*/
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("date", date);
namedParameterJdbcTemplate.queryForObject(QUERY, parameters, Integer.class);
}
public void isRecordExists2(Date date){
String sqlQuery=" select * from Dual where created_date=:date";
/**
* using sql Query at method level
*/
MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("date", date);
namedParameterJdbcTemplate.queryForObject(sqlQuery, parameters, Integer.class);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T13:15:39.730",
"Id": "469475",
"Score": "0",
"body": "Unrelated to the existing answers and perhaps only because it's example code, but surely these methods should return something (e.g boolean) as they are Queries, not Commands. Also you surely don't need to `select *`, you can just `select TOP 1` which will be a lot more efficient."
}
] | [
{
"body": "<p>Not many valid reasons, why would ever <code>isRecordExists2</code> be better method. It is almost always good to extract reusable strings into constants and split code into smaller pieces. I definitely vote for <code>isRecordExists</code>. If you decide to stick with <code>isRecordExists2</code>, why even create <code>sqlQuery</code> variable? You might as well just pass the string itself into <code>queryForObject</code>.</p>\n\n<p>Only possible downsides of using <code>isRecordExists</code> I can think of (but very small and insignificant imho):</p>\n\n<ul>\n<li>Static field is always there and taking some piece of memory. Local string would not unless while that method is being called.</li>\n<li>That string is not as close to method and therefore code might be harder for read (but we have IDEs to help with that). I would choose better name than <code>QUERY</code> to help with that too.</li>\n</ul>\n\n<p>If there are specific coding standards in Spring boot against it, please link them :-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T18:10:55.070",
"Id": "469421",
"Score": "1",
"body": "I don't think your first point about memory usage is correct - the string will be located in a constant pool regardless of how it's declared."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T18:37:02.473",
"Id": "469423",
"Score": "0",
"body": "So what's the justification to violate YAGNI? I mean it's almost certain that nobody is ever going to reuse an exact query string in another repository method. After all what would be the point?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T19:34:11.983",
"Id": "469432",
"Score": "0",
"body": "There isn't one. If that's only place to be used, there's no point. Agreed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T10:39:17.247",
"Id": "469468",
"Score": "0",
"body": "@PhilipRoman What I mean is, that there will be always be that string in constant pool after this class has been loaded. In second case, it can get removed when not used anywhere."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T11:04:09.687",
"Id": "239311",
"ParentId": "239308",
"Score": "4"
}
},
{
"body": "<p>Sorry to present the antithesis to an existing answer once more: if the string is neither reusable nor public, a constant makes no sense in my book. (And yes, this question is opinion-based ;-))</p>\n\n<p>I see why you use a string-variable inside the medthod (to keep it readable for longer strings) which I find totally OK.</p>\n\n<p>In general: aim to write the code for the audience of developers who come after you. In my experience, this future developer will dig through your code with a debugger because something goes wrong. Thus, he will <em>not</em> read the class in its entirity because he's curious, he will jump into that specific method from a stacktrace. All information that is locally there will be beneficial, as there is less jumping around in the code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T11:48:48.550",
"Id": "469398",
"Score": "0",
"body": "adding to above, Spring actually discourage the use of static members..... https://rules.sonarsource.com/java/tag/spring/RSPEC-3749"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T11:52:23.350",
"Id": "469399",
"Score": "2",
"body": "Glad to see reasonable disagreement. Good arguments."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T11:45:02.853",
"Id": "239315",
"ParentId": "239308",
"Score": "11"
}
},
{
"body": "<p>I agree with @mtj's answer : YAGNI, no point in making the string reusable if it's not being reused at the moment.</p>\n\n<p>I would want to add that in certain scenarios it may be smart to factor out only <strong>part</strong> of the SQL query.</p>\n\n<p>For example if you had a few queries with slightly more complicated WHERE statements, something like :</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>select * from image where (created_date is null or created_date > date)\n</code></pre>\n\n<p>and</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>select id from text where (created_date is null or created_date > date)\n</code></pre>\n\n<p>Then we can have </p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private static String WHERE_CREATED_IS_NULL_OR_AFTER_DATE = \" where (created_date is null or created_date > date) \"\n</code></pre>\n\n<p>and use it in the respective methods :</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public void getImages() {\n String query = \"select * from image\" + WHERE_CREATED_IS_NULL_OR_AFTER_DATE;\n ...\n}\n</code></pre>\n\n<pre class=\"lang-java prettyprint-override\"><code>public void getTextIds() {\n String query = \"select id from text\" + WHERE_CREATED_IS_NULL_OR_AFTER_DATE;\n ...\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T15:20:00.363",
"Id": "239368",
"ParentId": "239308",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T08:31:23.313",
"Id": "239308",
"Score": "5",
"Tags": [
"java",
"spring",
"jdbc"
],
"Title": "Using static final Strings for SQL Query in Spring Boot"
} | 239308 |
<p><a href="https://leetcode.com/problems/network-delay-time/" rel="nofollow noreferrer">https://leetcode.com/problems/network-delay-time/</a></p>
<blockquote>
<p>There are N network nodes, labelled 1 to N.</p>
<p>Given times, a list of travel times as directed edges times[i] = (u,
v, w), where u is the source node, v is the target node, and w is the
time it takes for a signal to travel from source to target.</p>
<p>Now, we send a signal from a certain node K. How long will it take for
all nodes to receive the signal? If it is impossible, return -1.
<a href="https://i.stack.imgur.com/s9FeP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/s9FeP.png" alt="enter image description here"></a></p>
</blockquote>
<p>Note:</p>
<blockquote>
<ol>
<li>N will be in the range [1, 100].</li>
<li>K will be in the range [1, N]. The</li>
<li>length of times will be in the range [1, 6000].</li>
<li>All edges times[i] = (u, v, w) will have 1 <= u, v <= N and 0 <= w <= 100.</li>
</ol>
</blockquote>
<p>Please review for performance</p>
<pre><code> [TestClass]
public class NetworkDelayTimeTest
{
[TestMethod]
public void ExampleTestBellmanFord()
{
int N = 4;
int K = 2;
int[][] times = { new[] { 2, 1, 1 }, new[] { 2, 3, 1 }, new[] { 3, 4, 1 } };
NetworkDelayTimeBellmanFord bellmanFord = new NetworkDelayTimeBellmanFord();
Assert.AreEqual(2, bellmanFord.NetworkDelayTime(times, N, K));
}
}
public class NetworkDelayTimeBellmanFord
{
public int NetworkDelayTime(int[][] times, int N, int K)
{
var dist = Enumerable.Repeat(int.MaxValue, N + 1).ToList();
dist[K] = 0;
for (int i = 0; i < N; i++)
{
foreach (var e in times)
{
int u = e[0];
int v = e[1];
int w = e[2];
if (dist[u] != int.MaxValue && dist[v] > dist[u] + w)
{
dist[v] = dist[u] + w;
}
}
}
int maxWait = 0;
for (int i = 1; i <= N; i++)
{
maxWait = Math.Max(maxWait, dist[i]);
}
if (maxWait == int.MaxValue)
{
return -1;
}
return maxWait;
}
}
</code></pre>
| [] | [
{
"body": "<p>You can optimize a bit by make it possible to step out of the first outer loop if the inner <code>foreach</code>-loop doesn't make any changes to <code>dist</code> in one iteration.</p>\n\n<hr>\n\n<p>Wouldn't it be possible to test for <code>maxWait</code> whenever you update <code>dist[v]</code> in the <code>foreach</code>-loop:</p>\n\n<pre><code>{\n dist[v] = dist[u] + w;\n maxWait = Math.Max(maxWait, dist[v]);\n}\n</code></pre>\n\n<p>This may og may not be an optimization - depending on the cost of comparing two integers potentially <code>N * N</code> times compared to the cost of an extra loop comparing them <code>N-1</code> times?</p>\n\n<hr>\n\n<p>You could make an early return in the find-max-loop:</p>\n\n<pre><code> int maxWait = 0;\n for (int i = 1; i <= N; i++)\n {\n maxWait = Math.Max(maxWait, dist[i]);\n\n if (maxWait == int.MaxValue)\n {\n return -1;\n }\n }\n</code></pre>\n\n<p>or change it to:</p>\n\n<pre><code>int maxWait = dist.Skip(1).Max();\nreturn maxWait < int.MaxValue ? maxWait : -1;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T12:44:41.487",
"Id": "239358",
"ParentId": "239309",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "239358",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T08:31:41.097",
"Id": "239309",
"Score": "3",
"Tags": [
"c#",
"programming-challenge",
"graph"
],
"Title": "LeetCode: Network Delay Time Bellman Ford C#"
} | 239309 |
<p>I have the following:</p>
<pre><code>#include <string>
#include <string_view>
#include <vector>
#include <unordered_map>
#include <iostream>
namespace utils
{
void replace_all(std::string& string, const std::string_view from, const std::string_view to)
{
std::size_t start_pos{ 0 };
while ((start_pos = string.find(from)) != std::string::npos)
{
string.replace(start_pos, from.length(), to);
start_pos += to.length();
}
}
void replace_all(std::string& string, const std::unordered_map<std::string_view, std::string_view>& map) // Warning 2 here
{
for (const auto [from, to] : map) // Warning 1 here
{
replace_all(string, from, to);
}
}
}
int main()
{
std::unordered_map<std::string_view, std::string_view> my_map{ {"this", "that"}, {"hes", "her"}, {"my", "yours"} };
std::string my_string{ "This is hes chocolate and my aswell" };
utils::replace_all(my_string, my_map);
std::cout << my_string << std::endl;
return 0;
}
</code></pre>
<p>It works and outputs: <code>This is her chocolate and yours aswell</code> as expected.</p>
<p>Analysing this in MSVC 2019 with C++ Core guidelines turned on I do get the following warnings though:</p>
<pre><code>C:\dev\MyVSProjects\AE\AE\include\AE\Main.cpp(23): warning C26486: Don't pass a pointer that may be invalid to a function. Parameter 0 '$S1' in call to '<move><std::pair<std::basic_string_view<char,std::char_traits<char> > const ,std::basic_string_view<char,std::char_traits<char> > > const & __ptr64>' may be invalid (lifetime.3).
C:\dev\MyVSProjects\AE\AE\include\AE\Main.cpp(21): warning C26487: Don't return a pointer '(*(*map))' that may be invalid (lifetime.4).
</code></pre>
<p>I'd like to remove these warnings and make the code as clean as possible.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T10:49:32.387",
"Id": "469396",
"Score": "0",
"body": "Can you post your complete code, including `#include` directives, so that we can find what the line numbers point to?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T11:03:49.260",
"Id": "469397",
"Score": "0",
"body": "I have updated the code to have the includes aswell as highlighted the lines with comments."
}
] | [
{
"body": "<p>This code is nicely written and clear in both code and description. Good job! I think there are still some things that might be improved.</p>\n\n<h2>Fix the bug</h2>\n\n<p>The updated value of <code>start_pos</code> is not being used for each iteration of the loop. Instead, it should be, so the <code>while</code> loop should be this:</p>\n\n<pre><code>while ((start_pos = string.find(from, start_pos)) != std::string::npos)\n</code></pre>\n\n<h2>Avoid creating copies if practical</h2>\n\n<p>I don't have MSVC 2019 available, but I suspect that it's pointing out that you've asked it to make copies of <code>from</code> and <code>to</code>. That is, instead of this:</p>\n\n<pre><code>for (const auto [from, to] : map)\n</code></pre>\n\n<p>Write this:</p>\n\n<pre><code>for (const auto& [from, to] : map)\n</code></pre>\n\n<p>And see if that helps. Another alternative would be to create a version of <code>replace_all</code> that takes a <code>std::pair<std::string_view, std::string_view></code> and rewrite the loop as:</p>\n\n<pre><code>for (const auto& pr: map) {\n replace_all(string, pr);\n}\n</code></pre>\n\n<h2>Consider using a different data structure</h2>\n\n<p>The <code>std::unordered_map</code> used here may seem like a logical and intuitive structure to use but it has some potential problems. First, the iterator has no defined ordering. That is, the ordering is implementation defined so the programmer has no control of it. That might be a problem if we want to do things in a specific order. For example, replacing literal characters with their corresponding <a href=\"https://www.w3.org/2003/entities/2007doc/predefined.html\" rel=\"noreferrer\">predefined XML entities</a>, such as <code>></code> to <code>&gt;</code> we typically want to do the <code>&</code> to <code>&amp;</code> conversion <em>first</em> for obvious reasons. There's no way to do that with the existing version of the code. Second, we can't create a <code>constexpr</code> version of the map because it has a non-trivial destructor. I'd suggest allowing something like a <code>std::array</code> of <code>std::pair<std::string_view, std::string_view></code>. This is the approach that is used in conjunction with the next few suggestions.</p>\n\n<h2>Use <code>using</code> to simplify code</h2>\n\n<p>The existing code could be simplified a bit by using <code>using</code> like so:</p>\n\n<pre><code>using MapContainer = std::unorded_map<std::string_view, std::string_view>;\nvoid replace_all(std::string& string, const MapContainer& map) { /* etc. */ }\n</code></pre>\n\n<p>Now any place we use the rather long name we can simply write <code>MapContainer</code>.</p>\n\n<h2>Use <code>templates</code> for flexibility</h2>\n\n<p>Instead of tying the <code>replace_all</code> function to a specific kind of structure, we could pass it a pair of templated iterators instead for flexibility:</p>\n\n<pre><code>template <class ForwardIt>\nvoid replace_all(std::string& string, ForwardIt first, ForwardIt last) {\n for ( ; first != last; ++first) {\n replace_all(string, *first);\n }\n}\n</code></pre>\n\n<p>Now all we need is any forward iterator that returns something that can be used by the inner <code>replace_all</code>. In fact, we can simplify even further because this is exactly like the definition of <code>std::for_each</code>.</p>\n\n<h2>Don't use <code>std::endl</code> if <code>'\\n'</code> will do</h2>\n\n<p>Using <code>std::endl</code> emits a <code>\\n</code> and flushes the stream. Unless you really need the stream flushed, you can improve the performance of the code by simply emitting <code>'\\n'</code> instead of using the potentially more computationally costly <code>std::endl</code>.</p>\n\n<h2>Consider creating a parallel version</h2>\n\n<p>The current version is simple and straightforward, but makes multiple passes through the string. It's possible to create a version that makes a single pass through or that makes multiple passes in parallel. The single pass version could be general purpose, but the parallel version would require that patterns be completely independent (unlike the entity-replacing example I mentioned).</p>\n\n<h2>Consider eliminating <code>return 0</code></h2>\n\n<p>You don't need to explicitly provide a <code>return 0;</code> at the end of main -- it's created implicitly by the compiler. Some people apparently feel very strongly both for and against this. I advocate omitting it but you can decide for yourself.</p>\n\n<h2>Alternate version</h2>\n\n<p>Here's what I came up with using all of these suggestions:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <string>\n#include <string_view>\n#include <array>\n#include <algorithm>\n#include <iostream>\n\nnamespace utils\n{\n using WordPair = std::pair<std::string_view, std::string_view>;\n void replace_all(std::string& string, const WordPair &pr) {\n for (std::size_t start_pos{ 0 };\n (start_pos = string.find(pr.first, start_pos)) != std::string::npos;\n start_pos += pr.second.length())\n {\n string.replace(start_pos, pr.first.length(), pr.second);\n }\n }\n}\n\nint main()\n{\n constexpr std::array<utils::WordPair, 5> my_map{{ \n {\"&\", \"&amp;\"}, \n {\"<\", \"&lt;\"}, \n {\">\", \"&gt;\"}, \n {\"'\", \"&apos;\"}, \n {\"\\\"\", \"&quot;\"} \n }};\n std::string my_string{ \"This & that aren't \\\"<>\\\".\" };\n // use a lambda for clarity\n auto repl = [&my_string](const utils::WordPair &p){\n utils::replace_all(my_string, p);\n };\n std::for_each(my_map.cbegin(), my_map.cend(), repl);\n std::cout << my_string << '\\n';\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T11:18:04.407",
"Id": "469538",
"Score": "0",
"body": "Is there any reason why you sometimes put the ampersand next to the type and sometimes next to the variable? e.g. `std::string& string, const WordPair &pr`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T11:21:30.643",
"Id": "469540",
"Score": "1",
"body": "No. I’m trying to change my style to always do `type&` but don’t always remember. It’s hard to break a decades old habit!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T17:47:53.337",
"Id": "239329",
"ParentId": "239310",
"Score": "7"
}
},
{
"body": "<p>One drawback of this implementation is that, when <code>from</code> and <code>to</code> are of different lengths, it works in quadratic time. Consider</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>auto attack = \"12324252627\";\nreplace_all(attack, \"2\", \"42\");\n</code></pre>\n\n<p>How many times most characters are copied to only be copied or, even worse, replaced later?</p>\n\n<p>(Coincidentally, when pattern and replacement are of equal lengths this shouldn't be an issue.)</p>\n\n<p>More reasonable would be to give up on in-place modification and return a freshly constructed string, with all the proper replacements done, in linear time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T21:42:51.743",
"Id": "469438",
"Score": "0",
"body": "Had not considered that. Interesting. For my use case it wont matter though, as I will be looking for very specific non 'replicating' keywords. Good to note though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T23:46:53.717",
"Id": "469441",
"Score": "0",
"body": "This issue is addressed in the \"Fix the bug\" section of my answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T02:13:20.713",
"Id": "469445",
"Score": "0",
"body": "@Edward How exactly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T11:20:58.940",
"Id": "469539",
"Score": "0",
"body": "@Edward suggest skipping ahead by the size of the replacement word, which means the replacement wouldn't be re-parsed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T12:21:40.620",
"Id": "469545",
"Score": "0",
"body": "@ades So what? All the quadratic copies still remain."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T19:57:33.757",
"Id": "239333",
"ParentId": "239310",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "239329",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T09:33:52.160",
"Id": "239310",
"Score": "4",
"Tags": [
"c++",
"performance",
"c++17"
],
"Title": "Improving function that replaces all instances of x with y in string"
} | 239310 |
<p>I have these following controller functions for registering a user and login, in my app, and I want to make it more clean and maintainable. </p>
<p>Probably by using <code>async/await</code> and <code>exec()</code>. Also, the validations do not look not good. It would be great if you suggested me good practices to refactor this.</p>
<pre class="lang-js prettyprint-override"><code> registerUser: (req, res) => {
const { username, email, password } = req.body
User.create(req.body, (err, createdUser) => {
if (err) {
return res.status(500).json({ error: "Server error occurred" })
} else if (!username || !email || !password) {
return res.status(400).json({ message: "Username, email and password are must" })
} else if (!validator.isEmail(email)) {
return res.status(400).json({ message: "Invaid email" })
} else if (password.length < 6) {
return res.status(400).json({ message: "Password should be of at least 6 characters" })
}
else {
return res.status(200).json({ user: createdUser })
}
})
},
loginUser: async (req, res, next) => {
const { email, password } = req.body
if (!email || !password) {
return res.status(400).json({ message: "Email and password are must" })
}
await User.findOne({ email }, (err, user) => {
if (err) {
return next(err)
} else if (!validator.isEmail(email)) {
return res.status(400).json({ message: "Invalid email" })
} else if (!user) {
return res.status(402).json({ error: "User not found" })
} else if (!user.confirmPassword(password)) {
return res.status(402).json({ error: "incorrect password" })
}
})
}
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T15:21:09.763",
"Id": "469409",
"Score": "0",
"body": "I suspect the reason you got a down vote was because of the title. The title should tell us about the code rather than about your concerns. A title might be something like `User registration and login for an app`"
}
] | [
{
"body": "<p>Regarding your validations - extract each of your validations in validation object.\nYou can do something like:</p>\n\n<pre><code>class Validator {\n\nisValid(obj) {\n//return false if obj is not valid\n}\n\nmessage(obj) {\n//return error object if obj is not valid\n}\n\nstatus() {\n//error status if validation fails\n}\n\n}\n</code></pre>\n\n<p>Then you can have like <code>EmailValidator</code>, <code>Required</code>, etc. implementation, which validates email strings, etc.\nYou then just iterate through all current validators and if any of them fails to validate, you use it's error message and status to return error object. That way you can easily configure this by editing current validator list and reuse them in different parts of code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T11:49:34.217",
"Id": "239316",
"ParentId": "239312",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "239316",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T11:17:59.493",
"Id": "239312",
"Score": "0",
"Tags": [
"javascript",
"node.js",
"async-await",
"express.js",
"callback"
],
"Title": "Registering a user and login"
} | 239312 |
<p>I sped through the 5hr F# pluralsight course this week-end and thought I'd sement my learning by going through as many Advent of Code puzzles I could with this new learning. However, already on day 2 I'm starting to question whether I'm too biased from C syntax and imperative coding to do it "right".</p>
<p>I really really miss being able to break from for loops for the second solution here. Sure I could make a <code>while</code> loop and have a mutable <code>i</code> and <code>j</code>, but it seems wrong either way. Also, I'd like function pointers for the "ops", but that's just a matter of doing some more work I guess.</p>
<p>In any case, some pointers on things to improve and make more declarative in the code would be super appreciated. Would really like to get going on the right foot before running off to day 3.</p>
<pre><code>open System
open System.IO
let parse = fun (x:String) -> x.Split ',' |> Array.map int
let run (ops:int[]) =
let mutable i = 0
while i < ops.Length do
match ops.[i] with
| 1 ->
let a = ops.[ops.[i+1]]
let b = ops.[ops.[i+2]]
ops.[ops.[i+3]] <- a + b
i <- i + 4
| 2 ->
let a = ops.[ops.[i+1]]
let b = ops.[ops.[i+2]]
ops.[ops.[i+3]] <- a * b
i <- i + 4
| 99 ->
i <- ops.Length
| _ ->
printfn "doh %A" i
ops
let test = parse >> run
let test1 = test "1,0,0,0,99"
let test2 = test "2,3,0,3,99"
let test3 = test "2,4,4,5,99,0"
let test4 = test "1,1,1,4,99,5,6,0,99"
let input = parse <| File.ReadAllText (Path.Combine [|__SOURCE_DIRECTORY__;@"input.txt"|])
let prog1 = Array.copy input
prog1.[1..2] <- [|12;2|]
run prog1 |> ignore
let exp = 19690720
let mutable solNounVerb = (0, 0)
for i = 0 to 100 do
for j = 0 to 100 do
let prg = Array.copy input
prg.[1..2] <- [|i;j|]
run prg |> ignore
if prg.[0] = exp then
solNounVerb <- (i, j)
let sol2 = (fun (i, j) -> i * 100 + j) solNounVerb
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T04:05:42.893",
"Id": "469450",
"Score": "1",
"body": "Here is the [exercise you're referring to](https://adventofcode.com/2019/day/2), for others looking for it"
}
] | [
{
"body": "<p>Possibly not the best solution, but here's one that uses F# more extensively:</p>\n\n<pre class=\"lang-ml prettyprint-override\"><code>let rec processProgram (i: int) (ops: int list) =\n match ops with\n | opCode :: aPos :: bPos :: outPos :: rest when opCode = 1 -> // add op code\n let a = ops |> List.item aPos\n let b = ops |> List.item bPos\n let complete = [opCode; aPos; bPos; outPos] @ processProgram (i + 4) rest\n let (left, right) = complete |> List.splitAt outPos\n left @ [a + b] @ (right |> List.skip 1)\n | opCode :: aPos :: bPos :: outPos :: rest when opCode = 2 -> // multiple op code\n let a = ops |> List.item aPos\n let b = ops |> List.item bPos\n let complete = [opCode; aPos; bPos; outPos] @ processProgram (i + 4) rest\n let (left, right) = complete |> List.splitAt outPos\n left @ [a * b] @ (right |> List.skip 1)\n | head :: rest when head = 99 -> // terminate\n ops\n | _ ->\n failwith \"Unsported opcode\"\n\n</code></pre>\n\n<p>I've turned the function into a recursive function with <code>let rec</code> so that it can be called from within itself, I'll generally use this rather than a loop.</p>\n\n<p>Next I'm using <code>list</code> rather than <code>array</code> so that I can pattern match on the operations. Let's look at that:</p>\n\n<pre class=\"lang-ml prettyprint-override\"><code>match ops with\n| opCode :: aPos :: bPos :: outPos :: rest when opCode = 1 -> // add op cod\n</code></pre>\n\n<p>This expects the list to have <em>at least</em> 4 elements, and I'm destructing it into the pieces we care about, <code>opCode</code> (what we're doing), <code>aPos</code> and <code>bPos</code> (where in the instruction set the values we want are) and <code>outPos</code> (where to put the output in the instruction list). It's then got a <code>when</code> test on the end to check the value of the <code>opCode</code> so we can hit the right op code branch.</p>\n\n<p>When the <code>match</code> is hit we grab the values from their current pos and then process the rest of the instruction set, generating a new <code>list</code> with:</p>\n\n<pre class=\"lang-ml prettyprint-override\"><code>let complete = [opCode; aPos; bPos; outPos] @ processProgram (i + 4) rest\n</code></pre>\n\n<p><em>The <code>@</code> operator concats two <code>list</code>'s together.</em></p>\n\n<p>Then we'll split it on the <code>outPos</code>:</p>\n\n<pre class=\"lang-ml prettyprint-override\"><code>let (left, right) = complete |> List.splitAt outPos\n</code></pre>\n\n<p>This gives us a tuple of <code>int list * int list</code> that we deconstruct into two variables and lastly we rebuild the <code>list</code> through concatinations:</p>\n\n<pre class=\"lang-ml prettyprint-override\"><code>left @ [a + b] @ (right |> List.skip 1)\n</code></pre>\n\n<p>We use the <code>left</code> part to start with, as it is all up until the <code>outPos</code>, then insert the result of the op-code (add in this place) and then <code>concat</code>-ing the <code>right</code> but skipping <code>outPos</code> which is the <code>head</code> of the list.</p>\n\n<p><em>Side note: it's not stated in the requirements that you can update positions beyond the current op stack, so I didn't implement that, it'll only do reverse-updates.</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T13:22:02.103",
"Id": "469477",
"Score": "0",
"body": "Lots of useful info here. Thanks! Think I'll also look into using sequences."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T04:18:00.240",
"Id": "239343",
"ParentId": "239314",
"Score": "4"
}
},
{
"body": "<p>A first simple clean up could be made here:</p>\n\n<blockquote>\n<pre><code> | 1 ->\n let a = ops.[ops.[i+1]]\n let b = ops.[ops.[i+2]]\n ops.[ops.[i+3]] <- a + b\n i <- i + 4\n | 2 ->\n let a = ops.[ops.[i+1]]\n let b = ops.[ops.[i+2]]\n ops.[ops.[i+3]] <- a * b\n i <- i + 4\n</code></pre>\n</blockquote>\n\n<p>The two entries are equal except from the operators (<code>+</code> and <code>*</code>). So you could define a function that takes an operator as argument and return the next <code>i</code>:</p>\n\n<pre><code>let operation i oper (ops: int[]) = \n let a = ops.[ops.[i+1]]\n let b = ops.[ops.[i+2]]\n ops.[ops.[i+3]] <- oper a b\n i + 4\n</code></pre>\n\n<p>This will clean up the main loop to:</p>\n\n<pre><code>let run (ops:int[]) = \n let mutable i = 0\n while i < ops.Length do\n match ops.[i] with\n | 1 -> i <- operation i (+) ops\n | 2 -> i <- operation i (*) ops\n | 99 -> i <- ops.Length\n | _ -> printfn \"doh %A\" i\n ops\n</code></pre>\n\n<hr>\n\n<p>The answer in F# to loops updating mutable variables is often (if not always) recursion (optimally with <a href=\"https://en.wikipedia.org/wiki/Tail_call\" rel=\"nofollow noreferrer\">tail calls</a>). Changing your <code>run</code> function to use recursion could be like this:</p>\n\n<pre><code>let run (ops:int[]) = \n\n let rec runner i =\n match ops.[i] with\n | 1 -> runner (operation i (+) ops)\n | 2 -> runner (operation i (*) ops)\n | 99 -> ops\n | _ -> failwith (sprintf \"Invalid value at index %d\" i)\n\n runner 0\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T13:20:52.343",
"Id": "469476",
"Score": "1",
"body": "Thanks, that was really useful! That's what I meant by function pointers. +1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T13:27:27.680",
"Id": "469479",
"Score": "1",
"body": "Not to mention tail calls. The Advent of Code puzzles will definitely exhaust the stack."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T09:02:50.093",
"Id": "239348",
"ParentId": "239314",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T11:31:34.740",
"Id": "239314",
"Score": "2",
"Tags": [
"programming-challenge",
"f#"
],
"Title": "Advent of Code 2019 day 2 in F#"
} | 239314 |
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class List<T>
{
private T[] arrayList;
private int arrayLenght = 5;
private int arrayIndex = 0;
public List()
{
arrayList = new T[arrayLenght];
}
internal string[] toArray()
{
string[] arrayListArray = new string[arrayLenght];
try
{
for (int j = 0; j < arrayList.Length; j++)
{
if (arrayList[j] == null)
{
arrayListArray[j] = "";
}
else
{
arrayListArray[j] = arrayList[j].ToString();
}
}
}
catch(Exception Ex)
{
Console.WriteLine(Ex);
}
return arrayListArray;
}
private void ArrayOverFlow(T genericParameter)
{
try
{
arrayLenght = 2 * arrayLenght;
T[] arrayListNewSize = new T[arrayLenght];
int arrayListNewSizeIndex = 0;
Array.Copy(arrayList, arrayListNewSize, arrayList.Length);
arrayList = new T[arrayLenght];
Array.Copy(arrayListNewSize, arrayList, arrayListNewSize.Length);
arrayListNewSize = null;
arrayList[arrayIndex] = genericParameter;
arrayIndex++;
}
catch (Exception Ex)
{
Console.WriteLine(Ex);
}
}
internal void Add(T genericParameter)
{
// Console.WriteLine("Parameter type: {0}, value: {1}", typeof(T).ToString(), genericParameter);
try
{
if (arrayIndex + 1 <= arrayLenght)
{
arrayList[arrayIndex] = genericParameter;
arrayIndex++;
}
else
{
ArrayOverFlow(genericParameter);
}
}
catch (Exception Ex)
{
Console.WriteLine(Ex);
}
}
internal void Insert(int index, T genericParameter)
{
try
{
arrayList[index] = genericParameter;
}
catch (Exception Ex)
{
Console.WriteLine(Ex);
}
}
private void RemoveArray(int index)
{
try
{
for (int i = index; i < arrayList.Length; i++)
{
if (i < arrayList.Length - 1)
{
arrayList[i] = arrayList[i + 1];
}
}
}
catch (Exception Ex) {
Console.WriteLine(Ex);
}
}
internal void RemoveAt(int index)
{
RemoveArray(index);
}
internal void Remove(T genericParameter)
{
try
{
for (int i = 0; i < arrayList.Length; i++)
{
if (arrayList[i] != null)
{
if (arrayList[i].Equals(genericParameter))
{
RemoveArray(i);
}
}
}
}
catch (Exception Ex)
{
Console.WriteLine(Ex);
}
}
}
}
</code></pre>
<p>I have also written test cases for the same </p>
<pre><code>using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
[TestFixture]
class Test1
{
[TestCase]
public void TestAdd1()
{
List<int> st = new List<int>();
st.Add(10);
st.Add(20);
st.Add(30);
st.Add(40);
st.Add(50);
st.Add(60);
Assert.AreEqual("10,20,30,40,50,60,0,0,0,0", string.Join(",", st.toArray()));
}
[TestCase]
public void TestAdd2()
{
List<string> st = new List<string>();
st.Add("10");
st.Add("20");
st.Add("30");
st.Add("40");
st.Add("50");
st.Add("60");
Assert.AreEqual("10,20,30,40,50,60,,,,", string.Join(",", st.toArray()));
}
[TestCase]
public void TestAdd3()
{
List<int> st = new List<int>();
st.Add(10);
st.Add(20);
st.Add(30);
st.Add(40);
st.Add(50);
st.Add(60);
st.Insert(2, 70);
Assert.AreEqual("10,20,70,40,50,60,0,0,0,0", string.Join(",", st.toArray()));
}
[TestCase]
public void TestAdd4()
{
List<string> st = new List<string>();
st.Add("10");
st.Add("20");
st.Add("30");
st.Add("40");
st.Add("50");
st.Add("60");
st.Insert(2, "70");
Assert.AreEqual("10,20,70,40,50,60,,,,", string.Join(",", st.toArray()));
}
[TestCase]
public void TestAdd5()
{
List<int> st = new List<int>();
st.Add(10);
st.Add(20);
st.Add(30);
st.Add(40);
st.Add(50);
st.Add(60);
st.RemoveAt(2);
Assert.AreEqual("10,20,40,50,60,0,0,0,0,0", string.Join(",", st.toArray()));
}
[TestCase]
public void TestAdd6()
{
List<string> st = new List<string>();
st.Add("10");
st.Add("20");
st.Add("30");
st.Add("40");
st.Add("50");
st.Add("60");
st.RemoveAt(2);
Assert.AreEqual("10,20,40,50,60,,,,,", string.Join(",", st.toArray()));
}
[TestCase]
public void TestAdd7()
{
List<int> st = new List<int>();
st.Add(10);
st.Add(20);
st.Add(30);
st.Add(40);
st.Add(50);
st.Add(60);
st.Remove(30);
Assert.AreEqual("10,20,40,50,60,0,0,0,0,0", string.Join(",", st.toArray()));
}
[TestCase]
public void TestAdd8()
{
List<string> st = new List<string>();
st.Add("10");
st.Add("20");
st.Add("30");
st.Add("40");
st.Add("50");
st.Add("60");
st.Remove("30");
Assert.AreEqual("10,20,40,50,60,,,,,", string.Join(",", st.toArray()));
}
}
}
</code></pre>
<p>I am learning data structure so I tried to implement a list for better understanding so any feedback and code review would be helpful.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T18:28:36.743",
"Id": "469422",
"Score": "1",
"body": "Does the current code work as intended?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T21:29:03.713",
"Id": "469437",
"Score": "0",
"body": "At least the sequence of letters in `arrayLenght` looks consistent. Who is to judge *works as intended*? No intention is documented. `Insert(i, T)` looks weird; `RemoveArray(i)` a reference hog."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T05:35:43.263",
"Id": "470067",
"Score": "0",
"body": "the above code works as expected so can you tell me what did look weird in insert in Insert"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T06:16:46.363",
"Id": "470071",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] | [
{
"body": "<p>Your Insert is wrong, you have to do it the same way as the Remove with shifting Elements. ArrayIndex is not increased to decreased on Remove/Insert. </p>\n\n<p>Better don't call any parameter a parameter or add the DataType to it. Name as you speak. You insert an 'item' or an 'element' to your list. Not a parameter.</p>\n\n<p>Always Doubling the array on overflow can lead to very huge arrays. Imagine you have a 1 Gigabyte Array and you want to add 1 element,you allocate 1 new gigabyte for that.\nIt's better to increase by a fixed amount of items, like 16 or may 1024.</p>\n\n<p>Why do you have to have two Array.Copy on reallocation ?\nUsual approach is to create a new array and copy existing elements.</p>\n\n<pre><code>var tmp = new T[newarraylength];\nArray.Copy(arrayList, tmp, oldarraylength);\narrayList = tmp;\n</code></pre>\n\n<p>I don't get why you copy something twice.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T05:43:00.570",
"Id": "470069",
"Score": "0",
"body": "I have edited my code as you said for array copy but as you said the insert code is wrong but .i have see code \nhttps://codereview.stackexchange.com/questions/144360/implementation-of-a-generic-list?rq=1 which see the same as mine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T07:53:15.387",
"Id": "470204",
"Score": "0",
"body": "No, the other code is fine. It does not have any Insert at all, and the place with two Array.Copy handles two sections of the same array. Sure I'm just assuming what insert means, for me it's adding an element in the middle. What you do is replacing an element."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T16:49:18.490",
"Id": "239326",
"ParentId": "239321",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T14:43:22.407",
"Id": "239321",
"Score": "2",
"Tags": [
"c#",
"object-oriented"
],
"Title": "simple implementation of List in c#"
} | 239321 |
<h2>What I'm trying to achieve</h2>
<p>From a list of lists of elements (one element can be in multiple lists, but only once in each list), I want to generate a map whose keys are each elements and the values are the collection of elements that appear at least once with the key in the first lists.</p>
<h2>Example</h2>
<p>This is the input :</p>
<pre><code>List<List<String>> input = Arrays.asList(
Arrays.asList("calculating", "label", "farm", "anger", "able", "aboriginal"),
Arrays.asList("injure", "label", "anger", "teeny-tiny", "able", "mindless", "teen"),
Arrays.asList("injure", "calculating", "teeny-tiny", "mindless", "aboriginal")
);
</code></pre>
<p>I simplified the problem by using Strings but the elements could be any object. Please notice that:</p>
<ul>
<li>some words appear in multiple lists</li>
<li>the list don't have any duplicates</li>
</ul>
<p>The expected output should look like this:</p>
<pre><code>{
able=[teeny-tiny, farm, calculating, aboriginal, label, mindless, anger, injure, teen],
teeny-tiny=[able, calculating, aboriginal, label, mindless, anger, injure, teen],
farm=[able, calculating, aboriginal, label, anger],
calculating=[able, teeny-tiny, farm, aboriginal, label, mindless, anger, injure],
aboriginal=[able, teeny-tiny, farm, calculating, label, mindless, anger, injure],
label=[able, teeny-tiny, farm, calculating, aboriginal, mindless, anger, injure, teen],
mindless=[able, teeny-tiny, calculating, aboriginal, label, anger, injure, teen],
anger=[able, teeny-tiny, farm, calculating, aboriginal, label, mindless, injure],
injure=[able, teeny-tiny, calculating, aboriginal, label, mindless, anger]
}
</code></pre>
<p>So for example you see that the list associated with the value <code>farm</code> contains the value <code>calculating</code> because those two words were together in the first list of the input.</p>
<p>Also note that the resulting collections should not have duplicates: <code>label</code> and <code>able</code> are together in the first <em>and</em> second lists of the input, but the list associated to the key <code>able</code> (resp. <code>label</code>) in the result contains only one <code>label</code> (resp. <code>able</code>).</p>
<p>This is just an example. For my real problem, the input would not contain 3 lists of 5 or 6 elements, but a few thousand lists with hundreds of elements.</p>
<h2>The language</h2>
<p>I'm implementing this in Java.</p>
<h2>My solution</h2>
<p>This is what I could come up with and I'd like you to review:</p>
<pre><code>Map<String, Set<String>> result = new HashMap<>();
for (List<String> values : input.values()) {
for (String str : values) {
Set<String> l = result.getOrDefault(str, new HashSet<>());
l.addAll(values);
l.remove(str);
result.put(str, l);
}
}
</code></pre>
<h2>What I am going to use that for</h2>
<p>It represents a simplification of a part of a problem I'm working with. I want to detect objects that are similar, but fully comparing two objects is computationally expensive. But I have a cheap way of grouping objects by characteristic. I want to use those characteristics to compare only objects that are potential matches.</p>
<p>For example, notice that, in the input of my example above, all the words of the first list contain an <code>a</code>, all the words of the second list contain a <code>e</code> and an <code>i</code> for the third list. With the resulting map, I will be able to tell, for each of the keys, the list of words sharing one of those vowels. That way, I can avoid comparing <code>farm</code> and <code>teen</code> because they have nothing in common.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T15:28:58.620",
"Id": "469412",
"Score": "5",
"body": "Welcome to code review. What are you using the map for? What is the language you are using. We could provide a better review with more code and more information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T15:59:00.697",
"Id": "469413",
"Score": "0",
"body": "(For your example, better have sets in `result` look widely different - choose none-too-common characters, consonants?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T07:08:52.167",
"Id": "469459",
"Score": "2",
"body": "I would have loved to vote to re-open this question. I would have much preferred to be presented the code where these `Map`s are used; one of my doubts: why not use this information \"on the fly\" instead of putting it into a map from keys to sets of related items? \"In order to give good advice, we need to see real, concrete code, and understand the context in which the code is used.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T09:06:31.550",
"Id": "469464",
"Score": "0",
"body": "Code Review does not do well with simplifications. Please take a look at our [FAQ on asking question](https://codereview.meta.stackexchange.com/q/2436/52915)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T11:20:34.237",
"Id": "469469",
"Score": "1",
"body": "I think closing this question is unduly harsh. However I suggest you wrap your solution code in a a method and class. Add a test case based on your data and expected results and appeal the closure. On Code Review do not worry about posting 'too much code'."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T14:53:33.597",
"Id": "239322",
"Score": "1",
"Tags": [
"java",
"hash-map"
],
"Title": "Map of objects sharing characteristics"
} | 239322 |
<p>I am a beginner with C++, I am not learning OOP yet, I will start when I finish this project.<br>
I'm working on "Educational Management System Project".<br>
So I had trouble to code the part of login and sign up,
I am not comfortable with this approach, I wonder if there is a solution to simplify this code and reducing <code>if</code>-statement and functions in authentication.cpp file.</p>
<p><strong>ems.h</strong></p>
<pre><code>#include <iostream>
#include <vector>
#include <string>
#include <memory>
using namespace std;
struct Person;
struct Doctor;
struct TeacherA;
struct Student;
struct Course;
struct Assignment;
struct AssignmentSolution;
// Main data
struct Person
{
int id;
string username;
string fullName;
string email;
string password;
};
struct Doctor
{
Person info;
vector <shared_ptr <Course>> courses;
};
struct TeacherA
{
Person info;
vector <shared_ptr <Course>> courses;
};
struct Student
{
Person info;
vector <shared_ptr <Course>> courses;
vector <shared_ptr <AssignmentSolution>> assignmentSolutions;
};
struct Course
{
string code;
string title;
shared_ptr <Doctor> lecturer;
shared_ptr <TeacherA> assistant;
vector <shared_ptr <Student>> registeredStudents;
vector <shared_ptr <Assignment>> assignments;
};
struct Assignment
{
string content;
int maxMark;
shared_ptr <Course> course;
vector <shared_ptr <AssignmentSolution>> assignmentSolutions;
};
struct AssignmentSolution
{
bool isMarked = false;
string solution;
int mark;
string comment = "There is no comment";
shared_ptr <Assignment> assignment;
shared_ptr <Student> student;
};
extern vector <shared_ptr <Doctor>> doctors;
extern vector <shared_ptr <TeacherA>> teachersA;
extern vector <shared_ptr <Student>> students;
extern vector <shared_ptr <Course>> courses;
int mainMenu();
int startMethod(int role);
void signUp(int role);
void signIn(int role);
bool verifyDoctorData(string username, string password);
bool verifyStudentData(string username, string password);
void addUserInfo(int role, Person info);
int createID(int role);
</code></pre>
<p><strong>ems.cpp</strong></p>
<pre><code>#include "ems.h"
vector <shared_ptr <Doctor>> doctors;
vector <shared_ptr <TeacherA>> teachersA;
vector <shared_ptr <Student>> students;
vector <shared_ptr <Course>> courses;
int main() {
cout <<"* Welcome in Educational Management System Project *\n";
mainMenu();
}
int mainMenu() {
int role = -1;
while (role) {
cout << "\nPlease enter a choice: \n"
<< "\t[1] Doctor\n"
<< "\t[2] Teacher Assistant\n"
<< "\t[3] Student\n"
<< "\t[0] Exit\n"
<<"Your choice: ";
cin >> role;
if (role) startMethod(role);
}
}
int startMethod(int role) {
int method = -1;
while (method) {
cout << "\nPlease enter a choice: \n"
<< "\t[1] Sign Up\n"
<< "\t[2] Sign In\n"
<< "\t[0] Back\n"
<<"Your choice: ";
cin >> method;
if (method == 1)
signUp(role);
else if (method == 2)
signIn(role);
}
}
</code></pre>
<p><strong>authentication.cpp</strong></p>
<pre><code>#include "ems.h"
void signUp(int role) {
Person info;
cout << "\nPlease enter the following information:\n";
cout << "Full Name: ";
getline(cin >> ws, info.fullName);
cout << "E-mail: ";
cin >> info.email;
cout << "Username: ";
cin >> info.username;
cout << "Password: ";
cin >> info.password;
info.id = createID(role);
if (role == 1 && !verifyDoctorData(info.username, info.password)) {
addUserInfo(role, info);
}
else if (role == 3 && !verifyStudentData(info.username, info.password)) {
addUserInfo(role, info);
} else {
cout << "This user already exist";
}
}
void signIn(int role) {
string username, password;
cout << "Username: ";
cin >> username;
cout << "Password: ";
cin >> password;
if (role == 1 && verifyDoctorData(username, password)) {
loginMenu(role, username);
}
else if (role == 3 && verifyStudentData(username, password)) {
loginMenu(role, username);
} else {
cout << "Username or Password Incorect";
}
}
bool verifyDoctorData(string username, string password) {
for (auto doctor: doctors) {
if (username == doctor->info.username && password == doctor->info.password) {
return true;
}
}
return false;
}
bool verifyStudentData(string username, string password) {
for (auto student: students) {
if (username == student->info.username && password == student->info.password) {
return true;
}
}
return false;
}
void addUserInfo(int role, Person info) {
if (role == 1) {
shared_ptr <Doctor> newDoctor (new Doctor);
newDoctor->info = info;
doctors.push_back(newDoctor);
} else if (role == 3) {
shared_ptr <Student> newStudent (new Student);
newStudent->info = info;
students.push_back(newStudent);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T17:42:33.620",
"Id": "469420",
"Score": "4",
"body": "Welcome to code review, you would get a better review if you posted the entire file so that we could properly review the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T18:43:55.677",
"Id": "469424",
"Score": "3",
"body": "@pacmaninbw I posted it, this was the first question here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T19:21:47.987",
"Id": "469428",
"Score": "0",
"body": "@AbdelwahabHussien Why don't you use inheritance from `Person` for `Teacher`, `Doctor` and `Student`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T19:24:39.460",
"Id": "469429",
"Score": "0",
"body": "@πάνταῥεῖ I don't think the poster is ready for inheritance based on the coding level, but it is a good suggestion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T19:28:06.280",
"Id": "469430",
"Score": "0",
"body": "@pacmaninbw _\"I don't think the poster is ready for inheritance based on the coding level,\"_ Well the we'll have a hard time to explain them how their code can be improved."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T19:33:17.030",
"Id": "469431",
"Score": "0",
"body": "Besides inheritance there's also the option to use a templated function to access the `info` class variables, instead of writing a own for each of the vectors."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T19:38:10.783",
"Id": "469433",
"Score": "1",
"body": "Does the code work? If it doesn't it might be better to ask this question on stackoverflow.com rather then on code review. We only review working code. FYI, it seems that you should have a header file called `authentication.h` that contains the function prototypes for `signUp(role);` and `signIn(role);`. The functions `createID(role)` and `addUserInfo(role, info);` also seem to be missing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T02:14:33.910",
"Id": "469446",
"Score": "0",
"body": "@pacmaninbw Yes the code work correctly in login and signup, I will complete this projects but I want to complete this part correctly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T02:16:40.167",
"Id": "469447",
"Score": "2",
"body": "@πάνταῥεῖ I am not learning OOP yet, I will start when I finish this project."
}
] | [
{
"body": "<p>Here are some things that may help you improve your code.</p>\n\n<h2>Don't abuse <code>using namespace std</code></h2>\n\n<p>Putting <code>using namespace std</code> at the top of every program is <a href=\"http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">a bad habit</a> that you'd do well to avoid. Know when to use it and when not to (as when writing include headers).</p>\n\n<h2>Provide complete code to reviewers</h2>\n\n<p>This is not so much a change to the code as a change in how you present it to other people. Without the full context of the code and an example of how to use it, it takes more effort for other people to understand your code. This affects not only code reviews, but also maintenance of the code in the future, by you or by others. One good way to address that is by the use of comments. Another good technique is to include test code showing how your code is intended to be used. For this code, I added these two functions to make it compileable:</p>\n\n<pre><code>int createID(int role) {\n static int id{1000};\n return ++id + role * 10000;\n}\n\nvoid loginMenu(int role, std::string& username)\n{\n std::cout << \"Successful login of \" << username << \" as role \" << role << '\\n';\n}\n</code></pre>\n\n<h2>Use objects</h2>\n\n<p>You have a <code>Person</code> structure and then separate functions that operate on <code>Person</code> data. With only a slight syntax change, you would have a real object instead of C-style code written in C++.<br>\nSo to begin with, you might define a <code>Person</code> class like this:</p>\n\n<pre><code>class Person\n{\npublic:\n Person(int id, std::string& username, std::string& fullName, std::string& email, std::string& password);\n bool isMatch(const std::string& name, const std::string& pw) const;\nprivate:\n int id;\n std::string username;\n std::string fullName;\n std::string email;\n std::string password;\n};\n</code></pre>\n\n<p>Now we can now create a <a href=\"https://en.cppreference.com/w/cpp/language/derived_class\" rel=\"nofollow noreferrer\">derived class</a> to define a <code>Doctor</code>:</p>\n\n<pre><code>class Doctor : public Person\n{\npublic:\n Doctor(Person& p) : Person{p} {}\nprivate:\n std::vector <std::shared_ptr <Course>> courses;\n};\n</code></pre>\n\n<p>This derivation is the Object Oriented Programming (OOP) way to express the <em>is-a</em> relationship. That is, a <code>Doctor</code> is a <code>Person</code> so everthing that a person has or can do, a doctor has or can do. </p>\n\n<h2>Add behavior to objects for simpler code</h2>\n\n<p>Note too that we have defined the <code>isMatch</code> function for a <code>Person</code>. We might define it like this:</p>\n\n<pre><code>bool Person::isMatch(const std::string& name, const std::string& pw) const {\n return name == username && pw == password;\n}\n</code></pre>\n\n<p>Now instead of this code:</p>\n\n<pre><code>bool verifyDoctorData(string username, string password) {\n for (auto doctor: doctors) {\n if (username == doctor->info.username && password == doctor->info.password) {\n return true;\n }\n }\n return false;\n}\n</code></pre>\n\n<p>We can write this:</p>\n\n<pre><code>bool verifyDoctorData(std::string username, std::string password) {\n for (const auto& doctor: doctors) {\n if (doctor->isMatch(username, password)) {\n return true;\n }\n }\n return false;\n}\n</code></pre>\n\n<p>However, even better is the following suggestion.</p>\n\n<h2>Use standard algorithms where practical</h2>\n\n<p>Do we really need to have separate <code>verifyDoctorData</code> and <code>verifyStudentData</code>? They're really nearly identical. What I'd do instead is to use <code>std::none_of</code> or <code>std::any_of</code> and the function mentioned above. So instead of this:</p>\n\n<pre><code>if (role == 1 && !verifyDoctorData(info.username, info.password)) {\n addUserInfo(role, info);\n}\n</code></pre>\n\n<p>One could write this:</p>\n\n<pre><code>if (role == 1 && std::none_of(doctors.cbegin(), doctors.cend(), std::bind(&Person::isMatch, std::placeholders::_1, username, password))) {\n addUserInfo(role, info);\n}\n</code></pre>\n\n<p>Now there is no need at all to write a <code>verifyDoctorData</code> function.</p>\n\n<h2>Use an <code>enum</code> where appropriate</h2>\n\n<p>In the code above, instead of <code>role == 1</code>, wouldn't it make more sense to write <code>role == doctor</code>? One could do that with an <code>enum</code>. </p>\n\n<p>There's much more, but this should be enough to get you started and to convey to you that learning C++ and learning OOP are not separate phases.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T13:07:30.427",
"Id": "469546",
"Score": "0",
"body": "Thanks, this was helpful to me, and of course, I'm going to start learning oop that looks powerful."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T21:55:31.020",
"Id": "239379",
"ParentId": "239328",
"Score": "3"
}
},
{
"body": "<p>Well, hello. I was getting a bit bored today, so thank you for giving me a nice little exercise to work on. I edited the code, removing unnecessary lines and editing things here and there.</p>\n\n<p>Since you specified that you don't yet know much about OOP I made sure not to take the easier approach, which in my mind is a vector of pointers to a virtual class named and then using it to fit in other higher derived classes in them. This is a hobby for me so I have no clue if I'm correctly communicating the concepts I'm trying to talk about, but I tried.</p>\n\n<p>Part of the question was if there was a better way to reduce the number of if statements in the code that are needed by the UI to test the user's input and make selections based on them. The best way of doing that than I ever thought about is by using a map with the selections already in it as keys and having function pointers as values that can be called with a key.</p>\n\n<p>There are suggestions I have for you, with a very shallow and not at all comprehensive explanation:</p>\n\n<ul>\n<li>Avoid <code>using namespace std;</code>; bad practice</li>\n<li>Learn OOP; It would have been more than beneficial in this case</li>\n<li><em>(Personal Opinion)</em> Start using the c io functions <code>printf()</code> and <code>scanf()</code>; format strings make code so much neater(It's a beautiful thing)</li>\n<li>Try to make your program as simple as you possibly can; it makes things easier to read, edit and understand(You didn't need to have all those function declarations in the header file, and there were some unneeded <code>std::shared_ptr</code>s)</li>\n<li><em>(Personal Opinion)</em> Make a <strong>main.cpp</strong> file for <code>main()</code>; putting it in a random file is unconventional</li>\n<li>Use the header guards; the errors that come with not using them are bothersome</li>\n<li>Usually, C++ header files are given the extension <strong>.hpp</strong>; I 99% sure it helps the compiler distinguish between C headers and C++ headers, but I'm doubting myself a little on this one.</li>\n<li><em>(For this program specifically)</em> If you intend on using it to a degree, you should probably get write a function that can pass out the information and another to read it in; Who wants to Sign-Up to a service every time to Sign-In</li>\n<li>Get in the habit of writing lists of things you can improve on.</li>\n</ul>\n\n<p>Don't worry, when I started off I got banned from stack overflow because of my cluelessness(Feel free to check out the questions I used to ask, they're fun to laugh at). I'm still banned to this day. Everyone has things they can work on. For me, it would be getting unbanned.</p>\n\n<p>Anyways, the insertion code is incomplete because I got bored, so you can't actually insert any information, but I gave you a starting point for your UI and I can't do everything for you(Basically I'm too lazy to finish, but you get to learn something and I get to relax, so it's a win-win). I might get bored of relaxing and come back and finish this, but this should sufficiently help you for now.</p>\n\n<p>Here's the code:</p>\n\n<p><strong>main.cpp</strong></p>\n\n<pre><code>#include \"ems.hpp\"\n\nint main(){\n runEducationalManagementSystemProject();\n return 0;\n}\n</code></pre>\n\n<p><strong>ems.hpp</strong></p>\n\n<pre><code>#ifndef ems_hpp\n#define ems_hpp\n\n#include <vector>\n#include <string>\n#include <memory>\n\n// Main data\nstruct Person\n{\n int id;\n std::string username;\n std::string fullName;\n std::string email;\n std::string password;\n\n\n};\n\nstruct Assignment;\nstruct AssignmentSolution\n{\n bool isMarked = false;\n std::string solution;\n int mark;\n std::string comment = \"There is no comment\";\n std::shared_ptr <Assignment> assignment;\n std::shared_ptr <Person> student;\n};\n\nstruct Course;\nstruct Assignment\n{\n std::string content;\n int maxMark;\n std::shared_ptr <Course> course;\n std::vector <std::shared_ptr <AssignmentSolution>> assignmentSolutions;\n};\n\nstruct Course\n{\n std::string code;\n std::string title;\n std::shared_ptr <Person> lecturer;\n std::shared_ptr <Person> assistant;\n std::vector <std::shared_ptr <Person>> registeredStudents;\n std::vector <std::shared_ptr <Assignment>> assignments;\n};\n\n\n// Data\nextern std::vector <Person> doctors;\nextern std::vector <Person> teachers;\nextern std::vector <Person> students;\nextern std::vector <std::shared_ptr <Course>> courses;\n\n// Current user\nextern std::string currentUser;\n\n// Functions\nvoid runEducationalManagementSystemProject();\n\n#endif /* ems_hpp */\n</code></pre>\n\n<p><strong>ems.cpp</strong></p>\n\n<pre><code>#include \"ems.hpp\"\n// Externs\nstd::vector <Person> doctors;\nstd::vector <Person> teachers;\nstd::vector <Person> students;\n\nstd::string currentUser;\n\n#include <cstdio>\n#include <map>\n#include <string.h>\n\nbool exists(std::string uName){\n printf(\"Checking if \\\"%s\\\" exitsts\", uName.c_str());\n for (int i = 0; i < doctors.size(); i++) {\n if (strcmp(doctors.at(i).username.c_str(),uName.c_str())) {\n return true;\n }\n }\n\n for (int i = 0; i < teachers.size(); i++) {\n if (strcmp(teachers.at(i).username.c_str(),uName.c_str())) {\n return true;\n }\n }\n\n for (int i = 0; i < students.size(); i++) {\n if (strcmp(students.at(i).username.c_str(),uName.c_str())) {\n return true;\n }\n }\n return false;\n}\n\nbool correctPassword(std::string uName, std::string password){\n for (int i = 0; i < doctors.size(); i++) {\n if (strcmp(doctors.at(i).username.c_str(),uName.c_str())) {\n if (strcmp(doctors.at(i).password.c_str(), password.c_str())) {\n return true;\n } else {\n return false;\n }\n }\n }\n\n for (int i = 0; i < teachers.size(); i++) {\n if (strcmp(teachers.at(i).username.c_str(),uName.c_str())) {\n if (strcmp(teachers.at(i).password.c_str(), password.c_str())) {\n return true;\n } else {\n return false;\n }\n }\n }\n\n for (int i = 0; i < students.size(); i++) {\n if (strcmp(students.at(i).username.c_str(),uName.c_str())) {\n if (strcmp(students.at(i).password.c_str(), password.c_str())) {\n return true;\n } else {\n return false;\n }\n }\n }\n\n exit(1); // No user exists even though exits returned true, stop the program from running in needless perpetual loop\n return false;\n}\n\nstruct MainMenu {\n static std::string display;\n static std::map<unsigned int, void (*)()> options;\n};\nstd::string MainMenu::display;\nstd::map<unsigned int, void (*)()> MainMenu::options;\n\nvoid mainMenu(){\n while (true) {\n printf(\"%s\",MainMenu::display.c_str());\n int option = 0;\n scanf(\"%d\", &option);\n MainMenu::options[option](); // Calls the function that has been connected to the key int the setup\n }\n}\n\nvoid signUp() {\n Person newUser;\n\n char* buffer;\n\n printf(\"\\nPlease enter the following information:\\n\");\n\n printf(\"Full Name: \");\n scanf(\"%s\", buffer);\n newUser.fullName = std::string(buffer);\n\n printf(\"E-mail: \");\n scanf(\"%s\", buffer);\n newUser.email = std::string(buffer);\n\n printf(\"Username: \");\n scanf(\"%s\", buffer);\n newUser.username = std::string(buffer);\n while (exists(newUser.username)) {\n printf(\"The username %s is already taken\\n\", newUser.username.c_str());\n printf(\"Username: \");\n scanf(\"%s\", buffer);\n newUser.username = std::string(buffer);\n }\n\n printf(\"Password: \");\n scanf(\"%s\", buffer);\n newUser.password = std::string(buffer);\n\n students.push_back(std::move(newUser));\n}\n\nvoid signIn() {\n\n printf(\"\\nPlease enter Sign-In details: \\n\\tUsername: \");\n char* buffer;\n scanf(\"%s\", buffer);\n\n std::string newSignIn(buffer);\n\n int chances = 3;\n tryAgain:\n printf(\"\\tPassword: \");\n scanf(\"%s\", buffer);\n\n std::string password(buffer);\n\n if (exists(newSignIn)) {\n // Check if the password given matches that users password\n if (correctPassword(newSignIn, password)) {\n currentUser = newSignIn;\n } else {\n printf(\"Incorrect Password try again(%d)\\n\", chances);\n chances--;\n if (chances == 0) {\n printf(\"Sorry, you've used up all your chances\\n\");\n return;\n }\n goto tryAgain;\n }\n } else {\n printf(\"User does not exits, did not sign-in\\n\");\n }\n}\n\nvoid quit(){\n exit(0);\n}\n\nvoid setup(){\n // Main Menu setup\n MainMenu::display = \"\\nPlease enter a choice: \\n\\t[1] Sign-In\\n\\t[2] Sign-Up\\n\\t[0] Quit\\n\";\n MainMenu::options.insert(std::make_pair(1, &signIn));\n MainMenu::options.insert(std::make_pair(2, &signUp));\n MainMenu::options.insert(std::make_pair(0, &quit));\n}\n\nvoid runEducationalManagementSystemProject() {\n setup();\n mainMenu();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T01:13:30.663",
"Id": "469581",
"Score": "0",
"body": "Stream formatting is indeed painful to use, but the C functions are worse because they are type unsafe, cannot be customized, and risk buffer overflow (for scanf). Use the [{fmt}](https://fmt.dev) library instead, which is also known to have the best performance among similar libraries and standardized in C++20."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T22:21:13.250",
"Id": "239380",
"ParentId": "239328",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T17:36:07.217",
"Id": "239328",
"Score": "4",
"Tags": [
"c++",
"beginner"
],
"Title": "login into school system"
} | 239328 |
<p>This is my first project and I wrote it to practice coding. However, I'm wondering if there is an actual practical use for it. What this code does is list the number of times a word occurs in a text entry, either by alphabetical order, listing the frequency of the word or listing the index in the text entry where that word occurs. I am wondering what improvements or useful features could be added to it, and (as stated earlier) what is a real world application of this code. </p>
<pre><code>from collections import Counter
from string import punctuation
import string
from typing import List
import operator
punctuate = ['\"',
',',
'\"',
"\'",
"\'",
'.' ,
":" ,
";" ,
"!" ,
"?" ,
"\'",
"\'",
"'" ,
"," ,
"(" ,
")" ,
"{",
"}" ,
"[" ,
"]" ,
'“',
'”',
"'",
"’",
'‘',
'.',
'#'
] # text from websites use different quote marks than Pycharm so they where not registered
# ...but here are all the annoying punctuation marks
# that took forever to figure out how to decipher them in syntax and then get rid of them
print(punctuation) # makes a list of punctuation
print("Enter/Paste your multi-line input / paragraph of text. Hit Ctrl + D to run it ")
print("DO NOT PRESS ENTER OR CTRL+V AFTER THE FIRST TIME YOU PASTED IN AND RUN YOUR TEXT(UNLESS PASTED TEXT IS A SINGLE LINE WITH NO BREAKS ")
print("INSTEAD HIT CTRL + D TO RUN IT AFTER TEXT IS INPUTTED WHEN TERMINAL HAS STOPPED RUNNING AND THE INPUT '|' IS STILL AND FLASHING")
###$%^&*()(*&^%$%^&*()_)(*&^%$#$r%t^&*()_)(*&^%$%^&*()_)(*&^%$%^&*()_)(*&^%$#$%^&*()(*&^%$#$%^&*()(*&^%$#$%^&*()*&^%$#$%^&*()_+@#$%^&*()_#$%^&*()_
work_on_this_string_built_from_loop = r"" # this initializes out of the loop and adds
# text from input as a single lined string
iteratory_count = 0 #initalized outside the loop to count the number of iteration required to process data..
# reports last iteration count accurately once CTRL + D is pushed
###$%^&*()(*&^%$%^&*()_)(*&^%$#$r%t^&*()_)(*&^%$%^&*()_)(*&^%$%^&*()_)(*&^%$#$%^&*()(*&^%$#$%^&*()(*&^%$#$%^&*()*&^%$#$%^&*()_+@#$%^&*()_#$%^&*()_
while True: # the loop will always = True so this creates an infinite loop
iteratory_count += 1
#print("DO NOT PRESS ENTER OR CTRL+V AFTER YOU HAVE INITIALLY RAN YOUR TEXT ") # this line will be used when trouble shooting output
print()
try:
print(f"THE OUTPUT ABOVE IS NOT THE FINAL RESULT, THE PROGRAM IS NOT DONE YET: WE ARE NOW ON ITERATION {iteratory_count}")
multi_lined_input = input("\n") # blank screen of input will appear after text is pasted in
multi_lined_input=multi_lined_input.lower()
multi_lined_input=multi_lined_input.replace('-', ' ') # this allows to get rid "-" while it is still a string, cannot do if string is in fact
# a string element that is part of an array of strings
work_on_this_string_built_from_loop += multi_lined_input + ('' if multi_lined_input == ' ' else ' ') # this breaks lines officially
# and stops the last character
# of a line of input being deleted
# because the else statement will repeat
# the if statement within the loop
#get_rid_of_refference_nums = list(range(0,10000000000) )
raw_word_list = work_on_this_string_built_from_loop.split()
get_rid_of_punctuation_marks = [item[:-1] if item[-1] in punctuate else item[1:] if item[0] in punctuate else item for item in raw_word_list]
#print(item[:-1]) # everything but last char
#
#print(item[-1]) # just the last char
#
#print(item[1:]) # everything but first char
# Punctuation marks must be get ridden of because if the are at the end of word (like a '.'at the end of a sentence)
# they will count the word with a trailing punctuation mark as a unique entry instead of being counted
# with the rest of the words in the entry. ie, 'for!' wouldn't be counted with 'for'
#first part of all_as_one makes item = every char in string element except last char IF
# the last char of string element is an entry in puncutate (list of puntaution marks)
#
# second part of all_as_one makes item = every char in string element except if the first char
# is the first char of string element is an element within puncutate (list of puntaution)
remove_consecutive_trailing_punctuation = [next_item[:-1] if next_item[-1] in punctuation else next_item for next_item in get_rid_of_punctuation_marks]
# same thing as the first part of all_as_one and removes if there is consecutive punctation marks at the end of the string element
capitalized_array=[ capz.capitalize() for capz in remove_consecutive_trailing_punctuation]
print()
print()
frequency_of_words_dict = dict( Counter( capitalized_array ) )
#print()
#print(f"THIS LINE IS MADE TO TEST THE FINAL OUTPUT WHEN TROUBLE SHOOTING {frequency_of_words_dict}")
except EOFError as error : # this allows for quiting the program using CTRL + D
# once the error is excepted, the program ends and this
#causes the break statement to execute and the loop ends
print("ITERATING THROUGH EXCEPTION")
print()
keys_and_values_tuples_list = [(key, value) for key, value in frequency_of_words_dict.items()] # creates a list of tuples out of array
#print(f"FOR TESTING TUPPLE LIST OUTPUT{keys_and_values_tuples_list}")
word_max_key=max(keys_and_values_tuples_list)[0]
max_val = max(keys_and_values_tuples_list)[1]
print("This sorts all words within the file by alphabetical order and tells the number of occurrences ")
for alphabetized_words, frequency_of_word in sorted(frequency_of_words_dict.items()): # sorted() sorts all the words alphabetically
# for loop REPORTS DATA AS WORD : NUM_OCCURENCES
assert isinstance(alphabetized_words, object) #just in case
print()
print(f"{alphabetized_words} : {frequency_of_word}")
#print()
#td= max(frequency_of_words_dict, key=lambda key: frequency_of_words_dict[key])
#if j == td:
#print(f" the word '{i}'occurs the most times with {j} occurences")
break
print()
print("#########################################################################################################")
print("PROGRAM COMPLETE")
print(f"the length of words in entry is : {len(work_on_this_string_built_from_loop.split() )}")
print(f"but the total number of unique words in the entry is {len(frequency_of_words_dict)}")
print()
print("here is the list of every number and at what location it occurs")
for index, word in enumerate(capitalized_array) : print(f"WORD: '{word}' INDEX : '{index}'")
most_frequent_words=[key for m in [max(frequency_of_words_dict.values())] for key, val in frequency_of_words_dict.items() if val == m]
print(f"The word(s) {most_frequent_words} occurs the most with { max(frequency_of_words_dict.values()) } occurrences.")
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T04:34:30.607",
"Id": "469454",
"Score": "2",
"body": "Welcome to CodeReview@SE. If you consider yourself a beginner in coding Python, please tag your question [tag:beginner]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T04:38:49.897",
"Id": "469455",
"Score": "2",
"body": "If this question is *seriously* about processing PDF, tag [tag:pdf]. I did not see code to interpret [PDF/ISO 32000-1](https://en.m.wikipedia.org/wiki/PDF) - contents is *filtered* / *compressed* more often than not. There are tools like [PyPDF2](https://pypi.org/project/PyPDF2/)."
}
] | [
{
"body": "<h1>Comments and whitespace</h1>\n\n<p>Out of the 174 lines in your program, only 50 are lines of code (that list that's excessively spaced out is only counted as one). I would definitely think about what comments are needed in your program, i.e comments that explain why you did something should stay, and code that's just been commented out because it's not needed should be removed. Trim your whitespace too. While separating chunks of code can be helpful, you're overdoing it a little.</p>\n\n<h1>Operator Spacing</h1>\n\n<p>There should be a space before and after an operator in your program. Have a look:</p>\n\n<pre><code>name=input(\"Name: \") # WRONG\nname = input(\"Name: \") # CORRECT\n</code></pre>\n\n<p>This is a convention outlined in <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a>, the python convention guide.</p>\n\n<h1>Utilizing newlines</h1>\n\n<p>Instead of</p>\n\n<pre><code>print()\nprint(\"testing 123\")\n\nprint(\"testing 123\")\nprint()\n</code></pre>\n\n<p>you can do this</p>\n\n<pre><code>print(\"\\ntesting 123\")\n\nprint(\"testing 123\\n\")\n</code></pre>\n\n<p>Just a little quirk to reduce line count a bit, and reduces clutter since it doesn't require an additional <code>print</code> statement.</p>\n\n<h1>Chain function calls</h1>\n\n<p>Instead of</p>\n\n<pre><code>multi_lined_input = input(\"\\n\")\nmulti_lined_input=multi_lined_input.lower()\nmulti_lined_input=multi_lined_input.replace('-', ' ')\n</code></pre>\n\n<p>you should chain these calls:</p>\n\n<pre><code>multi_lined_input = input(\"\\n\").lower().replace('-', ' ')\n</code></pre>\n\n<p>Reduces line count and is still pretty clear what's going on.</p>\n\n<h1>Dict to list of tuples</h1>\n\n<p>There's a simpler way of converting a dict to a list of tuples. Casting the items of a dict to a list automatically does it for you. Have a look:</p>\n\n<pre><code>keys_and_values_tuples_list = list(frequency_of_words_dict.items())\n</code></pre>\n\n<h1>Bug removing punctuation</h1>\n\n<p>When I enter <code>\"Linny\"</code>, I expect to see <code>Linny</code> with a frequency of one. Instead I see <code>\"Linny</code> with a frequency of one. This is because of the logic in your list comprehension. If it sees punctuation at the end, it will remove it and move onto the next word, instead of checking the beginning as well. The next line also only checks the end of the string. You can clean up this logic by utilizing some built in string methods, <code>translate</code> and <code>maketrans</code>. Have a look:</p>\n\n<pre><code>get_rid_of_punctuation_marks = [item.translate(str.maketrans('', '', string.punctuation)) for item in raw_word_list]\n</code></pre>\n\n<p>This removes all the punctuation by passing <code>string.punctuation</code> as a parameter to the <code>translate</code> function. This makes the next line with <code>remove_consecutive_trailing_punctuation</code> irrelevant. Then you can just use <code>get_rid_of_punctuation_marks</code> in your list comprehension when capitalizing the words.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T03:11:38.457",
"Id": "239342",
"ParentId": "239337",
"Score": "2"
}
},
{
"body": "<p>I think you need to work on naming things (I know, I know, <a href=\"https://deviq.com/naming-things/\" rel=\"nofollow noreferrer\">naming things is hard</a>). I would recommend to try to find slightly shorter names, and also names that do not contain the type of the variable. Usually it is enough to know if a variable contains one or multiple of something. It is fine to re-use a variable name if you just transform the element(s) it contains.</p>\n\n<p>Therefore I would use the following names:</p>\n\n<pre><code>Current Suggestion\n#############################################################\npunctuate punctuation\niteratory_count i\nmulti_lined_input multiline_input\nwork_on_this_string_built_from_loop user_input\nraw_word_list words\nget_rid_of_punctuation_marks words\nremove_consecutive_trailing_punctuation words\ncapitalized_array words\nfrequency_of_words_dict word_frequencies\nalphabetized_words word\nfrequency_of_word frequency\n</code></pre>\n\n<p>Names like <code>remove_punctuation</code> are not bad names. They are just not good names for variables. If you had a function named like that it would be perfectly fine and obvious what it does. And having a function like that might not be a bad idea as well.</p>\n\n<p>In addition I would also like to encourage you to use whitespace sparingly (as recommended by <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>) and to remove no longer needed code (at least before sharing your code with others).</p>\n\n<p>Here's how your code would look with these suggestions:</p>\n\n<pre><code># text from websites use different quote marks than Pycharm so they where not registered\n# ...but here are all the annoying punctuation marks\n# that took forever to figure out how to decipher them in syntax and then get rid of them\n\npunctuation = ['\\\"', ',', '\\\"', \"\\'\", '.', \":\", \";\", \"!\", \"?\" , \"\\'\", \"\\'\", \"'\" ,\n \"(\", \")\", \"{\", \"}\" , \"[\" , \"]\" , '“', '”', \"'\", \"’\", '‘', '.', '#']\nprint(punctuation)\npunctuation = \"\".join(punctuation)\n\nprint(\"Enter/Paste your multi-line input / paragraph of text. Hit Ctrl + D to run it \")\nprint(\"DO NOT PRESS ENTER OR CTRL+V AFTER THE FIRST TIME YOU PASTED IN AND RUN YOUR TEXT(UNLESS PASTED TEXT IS A SINGLE LINE WITH NO BREAKS \")\nprint(\"INSTEAD HIT CTRL + D TO RUN IT AFTER TEXT IS INPUTTED WHEN TERMINAL HAS STOPPED RUNNING AND THE INPUT '|' IS STILL AND FLASHING\")\n\nuser_input = []\nwhile True:\n print()\n try:\n multiline_input = input(\"\\n\").lower().replace('-', ' ').strip()\n if not multiline_input:\n continue\n user_input.append(multiline_input)\n except EOFError as error :\n print(\"FINISHED INPUT\\n\")\n break\n\nuser_input = \" \".join(user_input)\nwords = [word.strip(punctuation).capitalize() for word in user_input.split()]\nword_frequencies = dict(Counter(words))\nword_max_key, max_val = max(word_frequencies.items()) # unused\n\nprint(\"This sorts all words within the file by alphabetical order and tells the number of occurrences \")\nfor word, frequency in sorted(word_frequencies.items()):\n print(f\"\\n{word} : {frequency}\")\n\nprint(\"#########################################################################################################\")\nprint(\"PROGRAM COMPLETE\")\n\nprint(f\"the length of words in entry is : {len(words)}\")\nprint(f\"but the total number of unique words in the entry is {len(word_frequencies)}\")\nprint(\"\\nhere is the list of every number and at what location it occurs\")\nfor index, word in enumerate(words):\n print(f\"WORD: '{word}' INDEX : '{index}'\")\n\nm = max(word_frequencies.values())\nmost_frequent_words = [key for key, val in word_frequencies.items() if val == m]\nprint(f\"The word(s) {most_frequent_words} occurs the most with {m} occurrences.\")\n</code></pre>\n\n<p>Note that I also moved the splitting into words out of the loop so that you only need to do it once and accumulated the user input in a list instead of doing repeated string addition, which is costly. Your whole cleanup code fits into one list comprehension by using <code>str.strip</code> (note that <code>\"abcba\".strip(\"ab\") == \"c\"</code>). I also used tuple assignment instead of doing <code>max(...)</code> twice to get both the key and value of the maximum and cleaned up the code in the bottom.</p>\n\n<hr>\n\n<p><strong>If <code>assert isinstance(alphabetized_words, object)</code> ever fails, you will have done something horribly, horribly wrong</strong>. Everything (except for keywords) is an object in Python, so this has to be always true. It is true even for functions (also built-ins), classes (not only instances, but also the classes themselves, including built-ins) exceptions, basic types (like integers and lists) singletons (like <code>None</code>).</p>\n\n<p>The only way I can think of for this to be false is if you unnecessarily implemented your own <code>isinstance</code>, shadowing the built-in, which has some bug.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T06:43:03.173",
"Id": "469510",
"Score": "0",
"body": "In your naming suggestions, you name half the variables 'word'. While scalable, isn't that going to make debugging more complicated?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T07:15:02.787",
"Id": "469512",
"Score": "0",
"body": "@Mast: Not really, IMO. 1. any error message will contain the linenumber, and the part to the right of the `=`. 2. If the code becomes too complicated for that (i.e. more than one line per transformation) it should be encapsulated in a function anyway, which makes it again obvious where the error is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T07:16:19.423",
"Id": "469513",
"Score": "0",
"body": "@Mast: Also note what I added below the names, that some of the names the OP chose are not bad names, just that they would be better names for functions that do the transformation instead of the result of the transformation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T07:18:10.063",
"Id": "469514",
"Score": "0",
"body": "Fair enough, thanks."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T18:43:10.647",
"Id": "239374",
"ParentId": "239337",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-23T23:56:35.263",
"Id": "239337",
"Score": "3",
"Tags": [
"python"
],
"Title": "List the number of times a word occurs in a website article or PDF"
} | 239337 |
<p>Hi I recently wrote some code in python that does the following:</p>
<p>1.) Pulls stock closing data from yahoo finance for x number of stock</p>
<p>2.) finds all possible combinations of x stocks in groups of y size (so all combinations of 13 stocks in groups of 10)</p>
<p>3.) applies some calculations to each of these groups</p>
<p>4.) returns the optimal weights of each group. (weights means what percentage of money is to be placed in each stock and must = 100%)</p>
<p>5.) Creates a Dataframe with all the optimal portfolios (groups) weights</p>
<p>My code works however it is slow, each loop on average on my PC takes 2.45 seconds. This is fine for a small number of permutations such as the example above however when the number of selections increase the number of possibilities also increases significantly. For example a list of 30 stocks taken in unique groups of 15 has 155117520 possibilities which would take my code over 12 years..... Just looking for any suggestions or directions to improve the execution speed of my code. I am relatively new to coding but am aware python is slower than other languages at this task however I currently only know some python basics. I use a few for loops in this code which I know are slow and am exploring using .apply() instead, if you could help in any way it would be appreciated. </p>
<pre><code>import pandas as pd
from pandas_datareader import data
import datetime
import numpy as np
import random
import itertools
import requests
import time
time1 = time.time()
start = datetime.datetime(2015, 1, 1)
end = datetime.datetime(2019, 12, 31)
list2 = []
num = []
#################SP Download#######################
sptickers1 = ['MMM', 'ABT', 'ABBV', 'ABMD', 'ACN', 'ATVI', 'ADBE', 'AMD', 'AAP', 'AES', 'AFL', 'A', 'APD', 'AKAM', 'ALK', 'ALB', 'ARE', 'ALXN', 'ALGN', 'ALLE', 'AGN', 'ADS', 'LNT', 'ALL', 'GOOGL', 'GOOG', 'MO', 'AMZN', 'AMCR', 'AEE', 'AAL', 'AEP', 'AXP', 'AIG', 'T', 'AMT', 'AWK', 'AMP', 'ABC', 'AME', 'AMGN', 'APH', 'ADI', 'ANSS', 'ANTM', 'AON', 'AOS', 'APA', 'AIV', 'AAPL', 'AMAT', 'APTV', 'ADM', 'ARNC', 'ANET', 'AJG', 'AIZ', 'ATO', 'ADSK', 'ADP', 'AZO', 'AVB', 'AVY', 'BKR', 'BLL', 'BAC', 'BK', 'BAX', 'BDX', 'BBY', 'BIIB', 'BLK', 'BA', 'BKNG', 'BWA', 'BXP', 'BSX', 'BMY', 'AVGO', 'BR', 'CHRW', 'COG', 'CDNS', 'CPB', 'COF', 'CPRI', 'CAH', 'KMX', 'CCL', 'CAT', 'CBOE', 'CBRE', 'CDW', 'CE', 'CNC', 'CNP', 'CTL', 'CERN', 'CF', 'SCHW', 'CHTR', 'CVX', 'CMG', 'CB', 'CHD', 'CI', 'CINF', 'CTAS', 'CSCO', 'C', 'CFG', 'CTXS', 'CLX', 'CME', 'CMS', 'KO', 'CTSH', 'CL', 'CMCSA', 'CMA', 'CAG', 'CXO', 'COP', 'ED', 'STZ', 'COO', 'CPRT', 'GLW', 'CTVA', 'COST', 'COTY', 'CCI', 'CSX', 'CMI', 'CVS', 'DHI', 'DHR', 'DRI', 'DVA', 'DE', 'DAL', 'XRAY', 'DVN', 'FANG', 'DLR', 'DFS', 'DISCA', 'DISCK', 'DISH', 'DG', 'DLTR', 'D', 'DOV', 'DOW', 'DTE', 'DUK', 'DRE', 'DD', 'DXC', 'ETFC', 'EMN', 'ETN', 'EBAY', 'ECL', 'EIX', 'EW', 'EA', 'EMR', 'ETR', 'EOG', 'EFX', 'EQIX', 'EQR', 'ESS', 'EL', 'EVRG', 'ES', 'RE', 'EXC', 'EXPE', 'EXPD', 'EXR', 'XOM', 'FFIV', 'FB', 'FAST', 'FRT', 'FDX', 'FIS', 'FITB', 'FE', 'FRC', 'FISV', 'FLT', 'FLIR', 'FLS', 'FMC', 'F', 'FTNT', 'FTV', 'FBHS', 'FOXA', 'FOX', 'BEN', 'FCX', 'GPS', 'GRMN', 'IT', 'GD', 'GE', 'GIS', 'GM', 'GPC', 'GILD', 'GL', 'GPN', 'GS', 'GWW', 'HRB', 'HAL', 'HBI', 'HOG', 'HIG', 'HAS', 'HCA', 'PEAK', 'HP', 'HSIC', 'HSY', 'HES', 'HPE', 'HLT', 'HFC', 'HOLX', 'HD', 'HON', 'HRL', 'HST', 'HPQ', 'HUM', 'HBAN', 'HII', 'IEX', 'IDXX', 'INFO', 'ITW', 'ILMN', 'INCY', 'IR', 'INTC', 'ICE', 'IBM', 'IP', 'IPG', 'IFF', 'INTU', 'ISRG', 'IVZ', 'IPGP', 'IQV', 'IRM', 'JKHY', 'J', 'JBHT', 'SJM', 'JNJ', 'JCI', 'JPM', 'JNPR', 'KSU', 'K', 'KEY', 'KEYS', 'KMB', 'KIM', 'KMI', 'KLAC', 'KSS', 'KHC', 'KR', 'LB', 'LHX', 'LH', 'LRCX', 'LW', 'LVS', 'LEG', 'LDOS', 'LEN', 'LLY', 'LNC', 'LIN', 'LYV', 'LKQ', 'LMT', 'L', 'LOW', 'LYB', 'MTB', 'M', 'MRO', 'MPC', 'MKTX', 'MAR', 'MMC', 'MLM', 'MAS', 'MA', 'MKC', 'MXIM', 'MCD', 'MCK', 'MDT', 'MRK', 'MET', 'MTD', 'MGM', 'MCHP', 'MU', 'MSFT', 'MAA', 'MHK', 'TAP', 'MDLZ', 'MNST', 'MCO', 'MS', 'MOS', 'MSI', 'MSCI', 'MYL', 'NDAQ', 'NOV', 'NTAP', 'NFLX', 'NWL', 'NEM', 'NWSA', 'NWS', 'NEE', 'NLSN', 'NKE', 'NI', 'NBL', 'JWN', 'NSC', 'NTRS', 'NOC', 'NLOK', 'NCLH', 'NRG', 'NUE', 'NVDA', 'NVR', 'ORLY', 'OXY', 'ODFL', 'OMC', 'OKE', 'ORCL', 'PCAR', 'PKG', 'PH', 'PAYX', 'PAYC', 'PYPL', 'PNR', 'PBCT', 'PEP', 'PKI', 'PRGO', 'PFE', 'PM', 'PSX', 'PNW', 'PXD', 'PNC', 'PPG', 'PPL', 'PFG', 'PG', 'PGR', 'PLD', 'PRU', 'PEG', 'PSA', 'PHM', 'PVH', 'QRVO', 'PWR', 'QCOM', 'DGX', 'RL', 'RJF', 'RTN', 'O', 'REG', 'REGN', 'RF', 'RSG', 'RMD', 'RHI', 'ROK', 'ROL', 'ROP', 'ROST', 'RCL', 'SPGI', 'CRM', 'SBAC', 'SLB', 'STX', 'SEE', 'SRE', 'NOW', 'SHW', 'SPG', 'SWKS', 'SLG', 'SNA', 'SO', 'LUV', 'SWK', 'SBUX', 'STT', 'STE', 'SYK', 'SIVB', 'SYF', 'SNPS', 'SYY', 'TMUS', 'TROW', 'TTWO', 'TPR', 'TGT', 'TEL', 'FTI', 'TFX', 'TXN', 'TXT', 'TMO', 'TIF', 'TJX', 'TSCO', 'TT', 'TDG', 'TRV', 'TFC', 'TWTR', 'TSN', 'UDR', 'ULTA', 'USB', 'UAA', 'UA', 'UNP', 'UAL', 'UNH', 'UPS', 'URI', 'UTX', 'UHS', 'UNM', 'VFC', 'VLO', 'VAR', 'VTR', 'VRSN', 'VRSK', 'VZ', 'VRTX', 'V', 'VNO', 'VMC', 'WRB', 'WAB', 'WMT', 'WBA', 'DIS', 'WM', 'WAT', 'WEC', 'WFC', 'WELL', 'WDC', 'WU', 'WRK', 'WY', 'WHR', 'WMB', 'WLTW', 'WYNN', 'XEL', 'XRX', 'XLNX', 'XYL', 'YUM', 'ZBRA', 'ZBH', 'ZION', 'ZTS']
dstocks = sptickers1[0:13]
df = data.DataReader(dstocks, 'yahoo', start, end)['Close']
combinations = list(itertools.combinations(dstocks, 10))
combinationslist = []
for i in combinations:
combinationslist.append(list(i))
for i in combinationslist:
try:
start_time = time.time()
df1 = df[i].copy()
dfpct = df1.pct_change().apply(lambda x: np.log(x+1))
sdd = dfpct.std()
sda = sdd.apply(lambda x: x*np.sqrt(250))
var = dfpct.var()
cov_matrix = dfpct.cov()
dfer = df1.resample('Y').last().pct_change()
er = dfer.mean()
p_ret = []
p_vol = []
p_weights = []
num_p = 1000
for portfolio in range(num_p):
n = len(i)
weights = [random.random() for e in range(n)]
sum_weights = sum(weights)
weights = [w/sum_weights for w in weights]
p_weights.append(weights)
returns = np.dot(weights, er)
p_ret.append(returns)
p_var = cov_matrix.mul(weights, axis = 0).mul(weights, axis=1).sum().sum()
p_sd = np.sqrt(p_var)
p_sda = p_sd*np.sqrt(250)
p_vol.append(p_sda)
data = {'Returns':p_ret, 'Volatility':p_vol}
for counter, symbol in enumerate(dfpct.columns.tolist()):
data[symbol+ ' Weight'] = [w[counter] for w in p_weights]
portfolios = pd.DataFrame(data)
rf = 0.02
optimaln = ((portfolios['Returns']-rf)/portfolios['Volatility']).idxmax()
optimal = portfolios.loc[optimaln]
optimal1 = pd.DataFrame(optimal).transpose()
optimal1I = optimal1.index.tolist()
dictoptimal = portfolios.loc[optimal1I].to_dict(orient='records')
list2.append(dictoptimal)
end_time = time.time()
print("total time taken this loop: ", end_time - start_time)
except:
print('Didnt work')
num.append('didnt work')
continue
print(len(num))
fin = pd.DataFrame.from_dict(list2)
time2 = time.time()
print('program took ' + str(time2-time1) + ' Seconds')
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T03:31:58.487",
"Id": "469449",
"Score": "0",
"body": "Not enough for review but `combinations_list = [list(i) for i in combinations]`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T04:20:00.517",
"Id": "469451",
"Score": "0",
"body": "Welcome to CodeReview@SE."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T04:21:14.470",
"Id": "469452",
"Score": "0",
"body": "Your code uses *a lot* of vertical space. *I hold* this to impair readability."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T06:31:44.820",
"Id": "469458",
"Score": "1",
"body": "Noted, I'll take that into consideration in the future."
}
] | [
{
"body": "<p>Checking over 100 million possibilities is going to be slow in any language. That being said, here are some ways to speed up the code a bit.</p>\n\n<ul>\n<li><p>There is no need to actually get the list of all combinations when you only need them one at a time. Especially when you have 100 million of them this will be very big in memory. Instead just use it as the generator <code>itertools.combinations</code> returns, you can simply iterate over it.</p></li>\n<li><p>There is no need to copy the dataframe, you don't modify it anyway.</p></li>\n<li><p>The most important thing is using vectorized functions wherever possible. <code>numpy</code> functions by default work on arrays. So instead of </p>\n\n<pre><code>dfpct = df1.pct_change().apply(lambda x: np.log(x+1))\n</code></pre>\n\n<p>use</p>\n\n<pre><code>dfpct = np.log1p(df1.pct_change())\n</code></pre>\n\n<p>The <a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.log1p.html\" rel=\"nofollow noreferrer\"><code>numpy.log1p</code></a> function is the same as <code>numpy.log(1 + x)</code>, but more accurate if <code>x</code> is close to zero.</p>\n\n<p>Similarly, for the random weights:</p>\n\n<pre><code>weights = np.random.rand(n)\nweights /= weights.sum()\n</code></pre></li>\n<li><p><code>numpy.sum</code> by default sums along all axis, so doing two <code>sum</code> in a row without specifying an axis is meaningless.</p></li>\n<li><p>Don't use a bare <code>except</code> clause. This includes e.g. the user pressing <kbd>Ctrl</kbd>+<kbd>C</kbd> to abort the program (a very real possibility if your program is going to run 12 years), meaning they have to press that 150 million times. At least use <code>except Exception</code> and then you may as well print the error at least, so you know what is going wrong, by doing <code>except Exception as e</code>. You should also constrain the range of the <code>try..except</code> block as far as possible, e.g. only around the lines you know can cause problems. This is so you don't ignore unexpected errors.</p></li>\n<li><p>Using <code>'Didnt work'</code> as a special value for when something went wrong is maybe not the best idea. Consider using <code>None</code> or <code>np.nan</code> instead.</p></li>\n<li><p>Python has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>. It recommends using <code>lower_case</code> for variables and functions and not to use unnecessary whitespace (of which you have a lot).</p></li>\n</ul>\n\n<p>With these mostly fixed, your code would look like this:</p>\n\n\n\n<pre><code>import pandas as pd\nfrom pandas_datareader import data\nimport datetime\nimport numpy as np\nimport random\nimport itertools\nimport requests\nimport time\n\ntime1 = time.time()\nstart = datetime.datetime(2015, 1, 1)\nend = datetime.datetime(2019, 12, 31)\nlist2 = []\nnum = []\n\n#################SP Download#######################\n\nsptickers1 = ['MMM', 'ABT', 'ABBV', 'ABMD', 'ACN', 'ATVI', 'ADBE', 'AMD', 'AAP', 'AES', 'AFL', 'A', 'APD', ...]\ndstocks = sptickers1[:13]\ndf = data.DataReader(dstocks, 'yahoo', start, end)['Close']\ncombinations = itertools.combinations(dstocks, 10)\n\nfor i in combinations:\n try:\n start_time = time.time()\n df1 = df[list(i)]\n dfpct = np.log1p(df1.pct_change())\n sdd = dfpct.std()\n sda = sdd * np.sqrt(250)\n var = dfpct.var()\n cov_matrix = dfpct.cov()\n dfer = df1.resample('Y').last().pct_change()\n er = dfer.mean()\n\n p_ret = []\n p_vol = []\n p_weights = []\n num_p = 1000\n for portfolio in range(num_p):\n n = len(i)\n weights = np.random.rand(n)\n weights /= weights.sum()\n p_weights.append(weights)\n returns = np.dot(weights, er)\n p_ret.append(returns)\n p_var = cov_matrix.mul(weights, axis=0).mul(weights, axis=1).sum()\n p_sda = np.sqrt(p_var)*np.sqrt(250)\n p_vol.append(p_sda)\n\n data = {'Returns': p_ret, 'Volatility': p_vol}\n for counter, symbol in enumerate(dfpct.columns.tolist()):\n data[symbol+ ' Weight'] = [w[counter] for w in p_weights]\n\n portfolios = pd.DataFrame(data)\n rf = 0.02\n optimaln = ((portfolios['Returns']-rf)/portfolios['Volatility']).idxmax()\n optimal = portfolios.loc[optimaln].T \n optimal1I = optimal.index.tolist()\n dictoptimal = portfolios.loc[optimal1I].to_dict(orient='records')\n list2.append(dictoptimal)\n\n end_time = time.time()\n print(\"total time taken this loop: \", end_time - start_time)\n except Exception as e:\n print('Didnt work', e)\n num.append('didnt work')\n continue\n\nprint(len(num))\nfin = pd.DataFrame.from_dict(list2)\ntime2 = time.time()\nprint('program took ' + str(time2-time1) + ' Seconds')\n</code></pre>\n\n<p>This can probably be improved further, but at this point it is hard to follow what exactly your code does. In order to improve this, put independent things into their own function, which allows you to give them a clear name and <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstring</a>, explaining what the function does. You should probably have at least a <code>optimal_portfolio</code> and a <code>random_weights</code> function.</p>\n\n<p>Together with this you should also try to come up with more meaningful names than <code>sdd</code> and <code>sda</code> or <code>optimal</code>, <code>optimal1</code>, <code>optimal1I</code> and <code>dictoptimal</code>. <a href=\"https://martinfowler.com/bliki/TwoHardThings.html\" rel=\"nofollow noreferrer\">Naming things is hard, though</a>.</p>\n\n<p>Once you have done that, you should <a href=\"https://docs.python.org/3/library/profile.html\" rel=\"nofollow noreferrer\">profile your code</a> to determine which function takes the longest to identify where you need to focus your attention next. The easiest way to do that is to run your script as <code>python -m cProfile -s cumtime script.py</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T03:26:20.793",
"Id": "469590",
"Score": "0",
"body": "Hi thank you for your help, just a few things: you removed an extra .sum from p_var which led to an error. Also when I run the code optimal1I = optimal.index.tolist() is no longer returning the index instead retruning a list of the headers: ``` \n ['Returns', 'Volatility', 'MMM Weight', 'ABT Weight', 'ABBV Weight', 'ABMD Weight', 'ACN Weight', 'ATVI Weight', 'ADBE Weight', 'AMD Weight', 'AAP Weight', 'AES Weight'] as a result: dictoptimal = portfolios.loc[optimal1I].to_dict(orient='records') is not working"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T03:33:28.243",
"Id": "469591",
"Score": "0",
"body": "apologies for the format of my comment........."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T08:05:02.793",
"Id": "469603",
"Score": "0",
"body": "@JordanCodes: Ah yes, I had forgotten that it is a `pandas.DataFrame`, which sums each column on the first one and then each row on the second. What I said was only true for `numpy.array`. The latter I don't quite understand, you also have a `transpose()` in your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T11:22:53.697",
"Id": "469614",
"Score": "1",
"body": "Its all good I got it to work. Thank-you for your help! the transpose was for further down in my code but turned out to be useless so I dropped it anyway. The reason it wasn't working was the data frame came back a little different I think than my original so the .to_dict(orient= 'records') was no longer needed and returned an error on my end, instead .to_dict() worked just fine."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T08:17:04.580",
"Id": "239347",
"ParentId": "239338",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "239347",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T00:46:08.367",
"Id": "239338",
"Score": "2",
"Tags": [
"python",
"performance",
"python-3.x",
"numpy",
"pandas"
],
"Title": "Building optimal portfolios for all combinations of stocks"
} | 239338 |
<p>The goal of this code is to <em>remove subnets from the list that are redundant</em> (included in the larger ones)
It is <strong>VERY</strong> slow. Wondering how it can be sped up.</p>
<p>At present, I’m not looking to optimize the “CheckSubnet()” function, which isn’t my code... It MAY be slow (or not) but I’m hoping that a critical analysis of the code that I HAVE presented can expose something obvious that I might have missed.</p>
<p>CheckSubnet Function taken from here: <a href="http://www.gi-architects.co.uk/2016/02/powershell-check-if-ip-or-subnet-matchesfits/" rel="nofollow noreferrer">http://www.gi-architects.co.uk/2016/02/powershell-check-if-ip-or-subnet-matchesfits/</a></p>
<p>The function takes two CIDR notated subnets and returns an object that has two parts:</p>
<ol>
<li><code>bool</code> <code>Condition</code> which is <code>TRUE</code> if one of the subnets contains the other</li>
<li><code>string</code> SomeotherMemeberThatIDontCareAbout</li>
</ol>
<p>My code is as follows:</p>
<pre><code>if ((Get-Module az.network) -eq $null)
{
Import-Module az.network -Prefix AN
}
$Ranges = (Get-ANAzNetworkServiceTag -Location CentralUS).Values.Properties.AddressPrefixes | Sort-Object -Unique
#
#I think you need to be logged into your Azure Subscription for this to gather the results
#$Ranges returns over 8100 unique subnets
#
[System.Collections.ArrayList]$15 = $Ranges | ?{$_ -like "*/15"}
[System.Collections.ArrayList]$16 = $Ranges | ?{$_ -like "*/16"}
[System.Collections.ArrayList]$17 = $Ranges | ?{$_ -like "*/17"}
[System.Collections.ArrayList]$18 = $Ranges | ?{$_ -like "*/18"}
[System.Collections.ArrayList]$19 = $Ranges | ?{$_ -like "*/19"}
[System.Collections.ArrayList]$20 = $Ranges | ?{$_ -like "*/20"}
[System.Collections.ArrayList]$21 = $Ranges | ?{$_ -like "*/21"}
[System.Collections.ArrayList]$22 = $Ranges | ?{$_ -like "*/22"}
[System.Collections.ArrayList]$23 = $Ranges | ?{$_ -like "*/23"}
[System.Collections.ArrayList]$24 = $Ranges | ?{$_ -like "*/24"}
[System.Collections.ArrayList]$25 = $Ranges | ?{$_ -like "*/25"}
[System.Collections.ArrayList]$26 = $Ranges | ?{$_ -like "*/26"}
[System.Collections.ArrayList]$27 = $Ranges | ?{$_ -like "*/27"}
[System.Collections.ArrayList]$28 = $Ranges | ?{$_ -like "*/28"}
[System.Collections.ArrayList]$29 = $Ranges | ?{$_ -like "*/29"}
[System.Collections.ArrayList]$30 = $Ranges | ?{$_ -like "*/30"}
[System.Collections.ArrayList]$31 = $Ranges | ?{$_ -like "*/31"}
[System.Collections.ArrayList]$32 = $Ranges | ?{$_ -like "*/32"}
[System.Collections.ArrayList]$arrays= $15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$30,$31,$32
for ($j =0;$j -le $arrays.Count-1;$j++)
{
[System.Collections.ArrayList]$target = $arrays[$j+1]
$target.Count
$counter =1
[System.Collections.ArrayList]$ArraySubset=$arrays
[System.Collections.ArrayList]$arraySubset.RemoveRange($j+1,$arrays.Count-($j+1))
foreach ($Big in $arraySubset)
{
$iteration=0
$thecount=$target.Count
Write-host "Array number: $counter Remaining: $thecount"
foreach ($largecidr in $Big)
{
for($i=$target.count-1;$i -ge 0;$i--)
{
$iteration++
$checkval=CheckSubnet $largecidr $target[$i]
if ($checkval.Condition -eq $true)
{
Write-Host "Removing $($target[$i])"
$target[$i]
$target.RemoveAt($i)
}
if ($iteration % 100 -eq 0)
{
Write-Host "Iteration $iteration"
}
}
}
$counter++
}
[System.Collections.ArrayList]$arrays= $15,$16,$17,$18,$19,$20,$21,$22,$23,$24,$25,$26,$27,$28,$29,$30,$31,$32
}
$target.Count
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T04:29:51.807",
"Id": "469453",
"Score": "0",
"body": "Welcome to CodeReview@SE. Please edit into your question why to assume `CheckSubnet()`, called in the innermost loop, doesn't significantly contribute to the lamented performance. Or present its code, too. Have a look at [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T05:11:00.460",
"Id": "469457",
"Score": "0",
"body": "@greybeard thanks for fixing up some formatting. I don’t want to analyze CheckSubnet() (yet) as it isn’t my code - as referenced by my link to its location on the ‘Net. Hoping that there just might be a better approach to working through the subsets to do the comparison."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T15:33:22.050",
"Id": "469876",
"Score": "1",
"body": "The posted code doesn't have any obvious problems AFAICT. There's one thing missing though: measurements. Any performance analysis and improvement should start with measurements, otherwise it'd be a random guesswork. Look for examples of measuring execution time in powershell code, it's a rather tedious process when you have to isolate timing of sections inside loops."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T15:51:45.727",
"Id": "469881",
"Score": "0",
"body": "@wOxxOm thanks for the feedback! Will have a look. The woke thing took over 72 hours to complete, when I DID let it finally run to completion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T15:56:01.357",
"Id": "469882",
"Score": "0",
"body": "You can show the currently accumulated measurements every 10 seconds, for example."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T01:13:20.780",
"Id": "239339",
"Score": "2",
"Tags": [
"performance",
"powershell",
"ip-address"
],
"Title": "I am gathering all the Azure subnets for Central US and trying to filter out the smaller subnets that are part of the larger... Very slow"
} | 239339 |
<p>I have tried to write a simple <code>3 x 3</code> tic tac toe program. Please I need a code review on this program, whether it is readable, maintainable or not. Judge it as much as you can. </p>
<p>Here is the source code:</p>
<pre><code>#include <iostream>
#include <string>
#include <vector>
void draw_board(std::vector<std::string> &board) {
/**
-----------------------
| | | |
| 1 | 2 | 3 |
| | | |
| -------------------- |
| | | |
| 4 | 5 | 6 |
| | | |
| -------------------- |
| | | |
| 7 | 8 | 9 |
| | | |
-----------------------
**/
for (auto row : board) {
for (auto col : row) {
std::cout << col;
}
std::cout << '\n';
}
}
void toggle_player(char &current) {
if (current == 'X') current = 'O';
else current = 'X';
}
void update_board(char &current, std::vector<std::string> &board, int &choice,
std::vector<std::pair<int, int>> &choice_position, std::vector<std::string> &plays) {
int row = choice_position[choice].first;
int col = choice_position[choice].second;
board[row][col] = current;
switch (choice) {
case 1:
plays[0][0] = current;
break;
case 2:
plays[0][1] = current;
break;
case 3:
plays[0][2] = current;
break;
case 4:
plays[1][0] = current;
break;
case 5:
plays[1][1] = current;
break;
case 6:
plays[1][2] = current;
break;
case 7:
plays[2][0] = current;
break;
case 8:
plays[2][1] = current;
break;
case 9:
plays[2][2] = current;
break;
}
}
bool valid_move(int &choice, std::vector<bool> &taken) {
return 1 <= choice && choice <= 9 && !taken[choice];
}
void handle_input(char &current, std::vector<bool> &taken, std::vector<std::string> &plays
,std::vector<std::pair<int, int>> &choice_position
,std::vector<std::string> &board) {
std::cout << "Enter a number between [1, 9] (inclusive).\n";
std::cout << "It's " << current << " turn\n";
int choice;
std::cin >> choice;
while(!valid_move(choice, taken)) {
std::cout << "Invalid choice\n";
std::cin >> choice;
}
taken[choice] = true;
update_board(current, board, choice, choice_position, plays);
toggle_player(current);
}
std::string winner(std::vector<std::string> &plays) {
// check rows
std::string winner;
for (int i = 0; i < 3; i++) {
int cnt = 0;
for (int j = 0; j < 3; j++) {
if (plays[i][j] == plays[i][0])
cnt++;
}
if (cnt == 3 && plays[i][0] != '.') {
winner += plays[i][0];
winner += " wins the game.";
return winner;
}
}
// check columns
for (int i = 0; i < 3; i++) {
int cnt = 0;
for (int j = 0; j < 3; j++) {
if (plays[j][i] == plays[0][i])
cnt++;
}
if (cnt == 3 && plays[0][i] != '.') {
winner += plays[0][i];
winner += " wins the game.";
return winner;
}
}
// check diagonals
if (plays[0][0] == plays[1][1] && plays[1][1] == plays[2][2] && plays[1][1] != '.') {
winner += plays[1][1];
winner += " wins the game";
return winner;
}
if (plays[0][2] == plays[1][1] && plays[1][1] == plays[2][0] && plays[1][1] != '.') {
winner += plays[1][1];
winner += " wins the game";
return winner;
}
return "-1"; // no winner
}
void handle_winner(std::vector<std::string> &plays, std::vector<std::string> &board,
std::vector<std::pair<int, int>> &choice_position);
void start_game(std::vector<std::string> &board, std::vector<std::pair<int, int>> &choice_position) {
// initial state of the game
char current = 'X';
std::vector<std::string> plays(3);
plays[0] = plays[1] = plays[2] = "...";
std::vector<bool> taken(10);
board = {" ------------------------", "| | | |", "| 1 | 2 | 3 |",
"| | | |", " ------------------------", "| | | |", "| 4 | 5 | 6 |",
"| | | |", " ------------------------", "| | | |", "| 7 | 8 | 9 |",
"| | | |", " ------------------------"
};
while (true) {
draw_board(board);
handle_input(current, taken, plays, choice_position, board);
handle_winner(plays, board, choice_position);
}
}
void handle_winner(std::vector<std::string> &plays, std::vector<std::string> &board,
std::vector<std::pair<int, int>> &choice_position) {
if (winner(plays) != "-1") {
std::cout << winner(plays);
std::cout << "Do you want to play another game?\n";
std::cout << "Enter 0 to exit, 1 to continue\n";
int choice;
std::cin >> choice;
if (choice == 0)
exit(0);
start_game(board, choice_position);
}
}
int main() {
std::vector<std::string> board{" ------------------------", "| | | |", "| 1 | 2 | 3 |",
"| | | |", " ------------------------", "| | | |", "| 4 | 5 | 6 |",
"| | | |", " ------------------------", "| | | |", "| 7 | 8 | 9 |",
"| | | |", " ------------------------"
};
std::vector<std::pair<int, int>> choice_position(10);
// locations of numbers on the board
choice_position[1] = {2, 4};
choice_position[2] = {2, 12};
choice_position[3] = {2, 20};
choice_position[4] = {6, 4};
choice_position[5] = {6, 12};
choice_position[6] = {6, 20};
choice_position[7] = {10, 4};
choice_position[8] = {10, 12};
choice_position[9] = {10, 20};
start_game(board, choice_position);
return 0;
}
</code></pre>
| [] | [
{
"body": "<p>It has been a long time since I did something in c++ so I probably cannot give any pointers on c++ specific things.</p>\n\n<p>The first thing I notice is the data types you use to encode data. For example, you encode the board as a vector of strings <code>std::vector<std::string> &board</code> which has the entire printable board. Instead of encoding the board in this way you should instead ask what data represents a board. In the case of tic tac toe it is a grid of 3 by 3 with each square encoding information if it is empty, filled by <code>X</code> or filled by <code>O</code>. Printing the board can then be offloaded to the <code>draw_board</code> method. In this way the other methods using the board don't need to know how it is printed/drawn. You can create a struct out of the board (or even a class if you want to go that route)</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>struct Board {\n int pieces[3][3];\n}\n</code></pre>\n\n<p>if you decide to encode the pieces on the board as <code>int</code>s (more on that later). You can even add more information to the <code>Board</code> struct, for example the current player to move, how many moves the game has advanced etc.</p>\n\n<p>The same holds for the player encoding. You now use the <code>char</code>s <code>X</code> and <code>O</code> but you can also create an <code>enum</code> to state a player, for example</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>enum Player { Xs, Os }\n</code></pre>\n\n<p>This prevents you from making errors in the future where for example you typed <code>'P'</code> instead of <code>'O'</code>. Using enums will result in compiler errors if the enum value does not exist.</p>\n\n<p>You can also encode the squares on the board with an enum. Each square has only three possibilities: filled by Xs, filled by Os or empty. So a square can be</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>enum Square { Empty, X, O }\n</code></pre>\n\n<p>or something like that (maybe not <code>X</code> and <code>O</code> as that might give collisions in the future but you get the point).</p>\n\n<p>The goal for these enums and structs is to abstract the data you are working with (instead of working with a vector of strings, work with a Board) and to give a more clear expression of what the code is doing (instead of providing a char, provide a Player). This makes code more readable and also prevents some mental gymnastics in the future.</p>\n\n<p>In your <code>update_board</code> there is a switch case with a whopping 9 cases. Usually when I see a switch case with a lot of cases I try to reduce the amount of cases or even try to get rid of the switch case because all the cases are a lot of copy-pasting and can have possible errors in them. In this case, your <code>choice</code> is a value between 1 and 9. This is fine for the player input, but it might be better to use the values 0 to 8 for this as soon as you got the input from the player. In that way figuring out which item in <code>plays</code> to edit can be easily calculated using the division <code>/</code> and modules operators <code>%</code>:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>plays[choice / 3][choice % 3] = current\n</code></pre>\n\n<p>Of course, it is a very good idea to replace the <code>3</code>s in the above example with some variables like <code>boardHeight</code> and <code>boardWidth</code> so it is clear what the <code>3</code> means and if you would like to create a different version with a 4 by 4 board for example, you wouldn't need to change all the <code>3</code>s in your entire source code with <code>4</code>s.</p>\n\n<p>About the <code>winner</code> function. It might be better to have a method which expects a board and player as input and returns a boolean wether this player won as you only need to check for the player who just moved if if he won. This also makes you checking the different squares easier as you don't need to check the squares with each other but just check if each square matches the players piece/symbol. You can choose to write each case (ie each column, each row and each diagonal) instead of using for loops, in this case there are only 8 cases to check and it makes it a bit more clear, but the major downside is that you cannot change it that easily if you want to modify the game in the future to some other version as I mentioned earlier.</p>\n\n<p>I'll leave it at this, my main takeaway is to use data types and abstractions for the different pieces of information/data you use. You'll see that if you use these abstractions you'll realise that you can write some pieces of code a lot easier. I won't comment you on c++ specific styles, someone else can do that for you ;)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T06:55:00.187",
"Id": "469511",
"Score": "0",
"body": "Raw arrays are generally discouraged in C++. Multidimensional raw arrays are even more frowned upon ... Also, `enum class` is preferable to `enum` (the former doesn't have collision problems). But otherwise, good review!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T07:59:21.850",
"Id": "469515",
"Score": "0",
"body": "Thanks. I guess one should use `std::array` instead of raw arrays?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T08:00:08.173",
"Id": "469516",
"Score": "0",
"body": "Yeah, `std::array<Square, 9>` or `std::array<std::array<Square, 3>, 3>` would be fine."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T10:47:35.840",
"Id": "239350",
"ParentId": "239349",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "239350",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T09:54:50.483",
"Id": "239349",
"Score": "2",
"Tags": [
"c++"
],
"Title": "Tic Tac Toe Console Application in C++"
} | 239349 |
<p>I'm creating a small library of Python utilities, and I'd like feedback on a function which allows iterating over an arbitrary iterable in a sliding-window fashion.</p>
<p>Relevant parts of <code>iteration.py</code>:</p>
<pre><code>import collections
import itertools
def sliding_window_iter(iterable, size):
"""Iterate through iterable using a sliding window of several elements.
Creates an iterable where each element is a tuple of `size`
consecutive elements from `iterable`, advancing by 1 element each
time. For example:
>>> list(sliding_window_iter([1, 2, 3, 4], 2))
[(1, 2), (2, 3), (3, 4)]
"""
iterable = iter(iterable)
window = collections.deque(
itertools.islice(iterable, size-1),
maxlen=size
)
for item in iterable:
window.append(item)
yield tuple(window)
</code></pre>
<p>Relevant parts of the test file <code>iteration_test.py</code>:</p>
<pre><code>import doctest
import unittest
import iteration
from iteration import *
class TestSlidingWindowIter(unittest.TestCase):
def test_good(self):
self.assertSequenceEqual(
list(sliding_window_iter([1, 2, 3, 4], 2)),
[(1, 2), (2, 3), (3, 4)]
)
def test_exact_length(self):
self.assertSequenceEqual(
list(sliding_window_iter(["c", "b", "a"], 3)),
[("c", "b", "a")]
)
def test_short(self):
self.assertSequenceEqual(
list(sliding_window_iter([1, 2], 3)),
[]
)
def test_size_one(self):
self.assertSequenceEqual(
list(sliding_window_iter([1, 2, 3, 4], 1)),
[(1,), (2,), (3,), (4,)]
)
def test_bad_size(self):
with self.assertRaises(ValueError):
list(sliding_window_iter([1, 2], 0))
def run():
if not doctest.testmod(iteration)[0]:
print("doctest: OK")
unittest.main()
if __name__ == "__main__":
run()
</code></pre>
<p>I'm primarily looking for feedback in these areas:</p>
<ul>
<li>Is the code Pythonic? I'm primarily a C++ developer, so Python idioms don't come naturally to me; that's one thing I'm constantly trying to improve.</li>
<li>Are there any potential performance problems?</li>
<li>Am I reinventing a wheel and something like this already exists?</li>
</ul>
<p>I'll welcome any other feedback too, of course.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T21:21:48.773",
"Id": "469503",
"Score": "1",
"body": "As for the last question, of course you are. See _rolling_ or _more-itertools_ on PyPI."
}
] | [
{
"body": "<p>Looks pretty good to me. You are taking advantage of the standard library, are following the relevant style guides and you even have tests, good job! </p>\n\n<p>Personally, I am more in favor of using <code>import from</code>, at least for well-known standard library functions and maybe for utility functions that are used everywhere throughout a project. This way you can more often fit the code on one line easily, making it more readable.</p>\n\n<pre><code>from itertools import islice\nfrom collections import deque\n</code></pre>\n\n<p>One small improvement is that your initial slice can be one larger, the argument behaves just like a range or slice argument and is exclusive of the end (i.e <code>islice(x, 4)</code> takes the first four elements since it is analogous to <code>x[0:4]</code>, <code>x[:4]</code> and <code>range(0, 4)</code>). However, this way you need to deal with the last element in a special way, so YMMV:</p>\n\n<pre><code>def sliding_window_iter(iterable, size):\n \"\"\"...\"\"\"\n iterable = iter(iterable)\n window = deque(islice(iterable, size), maxlen=size)\n for item in iterable:\n yield tuple(window)\n window.append(item)\n if window: \n # needed because if iterable was already empty before the `for`,\n # then the window would be yielded twice.\n yield tuple(window)\n</code></pre>\n\n<p>This also reveals one behavior which you should at least be aware of (which seems to be the case, since you have a test for it). Arguable, <code>sliding_window_iter([1, 2], 3)</code> could yield <code>(1, 2)</code>, i.e. the function maybe shouldn't swallow any data. In any case, the chosen behavior should be documented in the docstring.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T13:00:17.013",
"Id": "469473",
"Score": "1",
"body": "Thanks! I actually consider \"swallow data if too short\" a feature, as my original motivation for this utility was computing differences of adjacent elements etc., and passing a further function a tuple shorter than it expects didn't sound healthy. On the other hand, I can imagine applications where yielding the shorter one would be preferable. Do you think adding an optional parameter like `, allow_smaller=False` would be a good idea?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T13:08:48.047",
"Id": "469474",
"Score": "0",
"body": "@AngewisnolongerproudofSO: Yeah, that might be a good compromise. Whether you add it or not, the (default) behaviour should be documented in the docstring."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T12:34:24.423",
"Id": "239357",
"ParentId": "239352",
"Score": "6"
}
},
{
"body": "<p>There are a couple of ways to do this. I thought using <code>deque()</code> like the original code would be slow, but it is actually faster than most I tried. For reasonable window sizes the code below runs in 2/3 the time. In some tests with large windows (>= 100), it was slower, but not always.</p>\n\n<pre><code>from itertools import islice, tee\n\ndef sliding_window_iter4(iterable, size):\n iterables = tee(iter(iterable), size)\n window = zip(*(islice(t, n, None) for n,t in enumerate(iterables)))\n yield from window\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T23:38:27.050",
"Id": "239386",
"ParentId": "239352",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "239357",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T11:36:19.030",
"Id": "239352",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"iteration"
],
"Title": "Sliding window iteration in Python"
} | 239352 |
<p>I have a Predicate which takes employee object.</p>
<pre><code>Predicate<Employee> getPredicate() {
return emp -> filter(emp);
}
</code></pre>
<p>Now the filter method is very complex, it calls four other methods which returns true/false if all the conditions are true, the <code>predicate</code> will return true.</p>
<pre><code>private boolean filter(Employee employee) {
String employeeJSONString = employeeToString(employee);
return filterBasedOnConsistAge(employeeJSONString) &&
filterBasedOnConsistGender(employeeJSONString) &&
filterBasedOnConsistNationality(employeeJSONString) &&
filterBasedOnConsistHandicap(employeeJSONString);
}
private String employeeToString(Employee employee) {
// converts domainObject to a formatted string, it's a business requirement
}
</code></pre>
<p>There are five-line methods, that are linked using logical AND. But the problem here is, the chaining is looking clean. is there a way to improve this logic?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-03T19:22:40.367",
"Id": "504307",
"Score": "1",
"body": "Your function names make me fear for the worst."
}
] | [
{
"body": "<p>One option would be to do it with <code>Stream</code>s. This is assuming that all different filters are in the same class as the <code>filter</code> method:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private boolean filter(Employee employee) {\n Stream<Predicate<String>> filters = Stream.of(\n this::filterBasedOnConsistAge,\n this::filterBasedOnConsistGender,\n this::filterBasedOnConsistNationality,\n this::filterBasedOnConsistHandicap\n );\n\n String employeeJSONString = employeeToString(employee);\n return filters.allMatch(f -> f.test(employeeJSONString));\n}\n</code></pre>\n\n<p>The <code>allMatch</code> method of <code>Stream</code> returns <code>true</code> if the condition is true for all elements in the <code>Stream</code> and <code>false</code> otherwise.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T14:51:08.763",
"Id": "469487",
"Score": "0",
"body": "This seems like a fairly inefficient way to reimplement the Predicate.and(...) method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T15:52:21.643",
"Id": "469491",
"Score": "0",
"body": "@TorbenPutkonen you are probably right, I forgot about the Predicate.and(...) method"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T12:16:03.297",
"Id": "239354",
"ParentId": "239353",
"Score": "3"
}
},
{
"body": "<p>What especially jumps at me is, that you take your real data object (the Employee), convert it to a <em>string representation</em> and do your checks on the string.</p>\n\n<p>Why? Can't you check your data object?</p>\n\n<p>Apart from that, I don't see a problem with 5 and-conditions. This is clearer to read than some clever stream-through-predicates-and-reduce code. Clear. Simple. Leave it like that.</p>\n\n<p>What I'd recommend is rethinking your naming:</p>\n\n<ul>\n<li><code>getPredicate()</code>: yes, it returns a predicate, we see that from the method signature. But <em>what</em> does this predicate test?</li>\n<li><code>filter()</code>: does some filtering, but according <em>to which criteria</em>?</li>\n</ul>\n\n<p>(Sorry to pepijno, I typed this without seeing your answer... no offense meant ;-))</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T14:09:10.600",
"Id": "469484",
"Score": "1",
"body": "@mtj non taken ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T03:23:30.347",
"Id": "469589",
"Score": "0",
"body": "@GovindaSakhare business requirements should not be dictating your implementation choice. What is the REST service (value-)adding into the `String` representation? Perhaps you should even consider deserializing that representation to some kind of `EnrichedEmployee` class and perform the filtering on that data object. String-based filtering is brittle and can be *easily* undone with data quality issues such as a stray delimiter."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T12:19:37.353",
"Id": "239356",
"ParentId": "239353",
"Score": "11"
}
},
{
"body": "<p>Each one of the <code>filterBasedOnConsist*</code> methods look like they would be individual predicates themselves. So convert each method into a <code>Predicate</code> class and use the default <code>and</code> method to chain them together into a composite predicate:</p>\n\n<pre><code>Predicate<String> employeePredicate =\n new FilterBasedOnConsistAge()\n .and(new FilterBasedOnConsistGender())\n .and(new FilterBasedOnConsistNationality())\n .and(new FilterBasedOnConsistHandicap())\n</code></pre>\n\n<p>Use a more descriptive name than <code>employeePredicate</code>. I have no idea what you are using it for so I just put a bad generic name there.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T14:45:54.783",
"Id": "239366",
"ParentId": "239353",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": "239356",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T11:50:45.517",
"Id": "239353",
"Score": "9",
"Tags": [
"java",
"object-oriented",
"design-patterns"
],
"Title": "Refactoring multiple boolean conditions?"
} | 239353 |
<p>I've got a function which takes a screenshot of a particular window. It's important that the screenshot works whether the window is focused/covered by other windows or not, hence why I've used <code>PrintWindow</code>.</p>
<p>This function takes 45ms to complete, and I was hoping to decrease that. The end goal is to:</p>
<ul>
<li>Take a screenshot of a window based on a <code>handle</code>, which works even if the window is covered by a different window</li>
<li>Finally return a <code>byte[]</code> to be exported as a PNG using NodeJS.</li>
</ul>
<p>screenshot.cs</p>
<pre><code>using System.Runtime.InteropServices;
using System;
using System.Threading.Tasks;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows;
using System.Windows.Forms;
public class main
{
[StructLayout(LayoutKind.Sequential)]
private struct Rect
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
[DllImport("user32.dll")]
private static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rect rect);
[DllImport("user32.dll")]
private static extern IntPtr GetClientRect(IntPtr hWnd, ref Rect rect);
[DllImport("user32.dll")]
private static extern IntPtr ClientToScreen(IntPtr hWnd, ref Point point);
[DllImport("User32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool PrintWindow(IntPtr hwnd, IntPtr hDC, uint nFlags);
public static Bitmap CaptureWindow(IntPtr handle)
{
var rect = new Rect();
GetClientRect(handle, ref rect);
var point = new Point(0,0);
ClientToScreen(handle, ref point);
var bounds = new Rectangle(point.X, point.Y, rect.Right, rect.Bottom);
var result = new Bitmap(bounds.Width, bounds.Height);
using (var graphics = Graphics.FromImage(result))
{
IntPtr dc = graphics.GetHdc();
bool success = PrintWindow(handle, dc, 0);
graphics.ReleaseHdc(dc);
}
return result;
}
public static byte[] ImageToByte(Image img)
{
ImageConverter converter = new ImageConverter();
return (byte[])converter.ConvertTo(img, typeof(byte[]));
}
}
</code></pre>
<p>NodeJS code</p>
<pre><code>const {K, U} = require('win32-api');
const user32 = U.load();
const edge = require('edge-js');
const ss = edge.func(path.join(__dirname, 'screenshot.cs'));
var hWnd = user32.FindWindowExW(0, 0, null, Buffer.from('application\0', 'ucs2'))
ss(hWnd, function (err, r) { fs.writeFileSync("screenshot.png", r); });
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T14:58:52.187",
"Id": "469488",
"Score": "3",
"body": "What is `ImageToByte` for? It doesn't seem to be used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T16:28:02.023",
"Id": "469492",
"Score": "4",
"body": "What is the expected formatting for `byte[]`? The .NET docs are woefully inadequate in describing how it does that particular conversion. A simple `LockBits` and then a buffer copy takes a fraction of the time that `converter.ConvertTo` takes, but the resulting byte array is not formatted at all the same as what's there now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T21:06:09.243",
"Id": "469502",
"Score": "0",
"body": "`ImageToByte( CaptureWindow(hWnd) )` is returned to a `nodejs` application and exported as a `png` file using `fs.writeFileSync`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T01:36:39.780",
"Id": "469508",
"Score": "1",
"body": "Obligatory \"have you used a profiler?\" comment. This will give you various metrics so you can target optimizations.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T08:51:18.520",
"Id": "469521",
"Score": "0",
"body": "Please include all relevant parts of the code. It looks like some of the core essentials are missing, which makes optimizing for performance unnecessarily hard on the reviewers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T08:53:10.003",
"Id": "469522",
"Score": "0",
"body": "The only other code is the nodejs code that simply calls the C# function and outputs to a png file, which is one line. The query on performance only relates to the function shown."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T09:03:16.347",
"Id": "469523",
"Score": "0",
"body": "@Mast I've added the `nodejs` code that calls the C# function and creates the `PNG` and a missing struct declaration"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T10:10:16.413",
"Id": "469528",
"Score": "0",
"body": "This code looks familiar; I seem to recall having done something similar, and it was also slower than I'd initially expected. I think I came to the conclusion that, if I wanted better performance, I'd need to use GPU primitives rather than hoisting the image into the .NET-VM for fully-CPU-bound processing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T10:12:41.840",
"Id": "469529",
"Score": "0",
"body": "You might want to see if this could be on-topic at [SE.ComputerGraphics](https://computergraphics.stackexchange.com/). Folks there might be more familiar with the details of optimizing stuff like this."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T12:53:51.960",
"Id": "239360",
"Score": "3",
"Tags": [
"c#",
"image",
"winapi"
],
"Title": "Taking a screenshot of a particular window"
} | 239360 |
<p>Please download the file and save in home directory and extract it:</p>
<p><a href="https://www.dropbox.com/s/swtw8bk35zr1i6d/analyse.7z?dl=0" rel="nofollow noreferrer">https://www.dropbox.com/s/swtw8bk35zr1i6d/analyse.7z?dl=0</a></p>
<p>I can get some warrants info.</p>
<pre><code>import analyse
df = analyse.warrants.get('0788')
</code></pre>
<p>Now we got <code>0788</code>'s warrants info. It output df with better format:</p>
<pre><code>analyse.tabulate.tabulate(df)
</code></pre>
<p>I want to simply the expression as <code>df.tabulate()</code>. How do I refactor the code in <code>analyse</code> directory?</p>
<p>Show content in tabulate.py:</p>
<pre><code>import pandas as pd
from terminaltables import AsciiTable
def tabulate(df):
rows = len(df)
head = [df.columns.tolist()]
nr = df.values.tolist()
content = head + nr
table = AsciiTable(content)
data_str = table.table.split('\n')
sep_line = data_str[0]
transformed_str = []
for ind in range(0,len(data_str)-1):
if ind < 3 :
transformed_str.append(data_str[ind])
else:
transformed_str.append(data_str[ind])
transformed_str.append(sep_line)
new_str = "\n".join(transformed_str) + '\n' + '\n' + '[ {} records ]'.format(rows-1)
print(new_str)
</code></pre>
<p>I want to refactor <code>analyse.tabulate.tabulate(df)</code> as <code>df.tabulate()</code>. It is the simplest way to use <code>df.tabulate()</code> to get well-formatted dataframe.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T14:37:24.877",
"Id": "469486",
"Score": "1",
"body": "I honestly have no idea what you're asking. You want to simplify your `tabulate` method?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T15:35:32.667",
"Id": "469489",
"Score": "0",
"body": "I want to refactor `analyse.tabulate.tabulate(df)` as `df.tabulate()`. It is simple to use `df.tabulate()` to get well-formatted dataframe."
}
] | [
{
"body": "<p>This if statement</p>\n\n<pre><code> if ind < 3 :\n transformed_str.append(data_str[ind])\n else:\n transformed_str.append(data_str[ind])\n transformed_str.append(sep_line)\n</code></pre>\n\n<p>Can be rewritten as</p>\n\n<pre><code> transformed_str.append(data_str[ind])\n if ind >= 3:\n transformed_str.append(sep_line)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T15:40:59.060",
"Id": "469490",
"Score": "0",
"body": "Not to simplify tabulate method ,the citation way `analyse.tabulate.tabulate(df)` is too long to write,i want to get same result with `df.tabulate()`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T15:14:00.707",
"Id": "239367",
"ParentId": "239362",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T13:21:33.437",
"Id": "239362",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"formatting",
"modules"
],
"Title": "Customized method for dataframe in my analysis module"
} | 239362 |
<p>I want a feedback on my code for the below known problem from Daily coding challenge:</p>
<p>You are given an M by N matrix consisting of booleans that represents a board. Each True boolean represents a wall. Each False boolean represents a tile you can walk on.</p>
<p>Given this matrix, a start coordinate, and an end coordinate, return the minimum number of steps required to reach the end coordinate from the start. If there is no possible path, then return null. You can move up, left, down, and right. You cannot move through walls. You cannot wrap around the edges of the board.</p>
<p>For example, given the following board:</p>
<pre><code>[[f, f, f, f],
[t, t, f, t],
[f, f, f, f],
[f, f, f, f]]
</code></pre>
<p>My solution in Python: I have added comments in my code itself to make it more explanatory</p>
<pre><code>import copy
def shortestpath(m, start, end):
# store the coordinates of start and end
p = end[0]
q = end[1]
a = start[0]
b = start[1]
# if end destination is a wall, return a message
if m[p][q] == 1:
return ('Destination is a wall')
if a==p and b==q:
return('Start and End same')
# store the size of matrix
M = len(m[0])
N = len(m)
# create a matrix of all -9 of the same size of the maze. this will be populated later according to distance from
# start and -1 if its a wall. So it will have -1 if the coordinate has wall and an integer for number of steps fro
# start
dist = [[-9 for _ in range(M)] for _ in range(N)]
# the starting point is initialised with distance 0 and also we take a deepcopy of the distance dist matrix,
# the usage of the copy will be exlained later
dist[a][b] = 0
distcopy = copy.deepcopy(dist)
while True:
# for the complete matrix, we iterate the matrix until we reach the destination
# the very first time, a and b will have value of the starting point so the iterations will start from
# starting point. I transverse from left to right and then down as normal 2D array
# as starting point is initialised to 0, its neighbour will be 0+1 and then further its neighbour will be 0+1+1
# also we not only popluate the current a,b position, but also all the neighbours, like up, down, right, left
for i in range(a, N):
for j in range(b, M):
# left neighbour
if i - 1 >= 0:
[dist[i][j] , dist[i-1][j]] = neighbours(dist[i][j] , dist[i-1][j] , m[i-1][j])
# right neighbour
if i + 1 < N:
[dist[i][j] , dist[i+1][j]] = neighbours(dist[i][j] , dist[i+1][j] , m[i+1][j])
# above neighbour
if j - 1 >= 0:
[dist[i][j] , dist[i][j-1]] = neighbours(dist[i][j] , dist[i][j-1] , m[i][j-1])
# below neighbour
if j + 1 < M:
[dist[i][j] , dist[i][j+1]] = neighbours(dist[i][j] , dist[i][j+1] , m[i][j+1])
# if the value -9 is replaced by any value, it means the number of steps have been found and hence ot returns
if dist[p][q] != -9:
return dist[p][q]
# here we check the dist matrix with the copy before the current iteration started
# if there is no change in M X N matrix, it means, no path was able to be found
# it can happen when there is a wall all together and traversing is not possible
if dist == distcopy:
return ('No path available')
# the copy is updated afer the last row is iterated. here the N-1 check is important as otherwise there will be
# instances when the complete row was same as earlier, but as it was not the last row, it came out,
# so we should ideally be checking the complete matrix of M X N instead of individual rows
else:
if i == N - 1:
distcopy = copy.deepcopy(dist)
a = 0
b = 0
def neighbours(d_curr , d_ngbr , m_ngbr):
# here we compute the distance of either the current position or the neighbour.
# passsed values are current position, position of neighbour and the status of neighbour if its a wall or not
# d_curr != -9 means, the position has been calculated, either wall or the distance from start
# similary for d_ngbr which corresponds to neighbour
# m_ngbr represnts the input matrix which tells about the walls within the maze
if d_curr != -9:
if d_ngbr == -9:
if m_ngbr == 0:
if d_curr != -1:
d_ngbr = d_curr + 1
else:
d_ngbr = -1
else:
if d_ngbr != -9 and m_ngbr == 0:
d_curr = d_ngbr + 1
return [d_curr , d_ngbr]
# here 1 represnts a wall and 0 is a valid path
m = [[0, 1, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 1, 0, 1, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 1, 0, 0, 1, 0, 1, 0],
[1, 1, 1, 1, 0, 1, 1, 1, 1, 0],
[0, 0, 0, 1, 0, 0, 0, 1, 0, 1],
[0, 1, 0, 0, 0, 0, 1, 0, 1, 1],
[0, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[0, 1, 0, 0, 0, 0, 1, 0, 0, 0],
[0, 0, 1, 1, 1, 1, 0, 1, 1, 0]]
start = [0, 0]
end = [3, 4]
shortestpath(m, start, end)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T18:39:24.413",
"Id": "469496",
"Score": "0",
"body": "FYI you've got a bug -- try `shortestpath(m, [2, 2], [8, 1])`..."
}
] | [
{
"body": "<p>As noted in a comment, I think you've got a bug, but I'll do a pass over the code for style since it works for your test case at least. These are mostly minor style points rather than addressing the overall structure of the code; my goal is going to be to make the code easier to read without doing a full rewrite from scratch or changing the way it works.</p>\n\n<ol>\n<li><p>Clearly specify what your functions take as arguments and what they return. One way to do this is docstrings; I usually prefer doing it with type annotations since those can be checked by <code>mypy</code> and the format is actually built into Python 3.</p></li>\n<li><p>Having added type annotations, I'd suggest changing some of those types: use 2-tuples for the coordinates (since you always want exactly two <code>int</code> values there, you can make mypy enforce this by specifying it as a <code>Tuple[int, int]</code>), and raise exceptions for errors rather than returning a string (this is a much more standard way of handling errors in Python). Same for <code>neighbors</code> where you're always returning two values.</p></li>\n<li><p>Use destructuring to assign multiple variables, e.g. <code>a, b = start</code>.</p></li>\n<li><p>Align your comments to the indentation of the blocks they describe. Also, omit comments like <code># the usage of the copy will be exlained later</code>. Either explain it or don't, but don't comment your comments. :)</p></li>\n<li><p>You state the problem in terms of <code>bool</code> values, but your code uses <code>int</code>s. Since you use lots of <code>ints</code> to keep track of distances and coordinates, it's already hard to keep track of what each number represents; if you can turn at least some of those into <code>bool</code>s it makes it easier to discern the use of each variable from its type.</p></li>\n<li><p>Try to reduce nested <code>if</code>s. For example, this:</p></li>\n</ol>\n\n<pre><code> if m_ngbr == 0:\n if d_curr != -1:\n d_ngbr = d_curr + 1\n else:\n d_ngbr = -1\n</code></pre>\n\n<p>could be written as:</p>\n\n<pre><code> if m_ngbr:\n d_ngbr = -1\n elif d_curr != -1:\n d_ngbr = d_curr +1\n</code></pre>\n\n<ol start=\"7\">\n<li>Magic values like <code>-9</code> and <code>-1</code> are dangerous, and I suspect one of those might be the origin of your bug. :) Consider defining them as constants to at least make them easier to distinguish from \"real\" numbers, or better yet, use alternate types like <code>None</code> to indicate unset values.</li>\n</ol>\n\n<pre><code>import copy\nfrom typing import List, Tuple\n\ndef shortestpath(m: List[List[bool]], start: Tuple[int, int], end: Tuple[int, int]) -> int:\n \"\"\"Returns the length of the shortest path through m from start to end. Raises if there's no path.\"\"\"\n\n # store the coordinates of start and end\n p, q = end\n a, b = start\n\n # if end destination is a wall, return a message\n if m[p][q]:\n raise Exception('Destination is a wall')\n\n if start == end:\n raise Exception('Start and End same')\n\n # store the size of matrix\n M = len(m[0])\n N = len(m)\n\n # create a matrix of all -9 of the same size of the maze. this will be populated later according to distance from \n # start and -1 if its a wall. So it will have -1 if the coordinate has wall and an integer for number of steps fro\n # start\n dist = [[-9 for _ in range(M)] for _ in range(N)]\n\n # the starting point is initialised with distance 0 and also we take a deepcopy of the distance dist matrix,\n dist[a][b] = 0\n distcopy = copy.deepcopy(dist)\n\n while True:\n # for the complete matrix, we iterate the matrix until we reach the destination\n # the very first time, a and b will have value of the starting point so the iterations will start from \n # starting point. I transverse from left to right and then down as normal 2D array\n\n # as starting point is initialised to 0, its neighbour will be 0+1 and then further its neighbour will be 0+1+1\n # also we not only popluate the current a,b position, but also all the neighbours, like up, down, right, left\n for i in range(a, N):\n for j in range(b, M):\n # left neighbour \n if i - 1 >= 0:\n dist[i][j] , dist[i-1][j] = neighbours(dist[i][j] , dist[i-1][j] , m[i-1][j])\n\n # right neighbour \n if i + 1 < N:\n dist[i][j] , dist[i+1][j] = neighbours(dist[i][j] , dist[i+1][j] , m[i+1][j])\n\n # above neighbour \n if j - 1 >= 0:\n dist[i][j] , dist[i][j-1] = neighbours(dist[i][j] , dist[i][j-1] , m[i][j-1])\n\n # below neighbour \n if j + 1 < M:\n dist[i][j] , dist[i][j+1] = neighbours(dist[i][j] , dist[i][j+1] , m[i][j+1])\n\n # if the value -9 is replaced by any value, it means the number of steps have been found and hence ot returns \n if dist[p][q] != -9:\n return dist[p][q]\n\n # here we check the dist matrix with the copy before the current iteration started\n # if there is no change in M X N matrix, it means, no path was able to be found\n # it can happen when there is a wall all together and traversing is not possible\n if dist == distcopy:\n raise Exception('No path available')\n\n # the copy is updated afer the last row is iterated. here the N-1 check is important as otherwise there will be\n # instances when the complete row was same as earlier, but as it was not the last row, it came out,\n # so we should ideally be checking the complete matrix of M X N instead of individual rows\n else:\n if i == N - 1:\n distcopy = copy.deepcopy(dist)\n\n a = 0\n b = 0\n\n\ndef neighbours(d_curr: int, d_ngbr: int, m_ngbr: bool) -> Tuple[int, int]:\n\n # here we compute the distance of either the current position or the neighbour.\n # passsed values are current position, position of neighbour and the status of neighbour if its a wall or not\n\n # d_curr != -9 means, the position has been calculated, either wall or the distance from start\n # similary for d_ngbr which corresponds to neighbour\n # m_ngbr represnts the input matrix which tells about the walls within the maze\n\n if d_curr != -9:\n if d_ngbr == -9:\n if m_ngbr:\n d_ngbr = -1\n elif d_curr != -1:\n d_ngbr = d_curr +1\n else:\n if d_ngbr != -9 and not m_ngbr:\n d_curr = d_ngbr + 1\n\n return d_curr, d_ngbr\n\n\n# here W represnts a wall and P is a valid path\nW = True\nP = False\n\nmaze = [\n [P, W, P, P, P, P, W, P, P, P],\n [P, W, P, W, P, P, P, W, P, P],\n [P, P, P, W, P, P, W, P, W, P],\n [W, W, W, W, P, W, W, W, W, P],\n [P, P, P, W, P, P, P, W, P, W],\n [P, W, P, P, P, P, W, P, W, W],\n [P, W, W, W, W, W, W, W, W, P],\n [P, W, P, P, P, P, W, P, P, P],\n [P, P, W, W, W, W, P, W, W, P],\n]\n\nstart = [0, 0]\nend = [3, 4]\n\nassert shortestpath(maze, (0, 0), (3, 4)) == 11\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T19:04:45.910",
"Id": "239375",
"ParentId": "239372",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T17:41:04.367",
"Id": "239372",
"Score": "1",
"Tags": [
"python",
"algorithm",
"python-3.x",
"programming-challenge"
],
"Title": "Shortest path in Binary Maze"
} | 239372 |
<p>This problem is tested against 3 sets of input data to see if the submitted solution gives an incorrect answer, if the solution exceeds the time limit, or if the solution exceeds the memory limit:</p>
<p>Test set 1 (Visible):</p>
<p>1 ≤ N ≤ 1000.</p>
<p>Test set 2 (Visible)</p>
<p>1 ≤ N ≤ 10^6.</p>
<p>Test set 3 (Hidden)</p>
<p>1 ≤ N ≤ 10^18.</p>
<p>My solution (below) passes test sets 1 & 2 but fails test set 3 due to an incorrect answer... This puzzles me. To see if there's a corner/edge case I'm missing here that's only present in the 3rd test set I have it running against a brute force (quadratic) algorithm, testing every allowed N & K combination but so far no differences.</p>
<p>Any help in identifying where I've gone wrong would be greatly appreciated! I'd love to find an example (N,K) input pair where the solution fails so I can debug.</p>
<p>Also, any tips on readability, code quality, best practices I should be following, pythonicness, etc would be helpful. If I should be adding comments to help any potential reviewers please let me know and I'll gladly oblige.</p>
<p>Many thanks!</p>
<blockquote>
<p><a href="https://codingcompetitions.withgoogle.com/codejam/round/0000000000000130/0000000000000652" rel="nofollow noreferrer">https://codingcompetitions.withgoogle.com/codejam/round/0000000000000130/0000000000000652</a></p>
<p><strong>Problem</strong></p>
<p>A certain bathroom has N + 2 stalls in a single row; the stalls on the
left and right ends are permanently occupied by the bathroom guards.
The other N stalls are for users.</p>
<p>Whenever someone enters the bathroom, they try to choose a stall that
is as far from other people as possible. To avoid confusion, they
follow deterministic rules: For each empty stall S, they compute two
values LS and RS, each of which is the number of empty stalls between
S and the closest occupied stall to the left or right, respectively.
Then they consider the set of stalls with the farthest closest
neighbor, that is, those S for which min(LS, RS) is maximal. If there
is only one such stall, they choose it; otherwise, they choose the one
among those where max(LS, RS) is maximal. If there are still multiple
tied stalls, they choose the leftmost stall among those.</p>
<p>K people are about to enter the bathroom; each one will choose their
stall before the next arrives. Nobody will ever leave.</p>
<p>When the last person chooses their stall S, what will the values of
max(LS, RS) and min(LS, RS) be?</p>
<p><strong>Input</strong></p>
<p>The first line of the input gives the number of test cases, T. T lines
follow. Each line describes a test case with two integers N and K, as
described above.</p>
<p><strong>Output</strong></p>
<p>For each test case, output one line containing Case #x: y z, where x
is the test case number (starting from 1), y is max(LS, RS), and z is
min(LS, RS) as calculated by the last person to enter the bathroom for
their chosen stall S.</p>
<p><strong>Limits</strong></p>
<p>1 ≤ T ≤ 100.
1 ≤ K ≤ N.
1 ≤ N ≤ 10^18.</p>
<pre><code>Input Output
5
4 2 Case #1: 1 0
5 2 Case #2: 1 0
6 2 Case #3: 1 1
1000 1000 Case #4: 0 0
1000 1 Case #5: 500 499
</code></pre>
</blockquote>
<p><strong>Solution (in need of review)</strong></p>
<pre><code>from collections import deque
def increment(counts, space, count, q, left=False):
try:
counts[space] += count
except:
counts[space] = count
if left:
q.appendleft(space)
else:
q.append(space)
def minmax(stalls, ppl):
if stalls == ppl:
return [0,0]
counts = {stalls: 1}
q_next = deque([stalls])
person = 0
while True:
q = q_next
q_next = deque()
while q:
space = q.popleft()
count = counts[space]
if space % 2:
if person + count >= ppl:
return [int((space - 1)/2), int((space - 1)/2)]
increment(counts, int((space - 1)/2), 2*count, q_next)
else:
if person + count >= ppl:
return [int(space/2), int(space/2 - 1)]
increment(counts, int(space/2), count, q_next, left=True)
increment(counts, int(space/2 - 1), count, q_next)
person += count
cases = int(input())
for case in range(cases):
stalls, ppl = map(int, input().split())
result = " ".join(map(str, minmax(stalls, ppl)))
print("Case #%d: %s" % (case + 1, result))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T02:15:06.970",
"Id": "469682",
"Score": "0",
"body": "_any tips on readability, code quality, best practices I should be following, pythonicness_ - yes, absolutely. However: _help in identifying where I've gone wrong_ - is off-topic for Code Review. It's probably best if you edit that particular request out, and then this question will be on-topic."
}
] | [
{
"body": "<h2>Missing-value logic</h2>\n\n<p>This:</p>\n\n<pre><code>try:\n counts[space] += count\nexcept:\n counts[space] = count\n</code></pre>\n\n<p>has a few problems:</p>\n\n<ul>\n<li>A bare <code>except</code> is ill-advised; you probably want to be catching <code>KeyError</code></li>\n<li>Avoid logic-by-exception; for instance:</li>\n</ul>\n\n<pre><code>if space in counts:\n counts[space] += count\nelse:\n counts[space] = count\n</code></pre>\n\n<p>Do one better by calling <code>setdefault</code>:</p>\n\n<pre><code>counts.setdefault(space, 0)\ncounts[space] += count\n</code></pre>\n\n<p>Do even better by using a defaultdict:</p>\n\n<pre><code>counts = defaultdict(int)\n# ... then unconditionally:\ncounts[space] += count\n</code></pre>\n\n<p>The last two options you might not be able to meaningfully use if you really need the <code>if left</code> stuff to execute only on the addition of a new key. So this might work:</p>\n\n<pre><code>if not counts.setdefault(space, 0):\n if left:\n q.appendleft(space)\n else:\n q.append(space)\ncounts[space] += count\n</code></pre>\n\n<h2>Returning a list</h2>\n\n<p>This:</p>\n\n<pre><code>return [int((space - 1)/2), int((space - 1)/2)]\n</code></pre>\n\n<p>should probably drop the brackets, so that you return an implicit 2-tuple:</p>\n\n<pre><code>return int((space - 1)/2), int((space - 1)/2)\n</code></pre>\n\n<h2>Input</h2>\n\n<p>Probably better off to have the user input two numbers on separate lines than one line with space separation; and avoid <code>map</code> in this case because it's a little clunky:</p>\n\n<pre><code>stalls, ppl = (int(input()) for _ in range(2))\n</code></pre>\n\n<h2>Formatting</h2>\n\n<pre><code>print(\"Case #%d: %s\" % (case + 1, result))\n</code></pre>\n\n<p>can become</p>\n\n<pre><code>print(f'Case #{case + 1}: {result}')\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T02:26:12.900",
"Id": "239482",
"ParentId": "239377",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T21:09:38.340",
"Id": "239377",
"Score": "2",
"Tags": [
"python",
"algorithm",
"programming-challenge"
],
"Title": "Bathroom stalls in Python 3 (Google Code Jam 2017)"
} | 239377 |
<p>I've decided to implement Python's <a href="https://docs.python.org/3/library/functions.html#any" rel="nofollow noreferrer"><code>any</code></a> in C++. I've gone about this using templates to allow multiple types of data to be passed, instead of overloading the function multiple times. This is my first time using templates so I would really like feedback about my usage of them. I'm also fairly new with references and pointers, so I would like some criticism about my use of them as well. Of course, anything else is on the table and appreciated.</p>
<p>While writing this program, I realized <a href="https://www.cplusplus.com/reference/algorithm/any_of/" rel="nofollow noreferrer"><code>std::any_of</code></a> existed. So yes, I do know there's already a built-in method for this.</p>
<p><code>any.hpp</code></p>
<pre><code>#ifndef ANY_HPP_INCLUDED
#define ANY_HPP_INCLUDED
/**
* @author Ben Antonellis
**/
#include <vector>
#include <iostream>
/**
* Returns True if any of the elements meet the callback functions parameters.
*
* @param elements - A list of elements.
* @param callback - Callback function to invoke on each element.
*
* @return bool - True if parameters are met, False otherwise.
**/
template <typename List, typename Function>
bool any(List &elements, Function *callback) {
for (auto element : elements) {
if (callback(element)) {
return true;
}
}
return false;
}
#endif
</code></pre>
<p>And here's how I'm testing this function:</p>
<p><strong>main.cpp</strong></p>
<pre><code>/**
* @author Ben Antonellis
**/
#include "Any.hpp"
int main() {
std::vector<double> doubleElements = {-1.0, -2.0, -3.0};
std::vector<std::string> stringElements = {"Hello", "Goodbye", "Testing 123"};
auto doubleFunc = [] (double number) {
return number < 0;
};
auto stringFunc = [] (std::string string) {
return string.length() >= 5;
};
/* Test Any Implementation */
if (any(doubleElements, *doubleFunc)) {
std::cout << "(any) Double Success." << std::endl;
}
if (any(stringElements, *stringFunc)) {
std::cout << "(any) String Success." << std::endl;
}
return 0;
}
</code></pre>
<p>If you would like to compile and run, below is the script I'm using to compile and run this program.</p>
<p><strong>run.sh</strong></p>
<pre><code># Compile c++ program to .o file #
g++ -std=gnu++2a -c main.cpp # gnu++2a = Working draft for ISO C++ 2020 with GNU extensions #
# Compile .o file to executable #
g++ main.o -o app
# Run the executable #
./app
# Delete executable and .o files after running #
rm app main.o
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T08:09:47.167",
"Id": "469517",
"Score": "11",
"body": "Off-topic, but note that [cppreference](https://en.cppreference.com) is a more up-to-date and (in general) high-quality community-driven documentation than cplusplus.com as far as I am concerned."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T15:11:41.593",
"Id": "469557",
"Score": "0",
"body": "Agreed, I use [cppreference](https://en.cppreference.com/w/cpp) almost exclusively. It ain't pretty, but it gets the job done :)"
}
] | [
{
"body": "<p>The algorithm looks correct.</p>\n\n<p>Regarding the function signature, I'd make three changes:</p>\n\n<ol>\n<li>You're not modifying elements, so take it by constant reference rather than reference. </li>\n<li>You don't need to specify a pointer to Function, Function is already a template parameter, and non-pointers could be valid (ex: a class with a () operator). </li>\n<li>\"callback\" isn't a very useful name for this case. \"predicate\" would be better. </li>\n</ol>\n\n<p>While this form is fine, I'd also include a version that takes a start/end iterator instead of a container.</p>\n\n<p>Also, there's no reason to include vector or iostream in any.hpp - only include things that are necessary.</p>\n\n<p>For completeness in the testing method, you should also test with an empty collection, and a collection with no matches.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T16:29:21.297",
"Id": "469562",
"Score": "2",
"body": "Although predicate is more specific, \"callback\" seems to have become a very common term to refer to the function passed to a higher-order function, regardless of its role in the algorithm."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T00:56:39.283",
"Id": "469580",
"Score": "11",
"body": "@Barmar No, predicate implies both argument list and return type, and as such is idiomatic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T02:13:13.790",
"Id": "469586",
"Score": "0",
"body": "See here for example: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter @CaptainGiraffe"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T12:19:39.787",
"Id": "469617",
"Score": "5",
"body": "@Barmar: That also says predicate in the description. Callback is a broad term, as you note, and in C++ _predicate_ is quite consistently used for any `bool (T)` functor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T21:04:02.977",
"Id": "469665",
"Score": "4",
"body": "@Barmar In they context of C++ (as well as other languages!) I'd expect a callback to be invoked predominantly for its side-effect. By contrast, and in addition to the other comments, I expect a predicate to be (logically) side-effect free."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T21:10:25.930",
"Id": "469666",
"Score": "0",
"body": "@KonradRudolph I'm not saying that predicate is wrong, I just took exception to the point that callback is a poor name for the parameter, since it's a common, although less specific, term for this. And I gave an example of a well known documentation site that uses it. I also just checked, and the EcmaScript 2020 spec calls it `callbackfn`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T02:40:30.970",
"Id": "469685",
"Score": "4",
"body": "@Barmar C++ terminology is quite different from other programming languages ... In C++, \"callback\" is generally redefined to mean functions / function objects registered in event managers to react to certain events, or in similar contexts where the registered operations are invoked by external signals and mainly for side-effect; [the one in `ios_base`](https://en.cppreference.com/w/cpp/io/ios_base/register_callback) is an example. Using `callback` when `predicate` is more appropriate sounds very anti-C++ish to my (possibly biased) C++-trained ears."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T23:49:11.540",
"Id": "239387",
"ParentId": "239381",
"Score": "32"
}
},
{
"body": "<p>I think you did a pretty good job as a <a href=\"/questions/tagged/beginner\" class=\"post-tag\" title=\"show questions tagged 'beginner'\" rel=\"tag\">beginner</a>. In addition to what Errorsatz said:</p>\n\n<ul>\n<li><p>Consider making <code>element</code> a const reference to prevent unnecessary copying: <code>const auto& element : elements</code></p></li>\n<li><p>You missed <code>#include <string></code> in the test file. </p></li>\n<li><p><code>std::endl</code> flushes the buffer and causes performance degradation; use <code>\\n</code> instead unless you need the flushing behavior. </p></li>\n<li><p>Try to avoid compiler-specific nonstandard extensions, because they make your program non portable. <code>-std=c++20 -pedantic-errors</code> makes g++ go into conforming mode and disables these nonstandard extensions. It is also unnecessary to separate the compiling step from the linking step — g++ does it for you. And remember to turn on warnings! They help you spot many logical bugs in your program. My usual compiling directive looks like this:</p>\n\n<pre><code>g++ main.cpp -o app -std=c++20 -Wall -Wextra -Werror -pedantic-errors\n</code></pre>\n\n<p>(Sometimes I turn on <code>-ftrapv</code> to avoid inadvertently relying on integer overflow behavior as well.)</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T01:05:21.067",
"Id": "239390",
"ParentId": "239381",
"Score": "17"
}
},
{
"body": "<p>Errorsatz already mentioned the <code>Functor</code> type, but I'd like to argue for <a href=\"https://stackoverflow.com/questions/12548614/should-templated-functions-take-lambda-arguments-by-value-or-by-rvalue-reference\"><code>Functor&&</code></a>. </p>\n\n<p>As for testing, this is a case where you <strong>literally</strong> want to test edge cases. I.e. where the first or only the last element has the desired property. Two additional special cases to test would be a single element, matching or not matching. (<a href=\"https://en.wikipedia.org/wiki/Zero_one_infinity_rule\" rel=\"nofollow noreferrer\">Zero-one-many</a> rule of thumb; your tests both have many=3 elements)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-28T04:06:57.377",
"Id": "469844",
"Score": "0",
"body": "I don't think using perfect forwarding is appropriate in this case - the function object is called multiple times. Using a forwarding reference to capture rvalues and call the function object unforwarded (i.e., as an lvalue) is fine though."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T12:31:40.997",
"Id": "239438",
"ParentId": "239381",
"Score": "2"
}
},
{
"body": "<p>I see some of the issues include copying the data and passing by reference or const reference. Might I suggest following the STL's method of using iterators?</p>\n\n<p>Your any function is essentially <a href=\"https://en.cppreference.com/w/cpp/algorithm/find\" rel=\"nofollow noreferrer\">std::find_if</a> using a container instead of iterators.</p>\n\n<p>Rewriting it to use <code>std::find_if</code> reveals the differences:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>template<typename List, typename Predicate>\nbool any(List&& list, Predicate&& pred)\n{\n return std::find_if(\n begin(list),\n end(list), \n std::forward<Predicate>(pred))\n != end(list);\n}\n</code></pre>\n\n<p>Some of the issues I see with your initial implementation are:</p>\n\n<ul>\n<li>Passing list as a non-const reference. This is fixed as in MSalters answer and shown above.</li>\n<li>Passing the predicate as a pointer. We're using templates here, so let the predicate be anything it wants without being converted to a function pointer.</li>\n<li>Reimplementing <code>std::find_if</code> (though I understand wanting to learn!)</li>\n</ul>\n\n<p>My recommended method of implementing this without <code>std::find_if</code> is:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>template<typename List, typename Predicate>\nbool any(List&& list, Predicate&& pred)\n{\n for(auto&& element : list) {\n if(pred(element))\n return true;\n }\n return false;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T13:32:51.250",
"Id": "239441",
"ParentId": "239381",
"Score": "3"
}
},
{
"body": "<p>I see one place where you could use a C++ comment:</p>\n\n<pre><code> /* Test Any Implementation */\n</code></pre>\n\n<p>Because this comment only spans one line, I generally prefer to use a C++ comment instead:</p>\n\n<pre><code> // Test Any Implementation\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T17:46:01.360",
"Id": "239518",
"ParentId": "239381",
"Score": "2"
}
},
{
"body": "<p>Your header guard is:</p>\n\n<pre><code>#ifndef ANY_HPP_INCLUDED\n</code></pre>\n\n<p>The style I most commonly see in modern code is</p>\n\n<pre><code>#ifndef INCLUDED_ANY_HPP\n</code></pre>\n\n<p>(or, just leave off the <code>_HPP</code> part). The reason is that <em>technically</em>, C and C++ reserve all uppercase names matching <code>E[A-Z].*</code> to the implementation, for macros like <code>EINVAL</code> and <code>EPERM</code>. Of course in practice your implementation won't have a macro named <code>EGG_HPP_INCLUDED</code>; but it's theoretically safer, and just as easy, to write <code>INCLUDED_EGG_HPP</code> and eliminate that consideration entirely. Names beginning with <code>I</code> aren't reserved to the implementation.</p>\n\n<hr>\n\n<pre><code>template <typename List, typename Function>\nbool any(List &elements, Function *callback) {\n</code></pre>\n\n<p>You should certainly pass <code>elements</code> by const reference, since you aren't planning to modify it. Consider this use-case:</p>\n\n<pre><code>std::vector<int> getPrimesBetween(int, int);\nbool isOdd(int);\nbool b = any(getPrimesBetween(3, 100), isOdd);\n</code></pre>\n\n<p>Since <code>getPrimesBetween(3, 100)</code> is an rvalue expression, your template taking by lvalue reference won't work.</p>\n\n<hr>\n\n<p>Similarly, taking <code>callback</code> by pointer is weird. Take callbacks either by value (STL style) or by const reference (to avoid unnecessary copying). Consider:</p>\n\n<pre><code>std::vector<int> primes;\nauto isOdd = [](int x) { return x % 2 != 0; };\nbool b = any(primes, isOdd);\n</code></pre>\n\n<p>This won't compile with your template, because <code>decltype(isOdd)</code> is a class type (an unnamed lambda class type) that doesn't pattern-match against <code>Function *</code>.</p>\n\n<p>You solve this in a very strange way that is nevertheless kind of cute:</p>\n\n<pre><code>bool b = any(primes, *isOdd);\n</code></pre>\n\n<p>What you probably <em>meant</em> to type here was <code>&isOdd</code>, not <code>*isOdd</code>. However, the latter also works, because the lambda type has no <code>operator*</code>, and therefore it undergoes implicit conversion to a scalar type so it can use the built-in <code>*</code>. The only implicit conversion available is the implicit conversion to a function-pointer type. So you convert the lambda to a function pointer, dereference the pointer to get a function <em>reference</em>, and then pass that function by value to your template, which decays it back into a function pointer, which happily pattern-matches against <code>Function *</code>.</p>\n\n<p>Observe the difference between <code>&isOdd</code> and <code>*isOdd</code> here: <a href=\"https://godbolt.org/z/ehdbvw\" rel=\"nofollow noreferrer\">https://godbolt.org/z/ehdbvw</a></p>\n\n<p>Specifically, <code>&isOdd</code> and <code>&isEven</code> have different types, but <code>*isOdd</code> and <code>*isEven</code> have the same type.</p>\n\n<p>By taking only function pointers, you're also preventing your template from ever being used with stateful lambdas:</p>\n\n<pre><code>auto isDivisibleBy(int n) { return [n](int x) { return x % n != 0; }; }\nbool b1 = any(primes, isDivisibleBy(3)); // ERROR during deduction\nauto isThreeven = isDivisibleBy(3);\nbool b2 = any(primes, *isThreeven); // ERROR no such operator\nbool b3 = any(primes, &isThreeven); // ERROR during instantiation\n</code></pre>\n\n<hr>\n\n<pre><code> for (auto element : elements) {\n</code></pre>\n\n<p>Since you don't intend to modify the elements, you might take them by <code>const&</code>; but actually you <em>should</em> take them by <code>auto&&</code>, because <a href=\"https://quuxplusone.github.io/blog/2018/12/15/autorefref-always-works/\" rel=\"nofollow noreferrer\"><code>auto&&</code> Always Works</a>.</p>\n\n<hr>\n\n<p>Putting it all together, you'd end up with something like</p>\n\n<pre><code>template<class List, class Function>\nbool any(const List& elements, const Function& callback) {\n for (auto&& element : elements) {\n if (callback(element)) {\n return true;\n }\n }\n return false;\n}\n</code></pre>\n\n<p>Personally I might use the names <code>Range</code>, <code>Callable</code>, and <code>pred[icate]</code> in place of <code>List</code>, <code>Function</code>, and <code>callback</code>... but I guess just putting that in writing makes it pretty plain which one of us has been steeped too long in the unhealthy waters of STL jargon. :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-31T17:53:06.247",
"Id": "470238",
"Score": "1",
"body": "@Linny: I just blogged the `*isOdd` quirk here — https://quuxplusone.github.io/blog/2020/03/31/asterisk-and-ampersand/"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T22:05:00.930",
"Id": "239525",
"ParentId": "239381",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "239387",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T22:22:18.217",
"Id": "239381",
"Score": "23",
"Tags": [
"c++",
"beginner",
"reinventing-the-wheel",
"lambda",
"c++20"
],
"Title": "Implementing any_of in C++"
} | 239381 |
<p>I'd like some feedback on code I wrote to obfuscate text on-disk. The basic idea is the same as <a href="https://en.wikipedia.org/wiki/ROT13" rel="nofollow noreferrer">ROT13</a> (which is <a href="https://github.com/python/cpython/blob/3.8/Lib/encodings/rot_13.py" rel="nofollow noreferrer">implemented</a> in the <a href="https://docs.python.org/3/library/codecs.html#text-transforms" rel="nofollow noreferrer">Python standard library</a>), except instead of rotating the English alphabet by 13, the underlying byte representation is rotated by 128. The use case is to hide data from a string-search.</p>
<p>Because this is such a general transformation, I decided that the user should specify a "base" codec, and then the code would register a version that performs ROT128 (<em>e.g.</em> specifying <code>'utf_8'</code> creates <code>'utf_8_rot128'</code>).</p>
<code>rot128.py</code>
<pre class="lang-py prettyprint-override"><code># -*- coding: utf-8 -*-
'''
Provides codecs that perform a ROT128 transformation on their underlying
byte representation.
This module is side-effect free; to register codecs, use e.g.
register_codecs(UTF_8, ASCII) # for 'utf_8_rot128' and 'ascii_rot128'
register_rot128_codec() # for the bytes-to-bytes 'rot128'
'''
from typing import Dict, Iterable, Optional as Opt
from collections import defaultdict
from collections.abc import MutableMapping
import codecs
### The ROT128 transformation
ROT128_TRANS = bytes(range(256)[128:]) + bytes(range(128))
def rot128_transform(input: bytes) -> bytes:
'''Rotate bytes from `input` by 128'''
try:
return input.translate(ROT128_TRANS)
except AttributeError:
return bytes(input).translate(ROT128_TRANS)
### Registration function and convenience aliases
UTF_8 = ('utf_8', 'U8', 'UTF', 'utf8') # in Python 3.8, add 'cp65001'
ASCII = ('ascii', '646', 'us-ascii')
def register_codecs(*encodings: Iterable[str]) -> None:
'''Create and register codecs (with aliases) that perform ROT128 on
their underlying byte representations. Arguments are iterables of aliases
to the original encoding, e.g.
```
register_rot128_codecs(('utf_8', 'U8', 'UTF', 'utf8'))
```
creates the codec `utf_8_rot128`, with aliases
```
u8_rot128, utf_rot128, utf8_rot128
```
fetchable via `codecs.lookup(...)`
'''
# register the search function only once
global _REGISTER_ONCE
if _REGISTER_ONCE:
codecs.register(_REGISTERED_CODECS)
_REGISTER_ONCE = False
# add codecs
for encoding in encodings:
# check that aliases refer to the same codec
info_orig = codecs.lookup(encoding[0])
if any(info_orig != codecs.lookup(alias) for alias in encoding[1:]):
msg = f'{encoding!r} are not all aliases for the same codec!'
raise ValueError(msg)
# have we built this codec before?
if info_orig in _REGISTERED_ALIASES:
# fetch codec info
for name in _REGISTERED_ALIASES[info_orig]:
break
info_rot128 = _REGISTERED_CODECS[name + '_rot128']
else:
# build codec, fetch info
info_rot128 = _build_codec(info_orig)
# register codec
unregistered = set(encoding) - _REGISTERED_ALIASES[info_orig]
for name in unregistered:
_REGISTERED_CODECS[name + '_rot128'] = info_rot128
# register aliases
_REGISTERED_ALIASES[info_orig] |= unregistered
def _build_codec(codec_info: codecs.CodecInfo) -> codecs.CodecInfo:
'''Create a ROT128'd codec based on `codec_info`'''
def encode(input, errors: str = 'strict') -> bytes:
input, inlen = codec_info.encode(input, errors)
return rot128_transform(input), inlen
def decode(input: bytes, errors: str ='strict'):
return codec_info.decode(rot128_transform(input), errors)
class Codec(codecs.Codec):
def encode(self, input: str, errors: str = 'strict') -> bytes:
return encode(input, errors)
def decode(self, input: bytes, errors: str ='strict') -> bytes:
return decode(input, errors)
class IncrementalEncoder(codec_info.incrementalencoder):
def encode(self, input, final: bool = False):
return rot128_transform(super().encode(input, final))
class IncrementalDecoder(codec_info.incrementaldecoder):
def decode(self, input, final: bool = False):
return super().decode(rot128_transform(input), final)
class StreamWriter(Codec, codec_info.streamwriter):
pass
class StreamReader(Codec, codec_info.streamreader):
pass
return codecs.CodecInfo(
name = codec_info.name + '_rot128',
encode = encode,
decode = decode,
incrementalencoder = IncrementalEncoder,
incrementaldecoder = IncrementalDecoder,
streamwriter = StreamWriter,
streamreader = StreamReader
)
### Maintain registration with `codecs` module
class _RegisteredCodecs(MutableMapping):
'''`dict`-like class that maps ROT128 codec names to their `CodecInfo`s'''
def __init__(self) -> None:
self._store: Dict[str, codecs.CodecInfo] = {}
@staticmethod
def _trans(key: str) -> str:
'''Normalize codec name'''
return key.lower().replace('-', '_')
def __call__(self, key: str) -> Opt[codecs.CodecInfo]:
'''Provide the search function interface to `codecs.register`'''
return self.get(key, None)
def __getitem__(self, key: str) -> codecs.CodecInfo:
return self._store[self._trans(key)]
def __setitem__(self, key: str, value: codecs.CodecInfo) -> None:
self._store[self._trans(key)] = value
def __delitem__(self, key: str) -> None:
del self._store[self._trans(key)]
def __contains__(self, key: str) -> bool:
return self._trans(key) in self._store
def __iter__(self):
return iter(self._store)
def __len__(self) -> int:
return len(self._store)
def __str__(self) -> str:
return str(list(self.keys()))
_REGISTERED_CODECS = _RegisteredCodecs()
_REGISTERED_ALIASES = defaultdict(set)
_REGISTER_ONCE = True
### ROT128 bytes-to-bytes codec
def register_rot128_codec() -> None:
'''Registers the 'rot128' bytes-to-bytes codec'''
global _REGISTER_ROT128_ONCE
if _REGISTER_ROT128_ONCE:
codecs.register(_rot128_search_function)
_REGISTER_ROT128_ONCE = False
def rot128_transcode(input: bytes, errors='strict') -> bytes:
'''A `codecs`-module-style ROT128 encode/decode method'''
return rot128_transform(input), len(input)
class Rot128Codec(codecs.Codec):
'''ROT128 bytes-to-bytes codec'''
def encode(self, input: bytes, errors: str = 'strict') -> bytes:
return rot128_transcode(input, errors)
decode = encode
class Rot128IncrementalEncoder(codecs.IncrementalEncoder):
'''ROT128 bytes-to-bytes incremental encoder'''
def encode(self, input: bytes, final: bool = False) -> bytes:
return rot128_transform(input)
class Rot128IncrementalDecoder(codecs.IncrementalDecoder):
'''ROT128 bytes-to-bytes incremental decoder'''
def decode(self, input: bytes, final: bool = False) -> bytes:
return rot128_transform(input)
class Rot128StreamWriter(Rot128Codec, codecs.StreamWriter):
'''ROT128 bytes-to-bytes stream writer'''
# need to specify (undocumented) charbuffertype for bytes-to-bytes;
# see https://github.com/python/cpython/blob/3.8/Lib/encodings/base64_codec.py
charbuffertype = bytes
class Rot128StreamReader(Rot128Codec, codecs.StreamReader):
'''ROT128 bytes-to-bytes stream reader'''
charbuffertype = bytes
_ROT128_CODEC_INFO = codecs.CodecInfo(
name = 'rot128',
encode = rot128_transcode,
decode = rot128_transcode,
incrementalencoder = Rot128IncrementalEncoder,
incrementaldecoder = Rot128IncrementalDecoder,
streamwriter = Rot128StreamWriter,
streamreader = Rot128StreamReader
)
def _rot128_search_function(encoding: str) -> Opt[codecs.CodecInfo]:
if encoding.lower() == 'rot128':
return _ROT128_CODEC_INFO
else:
return None
_REGISTER_ROT128_ONCE = True
</code></pre>
<p>And a simple example:</p>
<pre class="lang-py prettyprint-override"><code>import codecs
import rot128
rot128.register_rot128_codec()
rot128.register_codecs(rot128.UTF_8)
if __name__ == '__main__':
# seamless encoding
write_text = 'Hello world! \n'
with open('test.txt', 'w', encoding='utf_8_rot128') as f:
f.write(write_text)
# seamless decoding
with open('test.txt', 'r', encoding='utf_8_rot128') as f:
read_text = f.read()
assert read_text == write_text
# bytes-to-bytes is a little meaner
with codecs.open('test.txt', 'rb', encoding='rot128') as f:
read_bytes = f.read()
# codecs.open doesn't have universal newlines
read_text = codecs.decode(read_bytes, 'utf_8').replace('\r\n', '\n')
assert read_text == write_text
with open('test.txt', 'rb') as f:
read_bytes = codecs.decode(f.read(), 'rot128')
read_text = codecs.decode(read_bytes, 'utf_8').replace('\r\n', '\n')
assert read_text == write_text
# bytes-like object
mybytes = write_text.encode('utf_8')
memview = memoryview(mybytes)
assert codecs.encode(memview, 'rot128') == codecs.encode(mybytes, 'rot128')
</code></pre>
<p>There's a few ugly things I'd like to draw attention to, namely</p>
<ul>
<li><code>_RegisteredCodecs</code> is a reimplementation of <code>dict</code> to look up codecs (which is a lot of boilerplate). It does the same "normalization" as the <code>codecs</code> module, namely, lowercasing names and converting hyphens to underscores, and its <code>__call__</code> method implements the <a href="https://docs.python.org/3/library/codecs.html#codecs.register" rel="nofollow noreferrer">search function</a> interface to the <code>codecs</code> registry.</li>
<li><a href="https://docs.python.org/3/glossary.html#term-bytes-like-object" rel="nofollow noreferrer"><code>bytes</code>-like object</a> edge cases: the ROT128 transformation is implemented with <a href="https://docs.python.org/3/library/stdtypes.html#bytes.translate" rel="nofollow noreferrer"><code>translate</code></a>, but this does not exist for <em>e.g.</em> a <code>memoryview</code>, so it converts to <code>bytes</code> in that case; I'm not sure I should attempt to return the original class</li>
<li>The logic in <code>register_codecs</code> is pretty involved, to prevent the user from shooting themself in the foot if they try to register invalid aliases or re-register existing aliases</li>
</ul>
<p>As an outsider, I'm happy to accept style review as well.</p>
| [] | [
{
"body": "<ul>\n<li><p>Re-implementing a dict is completely unnecessary. <code>codecs.register()</code> expects a search <em>function</em>, so a plain function will work just fine. You can use a regular dict to store codecs (in a closure). Normalization can be implemented in its own function.</p>\n\n<p>Something as simple as this should work:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def register_codecs(*encodings: Iterable[str]) -> None:\n registered_codecs = {}\n\n def search(codecs_name):\n return registered_codecs.get(_normalize(codecs_name), None)\n\n codecs.register(search)\n\n # Add codecs\n\ndef _normalize(encoding: str) -> str:\n return encoding.lower().replace('-', '_')\n</code></pre>\n\n<p>Instead of storing codecs in the global variable <code>_REGISTERED_CODECS</code>, we just register another search function each time the user calls <code>register_codecs()</code> (which means <code>_REGISTER_ONCE</code> is also not needed any more; we just got rid of two global variables with one shot!)</p></li>\n<li><p>Now for the error checking in <code>register_codecs()</code>. Checking that aliases refer to the same codec is fine, but I doubt if it's really necessary to check for duplicates. The code works all right even if the same codec is registered twice. So I think it's probably not worth it.</p>\n\n<p>After removing the check for duplicates, the complete <code>register_codecs()</code> function now looks like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def register_codecs(*encodings: Iterable[str]) -> None:\n registered_codecs = {}\n\n def search(codecs_name):\n return registered_codecs.get(codecs_name, None)\n\n codecs.register(search)\n\n # then add codecs to registered_codecs\n for encoding in encodings:\n # check that aliases refer to the same codec\n info_orig = codecs.lookup(encoding[0])\n if any(info_orig != codecs.lookup(alias) for alias in encoding[1:]):\n msg = f\"{encoding!r} are not all aliases for the same codec!\"\n raise ValueError(msg)\n\n for name in encoding:\n registered_codecs[_normalize(name) + \"_rot128\"] = _build_codec(info_orig)\n</code></pre>\n\n<p>And that's also one less global variable!</p></li>\n<li><p><code>rot128_transform()</code> takes any bytes-like object as argument and returns bytes. It's OK to return bytes even if the caller passes in something else like a <code>memoryview</code>—the same way python's <code>Iterable</code> interface works.</p></li>\n<li><p>As a side note, the <code>range()</code> function takes two arguments: <code>start</code> and <code>end</code>. So instead of <code>range(256)[128:]</code>, try <code>range(128, 256)</code>.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T23:08:14.923",
"Id": "469576",
"Score": "0",
"body": "Hey, thanks for the review! Give me some time to try this out and then I'll mark it as \"Accepted\" :D"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T12:30:35.780",
"Id": "469620",
"Score": "0",
"body": "Fun fact: according to [the `typing` docs](https://docs.python.org/3/library/typing.html#typing.ByteString), `bytes` can be used as shorthand for a bytes-like object"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T17:04:02.997",
"Id": "469639",
"Score": "0",
"body": "\" Normalization is also not needed, since the standard library normalize the names for you before calling your search function.\" This is untrue, not only does the library not normalize these names before sending them to the search function, but since the codec names ALSO come from the user, they need to be normalized."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T03:08:47.567",
"Id": "469688",
"Score": "1",
"body": "Yeah, you're right. I thought the standard library does normalization because the `codecs.register()` docs says \"Search functions are expected to take one argument, being the encoding name in all lower case letters\". But it turns out that it only converts upper case letters to lower case and nothing else."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T16:56:09.427",
"Id": "239412",
"ParentId": "239382",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "239412",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-24T22:52:53.287",
"Id": "239382",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"formatting",
"bitwise"
],
"Title": "ROT128 byte-transformation encoding"
} | 239382 |
<p>This is a follow-up question to <a href="https://codereview.stackexchange.com/q/227820/120114">eCommerce Mockup App in JS</a>.</p>
<p>How do I implement the 'observe' pattern for the cart to regenerate html? So that, it will keep refresh its own. And any review on my coding style and code structure design?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>"use strict";
// Bugs
// 1. UI bug for cart item count. Non responsive.
// Initialization of data and page variables - start.
// For actual system, get data from database via API call either in JSON format.
const productList = [
{ id: 101, product: "Logitech Mouse", unitprice: 45.0, image: "LogitechMouse.jpg" },
{ id: 102, product: "Logitech Keyboard", unitprice: 50.0, image: "LogitechKeyboard.jpg" },
{ id: 103, product: "HP Mouse", unitprice: 35.0, image: "HpMouse.jpg" },
{ id: 104, product: "HP Keyboard", unitprice: 32.0, image: "HpKeyboard.jpg" },
{ id: 105, product: "Microsoft Mouse", unitprice: 43.0, image: "MsMouse.jpg" },
{ id: 106, product: "Microsoft Keyboard", unitprice: 39.0, image: "MsKeyboard.jpg" }
];
let productListFilter = []
var cart = [];
const $shoppingCartContainer = document.getElementById("shoppingCartContainer");
const $clearAll = document.getElementById("clearAll");
const $shoppingCart = document.getElementById("shoppingCart");
const $totalCartItems = document.getElementById("totalCartItems");
const $summary = document.getElementById("summary");
// Initialization of data and page variables - end.
// Functions - start -------------------------------------
const createCartHTMLElements = () => {
if (cart.length === 0) {
return;
}
// Start our HTML
let html = "<table><tbody>";
cart.forEach(function (item) {
html += `<tr class=productData><td class="productName">${item.product}</td>\
<td class="productPrice">${item.unitprice.toFixed(2)}</td>\
<td class="quantityProduct">\
<i class="fa fa-plus plus-btn" data-id="${item.id}"></i>\
<label class="quantity">${item.quantity}</label>\
<i class="fa fa-minus minus-btn" data-id="${item.id}"></i>\
</td>\
<td class="total">${item.total.toFixed(2)}</td>\
<td class="deleteProduct"><i class="fa fa-remove del" data-id="${
item.id
}"></i></td>\
</tr>`;
});
// Finish the table:
html += "</tbody></table>";
// Return the table
return html;
};
const updateQuantity = (operation, productId, tr) => {
// Update the quantity in UI
const $quantity = tr.find(".quantity");
const n = $quantity.html();
let i;
switch (operation) {
case "plus":
i = parseInt(n) + 1;
break;
case "minus":
i = parseInt(n) - 1;
if (i < 0) i = 0; // prevent negative quantity
if (i == 0) {
// Duplicate code with delete function - start
cart = cart.filter(function (el) {
return el.id != productId;
});
if (cart.length === 0) {
$clearAll.click();
}
updateCartCount();
updateOrderSummary();
// Duplicate code with delete function - end
tr.closest("tr").remove(); // this is different
}
break;
}
$quantity.html(i);
// Update the total price in UI
const $price = tr.find(".productPrice");
const price = parseFloat($price.html());
const $total = tr.find(".total");
const total = i * price;
$total.html(total.toFixed(2));
// Update the quantity and total in list object
// Find index of specific object using findIndex method.
const objIndex = cart.findIndex(obj => obj.id == productId);
if (objIndex >= 0) {
// Update object's name property.
cart[objIndex].quantity = i;
cart[objIndex].total = total;
updateOrderSummary();
}
};
const populateProducts = () => {
debugger
// Start our HTML
let html = "";
// Loop through members of the object
productListFilter.forEach(function (item) {
html += `<div class="column"><div class="card">\
<div><img class=AddToCart data-id="${item.id}"
src="img/${item.image}" width=250 height=250></div>
<h2>${item.product}</h2>
<p class="price">RM ${item.unitprice.toFixed(2)}</p>
<p><button class=AddToCart data-id="${item.id}">Add to Cart</button></p>\
</div></div>`;
});
document.getElementById("productRow").innerHTML = html;
createAddToCartEventListener();
};
const updateOrderSummary = () => {
document.getElementById("totalItem").innerHTML = cart.length + " item";
const subTotal = cart
.reduce(function (acc, obj) {
return acc + obj.total;
}, 0)
.toFixed(2);
const shippingFee = 10;
document.getElementById("subTotal").innerHTML = subTotal;
document.getElementById("shippingFee").innerHTML = shippingFee.toFixed(2);
document.getElementById("total").innerHTML = (
parseInt(subTotal) + shippingFee
).toFixed(2);
};
const updateCartCount = () => {
//let totalCount = 0;
//cart.forEach(element => totalCount += element.quantity)
$totalCartItems.innerHTML =
cart.reduce((previous, element) => previous + element.quantity, 0);
};
// Functions - End -------------------------------------
// Event listener - start -------------------------------------
const createAddToCartEventListener = () => {
var addToCart = document.getElementsByClassName("AddToCart");
//Array.prototype.forEach.call(addToCart, function (element) {
[...addToCart].forEach(function (element) {
element.addEventListener("click", function () {
// Filter the selected "AddToCart" product from the ProductList list object.
// And push the selected single product into shopping cart list object.
productList.filter(prod => {
if (prod.id == element.dataset.id) {
// Update the quantity in list object
// Find index of specific object using findIndex method.
let objIndex = cart.findIndex(
obj => obj.id == parseInt(element.dataset.id)
);
if (objIndex >= 0) {
// Old item found
cart[objIndex].quantity = cart[objIndex].quantity + 1;
cart[objIndex].total = cart[objIndex].quantity * prod.unitprice;
} else {
// For new item
prod.quantity = 1;
prod.total = prod.unitprice;
cart.push(prod);
}
$shoppingCart.innerHTML = createCartHTMLElements();
createDeleteEventListener();
createPlusButtonEventListener();
createMinusButtonEventListener();
$totalCartItems.style.display = "block";
$clearAll.style.display = "block";
$summary.style.display = "block";
updateCartCount();
updateOrderSummary();
return;
}
});
});
});
};
const createSearchProducts = () => {
document.getElementById('btnSearch').addEventListener('click', function () {
let $productName = document.getElementById('productName').value;
console.log($productName)
if ($productName.trim().length === 0) {
productListFilter = productList;
} else {
productListFilter = productList.filter(product =>
product.product.includes($productName)
)
}
populateProducts();
})
//document.getElementById('productName').addEventListener('keyup', function (element) {
// productList = productList.filter(product => {
// console.log(product.product)
// console.log(element.key)
// product.product == element.key;
// })
// createAddToCartEventListener();
//})
}
const createDeleteEventListener = () => {
var del = document.getElementsByClassName("del");
[...del].forEach(function (element) {
element.addEventListener("click", function () {
// Duplicate code with minus quantity function
// When quantity is zero, it will delete that item
cart = cart.filter(el => el.id != element.dataset.id);
if (cart.length === 0) {
$clearAll.click();
}
updateCartCount();
updateOrderSummary();
element.closest("tr").remove();
});
});
};
const createPlusButtonEventListener = () => {
var plusBtn = document.getElementsByClassName("plus-btn");
[...plusBtn].forEach(function (element) {
element.addEventListener("click", function () {
let productId = element.dataset.id;
let $tr = $(this).closest("tr");
updateQuantity("plus", productId, $tr);
})
})
}
const createMinusButtonEventListener = () => {
var minusBtn = document.getElementsByClassName("minus-btn");
[...minusBtn].forEach(function (element) {
element.addEventListener("click", function () {
let productId = element.dataset.id;
let $tr = $(this).closest("tr");
updateQuantity("minus", productId, $tr);
})
})
}
// $(document.body).on("click", ".plus-btn", function () {
// let productId = $(this).attr("data-id");
// let $tr = $(this).closest("tr");
// updateQuantity("plus", productId, $tr);
// });
// $(document.body).on("click", ".minus-btn", function () {
// let productId = $(this).attr("data-id");
// let $tr = $(this).closest("tr");
// updateQuantity("minus", productId, $tr);
// });
$clearAll.addEventListener("click", function () {
$shoppingCart.innerHTML = "";
$shoppingCartContainer.style.display = "none"
cart.length = 0;
$clearAll.style.display = "none";
$summary.style.display = "none";
updateOrderSummary();
updateCartCount();
});
document.getElementById("cartIcon").addEventListener("click", function () {
if ($shoppingCartContainer.style.display === "none") {
if (cart.length === 0) {
return
}
$shoppingCartContainer.style.display = "block";
} else {
$shoppingCartContainer.style.display = "none";
}
});
window.addEventListener("load", function () {
$shoppingCartContainer.style.display = "none";
window.setTimeout(function () { }, 1000); // prevent flickering
productListFilter = productList;
populateProducts();
createSearchProducts();
//createAddToCartEventListener();
//updateCartCount();
});
// Event listener - end -------------------------------------</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.card {
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
margin: auto;
text-align: center;
font-family: arial;
width: 18em;
}
.price {
color: grey;
font-size: 1.5em;
}
img {
cursor: pointer;
}
.card button {
border: none;
outline: 0;
padding: 12px;
color: white;
background-color: #000;
text-align: center;
cursor: pointer;
width: 100%;
font-size: 1em;
}
.card button:hover {
opacity: 0.7;
}
.productContainer {
margin: 15px;
}
.summaryDetails {
width: 100px;
text-align: right;
}
#productRow {
display: flex;
flex-wrap: wrap;
}
.column {
flex: 1;
margin-top: 12px;
}
@media (max-width: 1333px) {
.column {
flex-basis: 33.33%;
}
}
@media (max-width: 1073px) {
.column {
flex-basis: 33.33%;
}
}
@media (max-width: 815px) {
.column {
flex-basis: 50%;
}
}
@media (max-width: 555px) {
.column {
flex-basis: 100%;
}
}
#header {
width: 100%;
display: flex;
justify-content: space-between;
height: 50px;
}
#left,
#right {
width: 30%;
padding: 10px;
padding-right: 30px;
}
#right {
text-align: right;
position: relative;
}
#main {
max-width: 1000px;
border: 1px solid black;
margin: 0 auto;
position: relative;
}
#shoppingCartContainer {
width: 400px;
background-color: lightyellow;
border: 1px solid silver;
margin-left: auto;
position: absolute;
top: 50px;
right: 0;
padding: 10px;
}
.fa {
color: blue;
cursor: pointer;
}
.fa-shopping-cart {
font-size: 36px;
}
.fa-remove {
font-size: 24px;
color: red;
}
#totalCartItems {
margin: 0px 0px -2px auto;
color: red;
padding: 2px;
border-radius: 25px;
width: 10px;
font-size: 1em;
position: absolute;
}
.plus-btn img {
margin-top: 2px;
}
tr.productData,
td.productName,
td.productPrice,
td.quantityProduct,
td.price,
td.deleteProduct {
padding: 10px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="styles.css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div id="main">
<div id="header">
<div id="left">Login as Joe Doe, <a href="">Logout</a></div>
<div id="right">
<i id="cartIcon" class="fa fa-shopping-cart"> </i>
<span id="totalCartItems"></span>
</div>
</div>
<div>
<input type="text" placeholder="Search your product" id="productName" />
<button id="btnSearch">Search</button>
</div>
<hr>
<div class="productContainer">
<div id="productRow"></div>
</div>
<div id="shoppingCartContainer">
<div id="shoppingCart"></div>
<button id="clearAll">Clear Cart</button>
<div id="summary">
<hr>
<h3>Order Summary</h3>
<table>
<tr>
<td>Subtotal (<span id="totalItem"></span>)</td>
<td class="summaryDetails"><span id="subTotal"></span></td>
</tr>
<tr>
<td>Shipping Fee</td>
<td class="summaryDetails"><span id="shippingFee"></span></td>
</tr>
<tr>
<td>Total</td>
<td class="summaryDetails"><span id="total"></span></td>
</tr>
</table>
<button>Proceed to checkout</button>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<script src="app.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<p>I already gave many suggestions in <a href=\"https://codereview.stackexchange.com/a/228978/120114\">my review of your previous question</a>. I see that some of the advice has been incorporated - e.g. <code>"use strict"</code>, using the spread operator, etc. Yet it seems some of the advice hasn't been used (e.g. variables starting with <code>$</code>, using jQuery more, etc.) but I won't lose sleep about those.</p>\n<p>I suggest avoiding use of <code>var</code> unless you have a good reason - e.g. you need a global variable.</p>\n<p>In <code>createCartHTMLElements()</code> instead of appending to <code>html</code> each time, <code>map()</code> could be used to return the interpolated string for each row and then <code>Array.join()</code> could be used. Another option there is the HTML added in the <code>forEach()</code> callback could be stored in a <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template\" rel=\"nofollow noreferrer\"><code><template></code> element</a> though <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template#Browser_compatibility\" rel=\"nofollow noreferrer\">browser support</a> might be an issue.</p>\n<p>In <code>updateQuantity()</code> instead of finding the index of the object to update, use <code>find()</code> to get a reference to the object and update that directly.</p>\n<p>I see <code>updateOrderSummary()</code> has this variable:</p>\n<blockquote>\n<pre><code>const shippingFee = 10;\n</code></pre>\n</blockquote>\n<p>If that is a true variable, perhaps it should be declared at the top of the code:</p>\n<pre><code>const SHPPING_FEE = 10;\n</code></pre>\n<p>I suggest ALL_CAPS because that is a common convention in many style guides to distinguish constants within code - like you did for <code>DELAY</code> (even though it was commented out) in your <a href=\"https://codereview.stackexchange.com/q/219638/120114\">blackjack code</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-08T00:19:37.207",
"Id": "245161",
"ParentId": "239388",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "245161",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T00:05:34.383",
"Id": "239388",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"css",
"ecmascript-6",
"event-handling"
],
"Title": "eCommerce Mock App"
} | 239388 |
<p>I am a beginner using <code>R</code> and I am trying to solve some simple statistics problems and print the output. The following code takes in two datasets, computes the mean, variance and standard deviation. Finally it computes a 95-confidence interval for the standard deviation. </p>
<p>This is just a sample and my real data consists of a couple of thousand values, the files below are just for illustration. </p>
<p>Currently I read in my data files as follows</p>
<pre><code>list(as.numeric(unlist(read.table(filename)))
</code></pre>
<p>however, I strongly feel there must be a better method? My datafiles
usually consists of rows of data (anywhere from 3 to 10 columns) and about a 1000 rows.</p>
<p>Secondly I find myself doing the following a lot</p>
<pre><code>cat(paste(c("Confidence Intervall for the standard variation: (",
f(CI.sigma.low[1]),", ",#
f(CI.sigma.high[1]),")\n"), collapse = ""))
</code></pre>
<p>I tried to create a function that does this, however, I ran into problems when dealing with
multiple values. </p>
<p><strong>I am not looking for feedback on the mathematics. Only syntax, and tips on how to
improve the overall structure of the code</strong></p>
<h1>Code</h1>
<p><strong>data_01.txt</strong></p>
<pre><code>34.10
34.21
33.34
35.45
31.56
34.67
36.72
33.16
34.35
34.50
</code></pre>
<p><strong>data_02.txt</strong></p>
<pre><code>38.82518 37.61011 39.70940 41.19950 37.91823 39.06883 41.86497 38.87179
39.72824 39.46657 36.42833 39.73950 38.15764 38.49400 37.96093 38.31201
41.23278 37.50835 39.25816 39.72357 37.11235 38.84875 37.88969 38.86277
</code></pre>
<p><strong>Main.R</strong></p>
<pre><code>EXERCISE <- 1 # Global variable,
# Shorthand for printing without " or numbers
p <- function(text,value) {
cat(paste(c(text,value,"\n"), collapse = ""))
}
# Rounds number to X decimal places
f <- function(num, decimals=3) {
round(num*10^decimals)/10^decimals
}
# Fancy title for the problems
problem <- function(index=EXERCISE) {
w <- strrep("=",80); w.small <- strrep(" ",35)
cat("\n\n"); cat(w,"\n")
p(c(w.small,"Problem 3",letters[index],w.small),"")
cat(w,"\n\n")
#double << increments out of current scope
EXERCISE <<- EXERCISE + 1
}
problem() # Problem 3a
# A list makes it easy to change or add files
filenames = c("data_01.txt",
"data_02.txt")
kvm <- list()
for (i in 1:length(filenames)) {
kvm[i] = list(as.numeric(unlist(read.table(filenames[i]))))
}
# Applies the function "length" to each element of "kvm" u.z.w
N <- sapply(kvm, length, simplify = TRUE)
mu <- sapply(kvm, mean, simplify = TRUE)
sigma <- sapply(kvm, sd, simplify = TRUE)
p("Number of values: ",N[1])
p(" Expected value: ",f(mu[1]))
p(" Variance: ",f(sigma[1]^2))
problem() # Problem 3b
I <- 0.95 # 95-confidence intervall
alpha <- 1 - I
# qchisq is the Chi-squared Distribution
# df= degrees of freedom (frihetsgrader)
# CI = confidence interval
CI.sigma.low = (N-1) * sigma^2 / qchisq(1-alpha/2, df=N-1)
CI.sigma.high = (N-1) * sigma^2 / qchisq(alpha/2, df=N-1)
cat(paste(c("Confidence Intervall for the standard variation: (",
f(CI.sigma.low[1]),", ",#
f(CI.sigma.high[1]),")\n"), collapse = ""))
problem() # Problem 3e (T-interval)
I <- 0.95; alpha <- 1 - I
d.f <- sum(N) - length(N)
sigma.p <- sqrt(sum(sigma^2*(N-1))/d.f)
p("Pooled variance: ",f(sigma.p^2))
p("Pooled standard deviation: ",f(sigma.p))
v.p <- qt(1-alpha/2, d.f) * sigma.p * sqrt(sum(1/N))
CI.diff.mu.low <- (mu[1] - mu[2])-v.p
CI.diff.mu.high <- (mu[1] - mu[2])+v.p
p1 <- "Confidence Intervall for difference "
p2 <- "between mean values (mu_1-mu_2):"
cat(paste(c("\n",p1,p2,"\n"," (",
f(CI.diff.mu.low),", ",#
f(CI.diff.mu.high),")\n"), collapse = ""))
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T07:14:57.990",
"Id": "472986",
"Score": "0",
"body": "I have a few questions. Is it intentional that you treat all the values from `data_02.txt` as one variable even though they are in different columns? What problem are you actually trying to solve? Are you practicing `cat()` statements? From outside, I would, for example, rather use named vectors, a custom method (e.g., https://stackoverflow.com/a/6583639/2563804), or create a table. Furthermore, it seems to me that some of the code is reinventing the wheel (e.g., `t.test()` provides the CI for differences between means)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T07:15:56.533",
"Id": "472987",
"Score": "0",
"body": "In summary, there is nothing inherently wrong with the code, but the direction for improvements depends on the desired result and the aim of the project."
}
] | [
{
"body": "<p>This should not be a complete review, but the base R function <code>round</code> has an optional second argument <code>digits</code>. It works like this</p>\n\n<blockquote>\n<pre><code>> round(1.234567, digits=1)\n[1] 1.2\n> round(1.234567, digits=2)\n[1] 1.23\n</code></pre>\n</blockquote>\n\n<p>Therefore there is no need for your function <code>f</code>. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-02T12:13:54.997",
"Id": "239796",
"ParentId": "239389",
"Score": "2"
}
},
{
"body": "<p>Addressing the print formatting part of your question, base R's <code>sprintf</code> function handles all the formatting you're looking for and a lot more besides.</p>\n<p><code>sprintf</code> takes exactly one format string - which includes both your text and the placeholders for your variable data, including formatting instructions like numbers of decimal places and the variables. Its remaining arguments being the variable data to be inserted into the string.</p>\n<p>So with an example similar to yours:</p>\n<pre><code>> x <- 1.23012\n> y <- 1000.0001\n\n> # Equivalent to your paste solution\n> cat(paste("My results are", f(x,2), "and", f(y,0), "\\n"))\nMy results are 1.23 and 1000 \n\n> # Problem - Won't display trailing zeroes, if you want to display to the full number of digits\n> cat(paste("My results are", f(x,3), "and", f(y,0), "\\n"))\nMy results are 1.23 and 1000 \n\n> cat(sprintf("My results are %1.3f and %1.0f\\n", x, y))\nMy results are 1.230 and 1000\n</code></pre>\n<p>It's a lot more powerful than simply <code>paste</code>-ing snippets of strings together; is really good for tabular output - e.g. if you want your data to fill a certain number of characters in the output; and once you get the hang of it, pretty easy to use.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-11T14:52:34.307",
"Id": "269980",
"ParentId": "239389",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "269980",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T00:33:51.910",
"Id": "239389",
"Score": "2",
"Tags": [
"beginner",
"strings",
"formatting",
"r"
],
"Title": "Better filereading and print formating in R"
} | 239389 |
<p>This code is a purely for-fun project and it comes from <a href="https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/binary-agents" rel="nofollow noreferrer">this challenge</a> at freeCodeCamp. This is simply an algorithm challenge which is usually meant for JavaScript, but I decided to perform in C. It will not be used for any production reasons. Please leave any feedback you see fit, with special attention to the loops and data types. I purposely used pointer arithmetic, while, and for loops to explore different approaches to the problems. I also left the printf about number of tokens in there if you'd like to play with it by uncommenting. Also note that I've provided 2 sample binary strings but only one is currently used by default.</p>
<pre><code>#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
char* binary_agent(char *bin_str);
char bit_string_decode(char *const str);
bool bit_string_is_valid(char *bit_string);
int main(void)
{
char str[] = "01000001 01110010 01100101 01101110 00100111 01110100 00100000 "
"01100010 01101111 01101110 01100110 01101001 01110010 01100101 "
"01110011 00100000 01100110 01110101 01101110 00100001 00111111";
char str2[] = "01001001 00100000 01101100 01101111 01110110 01100101 00100000 01000110 01110010 01100101 01100101 01000011 01101111 "
"01100100 01100101 01000011 01100001 01101101 01110000 00100001";
char *result = binary_agent(str);
printf("%s\n", result);
free(result);
result = NULL;
return 0;
}
// Purpose: Return an English translated sentence of the passed binary string
// "Chars" must be space-separated
// E.G. binary_agent("01000001 01110010 01100101");
char* binary_agent(char *bin_str)
{
assert(bin_str);
size_t count;
char *token = NULL;
char *delim = " ";
count = 0;
char *ptr = bin_str;
while((ptr = strchr(ptr, ' ')) != NULL)
{
count++;
ptr++;
}
ptr = NULL;
//printf("Total number of tokens %lu\n", count);
char *output_buffer = malloc(sizeof(char)*(count+1));
assert(output_buffer);
token = strtok(bin_str,delim); // token is null-terminated
if(!token) return NULL;
output_buffer[0] = bit_string_decode(token);
size_t i;
for(i = 1; token != NULL; ++i) //convert to for loop
{
token = strtok(NULL, delim);
if(!token) break;
output_buffer[i] = bit_string_decode(token);
}
return output_buffer;
}
//Parses groups of 8 1s or 0s into a char
char bit_string_decode(char *const str)
{
assert(str && bit_string_is_valid(str));
char output = 0;
size_t i;
//String needs to be valid for sure here
for(i = 0; i < 8; ++i)
{
switch(str[i])
{
case '1':
output |= 1 << 7-i;
break;
case '0':
break;
}
}
return output;
}
bool bit_string_is_valid(char *bit_string)
{
assert(bit_string && (strlen(bit_string) == 8));
while(bit_string && *bit_string != '\0')
{
if((*bit_string != '0') && (*bit_string != '1')) return false;
bit_string++;
}
return true;
}
</code></pre>
| [] | [
{
"body": "<blockquote>\n <p>OP: Please leave any feedback you see fit, with special attention to the loops and data types.</p>\n</blockquote>\n\n<hr>\n\n<p><strong><code>char</code> type</strong></p>\n\n<p>Although <code>char</code> is <em>signed</em> or <em>unsigned</em>, string functions of the standard library work with the data as if it is was <code>unsigned char</code>.</p>\n\n<blockquote>\n <p>... each character shall be interpreted as if it had the type <code>unsigned char</code> ... C17dr §7.24.1 3</p>\n</blockquote>\n\n<p>Also: <code>char output = 0; ... output |= 1 << 7-i;</code> is or-ing bits potentially into the sign place. This really is not a concern, but in general, logical bit manipulation is best done with unsigned types.</p>\n\n<p><code>int/unsigned</code>, in general, is the preferred type to use for efficient/clean code. Thus using <code>unsigned/int</code> rather than <code>char output</code> can make for better code.</p>\n\n<p>Putting these ideas together: recommend something more like</p>\n\n<pre><code>char bit_string_decode(char *const str) {\n unsigned output = 0;\n size_t i;\n for(i = 0; i < 8; ++i) {\n switch(str[i]) {\n case '1':\n output |= 1u << 7-i; // I prefer unsigned types for bit manipulations\n break;\n case '0':\n break;\n }\n }\n return (char) output;\n}\n</code></pre>\n\n<p><strong><code>const</code></strong></p>\n\n<p><code>bit_string_decode(char *const str)</code> does not modify the reference data. Use <code>const</code> for greater functional usage, more function clarity and help weak compilers optimize. </p>\n\n<pre><code>// bit_string_decode(char *const str)\nbit_string_decode(const char *const str)\n// ^---^\n\n// bool bit_string_is_valid(char *bit_string)\nbool bit_string_is_valid(const char *bit_string)\n</code></pre>\n\n<p><strong>Simplifications</strong></p>\n\n<p>Some alternative ideas to simplify the loop:</p>\n\n<pre><code>char bit_string_decode(const char *str) {\n const unsigned char *ustr = (const unsigned char *) str;\n unsigned output = 0;\n while (*(const unsigned char*)ustr) { // cast: see note below\n output <<= 1;\n // Given *str is '0' or '1'\n output |= *ustr++ - '0';\n }\n return (char) output;\n}\n</code></pre>\n\n<p><strong>Allocate to the size of the referenced data, not type</strong></p>\n\n<p>Code is easier to code right, review and maintain.</p>\n\n<pre><code>// char *output_buffer = malloc(sizeof(char)*(count+1));\nchar *output_buffer = malloc(sizeof *output_buffer *(count+1));\n// ^------------^ Referenced data\n</code></pre>\n\n<p><strong>Consider decoding without destruction</strong></p>\n\n<p><code>binary_agent(char *bin_str)</code> messes up <code>bin_str</code> due to <code>strtok(bin_str,delim)</code>. Use of <code>strspn(), strcspn(), strchr()</code> could be used to find the delimiter without changing <code>bin_str</code>. This functional change I find would make for more useful code and greater applicability.</p>\n\n<p><strong>Missing validation in production</strong></p>\n\n<p>I would say <code>strlen(bit_string) == 8</code> (or equivalent) should always test, not in only in <code>assert</code>. Perhaps as</p>\n\n<pre><code>bool bit_string_is_valid(const char *bit_string) {\n if (bit_string == NULL) {\n return false;\n }\n const char *s = bit_string;\n while(* (const unsigned char*)s) { // cast: see note below\n if((*s != '0') && (*s != '1')) {\n return false;\n }\n s++;\n }\n return (s - bit_string) == 8;\n}\n</code></pre>\n\n<p>The cast <code>(const unsigned char*)</code> is only useful here for the all but extinct non-2's complement platforms to properly ID the null character. Drop it, unless code needs that level of portability.</p>\n\n<hr>\n\n<p><strong>Minor</strong></p>\n\n<p><strong>Spacing</strong></p>\n\n<p>Separate function declarations from functions a bit.</p>\n\n<pre><code>bool bit_string_is_valid(char *bit_string);\n// add space here\nint main(void)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T23:10:43.517",
"Id": "239421",
"ParentId": "239391",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T01:43:58.930",
"Id": "239391",
"Score": "3",
"Tags": [
"c",
"strings",
"unit-conversion"
],
"Title": "Convert a binary string, with each char separated by spaces, into a normal C string and print"
} | 239391 |
<p><strong>Songs Class:</strong></p>
<pre class="lang-java prettyprint-override"><code>public class Songs {
//-----------------------------------------------------------------
// Creates a SongCollection object and adds some songs to it. Prints
// reports on the status of the collection.
//-----------------------------------------------------------------
public static void main (String[] args)
{
SongCollection music = new SongCollection ();
music.addSong ("Storm Front", "Billy Joel", 14.95, 10);
music.addSong ("Come On Over", "Shania Twain", 14.95, 16);
music.addSong ("Soundtrack", "Les Miserables", 17.95, 33);
music.addSong ("Graceland", "Paul Simon", 13.90, 11);
System.out.println (music);
music.addSong ("Double Live", "Garth Brooks", 19.99, 26);
music.addSong ("Greatest Hits", "Jimmy Buffet", 15.95, 13);
System.out.println (music);
}
}
</code></pre>
<p><hr><strong>Song Collection Class:</strong></p>
<pre class="lang-java prettyprint-override"><code>import java.text.NumberFormat;
public class SongCollection {
private final int NUM_SONGS = 100;
private Song[] collection;
private int count;
private double totalCost;
//-----------------------------------------------------------------
// Constructor: Creates an initially empty collection.
//-----------------------------------------------------------------
public SongCollection ()
{
collection = new Song[NUM_SONGS];
count = 0;
totalCost = 0.0;
}
//-----------------------------------------------------------------
// Adds a song to the collection, increasing the size of the
// collection if necessary.
//-----------------------------------------------------------------
public void addSong (String title, String artist, double cost, int tracks)
{
if (count == collection.length)
increaseSize();
collection[count] = new Song (title, artist, cost, tracks);
totalCost += cost;
count++;
}
//-----------------------------------------------------------------
// Returns a report describing the CD collection.
//-----------------------------------------------------------------
public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String report = "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
report += "My Song Collection\n\n";
report += "Number of songs: " + count + "\n";
report += "Total cost: " + fmt.format(totalCost) + "\n";
report += "Average cost: " + fmt.format(totalCost/count);
report += "\n\nSong List:\n\n";
for (int i = 0; i < count; i++) {
report += collection[i].toString() + "\n";
}
return report;
}
//-----------------------------------------------------------------
// Increases the capacity of the collection by creating a
// larger array and copying the existing collection into it.
//-----------------------------------------------------------------
private void increaseSize ()
{
Song[] temp = new Song[collection.length * 2];
for (int i = 0; i < collection.length; i++)
temp[i] = collection[i];
collection = temp;
}
}
</code></pre>
<p><hr><strong>Song Class:</strong></p>
<pre class="lang-java prettyprint-override"><code>import java.text.NumberFormat;
public class Song {
private String title, artist;
private double cost;
private int tracks;
//-----------------------------------------------------------------
// Creates a new Song with the specified information.
//-----------------------------------------------------------------
public Song (String name, String singer, double price, int numTracks)
{
title = name;
artist = singer;
cost = price;
tracks = numTracks;
}
//-----------------------------------------------------------------
// Returns a string description of this song.
//-----------------------------------------------------------------
public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String description;
description = fmt.format(cost) + "\t" + tracks + "\t";
description += title + "\t" + artist;
return description;
}
}
</code></pre>
<p><strong>Output:</strong></p>
<pre class="lang-none prettyprint-override"><code>~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
My Song Collection
Number of songs: 6
Total cost: $97.69
Average cost: $16.28
Song List:
$14.95 10 Storm Front Billy Joel
$14.95 16 Come On Over Shania Twain
$17.95 33 Soundtrack Les Miserables
$13.90 11 Graceland Paul Simon
$19.99 26 Double Live Garth Brooks
$15.95 13 Greatest Hits Jimmy Buffet
</code></pre>
<p>I think the formatting of the output could be better and maybe the code could be written in a more cohesive manner to improve readability.</p>
| [] | [
{
"body": "<p><strong>Code Style</strong></p>\n\n<p>Use the standard JavaDoc markup when writing comments. You will be able to generate documentation and it allows you to use ready made tools for documenting stuff like method parameters and related classes. Also people expect to see JavaDoc style comments and are used to reading them, so by rolling out your own style you're adding unnecessary cognitive load to the reader.</p>\n\n<pre><code>/**\n * Creates a new Song with the specified information.\n *\n * @param name Song name\n * @param singer Singer name\n * @param price Song price, in USD.\n * @param numTracks I have no idea why a song would have several tracks. :)\n */\npublic Song(String name, String singer, double price, int numTracks) {\n</code></pre>\n\n<p>Maybe you meant the <code>numTracks</code> parameter to be <code>trackNumber</code>? But is it a track number in a recording the song was in or is it a sorting number in your collection? The name should describe the purpose of the parameter more accurately.</p>\n\n<p>Fields that are not meant to be changed should be final. I would rather see each field on their own line.</p>\n\n<pre><code>private final String title;\nprivate final String artist;\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency\">You should not use float or double types for currency</a>. I would also rather attach the currency code to any monetary value too, but that's probably just me working in the banking sector.</p>\n\n<pre><code>/**\n * Song cost in cents (USD).\n */\nprivate int cost;\n</code></pre>\n\n<p>When initializing fields in a constructor, you should use the same names for the constructor parameters as you have in the fields. That way the reader does not have to wonder what parameter goes to which field and you donä't have to spend time trying to figure out synonyms. And in case you were wondering, using \"this.\" in this context is not code clutter.</p>\n\n<pre><code>public Song(String title, String artist, int cost, int tracks) {\n this.title = title;\n this.artist = artist;\n this.cost = cost;\n this.tracks = numTracks;\n}\n</code></pre>\n\n<p>You are creating your own list data type in the <code>SongCollection</code> class. The class is now responsible for both being a song collection and implementing an extensible list data type. If you want to reinvent the wheel, you should extract the list data type into a separate class to maintain <a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"noreferrer\">single responsibility principle</a>. Otherwise just use the java.util.ArrayList class.</p>\n\n<pre><code>public class SongCollection {\n private List<Song> collection = new ArrayList<>();\n</code></pre>\n\n<p>You're duplicating the <code>Song</code> constructor in the <code>SongCollection</code> class by requiring the user to pass all the same parameters to <code>addSong(...)</code> as you have in the constructor for Song. Instead, have addSong accept just a Song object.</p>\n\n<pre><code>public void addSong(Song song) {\n ...\n</code></pre>\n\n<p><strong>Song Formatting</strong></p>\n\n<p>The <code>toString()</code> method is usually nothing more than a debugging aid. As the JavaDoc says: the result should be a concise but informative representation that is easy for a person to read. You're placing the whole complex formatting logic into the toString method, which again breaks the single responsibility principle and makes the class hard to maintain (the SongCollection class has three responsibilities at the moment). Instead you should encapsulate the formatting into a separate <code>SongFormatter</code> and <code>SongCollectionFormatter</code> classes. The topic is also fairly complex, so it's probably worth another post once you get it done.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T15:49:22.500",
"Id": "469635",
"Score": "0",
"body": "I am getting an error with my collection array. It says that it isn't an arraytype.\n```java\n private void increaseSize () {\n Album[] temp = new Album[collection.size() * 2];\n\n System.arraycopy(collection, 0, temp, 0, collection.size());\n\n collection = Arrays.asList(temp);\n }\n}\n```\nWould I have to use something other than arraycopy?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T15:53:27.533",
"Id": "469636",
"Score": "0",
"body": "I know that doubles and floats shouldn't be used, but I couldn't figure out a way to use ints or longs in order to get the result I wanted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-30T07:55:59.827",
"Id": "470082",
"Score": "0",
"body": "If you use collections instead of an array, you don't need the increaseSize method at all. You can remove it."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T06:40:09.390",
"Id": "239394",
"ParentId": "239392",
"Score": "10"
}
},
{
"body": "<p>In addition to the valuable answer already given:</p>\n\n<ul>\n<li>use JavaDoc for comments describing method/class</li>\n<li>do not use <code>float</code> or <code>double</code> for monetary values (calculation inaccuracies!)</li>\n<li>use existing collection implementations of Java, as <code>ArrayList</code> or at least wrap them</li>\n<li>learn the advantages of Single Responsibility Principle (<em>SRP</em>) </li>\n</ul>\n\n<p>Here some improvements on modelling and design:</p>\n\n<ul>\n<li>use <code>BigDecimal</code> for <strong>monetary values</strong> and store currency (at least in the names)</li>\n<li>use separate class for storing and calculating <strong>summary</strong> information (<strong>aggregation</strong>)</li>\n<li>use separate class for <strong>formatting</strong> (as everything UI related)</li>\n</ul>\n\n<h3>Monetary values</h3>\n\n<p>Monetary values (e.g. prices and costs) can be modeled in different, disputed ways in Java:</p>\n\n<ul>\n<li>using <code>BigDecimal</code> (see also <a href=\"https://en.wikipedia.org/wiki/Decimalisation\" rel=\"nofollow noreferrer\">Decimalisation</a></li>\n<li>using <code>Integer</code> (or <code>int</code>) by representing them as non-fractional numbers by their minor-units (e.g. cents). See also <a href=\"https://stackoverflow.com/questions/18934774/what-are-the-downsides-to-storing-money-values-as-cents-minor-units\">downsides</a>.</li>\n<li>wrapping them in their own types (class) with attached currency-symbol (see <code>Locale</code>)</li>\n<li>using Java's new \"Money & Currency API\" (JSR-354). See <a href=\"https://www.baeldung.com/java-money-and-currency\" rel=\"nofollow noreferrer\">tutorial</a>.</li>\n</ul>\n\n<p>Though for simple cases <code>BigDecimal</code> or even <code>int</code> will do a good job. Simple like single currency (no conversion, single representation) with calculating sums only (no division, tax, etc.).</p>\n\n<h3>Aggregation and Summary</h3>\n\n<p>Since the <strong>total costs</strong> or <strong>count of songs</strong> as well as <strong>average price</strong> are all aggregated facts of a collection of songs, they should be calculated (technical term: aggregated) separately (see SRP). Together they have the purpose of a \"summary\".</p>\n\n<p>So extract them in a class <code>SongCollectionSummary</code> which holds all summarized information, and may also do all the calculation/aggregation.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class SongCollectionSummary {\n private BigDecimal totalCostsInUSD;\n private int songsCount;\n private String description;\n\n public static summarize(Collection<Song> songs, String description) {\n // use only the factory method to create a summary\n SongCollectionSummary summary = new SongCollectionSummary(description);\n summary.songsCount = songs.size();\n // add each \n for (Song song : songs) {\n summary.totalCostsInUSD.add(song.getPrice())\n }\n\n return summary;\n }\n\n private SongCollectionSummary(String description) {\n this.description = description;\n this.totalCostsInUSD = BigDecimal.ZERO;\n this.songsCount = 0;\n }\n\n // only getters for the 3 private fields\n\n public BigDecimal getAveragePriceInUSD() {\n // prevent division by zero\n if (songsCount > 0) {\n return totalCostsInUSD.divide(songsCount);\n }\n // could also throw an exception here, since no songs, no average\n return null;\n }\n\n}\n</code></pre>\n\n<h3>Formatting</h3>\n\n<p>This is part of the UI and belongs in a separate class, better in a separate module (pacakge).\nResponsibility of the class is to build a representation of the domain model (e.g. single <code>Song</code> or collection of songs).</p>\n\n<p>To produce a textual representation there could be a class <code>SongFormatter</code>.\nThis class should allow to format a <code>Song</code> or a collection of many (parameter) and return a <code>String</code> (textual representation).</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class {\n // used with static methods, must also be static\n // a constant named in UPPER_CASE\n public static final NumberFormat CURRENCY_FORMAT = NumberFormat.getCurrencyInstance();\n\n public static String format(Song song) {\n // using an adjustable template to arrange text\n return String.format(\"%s\\t%d\\t%s\", CURRENCY_FROMAT.format(song.getPrice()), song.getTackId(), song.getTitle());\n }\n\n public static String format(Collection<Song> songs, String summaryText) {\n // using a builder to append songs (or summary) dynamically\n StringBuilder sb = new StringBuilder();\n sb.append(\"Song list: \");\n // helding the summary separately and inject customisable as parameter\n sb.append(summaryText);\n // format each song by calling dedicated method (if collection empty, end here)\n for (Song song : songs) {\n sb.append(\"\\n\").append(format(song));\n }\n\n return sb.toString();\n }\n\n}\n</code></pre>\n\n<p>You will find some missing spots above:</p>\n\n<ul>\n<li><code>summaryText</code> needs to be formatted by a separated class or method that may use calculated <code>SongCollectionSummary</code> (as explained before)</li>\n<li>if collection is empty, there will a line <code>Song list:</code> without any songs following, hence take care when calling the method and passing an empty <code>ArrayList</code> of songs (e.g. adjust <code>summaryText</code> to <code>\"[EMPTY] No songs added!\"</code></li>\n</ul>\n\n<p>Hope you will discover some benefits and make use valuable parts to improve your design.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-29T19:42:20.953",
"Id": "239627",
"ParentId": "239392",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "239627",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T01:58:46.283",
"Id": "239392",
"Score": "6",
"Tags": [
"java",
"sorting",
"formatting"
],
"Title": "Creating and listing a song collection"
} | 239392 |
<p><strong>Problem Description:</strong></p>
<p>The purpose of this function is to take a list of sorted numbers and split it into two evenly balanced lists. By evenly balanced I mean the numbers in the two lists have as close as possible to an equal average while as close as possible in length. Put simply, the resulting lists should have the same number of large numbers as small numbers. The algorithm I use is to remove the largest and smallest numbers from the input list and add alternate appending them to an output list. I am open to other algorithms.</p>
<p><strong>Assumptions:</strong></p>
<ul>
<li>input list is sorted in ascending order</li>
<li>all values in list are greater than 0</li>
<li>there are no duplicates in list</li>
<li>the input list will be at least 3 elements long</li>
<li>it is likely that adjacent elements in the input list will differ by very little. For example it's unlikely to have {1,2,500} and is much more likely to be {1,2,5}</li>
</ul>
<p><strong>Correct Examples:</strong></p>
<pre><code>{2,4,5,9}=>{2,9},{4,5}
{1,2,3}=>{1,3},{2}
{1,2,3,4,5,6}=>{1,6,3},{2,5,4}
{1,2,3,4,5,6}=>{2,6,3},{1,5,4}
</code></pre>
<p><strong>Incorrect Examples:</strong></p>
<pre><code>{1,2,3,4,5,6}=>{1,2,3},{4,5,6}
{2,4,5,9}=>{2,4},{5,9}
</code></pre>
<p><strong>The Code:</strong></p>
<pre><code>#include <iostream>
#include <vector>
#include <cmath>
#include <cassert>
using namespace std;
/*prototypes*/
void splitInTwo(vector<int> in, vector<int> &out1, vector<int> &out2);//should the last two be past by const reference?
void displayContents(const vector<int> in);
int main()
{
cout << "program started" << endl;
vector<int>a = {2,3,4,5,6,7,8,10};
vector<int>b = {2,3,5,7,8,12,20,40};
vector<int>c = {1,2,3};
vector<int>d = {10, 15, 33};
vector<int>e = {10, 20, 30, 40, 50, 60, 70};
vector<int>f = {1,2,3,4,5,6};
vector<int>g = {1,2,3,4,5,6,7,8,9,10};
vector<int>h = {1,2,3,4,5,6,7,8,9,10,11,12};
vector<int>i = {1,2,3,4,5,6,7,8,9,10,11,12,13};
vector<int>j = {1,2,3,4,5,6,7,8,9,10,11,12,14};
vector<int> out1, out2;
splitInTwo(a, out1, out2);
splitInTwo(b, out1, out2);
splitInTwo(c, out1, out2);
splitInTwo(d, out1, out2);
splitInTwo(e, out1, out2);
splitInTwo(f, out1, out2);
splitInTwo(g, out1, out2);
splitInTwo(h, out1, out2);
splitInTwo(i, out1, out2);
splitInTwo(j, out1, out2);
return 0;
}
void splitInTwo(vector<int> in, vector<int> &out1, vector<int> &out2)
{
out1.clear();
out2.clear();
out1.reserve(ceil(in.size()/2));
out2.reserve(floor(in.size()/2));
bool alternate = true;
for(int i = 0, j = in.size() - 1; i <= j; i++, j--)//why exactly doesn't auto work here?
{
if(i == j)//i and j point to same element
{
if(alternate)
{
out1.push_back(in[i]);
}
else
{
out2.push_back(in[i]);
}
}
else if(j - i == 1)//j and i point to adjacent elements
{
if(out1.size() < out2.size())
{
out1.push_back(in[i]);
out1.push_back(in[j]);
}
else if(out1.size() > out2.size())
{
out2.push_back(in[i]);
out2.push_back(in[j]);
}
else//equal size
{
out1.push_back(in[i]);
out2.push_back(in[j]);
}
break;
}
else if(alternate)
{
out1.push_back(in[i]);
out1.push_back(in[j]);
}
else
{
out2.push_back(in[i]);
out2.push_back(in[j]);
}
alternate = !alternate;//NB operator is not !=
}
assert(out1.size() - out2.size() <= 1 && "incorrect length of return vector");
//for testing only
cout << "in: " << endl;
displayContents(in);
cout << "out: " << endl;
displayContents(out1);
displayContents(out2);
}
void displayContents(const vector<int> in)
{
for(auto i : in)
cout << i << ", ";
cout << "\n";
}
</code></pre>
<p><strong>Specific Question:</strong></p>
<p>I had initially thought the problem was a lot simpler to solve. It would be nice to remove some of the variables or nested if-statements from the code. In the outer for loop, I'm curious why <code>auto</code> couldn't be used? I guess it's because the literal <code>0</code> is an <code>int</code> and <code>size()</code> returns an <code>unsigned int</code>?</p>
<p>Since I thought the problem was simpler to solve, some aspects of the code did not scale well. For example I wish I put all the test cases in an array. Any feedback regarding the unit testing or overall design principles? Any feedback at all is welcome, I would like to optimize this a learning experience :)</p>
<p><strong>Similar work:</strong></p>
<p>There is a similar problem at <a href="https://www.geeksforgeeks.org/divide-array-two-sub-arrays-averages-equal/" rel="nofollow noreferrer">GeeksForGeeks: find index such that total of elements to the left is "right total"</a>. However this is different because the input list need not be sorted. In the analysis of their "Efficient solution" they give "time complexity" as O(n). Mine I believe to have the runtime of θ(n/2). Is this correct? In this context isn't it more correct to discuss runtime than time complexity?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T08:32:47.767",
"Id": "469519",
"Score": "0",
"body": "I think your definition of \"evenly balanced\" need some clarification. Consider the list `{1, 100, 101, 102}`, which fits your assumptions. Your algorithm would yield `{1, 102}, {100, 101}`, with averages 49 apart. The solution `{1, 101, 102}, {100}` is better considering their 32 average difference, but can they be considered \"balanced\" as their lengths differ more?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T08:49:10.970",
"Id": "469520",
"Score": "0",
"body": "@gazoh you make a good point. Typically the difference between adjacent elements wont be very big (i.e. 99% of the time less than 20). I had constructed the algorithm so that the resulting lists are of the same size, or differ by 1. That being said, if you can think of a better algorithm please share."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-03T02:38:15.050",
"Id": "532114",
"Score": "0",
"body": "A sequence like 1 3 4 6 7 9 13 15 19 21 25 100 101 103 104 106 107 109 113 115 119 121 is bound to highlight problems with simplistic approaches. If the parts were to have about equal lengths, I'd go for • compute average value for a pair • for pairs from outside in: • append to part with lower total if above average, and vice-versa - and fail for #pairs not even…"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-03T07:34:23.783",
"Id": "532122",
"Score": "0",
"body": "*Very similar* problem: [Divide list into two equal parts](https://stackoverflow.com/q/10857755)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-03T08:16:04.887",
"Id": "532126",
"Score": "0",
"body": "en.wikipedia: [Two-way balanced partitioning](https://en.m.wikipedia.org/wiki/Balanced_number_partitioning#Two-way_balanced_partitioning) (going for *same sum*: adapt by adding dummies of average value) (deleted an answer where I seem to have re-invented one of those wheels)."
}
] | [
{
"body": "<p>I'll look at the current code first then look at algorithmic issues.</p>\n<ul>\n<li><p>Avoid <code>using namespace std</code> — while it probably won't cause issues in a small project like this it is bad practice and can unexpected conflicts. See <a href=\"//stackoverflow.com/q/1452721\">Why is "using namespace std;" considered bad practice?</a>.</p>\n</li>\n<li><p><code>ceil(in.size()/2)</code> does not do what you expect. In C++, division by an integer will return an integer, discarding and remainder (e.g. <code>3/2 = 1</code>), and <code>ceil()</code> will return the same integer value. I would replace those lines, using the modulus, with</p>\n<pre><code>out1.reserve((in.size()/2) + in.size()%2);\nout2.reserve(in.size()/2);\n</code></pre>\n</li>\n<li><p>You can't currently use <code>auto</code> in your <code>for</code> loop as <code>i</code> and <code>j</code> would have different types. <code>size()</code> returns a type of <code>std::size_t</code> (which is an unsigned integer type) where 0 is signed. Also in general you should prefer unsigned values for indices in a loop as they are always greater than 0.</p>\n</li>\n<li><p>Your <code>for</code> loop is correct, but personally I would write it with only 1 value like this. I find that easier to read, but is mainly a matter of taste.</p>\n<pre><code>for(std::size_t i = 0, mid = in.size()/2 + in.size()%2; i < mid; i++ )\n{\n size_t j = in.size() - i - 1;\n}\n</code></pre>\n</li>\n</ul>\n<p>In terms of the algorithm, despite what I initially thought I can't actually find an example where this approach doesn't work. So nice job on that count.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-02T14:47:50.267",
"Id": "532056",
"Score": "0",
"body": "Contraindications: [ES.107](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Res-subscripts), [ES.102]. Don't use an unsigned type because it won't be negative. Only use unsigned types when you are doing bit manipulation or require the wrap-around behavior."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-03T02:36:17.583",
"Id": "532113",
"Score": "0",
"body": "(`auto j = in.size() - 1, i = j - j` ?)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T10:32:10.460",
"Id": "239398",
"ParentId": "239393",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T02:08:10.530",
"Id": "239393",
"Score": "5",
"Tags": [
"c++",
"algorithm",
"mathematics"
],
"Title": "Splitting a list so the two resulting lists have the same average"
} | 239393 |
<p>I just created a BinarySeachTree class in c++ which is supposed to store words read from a txt and the number of occurances of those words and i would just like some feedback from you. I think it works correctly and i used valgrind to check if it creates any memory leaks (and it doesn't). I am just worried for some things like the two definitions of some functions, as i am not sure if it is a good practice the way i implemented it. There are a lot of comments in the code that i hope help make the code more understandable. Also i am required to do a technical report for my code and i am not sure how to go on about this, so any comments on this will be greatly appreciated. </p>
<p>Some questions I have are:</p>
<p>-Will the node class be inherited by the subclasses of the BinarySearchTree?</p>
<p>-Should the Node class have a destructor?</p>
<p>-I have to create the AVLTree class which inherits from BinarySearchTree and for the Insert function i will have to keep track of the height variable of Node. Would it be considered sloppy to just copy and paste the Insert function and just add some commands to keep track of height? If so, how could i go on about this?</p>
<p>Thank you for your time.</p>
<p>Header:</p>
<pre><code>#ifndef BINARYSEARCHTREE_H
#define BINARYSEARCHTREE_H
#include <string>
#include <iostream>
using namespace std;
class BinarySearchTree
{
public:
BinarySearchTree(); //constructor which creates an empty tree with a NULL root pointer
~BinarySearchTree(); //recursively deletes tree using postorder traversal by calling the Clear() method
void Insert(string); //insert method is used to insert and also count occurences if while searching the tree we find that the given string already exists
bool Search(string); //1st definition of search: this method will be used by main to search and display the contents of a node whose word is equal to the string
bool Delete(string); //1st definition: deletes the node with the given string as its word, if it exists, by calling the 2nd Delete() definition and is only used by main
void Preorder() {Preorder(root);} //For the traversal methods we use two definitions of each method, one that is called by main and one by the class,
void Inorder() {Inorder(root);} //as main does not have access to the root
void Postorder() {Postorder(root);}
protected:
//Node class to be used only by BinarySearchTree and its children
class Node
{
public:
Node(string s) {word = s; occurences = 1;right = left = NULL;} //Node's constructor initialises node's values
void print() {cout<<"Word: "<<word<<" Occurences: "<<occurences<<endl;}
//Node's variables are set to public because Node will only be used inside BinarySearchTree and its chidlren
int occurences;
string word;
Node* right;
Node* left;
int height; //this variable will be used only by BinarySearchTree's subclass AVLTree
};
Node* root;
//methods only accessible by BinarySearchTree and its children
bool Search(string, Node*&, Node*&); //2nd definition of search: this method will only be used by the class and its children to search for a node to be deleted and finds both the node and its parent
void Preorder(Node*);
void Inorder(Node*);
void Postorder(Node*);
void Clear(Node*);
void FindMinOfRight(Node*, Node*&, Node*&); //this method will be used to delete a node that has two subtrees and it finds the minimum node (and its parent) of the right subtree of the node passed to it
bool Delete(Node*, Node*);//2nd definition: first node is the child to be deleted and the second node is the parent
private:
};
#endif // BINARYSEARCHTREE_H
</code></pre>
<p>Implementation:</p>
<pre><code>#include "BinarySearchTree.h"
BinarySearchTree::BinarySearchTree()
{
root = NULL;
}
BinarySearchTree::~BinarySearchTree()
{
Clear(root);
}
void BinarySearchTree::FindMinOfRight(Node* n, Node* &m, Node* &pm)
{
Node* prev_n = n;
n = n->right;
while(n->left)
{
prev_n = n;
n = n->left;
}
m = n; //min
pm = prev_n; //parent min
}
void BinarySearchTree::Clear(Node* n)
{
if(!n)
return;
Clear(n->left);
Clear(n->right);
delete n;
}
void BinarySearchTree::Insert(string s)
{
if(root) //on the first insertion the new node is the root
{
Node* n = root;
Node* prev_n = NULL;
while(n)
{
prev_n = n; //pointer variable to keep track of the parent node once n becomes NULL
if(s > n->word) //if s is bigger than the current node's word we go to the right subtree
n = n->right;
else
{
if(s < n->word) //if s is smaller than current node's word we go to the left subtree
n = n->left;
else //if s already exists in a node we just increment occurances by 1 and return
{
n->occurences++;
return;
}
}
}
if(s > prev_n->word) //we create a new node in the place of the null pointer
{
prev_n->right = new Node(s);
if(!prev_n->right) //we check if the memory allocation succeded
cout<<"Memory allocation failed"<<endl;
}
else
{
prev_n->left = new Node(s);
if(!prev_n->left)
cout<<"Memory allocation failed"<<endl;
}
}
else
{
root = new Node(s);
if(!root)
cout<<"Memory allocation failed"<<endl;
}
}
bool BinarySearchTree::Search(string s)
{
Node* n = root;
while(n)
{
if(s > n->word) //if s is bigger than the node's word we search the right subtree of the node
n = n->right;
else
{
if(s < n->word) //if s is smaller than the node's word we search the left subtree of the node
n = n->left;
else //else the search was succesful
{
cout<<"Word: "<<n->word<<" Occurences: "<<n->occurences<<endl;
return true;
}
}
}
//if we find a null pointer that means that we have reached a leaf of the tree and that s is not in it
return false;
}
bool BinarySearchTree::Search(string s, Node* &c, Node* &p)
{
Node* n = root;
Node* prev_n = NULL;
while(n)
{
if(s > n->word)
{
prev_n = n;
n = n->right;
}
else
{
if(s < n->word)
{
prev_n = n;
n = n->left;
}
else
{
c = n; //we use identical code to the 1st definition of search with the exception that instead of printing the node's content we store the node's and the node's parent's adress in the parameters
p = prev_n;
return true;
}
}
}
return false;
}
bool BinarySearchTree::Delete(string s)
{
Node* c = NULL;
Node* p = NULL;
if(!(Search(s, c, p)))
return false;
return Delete(c, p);
}
bool BinarySearchTree::Delete(Node* c, Node* p)
{
bool flag = false; //we use this flag to determine whether the node to be deleted is the right(true) or the left(false) child of its parent
if(p && p->right == c)
flag = true;
//case 1: node to be deleted is a leaf
if(!c->right && !c->left)
{
if(p) //if there is no parent we are deleting the root
{
if(flag) //we set the pointer of the parent (left or right) that points to the node to be deleted to NULL then we delete the node
p->right = NULL;
else
p->left = NULL;
delete c;
}
else
{
delete root;
root = NULL;
}
return true;
}
//case 2: node to be deleted has only one subtree
if(c->right && !c->left)
{
if(p) //again we check to see if the node to be deleted is the root
{
if(flag) //we check if the node to be deleted is the right or the left child of its parent so we can bypass it and delete it
p->right = c->right;
else
p->left = c->right;
delete c;
}
else
{
Node* temp = root->right;
delete root;
root = temp;
}
return true;
}
if(!c->right && c->left)
{
if(p)
{
if(flag)
p->right = c->left;
else
p->left = c->left;
delete c;
}
else
{
Node* temp = root->left;
delete root;
root = temp;
}
return true;
}
//case 3: node to be deleted has two subtrees
Node* min_right;
Node* pmin_right;
Node* temp;
if(p)
{
FindMinOfRight(c, min_right, pmin_right);
temp = new Node(min_right->word); //we store the contents of the min_right node that will take the place of the node to be deleted in a temp node
temp->occurences = min_right->occurences;
Delete(min_right, pmin_right); //we first delete the min_right node because there is a chance the node to be deleted and the parent of the min_right are the same node
// this way we make sure the every node's chidlren will be correct
//also this call of Delete() will fall one one of the first two cases as min_right will either be a leaf or have a right subtree
temp->right = c->right; //then we assign to the temp node the children of the node to be deleted (as they should be after min_right is deleted)
temp->left = c->left;
delete c;
if(flag) //finally we replace the node to be deleted with the min_right node
p->right = temp;
else
p->left = temp;
return true;
}
else //in this case we want to delete the root so we work as we did above with the exception that the root has no parent
{
FindMinOfRight(root, min_right, pmin_right);
temp = new Node(min_right->word);
temp->occurences = min_right->occurences;
Delete(min_right, pmin_right);
temp->right = root->right;
temp->left = root->left;
delete root;
root = temp;
return true;
}
return false; //in case something goes wrong
}
void BinarySearchTree::Preorder(Node* n)
{
if(!n)
return;
n->print();
Preorder(n->left);
Preorder(n->right);
}
void BinarySearchTree::Inorder(Node* n)
{
if(!n)
return;
Inorder(n->left);
n->print();
Inorder(n->right);
}
void BinarySearchTree::Postorder(Node* n)
{
if(!n)
return;
Postorder(n->left);
Postorder(n->right);
n->print();
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T13:10:19.977",
"Id": "469547",
"Score": "0",
"body": "Could you remove \"asking for feedback\" part of your title? A title should be a general description of what the code does, as all questions imply improvment of feedback is needed."
}
] | [
{
"body": "<p>The binary search tree you have here is a very naive implementation and has fundamental flaws. And this binary search tree implementation is not an AVLTree.</p>\n\n<p>1) It lacks tree balancing scheme - meaning there is no promise that search will take <code>O(log(n))</code>. </p>\n\n<p>Imagine you put strings into the tree in ascending order. This implementation will always go to the rightmost and put it there. Meaning, it will take <code>O(n^2)</code> time just to make it. And all searches will require <code>O(n)</code> time.</p>\n\n<p>2) It suffers from quite likely stackoverflow on destruction. You have recursive clear functions. Imagine the tree isn't balanced as in example from (1) - then you'll have <code>n</code> stacked calls to <code>Clear()</code> which will overflow the callstack.</p>\n\n<p>3) It lack standart container interface. E.g., iterators and <code>begin()</code> and <code>end()</code> methods as well as efficient <code>size()</code> function.</p>\n\n<p>About your questions. </p>\n\n<blockquote>\n <p>Should the Node class have a destructor?</p>\n</blockquote>\n\n<p>Due to stackoverflow issues usually they don't bother implementing destructors for nodes - as the tree requires very specialized destructor. Unless you plan to use the nodes elsewhere (which I don't advice). In which case, you could use <code>std::unique_ptr<Node></code> for pointers instead of working with raw pointers <code>Node*</code> as these automatically handle most of the basic problems.</p>\n\n<blockquote>\n <p>Will the node class be inherited by the subclasses of the BinarySearchTree?</p>\n</blockquote>\n\n<p>Not sure what exactly you mean. Since it is defined under <code>protected</code> then all classes that inherit from <code>BinarySearchTree</code> will have access to it (lest there is some private inheritance in the middle).</p>\n\n<p>Generally, I don't think that there is any real point in defining simple classes under <code>private</code> or <code>protected</code>. Just make it public.</p>\n\n<blockquote>\n <p>I have to create the AVLTree class which inherits from BinarySearchTree and for the Insert function i will have to keep track of the height variable of Node. Would it be considered sloppy to just copy and paste the Insert function and just add some commands to keep track of height? If so, how could i go on about this?</p>\n</blockquote>\n\n<p>You really need such a design? I'd advise to write AVLTree directly without the BinarySearchTree as base class.</p>\n\n<p>Generally, I don't think there is much purpose in implementing a binary search tree other than for exercising since there are well maintained implementations in STL and some other libraries.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T16:01:13.513",
"Id": "469559",
"Score": "0",
"body": "Thanks a lot for your input. I should have said that I am a first year cs student and that this code is part of a project where we have to count the occurrences of words in a text by using a binary search tree, an AVL tree and a hashtable and then print the time it took each data structure to process all the words. That's why I can't use the STL library and that's why there are no extra methods as this implementation is a tree for a very specific purpose. Also thanks for pointing that the destructor might cause problems. About these fundamental flaws would you care to explain a bit more?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T16:10:54.393",
"Id": "469560",
"Score": "0",
"body": "And wouldn't the traversal functions cause the same stack overflow problem?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T17:42:37.957",
"Id": "469565",
"Score": "0",
"body": "@Kritsos some traversal functions will cause the same problem of (call)stack overflow and some won't - depending on whether they use recursion or not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T17:52:14.653",
"Id": "469566",
"Score": "0",
"body": "@Kritsos the problem is that the class lacks flexible interface. Not sure of all requirements on the AVL tree or some other methods you need - but it let's you'd want a bit of extra data per node for some algorithm implementation. And you cannot add it without changing or rewriting the tree class. And the functions themselves of the binary tree are unsafe (as long as there is no balancing) - so they shouldn't be exposed to the user. Which why I believe you should implement AVLTree directly without the unnecessary base class - and hide all the unsafe methods as private."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T18:10:10.227",
"Id": "469567",
"Score": "0",
"body": "Actually the binary search tree class is a requirement for my project as is the AVL class. And since I have already made the binary search tree making the AVL class inherit from it might save me some time (and was also suggested by our professor). Once again thanks for your feedback and i will try to make my code a bit more general-use"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T13:43:19.923",
"Id": "239404",
"ParentId": "239401",
"Score": "1"
}
},
{
"body": "<h2>Overview</h2>\n<p>One major issue.<br />\nYou take ownership of a pointer but don't implement the rule of three.</p>\n<p>A series issue is that the code is not const correct. If a method does not modify the state of the object then it should be marked const. It is quite common for parameters to be passed as const reference in C++. If that is the case then you can only call const methods (since you don't have any then you can't call any).</p>\n<p>An issue is that you pass parameters by value. This forces them to be copied. Most of the time you should pass by const reference to prevent a copy.</p>\n<h2>Code Review</h2>\n<p>That's relatively common guard name!</p>\n<pre><code>#ifndef BINARYSEARCHTREE_H\n#define BINARYSEARCHTREE_H\n</code></pre>\n<p>I would try an make it more unique, possibly by including the namesapce you put your code into the name of the guard.</p>\n<hr />\n<p>You did not put your code in a namespace.<br />\nShould probably do that <code>BinarySearchTree</code> seems like having. ahigh probability of being defined by multiple people.</p>\n<hr />\n<p>Never do this.</p>\n<pre><code>using namespace std;\n</code></pre>\n<p>Its terrible when people do this in a source file. But doing it in a header file can actually break other peoples code. Stuff like this will get you banned from contributing.</p>\n<ol>\n<li>Never ever ever do it in a header file.<br />\nIt not only affects your code but any code that includes your header.</li>\n<li>Preferably don't even do it your own source files.</li>\n<li>Limitted <code>using std::<something>;</code><br />\nThis can an be acceptable but prefer to limit its scope. But even this is not worth it.</li>\n<li>The reason that the "Standard" namespace is called "std" is so that it is not a burden to use the prefix on objects and types. <code>std::vector<int></code> is that so hard?</li>\n</ol>\n<p>Read details about the issues here:\n<a href=\"https://stackoverflow.com/a/1453605/14065\">Why is “using namespace std;” considered bad practice?\n</a></p>\n<hr />\n<p>Your comments are horrible:</p>\n<pre><code> public:\n BinarySearchTree(); //constructor which creates an empty tree with a NULL root pointer\n ~BinarySearchTree(); //recursively deletes tree using postorder traversal by calling the Clear() method\n void Insert(string); //insert method is used to insert and also count occurences if while searching the tree we find that the given string already exists\n bool Search(string); //1st definition of search: this method will be used by main to search and display the contents of a node whose word is equal to the string\n bool Delete(string); //1st definition: deletes the node with the given string as its word, if it exists, by calling the 2nd Delete() definition and is only used by main\n void Preorder() {Preorder(root);} //For the traversal methods we use two definitions of each method, one that is called by main and one by the class,\n void Inorder() {Inorder(root);} //as main does not have access to the root\n</code></pre>\n<p>Don't write this type of comment. A comment that only describes the code is worse than useless. This actually costs effort to maintain as you must make sure that the comments and code stay in sink over time (comment rot in old code bases is a real thing and is a problem).</p>\n<p>Write comments to explain WHY. The code explains HOW. Use self documenting code (like you have). Using good variable and method names is the key to writing good maintainable code.</p>\n<p>How not to writing bad comments should definitely be a course at university these days.</p>\n<hr />\n<p>You are passing parameters by value:</p>\n<pre><code> void Insert(string);\n bool Search(string);\n bool Delete(string);\n</code></pre>\n<p>This forces a copy of the object from the call location and creates a new value (as the parameter) in the function. What you should be doing is passing by const reference to prevent a copy.</p>\n<pre><code> void Insert(string const&);\n bool Search(string const&);\n bool Delete(string const&);\n</code></pre>\n<p>If you want to get advanced. The insert operator you can pass by r-value reference and allow the Node to re-use the pointer you created externally rather than make a copy when creating the node object.</p>\n<pre><code> void Insert(string&&);\n</code></pre>\n<hr />\n<p>OK. SO you have different methods to iterate over the tree.</p>\n<pre><code> void Preorder() {Preorder(root);}\n void Inorder() {Inorder(root);}\n void Postorder() {Postorder(root);}\n</code></pre>\n<p>But I don't understand how that helps me. I can't do anything by simply iterating over the tree. So what does this give me? Let me take a look at their implementation.</p>\n<p>Ahhh. They all call <code>print()</code>. So you can print out the tree in different orders. Sure that is fine. But name the functions mroe appropriately.</p>\n<pre><code> void PreorderPrint() {PreorderPrint(root);}\n void InorderPrint() {InorderPrint(root);}\n void PostorderPrint() {PostorderPrint(root);}\n</code></pre>\n<hr />\n<p>Lets look at the traversal of the tree for a second.</p>\n<p>Rather than simply supporting printing why not allow the user to iterate over the tree and perform some action. You could pass a functor (or lambda) as a parameter that then gets executed on each value in the tree.</p>\n<p>Or you could implement the visitor pattern.</p>\n<hr />\n<p>Personally I think this is fine.</p>\n<pre><code> Node* root;\n</code></pre>\n<p>You are explicitly making the <code>BinarySearchTree</code> the owner of the tree. But with that comes some extra responsibility that you need to take on (more of that in a second). Alternatively you can use a smart pointer to manage the memory:</p>\n<pre><code> std::unique_ptr<Node> root;\n</code></pre>\n<p>This delegates the ownership of the memory to <code>unique_ptr</code> to manage correctly (which it does).</p>\n<p>So what is the problem with your code?<br />\nYour code ownes the pointer <code>root</code> <strong>BUT</strong> you don't implement the rule of three (or five). This means your code is fundamentally broken.</p>\n<pre><code>{\n BinarySearchTree t;\n t.Insert("Loki");\n\n BinarySearchTree t2(t); // Shallow copy of the tree created.\n // Both t and t2 have the same value of root.\n // i.e. both point at the same tree.\n}\n// Both t and t2 go out of scope.\n// t2 destroyed and calls clear on tree (OK).\n// t1 destroyed and calls clear on tree (this is an issue as this tree\n// was already deleted......)\n</code></pre>\n<p>So if you want to make this a pointer you must implement the rule of three (look it up, it is a very common idiom in C++).</p>\n<p>The easiest way to solve this is simply to use <code>std::unique_ptr</code> for root and then the left and right pointers in <code>Node</code>. But the rest of this review assumes you want to keep ownership and implement the extra methods to solve this.</p>\n<hr />\n<p>If a method does not modify the tree then it should be marked const.</p>\n<pre><code> // I think all these functions should be marked const.\n bool Search(string, Node*&, Node*&);\n void Preorder(Node*);\n void Inorder(Node*);\n void Postorder(Node*);\n void FindMinOfRight(Node*, Node*&, Node*&);\n</code></pre>\n<hr />\n<p>You are using "OUT" parameters. This is pretty horrible to read. It is easy to return a value and it makes it obvious what the function does. You can return multiple values by creating a simple class or using a wrapper like <code>std::pair</code> or <code>std::tuple</code>.</p>\n<pre><code> bool Search(string, Node*&, Node*&);\n void FindMinOfRight(Node*, Node*&, Node*&);\n</code></pre>\n<p>I think you will find it will also make some of your code simpler.</p>\n<hr />\n<p>Not sure what this private section is for.</p>\n<pre><code> private:\n</code></pre>\n<p>Just remove it.</p>\n<hr />\n<p>The value <code>NULL</code> is no longer considered good practice. This is because it is a macro and is usually a number (not sure on the exact definition). But as a result it can be assigned to things it should not be able to assigned to and thus hide errors.</p>\n<p>In modern C++ we use <code>nullptr</code> to represent the value 'null'. It has a specific type <code>std::nullptr_t</code>. This type is automatically convertible to another pointer type but will not auto convert into a numeric type and thus can not accidentally be passed to methods that take <code>int</code> as parameter.</p>\n<hr />\n<p>Prefer to use an initializer liest.</p>\n<pre><code>BinarySearchTree::BinarySearchTree()\n{\n root = NULL;\n}\n</code></pre>\n<p>I would write like this:</p>\n<pre><code>BinarySearchTree::BinarySearchTree()\n : root(nullptr)\n{}\n</code></pre>\n<p>In this situation it does not make any difference (as there are no constructors called). But in a lot of situations this can cause a lot of extra work. So it is best to use the initializer list and be consistent about its use to prevent accidentally incurring extra cost.</p>\n<p>If we look at the node constructor:</p>\n<pre><code>Node(string s)\n{\n word = s;\n occurences = 1;\n right = left = NULL;\n} //Node's constructor initialises node's values\n</code></pre>\n<p>Example of a bad comment above!</p>\n<p>But if we look at what is actually happening here. The member <code>word</code> is default constructed, then in the body you are calling the assignment operator to update <code>word</code> with the value of <code>s</code>. Effectively your code is equivalent to:</p>\n<pre><code>Node(string s)\n : word() // Note word is defaulted constructed here.\n{\n word = s; // Now we call the assignment operator.\n // STUFF\n}\n</code></pre>\n<p>The better way to do it is using the initializer list:</p>\n<pre><code>Node(string s)\n : occurences(1)\n , word(s)\n , right(nullptr)\n , left(nullptr)\n , height(0)\n{}\n</code></pre>\n<hr />\n<p>Your function names are so good.<br />\nWhy are your variable names so bad!!!!!</p>\n<pre><code>void BinarySearchTree::FindMinOfRight(Node* n, Node* &m, Node* &pm)\n{\n // STUFF\n\n m = n; //min // You could have saved yourself a comment\n // and made the code more readable by nameing\n // these two variable "better"!!!!\n pm = prev_n; //parent min\n}\n</code></pre>\n<hr />\n<p>This could be better:</p>\n<pre><code>void BinarySearchTree::FindMinOfRight(Node* n, Node* &m, Node* &pm)\n</code></pre>\n<p>You don't need to return two values. You need to return a reference to the pointer that needs to be changed.</p>\n<pre><code>Node*& BinarySearchTree::FindMinOfRight(Node*& n)\n{\n auto nRef = std::ref(n);\n\n while(nRef->left) {\n nRef = nRef->left;\n }\n return *nRef;\n}\n\n// See below for usage:\n</code></pre>\n<hr />\n<p>Please always put in the braces.</p>\n<pre><code> if(!n)\n return;\n</code></pre>\n<p>I would write this:</p>\n<pre><code> if(!n) {\n return;\n }\n</code></pre>\n<p>The number of time I have fixed problems because people forgot that adding an indent line is not enough to make it executed by the loop the conditional etc...</p>\n<hr />\n<p>OK this is fine:</p>\n<pre><code> Clear(n->left);\n Clear(n->right);\n delete n;\n</code></pre>\n<p>I disagree with @ALX23z that this is likely to cause a SO. Remember that most implementations are going to use <code>std::unique_ptr<Node></code>. This results in exactly the same behavior.</p>\n<p><strong>BUT</strong>. If you do want to do this optimally its not that hard to convert this from a recursive call into a serial call.</p>\n<pre><code> void Clear(Node* n)\n {\n if (!node) {\n return;\n }\n\n // We are going to flatten the tree into a list.\n // by moving all the right nodes to the botomLeft as we go.\n // So:\n // bottomLeft: represents the current bottom left of our list.\n // n: The node we are about to delete.\n // If n has a right node then move it to the bottomLeft\n // and move the `bottomLeft` to a new point.\n // Now we can delete `n`\n //\n // We will eventually reach the end.\n // This is a simple serial deltion of the tree using a loop.\n\n Node* bottomLeft = n;\n while (bottomLeft->left) {\n bottomLeft = bottomLeft->left;\n }\n\n while (n) {\n bottomLeft->left = n->right;\n while (bottomLeft->left) {\n bottomLeft = bottomLeft->left;\n }\n Node* next = n->left;\n delete n;\n n = next;\n }\n}\n</code></pre>\n<hr />\n<p>You make this way to hard:</p>\n<pre><code>void BinarySearchTree::Insert(string s)\n</code></pre>\n<p>I would re-write like this:</p>\n<pre><code>void BinarySearchTree::Insert(string const& s)\n root = Insert(s, root);\n}\n\nNode* BinarySearchTree::Insert(string const& s, Node* n)\n if (n == nullptr) {\n return new Node(s);\n }\n if (s < n.value) {\n n->left = Insert(s, n->left);\n }\n else if (n.value < s) {\n n->right = Insert(s, n->right);\n }\n else {\n n->occurences++;\n }\n return n;\n}\n</code></pre>\n<hr />\n<p>Easy mistake:</p>\n<pre><code> prev_n->left = new Node(s);\n\n // This will NEVER be called. \n if(!prev_n->left)\n cout<<"Memory allocation failed"<<endl;\n</code></pre>\n<p>If <code>new</code> fails (i.e. it can't allocate anything) then it throws an exception. It will never return <code>nullptr</code>.</p>\n<hr />\n<p>Nothing wrong here (apart from unholy bad comments).</p>\n<pre><code>bool BinarySearchTree::Search(string s)\n{\n Node* n = root;\n\n while(n)\n {\n if(s > n->word)\n n = n->right;\n else\n {\n if(s < n->word)\n n = n->left;\n else\n {\n cout<<"Word: "<<n->word<<" Occurences: "<<n->occurences<<endl;\n return true;\n }\n }\n }\n return false;\n}\n</code></pre>\n<p>But I would simply write those <code>if else</code> blocks like they were all part of the same test.</p>\n<pre><code>bool BinarySearchTree::Search(string s)\n{\n Node* n = root;\n\n while(n)\n {\n if(s > n->word) {\n n = n->right;\n }\n else if(s < n->word) {\n n = n->left;\n }\n else\n {\n cout<<"Word: "<<n->word<<" Occurences: "<<n->occurences<<endl;\n return true;\n }\n }\n return false;\n}\n</code></pre>\n<hr />\n<p>Man you make this complicated:</p>\n<pre><code>bool BinarySearchTree::Delete(string s)\n</code></pre>\n<p>Easier:</p>\n<pre><code>bool BinarySearchTree::Delete(string const& s) {\n bool result = false;\n root = Delete(s, root, result);\n return result;\n}\n\nNode* BinarySearchTree::Delete(string const& s, Node* n, bool& result) {\n if (n == nullptr) {\n return nullptr;\n }\n\n Node* retValue = n;\n\n if (s < n.value) {\n n->left = Delete(s, n->left, result);\n }\n else if (n.value < s) {\n n->right = Delete(s, n->right, result);\n }\n else {\n // Found the node we want to delete:\n result = true;\n\n if (node->left == nullptr && node->right == nullptr) {\n retValue = nullptr\n }\n else if (node->left == nulltr) {\n retValue = node->right;\n }\n else if (node->right == nullptr) {\n retValue = node->left;\n }\n else {\n Node*& nodeToReplaceThis = FindMinOfRight(n->right);\n n->value = nodeToReplaceThis->value;\n \n n = nodeToReplaceThis;\n nodeToReplaceThis = n->right; // Remember this is a reference\n // So we are effectively changing\n // what the parent node points at.\n\n // Note: No change in retValue.\n // and n has been moved to the node we want to delete.\n }\n delete n;\n }\n return retValue;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T11:22:42.097",
"Id": "469736",
"Score": "0",
"body": "Thank you very much for the time you put into this. I am not familiar with what unique pointers are but I will look it up. Also about the namespace thing, I did it so I wouldn't have to include it twice in my main.cpp but I now see that my way of thinking is wrong. This is the first time I am doing OOP and C++ and I am still stuck in the way of thinking of C. This in combination with how bad I am at explaining things resulted in these terrible comments. What should my comments say? Also I am supposed to do a technical report afterwards, so the comments shouldn't include many details, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T14:19:48.820",
"Id": "469775",
"Score": "0",
"body": "@Kritsos Modern trends mean that the code should be self documenting. Comments should be reserved for explaining complex situations (so explain WHY/WHAT with comments. The code explains HOW) that are not obvious at first glance. Also comments are used for automatic documentation tools."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T14:47:24.387",
"Id": "469783",
"Score": "0",
"body": "Ok and once again thank you."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-27T01:20:25.480",
"Id": "239476",
"ParentId": "239401",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "239476",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-25T12:12:16.700",
"Id": "239401",
"Score": "1",
"Tags": [
"c++",
"binary-tree"
],
"Title": "Binary Search Tree in c++ used to count words in a text"
} | 239401 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.