body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>Lets say you have several .txt files in a folder and want to merge all text files into a single Excel document:</p>
<p><strong>A.txt</strong></p>
<pre><code>A1
A2
A3
A4
A5
A6
A7
A8
A9
A10
A11
A12
A13
A14
A15
A16
A17
A18
A19
A20
A21
A22
</code></pre>
<p><strong>B.txt</strong></p>
<pre><code>B1
B2
B3
B4
B5
B6
B7
B8
B9
B10
B11
B12
B13
B14
</code></pre>
<p><strong>C.txt</strong></p>
<pre><code>C1
C2
C3
C4
C5
C6
C7
C8
C9
C10
C11
C12
C13
C14
C15
C16
C17
C18
C19
C20
C21
C22
C23
C24
C25
C26
C27
C28
C29
C30
C31
C32
C33
</code></pre>
<p><strong>D.txt</strong></p>
<pre><code>//empty file
</code></pre>
<p><strong>E.txt</strong></p>
<pre><code>E1
E2
E3
E4
E5
E6
E7
E8
E9
E10
E11
E12
E13
E14
E15
E16
E17
E18
E19
E20
E21
E22
E23
E24
E25
E26
E27
E28
E29
E30
E31
E32
E33
E34
E35
E36
E37
E38
</code></pre>
<p><strong>The Output:</strong></p>
<p><a href="https://i.stack.imgur.com/viACe.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/viACe.jpg" alt="enter image description here"></a></p>
<p><strong>spreadsheet_to_text.py</strong></p>
<pre><code>"""
Reads all .txt files in path of the script into a single
spreadsheet. In the first line of the spreadsheet the filename were
the data is from is displayed. Then the data follows
"""
import os
from typing import List
import openpyxl
from openpyxl.utils import get_column_letter
def text_into_spreadsheet():
"""main logic for read .txt into spreadsheet"""
workbook = openpyxl.Workbook()
sheet = workbook.active
column: int = 1
filenames: List[str] = os.listdir()
for filename in filenames:
if filename.endswith(".txt"):
with open(filename) as textfile:
lines: List[int] = textfile.readlines()
sheet[get_column_letter(column) + '1'] = filename
row: int = 2
for line in lines:
sheet[get_column_letter(column) + str(row)] = line
row += 1
column += 1
workbook.save('result.xlsx')
if __name__ == "__main__":
text_into_spreadsheet()
</code></pre>
<p>What do you think about the code?
How can it be improved?</p>
<p>edit: you can find a programm doing it in reversed in <a href="https://codereview.stackexchange.com/questions/210000/spreadsheets-to-text-files">Spreadsheets to text files</a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T23:18:30.303",
"Id": "405777",
"Score": "2",
"body": "Does it *have* to be an Excel spreadsheet, or can it simply be importable by Excel? If the latter, you really should output to something like CSV, which will be faster and simpler."
}
] | [
{
"body": "<p>There are a few things we could improve:</p>\n\n<ul>\n<li><p>you could use the \"lazy\" <a href=\"https://docs.python.org/3/library/glob.html#glob.iglob\" rel=\"noreferrer\"><code>glob.iglob()</code></a> to filter out <code>*.txt</code> files instead of doing the <code>os.listdir()</code>, keeping the whole list if memory and having an extra check inside the loop:</p>\n\n<pre><code>for filename in glob.iglob(\"*.txt\"):\n</code></pre></li>\n<li><p>instead of using <code>textfile.readlines()</code> and read all the lines in a file into memory, iterate over the file object directly in a <em>\"lazy\" manner</em>:</p>\n\n<pre><code>for line in textfile:\n</code></pre></li>\n<li><p>instead of manually keeping track of <code>column</code> value, you could use <a href=\"https://docs.python.org/3/library/functions.html#enumerate\" rel=\"noreferrer\"><code>enumerate()</code></a>:</p>\n\n<pre><code>for column, filename in enumerate(glob.iglob(\"*.txt\"), start=1):\n</code></pre>\n\n<p>Same idea could be applied for rows.</p></li>\n<li><p>I think you don't have to use <code>get_column_letter()</code> and instead operate the numbers which you have:</p>\n\n<pre><code>sheet.cell(row=row, column=column).value = line\n</code></pre></li>\n<li><p>not to say anything against <code>openpyxl</code>, but I personally find <a href=\"https://xlsxwriter.readthedocs.io/\" rel=\"noreferrer\"><code>xlsxwriter</code></a> module's API more enjoyable and more feature rich</p></li>\n</ul>\n\n<hr>\n\n<p>Complete improved version:</p>\n\n<pre><code>import glob\n\nimport openpyxl\n\n\ndef text_into_spreadsheet():\n \"\"\"main logic for read .txt into spreadsheet\"\"\"\n workbook = openpyxl.Workbook()\n sheet = workbook.active\n\n for column, filename in enumerate(glob.iglob(\"*.txt\"), start=1):\n with open(filename) as textfile:\n sheet.cell(row=1, column=column).value = filename\n\n for row, line in enumerate(textfile, start=2):\n sheet.cell(row=row, column=column).value = line\n\n workbook.save('result.xlsx')\n\n\nif __name__ == \"__main__\":\n text_into_spreadsheet()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T18:17:39.170",
"Id": "405887",
"Score": "0",
"body": "I think this solution is very very nice. It is alot better to read compared to what i did."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T22:44:15.157",
"Id": "209940",
"ParentId": "209933",
"Score": "11"
}
},
{
"body": "<p>If you're on a Linux/Mac machine, it's as simple as this shell command:</p>\n\n<pre><code>paste ?.txt\n</code></pre>\n\n<p>The <code>?</code> wildcard will match all your files, <code>A.txt</code> to <code>E.txt</code> in order. The <code>paste</code> command will paste them in parallel columns, separated by TABs.</p>\n\n<p>You can then open your spreadsheet app and import the text file, and add the header.</p>\n\n<p>Per a question formerly in comments: Can you auto-generate the header as well? \nSure:</p>\n\n<pre><code>for f in ?.txt; do echo -en \"$f\\t\"; done; echo; paste ?.txt\n</code></pre>\n\n<p>Also, I'm assuming a single letter before <code>.txt</code>, as in the original example. If you want <em>all</em> files ending in <code>.txt</code>, then it's <code>*.txt</code> instead of <code>?.txt</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T16:13:57.820",
"Id": "209985",
"ParentId": "209933",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "209940",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T20:10:45.690",
"Id": "209933",
"Score": "9",
"Tags": [
"python",
"excel"
],
"Title": "Text file to spreadsheet"
} | 209933 |
<p>I use a Thymeleaf template to inject a set of files (which contain precalculated HTML) into one big HTML. The files with their metadata are stored in a map called <code>files</code>, the files content is stored in another map called <code>content</code>. Both maps share the same key which is basically an id of the files.</p>
<p>The relevant section of the template has these lines:</p>
<pre><code><div th:each="f : ${files}" th:id="${f.key}">
<h1 th:text="${f.value.pageTitle}"></h1>
[(${content[ f.key ]})]
</div>
</code></pre>
<p>The result after this template was processed is:</p>
<pre><code><div id="1">
<h1>Title of document with ID 1</h1>
Content of file with ID 1
</div>
<div id="2">
<h1>Title of document with ID 2</h1>
Content of file with ID 2
</div>
</code></pre>
<p>This works fine but in order to place the <code>th:each</code> I had to introduce a superfluous <code>div</code>. Can I get rid of the div in the template and have a result like this:</p>
<pre><code><h1>Title of document with ID 1</h1>
Content of file with ID 1
<h1>Title of document with ID 2</h1>
Content of file with ID 2
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T22:08:12.607",
"Id": "405770",
"Score": "0",
"body": "Have you tried `th:remove=\"tag\"` in the `div` element? https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#removing-template-fragments"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T07:34:30.497",
"Id": "405797",
"Score": "0",
"body": "@aventurin This looks promising, I will give it a try. I read the tutorial but overlooked this section."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T20:42:41.387",
"Id": "405910",
"Score": "0",
"body": "@Aventurin I can confirm this is working. Do you want to turn your comment into an answer ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T14:32:02.467",
"Id": "406319",
"Score": "0",
"body": "@Marget I've added this as an answer."
}
] | [
{
"body": "<p>Thymeleaf has a mechanism for <a href=\"https://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html#removing-template-fragments\" rel=\"nofollow noreferrer\">removing template fragments</a>. You can use the <code>th:remove=\"tag\"</code> attribute to remove the containing tag but not its children:</p>\n\n<pre><code><div th:each=\"f : ${files}\" th:remove=\"tag\">\n <h1 th:text=\"${f.value.pageTitle}\"></h1>\n [(${content[ f.key ]})]\n</div>\n</code></pre>\n\n<p>The resulting output will not contain the <code>div</code> but the <code>h1</code> element and the text node.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T14:30:42.297",
"Id": "210222",
"ParentId": "209936",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "210222",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T21:43:11.010",
"Id": "209936",
"Score": "0",
"Tags": [
"html",
"template",
"thymeleaf"
],
"Title": "Injecting a set of files in a Thymeleaf template while keeping the amount of tags at a minimum"
} | 209936 |
<p>This method add all numbers in list and return it as double</p>
<pre><code>public HashMap<String, Double> add(HashMap<String, List<? extends Number>> map){
HashMap<String, Double> result = new HashMap<>();
map.forEach((key, value) -> {
Double sum = 0.0;
for (Number num : value){
sum += num.doubleValue();
}
result.put(key, sum);
});
return result;
}
</code></pre>
<p>Testing my method with different types</p>
<pre><code>public static void main(String[] args) {
Adder adder = new Adder();
HashMap<String, List<? extends Number>> hashMap = new HashMap<>();
List<Integer> list1 = new ArrayList<>();
list1.add(1);
list1.add(2);
list1.add(3);
List<BigDecimal> list2 = new ArrayList<>();
list2.add(new BigDecimal("9.87654321e300"));
list2.add(new BigDecimal("987654321"));
list2.add(new BigDecimal("987654321"));
hashMap.put("list1", list1);
hashMap.put("list2", list2);
System.out.println(adder.add(hashMap));
}
</code></pre>
<p>Is there way to improve this?</p>
| [] | [
{
"body": "<p>The following code is very inefficient:</p>\n\n<pre><code> Double sum = 0.0;\n\n for (Number num : value){\n sum += num.doubleValue();\n }\n</code></pre>\n\n<p>It creates a <code>Double</code> object for <code>0.0</code>, and then, since <code>Double</code> objects are immutable, for every <code>num</code> in the <code>value</code> list, it creates yet another <code>Double</code> object for the resulting partial sum. If you replaced <code>Double</code> with <code>double</code>, then you won't be creating new objects for each iteration through the loop.</p>\n\n<hr>\n\n<p>Since you are already using the stream API, why not use <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/stream/DoubleStream.html#sum--\" rel=\"nofollow noreferrer\"><code>DoubleStream::sum</code></a> to sum the values as a <code>double</code>?</p>\n\n<pre><code> double sum = value.stream().mapToDouble(Number::doubleValue).sum();\n</code></pre>\n\n<hr>\n\n<p>Finally, you could use the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#toMap-java.util.function.Function-java.util.function.Function-\" rel=\"nofollow noreferrer\"><code>Collectors.toMap()</code></a> stream method to create the map.</p>\n\n<pre><code>public Map<String, Double> add(Map<String, List<? extends Number>> map) {\n return map.entrySet().stream()\n .collect(Collectors.toMap(Map.Entry::getKey,\n e -> e.getValue().stream()\n .mapToDouble(Number::doubleValue)\n .sum()));\n}\n</code></pre>\n\n<p>Whether or not this last step is an \"improvement\" may be a matter of taste.</p>\n\n<p>Note: the return type is no longer a <code>HashMap</code>; it just a <code>Map</code>.</p>\n\n<hr>\n\n<p>The <code>add()</code> method doesn't depend on any members of <code>Adder</code>, so the method should be <code>static</code>. Then you can get rid of the <code>Adder adder = new Adder()</code> object.</p>\n\n<hr>\n\n<p>Using <code>List.of(...)</code> and <code>Map.of(...)</code> can simplify your test code:</p>\n\n<pre><code>public static void main(String[] args) {\n\n List<Integer> list1 = List.of(1, 2, 3);\n List<BigDecimal> list2 = List.of(new BigDecimal(\"9.87654321e300\"),\n new BigDecimal(\"987654321\"),\n new BigDecimal(\"987654321\"));\n\n Map<String, List<? extends Number>> hashMap = Map.of(\"list1\", list1,\n \"list2\", list2);\n\n System.out.println(Adder.add(hashMap));\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T23:20:32.120",
"Id": "209942",
"ParentId": "209937",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "209942",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T21:43:35.637",
"Id": "209937",
"Score": "2",
"Tags": [
"java",
"generics"
],
"Title": "Numbers adder via generics"
} | 209937 |
<p>I asked about an abstraction layer for accessing files (<a href="https://codereview.stackexchange.com/questions/207585/multiple-file-access-abstractions">link</a>) a couple of days ago (I decided to not call it a follow-up anymore as there are too many changes). I tried to incorporate many of the ideas from the feedbacks but it wasn't easy. In the meantime I noticed that what I'm actually doing is nothing else but <a href="https://en.wikipedia.org/wiki/Create,_read,_update_and_delete" rel="nofollow noreferrer">CRUD</a> so by implementing this <em>pattern</em> I was able to solve a lot more problems that I initially intended to. I think I now have found <em>THE</em> API that is consistent, flexible and allows to work with various kinds of <em>resources</em>; and it's also dependency-injection-friendly.</p>
<p>The idea for the new API is inspired by REST and specifically by <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods" rel="nofollow noreferrer">HTTP verbs</a>: <code>GET</code>, <code>PUT</code>, <code>POST</code>, <code>DELETE</code> and that resources are being accessed by some <em>name</em>.</p>
<pre><code>[PublicAPI]
public interface IResourceProvider
{
[NotNull]
ResourceMetadata Metadata { get; }
[ItemNotNull]
Task<IResourceInfo> GetAsync([NotNull] UriString uri, ResourceMetadata metadata = null);
[ItemNotNull]
Task<IResourceInfo> PostAsync([NotNull] UriString uri, [NotNull] Stream value, ResourceMetadata metadata = null);
[ItemNotNull]
Task<IResourceInfo> PutAsync([NotNull] UriString uri, [NotNull] Stream value, ResourceMetadata metadata = null);
[ItemNotNull]
Task<IResourceInfo> DeleteAsync([NotNull] UriString uri, ResourceMetadata metadata = null);
}
</code></pre>
<p>This main interface is pretty generic so that I can use it with different resources. The <code>IResourceInfo</code> that each method returns is defined as:</p>
<pre><code>[PublicAPI]
public interface IResourceInfo : IEquatable<IResourceInfo>, IEquatable<string>
{
[NotNull]
UriString Uri { get; }
bool Exists { get; }
long? Length { get; }
DateTime? CreatedOn { get; }
DateTime? ModifiedOn { get; }
Task CopyToAsync(Stream stream);
Task<object> DeserializeAsync(Type targetType);
}
</code></pre>
<p>and provides basic information about the resource.</p>
<p>Resources are identified by my <code>UriString</code>. I use it as replacement for <code>Uri</code>. <em>(I asked about it <a href="https://codereview.stackexchange.com/questions/209777/replacing-uri-with-a-more-convenient-class">here</a> where it was called <code>SimpleUri</code>.)</em></p>
<p><code>ResourceMetadata</code> is just a wrapper around the <code>IImmutableDictionary</code></p>
<pre><code>public class ResourceMetadata
{
private readonly IImmutableDictionary<SoftString, object> _metadata;
private ResourceMetadata(IImmutableDictionary<SoftString, object> metadata) => _metadata = metadata;
public static ResourceMetadata Empty => new ResourceMetadata(ImmutableDictionary<SoftString, object>.Empty);
public object this[SoftString key] => _metadata[key];
public int Count => _metadata.Count;
public IEnumerable<SoftString> Keys => _metadata.Keys;
public IEnumerable<object> Values => _metadata.Values;
public bool ContainsKey(SoftString key) => _metadata.ContainsKey(key);
public bool Contains(KeyValuePair<SoftString, object> pair) => _metadata.Contains(pair);
public bool TryGetKey(SoftString equalKey, out SoftString actualKey) => _metadata.TryGetKey(equalKey, out actualKey);
public bool TryGetValue(SoftString key, out object value) => _metadata.TryGetValue(key, out value);
public ResourceMetadata Add(SoftString key, object value) => new ResourceMetadata(_metadata.Add(key, value));
public ResourceMetadata SetItem(SoftString key, object value) => new ResourceMetadata(_metadata.SetItem(key, value));
}
</code></pre>
<p>Its purpose is to carry additional information about the <em>request</em> (like a specific resource-provider name) or resource-provider <em>abbilities</em> or other metadata:</p>
<pre><code>public static class ResourceMetadataKeys
{
public static string ProviderDefaultName { get; } = nameof(ProviderDefaultName);
public static string ProviderCustomName { get; } = nameof(ProviderCustomName);
public static string CanGet { get; } = nameof(CanGet);
public static string CanPost { get; } = nameof(CanPost);
public static string CanPut { get; } = nameof(CanPut);
public static string CanDelete { get; } = nameof(CanDelete);
public static string Scheme { get; } = nameof(Scheme);
public static string Serializer { get; } = nameof(Serializer);
public static string AllowRelativeUri { get; } = nameof(AllowRelativeUri);
}
</code></pre>
<p>Each of these interfaces have an <code>abstract</code> implementation. Their purpose is provide general parameter validation and to wrap inner exceptions in exceptions adding information about the resource-provider and the request. This is useful for debugging and helps to reduce error-handling in concrete types. This also specifies a <code>DefaultScheme</code> which is <code>ionymous</code>. It means that the <em>scheme</em> part is irrelevant and should be ignored. This is used by the <code>CompositeResourceProvider</code> that can look for a resource in several places. Otherwise <em>scheme</em> matters.</p>
<pre><code>[DebuggerDisplay("{DebuggerDisplay,nq}")]
public abstract class ResourceProvider : IResourceProvider
{
public static readonly string DefaultScheme = "ionymous";
protected ResourceProvider(ResourceMetadata metadata)
{
if (!metadata.ContainsKey(ResourceMetadataKeys.Scheme)) throw new ArgumentException(paramName: nameof(metadata), message: $"Resource provider metadata must specify the scheme.");
// If this is a decorator then the decorated resource-provider already has set this.
if (!metadata.ContainsKey(ProviderDefaultName))
{
metadata = metadata.Add(ProviderDefaultName, GetType().ToPrettyString());
}
Metadata = metadata;
}
private string DebuggerDisplay => this.ToDebuggerDisplayString(builder =>
{
builder.DisplayCollection(x => x.Metadata.ProviderNames());
builder.DisplayMember(x => x.Scheme);
});
public virtual ResourceMetadata Metadata { get; }
public virtual SoftString Scheme => (SoftString)(string)Metadata[ResourceMetadataKeys.Scheme];
#region Wrappers
// These wrappers are to provide helpful exceptions.
public async Task<IResourceInfo> GetAsync(UriString uri, ResourceMetadata metadata = null)
{
ValidateCanMethod();
ValidateSchemeNotEmpty(uri);
ValidateSchemeMatches(uri);
try
{
return await GetAsyncInternal(uri, metadata);
}
catch (Exception inner)
{
throw CreateException(uri, metadata, inner);
}
}
public async Task<IResourceInfo> PostAsync(UriString uri, Stream value, ResourceMetadata metadata = null)
{
ValidateCanMethod();
ValidateSchemeNotEmpty(uri);
ValidateSchemeMatches(uri);
try
{
return await PostAsyncInternal(uri, value, metadata);
}
catch (Exception inner)
{
throw CreateException(uri, metadata, inner);
}
}
public async Task<IResourceInfo> PutAsync(UriString uri, Stream value, ResourceMetadata metadata = null)
{
ValidateCanMethod();
ValidateSchemeNotEmpty(uri);
ValidateSchemeMatches(uri);
try
{
return await PutAsyncInternal(uri, value, metadata);
}
catch (Exception inner)
{
throw CreateException(uri, metadata, inner);
}
}
public async Task<IResourceInfo> DeleteAsync(UriString uri, ResourceMetadata metadata = null)
{
ValidateCanMethod();
ValidateSchemeNotEmpty(uri);
ValidateSchemeMatches(uri);
try
{
return await DeleteAsyncInternal(uri, metadata);
}
catch (Exception inner)
{
throw CreateException(uri, metadata, inner);
}
}
#endregion
#region Internal
protected virtual Task<IResourceInfo> GetAsyncInternal(UriString uri, ResourceMetadata metadata = null) => throw new NotSupportedException();
protected virtual Task<IResourceInfo> PostAsyncInternal(UriString uri, Stream value, ResourceMetadata metadata = null) => throw new NotSupportedException();
protected virtual Task<IResourceInfo> PutAsyncInternal(UriString uri, Stream value, ResourceMetadata metadata = null) => throw new NotSupportedException();
protected virtual Task<IResourceInfo> DeleteAsyncInternal(UriString uri, ResourceMetadata metadata = null) => throw new NotSupportedException();
#endregion
#region Helpers
protected Exception CreateException(UriString uri, ResourceMetadata metadata, Exception inner, [CallerMemberName] string memberName = null)
{
// ReSharper disable once AssignNullToNotNullAttribute
var method = Regex.Replace(memberName, "Async$", string.Empty).ToUpper();
throw DynamicException.Create
(
memberName,
$"{GetType().ToPrettyString()} was unable to perform {method} for the given resource '{uri}'.",
inner
);
}
#endregion
#region Validations
protected void ValidateSchemeMatches([NotNull] UriString uri)
{
if (Metadata.TryGetValue(AllowRelativeUri, out bool allow) && allow)
{
return;
}
if (SoftString.Comparer.Equals(Scheme, DefaultScheme))
{
return;
}
if (!SoftString.Comparer.Equals(uri.Scheme, Scheme))
{
throw DynamicException.Create
(
"InvalidScheme",
$"{GetType().ToPrettyString()} requires scheme '{Scheme}'."
);
}
}
protected void ValidateCanMethod([CallerMemberName] string memberName = null)
{
// ReSharper disable once AssignNullToNotNullAttribute
var method = Regex.Replace(memberName, "Async$", string.Empty);
if (!Metadata.TryGetValue($"Can{method}", out bool can) || !can)
{
throw DynamicException.Create
(
$"{method}NotSupported",
$"{GetType().ToPrettyString()} doesn't support '{method.ToUpper()}'."
);
}
}
protected void ValidateSchemeNotEmpty([NotNull] UriString uri)
{
if (Metadata.TryGetValue(AllowRelativeUri, out bool allow) && allow)
{
return;
}
if (!uri.Scheme)
{
throw DynamicException.Create("SchemeNotFound", $"Uri '{uri}' does not contain scheme.");
}
}
#endregion
}
</code></pre>
<p><code>ResourceInfo</code> is implemented as following:</p>
<pre><code>[PublicAPI]
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public abstract class ResourceInfo : IResourceInfo
{
protected ResourceInfo([NotNull] UriString uri)
{
if (uri == null) throw new ArgumentNullException(nameof(uri));
Uri = uri.IsRelative ? new UriString($"{ResourceProvider.DefaultScheme}:{uri}") : uri;
}
private string DebuggerDisplay => this.ToDebuggerDisplayString(builder =>
{
builder.DisplayMember(x => x.Uri);
builder.DisplayMember(x => x.Exists);
});
#region IResourceInfo
public virtual UriString Uri { get; }
public abstract bool Exists { get; }
public abstract long? Length { get; }
public abstract DateTime? CreatedOn { get; }
public abstract DateTime? ModifiedOn { get; }
#endregion
#region Wrappers
// These wrappers are to provide helpful exceptions.
public async Task CopyToAsync(Stream stream)
{
AssertExists();
try
{
await CopyToAsyncInternal(stream);
}
catch (Exception inner)
{
throw DynamicException.Create
(
$"{nameof(CopyToAsync)}",
$"Affected resource '{Uri}'.",
inner
);
}
}
public async Task<object> DeserializeAsync(Type targetType)
{
AssertExists();
try
{
return await DeserializeAsyncInternal(targetType);
}
catch (Exception inner)
{
throw DynamicException.Create
(
$"{nameof(DeserializeAsync)}",
$"Affected resource '{Uri}'.",
inner
);
}
}
#endregion
#region Internal
protected abstract Task CopyToAsyncInternal(Stream stream);
protected abstract Task<object> DeserializeAsyncInternal(Type targetType);
#endregion
#region IEquatable<IResourceInfo>
public override bool Equals(object obj) => obj is IResourceInfo resource && Equals(resource);
public bool Equals(IResourceInfo other) => ResourceInfoEqualityComparer.Default.Equals(other, this);
public bool Equals(string other) => !string.IsNullOrWhiteSpace(other) && ResourceInfoEqualityComparer.Default.Equals((UriString)other, Uri);
public override int GetHashCode() => ResourceInfoEqualityComparer.Default.GetHashCode(this);
#endregion
#region Helpers
protected void AssertExists([CallerMemberName] string memberName = null)
{
if (!Exists)
{
// ReSharper disable once AssignNullToNotNullAttribute
throw DynamicException.Create(memberName, $"Resource '{Uri}' does not exist.");
}
}
#endregion
}
</code></pre>
<h3>Example</h3>
<p>As an example let me show you one of my many new resource-providers, the <code>AppSettingProvider</code>:</p>
<pre><code>public class AppSettingProvider : ResourceProvider
{
private readonly ITypeConverter _uriStringToSettingIdentifierConverter;
public AppSettingProvider(ITypeConverter uriStringToSettingIdentifierConverter = null)
: base(
ResourceMetadata.Empty
.Add(ResourceMetadataKeys.CanGet, true)
.Add(ResourceMetadataKeys.CanPut, true)
.Add(ResourceMetadataKeys.Scheme, "setting")
)
{
_uriStringToSettingIdentifierConverter = uriStringToSettingIdentifierConverter;
}
protected override Task<IResourceInfo> GetAsyncInternal(UriString uri, ResourceMetadata metadata = null)
{
var settingIdentifier = (string)_uriStringToSettingIdentifierConverter?.Convert(uri, typeof(string)) ?? uri;
var exeConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var actualKey = FindActualKey(exeConfig, settingIdentifier) ?? settingIdentifier;
var element = exeConfig.AppSettings.Settings[actualKey];
return Task.FromResult<IResourceInfo>(new AppSettingInfo(uri, element?.Value));
}
protected override async Task<IResourceInfo> PutAsyncInternal(UriString uri, Stream stream, ResourceMetadata metadata = null)
{
using (var valueReader = new StreamReader(stream))
{
var value = await valueReader.ReadToEndAsync();
var settingIdentifier = (string)_uriStringToSettingIdentifierConverter?.Convert(uri, typeof(string)) ?? uri;
var exeConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var actualKey = FindActualKey(exeConfig, settingIdentifier) ?? settingIdentifier;
var element = exeConfig.AppSettings.Settings[actualKey];
if (element is null)
{
exeConfig.AppSettings.Settings.Add(settingIdentifier, value);
}
else
{
exeConfig.AppSettings.Settings[actualKey].Value = value;
}
exeConfig.Save(ConfigurationSaveMode.Minimal);
return await GetAsync(uri);
}
}
[CanBeNull]
private static string FindActualKey(Configuration exeConfig, string key)
{
return
exeConfig
.AppSettings
.Settings
.AllKeys
.FirstOrDefault(k => SoftString.Comparer.Equals(k, key));
}
}
internal class AppSettingInfo : ResourceInfo
{
[CanBeNull]
private readonly string _value;
internal AppSettingInfo([NotNull] UriString uri, [CanBeNull] string value) : base(uri)
{
_value = value;
}
public override bool Exists => !(_value is null);
public override long? Length => _value?.Length;
public override DateTime? CreatedOn { get; }
public override DateTime? ModifiedOn { get; }
protected override async Task CopyToAsyncInternal(Stream stream)
{
// ReSharper disable once AssignNullToNotNullAttribute - this isn't null here
using (var valueStream = _value.ToStreamReader())
{
await valueStream.BaseStream.CopyToAsync(stream);
}
}
protected override Task<object> DeserializeAsyncInternal(Type targetType)
{
return Task.FromResult<object>(_value);
}
}
</code></pre>
<p>Other types that I've needed and implemented so far, are:</p>
<ul>
<li><code>AppSettingProvider</code> ✓</li>
<li><code>ConnectionStringProvider</code> ✓</li>
<li><code>PhysicalFileProvider</code> ✓</li>
<li><code>PhysicalDirectoryProvider</code> ✓</li>
<li><code>InMemoryResourceProvider</code> ✓</li>
<li><code>EmbeddedFileProvider</code> ✓</li>
<li><code>CompositeResourceProvider</code> ✓ (I use this for accessing resources by name or get the first match)</li>
<li><code>SqlServerProvider</code> ✓ (I use this for settings)</li>
<li><code>JsonResourceProvider</code> ✓ (I use this as a <em>translating</em> decorator for other resource-providers)</li>
<li><code>EnvironmentVariableProvider</code> ✓</li>
<li><code>SettingProvider</code> ✓ (I use this as a <em>translating</em> decorator for setting names) </li>
</ul>
<p>I intend to add more later, e.g.:</p>
<ul>
<li>Registry</li>
<li>Ftp (this one would require a new API for opening sessions)</li>
<li>and many more...</li>
</ul>
<hr>
<p>It works surprisingly well. So, how do you like it and how would you improve it? The interfaces are very simple and some things are <em>hidden</em> inside <code>ResourceMetadata</code> but with an API for <em>everything</em> you must make some tradeoffs.</p>
<p>I'm particularly interested about what you think of the <em>wrapper</em> or decorator methods and parameter validation. I know, I used a couple <code>region</code>s but this is an absolute excepiton. I also wonder what you say about how I specify the <em>abilities</em> of each resource-provider via their <code>ResourceMetadata</code>.</p>
<p>I call it <code>IOnymous</code> and the complete code is as always on <a href="https://github.com/he-dev/reusable/tree/dev/Reusable.IOnymous/src" rel="nofollow noreferrer">GitHub</a> where you can take a look at all of it.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-18T22:24:08.630",
"Id": "209939",
"Score": "4",
"Tags": [
"c#",
"api",
"io",
"dependency-injection",
"framework"
],
"Title": "One interface for multiple CRUD resources"
} | 209939 |
<p><a href="http://www.thymeleaf.org/" rel="nofollow noreferrer">Thymeleaf</a> is an XML/XHTML/HTML5 template engine (extensible to other formats) that can work both in web and non-web environments. It is better suited for serving XHTML/HTML5 at the view layer of web applications, but it can process any XML file even in offline environments.</p>
<p>It provides an optional module for integration with Spring MVC, so that you can use it as a complete substitute of JSP in your applications made with this technology, even with HTML5.</p>
<p>Unlike JSP, Thymeleaf is a <strong>natural</strong> template engine meaning that the file could be directly opened in browsers without having to run the application.</p>
<p>The main goal of Thymeleaf is to provide an elegant and well-formed way of creating templates, allowing to use them also as static prototypes.</p>
<p>Its architecture allows a fast processing of templates, relying on intelligent caching of parsed files in order to use the least possible amount of I/O operations during execution.</p>
<p>Thymeleaf is a Java library.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T00:08:05.327",
"Id": "209946",
"Score": "0",
"Tags": null,
"Title": null
} | 209946 |
Thymeleaf is an XML/XHTML/HTML5 template engine (extensible to other formats) that can work both in web and non-web environments. It is better suited for serving XHTML/HTML5 at the view layer of web applications, it can process any XML file even in offline environments. It provides an optional module for integration with Spring MVC, so that you can use it as a complete substitute of JSP in your applications made with this technology, even with HTML5. | [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T00:08:05.327",
"Id": "209947",
"Score": "0",
"Tags": null,
"Title": null
} | 209947 |
<p>I need to upload images to a remote HTTP server from a local script. The image name format is <code>{32-char MD5}.jpg</code>. Server directory format is <code>6c/d3/6cd3556deb0da54bca060b4c39479839.jpg</code>. So, for example, if I upload the image called <code>6cd3556deb0da54bca060b4c39479839.jpg</code>, it should be available at <code>https://example.com/6c/d3/6cd3556deb0da54bca060b4c39479839.jpg</code>.</p>
<p>The local script basically does a HTTPS multipart/form-data POST request with the "file" and "password" fields to a remote server (<code>https://example.com/up.php</code>).</p>
<p>Remote server has a PHP script (<code>up.php</code>) which checks if the "password" is correct and then either allows file uploading or disallows it.</p>
<p>Is this script secure? What can go wrong?</p>
<p>This is the code I use on the server. It checks password against SHA-512 hash and then checks if the filename extension is ".jpg".</p>
<pre><code><?php
// Upload Script
//
// You need to post "file" and "password", which is checked
// against using SHA-512
// Check if the password is correct
$password_hash = "128-characters long SHA-512 string here";
if (hash("sha512", $_POST["password"]) != $password_hash) {
http_response_code(403);
echo "403 Access Denied";
exit(1);
}
if(!empty($_FILES["file"])) {
// Check if the filename extension is ".jpg",
// otherwise deny uploading
$file_parts = pathinfo($_FILES["file"]["name"]);
if ($file_parts["extension"] != "jpg") {
http_response_code(500);
echo "Incorrect File Extension";
exit(1);
}
// Filename of the file being uploaded
$filename = $_FILES["file"]["name"];
// Build a directory path
$tmp_a = mb_substr($filename, 0, 2); // First 2 chars of a filename
$tmp_b = mb_substr($filename, 2, 2); // 3 to 4 chars of a filename
$tmp_c = $filename;
$directory = "$tmp_a/$tmp_b";
// Full path to the file including the directory
$full_path = "$directory/$filename";
// If the directory doesn't exist, then create it
if (!file_exists($directory)) {
mkdir($directory, 0755, true);
}
// Upload the file
if (move_uploaded_file($_FILES["file"]["tmp_name"], $full_path)) {
echo "Success";
} else {
http_response_code(500);
echo "Something went wrong";
exit(1);
}
}
</code></pre>
| [] | [
{
"body": "<p>Because you specifically ask about security:</p>\n<ul>\n<li><p>For comparing hashes like SHA, you should use <a href=\"https://secure.php.net/hash_equals\" rel=\"nofollow noreferrer\"><code>hash_equals()</code></a>.</p>\n</li>\n<li><p>If you are requiring the use of a password, you shouldn't use SHA-512. While it's certainly better than MD5, instead use <a href=\"https://en.wikipedia.org/wiki/Bcrypt\" rel=\"nofollow noreferrer\">bcrypt</a>. Bcrypt is <a href=\"https://security.stackexchange.com/q/4781\">heavily recommended</a> for password storage, especially long-term.</p>\n<p>With bcrypt, instead of using <code>hash()</code> and <code>hash_equals()</code>, you would use <a href=\"https://secure.php.net/password_hash\" rel=\"nofollow noreferrer\"><code>password_hash()</code></a> and <a href=\"https://secure.php.net/manual/en/function.password-verify.php\" rel=\"nofollow noreferrer\"><code>password_verify()</code></a>.</p>\n</li>\n<li><p>Should new directories really have read and execute permissions for the group and other users? Likewise, I would check the permissions of the file itself.</p>\n<p>I would personally have the files as <code>0600</code> and directories as <code>0700</code> unless other permissions are needed.</p>\n</li>\n<li><p>Checking the file extension is only helpful for preventing naive false uploads. On Linux and most UNIX-like operating systems, a file extension means very little (if anything). It could be any type of file with a JPEG extension, likewise anything could have a JPEG file extension.</p>\n</li>\n</ul>\n<p>I don't know about the rest of the code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T03:28:11.223",
"Id": "405931",
"Score": "0",
"body": "Thanks for the reply, I have a few questions. 2. I have only one client (only my PC) and I plan to use only one password. It's very long and randomly generated. I connect only over HTTPS. Should I still bother with bcrypt and salt or SHA-512 will be enough? 4. Is checking both the file extension and MIME type of the file will be sufficient?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T04:44:48.850",
"Id": "405934",
"Score": "0",
"body": "Yes, I still think you should use bcrypt. It adds extra security with very little additional work. `password_hash()` handles the salting automatically, so no extra work is needed for that. Even if you're the only client, that doesn't keep others from trying to connect to your remote server. If you're the only client, I would also set up the server's firewall to reflect that (but that's a separate topic). I would just skip the file type checking -- if your password check works then it should be sufficient. MIME types and file extensions can be spoofed and provide no inherent security."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T01:11:06.230",
"Id": "209951",
"ParentId": "209949",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "209951",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T00:33:56.227",
"Id": "209949",
"Score": "4",
"Tags": [
"php",
"security",
"http",
"network-file-transfer"
],
"Title": "PHP remote upload security"
} | 209949 |
<p>I am making a library where I need to generate a unique ID for a type where the ID must be known at compile time. I first relied on the address of a template function, but it proved itself unreliable both with MSVC and Clang on windows.</p>
<p>Then I came up with the address of a static data member inside a template class.</p>
<p>I want to support most use cases as possible here's what comes to my mind:</p>
<ul>
<li>Eager optimizations that would merge the definition of static variables or inline functions</li>
<li>DLL and shared libraries</li>
<li>Link time optimizations</li>
</ul>
<p>My tests were successful, but it wasn't an exotic setup with multiple level <code>dlopen</code> or stuff like that. I'm not an expert with the kind of use case I want to support so it's hard to tell if I can ensure my claims are okay.</p>
<p>My design work by declaring a static data member of type <code>T*</code> inside a template class, then taking its address as the value of the ID.</p>
<pre><code>namespace detail {
/**
* Template class that hold the declaration of the id.
*
* We use the pointer of this id as type id.
*/
template<typename T>
struct type_id_ptr {
// Having a static data member will ensure (I hope) that it has only one address for the whole program.
// Furthermore, the static data member having different types will ensure (I hope) it won't get optimized.
static const T* const id;
};
/**
* Definition of the id.
*/
template<typename T>
const T* const type_id_ptr<T>::id = nullptr;
} // namespace detail
/**
* The type of a type id.
*/
using type_id_t = const void*;
/**
* The function that returns the type id.
*
* It uses the pointer to the static data member of a class template to achieve this.
* Altough the value is not predictible, it's stable (I hope).
*/
template <typename T>
constexpr auto type_id() noexcept -> type_id_t {
return &detail::type_id_ptr<T>::id;
}
</code></pre>
<p>It there any caveats to be aware with this design? </p>
<hr>
<p>Here's some usage of this and motivation for this code:</p>
<pre><code>constexpr auto id_of_int_type = type_id_t{type_id<int>()};
constexpr auto id_of_float_type = type_id_t{type_id<float>()};
static_assert(id_of_int_type != id_of_float_type);
</code></pre>
<p>This can be compiled with <code>-fno-rtti</code>.</p>
<p>Also, it can fully be used at compile time. Here's the equivalent with RTTI:</p>
<pre><code>constexpr auto test = typeid(int); // won't compile
</code></pre>
<p>This code won't compile since <code>typeid</code> cannot be used at compile time. Also, disabling RTTI also disables static RTTI.</p>
<p>The code is useful because it can be used in data structure or to be couple with compile time type erasure.</p>
<pre><code>std::map<type_id_t, void*> anything;
// sorry for raw new
anything[type_id<std::string>()] = new std::string{"hello"};
// compile time example
static auto static_int = int{};
static auto static_double = double{};
// type_id as the keys in a compile time map
constexpr auto anything_compiletime = frozen::unordered_map<type_id_t, void*, 2>{
{type_id<int>(), &static_int},
{type_id<double>(), &static_double}
};
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T00:49:12.430",
"Id": "405783",
"Score": "1",
"body": "This relies on a kernel that does address space layout randomization, along with plenty of other assumptions about how the system allocates memory. Have you done [randomness tests](https://en.wikipedia.org/wiki/Randomness_tests) to see if this entropy pool is reliable on your system (leaving alone other people's systems)? There are [other](https://stackoverflow.com/q/11498304), possibly better, ways to have compile-time randomness. Are you trying to do something like library order randomization (ie since OpenBSD 6), I'm not sure I see the purpose?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T00:53:55.353",
"Id": "405784",
"Score": "3",
"body": "@esote My goal is not to generate compile time randomness, but instead to have a unique value for a given type. I use the ID as key in a `std::map` and a compile time map."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T00:56:43.983",
"Id": "405786",
"Score": "0",
"body": "I misunderstood your purpose, my bad. How about using what's described [here](https://stackoverflow.com/a/9859605)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T01:18:33.367",
"Id": "405787",
"Score": "0",
"body": "@esote It cannot work in a constexpr context as far as I know and it requires RTTI, which is the goal of designing an alternative solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T02:07:51.757",
"Id": "405788",
"Score": "2",
"body": "This really requires a language-lawyer tag. Great question, but unfortunately beyond me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T04:35:36.650",
"Id": "405791",
"Score": "0",
"body": "I'm with @vnp, this isn't really my area of expertise. Maybe this would belong better on Stack Overflow? Either way, I hope you get good answers, this is an interesting topic!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T07:39:24.270",
"Id": "405798",
"Score": "4",
"body": "`typeid` is resolved at compile time, if you don't apply it to a polymorphic type. With a polymorphic type, the type cannot be known at compile time, and thus your solution won't work either. I'm not sure what you're adding here. It would be nice if you could add an example usage where `typeid` doesn't work, but for `type_id` does work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T15:39:50.117",
"Id": "405851",
"Score": "1",
"body": "@CrisLuengo I added some motivation / example of uses. Tell me if this is enough."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T16:21:33.010",
"Id": "405859",
"Score": "0",
"body": "The static assert not compiling has nothing to do with RTTI. `static_assert(std::is_same_v<int, float>)` does compile. The `frozen::unordered_map` is a better example. Not sure why that is useful, but I don't see a quick alternative. `typeid(int).hash_code()` indeed does not work in a `constexpr`, even though `typeid(int)` is evaluated at compile time. And it requires RTTI. I learned something new!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T09:57:48.630",
"Id": "427935",
"Score": "0",
"body": "You say that \"most\" tests were successful; what was *un*successful, and what has been done to mitigate the failures?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T12:48:13.607",
"Id": "427973",
"Score": "0",
"body": "I suggest you edit to delete \"Most of\" from the beginning of that sentence, if I've understood you correctly (so that it reads, \"*My tests were successful ...*\"). It would be even better if you show what you tested - then reviewers might spot gaps in the testing!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-30T13:01:35.893",
"Id": "427977",
"Score": "0",
"body": "@TobySpeight done."
}
] | [
{
"body": "<p>I'm convinced that your design will work correctly. Uniqueness of static variables is guaranteed, and they won't be optimized away if you define and odr-use them (taking the address of a variable is odr-using it). Running it through stack-overflow would be a good idea though, because it will probably catch the eye of one of those 200K+ reputation guru who answer all the tricky language questions.</p>\n\n<p>What I can't understand is what you're trying to achieve with this. The only useful property of this compile-time <code>id</code> is its uniqueness, so it doesn't achieve anything more than the type itself: what is the difference between <code>if (type_id<A>() == type_id<B>())</code> and <code>if (std::is_same_v<A, B>)</code>? I would argue that it achieves a lot less, because types have other useful traits (for a partial but ready-made list, just take a look at the <code>type_traits</code> header in the standard library).</p>\n\n<p>Besides, your id generator isn't truly generic: <code>type_id<int&>()</code> won't compile because a pointer can't point to a reference (thus <code>static const int&* const id</code> is illegal). Of course there's always the possibility to remove the reference, but it means that you'll use <code>type_trait</code>s to make your <code>type_id</code> work -so it underlines that you should use well-established, standard type traits instead of this new compile-time <code>type_id</code>.</p>\n\n<p>I'd suggest, if it is possible, that you post here a larger part of your code,\n containing use cases, and let our collective brain work on the solution of the broader problem.</p>\n\n<hr>\n\n<p>Edit: I understand now better what you want to do. I really like the simplicity of use, and I find the hack very clever. Actually, if it was uglier, limitations like no-references-allowed wouldn't matter much, because everyone would see it as work-around. But since it seems so fluent, it could quickly become pervasive in the code; then limitations matter, all the more when they result in obscure error messages.</p>\n\n<p>Anyway, I believe I would have come up with a less ambitious design, which would also be easier to maintain and understand (this concrete implementation relies on C++17 but it wouldn't be to difficult to implement in previous standards):</p>\n\n<pre><code>#include <iostream>\n#include <vector>\n\ntemplate <typename... Types>\nstruct Type_register{};\n\ntemplate <typename Queried_type>\nconstexpr int type_id(Type_register<>) { static_assert(false, \"You shan't query a type you didn't register first\"); return -1; }\n\ntemplate <typename Queried_type, typename Type, typename... Types>\nconstexpr int type_id(Type_register<Type, Types...>) {\n if constexpr (std::is_same_v<Type, Queried_type>) return 0;\n else return 1 + type_id<Queried_type>(Type_register<Types...>());\n}\n\nint main() {\n Type_register<int, float, char, std::vector<int>, int&> registered_types;\n constexpr auto test1 = type_id<int&>(registered_types);\n constexpr auto test2 = type_id<int*>(registered_types);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T13:46:39.487",
"Id": "405832",
"Score": "1",
"body": "You are correct, references won''t work, but I think I'll simply require that `T` is an object type for now. Thanks! Also, for the usefulness of the code, it allow me using a [`frozen::unordered_map`](https://github.com/serge-sans-paille/frozen) with `type_id_t` as key. RTTI is also quite costly and many disable it, so we can safely replaces most previous use of RTTI without paying heavy cost for classes that don't use it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T15:42:23.233",
"Id": "405853",
"Score": "0",
"body": "I added some examples of uses."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T16:43:56.617",
"Id": "405863",
"Score": "0",
"body": "@GuillaumeRacicot: thanks, I've edited my answer to take the examples into account"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T10:52:34.830",
"Id": "209965",
"ParentId": "209950",
"Score": "12"
}
},
{
"body": "<p>I really liked your design, but for a reason that I'm not sure to understand it actually yields the same value for any type (your static_assert breaks).</p>\n<p>Perhaps it's due to my compiler, Visual Studio 2019, breaking the technique because of its <a href=\"https://docs.microsoft.com/en-us/cpp/build/reference/opt-optimizations?view=vs-2019\" rel=\"nofollow noreferrer\">identical COMDAT folding linker optimization</a>, like in <a href=\"https://codereview.stackexchange.com/a/45079\">this answer from another similar question</a>.</p>\n<p>Basically the compiler falsely assumes that it can throw away template information and do the same logic for any type, so the same value will be returned each time.</p>\n<p>But for instance, <a href=\"https://stackoverflow.com/questions/24252464/creation-of-unique-type-id-with-c11\">this approach</a> works on my machine. I like yours better though! :-(</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T12:01:47.047",
"Id": "488609",
"Score": "2",
"body": "Welcome to Code Review. Can you please explain why you like the code? Your compiler doesn't matter in an answer unless you are asserting there is something wrong with the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-06T15:39:29.347",
"Id": "530026",
"Score": "0",
"body": "\"The code doesn't work as intended in Visual Studio.\" That seems like a very useful review comment to me. :-\\"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-13T04:46:29.647",
"Id": "249303",
"ParentId": "209950",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T00:34:55.180",
"Id": "209950",
"Score": "18",
"Tags": [
"c++",
"c++11"
],
"Title": "Unique compile time (constexpr) type ID without RTTI"
} | 209950 |
<p>This code is a project that I am working on to eventually analyze some images but right now I am purely trying to read an image and convert it to black and white. The input should be either white or something else which would end up as black so it is easy to check for this.</p>
<pre><code>import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
img = mpimg.imread('./Training/Image1.png')
imgplot = plt.imshow(img)
width = img.shape[1]
height = img.shape[0]
def generateArray():
arr = []
for y in range(img.shape[0]):
arr.append([])
for x in range(img.shape[1]):
if img[y][x][0] != 1:
arr[y].append(1)
else:
arr[y].append(0)
return arr
arr = generateArray()
plt.show()
</code></pre>
<p>To be clear, I desire to create an array <code>arr</code> that contains either a 0 if the corresponding pixel in the inputted image is white or 1 if it is anything other than white.</p>
<p>I am somewhat of a beginner with Python but I am confused as to why this code takes so long to run (>19 seconds on my older Mac). Is there something that I am missing that would speed it up significantly?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T14:55:49.983",
"Id": "405835",
"Score": "0",
"body": "\"anything other than white\" - are you sure? This will make most images completely black. The usual thing to do is set the output white if the average of all input channels is above 0.5."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T15:10:15.913",
"Id": "405841",
"Score": "0",
"body": "@Reinderien yes, eventually that is probably my goal but right now all of my images are B/W RGB images so all I have to do is check if the pixel is white."
}
] | [
{
"body": "<p>Yes, there are a few things which can be done to speed up your code.</p>\n\n<p>You create local variables <code>width</code> and <code>height</code>. But then you don't use these variables. Instead you use <code>for x in range(img.shape[1]):</code> which ends up evaluating <code>img.shape[1]</code> a total of <code>height</code> times. Consider that <code>img.shape</code> retrieves the shape array from <code>img</code>, and then accesses the <code>[1]</code> member of that list. Using <code>for x in range(width):</code> doesn't have that overhead.</p>\n\n<p>Consider <code>arr[y].append(_)</code>. Again, this code is looking up in the <code>arr</code> list, the <code>[y]</code> element, and to that retrieved list appending a value. That done once for every pixel. If you kept a handle to the list that you are appending to, you wouldn't have to look it up each time.</p>\n\n<pre><code>def generateArray():\n arr = []\n for y in range(height):\n row = []\n for x in range(width):\n if img[y][x][0] != 1:\n row.append(1)\n else:\n row.append(0)\n arr.append(row)\n return arr\n</code></pre>\n\n<p>The above code should be a little faster.</p>\n\n<p>Appending is a time-consuming operation. If the <code>list</code> is stored as an array, rather than a linked-list, then appending an element will require frequent reallocation of the array capacity, and copying of all of the elements to the new storage area. We can prevent this reallocating and copying by allocating storage for all of the data all at once:</p>\n\n<pre><code>def generateArray():\n arr = [None] * height # Correctly sized array of rows\n for y in range(height):\n row = [0] * width # Correctly sized row, filled with 0's\n for x in range(width):\n if img[y][x][0] != 1:\n row[x] = 1\n arr[y] = row\n return arr\n</code></pre>\n\n<p>Here, the <code>row</code> array starts off with <code>[0, 0, 0, 0, ..., 0, 0, 0]</code> so it is only necessary to set the elements to <code>1</code> where needed.</p>\n\n<hr>\n\n<p>Looping and list lookup can be slow. Consider:</p>\n\n<pre><code> for x in range(width):\n if img[y][x][0] != 1:\n row[x] = 1\n</code></pre>\n\n<p>which loops over all the <code>x</code> values of a row, and for every <code>x</code> value, looks up the row <code>img[y]</code>, and then the pixel in the row <code>img[y][x]</code>, for each pixel in that row, and then accesses the <code>[0]</code> element of that pixel. That's a lot of lookups. If instead we used:</p>\n\n<pre><code> for x, pixel in enumerate(img[y]):\n if pixel[0] != 1:\n row[x] = 1\n</code></pre>\n\n<p>we'd be iterating over the row of pixels, getting their values without the double list lookup.</p>\n\n<p>We could also use list comprehension to build the list. Since each row is of a fixed, known length, the list comprehension can allocate the correctly sized list, and fill in the elements one-at-a-time, without indexing or appending.</p>\n\n<pre><code>def generateArray():\n arr = [None] * height\n for y in range(height):\n arr[y] = [ 1 if pixel[0] != 1 else 0 for pixel in img[y] ]\n return arr\n</code></pre>\n\n<p>That also applies to building each row.</p>\n\n<pre><code>def generateArray():\n return [ [ 1 if pixel[0] != 1 else 0 for pixel in row ] for row in img ]\n</code></pre>\n\n<hr>\n\n<p>The function <code>generateArray()</code> uses a global variable <code>img</code>. It would be better to pass <code>img</code> into the function.</p>\n\n<pre><code>def generateArray(img):\n # code which uses img\n</code></pre>\n\n<hr>\n\n<p><code>generateArray()</code> is a terrible name for the function. Maybe <code>generateMaskFromImage()</code>?</p>\n\n<hr>\n\n<p>The output <code>arr</code> is not being used by your code. If you omitted the line:</p>\n\n<pre><code>arr = generateArray()\n</code></pre>\n\n<p>your code would run much, much faster. ;-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T13:21:21.503",
"Id": "405830",
"Score": "0",
"body": "Absolutely excellent answer! Iโll hold off on accepting this answer for a little while to allow others to answer but this answers everything I was looking for."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T14:49:14.717",
"Id": "405834",
"Score": "1",
"body": "Glad you like the answer. And also glad you arenโt accepting it. You `import numpy` and there is probably a 1-line `numpy` answer that is faster than my solution, possibly clearer to read, and will result in a more memory efficient structure than my double list comprehension answer."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T04:02:05.093",
"Id": "209954",
"ParentId": "209952",
"Score": "6"
}
},
{
"body": "<p>While <a href=\"https://codereview.stackexchange.com/a/209954/98493\">the answer by</a> <a href=\"https://codereview.stackexchange.com/users/100620/ajneufeld\">@AJNeufeld</a> correctly explains the shortcomings regarding normal Python in your code, there is indeed a faster way using <code>numpy</code>.</p>\n\n<p>First, you can build a mask of all pixels that have the value 1:</p>\n\n<pre><code>mask = (img == [1, 1, 1]).all(axis=-1)\n</code></pre>\n\n<p>This mask is already the same as the output of your <code>generateArray</code>.</p>\n\n<p>Executing your function takes about 720 ms ยฑ 17.9 ms on my machine with some image file I had lying around (PNG, 471 x 698 pixels), whereas the generation of this mask is a hundred times faster at 7.37 ms ยฑ 96.6 ยตs.</p>\n\n<p>Now we construct two images, one completely black and one completely white:</p>\n\n<pre><code>black = np.zeros_like(img)\nwhite = np.ones_like(img)\n</code></pre>\n\n<p>And then you can use <a href=\"https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.where.html\" rel=\"nofollow noreferrer\"><code>numpy.where</code></a> to conditionally on the <code>mask</code> use those two images:</p>\n\n<pre><code>img_bw = np.where(mask[:,:,None], white, black)\n</code></pre>\n\n<p>The weird looking slicing with <code>None</code> just makes sure that the mask has the right dimensionality (i.e. three values per pixel, instead of just one).</p>\n\n<p>Putting it all together:</p>\n\n<pre><code>import matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport numpy as np\n\ndef to_bw(img):\n \"\"\"Return a black and white copy of `img`.\n\n Pixels which are white in the original image stay white,\n all other pixels are turned black.\n \"\"\"\n mask = (img == [1, 1, 1]).all(axis=-1)\n black = np.zeros_like(img)\n white = np.ones_like(img)\n return np.where(mask[:,:,None], white, black)\n\nif __name__ == \"__main__\":\n img = mpimg.imread('./Training/Image1.png')\n img_bw = to_bw(img)\n plt.imshow(img_bw)\n plt.show()\n</code></pre>\n\n<p>The whole <code>to_bw</code> function only takes 14 ms ยฑ 324 ยตs.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T15:07:46.697",
"Id": "405839",
"Score": "1",
"body": "a perf comparison would be nice, but other than that, this is a great answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T15:18:22.143",
"Id": "405846",
"Score": "1",
"body": "@OscarSmith: Added some timings, for some random smallish png file using `numpy` to generate the mask is about a hundred times faster."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T16:02:44.047",
"Id": "406003",
"Score": "1",
"body": "The `np.where` and weird looking slicing can be avoided with: `arr = np.zeros_like(img)` and `arr[mask] = [1.0, 1.0, 1.0]`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T17:29:15.783",
"Id": "406023",
"Score": "0",
"body": "@JanKuiken Yes, I had also tried that when I wrote the answer. Interestingly this was about 50% slower with my image."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T15:03:01.737",
"Id": "209979",
"ParentId": "209952",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "209954",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T02:55:26.990",
"Id": "209952",
"Score": "4",
"Tags": [
"python",
"performance"
],
"Title": "Converting an image to black and white"
} | 209952 |
<p>This simple game tries to solve the problem of a game that often end in a lock. It does so by providing the players with Xs and Os with superpowers. With great powers come possible disadvantages. For example the X- can delete an O already on the board, but because the effect contains a random element, it is just as likely to remove one of your own pieces. Therefore, a player must manage risk, in addition to other normal strategies.</p>
<p>The game is a two player game at the moment and the interface is very simple. But it works. A few minor bugs I haven't figured how fix don't affect the gameplay. An example is that the "Player 'x' has won the game" alert fires off before the game piece is drawn on the board. I have also hard coded the coordinates for game winning checks. I am sure there is an easier (algorithmic) way of doing that.</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>var currentPlayer = "O";
var currentType = "Noughts";
var currentAction = "picking";
var coordList = ["0_0", "1_0", "2_0", "0_1", "1_1", "2_1", "0_2", "1_2", "2_2"];
function place(box) {
//Verifies the box is empty
if(box.innerText != "") return;
//insert object current object into box
box.innerText = currentPlayer.substring(0,1);
//rules for alternatives
//+ Battle Rule
if(currentPlayer.substring(1,2) == "+") {
var adjacents = checkAdjecent("full", box.id);
var attackOpt = [];
for(i=0; i<adjacents.length; i++) {
if(document.getElementById(adjacents[i]).innerText != currentPlayer.substring(0,1)
&& document.getElementById(adjacents[i]).innerText != "") {
attackOpt.push(adjacents[i])
}
}
var fightingNumber = Math.floor(Math.random() * 6) + 1;
if(attackOpt.length != 0){
var opponentBox = attackOpt[Math.floor(Math.random() * attackOpt.length)];
if(fightingNumber => 4){
document.getElementById(opponentBox).innerHTML = box.innerText;
}
else {
box.innerText = document.getElementById(opponentBox).innerHTML
}
}
}
//- Remove Rule
if(currentPlayer.substring(1,2) == "-") {
var delOpt = checkAdjecent("full", box.id);
if(delOpt.length != 0){
var delBox = delOpt[Math.floor(Math.random() * delOpt.length)];
document.getElementById(delBox).innerText = "";
}
}
//รท Trade Places Rule
if(currentPlayer.substring(1,2) == "รท") {
var adjacents = checkAdjecent("full", box.id);
var tradeOpt =[];
for(i=0; i<adjacents.length; i++) {
if(document.getElementById(adjacents[i]).innerText != currentPlayer.substring(0,1)
&& document.getElementById(adjacents[i]).innerText != "") {
tradeOpt.push(adjacents[i])
}
}
if(tradeOpt.length != 0){
var tradeBox = tradeOpt[Math.floor(Math.random() * tradeOpt.length)];
var contents = document.getElementById(tradeBox).innerText;
document.getElementById(tradeBox).innerText = box.innerText;
box.innerText = contents;
}
}
//* Dupicate Rule
if(currentPlayer.substring(1,2) == "*") {
var cloneOpt = checkAdjecent("empty", box.id);
if(cloneOpt.length != 0){
var cloneBox = cloneOpt[Math.floor(Math.random() * cloneOpt.length)];
document.getElementById(cloneBox).innerText = box.innerText;
}
}
// alert(byThisBox)
//Flips and prepares for next player
currentType == "Noughts" ? currentType = "Crosses": currentType = "Noughts";
currentType == "Crosses" ? document.getElementById("PlayerChoise").innerHTML = '<input type="button" value="Ready Player Two? (X)" id="PlayerOne" onclick="showOptions()">':
document.getElementById("PlayerChoise").innerHTML = '<input type="button" value="Ready Player One? (O)" id="PlayerOne" onclick="showOptions()">';
//alert(parseInt(box.id.substring(2,3))+3);
//Checks for Winning Conditions
//Box 1
if(box.id == "0_0"){
alert(box.id)
checkGameBoard("0_0","1_0","2_0");
checkGameBoard("0_0","1_1","2_2");
checkGameBoard("0_0","0_1","0_2");
}
//Box 2
if(box.id == "1_0"){
checkGameBoard("0_0","1_0","2_0");
checkGameBoard("1_0","1_1","1_2");
}
//Box 3
if(box.id == "2_0"){
checkGameBoard("0_0","1_0","2_0");
checkGameBoard("2_0","1_1","0_2");
checkGameBoard("2_0","2_1","2_2");
}
//Box 4
if(box.id == "0_1"){
checkGameBoard("0_1","1_1","2_1");
checkGameBoard("0_0","0_1","0_2");
}
//Box 5
if(box.id == "1_1"){
checkGameBoard("0_0","1_1","2_2");
checkGameBoard("1_0","1_1","1_2");
checkGameBoard("2_0","1_1","0_2");
checkGameBoard("0_1","1_1","2_1");
}
//Box 6
if(box.id == "2_1"){
checkGameBoard("0_1","1_1","2_1");
checkGameBoard("2_0","2_1","2_2");
}
//Box 7
if(box.id == "0_2"){
checkGameBoard("0_0","0_1","0_2");
checkGameBoard("0_2","1_1","2_0");
checkGameBoard("0_2","1_2","2_2");
}
//Box 8
if(box.id == "1_2"){
checkGameBoard("0_2","1_2","2_2");
checkGameBoard("1_0","1_1","1_2");
}
//Box 9
if(box.id == "2_2"){
checkGameBoard("0_2","1_2","2_2");
checkGameBoard("2_2","1_1","0_0");
checkGameBoard("2_0","2_1","2_2");
}
currentAction = "picking";
}
function checkAdjecent(status, currentBox) {
adjecentEmpty = [];
adjecentFull = [];
currentX = parseInt(currentBox.substring(0,1));
currentY = parseInt(currentBox.substring(2,3));
if(currentX == 0) {
currentXOptions = [currentX, currentX + 1];
}
if(currentX == 1) {
currentXOptions = [currentX, currentX + 1, currentX -1];
}
if(currentX == 2) {
currentXOptions = [currentX, currentX - 1];
}
if(currentY == 0) {
currentYOptions = [currentY, currentY + 1];
}
if(currentY == 1) {
currentYOptions = [currentY, currentY + 1, currentY -1];
}
if(currentY == 2) {
currentYOptions = [currentY, currentY - 1];
}
adjacentTiles = [];
for(x=0; x<currentXOptions.length; x++){
for(y=0; y<currentYOptions.length; y++){
adjacentTiles.push(currentXOptions[x] + "_" + currentYOptions[y]);
}
}
for(item=0; item<adjacentTiles.length; item++){
if(adjacentTiles[item] != currentBox) {
if(document.getElementById(adjacentTiles[item]).innerText != ""){
adjecentFull.push(adjacentTiles[item])
}
else {
adjecentEmpty.push(adjacentTiles[item])
}
}
}
if(status == "full"){
return adjecentFull;
}
else {
return adjecentEmpty;
}
}
function checkGameBoard(firstCoord,secondCoord,thirdCoord) {
var first = document.getElementById(firstCoord).innerText;
var second = document.getElementById(secondCoord).innerText;
var thrid = document.getElementById(thirdCoord).innerText;
if(first == "") return;
if(first == second && first == thrid){
alert(currentPlayer.substring(0,1) + " is the winner")
location.reload()
// for(i=0; i<coordList; i++) {
// document.getElementById(coordList[i]).innerText = currentPlayer.substring(0,1);
// }
}
}
//+ attacks a random adjacent oppenent peice รท trades places with random adjacent opopnet * places a second copy on empty adjacent square
var noughts = ["O", "O+","O-", "Oรท", "O*"]
var crosses = ["X", "X+", "X-", "Xรท", "X*"]
function showOptions() {
if(currentType == "Noughts") {
document.getElementById("PlayerChoise").innerHTML = "";
for(i=0; i<noughts.length; i++) {
document.getElementById('PlayerChoise').innerHTML += '<input type="button" value="'+ noughts[i] + '" onclick="chooseThis(\'' + noughts[i] + '\')">';
//alert(document.getElementById("Player1").innerHTML)
}
}
else {
document.getElementById("PlayerChoise").innerHTML = "";
for(i=0; i<crosses.length; i++) {
document.getElementById('PlayerChoise').innerHTML += '<input type="button" value="'+ crosses[i] + '" onclick="chooseThis(\'' + crosses[i] + '\')">';
}
}
}
function chooseThis(item) {
if(currentAction == "picking") {
currentPlayer = item;
if(currentType == "Noughts") {
for(index=0; index<noughts.length; index++){
if(noughts[index]== item){
noughts.splice(index,1)
}
}
}
else {
for(index=0; index<crosses.length; index++){
if(crosses[index]== item){
crosses.splice(index,1)
}
}
}
showOptions();
currentAction = "playing";
//alert(noughts);
}
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.home {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
height: 98vh;
padding: 0;
margin: none;
}
.row {
display: flex;
flex-direction: row;
}
.row div {
padding: 10px;
border: 1px solid;
height: 30px;
width: 30px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<title>Noughts and Crosses</title>
<link rel="stylesheet" href="tictac.css">
<script src="xoxo.js"></script>
<meta charset="UTF-8">
</head>
<body>
<div class="home">
<div class="tittle">
<h1>O vs. X</h1>
</div>
<div class="row">
<div id="0_0" onclick="place(this)"></div>
<div id="1_0" onclick="place(this)"></div>
<div id="2_0" onclick="place(this)"></div>
</div>
<div class="row">
<div id="0_1" onclick="place(this)"></div>
<div id="1_1" onclick="place(this)"></div>
<div id="2_1" onclick="place(this)"></div>
</div>
<div class="row">
<div id="0_2" onclick="place(this)"></div>
<div id="1_2" onclick="place(this)"></div>
<div id="2_2" onclick="place(this)"></div>
</div>
<div id="PlayerChoise">
<input type="button" value="Ready Player One? (O)" id="PlayerOne" onclick="showOptions()">
</div>
<div class="instructions">
<p>+ battles a random adjacent opponent (loss will give box to oponent)</p>
<p>- deletes a random adjacent nought or cross</p>
<p>รท trades places with random adjacent opponent</p>
<p>* clones current box into random empty adjacent box</p>
</div>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<h1>Review</h1>\n<p>Welcome to Code review.</p>\n<p>Interesting project, I have never seen Battle TicTacToe so created a review to see how it played. It got a little out of hand.</p>\n<p>I have trimmed quite a lot and I normally do a rewrite of the code. But in this case I found that I had to make major changes, thus making the rewrite completely unrelated to the original code. There is not much to learn from such an extensive rewrite.</p>\n<p>Feel free to ask questions in the comments.</p>\n<h2>Bugs</h2>\n<p>Bugs I found just reading your source. I have not run your code.</p>\n<p>There are potential and hidden bugs in your code. Hidden bugs are bugs that break the intended logic but are not obviously apparent (they don't throw errors)</p>\n<ul>\n<li><strong>ALWAYS</strong> define variables. You have undefined variable <code>i</code> and many more. Using variables without defining them means that they are globals. Though in this example the undefined variable <code>i</code> will not cause you a problem. It would, if you called a function that used <code>i</code> as well.</li>\n</ul>\n<p>Example the following code will lock up the page and require you to close it manually, because the second function <code>doTwoThings</code> will change the global <code>i</code> to 2 when it returns meaning the calling loop will never reach 10</p>\n<pre class=\"lang-js prettyprint-override\"><code>doTenThings();\nfunction doTwoThings() {\n for(i = 0; i < 2; i++){\n console.log("Hi there");\n }\n}\n \nfunction doTenThings() {\n for(i = 0; i < 10; i++){\n doTwoThings()\n }\n}\n</code></pre>\n<p>For learning JavaScript you should make a habit of adding the directive <code>"use strict";</code> as the first line of any javascript file or <code><script></code> tag as it will throw an error when you use an undefined variable. If added to the above example it would not run.</p>\n<ul>\n<li>You have the line <code>if(fightingNumber => 4) {</code> (which is a new one for me). Lucky (or unlucky) it does not create a parsing error because its an arrow function and the statement <code>(fightingNumber => 4) === true</code>. I assume you meant <code>if(fightingNumber >= 4) {</code></li>\n</ul>\n<h2>Style</h2>\n<p>Good code style is the most important attribute of a good programmer. There are a zillion styles out there, and the arguments as to which is best get heated.</p>\n<p>Which is best is up to the individual but there are some style rules that help avoid some common language specific problems.</p>\n<ul>\n<li>Use <code>===</code> rather than <code>==</code> and <code>!==</code> rather than <code>!=</code>.</li>\n<li>Make unchanging variables constants. Eg <code>var coordList = [</code> should be <code>const coordList = [</code></li>\n<li>Don't forget to add semicolon to the end of lines.</li>\n<li>Variables declared as <code>var</code> should be defined at the top of the function. Do not define them as needed. Learn the difference between <code>let</code>, <code>const</code> and <code>var</code> and use the appropriate type of variable.</li>\n<li>Don't add code in the markup (HTML). Eg <code>onclick="place(this)"</code> should be in the JavaScript using <code>addEventListener</code></li>\n</ul>\n<p>There are style rules that make code readable, these are the most argued rules and thus none are definitive</p>\n<ul>\n<li><p>Spaces between operators. examples</p>\n<ul>\n<li><code>a+b</code> as <code>a + b</code></li>\n<li><code>if(a===b){</code> as <code>if (a === b) {</code></li>\n<li><code>[1,2,3,4];</code> as <code>[1, 2, 3, 4];</code></li>\n</ul>\n</li>\n<li><p>Don't use comments to remove code. Remove it if it's no longer needed.</p>\n</li>\n<li><p>If you find yourself prefixing variables with the same name it is a good sign that that prefix should be an object. Eg you have <code>currentPlayer</code>, <code>currentAction</code>, and <code>currentType</code>, is better as <code>const current = {action: "picking", type: "Noughts", player: "O"};</code></p>\n</li>\n<li><p>Use constants to define magic numbers and strings.</p>\n</li>\n<li><p>Define grouped constants by name. E.g. <code>actions = {picking: 1, playing: 2};</code> then you check for the current action with <code>current.action === actions.playing</code></p>\n</li>\n</ul>\n<h2>Consistent style</h2>\n<p>There is one style rule that everyone can at least agree upon, it is by far the most important you must master.</p>\n<p><strong>Be Consistent</strong> If you add spaces between operators, then always do it. If you don't like semicolons, then never use them. Inconsistent style makes looking for bugs so much harder.</p>\n<h2>Code</h2>\n<p>Good code has the following attributes</p>\n<ol>\n<li>Is simple.</li>\n<li>Is granular (many short functions rather than a few long functions).</li>\n<li>Is well organised (related functions keep together, variables declared together, magic numbers as constants),</li>\n<li>Is efficient.</li>\n</ol>\n<p>Most of these relate to readability and maintainability, but an eye for efficiency is also important as users of your software don't see code, they see the end product and slow inefficient code does not make for happy clients and they are always the most important reviewers of your software.</p>\n<p>Many of the following points cross over, they are listed in the most appropriate category.</p>\n<h3>Incorrect language use</h3>\n<ul>\n<li>You incorrectly use the ternary <code>currentType == "Noughts" ? currentType = "Crosses": currentType = "Noughts";</code> should be <code>currentType = currentType == "Noughts" ? "Crosses" : "Noughts";</code></li>\n</ul>\n<h3>Maintainability</h3>\n<ul>\n<li><p>If you have many elements that you assign the same event handler, you should consider a single handler and use the event object to determine which item has been clicked.</p>\n</li>\n<li><p>The function <code>place</code> is way to long and should be reduced into smaller functions.</p>\n</li>\n<li><p>Don't over complicate the system. The game has 9 items and you are indexing them as 9 3 character strings "0_0" to "2_2" which means your code is full of strings. These can be replace via an index, 0-8, that can be used as an array indexes to lookup content as needed. (you can almost half the code size by using index rather than the coord string)</p>\n</li>\n<li><p>If you have a set of <code>if</code> statements that are exclusive, use <code>else</code>. Or if you have large sets of <code>if {} else if {} ... else {}</code> consider using <code>switch</code> statements, or even use lookups.</p>\n</li>\n<li><p>The function <code>checkGameBoard</code> does more than check the board for a win, it handles the win as well. Try to keep a functions role too just one thing. It would be better if it returned the game status and then the calling function can handle the result.</p>\n</li>\n</ul>\n<h3>Performance</h3>\n<ul>\n<li><p>Use <code>element.textContent</code> rather than <code>element.innerText</code> as it is faster and does not force a reflow.</p>\n</li>\n<li><p>DOM queries such as <code>document.getElementById</code> are very sloooowwww.... Locate them once and put them in variables so you don't have to interrogate the DOM each time you need access.</p>\n</li>\n<li><p>Learn to use the DOM API to create and add elements. Using <code>innerHTML</code> is again very sloooowwww....</p>\n</li>\n<li><p>Use CSS style rules to change content. You keep removing and adding option buttons. You should have the button already defined and use a class rule to hide and show them as needed rather than add new ones each move.</p>\n</li>\n<li><p>You can improve efficiency by precalculating information and storing it. For example the function <code>checkAdjecent</code> does a complicated sequence of steps to find locations. These locations can be stored in an array <code>const adjacent = [[1,3], [0,4,2], [1,5], [0,4,6], [1,3,5,7], [2,4,8], [3,7], [4,6,8], [5,7]];</code> where the cells (boxes) are numbered from 0 to 8. Thus the adjacent boxes for box 4 (center) is array <code>adjacent[4]</code>, <code>[1,3,5,7]</code></p>\n</li>\n</ul>\n<h3>Simplify</h3>\n<p>Every extra line, even every character is another point where an error can occur. When looking for bugs, every extra character and line is more check. In a mass of code it is difficult to find typos. To reduce the chance of bugs you should constantly be thinking of ways to reduce the complexity of the code, both logically and in terms of size.</p>\n<p>Some points on simplifying.</p>\n<ul>\n<li><p>You check for a win on each cell (box), however a win is a win no matter which cell is set so you can simplify the win by checking for all wins in the function. Thus you don't need that long list of <code>if(bos == "1_1")</code> just one call and check all winning rows for any win.</p>\n</li>\n<li><p>If you are getting one character from a string you can use brackets to index the character <code>currentPlayer.substring(1,2)</code> becomes <code>currentPlayer[1]</code></p>\n</li>\n<li><p>You generate a random number from 0-6 and add one to it <code>const fightingNumber = Math.random() * 6 + 1 | 0;</code>, then you test if that number is <code>fightingNumber >= 4</code>. You can skip adding one and test if the number is <code>> 2</code>. However if you think about it you are using the random number to pick a 50% chance for one action or the other which can be done with <code>if (Math.random() < 0.5) {</code> or <code>if (Math.random() >= 0.5) {</code></p>\n</li>\n<li><p>You test for not an empty array with <code>if(array.length !== 0)</code> however the number <code>0</code> (and <code>-0</code>) equate to <code>false</code> and other numbers are <code>true</code> so you can do the same with <code>if (array.length) {</code></p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T22:22:38.877",
"Id": "405918",
"Score": "0",
"body": "Ok! So many questions. I guess one at the time. On the **Bug** I am afraid this is the first time that the global and local thing has clicked for me. Am I correct to assume that ANYTIME I do not put var in front of a variable it becomes global? If I did var i = 0; in the precedent line would that work. That is understanding that I should probably use more descriptive variable names."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T22:28:34.873",
"Id": "405919",
"Score": "0",
"body": "@GabeRuiz Yes you can define the as a `var` at the top of the function, you need only `var i;` as it is assigned a value in the for loop, or you can define it as a `let` in the `for` loop `for(let i = 0;...`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T21:07:15.830",
"Id": "210006",
"ParentId": "209959",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T05:26:43.053",
"Id": "209959",
"Score": "4",
"Tags": [
"javascript",
"beginner",
"html",
"tic-tac-toe"
],
"Title": "Battle Noughts vs Crosses in Javascript"
} | 209959 |
<p>Before a job interview, I was asked to create a program that can calculate the score of a bowling game. The full assignment and my code can be viewed on <a href="https://github.com/Noxxys/BowlingScore" rel="noreferrer">my Github</a>. The company told me that this was not good enough, so I would like to get feedback about what's wrong and how to improve it.</p>
<h1>Assignment</h1>
<p><img src="https://i.postimg.cc/v8t6k9qw/Bowling-score.png" alt="bowling score"></p>
<p>The game consists of 10 frames as shown above. In each frame the player has two opportunities to knock down 10 pins. The score for the frame is the total number of pins knocked down, plus bonuses for strikes and spares.</p>
<p>A spare is when the player knocks down all 10 pins in two tries. The bonus for that frame is the number of pins knocked down by the next roll. So in frame 3 above, the score is 10 (the total number knocked down) plus a bonus of 5 (the number of pins knocked down on the next roll.)</p>
<p>A strike is when the player knocks down all 10 pins on his first try. The bonus for that frame is the value of the next two balls rolled.</p>
<p>In the tenth frame a player who rolls a spare or strike is allowed to roll the extra balls to complete the frame. However no more than three balls can be rolled in tenth frame.</p>
<h2>Requirements</h2>
<p>Write a class named โGameโ that has two methods</p>
<p><code>roll(pins : int)</code> is called each time the player rolls a ball. The argument is the number of pins knocked down.</p>
<p><code>score() : int</code> is called only at the very end of the game. It returns the total score for that game.</p>
<h1>My solution</h1>
<p>Program.cs</p>
<pre><code>using System;
namespace BowlingScore
{
class Program
{
static void Main(string[] args)
{
var game = new Game();
game.Roll(1);
game.Roll(4);
game.Roll(4);
game.Roll(5);
game.Roll(6);
game.Roll(4);
game.Roll(5);
game.Roll(5);
game.Roll(10);
game.Roll(0);
game.Roll(1);
game.Roll(7);
game.Roll(3);
game.Roll(6);
game.Roll(4);
game.Roll(10);
game.Roll(2);
game.Roll(8);
game.Roll(6);
Console.WriteLine("Score: " + game.Score());
Console.ReadLine();
}
}
}
</code></pre>
<p>Game.cs</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
namespace BowlingScore
{
internal class Game
{
/// <summary>
/// Maximum number of Frames allowed in this game
/// </summary>
private const int MaxFrameCount = 10;
/// <summary>
/// Number of pins that each Frame should start with
/// </summary>
private const int StartingPinCount = 10;
private readonly List<Frame> frames = new List<Frame>();
private int score;
/// <summary>
/// Register the result of a roll
/// </summary>
/// <param name="knockedDownPins">How many pins have been knocked down</param>
public void Roll(int knockedDownPins)
{
if (frames.Count == MaxFrameCount && frames.Last().IsClosed)
{
throw new InvalidOperationException("You've played enough for today! Consider calling Score()");
}
if (!frames.Any() || frames.Last().IsClosed)
{
var isLastFrame = frames.Count == MaxFrameCount - 1;
frames.Add(new Frame(StartingPinCount, isLastFrame));
}
frames.Last().RegisterRoll(knockedDownPins);
}
/// <summary>
/// Get the total score
/// </summary>
/// <returns>The total score calculated from all Frames</returns>
public int Score()
{
for (var frameIndex = 0; frameIndex < frames.Count; frameIndex++)
{
var frame = frames[frameIndex];
var frameScore = 0;
var bonusScore = 0;
var isStrike = false;
// cap the roll index to 2 to avoid over-counting points if the last frame has bonus rolls
var maxRollIndex = frame.RollResults.Count < 2 ? frame.RollResults.Count : 2;
for (var rollIndex = 0; rollIndex < maxRollIndex; rollIndex++)
{
var result = frame.RollResults[rollIndex];
frameScore += result;
// calculate bonus score for a strike
if (result == StartingPinCount)
{
isStrike = true;
// look 2 rolls ahead
bonusScore += CalculateBonusScore(frameIndex, rollIndex, 2);
break;
}
}
// calculate bonus score for a spare
if (!isStrike && frameScore == StartingPinCount)
{
// look 1 roll ahead
bonusScore += CalculateBonusScore(frameIndex, maxRollIndex - 1, 1);
}
score += frameScore + bonusScore;
}
return score;
}
/// <summary>
/// Recursive function to calculate the bonus score of the next X rolls
/// </summary>
/// <param name="frameIndex">Index of the current frame</param>
/// <param name="rollIndex">Index of the current roll</param>
/// <param name="rollCount">How many rolls to look ahead</param>
/// <returns>The amount of bonus score calculated from the next X rolls</returns>
private int CalculateBonusScore(int frameIndex, int rollIndex, int rollCount)
{
if (rollCount == 0)
{
return 0;
}
var bonusPoints = 0;
// add the next roll in the same frame, if any
if (frames[frameIndex].RollResults.Count > rollIndex + 1)
{
bonusPoints += frames[frameIndex].RollResults[rollIndex + 1];
bonusPoints += CalculateBonusScore(frameIndex, rollIndex + 1, rollCount - 1);
}
else
{
// add the first roll of the next frame, if any
if (frames.Count > frameIndex + 1)
{
bonusPoints += frames[frameIndex + 1].RollResults[0];
bonusPoints += CalculateBonusScore(frameIndex + 1, 0, rollCount - 1);
}
}
return bonusPoints;
}
}
}
</code></pre>
<p>Frame.cs</p>
<pre><code>using System;
using System.Collections.Generic;
namespace BowlingScore
{
internal class Frame
{
/// <summary>
/// How many pins have been knocked down in each roll
/// </summary>
public List<int> RollResults { get; } = new List<int>();
/// <summary>
/// No more rolls can be registered on a closed Frame
/// </summary>
public bool IsClosed => !isLastFrame && standingPins == 0 ||
!isLastFrame && RollResults.Count == 2 ||
RollResults.Count == 3;
private int standingPins;
private readonly int startingPinCount;
private readonly bool isLastFrame;
private bool extraRollAllowed;
/// <summary>
/// Create a new Frame
/// </summary>
/// <param name="startingPinCount">Number of pins that the Frame should start with</param>
/// <param name="isLastFrame">Special rules apply on the last frame</param>
public Frame(int startingPinCount, bool isLastFrame = false)
{
this.startingPinCount = startingPinCount;
standingPins = startingPinCount;
this.isLastFrame = isLastFrame;
}
/// <summary>
/// Register the result of a roll
/// </summary>
/// <param name="knockedDownPins">How many pins have been knocked down</param>
public void RegisterRoll(int knockedDownPins)
{
ValidateRoll(knockedDownPins);
RollResults.Add(knockedDownPins);
standingPins -= knockedDownPins;
ResetPinsIfNecessary();
}
private void ResetPinsIfNecessary()
{
if (isLastFrame && standingPins == 0)
{
standingPins = startingPinCount;
extraRollAllowed = true;
}
}
private void ValidateRoll(int knockedDownPins)
{
if (standingPins == 0)
{
throw new InvalidOperationException("Can't roll when there are no standing pins");
}
if (!isLastFrame && RollResults.Count == 2 ||
isLastFrame && RollResults.Count == 2 && !extraRollAllowed ||
RollResults.Count > 2)
{
throw new InvalidOperationException($"Can't register more than {RollResults.Count} rolls in this frame");
}
if (knockedDownPins < 0 || knockedDownPins > standingPins)
{
throw new InvalidOperationException($"Can't knock down {knockedDownPins} while there are only {standingPins} standing pins");
}
}
}
}
</code></pre>
| [] | [
{
"body": "<blockquote>\n <p>The company told me that this was not good enough, so I would like to get feedback about what's wrong and how to improve it.</p>\n</blockquote>\n\n<p>Fundamentally, you have to ask them. We can give your our thoughts, but it might come down to company culture / style.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> class Program\n {\n static void Main(string[] args)\n {\n var game = new Game();\n\n game.Roll(1);\n ...\n game.Roll(6);\n\n Console.WriteLine(\"Score: \" + game.Score());\n</code></pre>\n</blockquote>\n\n<p>To be honest, I'd prefer to submit the class with no tests whatsoever than with this \"test\". It's very long-winded (why not use a loop for the rolls?) and doesn't even compare the observed score with the expected score.</p>\n\n<p>Better, though, would be to provide a test suite using a proper test framework (NUnit, Microsoft.VisualStudio.TestTools.UnitTesting, ...) with a series of tests to cover the corner cases and comments to show what corner cases they cover: at least the exceptions, scenarios with and without an extra roll in the last frame, and the maximum score.</p>\n\n<hr>\n\n<p>My personal opinion is that the code is very complicated for the task it does. The scoring could be implemented without a separate method to calculate the bonus and with a single loop: it just needs variables to indicate whether the previous ball was a normal throw, a spare, or a strike; and whether the ball before that was a strike or not. Then on the basis of those variables you multiply the score for the current ball by 1, 2, or 3. If the person assessing the code was an architecture astronaut you're probably fine; if they were an optimisation obsessive then this might count quite heavily in their assessment.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public List<int> RollResults { get; } = new List<int>();\n</code></pre>\n</blockquote>\n\n<p>It's a read-only property which can be freely modified. Prefer to expose <code>IReadOnlyList<T></code> so that all modification has to be done by calling methods on the class.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> if (!isLastFrame && RollResults.Count == 2 || \n isLastFrame && RollResults.Count == 2 && !extraRollAllowed ||\n RollResults.Count > 2)\n {\n throw new InvalidOperationException($\"Can't register more than {RollResults.Count} rolls in this frame\");\n }\n</code></pre>\n</blockquote>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a>. The condition should be <code>if (IsClosed)</code> - and if it isn't, I suspect a bug.</p>\n\n<hr>\n\n<p>There are other things I would do differently, but that's questions of style and shouldn't matter in an interview unless you've been given a style document to follow. The first two points are my best guess as to why the company rejected the code. The other two are minor points - they might count against you in comparison against another candidate, but I wouldn't expect them to disqualify you.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T11:11:04.367",
"Id": "209967",
"ParentId": "209960",
"Score": "3"
}
},
{
"body": "<p>The code is enormously bloated and complicated for what it does. The score of each frame can be calculated in a simple loop, nicely encapsulated in a static method or extension method.</p>\n\n<pre><code>public static IEnumerable<int> Scores(this IList<int> pins)\n{\n // Walk the list in steps of two rolls (= one frame)\n for (int i = 0; i + 1 < pins.Count; i += 2)\n {\n // Neither strike nor spare\n if (pins[i] + pins[i + 1] < 10)\n {\n yield return pins[i] + pins[i + 1];\n continue;\n }\n\n // Score can only be determined if third roll is available\n if (i + 2 >= pins.Count)\n yield break;\n\n yield return pins[i] + pins[i + 1] + pins[i + 2];\n\n // In case of strike, advance only by one\n if (pins[i] == 10)\n i--;\n }\n}\n</code></pre>\n\n<p>The required interface can then be implemented in a small wrapper class.</p>\n\n<pre><code>public class Bowling\n{\n private List<int> pins = new List<int>();\n\n public void Roll(int n) => pins.Add(n);\n\n public int Score() => pins.Scores().Take(10).Sum();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T11:45:39.453",
"Id": "209970",
"ParentId": "209960",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T07:35:56.473",
"Id": "209960",
"Score": "7",
"Tags": [
"c#",
"interview-questions"
],
"Title": "Calculate the score of a bowling game"
} | 209960 |
<p>I'm in the unfortunate position to where I have to create files and folders programmatically that have to work with a legacy system. In this process, the file and folder names have to be heavily sanitized.</p>
<p>The POST requests that create the files and folders are sent from the client in javascript, while the actual creation happens on a server. For this, I wrote a function used to display to users what their input folder or file names will look like and to sanitize their input to work with the legacy system.</p>
<p>I've let this run over quite a few test cases including irregular file names that broke the legacy system prior and it seems to work fine. I'm curious about what could be improved though, especially with respect to readability and extensibility.</p>
<pre><code>/**
* @description sanitizes a folder or file name to work with #name of legacy system
* @author me
* @param {string} object_name
* @param {string} mode "file" / "folder"
*/
function sanitizeFolderOrFile(object_name, mode) {
if (mode !== 'file' && mode !== 'folder') {
return false;
}
let suffix = '';
let retvar = '';
if (mode === 'file') {
suffix = object_name.split('.').pop();
retvar = object_name.replace(new RegExp('(\.' + suffix + ')', 'g'), '');
} else if (mode === 'folder') {
retvar = object_name;
}
// values to replace
const replace_values = [{
value: '+\\&',
replacement: 'u'
}, {
value: 'รคร',
replacement: 'ae'
}, {
value: 'รถร',
replacement: 'oe'
}, {
value: 'รผร',
replacement: 'ue'
}, {
value: 'ร',
replacement: 'ss'
}, {
value: ' \\`\\ยด\\?\\(\\)\\[\\]\\{\\}\\/\\\\$\\ยง\\"\\\'\\!\\=\\-\\.\\,\\;\\:<>\\|\\^\\ยฐ\\*\\+\\~\\%',
replacement: '_'
}];
replace_values.forEach(function(element) {
retvar = retvar.replace(new RegExp('([' + element.value + '])', 'g'), element.replacement);
});
retvar = retvar.toLowerCase();
if (mode === 'file') {
retvar += '.' + suffix;
}
return retvar;
}
</code></pre>
| [] | [
{
"body": "<p>I think you need separate some parts of code.</p>\n\n<ol>\n<li><p>If you use ES5 with Decorators you can todo general determination Errors, and add for instance, function-condition in this Decorator.</p></li>\n<li><p>You can apply mechanismes <a href=\"https://refactoring.guru/extract-method\" rel=\"nofollow noreferrer\">Extract Methods</a>, <a href=\"https://refactoring.guru/refactoring/techniques/simplifying-conditional-expressions\" rel=\"nofollow noreferrer\">Simplifying Conditional Expressions</a> and <a href=\"https://refactoring.guru/replace-magic-number-with-symbolic-constant\" rel=\"nofollow noreferrer\">Replace Magic Number with Symbolic Constant</a> from <code>sanitizeFolderOrFile</code>.</p></li>\n</ol>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>/* Decorator file */\n function determinationError(condition) {\n return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {\n const method = descriptor.value;\n descriptor.value = function () {\n try {\n condition.apply(this, arguments);\n method.apply(this, arguments);\n }\n catch(e) {\n console.error(e.message);\n }\n };\n return descriptor;\n };\n}\n\n//export determinationError;\n\n/*enum MODE file */\n const MODE = {\n FILE: 'file',\n folder: 'folder'\n };\n\n//export MODE;\n\n\n\n/*file sanitizeFolderOrFile */\n\n\n//determinationError = require('determinationError'); // require our decorator file\n//MODE = require('MODE'); // require our MODE file\n\nfunction isFileOrFolderCondition(mode) {\n if (mode !== MODE.FILE && mode !== MODE.FOLDER) {\n throw new Error('It is not file or folder') ;\n }\n}\n\n const replaceValues = [{\n value: '+\\\\&',\n replacement: 'u'\n }, {\n value: 'รคร',\n replacement: 'ae'\n }, {\n value: 'รถร',\n replacement: 'oe'\n }, {\n value: 'รผร',\n replacement: 'ue'\n }, {\n value: 'ร',\n replacement: 'ss'\n }, {\n value: ' \\\\`\\\\ยด\\\\?\\\\(\\\\)\\\\[\\\\]\\\\{\\\\}\\\\/\\\\\\\\$\\\\ยง\\\\\"\\\\\\'\\\\!\\\\=\\\\-\\\\.\\\\,\\\\;\\\\:<>\\\\|\\\\^\\\\ยฐ\\\\*\\\\+\\\\~\\\\%',\n replacement: '_'\n }];\n\nfunction replacerAndToLowerCase(name) {\n replaceValues.forEach(function(element) {\n name = name.replace(new RegExp('([' + element.value + '])', 'g'), element.replacement);\n });\n\n return name.toLowerCase();\n}\n\nfunction sanitizeFile(fullName) {\n const ext = fullName.split('.').pop();\n let name = fullName.replace(new RegExp('(\\.' + ext + ')', 'g'), '');\n name = replacerAndToLowerCase(name);\n \n return `${name}.${ext}`;\n}\n\n\nfunction sanitizeFolder(fullName) {\n return replacerAndToLowerCase(fullName);\n}\n\n\n//@determinationError(isFileOrFolderCondition)\nfunction sanitize(mode, name) {\n if (mode === MODE.FILE) {\n return sanitizeFile(name);\n }\n \n return sanitizeFolder(name);\n}\n\n\nconst fileName = sanitize(MODE.FILE, 'TeSรครtTE.txt');\nconsole.log('fileName', fileName);\n\nconst folderName = sanitize(MODE.FOLDER, 'SuperFolder???????');\nconsole.log('folderName', folderName);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<hr>\n\n<p><em>I added comment in Snippet when you can add Decorator and separate on files</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T11:46:35.920",
"Id": "405812",
"Score": "0",
"body": "is \"file\" still considered a magic number? Similar existing functions in our env use numbers like 1 for \"file\" and 2 for \"folder\" for modes, for instance. I assumed that naming them what they do would kill the magic number source of badness"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T12:40:36.887",
"Id": "405815",
"Score": "0",
"body": "Everywhere where simple types are used is Magic Constant. You are comparing Something with Constant. `mode === \"file\"` - file you have to wrap in constant const FILE = 'file'."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T12:45:35.187",
"Id": "405819",
"Score": "0",
"body": "Magic Constant - is number, string, bool. Problems arise when you change mode for example \"FILEs\" , \"FOLDERs\" and you have another constants. And Everywhere when you use \"file\" and \"folder\" you must change to \"FILEs\" , \"FOLDERs\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T12:49:25.167",
"Id": "405821",
"Score": "0",
"body": "And if your project has \"file\" and \"folder\" as string you will be have lot of places where you need change this. However, if you add constant FILE, FOLDER you will change only once place"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T12:51:22.437",
"Id": "405822",
"Score": "0",
"body": "Please, confirm that you understand?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T12:57:51.953",
"Id": "405825",
"Score": "0",
"body": "Wouldn't that then mean that even your implementation of it is incomplete, e.g wouldn't the function call need to be `sanitize(MODE.FILE, 'TeSรครtTE.txt');` strictly speaking? I mean, if I only use the enum type modes within the function itself, then if they ever change every function call will still have to be modified, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T13:05:24.557",
"Id": "405827",
"Score": "0",
"body": "Yes of course , you right `sanitize(MODE.FILE, 'TeSรครtTE.txt');` `sanitize(MODE.FOLDER, 'TeSรครtTE.txt');` will be more right way"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T13:07:25.230",
"Id": "405828",
"Score": "0",
"body": "Thanks, I changed call `sanitize` method"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T13:26:15.230",
"Id": "405831",
"Score": "0",
"body": "One more important note. inside `sanitizeFolder` only one method call. It is smell [Middle Man](https://refactoring.guru/smells/middle-man). But currently situation we need this delegate for consistency `sanitize` method (sanitizeFile, sanitizeFolder)."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T11:12:26.147",
"Id": "209968",
"ParentId": "209961",
"Score": "2"
}
},
{
"body": "<h2>Style</h2>\n<ul>\n<li>Javascript uses camelCase for naming. Don't use snake_case.</li>\n<li>Use functions to reduce repetition.</li>\n<li>Use the shortest or simplest form. Eg you define RegExp as strings and then create them when needed. It is simpler to define the RegExp directly, saving the need to add the extra control character delimiter <code>\\\\</code>.</li>\n<li>Don't duplicate code. You test for <code>mode</code> not equal to <code>"file"</code> and <code>"folder"</code> then you test for mode equal to <code>"file"</code> then <code>"folder"</code> where a final else clause will do the first test without extra overhead. However I would wonder why the function is called with an unknown mode?</li>\n<li>Use arrow functions when you can to reduce code size and thus increasing readability.</li>\n<li>Don't assign variables with unused content that will be replaced further in the code. Eg <code>let suffix = "";</code> should be <code>let suffix;</code>.</li>\n<li>Learn to use the correct scope variable. In function scope you should use <code>var</code> not <code>let</code> and should be defined at the top of the function</li>\n<li>In JavaScript for the browser an element is a very specific type of object, generally when iterating a nondescript array of items we call the item <code>item</code>, using <code>element</code> is misrepresenting what it is.</li>\n</ul>\n<h2>Code</h2>\n<ul>\n<li>You say legacy, but there is no clue as to which system you are converting to.</li>\n<li>Your code comments indicate that <code>mode</code> is <code>* @param {string} mode "file" / "folder"</code> as a string yet no indication that it can be another value and such value would modify the return type.</li>\n<li>The documentation comments give no return value and type. This is a particularly glaring omission as the return type can be two different types, a <code>string</code> or a <code>boolean</code>. Parcial, or incorrect documentation is worse than no documentation.</li>\n<li>The differing return types based on <code>mode</code> is very problematic, and means that you need to add code to the calling function to test the return. This means that there is an indirect duplication of the test, in the function and the calling function. You may as well have the calling function determine if it should call the function in the first place and hive the function only return a fixed type.</li>\n<li>Convert to the file/dir name to lowercase as first step.</li>\n<li>Is the extension to keep its case?? I would think not (though this is a guess on my part)</li>\n<li>There is no need to add the grouping to the regExp's <code>\\()\\</code> as you don't use them.</li>\n<li>There is no need to create a new variable to hold <code>object_name</code>, you can use it (the argument) rather than create a new one.</li>\n<li>When you strip the extension (suffix) from the filename, you use a global regExp. It is possible for filenames to include many <code>"."</code> eg the filename <code>"myfile.common.com"</code> would be replaced with <code>"myfilemon"</code> rather than <code>"myfile.common"</code>. You could store the split name and join it after popping the extension, or just trim the string.</li>\n<li>Names.\n<ul>\n<li><code>object_name</code> is a bit vague, its a filename or directory name, <code>name</code> is ma ybe a better name?</li>\n<li><code>mode</code> a little odd, maybe <code>type</code> is a better description?</li>\n<li><code>suffix</code> though not incorrect the more common name is <code>fileExtension</code>, <code>fileExt</code>, <code>extension</code> or <code>ext</code>.</li>\n<li><code>retvar</code> Should be <code>retVar</code> (camelCase) but that said it is a bad name. It is a <code>var</code> (well technically a <code>let</code>) so you have included a obvious implied attribute of the variable. Generally for non specific return variable we use <code>result</code> or in this case may be <code>sanitizedName</code> would be better? (or see example where <code>name</code> is used to hold the result)</li>\n<li><code>element</code> is a DOM object, can be confusing so maybe a better name is <code>item</code>?</li>\n</ul>\n</li>\n</ul>\n<h2>The rewrite</h2>\n<p>Addressing most of the points above the rewrite only returns a string (<code>mode</code> now called <code>type</code> is <code>"file"</code> or it defaults as <code>"folder"</code>). Converts the extension to lowercase. Use RegExp literals rather than create them via instantiation. Use arrays to hold replacement arguments so that the spread operator can be used to call replace.</p>\n<p>Please Note that I had to remove many <code>/</code> from the reg expressions, I did not test the edited regExps so the last one may have errors regarding what it replaces.</p>\n<pre><code>/**\n * @description Sanitizes a folder or file name to work with #name of legacy system\n * Legacy system unknown\n * @author BM67\n * @param {String} name The string to sanitize\n * @param {String} type Optional "file" or default is assumed "folder"\n * @return {String} The sanitized name\n */ \n\nfunction sanitizeFolderOrFile(name, type) { // type is "file" all else is "folder"\n var ext = ""; // adds the default at return if type is folder\n name = name.toLowerCase(); // move below following statement if case must be maintained\n if (type === "file") {\n const parts = name.split(".");\n ext = "." + parts.pop();\n name = parts.join("."); // Could join with "_" as you replace it later\n } \n [[/[+\\&]/g, "u"], [/รค/g, "ae"], [/รถ/g, "oe"], [/รผ/g, "ue"], [/ร/g, "ss"],\n [/[ \\`\\ยด\\?\\(\\)\\[\\]\\{\\}\\/\\\\$\\ยง\\"\\'\\!\\=\\-\\.\\,\\;\\:<>\\|\\^\\ยฐ\\*\\+\\~\\%]/g, "_"]\n ].forEach(item => name = name.replace(...item));\n return name + ext;\n}\n</code></pre>\n<p>Or for those that like it spaced out (Note also keep extension case)</p>\n<pre><code>function sanitizeFolderOrFile(name, type) {\n var ext = "";\n if (type === "file") {\n const parts = name.split(".");\n ext = "." + parts.pop();\n name = parts.join("_"); \n }\n name = name.toLowerCase();\n [\n [/[+\\&]/g, "u"], \n [/รค/g, "ae"], \n [/รถ/g, "oe"], \n [/รผ/g, "ue"], \n [/ร/g, "ss"],\n [/[ \\`\\ยด\\?\\(\\)\\[\\]\\{\\}\\/\\\\$\\ยง\\"\\'\\!\\=\\-\\.\\,\\;\\:<>\\|\\^\\ยฐ\\*\\+\\~\\%]/g, "_"]\n ].forEach(item => name = name.replace(...item));\n return name + ext;\n}\n</code></pre>\n<p>And the ES5 version</p>\n<pre><code>function sanitizeFolderOrFile(name, type) {\n var parts, ext = "";\n if (type === "file") {\n parts = name.split(".");\n ext = "." + parts.pop();\n name = parts.join("_"); \n }\n name = name.toLowerCase();\n [\n [/[+\\&]/g, "u"], \n [/รค/g, "ae"], \n [/รถ/g, "oe"], \n [/รผ/g, "ue"], \n [/ร/g, "ss"],\n [/[ \\`\\ยด\\?\\(\\)\\[\\]\\{\\}\\/\\\\$\\ยง\\"\\'\\!\\=\\-\\.\\,\\;\\:<>\\|\\^\\ยฐ\\*\\+\\~\\%]/g, "_"]\n ].forEach(item => name = name.replace(item[0], item[1]));\n return name + ext;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T15:16:13.453",
"Id": "405844",
"Score": "0",
"body": "Thanks for your review. Adressing your first comment about casing, I'm working within a project framework where `snake_case` is to be used for all variables while `camelCase` is reserved for functions. My project lead also told me to curb use of `var` and use `let` or `const` exclusively instead. As for the legacy system, it's a ms access application that is not extensible anymore but uses file and folder names in eval type statements (constructed command line calls) without escaping them at all, so any kind of special chars in names break it in one way or another."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T15:19:45.883",
"Id": "405847",
"Score": "0",
"body": "And yes, the extension needs to keep its case. The code could probably benefit from a comment stressing that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T15:25:25.897",
"Id": "405848",
"Score": "1",
"body": "@Magisch Well you must follow the team directives. Though snake_case in javascript is not idiomatic, and tenicaly function names are variables so the naming based on variable type is not a good thing (IMHO). Though there are arguments for"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T15:08:26.363",
"Id": "209980",
"ParentId": "209961",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T08:54:57.877",
"Id": "209961",
"Score": "4",
"Tags": [
"javascript",
"regex"
],
"Title": "Sanitize file or folder names to work with a legacy system"
} | 209961 |
<p>Given a linked list and two positions <code>m</code> and <code>n</code>. The task is to rotate the sub-list from position <code>m</code> to <code>n</code>, to the right by <code>k</code> places. <a href="https://www.geeksforgeeks.org/rotate-the-sub-list-of-a-linked-list-from-position-m-to-n-to-the-right-by-k-places/" rel="nofollow noreferrer">(link to GeeksforGeeks)</a></p>
<h2>Examples</h2>
<p><strong>Input:</strong>
list 1->2->3->4->5->6, m = 2, n = 5, k = 2</p>
<p><strong>Output:</strong> 1->4->5->2->3->6</p>
<p><strong>Explanation:</strong> Rotate the sub-list 2 3 4 5 towards right 2 times
then the modified list is: 1 4 5 2 3 6</p>
<p><strong>Input:</strong> list = 20->45->32->34->22->28, m = 3, n = 6, k = 3</p>
<p><strong>Output:</strong> 20->45->34->22->28->32</p>
<p><strong>Explanation:</strong> Rotate the sub-list 32 34 22 28 towards right 3 times
then the modified list is: 20 45 34 22 28 32</p>
<pre><code>// Rotate the sub-list of a linked list from position M to N to the right by K places
#include <iostream>
using namespace std;
// structure of the node in the linked list
struct Node {
int data;
Node* next;
};
// inserting at the beggining
void push( Node **head, int data ) {
Node *newNode = new Node();
newNode->data = data;
if((*head) == NULL) {
(*head) = newNode;
return;
}
Node *temp = (*head);
while(temp->next != NULL)
temp = temp->next;
temp->next = newNode;
newNode->next = NULL;
}
// display
void display(Node *head) {
cout << "The list : \t";
while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
}
// Rotate the linked list by k
void rotate(Node *head, int m, int n, int k) {
Node *temp1 = head ;
Node *temp3 = NULL, *ref = NULL, *last = NULL;
for (int i = 0; i < m - 1 ; i++)
temp1 = temp1->next;
ref = temp1->next;
temp3 = ref ;
for (int i = 0; i < n - m; i++)
temp3 = temp3->next;
last = temp3->next;
temp3->next = ref ;
k = k%(n - m + 1);
for(int i = 0; i < k; i++) {
temp3 = ref;
ref = ref->next;
}
temp3->next = last;
// if the starting point is not 1st element
if (m == 0)
head = ref;
else
temp1->next = ref;
display(head);
}
// Driver function
int main() {
Node *head = NULL;
push(&head, 1);
push(&head, 2);
push(&head, 3);
push(&head, 4);
push(&head, 5);
push(&head, 6);
push(&head, 7);
display(head);
cout << "\n\n";
int m, n, k;
cout << "m, n, k = \t";
cin >> m >> n >> k ;
rotate(head, m - 1, n - 1, k);
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T12:38:04.810",
"Id": "406094",
"Score": "0",
"body": "Welcome to Code Review! 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>I see a number of things that may help you improve your program.</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. </p>\n\n<h2>Omit <code>return 0</code></h2>\n\n<p>When a C++ program reaches the end of <code>main</code> the compiler will automatically generate code to return 0, so there is no reason to put <code>return 0;</code> explicitly at the end of <code>main</code>.</p>\n\n<h2>Make sure the comments don't mislead</h2>\n\n<p>The code currently includes this comment and function:</p>\n\n<pre><code>// inserting at the beggining\nvoid push( Node **head, int data ) {\n</code></pre>\n\n<p>However, that comment is false (and spelled incorrectly). In fact, the data is appended to the <em>end</em> of the linked list. For that reason, I'd suggest changing the name to <code>append</code>.</p>\n\n<h2>Use <code>nullptr</code> rather than <code>NULL</code></h2>\n\n<p>Modern C++ uses <code>nullptr</code> rather than <code>NULL</code>. See <a href=\"http://stackoverflow.com/questions/1282295/what-exactly-is-nullptr/1283623#1283623\">this answer</a> for why and how it's useful. </p>\n\n<h2>Return something useful from functions</h2>\n\n<p>It is not very useful to have every function return <code>void</code>. Instead, I'd suggest that <code>push</code> (now renamed to <code>append</code> per previous suggestion) could return a pointer to the head of the list. Here's one way to write that:</p>\n\n<pre><code>// append data to end of linked list\nNode* append(Node *head, int data) {\n auto newNode = new Node{data, nullptr};\n if (head == nullptr) {\n return newNode;\n }\n auto temp{head};\n while (temp->next) {\n temp = temp->next; \n }\n temp->next = newNode;\n return head;\n}\n</code></pre>\n\n<h2>Don't leak memory</h2>\n\n<p>This code calls <code>new</code> but never <code>delete</code>. This means that the routines are leaking memory. It would be much better to get into the habit of using <code>delete</code> for each call to <code>new</code> and then assuring that you don't leak memory. </p>\n\n<h2>Use objects</h2>\n\n<p>The <code>Node</code> object is a decent start, but I'd recommend and actual linked list object to better take care of memory management and node initialization.</p>\n\n<h2>Sanitize user input</h2>\n\n<p>If the user enters a negative number or a number that's larger than the array, or numbers that are not in the right order, bad things happen in the current program. In general, it's better to be very wary of user input and test for and handle any bad input.</p>\n\n<h2>Fix the bug</h2>\n\n<p>If the subsequence includes the first node, the output is incorrect. That's a bug.</p>\n\n<h2>Rethink the problem</h2>\n\n<p>There are two essential parts to the algorithm. First, we identify the subsequence and then we do the rotation. With some thought, you can figure out either 0 or 3 <code>next</code> links will need to be changed. We can immediately understand that if <span class=\"math-container\">\\$n - m + 1 = k \\mod (n-m+1)\\$</span> then no links need to change and we're done. Otherwise 3 links need to change. Let's number each of the nodes, starting from 1. So the first node is <span class=\"math-container\">\\$N[1]\\$</span>, and the second is <span class=\"math-container\">\\$N[2]\\$</span>, etc.</p>\n\n<ul>\n<li>Now the first node that needs to be altered is <span class=\"math-container\">\\$N[m-1]\\$</span>. It needs to point to <span class=\"math-container\">\\$N[m + k]\\$</span>.</li>\n<li>Next <span class=\"math-container\">\\$N[n]\\$</span> (the last node of the subset) points to <span class=\"math-container\">\\$N[m]\\$</span> (the first of the subset).</li>\n<li>Then <span class=\"math-container\">\\$N[m + k - 1]\\$</span> must point to <span class=\"math-container\">\\$N[n+1]\\$</span></li>\n</ul>\n\n<p>With that in mind, it should be apparent that only a <em>single pass</em> through the data structure is needed with only two temporary pointers. I'll leave it to you to write the code for that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T09:18:23.757",
"Id": "405956",
"Score": "0",
"body": "thank you very much for the detailed response, i was able to learn many new things."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T13:01:10.753",
"Id": "405978",
"Score": "0",
"body": "Iโm glad you found it helpful! I enjoyed thinking about the problem."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T19:08:16.050",
"Id": "209998",
"ParentId": "209962",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "209998",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T09:58:00.127",
"Id": "209962",
"Score": "3",
"Tags": [
"c++",
"programming-challenge",
"linked-list"
],
"Title": "Rotate the sub-list of a linked list from position M to N to the right by K places"
} | 209962 |
<p>I have been learning Java for the past two months, and started writing this task about simulating Bank and BankAccount to practise a bit of OOP and exception handling. Problem is I am not confident that the solution is ok. It is working fine, I just think it could be written better, but since I am a novice, I would really appreciate some advice.
I cannot yet grasp the difference when I should return true/false on success/failure of a method and when to throw an exception.</p>
<blockquote>
<p><strong>Bank account</strong>
Make a BankAccount class.
It should have unique number and store information about its and owner - First, Last name and age.</p>
<p>It should store information about the balance of the account, the interest of the account and the type of the interest (complex and simple year interest).</p>
<p>If someone tries to create a bank account with invalid information an appropriate exception should be thrown.</p>
<p>It should support add, withdraw, transfer and history operations.</p>
<p>When the iterest is greater than 1% the withdraws are forbidden.</p>
<p>It should remember the last 5 operations of the account.</p>
<p><strong>Make a CLI (Command Line Interpreter)</strong> for operating with the Bank accounts
It should have the following functions:</p>
<p><strong>create_bank_account</strong>
It should prompt the user for the needed information and if everything is ok it should create a new bank account.</p>
<p><strong>show_history</strong>
It should prompt the user for the bank account number and show its history.</p>
<p><strong>add_money</strong>
It should prompt the user for the amount and the bank account number.</p>
<p><strong>withdraw_money</strong>
It should prompt the user for the amount and the bank account number.</p>
<p><strong>transfer_money</strong>
It should prompt the user for the origin and destination bank account numbers and the amount</p>
<p><strong>calculate_amount</strong>
It should prompt the user for bank account number and number of months. It should return the amount after the given number of months.</p>
<p><strong>The Bank</strong>
It should store the bank accounts.</p>
<p><strong>Notes:</strong>
you should create and use your own custom exceptions:</p>
<p><strong>InsufficientFundsException</strong></p>
<p><strong>NonExistingBankAccountException</strong></p>
</blockquote>
<p>Here is my code:
<strong>Exceptions</strong></p>
<pre><code> package bank.exceptions;
public class NonExcistingBankAccountException extends Exception {
public NonExcistingBankAccountException(){
super();
}
public NonExcistingBankAccountException(String message){
super(message);
}
}
package bank.exceptions;
public class InsufficientFundsException extends Exception {
public InsufficientFundsException(){
super();
}
public InsufficientFundsException(String message){
super(message);
}
}
</code></pre>
<p><strong>Person</strong></p>
<pre><code>package bank;
public class Person {
private String firstName;
private String lastName;
private int age;
public Person(String first, String last, int age){
this.firstName = first;
this.lastName = last;
this.age = age;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
}
</code></pre>
<p><strong>Enum</strong></p>
<pre><code>package bank;
enum InterestType {
SIMPLE,
COMPLEX;
}
</code></pre>
<p><strong>Bank account</strong></p>
<pre><code>package bank;
import bank.exceptions.InsufficientFundsException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Queue;
import java.util.UUID;
public class BankAccount {
private String id;
private Person owner;
private double balance;
private double interest;
private InterestType interestType;
private Queue<String> operations;
public BankAccount(Person owner, double interest, InterestType interestType){
this.owner = owner;
this.interest = interest;
this.interestType = interestType;
this.id = UUID.randomUUID().toString();
this.operations = new ArrayDeque<>(5);
}
public BankAccount(String firstName, String lastName, int age,double interest, InterestType interestType ){
this(new Person(firstName,lastName,age),interest,interestType);
}
public void add(double money){
balance += money;
addOperation(String.format("%s %.2f%n", "added", money));
}
public boolean withdraw(double money) throws InsufficientFundsException {
if(interest > 1){
return false;
}
if(money > balance){
throw new InsufficientFundsException("Not enough money to complete operation");
}
balance -= money;
addOperation(String.format("%s %.2f%n", "withdrawn", money));
return true;
}
public List<String> getHistory(){
List<String> operationsList = new ArrayList<>(this.operations);
addOperation(String.format("%s%n", "viewed history"));
return operationsList;
}
public boolean transfer(BankAccount account, double amount) throws InsufficientFundsException {
boolean withdrawn = withdraw(amount);
if(withdrawn){
account.add(amount);
addOperation(String.format("%s %.2f to %s %n","transferred",amount,account.getId()));
}
return withdrawn;
}
public String getId() {
return id;
}
public Person getOwner() {
return owner;
}
public double getBalance() {
return balance;
}
public double getInterest() {
return interest;
}
public InterestType getInterestType() {
return interestType;
}
private void addOperation(String operation){
if(operations.size() == 5){
operations.remove();
}
operations.add(operation);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof BankAccount)) return false;
BankAccount that = (BankAccount) o;
return Objects.equals(getId(), that.getId());
}
@Override
public int hashCode() {
return Objects.hash(getId());
}
}
</code></pre>
<p><strong>Bank</strong></p>
<pre><code>package bank;
import bank.exceptions.InsufficientFundsException;
import bank.exceptions.NonExcistingBankAccountException;
import java.util.List;
import java.util.Set;
import java.util.HashSet;
import static java.lang.Math.pow;
public class Bank {
private Set<BankAccount> accounts;
public Bank(){
accounts = new HashSet<>();
}
void createBankAccount(Person owner, double interest, InterestType interestType){
BankAccount account = new BankAccount(owner,interest,interestType);
accounts.add(account);
System.out.println(account.getId());
}
void createBankAccount(String firstName, String lastName, int age, double interest, InterestType interestType){
Person owner = new Person(firstName,lastName, age);
createBankAccount(owner,interest,interestType);
}
public List<String> showOperations(String accountID) throws NonExcistingBankAccountException {
for(BankAccount account : accounts){
if(accountID.equals(account.getId())){
return account.getHistory();
}
}
throw new NonExcistingBankAccountException(String.format("Bank account %s does not exist.%n",accountID));
}
public void addMoney(String accountID, double amount) throws NonExcistingBankAccountException {
BankAccount account = findAccount(accountID);
account.add(amount);
}
public boolean withdrawMoney(String accountID,double amount) throws NonExcistingBankAccountException, InsufficientFundsException {
BankAccount account = findAccount(accountID);
return account.withdraw(amount);
}
public boolean transferMoney(String source, String destination, double amount) throws NonExcistingBankAccountException, InsufficientFundsException {
BankAccount sourceAccount = findAccount(source);
BankAccount destinationAccount = findAccount(destination);
return sourceAccount.transfer(destinationAccount,amount);
}
public double calculateAmount(String accountID, int months) throws NonExcistingBankAccountException{
BankAccount account = findAccount(accountID);
double years = ((double) months)/12;
switch(account.getInterestType()) {
case SIMPLE:
return account.getBalance() * account.getInterest() * years;
case COMPLEX:
return account.getBalance() * (pow((1 + account.getInterest()), years) - 1);
default:
throw new IllegalArgumentException();
}
}
private BankAccount findAccount(String accountID) throws NonExcistingBankAccountException{
for(BankAccount account : accounts){
if(accountID.equals(account.getId())){
return account;
}
}
throw new NonExcistingBankAccountException(String.format("Bank account %s does not exist.%n",accountID));
}
}
</code></pre>
<p><strong>The command line interpreter</strong></p>
<pre><code>package bank;
import bank.exceptions.InsufficientFundsException;
import bank.exceptions.NonExcistingBankAccountException;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Scanner;
public class CommandLineInterpreter{
private Bank bank;
private static final String SUCCESS = "Operation completed.";
private static final String PROMPT_BANK_ACCOUNT = "Enter bank account ID: ";
private static final String FAIL = "Operation failed.";
private static final String CANNOT_WITHDRAW = "Either you do not have enough money to complete the operation or your interest is greater than 1% in which case withdraws are forbidden.";
private static final String PROMPT_AMOUNT = "Enter amount: ";
public CommandLineInterpreter(){
bank = new Bank();
}
private void showOpitons(){
System.out.println("Choose an option: ");
System.out.println("1: Create a bank account.");
System.out.println("2: Show history.");
System.out.println("3: Deposit money.");
System.out.println("4: Withdraw money");
System.out.println("5: Transfer money.");
System.out.println("6: Calculate amount");
System.out.println("7: Exit");
}
public void start() throws IOException {
int option;
Scanner reader = new Scanner(System.in);
do{
showOpitons();
try{
option = reader.nextInt();
reader.nextLine();
if(option<1 || option > 6) {
break;
}
switch (option) {
case 1:
createBankAccount(reader);
break;
case 2:
showHistory(reader);
break;
case 3:
addMoney(reader);
break;
case 4:
withdrawMoney(reader);
break;
case 5:
transferMoney(reader);
break;
case 6:
calculateAmount(reader);
break;
}
}catch(InputMismatchException e){
System.err.println("Invalid argument. Try again.");
reader.next();
}catch(Exception e){
System.err.println(e.getMessage());
}
} while(true);
reader.close();
}
private Person readOwner(Scanner reader){
System.out.println("Enter owner's name: ");
String name = reader.nextLine();
String names[] = name.split("\\s");
System.out.println("Enter owner's age: ");
int age = reader.nextInt();
return new Person(names[0],names[1],age);
}
private InterestType readInterestType(Scanner reader){
System.out.println("Choose interest type:\n1. Simple\n2. Complex");
short option = reader.nextShort();
switch(option){
case 1:
return InterestType.SIMPLE;
case 2:
return InterestType.COMPLEX;
default:
throw new IllegalArgumentException();
}
}
public void createBankAccount(Scanner reader) {
Person owner = readOwner(reader);
System.out.println("Enter interest rate: ");
double interest = reader.nextDouble();
InterestType interestType = readInterestType(reader);
bank.createBankAccount(owner,interest,interestType);
}
public void showHistory(Scanner reader) throws NonExcistingBankAccountException{
System.out.println(PROMPT_BANK_ACCOUNT);
String account = reader.nextLine();
List<String> operations = bank.showOperations(account);
for(String operation : operations){
System.out.println(operation);
}
}
public void addMoney(Scanner reader) throws NonExcistingBankAccountException{
System.out.println(PROMPT_BANK_ACCOUNT);
String account = reader.nextLine();
System.out.println(promptAmount);
double amount = reader.nextDouble();
bank.addMoney(account, amount);
System.out.println(success);
}
public void withdrawMoney(Scanner reader) throws InsufficientFundsException, NonExcistingBankAccountException {
System.out.println(PROMPT_BANK_ACCOUNT);
String account = reader.nextLine();
System.out.println(PROMPT_AMOUNT);
double amount = reader.nextDouble();
if(bank.withdrawMoney(account, amount)){
System.out.println(SUCCESS);
}else {
System.err.println(FAIL);
System.err.println(CANNOT_WITHDRAW);
}
}
public void transferMoney(Scanner reader) throws InsufficientFundsException, NonExcistingBankAccountException{
System.out.println("Enter source bank account ID: ");
String source = reader.nextLine();
System.out.println("Enter destination bank account ID: ");
String destination = reader.nextLine();
System.out.println(PROMPT_AMOUNT);
double amount = reader.nextDouble();
if(bank.transferMoney(source,destination , amount)){
System.out.println(SUCCESS);
}else {
System.err.println(FAIL);
System.err.println(CANNOT_WITHDRAW);
}
}
public void calculateAmount(Scanner reader) throws NonExcistingBankAccountException {
System.out.println(PROMPT_BANK_ACCOUNT);
String account = reader.nextLine();
System.out.println("Enter months for which you want to calculate the amount: ");
int months = reader.nextInt();
System.out.println(String.format("%.2f",bank.calculateAmount(account, months)));
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T11:10:45.180",
"Id": "405806",
"Score": "0",
"body": "Nice code. Parallel usage of the same bank account (concurrency) is probably a future subject. `double` is just an approximation of a sum of (negative) powers of 2 and hence might be problematic. BigDecimal can set the \"scale\", number of decimals. `private static final String SUCCESS = ...`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T11:23:21.370",
"Id": "405808",
"Score": "0",
"body": "Thank you.\nYes, I will keep upgrading it, as long as I have laid the foundations right."
}
] | [
{
"body": "<p>This is already a good piece of code. Good job.</p>\n\n<p>I can imagine some improvements for your code:</p>\n\n<p><strong>Exceptions:</strong></p>\n\n<p>Except a typo into the name of <code>NonExistingBankAccountException</code> I would suggest \nto move the construction of the message in the exception itself. So that you \nwill always have the same message and your code is more concise:</p>\n\n<pre><code>new NonExistingBankAccountException(String accountId)\n</code></pre>\n\n<p><strong>Bank:</strong></p>\n\n<p>There is a good Object Oriented case study into your <code>calculateAmount</code> method: How can you get rid of this switch ? </p>\n\n<p>The <code>switch</code> expression is useful but may be a code smell in some case. And it can be a code smell in your case.</p>\n\n<p>Imagine that you want to add another <code>InterestType</code>. You should change this enum \nAND your <code>Bank</code> class. What can you do to preserve the <em>single responsibility principe</em> ?</p>\n\n<p><strong>BankAccount:</strong></p>\n\n<p>For the withdraw forbidden rule when interest is greater than 1% I will also \nuse an exception but provide a test method to verify if we can withdraw. \nHaving a interest under % is then a pre-condition of the <code>withdraw</code> method.</p>\n\n<p>For the <em>operations</em>, instead of storing a list of strings, you can view the operations as executable treatments on the account. So you do not have to maintain the state of the account but storing his operations history and executing them to have the current state. This a kind of <em>event sourcing</em> that I suggest in another similar question : <a href=\"https://codereview.stackexchange.com/a/188370/115154\">https://codereview.stackexchange.com/a/188370/115154</a></p>\n\n<p><strong>CommandLineInterpreter:</strong></p>\n\n<p>There is a typo in <code>showOpitons</code>. </p>\n\n<p><strong>Person:</strong></p>\n\n<p>It is usually easier to store the birth date instead of the age. Because the age \nchange in time while the birth date don't. And you can always compute the age \nfrom the birth date. </p>\n\n<p><strong>Your question:</strong></p>\n\n<blockquote>\n <p>I cannot yet grasp the difference when I should return true/false on\n success/failure of a method and when to throw an exception.</p>\n</blockquote>\n\n<p>I would just say that exceptions are for exceptional cases, an exception occur \nwhen you encounter and invalid state but they should never be used to control \nthe flow of your program while booleans can.</p>\n\n<p>This is sometimes more clear when you use reason with pre and post conditions. \nAn exception is thrown when a pre condition is not matched:</p>\n\n<pre><code>/**\n * Attempt to remove the given amount from this account balance.\n * @param amount a positive double indicating the amount to be withdrawn. `> -1`.\n * @return true when the amount has been withdrawn. Otherwise false.\n * @throw InvalidAmountException iff the amount is a nagtive number.\nboolean withdraw(double amount) {\n // ...\n}\n</code></pre>\n\n<p>The param has a precondition of being positive. If this precondition is not met, \nthen you may receive an exception. However for some reasons it happens that \neverything is fine but the withdrawal cannot be executed. Then you get a <code>false</code> \nbecause this is no due to a violation of the contract or invalid state.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T15:30:01.507",
"Id": "405849",
"Score": "0",
"body": "Thank you for the detailed answered!\nAs for the `InterestType` class I hope you are talking about doing something like this:\n\n`enum InterestType { \n SIMPLE {\n public double calculateAmount ( double amount, double interest, double years ) { //..\n`\n\nIn which case the switch will disappear?\nI just was not aware of being able to use enums in that way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T06:46:45.957",
"Id": "405939",
"Score": "0",
"body": "Yes, that was my idea. But there may be other solutions like having one `BankAccount` subclass for each type of intereset."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T14:35:06.360",
"Id": "209975",
"ParentId": "209963",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "209975",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T10:06:07.453",
"Id": "209963",
"Score": "1",
"Tags": [
"java",
"object-oriented"
],
"Title": "Simulate BankAccount in Java"
} | 209963 |
<p>I have this code and I would like to know if I filtered my code correctly. I am practicing my security coding for a system that I am working on and I would like to know if I am doing it the right way.</p>
<p>If there is any thing that I can improve to get things more solid I would very much like to know about them.</p>
<pre><code><?php
require_once 'app/helpers.php';
session_start();
$error = '';
if($_POST){
$itemtype = filter_input(INPUT_POST, 'itemtype', FILTER_SANITIZE_STRING);
$itemtype = trim($itemtype);
$display = filter_input(INPUT_POST, 'itemdisplay', FILTER_SANITIZE_STRING);
$display = trim($display);
$brand = filter_input(INPUT_POST, 'brand', FILTER_SANITIZE_STRING);
$brand = trim($brand);
$model = filter_input(INPUT_POST, 'model', FILTER_SANITIZE_STRING);
$model = trim($model);
$spec = filter_input(INPUT_POST, 'spec', FILTER_SANITIZE_STRING);
$spec = trim($spec);
$sn = filter_input(INPUT_POST, 'sn', FILTER_SANITIZE_STRING);
$sn = trim($sn);
$setname = filter_input(INPUT_POST, 'setname', FILTER_SANITIZE_STRING);
$setname = trim($setname);
$itemstat = filter_input(INPUT_POST, 'itemstat', FILTER_SANITIZE_STRING);
$itemstat = trim($itemstat);
if(empty($itemtype)){
$error = '<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">ร</button> ืชืื ืืก ืืช ืืคืจืื ืืงืืืฆื ืื ืืคื! </div>';
}elseif (empty($display)){
$error = '<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">ร</button> ืื ืื ื ืฆืื ื ืืชื ืื ืฉื ืืื ืืงืื ืืืชื? </div>';
}elseif (empty($brand)){
$error = '<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">ร</button> ืกืืืื... ืื ืืฆืจ ืืช ืืคืจืื? </div>';
}elseif (empty($model)){
$error = '<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">ร</button> ืจืืข...ืืืื ืืื ืื? </div>';
}elseif (empty($spec)){
$error = '<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">ร</button> ืื ืืืืข ืฉืชืืชืื ืขืืื ืืื ืืืืื? </div>';
}elseif (empty($sn)){
$error = '<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">ร</button> ืืกืคืจ ืกืืืืจื ืื ืืื ืืื (ืืฉืื ืืืื ืืืชื ืืืจ ืืื ืฉื ืคืจืื ืืืจ...ืื ื ืขืื..) </div>';
}elseif (empty($setname)){
$error = '<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">ร</button> ืื ื ืืืื ืืืืืช ืืืืืืืช...ืื ืฉื ืืกื ืฉืื? </div>';
}elseif (empty($itemstat)){
$error = '<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">ร</button> ืืืืจืื ื ืกืืืืชื ืงืฉืจ ืจืฆืื ื... ืื ืืกืืืืก ืฉืื? </div>';
}else{
if(!empty(filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING)) || !empty(filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING)) || !empty($_FILES['file']['name'])) {
$uploadedFile = '';
if (!empty($_FILES["file"]["type"])) {
$fileName = $_FILES['file']['name'];
$valid_extensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")) && in_array($file_extension, $valid_extensions)) {
$sourcePath = $_FILES['file']['tmp_name'];
$targetPath = "items-img/" . $fileName;
if (move_uploaded_file($sourcePath, $targetPath)) {
$uploadedFile = $fileName ;
}
}
}
}
$stm = $link -> prepare("INSERT INTO item (item_desc,display,brand,model,spec,sn,set_name,status,item_pic) VALUES ('$itemtype','$display','$brand','$model','$spec','$sn','$setname','$itemstat','$uploadedFile')");
$stm->execute(array('item_desc' => $itemtype , 'display' => $display ,'brand' => $brand ,'model' => $model ,'item_desc' => $itemtype ,'spec' => $spec ,
'sn' => $sn ,'set_name' => $setname ,'status' => $itemstat ,'name' => $uploadedFile ));
$error = '<div class="alert alert-success alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">ร</button> ืืฉ ืื ื ืคืจืื ืืืฉ! </div>';
}
}
?>
<div>
<?= $error ?>
</div>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T11:29:51.190",
"Id": "405810",
"Score": "1",
"body": "Please tell us more about your code. The description doesn't reveal much yet."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-19T13:49:46.613",
"Id": "426064",
"Score": "1",
"body": "Next time, make sure that your code is formatted and indented properly. In its current form it's hardly readable."
}
] | [
{
"body": "<p>Instead of calling <code>filter_input</code> then <code>trim</code> combine them into a single statement.</p>\n\n<pre><code>$itemtype = trim(filter_input(INPUT_POST, 'itemtype', FILTER_SANITIZE_STRING));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T12:41:31.150",
"Id": "405816",
"Score": "0",
"body": "Could you provide a scenario when to just check the extension is not enough?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T12:43:23.933",
"Id": "405817",
"Score": "0",
"body": "Take a PHP file or JS file and rename to .jpg or .png or anything else."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T12:44:53.023",
"Id": "405818",
"Score": "0",
"body": "and...? Ok I renamed it, and what next?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T12:48:04.093",
"Id": "405820",
"Score": "0",
"body": "Nevermind, removed that portion of my answer .... though I still think it's a very good sanity/double check."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T12:58:14.897",
"Id": "405826",
"Score": "2",
"body": "It is but it is very easy to fool fileinfo as well, a file could be of several types at once, serving as a valid image and no less valid PHP file at the same time. The question is whether you'll be able to execute the file, not what are first dozen bytes which fileinfo sniffs."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T12:34:43.517",
"Id": "209973",
"ParentId": "209964",
"Score": "0"
}
},
{
"body": "<p>Your code is vulnerable, at least to SQL injection, Unrestricted File Upload, and Full Path Disclosure. For example, they can be exploited as follows:</p>\n\n<ul>\n<li><p>SQL Injection: <code>file.name='(SQL injection).jpg</code></p></li>\n<li><p>Full Path Disclosure: <code>file.name=a:b.jpg</code>, <code>file.name=%long_string%.jpg</code> or <code>itemtype=\\</code></p></li>\n<li><p>Unrestricted File Upload means that intruder can upload a PHP file with the โ.jpgโ extension, which is a โgreatโ gift together with a LFI. Also, I would not trust file names from user and save them as is.</p></li>\n</ul>\n\n<p>Some additional thoughts about your code:</p>\n\n<p>• SQL injection as well as Full Path Disclosure are result of improper use of prepared statements. To fix this, use bind methods or the following:</p>\n\n<pre><code>$stm = $link->prepare(\"INSERT INTO item (item_desc, display, brand, ...) VALUES (?, ?, ?, ...)\");\n$stm->execute([$itemtype, $display, $brand, ...]);\n</code></pre>\n\n<p>• You can never upload โ.pngโ files or images that have uppercase extensions.</p>\n\n<p>• <code>filter_input(INPUT_POST, $var, FILTER_SANITIZE_STRING)</code> is designed to sanitize HTML strings, not MySQL queries. For example, it will not escape characters such as โ%โ, โ_โ or โ\\โ.</p>\n\n<p>• The main rule of programming โ โdo not repeat yourselfโ. You can significantly improve your code by replacing all variable definitions and conditions:</p>\n\n<pre><code>$vars = [\n 'itemtype' => 'Error 1',\n 'itemdisplay' => 'Error 2',\n 'brand' => 'Error 3',\n /* ... */\n];\n\n$error = '';\n$values = [];\nforeach ($vars as $varname => $varmsg) {\n $value = trim(filter_input(INPUT_POST, $varname FILTER_SANITIZE_STRING));\n if (empty($value)) {\n $error = $varmsg;\n break;\n }\n}\n\nif ($error) {\n echo <<<HTML\n<div class=\"alert alert-danger alert-dismissable\">\n <button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-hidden=\"true\">ร</button>\n {$error}\n</div>\nHTML;\n} else {\n /* ... */\n\n $stm = $link->prepare(\"INSERT INTO item (item_desc,display,brand) VALUES(?,?,?)\");\n $stm->execute($values);\n\n /* ... */\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T11:49:14.327",
"Id": "405971",
"Score": "0",
"body": "They say it's quite hard to prevent the upload of a PHP code inside of a jpeg file. Either way you didn't offer any solution. I don't think a good review should name a problem but offer no solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T12:01:21.710",
"Id": "405973",
"Score": "0",
"body": "@YourCommonSense You can very easily append PHP to the image, and it will remain perfectly valid (for example, you can do it with `file_put_contents('image.jpg', '<?php', FILE_APPEND)`). As for solutions, they are not specific to this code. It is better to learn about them on specialized sites (https://www.owasp.org/) or publish new relevant questions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T12:02:54.167",
"Id": "405974",
"Score": "0",
"body": "I would say the opposite, solutions are *essential* for this code. Least a link in just a general direction offers any help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T12:16:56.300",
"Id": "405975",
"Score": "2",
"body": "You want to say, that for every question we should explain what are SQL injection, Unrestricted File Upload, and Full Path Disclosure vulnerabilities? And every time to provide full snippets how to protect against them? Or maybe we should waste our time to search good links for each of them? Hm... I think, my task was to direct the author to the right path and tell him about vulnerabilities. I hope he will appreciate it. At least because no one told him about these vulnerabilities."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T11:43:03.933",
"Id": "210040",
"ParentId": "209964",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T10:21:29.253",
"Id": "209964",
"Score": "3",
"Tags": [
"php",
"pdo"
],
"Title": "Sanitize vars on form submit"
} | 209964 |
<p>While reviewing a PR, I found an enum being used like this:</p>
<pre><code>class Entity {
public enum STATUS { NEW, SENT, FAILED, OK }
@Column(name = "STATUS") // a NUMBER(1) column in DB
private int status; // + get/set
//...
}
// Inside methods...
Entity e = new Entity();
e.setStatus(STATUS.SENT.ordinal());
EntityDAO.save(e);
Entity e = EntityDAO.findByStatus(STATUS.FAILED.ordinal());
logger.info("Found entity with status: " + STATUS.values()[e.getStatus()]);
</code></pre>
<p>Assume the necessary imports etc.</p>
<p>I find this use of <code>ordinal()</code> to be an antipattern, and consider that it should be avoided.<br>
Instead, an inner field with the equivalent DB representation (e.g. <code>NEW(1)</code> or <code>NEW("N")</code>) should be used, in order to decouple the semantically meaningful representation of the enum value in the code (<code>NEW</code>) from the DB-optimized representation of such value when persisted (<code>1</code> or <code>'N'</code> or whatever). </p>
<p>Now, I don't have this POV for nothing: we've already had bugs stemming from altering the order of enum elements that were being used based on its <code>ordinal()</code> value (some times because of adding new values in between, some times because someone decided the values looked better in alphabetical order ยฏ\_(ใ)_/ยฏ).</p>
<p>That's the case I made in the PR comments -- but in the end the PR got approved anyway, reasoning that my proposed correction would add too much clutter to the enum for little gain, and that we should all just be careful with enums.<br>
And so the enum made its way to production.</p>
<p>Time has passed, and now I've got the chance to change that enum so its usage is not tied to the ordering of its elements.<br>
However, since this has been in production for quite some time, I have to make it so the current DB values (0, 1, 2...) are kept and still interpreted correctly (as changing the DB values or column type would be too costly now).</p>
<p>This is the first version I came up with:</p>
<pre><code>public enum STATUS {
NEW (0),
SENT (1),
FAILED (2),
OK (3),
;
private final int val;
STATUS (int val) { this.val = val; }
public int val() { return val; }
public static STATUS get(final int val) {
switch (val) {
case 0: return NEW;
case 1: return SENT;
case 2: return FAILED;
case 3: return OK;
default: throw new IllegalArgumentException();
}
}
}
</code></pre>
<p>I think this is as concise as it can get.<br>
However, if a dev wanted to add a new enum value, they'd have to modify both the enum list <strong><em>and</em></strong> the <code>switch</code> inside the <code>get(int)</code> method. I find this to be inconvenient and, in a way, ammunition for my peers in favor of just using <code>ordinal()</code>.<br>
So I came up with this second version:</p>
<pre><code>public static enum STATUS {
NEW (0),
SENT (1),
FAILED (2),
OK (3),
;
private static final STATUS[] values;
static { // like caching values() but sorted by dbValue
STATUS[] st = values();
values = new STATUS[st.length];
for (STATUS s : st) {
values[s.dbValue] = s;
}
}
public static STATUS fromDB(final int dbValue) {
return values[dbValue];
}
private final int dbValue;
public int toDBValue() {
return dbValue;
}
STATUS(int dbValue) {
this.dbValue = dbValue;
}
}
</code></pre>
<p>In this version, adding a new enum element is as simple as adding it to the list, just like a normal enum. And getting an element from its DB value is O(1) and rather efficient (compared to, say, using Streams to filter <code>values()</code> by <code>dbValue</code> every time). But maybe it is too complex for an enum? Also, this relies on DB values being consecutive numbers, as adding e.g. <code>CANCELLED(99)</code> would throw an AIOOB exception upon execution.</p>
<p>So my question is: <strong>how can I enhance this enum</strong> so adding elements to it is as simple as possible, getting elements by value is as efficient as possible, and it doesn't depend on <code>ordinal()</code>?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T16:48:17.877",
"Id": "405866",
"Score": "0",
"body": "The question is at +1/-1 right now. I don't mind the downvotes but, if anybody feels there's something I could improve, I'd appreciate a comment pointing it out."
}
] | [
{
"body": "<p>A negative parameter value or a parameter value >= <code>values.length</code> passed to <code>fromDB()</code> will throw an IndexOutOfBoundsException, which is less meaningful than the original IllegalArgumentException since the IndexOutOfBoundsException is complaining about an implementation detail rather than about bad input.</p>\n\n<p>To avoid the IndexOutOfBoundsException, use a <code>Map<Integer, STATUS></code> instead of an array.</p>\n\n<p>However, if there are only a few defined values as in the question, a Map is probably not needed either. <code>fromDB()</code> can simply iterate over values() and return the match when found, otherwise throw IllegalArgumentException. <strong>Add the Map when performance profiling indicates <code>fromDB()</code> is a bottleneck.</strong></p>\n\n<p>Also, consider changing <code>STATUS</code> to <code>Status</code>, to follow standard naming conventions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T19:25:27.417",
"Id": "209999",
"ParentId": "209972",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "209999",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T11:52:30.453",
"Id": "209972",
"Score": "1",
"Tags": [
"java",
"enum"
],
"Title": "Avoiding the use of ordinal() in an already-deployed enum"
} | 209972 |
<p><strong>Scenario:</strong> I have an excel file that contains some data in the first sheet. That data can be simple strings on a cell or CheckBoxes (marked or not).</p>
<p><strong>Data example:</strong></p>
<pre><code>+---------+-------+------------------+------+------------------+
| item1 | 2004 | | | |
+---------+-------+------------------+------+------------------+
| value x | rfd | checkbox for rfd | nfd | checkbox for nfd |
+---------+-------+------------------+------+------------------+
| ident | test7 | call3 | | |
+---------+-------+------------------+------+------------------+
</code></pre>
<p>Where "checkbox for rfd" and "checkbox for nfd" are normal checkboxes.</p>
<p><strong>Objective:</strong> I want to retrieve all that information with python.</p>
<p><strong>Issue:</strong> I did not find many ways to do this: the only viable things I found was to either use a module (such as win32com) to rum the VBA instance and get the data there. Another was to just open a file, run the VBA subs, then import that to python.
This works, but it is unnefective for 2 reasons: 1 - this requires me to do a previous VBA manipulation, and since I am trying to automate this process, it is not very smart. 2 - The excel file I am reading is a complete mess, and the checkboxes are all over the place, sometimes duplicated with no reason (that is not something I can fix before hand, since there is a considerable number of files and each of them varies in a different way).</p>
<p><strong>Question:</strong> Is there a better / more efficient way to do this (particularly directly with python?</p>
<p><strong>VBA subs:</strong></p>
<pre class="lang-vba prettyprint-override"><code>Option Explicit
Sub getControlValues() 'This retrieves the names, values and locations of all objects in the Worksheet
Dim objx As Object
Dim cb As Shape
Dim i As Long
i = 1
'Loop Through ActiveX Checkboxes
For Each objx In ThisWorkbook.Sheets(1).OLEObjects
If objx.Object.Value = True Then
ThisWorkbook.Sheets(3).Cells(i, 1).Value = "X"
ThisWorkbook.Sheets(3).Cells(i, 2).Value = objx.Name
ThisWorkbook.Sheets(3).Cells(i, 3).Value = objx.BottomRightCell.Address()
ThisWorkbook.Sheets(3).Cells(i, 4).Value = objx.BottomRightCell.Column
ThisWorkbook.Sheets(3).Cells(i, 5).Value = objx.BottomRightCell.Row
ElseIf objx.Object.Value = False Then
ThisWorkbook.Sheets(3).Cells(i, 1).Value = ""
ThisWorkbook.Sheets(3).Cells(i, 2).Value = objx.Name
ThisWorkbook.Sheets(3).Cells(i, 3).Value = objx.BottomRightCell.Address()
ThisWorkbook.Sheets(3).Cells(i, 4).Value = objx.BottomRightCell.Column
ThisWorkbook.Sheets(3).Cells(i, 5).Value = objx.BottomRightCell.Row
End If
i = i + 1
Next objx
'Loop through Form Checkboxes
For Each cb In ThisWorkbook.Sheets(1).Shapes
If cb.Type = msoFormControl Then
If cb.FormControlType = xlCheckBox Then
If cb.ControlFormat.Value = xlOn Then
ThisWorkbook.Sheets(3).Cells(i, 1).Value = "X"
ThisWorkbook.Sheets(3).Cells(i, 2).Value = cb.Name
ThisWorkbook.Sheets(3).Cells(i, 3).Value = cb.BottomRightCell.Address()
ThisWorkbook.Sheets(3).Cells(i, 4).Value = cb.BottomRightCell.Column
ThisWorkbook.Sheets(3).Cells(i, 5).Value = cb.BottomRightCell.Row
ElseIf cb.ControlFormat.Value = xlOff Then
ThisWorkbook.Sheets(3).Cells(i, 1).Value = ""
ThisWorkbook.Sheets(3).Cells(i, 2).Value = cb.Name
ThisWorkbook.Sheets(3).Cells(i, 3).Value = cb.BottomRightCell.Address()
ThisWorkbook.Sheets(3).Cells(i, 4).Value = cb.BottomRightCell.Column
ThisWorkbook.Sheets(3).Cells(i, 5).Value = cb.BottomRightCell.Row
End If
i = i + 1
End If
End If
Next cb
End Sub
Sub getNormalData() 'This will get all non-object values from the sheet and past the checkbox values into final output
Dim array_test As Variant
Dim i As Long, j As Long, a As Long
array_test = ThisWorkbook.Sheets(1).UsedRange
For i = 1 To ThisWorkbook.Sheets(1).Cells(Rows.Count, 1).End(xlUp).Row
For j = 1 To ThisWorkbook.Sheets(1).Cells(1, Columns.Count).End(xlToLeft).Column
ThisWorkbook.Sheets(2).Cells(i, j) = array_test(i, j)
Next j
Next i
For a = 1 To ThisWorkbook.Sheets(3).Cells(Rows.Count, 1).End(xlUp).Row
If ThisWorkbook.Sheets(3).Cells(a, 1).Value <> "" Then
ThisWorkbook.Sheets(2).Cells(ThisWorkbook.Sheets(3).Cells(a, 5).Value, ThisWorkbook.Sheets(3).Cells(a, 4).Value) = ThisWorkbook.Sheets(3).Cells(a, 1).Value
End If
Next a
End Sub
</code></pre>
<p><strong>Python miniscript to retrieve that data:</strong></p>
<pre class="lang-python prettyprint-override"><code>import xlrd
db1 = pd.DataFrame()
workbook = xlrd.open_workbook("C:\\Users\\DGMS89\\Downloads\\TEMPLATE.XLSM")
worksheet = workbook.sheet_by_index(2)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T15:49:53.530",
"Id": "405996",
"Score": "0",
"body": "Are your checkboxes linked to specific cells in the worksheet? (Can you change the workbook to link each checkbox to a different cell?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T15:55:33.143",
"Id": "406000",
"Score": "0",
"body": "@PeterT Unfortunately, no. They are not linked and since the files are a mess, I could find no way to viably standardize and link each to a specific cell."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T17:57:48.680",
"Id": "406031",
"Score": "1",
"body": "Have you looked at `pyxll`? It looks like you can access the COM model (as you mention above) without running the VBA script. This [example](https://www.pyxll.com/docs/examples/automation.html) shows accessing a checkbox."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T18:41:19.430",
"Id": "406449",
"Score": "1",
"body": "You could read the XML of the Excel file instead of opening the file with VBA, this may be faster too. Try writing in memory to Python, rather than to a file, memory ops will be faster than opening/writing to an excel file."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T14:14:53.033",
"Id": "209974",
"Score": "3",
"Tags": [
"python",
"vba",
"excel"
],
"Title": "Retrieving data in multiple formats from Excel with Python"
} | 209974 |
<p>If I create a class that implements <code>IComparable<T></code>, I must implement <code>CompareTo<T></code>. It is also recommended that I implement <code>IEquatable<T></code> and the non-generic <code>IComparable</code>. If I do all that, I am required or encouraged to:</p>
<ul>
<li>Override <code>GetHashCode()</code></li>
<li>Implement <code>CompareTo(Object)</code></li>
<li>Override <code>Equals(Object)</code></li>
<li>Implement <code>Operator ==(T, T)</code> </li>
<li>Implement <code>Operator !=(T, T)</code> </li>
<li>Implement <code>Operator >(T, T)</code> </li>
<li>Implement <code>Operator <(T, T)</code> </li>
<li>Implement <code>Operator >=(T, T)</code> </li>
<li>Implement <code>Operator <=(T, T)</code> </li>
</ul>
<p>That's 9 additional methods, most of which depend on the logic that compares two instances of the class. Rather than having to implement all those methods in any class that implements <code>IComparable<T></code>, I decided to create a base class that implements <code>IComparable<T></code> and the other recommended interfaces (similar to the way Microsoft provides <code>Comparer</code> as a base class for implementations of <code>IComparer<T></code>)</p>
<p>It doesn't make sense to compare instances of two different classes that each inherit from the base class. preventing that was the main reason for making the class generic (although it makes coding a derived class a little more complicate).</p>
<p>I would like to ask for a review of the code for the base class. Am I missing something? Can it be simplified? Is this a bad idea?</p>
<p>Here is the base class</p>
<pre><code>public abstract class Comparable<T> : IComparable, IComparable<T>, IEquatable<T> where T: Comparable<T> {
public abstract override int GetHashCode();
public abstract int CompareTo(T other);
public int CompareTo(object obj) {
T other = obj as T;
if (other == null && obj != null) {
throw new ArgumentException($"Objects of type {typeof(T).Name} can only be compared to objects of the same type", nameof(obj));
}
return CompareTo(other);
}
public override bool Equals(object obj) {
return CompareTo(obj) == 0;
}
new public bool Equals(T other) {
return CompareTo(other) == 0;
}
private static int Compare(Comparable<T> comp1, Comparable<T> comp2) {
if (comp1 == null) {
return ((comp2 == null) ? 0 : -1);
}
return comp1.CompareTo(comp2);
}
public static bool operator == (Comparable<T> comp1, Comparable<T> comp2) {
return Compare(comp1, comp2) == 0;
}
public static bool operator != (Comparable<T> comp1, Comparable<T> comp2) {
return Compare(comp1, comp2) != 0;
}
public static bool operator > (Comparable<T> comp1, Comparable<T> comp2) {
return Compare(comp1, comp2) > 0;
}
public static bool operator < (Comparable<T> comp1, Comparable<T> comp2) {
return Compare(comp1, comp2) < 0;
}
public static bool operator >= (Comparable<T> comp1, Comparable<T> comp2) {
return Compare(comp1, comp2) >= 0;
}
public static bool operator <= (Comparable<T> comp1, Comparable<T> comp2) {
return Compare(comp1, comp2) <= 0;
}
}
</code></pre>
<p>Below is a minimal implementation of the base class.</p>
<pre><code>public class SeasonCompare : Comparable<SeasonCompare> {
public int Number {get; set;}
public override int GetHashCode() {
return Number;
}
public override int CompareTo(SeasonCompare other) {
if (other == null) {
return 1;
}
return Number.CompareTo(other.Number);
}
}
</code></pre>
| [] | [
{
"body": "<blockquote>\n <p>It is also recommended that I implement ... the non-generic <code>IComparable</code>.</p>\n</blockquote>\n\n<p>I don't see that recommendation in <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.icomparable-1?view=netframework-4.7.2\" rel=\"noreferrer\">the current doc for IComparable</a>. I would recommend against it: having the non-generic method turns compile-time errors into runtime errors, which are more expensive to find and fix.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> private static int Compare(Comparable<T> comp1, Comparable<T> comp2) {\n if (comp1 == null) {\n return ((comp2 == null) ? 0 : -1);\n }\n return comp1.CompareTo(comp2);\n }\n</code></pre>\n</blockquote>\n\n<p>For consistency, this requires that subclasses guarantee that <code>CompareTo(null)</code> returns a positive value, but that requirement isn't documented.</p>\n\n<p>Perhaps a better solution would be:</p>\n\n<pre><code> private static int Compare(Comparable<T> comp1, Comparable<T> comp2) {\n if (comp1 == null) {\n return comp2 == null ? 0 : 0.CompareTo(comp2.CompareTo(comp1));\n }\n return comp1.CompareTo(comp2);\n }\n</code></pre>\n\n<p>That way the only requirement is that <code>CompareTo(null)</code> be consistent.</p>\n\n<p>There may be a more elegant way of inverting the sense of a comparison, but that's the easiest one I can think of which doesn't fail on corner cases.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T17:23:23.563",
"Id": "405869",
"Score": "0",
"body": "Thanks @petertaylor. I suppose I just assumed that `CompareTo(null)` should return a positive value. I'll take your advice and change the `Compare` method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T17:34:36.750",
"Id": "405872",
"Score": "0",
"body": "On the subject of implementing IComparable, it is true that this is not suggested in the documentation. I got the recommendation from a Stack Overflow answer (that I now can't find) that argued for implementing IComparable in order to avoid problems when sorting an ArrayList containing objects of the class. If I don't implement IComparable, I get an InvalidOperationException when sorting an ArrayList containing objects of my class. I wouldn't use an ArrayList myself, but I suppose I should allow for people who would. Do you still recommend against implementing IComparable?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T20:26:06.240",
"Id": "405907",
"Score": "0",
"body": "@Blackwood, I see it as a tradeoff between a little pain for people who chose runtime checks over compile-time checks by not upgrading to Net Framework 2.0 vs a little pain for everyone else. As far as I'm concerned, let the `ArrayList` users call a `Sort` overload which takes an `IComparer`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T20:32:31.613",
"Id": "405909",
"Score": "0",
"body": "That makes sense (and simplifies my code). Thanks."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T15:41:41.127",
"Id": "209982",
"ParentId": "209976",
"Score": "7"
}
},
{
"body": "<h3>Stack Overflow Exception</h3>\n\n<p>You did not test your code appropriately because it throws the <code>StackOverflowException</code> for</p>\n\n<pre><code>(x == y)\n</code></pre>\n\n<p>This is the rare case when this happens and is triggered by these two methods.</p>\n\n<blockquote>\n<pre><code>public static bool operator ==(Comparable<T> comp1, Comparable<T> comp2)\n{\n return Compare(comp1, comp2) == 0;\n}\n</code></pre>\n</blockquote>\n\n<p>This calls the <code>Compare</code> method which in turn calls <code>comp1 == null</code> which means that <code>Compare</code> is called... and so on...</p>\n\n<blockquote>\n<pre><code>private static int Compare(Comparable<T> comp1, Comparable<T> comp2)\n{\n if (comp1 == null)\n {\n return ((comp2 == null) ? 0 : -1);\n }\n return comp1.CompareTo(comp2);\n}\n</code></pre>\n</blockquote>\n\n<p>When implementing comparers or equalities you should <strong>always</strong> use <code>object.ReferenceEquals</code> for checking arguments against <code>null</code> and <strong>never</strong> <code>== null</code>.</p>\n\n<hr>\n\n<p>You should also use standard names for parameters like <code>x</code> & <code>y</code> or <code>left</code> & <code>right</code> and not <code>comp1</code> and <code>comp2</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T17:54:08.563",
"Id": "405883",
"Score": "0",
"body": "How embarrassing. I had not tested the equality operator since I converted the code from VB.Net (where `comp1 Is Nothing` does not cause the error) to C#. I apologize."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T17:56:38.130",
"Id": "405885",
"Score": "1",
"body": "@Blackwood yeah, VB.NET is full of surprises by doing things differently than the rest of the world ;-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T17:09:26.923",
"Id": "209989",
"ParentId": "209976",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "209982",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T14:50:42.413",
"Id": "209976",
"Score": "6",
"Tags": [
"c#"
],
"Title": "Base class for implementing IComparable<T>"
} | 209976 |
<p>I am working on a choice-based simulation and players have to choose between different locations, I am pushing those choices to an array <code>locationLog</code> and my <code>MakeStats()</code> function below builds an array from it. I tend to break code into bits because it helps me, but want to make sure others can understand it.</p>
<pre><code>var hasAttorney = false;
var hasMoney = true;
var hasAC = true;
var currentlocation = "home";
var locationLog = []; //push locations
//Builds a JSON object with game stats
function MakeStats() {
let home = 0,
motel = 0,
relative = 0,
shelter = 0,
apartment = 0;
for (var i = 0; i < locationLog.length; i++) {
if (locationLog[i] === "home")
home++;
else if (locationLog[i] === "motel")
motel++;
else if (locationLog[i] === "relative")
relative++;
else if (locationLog[i] === "shelter")
shelter++;
else if (locationLog[i] === "apartment")
apartment++;
}
let tempJSON = {
"location": {
"home": home,
"motel": motel,
"relative": relative,
"shelter": shelter,
"apartment": apartment
},
"moneyLeft": money,
"ACLeft": AC,
"finalDestination": currentlocation,
"hasAttorney": hasAttorney,
"hasAC": hasAC,
"hasMoney": hasMoney
};
statJSON = tempJSON;
localStorage.setItem("playerStats", JSON.stringify(statJSON));
console.log(statJSON);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T15:39:50.887",
"Id": "405852",
"Score": "0",
"body": "Welcome to Code review! Some variables are declared in that function but others are not - e.g. `AC`, `money`, `locationLog`, etc. Where are those defined? Can you update the code sample to provide sample values for those?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T16:35:18.903",
"Id": "405861",
"Score": "0",
"body": "updated the variables, the JSON works just fine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T16:39:09.823",
"Id": "405862",
"Score": "0",
"body": "okay I am guessing `money` is declared something like `var money = 0` and `AC` something like `var AC = 0`;?"
}
] | [
{
"body": "<h2>Feedback</h2>\n\n<h3>Simplifying block of <code>if</code> statements</h3>\n\n<p>The set of <code>if</code> statements is a bit repetitive, especially since the values match the property names of the nested JSON object that is stored in <code>localStorage</code>. A simpler way to implement this would be to declare <code>tempJSON</code> first, with the nested location values at <code>0</code>, then iterate through <code>locationLog</code> and increment the appropriate nested value. One can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty\" rel=\"nofollow noreferrer\"><code>Object.hasOwnProperty()</code></a>:</p>\n\n<pre><code>if (tempJSON.location.hasOwnProperty(locationLog[i])) {\n tempJSON.location[locationLog[i]]++;\n</code></pre>\n\n<p>Or use the <code>in</code> operator:</p>\n\n<pre><code>if (locationLog[i] in tempJSON.location) {\n tempJSON.location[locationLog[i]]++;\n</code></pre>\n\n<p>Both will work the same. For the discussion of the difference, see answers to <a href=\"https://stackoverflow.com/q/13632999/1575353\"><em>if (key in object) or if(object.hasOwnProperty(key)</em> on SO</a>.</p>\n\n<h3>Iterating over <code>locationLog</code></h3>\n\n<p>Since your code is using <a href=\"/questions/tagged/ecmascript-6\" class=\"post-tag\" title=\"show questions tagged 'ecmascript-6'\" rel=\"tag\">ecmascript-6</a> features like <code>let</code>, it can also utilize the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\"><code>for...of</code></a> loop construct instead of setting up variable <code>i</code> and using it to index into the array.</p>\n\n<pre><code>for (const location of locationLog) {\n if (location in tempJSON.location) {\n</code></pre>\n\n<h3>Default to using <code>const</code> for variables to avoid unintentional re-assignment</h3>\n\n<p>Variables that should not be re-assigned, like <code>tempJSON</code> can be declared with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\"><code>const</code></a> instead of <code>let</code>. If you determine later that re-assignment should be allowed (e.g. in a loop or conditional expression) then use <code>let</code>.</p>\n\n<h3>variable <code>statJSON</code></h3>\n\n<p>That may be a global variable or else you just didn't include the local declaration (and assignment) but if it is a global variable then consider making it a local variable. In the scope of the code you included, it appears superfluous...</p>\n\n<h2>Rewritten code</h2>\n\n<p>See the snippet below utilizing the feedback above.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var hasAttorney = false;\nvar hasMoney = true;\nvar money = 0;\nvar AC = 1;\nvar hasAC = true;\nvar currentlocation = \"home\";\nvar locationLog = [\"relative\", \"shelter\", \"relative\"]; //push locations\n\n//Builds a JSON object with game stats\nfunction MakeStats() {\n const tempJSON = {\n \"location\": {\n \"home\": 0,\n \"motel\": 0,\n \"relative\": 0,\n \"shelter\": 0,\n \"apartment\": 0\n },\n \"moneyLeft\": money,\n \"ACLeft\": AC,\n \"finalDestination\": currentlocation,\n \"hasAttorney\": hasAttorney,\n \"hasAC\": hasAC,\n \"hasMoney\": hasMoney\n };\n for (const location of locationLog) {\n if (location in tempJSON.location) {\n tempJSON.location[location]++;\n }\n }\n \n //localStorage not allowed in SE snippets for security reasons\n //localStorage.setItem(\"playerStats\", JSON.stringify(tempJSON));\n console.log(tempJSON);\n}\nMakeStats();</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T19:22:51.330",
"Id": "405901",
"Score": "1",
"body": "much better, just getting acquainted with ES6. It's a bit weird an object with const lets you update values."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T19:24:45.813",
"Id": "405902",
"Score": "1",
"body": "Yes - \"_The **`const` declaration** creates a read-only reference to a value. It does **not** mean the value it holds is immutable, just that the variable identifier cannot be reassigned._\" - [MDN documentation for `const`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const#Description)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T03:20:23.867",
"Id": "405927",
"Score": "0",
"body": "`for (let location of locationLog)` could be `for (const location of locationLog)` if `location` is not going to be reassigned"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T05:15:03.733",
"Id": "405935",
"Score": "0",
"body": "Good on ya! [the documentation on MDN even says so](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of#Examples) ... but then the subsequent examples about iterating over a string use `let` though the value isn't reassigned inside the loop block- SERENITY NOW!! Maybe I should edit those examples"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T17:03:02.337",
"Id": "209988",
"ParentId": "209977",
"Score": "2"
}
},
{
"body": "<p>Some extra points that Sam Onแดแดแด's good review skipped.</p>\n\n<h2>Capitalizing function names</h2>\n\n<p>Don't capitalize functions if they are not used to create an object. In JavaScript we only capitalize functions or objects that can be instantiated with the <code>new</code> token. Thus <code>MakeStats</code> should be <code>makeStats</code>.</p>\n\n<p>However if you were to return the object <code>statJSON</code> then you could use the name <code>MakeStats</code> to indicate that it instantiates an object. You can then create the object in 3 ways, each of which return the same object.</p>\n\n<pre><code> // last 2 lines of MakeStats to be\n return statJSON;\n}\n\nconst s1 = new MakeStats();\nconst s2 = new MakeStats; // with new objects () is not needed if there are no arguments\nconst s3 = MakeStats();\n</code></pre>\n\n<h2>Quoted property names</h2>\n\n<p>I see this a lot, when people create an object that is to be stringified. For some reason quoted property names are used. Doing so is just adding unneeded noise to the code. </p>\n\n<p>The only time you need to use quotes to define a property is if the property is not a valid javascript variable name. e.g. <code>{data-one: \"one\"}</code> will throw an error as <code>data-one</code> is not a valid name, you would thus write it <code>{\"data-one\": \"one\"}</code> </p>\n\n<h2>Shorthand property names (ES2015)</h2>\n\n<p>Use object property shorthand if you are adding existing named variables to an object.</p>\n\n<p>You have</p>\n\n<pre><code>let tempJSON = {\n \"location\": {\n \"home\": home,\n \"motel\": motel,\n \"relative\": relative,\n \"shelter\": shelter,\n \"apartment\": apartment\n },\n \"moneyLeft\": money,\n \"ACLeft\": AC,\n \"finalDestination\": currentlocation,\n \"hasAttorney\": hasAttorney,\n \"hasAC\": hasAC,\n \"hasMoney\": hasMoney\n};\n</code></pre>\n\n<p>can be written as</p>\n\n<pre><code>const tempJSON = {\n location: {home, motel, relative, shelter, apartment},\n moneyLeft: money,\n ACLeft: AC,\n finalDestination: currentlocation,\n hasAttorney, \n hasAC,\n hasMoney\n};\n</code></pre>\n\n<p>the resulting object is identical to the longhand version.</p>\n\n<h2><code>localStorage</code></h2>\n\n<p>You can use simpler notation when accessing <code>localStorage</code>.</p>\n\n<p>You have </p>\n\n<pre><code>localStorage.setItem(\"playerStats\", JSON.stringify(statJSON));\n</code></pre>\n\n<p>is identical to </p>\n\n<pre><code>localStorage.playerStats = JSON.stringify(statJSON);\n</code></pre>\n\n<p>The same applies to reading from <code>localStorage</code></p>\n\n<pre><code>stats = localStorage.playerStats; // Note If that data is not there you get undefined\n // Note All data from local storage is a string\n</code></pre>\n\n<h2>Don't trust <code>localStorage</code></h2>\n\n<p>There is no way to guarantee that <code>localStorage</code> content written in one session will be available next time, nor can you trust the data you read back, and many 3rd party extensions have full access to <code>localStorage</code>. </p>\n\n<p>If the data is important, requires trust, or contains personal client data it should be saved on the server.</p>\n\n<h2>Warning about cyclic data</h2>\n\n<p><code>JSON.stringify</code> will throw a <code>TypeError: \"Converting circular structure to JSON\"</code> if the data contains cyclic references. </p>\n\n<p>Cyclic references are everywhere in JavaScript so if you are stringifying data from unknown or unsure sources is pays to wrap the <code>stringify</code> in a <code>try</code> <code>catch</code> so at least you can recover gracefully. As your function is using data from outside its control it would pay to be safe (unless you are in full control of all data).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T05:34:19.657",
"Id": "405936",
"Score": "0",
"body": "`Don't capitalize functions if they are not used to create an object. In JavaScript we only capitalize functions or objects that can be instantiated with the new token.` I considered Modifying the second sentence to begin \"In _idiomatic_ JavaScript...\" but am not sure what you would want.... it may be wise to mention conventions/style guides there..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T04:18:14.523",
"Id": "210017",
"ParentId": "209977",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "209988",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T14:58:45.557",
"Id": "209977",
"Score": "3",
"Tags": [
"javascript",
"json",
"ecmascript-6",
"iteration",
"scope"
],
"Title": "Storing statistics as JSON in a simulation game"
} | 209977 |
<p>I'm making an e-commerce site, using MySQL for storing data.</p>
<p><a href="https://i.stack.imgur.com/ATX8V.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ATX8V.png" alt="Diagram of my database"></a></p>
<pre><code> CREATE TABLE `admins` (
`id` int(10) UNSIGNED NOT NULL,
`shop_id` int(10) UNSIGNED DEFAULT NULL,
`name` varchar(75) COLLATE utf8mb4_unicode_ci NOT NULL,
`username` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL,
`phone` int(11) NOT NULL,
`email` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
`email_verified_at` timestamp NULL DEFAULT NULL,
`password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `brands` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `brand_models` (
`id` int(10) UNSIGNED NOT NULL,
`brand_id` int(10) UNSIGNED DEFAULT NULL,
`product_type_id` int(10) UNSIGNED DEFAULT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `categories` (
`id` int(10) UNSIGNED NOT NULL,
`_lft` int(10) UNSIGNED NOT NULL DEFAULT '0',
`_rgt` int(10) UNSIGNED NOT NULL DEFAULT '0',
`parent_id` int(10) UNSIGNED DEFAULT NULL,
`top` tinyint(4) NOT NULL,
`sort_order` int(11) NOT NULL,
`status` tinyint(4) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `countries` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `markets` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`address` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`shops_count` int(11) NOT NULL,
`products_count` int(11) NOT NULL,
`photo` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`status` tinyint(4) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `migrations` (
`id` int(10) UNSIGNED NOT NULL,
`migration` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`batch` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `m_options` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `m_option_values` (
`id` int(10) UNSIGNED NOT NULL,
`m_option_id` int(10) UNSIGNED DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `options` (
`id` int(10) UNSIGNED NOT NULL,
`product_type_id` int(10) UNSIGNED DEFAULT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `option_values` (
`id` int(10) UNSIGNED NOT NULL,
`option_id` int(10) UNSIGNED DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `password_resets` (
`email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`token` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `products` (
`id` int(10) UNSIGNED NOT NULL,
`product_type_id` int(10) UNSIGNED DEFAULT NULL,
`category_id` int(10) UNSIGNED DEFAULT NULL,
`market_id` int(10) UNSIGNED DEFAULT NULL,
`shop_id` int(10) UNSIGNED DEFAULT NULL,
`country_id` int(10) UNSIGNED DEFAULT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`price` int(11) NOT NULL,
`discount_price` int(11) NOT NULL,
`discount` int(11) NOT NULL,
`quantity` int(11) NOT NULL,
`views` int(11) NOT NULL,
`likes` int(11) NOT NULL,
`sort_order` int(11) NOT NULL,
`status` tinyint(4) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `product_m_option_values` (
`id` int(10) UNSIGNED NOT NULL,
`product_type_id` int(10) UNSIGNED DEFAULT NULL,
`m_option_id` int(10) UNSIGNED DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `product_option_values` (
`id` int(10) UNSIGNED NOT NULL,
`product_id` int(10) UNSIGNED DEFAULT NULL,
`option_id` int(10) UNSIGNED DEFAULT NULL,
`option_value_id` int(10) UNSIGNED DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `product_types` (
`id` int(10) UNSIGNED NOT NULL,
`category_id` int(10) UNSIGNED DEFAULT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `product_type_m_options` (
`id` int(10) UNSIGNED NOT NULL,
`product_type_id` int(10) UNSIGNED DEFAULT NULL,
`m_option_id` int(10) UNSIGNED DEFAULT NULL,
`m_option_value_id` int(10) UNSIGNED DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `shops` (
`id` int(10) UNSIGNED NOT NULL,
`market_id` int(10) UNSIGNED DEFAULT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`address` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`product_types_count` int(11) NOT NULL,
`products_count` int(11) NOT NULL,
`views` int(11) NOT NULL,
`photo` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`status` tinyint(4) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
ALTER TABLE `admins`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `admins_username_unique` (`username`),
ADD UNIQUE KEY `admins_phone_unique` (`phone`),
ADD UNIQUE KEY `admins_email_unique` (`email`),
ADD KEY `admins_shop_id_foreign` (`shop_id`);
ALTER TABLE `brands`
ADD PRIMARY KEY (`id`);
ALTER TABLE `brand_models`
ADD PRIMARY KEY (`id`),
ADD KEY `brand_models_brand_id_foreign` (`brand_id`),
ADD KEY `brand_models_product_type_id_foreign` (`product_type_id`);
ALTER TABLE `categories`
ADD PRIMARY KEY (`id`),
ADD KEY `categories__lft__rgt_parent_id_index` (`_lft`,`_rgt`,`parent_id`);
ALTER TABLE `countries`
ADD PRIMARY KEY (`id`);
ALTER TABLE `markets`
ADD PRIMARY KEY (`id`);
ALTER TABLE `migrations`
ADD PRIMARY KEY (`id`);
ALTER TABLE `m_options`
ADD PRIMARY KEY (`id`);
ALTER TABLE `m_option_values`
ADD PRIMARY KEY (`id`),
ADD KEY `m_option_values_m_option_id_foreign` (`m_option_id`);
ALTER TABLE `options`
ADD PRIMARY KEY (`id`),
ADD KEY `options_product_type_id_foreign` (`product_type_id`);
ALTER TABLE `option_values`
ADD PRIMARY KEY (`id`),
ADD KEY `option_values_option_id_foreign` (`option_id`);
ALTER TABLE `password_resets`
ADD KEY `password_resets_email_index` (`email`);
ALTER TABLE `products`
ADD PRIMARY KEY (`id`),
ADD KEY `products_product_type_id_foreign` (`product_type_id`),
ADD KEY `products_category_id_foreign` (`category_id`),
ADD KEY `products_market_id_foreign` (`market_id`),
ADD KEY `products_shop_id_foreign` (`shop_id`),
ADD KEY `products_country_id_foreign` (`country_id`);
ALTER TABLE `product_m_option_values`
ADD PRIMARY KEY (`id`),
ADD KEY `product_m_option_values_product_type_id_foreign` (`product_type_id`),
ADD KEY `product_m_option_values_m_option_id_foreign` (`m_option_id`);
ALTER TABLE `product_option_values`
ADD PRIMARY KEY (`id`),
ADD KEY `product_option_values_product_id_foreign` (`product_id`),
ADD KEY `product_option_values_option_id_foreign` (`option_id`),
ADD KEY `product_option_values_option_value_id_foreign` (`option_value_id`);
ALTER TABLE `product_types`
ADD PRIMARY KEY (`id`),
ADD KEY `product_types_category_id_foreign` (`category_id`);
ALTER TABLE `product_type_m_options`
ADD PRIMARY KEY (`id`),
ADD KEY `product_type_m_options_product_type_id_foreign` (`product_type_id`),
ADD KEY `product_type_m_options_m_option_id_foreign` (`m_option_id`),
ADD KEY `product_type_m_options_m_option_value_id_foreign` (`m_option_value_id`);
ALTER TABLE `shops`
ADD PRIMARY KEY (`id`),
ADD KEY `shops_market_id_foreign` (`market_id`);
</code></pre>
<p>I have previously used only <code>LIKE</code> based searches. But in e-commerce I'll have to use full-text search. Searching must be from <code>name</code> column of every table where <code>name</code> column exists.</p>
<p>For now I want to index' my database only in MySQL but I'm not sure if I can and if it is even possible with this kind of structure.</p>
<p>And later on, when I'll have enough time to learn Elasticsearch I'm planing to use it for indexing.</p>
<p>I want to know your opinions about my database and get your advice for my search. </p>
<ul>
<li>Is it the best DB structure or should I change something?</li>
<li>Will it be good for searching? </li>
<li>Is this DB structure indexible in MySQL and/or Elasticsearch?</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T15:04:35.237",
"Id": "405838",
"Score": "2",
"body": "Welcome to Code Review! Please post your entire schema (the `CREATE TABLE` statements), because that is the code to be reviewed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T15:09:57.620",
"Id": "405840",
"Score": "0",
"body": "ok, but ist hard to add code here"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T15:11:36.110",
"Id": "405842",
"Score": "1",
"body": "Paste the code into the question editor, then highlight it and press Ctrl-K to mark it as a code block."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T15:01:31.103",
"Id": "209978",
"Score": "2",
"Tags": [
"sql",
"mysql",
"database",
"e-commerce"
],
"Title": "MySQL database schema for e-commerce website"
} | 209978 |
<p>I've written an implementation of <code>malloc</code>, <code>realloc</code>, and <code>free</code>. I wanted to make a <code>malloc</code> implementation that is sufficiently simple and easy to maintain.</p>
<p>I don't care so much for performance, but I'd like to know if anything stands out that can easily be fixed.</p>
<p>An explanation of how it works is in the source file. Other malloc reviews I've seen on this site use linked lists, but just note that this implementation does not.</p>
<p>The prefix <code>alloy</code> is the name of the project, so if you see it in the global functions, that's what it means and you can ignore it.</p>
<p>Here's <code>malloc.h</code></p>
<pre><code>#ifndef alloy_malloc_h
#define alloy_malloc_h
#ifdef __cplusplus
extern "C" {
#endif
#ifndef NULL
/** This value represents an invalid memory address.
* It contains a value of zero, by default. Zero is
* usually the standard value of a 'null' pointer. */
#define NULL ((void *) 0x00)
#endif
/** This function must be called for the memory
* allocation functions to work. It tells malloc
* where it can find extra memory at.
* @param addr The base address to allocate memory at.
* @param size The max number of bytes that can be allocated.
* This must be at least 64 bytes on 64-bit systems and
* 32 bytes on 32-bit systems.
* @returns Zero on success, a negative one on failure. */
int alloy_init_heap(void *addr, unsigned long int size);
/** This function allocates a new memory section of a specified size.
* @param size The number of bytes to allocate.
* @returns A pointer to the memory section, if one is
* found that can fit the number of bytes requested.
* If the memory can't be allocated, then a @ref NULL
* value is returned instead. */
void *alloy_malloc(unsigned long int size);
/** Resizes an existing memory section that was allocated with @ref alloy_malloc.
* New memory can also be allocated with this function, by passing @p addr with
* a value of @ref NULL. The data from the previous section is copied to the new section.
* @param addr The address of the memory section to resize.
* @param size The number of bytes to resize the section to.
* @returns A pointer to the newly allocation memory section.
* If space could not be found for the new section, then a value
* of @ref NULL is returned instead and the memory section remains unchanged. */
void *alloy_realloc(void *addr, unsigned long int size);
/** Releases memory previously allocated with @ref alloy_malloc
* or @ref alloy_realloc. If the memory address passed to this
* function does not exist within the heap, then this function has no effect.
* @param addr The address of the memory section to free. */
void alloy_free(void *addr);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif // alloy_malloc_h
</code></pre>
<p>Here's <code>malloc.c</code></p>
<pre><code>#include "malloc.h"
/* This file contains the malloc implementation for the Alloy project.
*
* Here's how it works.
*
* The implementation is made up of a 'header' and an allocation table.
*
* The header is used for tracking the position of the allocation table
* entries, then number of allocations, and the size of the heap. The header
* sits at the very beginning of the heap and remains there for the duration
* of the library usage.
*
* The allocation table is used for keeping track of the memory sections
* to ensure that they don't overlap. When the heap is first initialized,
* the allocation table begins immediately after the header. As more allocations
* are added to the table, it gets resized and moved around the heap. The
* first two allocations in the allocation table that are made is the heap
* header allocation and the allocation entry for the allocation table itself.
* Thus, the allocation table is able to resize itself.
* */
/** Used for memory sizes. */
typedef unsigned long int size_type;
/** The base address of the heap. */
unsigned char *heap_addr = NULL;
/** A single memory allocation. */
struct allocation {
/// The memory address that the
/// allocation is responsible for.
void *addr;
/// The number of bytes allocated
/// for the address.
size_type size;
};
/** Gives the allocation the highest address value
* and a size of zero. */
static void mark_allocation_invalid(struct allocation *allocation) {
allocation->addr = (void *) 0xffffffffffffffff;
allocation->size = 0;
}
/** Indicates whether or not an allocation is invalid. */
static unsigned int is_invalid_allocation(const struct allocation *allocation) {
return allocation->addr == ((void *) 0xffffffffffffffff);
}
/** Magic number used for sanity checking (= speed of light in m/s). */
const size_type valid_magic_number = 299792458;
/** Used at the start of the heap
* to keep track of the allocation table. */
struct header {
/** Used for verifying that the
* heap was initialized properly. */
size_type magic_number;
/** The array of allocations. */
struct allocation *allocations;
/** The number of allocations made. */
size_type allocation_count;
/** The size of the heap (including this header.) */
size_type heap_size;
};
/** Retrieves the header from the heap address.
* This function also checks to ensure that the
* heap has been initialized first.
* @returns A pointer to the header. */
static struct header *get_header() {
if (heap_addr == NULL) {
return NULL;
}
struct header *header = (struct header *) heap_addr;
if (header->magic_number != valid_magic_number) {
return NULL;
}
return header;
}
/** Copies memory from one location to another. */
static void alloy_memcpy(void *dst, const void *src, size_type size) {
unsigned char *d = (unsigned char *) dst;
const unsigned char *s = (const unsigned char *) src;
for (size_type i = 0; i < size; i++) {
d[i] = s[i];
}
}
/** Performs a single iteration of the bubblesort algorithm,
* where the sort key is the allocation address. The number of
* sorted items is returned. */
static size_type single_bubblesort(struct allocation *allocations,
size_type allocation_count) {
struct allocation *a;
struct allocation *b;
struct allocation tmp;
size_type sorted = 0;
for (size_type i = 0; (i + 1) < allocation_count; i++) {
a = &allocations[i];
b = &allocations[i + 1];
size_type a_addr = (size_type) a->addr;
size_type b_addr = (size_type) b->addr;
if (a_addr > b_addr) {
tmp.addr = a->addr;
tmp.size = a->size;
a->addr = b->addr;
a->size = b->size;
b->addr = tmp.addr;
b->size = tmp.size;
sorted = 1;
}
}
return sorted;
}
/** Sorts the allocations to have ascending
* starting addresses. Should be called whenever
* the allocation table is modified. */
static void sort_allocations() {
struct header *header = get_header();
if (header == NULL) {
return;
}
size_type sorted = 0;
for (;;) {
sorted = single_bubblesort(header->allocations, header->allocation_count);
if (!sorted) {
break;
}
}
}
/** Locates an address that will fit the specified size.
* This function does not reserve the address that is found,
* it just locates an address that will fit the space requested. */
static void *find_space_for(size_type size) {
struct header *header = get_header();
if (header == NULL) {
return NULL;
}
size_type next_addr = (size_type) heap_addr;
for (size_type i = 0; i < header->allocation_count; i++) {
struct allocation *allocation = &header->allocations[i];
size_type allocation_addr = (size_type) allocation->addr;
if ((next_addr + size) <= allocation_addr) {
break;
} else {
next_addr = allocation_addr + allocation->size;
}
}
if ((next_addr + size) <= (((size_type) heap_addr) + header->heap_size)) {
return (void *) next_addr;
}
return NULL;
}
/** Locates an allocation using iterative binary search algorithm,
* where the search key is the allocation address. */
static struct allocation *binary_search(struct allocation *allocations,
size_type left_index,
size_type right_index,
size_type addr) {
while (left_index <= right_index) {
size_type middle_index = left_index + ((right_index - left_index) / 2);
size_type candidate_addr = (size_type) allocations[middle_index].addr;
if (candidate_addr == addr) {
return &allocations[middle_index];
} else if (candidate_addr < addr) {
left_index = middle_index + 1;
} else {
right_index = middle_index - 1;
}
}
return NULL;
}
/** Locates the allocation entry for a specified address.
* If no allocation exists for the specified address,
* then a null pointer is returned. */
static struct allocation *find_allocation(void *addr) {
/* Check if addr is NULL so we can just quickly exit. */
if (addr == NULL) {
return NULL;
}
struct header *header = get_header();
if (header == NULL) {
return NULL;
}
return binary_search(header->allocations, 0, header->allocation_count, (size_type) addr);
}
/** Creates an allocation entry within the allocation table. */
static struct allocation *create_allocation(void) {
struct header *header = get_header();
if (header == NULL) {
return NULL;
}
size_type next_allocations_size = sizeof(struct allocation) * (header->allocation_count + 1);
struct allocation *next_allocations = find_space_for(next_allocations_size);
if (next_allocations == NULL) {
return NULL;
}
for (size_type i = 0; i < header->allocation_count; i++) {
struct allocation *allocation = &header->allocations[i];
if (allocation->addr == header->allocations) {
allocation->addr = next_allocations;
allocation->size = next_allocations_size;
sort_allocations();
break;
}
}
alloy_memcpy(next_allocations, header->allocations, sizeof(struct allocation) * header->allocation_count);
header->allocations = next_allocations;
header->allocation_count++;
struct allocation *new_allocation = &next_allocations[header->allocation_count - 1];
mark_allocation_invalid(new_allocation);
return new_allocation;
}
/** Removes an invalid allocation from the end of the
* allocation table, if one is present. */
static void remove_invalid_allocation_if_present(void) {
struct header *header = get_header();
if (header == NULL) {
return;
}
if (header->allocation_count <= 0) {
return;
}
struct allocation *last_allocation = &header->allocations[header->allocation_count - 1];
if (is_invalid_allocation(last_allocation)) {
header->allocation_count--;
}
}
int alloy_init_heap(void *addr, unsigned long int size) {
/** Ensure that the heap given can fit a header and two allocations. */
if (size < (sizeof(struct header) + (sizeof(struct allocation) * 2))) {
return -1;
}
heap_addr = (unsigned char *) addr;
/** This creates an allocation table for the heap header.
* This ensures that memory allocations won't allocate space
* over the header. */
struct allocation *first_allocation = (struct allocation *) &heap_addr[sizeof(struct header)];
first_allocation->addr = heap_addr;
first_allocation->size = sizeof(struct header);
/** This creates an allocation entry for the allocation table itself.
* This ensures that memory isn't allocated over the allocation table
* and it also allows the allocation table to be resized. */
struct allocation *second_allocation = first_allocation + 1;
second_allocation->addr = first_allocation;
second_allocation->size = sizeof(struct allocation) * 2;
/** Initialize the header. */
struct header *header = (struct header *) heap_addr;
header->magic_number = valid_magic_number;
header->allocations = first_allocation;
header->allocation_count = 2;
header->heap_size = size;
return 0;
}
void *alloy_malloc(unsigned long int size) {
return alloy_realloc(NULL, size);
}
void *alloy_realloc(void *addr, unsigned long int size) {
struct header *header = get_header();
if (header == NULL) {
return NULL;
}
struct allocation *dst_entry = NULL;
struct allocation *existing_entry = find_allocation(addr);
if (existing_entry != NULL) {
dst_entry = existing_entry;
} else {
dst_entry = create_allocation();
if (dst_entry == NULL) {
return NULL;
}
}
/* align size to 16 bytes. */
size = ((size + 15) / 16) * 16;
void *next_addr = find_space_for(size);
if (next_addr == NULL) {
remove_invalid_allocation_if_present();
return NULL;
}
if (existing_entry != NULL) {
alloy_memcpy(next_addr, existing_entry->addr, existing_entry->size);
}
dst_entry->addr = next_addr;
dst_entry->size = size;
sort_allocations();
return next_addr;
}
void alloy_free(void *addr) {
struct header *header = get_header();
if (header == NULL) {
return;
}
struct allocation *allocation = find_allocation(addr);
if (allocation != NULL) {
mark_allocation_invalid(allocation);
/** Invalid allocations go to the back
* of the allocation table when sorted. */
sort_allocations();
/** Now that the free'd allocation is at
* the back of the table, just reduce the
* allocation count to get rid of it. */
header->allocation_count--;
}
}
</code></pre>
<p>Here's a test I wrote to verify the functions.</p>
<pre><code>#include "malloc.h"
#include <assert.h>
#include <string.h>
int main(void) {
/* Initialize the heap. */
unsigned char heap[1024];
int err = alloy_init_heap(heap, sizeof(heap));
assert(err == 0);
/* Allocate memory that is definitely out of range of
* the heap size given. Ensure that it fails. */
unsigned char *failed_malloc = (unsigned char *) alloy_malloc(2048);
assert(failed_malloc == NULL);
/* Allocate three ranges, A, B, and C and allocate
* them on the heap. */
unsigned char a_expected[32];
memset(a_expected, 'a', sizeof(a_expected));
unsigned char b_expected[64];
memset(b_expected, 'b', sizeof(b_expected));
unsigned char b_expected_2[128];
memset(b_expected_2, 'B', sizeof(b_expected_2));
unsigned char c_expected[128];
memset(c_expected, 'c', sizeof(c_expected));
unsigned char *a = (unsigned char *) alloy_malloc(32);
assert(a != NULL);
memset(a, 'a', 32);
unsigned char *b = (unsigned char *) alloy_malloc(64);
assert(b != NULL);
memset(b, 'b', 64);
unsigned char *c = (unsigned char *) alloy_malloc(128);
assert(c != NULL);
memset(c, 'c', 128);
/* Check to ensure that all memory ranges contain the
* values that were given to them. Make sure they aren't
* overlapping. */
assert(memcmp(a, a_expected, sizeof(a_expected)) == 0);
assert(memcmp(b, b_expected, sizeof(b_expected)) == 0);
assert(memcmp(c, c_expected, sizeof(c_expected)) == 0);
/* The remaining space is 832 (1024 - (32 + 64 + 128)),
* but is should fail due to the memory used for housekeeping. */
failed_malloc = (unsigned char *) alloy_malloc(832);
assert(failed_malloc == NULL);
/* Resize section B, ensure that all sections still contain
* their values. */
b = alloy_realloc(b, 128);
assert(b != NULL);
assert(memcmp(a, a_expected, sizeof(a_expected)) == 0);
assert(memcmp(b, b_expected, sizeof(b_expected)) == 0);
assert(memcmp(c, c_expected, sizeof(c_expected)) == 0);
/* Use the rest of the space in B, ensure that all sections
* still contain their values. */
memset(b, 'B', 128);
assert(memcmp(a, a_expected, sizeof(a_expected)) == 0);
assert(memcmp(b, b_expected_2, sizeof(b_expected_2)) == 0);
assert(memcmp(c, c_expected, sizeof(c_expected)) == 0);
/* Release all the memory and verify that a sufficiently
* large memory section can be allocated again (that would
* otherwise fail.) */
/* 896 is 1024 - 128. */
void *large_section = alloy_malloc(896);
assert(large_section == NULL);
alloy_free(a);
alloy_free(b);
alloy_free(c);
large_section = alloy_malloc(896);
assert(large_section != NULL);
return EXIT_SUCCESS;
}
</code></pre>
<p>Here's a test I wrote to benchmark the function (takes 40 seconds on my VM.)</p>
<pre><code>#include "malloc.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
/* Initialize the heap (32 MiB). */
unsigned long int heap_size = 32UL * 1024UL * 1024UL;
void *heap = malloc(heap_size);
if (heap == NULL) {
fprintf(stderr, "Failed to allocate heap space.\n");
return EXIT_FAILURE;
}
int err = alloy_init_heap(heap, heap_size);
if (err != 0) {
free(heap);
fprintf(stderr, "Failed to initialize heap.\n");
return EXIT_FAILURE;
}
unsigned long int leftover_size = heap_size;
unsigned long int size_index = 0;
unsigned long int size_array[8] = {
8, 16, 32, 64,
128, 256, 512, 1024
};
while (leftover_size > 0) {
unsigned long int size = size_array[size_index % 8];
void *addr = alloy_malloc(size);
if (addr == NULL) {
break;
}
leftover_size -= size;
size_index++;
}
unsigned long int bytes_allocated = heap_size - leftover_size;
printf("Made %lu allocations.\n", size_index);
printf("Allocated %lu bytes.\n", bytes_allocated);
printf("Used %lu bytes for house keeping.\n", leftover_size);
float space_efficiency = 0.0f;
space_efficiency += bytes_allocated;
space_efficiency /= heap_size;
space_efficiency *= 100.0f;
printf("Heap space efficiency: %f%%\n", space_efficiency);
free(heap);
return EXIT_SUCCESS;
}
</code></pre>
| [] | [
{
"body": "<p><code>0x00</code> can simply be written <code>0</code>; the hexadecimal notation doesn't buy you anything here.</p>\n\n<p>In your function signatures such as</p>\n\n<pre><code>int alloy_init_heap(void *addr, unsigned long int size);\n</code></pre>\n\n<p>you should rearrange your code so that you can use your <code>size_type</code> instead of rewriting <code>unsigned long int</code>.</p>\n\n<p>For your structs (<code>allocation</code>, <code>header</code>, etc.) use <code>typedef</code> so that you don't have to re-write <code>struct</code> on instantiation.</p>\n\n<p>In <code>alloy_memcpy</code>, rather than char-by-char copy, consider doing word-by-word copy. 64-bit copies will be much more efficient here.</p>\n\n<p>This loop:</p>\n\n<pre><code>for (;;) {\n sorted = single_bubblesort(header->allocations, header->allocation_count);\n if (!sorted) {\n break;\n }\n}\n</code></pre>\n\n<p>can simply be</p>\n\n<pre><code>while (single_bubblesort(header->allocations, header->allocation_count));\n</code></pre>\n\n<p>This:</p>\n\n<pre><code>if ((next_addr + size) <= allocation_addr) {\n</code></pre>\n\n<p>and this:</p>\n\n<pre><code>if ((next_addr + size) <= (((size_type) heap_addr) + header->heap_size)) {\n</code></pre>\n\n<p>do not need inner parens, due to operator precedence.</p>\n\n<p>Rather than writing <code>unsigned char</code> everywhere, consider using <code>uint8_t</code> from <code>stdint.h</code>.</p>\n\n<p>This:</p>\n\n<pre><code>float space_efficiency = 0.0f;\nspace_efficiency += bytes_allocated;\nspace_efficiency /= heap_size;\nspace_efficiency *= 100.0f;\n</code></pre>\n\n<p>can simply be</p>\n\n<pre><code>float space_efficiency = bytes_allocated*100. / heap_size;\n</code></pre>\n\n<p>This array:</p>\n\n<pre><code>unsigned long int size_array[8] = {\n 8, 16, 32, 64,\n 128, 256, 512, 1024\n};\n</code></pre>\n\n<p>doesn't need to be initialized literally. You can do:</p>\n\n<pre><code>for (int i = 0; i < 8; i++)\n size_array[i] = 8 << i;\n</code></pre>\n\n<p>Whenever you write <code>0xffffffffffffffff</code>, you can replace it with <code>-1</code>.</p>\n\n<p>In this function (and similar ones elsewhere):</p>\n\n<pre><code>static struct allocation *create_allocation(void) {\n</code></pre>\n\n<p><code>(void)</code> is redundant. Just write <code>()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T16:00:23.583",
"Id": "405854",
"Score": "0",
"body": "To typedef a struct just clobbers the namespace.I believe the way I wrote the loop shows the meaning behind the return value, making it a bit more readable. I figured GCC would optimize the memcpy function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T16:05:07.643",
"Id": "405857",
"Score": "1",
"body": "`(void)` and `()` don't mean the same thing, and some versions of MSVC will barf when it comes across `()` in a function declaration. Overall I was hoping to have more feedback about the `malloc` algorithm and the implementation. I feel like this answer gives more about the syntax usage then anything about the actual implementation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T16:26:06.647",
"Id": "405860",
"Score": "0",
"body": "@tayl0r Wrong. Read ISO9899, chapter 6.9.1. It spells it out: given `typedef int F(void)`, the following are compatible function signatures: `int f(void)`, and `int g()`. I've never seen MSVC choke on that, and if it ever did, MSVC would be wrong, too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T16:45:51.223",
"Id": "405864",
"Score": "0",
"body": "Sure but historically `()` meant any number of arguments and `(void)` meant none. I've always written it that way in C and like `()` in C++. MSVC probably doesn't anymore but it definitely use to, which is why I started writing it that way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T16:47:43.863",
"Id": "405865",
"Score": "0",
"body": "`()` has never, ever meant any number of arguments. `(...)`, the ellipsis token, means any number of arguments."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T17:35:29.360",
"Id": "405873",
"Score": "0",
"body": "lots of projects use `(void)`. I didn't just conjure up the practice. Please let me know if you have something to add aside from your opinion on my coding style."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T17:43:31.447",
"Id": "405877",
"Score": "1",
"body": "I'm not saying your usage is invalid or conjured. I'm suggesting ways to make your code more concise. You made a generic request for anything that 'stands out'; the above stand out to me. If I find more time I'll review your algorithm."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T22:02:55.253",
"Id": "405916",
"Score": "3",
"body": "@tay10r `(void)` and `()` in a function _declaration_ do not mean the same thing. Yet in a function _definition_, they do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T22:12:36.373",
"Id": "405917",
"Score": "2",
"body": "@Reinderien `()` in a function _declaration_ has meant \"no info about the arguments\" which does allow calling the function with any number of arguments - rightly or wrongly - without warning. A C89 throwback."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T15:47:49.010",
"Id": "209983",
"ParentId": "209981",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T15:25:22.820",
"Id": "209981",
"Score": "2",
"Tags": [
"c",
"memory-management"
],
"Title": "Simple Malloc Implementation"
} | 209981 |
<p>I have an object (<code>ShoppingCart</code>) that has a list of <code>CartItem</code>s, which contains the related <code>Product</code> and the quantity bought.</p>
<pre><code>public class ShoppingCart extends BaseEntity {
@OneToMany(mappedBy = "shoppingCart", cascade = CascadeType.ALL, orphanRemoval = true)
private List<CartItem> cartItems = new ArrayList<>();
@DateTimeFormat(pattern = "dd/MM/yyyy hh:MM:ss")
private LocalDateTime dateTime;
@Enumerated
private PaymentMethod paymentMethod = PaymentMethod.CASH;
</code></pre>
<pre><code>public class CartItem extends BaseEntity {
@ManyToOne
private Product product;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn
private ShoppingCart shoppingCart;
</code></pre>
<pre><code>public class Product extends BaseEntity {
@NotEmpty
private String name;
private double price;
private int quantity;
</code></pre>
<p>I have a view that sums all shopping carts, and I don't know if I should store that sum inside <code>ShoppingCart</code> entity, or iterate to find the sum.
Here's the code, right now I'm iterating.</p>
<pre><code>@GetMapping("/")
public String getProduct(@ModelAttribute("reportDto") ReportDto reportDto, Model model) {
double total = 0, cash = 0, credit = 0, debit = 0;
int quantity;
List<ShoppingCart> results;
if (reportDto.getBeginDate() == null || reportDto.getEndDate() == null) {
results = shoppingCartService.findAll();
} else {
results = shoppingCartService.findByDateTimeBetween(reportDto.getBeginDate(), reportDto.getEndDate());
}
total = results.stream()
.mapToDouble(shoppingCart -> shoppingCart.getCartItems().stream()
.mapToDouble(cartItem -> cartItem.getProduct().getPrice() * cartItem.getQuantity()).sum())
.sum();
quantity = results.stream().mapToInt(
shoppingCart -> shoppingCart.getCartItems().stream().mapToInt(cartItem -> cartItem.getQuantity()).sum())
.sum();
cash = results.stream().filter(shoppingCart -> shoppingCart.getPaymentMethod().isCash())
.mapToDouble(shoppingCart -> shoppingCart.getCartItems().stream()
.mapToDouble(cartItem -> cartItem.getProduct().getPrice() * cartItem.getQuantity()).sum())
.sum();
credit = results.stream().filter(shoppingCart -> shoppingCart.getPaymentMethod().isCredit())
.mapToDouble(shoppingCart -> shoppingCart.getCartItems().stream()
.mapToDouble(cartItem -> cartItem.getProduct().getPrice() * cartItem.getQuantity()).sum())
.sum();
debit = results.stream().filter(shoppingCart -> shoppingCart.getPaymentMethod().isDebit())
.mapToDouble(shoppingCart -> shoppingCart.getCartItems().stream()
.mapToDouble(cartItem -> cartItem.getProduct().getPrice() * cartItem.getQuantity()).sum())
.sum();
model.addAttribute("quantity", quantity);
model.addAttribute("cash", cash);
model.addAttribute("credit", credit);
model.addAttribute("debit", debit);
model.addAttribute("total", total);
return "reports/reports";
}
</code></pre>
<p>Also, any feedback regarding the code will be appreciated! </p>
| [] | [
{
"body": "<p>Storing the sum in <code>ShoppingCart</code> or computing it is up to you. I will compute it each time and eventually \"cache\" it if there is a lot of items.</p>\n\n<p>However your code will be more maintainable by enforcing encapuslation and moving all this computation code in the <code>ShoppingCart</code> itself. You can also continue with encapsulation by adding a <code>getUnitPrice():double</code> and <code>getPrice()</code> in your <code>CartItem</code>.</p>\n\n<p>--</p>\n\n<p>Note that <code>double</code> is not a good type for money.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T10:02:15.453",
"Id": "405959",
"Score": "0",
"body": "I've decided to use get the sum directly from the database (From '@repository', using '@Query').\nAlso changing from double to BigDecimal.\nAbout encapsulation, I got your point and I kinda agree with you, but since I'm using Spring, I'm not sure about injecting the '@repository' inside the entity to do the sum. Maybe because I'm using the database sum approach, I should leave the logic to a service?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T10:47:21.610",
"Id": "405960",
"Score": "0",
"body": "If you want to place the `sum` in your `@Entity` you should not use SQL to compute it. At some time you should decide of your architectural patterns and choose one. Are you really sure that executing an SQL query to get the sum of something that is alrdeay loaded is the best approach ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T17:54:15.527",
"Id": "406029",
"Score": "0",
"body": "I decided the sql sum over iterating inside the entities. Thanks for pointing it out!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T06:56:47.540",
"Id": "210023",
"ParentId": "209984",
"Score": "0"
}
},
{
"body": "<p>First of all i think making a view in your database which sums your needs will be better because generally sql engine sum operator's performance is way better than lopping values in programming languages.</p>\n\n<p>Second if we go through your code:\nYou have done mapping for all objects one by one. Java stream mapping is similar to for loops in compile time. So here what you make is similar to creating for loop foreach object which is bad for performance. \nTo be performance wise you can create one for loop and generate your sum values in it. </p>\n\n<p>Note: BigDecimal is the preferred way to store double money values in Java</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T09:55:08.397",
"Id": "405958",
"Score": "0",
"body": "I'll refactor and create separate methods to get the sum directly from the database (throught spring @repository, using @Query).\nI'll also change from double to BigDecimal.\nI understood the current loop problem, but since i'll change to database sum, I won't be able to sum it all in 1 loop, right? I'll have to do separate calls, for each sum."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T10:53:51.660",
"Id": "405961",
"Score": "0",
"body": "Hi @fsakiyama In database when you create your view try to put all sum operations to different columns means for instance => create view as select sum(cash) as cash, sum(quantity) as quantity and other columns from ... Then you can get all your results with only one database call."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T17:55:23.027",
"Id": "406030",
"Score": "0",
"body": "Well, I'll still have to call the method X times (sum(cash), sum(quantity), etc), but at least it will be one method only! Thanks!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T06:56:53.550",
"Id": "210024",
"ParentId": "209984",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "210024",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T15:55:40.617",
"Id": "209984",
"Score": "1",
"Tags": [
"java",
"spring",
"e-commerce",
"spring-mvc"
],
"Title": "Reporting sums of shopping carts"
} | 209984 |
<p>I am trying to learn what <a href="https://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error" rel="nofollow noreferrer">SFINAE</a> is. I believe I understand it quite well; however, I do not have a lot of practice in the subject. I mean I would find it difficult to list all the cases in which <code>SFINAE</code> should or could be used, or it would be difficult for me to immediately understand what a given sample of an SFINAE code should do. However, I believe I understand the core concept well enough to use it effectively.</p>
<p>Nonetheless looking through examples of SFINAE usage I came to the few conclusions.</p>
<p>One of which is: it is extremely pointless to use a chain of <code>std::enable_if_t</code>, <code>std::void_t</code>, <code>std::is_same</code>, etc, etc, etc, to define a single type <code>using type = int *</code>. IMHO (of a "newbie" with untrained eyes) such chains make the code less (extremely less) readable. </p>
<p>The second conclusion was: wouldn't it be useful to have the ability to check few conditions at the same time?</p>
<p>So I created this alias: (well "created" is waaay too big word... I just wrote 4 lines of code...)</p>
<pre><code>template<typename T, typename ...>
using sfinae = T;
template<typename T, typename ...>
using SFINAE = T;
</code></pre>
<h3>Usage examples</h3>
<pre><code>// 1) within class declaration:
template <typename T,
sfinae<bool,
std::enable_if_t<std::is_integral_v<T>>,
std::enable_if_t<std::is_arithmetic_v<T>>
> = true /* provide default option, bc reasons */>
class foo;
// 2) within function declaration:
template <typename T,
sfinae<bool,
std::enable_if_t<std::is_integral_v<T>>,
std::enable_if_t<std::is_arithmetic_v<T>>
> = true /* provide default option, bc reasons */>
void foo;
// 3) as a function return type:
template <typename T>
sfinae<T,
std::enable_if_t<std::is_integral_v<T>>,
std::enable_if_t<std::is_arithmetic_v<T>>
> const & foo(T const & val);
// 4) To define other SFINAE-conditions as aliases:
template <typename T>
using check_xyz = sfinae<void,
std::enable_if_t<std::is_integral_v<T>>,
std::enable_if_t<std::is_arithmetic_v<T>>
>;
template <typename T, typename = check_xyz<T>>
class foo;
</code></pre>
<p>And my main concern/question is: would a professional c++ developer deem <code>sfinae</*...*/></code> (as I proposed it) useful or extremely unnecessary? Are there any changes that could be introduced to the idea? </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T17:43:15.893",
"Id": "405876",
"Score": "0",
"body": "Please turn all `...` into actual code. We review only complete snippets."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T17:47:41.377",
"Id": "405878",
"Score": "7",
"body": "@t3chb0t, but the actual code is `template<typename T, typename ...> using sfinae = T;` and `template<typename T, typename ...> using SFINAE = T;` everything else is just a usage examples... Also because of the keywords \"immediate context\" (which can be found in cpp draw, the `sfinae` section. Usage of this aliases is limited declarations only. However... I could delete definitions (it would by erase all `...` by an extension)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T17:48:12.680",
"Id": "405879",
"Score": "0",
"body": "**Lacks concrete context:** Code Review requires concrete code from a project, with sufficient context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site. Please take a look at the [help/on-topic]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T17:50:16.410",
"Id": "405880",
"Score": "0",
"body": "I know, inside templates yes, but there are many `...` elsewhere and I now admit that I didn't see the `// usage examples:` comment. I'd be better if it was a heading so that it's better visible... let me edit this..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T17:50:54.390",
"Id": "405881",
"Score": "0",
"body": "@Mast but... the actual code is: `template<typename T, typename ...> using sfinae = T;` and `template<typename T, typename ...> using SFINAE = T;` Everything related to the `SFINAE` is limited to declarations.There isn't a lot i could do. I \"believe\" I provided usage examples."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T17:52:57.180",
"Id": "405882",
"Score": "1",
"body": "I think your quesiton is fine after all. Not much code but the rest is just examples that weren't easy to notice. I'll retract my close-vote now... @Mast?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T17:54:36.227",
"Id": "405884",
"Score": "0",
"body": "@t3chb0t thank you for edit. yes... I should separate the code from the examples... I am sorry, I didn't do that in the 1st place."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T18:46:12.483",
"Id": "405894",
"Score": "0",
"body": "@cukier9a7b5, I do not recommend accepting an answer yet. There might be people with even more interesting reviews, though outperforming Arthur is gonna be hard."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T18:48:36.213",
"Id": "405895",
"Score": "0",
"body": "@Incomputable ok... I am sorry... I do not know customs on this side... I am sincerely sorry for messing with you guys."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T18:54:26.383",
"Id": "405896",
"Score": "0",
"body": "@cukier9a7b5, I wouldn't consider this messing. I don't think either of us are interested in reputation at all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T20:12:41.833",
"Id": "405906",
"Score": "0",
"body": "@t3chb0t It's 4 lines of codes which boils down to a glorified alias. I still have doubts."
}
] | [
{
"body": "<h2>A bit dated...</h2>\n\n<p>First of all, let me say that since C++20 much of SFINAE will be unnecessary. Concepts have SFINAE enabled by default, have much nicer syntax, and have greater reuse capabilities.</p>\n\n<h2>Code Review</h2>\n\n<p>Personally I don't see much improvement over original one. What I would prefer instead of </p>\n\n<pre><code>template <typename T, typename ... >\n...\n</code></pre>\n\n<p>is </p>\n\n<pre><code>template <typename T, bool ... Conditionals>\n... //perform folding\n</code></pre>\n\n<p>Even then, people sometimes have non-trivial logic like AND-ing and OR-ing the results of conditionals.</p>\n\n<p>Much of the complexity lies in that conditional statements, which could be moved away by using something like template variable:</p>\n\n<pre><code>template <typename T>\nconstexpr inline bool supports_xxx = /*is_same, trivial, etc*/;\n</code></pre>\n\n<p>and then people could just use</p>\n\n<pre><code>template <typename T, typename = std::enable_if_t<supports_xxx<T>>>\n...\n</code></pre>\n\n<hr>\n\n<h2>Example</h2>\n\n<pre><code>// 1) within class declaration:\ntemplate <typename T, \n sfinae<bool,\n std::enable_if_t<std::is_integral_v<T>>,\n std::enable_if_t<std::is_arithmetic_v<T>>\n > = true /* provide default option, bc reasons */>\nclass foo;\n</code></pre>\n\n<p>is better written as</p>\n\n<pre><code>template <typename T>\nconstexpr inline bool is_int_arithmetic_v = std::is_integral_v<T> \n && std::is_arithmetic_v<T>;\n\ntemplate <typename T, \n typename = std::enable_if_t<is_int_arithmetic_v<T>>>\nclass foo;\n</code></pre>\n\n<p>Do note the <code>inline</code>, it will help users of the code to deal with ODR issues.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T18:41:00.860",
"Id": "405890",
"Score": "0",
"body": "`typename = void_t<things...>` doesn't work if you want multiple mutually exclusive templates. `bool_if_t<things...> = true` works in that case. See https://www.youtube.com/watch?v=ybaE9qlhHvw&t=37m00s ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T18:43:39.800",
"Id": "405893",
"Score": "0",
"body": "@Quuxplusone, shouldn't specialization paired with some sort of tag dispatch be used in that case? I believe it also scales better in cases where more than 2 mutually exclusive cases are present. But yeah, my advice is not a good one to make."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T18:54:51.123",
"Id": "405897",
"Score": "0",
"body": "\"Shouldn't\" is a strong word. ;) I agree that tag dispatch is usually more readable and should be preferred (or `if constexpr` in C++17). But sometimes tag dispatch can't be used; see the video's example of a conditionally `explicit` constructor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T09:14:37.360",
"Id": "405954",
"Score": "2",
"body": "Review review: It is _\"Dated\"_ _\"**since** C++20\"_ because it _\"**will be** unecessary\"_. Sounds like a plot from Back to the Future IV ;) Anyways, learning SFINAE may still be worthwhile while writing library code that should be backwards compatible and/or useful within older codebases. And compilers still not to catch up a lot 'til they support fully C++20."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T11:36:26.233",
"Id": "405968",
"Score": "1",
"body": "`since C++20` Still a year off! Since `Concepts` were initially proposed for C++11 C++14 and C++17 but dropped before the standard was published I am not going to hold my breath until I see them in the ratified standard."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T16:33:56.620",
"Id": "406011",
"Score": "0",
"body": "@MartinYork: Pedantically, Concepts were only ever in the C++11 (C++0x) draft; they never again made it far enough to get \"dropped\" from C++14 or C++17. Also, the single least-controversial part of C++2a Concepts is the ability to attach explicit `requires` clauses to functions, which is all OP needs here. A C++2a solution to his problem wouldn't mention the keyword `concept`, just `requires`. And even in the unlikely case that Concepts gets dropped from C++2a, I'm confident that the `requires` keyword would remain in."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T18:20:25.160",
"Id": "209995",
"ParentId": "209992",
"Score": "9"
}
},
{
"body": "<blockquote>\n <p>I just wrote four lines of code...</p>\n\n<pre><code>template<typename T, typename ...>\nusing sfinae = T;\n\ntemplate<typename T, typename ...>\nusing SFINAE = T;\n</code></pre>\n</blockquote>\n\n<p>You should have written just <em>two</em> lines of code โ either the first two or the last two. Not both. \"There's more than one way to [spell] it\" is the Perl way, not the C++ way. ;) (At least not intentionally! Not intentionally pre-C++2a! Now we're getting both <code>std::filesystem</code> and <code>std::fs</code>, that's a less airtight position.)</p>\n\n<hr>\n\n<p>As you show, your thing can be used for</p>\n\n<pre><code>template<class T, \n sfinae<bool,\n std::enable_if_t<std::is_integral_v<T>>,\n std::enable_if_t<std::is_arithmetic_v<T>>\n > = true>\nvoid foo();\n</code></pre>\n\n<p>However, this is pretty verbose; surely we'd rather write <code>std::enable_if_t<std::is_integral_v<T> && std::is_arithmetic_v<T>></code> than <code>std::enable_if_t<std::is_integral_v<T>>, std::enable_if_t<std::is_arithmetic_v<T>></code>. </p>\n\n<p>So personally I have a different alias that accomplishes the same goal: <code>bool_if_t</code>.</p>\n\n<pre><code>template<bool B>\nusing bool_if_t = std::enable_if_t<B, bool>;\n\ntemplate<class T, \n bool_if_t<\n std::is_integral_v<T> &&\n std::is_arithmetic_v<T>\n > = true>\nvoid foo();\n</code></pre>\n\n<p>This has the advantage that the inner expression is written using normal C++ syntax rules. We don't have to remember some arbitrary rule like \"<code>x, y</code> means both <code>x</code> and <code>y</code> must be true\"; we just write <code>x && y</code>. And if we want to enable this function when <em>either</em> <code>x</code> <em>or</em> <code>y</code> is true, we don't have to invent a new primitive; we just write <code>bool_if_t<x || y></code>. <code>bool_if_t</code> is much more composable than your <code>sfinae<Ts...></code>, because <code>bool_if_t</code> can exploit the existing expression syntax of C++.</p>\n\n<hr>\n\n<p>Recommended viewing: <a href=\"https://www.youtube.com/watch?v=ybaE9qlhHvw\" rel=\"noreferrer\">\"A Soupรงon of SFINAE\"</a> (Arthur O'Dwyer, CppCon 2017). (Yes, that's me.)</p>\n\n<p>You picked examples that don't really show off the power of <code>sfinae</code>, by the way.\nConsider this example:</p>\n\n<pre><code>// 3) as a function return type:\ntemplate <typename T> \nsfinae<T,\n std::enable_if_t<std::is_integral_v<T>>,\n std::enable_if_t<std::is_arithmetic_v<T>>\n> const & foo(T const & val);\n</code></pre>\n\n<p>You take a \"value-space\" boolean (<code>is_integral_v<T></code>), lift it up into \"SFINAE-space\" with <code>enable_if_t</code>, and then apply a logical AND operation in SFINAE-space using your <code>sfinae</code> alias.</p>\n\n<pre><code>template <typename T> \nstd::enable_if_t<\n std::is_integral_v<T> &&\n std::is_arithmetic_v<T>, T\n> const & foo2(T const & val);\n</code></pre>\n\n<p>Here I take the same \"value-space\" boolean, perform the logical AND <em>in value space</em> where we have a dedicated operator <code>&&</code> for maximum expressiveness; and I lift it up into SFINAE-space <em>after</em> doing the AND. This is clearer and also probably more efficient in terms of compile time.</p>\n\n<p>Where your version helps is when your values <em>start</em> in SFINAE-space!</p>\n\n<pre><code>template<class T> \nsfinae<T,\n decltype(std::declval<T>() + std::declval<T>()),\n T*,\n T&\n> const & foo3(T const & val);\n</code></pre>\n\n<p>If we were trying to replicate this code's behavior with the standard tools, we'd say something like</p>\n\n<pre><code>template<class, class=void> struct has_plus : std::false_type {};\ntemplate<class T> struct has_plus<T, decltype(void(std::declval<T>() + std::declval<T>()))> : std::true_type {};\ntemplate<class T> inline constexpr bool has_plus_v = has_plus<T>::value;\n\ntemplate<class T> \nstd::enable_if_t<\n has_plus_v<T> &&\n not std::is_reference_v<T> &&\n not std::is_void_v<T>, T\n> const & foo4(T const & val);\n</code></pre>\n\n<p>That is, we start with a value in SFINAE-space (<code>decltype(std::declval<T>() + std::declval<T>())</code>), lift it into value-space (<code>has_plus_v<T></code>), do the logical AND in value-space, and lift the result back into SFINAE-space.</p>\n\n<p>Whereas with your <code>foo3</code>, you start in SFINAE-space, do the logical AND via <code>sfinae<...></code> <em>without leaving SFINAE-space</em>, and then you're done. Much simpler! But harder to read, I think.</p>\n\n<hr>\n\n<p>A simple way to improve readability is to pick a good name. <code>sfinae_space_and<Ts...></code> might be clearer. Can you think of a way to write <code>sfinae_space_or<Ts...></code>? How about <code>sfinae_space_not<T></code>? Does it make sense, maintainability-wise, to provide one without the others?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T18:42:22.513",
"Id": "405891",
"Score": "5",
"body": "Incredible how much one can write about four (two) lines of code. Very informative ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T11:56:40.933",
"Id": "405972",
"Score": "0",
"body": "What's the use of `bool_if_t = std::enable_if_t<B, bool>;`? IMO it hides the intent behind it by removing the informative \"enable_if\" part."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T16:28:02.340",
"Id": "406009",
"Score": "0",
"body": "@Flamefire: I see your point, but OTOH, the \"intent\" is usually obvious from context. Significantly, `bool_if_t<B>=true` is 8 characters shorter than `enable_if_t<B, bool>=true`. Perhaps most significantly, it eliminates a bikeshed point: if all you have is the low-level `enable_if_t`, then you'll see people writing `enable_if_t<B, XXX>={}` for many different values of `XXX` (bool, int, etc). The slightly-higher-level abstraction eliminates that needless variation. (Murphy's Law: if you don't want people fiddling with the knobs, you have to remove the knobs.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T16:30:07.967",
"Id": "406010",
"Score": "0",
"body": "Full disclosure: `enable_if_t<B, int>=0` is 4 characters shorter than `enable_if_t<B, bool>=true`, and `int_if_t<B>=0` would be 4 characters shorter than `bool_if_t<B>=true`. Why did I pick `bool`?... I don't know. :P Maybe I should switch to `int_if_t` as my primitive."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T11:32:18.320",
"Id": "406089",
"Score": "0",
"body": "I don't buy this. Why would you need the assignment/value in `bool_if_t<B>=true`? The 2nd parameter in `enable_if_t` is for the use case of using it as a return value of a function. In class templates you'd use `typename = enable_if_t<foo>`, or in a function parameter `enable_if_t<foo>*=0` So if people use different types for the 2nd param, they probably did not understand how to use this template in the first place. Or am I missing anything? See the last example of @Incomputable for a better example"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T15:37:04.143",
"Id": "406105",
"Score": "0",
"body": "@Flamefire: Recommended viewing: [\"A Soupรงon of SFINAE\" (Arthur O'Dwyer, CppCon 2017)](https://www.youtube.com/watch?v=ybaE9qlhHvw). (Yes, that's me.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T18:31:03.583",
"Id": "406143",
"Score": "0",
"body": "@QuuxplusoneI am sorry I made you wait, for soo long, for my response... In fact, I was actually trying to implement `sfinae_space_not<>` and `sfinae_space_or<Ts...>` trying to match your points about `SFINAE-space` and other \"pluses\" You did mention about `sfinae<t, ts>`. Unfortunately, my attempts boiled down to two cases: (1) detection idiom - converting substitution failure into a `false`/`std::false_type` while performing all logical operations within \"value-space\", or (2) \"trying\" to utilize properties of argument packs which also required some sort of conversion type --> bool."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T18:38:04.170",
"Id": "406146",
"Score": "0",
"body": "Neither of these met the requirements set by You (about performing operations in the SFINAE space). Answering the rest of your question, Yes I definitely think that, maintainability-wise, it is a must to provide at least syntax for `not`, `and`, `or` cases. A preferable solution is to allow the \"users\" to create their own logical statements. Which is something that is impossible to do on types? well, at least I believe so. Now that I think about it, if I can't provide anything like that, the best solution would be to change `sfinae<T, Ts...>` to `sfinae<T, U>`. To check just a single condition"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T18:44:09.603",
"Id": "406147",
"Score": "0",
"body": "Oh, I almost forget. Thank you very much for such full, and detailed answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T22:23:37.487",
"Id": "406183",
"Score": "1",
"body": "@cukier9a7b5: _\"I was actually trying to implement `sfinae_space_not` and `sfinae_space_or` ... Unfortunately [I failed] ... I definitely think that, maintainability-wise, it is a must to provide at least syntax for `not`, `and`, `or` cases.\"_ Your thoughts parallel mine! :) I'm about 95% sure that it is impossible to write either `sfinae_not` or `sfinae_or`. So, by the laws of syllogism, as you stated: you shouldn't provide `sfinae_and`, either."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T18:38:42.700",
"Id": "209996",
"ParentId": "209992",
"Score": "14"
}
},
{
"body": "<pre><code>template <typename T, \n sfinae<bool,\n std::enable_if_t<std::is_integral_v<T>>,\n std::enable_if_t<std::is_arithmetic_v<T>>\n > = true /* provide default option, bc reasons */>\nclass foo;\n</code></pre>\n\n<p>vs</p>\n\n<pre><code>template <typename T, \n std::enable_if_t<\n std::is_integral_v<T>\n && std::is_arithmetic_v<T>,\n bool\n > = true\nclass foo;\n</code></pre>\n\n<p>This version doesn't use your new <code>sfinae</code> template, and uses fewer characters, and seems no less functional.</p>\n\n<p>What more in C++20 we'll have named concepts (and failing that) requires clauses. That will make much SFINAE obsolete.</p>\n\n<p>What more, there are fancier ways to do SFINAE, especially in <a href=\"/questions/tagged/c%2b%2b20\" class=\"post-tag\" title=\"show questions tagged 'c++20'\" rel=\"tag\">c++20</a></p>\n\n<p>There is this:</p>\n\n<pre><code>template<template<class...>class, class...>\nstruct can_apply;\n</code></pre>\n\n<p>which tests if a template can be applied to a list of types.</p>\n\n<p>With <code>constexpr</code> lambdas that can appear in template non type parameter argument calculations, we can do:</p>\n\n<pre><code>template<class F>\nconstexpr auto apply_test(F &&);\n</code></pre>\n\n<p>which returns an object that, when evaluated on some arguments, returns <code>true_type</code> if you can invoke <code>F</code> on it, and <code>false_type</code> otherwise.</p>\n\n<pre><code>template<class T,\n std::enable_if_t<\n apply_test([](auto a, auto b)RETURNS(a+b))( std::declval<T>(), std::declval<T>() ),\n bool\n > = true\n>\nstruct foo;\n</code></pre>\n\n<p>here we test if a type <code>T</code> can be added to itself. (I also use the somewhat ubiquitous <code>RETURNS</code> macro)</p>\n\n<p>Or, more cleanly:</p>\n\n<pre><code>template<class T>\nauto foo( T const& lhs, T const& rhs )\nrequires test_apply(std::plus<T>{})(lhs, rhs)\n</code></pre>\n\n<p>assuming sufficiently SFINAE friendly <code>std::plus<T></code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T19:47:21.460",
"Id": "210002",
"ParentId": "209992",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "209996",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T17:31:49.523",
"Id": "209992",
"Score": "10",
"Tags": [
"c++",
"sfinae"
],
"Title": "`sfinae</* ... */>` proposal... useful or unnecessary?"
} | 209992 |
<p>This is like the reverse functionality of <a href="https://codereview.stackexchange.com/questions/209933/text-file-to-spreadsheet">Text file to spreadsheet</a>.</p>
<p>One or multiple <code>.xlsx</code> files in the path of the script get opened and the content is split into multiple <code>.txt</code> files.</p>
<p>For example, say you have two excel files in the folder:</p>
<p><strong>file1.xlsx</strong></p>
<p><a href="https://i.stack.imgur.com/eiwh6.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eiwh6.jpg" alt="enter image description here"></a></p>
<p><strong>file2.xlsx</strong></p>
<p><a href="https://i.stack.imgur.com/IisMR.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IisMR.jpg" alt="enter image description here"></a></p>
<p><strong>The output created:</strong></p>
<p><a href="https://i.stack.imgur.com/sjxkK.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sjxkK.jpg" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/3aEVy.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3aEVy.jpg" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/Bucxw.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Bucxw.jpg" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/lBcbP.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lBcbP.jpg" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/MhEc5.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MhEc5.jpg" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/Kb5Zj.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Kb5Zj.jpg" alt="enter image description here"></a></p>
<p><strong>spreadsheet_to_text.py</strong></p>
<pre><code>"""
Reads in .xlsx files from path were the script is located.
Then the data of each column is split into a .txt file
"""
import glob
import openpyxl
from openpyxl.utils import get_column_letter
def get_text_filename(filename: str, column: int)->str:
"""
Creates a text filename based on .xlsx file filename and column
"""
return (filename.rstrip(".xlsx")
+ "_" + get_column_letter(column) + '.txt')
def xlsx_to_txt(filename: str):
"""
Extract data from a .xlsx file in the script folder into
multiple .txt files
"""
workbook = openpyxl.load_workbook(filename)
sheet_names = workbook.sheetnames
sheet = workbook[sheet_names[0]]
for column in range(1, sheet.max_column + 1):
if sheet.cell(row=1, column=column).value:
text_filename = get_text_filename(filename, column)
with open(text_filename, mode='w') as textfile:
for row in range(1, sheet.max_row + 1):
if sheet.cell(column=column, row=row).value:
textfile.writelines(
sheet.cell(column=column, row=row).value + '\n')
def spreadsheet_into_text():
"""main logic for split spreadsheet data into multiple text files"""
for filename in glob.iglob("*.xlsx"):
xlsx_to_txt(filename)
if __name__ == "__main__":
spreadsheet_into_text()
</code></pre>
<p>I already incorporated some improvements from <a href="https://codereview.stackexchange.com/questions/209933/text-file-to-spreadsheet">Text file to spreadsheet</a>. I wonder how the code can get further improved.</p>
| [] | [
{
"body": "<p>This looks quite clean in general. May I suggest a few minor improvements:</p>\n\n<ul>\n<li>I think you could just use <code>workbook.active</code> to get the sheet</li>\n<li><p>instead of doing the <code>rstrip(\".xlsx\")</code> which would also right-strip out <code>.sslsx</code> or <code>sl.xs.ss</code> and even grab a part of the actual filename:</p>\n\n<pre><code>In [1]: \"christmas.xlsx\".rstrip(\".xlsx\")\nOut[1]: 'christma'\n</code></pre>\n\n<p>use <a href=\"https://stackoverflow.com/q/678236/771848\"><code>os</code> module or the beautiful <code>pathlib</code> to properly extract a filename without an extension</a>:</p>\n\n<pre><code>In [1]: from pathlib import Path\n\nIn [2]: Path(\"christmas.xlsx\").resolve().stem\nOut[2]: 'christmas'\n</code></pre></li>\n<li><p>calculate what you can before the loop instead of inside it. For instance, <code>sheet.max_row</code> is something you could just remember in a variable at the top of your function and re-use inside. It's not a lot of savings, but <em><a href=\"https://stackoverflow.com/questions/28597014/python-why-is-accessing-instance-attribute-is-slower-than-local\">attribute access still has its cost in Python</a></em>:</p>\n\n<pre><code>max_row = sheet.max_row\n</code></pre></li>\n<li><p>something similar is happening when you get the value of a cell twice, instead:</p>\n\n<pre><code>cell_value = sheet.cell(column=column, row=row).value\n\nif cell_value:\n textfile.writelines(cell_value + '\\n')\n</code></pre></li>\n<li><p>it may be a good idea to keep the nestedness at a minimum (<a href=\"https://www.python.org/dev/peps/pep-0020/\" rel=\"nofollow noreferrer\">\"Flat is better than nested.\"</a>) and would rather check for a reverse condition and use <code>continue</code> to move to the next iteration:</p>\n\n<pre><code>for column in range(1, sheet.max_column + 1):\n if not sheet.cell(row=1, column=column).value:\n continue\n\n text_filename = get_text_filename(filename, column)\n</code></pre></li>\n</ul>\n\n<p><strong>Some out-of-the-box ideas:</strong></p>\n\n<ul>\n<li>feels like if you do it with <a href=\"https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html#pandas-read-excel\" rel=\"nofollow noreferrer\"><code>pandas.read_excel()</code></a> it may just become way more easier and beautiful</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-07T19:34:53.717",
"Id": "408030",
"Score": "0",
"body": "thanks for the high quality answer. I really liked how it simplyfies the code. One little thing. I think in the question i already use `writelines` instead of `write` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-07T19:36:51.460",
"Id": "408032",
"Score": "0",
"body": "@Sandro4912 :) oh sorry, fixed that. Thanks!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T00:57:23.103",
"Id": "210015",
"ParentId": "210000",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "210015",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T19:29:31.350",
"Id": "210000",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"excel"
],
"Title": "Migrating data from multiple spreadsheets to multiple text files"
} | 210000 |
<p>I like to play word games that give you a set of letters and you get points for the more words you can make out of those letters. I have some code that works, but it's pretty slow. I was wondering if anyone had any idea on how to speed it up or if this is even the right place for this.</p>
<p>Here's the code </p>
<pre><code>import itertools
import os
import urllib.request
import sys
# PREWORK
DICTIONARY = os.path.join(sys.path[0], 'words.txt')
dictionary = []
with open(DICTIONARY) as f:
[dictionary.append(word.strip().lower()) for word in f.read().split()]
def get_possible_dict_words(draw):
"""Get all possible words from a draw (list of letters) which are
valid dictionary words. Use _get_permutations_draw and provided
dictionary"""
combinations = _get_permutations_draw(draw)
listOfPossibleWords = []
try:
while True:
combination = next(combinations)
combination = ''.join(combination)
if combination in listOfPossibleWords:
continue
if combination in dictionary:
listOfPossibleWords.append(combination)
except StopIteration:
if listOfPossibleWords:
return listOfPossibleWords
else:
print("There are no combinations made with those letters.")
def _get_permutations_draw(draw):
"""Helper to get all permutations of a draw (list of letters), hint:
use itertools.permutations (order of letters matters)"""
for _ in range(1, len(draw) + 1):
for subset in itertools.permutations(draw, _):
yield(subset)
def main():
draw = input("Please enter each letter seperated by spaces: ").split(" ")
print(get_possible_dict_words(draw))
if __name__ == '__main__':
main()
</code></pre>
| [] | [
{
"body": "<p>Couple straightforward things that should provide performance and memory usage improvements:</p>\n\n<ul>\n<li><p><code>if combination in listOfPossibleWords:</code> if <code>listOfPossibleWords</code> is a list is a <em>slow full-scan operation</em> with <span class=\"math-container\">\\$O(n)\\$</span> complexity. By switching to a set, you would get constant time lookups</p>\n\n<pre><code>possible_words = set([])\ntry:\n while True:\n combination = next(combinations)\n combination = ''.join(combination)\n if combination in possible_words:\n continue\n if combination in dictionary:\n possible_words.add(combination)\n # ...\n</code></pre>\n\n<p>FYI, here is a handy complexity table for Python date structures: <a href=\"https://wiki.python.org/moin/TimeComplexity\" rel=\"nofollow noreferrer\">TimeComplexity</a></p></li>\n<li><p>when you are reading the file, the <code>f.read()</code> would read the whole contents of the file into memory. You could iterate over the file line by line in a \"lazy\" manner instead:</p>\n\n<pre><code>with open(DICTIONARY) as f:\n dictionary = [word.strip().lower() for word in f]\n</code></pre>\n\n<p>Note that I've also updated it to be a proper pythonic list comprehension.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T20:09:36.370",
"Id": "210004",
"ParentId": "210001",
"Score": "1"
}
},
{
"body": "<p><a href=\"https://codereview.stackexchange.com/users/24208/alecxe\">@alecxe</a> has the right idea, but there is more to improve</p>\n\n<h1>Review</h1>\n\n<ul>\n<li><p><code>sys.path[0]</code> is unnecessary</p>\n\n<p>The default of <code>open(filename)</code> will look in the in the current directory, so there is no need to convert it to a full path beforehand</p></li>\n<li><p><code>dictionary</code> should also be a CONSTANT</p>\n\n<p>Since dictionary is a global constant it should be written in <code>ALL_CAPS</code></p>\n\n<p>Secondly this variable is oddly named, <code>dictionary</code> is a datatype (hashmap) in python.</p></li>\n<li><p>Change the data type of <code>dictionary</code></p>\n\n<p>@alecxe mentioned this as well, but a <code>set</code> will give O(0) lookup, instead of O(n), we can make the dictionary of words a set for faster lookup times</p></li>\n<li><p><code>_</code> variables are used for variables you don't use later on.</p>\n\n<p>You do use the variable so rename it.</p></li>\n</ul>\n\n<h1>Code</h1>\n\n<pre><code>from itertools import permutations\n\nWORD_FILE = 'words.txt'\n\ndef read_words(filename):\n with open(filename) as f:\n return {word.strip().lower() for word in f.readlines()}\n\ndef get_possible_words(target, word_set):\n used_words = set()\n for comb in get_permutations(target):\n if comb in word_set:\n used_words.add(comb)\n return used_words or \"There are no combinations made with those letters.\"\n\ndef get_permutations(target):\n for i in range(1, len(target) + 1):\n for subset in permutations(target, i):\n yield(''.join(subset))\n\ndef main():\n target = input(\"Please enter each letter seperated by spaces: \").split()\n print(get_possible_words(target, read_words(WORD_FILE)))\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T22:32:09.340",
"Id": "406184",
"Score": "1",
"body": "You may want to clarify your sentence about `_`: It's *by convention* that it's used for temporary variables, but there's nothing inherently special about an underscore. It's a variable like any other. [This](https://stackoverflow.com/a/5893946/8117067) may be a useful link to add to your answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T12:39:51.940",
"Id": "406233",
"Score": "0",
"body": "@Graham I should've made it more clear it is convention to use `_` for throwaway variables. Thnx for the link, will edit when I have a little more time"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T08:47:12.960",
"Id": "210029",
"ParentId": "210001",
"Score": "3"
}
},
{
"body": "<p>My idea when it comes to optimizing code is to check the runtime with a profiler. Python has a useful module called cProfile with which you can easily track how long the individual function calls take.\nWith the main call wrapped in to</p>\n\n<pre><code>import cProfile\n...\ncProfile.run('main()')\n</code></pre>\n\n<p>I get the following result</p>\n\n<pre><code>Please enter each letter seperated by spaces: t e s t d a r r e\n['a', 'at', 'as', 'ad', 'art', 'test', 'dear', 'date', 'dare', 'desert', 'arrest']\n 4932040 function calls in 20.747 seconds\n\n Ordered by: standard name\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 1 0.000 0.000 20.747 20.747 <string>:1(<module>)\n 1 0.000 0.000 0.000 0.000 codecs.py:318(decode)\n 1 0.000 0.000 0.000 0.000 codecs.py:330(getstate)\n 986409 0.234 0.000 0.234 0.000 word_game.py:14(_in_list_of_possibles)\n 986379 14.626 0.000 14.626 0.000 word_game.py:21(_in_dictionary)\n 1 0.800 0.800 16.245 16.245 word_game.py:28(get_possible_dict_words)\n 986410 0.205 0.000 0.205 0.000 word_game.py:49(_get_permutations_draw)\n 1 0.000 0.000 20.747 20.747 word_game.py:57(main)\n 1 0.000 0.000 0.000 0.000 {built-in method _codecs.utf_8_decode}\n 1 0.000 0.000 20.747 20.747 {built-in method builtins.exec}\n 1 4.501 4.501 4.501 4.501 {built-in method builtins.input}\n 1 0.000 0.000 0.000 0.000 {built-in method builtins.len}\n 986410 0.205 0.000 0.411 0.000 {built-in method builtins.next}\n 1 0.000 0.000 0.000 0.000 {built-in method builtins.print}\n 11 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects}\n 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}\n 986409 0.175 0.000 0.175 0.000 {method 'join' of 'str' objects}\n 1 0.000 0.000 0.000 0.000 {method 'split' of 'str' objects}\n</code></pre>\n\n<p>I added two functions </p>\n\n<pre><code>def _in_list_of_possibles(combi, list_of_possibles):\n if combi in list_of_possibles:\n return True\n else:\n return False\n\n\ndef _in_dictionary(combi, dictionary):\n if combi in dictionary:\n return True\n else:\n return False\n</code></pre>\n\n<p>in order to get a better understanding of how long these steps take.\nAnd with this we can see that the lookup of the combination in the dictionary is the culprit whereas the look up in the newly composed list of possibles doesn't really affect performance. </p>\n\n<p><strike>My idea of performance increase would go into the direction of multi threading the lookup in the dictionary.</strike></p>\n\n<p>Following the idea of <a href=\"https://codereview.stackexchange.com/users/140549/ludisposed\">@ludisposed</a>: Converting the dictionary into a set increases performance quite significantly.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T14:39:38.100",
"Id": "405981",
"Score": "0",
"body": "While I agree with parts of your answer, (use cprofile to check where the bottlenecks are) I don't agree with your last point. Why use multi threading, if you could make the `dictionary` variable a `set` essentially giving O(0) lookup."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T14:45:38.423",
"Id": "405982",
"Score": "0",
"body": "You are absolutely correct. \nAccording to the Zen of python: Simple is better than complex."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T14:56:44.580",
"Id": "405984",
"Score": "0",
"body": "I apologize for that, I fixed it in the answer."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T14:25:49.990",
"Id": "210052",
"ParentId": "210001",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T19:36:29.987",
"Id": "210001",
"Score": "4",
"Tags": [
"python",
"python-3.x"
],
"Title": "Word Game Solver"
} | 210001 |
<h2>Background<br/></h2>
<p>This year I've taken on the challenge of Advent of Code. The second challenge of the first day is to calculate a frequency for a special device based on a series of numbers. Here's a quote from the <a href="https://adventofcode.com/2018/day/1" rel="nofollow noreferrer">challenge</a> describing the problem.</p>
<blockquote>
<p>--- Part Two ---<br/>
You notice that the device repeats the same frequency change list over and over. To calibrate the device, you need to find the first frequency it reaches twice.</p>
<p>For example, using the same list of changes above, the device would loop as follows:</p>
<p>Current frequency 0, change of +1; resulting frequency 1.<br/>
Current frequency 1, change of -2; resulting frequency -1.<br/>
Current frequency -1, change of +3; resulting frequency 2.<br/>
Current frequency 2, change of +1; resulting frequency 3.<br/>
(At this point, the device continues from the start of the list.)<br/>
Current frequency 3, change of +1; resulting frequency 4.<br/>
Current frequency 4, change of -2; resulting frequency 2, which has already been seen.<br/></p>
<p>In this example, the first frequency reached twice is 2. Note that your device might need to repeat its list of frequency changes many times before a duplicate frequency is found, and that duplicates might be found while in the middle of processing the list.</p>
<p>Here are other examples:</p>
<p>+1, -1 first reaches 0 twice.<br/>
+3, +3, +4, -2, -4 first reaches 10 twice.<br/>
-6, +3, +8, +5, -6 first reaches 5 twice.<br/>
+7, +7, -2, -7, -4 first reaches 14 twice.<br/></p>
<p>What is the first frequency your device reaches twice?</p>
</blockquote>
<p><br/></p>
<h2>Solution<br/></h2>
<p>I've chosen to solve these challenges with elm and since it's a functional programming language the solution I went with for this problem was a recursive function. This function is named calculateFirstDuplicatedFrequency. It will firstly be called in main with a large <a href="https://github.com/sarjir/adventOfCode2018/blob/master/src/Frequency.elm" rel="nofollow noreferrer">list of Ints defined in another module</a>, and some other "empty values" to start it. The function will loop through until it finds the first duplicated accumulated frequency. If there are at least two items in the list, then there is a check for if that current accumulated value is in the combos Set, if it is it will stop the loop (so this is my base case).</p>
<p>If the current frequency isn't in that Set, then it will run calculateFirstDuplicatedFrequency again with the original list, the tail, currently accumulated combos and the current frequency.</p>
<p>If the function is called with a list of just one item, then it will run calculateFirstDuplicatedFrequency again, but sending in the original list as input, making the loop "start over" from the top and iterating over all the items in the list that was sent in the beginning once again. </p>
<p>If calculateFirstDuplicatedFrequency is called with an empty list as its frequencyModifiers, then it will just return 0...</p>
<p><em>OBS. If you think this snippet is a bit unreadable, you can always look at my <a href="https://github.com/sarjir/adventOfCode2018/blob/master/src/Main.elm" rel="nofollow noreferrer">github</a> instead</em></p>
<pre><code>import Set exposing (Set)
import Html exposing (Html, button, div, text)
import Frequency exposing (frequencyInput)
main =
div []
[ text "Second puzzle"
, createText (calculateFirstDuplicatedFrequency frequencyInput frequencyInput Set.empty 0)
]
createText : Int -> Html msg
createText finalNumber =
div [] [ text (String.fromInt finalNumber) ]
calculateFirstDuplicatedFrequency : List Int -> List Int -> Set Int -> Int -> Int
calculateFirstDuplicatedFrequency originalFrequencies frequenciesModifiers frequencyCombos currentFrequency =
let
createNewFreq = addFrequency currentFrequency
updateCombos = updateFrequencySet frequencyCombos
checkFrequencyCombos = checkCombos frequencyCombos
in
case frequenciesModifiers of
[] -> 0
[x] ->
calculateFirstDuplicatedFrequency originalFrequencies originalFrequencies (updateCombos (createNewFreq x)) (createNewFreq x)
(x::xs) ->
if checkFrequencyCombos (createNewFreq x) then
createNewFreq x
else
calculateFirstDuplicatedFrequency originalFrequencies xs (updateCombos (createNewFreq x)) (createNewFreq x)
addFrequency : Int -> Int -> Int
addFrequency currentFrequency frequency =
currentFrequency + frequency
updateFrequencySet : Set Int -> Int -> Set Int
updateFrequencySet frequencyCombos newFreq =
Set.insert newFreq frequencyCombos
checkCombos : Set Int -> Int -> Bool
checkCombos frequencyCombos frequency =
Set.member frequency frequencyCombos
</code></pre>
<p><br/></p>
<h2>Questions<br/></h2>
<p>This is my first time using a functional programming language and I have so many questions regarding best practices! But my main concern with this code is:<br/></p>
<ol>
<li>When I searched for recursive patterns I could not find any examples of recursion where they started the loop over again. Is my solution an okey way to do it?<br/></li>
<li>Is it bad to send as many arguments as I am to calculateFirstDuplicatedFrequency? Is there any way I can refactor this code to take in less arguments? Do I need to?<br/></li>
<li>Have I used <code>let...in</code> in the correct way? It feels so nested and ugly. Are there better ways to keep track of all the paramters?<br/></li>
<li>I feel like the way I handle the empty list case isn't too good. I would like to show some kind of error message, or in some other way say that this function won't work if it's called with an empty List. Do you have any suggestion to how I could handle it?</li>
</ol>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T20:07:26.033",
"Id": "210003",
"Score": "2",
"Tags": [
"recursion",
"functional-programming",
"elm"
],
"Title": "Finding first duplicated value from \"circular\" list with a recursive function"
} | 210003 |
<p>I wanted to get some constructive feedback on my solution to the <a href="https://www.hackerrank.com/challenges/fraudulent-activity-notifications/" rel="noreferrer">Fraudulent Activity Notification</a> problem from HackerRank:</p>
<blockquote>
<p>HackerLand National Bank has a simple policy for warning clients about possible fraudulent account activity. If the amount spent by a client on a particular day is greater than or equal to 2ร the client's median spending for a trailing number of days, , they send the client a notification about potential fraud. The bank doesn't send the client any notifications until they have at least that trailing number of prior days' transaction data.</p>
<p>Given the number of trailing days <em>d</em> and a client's total daily expenditures for a period of <em>n</em> days, find and print the number of times the client will receive a notification over all <em>n</em> days.</p>
<p>For example, <em>d</em>ย =ย 3 and <em>expenditures</em> = [10, 20, 30, 40, 50]. On the first three days, they just collect spending data. At day 4, we have trailing expenditures of [10, 20, 30]. The median is 20 and the day's expenditure is 40. Because 40ย โฅย 2ย รย 20, there will be a notice. The next day, our trailing expenditures are [20, 30, 40] and the expenditures are 50. This is less than 2ย รย 30 so no notice will be sent. Over the period, there was one notice sent.</p>
<h3>Input Format</h3>
<p>The first line contains two space-separated integers <em>n</em> and <em>d</em>, the number of days of transaction data, and the number of trailing days' data used to calculate median spending.
The second line contains <em>n</em> space-separated non-negative integers where each integer <em>i</em> denotes <em>expenditure</em>[<em>i</em>].</p>
<h3>Constraints</h3>
<ul>
<li>1ย โคย <em>n</em>ย โค 2ร10<sup>5</sup></li>
<li>1ย โคย <em>d</em>ย โคย <em>n</em></li>
<li>0ย โคย <em>expenditure</em>[<em>i</em>]ย โคย 200</li>
</ul>
</blockquote>
<p>I believe having the a sort in there in raising the timeout for some problems.
How would you solve it without a sort? Sorting while inserting has a much higher complexity...</p>
<pre><code>#include <bits/stdc++.h>
#include <array>
using namespace std;
vector<string> split_string(string);
// Complete the activityNotifications function below.
int activityNotifications(vector<int> expenditure, int d) {
int result=0;
int dq_idx=0;
double median=0;
vector<int> dq;
for (int i =0; i< expenditure.size()-1; i++){
if (dq_idx >= dq.size()){
dq.push_back(expenditure[i]);
}else {
dq.at(dq_idx) = expenditure[i];
}
dq_idx=(dq_idx+1) %d;
if (dq.size()>=d){
sort(dq.begin(), dq.end());
if (d %2 ==0){
median = 2* (dq[d/2 -1 ] + dq[(d/2)])/2;
}else {
median = 2 * dq[d%2];
}
if ((float)expenditure[i+1] >= median) {
result++;
}
}
}
return result;
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
string nd_temp;
getline(cin, nd_temp);
vector<string> nd = split_string(nd_temp);
int n = stoi(nd[0]);
int d = stoi(nd[1]);
string expenditure_temp_temp;
getline(cin, expenditure_temp_temp);
vector<string> expenditure_temp = split_string(expenditure_temp_temp);
vector<int> expenditure(n);
for (int i = 0; i < n; i++) {
int expenditure_item = stoi(expenditure_temp[i]);
expenditure[i] = expenditure_item;
}
int result = activityNotifications(expenditure, d);
fout << result << "\n";
fout.close();
return 0;
}
vector<string> split_string(string input_string) {
string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) {
return x == y and x == ' ';
});
input_string.erase(new_end, input_string.end());
while (input_string[input_string.length() - 1] == ' ') {
input_string.pop_back();
}
vector<string> splits;
char delimiter = ' ';
size_t i = 0;
size_t pos = input_string.find(delimiter);
while (pos != string::npos) {
splits.push_back(input_string.substr(i, pos - i));
i = pos + 1;
pos = input_string.find(delimiter, i);
}
splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1));
return splits;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T21:32:43.720",
"Id": "405911",
"Score": "0",
"body": "Is `%` in `median = 2 * dq[d%2];` a copy-paste typo?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T22:02:26.137",
"Id": "405915",
"Score": "4",
"body": "Besides, the algorithm doesn't look correct to me. It may accidentally produce the correct result, but... once `dq` is sorted, the `dq.at(dq_idx)` is not the oldest expenditure anymore, so you overwrite the wrong one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T08:33:31.393",
"Id": "405949",
"Score": "0",
"body": "@vnp: that's correct. it was a typo and I see your point about the sorting... good catch"
}
] | [
{
"body": "<h1>Bad Habits</h1>\n<p>I'd get out of the habit of including <code>bits/stdc++.h</code> as it's <a href=\"https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h\">non-standard and makes your compile times much longer</a> than they need to be. Especially with such a short program.</p>\n<p>Likewise, <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\"><code>using namespace std</code></a> can lead to problems and should be avoided.</p>\n<h1>Naming</h1>\n<p>You should use clearer variable and function names. The function name <code>activityNotifications()</code> sounds like it could be presenting the user with notifications. Or it could be processing activity notifications. Instead it's counting them. It might be better named <code>countActivityNotifications()</code>.</p>\n<p>Within the function, you have a few good variable names. Namely, <code>median</code> and <code>results</code>. I have no idea what <code>dq</code> stands for, which means I also have no idea what <code>dq_idx</code> stands for (beyond that it's an index for <code>dq</code>). <code>expenditure</code> is singular, but it holds multiple expenditures, so I'd make the name plural. <code>d</code> is unhelpful as well. Just because the problem description named the variables <code>n</code> and <code>d</code> doesn't mean your code should use those names. They should be <code>numberOfExpenditureDays</code> and <code>numberOfTrailingDays</code>. (If you prefer <code>num</code> to <code>number</code> and removing <code>Of</code>, that's fine.)</p>\n<h1>Simplify</h1>\n<p>You don't need to sort the expenditures. You can get the median by generating a histogram and finding the middle value. A histogram is just an array where each element is the number of times that value was in the input. So a histogram of expenditures would hold the count of how many expenditures were for 1 dollar, and 2 dollars, and 3 dollars, etc. Since the expenditures are between 0 and 200 dollars each, you would have 200 buckets in your histogram. Furthermore, since you're dealing with trailing days, once you have the first one calculated, you can simply update 2 values on each subsequent pass. (Decrement the expenditure from the day that's falling off the array and increment the one that's being added in.)</p>\n<p>Your <code>split_string()</code> function goes to a lot of trouble to clean the string before you tokenize it. But you don't need to. You can simply not add empty strings to the results. Something like this:</p>\n<pre><code>void split(const std::string& s, std::vector<std::string>& results)\n{\n size_t lastPos = 0;\n size_t nextPos = 0;\n while ((nextPos = s.find(" ", lastPos)) != std::string::npos)\n {\n std::string word = s.substr(lastPos, nextPos - lastPos);\n if (!word.empty()) {\n results.push_back(word);\n }\n lastPos = nextPos + 1;\n }\n \n if (lastPos != std::string::npos)\n {\n std::string word = s.substr(lastPos, std::string::npos);\n if (!word.empty())\n {\n results.push_back(word);\n }\n }\n}\n</code></pre>\n<p>I had to read your function several times to realize what it was trying to do with <code>std::unique()</code>, <code>std::string::erase()</code>, and <code>std::string::pop_back()</code>.</p>\n<h1>Readability</h1>\n<p>The <code>activityNotifications()</code> function is really hard to read due to the odd, inconsistent spacing it uses. I recommend a space before and after every operator to make it more clear. So this line, for example:</p>\n<pre><code>dq_idx=(dq_idx+1) %d;\n</code></pre>\n<p>is more readable when written like this:</p>\n<pre><code>dq_idx = (dq_idx + 1) % d;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T19:16:51.427",
"Id": "406036",
"Score": "0",
"body": "Few comments: 1) I started with dq because I wanted to have a fixed size double ended deque, and realised that might not be the cleverest idea from the box. 2) Thanks for the input on split string and readability. I'll improve on that. Let me give a shot to the function I am supposed to write."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T19:18:05.237",
"Id": "406037",
"Score": "0",
"body": "I'll accept it as soon as I get my solution on board. please bear with me."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T06:46:52.060",
"Id": "210022",
"ParentId": "210005",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "210022",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T20:27:40.123",
"Id": "210005",
"Score": "5",
"Tags": [
"c++",
"programming-challenge",
"time-limit-exceeded",
"c++14"
],
"Title": "HackerRank: Fraudulent activity notification"
} | 210005 |
<p>I was solving Project Euler #7 on <a href="https://www.hackerrank.com/contests/projecteuler/challenges/euler007/submissions/code/1311851301" rel="nofollow noreferrer">Hackerrank</a>
but for two cases, execution time is more than 2 sec.
Can you help with optimizing? I'm new to programming.</p>
<pre><code>#include <stdio.h>
#include <stdbool.h>
/*INPUT EXAMPLE
2 -> no of test cases
3 -> 1st test case
5 -> 2nd test case
*/
bool IsPrime(unsigned long);
int main(){
int n;
scanf("%d", &n);
while (n != 0) {
n--;
unsigned long m, l = 2, k = 1;
scanf("%lu", &m);
if (m == 1) {
printf("%d\n", 2);
} else if(m == 2){
printf("%d\n", 3);
}else{
while(1){
if(IsPrime(6*k-1) == true){
l++;
if(l == m){
printf("%lu\n", 6*k-1);
break;
}
}
if(IsPrime(6*k+1) == true){
l++;
if(l == m){
printf("%lu\n", 6*k+1);
break;
}
}
k++;
}
}
}
}
bool IsPrime(unsigned long n){
unsigned long k;
for(k = 2; k*k <= n; k++){
if(n % k == 0){
return false;
}
}
return true;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T06:38:51.370",
"Id": "405938",
"Score": "0",
"body": "\"but for two cases, execution time is more than 2 sec\" --> What are those 2 cases?"
}
] | [
{
"body": "<blockquote>\n<pre><code>bool IsPrime(unsigned long n){\n unsigned long k;\n for(k = 2; k*k <= n; k++){\n if(n % k == 0){\n return false;\n }\n }\n return true;\n}\n</code></pre>\n</blockquote>\n\n<p>A couple things off the bat. </p>\n\n<pre><code>bool isPrime(unsigned long n) {\n for (unsigned long k = 2; k*k <= n; k++) {\n if (n % k == 0) {\n return false;\n }\n }\n\n return true;\n}\n</code></pre>\n\n<p>The general standard is to name functions either camelCase or snake_case. You used PascalCase, which is generally only used for classes and structs. </p>\n\n<p>It is standard to declare loop variables that are not used outside the loop in the <code>for</code> declaration. That's one of the advantages of a <code>for</code> loop, that it allows you to do that. </p>\n\n<p>But neither of those would cause performance problems. This code checks if each number from 2 to <span class=\"math-container\">\\$\\sqrt{n}\\$</span> is a factor of <code>n</code>. But you don't need to check all the numbers. You only need to check the primes. And of course, you generate a list of primes, so it's easy enough to save that and check just the primes. </p>\n\n<p>Something like </p>\n\n<pre><code>bool isPrime(unsigned long n, unsigned long *primes) {\n for (size_t k = 0; primes[k]*primes[k] <= n; k++) {\n if (n % primes[k] == 0) {\n return false;\n }\n }\n\n return true;\n}\n</code></pre>\n\n<p>Back in the calling function, you will need to add some code to handle <code>primes</code>. </p>\n\n<p>Before the loop. </p>\n\n<pre><code>unsigned long *primes = malloc(2 * sizeof *primes);\nif (!primes) {\n // panic: exit, return, or whatever seems reasonable\n}\nprimes[0] = 2;\nprimes[1] = 3;\n\nsize_t length = 2;\n</code></pre>\n\n<p>Then take </p>\n\n<blockquote>\n<pre><code> unsigned long m, l = 2, k = 1;\n scanf(\"%lu\", &m);\n if (m == 1) {\n printf(\"%d\\n\", 2);\n } else if(m == 2){\n printf(\"%d\\n\", 3);\n }else{\n while(1){\n</code></pre>\n</blockquote>\n\n<p>and replace it with </p>\n\n<pre><code> size_t m;\n scanf(\"%u\", &m);\n if (m > length) {\n unsigned long *temp = realloc(primes, m * sizeof *primes);\n\n if (!temp) {\n free(primes);\n // panic: same way as last time\n }\n\n primes = temp;\n }\n m--;\n\n unsigned long candidate = 5;\n unsigned long increment = 4;\n while (length <= m) {\n increment = 6 - increment;\n</code></pre>\n\n<p>This changes the array index to <code>size_t</code>. This will easily support 10,000, which is the maximum <code>m</code> (what HackerRank calls <span class=\"math-container\">\\$N\\$</span>). </p>\n\n<p>This also changes <code>l</code> to a <code>size_t</code>, since it has to be smaller than <code>m</code> and it will index an array. </p>\n\n<p>This expands the <code>primes</code> array as necessary to handle the inputs. </p>\n\n<p>I moved declarations to when they are initialized. </p>\n\n<p>Your <code>k</code> code has some problems: </p>\n\n<ol>\n<li>You do an increment, a multiplication, a subtraction, and an addition every two iterations. </li>\n<li>You do two iterations of <code>l</code> per loop iteration. </li>\n<li>You have to duplicate code to handle both the same. </li>\n<li>You have to loop forever since the exit criterion is hidden. </li>\n<li>You have to check two conditions before the loop to handle the first two primes. </li>\n</ol>\n\n<p>This version of the code prepares to do </p>\n\n<ol>\n<li>One iteration per loop iteration. </li>\n<li>The exit criterion is in the loop declaration. </li>\n<li>This does one subtraction and one addition on every iteration. </li>\n<li>The code no longer needs duplicated. </li>\n<li>No special cases are needed for the first two primes. </li>\n<li>The solution can be printed after the loop, once rather than in four different places. </li>\n<li>If some previous test looked for a later prime, we remember that and don't enter the loop at all. </li>\n</ol>\n\n<p>The <code>candidate</code> variable will have the same values as <code>6*k-1</code> and <code>6*k+1</code>. The increment will alternate between 2 and 4 (<code>6-2=4</code> and <code>6-4=2</code>). So <code>candidate</code> will be 5, 7, 11, 13, 17, ... Just as previously. </p>\n\n<p>The rest of the loop can be </p>\n\n<pre><code> if (isPrime(candidate, primes)) {\n primes[length] = candidate;\n length++;\n }\n\n candidate += increment;\n }\n</code></pre>\n\n<p>And then </p>\n\n<pre><code> printf(\"%lu\\n\", primes[m]);\n</code></pre>\n\n<p>If <code>m</code> was originally 1, it will now be 0 and <code>primes[0]</code> is 2. If <code>m</code> was originally 2, it will now be 1 and <code>primes[1]</code> is 3. So there's the special cases. </p>\n\n<p>Outside the outer loop, you should </p>\n\n<pre><code>free(primes);\n</code></pre>\n\n<p>The big performance improvements are </p>\n\n<ol>\n<li>Not recalculating the same primes for each test case. </li>\n<li>Not checking for non-prime factors in <code>isPrime</code>. </li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T09:24:16.373",
"Id": "406082",
"Score": "0",
"body": "Thank you so much for making this more clear and way of explanation is very helpful and nice."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T05:37:54.077",
"Id": "210019",
"ParentId": "210008",
"Score": "2"
}
},
{
"body": "<p><strong>Avoid overflow, infinite loop</strong></p>\n\n<p>For large <code>n</code>, <code>k*k</code> can overflow mathematically.</p>\n\n<p>When <code>n == ULONG_MAX</code>, <code>for(k = 2; k*k <= n; k++)</code> is an infinite loop.</p>\n\n<p>Both of these can be solved with <code>k*k <= n</code> --> <code>k <= n/k</code>. As an added bonus, good compilers will see the nearby <code>n/k</code> and <code>n%k</code> and emit code that costs little extra as both are computed together - thus a candidate <strong>linear speed improvement</strong></p>\n\n<p><strong>Minor: Incorrect functionality</strong></p>\n\n<p>As a point of correct-ness, <code>IsPrime(0), IsPrime(1)</code> should return <code>false</code>.</p>\n\n<p><strong>Minor: Detect limits</strong></p>\n\n<p><code>6*k+1</code> in <code>IsPrime(6*k+1)</code> is a potential overflow. Ensure <code>k</code> is not too large. This test may not be necessary given the <code>if(l == m) ... break</code>. One would need to test.</p>\n\n<pre><code>k++;\nif (k > (ULONG_MAX - 1)/6) break; // add\n</code></pre>\n\n<hr>\n\n<pre><code>bool IsPrime(unsigned long n){\n unsigned long k;\n // for(k = 2; k*k <= n; k++){\n for(k = 2; k <= n/k; k++){\n if(n % k == 0){\n return false;\n }\n }\n // return true;\n return n > 1;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T09:27:08.830",
"Id": "406083",
"Score": "1",
"body": "Thank you for helping. \"k*k <= n --> k <= n/k\" I like this."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T06:37:11.830",
"Id": "210021",
"ParentId": "210008",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T22:03:34.750",
"Id": "210008",
"Score": "3",
"Tags": [
"beginner",
"c",
"programming-challenge",
"time-limit-exceeded",
"primes"
],
"Title": "Project Euler #7: Nth prime number"
} | 210008 |
<p>I made an object tracker for debugging and testing purposes called <code>ccm_counter</code> (construction, copy, move counter). It counts constructor, copy and move calls. It can be used to detect inefficient forwarding and unnecessary (or unintended) copies. The behavior is as follows:</p>
<h1>What it does</h1>
<p>Let <code>vector<A></code> be the type you want to test and <code>A</code> its element type (<code>A</code> must be move and copy constructable and must not be final). Drop in the counter like <code>vector<ccm_counter<A>></code>. <code>ccm_counter</code> behaves like <code>A</code> except that it also counts:</p>
<ol>
<li>constructor calls</li>
<li>copy constructor calls</li>
<li>move constructor calls</li>
<li>copy assignment calls</li>
<li>move assignment calls</li>
<li>copies</li>
<li>moves</li>
</ol>
<p>Point 1 to 5 are bound to the object (or variable) while point 6 and 7 are bound to the value of the object. For example:</p>
<pre><code>struct A{};
ccm_counter<A> a, b; // a and b increment constructor call count by 1
b = a; // a +1 copies -> import copies and moves from a -> b +1 copy assignment
a = b; // b +1 copies -> import copies and moves from b -> a +1 copy assignment
b = a;
</code></pre>
<p>This example results in (shortened)</p>
<pre><code>a:
constructor calls: 1
copy assignment calls: 1
total copies made: 3
b:
constructor calls: 1
copy assignment calls: 2
total copies made: 3
</code></pre>
<p>Now we add the <code>vector<A></code> (the examples uses <code>std::vector</code>):</p>
<pre><code>struct A{};
vector<ccm_counter<A>> vec;
ccm_counter<A> a, b;
vec.shrink_to_fit();
vec.push_back(a);
vec.push_back(a);
vec.push_back(a);
vec.push_back(b);
for (int i = 0; i < vec.size(); i++)
cout << "element " << i << ":\n" << vec[i].get_object_stats() << "\n" << *vec[i].get_value_stats() << "\n\n";
</code></pre>
<p>which prints:</p>
<pre><code>element 0:
constructor calls: 0
copy constructor calls: 0
move constructor calls: 1
copy assignment calls: 0
move assignment calls: 0
total copies made: 3
total moves made: 6
element 1:
constructor calls: 0
copy constructor calls: 0
move constructor calls: 1
copy assignment calls: 0
move assignment calls: 0
total copies made: 3
total moves made: 6
element 2:
constructor calls: 0
copy constructor calls: 0
move constructor calls: 1
copy assignment calls: 0
move assignment calls: 0
total copies made: 3
total moves made: 6
element 3:
constructor calls: 0
copy constructor calls: 1
move constructor calls: 0
copy assignment calls: 0
move assignment calls: 0
total copies made: 1
total moves made: 0
</code></pre>
<p>The constructor and assignment call counts are not very useful in this example, because they are bound to the object itself, which, in this case, is just an element in the internal buffer of the vector (which also changes as soon as the buffer is reallocated). However, the total copies and moves were tracked by the value. Element 0 gets copied when we call <code>vec.push_back(a)</code> the first time. Element 1 gets copied when we call <code>vec.push_back(a)</code> the second time. Because the vector exceeds his size each time we call <code>vec.push_back(...)</code>, its internal buffer has to be reallocated each time. This results in element 0 beeing moved into the new buffer which is reflected in the output and so on.</p>
<h1>Implementation</h1>
<pre><code>#include <algorithm>
#include <cmath>
#include <iomanip>
#include <memory>
#include <ostream>
#include <type_traits>
struct ccm_object_stats
{
std::size_t ctor = 0; // number of (any, except copy and move) constructor calls
std::size_t copy_ctor = 0; // number of copy constructor calls
std::size_t copy_assign = 0; // number of copy assignment calls
std::size_t move_ctor = 0; // number of move constructor calls
std::size_t move_assign = 0; // number of move assignment calls
constexpr ccm_object_stats& operator+=(const ccm_object_stats& rhs)
{
ctor += rhs.ctor;
copy_ctor += rhs.copy_ctor;
move_ctor += rhs.move_ctor;
copy_assign += rhs.copy_assign;
move_assign += rhs.move_assign;
return *this;
}
constexpr ccm_object_stats operator+(const ccm_object_stats& rhs)
{
ccm_object_stats ret(*this);
return ret += rhs;
}
};
std::ostream& operator<<(std::ostream& os, const ccm_object_stats& stats)
{
using namespace std;
constexpr size_t sw = 24;
const size_t nw = static_cast<size_t>(
log10(max({ stats.ctor, stats.copy_ctor, stats.copy_assign, stats.move_ctor, stats.move_assign }))) + 1;
os
<< setw(sw) << left << "constructor calls: " << setw(nw) << right << stats.ctor << "\n"
<< setw(sw) << left << "copy constructor calls: " << setw(nw) << right << stats.copy_ctor << "\n"
<< setw(sw) << left << "move constructor calls: " << setw(nw) << right << stats.move_ctor << "\n"
<< setw(sw) << left << "copy assignment calls: " << setw(nw) << right << stats.copy_assign << "\n"
<< setw(sw) << left << "move assignment calls: " << setw(nw) << right << stats.move_assign;
return os;
}
struct ccm_value_stats
{
std::size_t copies = 0; // number of copies made
std::size_t moves = 0; // number of moves made
constexpr ccm_value_stats& operator+=(const ccm_value_stats& rhs)
{
copies += rhs.copies;
moves += rhs.moves;
return *this;
}
constexpr ccm_value_stats operator+(const ccm_value_stats& rhs)
{
ccm_value_stats ret(*this);
return ret += rhs;
}
};
std::ostream& operator<<(std::ostream& os, const ccm_value_stats& stats)
{
using namespace std;
constexpr size_t sw = 24;
const size_t nw = static_cast<size_t>(
log10(max({ stats.copies, stats.moves }))) + 1;
os
<< setw(sw) << left << "total copies made: " << setw(nw) << right << stats.copies << "\n"
<< setw(sw) << left << "total moves made: " << setw(nw) << right << stats.moves;
return os;
}
// A wrapper object that inherits from `T` and counts construction, copy and move operations of `T`.
template <typename T>
class ccm_counter : public T
{
public:
template <typename ...Args, typename = std::enable_if_t<std::is_constructible_v<T, Args...>>>
constexpr explicit ccm_counter(Args... args) noexcept(std::is_nothrow_constructible_v<T, Args...>)
: T(std::forward<Args>(args)...), _val_stats{ std::make_shared<ccm_value_stats>() }
{
_obj_stats.ctor++;
}
constexpr ccm_counter(const ccm_counter& other) noexcept(std::is_nothrow_copy_constructible_v<T>)
: T(other), _val_stats(other._val_stats)
{
static_assert(std::is_copy_constructible_v<T>, "T must be copy constructible.");
_val_stats->copies++;
_obj_stats.copy_ctor++;
}
constexpr ccm_counter(ccm_counter&& other) noexcept(std::is_nothrow_move_constructible_v<T>)
: T(other), _val_stats(other._val_stats)
{
static_assert(std::is_move_constructible_v<T>, "T must be move constructible.");
_val_stats->moves++;
_obj_stats.move_ctor++;
}
constexpr auto operator=(const ccm_counter& other) noexcept(std::is_nothrow_copy_assignable_v<T>)
-> std::enable_if_t<std::is_copy_assignable_v<T>, ccm_counter&>
{
T::operator=(other);
_val_stats = other._val_stats;
_val_stats->copies++;
_obj_stats.copy_assign++;
return *this;
}
constexpr auto operator=(ccm_counter&& other) noexcept(std::is_nothrow_move_assignable_v<T>)
-> std::enable_if_t<std::is_move_assignable_v<T>, ccm_counter&>
{
T::operator=(other);
_val_stats = other._val_stats;
_val_stats->moves++;
_obj_stats.move_assign++;
return *this;
}
[[nodiscard]] constexpr ccm_object_stats get_object_stats() const noexcept
{
return _obj_stats;
}
constexpr void set_object_stats(ccm_object_stats stats)
{
_obj_stats = std::move(stats);
}
[[nodiscard]] constexpr std::shared_ptr<ccm_value_stats> get_value_stats() const noexcept
{
return _val_stats;
}
constexpr void set_value_stats(std::shared_ptr<ccm_value_stats> stats)
{
_val_stats = std::move(stats);
}
private:
ccm_object_stats _obj_stats{};
std::shared_ptr<ccm_value_stats> _val_stats;
};
template <typename T>
std::ostream& operator<<(std::ostream& os, const ccm_counter<T>& counter)
{
return os << counter.get_ccmd_stats();
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T22:44:37.497",
"Id": "210011",
"Score": "4",
"Tags": [
"c++",
"object-oriented",
"memory-management",
"template",
"c++17"
],
"Title": "Tracker for object construction, copy, and movement"
} | 210011 |
<p>It is sometimes necessary for a generator function to expose state. In those situations it is advised to wrap the generator function as method <code>__iter__</code> in a class. Here is an example:</p>
<pre><code>class C:
def __iter__(self):
for i in range(4):
yield i
self.state = i
</code></pre>
<p>It is convenient to use this in a for loop since the for loop will call iter() on the object, however, the object itself is not an iterator, so you cannot do this:</p>
<pre><code>c = C()
print(next(c))
</code></pre>
<p>Which is inconvenient. To get around this inconvenience I have come up with the following class:</p>
<pre><code>class C:
def __init__(self):
self.next = self.__iter__().__next__
def __iter__(self):
for i in range(4):
yield i
self.state = i
def __next__(self):
return self.next()
</code></pre>
<p>Usage example:</p>
<pre><code>c = C()
while 1:
try:
num = next(c)
print(num)
if num == 2:
print("state:", c.state)
except Exception:
break
</code></pre>
<p>Is this the best way to design the class? I haven't seen this technique used anywhere else so I'm wondering why everyone else isn't using it, since the C objects can be used both as iterators and as iterables. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T04:42:49.280",
"Id": "405933",
"Score": "5",
"body": "_\"It is sometimes necessary for a generator function to expose state\"_ โ I'd say that you should have a concrete use case to demonstrate that claim, and that the example you have posted is too sketchy or hypothetical to be on-topic for Code Review."
}
] | [
{
"body": "<p>Looks like a lot of extra code for very little gain, considering you can simply call <code>iter()</code> on an iterable object to return an iterator:</p>\n\n<pre><code>>>> c = C()\n>>> i = iter(c)\n>>> next(i)\n0\n>>> next(i)\n1\n>>> next(i)\n2\n>>> c.state\n1\n</code></pre>\n\n<p>Also, note your new <code>class C</code> can have more than one iterator, with only 1 \"state\". The first iterator is created automatically by the constructor, for use with the <code>next(c)</code> call. Additional iterators are created each time you start looping over <code>c</code>, since <code>iter(c)</code> gets called and returns a new generator!</p>\n\n<pre><code>>>> c = C()\n>>> next(c)\n0\n>>> print(next(c), c.state)\n1 0\n>>> print(next(c), c.state)\n2 1\n>>> for x in c: print(x, c.state) # Start a new iteration\n...\n0 1\n1 0\n2 1\n3 2\n>>> print(next(c), c.state) # Continue original iteration\n3 2\n>>> next(c)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"<stdin>\", line 9, in __next__\nStopIteration\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T23:45:54.513",
"Id": "210014",
"ParentId": "210012",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-19T22:45:45.597",
"Id": "210012",
"Score": "0",
"Tags": [
"python",
"python-3.x"
],
"Title": "iterator class using generator function"
} | 210012 |
<p>I made a simply user vs. computer game on Tic Tac Toe. I used Object Oriented Programming to increase my understanding of this programming paradigm. Can you criticize any design flaws I have in my code?</p>
<pre><code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 15 20:56:48 2018
@author: von-vic
"""
import random
from itertools import combinations
class Board(object):
def __init__(self):
self.board = {x:None for x in (7,8,9,4,5,6,1,2,3)}
def display(self):
"""
Displays tic tac toe board
"""
d_board = '\nTIC TAC TOE:\n'
for pos, obj in self.board.items():
if obj == None:
d_board += '_'
elif obj == 'X':
d_board += 'X'
elif obj == 'O':
d_board += 'O'
if pos%3 == 0:
d_board += '\n'
print(d_board)
def getAvailable(self):
"""
Returns available positions
"""
available = []
for pos, obj in self.board.items():
if obj == None:
available.append(pos)
return available
class Tic_Tac_Toe(Board):
pieces = ['O', 'X']
def __init__(self):
super().__init__()
self.piece = Tic_Tac_Toe.pieces.pop(random.choice([0,1]))
self.cp_piece = Tic_Tac_Toe.pieces[0]
def user_setPiece(self, position):
"""
Position parameter denoted by a number on the keypad (1-9)
"""
self.board[position] = self.piece
def user_getPiece(self):
return self.piece
def cp_setPiece(self):
self.board[random.choice(self.getAvailable())] = self.cp_piece
def cp_getPiece(self):
return self.cp_piece
def checkWin(self, player):
"""
Checks if move by either the user or computer results in a win
"""
def at_least_one(A, B):
for i in A:
for j in B:
if i == j:
return True
return False
win_patterns = [(1,2,3),(4,5,6),(7,8,9),
(1,4,7),(2,5,8),(3,6,9),
(3,5,7),(1,5,9)]
spots = [k for k, v in self.board.items() if v == player]
spots.sort()
player_combinations = list(combinations(spots,3))
if at_least_one(player_combinations, win_patterns) == True:
return True
return False
def checkFullBoard(self):
if None not in self.board.values():
self.display()
print('Draw! Game board full!')
return True
return False
#---------
def main():
# Setup game
game = Tic_Tac_Toe()
input('Hello user! Welcome to Tic Tac Toe! Press any key to continue')
if game.user_getPiece() == 'X':
print('You are X. You are going first.')
else:
print('You are O. You are going second.')
game.cp_setPiece()
# Main game loop
while True:
game.display()
position = input('Use the number pad on the lefthand side of your keyboard\nto select your position (1-9):')
try:
position = int(position)
if position in range(1,10):
if position in game.getAvailable():
game.user_setPiece(position)
else:
print('----Please input an available position.')
continue
else:
print('----Please input a number between 1 and 9.')
except ValueError:
print('----Please input a number.')
continue
# FOR USER
# Check for win
if game.checkWin(game.user_getPiece()) == True:
game.display()
print('Congratulations! You win!')
break
# Check for full board
if game.checkFullBoard() == True:
break
# FOR COMPUTER
game.cp_setPiece()
# Check for win
if game.checkWin(game.cp_getPiece()) == True:
game.display()
print('Sorry. You lost.')
break
# Check for full board
if game.checkFullBoard() == True:
break
if __name__ == '__main__':
main()
</code></pre>
| [] | [
{
"body": "<p>The first things which pop up are violations of the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">pep8</a> coding guidelines of python, for example </p>\n\n<pre><code>self.board = {x:None for x in (7,8,9,4,5,6,1,2,3)}\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>self.board = {x:None for x in (7, 8, 9, 4, 5, 6, 1, 2, 3)}\n</code></pre>\n\n<p>because of \"missing white space after ','\"\nThere are more violations like naming conventions</p>\n\n<ul>\n<li>Class names should be CamelCase </li>\n<li>Function names should be lower_case and snake_case</li>\n<li>As should variables</li>\n</ul>\n\n<p>it is more pythonian to write</p>\n\n<pre><code> if at_least_one(player_combinations, win_patterns):\n return True\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code> if at_least_one(player_combinations, win_patterns) == True:\n return True\n</code></pre>\n\n<p>And in the same function the naming can be improved: If you read the statement it doesn't convey what you are testing for: \"if at_least_one\"\nThe tipp I can give here: Write your code like an essay.</p>\n\n<p>The last thing I want to mention is </p>\n\n<pre><code>if obj == None:\n</code></pre>\n\n<p>it would be more pythonic to write</p>\n\n<pre><code>if obj is None\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T16:08:12.970",
"Id": "210060",
"ParentId": "210020",
"Score": "2"
}
},
{
"body": "<p>First of all, you're off to a good start. You have some comments, but it's important to be rigorous and consistent with your documentation. Uisdean's points about <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> styling are valid, but don't address the organization of your code. Additionally, stylistic changes can largely be fixed by automatic tools (e.g. <a href=\"https://github.com/ambv/black\" rel=\"nofollow noreferrer\">Black</a>).</p>\n\n<p>From an OOP point of view, it's important to understand the semantics of your class structure. From what you have now, <code>Board</code> is a base class, and because <code>Tic_Tac_Toe</code> subclasses <code>Board</code>, semantically this says that <code>Tic_Tac_Toe</code> is a variety of <code>Board</code>. The functions in <code>Tic_Tac_Toe</code> allow it to manipulate itself with moves, and then you have a <code>main</code> loop to run the logic. This is a good start, but I think we can do better.</p>\n\n<p>My understanding is that Tic Tac Toe is a type of game, not a type of board, but it does use a board as an internal state. Also, the game Tic Tac Toe doesn't manipulate itself. Instead, players manipulate the state of the game by making taking turns.</p>\n\n<p>Therefore, my advice about how to organize this code from a object oriented point of view would be to create classes like (parenthesis indicate a class' superclass): Game, TicTacToe(Game), Board, Player, Human(Player), Computer(Player), Turn, and Move. Then, each Game would have a set of Turns, each with a corresponding Move and Player. Moves would affect the state of the Board within the Game instance. The kind of Moves that are allowed depend on the rules defined by the subclasses of Game (TicTacToe in this instance). Depending on the kind of Player, the Move for each Player's Turn could be generated automatically (for a Computer), or through keyboard/mouse input (for a Human).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T17:03:11.423",
"Id": "210063",
"ParentId": "210020",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "210063",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T05:42:58.000",
"Id": "210020",
"Score": "3",
"Tags": [
"python",
"beginner",
"object-oriented",
"tic-tac-toe"
],
"Title": "Beginner's user vs. computer Tic Tac Toe"
} | 210020 |
<p>Given an input <code>N</code> as the size of a centrifuge, I need to find out the number of balanced configurations. The full description is <a href="https://www.codingame.com/contribute/view/18191e066be816d23bc5c5b0d4720246aea5" rel="nofollow noreferrer">here</a>.</p>
<blockquote>
<p>Centrifuge is a piece of equipment that puts multiple test tubes in rotation at very high speeds. It consists of a cylindrical rotor with holes situated evenly along the circumference of the rotor.
Because the device is operating at high speeds, the center of mass of all tubes must coincide with the center of the rotor. We assume all tubes have the same mass.</p>
<p>For the sake of simplicity, we also assume that tubes are point masses, fixed firmly to the rotor. All at the same distance from the center. You may safely assume the <code>(x,y)</code> coordinates of tube <code>k</code> are <span class="math-container">\$R\sin a, R\cos a\$</span>, where <span class="math-container">\$a = 2\pi\frac{k}{n}\$</span></p>
<p>The problem is: Given a centrifuge with N holes and K tubes, is it possible to balance it?</p>
<p>example 1: given N = 6 possible values for K are 2,3,4,6.</p>
<p>example 2: given N = 12, it is possible to balance 5 tubes: put 3 evenly dispersed (every 4th hole), then find a pair of opposite unoccupied holes and insert remaining 2 tubes there.</p>
<p>example 3: given N = 10, it is impossible to balance 7 tubes: put 5 evenly dispersed, and there's no opposite unoccupied holes left!</p>
<p><strong>Input</strong></p>
<p>Line 1: An integer N for the capacity of the centrifuge.</p>
<p><strong>Output</strong></p>
<p>Line 1: An integer M for the number of different possible values of K.</p>
</blockquote>
<p>This is my code:</p>
<pre><code>import numpy as np
N=int(input())
angle = 2*np.pi/N
z = complex(np.cos(angle), np.sin(angle))
import itertools
combs = []
lst = range(1,N)
for i in range(2, N-1):
combs.append(i)
els = [list(x) for x in itertools.combinations(lst, i)]
combs.append(els)
count=1
lis = []
while count<=len(combs):
for a in range(len(combs[count])):
s=0
for b in range(len(combs[count][a])):
s+=z**combs[count][a][b]
if abs(s)<1e-10:
lis.append(combs[count][a])
count+=2
lengths = []
for i in lis:
if len(i) not in lengths:
lengths.append(len(i))
print(len(lengths)+1)
</code></pre>
<p>The code works fine, but slows down after input size of above 20, and is practically unusable after the input grows to 50 or above, due to the <code>for</code> loops. How do I optimize it?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T07:58:14.663",
"Id": "405944",
"Score": "0",
"body": "Welcome to Code Review. The current question title, which states your concerns about the code, obfuscates the original intend of your code. 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": "2018-12-20T08:06:24.520",
"Id": "405945",
"Score": "0",
"body": "@Zeta Is it better now?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T08:10:21.290",
"Id": "405946",
"Score": "2",
"body": "Now your title *only* states the concerns and wishes you have for your code. A better title would be something similar to \"Balancing centrifuges\" or \"Balanced centrifuge configurations\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T08:11:01.453",
"Id": "405947",
"Score": "0",
"body": "Ok, got it. Replacing it now with your suggested title."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T07:38:49.277",
"Id": "435945",
"Score": "1",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T07:40:17.783",
"Id": "435946",
"Score": "0",
"body": "@Mast Oh, I see. I did not know this. Let me delete the edit then."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T07:43:26.223",
"Id": "435947",
"Score": "0",
"body": "No need, I've already done that :-)"
}
] | [
{
"body": "<p>This is not a review, but an extended comment.</p>\n\n<p>The code cannot be meaningfully optimized. Few notes though.</p>\n\n<ul>\n<li><p>First, thou shalt not bruteforce. It is almost inevitably wrong.</p></li>\n<li><p>Next, you must realize that it is a number-theoretical problem. Even the names of the test cases suggest so. Among other things it means that testing the sum against <code>1e-10</code> is not right.</p></li>\n<li><p>Finally, do watch the video referenced in the problem. It is a big spoiler, and it doesn't provide a proof of the claim. The proof is far from trivial; if you are interested in the proof, follow up with <a href=\"https://ac.els-cdn.com/S0021869399980894/1-s2.0-S0021869399980894-main.pdf?_tid=05e98a71-5bfe-4ab5-9b66-24ee45b8ca47&acdnat=1545293045_b25f9696d79d219a4ff7eef490cdf2c1\" rel=\"noreferrer\">this</a> is a fascinating reading (trigger warning: heavy-duty math).</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T09:18:19.310",
"Id": "405955",
"Score": "0",
"body": "Well, about the 1e-10, I used it because of the floating point error. So, I thought 1e-10 should be a sufficiently small difference between 0 and s to establish their equality (i.e., s=0)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T09:20:04.327",
"Id": "405957",
"Score": "0",
"body": "@Kristada673 Sufficiently small for which `N`s?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T19:50:57.763",
"Id": "406038",
"Score": "1",
"body": "\"First, thou shalt not bruteforce. It is almost inevitably wrong.\" In what context? This is definitely not true in real life (http://wiki.c2.com/?PrematureOptimization), and often not true in coding challenges either. I was in a coding competition in college. Our team was doing practice problems, and I was working on an efficient way to solve the next one. My teammate beat me handily by using a much simpler, brute-force approach. It all depends on the size and complexity of the data and the algorithm. In this case, yes, brute-force is the wrong approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T07:21:18.070",
"Id": "435937",
"Score": "1",
"body": "The link now 404s."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-23T07:57:09.373",
"Id": "435949",
"Score": "0",
"body": "Was it one of the references mentioned in http://oeis.org/A322366 ?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T09:06:24.457",
"Id": "210030",
"ParentId": "210025",
"Score": "9"
}
},
{
"body": "<p>There are two main problems:</p>\n\n<ol>\n<li><p>Enumerating all combinations, even those that are obviously unbalanced</p></li>\n<li><p>The use of floating point calculus in a combinatorics problem</p></li>\n</ol>\n\n<p>Re-read the task carefully, especially examples 2 and 3, which hint a better algorithm:</p>\n\n<ol>\n<li><p>Factorize <code>N</code>. The factors of <code>N=12</code> are <code>[2,3]</code>, which tells us that all tubes are members of either a balanced pair or triplet.</p></li>\n<li><p>Find all combinations of factors that sum to <code>K</code>. For <code>N=12, K=10</code>, there are two solutions: <code>2+2+2+2+2=10</code> and <code>2+2+3+3=10</code>.</p></li>\n<li><p>Find out if the solutions are valid. For <code>N=10, K=7</code> the only solution is <code>2+5=7</code>, which is not valid (see example 3).</p></li>\n</ol>\n\n<p>For large values of <code>K</code>, balance holes instead of tubes. So <code>N=12, K=10</code> is the same as <code>N=12, K=2</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T09:13:18.550",
"Id": "210031",
"ParentId": "210025",
"Score": "6"
}
},
{
"body": "<p>Revisiting this problem exactly 1 year after asking it, the following is a dynamic-programming based solution, thanks to commenter Niako in the original post (linked in the question):</p>\n\n<pre><code>N = int(input())\n\ndef primeFactorization(n):\n \"\"\" Return the prime factors of n \"\"\"\n p_factors = []\n lastresult = n\n while 1:\n if lastresult == 1:\n break\n c = 2\n while 1:\n if lastresult % c == 0:\n break\n c += 1\n if c not in p_factors:\n p_factors.append(c)\n lastresult /= c\n return p_factors\n\nF = primeFactorization(N)\nR = [False]*(N+1)\nR[0] = True\nfor p in F:\n for n in range(p,N+1):\n R[n] = R[n] or R[n-p]\n\nsols = []\nfor i in range(2,int(N/2)+1):\n if R[i]==True:\n sols.append(i)\n sols.append(N-i)\nsols.append(N)\nprint(len(set(sols)))\n</code></pre>\n\n<p>This works, except for 2 test cases, cases 7 and 8 (i.e., inputs 33 and 35, where the expected outputs are 13 and 11 respectively, but this program outputs 15 for both). It would be great if someone can point out why.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-12-20T01:29:05.027",
"Id": "234362",
"ParentId": "210025",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T07:06:30.517",
"Id": "210025",
"Score": "8",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"time-limit-exceeded",
"mathematics"
],
"Title": "Balanced centrifuge configurations"
} | 210025 |
<h1>Motivation</h1>
<p>I recently picked up Emacs. As part of the process, I've started to configure the editor to fit my needs with Emacs Lisp. The Elisp indentation rules are still foreign to me, so I pretty much depend on Emacs' <code>electric-indent-mode</code> to work. There's always <code>C-x h</code> and <code>C-M-\</code> to the rescue, though.</p>
<p>That being said, I recently came across a user who cannot use this functionality, as the Emacs user interface in its default state is apparently incompatible with their screen reader. Still, I think that Emacs' Lisp indentation works great, so I tried to make it more accessible. And since I also needed some experience with Lisp, why not write it in Elisp?</p>
<h1>Emacs driven indentation script</h1>
<p>The <strong>Emacs driven indentation script</strong> (<strong>Edis</strong>) is single script to indent files with Emacs' indentation logic. It has no requirement except an Emacs installation and should—in theory—work on all supported platforms and in most Emacs versions, although I only tested Linux and Emacs 26 so far.</p>
<p>Files must be given as command line arguments. It's a script, after all, and doesn't use any graphical interface:</p>
<pre><code>/path/to/edis file1.elisp file2.elisp file3.elisp โฆ
</code></pre>
<p>On Windows, a small wrapper is necessary, since it doesn't support shebangs, but that's probably just two lines of CMD or PowerShell.</p>
<p>Mistyped file names should get reported, but other than that, there shouldn't be any restriction on the number of files unless enforced by the OS, shell or Emacs. In theory, you can even use TRAMP to indent remote files, but I haven't tested that exhaustively (try <code>edis /ssh:server:/path/to/file</code> if you're interested).</p>
<pre><code>#!/usr/bin/emacs --script
(defun edis-indent-file (filename)
"Re-indents a given file"
(interactive "fFile to indent")
(cond
((file-exists-p filename)
(find-file filename)
(indent-region (point-min) (point-max))
(save-buffer))
(t
(message "File not found (need existing file): %s" filename))))
(mapc 'edis-indent-file argv)
</code></pre>
<p>The code has been indented with itself. As usual, it will respect file and global variables, so you can specify for example <code>(setq lisp-indent-offset 2)</code> in your <code>init.el</code> or use file local variables, for example:</p>
<pre><code>;; -*- lisp-body-indent: 4 ; lisp-indent-offset: 2 -*-
</code></pre>
<p>This is the first Emacs Lisp code I've written so far that's outside my
<code>init.el</code> (where I mostly use <code>use-package</code>, to be honest). Since Emacs is, after all, a text editor, all necessary tools seem to be at hand, so the code isn't that long.</p>
<p>I haven't read the complete Elisp manual yet and got the functions from the <code>C-h k</code> or quick searches in the manual, so I'm not sure whether the code is idiomatic Elisp or completely fails any good practice, so feel free to comment on any part of the code.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T16:19:47.680",
"Id": "406007",
"Score": "0",
"body": "I have nothing to say on this. This is IMO perfect."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-08T14:56:17.430",
"Id": "408136",
"Score": "2",
"body": "@ErnestFriedman-Hill Explain why it is perfect in an answer and it might give you a +50 bounty."
}
] | [
{
"body": "<p>One of the pitfalls with any language using formatting constructs you're not that familiar with, is that it becomes an unreadable mess. Your code though is properly formatted, properly indented (it would be poor style for an indentation script to be badly indented itself, wouldn't it?) and even self-documenting. On every line, it's perfectly clear where we are, what's going on and how it's done.</p>\n\n<p>If we're really going to nitpick, the documentation of Emacs Lisp uses the following indentation style for conditionals:</p>\n\n<pre><code>(cond ((file-exists-p filename)\n (find-file filename)\n (indent-region (point-min) (point-max))\n (save-buffer))\n (t (message \"File not found (need existing file): %s\" filename))))\n</code></pre>\n\n<p>Which slightly differs from yours, and is more in line with the rest of the language. But I can understand a preference for either.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-14T08:26:56.130",
"Id": "226097",
"ParentId": "210036",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "226097",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T10:10:50.553",
"Id": "210036",
"Score": "8",
"Tags": [
"beginner",
"formatting",
"lisp",
"elisp"
],
"Title": "Edis: Emacs driven indentation script"
} | 210036 |
<p>I'm trying to replace a number of keywords with other corresponding values. I started with this method:</p>
<pre><code>Dictionary<string, string> keywords = GetKeywords();
foreach (var pair in keywords)
{
var re = new Regex($@"\b{pair.Key}\b");
if (re.IsMatch(text))
text = re.Replace(text, pair.Value);
}
</code></pre>
<p>..which becomes slower and slower when the number of keywords increases. So, I used a different method <em>(by only scanning the string once and checking each word against the dictionary)</em>:</p>
<pre><code>text =
Regex.Replace(text, @"\w+", delegate (Match m)
{
string word = m.Value;
string value;
if (keywords.TryGetValue(word, out value))
return value;
else
return word;
});
</code></pre>
<p>..which worked great for the original requirement. However, I was forced to switch back to the first method because I need to match/replace keywords that are not 100% equal to what's in the dictionary. For example, in the first method, I would do something like this:</p>
<pre><code>string keyword = pair.Key.Replace("e", "[eรฉ]")
var re = new Regex($@"\b{keyword}\b");
</code></pre>
<p><strong>Is there a way around this using the second method? Or any other methods faster than the first one?</strong></p>
<p>Notes:</p>
<ul>
<li>It's not just accented letters, so something like <a href="https://stackoverflow.com/a/368850/4934172"><code>IgnoreNonSpace</code></a> will not work.</li>
<li>Both regex patterns are a little bit more complicated, that is, they both have a negative lookahead (<code>(?![^<]*>|[^&]*;)</code>) but I don't think that affects the outcome as the pattern is essentially just matching single words.</li>
</ul>
<p>The only solution I could think of is to "normalize" the keywords before adding them to the dictionary (e.g., replace <code>"[eรฉ]"</code> with <code>"e"</code>) and then "normalize" each word before passing it to <code>TryGetValue()</code> but I'd like to see if there's a better solution first because this one will be a little bit messy.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T11:09:14.597",
"Id": "405964",
"Score": "4",
"body": "_Both regex patterns are a little bit more complicated but I don't think that's relevant._ - on the contrary, they are very relevant because the whole question is about parsing and since there are no patterns, there is no parsing and your question becomes off-topic due to the lack of context. Please include _everything_. No body can give you any advice how to do it better if we don't see how it's currently done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T11:17:38.117",
"Id": "405966",
"Score": "0",
"body": "@t3chb0t You can safely assume that the patterns in the question are the ones used and just ignore that sentence (which is what I did for my test case). Does that still make the question off-topic? Anyway, I added more context on what the removed bit of the patterns is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T12:23:42.993",
"Id": "405976",
"Score": "1",
"body": "You are speaking about dictionaries and keywords etc but don't give us enough context as to how this looks like or what issue you exactly try to solve. I suggest reframing your question like that: I'm doing A, but this is slow, so I tried B, it was faster but _I need to match/replace keywords that are not 100% equal to what's in the dictionary._ (whatever this is - it needs explanation) - in this part you post the original and unchanged code... Then you can add another snippet that you've created for demonstration purposes - this one can be simplified if it properly reproduces the problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T13:42:15.457",
"Id": "406315",
"Score": "0",
"body": "Note also that this is not [so]. We *do* want to know the gritty details of your code and try to make it better, as opposed to answering one specific question, where one generally wants an abstracted, general piece of code (aka a Minimal, Complete and Verifiable Example)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T16:04:24.473",
"Id": "406336",
"Score": "0",
"body": "@Graipher I understand. Thank you for the feedback!"
}
] | [
{
"body": "<p>I can be wrong, but it seems that the problem is that if you have a large number of keywords, you are defining a lot of regular expressions in vain. How about creating a single regex and replacing values only for found keywords?</p>\n\n<pre><code>var words = string.Join(\"|\", keywords.Keys);\ntext = Regex.Replace(text, $@\"\\b({words})\\b\", delegate (Match m)\n{\n return keywords[m.Value];\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T14:14:08.163",
"Id": "210048",
"ParentId": "210038",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "210048",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T10:58:58.640",
"Id": "210038",
"Score": "1",
"Tags": [
"c#",
"performance",
"regex"
],
"Title": "Multiple string replacement (with similarity) using a dictionary"
} | 210038 |
<p>I'm a beginner and I wrote this (working) code for n-ary tree.</p>
<p>The specifics:</p>
<ul>
<li>Each node is to be built with an integer value.</li>
<li>Each node has a variable number of children. </li>
<li>The nodes should have an add(Node n) method, that adds a child node.</li>
<li>The Tree should have a contains(int val) method, that returns a Boolean value (true if the number val is found in a node). </li>
<li>It should have an <code>add(int... intArray)</code> method, that attaches a branch to the root if the root corresponds to the first number in <code>intArray</code>. The other numbers in the <code>intArray</code> are to be added only if they don't already exist (each as a child of the number before it). </li>
<li>The Tree should have a <code>remove(int r)</code> method, that removes a the node with the value of r (if present) and attaches its children to its parent. If the node happens to be the root, then the first child of the root becomes the root.</li>
</ul>
<pre><code>import java.util.*;
public class NaryTree
{
private Node root;
static public class Node
{
private List<Node> children;
private int value;
public Node(List<Node> children, int value)
{
this.children = children;
this.value = value;
}
public void add(Node n)
{
if (children == null) children = new ArrayList<>();
children.add(n);
}
}
public void add(int ... intArray) throws RootsNotEquals
{
if (root == null) root = new Node(null, intArray[0]);
if (root.value != intArray[0]) { throw new RootsNotEquals(); }
else
{
if (intArray.length >= 1) { intArray = Arrays.copyOfRange(intArray, 1, intArray.length); }
add(root, intArray);
}
}
public void add(Node tempRoot, int ... intArray)
{
boolean present = false;
int index = -1;
for (int i = 0; i < intArray.length; i++)
{
if (tempRoot.children != null)
{
for (int j = 0; j < tempRoot.children.size()-1; j++)
{
if (tempRoot.children.get(j).value == intArray[0]) present = true;
}
}
if (!present) { tempRoot.add(new Node(null, intArray[0])); }
for (Node f : tempRoot.children)
{
index++;
if (f.value == intArray[0])
{
if (index <= tempRoot.children.size()-1) tempRoot = tempRoot.children.get(index);
if (intArray.length >= 1) intArray = Arrays.copyOfRange(intArray, 1, intArray.length);
add(tempRoot, intArray);
break;
}
}
break;
}
}
public void remove(int r) throws NodeNotFound
{
if (!contains(r)) throw new NodeNotFound();
if (root.value == r)
{
for (int i = 1; i < root.children.size(); i++)
{
root.children.get(0).children.add(root.children.get(i));
}
root = root.children.get(0);
}
else { remove(root, r); }
}
public void remove(Node tempRoot, int r)
{
if (tempRoot.children != null)
{
for (int i = 0; i < tempRoot.children.size(); i++)
{
if (tempRoot.children.get(i).value == r)
{
for (Node n : tempRoot.children.get(i).children) tempRoot.children.add(n);
tempRoot.children.remove(i);
}
else
{
tempRoot = tempRoot.children.get(i);
remove(tempRoot, r);
break;
}
}
}
}
public boolean contains(int val) { return contains(root, val); }
private boolean contains(Node n, int val)
{
boolean found = false;
if (n == null) return found;
if (n.value == val) found = true;
else if (n.children != null) for (Node f : n.children) { return contains(f, val); }
return found;
}
public void print()
{
System.out.println("The root is "+root.value+".");
for (Node n : root.children)
{
System.out.println(n.value+" is a child of the root.");
printChildren(n);
}
}
public void printChildren(Node n)
{
if (n.children != null)
{
for (Node child : n.children)
{
System.out.println("Node "+n.value+" has node "+child.value+" as a child.");
printChildren(child);
}
}
}
public static void main(String[] args) throws RootsNotEquals, NodeNotFound
{
NaryTree poplar = new NaryTree();
poplar.add( new int[] { 1, 2, 5 });
poplar.add( new int[] { 1, 4, 0, 0 } );
poplar.add( new int[] { 1, 3, 6 });
poplar.add( new int[] { 1, 2, 7 });
poplar.print();
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T16:39:25.183",
"Id": "406012",
"Score": "0",
"body": "I wrote up a review, but `contains` doesn't seem right, so I left it off. Have you tried adding `poplar.remove(3)` just before you print? Does it remove or not?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T07:45:05.737",
"Id": "406069",
"Score": "0",
"body": "Yes, I've tested it and it works as intended."
}
] | [
{
"body": "<blockquote>\n<pre><code> private List<Node> children;\n</code></pre>\n</blockquote>\n\n<p>Your logic would become a lot easier if you changed this to </p>\n\n<pre><code> private List<Node> children = new ArrayList<>();\n</code></pre>\n\n<p>A large number of null checks would disappear. This would increase the amount of memory used, but it is unclear how much of a difference that would make. </p>\n\n<blockquote>\n<pre><code> public Node(List<Node> children, int value)\n</code></pre>\n</blockquote>\n\n<p>This seems like a solution in search of a problem. Your caller should not need to know about <code>Node</code> at all, so this always be called with <code>null</code>. </p>\n\n<pre><code> public Node(int value)\n</code></pre>\n\n<p>This way, you support the natural path. The caller only needs to know that the tree holds integers. It does not need to know anything about how it holds them. </p>\n\n<blockquote>\n<pre><code> if (root.value != intArray[0]) { throw new RootsNotEquals(); }\n else\n</code></pre>\n</blockquote>\n\n<p>You don't need an <code>else</code> here. The <code>throw</code> ends the current method. </p>\n\n<p>If you are going to put brackets around your single statement in control structures, you should do so consistently. You sometimes use the more common single statement form and sometimes this one. You should pick one. </p>\n\n<p>Incidentally, the java standard is to write control structures like </p>\n\n<pre><code> if (root.value != intArray[0]) {\n throw new RootsNotEquals();\n }\n</code></pre>\n\n<p>If you write them like this every time, you will tend to use less vertical space than you do with your mixture of all on the same line and all on separate lines. </p>\n\n<blockquote>\n<pre><code> if (intArray.length >= 1) { intArray = Arrays.copyOfRange(intArray, 1, intArray.length); }\n add(root, intArray);\n</code></pre>\n</blockquote>\n\n<p>This seems silly. You call <code>add</code> even if it's unnecessary despite checking the right condition immediately before it. Why not </p>\n\n<pre><code> if (intArray.length >= 1) {\n intArray = Arrays.copyOfRange(intArray, 1, intArray.length);\n add(root, intArray);\n }\n</code></pre>\n\n<p>This will save you a method call that will end up being a no-op. </p>\n\n<p>You also might consider doing the length check at the beginning of the method. Because if the length is 0, then <code>intArray[0]</code> will throw an exception. So you'd never reach the code that does the check. </p>\n\n<p>I also think that this method's behavior is rather silly. In order to add multiple, you need to pass in the root value. As a password? In the real world, if you received a requirement like this, it would be natural to push back and ask for the requirement to be removed. Perhaps it exists here for didactic purpose. </p>\n\n<blockquote>\n<pre><code> for (int i = 0; i < intArray.length; i++)\n</code></pre>\n</blockquote>\n\n<p>Why? At the end of the iteration, you have </p>\n\n<blockquote>\n<pre><code> break;\n</code></pre>\n</blockquote>\n\n<p>So this only ever does one iteration. Just take it out. It does not actually accomplish anything and you never use <code>i</code>. </p>\n\n<blockquote>\n<pre><code> if (index <= tempRoot.children.size()-1) tempRoot = tempRoot.children.get(index);\n</code></pre>\n</blockquote>\n\n<p>This will always be true, so it could be just </p>\n\n<pre><code> tempRoot = f;\n</code></pre>\n\n<p>And you could get rid of <code>index</code> entirely. </p>\n\n<blockquote>\n<pre><code> if (intArray.length >= 1) intArray = Arrays.copyOfRange(intArray, 1, intArray.length);\n</code></pre>\n</blockquote>\n\n<p>Again, this will always be true. </p>\n\n<blockquote>\n<pre><code> add(tempRoot, intArray);\n</code></pre>\n</blockquote>\n\n<p>This could be </p>\n\n<pre><code> add(f, Arrays.copyOfRange(intArray, 1, intArray.length));\n</code></pre>\n\n<p>Note that this creates a new array each time. You might be better off passing an <code>index</code> variable and changing your <code>[0]</code> to <code>[index]</code>. </p>\n\n<p>In <code>remove(int)</code>, you have </p>\n\n<blockquote>\n<pre><code> if (!contains(r)) throw new NodeNotFound();\n</code></pre>\n</blockquote>\n\n<p>Consider implementing a <code>findParentOf(int)</code> instead. Because this essentially searches the tree, finds the element that you want, forgets the location of the element, and returns true or false. Then you go off and find the element again. You'd use it like </p>\n\n<pre><code> Node parent = findParentOf(r);\n if (r == null) {\n throw new NodeNotFound();\n }\n</code></pre>\n\n<p>And of course, you'd do this after checking if it's the root value (don't forget to check for null first). </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T16:19:30.253",
"Id": "210061",
"ParentId": "210039",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "210061",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T10:59:01.430",
"Id": "210039",
"Score": "2",
"Tags": [
"java",
"beginner",
"object-oriented",
"recursion",
"tree"
],
"Title": "Java n-ary Tree class with custom made methods and nested Node class"
} | 210039 |
<p>Previous post: <a href="https://codereview.stackexchange.com/questions/209823/display-all-files-in-a-folder-object-along-with-nested-subdirectories?noredirect=1#comment405970_209823">Display all files in a folder (object) along with nested subdirectories</a></p>
<p><strong>Task:</strong> Given a main directory/folder, list all the files from it and if this directory contains nested sub-directories, list their files as well.</p>
<p><strong>Background:</strong> It was bought to my attention that the use of dummyCounter is considered bad practices. But, I still haven't managed to find a different approach that suits my needs.
Currently, my dummyCounter is used to prevent duplicating the parentFolder, as well as allowing me to break my loop.</p>
<p><strong>My previous approach:</strong> I have used folderStack.Any() as a condition for my while loop, but that resulted in the last nested sub-directory not getting shown. Then I tried using a "dept counter" but that proved too difficult to intercorporate while using a Stack approach to hold my data.</p>
<p>I would greatly appreciate community feedback. And should there be any problems with my post regarding community rules, let me know. - I tried not to repeat any of my previous issues.</p>
<p><strong> _Folder Partial View</strong></p>
<pre><code>@{
string GlyphionFolderIcon = "glyphicon glyphicon-folder-open";
}
<div class="row">
<div class="col-sm-2">
<a class="btn"
role="button"
data-toggle="collapse"
href="#@Model.Id"
aria-expanded="false"
aria-controls="@Model.Id">
<span class="@GlyphionFolderIcon"></span>
</a>
</div>
<div class="col-sm-5">@Model.Id</div>
<div class="col-sm-5">@Model.Name</div>
</code></pre>
<p></p>
<p><strong> _File Partial View</strong></p>
<pre><code>@{
string GlyphionModelIcon = "glyphicon glyphicon-paperclip";
}
<div class="row">
<div class="col-sm-2">
<a class="btn"
role="button"
href="@webUrl@Model.Url"
target="_blank">
<span class="@GlyphionModelIcon"></span>
</a>
</div>
<div class="col-sm-5">@Model.Id</div>
<div class="col-sm-5">@Model.Name</div>
</div>
</code></pre>
<p><strong>_Layout View</strong></p>
<pre><code>@foreach (var parentFolder in Model)
{
Stack<Folder> folderStack = new Stack<Folder>();
folderStack.Push(parentFolder);
var currentFolder = folderStack.Pop();
int dummyCounter = 1;
//Parent folder
@Html.Partial("_Folder", parentFolder);
<div class="collapse" id="@currentFolder.Id">
@if (currentFolder.FoldersContained != 0)
{
do
{
//Prevents a copy of the parent folder
//otherwise, this display nested folders
if (dummyCounter != 1)
{
@Html.Partial("_Folder", currentFolder);
}
<div class="collapse" id="@currentFolder.Id">
@if (currentFolder.FoldersContained > 0)
{
for (int i = currentFolder.FoldersContained; i > 0; i--)
{
//Pushes all nested directories into my stack
//in reverse inorder to display the top directory
folderStack.Push(currentFolder.Folders[i - 1]);
dummyCounter++;
}
}
@if (currentFolder.FilesContained != 0)
{
// Should they contain any files, display them
foreach (var file in currentFolder.Files)
{
@Html.Partial("_File", file);
}
}
</div>
//Ends the while loop
if (folderStack.Count == 0)
{
dummyCounter = 0;
}
//Prepares the next nested folder object
if (folderStack.Count != 0)
{
currentFolder = folderStack.Pop();
}
// I make use of a dummy counter inorder to break the loop
// should there no longer be any nested directories and files
// left to display
} while (dummyCounter != 0);
}
<!-- //Finally, display all files in the parent folder, should there be any-->
@if (parentFolder.FilesContained != 0)
{
foreach (var file in parentFolder.Files)
{
@Html.Partial("_File", file);
}
}
</div>
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T12:48:28.437",
"Id": "405977",
"Score": "1",
"body": "Oh yeah, this is much cooler now ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T13:04:56.230",
"Id": "405979",
"Score": "0",
"body": "@t3chb0t Thank you. I'm glad for the continuous support you provided so far. It has given me a good impression of code review while introducing me to some of its guidelines =)"
}
] | [
{
"body": "<p>You should remove </p>\n\n<pre><code>int dummyCounter = 1; \n</code></pre>\n\n<p>and change the <code>if</code>'s checking for <code>folderStack.Count</code> to an <code>if..else</code> like so </p>\n\n<pre><code> //Ends the while loop\n if (folderStack.Count == 0)\n {\n break;\n } \n else\n {\n currentFolder = folderStack.Pop();\n } \n</code></pre>\n\n<p>While writing this I thought about this </p>\n\n<blockquote>\n<pre><code>if (dummyCounter != 1)\n{\n @Html.Partial(\"_Folder\", currentFolder);\n}\n</code></pre>\n</blockquote>\n\n<p>as well and again checked the program-flow. If we assume that the <code>parentFolder.FoldersContained != 0</code> we output the files of the <code>parentFolder</code> twice. One time inside the <code>do..while</code> loop and one time after the loop. We could remove this <code>if</code> and this </p>\n\n<pre><code>//Parent folder\n@Html.Partial(\"_Folder\", parentFolder); \n</code></pre>\n\n<p>like so </p>\n\n<pre><code>@foreach (var parentFolder in Model)\n{\n\n Stack<Folder> folderStack = new Stack<Folder>();\n folderStack.Push(parentFolder);\n\n @while (folderStack.Count > 0)\n {\n\n var currentFolder = folderStack.Pop();\n @Html.Partial(\"_Folder\", currentFolder);\n\n <div class=\"collapse\" id=\"@currentFolder.Id\">\n\n @for (int i = currentFolder.FoldersContained; i > 0; i--)\n {\n //Pushes all nested directories into my stack\n //in reverse inorder to display the top directory\n folderStack.Push(currentFolder.Folders[i - 1]);\n }\n\n // Should they contain any files, display them\n @foreach (var file in currentFolder.Files)\n {\n @Html.Partial(\"_File\", file);\n }\n\n </div>\n\n }\n}\n</code></pre>\n\n<p>I know that this isn't exactly the same as you had before (the most outer <code><div class=\"collapse\" id=\"@currentFolder.Id\"></code> is missing) but it is much clearer and easier to read. If you need this <code>div</code>'s I would suggest to just use a separate method to process the contained folders and files of the parentFolders. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-16T19:15:55.033",
"Id": "409261",
"Score": "0",
"body": "Thanks for the advices, even if they didn't nessercary solve the issue. I will how ever use them for further improvements. I think you're right about finding a different approach. And also made me aware that, just like your code doesn't work with having subdirectories showned under my parent folder. Any subdirectories greater than 1 level down wouldn't be showned as expected either unfortunately.\n\nWasn't aware of that mistakes giving the data I was working with didn't offer such a senario. Much appriciated."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-27T10:52:53.773",
"Id": "210416",
"ParentId": "210041",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "210416",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T12:44:33.500",
"Id": "210041",
"Score": "5",
"Tags": [
"c#",
"performance",
"asp.net-mvc-5",
"razor"
],
"Title": "Display all files in a folder (object) along with nested subdirectories part 2"
} | 210041 |
<p>I created online shop with angular 7 and I am not sure is good architecture. I created 5 modules:</p>
<ul>
<li>main module </li>
<li>products</li>
<li>shop-cart </li>
<li>core</li>
<li>admin</li>
</ul>
<p>I have <code>service</code> :</p>
<ul>
<li>admin.service.ts</li>
<li>products.service.ts</li>
<li>data-storage-service.ts</li>
<li>message-data.service.ts</li>
<li>shop-cart.service.ts</li>
</ul>
<p>I have module for routing:</p>
<ul>
<li>app-routing.module.ts</li>
<li>products.service.ts</li>
</ul>
<p>In main module I include all others module: </p>
<pre><code>@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
CoreModule,
AdminModule,
SharedModule,
ShopCartModule,
ProductsModule,
HttpClientModule,
FormsModule,
ModalModule.forRoot(),
HttpClientInMemoryWebApiModule.forRoot(
InMemoryDataService, { dataEncapsulation: false }
)
],
providers: [,
InMemoryDataService],
bootstrap: [AppComponent]
})
export class AppModule { }
</code></pre>
<p>This is my core module where I include all <code>service</code>:</p>
<pre><code>@NgModule({
imports: [
CommonModule,
AppRoutingModule
],
exports: [
AppRoutingModule,
HeaderComponent,
FooterComponent
],
declarations: [
HeaderComponent,
HomeComponent,
FooterComponent
],
providers:[
DataStorageServiceService,
ProductsService,
ShopCartService,
AdminSerivice,
MessageService
]
})
export class CoreModule { }
</code></pre>
<p>I using <code>data-storage-service.ts</code> for communication with server. In my <code>admin.service.ts</code> and <code>products.service.ts</code> I have methods for calling method form <code>data-storage-service.ts</code> and store data in list.
Example:
<code>data-storage-service.ts</code> have method : </p>
<pre><code> /** GET Category from the server */
getCategory(): Observable<CategoryModel[]> {
return this.http.get<CategoryModel[]>(this.cateogryUrl).pipe(
catchError(this.handleError('getProduct', []))
)
}
</code></pre>
<p><code>admin.service.ts</code> have method: </p>
<pre><code>getCategoryFromServer() {
this.dataStorageServiceServiceta.getCategory().subscribe((category: CategoryModel[]) => {
this.categoryList = category;
this.cateogoryChanged.next(this.categoryList.slice())
})
}
</code></pre>
<p>And in component<code>admin.componenet.ts</code> in <code>ngOnInit</code> I have </p>
<pre><code> ngOnInit() {
this.admin.getCagegoryFromServer();
}
</code></pre>
<p>Are is this correct <a href="https://i.stack.imgur.com/eN3dy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eN3dy.png" alt="enter image description here"></a>?</p>
| [] | [
{
"body": "<p>It seems to me more logical that the declaration of all services is done in your \"main\" rather than in \"core\". It is better to separate as much as possible the dependencies between modules of the same level.</p>\n\n<p>In addition, the module \"core\" and \"shared\" are quite close in philosophy, they allow to share basic code in your project. I think that in the future it will be confusing.</p>\n\n<p>Maybe renamed core to \"home\" or just a part of your application and just use \"shared\" to share modules.</p>\n\n<p>Then, personally I will pass the definition of routes in the module file.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T13:30:41.767",
"Id": "210043",
"ParentId": "210042",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T12:56:15.797",
"Id": "210042",
"Score": "1",
"Tags": [
"typescript",
"angular-2+"
],
"Title": "Arhitecture of Angular 7 online shop"
} | 210042 |
<p>I have two arrays:</p>
<pre><code>char input[] = "ughIuytLikeretC";
</code></pre>
<p>and</p>
<pre><code>bool mask[] = {
false, false, false, true, false,
false, false, true, true, true,
true, false, false, false, true,
};
</code></pre>
<p>My function takes these two arrays and returns the characters in input whose positions are true in mask such that in this example, the result being ILikeC.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
char *filtArray(char input[], bool mask[], char *filtered) {
int j = 0;
int i;
for (i = 0; input[i]; i++) {
filtered[j] = input[i];
j += mask[i];
}
filtered[j] = 0;
return filtered;
}
</code></pre>
<p><code>filtArray</code> will run on billions of "input" strings of constant length and "mask" will be the same for all "input"s.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T15:58:55.193",
"Id": "406001",
"Score": "0",
"body": "It's bad practice to write data to a result array that shouldn't be there. You write the contents to `filtered` regardless of if it should be there or not, then overwrite it. Avoid this. Suppose there is no correct data - you will then corrupt the result array. I would also avoid using booleans for arithmetic, it's quite ugly and hard to read."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T16:52:23.967",
"Id": "406014",
"Score": "0",
"body": "@Lundin: I'm not clear on what you mean when you say the array \"shouldn't be there.\" Seems to me it should always exist since that result is the point of calling the function in the first place."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T17:30:21.903",
"Id": "406024",
"Score": "0",
"body": "Please fix the indentation in your sample code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T17:32:07.317",
"Id": "406026",
"Score": "0",
"body": "Is it a hard requirement that `mask` be an array of booleans? Because that's quite inefficient. You really should be using a binary mask in an integer."
}
] | [
{
"body": "<p>The code compiled with no warnings and ran properly on first time which is great.</p>\n\n<p>Let's see what can be improved.</p>\n\n<p><strong>Style</strong></p>\n\n<p>The indentation of the code seems a bit weird. I do not know if this is how it looked originally or if it got broken when it was copied here.</p>\n\n<p>Also, it may be worth adding some documentation describing the inputs you are expecting (in your case, 3 arrays of same size, the first one being 0-terminated).</p>\n\n<p><strong>Do less</strong></p>\n\n<p>You use the mask only to know whether <code>j</code> is to be incremented. Actually, you could rewrite:</p>\n\n<pre><code>j += mask[i];\n</code></pre>\n\n<p>as</p>\n\n<pre><code> if (mask[i])\n j++;\n</code></pre>\n\n<p>which is more explicit but less concise.</p>\n\n<p>The real benefic is when you realize than updating <code>filtered</code> can be done only when we have <code>mask[i]</code>. We can write:</p>\n\n<pre><code> if (mask[i])\n {\n filtered[j] = input[i];\n j++;\n }\n</code></pre>\n\n<p>or the equivalent:</p>\n\n<pre><code> if (mask[i])\n filtered[j++] = input[i];\n</code></pre>\n\n<p><strong>Null character</strong></p>\n\n<p>Instead of <code>filtered[j] = 0;</code>, you could use the <a href=\"https://en.wikipedia.org/wiki/Null_character\" rel=\"nofollow noreferrer\">Null Character</a> which is equivalent here but more usual and write: <code>filtered[j] = '\\0';</code>.</p>\n\n<p><strong>Signature</strong></p>\n\n<p>I am not sure if it is really useful to have the <code>filtered</code> value returned as it is already known by the calling function. Also, <code>filterArray</code> may be a better name.</p>\n\n<p><strong>Going further</strong></p>\n\n<p>Instead of definining a mask as an array of boolean, you could provide an array with the positions of the characters you are interested in.</p>\n\n<p>In your case, you'd provide something like: <code>{3, 7, 8, 9, 10, 14 }</code>.</p>\n\n<p>This could be less efficient because we'd perform a smaller number of iterations. Here, we'd iterate over 6 elements instead of 15.</p>\n\n<p>The corresponding mask could be converted manually (which is what I did here) if it is for a known value or you could write a function to pre-process the mask. This seems to be relevant in your case as the same mask is used many times on different inputs.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T14:19:18.677",
"Id": "210051",
"ParentId": "210044",
"Score": "1"
}
},
{
"body": "<p>I see some things that may help you improve your code.</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. Here's the test <code>main</code> I used for your code:</p>\n\n<pre><code>int main() {\n const char *input[2] = {\n \"ughIuytLikeretC\", \n \"xxxExxxdwarxxxd\",\n };\n const bool mask[] = {\n false, false, false, true, false,\n false, false, true, true, true,\n true, false, false, false, true,\n };\n char filt[100];\n char maskstr[100];\n // create the mask string\n pmask(mask, maskstr);\n\n printf(\"Orig: %s\\nMask: %s\\nFilt: %s\\n\", input[0], maskstr, filtArray(input[0], mask, filt));\n printf(\"Orig: %s\\nMask: %s\\nFilt: %s\\n\", input[1], maskstr, filtArray(input[1], mask, filt));\n for (int i = 0; i < 10000000; ++i) {\n int n = rand() > RAND_MAX/2 ? 1 : 0;\n printf(\"Orig: %s\\nMask: %s\\nFilt: %s\\n\", input[n], maskstr, filtArray(input[n], mask, filt));\n }\n}\n</code></pre>\n\n<p>After it applies the function to two strings, it then iterates 10 million times, choosing one or the other test inputs randomly. This is for testing timing.</p>\n\n<h2>Use <code>const</code> where practical</h2>\n\n<p>The <code>filtArray</code> function does not (and should not) alter either the passed <code>input</code> or <code>mask</code> arrays and so both of those should be declared <code>const</code>.</p>\n\n<pre><code>char *filtArray(const char input[], const bool mask[], char *filtered) {\n</code></pre>\n\n<h2>Consider bounds checking</h2>\n\n<p>If the input strings have already been validated for length, the function you have is OK, but in general, it's good to make sure there is enough room to copy the masked characters. If there isn't enough room, that's the recipe for a <a href=\"https://en.wikipedia.org/wiki/Buffer_overflow\" rel=\"nofollow noreferrer\">buffer overflow vulnerability</a> and must be eliminated, either by the calling routine or by this one. </p>\n\n<h2>Consider a custom copy</h2>\n\n<p>If the same mask is used for billions of strings, it would probably make sense to do things differently. For example, one alternative might look like this:</p>\n\n<pre><code>#include <string.h>\n\nchar *filtArray(const char input[], char *filtered) {\n memcpy(&filtered[1], &input[7], 4);\n filtered[0] = input[3];\n filtered[5] = input[14];\n filtered[6] = '\\0';\n return filtered;\n}\n</code></pre>\n\n<p>Note that the <code>mask</code> is no longer used in this version, because the code has implemented it implicitly. This is less flexible but offers better performance. For 10 million strings on my machine, your original version takes about 1.3 seconds, while the version shown here takes around 1.0 seconds (redirecting the output to <code>/dev/null</code> on a Linux machine).</p>\n\n<h2>Use pointers rather than indexing for speed</h2>\n\n<p>Pointers are generally a faster way to access elements than using index variables. For example, your <code>filtArray</code> routine could be written like this:</p>\n\n<pre><code>char *filtArray(const char *input, const bool *mask, char *filtered) {\n char *beginning = filtered;\n for ( ; *input; ++input, ++mask) {\n if (*mask) {\n *filtered++ = *input;\n }\n }\n *filtered = '\\0';\n return beginning;\n}\n</code></pre>\n\n<p>Because you're just beginning, this may seem strange to you, but this kind of use of pointers is a very common idiom in C. </p>\n\n<h3>Compilers are good, but not quite that good yet</h3>\n\n<p>Because there's a tendency to assume the compiler will take care of it, here's compiler output comparison of the two approaches using gcc for ARM using the on-line compiler explorer: <a href=\"https://godbolt.org/z/Y0TeVX\" rel=\"nofollow noreferrer\">https://godbolt.org/z/Y0TeVX</a></p>\n\n<p>As can be seen in this case, the generated assembly code for the pointer version is much shorter. Shorter code is usually faster (and it is in this case according to my testing) but not always. For those who are expert in compiler design: The typical improvement is as likely to be the elimination of extra live variables as for the use of pointers <em>per se</em>, but the effect is nonetheless real.</p>\n\n<h3>Measured timings</h3>\n\n<p>For each of the three variations, original, pointer, and memcpy, here are the measured times for 10 million iterations and the variances of each set of samples and the relative speed measured as the average speed compared with the average speed of the original expressed as a percentage. With no optimization:</p>\n\n<p><span class=\"math-container\">\\$\\begin{array}{l|c|c|c}\n{\\bf name}&{\\bf avg (s)}&{\\bf var (s)}&{\\bf relative}\\\\\n\\hline\n\\text{original}&1.344&0.01853&100.00\\% \\\\\n\\text{pointer}&1.244&0.01193&92.56\\% \\\\\n\\text{memcpy}&0.998&0.01177&74.26\\%\n\\end{array}\\$</span></p>\n\n<p>With <code>-O2</code> optimization:</p>\n\n<p><span class=\"math-container\">\\$\\begin{array}{l|c|c|c}\n{\\bf name}&{\\bf avg (s)}&{\\bf var (s)}&{\\bf relative}\\\\\n\\hline\n\\text{original}&1.038&0.01462&100.00\\% \\\\\n\\text{pointer}&1.000&0.00135&96.34\\% \\\\\n\\text{memcpy}&0.948&0.00692&91.33\\%\n\\end{array}\\$</span></p>\n\n<p>These results were on a 64-bit Linux machine using <code>gcc</code> version 8.2.1. I look forward to seeing other measured timing results. Time is user time as measured by <code>time -f %U</code> (See <a href=\"https://linux.die.net/man/1/time\" rel=\"nofollow noreferrer\">https://linux.die.net/man/1/time</a> for man page).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T16:08:37.367",
"Id": "406006",
"Score": "4",
"body": "\"Pointers are generally a faster way to access elements than using index variables.\" This is very subjective. The opposite may as well be true, depending on system. We should not replace indexing with pointer arithmetic unless we have very good reasons - doing so for the sake of performance is pre-mature optimization. To truly optimize for speed, it might be better to drop the bool array in favour of true bit masks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T16:43:27.770",
"Id": "406013",
"Score": "0",
"body": "It's not actually subjective, but based on *measurement and experience.* On my machine it's faster, and for many embedded systems compilers (which is what I use often) it's generally faster. But what matters is whether it's faster for the author of the code. Only measurement on that system and with real data will tell whether it's faster or not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T18:06:21.110",
"Id": "406032",
"Score": "0",
"body": "I've added more data and explanation to show why pointers are faster with this code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T19:57:12.587",
"Id": "406039",
"Score": "0",
"body": "The resulting assembly is still very dependent on compiler as well. Switching to using the intel compiler on godbolt results in indexing generating shorter assembly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T20:34:16.170",
"Id": "406043",
"Score": "0",
"body": "@pseudonym117 At the risk of stating the obvious, the output assembly is *always* dependent on the compiler. In the example you mentioned, while there are fewer instructions, the assembled code is both longer and slower with the indexed version vs the pointer version. (42 bytes vs. 38 bytes for pointer version). https://godbolt.org/z/Sr1Bsq It's another example of why we must *measure* rather than guess."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T18:07:08.477",
"Id": "406140",
"Score": "0",
"body": "`if (mask) {\n *filtered++ = *input;\n }` looks wrong. Perhaps `if (*mask) {\n *filtered++ = *input;\n }` (Add `*`). Note: this error negates your code comparison. As with all performance improvements, insure correct functionality first."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T18:14:08.417",
"Id": "406141",
"Score": "0",
"body": "With code fixed, the 2 alternatives are closer in size."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T19:25:36.330",
"Id": "406158",
"Score": "0",
"body": "The code I timed was correct -- somehow made an error pasting it. Thanks! Also, since there seems to be a lot of resistance to the idea, I've posted detailed timing results. If anybody would like to post other results (or faster code!) I'd like to see the measured results."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T14:36:05.537",
"Id": "210053",
"ParentId": "210044",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T13:37:21.600",
"Id": "210044",
"Score": "6",
"Tags": [
"performance",
"beginner",
"c",
"strings"
],
"Title": "Extract specific positions from a char array"
} | 210044 |
<p>I am doing a simple application for a pet hotel. I have almost finished but I'm still new on Python and I would like to see if there is a more efficient way to write this, whilst supporting both Python 2 and 3.</p>
<p>My next steps would be to write a searching algorithm (search by booking ID) and sorting algorithm (merge sort/selection sort etc.) to sort out the different pet types.</p>
<pre><code>import datetime
staffID = 'admin'
password = 'admin'
petName = []
petType = []
bookingID = []
roomID = []
boardedPets = []
history = []
roomInUse = []
roomToUse = []
roomRates = {'dogs':50, 'cats':45, 'birds':30, 'rodents':25}
dogcatRoomsAvailable = 60
birdRoomsAvailable = 80
rodentRoomsAvailable = 100
totalPriceStr = ""
# Login Function
# Requests user for staffID and password to gain access to the menu system
def loginFunction(s, p):
# Login inputs
staffID = input("Enter Staff ID: ")
password = input("Password: ")
# Check if staffID and password is correct;
# If input is not valid, it informs user that ID and password is invalid and requests again
loginTrust = False
while (loginTrust is False):
if (staffID == 'admin') and (password == 'admin'):
print("Successfully logged in")
loginTrust = True
else:
print("Wrong ID or Password. Please enter again. ")
loginTrust = False
staffID = input("Enter Staff ID: ")
password = input("Password: ")
# Check In Function
# Allows user to check in customers' pets
def checkIn(petNm, petTy, bookID, roomuse):
global dogcatRoomsAvailable
global birdRoomsAvailable
global rodentRoomsAvailable
# Pet Name Input
petName= input("Enter pet name: ")
petNm.append(petName)
#Pet Type Input
petType= input("\n'Dog', 'Cat', 'Bird', 'Rodent'\n Enter pet type: ")
# Check if petType is valid
petTyCheck = False
while petTyCheck == False:
if (petType.lower() == 'dog' or petType.lower() == 'cat' or petType.lower() == 'bird' or petType.lower() == 'rodent'):
# Check if rooms are still available
if (dogcatRoomsAvailable != 0):
petTy.append(petName)
petTyCheck = True
elif (birdRoomsAvailable != 0):
petTy.append(petName)
petTyCheck = True
elif (rodentRoomsAvailable != 0):
petTy.append(petName)
petTyCheck = True
else:
print("Rooms for dogs & cats are not available anymore. ")
print(boardedPets)
petTyCheck = True
FrontDeskMenu()
else:
print("Pet type must be only from the list")
petTyCheck = False
petType= input("\n'Dog', 'Cat', 'Bird', 'Rodent'\n Enter pet type: ")
# Check In Date Allocators
checkInDate = datetime.datetime.now()
cIdString = str(checkInDate)
bookingID = str(cIdString[0:4] + cIdString[5:7] + cIdString[8:10] + cIdString[11:13] + cIdString[14:16] + cIdString[17:19])
bookID.append(bookingID)
# Check Out Date Default
checkOutDate = 'Nil'
# Room Allocators
# Pet type input
print("\nRules when assigning rooms: \nFor dogs: 'D' + any numbers \nFor cats: 'C' + any numbers \nFor birds: 'B' + any numbers \nFor rodents: 'R' + any numbers")
print("Remember to insert letter and number plates in front of the kennel after bring the pets in! ")
roomToUse = input('\nAssign a room for the pet: ')
roomCheck = False
rIU = roomToUse[0]
print(rIU)
# Check if rooms are assigned accordingly for the animal
if (petType.lower() == 'dog'):
# Check if input starts with 'D' and is not in use
while roomCheck == False:
if (rIU.lower() == 'd' and (roomInUse.count(roomToUse.upper()) == 0)):
roomInUse.append(roomToUse.upper())
dogcatRoomsAvailable = dogcatRoomsAvailable - 1
print("Rooms left: ", dogcatRoomsAvailable)
roomCheck = True
# If input does not start with 'D'
elif (rIU.lower() != 'd'):
print("Room Number is either invalid or the room may be in use. Make sure the first letter starts with a 'D'. ")
roomCheck = False
roomToUse = input('Assign a room for the pet: ')
rIU = roomToUse[0]
# If room is in use
elif (roomInUse.count(roomToUse.upper()) != 0):
print("Room Number is either invalid or the room may be in use. Make sure the first letter starts with a 'D'. ")
roomCheck = False
roomToUse = input('Assign a room for the pet: ')
rIU = roomToUse[0]
else:
None
if (petType.lower() == 'cat'):
# Check if input starts with 'C' and is not in use
while roomCheck == False:
if (rIU.lower() == 'c' and (roomInUse.count(roomToUse.upper()) == 0)):
roomInUse.append(roomToUse.upper())
dogcatRoomsAvailable = dogcatRoomsAvailable - 1
print("Rooms left: ", dogcatRoomsAvailable)
roomCheck = True
# If input does not start with 'C'
elif (rIU.lower() != 'c'):
print("Room Number is either invalid or the room may be in use. Make sure the first letter starts with a 'C'. ")
roomCheck = False
roomToUse = input('Assign a room for the pet: ')
rIU = roomToUse[0]
# If room is in use
elif (roomInUse.count(roomToUse.upper()) != 0):
print("Room Number is either invalid or the room may be in use. Make sure the first letter starts with a 'C'. ")
roomCheck = False
roomToUse = input('Assign a room for the pet: ')
rIU = roomToUse[0]
else:
None
if (petType.lower() == 'bird'):
# Check if input starts with 'C' and is not in use
while roomCheck == False:
if (rIU.lower() == 'b' and (roomInUse.count(roomToUse.upper()) == 0)):
roomInUse.append(roomToUse.upper())
birdRoomsAvailable = birdRoomsAvailable - 1
print("Rooms left: ", birdRoomsAvailable)
roomCheck = True
# If input does not start with 'C'
elif (rIU.lower() != 'b'):
print("Room Number is either invalid or the room may be in use. Make sure the first letter starts with a 'C'. ")
roomCheck = False
roomToUse = input('Assign a room for the pet: ')
rIU = roomToUse[0]
# If room is in use
elif (roomInUse.count(roomToUse.upper()) != 0):
print("Room Number is either invalid or the room may be in use. Make sure the first letter starts with a 'C'. ")
roomCheck = False
roomToUse = input('Assign a room for the pet: ')
rIU = roomToUse[0]
else:
None
if (petType.lower() == 'rodent'):
# Check if input starts with 'R'
while roomCheck == False:
if (rIU.lower() == 'r' and (roomInUse.count(roomToUse.upper()) == 0)):
roomInUse.append(roomToUse.upper())
rodentRoomsAvailable = rodentRoomsAvailable - 1
print("Rooms left: ", rodentRoomsAvailable)
roomCheck = True
# If input does. not start with 'R'
elif (rIU.lower() != 'r'):
print("Room Number is either invalid or the room may be in use. Make sure the first letter starts with a 'R'. ")
roomCheck = False
roomToUse = input('Assign a room for the pet: ')
rIU = roomToUse[0]
# If room is in use
elif (roomInUse.count(roomToUse.upper()) != 0):
print("Room Number is either invalid or the room may be in use. Make sure the first letter starts with a 'R'. ")
roomCheck = False
roomToUse = input('Assign a room for the pet: ')
rIU = roomToUse[0]
else:
None
# Put information into boardedPets
boardedPets.append([bookingID, petName.title(), petType.title(), cIdString, roomToUse.title(), checkOutDate])
print(boardedPets)
print(roomInUse)
print(len(roomInUse))
print(petName)
# Call back the menu after finishing task
FrontDeskMenu()
def CheckOut():
# Requests for bookingID to checkout
cObid = str(input("Please enter booking ID: "))
counter = 0
outCheck = False
# Misc
cBidLenC = [cObid[i:i+1] for i in range(0, len(cObid), 1)]
print(cBidLenC)
boardNum = len(boardedPets)
print("Boarded pets left: ", boardNum)
# Check out date to be assigned
checkOutDate = datetime.datetime.now()
cOdString = str(checkOutDate)
if (len(cBidLenC) > 14):
print("Invalid booking ID")
cObid = str(input("Please enter booking ID: "))
elif (len(cBidLenC) < 14):
print("Invalid booking ID")
cObid = str(input("Please enter booking ID: "))
elif (len(cBidLenC) == 14):
print("Correct booking ID: ")
# Check out the pets
# Remove pet to check out from boardedPets list
# Insert the pet into history list
while outCheck == False:
for e in boardedPets: # for each list in boardedpets
print('xyz')
for element in e: # for each element in list
print('abc')
if cObid in element:
print('qwe')
# Payment
checkInDay = int(e[3][8:10])
checkOutDay = int(cOdString[8:10])
daysStayed = checkOutDay - checkInDay
if (e[2] == 'Dog'):
# Assume same day checkout rate is also the rate of one day
if (daysStayed == 0):
totalPrice = roomRates['dogs'] * daysStayed + roomRates['dogs']
print("Total days stayed: ", daysStayed)
print("Total: ", totalPrice)
totalPriceStr = ("$" + str(totalPrice))
elif (daysStayed >= 1):
totalPrice = roomRates['dogs'] * daysStayed
print("Total days stayed: ", daysStayed)
print("Total price: $", totalPrice)
elif (e[2] == 'Cat'):
# Assume same day checkout rate is also the rate of one day
if (daysStayed == 0):
totalPrice = roomRates['cats'] * daysStayed + roomRates['cats']
print("Total days stayed: ", daysStayed)
print("Total: ", totalPrice)
totalPriceStr = ("$" + str(totalPrice))
elif (daysStayed >= 1):
totalPrice = roomRates['birds'] * daysStayed
print("Total days stayed: ", daysStayed)
print("Total price: $", totalPrice)
elif (e[2] == 'Bird'):
# Assume same day checkout rate is also the rate of one day
if (daysStayed == 0):
totalPrice = roomRates['birds'] * daysStayed + roomRates['birds']
print("Total days stayed: ", daysStayed)
print("Total: ", totalPrice)
totalPriceStr = ("$" + str(totalPrice))
elif (daysStayed >= 1):
totalPrice = roomRates['birds'] * daysStayed
print("Total days stayed: ", daysStayed)
print("Total price: $", totalPrice)
elif (e[2] == 'Rodent'):
# Assume same day checkout rate is also the rate of one day
if (daysStayed == 0):
totalPrice = roomRates['rodents'] * daysStayed + roomRates['rodents']
print("Total days stayed: ", daysStayed)
print("Total: ", totalPrice)
totalPriceStr = ("$" + str(totalPrice))
elif (daysStayed >= 1):
totalPrice = roomRates['rodents'] * daysStayed
print("Total days stayed: ", daysStayed)
print("Total price: $", totalPrice)
# Data manipulations
outCheck = True
e.pop(5)
e.insert(5, cOdString)
e.append(totalPriceStr)
history.append(e)
boardedPets.pop(counter)
print("Checked out. Remaining: ", len(boardedPets))
print(boardedPets)
print("History length: ", len(history))
print(history)
counter += 1
if outCheck == True:
print("Finished checkout. ")
else:
print("Booking ID not found. Please enter again. ")
cObid = str(input("Please enter booking ID: "))
# Call back the menu after finishing task
FrontDeskMenu()
# Room Availability
# Check for availability of rooms
def roomAvailability():
print("\nRoom Availability\n")
print("Dogs: ", dogcatRoomsAvailable)
print("Birds: ", birdRoomsAvailable)
print("Rodents: ", rodentRoomsAvailable)
FrontDeskMenu()
# History function
# Reads history of pets boarded
def History():
print(history)
FrontDeskMenu()
# Search function
# note: the booking ID is ALWAYS sorted
def SearchFunction():
boardedIDList = []
count = 0
search = str(input("Enter booking ID: "))
while (count < len(boardedPets)):
bc = boardedPets[count][0]
boardedIDList.append(bc)
count = count + 1
search = ("Enter booking ID: ")
for el in boardedIDList:
print(el)
print(boardedIDList)
FrontDeskMenu()
# Menu
# Menu used for calling functions
def FrontDeskMenu():
print("\nTaylor's Pet Hotel\nFront Desk Admin")
print("A. Check in pets")
print("B. Check out pets")
print("C. Rooms Availability")
print("D. History")
print("E. Binary Search")
print("F. Exit\n")
# Input for calling functions
userInput = input("What would you like to do today?: ")
# Check if userInput is valid; if input is not valid, it continues to ask for a valid input
inputCheck = False
while (inputCheck is False):
# Checks userInput and exccute function as requested by user
if (userInput.lower() == 'a'):
checkIn(petName, petType, bookingID, roomInUse)
inputCheck = True
elif (userInput.lower() == 'b'):
CheckOut()
inputCheck = True
elif (userInput.lower() == 'c'):
roomAvailability()
inputCheck = True
elif (userInput.lower() == 'd'):
History()
inputCheck = True
elif (userInput.lower() == 'e'):
SearchFunction()
inputCheck = True
elif (userInput.lower() == 'f'):
quit()
else:
print("Invalid value! Please try again.")
userInput = input("What would you like to do today?: ")
inputCheck = False
loginFunction(staffID, password)
FrontDeskMenu()
print(boardedPets)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T15:43:23.690",
"Id": "405993",
"Score": "1",
"body": "Is it really a requirement for this code to work in both Python 2 and 3? Have you actually tested it in both?"
}
] | [
{
"body": "<blockquote>\n <p>I also want to write a searching algorithm (search by booking ID) and sorting algorithm (merge sort/selection sort etc.) to sort out the different pet types. Which algorithm is recommended for this particular situation?</p>\n</blockquote>\n\n<p>Do you <em>have</em> to write it yourself?</p>\n\n<p>A common expression is <a href=\"https://www.python.org/dev/peps/pep-0206/#id3\" rel=\"nofollow noreferrer\">Python comes with Batteries included</a>, so why not make use of the built in <code>sort</code>?</p>\n\n<h1>Review</h1>\n\n<ul>\n<li><p>Definitely check out the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8 style guide</a> for python</p>\n\n<p>This will help you write cleaner code</p></li>\n<li><p>There is no need for parenthesis around statements</p>\n\n<p><code>while (expression):</code> --> <code>while expression:</code></p>\n\n<p><code>if (expression):</code> --> <code>if expression:</code></p>\n\n<p>...</p></li>\n<li><p>Variables should be in <code>snake_case</code></p></li>\n<li><p>Avoid using <code>global</code> variables</p>\n\n<p>The reason they are bad is that they allow functions to have hidden (as in \"non-obvious\" and \"undeclared\") and thus hard to understand side effects.</p></li>\n<li><p>stay DRY(Don't repeat yourself)</p>\n\n<p>For instance</p>\n\n<p>The checks you do after each</p>\n\n<pre><code>if (petType.lower() == 'dog'):\n ...\nif (petType.lower() == 'cat'):\n ...\n</code></pre>\n\n<p>Are mostly similar, you could make this another function and give the roomtype, pettype as arguments</p></li>\n<li><p>You can assign multiple statements in one line</p>\n\n<p>For instance</p>\n\n<pre><code>if (len(cBidLenC) > 14):\n print(\"Invalid booking ID\")\n cObid = str(input(\"Please enter booking ID: \"))\nelif (len(cBidLenC) < 14):\n print(\"Invalid booking ID\")\n cObid = str(input(\"Please enter booking ID: \"))\n</code></pre>\n\n<p>Could be rewritten with </p>\n\n<p><code>if len(cBidLenc) > 14 or len(cBidLenc) < 14:</code></p>\n\n<p>Or even <code>if len(cBidLenc) != 14:</code></p></li>\n</ul>\n\n<p><em>There are still plenty of improvements to be made, but if you adhere PEP, and stay DRY this code should already be massively improved</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T14:26:24.850",
"Id": "405980",
"Score": "0",
"body": "Hi, thanks for your reply. Yes I have to write my sorting algorithm myself."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T14:17:08.413",
"Id": "210050",
"ParentId": "210046",
"Score": "2"
}
},
{
"body": "<pre><code>password = 'admin'\n</code></pre>\n\n<p>You may have guessed this already, but this is not a secure way to store a password. It should be hashed, and stored in a file that has restrictive permissions. This is only a start - you can do more advanced things like using the OS keychain, etc.</p>\n\n<pre><code>while (loginTrust is False):\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>while not loginTrust:\n</code></pre>\n\n<p>The same applies to <code>while petTyCheck == False</code>.</p>\n\n<p>This:</p>\n\n<pre><code>if (petType.lower() == 'dog' or petType.lower() == 'cat' or petType.lower() == 'bird' or petType.lower() == 'rodent'):\n</code></pre>\n\n<p>can be:</p>\n\n<pre><code>if petType.lower() in ('dog', 'cat', 'bird', 'rodent'):\n</code></pre>\n\n<p>Even better, if you de-pluralize your key names in <code>roomRates</code>, you can write:</p>\n\n<pre><code>if petType.lower() in roomRates.keys():\n</code></pre>\n\n<p>When you write this:</p>\n\n<pre><code> petType= input(\"\\n'Dog', 'Cat', 'Bird', 'Rodent'\\n Enter pet type: \")\n</code></pre>\n\n<p>You shouldn't hard-code those pet names. Instead, use a variable you already have, such as <code>roomRates</code>:</p>\n\n<pre><code>print(', '.join(roomRates.keys()))\ninput('Enter pet type: ')\n</code></pre>\n\n<p>This:</p>\n\n<pre><code>bookingID = str(cIdString[0:4] + cIdString[5:7] + cIdString[8:10] + cIdString[11:13] + cIdString[14:16] + cIdString[17:19])\n</code></pre>\n\n<p>should not be done this way. As far as I can tell, you're using a custom date format. Read about using <code>strftime</code> for this purpose.</p>\n\n<p>This:</p>\n\n<pre><code>print(\"\\nRules when assigning rooms: \\nFor dogs: 'D' + any numbers \\nFor cats: 'C' + any numbers \\nFor birds: 'B' + any numbers \\nFor rodents: 'R' + any numbers\")\n</code></pre>\n\n<p>should have you iterating over the list of pet type names, taking the first character and capitalizing it. Similarly, any other time that you've hard-coded a pet type name, you should attempt to get it from an existing variable.</p>\n\n<p>This:</p>\n\n<pre><code>if (len(cBidLenC) > 14):\n print(\"Invalid booking ID\")\n cObid = str(input(\"Please enter booking ID: \"))\nelif (len(cBidLenC) < 14):\n print(\"Invalid booking ID\")\n cObid = str(input(\"Please enter booking ID: \"))\nelif (len(cBidLenC) == 14): \n print(\"Correct booking ID: \")\n</code></pre>\n\n<p>should be:</p>\n\n<pre><code>if len(cBidLenC) != 14:\n print('Invalid booking ID')\nelse:\n print('Valid booking ID.')\n</code></pre>\n\n<p>Also, that logic needs to be adjusted so that you loop until the ID is valid.</p>\n\n<p>These:</p>\n\n<pre><code>checkInDay = int(e[3][8:10])\ncheckOutDay = int(cOdString[8:10])\n</code></pre>\n\n<p>should not be using string extraction for date components. You should be using actual date objects and getting the day field from them.</p>\n\n<p>This:</p>\n\n<pre><code>count = count + 1\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>count += 1\n</code></pre>\n\n<p>You should also consider writing a <code>main</code> function rather than having global code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T17:26:48.897",
"Id": "210065",
"ParentId": "210046",
"Score": "3"
}
},
{
"body": "<p>Your check-out <code>daysStayed</code> and <code>totalPrice</code> code is very verbose.</p>\n\n<pre><code> daysStayed = checkOutDay - checkInDay\n\n if (e[2] == 'Dog'): \n # Assume same day checkout rate is also the rate of one day\n if (daysStayed == 0):\n totalPrice = roomRates['dogs'] * daysStayed + roomRates['dogs']\n print(\"Total days stayed: \", daysStayed)\n print(\"Total: \", totalPrice)\n totalPriceStr = (\"$\" + str(totalPrice))\n elif (daysStayed >= 1):\n totalPrice = roomRates['dogs'] * daysStayed\n print(\"Total days stayed: \", daysStayed)\n print(\"Total price: $\", totalPrice)\n</code></pre>\n\n<p>If check-in and check-out are on the same day, the <code>daysStayed = 0</code>. You want to charge for at least one day, so you: <code>totalPrice = roomRates['dogs'] * daysStayed + roomRates['dogs']</code>. But <code>daysStayed</code> is zero, so the first half of that expression is useless. The <code>if:</code> and <code>else:</code> clauses contain essentially the same code. The only difference is you want a minimum of 1 day. So ...</p>\n\n<pre><code> daysStayed = max(checkOutDay - checkInDay, 1)\n\n if (e[2] == 'Dog'): \n totalPrice = roomRates['dogs'] * daysStayed\n print(\"Total days stayed: \", daysStayed)\n print(\"Total price: $\", totalPrice)\n</code></pre>\n\n<hr>\n\n<p>You charge cats the bird's rate:</p>\n\n<pre><code> elif (e[2] == 'Cat'): \n # Assume same day checkout rate is also the rate of one day\n if (daysStayed == 0):\n #...\n elif (daysStayed >= 1):\n totalPrice = roomRates['birds'] * daysStayed\n #....\n</code></pre>\n\n<hr>\n\n<p>Why even separate the cat/dog/bird/rodent into separate <code>if .. elif .. elif ..</code> statements?</p>\n\n<pre><code> daysStayed = max(checkOutDay - checkInDay, 1)\n\n look_up_key = e[2].lower() + 's' # Or choose better keys\n\n totalPrice = roomRates[look_up_key] * daysStayed\n\n print(\"Total days stayed: \", daysStayed)\n print(\"Total price: $\", totalPrice)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T02:50:51.803",
"Id": "210092",
"ParentId": "210046",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "210065",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T13:45:15.453",
"Id": "210046",
"Score": "4",
"Tags": [
"python",
"beginner"
],
"Title": "Pet hotel system in Python"
} | 210046 |
<p>This is my attempt at an implementation of the modern Fisher-Yates shuffle in Java. I'm not sure if it can be made more efficient, but I did my best to make it as simple as possible, and I learned how to use generics specifically for this, so If I did something wrong in that regard, let me know.</p>
<pre><code>package com.kestrel.test;
import java.util.ArrayList;
import java.util.Random;
public class ShuffleTest
{
public static <T> ArrayList<T> shuffle(ArrayList<T> a)
{
Random rand = new Random();
for(int n = a.size() - 1; n > 0; n--)
{
int index = rand.nextInt(n + 1);
T temp = a.get(index);
a.set(index, a.get(n));
a.set(n, temp);
}
return a;
}
public static <T> T[] shuffle(T[] a)
{
Random rand = new Random();
for(int n = a.length - 1; n > 0; n--)
{
int index = rand.nextInt(n + 1);
T temp = a[index];
a[index] = a[n];
a[n] = temp;
}
return a;
}
}
</code></pre>
<p>I know that I would have to implement methods for all of the primitive array types separately, but I'm short on time, and I don't think autoboxing will slow down my code all that much.</p>
| [] | [
{
"body": "<p>You are both mutating & returning the value you are passing to the function. Pick one. Either return <code>void</code> or return a new array/<code>ArrayList</code> without mutating the input. </p>\n\n<p>Your first <code>shuffle()</code> method requires an <code>ArrayList</code>, yet any <code>Collection</code> which implements the <code>List</code> interface would work, and will work well if it has <span class=\"math-container\">\\$O(1)\\$</span> get & set complexity. So consider loosening the type from a concrete type to the <code>List</code> interface. (It will even work for <code>LinkedList</code>, albeit with horrible performance, but working slowly is arguably better than not being able to work at all.)</p>\n\n<hr>\n\n<p>The value returned by <code>ArrayList<T>::set(int idx, T obj)</code> is the previous contents of that location. Therefor, the temporary is not necessary.</p>\n\n<pre><code> T temp = a.get(index);\n a.set(index, a.get(n));\n a.set(n, temp);\n</code></pre>\n\n<p>can become:</p>\n\n<pre><code> a.set(n, a.set(index, a.get(n)));\n</code></pre>\n\n<p>or more clearly, just <code>Collections.swap(a, n, index);</code>.</p>\n\n<p>Similarly,</p>\n\n<pre><code> T temp = a[index];\n a[index] = a[n];\n a[n] = temp;\n</code></pre>\n\n<p>can also become <code>Collections.swap(a, n, index);</code>, a similar function which takes a <code>T[]</code> instead of a <code>List<?></code> as the first argument.</p>\n\n<hr>\n\n<p>Here is an implementation of your \"<em>something like <code>K<T></code> using generics</em>\" from the comments. And no longer coding from the hip, so the Java syntax is actually correct.</p>\n\n<pre><code>MacBook-Pro:~ aneufeld$ jshell\n| Welcome to JShell -- Version 10.0.1\n| For an introduction type: /help intro\n\njshell> public class ShuffleTest {\n ...> public static <T,K extends List<T>> K shuffle(Collection<T> a, Supplier<K> supplier) {\n ...> K dup = supplier.get();\n ...> dup.addAll(a);\n ...> Collections.shuffle(dup); // Or use your shuffle implementation\n ...> return dup;\n ...> }\n ...> }\n| created class ShuffleTest\n\njshell> var orig = List.of(\"Hello\", \"world\");\norig ==> [Hello, world]\n\njshell> ArrayList<String> shuffled = ShuffleTest.shuffle(orig, ArrayList<String>::new);\nshuffled ==> [world, Hello]\n\njshell> \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T14:45:03.590",
"Id": "406098",
"Score": "0",
"body": "If I change ArrayList to List would there be any downsides?Also, I had thought I was only passing by value/returning. how to I tell whether or not something will get mutated or just have its value passed?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T15:08:38.070",
"Id": "406099",
"Score": "1",
"body": "Due to โType Erasureโ, if you change `ArrayList` to `List`, and you pass in an `ArrayList`, you will notice zero difference in behaviour or performance, because exactly the same bytecode will being generated. There shouldnโt be any downside."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T15:16:40.310",
"Id": "406100",
"Score": "1",
"body": "Java is strictly pass-by-value. However, what is being passed by value is a **reference** to the object (in this case, `List` or `ArrayList`). If you change the object in anyway, everyone with a reference to the object will see the change. If you mutate the `a` object, the caller will see their list has changed. If you set the variable `a` to a different value, such as `null`, the caller wonโt see that change because the reference was passed by value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T15:19:03.307",
"Id": "406101",
"Score": "0",
"body": "if I change `public static <T> ArrayList<T> shuffle(ArrayList<T> a)` to `public static <T> List<T> shuffle(List<T> a)` it no longer lets me return into an ArrayList. Am I just doing It wrong? should I be using something like wildcards?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T15:31:11.037",
"Id": "406104",
"Score": "1",
"body": "Iโd not return anything. `public static <T> void shuffle(List<T> a)`. Because the list is being mutated, you donโt need a return value to assign to anything."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T15:41:45.517",
"Id": "406106",
"Score": "0",
"body": "In this case however, I'd like to be able to keep the original copy intact if necessary, and I figured returning a value is the cleanest way of doing that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T16:17:59.610",
"Id": "406119",
"Score": "1",
"body": "In that case, perhaps `public static <T> ArrayList<T> shuffle(Collection<T> c)`. The first thing the function should do would be `ArrayList<T> dup = new ArrayList<T>(c);`, and then it would be free to sort this duplicate list. You could pass in an `ArrayList<>`, but you could also pass in a `Vector<>`. Even a `LinkedList<>` would now shuffle in \\$O(n)\\$ time. Unordered collections like `HashSet<>` could even be shuffled. The catch is: it would always return an `ArrayList<>`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T16:35:27.283",
"Id": "406123",
"Score": "0",
"body": "so is it possible to do something like K<T> with generics?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T20:07:54.127",
"Id": "406165",
"Score": "1",
"body": "Like: `public static <T, K extends List<? extends T>> K shuffle(K a) { ... }`? Sure. But now you need to use reflection to create your duplicate `K`. Better, you could pass in a `Supplier<K>` to create the object that will be returned. Coding from the hip ... something like ... `public static <T, K extends List<? extends T>> K shuffle(K a, Supplier<K> supplier) { K dup = supplier.get(); dup.addAll(a); ...do_the_shuffle... ; return dup; }`. You would call it with ... `ArrayList<String> shuffled_dup = ShuffleTest::shuffle(orig, ArrayList<String>::new);`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T21:57:34.350",
"Id": "406175",
"Score": "0",
"body": "wow... that got really complicated really quick. so if I'm understanding you correctly, a supplier is used to tell the function what type of collection to use? I didn't even know the double colon operator was a thing in java. would a high school computer science class teach this stuff? I think I might be approaching the limits of what I can do on my own."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T22:02:55.157",
"Id": "406176",
"Score": "0",
"body": "Sorry. First double colon was a typo; should be a single period. The double colon of `ArrayList<String>::new` is correct. It is a method reference, introduced in Java 8."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T22:06:24.763",
"Id": "406277",
"Score": "0",
"body": "so, most of that works. however, function from the list class, (set, addAll) gets an error. `The method set(int, capture#4-of ? extends T) in the type List<capture#4-of ? extends T> is not applicable for the arguments (int, capture#3-of ? extends T)` my best guess is that it wont let me assume that those functions will be available in whatever I pass in later, but I'm not sure, and I have no way of knowing how to fix it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T10:46:24.137",
"Id": "406295",
"Score": "1",
"body": "I said I was coding from the hip. See edit."
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T03:30:38.380",
"Id": "210096",
"ParentId": "210055",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "210096",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T15:05:10.843",
"Id": "210055",
"Score": "1",
"Tags": [
"java",
"algorithm",
"generics",
"shuffle"
],
"Title": "Fisher-Yates shuffle Java implementation"
} | 210055 |
<p>I wanted to update some properties of my <a href="https://codereview.stackexchange.com/questions/209777/replacing-uri-with-a-more-convenient-class">UriString</a> but since this type is immutable, it wouldn't work. Actually, I just wanted to update the <code>Path</code> property but I don't want to have a constructor with several parameters like in the <a href="https://codereview.stackexchange.com/questions/193804/selective-updates-to-immutable-types">other question</a> because this is too much work and sometime not desireable. Instead, I require the immutable type to have an <em>immutable-update-construtor</em> that takes the <code>ImmutableUpdate</code> object that I use for this purpose.</p>
<p>To the user it looks like a dummy class without any useful properties:</p>
<pre><code>public sealed class ImmutableUpdate : IEnumerable<(PropertyInfo Property, object Value)>
{
private readonly IEnumerable<(PropertyInfo Property, object Value)> _updates;
internal ImmutableUpdate(IEnumerable<(PropertyInfo Property, object Value)> updates)
{
_updates = updates;
}
public IEnumerator<(PropertyInfo Property, object Value)> GetEnumerator() => _updates.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => _updates.GetEnumerator();
}
</code></pre>
<p>and it should, because it's only a carrier type for updates and an <em>alias</em> for the lengthy enumeration signature. These updates are created and used by the <code>ImmutableUpdater</code> that binds values to properties via their backing-fields and allows the <code>Bind</code> method to be called only from within the constructor of the object being updated. This should be a simple protection against mutating random instances. <code>ImmutableUpdate</code> has also an <code>internal</code> constructor and is <code>sealed</code> which also prevents using it in a wrong way. (<code>ImmutableUpdater</code> currently looks for properties that have no <em>setter</em> but extending it to understand some special attributes to customize this procees should be possible.)</p>
<pre><code>public static class ImmutableUpdater
{
public static T With<T, TMember>(this T obj, Expression<Func<T, TMember>> memberSelector, TMember newValue)
{
if (!(memberSelector.Body is MemberExpression memberExpression))
{
throw new ArgumentException($"You must select a member. Affected expression '{memberSelector}'.");
}
if (!(memberExpression.Member is PropertyInfo selectedProperty))
{
throw new ArgumentException($"You must select a property. Affected expression '{memberSelector}'.");
}
if (selectedProperty.GetSetMethod() != null)
{
throw new ArgumentException($"You must select a readonly property. Affected expression '{memberSelector}'.");
}
if (GetBackingField<T>(selectedProperty.Name) == null)
{
throw new ArgumentException($"You must select a pure readonly property (not a computed one). Affected expression '{memberSelector}'.");
}
var immmutableUpdateCtor =
typeof(T)
.GetConstructor(new[] { typeof(ImmutableUpdate) });
var updates =
from property in obj.ImmutableProperties()
let getsUpdated = property.Name == selectedProperty.Name
select
(
property,
getsUpdated ? newValue : property.GetValue(obj)
);
return (T)Activator.CreateInstance(typeof(T), new ImmutableUpdate(updates));
}
public static void Bind<T>(this ImmutableUpdate update, T obj)
{
// todo - this could be cached
var isCalledByImmutableUpdateCtor = new StackFrame(1).GetMethod() == ImmutableUpdateConstructor(typeof(T));
if (!isCalledByImmutableUpdateCtor)
{
throw new InvalidOperationException($"You can call '{nameof(Bind)}' only from within an ImmutableUpdate constructor.");
}
foreach (var (property, value) in update)
{
GetBackingField<T>(property.Name)?.SetValue(obj, value);
}
}
private static FieldInfo GetBackingField<T>(string propertyName)
{
var backingFieldBindingFlags = BindingFlags.NonPublic | BindingFlags.Instance;
var backingFieldName = $"<{propertyName}>k__BackingField";
return typeof(T).GetField(backingFieldName, backingFieldBindingFlags);
}
private static IEnumerable<PropertyInfo> ImmutableProperties<T>(this T obj)
{
return
typeof(T)
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(p => p.GetSetMethod() is null);
}
private static ConstructorInfo ImmutableUpdateConstructor(Type type)
{
return type.GetConstructor(new[] { typeof(ImmutableUpdate) });
}
}
</code></pre>
<h3>Example</h3>
<p>Its usage is pretty simple, just use <code>With</code> to set a new value.</p>
<pre><code>var user = new User();
var updatedUser = user
.With(x => x.FirstName, "John")
.With(x => x.LastName, "Doe")
//.With(x => x.FullName, "Doe") // Boom!
.Dump();
user.Dump();
</code></pre>
<p>This is the type using <code>Bind</code> inside its special constructor:</p>
<pre><code>class User
{
public User() { }
public User(ImmutableUpdate update)
{
update.Bind(this);
}
public string FirstName { get; }
public string LastName { get; }
}
</code></pre>
<hr>
<p>Is this solution any better than others, or worse? What do you say? I'm not really concerned about performance as this won't be used for any crazy scenarios (yet).</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T15:34:33.517",
"Id": "405991",
"Score": "1",
"body": "I was literally just contemplating writing one of these... I was wondering how best to specify properties, and had completely forgotten about Expressions, so thanks ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T17:16:32.900",
"Id": "406019",
"Score": "1",
"body": "At first blush, the chained `With`s that return a new object each time seem a little wasteful if the next one is discarding the previous. Perhaps it could return an \"interim\" container object that can accumulate the `With` expressions and a final `Apply()` that executes them once and produces a single `User` (in this case) object?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T13:53:39.213",
"Id": "440678",
"Score": "1",
"body": "_You must select a pure readonly property_ that is just cruel xD"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-23T13:55:19.663",
"Id": "440679",
"Score": "1",
"body": "@dfhwze hahaha I probably should name this thing an immutable virus as it infects immutables from inside and eats them like a parasite ;-]"
}
] | [
{
"body": "<p>A couple of small things here. My bigger thought is in the comment on the original question.</p>\n\n<p><strong>One:</strong></p>\n\n<p>Empty collections are nice if <code>null</code>s show their ugly faces:</p>\n\n<pre><code>internal ImmutableUpdate(IEnumerable<(PropertyInfo Property, object Value)> updates)\n{\n _updates = updates ?? Enumerable.Empty<(PropertyInfo Property, object Value)>();\n}\n</code></pre>\n\n<p><strong>Two:</strong></p>\n\n<pre><code> var immmutableUpdateCtor =\n typeof(T)\n .GetConstructor(new[] { typeof(ImmutableUpdate) });\n</code></pre>\n\n<p>is never used. I'd rewrite that little block as:</p>\n\n<pre><code>var immmutableUpdateCtor = ImmutableUpdateConstructor(typeof(T));\n\nif (immutableUpdateCtor == null)\n{\n return obj;\n}\n\nvar updates =\n from property in obj.ImmutableProperties()\n let getsUpdated = property.Name == selectedProperty.Name\n select\n (\n property,\n getsUpdated ? newValue : property.GetValue(obj)\n );\n\nreturn (T)immutableUpdateCtor.Invoke(new object[] { new ImmutableUpdate(updates) });\n</code></pre>\n\n<p>I'll addend more if I think of anything.</p>\n\n<p><strong>Three:</strong></p>\n\n<p>The caching of constructor information as was commented in the code:</p>\n\n<pre><code> private static readonly ConcurrentDictionary<Type, ConstructorInfo> _ImmutableConstructors =\n new ConcurrentDictionary<Type, ConstructorInfo>();\n\n private static ConstructorInfo ImmutableUpdateConstructor(Type type)\n {\n if (!_ImmutableConstructors.TryGetValue(type, out var constructor))\n {\n constructor = type.GetConstructor(new[] { typeof(ImmutableUpdate) });\n _ImmutableConstructors.TryAdd(type, constructor);\n }\n\n return constructor;\n }\n</code></pre>\n\n<p><strong>Four:</strong></p>\n\n<p>Here are the builder pieces:</p>\n\n<p>In <code>ImmutableUpdater</code> class:</p>\n\n<pre><code>public static UpdateBuilder<T> With<T, TMember>(this T obj, Expression<Func<T, TMember>> memberSelector, TMember newValue)\n{\n ConstructorInfo immutableUpdateCtor = ImmutableUpdateConstructor(typeof(T));\n\n return new UpdateBuilder<T>(obj, immutableUpdateCtor).With(memberSelector, newValue);\n}\n\npublic static UpdateBuilder<T> With<T, TMember>(this UpdateBuilder<T> obj, Expression<Func<T, TMember>> memberSelector, TMember newValue)\n{\n if (!(memberSelector.Body is MemberExpression memberExpression))\n {\n throw new ArgumentException($\"You must select a member. Affected expression '{memberSelector}'.\");\n }\n\n if (!(memberExpression.Member is PropertyInfo selectedProperty))\n {\n throw new ArgumentException($\"You must select a property. Affected expression '{memberSelector}'.\");\n }\n\n if (selectedProperty.GetSetMethod() != null)\n {\n throw new ArgumentException(\n $\"You must select a readonly property. Affected expression '{memberSelector}'.\");\n }\n\n if (selectedProperty.Name.GetBackingField<T>() == null)\n {\n throw new ArgumentException(\n $\"You must select a pure readonly property (not a computed one). Affected expression '{memberSelector}'.\");\n }\n\n var updates =\n from property in obj.ImmutableProperties()\n where property.Name == selectedProperty.Name\n select\n (\n property, (object)newValue\n );\n\n return obj.Add(updates);\n}\n\nprivate static IEnumerable<PropertyInfo> ImmutableProperties<T>(this UpdateBuilder<T> obj)\n{\n return\n typeof(T)\n .GetProperties(BindingFlags.Public | BindingFlags.Instance)\n .Where(propertyInfo => propertyInfo.GetSetMethod() is null);\n}\n</code></pre>\n\n<p>and finally, the <code>UpdateBuilder<T></code> class:</p>\n\n<pre><code>using System.Linq;\nusing System.Reflection;\n\nusing IEnumerablePropertyValue = System.Collections.Generic.IEnumerable<(System.Reflection.PropertyInfo Property, object Value)>;\nusing PropertyValueList = System.Collections.Generic.List<(System.Reflection.PropertyInfo Property, object Value)>;\n\npublic sealed class UpdateBuilder<T>\n{\n private readonly PropertyValueList _updates = new PropertyValueList();\n\n private readonly ConstructorInfo _immutableUpdateCtor;\n\n public UpdateBuilder(T obj, ConstructorInfo immutableUpdateCtor)\n {\n this.Object = obj;\n this._immutableUpdateCtor = immutableUpdateCtor;\n }\n\n public T Object { get; }\n\n public UpdateBuilder<T> Add(IEnumerablePropertyValue updates)\n {\n foreach (var update in updates ?? Enumerable.Empty<(PropertyInfo Property, object Value)>())\n {\n this._updates.Add(update);\n }\n\n return this;\n }\n\n public static implicit operator T(UpdateBuilder<T> updateBuilder)\n {\n if (updateBuilder == null)\n {\n return default(T);\n }\n\n if (updateBuilder._immutableUpdateCtor == null)\n {\n return updateBuilder.Object;\n }\n\n return (T)updateBuilder._immutableUpdateCtor.Invoke(new object[] { new ImmutableUpdate(updateBuilder._updates) });\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T17:35:57.503",
"Id": "406027",
"Score": "1",
"body": "Ooops, it stayed there after _moving_ it do the helper ;-]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T20:21:01.320",
"Id": "406042",
"Score": "1",
"body": "You must like it ;-) I see you've added a builder. I'll definitely _borrow_ it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T17:34:09.683",
"Id": "210066",
"ParentId": "210056",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "210066",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T15:31:46.597",
"Id": "210056",
"Score": "4",
"Tags": [
"c#",
"reflection",
"extension-methods",
"immutability"
],
"Title": "Immutable type updater using a special constructor"
} | 210056 |
<p>I am enrolled in an online JavaScript course and one of our coding challenges was presented as follows:</p>
<blockquote>
<p>John and his family went on a holiday and went to 3 different restaurants. The bills were $124, $48, and $268.</p>
<p>To tip the waiter a fair amount, John created a simple tip calculator (as a function). He likes to tip 20% of the bill when the bill is less than $50,
15% when the bill is between $50 and $200, and 10% if the bill is more than $200.</p>
<p>In the end, John would like to have 2 arrays:</p>
<ol>
<li>Containing all three tips (one for each bill)</li>
<li>Containing all three final paid amounts (bill + tip)</li>
</ol>
</blockquote>
<p>I have come up with the following solution:</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>var bills = [124, 48, 268];
var totals = [];
var pointlessArray = [];
function calculateTip(cost) {
switch (true) {
case cost < 50:
return cost * .2;
break;
case cost > 49 && cost < 201:
return cost * .15;
break;
case cost > 200:
return cost * .1;
break;
default:
Error('Unsupported input.');
}
}
function makePointlessArray(inputArray) {
var length = inputArray.length;
for (var i = 0; i < length; i++) {
pointlessArray[i] = calculateTip(inputArray[i]);
}
}
function calculateTotal(billArray) {
var length = billArray.length;
for (var i = 0; i < length; i++) {
totals[i] = billArray[i] + calculateTip(billArray[i]);
}
}
makePointlessArray(bills);
calculateTotal(bills);
console.log(`The bills are: ${bills}`);
console.log(`The calculated tips are: ${pointlessArray}`);
console.log(`The calculated totals are: ${totals}`);</code></pre>
</div>
</div>
</p>
<p>I don't think this is practical at all for calculating tips, but have tried to stay within the parameters of the challenge. </p>
<p>I am unsure if declaring the arrays as global variables is the best practice or if some other method should be used, but as a JS newbie I would appreciate any input on pitfalls in my code.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T22:04:54.233",
"Id": "406048",
"Score": "0",
"body": "So the waiter gets more money if the bill is $49 than if itโs $51? Weird... :)"
}
] | [
{
"body": "<h3><code>break</code> statements after <code>return</code></h3>\n\n<p>While it is a great habit to include the <code>break</code> statements, there is no need to include <code>break</code> statements following a <code>return</code>, since anything following the <code>return</code> statement within a function is unreachable.</p>\n\n<h3><code>switch(true)</code></h3>\n\n<p>while this works because each <code>case</code> statement must evaluate to true, it is simpler to just use <code>if</code> statements. Your logic checks if the value is less than 50, then if it is greater than 49 and less than 201. The requirements never specified if the values would be integers, floats, etc. So it would be wise to consider a value like 49.5. That value would be less than 50 so the first condition would be true. However if the value was $200.50 the second condition would evaluate to true, even though the value was more than 200. So update the condition to <code>cost <= 200</code>. Otherwise if neither of those conditions have been met, the value <strong>must</strong> be more than 200.</p>\n\n<pre><code>function calculateTip(cost) {\n if (cost < 50) {\n return cost * .2;\n }\n if (cost <= 200) {\n return cost * .15;\n }\n return cost * .1;\n}\n</code></pre>\n\n<h3>Error</h3>\n\n<p>The default case of the switch statement merely calls <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error\" rel=\"nofollow noreferrer\"><code>Error</code></a></p>\n\n<blockquote>\n<pre><code>default:\n Error('Unsupported input.');\n</code></pre>\n</blockquote>\n\n<p>This likely won't do what you expect. If you want an error to be thrown, then instantiate an error with the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new\" rel=\"nofollow noreferrer\"><code>new</code></a> operator and precede it with the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw\" rel=\"nofollow noreferrer\"><code>throw</code></a> operator:</p>\n\n<pre><code>throw new Error('Unsupported input.');\n</code></pre>\n\n<p>It would be wise the check the input before comparing the value against other numbers, perhaps with the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat\" rel=\"nofollow noreferrer\"><code>parseFloat()</code></a> function:</p>\n\n<pre><code>function calculateTip(cost) {\n if (!parseFloat(cost)) {\n throw new Error('Unsupported input.');\n }\n</code></pre>\n\n<p>That way anything that cannot be coerced the an integer (e.g. <code>{}</code>) will cause the error to be thrown.</p>\n\n<h3>Updated code</h3>\n\n<p>See the code below with the advice above implemented.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var bills = [124, 48, 268];\nvar totals = [];\nvar pointlessArray = [];\n\nfunction calculateTip(cost) {\n if (!parseFloat(cost)) {\n throw new Error('Unsupported input.');\n }\n if (cost < 50) {\n return cost * .2;\n }\n if (cost <= 200) {\n return cost * .15;\n }\n return cost * .1;\n}\n\nfunction makePointlessArray(inputArray) {\n var length = inputArray.length;\n for (var i = 0; i < length; i++) {\n pointlessArray[i] = calculateTip(inputArray[i]);\n }\n}\n\nfunction calculateTotal(billArray) {\n var length = billArray.length;\n for (var i = 0; i < length; i++) {\n totals[i] = billArray[i] + calculateTip(billArray[i]);\n }\n}\n\nmakePointlessArray(bills);\ncalculateTotal(bills);\n\nconsole.log(`The bills are: ${bills}`);\nconsole.log(`The calculated tips are: ${pointlessArray}`);\nconsole.log(`The calculated totals are: ${totals}`);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T00:16:33.537",
"Id": "406194",
"Score": "1",
"body": "You forgot that cash money does not exchange in fractions of a cent. Doubles and cash do not mix well.... The OP's questions question is a classic \"don't forget to round\" trap."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T18:18:07.037",
"Id": "210067",
"ParentId": "210059",
"Score": "2"
}
},
{
"body": "<p>There's a small bug in your code: a bill of $200.50 will be tipped at the wrong amount since you are testing for <code>cost < 201</code>.</p>\n\n<p>It's probably easier to just us <code>if</code>s that are sorted and return the tip from the function on the first one that passes. That avoids the need to test ranges like <code>cost > 49 && cost < 201</code>. If there were lots of categories you could make a lookup table that would work like this: </p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const tiptable = [\n {min: 200, tip: .1},\n {min: 50, tip: .15},\n {min: 0, tip: .2} \n]\n\nlet cost = 51\nlet tip = tiptable.find(tip => cost > tip.min).tip\nconsole.log(tip)\n\n`find()` will give you the first object that matches. But that only makes sense if there are enough categories that `if` statement get unwieldy.</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><code>find()</code> will give you the first object that matches. But that only makes sense if there are enough categories that <code>if</code> statement get unwieldy.</p>\n\n<p>Other parts of the code can be simplified with some of the nice functional tools javascript gives us. You can make a one-line sum using <code>reduce()</code> and you can make an array of tips using <code>map()</code> allowing you to make the arrays directly without <code>for</code> loops.</p>\n\n<p>For example:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const bills = [124, 48, 268];\n\nfunction getTip(cost){\n if (cost < 50) return .2\n if (cost <= 200) return .15 // not clear whether this should be < or <=\n return .1\n}\n\nlet with_tip = bills.map(cost => cost + cost * getTip(cost) )\nlet sum = with_tip.reduce((total, n) => total + n)\n\nconsole.log('Bills with tip: ', with_tip.map(t => t.toLocaleString(\"en-US\", {style: 'currency', currency: 'USD'})))\nconsole.log('Total:', sum.toLocaleString(\"en-US\", {style: 'currency', currency: 'USD'}))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Also, just as an example I added nicely-formatted currency strings with <code>toLocaleString</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T23:47:57.370",
"Id": "406189",
"Score": "0",
"body": "Great answer +1 Would give another +1 for the `tiptable` if I could (BTW should be `tipTable`) and +1 for `toLocaleString`. One tiny problem. What if there are 6 bills of $6.06 each. Your code reports the total as $43.63 which is not a factor of 6, who gets the extra cent? The correct answer is $43.62 with each tip being the same amount. Money values are discrete and you have forgotten to round to nearest cent each time you do a calculation. Always work in whole cents rounding each calculation or you will end up trying to split fractions of a cent."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T23:49:29.553",
"Id": "406190",
"Score": "0",
"body": "Yes, that a great point @Blindman67 and I totally agree about working with whole cents."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T00:40:39.460",
"Id": "406195",
"Score": "0",
"body": "It would be wise to disclose that ecmascript-6 features like arrow functions and `let`/`const` have certain [browser compatibilities](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const#Browser_compatibility) to be aware of- while most modern browsers support them, certain users might be using legacy browsers"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T18:59:19.137",
"Id": "210068",
"ParentId": "210059",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "210067",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T15:57:13.517",
"Id": "210059",
"Score": "3",
"Tags": [
"javascript",
"homework"
],
"Title": "Calculating tips"
} | 210059 |
<p>I wrote this simple program similar to "tiny password manager". Now I am looking for feedback how I can improve it.</p>
<p>As always, a big topic in C code is error handling. So what programming techniques could I use to write nicer code instead of all this boilerplate. Also, which errors should I catch and what error could I safely ignore?</p>
<p>Also, code style in general. Are there any lines I could rewrite in a nicer way?</p>
<pre><code>#include <assert.h>
#include <errno.h>
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <gpgme.h>
static void usage(void)
{
printf("USAGE: pw CMD KEY\n");
}
#define ENV_PW_STORE "PW_STORE"
#define DEFAULT_PW_STORE ".pw_store"
enum {
ERR_OK = 0,
ERR_SYS_ERROR = 1,
ERR_NO_KEY = 2,
ERR_NO_CMD = 3,
ERR_CRYPTO_ERROR = 4,
};
static char input_buffer[256] = {'\0'};
static char file_buffer[256] = {'\0'};
static char *get_store_dir(void)
{
char *env = getenv(ENV_PW_STORE);
if (env != NULL)
return strdup(env);
// build the default from HOME/DEFAULT_PW_STORE
const char *home = getenv("HOME");
if (home == NULL)
return NULL;
size_t required = strlen(home) + strlen(DEFAULT_PW_STORE) + 2;
assert(required > 0);
char *def = malloc(required);
if (def == NULL)
return NULL;
snprintf(def, required, "%s/%s", home, DEFAULT_PW_STORE);
return def;
}
static char *open_password_store(void)
{
char *pstore = get_store_dir();
if (pstore == NULL)
return NULL;
struct stat sb;
if (!((stat(pstore, &sb) == 0) && S_ISDIR(sb.st_mode))) {
if (mkdir(pstore, S_IRWXU)) {
fprintf(stderr, "Failed to create keystore directory\n");
}
}
return pstore;
}
static char *get_passfile(const char *dir, const char *key)
{
assert(dir != NULL);
assert(key != NULL);
// build the filename from DIR/KEY.gpg
size_t required = strlen(dir) + strlen(key) + strlen(".gpg") + 2;
assert(required > 0);
char *path = malloc(required);
if (path == NULL)
return NULL;
snprintf(path, required, "%s/%s.gpg", dir, key);
return path;
}
static struct crypto_ctx {
gpgme_ctx_t ctx;
gpgme_key_t keylist[2];
gpgme_data_t data[2];
} cc = {};
static char *decrypt_from_file(const char *path, size_t *len)
{
assert(path != NULL);
if (gpgme_data_new_from_file(&cc.data[0], path, 1))
return NULL;
gpgme_data_new(&cc.data[1]);
if (gpgme_op_decrypt(cc.ctx, cc.data[0], cc.data[1])) {
gpgme_data_release(cc.data[0]);
gpgme_data_release(cc.data[1]);
return NULL;
}
gpgme_data_release(cc.data[0]);
return gpgme_data_release_and_get_mem(cc.data[1], len);
}
static int encrypt_to_file(const char *path, char *buf, size_t len)
{
gpgme_data_new_from_mem(&cc.data[0], buf, len, 1);
gpgme_data_new(&cc.data[1]);
memset(buf, '\0', len);
if (gpgme_op_encrypt(cc.ctx, cc.keylist, GPGME_ENCRYPT_ALWAYS_TRUST,
cc.data[0], cc.data[1])) {
gpgme_data_release(cc.data[0]);
gpgme_data_release(cc.data[1]);
return 1;
}
FILE *fd = fopen(path, "wb");
if (fd == NULL) {
gpgme_data_release(cc.data[0]);
gpgme_data_release(cc.data[1]);
return 1;
}
size_t enc_len = 0;
char *enc = gpgme_data_release_and_get_mem(cc.data[1], &enc_len);
fwrite(enc, sizeof(char), enc_len, fd);
gpgme_data_release(cc.data[0]);
gpgme_free(enc);
fclose(fd);
return 0;
}
static int get_console_input(char *buf, size_t bufsize)
{
fflush(stdin);
fgets(buf, bufsize, stdin);
size_t last = strlen(buf) - 1;
// get rid of the ending newline, if present
if (buf[last] == '\n')
buf[last] = '\0';
return last;
}
static int init_crypto(void)
{
gpgme_check_version(NULL);
setlocale(LC_ALL, "");
gpgme_set_locale(NULL, LC_CTYPE, setlocale(LC_CTYPE, NULL));
if (gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP)) {
return 1;
}
if (gpgme_new(&cc.ctx)) {
return 1;
}
char *key = getenv("PW_ENC_KEY");
if (key == NULL) {
gpgme_op_keylist_start(cc.ctx, NULL, 0);
if (gpgme_op_keylist_next(cc.ctx, &cc.keylist[0])) {
return 1;
}
gpgme_op_keylist_end(cc.ctx);
} else {
if (gpgme_get_key(cc.ctx, key, &cc.keylist[0], 0)) {
return 1;
}
}
if (cc.keylist[0] == NULL) {
return 1;
}
return 0;
}
static void cleanup_crypto(void)
{
if (cc.keylist[0])
gpgme_key_unref(cc.keylist[0]);
gpgme_release(cc.ctx);
}
static int insert_entry(const char *keyfile)
{
assert(keyfile != NULL);
if (access(keyfile, F_OK)) {
printf("Inserting new key...\n");
} else {
printf("Updating existing key...\n");
}
printf("Insert password (no input to abort): ");
size_t input_len = get_console_input(input_buffer, 255);
if (input_len <= 0) {
printf("No password inserted, aborting...\n");
return ERR_OK;
}
if (encrypt_to_file(keyfile, input_buffer, input_len)) {
return ERR_CRYPTO_ERROR;
}
return ERR_OK;
}
static int get_entry(const char *keyfile)
{
assert(keyfile != NULL);
if (access(keyfile, F_OK)) {
printf("Given key does not exist.\n");
return ERR_OK;
}
size_t plain_len = 0;
char *plain = decrypt_from_file(keyfile, &plain_len);
if (plain == NULL) {
return ERR_CRYPTO_ERROR;
}
printf("%.*s\n", plain_len, plain);
gpgme_free(plain);
return ERR_OK;
}
int main(int argc, const char **argv)
{
if (argc != 3) {
usage();
return 1;
}
char *pstore = open_password_store();
if (pstore == NULL) {
fprintf(stderr, "Failed to open password store\n");
return ERR_SYS_ERROR;
}
char *filename = get_passfile(pstore, argv[2]);
if (filename == NULL) {
fprintf(stderr, "Failed to modifify key\n");
return ERR_NO_KEY;
}
if (init_crypto()) {
fprintf(stderr, "Failed to set up crypto backend\n");
return ERR_CRYPTO_ERROR;
}
int ret = 0;
// process possible commands
// new - insert or override an entry
// get - return an entry
if (strcmp("new", argv[1]) == 0) {
ret = insert_entry(filename);
} else if (strcmp("get", argv[1]) == 0) {
ret = get_entry(filename);
} else {
fprintf(stderr, "Unknown command! Use new or get!\n");
ret = ERR_NO_CMD;
}
cleanup_crypto();
free(pstore);
free(filename);
return ret;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T09:16:44.463",
"Id": "406081",
"Score": "0",
"body": "Did you run your code through a static code analyser? [CppCheck]|(http://cppcheck.sourceforge.net/) works for C, as well as C++. And don't forget to do unit testing."
}
] | [
{
"body": "<p>I'm fairly new in C, so feel free to ignore me, however, this section concerned me:</p>\n\n<pre><code> size_t input_len = get_console_input(input_buffer, 255);\n if (input_len <= 0) {\n printf(\"No password inserted, aborting...\\n\");\n return ERR_OK;\n }\n</code></pre>\n\n<p>You've set an input length of 255, great. I noticed no error trapping for someone entering a length greater than 255. This could lead to buffer overflow attacks, since this program is expected to run as root level. </p>\n\n<p>I'd suggest adding a routine for that, similar to the one that you've added to detect 0 characters entered. </p>\n\n<p>Love the fact that you've ended with a cleanup command and the following two free commands!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T21:58:44.360",
"Id": "406046",
"Score": "0",
"body": "The two bits of code you posted seem identical. What am I missing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T22:00:22.657",
"Id": "406047",
"Score": "0",
"body": "Oops... my bad....they are! Sorry!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T22:10:58.827",
"Id": "406050",
"Score": "0",
"body": "Thank you Cris Luengo. I hadn't seen that before. I fixed the problem! :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T20:38:35.853",
"Id": "210074",
"ParentId": "210069",
"Score": "4"
}
},
{
"body": "<pre><code>static int insert_entry(const char *keyfile)\n</code></pre>\n\n<p>Don't write <code>int</code>. <code>typedef</code> your <code>enum</code> so that you can write your own type instead. Similarly, here:</p>\n\n<pre><code>if (argc != 3) {\n usage();\n return 1;\n}\n</code></pre>\n\n<p>You're returning 1, but elsewhere in the same function you're returning enum constants. You should choose one or the other for consistency - probably the enum constants.</p>\n\n<pre><code>static struct crypto_ctx {\n gpgme_ctx_t ctx;\n gpgme_key_t keylist[2];\n gpgme_data_t data[2];\n} cc = {};\n</code></pre>\n\n<p>This is good, but not quite good enough. Since you've made <code>cc</code> a global, your code is non-reentrant. You should convert that <code>struct</code> to a <code>typedef struct</code>, remove the instance <code>cc</code>, and in all functions that use <code>cc</code>, accept a pointer to it as an argument.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T06:49:20.223",
"Id": "406068",
"Score": "1",
"body": "Could you cite exact section of C99 that declares `(void)` in argument list redundant? You seem to be confusing C99 with C++. At least GCC compiles the following without problem with `-std=c99`, which contradicts your claim: `void f(){} void test(){f(2,3);}`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T15:44:51.143",
"Id": "406107",
"Score": "0",
"body": "@Ruslan ISO9899, chapter 6.9.1. Given `typedef int F(void)`, the following are compatible function signatures: `int f(void)`, and `int g()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T15:47:37.090",
"Id": "406108",
"Score": "0",
"body": "@Ruslan Also, your example produces quite obvious warnings from gcc: `warning: too many arguments in call to 'f'` ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T16:03:32.377",
"Id": "406112",
"Score": "0",
"body": "If you mean the footnote, then it doesn't say that `int g()` is _the same_ signature as `int f(void)`: it's simply _compatible_, i.e. won't cause an error when you declare as `int(void)` and define as `int()`, and vice-versa. Moreover, I've still not found any normative description of `(void)` as redundant (footnotes aren't normative). As for your warning, I can't reproduce it with gcc 7 with options `-std=c99 -pedantic-errors -Wall -Wextra`. I do get this as an error in C++ mode though, which once more confirms that it's only C++ feature, not C one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T16:52:50.017",
"Id": "406126",
"Score": "0",
"body": "@Ruslan See https://stackoverflow.com/questions/41803937/func-vs-funcvoid-in-c99"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T21:51:32.060",
"Id": "210078",
"ParentId": "210069",
"Score": "4"
}
},
{
"body": "<blockquote>\n <p>a big topic in C code is error handling</p>\n</blockquote>\n\n<p>Yes. The best C code can do is to strive for <strong>uniformity</strong> as there are a number of good approaches.</p>\n\n<hr>\n\n<blockquote>\n <p>which errors should I catch (?)</p>\n</blockquote>\n\n<p>Some of the most important errors to catch are the ones outside code control - this is usually all I/O functions.</p>\n\n<p>Missing check:</p>\n\n<pre><code>// fgets(buf, bufsize, stdin);\nif (fgets(buf, bufsize, stdin) == NULL) {\n Handle_EndOfFile_or_Error();\n}\n</code></pre>\n\n<p>Naked <code>fwrite()</code>:</p>\n\n<pre><code>// fwrite(enc, sizeof(char), enc_len, fd);\nif (fwrite(enc, sizeof(char), enc_len, fd) < enc_len) {\n // Report error\n}\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p>which errors ... could I safely ignore?</p>\n</blockquote>\n\n<p>Code well does extensive checking.</p>\n\n<p>The following <code>assert()</code> only applies if the addition rolls over to 0 - a pedantic concern.</p>\n\n<pre><code>size_t required = strlen(home) + strlen(DEFAULT_PW_STORE) + 2;\n// Questionable assert.\nassert(required > 0);\n</code></pre>\n\n<p>If code is pedantic, could detect overflow with wider math.</p>\n\n<pre><code>#include <stdint.h>\n....\n// v----------v form a `uintmax_t` and add using that math\nuintmax_t sum = UINTMAX_C(2) + strlen(home) + strlen(DEFAULT_PW_STORE);\nassert(sum <= SIZE_MAX); \nsize_t required = (size_t) sum;\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p>how I can improve it.</p>\n</blockquote>\n\n<p><strong>Advanced: password scrubbing</strong></p>\n\n<p>Although not key to OP review request, secure code that uses <em>passwords</em> will 1) scrub buffers when done 2) insure atomic access 3) use functions that do 1 & 2.</p>\n\n<p>Example scrubbing:</p>\n\n<pre><code>void scrub(void *p, size_t sz) {\n volatile unsigned char *m = p;\n while (sz-- > 0) m[sz] = 0;\n}\n\nchar *filename = get_passfile(pstore, argv[2]);\n// Code is done with `pstore, argv[2]`, so zero it.\nscrub(pstore, strlen(pstore));\nscrub(argv[2], strlen(argv[2]));\n</code></pre>\n\n<p>Scrubbing is especially important when an error occurs someplace as that is often a hack approach to cause a core dump, etc.</p>\n\n<p>Interestingly, code can write to <code>argv[2]</code>. </p>\n\n<p>This is a deep issue only cursorily covered here.</p>\n\n<p><strong>Avoid UB</strong></p>\n\n<p><code>fflush(stdin);</code> is <em>undefined behavior</em> (UB). Avoid this compiler specific feature.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T00:57:02.190",
"Id": "406060",
"Score": "4",
"body": "`memset` should not be used for memory scrubbing. See note here: https://en.cppreference.com/w/c/string/byte/memset"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T04:22:45.797",
"Id": "406066",
"Score": "0",
"body": "@DavidBrown Fair enough - `memset()` is potentially optimized out. Post amened. I do not see `scrub()` will get optimized out. Your thoughts?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T08:43:01.900",
"Id": "406079",
"Score": "0",
"body": "So what could I do about `fflush(stdin);`? I need at least some way to ensure there are no characters read that the user did not enter after the promt."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T14:37:22.860",
"Id": "406097",
"Score": "0",
"body": "@flowit 1) The usual solution is to insure the prior read of user input read all the data up to the end of line. 2) After that fixing that, please provide more detail why \"ensure there are no characters read that the user did not enter after the prompt\"."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T21:57:58.683",
"Id": "210079",
"ParentId": "210069",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T19:02:56.810",
"Id": "210069",
"Score": "9",
"Tags": [
"c"
],
"Title": "A simple password manager in C"
} | 210069 |
<p>I am trying to compute the difference in timestamps and make a delta time column in a Pandas dataframe. This is the code I am currently using:</p>
<pre><code># Make x sequential in time
x.sort_values('timeseries',ascending=False)
x.reset_index(drop=True)
# Initialize a list to store the delta values
time_delta = [pd._libs.tslib.Timedelta('NaT')]
# Loop though the table and compute deltas
for i in range(1,len(x)):
time_delta.append(x.loc[i,'timestamp'] - x.loc[i-1,'timestamp'])
# Compute a Pandas Series from the list
time_delta = pd.Series(time_delta)
# Attach the Series back to the original df
x['time_delta'] = time_delta
</code></pre>
<p>It seems like there should be a more efficient / vectorized way of doing this simple operation, but I can't seem to figure it out. </p>
<p>Suggestions on improving this code would be greatly appreciated. </p>
| [] | [
{
"body": "<p>Probably you miss:</p>\n\n<ul>\n<li><a href=\"https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shift.html\" rel=\"noreferrer\"><code>shift()</code></a> possibility. With it you don't need loop by hand</li>\n<li><code>inplace</code> variable in methods, e.g. <a href=\"https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html\" rel=\"noreferrer\"><code>x.sort_values()</code></a></li>\n</ul>\n\n<p>Example code</p>\n\n<pre><code>\nfrom datetime import datetime, timedelta\nimport pandas as pd\nfrom random import randint\n\nif __name__ == \"__main__\":\n # Prepare table x with unsorted timestamp column\n date_today = datetime.now()\n timestamps = [date_today + timedelta(seconds=randint(1, 1000)) for _ in range(5)]\n x = pd.DataFrame(data={'timestamp': timestamps})\n\n # Make x sequential in time\n x.sort_values('timestamp', ascending=True, inplace=True)\n # Compute time_detla\n x['time_delta'] = x['timestamp'] - x['timestamp'].shift()\n\n print(x)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T16:56:28.670",
"Id": "406129",
"Score": "3",
"body": "Using [`x.time_delta.diff()`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.diff.html) (possibly with `-1` as argument) might be even simpler."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T22:46:39.630",
"Id": "406185",
"Score": "0",
"body": "Yes, `x['time_delta'] = x.timestamp.diff()` is simpler."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T23:52:34.657",
"Id": "406191",
"Score": "0",
"body": "Feel free to include it in your answer if you want."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T22:36:15.797",
"Id": "210081",
"ParentId": "210070",
"Score": "5"
}
},
{
"body": "<p>Use the <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.diff.html\" rel=\"noreferrer\">diff()</a>.</p>\n\n<pre><code> x['time_delta'] = x.timestamp.diff().fillna(x['time_delta'])\n</code></pre>\n\n<p>This works as below, in a simpler example. </p>\n\n<p>You could use the <code>diff()</code> Series method (with <code>fillna</code> to replace the first value in the series):</p>\n\n<pre><code>s = pd.Series([11, 13, 56, 60, 65])\ns.diff().fillna(s)\n0 11\n1 2\n2 43\n3 4\n4 5\ndtype: float64\n</code></pre>\n\n<p>This was compiled from the comments below the current best answer (which I failed to see and kept searching), and the <a href=\"https://stackoverflow.com/questions/26870116/get-original-values-from-cumulative-sum\">stack overflow link</a> that explained it with <code>fillna</code> so I am hoping this can be lifted up to the top for future seekers. Happy data processing!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-16T20:40:59.597",
"Id": "508126",
"Score": "0",
"body": "An alternative to fillna(), is to drop the first element altogether. s = pd.Series([11, 13, 56, 60, 65]) s.diff()[1:] 1 2.0 2 43.0 3 4.0 4 5.0 dtype: float64"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-05T22:47:10.947",
"Id": "241786",
"ParentId": "210070",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "210081",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T19:34:12.977",
"Id": "210070",
"Score": "10",
"Tags": [
"python",
"numpy",
"pandas"
],
"Title": "Calculating time deltas between rows in a Pandas dataframe"
} | 210070 |
<p>I'm almost sure that this can be done more efficiently than it is, but I've spent about 30 minutes just staring at my screen. This is for a home project, but I'm using it as a way to improve my coding, so while it works, I'm almost sure that there is a better way to do this.</p>
<p>Effectively, on my website there is an element that contains a value (1-5). I'm accessing that value, then I want to put in into an object with a key that is titled in regards to what the value is.</p>
<p>I know I can iterate through the array using a for...of loop, and for...in for the object. However, since there's no way to refer to an object with it's numerical index ('cause they're unsorted, by definition), I'm not sure how I can do this. </p>
<p>I'm not using any libraries; I'd like to do this with pure javascript if possible. If possible, I'd also like to avoid just adding 0: "strength", 1: "dexterity",... etc. If that's not possible though, it's not a big deal if I have to, I just was hoping there was a more elegant solution.</p>
<pre><code>var attArray = ["suStr","suDex","suSta","suPres","suMan","suCom","suInt","suWit","suRes"];
let attObj = {strength:0,dexterity:0,stamina:0,presence:0,manipulation:0,composure:0,intelligence:0,wits:0,resolve:0};
document.getElementById(attArray[0]).innerHTML = attObj.strength;
document.getElementById(attArray[1]).innerHTML = attObj.dexterity;
document.getElementById(attArray[2]).innerHTML = attObj.stamina;
document.getElementById(attArray[3]).innerHTML = attObj.presence;
document.getElementById(attArray[4]).innerHTML = attObj.manipulation;
document.getElementById(attArray[5]).innerHTML = attObj.composure;
document.getElementById(attArray[6]).innerHTML = attObj.intelligence;
document.getElementById(attArray[7]).innerHTML = attObj.wits;
document.getElementById(attArray[8]).innerHTML = attObj.resolve;
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T23:24:09.530",
"Id": "406054",
"Score": "1",
"body": "Please include enough contextual code so that we may advise you properly. I suggest that you add the relevant HTML as well. (Press Ctrl-M in the question editor to make a live demo.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T16:09:10.687",
"Id": "406115",
"Score": "0",
"body": "@200_success What really? this question does not need the HTML to understand. All the information that is needed is in the code, the markup will add nothing new to the question."
}
] | [
{
"body": "<p>There's almost always a more elegant solution that \"manually\" iterating through an array. Instead of defining <code>attArray</code>, you can define a mapping object that maps element ids to <code>attObj</code> properties, or <code>attObj</code> properties to element ids.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>const attributeToIdMap = {\n strength: \"suStr\",\n dexterity: \"suDex\",\n ...\n</code></pre>\n\n<p>Demo: </p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const attributeToIdMap = {\n strength: \"suStr\",\n dexterity: \"suDex\",\n stamina: \"suSta\",\n presence: \"suPres\",\n manipulation: \"suMan\",\n composure: \"suCom\",\n intelligence: \"suInt\",\n wits: \"suWit\",\n resolve: \"suRes\"\n};\n\nconst attributes = {\n strength: 0,\n dexterity: 0,\n stamina: 0,\n presence: 0,\n manipulation: 0,\n composure: 0,\n intelligence: 0,\n wits: 0,\n resolve: 0\n};\n\n// Create the HTML for the demo\nconst root = document.body.appendChild(document.createElement('ul'));\nfor (const [attribute, id] of Object.entries(attributeToIdMap)) {\n const li = root.appendChild(document.createElement('li'));\n li.appendChild(document.createTextNode(attribute + ': '));\n const attributeElement = li.appendChild(document.createElement('span'));\n attributeElement.id = id;\n}\n\n// Loop through attributes\nfor (const [attribute, id] of Object.entries(attributeToIdMap)) {\n document.getElementById(id).textContent = attributes[attribute];\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Alternatively, since in this case the element ids can be derived from the attribute name, you can do away with the <code>attributeToIdMap</code> object and apply the transformation. With your current id setup, this probably isn't a great idea since the mapping isn't immediately obvious, but if the ids were renamed to something like <code>attribute + 'El'</code>, it would be immediately clear what each element belonged to.</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function getId(attribute) {\n return `su${attribute[0].toLocaleUpperCase()}${attribute.substring(1, 3)}`;\n}\n</code></pre>\n\n<p>Demo:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function getId(attribute) {\n return `su${attribute[0].toLocaleUpperCase()}${attribute.substring(1, 3)}`;\n}\n\nconst attributes = {\n strength: 0,\n dexterity: 0,\n stamina: 0,\n presence: 0,\n manipulation: 0,\n composure: 0,\n intelligence: 0,\n wits: 0,\n resolve: 0\n};\n\n// Create the HTML for the demo\nconst root = document.body.appendChild(document.createElement('ul'));\nfor (const attribute of Object.keys(attributes)) {\n const li = root.appendChild(document.createElement('li'));\n li.appendChild(document.createTextNode(attribute + ': '));\n const attributeElement = li.appendChild(document.createElement('span'));\n attributeElement.id = getId(attribute);\n}\n\n// Loop through attributes\nfor (const [attribute, value] of Object.entries(attributes)) {\n document.getElementById(getId(attribute)).textContent = value;\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>I have a few other concerns about your code as well:</p>\n\n<ol>\n<li><p>Nonstandard abbreviations don't help. You will spend much more time reading code than writing it. Abbreviating <code>att</code> means that someone unfamiliar with the context wonders does this mean \"AT&T\", \"attribute\", \"attrition\"? Standard abbreviations like <code>min</code>, <code>max</code>, etc. are obviously fine.</p></li>\n<li><p>Don't mix <code>var</code> and <code>let</code>. If you can, use <code>let</code> (or even <code>const</code>)</p></li>\n<li><p>If possible, avoid <code>.innerHTML</code>. By using it you can open yourself up to XSS if the user is ever able to control the input. Prefer <code>.textContent</code>.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T23:49:32.347",
"Id": "406056",
"Score": "0",
"body": "As far as concerns about my code;\n\n1. I'm a bit dyslexic, and I have a tendency to misspell attribute, and later not track down the misspelling. I generally avoid shorthand in my variable names, but in this particular case, I am less likely to make a mistake.\n\n2. The var is actually a global variable that I use in other parts in the code. In my actual script it's 100's of lines away; I just pulled into this snippet for clarity. I tend to use let.\n\n3. What is XXS? The input is controllable, but only through a button that increments or decrements a number. Should I be worried?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T00:02:38.593",
"Id": "406057",
"Score": "0",
"body": "1. Autocomplete is great, tab is probably my most used character. 3. Typo, sorry, should have been XSS. You are probably fine since this is just numbers. XSS generally sneaks in when outputting text from a user."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T00:06:26.133",
"Id": "406058",
"Score": "0",
"body": "I use Notepad++, so I don't really have a spellcheck. I think there might be a plugin or something; I'll take a look around"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T15:54:52.223",
"Id": "406110",
"Score": "1",
"body": "Point 1. Abbreviations as in `Math` `min`, `max` and `cos` it's not `minimum`, `maximum`, and `cosine`. Tokens `var`, `const` are abbreviations for `variable` and `constant` Abbreviations make code easier to read and reduce the number of long lines that often must be split. Code complete does not read the code for you and many coders prefer to not use such tools. Learning common abbreviations and using them is an important part of writing good code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T15:58:18.730",
"Id": "406111",
"Score": "0",
"body": "Point 2. Is function scope too difficult? Did you know that `let` declarations can be a huge source mem over use example `var i=1000; while(i--){ let a = new Uint8Array(1024 * 1024); setTimeout(()=>{}) };` uses 1Gig of mem while `var a,i=1000; while(i--){ a = new Uint8Array(1024 * 1024); setTimeout(()=>{}) };` uses a few Mb. Beginners should not be advised to avoid difficult parts, they learn nothing from that. Rather you should explain when it is prefered to use parts of the language and when it's not such a good idea, including the why"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T16:05:38.477",
"Id": "406113",
"Score": "1",
"body": "And your advice to map names is adding complexity with no advantage, Why not advise the OP to change the element ids to a more conducive form eg using a postfix `<div id=\"strengthEl\">` can be found post fixing attribute name with \"El\" making the need for a map redundant. However point 3 is a good point +1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T18:50:11.877",
"Id": "406150",
"Score": "0",
"body": "@Blindman67 1 - fair point, I should clarify that I mean nonstandard abbreviations. `att` could mean a ton of different things, I certainly wouldn't advise spelling out `ast` all the time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T18:53:39.847",
"Id": "406151",
"Score": "0",
"body": "2. No, not too difficult, it just leads to less clear code. In your example I wouldn't be surprised if the declaration outside of the loop has a bug, and if it doesn't, there's still no harm in using `let` outside the loop.\n3. Mapping names - good point regarding choosing different ids, the mapping might still be useful if element ids are out of your control."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T21:25:40.567",
"Id": "406170",
"Score": "0",
"body": "Code in comment? No bug, func in `setTimeout` closes over `let a` 1Mb array each iter * 1000~1Gig `var` is safer. Block Scope (BS) being safer is a myth, with no evidence in support. BS came from C like languages as a natural step from ASM, optimising register, memory, and now cache use, BS gave performance benefits. It's been corrupted into being safe (likely due to many C coders confused about JS scope) BS is useful only. Loops using let are slower than var counters. Functional style code with BS chews memory. Im personally near advocating var over let due to the problems inherent in its use"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T21:29:38.097",
"Id": "406171",
"Score": "0",
"body": "Eeeek I just reread my comment. Everything past 1Gig is a rant, not directed at you, rather anyone that may read it. (likely no one LOL)"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T23:34:54.123",
"Id": "210084",
"ParentId": "210075",
"Score": "1"
}
},
{
"body": "<h1>Review to improve</h1>\n\n<p>Mapping named objects is a pain, makes code overly complex, and increases the chance of typos and bugs.</p>\n\n<p>This review outlines 3 ways to improve. From the most basic to very advanced with a few points in regard to your original code.</p>\n\n<p>You say you would like to locate attribute via a numeric index. This is possible but I can guarantee you will regret that approach very quickly.</p>\n\n<p>Programmers are inherently lazy, we write code because it makes things easier to do. Many beginners miss this point and find themselves writing huge tracts of repeated names, code, tables, and whatnot. As a classic example your code</p>\n\n<pre><code>document.getElementById(attArray[0]).innerHTML = attObj.strength;\ndocument.getElementById(attArray[1]).innerHTML = attObj.dexterity;\ndocument.getElementById(attArray[2]).innerHTML = attObj.stamina;\ndocument.getElementById(attArray[3]).innerHTML = attObj.presence;\ndocument.getElementById(attArray[4]).innerHTML = attObj.manipulation;\ndocument.getElementById(attArray[5]).innerHTML = attObj.composure;\ndocument.getElementById(attArray[6]).innerHTML = attObj.intelligence;\ndocument.getElementById(attArray[7]).innerHTML = attObj.wits;\ndocument.getElementById(attArray[8]).innerHTML = attObj.resolve;\n</code></pre>\n\n<p>OMDG thank god for cut and paste, hey...</p>\n\n<p>Good source code is what we call DRY (Don't Repeat Yourself). We use functions, loops, arrays, objects and more to help reduce the amount of repeated source, and thus the amount of characters we must type and the amount of code we must keep in our heads.</p>\n\n<p>In the bottom advanced example you will see that I only named all the attributes once (ignoring the HTML which was generated by a utility app on my part), yet still have a sophisticated interface.</p>\n\n<h2>The simplest improvement</h2>\n\n<p>Your best bet is to rename the elements such that you can prefix or postfix to the existing name (<code>attObj</code> property names) to locate the element</p>\n\n<p>Your HTML would look like</p>\n\n<pre><code><!-- id is postfixed with El to indicate it is an element-->\n<div id=\"strengthEl\"></div>\n...\n<div id=\"manipulationEL\"></div>\n</code></pre>\n\n<p>Then your code need only the <code>attObj</code> </p>\n\n<pre><code>const playerAtt = {strength: 0, dexterity: 0, stamina: 0, presence: 0, manipulation: 0};\nfor (const key of Object.keys(playerAtt)) {\n document.getElementById(key + \"El\").innerHTML = playerAtt[key];\n}\n</code></pre>\n\n<p><strong>Note:</strong> You should not need to postfix a variable type on a variables name, <code>attObj</code> would be better named <code>attributes</code>.</p>\n\n<p><strong>Note:</strong> The variable is a reference to (points to) the object, thus it can be a constant.</p>\n\n<p><strong>Note:</strong> In your question you mension <code>for in</code> FORGET you ever heard of <code>for in</code> as it has a pile of caveats a mile long and requires additional code to ensure property names belong to the object. Use <code>for of</code> instead</p>\n\n<p>That is a simple fix for your problem</p>\n\n<h2>More improvements</h2>\n\n<p><code>document.getElementById</code> is a node query and is excruciatingly slooowwwww... compared to alternative access methods. The general practice in JavaScript when accessing elements frequently is to store them in javascript variable. You do this as part of the setup or constructing code.</p>\n\n<pre><code>const playerAtt = {strength: 0, dexterity: 0, stamina: 0, presence: 0, manipulation: 0};\nconst attElement = {};\nfor (const key of Object.keys(playerAtt)) { \n attElement[key] = document.getElementById(key + \"El\");\n}\n\n// Then when you make changes you can access elements via the attElement obj\nfor (const key of Object.keys(playerAtt)) { \n attElement[key].textContent = playerAtt[key];\n}\n</code></pre>\n\n<p><strong>Note:</strong> That rather than use <code>innerHTML</code> which forces a parsing, page reflow, and knock out event handlers, use <code>textContent</code> if its only text you are writing to the page. It has no parsing or reflow overheads and is safe to use with a page full of event handlers.</p>\n\n<h2>Advanced version</h2>\n\n<p>This introduces a library type approach, with the complex code of writing and reading values from the object separated from the game code (via a separate JS file, best as a module but snippets here don't do modules).</p>\n\n<p>This may be a little too much, but it is good to have in mind what can be done. There are also various frameworks that use similar approaches to this <a href=\"https://vuejs.org/\" rel=\"nofollow noreferrer\">VUE.js</a> for example (I have not looked at their code so I am guessing their approach)</p>\n\n<h3>A smarter object</h3>\n\n<p>We can improve how the attributes are displayed by creating a more complex attribute object that uses a setter to...</p>\n\n<ol>\n<li>Vet the value so that it can only ever hold correct values.</li>\n<li>Knows that the value is linked to an element and thus automatically updates the element with any changes.</li>\n</ol>\n\n<p>.</p>\n\n<pre><code>const MAX_ATT_VALUE = 5;\nfunction WatchedObj(obj, name) {\n if (!obj) {//Just incase you call the function incorrectly. Only for development.\n throw new ReferenceError(\"WatchedObj requires a template object.\");\n }\n const contElement = name ? document.getElementById(name + \"El\") : document;\n function addAttribute(obj, key, value) {\n const element = contElement.querySelector(\"[data-attribute-name=\" + key + \"]\");\n Object.defineProperty(obj, name, {\n enumerable: true, \n configurable: false, \n get() { return value },\n set(val) {\n val = isNaN(val) ? 0 : val;\n val = val < 0 ? 0 : val > MAX_ATT_VALUE ? MAX_ATT_VALUE : val; \n if (value !== val) {\n value = val;\n if (element) { element.textContent = value }\n }\n }\n });\n }\n const watched = {};\n for (const [key, value] of Object.entries(obj)) { \n addAttribute(watched, key, obj);\n }\n return watched;\n}\n</code></pre>\n\n<p>Now that is a lot of code with some advanced concepts in it, getters, setters, closure, destructuring, and more. The point is that once written the object represent player attributes becomes nearly a no brainer.</p>\n\n<h3>Locating elements</h3>\n\n<p>As it is likely that you will want to display many players, you can not use the same id for more than one element as that will force the page into quirks mode, which has a pile of performance hits. So to solve the problem of locating element we can use a selector string that will find an element based on a data attribute value. eg see HTML below to find strength for player one the following selector can be used <code>document.querySelector(\"#playerOneEl [data-attribute-name=strength]\");</code></p>\n\n<p>So the HTML will look like</p>\n\n<pre><code><div id=\"playerOneEl\">\n Strength<span data-attribute-name=\"strength\"></span>\n Dexterity<span data-attribute-name=\"dexterity\"></span>\n Stamina<span data-attribute-name=\"stamina\"></span>\n Presence<span data-attribute-name=\"presence\"></span>\n Manipulation<span data-attribute-name=\"manipulation\"></span>\n Composure<span data-attribute-name=\"composure\"></span>\n Intelligence<span data-attribute-name=\"intelligence\"></span>\n Wits<span data-attribute-name=\"wits\"></span>\n Resolve<span data-attribute-name=\"resolve\"></span>\n</div>\n<div id=\"playerTwoEl\">\n Strength<span data-attribute-name=\"strength\"></span>\n Dexterity<span data-attribute-name=\"dexterity\"></span>\n Stamina<span data-attribute-name=\"stamina\"></span>\n Presence<span data-attribute-name=\"presence\"></span>\n Manipulation<span data-attribute-name=\"manipulation\"></span>\n Composure<span data-attribute-name=\"composure\"></span>\n Intelligence<span data-attribute-name=\"intelligence\"></span>\n Wits<span data-attribute-name=\"wits\"></span>\n Resolve<span data-attribute-name=\"resolve\"></span>\n</div>\n</code></pre>\n\n<p>Another approach is to use a <code><template></code> and generate the player elements by cloning the template element.</p>\n\n<h3>Defining a player object</h3>\n\n<p>Then in the code you can define an object that is the default template for a players attributes, and a helper function</p>\n\n<pre><code>const DEFAULT_PLAYER_OBJECT = {\n strength: 0, dexterity: 0, stamina: 0, presence: 0, manipulation: 0, \n composure: 0, intelligence: 0, wits: 0, resolve: 0\n};\nconst CreatePlayer = name => WatchedObj(DEFAULT_PLAYER_OBJECT, name);\nfunction randomizePlayer(player) {\n const randOf5 = () => Math.random() * 5 | 0;\n for (const key of player) {\n player[key] = randOf5();\n }\n return player;\n}\n</code></pre>\n\n<p>Then you need only create the players. All the hard work is done for you.</p>\n\n<pre><code>const playerOne = randomizePlayer(CreatePlayer(\"playerOne\")); \nconst playerTwo = randomizePlayer(CreatePlayer(\"playerTwo\")); \n</code></pre>\n\n<p>Now if you change an attribute the HTML is automatically updated as well</p>\n\n<pre><code>playerOne.strength = 5; // value set and HTML for player one strength is set to 5\nplayerTwo.wit = -5; // as it also vets the value out of range -5 is changed\n // to 0 and displayed as 0. The -5 is total forgotten \n</code></pre>\n\n<h2>Put it into play</h2>\n\n<p>Making the advanced version a little more complex the example adds a color flash indicating if an attribute as increased or decreased. Yet the code to change an attribute is as basic as can be</p>\n\n<pre><code>playerOne.strength += 1; // If not at max the value is changed and flashes cyan.\n</code></pre>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>setTimeout(() => { // simulate page load using timer\n\n // create two players\n const playerOne = randomizePlayer(CreatePlayer(\"playerOne\")); \n const playerTwo = randomizePlayer(CreatePlayer(\"playerTwo\")); \n\n\n // randomly change a player attribute every 200 to 1200 ms\n function randomPlayer(){\n const randPick = array => array[Math.random() * array.length | 0];\n var attName = randPick(Object.keys(DEFAULT_PLAYER_OBJECT));\n if (Math.random() < 0.5) {\n playerOne[attName] += Math.random() < 0.5 ? -1 : 1;\n } else {\n playerTwo[attName] += Math.random() < 0.5 ? -1 : 1;\n }\n setTimeout(randomPlayer, Math.random() * 1000 + 200);\n\n }\n randomPlayer();\n\n},0);\n\n/* Library scroll down*/\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n// Code below can be in another library js file and common to all pages.\n\n\nconst DEFAULT_PLAYER_OBJECT = {strength: 0, dexterity: 0, stamina: 0, presence: 0, manipulation: 0, composure: 0, intelligence: 0, wits: 0, resolve: 0};\nfunction CreatePlayer(name) { return WatchedObj(DEFAULT_PLAYER_OBJECT, name) }\n// to create random settings\nfunction randomizePlayer(player) {\n const randOf5 = () => Math.random() * 5 | 0;\n for (const key of Object.keys(player)) {\n player[key] = randOf5();\n }\n return player;\n}\n\n\nconst MAX_ATT_VALUE = 5;\nconst FLASH_TIME = 500; // time in ms of flash\nconst UP_FLASH_CLASS = \"upFlash\"; // name of class\nconst DOWN_FLASH_CLASS = \"downFlash\"; // name of class\nfunction WatchedObj(obj, name) {\n\n if (!obj) { // just incase you call the function incorrectly. This is only for development.\n throw new ReferenceError(\"WatchedObj requires a template object.\");\n }\n const containingElement = name ? document.getElementById(name + \"El\") : document;\n function addAttribute(obj, name, value) {\n var flashTimer, lastFlash = \"\";\n const element = containingElement.querySelector(\"[data-attribute-name=\" + name + \"]\");\n const contEl = element.parentElement;\n Object.defineProperty(obj, name, {\n enumerable: true, \n configurable: false, \n get() { return value },\n set(val) {\n val = isNaN(val) ? 0 : val; // max it a number if not already so\n val = val < 0 ? 0 : val > MAX_ATT_VALUE ? MAX_ATT_VALUE : val; // make sure is in range\n if (value !== val) { // only if the new value is different\n\n if (element) { // only if the element has been found\n clearTimeout(flashTimer);\n if (lastFlash !== \"\"){\n contEl.classList.remove(lastFlash);\n }\n lastFlash = val < value ? DOWN_FLASH_CLASS : UP_FLASH_CLASS;\n element.textContent = val; \n contEl.classList.add(lastFlash);\n flashTimer = setTimeout(() => contEl.classList.remove(lastFlash), 500);\n }\n value = val;\n }\n }\n });\n }\n const watched = {};\n for (const [key, value] of Object.entries(obj)) { // for each key value pair create a property\n addAttribute(watched, key, obj);\n }\n return watched;\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code> .player {\n display: inline-grid;\n width : 150px;\n margin-right: 20px;\n}\n.playerAtt {\n}\n\nspan {\n text-align: right;\n}\n.playerAtt span:last-child {\n float: right;\n}\n.upFlash {\n background : #09F;\n animation-duration: 0.25s;\n transition-timing-function: ease-in;\n animation-fill-mode: both; \n animation-name: fadeOut;\n}\n.downFlash {\n background : red;\n animation-duration: 0.25s;\n transition-timing-function: ease-in;\n animation-fill-mode: both; \n animation-name: fadeOut;\n \n}\n@keyframes fadeOut {\n 0% {}\n 100% { background: #FFF; }\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code> <div id=\"playerOneEl\" class=\"player\">\n <div>Player One</div>\n <div class=\"playerAtt\">Strength<span data-attribute-name=\"strength\"></span></div>\n <div class=\"playerAtt\">Dexterity<span data-attribute-name=\"dexterity\"></span></div>\n <div class=\"playerAtt\">Stamina<span data-attribute-name=\"stamina\"></span></div>\n <div class=\"playerAtt\">Presence<span data-attribute-name=\"presence\"></span></div>\n <div class=\"playerAtt\">Manipulation<span data-attribute-name=\"manipulation\"></span></div>\n <div class=\"playerAtt\">Composure<span data-attribute-name=\"composure\"></span></div>\n <div class=\"playerAtt\">Intelligence<span data-attribute-name=\"intelligence\"></span></div>\n <div class=\"playerAtt\">Wits<span data-attribute-name=\"wits\"></span></div>\n <div class=\"playerAtt\">Resolve<span data-attribute-name=\"resolve\"></span></div>\n </div>\n <div id=\"playerTwoEl\" class=\"player\">\n <div>Player Two</div>\n <div class=\"playerAtt\">Strength<span data-attribute-name=\"strength\"></span></div>\n <div class=\"playerAtt\">Dexterity<span data-attribute-name=\"dexterity\"></span></div>\n <div class=\"playerAtt\">Stamina<span data-attribute-name=\"stamina\"></span></div>\n <div class=\"playerAtt\">Presence<span data-attribute-name=\"presence\"></span></div>\n <div class=\"playerAtt\">Manipulation<span data-attribute-name=\"manipulation\"></span></div>\n <div class=\"playerAtt\">Composure<span data-attribute-name=\"composure\"></span></div>\n <div class=\"playerAtt\">Intelligence<span data-attribute-name=\"intelligence\"></span></div>\n <div class=\"playerAtt\">Wits<span data-attribute-name=\"wits\"></span></div>\n <div class=\"playerAtt\">Resolve<span data-attribute-name=\"resolve\"></span></div>\n </div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T15:06:12.180",
"Id": "210124",
"ParentId": "210075",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "210124",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T21:25:45.787",
"Id": "210075",
"Score": "-1",
"Tags": [
"javascript"
],
"Title": "Takes a value from website; places it into an object"
} | 210075 |
<p>I have a collection of items in my database with a ParentId property. I'm reading the categories as a flat structure and I would like to convert it to a hierarchy list by populating the ParentCategory and ChildCategories properties.</p>
<pre><code>// Domain class
public class Category
{
public Category()
{
this.ChildCategories = new HashSet<Category>();
}
public int CategoryId { get; set; }
public string Name { get; set; }
public int Position { get; set; }
// ... many more properties
public int? CategoryParentId { get; set; }
public virtual Category ParentCategory { get; set; }
public virtual ICollection<Category> ChildCategories { get; set; }
}
// DTO class
public class CategoryDto
{
public CategoryDto()
{
this.ChildCategories = new HashSet<CategoryDto>();
}
public int CategoryId { get; set; }
public string Name { get; set; }
public int? CategoryParentId { get; set; }
public CategoryDto ParentCategory { get; set; }
public IEnumerable<CategoryDto> ChildCategories { get; set; }
}
</code></pre>
<p>Since that we cannot do hierarchy query directly with Entity Framework Core, I can only retrieve them in a flat list like so:</p>
<pre><code>var result = myDbContext.Categories
.Select(category => new Dto.CategoryIndexDto()
{
CategoryId = category.CategoryId,
Name = category.Name,
Position = category.Position,
CategoryParentId = category.CategoryParentId,
});
</code></pre>
<p>So I needed a way to convert this list of dto objects into hierarchy list where the ParentCategory and ChildCategories are populated for each dto object. So I've made this extension:</p>
<pre><code>public static IEnumerable<TEntity> AsHierarchy<TEntity, TKeyProperty, TChildrenProperty>(
this IEnumerable<TEntity> items,
Func<TEntity, TKeyProperty> keyProperty,
Func<TEntity, TKeyProperty> parentKeyProperty,
Expression<Func<TEntity, TEntity>> parentPropertySelector,
Expression<Func<TEntity, TChildrenProperty>> childrenPropertySelector)
where TChildrenProperty : IEnumerable<TEntity>
{
return items.AsHierarchy(keyProperty, parentKeyProperty, parentPropertySelector, childrenPropertySelector, default(TKeyProperty), default(TEntity));
}
private static IEnumerable<TEntity> AsHierarchy<TEntity, TKeyProperty, TChildrenProperty>(
this IEnumerable<TEntity> items,
Func<TEntity, TKeyProperty> keyProperty,
Func<TEntity, TKeyProperty> parentKeyProperty,
Expression<Func<TEntity, TEntity>> parentPropertySelector,
Expression<Func<TEntity, TChildrenProperty>> childrenPropertySelector,
TKeyProperty parentKeyValue,
TEntity parentValue)
where TChildrenProperty : IEnumerable<TEntity>
{
foreach (var item in items.Where(item => parentKeyProperty(item).Equals(parentKeyValue)))
{
var parentProperty = (parentPropertySelector.Body as MemberExpression).Member as PropertyInfo;
var childrenProperty = (childrenPropertySelector.Body as MemberExpression).Member as PropertyInfo;
parentProperty.SetValue(item, parentValue, null);
var childrenValues = items.AsHierarchy(keyProperty, parentKeyProperty, parentPropertySelector, childrenPropertySelector, keyProperty(item), item).ToList();
childrenProperty.SetValue(item, childrenValues, null);
yield return item;
}
}
</code></pre>
<p>And now I can call my database that way:</p>
<pre><code>var result = myDbContext.Categories
.Select(category => new Dto.CategoryIndexDto()
{
CategoryId = category.CategoryId,
Name = category.Name,
Position = category.Position,
CategoryParentId = category.CategoryParentId,
})
.ToList() // query the database
.AsHierarchy(x => x.CategoryId, x => x.CategoryParentId, x => x.ParentCategory, x => x.ChildCategories)
.ToList();
</code></pre>
<p>Now my flat list is fully converted to an hierarchy list and they are all linked together by the navigation properties (ParentCategory and ChildCategories).</p>
<p>I would like to know if the AsHierarchy function is well coded for performance and if there's a way to simplify it?</p>
<h2>Edit</h2>
<p>I have modified the code of the accepted answer a little bit to answer my needs. With my modification, you can have many roots element instead of just one.</p>
<pre><code>public delegate void ParentSetter<T>(T parent, T child);
public delegate void ChildSetter<T>(T parent, T child);
public static IEnumerable<T> AsHierarchy<T, TID>(
this IEnumerable<T> elements,
Func<T, TID> idSelector,
Func<T, TID> parentIdSelector,
ParentSetter<T> parentSetter,
ChildSetter<T> childAdder)
{
Dictionary<TID, T> lookUp = elements.ToDictionary(e => idSelector(e));
foreach (T element in lookUp.Values)
{
TID parentId = parentIdSelector(element);
if (parentId == null)
{
yield return element;
continue;
}
if (!lookUp.TryGetValue(parentId, out T parent))
{
throw new InvalidOperationException($"Parent not found for: {element}");
}
parentSetter(parent, element);
childAdder(parent, element);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T22:18:44.727",
"Id": "406051",
"Score": "0",
"body": "You might find my question about the same task interesting. It's [here](https://codereview.stackexchange.com/questions/138524/recreating-a-tree-from-a-flat-collection-or-unflatten-a-tree)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T13:54:52.417",
"Id": "406096",
"Score": "0",
"body": "I think there's a little difference with what I want. I want to move my objects in is own tree, not use another class that will make the tree. But I will read your code carefully and see if I can use some logic in my own implementation. Thank you very much!"
}
] | [
{
"body": "<p>Your algorithm seems to be working as expected, and for very small data sets it is okay. But for larger data sets it is not optimal and for sets larger than 1000 it is very inefficient.</p>\n\n<p><strong>Some minor problems:</strong></p>\n\n<blockquote>\n<pre><code>foreach (var item in items.Where(item => parentKeyProperty(item).Equals(parentKeyValue)))\n{\n var parentProperty = (parentPropertySelector.Body as MemberExpression).Member as PropertyInfo;\n var childrenProperty = (childrenPropertySelector.Body as MemberExpression).Member as PropertyInfo;\n</code></pre>\n</blockquote>\n\n<p>The member information for the child and parent properties are invariant per item, so place their statements before the loop:</p>\n\n<pre><code>var parentProperty = (parentPropertySelector.Body as MemberExpression).Member as PropertyInfo;\nvar childrenProperty = (childrenPropertySelector.Body as MemberExpression).Member as PropertyInfo;\n\nforeach (var item in items.Where(item => parentKeyProperty(item).Equals(parentKeyValue)))\n{\n</code></pre>\n\n<hr>\n\n<p>Personally I try to only use reflection as the last resort and here it is not necessary. You can change your method signatures to something like this instead:</p>\n\n<pre><code>public static IEnumerable<TEntity> AsHierarchyReview<TEntity, TKeyProperty>(\n this IEnumerable<TEntity> items,\n Func<TEntity, TKeyProperty> keyProperty,\n Func<TEntity, TKeyProperty> parentKeyProperty,\n Action<TEntity, TEntity> parentSetter,\n Action<TEntity, TEntity> childSetter)\n{\n return items.AsHierarchyReview(keyProperty, parentKeyProperty, parentSetter, childSetter, default(TKeyProperty), default(TEntity));\n}\n\nprivate static IEnumerable<TEntity> AsHierarchyReview<TEntity, TKeyProperty>(\n this IEnumerable<TEntity> items,\n Func<TEntity, TKeyProperty> keyProperty,\n Func<TEntity, TKeyProperty> parentKeyProperty,\n Action<TEntity, TEntity> parentSetter,\n Action<TEntity, TEntity> childSetter,\n TKeyProperty parentKeyValue,\n TEntity parentValue)\n{\n foreach (var item in items.Where(item => parentKeyProperty(item).Equals(parentKeyValue)))\n {\n parentSetter(item, parentValue);\n\n var childrenValues = items.AsHierarchyReview(keyProperty, parentKeyProperty, parentSetter, childSetter, keyProperty(item), item).ToList();\n foreach (var child in childrenValues)\n {\n childSetter(child, item);\n }\n\n yield return item;\n }\n</code></pre>\n\n<hr>\n\n<p><strong>But the overall problem with your algorithm is this:</strong></p>\n\n<blockquote>\n<pre><code> foreach (var item in items.Where(item => parentKeyProperty(item).Equals(parentKeyValue)))\n {\n ...\n</code></pre>\n</blockquote>\n\n<p>Here you requery the entire collection for every item in the collection to find possible child elements to the argument parent and that is too expensive. </p>\n\n<p>If you know that the elements in the data set are given in hierarchical order, the most optimized solution would be to go along with <a href=\"https://codereview.stackexchange.com/questions/138524/recreating-a-tree-from-a-flat-collection-or-unflatten-a-tree#138532\">Nikita B</a>'s answer in the link suggested by t3chb0t.</p>\n\n<p>If not, you could go along the below path:</p>\n\n<pre><code>public delegate void ParentSetter<T>(T child, T parent);\npublic delegate void ChildSetter<T>(T child, T parent);\n\npublic static IEnumerable<T> AsHierarchy<T, TID>(\n this IEnumerable<T> elements,\n Func<T, TID> idSelector,\n Func<T, TID> parentIdSelector,\n ParentSetter<T> parentSetter,\n ChildSetter<T> childAdder,\n TID rootId)\n{\n Dictionary<TID, T> lookUp = elements.ToDictionary(e => idSelector(e));\n\n foreach (T element in lookUp.Values)\n {\n TID parentId = parentIdSelector(element);\n if (!lookUp.TryGetValue(parentId, out T parent))\n {\n if (parentId.Equals(rootId))\n {\n yield return element;\n continue;\n }\n else\n throw new InvalidOperationException($\"Parent not found for: {element}\");\n }\n\n parentSetter(element, parent);\n childAdder(element, parent);\n }\n}\n</code></pre>\n\n<p>Here a dictionary is created as a look up table for the parent of each element. To create a dictionary is a remarkable inexpensive operation. </p>\n\n<p>When an elements parent is not found it is checked if the parent id is the root id. If true the element is returned otherwise an exception is thrown.</p>\n\n<p>A pair of explicit delegates for setting the parent and child are provided in order to show which argument is supposed to be the child and which the parent.</p>\n\n<hr>\n\n<p><strong>EDIT</strong></p>\n\n<p>You can then call the method like:</p>\n\n<pre><code> Category[] categories = new Category[1000]; // TODO: Convert from DTO-object\n IEnumerable<Category> tree = categories.AsHierarchy(\n c => c.CategoryId, \n c => c.CategoryParentId, \n (child, parent) => child.ParentCategory = parent, \n (child, parent) => parent.ChildCategories.Add(child), 0);\n</code></pre>\n\n<p>Here the last <code>0</code> is the supposed rootId.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-10T20:21:03.003",
"Id": "408556",
"Score": "0",
"body": "Presently, I feel more secure to use the one that doesn't require that the data is in order. But how do you use the ParentSetter and ChildSetter? When i call the function, I don't know what to pass for these params."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-11T06:17:55.850",
"Id": "408601",
"Score": "0",
"body": "@AlexandreJobin: Please see my update..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-11T16:50:38.163",
"Id": "408668",
"Score": "0",
"body": "What is the advantage to use delegates for the parent/child setters vs using a Func<TEntity, TEntity>? Instead of declaring how to set the parent and child, you just have to tell who is the parent and who is the child property."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-14T21:01:35.927",
"Id": "408976",
"Score": "0",
"body": "I've put an updated version of your code in my description to accept more than one root element."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T07:02:25.577",
"Id": "409004",
"Score": "0",
"body": "@AlexandreJobin: OK, you can do it like that, but it will limit the use to having a parent id as reference or nullable type. Another way would be to inject a delegate, that can determine whether a parent id is the root id or not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T07:04:42.177",
"Id": "409005",
"Score": "0",
"body": "@AlexandreJobin: delegates vs Func<TEntity, TEntity>: The only advantage is, that I can name the parameters to state which is which, instead of having to explain it in comments"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T15:14:04.040",
"Id": "409050",
"Score": "0",
"body": "What do you mean that it will limit the use to have a parentId or a nullable. I thought that by doing it my way, it is less limiting that your version :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T15:15:26.063",
"Id": "409052",
"Score": "0",
"body": "About the delegates, that is true that you can easly name the parameters \"parent\" and \"child\" but you have to know in which order to declare them. Is there any trick so you can easly tell the developer how to declare them in what order? How do people know that you have to use `(child, parent) => ...` instead of `(parent, child) => ...`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-15T18:40:06.693",
"Id": "409080",
"Score": "0",
"body": "@AlexandreJobin: Nullable id: Because you do the check `if (parentId == null)`. This has no meaning if `parentId` is of type `int` or any other value type. Delegates: The names of the arguments in my delegates tell which order (child, parent) they are expected to be."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-22T20:28:39.670",
"Id": "409968",
"Score": "0",
"body": "with delegates, I don't see in the VS intellisense the description that tell me that the first param is the child and the second one is the parent. Do I miss something? I only see `ParentSetter<abc> parentSetter`."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T04:55:24.583",
"Id": "210154",
"ParentId": "210076",
"Score": "3"
}
},
{
"body": "<p>It seems to me that since you have all these Funcs for getting/setting parents/children and their identifiers, any class you want to use this on basically has to be \"ready\" to be a heirarchy item and already have a notion of parents/children etc.</p>\n\n<p>Because of this I'd create a interface to indicate how the heirarchy items relate to each other. Something like:</p>\n\n<pre><code>public interface IHeirarchyItem<TKey, TItem> where TItem : IComparable<T> {\n TKey HeirarchyKey {get;}\n TKey ParentKey {get;}\n}\n</code></pre>\n\n<p>And a interface for a heirarchy \"node\":</p>\n\n<pre><code>public interface IHeirarchyNode<TKey, TItem> where TItem : IHeirarchyItem {\n void AddChild(TItem child);\n TItem Parent {get; set; }\n}\n</code></pre>\n\n<p>Category and CategoryDTO can implement these interfaces through existing methods (it is my understanding that those classes are generated by you). Such an implementation would be something like:</p>\n\n<pre><code>public class CategoryDto : IHeirarchyItem<int, CategoryDTO>\n{\n public CategoryDto()\n {\n this.ChildCategories = new HashSet<CategoryDto>();\n }\n\n public int HeirarchyKey { get { return CategoryId;}}\n public int? ParentKey { get { return CategoryParentId ;}}\n\n public int CategoryId { get; set; } \n public string Name { get; set; } \n public int? CategoryParentId { get; set; } \n public CategoryDto ParentCategory { get; set; } \n public IEnumerable<CategoryDto> ChildCategories { get; set; }\n}\n</code></pre>\n\n<p>Or alternatively:</p>\n\n<pre><code>public class CategoryDto : IHeirarchyItem<int, CategoryDto>, IHeirarchyNode<int, CategoryDto>, IComparable<CategoryDto>\n{\n public CategoryDto()\n {\n this.ChildCategories = new HashSet<CategoryDto>();\n }\n\n public int HeirarchyKey { get { return CategoryId;}}\n public int? ParentKey { get { return CategoryParentId ;}}\n\n public void AddChild(CategoryDto child) => ChildCategories.Append(child); //not efficient at all! Just an example\n\n public CategoryDto Parent {\n get => ParentCategory; \n set => ParentCategory= value;\n }\n\n public int CategoryId { get; set; } \n public string Name { get; set; } \n public int? CategoryParentId { get; set; } \n public CategoryDto ParentCategory { get; set; } \n public IEnumerable<CategoryDto> ChildCategories { get; set; }\n\n public int CompareTo (T other) {//do comparison}; \n}\n</code></pre>\n\n<p>You can also have a concrete HeirarchyNode : IHeirarchyNode where TItem : IHeirarchyItem {...} which has an actual list of children and a reference to a parent e.g. </p>\n\n<pre><code>public class HeirarchyNode<TKey, TItem> : IHeirarchyNode<int, TItem> where TKey : struct where TItem : IHeirarchyItem<int, TItem>, IComparable<TItem> {\n public List<TItem> Children {get;set;}\n public TItem Parent {get;set;}\n\n public void AddChild(TItem child) => Children.Add(child);\n }\n</code></pre>\n\n<p>Your code for setting up the heirarchy can then work off these interfaces.</p>\n\n<p>The benefit of this approach is that the Category objects always have control of how they fit into a heirarchy with each other and AsHierarchy() method can have a shorter, more readable signature.</p>\n\n<p>If you cannot or do not want to have classes implementing these heirarchy interfaces directly, you could have a implementation of IHeirarchyItem which takes in Func(s) for getting the keys etc. I recommend you do this using some kind of factory so that you can ensure that the way a IHeirarchyItem for a given type works will be consistent in all cases.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-10T20:34:33.837",
"Id": "408561",
"Score": "0",
"body": "Can you tell me how it will look like when you use the interface in the class? It's like if you will have 2 properties for the key and 2 properties for the parentKey: CategoryId, HierarchyKey, ParentCategoryId, ParentKey. Am I right?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-05T20:42:46.710",
"Id": "210946",
"ParentId": "210076",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "210154",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T21:27:12.587",
"Id": "210076",
"Score": "5",
"Tags": [
"c#",
".net",
"extension-methods"
],
"Title": "Generic extension to transform a flat nested list to hierarchy list"
} | 210076 |
<h1>Background</h1>
<p>I am since a long time ago developing a JavaFX application for <a href="http://li-soft.org" rel="nofollow noreferrer">creating and analysing</a> 'Mech loadouts for <a href="https://mwomercs.com/" rel="nofollow noreferrer">Mechwarrior Online</a>. </p>
<p>I previously had a very crude search function based on a FilteredList and <a href="https://github.com/EmilyBjoerk/lsml/blob/480d096ac8b5f5149db02679d44bf996ea1b3196/src/main/java/org/lisoft/lsml/view_fx/util/SearchFilter.java" rel="nofollow noreferrer">a big and complicated predicate</a>. This proved to have many drawbacks, prefix hits were a pain to do and this made searching hard as you had to correctly spell long strings which weren't always obvious.</p>
<p>I have replaced the above implementation with an actual search index based on the <a href="https://en.wikipedia.org/wiki/Inverted_index" rel="nofollow noreferrer">Inverted Index</a> approach. </p>
<p>As this is production code that depends on the core data structures of my application, I cannot give an easily runnable example. But if you want, you can fetch the <a href="https://github.com/EmilyBjoerk/lsml" rel="nofollow noreferrer">source tree from github</a> and run the tests with <code>./gradlew test</code> and if you want, you can run the application with <code>./gradlew run</code>, if you're using Windows cmd.exe, then change <code>./gradlew</code> to <code>gradlew.bat</code>.</p>
<p>One comment on <code>update()</code>: I made a decision to simply rebuild the index if any of the documents got updated, I found it to be very hard to find which entries in the index matched to to the updated document as the old terms were not available any more to compare to (pointed to document had changed).</p>
<p>I store the full keyword (phrase?) because in the future I intend to support <code>"match all words in this order in one attribute"</code> syntax.</p>
<h1>Source</h1>
<p>Here is the implementation (<a href="https://github.com/EmilyBjoerk/lsml/blob/develop/src/main/java/org/lisoft/lsml/model/search/SearchIndex.java" rel="nofollow noreferrer">github</a>):</p>
<pre><code>/*
* @formatter:off
* Li Song Mechlab - A 'mech building tool for PGI's MechWarrior: Online.
* Copyright (C) 2013 Emily Bjรถrk
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//@formatter:on
package org.lisoft.lsml.model.search;
import java.util.*;
import org.lisoft.lsml.model.chassi.Chassis;
import org.lisoft.lsml.model.item.Faction;
import org.lisoft.lsml.model.loadout.Loadout;
import org.lisoft.lsml.model.modifiers.Modifier;
/**
* A search index that can be used for finding loadouts based on keywords
*
* @author Emily Bjรถrk
*/
public class SearchIndex {
private final static String ALL_DOCUMENTS = "";
private boolean dirty = false;
private final Map<String, Set<Loadout>> invertedIndex = new HashMap<>();
private void addPrefixes(Loadout aLoadout, String aKeyword) {
if (null == aKeyword) {
// These keywords will never be null in production but makes
// setting up tests much easier.
return;
}
if (aKeyword.contains(" ")) {
for (final String part : aKeyword.split(" ")) {
addPrefixes(aLoadout, part);
}
}
String prefix = aKeyword.toLowerCase();
while (!prefix.isEmpty()) {
final Set<Loadout> documents = documentsByKey(prefix);
documents.add(aLoadout);
prefix = prefix.substring(0, prefix.length() - 1);
}
}
private Set<Loadout> documentsByKey(String aKeyword) {
return invertedIndex.computeIfAbsent(aKeyword, k -> new HashSet<>());
}
/**
* Merges the given loadout into the search index.
*
* @param aLoadout
* A loadout to merge
*/
public void merge(Loadout aLoadout) {
documentsByKey(ALL_DOCUMENTS).add(aLoadout);
addPrefixes(aLoadout, aLoadout.getName());
final Chassis chassis = aLoadout.getChassis();
addPrefixes(aLoadout, chassis.getSeriesName());
addPrefixes(aLoadout, chassis.getShortName());
addPrefixes(aLoadout, chassis.getName());
addPrefixes(aLoadout, Integer.toString(chassis.getMassMax()) + "ton");
addPrefixes(aLoadout, Integer.toString(chassis.getMassMax()) + " ton");
final Faction faction = chassis.getFaction();
addPrefixes(aLoadout, faction.getUiName());
addPrefixes(aLoadout, faction.getUiShortName());
for (final Modifier modifier : aLoadout.getAllModifiers()) {
addPrefixes(aLoadout, modifier.getDescription().getUiName());
}
}
/**
* Queries the index for a search string. It will match substrings of the indexed document and it will be case
* insensitive.
*
* @param aSearchString
* @return A {@link Collection} of {@link Loadout}s.
*/
public Collection<Loadout> query(String aSearchString) {
if (dirty) {
rebuild();
}
final List<Set<Loadout>> hits = new ArrayList<>();
for (final String part : aSearchString.toLowerCase().split(" ")) {
hits.add(invertedIndex.getOrDefault(part, Collections.EMPTY_SET));
}
hits.sort((l, r) -> l.size() - r.size());
final Iterator<Set<Loadout>> it = hits.iterator();
final Set<Loadout> ans = new HashSet<>(it.next());
while (it.hasNext()) {
ans.retainAll(it.next());
}
return ans;
}
/**
* Rebuilds the search index to take updated documents changes into the index.
*/
public void rebuild() {
final Set<Loadout> documents = documentsByKey(ALL_DOCUMENTS);
invertedIndex.clear();
for (final Loadout document : documents) {
merge(document);
}
dirty = false;
}
/**
* Removes the given loadout from the search index.
*
* An index rebuild is automatically performed on the next query if it has not been forced before the query.
*
* @param aLoadout
* The {@link Loadout} to remove from the index.
*/
public void unmerge(Loadout aLoadout) {
documentsByKey(ALL_DOCUMENTS).remove(aLoadout);
dirty = true;
}
/**
* Call when a document has been changed. Will cause a reindexing of all documents on the next query.
*/
public void update() {
dirty = true;
}
}
</code></pre>
<p>Here are the unit tests (<a href="https://github.com/EmilyBjoerk/lsml/blob/develop/src/test/java/org/lisoft/lsml/model/search/SearchIndexTest.java" rel="nofollow noreferrer">github</a>):</p>
<pre><code>/*
* @formatter:off
* Li Song Mechlab - A 'mech building tool for PGI's MechWarrior: Online.
* Copyright (C) 2013 Emily Bjรถrk
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//@formatter:on
package org.lisoft.lsml.model.search;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import java.util.*;
import org.junit.Test;
import org.lisoft.lsml.model.chassi.Chassis;
import org.lisoft.lsml.model.item.Faction;
import org.lisoft.lsml.model.loadout.Loadout;
import org.lisoft.lsml.model.modifiers.*;
/**
* Unit tests for {@link SearchIndex}.
*
* @author Emily Bjรถrk
*/
public class SearchIndexTest {
private final SearchIndex cut = new SearchIndex();
private final List<Modifier> modifiers = new ArrayList<>();
private Loadout makeLoadout() {
return makeLoadout(Faction.CLAN);
}
private Loadout makeLoadout(Faction aFaction) {
final Loadout l = mock(Loadout.class);
final Chassis c = mock(Chassis.class);
when(l.getChassis()).thenReturn(c);
when(l.getAllModifiers()).thenReturn(modifiers);
when(c.getFaction()).thenReturn(aFaction);
return l;
}
@Test
public void testModifiers() {
final ModifierDescription description = mock(ModifierDescription.class);
final Modifier modifier = mock(Modifier.class);
modifiers.add(modifier);
when(modifier.getDescription()).thenReturn(description);
when(description.getUiName()).thenReturn("ENERGY HEAT 5%");
final Loadout l = makeLoadout();
cut.merge(l);
final Collection<Loadout> ans = cut.query("ENERGY HEAT");
assertTrue(ans.contains(l));
assertEquals(1, ans.size());
}
@Test
public void testQueryAND() {
final Loadout l1 = makeLoadout();
when(l1.getName()).thenReturn("def abc");
cut.merge(l1);
final Loadout l2 = makeLoadout();
when(l2.getName()).thenReturn("ghi abc");
cut.merge(l2);
final Collection<Loadout> ans = cut.query("abc ghi");
assertFalse(ans.contains(l1));
assertTrue(ans.contains(l2));
}
@Test
public void testQueryByChassisMass() {
final Loadout l = makeLoadout();
when(l.getChassis().getMassMax()).thenReturn(95);
cut.merge(l);
final Collection<Loadout> ans = cut.query("95ton");
assertTrue(ans.contains(l));
assertEquals(1, ans.size());
}
@Test
public void testQueryByChassisMassSpace() {
final Loadout l = makeLoadout();
when(l.getChassis().getMassMax()).thenReturn(95);
cut.merge(l);
final Collection<Loadout> ans = cut.query("95 ton");
assertTrue(ans.contains(l));
assertEquals(1, ans.size());
}
@Test
public void testQueryByChassisName() {
final Loadout l = makeLoadout();
when(l.getChassis().getName()).thenReturn("ILYA MUROMETS");
cut.merge(l);
final Collection<Loadout> ans = cut.query("ILYA MUROMETS");
assertTrue(ans.contains(l));
assertEquals(1, ans.size());
}
@Test
public void testQueryByChassisSeries() {
final Loadout l = makeLoadout();
when(l.getChassis().getSeriesName()).thenReturn("SERIES");
cut.merge(l);
final Collection<Loadout> ans = cut.query("SERIES");
assertTrue(ans.contains(l));
assertEquals(1, ans.size());
}
@Test
public void testQueryByChassisShort() {
final Loadout l = makeLoadout();
when(l.getChassis().getShortName()).thenReturn("CPLT-K2");
cut.merge(l);
final Collection<Loadout> ans = cut.query("CPLT-K2");
assertTrue(ans.contains(l));
assertEquals(1, ans.size());
}
@Test
public void testQueryByFaction() {
final Loadout l = makeLoadout(Faction.CLAN);
cut.merge(l);
final Collection<Loadout> ans = cut.query(Faction.CLAN.getUiName());
assertTrue(ans.contains(l));
assertEquals(1, ans.size());
}
@Test
public void testQueryByFactionShort() {
final Loadout l = makeLoadout(Faction.INNERSPHERE);
cut.merge(l);
final Collection<Loadout> ans = cut.query(Faction.INNERSPHERE.getUiShortName());
assertTrue(ans.contains(l));
assertEquals(1, ans.size());
}
@Test
public void testQueryByName() {
final Loadout l = makeLoadout();
when(l.getName()).thenReturn("arbitrary string");
cut.merge(l);
final Collection<Loadout> ans = cut.query("arbitrary string");
assertTrue(ans.contains(l));
assertEquals(1, ans.size());
}
@Test
public void testQueryByNameCaseInsensitive() {
final Loadout l = makeLoadout();
when(l.getName()).thenReturn("abc");
cut.merge(l);
final Collection<Loadout> ans = cut.query("AB");
assertTrue(ans.contains(l));
}
@Test
public void testQueryByNamePrefix() {
final Loadout l = makeLoadout();
when(l.getName()).thenReturn("abc");
cut.merge(l);
final Collection<Loadout> ans2 = cut.query("ab");
assertTrue(ans2.contains(l));
final Collection<Loadout> ans1 = cut.query("a");
assertTrue(ans1.contains(l));
final Collection<Loadout> ans0 = cut.query("");
assertTrue(ans0.contains(l));
}
@Test
public void testQueryMultipleHits() {
final Loadout l1 = makeLoadout();
when(l1.getName()).thenReturn("def abc");
cut.merge(l1);
final Loadout l2 = makeLoadout();
when(l2.getName()).thenReturn("ghi abc");
cut.merge(l2);
final Collection<Loadout> ans = cut.query("abc");
assertTrue(ans.contains(l1));
assertTrue(ans.contains(l2));
}
/**
* A bug caused the index to be modified on queries because the smallest document set for any keyword was used
* directly without a copy when computing the intersection of all the document sets for the keywords.
*/
@Test
public void testQueryNoModifyIndex() {
final Loadout l1 = makeLoadout();
when(l1.getName()).thenReturn("x b");
cut.merge(l1);
final Loadout l2 = makeLoadout();
when(l2.getName()).thenReturn("x y");
cut.merge(l2);
final Loadout l3 = makeLoadout();
when(l3.getName()).thenReturn("a y");
cut.merge(l3);
cut.query("x y");
cut.query("x b");
cut.query("a y");
assertEquals(2, cut.query("x").size());
assertEquals(2, cut.query("y").size());
assertEquals(1, cut.query("a").size());
assertEquals(1, cut.query("b").size());
}
@Test
public void testRebuildEmpty() {
cut.rebuild();
final Collection<Loadout> ans = cut.query("");
assertTrue(ans.isEmpty());
}
@Test
public void testUnmerge() {
final Loadout l1 = makeLoadout();
when(l1.getName()).thenReturn("def abc");
cut.merge(l1);
final Loadout l2 = makeLoadout();
when(l2.getName()).thenReturn("ghi abc");
cut.merge(l2);
cut.unmerge(l2);
final Collection<Loadout> ans = cut.query("abc ghi");
assertTrue(ans.isEmpty());
}
@Test
public void testUnmergeEmptyIndex() {
final Loadout l2 = makeLoadout();
when(l2.getName()).thenReturn("abc");
cut.unmerge(l2);
final Collection<Loadout> ans = cut.query("abc");
assertTrue(ans.isEmpty());
}
@Test
public void testUpdate() {
final Loadout l = makeLoadout();
when(l.getName()).thenReturn("nope").thenReturn("hello");
cut.merge(l);
cut.update();
assertFalse(cut.query("nope").contains(l));
assertTrue(cut.query("hello").contains(l));
}
}
</code></pre>
| [] | [
{
"body": "<h2>Production code</h2>\n\n<ol>\n<li><p>In <code>addPrefixes</code>, my suggestions would be:</p>\n\n<ul>\n<li><p>To split into smaller private sub-methods with hierarchy:</p>\n\n<pre><code>addPrefixes -> //performs split by \" \"\n addPrefixesOfWord -> //divides word into prefixes\n addParticularKeyword //adds particular prefix\n</code></pre></li>\n</ul>\n\n<p>Also I was wondering why your program continues execution even after: <br>\n<code>if (aKeyword.contains(\" \")) {</code><br>\nbefore reading your explanation<br>\nIt could be more clear if you just stated: <code>addPrefixesOfWord(longKeyword)</code> explicitely.</p>\n\n<ul>\n<li>To replace <code>while</code> loop with <code>for</code></li>\n</ul></li>\n</ol>\n\n<p></p>\n\n<ol start=\"2\">\n<li><p>I have noticed that lot of people use some good practice along with <a href=\"https://en.wikipedia.org/wiki/Command%E2%80%93query_separation\" rel=\"nofollow noreferrer\">C&QSP (or CQRS)</a>. They simply return immutable objects from their query methods (I mean <code>documentsByKey</code> in your particular case).</p>\n\n<p>In your code, to add new value into <code>invertedIndex</code>, you queried <code>documentsByKey</code> method and modified its result, which is a breach of this practice.</p>\n\n<p>To introduce it in my own project, I hid <code>Map<String, Set<Loadout>></code> equivalent behind separate interface/class with two methods:</p>\n\n<ul>\n<li>To associate new document with particular string keyword. (If you decide to apply my previous suggestions, the <code>addParticularKeyword</code> method would be just moved into that class.)</li>\n<li>To get all documents associated with particular keyword.</li>\n</ul></li>\n<li><p>From the <code>query</code> method it is possible to extract two smaller private sub-methods:</p>\n\n<ul>\n<li>Getting <code>set</code> of results for each keyword.</li>\n<li>Finding common subset of all previously gathered sets.</li>\n</ul></li>\n<li><p>I'm wondering what is the reason of <code>sort</code> inside <code>query</code>. If it is a performance adjustment, I guess that simply choosing <code>Set<Loadout> ans</code> to be the smallest set will be even a little bit faster.</p></li>\n</ol>\n\n<h2>Unit tests</h2>\n\n<ol>\n<li><p>I might be wrong, but I believe that tests like: <code>testQueryAND</code> or <code>testQueryByNamePrefix</code> or <code>testQueryNoModifyIndex</code> in particular could be divided into smaller independent test cases.</p></li>\n<li><p>You can split your suite into smaller classes in the same package anyway to maintain some hierarchy. My proposition would be:</p>\n\n<ul>\n<li>Simple tests that provide some loadout seeded with custom data and test if are able to be found by query. (I suppose that in reality they test <code>merge</code> method)</li>\n<li>More complex test cases which test scenarios, what happens when an entry is overwritten by another etc.</li>\n</ul></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T17:49:10.537",
"Id": "406136",
"Score": "0",
"body": "Can you clarify your second point? I haven't heard the acronym C&QSP before and a Google search doesn't really tell me what it is. The sort of a performance optimization the number of search terms is expected low so the sort is cheap."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T17:58:13.127",
"Id": "406137",
"Score": "0",
"body": "@EmilyL. Added reference to wiki. It is even more broadly known as CQRS -sorry for that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T18:33:00.853",
"Id": "406144",
"Score": "0",
"body": "Also here it is more easily and broadly explained: https://dzone.com/articles/cqrs-understanding-from-first-principles"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T19:09:48.907",
"Id": "406154",
"Score": "1",
"body": "Oh so it's basically interface segregation based on if the method mutates state or not. I do something similar to this for my domain model using the command pattern. I don't think it makes sense in this case as it's application would likely introduce more problems than it solves. The class as it is is fairly straight forward and doesn't mutate any global state and all methods have well defined and expected side effects."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T23:02:53.930",
"Id": "406186",
"Score": "0",
"body": "To clarify, I didn't mean to apply this pattern to whole class. As I see, your `query` method lazy-rebuilds index. For that reason, Command/Query segregation can be troublesome. Instead, I meant to introduce this pattern for index data structure as it would apply better!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T10:57:25.573",
"Id": "210112",
"ParentId": "210083",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "210112",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-20T23:33:56.107",
"Id": "210083",
"Score": "4",
"Tags": [
"java",
"search"
],
"Title": "Search indexing of Battle Mech Loadouts"
} | 210083 |
<p>The <a href="https://en.wikipedia.org/wiki/Set_(card_game)" rel="nofollow noreferrer">game of Set</a> involves cards with four properties: number, symbol, shading, and colour. </p>
<p>Three cards make a "Set" if the property is either all the same or all different across the three cards, for each of the four properties.</p>
<p>I wrote some code to verify if three cards constitute a "Set". But I'm not satisfied with the final function <code>isSet</code>. I feel there should be some way to iterate over the four properties instead of writing four separate lines. Any help would be appreciated - I'm fairly new to F#.</p>
<pre><code>type Number = | One | Two | Three
type Symbol = | Round | Wavy | Diamond
type Shading = | Empty | Lines | Full
type Colour = | Red | Green | Blue
type Card = {number: Number;
symbol: Symbol;
shading: Shading;
colour: Colour}
let all =
List.reduce (=)
let numUnique list =
list
|> List.distinct
|> List.length
let allSame list =
list
|> numUnique
|> (=) 1
let allUnique list =
let length = List.length list
list
|> numUnique
|> (=) length
let allSameOrUnique list =
allSame list || allUnique list
let isSet card1 card2 card3 =
let check1 = allSameOrUnique [card1.number; card2.number; card3.number]
let check2 = allSameOrUnique [card1.symbol; card2.symbol; card3.symbol]
let check3 = allSameOrUnique [card1.shading; card2.shading; card3.shading]
let check4 = allSameOrUnique [card1.colour; card2.colour; card3.colour]
all [check1; check2; check3; check3; check4]
let card1 = {number = Two; symbol = Round; shading = Lines; colour = Green}
let card2 = {number = One; symbol = Round; shading = Empty; colour = Green}
let card3 = {number = Three; symbol = Round; shading = Full; colour = Green}
</code></pre>
<p>The final function returns a boolean for verifying the set:</p>
<pre><code>> isSet card1 card2 card3
val it : bool = true
</code></pre>
| [] | [
{
"body": "<blockquote>\n <p>I feel there should be some way to iterate over the four properties instead of writing four separate lines.</p>\n</blockquote>\n\n<p>You can use a higher-order function that takes in a function that returns a card property. Here is an example of how that could look. I've also simplified the code to the extent that none of the helper functions are needed, and changed some formatting to more idiomatic F#:</p>\n\n<pre><code>type Number = One | Two | Three\ntype Symbol = Round | Wavy | Diamond\ntype Shading = Empty | Lines | Full\ntype Colour = Red | Green | Blue\n\ntype Card =\n { Number: Number\n Symbol: Symbol\n Shading: Shading\n Colour: Colour}\n\nlet isSet card1 card2 card3 =\n let sameOrUniqueBy prop =\n let unique = [ card1; card2; card3 ] |> List.distinctBy prop |> List.length\n unique = 1 || unique = 3\n\n sameOrUniqueBy (fun c -> c.Number)\n && sameOrUniqueBy (fun c -> c.Symbol)\n && sameOrUniqueBy (fun c -> c.Shading)\n && sameOrUniqueBy (fun c -> c.Colour)\n</code></pre>\n\n<p>In this code, <code>sameOrUniqueBy</code> is a higher-order function because it takes a function as an argument. It is defined as a local function inside <code>isSet</code> so that the cards don't have to be passed in each time it's used.</p>\n\n<p>Testing:</p>\n\n<pre><code>let card1 = { Number = Two; Symbol = Round; Shading = Lines; Colour = Green }\nlet card2 = { Number = One; Symbol = Round; Shading = Empty; Colour = Green }\nlet card3 = { Number = Three; Symbol = Round; Shading = Full; Colour = Green }\n\nisSet card1 card2 card3 = true // โ\n\nisSet card1 card1 card3 = false // โ\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T11:44:06.390",
"Id": "210115",
"ParentId": "210087",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "210115",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T01:11:01.543",
"Id": "210087",
"Score": "6",
"Tags": [
"beginner",
"f#",
"playing-cards"
],
"Title": "Verifying that three cards make a \"Set\""
} | 210087 |
<p>This is my first pygame project that I've worked on and wanted to start with something simple. Pong was, I think, a pretty good choice now that I'm done with it. I will continue to make improvements to the game and adjustments, but I would like the community to review and give suggestions for improvements. I'm a hobbyist and know next to nothing about computer science.</p>
<p>The improvements I had in mind for the next version would be changing the angle of the ball based on where on the paddle the ball hits and adding sound. I'm also going to work on a simple AI for single player.</p>
<p>I'm looking to see if my code is structured in a way that is not normal or is just bad by design. I'm interested to hear about using this style of coding for larger games and how it scales as the game gets bigger. Let me know what you think. </p>
<pre><code>import pygame
import math
pygame.init()
screensize1 = 1500
screensize2 = 1000
win = pygame.display.set_mode((screensize1, screensize2))
pygame.display.set_caption('Test Environment')
class Player(object):
def __init__(self, color, x, y, width, height, score):
self.color = color
self.x = x
self.y = y
self.width = width
self.height = height
self.vel = 20
self.score = score
self.up = False
self.down = False
class Projectile(object):
def __init__(self, x, y, angle):
self.x = x
self.y = y
self.radius = 6
self.color = (255, 255, 255)
self.angle = angle
self.vel = 20
self.xvel = int(round((math.sin(math.radians(self.angle)) * self.vel), 0))
self.yvel = int(round((math.cos(math.radians(self.angle)) * self.vel), 0))
def redraw_game_window():
global Char2Win, Char1Win, s1_WaitToStart
win.fill((0, 0, 0))
pygame.draw.line(win, (255, 0, 0), (screensize1//2, 0), (screensize1//2, screensize2), 4)
if s1_WaitToStart is True:
win.blit(pygame.font.SysFont('None', 50).render('Press Space To Start', 0, (255, 255, 255)), ((screensize1//2)-180, ((screensize2//2)-25)))
if Char1Win is True:
win.blit(pygame.font.SysFont('None', 50).render('Player 1 Wins', 0, (255, 255, 255)), ((screensize1//4)-160, ((screensize2//2)-25)))
win.blit(pygame.font.SysFont('None', 50).render('Press Space To Start New Game', 0, (255, 255, 255)), ((screensize1//2)-200, ((screensize2//4 + screensize2//2)-25)))
if Char2Win is True:
win.blit(pygame.font.SysFont('None', 50).render('Player 2 Wins', 0, (255, 255, 255)), ((screensize1//4 + screensize1//2)-160, ((screensize2//2)-25)))
win.blit(pygame.font.SysFont('None', 50).render('Press Space To Start New Game', 0, (255, 255, 255)), ((screensize1//2)-200, ((screensize2//4 + screensize2//2)-25)))
win.blit(pygame.font.SysFont('None', 100).render(str(char1.score) + ' ' + str(char2.score), 0, (255, 255, 255)), ((screensize1//2)-85, 20))
pygame.draw.rect(win, char1.color, (char1.x, char1.y, char1.width, char1.height))
pygame.draw.rect(win, char2.color, (char2.x, char2.y, char2.width, char2.height))
pygame.draw.circle(win, ball.color, (ball.x, ball.y), ball.radius)
pygame.display.update()
char1 = Player((255, 0, 0), 25, (screensize2//2) - 90, 25, 160, 0)
char2 = Player((255, 0, 0), screensize1 - 50, (screensize2//2) - 90, 25, 160, 0)
ball = Projectile((screensize1//8) + (screensize1//4), screensize2//4, 315)
s1_WaitToStart = True
s2_BallAtPlayerOne = False
s3_PlayerTwoScore = False
s4_PlayerOneHit = False
s5_HitsWall = False
s6_BallAtPlayerTwo = False
s7_PlayerOneScore = False
s8_PlayerTwoHit = False
Char1Win = False
Char2Win = False
laststate = ''
run = True
while run:
pygame.time.delay(30)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_w] and char1.y > char1.vel:
char1.y -= char1.vel
if keys[pygame.K_s] and char1.y < screensize2 - char1.height - char1.vel:
char1.y += char1.vel
if keys[pygame.K_UP] and char2.y > char2.vel:
char2.y -= char2.vel
if keys[pygame.K_DOWN] and char2.y < screensize2 - char2.height - char2.vel:
char2.y += char2.vel
# STATES OF GAME PLAY *************************************************************************************************
if s1_WaitToStart is True:
ball.x = (screensize1//8) + (screensize1//4)
ball.y = screensize2//4
if keys[pygame.K_SPACE]:
s2_BallAtPlayerOne = True
s1_WaitToStart = False
if s1_WaitToStart is False and s7_PlayerOneScore is False and s3_PlayerTwoScore is False and s4_PlayerOneHit is False and s8_PlayerTwoHit is False and s5_HitsWall is False:
ball.x += ball.xvel
ball.y += ball.yvel
if s2_BallAtPlayerOne is True:
ball.xvel = int(round((math.sin(math.radians(ball.angle)) * ball.vel), 0))
ball.yvel = int(round((math.cos(math.radians(ball.angle)) * ball.vel), 0))
if ball.x <= char1.x + char1.width:
if char1.y - (2 * ball.radius) < ball.y or ball.y < char1.y + char1.height:
s4_PlayerOneHit = True
s2_BallAtPlayerOne = False
if ball.x < char1.x + char1.width + ball.radius:
if char1.y + char1.height + ball.radius <= ball.y or ball.y <= char1.y - ball.radius:
s3_PlayerTwoScore = True
s2_BallAtPlayerOne = False
if ball.y >= screensize2 - (2 * ball.radius):
if laststate != 's5':
s5_HitsWall = True
s2_BallAtPlayerOne = False
if ball.y <= 0 + (2 * ball.radius):
if laststate != 's5':
s5_HitsWall = True
s2_BallAtPlayerOne = False
laststate = 's2'
if s3_PlayerTwoScore is True:
char2.score += 1
if char2.score == 4:
Char2Win = True
s3_PlayerTwoScore = False
ball.x = (screensize1 // 8) + (screensize1 // 2)
ball.y = screensize2 // 4
ball.angle = 315
s2_BallAtPlayerOne = True
s3_PlayerTwoScore = False
laststate = 's3'
if s4_PlayerOneHit is True:
ball.xvel = 0
ball.yvel = 0
if 0 < ball.angle > 270:
ball.angle -= 270
ball.x += ball.xvel
ball.y += ball.yvel
s6_BallAtPlayerTwo = True
s4_PlayerOneHit = False
elif 270 > ball.angle > 180:
ball.angle -= 90
ball.x += ball.xvel
ball.y += ball.yvel
s6_BallAtPlayerTwo = True
s4_PlayerOneHit = False
laststate = 's4'
if s5_HitsWall is True:
ball.xvel = 0
ball.yvel = 0
if ball.y < screensize2//2:
if 180 > ball.angle > 90:
ball.angle -= 90
s6_BallAtPlayerTwo = True
s5_HitsWall = False
else:
ball.angle += 90
s2_BallAtPlayerOne = True
s5_HitsWall = False
if ball.y > screensize2//2:
if 0 < ball.angle < 90:
ball.angle += 90
s6_BallAtPlayerTwo = True
s5_HitsWall = False
else:
ball.angle -= 90
s2_BallAtPlayerOne = True
s5_HitsWall = False
laststate = 's5'
if s6_BallAtPlayerTwo is True:
ball.xvel = int(round((math.sin(math.radians(ball.angle)) * ball.vel), 0))
ball.yvel = int(round((math.cos(math.radians(ball.angle)) * ball.vel), 0))
if ball.x >= char2.x - (2 * ball.radius):
if char2.y - (2 * ball.radius) < ball.y or ball.y < char2.y + char2.height + ball.y:
s8_PlayerTwoHit = True
s6_BallAtPlayerTwo = False
if ball.x > char2.x - (2 * ball.radius):
if char2.y + char2.height <= ball.y or ball.y <= char2.y - (2 * ball.radius):
s7_PlayerOneScore = True
s6_BallAtPlayerTwo = False
if ball.y >= screensize2 - (2 * ball.radius):
if laststate != 's5':
s5_HitsWall = True
s6_BallAtPlayerTwo = False
if ball.y <= 0 + (2 * ball.radius):
if laststate != 's5':
s5_HitsWall = True
s6_BallAtPlayerTwo = False
laststate = 's6'
if s7_PlayerOneScore is True:
char1.score += 1
if char1.score == 4:
Char1Win = True
s7_PlayerOneScore = False
ball.x = (screensize1 // 8) + (screensize1 // 4)
ball.y = screensize2 // 4
ball.angle = 45
s6_BallAtPlayerTwo = True
s7_PlayerOneScore = False
laststate = 's7'
if s8_PlayerTwoHit is True:
ball.xvel = 0
ball.yvel = 0
if 0 < ball.angle < 90:
ball.angle += 270
ball.x += ball.xvel
ball.y += ball.yvel
s2_BallAtPlayerOne = True
s8_PlayerTwoHit = False
elif 90 < ball.angle < 180:
ball.angle += 90
ball.x += ball.xvel
ball.y += ball.yvel
s2_BallAtPlayerOne = True
s8_PlayerTwoHit = False
laststate = 's8'
if Char2Win is True:
ball.xvel = 0
ball.yvel = 0
ball.x = (screensize1 // 8) + (screensize1 // 4)
ball.y = screensize2 // 4
if keys[pygame.K_SPACE]:
char2.score = 0
char1.score = 0
Char2Win = False
s1_WaitToStart = True
if Char1Win is True:
ball.xvel = 0
ball.yvel = 0
ball.x = (screensize1 // 8) + (screensize1 // 4)
ball.y = screensize2 // 4
if keys[pygame.K_SPACE]:
char2.score = 0
char1.score = 0
Char1Win = False
s1_WaitToStart = True
redraw_game_window()
pygame.quit()
</code></pre>
| [] | [
{
"body": "<p>This is a good start. Working from top to bottom here are some things I notice:</p>\n\n<ul>\n<li><p>Minimal imports is usually a good sign, just make sure you aren't doing unnecessary work because <a href=\"https://www.python.org/dev/peps/pep-0206/#batteries-included-philosophy\" rel=\"nofollow noreferrer\">Python is batteries included</a></p></li>\n<li><p>Classes are a good way to organize things, but I would suggest that you add some default values to your initializers, and potentially some verification that values are valid (e.g. can <code>x</code>/<code>y</code>/<code>radius</code> be negative, etc.)</p></li>\n<li><p><code>if s1_WaitToStart is True:</code> can just be <code>if s1_WaitToStart:</code> (this happens a lot in the code you provided)</p></li>\n<li><p>Global variables are (usually) bad. I would consider wrapping them in a <code>Config</code> or <code>State</code> object</p></li>\n<li><p>I would wrap the <code>while run:</code> block in a <a href=\"https://docs.python.org/3/library/__main__.html\" rel=\"nofollow noreferrer\">top-level environment</a></p></li>\n<li><p><code># STATES OF GAME PLAY *************************************************************************************************</code> oof</p></li>\n</ul>\n\n<p>At this point we've made it pretty far into your example and things are looking alright. But usually a long comment dividing up some code indicates that things are getting <a href=\"https://en.wikipedia.org/wiki/Code_smell\" rel=\"nofollow noreferrer\">smelly</a>. I would think about how you keep track of the game's state with its own object, and refactor your ball mechanics into reusable functions. Really just breaking up the game logic loop that you have would make this more digestible to the reader, and closer to what someone with software engineering experience would expect. Adding comments is (usually) a good thing as well. To help you think about what behavior lends itself to good code, ask yourself if the code you're writing would scale to 2, 5, 10, 100+ users, and if you would be able to jump back into the block you're in the middle of after a month without looking at it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T03:03:07.043",
"Id": "406064",
"Score": "0",
"body": "Oh nice. yeah the state objects idea could help a lot I think. https://stackoverflow.com/questions/19702168/python-define-a-state-object here is a different thread that talks about it a little bit. The `STATES OF GAMEPLAY COMMENT` was part of my working notes that I forgot to delete. I found myself scrolling back and forth a lot when working on the redraw function and just needed something to pop at my eye. I'll have to read up on top level environments. It's not something I know anything about. what would the benefit be?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T02:10:44.513",
"Id": "210091",
"ParentId": "210089",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "210091",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T01:50:54.147",
"Id": "210089",
"Score": "2",
"Tags": [
"python",
"pygame"
],
"Title": "First Pong game"
} | 210089 |
<p>I have made a small and simple tool for Windows using C++ and the Win32 API to allow people to change their resolution in <em>Fortnite</em>, without having to search for the configuration file and manually edit it themselves. The program has a width and height input for the user to enter their desired resolution, and an apply button to save the changes to the configuration file. I have tested it on a few machines, and it seems to work as expected.</p>
<p>This is my first attempt at using C++ or the Win32 API, and I would love to release this project to the <em>Fortnite</em> community, but I want ensure there are no glaring issues with it.</p>
<p><strong>My questions/concerns are:</strong></p>
<ol>
<li>Have I deleted the system resources correctly? Any potential memory leaks? (brushes, fonts, etc)</li>
<li>Do I need more error handling? Any improvements on what I do have?</li>
<li>Should I separate the <code>GetFortniteConfiguration()</code>, <code>SetFortniteConfiguration()</code> and <code>CenterWindow()</code> functions into their own file or is the project small enough to keep it as is?</li>
</ol>
<p>I will also be adding comments to the code shortly, but any other tips, suggestions or learning resources are welcome.</p>
<pre><code>#include <stdio.h>
#include <sys/stat.h>
#include <windows.h>
#include <string>
#include "resources.h"
#include "simpleini/simpleini.h"
LRESULT CALLBACK WindowProc(
HWND hwnd,
UINT message,
WPARAM wParam,
LPARAM lParam);
void CenterWindow(HWND window, DWORD style, DWORD exStyle) {
int screen_width = GetSystemMetrics(SM_CXSCREEN);
int screen_height = GetSystemMetrics(SM_CYSCREEN);
RECT client_rect;
GetClientRect(window, &client_rect);
AdjustWindowRectEx(&client_rect, style, FALSE, exStyle);
int client_width = client_rect.right - client_rect.left;
int client_height = client_rect.bottom - client_rect.top;
SetWindowPos(window, NULL,
screen_width / 2 - client_width / 2,
screen_height / 2 - client_height / 2,
client_width, client_height, 0);
}
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR pCmdLine, int nCmdShow) {
const wchar_t CLASS_NAME[] = L"alphares";
const wchar_t WINDOW_NAME[] = L"alphares";
WNDCLASS wc = { };
MSG message = { };
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.hbrBackground = CreateSolidBrush(RGB(43, 45, 92));
wc.hIcon = LoadIcon(wc.hInstance, MAKEINTRESOURCE(IDR_ICON));
wc.lpszClassName = CLASS_NAME;
if (!RegisterClass(&wc)) {
return 0;
}
HWND hwnd = CreateWindowEx(
0,
CLASS_NAME,
WINDOW_NAME,
WS_OVERLAPPEDWINDOW&~WS_MAXIMIZEBOX^WS_THICKFRAME,
CW_USEDEFAULT, CW_USEDEFAULT, 250, 150,
NULL,
NULL,
hInstance,
NULL);
CenterWindow(hwnd, WS_OVERLAPPEDWINDOW&~WS_MAXIMIZEBOX^WS_THICKFRAME, 0);
if (hwnd == NULL) {
return 0;
}
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
while (GetMessage(&message, NULL, 0, 0)) {
if (!IsDialogMessage(hwnd, &message)) {
TranslateMessage(&message);
DispatchMessage(&message);
}
}
return 0;
}
LPCSTR GetFortniteConfiguration() {
char *path;
size_t length;
_dupenv_s(&path, &length, "LOCALAPPDATA");
std::string fortnite = "\\FortniteGame\\Saved\\Config\\WindowsClient\\GameUserSettings.ini";
std::string fullpath = path + fortnite;
free(path);
return fullpath.c_str();
}
void SetFortniteConfiguration(LPCSTR file, int user_width, int user_height) {
std::string width_string = std::to_string(user_width);
std::string height_string = std::to_string(user_height);
char const *width = width_string.c_str();
char const *height = height_string.c_str();
DWORD attributes = GetFileAttributesA(file);
if (attributes & FILE_ATTRIBUTE_READONLY) {
attributes &= ~FILE_ATTRIBUTE_READONLY;
SetFileAttributesA(file, attributes);
}
const char *section = "/Script/FortniteGame.FortGameUserSettings";
CSimpleIniA ini;
ini.SetSpaces(false);
ini.SetUnicode();
ini.LoadFile(file);
ini.SetValue(section, "ResolutionSizeX", width);
ini.SetValue(section, "ResolutionSizeY", height);
ini.SetValue(section, "LastUserConfirmedResolutionSizeX", width);
ini.SetValue(section, "LastUserConfirmedResolutionSizeY", height);
ini.SetValue(section, "DesiredScreenWidth", width);
ini.SetValue(section, "DesiredScreenHeight", height);
ini.SetValue(section, "LastUserConfirmedDesiredScreenWidth", width);
ini.SetValue(section, "LastUserConfirmedDesiredScreenHeight", height);
ini.SaveFile(file);
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {
NONCLIENTMETRICS ncm;
ncm.cbSize = sizeof(ncm);
SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(ncm), &ncm, 0);
HINSTANCE hInstance;
static HFONT hFont = CreateFontIndirect(&ncm.lfMessageFont);
static HBRUSH hBrushStatic = CreateSolidBrush(RGB(43, 45, 92));
static HBRUSH hBrushEdit = CreateSolidBrush(RGB(35, 35, 79));
static HBRUSH hBrushButton = CreateSolidBrush(RGB(93, 107, 238));
switch (message) {
case WM_CREATE:
hInstance = GetModuleHandle(nullptr);
CreateWindowEx(
NULL,
TEXT("Static"),
TEXT("Width"),
WS_CHILD | WS_VISIBLE | ES_CENTER,
50, 15, 60, 20,
hwnd,
(HMENU)IDC_WIDTH_LABEL,
hInstance,
NULL);
SendMessage(
GetDlgItem(hwnd, IDC_WIDTH_LABEL),
WM_SETFONT,
(WPARAM)hFont,
TRUE);
CreateWindowEx(
NULL,
TEXT("Static"),
TEXT("Height"),
WS_CHILD | WS_VISIBLE | ES_CENTER,
125, 15, 60, 20,
hwnd,
(HMENU)IDC_HEIGHT_LABEL,
hInstance,
NULL);
SendMessage(
GetDlgItem(hwnd, IDC_HEIGHT_LABEL),
WM_SETFONT,
(WPARAM)hFont,
TRUE);
CreateWindowEx(
NULL,
TEXT("Edit"),
TEXT("1920"),
WS_CHILD | WS_VISIBLE | ES_NUMBER | ES_CENTER | WS_TABSTOP,
50, 35, 60, 15,
hwnd,
(HMENU)IDC_WIDTH_EDIT,
hInstance,
NULL);
SendMessage(
GetDlgItem(hwnd, IDC_WIDTH_EDIT),
WM_SETFONT,
(WPARAM)hFont,
TRUE);
SendMessage(
GetDlgItem(hwnd, IDC_WIDTH_EDIT),
EM_SETLIMITTEXT,
4, 0);
CreateWindowEx(
NULL,
TEXT("Edit"),
TEXT("1080"),
WS_CHILD | WS_VISIBLE | ES_NUMBER | ES_CENTER | WS_TABSTOP,
125, 35, 60, 15,
hwnd,
(HMENU)IDC_HEIGHT_EDIT,
hInstance,
NULL);
SendMessage(
GetDlgItem(hwnd, IDC_HEIGHT_EDIT),
WM_SETFONT,
(WPARAM)hFont,
TRUE);
SendMessage(
GetDlgItem(hwnd, IDC_HEIGHT_EDIT),
EM_SETLIMITTEXT,
4, 0);
CreateWindowEx(
NULL,
TEXT("Button"),
TEXT("Apply"),
WS_CHILD | WS_VISIBLE | BS_OWNERDRAW,
50, 65, 135, 25,
hwnd,
(HMENU)IDC_APPLY_BUTTON,
hInstance,
NULL);
SendMessage(
GetDlgItem(hwnd, IDC_APPLY_BUTTON),
WM_SETFONT,
(WPARAM)hFont,
TRUE);
break;
case WM_CTLCOLORSTATIC:
{
HDC hdcStatic = (HDC)wParam;
SetTextColor(hdcStatic, RGB(93, 107, 238));
SetBkColor(hdcStatic, RGB(43, 45, 92));
return (INT_PTR)hBrushStatic;
}
case WM_CTLCOLOREDIT:
{
HDC hdcEdit = (HDC)wParam;
SetTextColor(hdcEdit, RGB(255, 255, 255));
SetBkColor(hdcEdit, RGB(35, 35, 79));
return (INT_PTR)hBrushEdit;
}
case WM_CTLCOLORBTN:
{
HDC hdcButton = (HDC)wParam;
SetTextColor(hdcButton, RGB(255, 255, 255));
SetBkColor(hdcButton, RGB(93, 107, 238));
return (INT_PTR)hBrushButton;
}
case WM_COMMAND:
if (LOWORD(wParam) == IDC_APPLY_BUTTON) {
LPCSTR file = GetFortniteConfiguration();
struct stat buffer;
if (stat(file, &buffer) == 0) {
BOOL success;
int width = GetDlgItemInt(
hwnd,
IDC_WIDTH_EDIT,
&success,
FALSE);
int height = GetDlgItemInt(
hwnd,
IDC_HEIGHT_EDIT,
&success,
FALSE);
if (success == TRUE) {
SetFortniteConfiguration(file, width, height);
MessageBoxA(
hwnd,
"Your resolution was successfully saved.",
"Success",
MB_OK);
} else {
MessageBoxA(
hwnd,
"Please enter a resolution.",
"Warning",
MB_OK | MB_ICONWARNING);
}
} else {
MessageBoxA(
hwnd,
"There was an error finding your configuration file.",
"Error",
MB_OK | MB_ICONERROR);
}
}
break;
case WM_DRAWITEM:
if (wParam == IDC_APPLY_BUTTON) {
LPDRAWITEMSTRUCT pdis = (LPDRAWITEMSTRUCT)lParam;
RECT rect = pdis->rcItem;
DrawTextA(
pdis->hDC,
"Apply",
5,
&rect,
DT_CENTER | DT_SINGLELINE | DT_VCENTER);
return TRUE;
}
break;
case WM_DESTROY:
DeleteObject(hFont);
DeleteObject(hBrushStatic);
DeleteObject(hBrushEdit);
DeleteObject(hBrushButton);
PostQuitMessage(0);
return 0;
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
EndPaint(hwnd, &ps);
break;
}
return 0;
}
return DefWindowProc(hwnd, message, wParam, lParam);
}
</code></pre>
| [] | [
{
"body": "<p>I gave it a quick glance the one thing that stood out is:</p>\n\n<pre><code>LPCSTR GetFortniteConfiguration() {\n char *path;\n size_t length;\n _dupenv_s(&path, &length, \"LOCALAPPDATA\");\n std::string fortnite = \"\\\\FortniteGame\\\\Saved\\\\Config\\\\WindowsClient\\\\GameUserSettings.ini\";\n std::string fullpath = path + fortnite;\n free(path);\n\n return fullpath.c_str();\n}\n</code></pre>\n\n<p>The variable <code>fullpath</code> is destroyed and the memory released when you leave the function, so the pointer you return is dangling and points to freed memory. It only works because that memory is not overwritten in the short time your program lives. Of course this is random and may result in \"random crashes\".</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T18:50:13.633",
"Id": "406252",
"Score": "0",
"body": "Thanks Emily. Is it better if I return `fullpath` as a std::string, and then use `c_str()` on the return value in `SetFortniteConfiguration` and the `WM_COMMAND` case? **For example:** `std::string path = GetFortniteConfiguration();` and then `LPCSTR file = path.c_str();`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T19:37:31.903",
"Id": "406255",
"Score": "0",
"body": "Return `std::string` and make sure it stays alive for the whole time that the `LPCSTR` is used."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T09:48:55.910",
"Id": "210163",
"ParentId": "210093",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "210163",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T03:01:35.060",
"Id": "210093",
"Score": "3",
"Tags": [
"c++",
"beginner",
"configuration"
],
"Title": "Editing a configuration file using C++ and Win32"
} | 210093 |
<p>The <a href="https://en.wikipedia.org/wiki/Needleman%E2%80%93Wunsch_algorithm" rel="noreferrer">Needleman-Wunsch algorithm</a> is a way to align sequences in a way that optimizes "similarity". Usually, a grid is generated and then you follow a path down the grid (based off the largest value) to compute the optimal alignment between two sequences. I have created a Python program, that given two strings, will create the resulting matrix for the Needleman-Wunsch algorithm. Currently, the program when ran will generate two random sequences of DNA and then print out the resulting Needleman-Wunsch matrix.</p>
<h1>needlemanwunsch.py</h1>
<pre><code>import random
from tabulate import tabulate
class NeedlemanWunsch:
"""
Class used for generating Needleman-Wunsch matrices.
"""
def _compute_block(self, result, i, j):
"""
Given a block (corresponding to a 2 x 2 matrix), calculate the value o-
f the bottom right corner.
(Based on the equation:
M_{i,j} = max(M_{i-1,j-1} + S_{i,j},
M_{i,j-1} + W,
M_{i-1,j} + W)
Found here: https://vlab.amrita.edu/?sub=3&brch=274&sim=1431&cnt=1)
Args:
result : The current matrix that is being computed.
i : The right most part of the block being computed.
j : The bottom most part of the block being computed.
Returns:
The value for the right bottom corner of a particular block.
"""
return max(result[i-1][j-1] +
self._calc_weight(self._second_seq[i-1],
self._first_seq[j-1]),
result[i-1][j] + self.gap,
result[i][j-1] + self.gap)
def _calc_weight(self, first_char, second_char):
"""
Helper function, given two characters determines (based on the sc-
oring scheme) what the score for the particular characters can be.
Args:
first_char : A character to compare.
second_char : A character to compare.
Returns:
Either self.match or self.mismatch.
"""
if first_char == second_char:
return self.match
else:
return self.mismatch
def generate(self, first_seq, second_seq):
"""
Generates a matrix corresponding to the scores to the Needleman-Wu-
nsch algorithm.
Args:
first_seq : One of the sequences to be compared for similarity.
second_seq : One of the sequences to be compared for
similarity.
Returns:
A 2D list corresponding to the resulting matrix of the Needlem-
an-Wunsch algorithm.
"""
# Internally requies that the first sequence is longer.
if len(second_seq) > len(first_seq):
first_seq, second_seq = second_seq, first_seq
self._first_seq = first_seq
self._second_seq = second_seq
# Adjust sequence with "intial space"
# Initialize the resulting matrix with the initial row.
result = [list(range(0, -len(first_seq) - 1, -1))]
# Create initial columns.
for i in range(-1, -len(second_seq) - 1, -1):
row = [i]
row.extend([0]*len(first_seq))
result.append(row)
# Sweep through and compute each new cell row-wise.
for i in range(1, len(result)):
for j in range(1, len(result[0])):
result[i][j] = self._compute_block(result, i, j)
# Format for prettier printing.
for index, letter in enumerate(second_seq):
result[index + 1].insert(0, letter)
result[0].insert(0, ' ')
result.insert(0, list(" " + first_seq))
return result
def __init__(self, match=1, mismatch=-1, gap=-1):
"""
Initialize the Needleman-Wunsch class so that it provides weights for
match (default 1), mismatch (default -1), and gap (default -1).
"""
self.match = match
self.mismatch = mismatch
self.gap = gap
self._first_seq = ""
self._second_seq = ""
def deletion(seq, pos):
"""
Deletes a random base pair from a sequence at a specified position.
Args:
seq : Sequence to perform deletion on.
pos : Location of deletion.
Returns:
seq with character removed at pos.
"""
return seq[:pos] + seq[pos:]
def base_change(seq, pos):
"""
Changes a random base pair to another base pair at a specified position.
Args:
seq : Sequence to perform base change on.
pos : Locaion of base change.
Returns:
seq with character changed at pos.
"""
new_base = random.choice("ACTG".replace(seq[pos], ""))
return seq[:pos] + new_base + seq[pos:]
def mutate(seq, rounds=3):
"""
Mutates a piece of DNA by randomly applying a deletion or base change
Args:
seq : The sequence to be mutated.
rounds : Defaults to 3, the number of mutations to be made.
Returns:
A mutated sequence.
"""
mutations = (deletion, base_change)
for _ in range(rounds):
pos = random.randrange(len(seq))
seq = random.choice(mutations)(seq, pos)
return seq
def main():
"""
Creates a random couple of strings and creates the corresponding Needleman
-Wunsch matrix associated with them.
"""
needleman_wunsch = NeedlemanWunsch()
first_seq = ''.join(random.choices("ACTG", k=5))
second_seq = mutate(first_seq)
data = needleman_wunsch.generate(first_seq, second_seq)
print(tabulate(data, headers="firstrow"))
if __name__ == '__main__':
main()
</code></pre>
<p>I ended up using a <code>NeedlemanWunsch</code> class, because using only function resulted in a lot DRY for the parameters <code>match</code>, <code>mismatch</code>, and <code>gap</code>.</p>
<p>I am not particularly fond of the code. I haven't used <code>numpy</code> or any related libraries because I couldn't see any way that it would significantly shorten the code, however, I would be willing to use <code>numpy</code> if there is a significantly shorter way of expressing the matrix generation. However, the code seems frail, and very prone to off by one errors.</p>
| [] | [
{
"body": "<p><strong>Code</strong></p>\n\n<ul>\n<li><code>base_change</code> is not good name for function. It's suggest change. At <a href=\"https://en.wikipedia.org/wiki/Needleman%E2%80%93Wunsch_algorithm\" rel=\"nofollow noreferrer\">wikipedia</a> they use <code>Indel (INsertion or DELetion)</code> names.</li>\n<li><code>first_seq</code> and <code>second_seq</code> strings could be lists. In this case <code>mutate</code>/<code>deletion</code>/<code>base_change</code> function can do its stuff <em>in-place</em></li>\n<li><code>_first_seq</code> and <code>_second_seq</code> changes after every call <code>generate</code> method. No need to cache these variables, because of they not use in future by public method of class</li>\n<li><em>numpy</em> simplify code</li>\n</ul>\n\n<p><strong>Design</strong></p>\n\n<ul>\n<li>you have two main public functionalities: <code>mutate</code> and <code>generate</code> methods. <code>generate</code> mess presentation layer and logic one. Generally it's not good idea. Imho better design <code>generate</code> (<code>needleman_wunsch</code>) to calc only logic (without first row and column with <code>first_seq</code>, <code>second_seq</code>). Additional method <code>print_needleman_wunsch_matrix</code> could add these lines if needed.</li>\n</ul>\n\n<p>Example code (without <em>design</em> warning, additionally i exchange <em>tabulate</em> for <em>pandas</em> but this no needed)</p>\n\n<pre><code>import numpy as np\nimport pandas as pd\nfrom random import choice, choices, randrange\n\ndef needleman_wunsch(first, second, match=1, mismatch=-1, gap=-1):\n tab = np.full((len(second) + 2, len(first) + 2), ' ', dtype=object)\n tab[0, 2:] = first\n tab[1, 1:] = list(range(0, -len(first) - 1, -1))\n tab[2:, 0] = second\n tab[1:, 1] = list(range(0, -len(second) - 1, -1))\n is_equal = {True: match, False: mismatch}\n for f in range(2, len(first) + 2):\n for s in range(2, len(second) + 2):\n tab[s, f] = max(tab[s - 1][f - 1] + is_equal[first[f - 2] == second[s - 2]],\n tab[s - 1][f] + gap,\n tab[s][f - 1] + gap)\n return tab\n\n\ndef mutate(seq, rounds=3):\n mutate_seq = seq.copy()\n for change in choices((deletion, insertion), k=rounds):\n pos = randrange(len(mutate_seq))\n change(mutate_seq, pos)\n return mutate_seq\n\n\ndef deletion(seq, idx):\n seq.pop(idx)\n\n\ndef insertion(seq, idx):\n seq.insert(idx, choice(\"ACTG\".replace(seq[idx], \"\")))\n\n\ndef main():\n first_seq = choices(\"ACTG\", k=5)\n second_seq = mutate(first_seq)\n data = needleman_wunsch(first_seq, second_seq)\n print(pd.DataFrame(data))\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T19:01:45.937",
"Id": "210180",
"ParentId": "210099",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T05:59:24.113",
"Id": "210099",
"Score": "6",
"Tags": [
"python",
"algorithm",
"python-3.x",
"bioinformatics"
],
"Title": "Needleman-Wunsch Grid Generation in Python"
} | 210099 |
<p>Definition of <a href="https://en.wikipedia.org/wiki/Happy_number" rel="nofollow noreferrer">Happy numbers taken from Wikipedia</a>.</p>
<blockquote>
<p>A happy number is defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits in base-ten, and repeat the process until the number either equals 1 (where it will stay), or it loops endlessly in a cycle that does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers (or sad numbers)</p>
<p>Example: 19 is happy, as the associated sequence is</p>
<p>1*1 + 9*9 = 82,<br>
8*8 + 2*2 = 68,<br>
6*6 + 8*8 = 100,<br>
1*1 + 0*0 + 0*0 = 1.</p>
</blockquote>
<pre><code>import scala.collection.mutable.Set
object HappyNumber extends App {
def findSquareSum(n: Int): Int =
n.toString.foldLeft(0) { (product, num) => product + num.asDigit * num.asDigit }
val visited = Set[Int]()
def isHappyNumber(n: Int): Boolean = {
n match {
case 1 => true
case _ =>
if (visited contains n) false
else {
visited += n
if (isHappyNumber(findSquareSum(n))) { visited -= n; true} else false
}
}
}
(1 to 247) foreach { num => if(isHappyNumber(num)) println(num) }
}
</code></pre>
| [] | [
{
"body": "<p>In <code>findSquareSum()</code>, what you've labelled as <code>product</code> is actually a sum. So that's a little confusing. The digits squared is a product but adding them together is a running sum.</p>\n\n<p>I like to avoid transitions to/from <code>String</code> representation whenever possible, but that's mostly a style thing.</p>\n\n<p>If you make the <code>visited</code> set a passed parameter to the <code>isHappyNumber()</code> method, you can</p>\n\n<ol>\n<li>keep it immutable</li>\n<li>avoid emptying it between runs</li>\n<li>make the method tail recursive, which will be faster and more memory efficient</li>\n</ol>\n\n<p>.</p>\n\n<pre><code>def isHappyNumber(n: Int, seen: Set[Int] = Set()): Boolean =\n if (n == 1) true\n else if (seen(n)) false\n else isHappyNumber(findSquareSum(n), seen+n)\n</code></pre>\n\n<p>Here I've given the <code>Set</code>, now called <code>seen</code>, a default value (empty) so it doesn't have to be specified when invoked.</p>\n\n<pre><code>(1 to 247).filter(isHappyNumber(_)).foreach(println)\n</code></pre>\n\n<hr>\n\n<p><strong>UPDATE</strong></p>\n\n<p>Ah, I see that I've missed the point and purpose of your <code>visited</code> set, which is to cache unhappy numbers in order to reduce the recursive iterations in future calculations. Not a bad idea, but the obvious next question is: Why not cache all the <code>isHappyNumber()</code> results? You'll have quick lookups on all calculations and you won't have to back-out the happy number results.</p>\n\n<pre><code>//memoize a function of arity-2 but only cache the 1st parameter\n//\ndef memo[A,B,R](f :(A,B)=>R): (A,B)=>R = {\n val cache = new collection.mutable.WeakHashMap[A,R]\n (a:A,b:B) => cache.getOrElseUpdate(a,f(a,b))\n}\n\n//isHappyNumer() is now a memoized function\n// for quick lookup of both happy and unhappy numbers\n//\nval isHappyNumber :(Int, Set[Int]) => Boolean = memo { (n, seen) =>\n if (n == 1) true\n else if (seen(n)) false\n else isHappyNumber(findSquareSum(n), seen + n)\n}\n\n(1 to 24).filter(isHappyNumber(_,Set())).foreach(println)\n</code></pre>\n\n<p>You'll note that the scope (visibility) of the mutable hash map is kept quite small and local.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T00:06:46.380",
"Id": "406192",
"Score": "0",
"body": "thanks for your comment. I am not emptying the set between runs, but just removing a HappyNumber from it. That makes this algorithm remember the previously explored \"sad numbers\" and makes it fast.\n\nIf I pass an empty set for every number I will endup computing the set over and over again."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T08:20:32.167",
"Id": "210102",
"ParentId": "210100",
"Score": "3"
}
},
{
"body": "<p>Just a nitpick about naming: the \"find\" in <code>findSquareSum</code> is meaningless, and perhaps even misleading, since it's not searching for anything. Just <code>squareSum</code> would be fine. Even better, call it something like <code>sumSquaresOfDigits</code> to be explicit about what the function does.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T08:21:47.953",
"Id": "210157",
"ParentId": "210100",
"Score": "4"
}
},
{
"body": "<p>It's better to cache both <code>happy</code> and <code>unhappy</code> numbers</p>\n<pre><code>def squareSum(n: Int): Int = n.toString.map(_.asDigit).map(x => x * x).sum\n\ndef happyNum(n: Int, book: Set[Int], happy: Set[Int], unhappy: Set[Int]): List[Set[Int]] = {\n if(n==1 || happy.contains(n)) List(happy ++ book, unhappy)\n else if(book.contains(n) || unhappy.contains(n)) List(happy, unhappy ++ book)\n else happyNum(squareSum(n), book + n, happy, unhappy)\n}\n\ndef helper(): Set[Int] = {\n var happy, unhappy = Set[Int]()\n for(i <- 1 to 1000){\n val lis: List[Set[Int]] = happyNum(i, Set(), happy, unhappy)\n happy = lis(0)\n unhappy = lis(1)\n }\n happy + 1\n}\n\ndef solution(): List[Int] = helper.toList\n\ndef solution(num: Int): Boolean = helper.contains(num)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T09:16:29.563",
"Id": "489214",
"Score": "0",
"body": "Welcome to Code Review! Can you explain why your solution is better than the original? Alternative implementations by themselves are not reviews."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-18T09:01:06.607",
"Id": "249530",
"ParentId": "210100",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "210102",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T06:10:14.617",
"Id": "210100",
"Score": "2",
"Tags": [
"programming-challenge",
"interview-questions",
"functional-programming",
"scala",
"memoization"
],
"Title": "List of Happy Numbers in scala"
} | 210100 |
<p>I am relatively new to Python. I wrote this solution to the well known map coloring problem and also implemented the MRV and Degree heuristics. Here, I am considering the map of Australia - <code>['WA', 'NT', 'SA', 'Q', 'NSW', 'V', 'T']</code> and 3 given colors - <code>['R','G', 'B']</code></p>
<pre><code># choosing first node with degree heruistics
# applying MRV with backtracking
from enum import Enum
import pdb
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
class Graph:
def __init__(self, totalNodes, adjacencyList, color):
self.totalNodes = totalNodes
self.adjacencyList = adjacencyList
self.color = color
self.nodeSequence = [""]*totalNodes
def isSafe(self, node, c):
for i in range(len(self.adjacencyList[node])):
if(self.color[self.adjacencyList[node][i]] == c):
return False
return True
def graphColorUtil(self, node, colorLimit):
if node == '':
# check and color any uncolored node
for key, value in self.color.items():
if value == 0:
self.graphColorUtil(key, colorLimit)
return True
# pdb.set_trace()
for c in range(1, colorLimit+1):
if(self.isSafe(node, c) == True):
self.color[node] = c
nextNode = self.getNodeWithMRV(node, colorLimit)
if(self.graphColorUtil(nextNode, colorLimit) == True):
return True
else:
self.color[node] = 0
return False
def graphColoring(self, colorLimit):
# pdb.set_trace()
startNode = self.pickNode('')
if(self.graphColorUtil(startNode, colorLimit) == True):
return True
else:
print("Solution does not exists")
return False
# pick node using MRV
def pickNode(self, initialNode):
maxCount = 0
selectedNode = ''
# the very first node
if (initialNode == ''):
for node, neighbourList in self.adjacencyList.items():
if (len(neighbourList) > maxCount and self.color[node] == 0):
maxCount = len(neighbourList)
selectedNode = node
# the other nodes
else:
for i in range(len(self.adjacencyList[initialNode])):
childNode = self.adjacencyList[initialNode][i]
if (self.color[childNode] == 0 and len(self.adjacencyList[childNode]) > maxCount):
maxCount = len(self.adjacencyList[childNode])
selectedNode = childNode
return selectedNode
def getNodeWithMRV(self, parentNode, colorLimit):
selectedNode = ''
for i in range(len(self.adjacencyList[parentNode])):
childNode = self.adjacencyList[parentNode][i]
countColor = 0
for c in range(1, colorLimit+1):
if(self.isSafe(childNode, c) == True):
countColor += 1
if (countColor < minCount):
selectedNode = childNode
return selectedNode
# driver code
def main():
adjacencyList = {
'WA': ['NT', 'SA'],
'NT': ['WA', 'SA', 'Q'],
'SA': ['WA', 'NT', 'Q', 'NSW', 'V'],
'Q': ['NT', 'SA', 'NSW'],
'NSW': ['SA', 'Q', 'V'],
'V': ['SA', 'T', 'NSW'],
'T': ['V']
};
color = {
'WA': 0,
'NT': 0,
'SA': 0,
'Q': 0,
'NSW': 0,
'V': 0,
'T': 0
};
g = Graph(7, adjacencyList, color)
colorLimit = 3
g.graphColoring(colorLimit)
for node, color in g.color.items():
print(node, Color(color).name)
main()
</code></pre>
<p>What could be the possible ways to refactor this code? I am also interested for feedback on Python code style in general.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T18:24:46.027",
"Id": "406142",
"Score": "0",
"body": "You seem to lose something while copying. How `minCount` ever changes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T03:19:04.233",
"Id": "406199",
"Score": "0",
"body": "You mean `maxCount` in the `pickNode()` function?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T03:31:34.480",
"Id": "406200",
"Score": "0",
"body": "No. I mean `minCount` in `getNodeWithMRV`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T03:40:56.967",
"Id": "406201",
"Score": "0",
"body": "sorry, `minCount` is unnecessary there. Updated code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T04:14:45.883",
"Id": "406203",
"Score": "0",
"body": "`if (countColor < minCount):` is still there."
}
] | [
{
"body": "<p>Although not familiar with MRV and degree heuristics, i can make some remarks about the Python code style:</p>\n\n<p><strong>Loops can be made more Pythonic</strong></p>\n\n<pre><code>for i in range(len(self.adjacencyList[initialNode])):\n childNode = self.adjacencyList[initialNode][i]\n</code></pre>\n\n<p>should be written as: </p>\n\n<pre><code>for childNode in self.adjacencyList[initialNode]:\n</code></pre>\n\n<p><strong>Conditionals</strong></p>\n\n<pre><code>if(self.isSafe(childNode, c) == True):\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>if self.isSafe(childNode, c):\n</code></pre>\n\n<p><strong>method <code>isSafe</code></strong></p>\n\n<pre><code>def isSafe(self, node, c):\n for i in range(len(self.adjacencyList[node])):\n if(self.color[self.adjacencyList[node][i]] == c):\n return False\n return True\n</code></pre>\n\n<p>could be:</p>\n\n<pre><code>def isSafe(self, node, c):\n for adjacency in self.adjacencyList[node]:\n if self.color[adjacency] == c:\n return False\n return True\n</code></pre>\n\n<p>or even, more Pythonic, but a bit cryptic:</p>\n\n<pre><code>def isSafe(self, node, c):\n # return True if all node neighbours colors differ from c\n return all([self.color[adj] != c for adj in self.adjacencyList[node]]) \n</code></pre>\n\n<p><strong>Data structure</strong></p>\n\n<p>The repetition of the keys in the <code>adjacencyList</code> and <code>color</code>\nsuggest a data structure like the following, although this requires a \nlot changes in the existing code:</p>\n\n<pre><code>nodes = {\n 'WA' : {'color' : 0, 'neighbours' : ['NT', 'SA']},\n 'NT' : {'color' : 0, 'neighbours' : ['WA', 'SA', 'Q']},\n 'SA' : {'color' : 0, 'neighbours' : ['WA', 'NT', 'Q', 'NSW', 'V']},\n 'Q' : {'color' : 0, 'neighbours' : ['NT', 'SA', 'NSW']},\n 'NSW': {'color' : 0, 'neighbours' : ['SA', 'Q', 'V']},\n 'V' : {'color' : 0, 'neighbours' : ['SA', 'T', 'NSW']},\n 'T' : {'color' : 0, 'neighbours' : ['V']},\n} \n</code></pre>\n\n<p><strong>Others:</strong></p>\n\n<ul>\n<li><code>self.nodeSequence</code> is not used</li>\n<li><code>self.totalNodes</code> is not used</li>\n<li><code>minCount = 0</code> was edited out in <code>getNodeWithMRV</code> but should be there, or <code>if (countColor < minCount)</code> should be <code>if (countColor < 0)</code></li>\n<li><code>pickNode</code> is called only once with a constant argument <code>''</code>, and can therefor be made simpler </li>\n<li><code>getNodeWithMRV</code> will always return <code>''</code> because <code>countColor</code> will never be smaller than 0.</li>\n<li>the <code>;</code> at the end of <code>adjacencyList = ...</code> and <code>color = ...</code> an origin in another language :-) </li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T12:02:57.283",
"Id": "210168",
"ParentId": "210103",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "210168",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T08:35:38.523",
"Id": "210103",
"Score": "3",
"Tags": [
"python",
"algorithm",
"graph"
],
"Title": "Map coloring with MRV and Degree heuristics in Python"
} | 210103 |
<p>In some specific scenarios, I want to run code after the constructor for a class has run (namely: access std::enable_shared_from_this::shared_from_this()).</p>
<p>To solve this without introducing an error prone init method for all classes with this behaviour I have built a generic pattern that allows constructors to "defer" lambdas to run after the constructor has run (example in end of snippet):</p>
<pre><code>// If derived from this subclasses may call enable_defer::defer in their
// constructor to run code directly _after_ their constructor has completed
// This is useful when for example the constructor wants to access the weak_ptr
// from std::enable_shared_from_this in the constructor.
// Note naming convention matching std::enable_shared_from_this & underscores to avoid collisions in subclasses
class enable_defer
{
// Allowed factories
template <typename T>
friend std::shared_ptr<T> make_shared_deferrable();
template <typename T, typename... Args>
friend std::shared_ptr<T> make_shared_deferrable(Args&&... args);
// Allowed implementations
template <typename T>
friend class __impl__;
private:
std::vector<std::function<void()>> defered;
bool constructed = false;
// Only friend classes may have access to this type
// this is because we only want friend classes to be able to implement the interface
class __Tag__ {};
virtual void __constructed__(__Tag__ = __Tag__()) = 0;
// Implementation of enable_defer kept private
// to make sure only friend factories above may
// construct implementations
template <typename T>
class __impl__ : public T
{
static_assert(std::is_base_of<enable_defer, T>::value, "Must be enable_defer");
// Forward base class constructors
using T::T;
virtual void __constructed__(__Tag__) override
{
constructed = true;
for (auto fn : defered)
fn();
}
};
protected:
void defer(std::function<void()> fn)
{
// Make sure defer is only called in constructor
assert(!constructed);
defered.push_back(fn);
}
};
// Create std::shared_ptr from enable_defer
template <typename T>
std::shared_ptr<T> make_shared_deferrable()
{
auto shared(std::shared_ptr<T>(new enable_defer::__impl__<T>()));
shared->__constructed__();
return shared;
}
// Create std::shared_ptr from enable_defer
template <typename T, typename... Args>
std::shared_ptr<T> make_shared_deferrable(Args&&... args)
{
auto shared(std::shared_ptr<T>(new enable_defer::__impl__<T>(std::forward<Args>(args)...)));
shared->__constructed__();
return shared;
}
class Example : public enable_defer, public std::enable_shared_from_this<Example>
{
public:
Example()
{
defer([this]() {
shared_from_this(); // Works!
});
}
// Factory
static std::shared_ptr<Example> create()
{
return make_shared_deferrable<Example>();
}
};
</code></pre>
<p>Questions:</p>
<ul>
<li>Are there better ways to accomplish the enforcements of the implementation class and factories?</li>
<li>General improvements</li>
<li>Bugs?</li>
<li>Naming?</li>
<li>General thoughts on this pattern.</li>
</ul>
| [] | [
{
"body": "<ul>\n<li><p><a href=\"https://stackoverflow.com/a/228797/673679\">Identifiers with leading underscore(s) followed by a capital letter are reserved for the implementation</a> and should not be used in your own code. It's easiest to just avoid leading underscores.</p></li>\n<li><p>When using <code>enable_shared_from_this</code> it's important to use a static factory function <strong>and</strong> make the other constructors private. This prevents calling the <code>Example</code> constructor directly (where calling <code>shared_from_this</code> will be undefined behaviour, since we don't have a <code>shared_ptr</code>).</p></li>\n</ul>\n\n<hr>\n\n<p>Do we really need <code>enable_shared_from_this</code>? The whole thing could be more easily written as:</p>\n\n<pre><code> class Example\n {\n private:\n\n Example() { }\n\n public:\n\n static std::shared_ptr<Example> Create()\n {\n auto example = std::make_shared<Example>();\n example->do_the_thing();\n\n return example;\n }\n };\n</code></pre>\n\n<p>It really depends on what <code>do_the_thing()</code> is...</p>\n\n<p>If we have to register the class somewhere after creation (or consistently perform some action), perhaps that logic doesn't belong in the <code>Example</code> class at all.</p>\n\n<pre><code>struct Example {};\n\nstruct Registry\n{\n template<class T, class... Args>\n std::shared_ptr<T> CreateAndRegister(Args&&... args)\n {\n auto object = std::make_shared<T>(std::forward<Args>(args)...);\n Register(object);\n return object;\n }\n};\n\nauto registry = Registry();\nauto e = registry.CreateAndRegister<Example>();\n</code></pre>\n\n<p>While an object has control over it's own copy / move semantics, it generally shouldn't care who / what owns it.</p>\n\n<p>So the question is: why does <code>Example</code> need to \"break the 4th wall\" and know that it exists inside a <code>shared_ptr</code>?</p>\n\n<hr>\n\n<p>Large inheritance hierarchies are out of fashion nowadays (with good reason), but with a general solution, you may need to cope with:</p>\n\n<pre><code>struct ExampleA : enable_defer, enable_shared_from_this<ExampleA> {};\nstruct ExampleB : ExampleA {}; // what if B wants to defer something?\n</code></pre>\n\n<p>and</p>\n\n<pre><code>struct ExampleA : enable_defer, enable_shared_from_this<ExampleA> {};\nstruct ExampleB : enable_defer, enable_shared_from_this<ExampleB> {};\nstruct ExampleC : ExampleA, ExampleB {}; // uh oh... ?\n</code></pre>\n\n<p><code>shared_from_this</code> <a href=\"https://stackoverflow.com/questions/16082785/use-of-enable-shared-from-this-with-multiple-inheritance\">is quite complicated to use</a> as it is with a class hierarchy.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T11:45:47.543",
"Id": "406091",
"Score": "0",
"body": "I generally agree that std::enable_shared_from_this is bad practice. In my use case, Example needs to register itself as a listener on a child object (that is created in the constructor as well) that takes a shared_ptr/weak_ptr. It's one of the few instances where I think it's appropriate, but I rather implement this general pattern than hard code it into the classes that needs it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T12:01:57.793",
"Id": "406092",
"Score": "0",
"body": "If it's a child object, and you can change the interface, can it not just take a raw pointer? The lifetimes should be well defined, and the child object probably shouldn't own it's parent. Otherwise, I'd still argue for a plain factory function. It's one function call, vs. one function call *and* multiple inheritance to add an intrusive deferral mechanism."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T11:17:43.500",
"Id": "210113",
"ParentId": "210108",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T10:05:07.337",
"Id": "210108",
"Score": "4",
"Tags": [
"c++",
"design-patterns",
"template-meta-programming"
],
"Title": "Defer pattern for constructors in C++"
} | 210108 |
<p>I am building a Quiz app in swift (my first app) to practice a few skills (using CoreData, working with plists, UIKit etc.) and later to work with a server which stores the Exercises.</p>
<p>Here's my current point in development: <a href="https://bitbucket.org/paescebu/staplerch/src/master/" rel="nofollow noreferrer">https://bitbucket.org/paescebu/staplerch/src/master/</a></p>
<p>My question is not precise, more general, I hope this is accepted here. <strong>I wanted to know if what I am practicing in my Code is good or bad practice so far.</strong>
Any specifics like:
- Design pattern
- Conventions
- bad practices
are welcome</p>
<p>example of my uncertainties (my AppDelegate):</p>
<pre><code>import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
preloadData()
return true
}
private func preloadData() {
let preloadedDataKey = "didPreloadData"
let userDefaults = UserDefaults.standard
if userDefaults.bool(forKey: preloadedDataKey) == false
{
var categories: [Category] = []
if let path = Bundle.main.path(forResource: "demoExercises", ofType: "plist") {
categories = readDemoDataPlist(withPath: path)
}
//preload into Core Data
let backgroundContext = persistentContainer.newBackgroundContext()
persistentContainer.viewContext.automaticallyMergesChangesFromParent = true
backgroundContext.perform
{
do {
for item in categories {
let category = CDCategory(context: backgroundContext)
category.title = item.title
category.imageName = item.imageName
if let exerciseArray = item.exercises {
for eachExercise in exerciseArray {
let exercise = CDExercise(context: backgroundContext)
exercise.question = eachExercise.question
exercise.explanation = eachExercise.explanation
exercise.imageName = eachExercise.imageName
exercise.correctAnswer = eachExercise.correctAnswer
if let answersArray = eachExercise.answers
{
for eachAnswer in answersArray {
let answer = CDAnswers(context: backgroundContext)
answer.answer = eachAnswer
exercise.addToAnswers(answer)
}
}
category.addToExercises(exercise)
}
}
}
try backgroundContext.save()
userDefaults.set(true, forKey: preloadedDataKey)
print("Sucess!")
}
catch {
print("failed saving Context:\(error.localizedDescription)")
}
}
}
}
func readDemoDataPlist(withPath: String) -> [Category] {
var categoriesArray : [Category] = []
if let arrayWithCategories = NSArray(contentsOfFile: withPath) as? [[String : Any]] {
for eachCategory in arrayWithCategories {
let category = Category()
if let categoryTitle = eachCategory["title"] as? String {
category.title = categoryTitle
}
if let categoryImage = eachCategory["imageName"] as? String {
category.imageName = categoryImage
}
if let arrayWithExercises = eachCategory["exercises"] as? [[String : Any]] {
var exerciseArray: [Exercise] = []
for eachExercise in arrayWithExercises {
let exercise = Exercise()
if let question = eachExercise["question"] as? String {
exercise.question = question
}
if let correctAnswerIndex = eachExercise["correctAnswer"] as? String {
exercise.correctAnswer = correctAnswerIndex
}
if let answers = eachExercise["answers"] as? [String] {
exercise.answers = answers
}
if let image = eachExercise["image"] as? String {
exercise.imageName = image
}
if let explanation = eachExercise["explanation"] as? String {
exercise.explanation = explanation
}
exerciseArray.append(exercise)
category.exercises = exerciseArray
}
}
categoriesArray.append(category)
}
}
return categoriesArray
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "StaplerCH")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
</code></pre>
<p><strong>UPDATE</strong></p>
<p>I changed it quite a bit now, directly using the NSManagedObject model created from CoreData, instead of this step in between storing from plist, and the reading into persistent store.</p>
<p>Looks now like this:</p>
<pre><code>import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
preloadData()
return true
}
private func preloadData() {
let preloadedDataKey = "didPreloadData"
let userDefaults = UserDefaults.standard
if userDefaults.bool(forKey: preloadedDataKey) == false
{
if let path = Bundle.main.path(forResource: "demoExercises", ofType: "plist")
{
if let arrayWithCategories = NSArray(contentsOfFile: path) as? [[String : Any]]
{
//preload into Core Data
let backgroundContext = persistentContainer.newBackgroundContext()
persistentContainer.viewContext.automaticallyMergesChangesFromParent = true
backgroundContext.perform {
do {
for eachCategory in arrayWithCategories {
let category = Category(context: backgroundContext)
if let categoryTitle = eachCategory["title"] as? String {
category.title = categoryTitle
}
if let categoryImage = eachCategory["imageName"] as? String {
category.imageName = categoryImage
}
if let exerciseArray = eachCategory["exercises"] as? [[String: Any]] {
for eachExercise in exerciseArray {
let exercise = Exercise(context: backgroundContext)
if let question = eachExercise["question"] as? String {
exercise.question = question
}
if let image = eachExercise["image"] as? String {
exercise.imageName = image
}
if let explanation = eachExercise["explanation"] as? String {
exercise.explanation = explanation
}
if let arrayWithAnswers = eachExercise["answers"] as? [[String : Any]] {
for eachAnswer in arrayWithAnswers {
if let answerText = eachAnswer["text"] as? String, let answerIsCorrect = eachAnswer["isCorrect"] as? Bool {
let answer = Answer(context: backgroundContext)
answer.text = answerText
answer.isCorrect = answerIsCorrect
exercise.addToAnswers(answer)
}
}
}
category.addToExercises(exercise)
}
}
}
try backgroundContext.save()
userDefaults.set(true, forKey: preloadedDataKey)
print("Sucess!")
}
catch {
print("failed saving Context:\(error.localizedDescription)")
}
}
}
}
}
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "StaplerCH")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
</code></pre>
<p>Short workflow: After first installation, the app will load some demoQuestions from a plist into the persistent Store using the CoreData stack, so that the app is already preloaded with some Exercises, as said, in a later stage I'd like to be able to keep Exercises on a server from which the user can keep the Exercises updated.</p>
<p>The App has 2 Modes, a Practice and an Exam Mode (depending of the mode the ExerciseVC behaves differently), I really tried hard to have one VC only for that.</p>
<p>The other two Pages of the Start Page are quite irrelevant so far.</p>
<p>I am very thankful for any input.</p>
| [] | [
{
"body": "<h3>Coding style</h3>\n\n<p>Generally your code is written clearly. Just two points that I noticed:</p>\n\n<ul>\n<li><p>Two different styles of positioning the opening braces of a code block are used:</p>\n\n<pre><code>if userDefaults.bool(forKey: preloadedDataKey) == false\n{\n</code></pre>\n\n<p>vs</p>\n\n<pre><code>if let exerciseArray = item.exercises {\n</code></pre>\n\n<p>I prefer the second version, that is also what you'll find in the โSwift Programming Languageโ book and in the Swift source code. You can choose your favorite style, but it should be used consistently.</p></li>\n<li><p>Testing boolean values: I prefer </p>\n\n<pre><code>if !someBooleanExpression \n</code></pre>\n\n<p>over</p>\n\n<pre><code>if someBooleanExpression == false\n</code></pre></li>\n</ul>\n\n<h3>Naming variables</h3>\n\n<p>From the Swift <a href=\"https://swift.org/documentation/api-design-guidelines/\" rel=\"nofollow noreferrer\">API Design Guidelines</a>,</p>\n\n<blockquote>\n <p>Name variables, parameters, and associated types according to their roles, rather than their type constraints.</p>\n</blockquote>\n\n<p>This applies to <code>exerciseArray</code>, <code>answersArray</code> etc in your code. Better choices would be <code>exercises</code>, <code>answers</code>. I would also omit the <code>each</code> prefix in <code>eachExercise</code>, <code>eachAnswer</code>, just</p>\n\n<pre><code>for exercise in exercises { ... }\n</code></pre>\n\n<p>In your first approach, where you have โplainโย model classes in addition to the Core Data classes you could use the โcdโ prefix to distinguish between the variables โ as you already do to distinguish the classes:</p>\n\n<pre><code>for exercise in exercises {\n let cdexercise = CDExercise(context: backgroundContext)\n ceexercise.question = exercise.question\n // ...\n}\n</code></pre>\n\n<h3>The Core Data models</h3>\n\n<p>It seems that most (all?) attributes in the Core Data model classes are declared as <em>optionals.</em> But what happens if an attribute is not set? An exercise without question, an answer without text? It could lead to a runtime error later, or to unexpected results. You should check which attributes are required, and declare those as non-optionals.</p>\n\n<p>The <code>isCorrect</code> attribute of <code>CDAnswer</code> seems unnecessary since there is already a <code>correctAnswer</code> attribute in <code>CDExercise</code>. However, I would make that attribute a relationship to <code>CDAnswer</code> instead of a string.</p>\n\n<h3>The property list</h3>\n\n<p>From </p>\n\n<pre><code>if let categoryImage = eachCategory[\"imageName\"] as? String\n// ...\nif let image = eachExercise[\"image\"] as? String {\n</code></pre>\n\n<p>it seems that the keys in the default property list are not consistent. I'd suggest to use same names as the properties in the model classes, to avoid confusion.</p>\n\n<h3>To force unwrap or not to force unwrap โย loading resources</h3>\n\n<p>You carefully use optional binding and conditional casts, which is generally a good practice to avoid runtime errors. However, when loading the property list, you <em>know</em> that it is present, and what it contains. Any error here would be a <em>programming error</em> and must be fixed before deploying the program.</p>\n\n<p>Therefore forced unwrapping/casting is actually better: It helps to detect the programming error early:</p>\n\n<pre><code>let url = Bundle.main.url(forResource: \"demoExercises\", withExtension: \"plist\")!\n// ...\n</code></pre>\n\n<p>The same applies to the optional casts: You <em>know</em> that category has a key \"exercises\" with a value which is an array of dictionaries, so instead of</p>\n\n<pre><code>if let arrayWithExercises = eachCategory[\"exercises\"] as? [[String : Any]]\n</code></pre>\n\n<p>you can write</p>\n\n<pre><code>let arrayWithExercises = eachCategory[\"exercises\"] as! [[String : Any]]\n</code></pre>\n\n<h3>Approach #1: Loading the data into non-Core Data model objects first</h3>\n\n<p>Your first approach is to load the default data into separate structures first, and then create the managed objects. That requires some extra space and time, but that matters only if the default data is big.</p>\n\n<p>It can be simplified considerably however, using a <code>PropertyListDecoder</code>. It suffices to declare conformance to the <code>Decodable</code> protocol in your plain model classes</p>\n\n<pre><code>struct Category: Decodable {\n let title: String\n let imageName: String\n let exercises: [Exercise]\n}\n\nstruct Exercise: Decodable { ... }\n\nstruct Answer: Decodable {ย ... }\n</code></pre>\n\n<p>and to make sure that the property names are identical to the keys in the property list file. Then reading the default data becomes as simple as</p>\n\n<pre><code>let url = Bundle.main.url(forResource: \"demoExercises\", withExtension: \"plist\")!\nlet data = try! Data(contentsOf: url)\nlet categories = try! PropertyListDecoder().decode([Category].self, from: data)\n</code></pre>\n\n<p>The disadvantage of this approach is that you have to define extra types.</p>\n\n<h3>Approach #2: Load the default data into Core Data directly</h3>\n\n<p>I would use <code>PropertyListSerialization</code> to load the file (which works with both dictionaries and arrays):</p>\n\n<pre><code>let url = Bundle.main.url(forResource: \"demoExercises\", withExtension: \"plist\")!\nlet data = try! Data(contentsOf: url)\nlet categories = try! PropertyListSerialization.propertyList(from: data, format: nil)\n as! [[String: Any]]\n</code></pre>\n\n<p>Instead of the <code>addToXXX</code> methods I would use the inverse relationships to connect the objects, e.g.</p>\n\n<pre><code>category.addToExercises(exercise)\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>exercise.category = category\n</code></pre>\n\n<p>Together with the previously mentioned points the loop to read the property list contents into Core Data would look like this:</p>\n\n<pre><code>for category in categories {\n let cdcategory = Category(context: backgroundContext)\n cdcategory.title = category[\"title\"] as! String\n cdcategory.imageName = category[\"imageName\"] as! String\n\n for exercise in category[\"exercises\"] as! [[String: Any]] {\n let cdexercise = Exercise(context: backgroundContext)\n cdexercise.category = cdcategory // Add exercise to the category\n cdexercise.question = exercise[\"question\"] as! String\n // ...\n\n for answers in exercise[\"answers\"] as! [[String: Any]] {\n let cdanswer = Answer(context: backgroundContext)\n cdanswer.exercise = cdexercise // Add answer to the exercise\n // ...\n }\n }\n}\n</code></pre>\n\n<p>which is a bit shorter and easier to read than your original code. </p>\n\n<p>One could also try to load the managed objects directly from the property list as in approach #1. That requires to add <code>Decodable</code> conformance to the <code>NSManagedObject</code> subclasses. A possible solution is described in <a href=\"https://stackoverflow.com/q/44450114/1187415\">How to use swift 4 Codable in Core Data?</a> on Stack Overflow. However, it requires to write all the </p>\n\n<pre><code> convenience init(from decoder: Decoder)\n</code></pre>\n\n<p>methods, so it may not be worth the effort.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T07:58:17.937",
"Id": "406290",
"Score": "0",
"body": "Wow, this answer surpassed everything i expected from my question, thank you very much for going that deeply through my code, this helps me a lot! wish you merry christmas!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T09:10:53.827",
"Id": "406292",
"Score": "0",
"body": "@paescebu: You are welcome โย Merry Christmas!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T23:09:21.700",
"Id": "210190",
"ParentId": "210110",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "210190",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T10:45:55.493",
"Id": "210110",
"Score": "2",
"Tags": [
"beginner",
"comparative-review",
"swift",
"ios",
"core-data"
],
"Title": "Quiz app with Practice and Exam modes"
} | 210110 |
<p>I have rolled this program for reading the MBR:</p>
<pre><code>#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <cctype>
#include <iostream>
#include <string>
#include <utility>
using std::isprint;
using std::cout;
using std::cin;
using std::move;
using std::size_t;
using std::string;
constexpr size_t MBR_SIZE = 512;
constexpr size_t BYTES_PER_LINE = 4;
constexpr size_t NUMBER_OF_LINES = MBR_SIZE / BYTES_PER_LINE;
// Converts 4 least significant bits of 'c' to corresponding
// hexadecimal string.
static string fourBitsToString(char c)
{
string s = " ";
if (c >= 0 && c <= 9) {
s[0] = '0' + c;
} else {
c -= 10;
s[0] = 'A' + c;
}
return move(s);
}
// Converts a character to its hexadecimal representation.
static string charToHex(char c)
{
char lo = c & 0xf;
char hi = (c >> 4) & 0xf;
string s;
char chars[] = {hi, lo};
for (char ch : chars) {
s += fourBitsToString(ch);
}
return std::move(s);
}
// Prints the MBR to console.
static void PrintMBR(char buffer[MBR_SIZE])
{
size_t byteIndex = 0;
string lineSeparator;
string columnSeparator;
for (size_t i = 0; i < NUMBER_OF_LINES; i++) {
cout << lineSeparator;
lineSeparator = '\n';
columnSeparator = "";
for (size_t j = 0; j < BYTES_PER_LINE; j++) {
string ch = charToHex(buffer[byteIndex++]);
cout << columnSeparator << ch;
columnSeparator = " ";
}
cout << ' ';
for (size_t j = 0; j < BYTES_PER_LINE; j++) {
char c = buffer[byteIndex - BYTES_PER_LINE + j];
cout << (isprint((unsigned int) c) ? c : '.');
}
}
}
// Reads the entire master boot record (MBR) into lpBuffer.
// Expects lpBuffer to point to a memory point that may
// hold at leasst 512 bytes.
static DWORD ReadMBR(PCHAR lpBuffer)
{
HANDLE diskHandle = CreateFile(
TEXT("\\\\.\\PhysicalDrive0"),
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
0,
NULL);
char* buffer = new char[MBR_SIZE];
ReadFile(
diskHandle,
lpBuffer,
MBR_SIZE,
NULL,
NULL);
return GetLastError();
}
int main() {
char buffer[MBR_SIZE];
ReadMBR(buffer);
PrintMBR(buffer);
cin.get();
return 3;
}
</code></pre>
<p>(Compile as <code>Release</code> instead of <code>Debug</code> if it throws a nasty runtime breakpoint.)</p>
<p>I would love to hear any comments possible, but my main question is whether it is idiomatic C/C++/WinAPI.</p>
<p><strong>Note:</strong> To see the actual MBR, run this as administrator.</p>
| [] | [
{
"body": "<p>Idiomatic is relative. I guess it's a coding style you could find in older code-bases (and many winapi based applications are rather old), but you wouldn't write C++ like this today. Consider for instance:</p>\n\n<pre><code>#include <iostream>\n#include <iomanip>\n#include <iterator>\n#include <algorithm>\n#include <numeric>\n#include <array>\n\nconstexpr std::size_t MBR_SIZE = 255;\nconstexpr std::size_t BYTES_PER_COLUMN = 4;\nconstexpr char LINE_DELIMITER = '\\n';\nconstexpr const char* COL_DELIMITER = \" \";\n\nint main() {\n std::array<unsigned char, MBR_SIZE> mbr;\n std::iota(std::begin(mbr), std::end(mbr), 0); // filling it for testing purposes\n\n std::cout << std::hex << std::setfill('0');\n std::size_t index = 0;\n std::transform(std::begin(mbr), std::end(mbr), std::ostream_iterator<int>(std::cout, COL_DELIMITER), [index](auto c) mutable {\n if (index++ % BYTES_PER_COLUMN == 0) std::cout << LINE_DELIMITER;\n std::cout << std::setw(2); // setw must be applied for each output\n return c;\n });\n std::cout << std::endl;\n}\n</code></pre>\n\n<p>In a dozen of lines you get the same result as <code>printMBR</code> and its two auxiliary functions (at least I believe so, I haven't had the chance to run your code), which are longer and more complicated.</p>\n\n<p>To be more specific about your code:</p>\n\n<ul>\n<li><p>don't declare a variable before you're ready to define it, and don't define it before you're ready to use it.</p></li>\n<li><p>don't <code>std::move</code> your return value, it prevents copy elision</p></li>\n<li><p>don't declare free functions <code>static</code>, it's a java thing</p></li>\n<li><p>inside <code>ReadMBR</code> there's a <code>char* buffer = new char[MBR_SIZE];</code> you don't use afterwards</p></li>\n<li><p>I'm not a fan of that many <code>using</code> directives; prefix the names with <code>std::</code> and be done with it, unless you prefer to set up aliases: then <code>using string = std::string</code> is clearer</p></li>\n<li><p>use standard algorithms, such as <code>std::copy</code>, <code>std::accumulate</code>, etc (in headers <code><algorithm></code> and <code><numeric></code>) or range-base for loops <code>(for auto item : sequence)</code> instead of \"raw\" loops. For instance, <code>charToHex</code> could be written</p></li>\n</ul>\n\n<p>like this:</p>\n\n<pre><code>std::string s;\nfor (auto nibble : { (c >> 4) & 0xf, c & 0xf }) \n s += fourBitsToString(nibble);\nreturn s;\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>char lo = c & 0xf;\nchar hi = (c >> 4) & 0xf;\nchar chars[] = {hi, lo};\n\nreturn std::accumulate(std::begin(chars), std::end(chars), std::string(), [](auto init, auto elem) {\n return init += (fourBitsToString(elem));\n});\n</code></pre>\n\n<p>And, on a more aesthetic note, a four-bits aggregate can be called a half-byte or a nibble.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T16:32:10.147",
"Id": "406122",
"Score": "0",
"body": "\"don't declare free functions `static`\" - unless you want to explicitly restrict them to that specific translation unit (e.g. because it's an implementation detail not intended to be part of the public API). (This might also allow for better optimization, though I wouldn't suggest doing so just because of this reason.) // For printing, you suggest a call to `std::transform` with a `std::ostream_iterator` for `std::cout` and some custom logic also printing to `std::cout`. Methinks it would be cleaner to just use a `std::for_each` call and placing all printing logic into the lambda."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T19:02:40.950",
"Id": "406153",
"Score": "2",
"body": "@hoffmale: if you want to restrict functions to a specific TU, an anonymous namespace is generally preferred."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T14:26:04.020",
"Id": "210122",
"ParentId": "210116",
"Score": "5"
}
},
{
"body": "<h1><code>fourBitsToString</code> and <code>charToHex</code></h1>\n<p>Both of these functions are basically reimplementations of existing features of the <code><iostream></code> and <code><iomanip></code> headers.</p>\n<p>The whole call to <code>charToHex</code> could simply be replaced by <code>std::cout << std::uppercase << std::hex << std::setfill('0') << std::setw(2) << static_cast<int>(c);</code>.</p>\n<blockquote>\n<p>Note the <code>static_cast<int></code>: We want to print the numerical value, not the ASCII character glyph!</p>\n</blockquote>\n<p>However, setting <code>std::uppercase</code>, <code>std::hex</code> and <code>std::setfill('0')</code> for every byte to be printed would be wasteful, plus it would overwrite any previously set flags on <code>std::cout</code>.</p>\n<p>A better approach would be using a intermediary <code>std::ostringstream</code> instead, setting the flags once and retrieving (and resetting) its contents when sufficiently filled.</p>\n<blockquote>\n<p>More on that in the section below.</p>\n</blockquote>\n<p>Also, both functions end with <code>return move(s);</code>. This seems like misguided premature optimization ("Hey, we can move here! No need for a copy!"), but it likely is actually a pessimization instead!</p>\n<p>Compilers actually know that the returned value is a temporary and can optimize for this case (usually called NRVO - "Named return value optimization"). But: They can only do this if the variable is returned directly, and the call to <code>std::move</code> prevents that.</p>\n<p>Prefer <code>return s;</code>, unless you have good reasons (e.g. measurements/bad compiler) indicating otherwise.</p>\n<h1><code>PrintMBR</code></h1>\n<p>This function is a big pile of unnecessarily complicated code with poorly documented/enfored preconditions.</p>\n<p>First off, let's take a look at the function signature:</p>\n<pre><code>static void PrintMBR(char buffer[MBR_SIZE])\n</code></pre>\n<p>The flaw is really subtle: <code>buffer</code> isn't actually restricted to arrays of size <code>MBR_SIZE</code> at all! It's basically just a slightly fancier markup of <code>static void PrintMBR(char *buffer)</code>, and the compiler will actually treat it as such.</p>\n<p>This allows <code>PrintMBR</code> to be called with <code>char</code> arrays of all possible sizes, including smaller than <code>MBR_SIZE</code>, or even just <code>nullptr</code>.</p>\n<blockquote>\n<p>How to fix this?</p>\n<p>Well, the first inclination might be to just limit the size of <code>buffer</code> by explicitly making it keep track of the size information, e.g. by using a reference to a C-style array <code>char (&buffer)[MBR_SIZE]</code> or a fancier <code>std::array</code> reference <code>const std::array<char, MBR_SIZE> &buffer</code>.</p>\n<p>And that is a valid option if the only purpose was to print MBR contents.</p>\n<p>But looking at it's actually implementation, it seems like the intention was to print the hex values in one big column next to a column containing to the ASCII characters (if printable) nicely aligned. This could be generalized for printing arbitrary <code>char</code> arrays by amending some of the assumptions made further down in the implementation.</p>\n</blockquote>\n<p>Next, let's have a look at the function body:</p>\n<pre><code>size_t byteIndex = 0;\nstring lineSeparator;\nstring columnSeparator;\n\nfor (size_t i = 0; i < NUMBER_OF_LINES; i++) {\n cout << lineSeparator;\n lineSeparator = '\\n';\n columnSeparator = "";\n\n for (size_t j = 0; j < BYTES_PER_LINE; j++) {\n string ch = charToHex(buffer[byteIndex++]);\n cout << columnSeparator << ch;\n columnSeparator = " ";\n }\n\n cout << ' ';\n\n for (size_t j = 0; j < BYTES_PER_LINE; j++) {\n char c = buffer[byteIndex - BYTES_PER_LINE + j];\n cout << (isprint((unsigned int) c) ? c : '.');\n }\n}\n</code></pre>\n<p>If I understand correctly, the intention is to print the MBR in a <code>XX XX XX XX xxxx</code> line format (where <code>X</code> is a hex digit and <code>x</code> is an ASCII character).</p>\n<p>First off, it's hard to keep track of "constants" if their values are constantly changing. With one more check and a tiny bit of reordering, we can fix this:</p>\n<pre><code>size_t byteIndex = 0;\nstatic const string lineSeparator = "\\n";\nstatic const string columnSeparator = " ";\n\nfor (size_t i = 0; i < NUMBER_OF_LINES; i++) {\n if(i != 0) cout << lineSeparator;\n\n for (size_t j = 0; j < BYTES_PER_LINE; j++) {\n string ch = charToHex(buffer[byteIndex++]);\n cout << ch << columnSeparator;\n }\n\n for (size_t j = 0; j < BYTES_PER_LINE; j++) {\n char c = buffer[byteIndex - BYTES_PER_LINE + j];\n cout << (isprint((unsigned int) c) ? c : '.');\n }\n}\n</code></pre>\n<p>A bit more readable, and I don't have to keep track of all the possible states (and weird reassignments).</p>\n<p>I mentioned above that instead of using <code>charToHex</code>, one could use <code>std::ostringstream</code> and <code><iomanip></code> facilities instead:</p>\n<pre><code>void PrintMBR(char (&buffer)[MBR_SIZE]) {\n static constexpr auto bytes_per_line = 4;\n static const auto column_delimiter = " "s;\n static const auto line_delimiter = "\\n"s;\n\n auto hex_part = std::ostringstream{};\n auto ascii_part = std::ostringstream{};\n auto counter = 0;\n\n hex_part << std::uppercase << std::hex << std::setfill('0');\n\n for(auto c : buffer)\n {\n hex_part << std::setw(2) << static_cast<int>(c) << column_delimiter;\n ascii_part << (isprint(static_cast<unsigned int>(c)) ? c : '.');\n\n ++counter;\n\n if(counter % bytes_per_line == 0)\n {\n std::cout << hex_part.str() << ascii_part.str() << line_delimiter;\n hex_part.str("");\n ascii_part.str("");\n }\n }\n}\n</code></pre>\n<blockquote>\n<p>This could easily be made more generic to allow printing any byte buffer in this format.</p>\n</blockquote>\n<h1><code>ReadMBR</code></h1>\n<ul>\n<li><p>Memory leak: <code>buffer</code> doesn't ever get used after being allocated, including being deleted.</p>\n</li>\n<li><p>I don't like the <code>return GetLastError();</code> bit. I guess it's fine in pure C, but in C++ there is a more common way to communicate error conditions: exceptions.</p>\n<p>I get this is kind of a glue layer between C WinAPI and C++, but that doesn't mean you have to port idioms from one side into the other, especially if there are more idiomatic alternatives.</p>\n<blockquote>\n<p>I see this as problematic in this case, as likely nobody checks return codes unless they have to. Case in point: <code>main()</code>.</p>\n</blockquote>\n</li>\n<li><p>To be more generic, I would really like for this method to accept an <code>OutputIterator</code>. But sadly, the C WinAPI doesn't know those, so that would require another copy of the data (using an intermediary buffer). That's one of the design trade-offs: Performance vs. Usability.</p>\n</li>\n</ul>\n<h1><code>main</code></h1>\n<ul>\n<li>No check on the return code of <code>ReadMBR</code>.</li>\n<li><code>return 3;</code> - What does this <code>3</code> represent?</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T06:59:56.560",
"Id": "406389",
"Score": "0",
"body": "Thanks a lot, man! Accepted after the first 3 paragraphs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-25T00:59:30.590",
"Id": "406463",
"Score": "0",
"body": "Do note that guaranteed copy elision [does not extend to NRVO](https://godbolt.org/z/Dxq02b). Named object is glvalue, whereas the elision guarantees only cases with prvalues. I actually was not sure myself, had to spend some time to figure out. Great review otherwise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-27T20:22:17.200",
"Id": "406781",
"Score": "1",
"body": "@hoffmale, they certainly can be returned by value (commenting first two lines and uncommenting last line will make the code compile). It was just a little objection, but I believe it is important. [Link to RVO version](https://godbolt.org/z/R6OsRT). I believe mandatory copy elision is very different from compiler extension, as it allows slightly different techniques to be used. Perhaps I didn't communicate my intent correctly: the post mentions that mandatory copy elision extends to NRVO, but it is not the case, which I'm trying to prove."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-28T11:39:16.777",
"Id": "406854",
"Score": "0",
"body": "@Incomputable: After reading up elsewhere it finally clicked what it was you wanted to show me, and you're correct. Fixed that part of the answer ;)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T17:40:25.587",
"Id": "210175",
"ParentId": "210116",
"Score": "4"
}
},
{
"body": "<p>Here are some things that may help you improve your program.</p>\n\n<h2>Release resources as soon as practical</h2>\n\n<p>The <code>diskHandle</code> should be released immediately after the <code>ReadFile</code> call to minimize the time that the handle is open. Call <code>CloseHandle</code> to close the file and release the handle.</p>\n\n<h2>Use minimal sufficient privileges</h2>\n\n<p>In this case, the MBR is only read and not written, so the file should be opened only with the <code>FILE_SHARE_READ</code> option and not <code>FILE_SHARE_WRTE</code>.</p>\n\n<h2>Use <code>const</code> where practical</h2>\n\n<p>The <code>PrintMBR</code> function does not alter the passed <code>buffer</code> so the <code>buffer</code> parameter should be <code>const</code>.</p>\n\n<h2>Use an object</h2>\n\n<p>I'm surprised that other reviews didn't mention this, but why not treat the MBR as a C++ object? That way your <code>main</code> could look like this:</p>\n\n<pre><code>int main() {\n MBR mbr;\n if (mbr.read()) {\n std::cout << mbr << '\\n';\n } else {\n std::cout << \"Error reading MBR\\n\";\n }\n}\n</code></pre>\n\n<h2>Isolate platform-specific code</h2>\n\n<p>It would be very simple to write this code so that it also runs under Linux and doesn't rely on any particular compiler. The easiest way to do that is to isolate the Windows-specific code so that it is easy to port. This may not seem like a big deal if you're only interested in having a Windows version at the moment, but writing portable code by habit generally pays off in the long run in my experience.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-28T17:24:36.030",
"Id": "210512",
"ParentId": "210116",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "210175",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T12:57:40.100",
"Id": "210116",
"Score": "5",
"Tags": [
"c++",
"winapi"
],
"Title": "A WinAPI C++ program for printing the master boot record of the hard drive"
} | 210116 |
<p>I am working on a project that requires me to modify an input list as follows:</p>
<p>INPUT: List of numbers, each tagged with a label i.e. [[2, 'a'], [3, 'b'], [1, 'c'], ...]</p>
<p>DESIRED OUTPUT: Sort the list and grab the elements with the highest numerical component, store them in another list, and maybe rerun the function on the new list. This is an order determination scheme based on players rolling dice.</p>
<p>I have created the following code in Python 3.7 and it works just fine for me. I am curious to see if there are more clever ways to arrive at the same output. For some reason this took me about two hours to come up with (I am learning from scratch).</p>
<pre><code>list = [[1,'a'],[3,'b'],[7,'c'],[6,'d'],[4,'e'],[1,'f'],[7,'g'],[4,'h'],[6,'i']]
def comp(list):
new_list = []
list.sort(reverse = True)
for y in range(1, len(list)):
if list[0][0] > list[y][0]:
new_list.append(list[y])
top_rolls = [x for x in list if x not in new_list]
return(top_rolls)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T15:50:08.687",
"Id": "406109",
"Score": "1",
"body": "I'd like to point out that \"maybe\" has no place in a proper requirements statement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T16:53:57.217",
"Id": "406127",
"Score": "0",
"body": "Thanks Reinderien, I was simply writing shorthand instead of saying that I would like to rerun the function if the new list contains more than one element. I understand the logic behind your statement."
}
] | [
{
"body": "<p>You could simplify by directly making a list with the highest scores instead of creating and subtracting another list containing what you don't want :</p>\n\n<pre><code>def comp(rolls):\n top_rolls = []\n rolls.sort(reverse=True)\n for y in range(len(rolls)):\n if rolls[0][0] == rolls[y][0]:\n top_rolls.append(rolls[y])\n return top_rolls\n</code></pre>\n\n<p>Once you've done that it becomes easy to fit it in a list comprehension:</p>\n\n<pre><code>def comp(list):\n rolls.sort(reverse=True)\n top_rolls = [rolls[y] for y in range(len(rolls)) if rolls[0][0] == rolls[y][0]]\n return top_rolls\n</code></pre>\n\n<p>Or even shorter:</p>\n\n<pre><code>def comp(list):\n list.sort(reverse=True)\n return [rolls[y] for y in range(len(rolls)) if rolls[0][0] == rolls[y][0]]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T16:55:33.713",
"Id": "406128",
"Score": "0",
"body": "That's great, thank you. I don't know why I created a list of things that I don't want just to subtract it from the overall list. Your method is much more concise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T18:00:20.423",
"Id": "406138",
"Score": "0",
"body": "Don't name an argument `list`. That will shadow the built-in type also called `list`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T18:45:59.860",
"Id": "406148",
"Score": "0",
"body": "I am renaming everything after I am finished, I am more concerned about the appropriate syntax for now."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T14:56:59.293",
"Id": "210123",
"ParentId": "210117",
"Score": "3"
}
},
{
"body": "<p><strong>Names</strong></p>\n\n<p>Using the name <code>list</code> for a variable is legal but usually avoided because it hides the <code>list</code> builtin. The name <code>lst</code> would be a better candidate.</p>\n\n<p>The function name <code>comp</code> could be improved as well. Maybe <code>get_best_elements</code> (even though I am not fully convinced).</p>\n\n<p><strong>Tests</strong></p>\n\n<p>Before going further, it may be wise to add tests so that you can easily be sure that we do not break anything.</p>\n\n<p>A proper solution would involve a unit-test framework but for the time being, we can go for the simple:</p>\n\n<pre><code>TESTS = (\n ([], []),\n ([[1,'a']], [[1, 'a']]),\n ([[1,'a'], [1,'a'], [1,'a'], [1,'a']], [[1,'a'], [1,'a'], [1,'a'], [1,'a']]),\n ([[1,'a'], [1,'b'], [1,'c'], [1,'d']], [[1,'d'], [1,'c'], [1,'b'], [1,'a']]),\n ([[1,'a'],[3,'b'],[7,'c'],[6,'d'],[4,'e'],[1,'f'],[7,'g'],[4,'h'],[6,'i']], [[7, 'g'], [7, 'c']]),\n ([[1,'a'],[3,'b'],[7,'c'],[6,'d'],[4,'e'],[1,'f'],[4,'h'],[6,'i']], [[7, 'c']]),\n)\n\nfor test_input, expected_output in TESTS:\n output = get_best_elements(test_input)\n assert output == expected_output\nprint(\"OK\")\n</code></pre>\n\n<p><strong>Style</strong></p>\n\n<p>Parenthesis are not required in the return statements.\nAlso, the temporary variable is not really required.</p>\n\n<p><strong>List comprehension</strong></p>\n\n<p>The <code>new_list</code> could be defined with a list comprehension.</p>\n\n<pre><code>def get_best_elements(lst):\n lst.sort(reverse = True)\n new_lst = [lst[y] for y in range(1, len(lst)) if lst[0][0] > lst[y][0]]\n return [x for x in lst if x not in new_lst]\n</code></pre>\n\n<p><strong>Loop like a native</strong></p>\n\n<p>I highly recommend <a href=\"https://nedbatchelder.com/text/iter.html\" rel=\"noreferrer\">Ned Batchelder's talk \"Loop like a native\"</a> about iterators. One of the most simple take away is that whenever you're doing <code>range(len(lst))</code>, you can probably do things in a better way: more concise, clearer and more efficient.</p>\n\n<p>In our case, we'd have something like:</p>\n\n<pre><code>def get_best_elements(lst):\n lst.sort(reverse = True)\n new_lst = [e for e in lst if e[0] < lst[0][0]]\n return [x for x in lst if x not in new_lst]\n</code></pre>\n\n<p><strong>Another approach</strong></p>\n\n<p>The last list comprehension can be quite expensive because for each element <code>x</code>, you may perform a look-up in the list. This can lead to a <code>O(nยฒ)</code> behavior.</p>\n\n<p>Instead of filtering out elements that do not correspond to the biggest number, we could just keep the one that do correspond to the biggest number.</p>\n\n<pre><code>def get_best_elements(lst):\n if not lst:\n return []\n lst.sort(reverse = True)\n big_n = lst[0][0]\n return [x for x in lst if x[0] == big_n]\n</code></pre>\n\n<p><strong>Sort a smaller numbers of elements</strong></p>\n\n<p>You could use <code>max</code> to get <code>big_n</code>.</p>\n\n<p>Also, we could perform the sorting on the filtered list so that we have fewer elements to sort:</p>\n\n<pre><code>def get_best_elements(lst):\n if not lst:\n return []\n big_n = max(lst)[0]\n return list(sorted((x for x in lst if x[0] == big_n), reverse=True))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T16:09:11.810",
"Id": "210128",
"ParentId": "210117",
"Score": "7"
}
},
{
"body": "<p>Based on your stated use case:</p>\n\n<blockquote>\n <p>I would like to rerun the function if the new list contains more than one element.</p>\n</blockquote>\n\n<p>you don't even need to return a list; just return the highest element's roll and name, which can be unpacked by the caller as a 2-tuple:</p>\n\n<pre><code>def comp(rolls):\n return max(rolls)\n</code></pre>\n\n<p>That said, you haven't explicitly stated how to resolve ties with rolls of the same value. That will affect this solution.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T18:47:37.393",
"Id": "406149",
"Score": "0",
"body": "The max function on it's own will only return one players roll, so if there is a tie it will not be handled. Working with a simplification similar to one that @Comte_Zero provided, I am handling the case of a tie separately. I am sure that code could use some enhancing as well, I am just trying to get the basic form nailed down and make edits later."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T19:12:02.740",
"Id": "406155",
"Score": "0",
"body": "I'd propose that tie resolution should be built into this function."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T18:21:14.580",
"Id": "210134",
"ParentId": "210117",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "210128",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T13:07:47.267",
"Id": "210117",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"sorting"
],
"Title": "Sorting a list of numbers, each with a character label"
} | 210117 |
<p>I created a mega menu using flexbox, and because I'm not really into CSS, a review would be helpful.</p>
<p>I know it would be better to avoid the third ul-level but this is not possible, because the HTML is generated by another system. And we decided to use the second ul level as a marker for a new row in the mega menu.</p>
<p>With saying "Mega Menu" I mean that when you hover over "products" you will not just see a single list of sub items, but instead multiple lists. Often in "Mega Menus" they also add more content like text or pictures (not needed for me).</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-css lang-css prettyprint-override"><code>ul {
width: 100%;
display: flex;
flex-direction: column;
list-style: none;
margin: 0 0 0 0;
padding: 0;
position: relative;
background: red;
}
ul li {
flex: 1 1 auto;
display: block;
text-align: left;
}
ul li:hover {
background: tomato;
}
ul li:hover ul {
display: flex;
}
ul li a {
display: block;
padding: 1rem 0;
}
ul li ul {
display: none;
left: 0;
width: 100%;
}
ul li ul li {
flex: 0 0 auto;
}
@media screen and (min-width: 37.5em) {
ul {
flex-direction: row;
}
ul li {
text-align: center;
background: green;
}
ul ul {
position: absolute;
}
ul ul a {
padding: 1rem;
}
ul ul li {
position: relative;
text-align: left;
}
ul ul li ul {
position: relative;
}
ul ul li ul li {
flex-basis: 100%;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
<ul>
<li><a href="#">home</a></li>
<li><a href="#">products</a>
<ul>
<li><a href="#">short</a>
<ul>
<li><a href="#">long</a></li>
</ul>
</li>
<li><a href="#">item 1</a>
<ul>
<li><a href="#">long item 2</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#">whatever</a>
<ul>
<li><a href="#">superlong sub 1</a></li>
<li><a href="#">s 2</a></li>
</ul>
</l>
<li><a href="#">go</a></li>
<li><a href="#">on</a></li>
</ul>
</nav></code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T16:11:45.507",
"Id": "406117",
"Score": "0",
"body": "Welcome to Code Review. At least for me, a \"mega menu\" is a foreign term. Can you add a link to some external resources or---even better---describe in your own words what you intended to create? Thanks! (Keep in mind that you don't need to add \"Update\" or \"Edit\" to your [edit]s; every post on Code Review has a revision log)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T23:42:46.913",
"Id": "406281",
"Score": "0",
"body": "@Zeta Thanks for the welcome. I tried to describe it in my own words. But I thought the term \"mega menu\" is quite common when talking about css menus."
}
] | [
{
"body": "<p>I'd change the color scheme, the colors are a retinal burning :) Also, it would make the colors easier to read. Also you have the sub menu over to the left irregardless of what choice is selected. I'm a fan of the choices being under the selection I mouse over myself. Other than that, it looks good!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T15:21:31.257",
"Id": "406102",
"Score": "0",
"body": "the color's where just for development =) I tried to just make it as basic as possible and focus on functionality. will think about the choices under the selection. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T14:17:30.713",
"Id": "210121",
"ParentId": "210119",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "210121",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T13:52:21.523",
"Id": "210119",
"Score": "1",
"Tags": [
"css"
],
"Title": "Horizontal mega menu with flexbox"
} | 210119 |
<p>The code works; the problem is in the processing. I feel like the code can further improved and I believe the answer is Arrays however, my knowledge is very limited. Here, I loop through ~ 1000 columns. Each column has a start and end date; which will span from 1 day to 20 days, averaging ~ 3-5 days for each column. Upwards of 5000 lines are moved through and it shows in the speed of return. I will be adding <code>If</code> statements and I feel that if I add too much more where I am at that the program will crash.</p>
<p>I am hoping to speed it up. I believe arrays will do this however, the only array I use in here is borrowed from SO.</p>
<p><a href="https://ibb.co/cJx0f9v" rel="nofollow noreferrer">Tab Month Tracker</a></p>
<p><a href="https://ibb.co/1J5gHbf" rel="nofollow noreferrer">Raw Data Columns</a></p>
<p><a href="https://ibb.co/8m6ymY4" rel="nofollow noreferrer">Tabs Example</a></p>
<p><a href="https://uploadfiles.io/che18" rel="nofollow noreferrer">Download:Mock Data.xlsx</a></p>
<pre><code>'Function to return array for dates between Start Date and End Date
Function GetDatesRange(dateStart As Date, dateEnd As Date) As Collection
Dim dates As New Collection
Dim currentDate As Date
currentDate = dateStart
Do While currentDate <= dateEnd
dates.Add currentDate
currentDate = DateAdd("d", 1, currentDate)
Loop
Set GetDatesRange = dates
End Function
'Sub to move raw data into predictable format
Sub Program()
Application.ScreenUpdating = False
Dim dateStartCell As Range, dateEndCell As Range, StartDate As Range, Cell As Range
Dim allDates As Collection
Dim currentDateSter As Variant
Dim currentDate As Date
Dim TestDate As Integer
Dim NextRow As Long
Dim AdvRow As Long
Dim Facility As String
Dim Unit As String
Dim TheDay As String
Dim TheUnit As String
Dim Pax As String
Dim Test1 As Boolean
Dim Test2 As Boolean
Set StartDate = Range("E2:E1000")
NextRow = 2
Sheets("Raw").Activate
'Evaluating Each Date in Range
For Each Cell In StartDate
Set dateStartCell = Range("E" & NextRow)
Set dateEndCell = Range("G" & NextRow)
Set allDates = GetDatesRange(dateStartCell.Value, dateEndCell.Value)
Facility = Cells(NextRow, 3)
Unit = Cells(NextRow, 2)
Pax = Cells(NextRow, 12)
'Evaluating if the date and name already exist
For Each currentDateSter In allDates
currentDate = CDate(currentDateSter)
Sheets(MonthName(Month(currentDate), True) & Year(currentDate)).Activate
AdvRow = 3
PropRow = Empty
Test1 = False
Test2 = False
'evaluating if the date and name already exists if it does, and determines row for data entry
'eventually end up writing over data if it already exists however, column C has 125 unique possibilities
'that will fill another column in the month tabs
Do
AdvRow = AdvRow + 1
PropRow = AdvRow
TheDay = Cells(AdvRow, 1)
TheUnit = Cells(AdvRow, 2)
If TheDay = Day(currentDate) And TheUnit = Unit Then
Test1 = True
Else: Test1 = False
End If
If TheDay = TheUnit Then
Test2 = True
Else: Test2 = False
End If
Loop Until Test1 = True Or Test2 = True
Cells(PropRow, 2).Value = Unit
Cells(PropRow, 1).Value = Day(currentDate)
Cells(PropRow, 3).Value = Pax
Sheets("Raw").Activate
Next currentDateSter
NextRow = NextRow + 1
Next Cell
Application.ScreenUpdating = True
End Sub
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T15:53:29.847",
"Id": "406241",
"Score": "0",
"body": "The first thing that you need to do is stop Activating the Worksheets. Watch: [Excel VBA Introduction Part 5 - Selecting Cells (Range, Cells, Activecell, End, Offset)](https://www.youtube.com/watch?v=c8reU-H1PKQ). This will speed up your code immensely."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T15:55:38.067",
"Id": "406242",
"Score": "0",
"body": "Can you provide a mock workbook? It will need to have a couple of rows of mock `Raw Data` and a couple of matching entries on one of the monthly tabs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T18:11:16.050",
"Id": "406250",
"Score": "0",
"body": "Yeah, I have to scrub some data, Someone changed the name of the post, and it is sort of correct, but that is only part of what is happening. Essentially `column b` hold a `organization`, `column E` holds a `start date` and `column G` holds an `end date`. for each `organization` in `b` I am breaking it up from the `start date` to the `end date` 1 instance of `organization` for each day. The `if statements` I will add in, will put facilities arrayed across the rest of the `month tab` trackers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T18:39:50.080",
"Id": "406251",
"Score": "0",
"body": "[link to scrubbed file]:https://ufile.io/che18"
}
] | [
{
"body": "<p>There are many areas of improvement in this coding.</p>\n\n<p>A most important part of code hygiene is proper indenting, and <strong>always</strong> use <code>Option Explicit</code>.</p>\n\n<p>Also, name your variables to something meaningful. For example, you use <code>StartDate</code>, but it is not a date (which the name implies), but a range.</p>\n\n<p>You comment that your first function returns an <code>Array</code>, but it actually returns a <code>Collection</code>. <code>Array</code>s are ordered, <code>Collection</code>s are not, particularly in VBA. </p>\n\n<p>You have some <code>Boolean</code> anti-patterns happening:</p>\n\n<pre><code>If TheDay = Day(currentDate) And TheUnit = Unit Then\nTest1 = True\nElse: Test1 = False ' No need to run things onto a single line, especially if this is inconsistent with the other code.\nEnd If\n</code></pre>\n\n<p>Can simply be:</p>\n\n<pre><code>Test1 = (TheDay = Day(currentDate)) And (TheUnit = Unit ) ' perhaps \"FindMatch\" is better descriptive name.\n</code></pre>\n\n<p>You set <code>AdvRow</code> and <code>PropRow</code> (what are these anyway - proper naming?) relative to each other within the loop, but you don't change either in that loop - so a single variable (<code>AdvRow</code>) will suffice.</p>\n\n<p>You don't error check to ensure that the data you are reading is the right form - what happens if the data sheet does not exist, or that cell that is read is not a date?</p>\n\n<p>You use <code>NextRow</code> while in a loop - but you already access a cell in the loop that tells you what the row is. This is one variable that can be dropped. And you are using <code>NextRow</code> as the <code>CurrentRow</code> - this is another example of a confusing variable name.</p>\n\n<p>A big performance hit will come from having three nested loops, but also accessing each cell individually within those loops. Each time you make the program switch from looking at the VBA to looking at the Excel ranges is a cost in performance - this is why taking a range and putting it into an array improves efficiency.</p>\n\n<pre><code>'Function to return Collection of dates between Start Date and End Date\n'**** You don't check to see if Start comes before End - what does it mean if they are the wrong way round?\nFunction GetDatesRange(dateStart As Date, dateEnd As Date) As Collection\nDim dates As New Collection\nDim currentDate As Date\n currentDate = dateStart\n Do While currentDate <= dateEnd\n dates.Add currentDate\n currentDate = DateAdd(\"d\", 1, currentDate)\n Loop\n Set GetDatesRange = dates\nEnd Function\n\n'Sub to move raw data into predictable format\nSub Program()\nDim rawData As Variant\nDim currentRow As Long\n Application.ScreenUpdating = False\n With Sheets(\"Raw\")\n rawData = .Range(Union(.Range(\"E2:E1000\"), .Range(\"G2:G1000\"), .Range(\"C2:C1000\"), .Range(\"B2:B1000\"), .Range(\"L2:L1000\"))).Value\n End With\n\n 'will be a more efficient way of setting the array, but this will do for now\n ' 0..998, 0..4 array - datestart, dateend, facility, unit, pax\n\n 'Removes the following code:\n 'Set StartDate = Range(\"E2:E1000\")\n 'NextRow = 2\n 'Sheets(\"Raw\").Activate\n 'For Each Cell In StartDate\n 'Set dateStartCell = Range(\"E\" & NextRow)\n 'Set dateEndCell = Range(\"G\" & NextRow)\n\n For currentRow = LBound(rawData, 1) To UBound(rawData, 1)\n Dim allDates As Collection\n Dim currentDateSter As Variant\n 'Set allDates = GetDatesRange(dateStartCell.Value, dateEndCell.Value)\n Set allDates = GetDatesRange(CDate(rawData(currentRow, 0)), CDate(rawData(currentRow, 0)))\n\n 'Following code is no longer necessary\n' Facility = Cells(NextRow, 3)\n' Unit = Cells(NextRow, 2)\n' Pax = Cells(NextRow, 12)\n\n 'Evaluating if the date and name already exist\n For Each currentDateSter In allDates\n Dim checkSheet As Worksheet ' not sure what to call this\n Dim currentDate As Date\n Dim advRow As Long\n currentDate = CDate(currentDateSter) ' what if this is not a date?\n Set checkSheet = Sheets(MonthName(Month(currentDate), True) & Year(currentDate))\n\n advRow = 3\n 'evaluating if the date and name already exists if it does, and determines row for data entry\n 'eventually end up writing over data if it already exists however, column C has 125 unique possibilities\n 'that will fill another column in the month tabs\n Do\n Dim isMatch As Boolean ' Test1\n Dim isOffsetMatch As Boolean ' Test2\n Dim theDay As String\n Dim theUnit As String\n advRow = advRow + 1\n 'PropRow = AdvRow\n\n theDay = checkSheet.Cells(advRow, 1) ' fully qualified access to cells - no ambiguity\n theUnit = checkSheet.Cells(advRow, 2)\n isMatch = (theDay = Day(currentDate)) And (theUnit = rawData(currentRow, 3))\n isOffsetMatch = (theDay = theUnit)\n Loop Until isMatch Or isOffsetMatch\n checkSheet.Cells(advRow, 2).Value = rawData(currentRow, 3)\n checkSheet.Cells(advRow, 1).Value = Day(currentDate)\n checkSheet.Cells(advRow, 3).Value = rawData(currentRow, 4)\n Next currentDateSter\n Next currentRow\n Application.ScreenUpdating = True\nEnd Sub\n</code></pre>\n\n<p>Removing all my additional comments in <code>Program</code> gives you:</p>\n\n<pre><code>'Sub to move raw data into predictable format\nSub Program()\nDim rawData As Variant\nDim currentRow As Long\n Application.ScreenUpdating = False\n With Sheets(\"Raw\")\n rawData = .Range(Union(.Range(\"E2:E1000\"), .Range(\"G2:G1000\"), .Range(\"C2:C1000\"), .Range(\"B2:B1000\"), .Range(\"L2:L1000\"))).Value\n End With\n For currentRow = LBound(rawData, 1) To UBound(rawData, 1)\n Dim allDates As Collection\n Dim currentDateSter As Variant\n Set allDates = GetDatesRange(CDate(rawData(currentRow, 0)), CDate(rawData(currentRow, 0)))\n 'Evaluating if the date and name already exist\n For Each currentDateSter In allDates\n Dim checkSheet As Worksheet ' not sure what to call this\n Dim currentDate As Date\n Dim advRow As Long\n currentDate = CDate(currentDateSter) ' what if this is not a date?\n Set checkSheet = Sheets(MonthName(Month(currentDate), True) & Year(currentDate))\n\n advRow = 3\n 'evaluating if the date and name already exists if it does, and determines row for data entry\n 'eventually end up writing over data if it already exists however, column C has 125 unique possibilities\n 'that will fill another column in the month tabs\n Do\n Dim isMatch As Boolean ' Test1\n Dim isOffsetMatch As Boolean ' Test2\n Dim theDay As String\n Dim theUnit As String\n advRow = advRow + 1\n theDay = checkSheet.Cells(advRow, 1) ' fully qualified access to cells - no ambiguity\n theUnit = checkSheet.Cells(advRow, 2)\n isMatch = (theDay = Day(currentDate)) And (theUnit = rawData(currentRow, 3))\n isOffsetMatch = (theDay = theUnit)\n Loop Until isMatch Or isOffsetMatch\n checkSheet.Cells(advRow, 2).Value = rawData(currentRow, 3)\n checkSheet.Cells(advRow, 1).Value = Day(currentDate)\n checkSheet.Cells(advRow, 3).Value = rawData(currentRow, 4)\n Next currentDateSter\n Next currentRow\n Application.ScreenUpdating = True\nEnd Sub\n</code></pre>\n\n<p>Of course, there may be some other logic paths, or even, perhaps, using Excel native functions that could help refine the problem.</p>\n\n<p>I haven't been able to test the code (naturally), but it does compile in VBA.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T14:57:52.333",
"Id": "406324",
"Score": "0",
"body": "`rawData = Sheets(\"Raw\").Range(\"E2:E1000\", \"G2:G1000\", \"C2:C1000\", \"B2:B1000\", \"L2:L1000\")` gives me a `run-time error \"450\" wrong number of arguments or invalid property assignment`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T14:59:52.923",
"Id": "406325",
"Score": "0",
"body": "`startdate` will not be after `enddate`, the data source the info is being pulled from will not allow submission if it is incorrect. The data as is, is very predictable. I should have qualified that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T21:02:31.747",
"Id": "406363",
"Score": "0",
"body": "I had slipped into some Excel shorthand about evalutating this union. Try: `rawData = Sheets(\"Raw\").Range(Union(\"E2:E1000\", \"G2:G1000\", \"C2:C1000\", \"B2:B1000\", \"L2:L1000\")).Value`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T21:26:04.180",
"Id": "210187",
"ParentId": "210120",
"Score": "0"
}
},
{
"body": "<h2>Editor Options</h2>\n\n<p>The first thing that I would recommend is adjusting your VBEditor options.</p>\n\n<p>Checking <code>Require Variable Declaration</code> will automatically put <code>Option Explicit</code> at the top of newly created code modules. This makes it easier to clean up code as you modify it and catch undeclared variables, such as, <code>PropRow</code>.</p>\n\n<p>Unchecking <code>Auto Syntax Check</code> will prevent the <code>Syntax Error</code> MsgBox from appearing will you are writing your code. You will still know that there is a syntax error because the text is red but you will not have to stop to click the message.</p>\n\n<p><a href=\"https://i.stack.imgur.com/D25Kl.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/D25Kl.png\" alt=\"VBE Options\"></a></p>\n\n<p>Download <a href=\"https://rubberduckvba.wordpress.com/2017/10/25/userform1-show/\" rel=\"nofollow noreferrer\">Rubberduck VBA: UserForm1.Show</a> and use it's code formatting tool. This tool will not only save a ton of time in formatting but will help catch unclosed blocks of code.</p>\n\n<h2>Data Typing</h2>\n\n<p>Using the correct data type is crucial to writing solid code. It will prevent unintended bugs from creeping in and improve the overall performance of the code. <code>TheDay</code> should be typed as Long because it will always be an Integer. Note: There is no advantage to using a smaller data type, such as: Byte or Integer. It looks like <code>TheUnit</code> should probably be long also bit that might because of the dummy data.</p>\n\n<h2>Dynamic Ranges</h2>\n\n<p>Using Dynamic Ranges <code>Range(\"E2\", Range(\"E\" & Rows.Count).End(xlUp))</code> over staatic ranges <code>Set StartDate = Range(\"E2:E1000\")</code> will prevent you from having to update the code as rows are added and optimize the code as the rows are deleted.</p>\n\n<h2>Loops</h2>\n\n<p>If you are going to iterate over each cells in the range then you should use the <code>Cell</code> object. Resolving the <code>Cell</code> is not free. It is causing the CPU to do extra work.</p>\n\n<blockquote>\n<pre><code>For Each Cell In startDate\n</code></pre>\n</blockquote>\n\n<p>Here is how you should use this loop:</p>\n\n<blockquote>\n<pre><code> Set dateStartCell = Cell.Offset(0, 4).Value\n Set dateEndCell = Cell.Offset(0, 6).Value\n</code></pre>\n</blockquote>\n\n<p>Otherwise just use a standard <code>For Loop</code>.</p>\n\n<blockquote>\n<pre><code>For r = 2 to Range(\"E\" & Rows.Count).End(xlUp).Row\n</code></pre>\n</blockquote>\n\n<p>In many cases it makes sense to have another function return a collection and iterate over it. After all, the fewer tasks that a subroutine performs the easier it is to test. This is not one of those cases.</p>\n\n<blockquote>\n<pre><code>For Each currentDateSter In allDates\n</code></pre>\n</blockquote>\n\n<p>Basically, all the collection is used for is to start an iteration at the start date and add 1 to until you reach the end date. Not only can this be accomplished a lot cheaper by using a standard <code>For Loop</code> but it makes the more condense and easier to read.</p>\n\n<blockquote>\n<pre><code>For dateOf = dateStartCell.Value to dateEndCell.Value\n</code></pre>\n</blockquote>\n\n<h2>Selecting and Activating</h2>\n\n<p>It is rarely necessary to <code>Select</code> or <code>Activate</code> an Object. It is much better to fully qualify your Objects and refer to them directly. This is the biggest slow down in your code. </p>\n\n<p>Watch: <a href=\"https://www.youtube.com//watch?v=c8reU-H1PKQ&index=5&list=PLNIs-AWhQzckr8Dgmgb3akx_gFMnpxTN5\" rel=\"nofollow noreferrer\">Excel VBA Introduction Part 5 - Selecting Cells (Range, Cells, Activecell, End, Offset)</a></p>\n\n<h2>If Statements</h2>\n\n<p>I prefer to make direct boolean assignments over the bulkier <code>If</code> blocks.</p>\n\n<blockquote>\n<pre><code>Test1 = TheDay = Day(currentDate) And TheUnit = Unit\nTest2 = TheDay = TheUnit\n</code></pre>\n</blockquote>\n\n<p><code>Test2</code> is misleading. Its true function is to test whether or not <code>Cells(AdvRow, 2)</code> is empty.</p>\n\n<p><code>Test1</code> and <code>Test2</code> are not very descriptive names. I would prefer <code>dataMatched</code> and <code>emtpyRow</code> but would have eliminated both variables by using the code below.</p>\n\n<blockquote>\n<pre><code>Loop Until (TheDay = Day(currentDate) And TheUnit = Unit) Or Cells(AdvRow, 2) = \"\"\n</code></pre>\n</blockquote>\n\n<h2>Raw Data: Deleted Rows</h2>\n\n<p>Deleted rows in the Raw Data will not reflect in the monthly reports. This could lead to big problems and should be addressed.</p>\n\n<h2>Refactored Code</h2>\n\n<p>This code ran 95% faster the the original. The code could further be improved by using arrays for each month's data but that is way outside the scope of this website.</p>\n\n<pre><code>Sub Program2()\n Dim t As Double: t = Timer\n Application.ScreenUpdating = False\n Application.Calculation = xlCalculationManual\n\n Dim data As Variant\n With Worksheets(\"Raw\") 'Load the data into an Array\n data = .Range(\"A2:N2\", .Cells(.Rows.Count, \"E\").End(xlUp)).Value\n End With\n\n Dim dateOf As Date\n Dim r1 As Long\n\n For r1 = 1 To UBound(data)\n For dateOf = data(r1, 5) To data(r1, 7)\n Dim wsMonth As Worksheet, wsName As String\n\n If wsName <> Format(dateOf, \"mmmyyyy\") Then\n wsName = Format(dateOf, \"mmmyyyy\")\n Set wsMonth = Worksheets(wsName)\n End If\n\n With wsMonth\n Dim r2 As Long\n For r2 = 4 To .Cells(.Rows.Count, \"A\").End(xlUp).Row + 1\n Dim TheDay As Long\n Dim TheUnit As Long\n Dim Pax As String\n TheDay = Day(dateOf)\n TheUnit = data(r1, 2)\n Pax = data(r1, 12)\n If (.Cells(r2, 1).Value = TheDay And .Cells(r2, 2).Value = TheUnit) Then\n .Cells(r2, 3).Value = Pax\n Exit For\n ElseIf .Cells(r2, \"A\").Value = \"\" Then\n .Cells(r2, 1).Value = TheDay\n .Cells(r2, 2).Value = TheUnit\n .Cells(r2, 3).Value = Pax\n Exit For\n End If\n Next\n End With\n Next\n Next\n Application.Calculation = xlCalculationAutomatic\n Application.ScreenUpdating = True\n Debug.Print Round(Timer - t, 2)\nEnd Sub\n</code></pre>\n\n<h2>Addendum</h2>\n\n<p>In order to speed up the code I would use arrays to write the data to each month in one operation and dictionaries because of their lightning fast look-up speed. These references will help:</p>\n\n<ul>\n<li><a href=\"https://www.youtube.com//watch?v=dND4coLI_B8&index=43&list=PLNIs-AWhQzckr8Dgmgb3akx_gFMnpxTN5\" rel=\"nofollow noreferrer\">Excel VBA Introduction Part 39 - Dictionaries</a></li>\n<li><a href=\"https://www.youtube.com//watch?v=h9FTX7TgkpM&index=28&list=PLNIs-AWhQzckr8Dgmgb3akx_gFMnpxTN5\" rel=\"nofollow noreferrer\">Excel VBA Introduction Part 25 - Arrays</a></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T14:31:59.397",
"Id": "406318",
"Score": "0",
"body": "`Loop Until (TheDay = Day(currentDate) And TheUnit = Unit) Or Cells(AdvRow, 2) = \"\"`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T14:41:29.640",
"Id": "406321",
"Score": "0",
"body": "LOL, sorry, Newb, hit enter and was going to go into edit. I was meaning to say thank you for you time, but most importantly, I especially appreciate the explanation of the thought process and the references to assist. I only started playing with VBA a couple of weeks ago, so the language and syntax rules I am still trying to learn as I put together this project that will save me tons of time!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T14:49:23.473",
"Id": "406322",
"Score": "0",
"body": "I did have to change `theunit` to a string due to `error 13` (which I am becoming very familiar with!), When I data cleansed, I went for simple versus helpful, my apologies. On `arrays` would you have a suggestion of any good references? Also, this code ran in `1/4` of the time I had. Next is to move it to the computer it will run on, that is where the biggest issues is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T14:50:12.060",
"Id": "406323",
"Score": "0",
"body": "I cannot up vote your post as I am a NEWB, not enough points."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T15:08:20.993",
"Id": "406327",
"Score": "0",
"body": "`Raw Data: Deleted Rows` the rows that I am not writing (where the `theday = day` and `theunit = unit`) is because I will right the facility out to the right on the same row, so as it goes through each iteration, `if` `theday` `and` `theunit` exist, the difference will be the `facility` which will fill in the information to the right. I thought this to be easier than looking to right everything and then collapse it later."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T15:47:44.290",
"Id": "406332",
"Score": "0",
"body": "@JonDee the problem I see with the setup is if you discover a typo in `Raw` after you run the code. Now you not only have to fix the typo in both `Raw` and the monthly worksheets manually."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T15:54:21.440",
"Id": "406334",
"Score": "0",
"body": "The reason that strong data typing is so crucial is that we want the errors to show up during testing. `Data type mismatch` errors are a strong code smell. They're signs that there are errors in the logic that should be fixed for good not patched. It's much easier to to handle errors early in the developmental process then when an end user finds it later."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T15:56:03.097",
"Id": "406335",
"Score": "0",
"body": "I modified my code setting `Application.Calculation = xlCalculationManual` while its running. This will make a huge difference if you have a lot of formulas in the workbook."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T16:05:02.307",
"Id": "406338",
"Score": "0",
"body": "@JonDee I will try and write some pseudo code Thursday to help you take it to the next level. Excellent first project. Thanks for accepting my answer. +1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-28T21:26:48.450",
"Id": "406950",
"Score": "0",
"body": "Solid on the review, suggestions, and code improvement. Ran this on the computer it will run on. Previous time ~5.5 minutes, now, 5.25 seconds (the in program timer is cool and now I know how to do that). With the resources, suggestions and so forth, I imagine that my next piece of this program will be spot on. Stepped back to look at the parts that run into this piece to improve them as well. Thanks brother!"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T12:26:57.703",
"Id": "210218",
"ParentId": "210120",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "210218",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T14:05:39.953",
"Id": "210120",
"Score": "1",
"Tags": [
"performance",
"vba",
"excel"
],
"Title": "Tab month tracker"
} | 210120 |
<p>I've stopped programming in Python for a long time now, someone recommended to me that the best way to get into it is by trying to code a game of Hangman, and that's what I did. Or tried to, at least.</p>
<pre><code>import random
class Game:
def __init__(self, game_word):
self.game_word = game_word
class Player:
def __init__(self, guessed_word, guess_count, used_letters):
self.guess_count = guess_count
self.guessed_word = guessed_word
self.used_letters = used_letters
def get_word(): # getting a word from a txt file with a list of single words
word_file = open("words.txt")
game_word = random.choice(word_file.readlines())
game_word = game_word.strip().lower()
word_file.close()
return game_word
def user_guess(game, player):
print("Enter a letter: ")
letter = input().lower()
if check_input(letter, player.used_letters) == 0: # if check_input is 0 then there are no errors in player input
if letter in game.game_word: # determining if the guessed letter in the word
for i in range(0, len(game.game_word)):
if letter == game.game_word[i]:
player.guessed_word[i] = letter # replacing the '-' in the player's "guessed_word" with the letter
player.used_letters.append(letter)
else:
player.guess_count -= 1 # letter is not in the word, so player loses a life
player.used_letters.append(letter)
def check_input(letter, used_letters): # Just some error checking
if letter in used_letters:
print("Already guessed using this letter, try again with a different one!")
return 1
elif not letter.isalpha():
print("Only alphabets allowed!")
return 1
elif len(letter) > 1:
print("Only one character allowed per guess")
return 1
return 0
def game_round(game, player):
print("".join(player.guessed_word))
print("Letters used: " + " ".join(player.used_letters))
print("Number of tries left: " + str(player.guess_count))
user_guess(game, player)
def game_init():
guessed_word = list() # what the user guesses so far
used_letters = list() # used_letters will be used to store all the letters the player inputs throughout the game
game_word = get_word() # get a random word from a text file
for i in range(len(game_word)): # Print '-' for each letter in the word by default
guessed_word.append("-")
guess_count = int(input("Set the maximum number of guesses that you want\n"
"Number of guesses(lives): "))
return Game(game_word), Player(guessed_word, guess_count, used_letters)
def end_condition(game, player):
if "-" not in player.guessed_word: # if there are no more '-' then it means the user guessed the whole word
print("".join(player.guessed_word))
print("Game won!")
return True
elif player.guess_count == 0: # no more guesses remain
print("The correct word is \'" + game.game_word + "\'")
print("Game lost!")
return True
return False
def retry():
choice = input("Would you like to play again? Press \'y\' to start over\nNew round: ")
if choice == "y":
return True
return False
def main():
input("Press \"Enter\" to start the game\n")
while True:
game, player = game_init()
while True:
game_round(game, player) # player makes a guess
if not end_condition(game, player): # if game not over, player makes another guess
continue
break
if retry(): # start new game
continue
break
print("Game Over!")
if __name__ == "__main__":
main()
</code></pre>
<p>I feel like this could be improved more since I've done a similar version where everything was in the main function, and it was half as long.</p>
<pre><code>import random
def main():
input("Press \"Enter\" to start the game\n")
while True:
word_file = open("words.txt")
game_word = random.choice(word_file.readlines())
game_word = game_word.strip().lower()
word_file.close()
guessed = list()
used_letters = list()
for i in range(len(game_word)):
guessed.append("-")
count = 10
while True:
print("".join(guessed))
print("Letters used: " + " ".join(used_letters))
print("Number of tries left: " + str(count))
print("Enter a letter: ")
letter = input().lower()
if letter in used_letters:
print("Already guessed using this letter, try again with a different one!")
continue
elif not letter.isalpha():
print("Only alphabets allowed!")
continue
elif len(letter) > 1:
print("Only one character allowed per guess")
continue
elif letter in game_word:
for i in range(0, len(game_word)):
if letter == game_word[i]:
guessed[i] = letter
else:
count -= 1
used_letters.append(letter)
if "-" not in guessed:
print("".join(guessed))
print("Game won!")
game_over = True
break
elif count == 0:
print("The correct word is \'" + game_word + "\'")
print("Game lost!")
game_over = True
break
if game_over:
choice = input("Would you like to play again? Press \'y\' to start over\nNew round: ")
if choice == "y":
continue
else:
break
print("Game Over!")
if __name__ == "__main__":
main()
</code></pre>
<p>The <a href="https://pastebin.com/iEV6RFzS" rel="nofollow noreferrer">words text file</a>. In case the link doesn't work, the text file is just single-words separated by a new line.</p>
| [] | [
{
"body": "<p>In this code:</p>\n\n<pre><code>def __init__(self, guessed_word, guess_count, used_letters):\n self.guess_count = guess_count\n self.guessed_word = guessed_word\n self.used_letters = used_letters\n</code></pre>\n\n<p><code>used_letters</code> should not be passed as an argument, nor should it be constructed as a <code>list</code> in <code>game_init</code>. Just construct it in <code>__init__</code>. Also, it should be a <code>set</code> instead of a <code>list</code> for efficiency.</p>\n\n<p>Similarly, rather than <code>guessed_word</code> being initialized in <code>game_init</code>, it should be initialized in <code>Player.__init__</code>. You can pass <code>game_word</code> to <code>__init__</code>, and then in there, you can write</p>\n\n<pre><code>guessed_word = '-' * len(game_word)\n</code></pre>\n\n<p>As for <code>guess_count</code>, the name is a little confusing, because it isn't strictly \"guess count\", but rather \"remaining guesses\".</p>\n\n<p>This:</p>\n\n<pre><code>if choice == \"y\":\n return True\nreturn False\n</code></pre>\n\n<p>can be abbreviated to</p>\n\n<pre><code>return choice == 'y'\n</code></pre>\n\n<p>but you should also convert <code>choice</code> to lowercase before doing that comparison.</p>\n\n<p>This loop:</p>\n\n<pre><code> while True:\n game_round(game, player) # player makes a guess\n if not end_condition(game, player): # if game not over, player makes another guess\n continue\n break\n</code></pre>\n\n<p>can be abbreviated to</p>\n\n<pre><code>while not end_condition(game, player):\n game_round(game, player)\n</code></pre>\n\n<p>These lines:</p>\n\n<pre><code>print(\"\".join(player.guessed_word))\nprint(\"Letters used: \" + \" \".join(player.used_letters))\nprint(\"Number of tries left: \" + str(player.guess_count))\n</code></pre>\n\n<p>should be moved to a method of <code>Player</code>, perhaps called <code>print_round</code>.</p>\n\n<p>This:</p>\n\n<pre><code>word_file = open(\"words.txt\")\ngame_word = random.choice(word_file.readlines())\ngame_word = game_word.strip().lower()\nword_file.close()\n</code></pre>\n\n<p>should have <code>word_file</code> in a <code>with</code> statement, rather than an explicit close.</p>\n\n<p>More generally, you're using <code>Game</code> and <code>Player</code> as C struct-like objects with no methods. You should make an attempt to convert them to true classes with methods on the objects, rather than global methods that operate on the class member variables.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T17:07:32.067",
"Id": "210130",
"ParentId": "210129",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "210130",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T16:51:00.923",
"Id": "210129",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"hangman"
],
"Title": "Basic Hangman using Python"
} | 210129 |
<p>I have the following code snippet, which essentially does the following:
Given a 2d numpy array, <code>arr</code>, compute <code>sum_arr</code> as follow:
<span class="math-container">$$sum\_arr[i, j] = \begin{cases}
arr[i, j] + min(sum\_arr[i - 1, j-1:j+2]), &i > 0\\ arr[i, j], &i = 0\end{cases}$$</span>
(reasonable indices for <code>j - 1 : j + 2</code> of course, all within <code>0</code> and <code>w</code>) </p>
<p>Here's my implementation:</p>
<pre><code>import numpy as np
h, w = 1000, 1000 # Shape of the 2d array
arr = np.arange(h * w).reshape((h, w))
sum_arr = arr.copy()
def min_parent(i, j):
min_index = j
if j > 0:
if sum_arr[i - 1, j - 1] < sum_arr[i - 1, min_index]:
min_index = j - 1
if j < w - 1:
if sum_arr[i - 1, j + 1] < sum_arr[i - 1, min_index]:
min_index = j + 1
return (i - 1, min_index)
for i, j in np.ndindex((h - 1, w)):
sum_arr[i + 1, j] += sum_arr[min_parent(i + 1, j)]
</code></pre>
<p>And here's the problem: this code snippet takes way too long to execute for only 1e6 operations (About 5s on average on my machine)</p>
<p>What is a better way of implementing this?</p>
| [] | [
{
"body": "<ul>\n<li>first, your problem is example of <a href=\"https://en.wikipedia.org/wiki/Dynamic_programming\" rel=\"nofollow noreferrer\">dynamic programming</a>. <a href=\"https://stackoverflow.com/questions/50974371/efficient-dynamic-programming-using-python\">Here some tips</a> how to approach problem in python</li>\n<li>your solution calculate each table cell separately. But function <code>min_parent()</code> use data only from previous row, so you can calculate row by row (and <code>numpy</code> is designed to fast operations on vectors)</li>\n<li>i am using like you range <code><j - 1 : j + 2)</code> but check if task don't need <code><j - 1, j + 2></code></li>\n</ul>\n\n<p>Example code</p>\n\n<pre><code>\nassert(w >= 2) # if not, you should handle w == 1 in special way\n\ndef vectorized_solution(arr, h):\n sum_arr = arr.copy()\n for i in range(1, h):\n parent = sum_arr[i - 1, :]\n sum_arr[i, 0] += min(parent[0], parent[1])\n sum_arr[i, 1:-1] += np.minimum.reduce([parent[0:-2], parent[1:-1], parent[2:]])\n sum_arr[i, -1] += min(parent[-2], parent[-1])\n return sum_arr\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T06:41:01.120",
"Id": "406204",
"Score": "0",
"body": "Storing parent seems unnecessary given we could replace `parent[j]` with `sum_arr[i - 1, j]`. Also a (slightly, just about 0.04s for h, w = 1000 in the given code) faster vectorization could be found here: https://stackoverflow.com/questions/53889590/calls-to-constant-time-function-iterating-through-numpy-array-results-in-very-sl/53890258#53890258"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T02:20:28.197",
"Id": "210152",
"ParentId": "210132",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "210152",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T17:42:27.350",
"Id": "210132",
"Score": "8",
"Tags": [
"python",
"performance",
"python-3.x",
"numpy"
],
"Title": "Cumulative sum of the smallest neighbors in the previous row in a Numpy array"
} | 210132 |
<p>I was trying to implement the algorithm of the 3D well-separated pair decomposition <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.94.9691&rep=rep1&type=pdf" rel="nofollow noreferrer">WSPD</a> using an <a href="https://en.wikipedia.org/wiki/Octree" rel="nofollow noreferrer">octree</a>. </p>
<p>First, I begin by implementing the class <code>OctreeNode</code> as follows:</p>
<pre><code>public class OctreeNode {
public static final int BSW = 0;
public static final int BSE = 1;
public static final int BNW = 2;
public static final int BNE = 3;
public static final int ASW = 4;
public static final int ASE = 5;
public static final int ANW = 6;
public static final int ANE = 7;
public int level = 0; // level set to 0.
public OctreeNode[] children = null;
public OctreeNode father = null; // father is null
public Point_3 p = null; //point stored in a leaf
public Point_3 center = null; // point to define the center of the box of the node.
public double height = 0.0, width = 0.0, depth = 0.0;
</code></pre>
<p>Every non-leaf Node has exactly 8 children. I implement a constructor for the class which takes a list of points in 3D.</p>
<pre><code>/**
* Create the octree for storing an input point cloud.
*/
public OctreeNode(List<Point_3> points) {
// We construct the octree only for non empty point cloud.
assert(points.size() > 0);
/**
* We start by computing a box containing the point cloud.
*/
// The minimum value of x,y,z in the point cloud.
double minX = points.get(0).getX().doubleValue();
double minY = points.get(0).getY().doubleValue();
double minZ = points.get(0).getZ().doubleValue();
// The maximum value of x,y,z in the point cloud.
double maxX = points.get(0).getX().doubleValue();
double maxY = points.get(0).getY().doubleValue();
double maxZ = points.get(0).getZ().doubleValue();
for(Point_3 point : points) {
// update the minimum.
if(minX > point.getX().doubleValue()) {
minX = point.getX().doubleValue();
}
// update the minimum.
if(minY > point.getY().doubleValue()) {
minY = point.getY().doubleValue();
}
// update the minimum.
if(minZ > point.getZ().doubleValue()) {
minZ = point.getZ().doubleValue();
}
// update the maximum.
if(maxX < point.getX().doubleValue()) {
maxX = point.getX().doubleValue();
}
// update the maximum.
if(maxY < point.getY().doubleValue()) {
maxY = point.getY().doubleValue();
}
// update the maximum.
if(maxZ < point.getZ().doubleValue()) {
maxZ = point.getZ().doubleValue();
}
}
this.center = new Point_3((minX + maxX) / 2, (minY + maxY) / 2, (minZ + maxZ) / 2);
this.width = 0.75*(maxX - minX);
this.height = 0.75*(maxY - minY);
this.depth = 0.75*(maxZ - minZ);
for(Point_3 point : points) {
this.add(point);
}
}
</code></pre>
<p>After, I implement the add function of my class:</p>
<pre><code>/**
* @return true if the current node is a leaf.
*/
public boolean isLeaf() {
return (this.children == null);
}
/**
* @return true if the current node is empty.
*/
public boolean isEmpty() {
return (this.children == null && this.p == null);
}
/**
* @return true if the current node is single point.
*/
public boolean isSinglePoint() {
return (this.children == null && this.p != null);
}
/**
* @param o an Object.
* @return true if the current node is equals to o
*/
@Override
public boolean equals(Object o) {
OctreeNode n = (OctreeNode) o;
return (n != null) && (this.center.equals(n.center));
}
/**
* @return the diameter of the node : 0 if is empty or single point and the diameter of the box otherwise.
*/
public double diam() {
if(this.isLeaf()) {
return 0.0;
}
return 2*Math.sqrt(this.width*this.width
+ this.height*this.height
+ this.depth*this.depth);
}
/**
* Check if the point is in the boundary of the OctreeNode
* @param p a Point_3.
* @return true if p is in the cube of the OctreeNode
*/
public boolean inBoundary(Point_3 p) {
Vector_3 v = (Vector_3) this.center.minus(p);
return (Math.abs(v.getX().doubleValue()) <= this.width && Math.abs(v.getY().doubleValue()) <= this.height && Math.abs(v.getZ().doubleValue()) <= this.depth);
}
/**
* Add a node into the OctreeNode
*/
public void add(Point_3 p) {
assert(this.center != null);
if(!this.inBoundary(p))
return;
// Check if the current node is a leaf.
if(this.isLeaf()) {
// Check if the current node is empty.
if(this.isEmpty()) {
this.p = p;
return;
}
else {
// Check if the node contains the same point already.
if(this.p.equals(p)) {
return;
}
// The current node contains only one point and the new point
// is different from the point of the current OctreeNode.
// We create the set of children for the current OctreeNode.
this.children = new OctreeNode[8];
// Initialize the children.
for(int i = 0; i < 8; i++) {
this.children[i] = new OctreeNode();
}
// For all children we put the current OctreeNode as father and
// we increment the level.
for(OctreeNode child : this.children) {
child.father = this;
child.level = this.level + 1;
}
// We compute then the center points for every child
Vector_3 vi = new Vector_3(this.width / 2, 0.0, 0.0);
Vector_3 vj = new Vector_3(0.0, this.height / 2, 0.0);
Vector_3 vk = new Vector_3(0.0, 0.0, this.depth / 2);
this.children[BSW].center = this.center.sum(vk.opposite()).sum(vj.opposite()).sum(vi.opposite());
this.children[BSE].center = this.center.sum(vk.opposite()).sum(vj.opposite()).sum(vi);
this.children[BNW].center = this.center.sum(vk.opposite()).sum(vj).sum(vi.opposite());
this.children[BNE].center = this.center.sum(vk.opposite()).sum(vj).sum(vi);
this.children[ASW].center = this.center.sum(vk).sum(vj.opposite()).sum(vi.opposite());
this.children[ASE].center = this.center.sum(vk).sum(vj.opposite()).sum(vi);
this.children[ANW].center = this.center.sum(vk).sum(vj).sum(vi.opposite());
this.children[ANE].center = this.center.sum(vk).sum(vj).sum(vi);
// We put half of the dimensions of the cube for every child.
for(OctreeNode child : children) {
child.width = this.width / 2;
child.depth = this.depth / 2;
child.height = this.height / 2;
}
// Look for the child to add the point of the current OctreeNode.
for(OctreeNode child : children) {
if(child.inBoundary(this.p)) {
child.add(this.p);
break;
}
}
// Look for the child to add the point p.
for(OctreeNode child : children) {
if(child.inBoundary(p)) {
child.add(p);
break;
}
}
// this.p = null;
}
}
else {
// Look for the child to add the point p.
for(OctreeNode child : children) {
if(child.inBoundary(p)) {
child.add(p);
break;
}
}
}
}
</code></pre>
<p>I also implement a function distance to compute the distance between two nodes in the <code>Octree</code> which is the distance between the two boxes of the nodes:</p>
<pre><code>/**
* @param o an OctreeNode.
* @param u an OctreeNode.
* @return the distance between the two nodes.
*/
public static double distance(OctreeNode o, OctreeNode u) {
if(o == null || o.isEmpty() || u == null || u.isEmpty()) {
return 0.0;
}
if(u.isLeaf() && o.isLeaf()) {
return u.p.distanceFrom(o.p).doubleValue();
}
double x = 0.0;
double y = 0.0;
double z = 0.0;
Vector_3 v;
if(u.isLeaf()) {
v = (Vector_3) u.p.minus(o.center);
x = Math.min(Math.abs(v.getX().doubleValue()) - o.width, 0.0);
y = Math.min(Math.abs(v.getX().doubleValue()) - o.height, 0.0);
z = Math.min(Math.abs(v.getX().doubleValue()) - o.depth, 0.0);
return Math.sqrt(x*x + y*y + z*z);
}
if(o.isLeaf()) {
return distance(u, o);
}
v = (Vector_3) u.center.minus(o.center);
x = Math.min(Math.abs(v.getX().doubleValue()) - o.width - u.width, 0.0);
y = Math.min(Math.abs(v.getX().doubleValue()) - o.height - u.height, 0.0);
z = Math.min(Math.abs(v.getX().doubleValue()) - o.depth - u.depth, 0.0);
return Math.sqrt(x*x + y*y + z*z);
}
}
</code></pre>
<p>Now, I implement the class Octree representing and Octree</p>
<pre><code>public class Octree {
public OctreeNode root;
/**
* Create an octree from the array points.
*/
public Octree(Point_3[] points){
/**
* We use the constructor provided by the class OctreeNode to
* construct the root.
*/
this.root = new OctreeNode(Arrays.asList(points));
}
}
</code></pre>
<p>Here I have a question. Do you think my implementation is the best way to do it?</p>
<p>After this part I implement the well-separated pair decomposition class:</p>
<pre><code>public class WellSeparatedPairDecomposition {
class Pair<X,Y> {
X x; Y y;
Pair(X xx, Y yy) {
x = xx;
y = yy;
}
public X getFirst() {
return x;
}
public Y getSecond() {
return y;
}
@Override
public boolean equals(Object o) {
Pair<X,Y> p = (Pair<X,Y>) o;
return (p!=null && p.getFirst() == x && p.getSecond() == y);
}
}
/**
* Compute the WSPD from an octree and a threshold s.
* @param T the Octree,
* @param s threshold.
* @return the pairs of WSPD.
*/
public OctreeNode[][] wspd (Octree T, double epsilon) {
Set<Pair<OctreeNode, OctreeNode>> H = new HashSet<Pair<OctreeNode, OctreeNode>>();
wspd(T.root, T.root, epsilon, H);
int n = H.size();
OctreeNode[][] result = new OctreeNode[n][2];
int i = 0;
for(Pair<OctreeNode, OctreeNode> pair : H) {
result[i][0] = pair.getFirst();
result[i][1] = pair.getSecond();
i++;
}
return result;
}
boolean isWS(OctreeNode u, OctreeNode v, double epsilon) {
if(u == null || v == null || u.isEmpty() || v.isEmpty()) {
return false;
}
double distance = OctreeNode.distance(u, v);
return (u.diam() < epsilon*distance && v.diam() < epsilon*distance);
}
void wspd(OctreeNode u, OctreeNode v, double epsilon, Set<Pair<OctreeNode, OctreeNode>> H) {
if(u.isEmpty() || v.isEmpty() || (v.isLeaf() && u.isLeaf() && v.equals(u)))
return;
if(isWS(u, v, epsilon)) {
H.add(new Pair<OctreeNode, OctreeNode>(u, v));
return;
}
if(u.level > v.level) {
OctreeNode temp = u;
u = v;
v = temp;
}
if(!u.isLeaf()) {
for(OctreeNode uchild : u.children) {
wspd(uchild, v, epsilon, H);
}
}
}
}
</code></pre>
<p>My implementation works without errors. However, when I tested, it is very slow and for big size tests it gives an <code>outOfMemoryError</code>. How can I improve this implementation?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T21:23:05.007",
"Id": "406169",
"Score": "1",
"body": "The lack of indentation makes parts of the code hard to follow."
}
] | [
{
"body": "<p>Overall the code is okay but can definitely be improved.</p>\n\n<p>Some things I would however change.</p>\n\n<p>Instead of writing short variable names and then explaining them in comments, a better approach is to have \"self-documenting code\". What this means is to make your variables descriptive enough to convey to the reader what they represent.</p>\n\n<p>An example is in your method</p>\n\n<pre><code>/**\n * @param o an OctreeNode.\n * @param u an OctreeNode.\n * @return the distance between the two nodes.\n */\npublic static double distance(OctreeNode o, OctreeNode u) {\n</code></pre>\n\n<p>Here you can simply use firstNode and secondNode since we are returning the distance between them.</p>\n\n<p>Here is another example:</p>\n\n<pre><code>/**\n* Compute the WSPD from an octree and a threshold s.\n* @param T the Octree,\n* @param s threshold.\n* @return the pairs of WSPD.\n*/\npublic OctreeNode[][] wspd (Octree T, double epsilon) {\n</code></pre>\n\n<p>Here the T would be better called a tree, or the threshold would be better called exactly that, the threshold. Also, I don't see the parameter you mentioned passed into the function (possibly a bug)?</p>\n\n<pre><code>Pair(X xx, Y yy) {\n x = xx;\n y = yy;\n }\n</code></pre>\n\n<p>Here I would change xx and yy, as they could be better represented with a different variable name.</p>\n\n<p>Over here, what are these nodes?</p>\n\n<pre><code>OctreeNode u, OctreeNode v\n</code></pre>\n\n<p>It would be preferred to describe them, so that it's easier to see what's going on when you use these variables throughout your code.</p>\n\n<pre><code>@param p a Point_3.\n</code></pre>\n\n<p>Why is a <code>Point_3</code> here is the only object which has an underscore? You want to pick a naming style and consistently use it. Inconsistency in code leads to possible subtle bugs down the road - along with difficulty for an outside reader to follow it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-26T06:51:38.397",
"Id": "210343",
"ParentId": "210138",
"Score": "1"
}
},
{
"body": "<p>You should make an attempt to vectorize much of your code. It's an important way to re-think your code in terms that allow for computers to efficiently execute SIMD (single-instruction multiple-data) and achieve massive speedup as compared to naive implementations. There are many libraries to allow you to vectorize your code. So far the most promising-looking one (caveat: I haven't tried it) seems to be <a href=\"http://jblas.org/\" rel=\"nofollow noreferrer\">JBLAS</a>.</p>\n\n<p>Specifically, this:</p>\n\n<pre><code>double minX = points.get(0).getX().doubleValue();\ndouble minY = points.get(0).getY().doubleValue();\ndouble minZ = points.get(0).getZ().doubleValue();\n</code></pre>\n\n<p>should be represented by one vector, and this:</p>\n\n<pre><code>double maxX = points.get(0).getX().doubleValue();\ndouble maxY = points.get(0).getY().doubleValue();\ndouble maxZ = points.get(0).getZ().doubleValue();\n</code></pre>\n\n<p>should be represented by one vector. This loop:</p>\n\n<pre><code>for(Point_3 point : points) {\n\n // update the minimum.\n // ...\n</code></pre>\n\n<p>should not exist at all, and you should be calling a vectorized routine instead.</p>\n\n<p>Similar to the above, this:</p>\n\n<pre><code>this.width = 0.75*(maxX - minX);\nthis.height = 0.75*(maxY - minY);\nthis.depth = 0.75*(maxZ - minZ);\n</code></pre>\n\n<p>should not be represented by three separate members, nor should you be repeating the same operation three times. Instead, represent it as one vector perhaps called <code>this.size</code>.</p>\n\n<p>This:</p>\n\n<pre><code>public double diam() {\n if(this.isLeaf()) {\n return 0.0;\n }\n return 2*Math.sqrt(this.width*this.width + \n this.height*this.height + \n this.depth*this.depth);\n}\n</code></pre>\n\n<p>is you rolling your own Euclidean norm, which you shouldn't do. BLAS has functions for this. Similar vectorization should be done elsewhere in your code, such as <code>inBoundary</code>. This:</p>\n\n<pre><code>for(OctreeNode child : children) {\n child.width = this.width / 2;\n child.depth = this.depth / 2;\n child.height = this.height / 2;\n}\n</code></pre>\n\n<p>should treat every child's size as a single vector rather than separate components. You should also compute <code>this.size / 2</code> outside of the loop. It may even be possible to represent <code>children</code> as a matrix with each row representing a child and the columns representing <code>x</code>, <code>y</code> and <code>z</code> respectively, which would eliminate the need for a loop altogether.</p>\n\n<p>Along the same lines, <code>distance</code> can be greatly tightened up by dealing with vectors rather than individual components, particularly lines like these:</p>\n\n<pre><code>x = Math.min(Math.abs(v.getX().doubleValue()) - o.width - u.width, 0.0);\ny = Math.min(Math.abs(v.getX().doubleValue()) - o.height - u.height, 0.0);\nz = Math.min(Math.abs(v.getX().doubleValue()) - o.depth - u.depth, 0.0);\nreturn Math.sqrt(x*x + y*y + z*z);\n</code></pre>\n\n<p>This can be done in one line of vectorized code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-29T03:16:35.163",
"Id": "210538",
"ParentId": "210138",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T20:38:37.263",
"Id": "210138",
"Score": "3",
"Tags": [
"java",
"tree"
],
"Title": "Java implementation of well-separated pair decomposition"
} | 210138 |
<p>I'm new to React and started this project as a sandbox to experiment with it. I implemented a main page wich has a header and some content. The content is selected on the header. I'm wondering how it stands on the react best practices and other ways it could be implemented.</p>
<p>On the main app, we hold as state the index of the content we want to show, and we pass to the header as a property a reference to the funtion that handles the index state, like so</p>
<pre><code> class App extends Component {
constructor() {
super();
this.state = {
cidx: 0,
//content:[<Heroes/>, <Teams/>]
}
this.updateContent = this.updateContent.bind(this);
this.getContent = this.getContent.bind(this);
}
updateContent(idx) {
this.setState({cidx:idx});
}
getContent() {
//return this.state.content[this.state.cidx];
switch(this.state.cidx) {
case 0:
return <Heroes/>
case 1:
return <Teams/>
}
}
render() {
const Content = this.getContent();
return (
<div>
<Header updateContent={this.updateContent} textItems={["Heroes", "Teams"]}/>
{Content}
</div>
);
}
}
export default App;
</code></pre>
<p>Like that we can inject the content in our render function based on user interaction with the header. I used a switch statement in getContent to avoid having an array of objects in memory all the time. Is it actually better performance-wise ?</p>
<p>This is the header code </p>
<pre><code>class Header extends Component {
constructor(props) {
super(props);
}
render() {
const items = this.props.textItems.map(
(item, index)=>{
return <NavItem key={index} onClick={()=>{this.props.updateContent(index)}}>{item}</NavItem>
}
);
return (
<div className="App">
<Navbar className="deep-purple" brand='Dota Wizard' right>
{items}
</Navbar>
</div>
);
}
}
export default Header;
</code></pre>
<p>A working version of the project is found on <a href="https://glitch.com/~absorbing-buzzard" rel="nofollow noreferrer">https://glitch.com/~absorbing-buzzard</a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T08:59:09.990",
"Id": "406217",
"Score": "0",
"body": "Welcome to Code Review. As far as I can see, there are some JSX elements missing at the moment, for example `Navbar`, `Heroes` and `Teams`. Even if they're not required, a short description of those can help reviewers."
}
] | [
{
"body": "<h1>Quick review.</h1>\n<p>This is a very basic review as I am not a react fan. Do not accept this post as an answer or you will likely dissuade others from adding a better one.</p>\n<h2>Your question</h2>\n<blockquote>\n<p><em>"I used a switch statement in getContent to avoid having an array of objects in memory all the time. Is it actually better performance-wise ?"</em></p>\n</blockquote>\n<p>By <em>"better performance-wise"</em> I assume you mean CPU cycles. The answer is, "No its not better."</p>\n<h3>Computation complexity</h3>\n<p>For 2 items the difference is tiny, but if you had a long list of items say <strong>n</strong> is number of items. To display the last item would require <strong>n</strong> comparisons so worst case is <strong>O(n)</strong>, and best case display the first item is <strong>O(1)</strong>. Picking random items the complexity is <strong>O((log n)<sup>c</sup>)</strong> with <strong>c</strong> just above 2 (AKA polylogarithmic)</p>\n<p>What you had <code>return this.state.content[this.state.cidx];</code>, basicly a lookup table, is <strong>O(1)</strong> the best performance you can get.</p>\n<h3>Storage complexity</h3>\n<p>Many times there is a price to pay for using a lookup table and that is memory. But in this case that makes no difference as you are after already stored items rather than looking up a precomputed value.</p>\n<p>As I understand it the react elements you defined as <code><Heroes/></code>, <code><Teams/></code> are store in an internal node tree, having them in an array means you have an extra item in the <code>state</code> object to reference the array and one reference per item. That would require storage <strong>O(2n + 1)</strong> rather than <strong>O(n)</strong>. Where <strong>n</strong> in this case refers to a reference to the react elements, not the elements themselves.</p>\n<p><strong>O(2n+1)</strong> and <strong>O(n)</strong> are the same, and tiny compared to the elements actual needs.</p>\n<h2>Style</h2>\n<p>You could make a slight change</p>\n<pre><code> updateContent(idx) {\n this.setState({cidx:idx});\n }\n</code></pre>\n<p>to</p>\n<pre><code> updateContent(cidx) {\n this.setState({cidx});\n }\n</code></pre>\n<p>But really I only say so as filler as your code looks good, like its almost a cut and paste from the best of react, a good thing (I am not implying you cut and pasted anything )</p>\n<p>I do have a long list of style points in regard to your code, but as that list directly contradicts the react style guide it would be rather bad advice.</p>\n<p>Merry Xmas</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T07:06:10.053",
"Id": "210155",
"ParentId": "210140",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "210155",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T21:12:55.637",
"Id": "210140",
"Score": "1",
"Tags": [
"react.js",
"jsx"
],
"Title": "Header navigation with React"
} | 210140 |
<p>Request input (Z) from user, <span class="math-container">\$-65535 \leq Z \leq 65535\$</span>.<br>
Check if <span class="math-container">\$(X^2)-(Y^2)=Z\$</span> (while <span class="math-container">\$0 \leq X,Y \leq 1000\$</span>). </p>
<p>I wrote a code which will receive Z from user, if it's negative, store the negative value and continue as if Z is positive. Two loops, one which will check Y from <span class="math-container">\$0 \mapsto 1000\$</span>, after that add <span class="math-container">\$1\$</span> to X and continue, until both X and Y are 1000 (meaning no answer) or until an answer is found. </p>
<p>If Z contained a negative value, exchange X and Y after answer is found.
Would love to see some reviews.</p>
<pre><code> .MODEL SMALL
.STACK 100h
.DATA
EnterNum DB 13,10,'Please enter a number between (and including) -65535 and 65535: ',13,10,'$'
AnswerSTR DB 13,10,'Z = , X = , Y = ',13,10,'$'
WrongSTR DB 13,10,'Wrong input, please type a number again (-65535 <= X <= 65535): ',13,10,'$'
NoAnswerSTR DB 13,10,' has no solution below 1000',13,10,'$'
Z DD ?
X DD ?
Y DD ?
I DD ?
J DD ?
NumSign DD 1
Ten DD 10
.CODE
.386
MOV AX,@DATA
MOV DS,AX
XOR EAX,EAX
MOV CX,6 ;Initialize CX for the loop of receiving num
MOV AH,9
MOV DX,OFFSET EnterNum
INT 21h ;Print request num from user
TypeAgain:
XOR DX,DX
ReceiveNum:
MOV AH,1
INT 21h
CMP AL,45 ;Ascii for minus
JE SignSave
CMP AL,13 ;Ascii for enter key
JE EnterKey
SUB AL,'0' ;Convert from Ascii value to numeral value (if reached this point then it's SUPPOSED to be a number)
CMP AL,0
JB WrongInput
CMP AL,9
JA WrongInput ;Check if input is correct (0-9)
XOR AH,AH
ADD Z,EAX ;Save digit in Z
MOV EAX,Z
MUL Ten
MOV Z,EAX ;Save digit multiplied by 10 in order to make place for the new digit (if enter, will go to EnterKey label)
XOR EAX,EAX
LOOP ReceiveNum
MOV AH,1
INT 21h
SUB AL,'0'
CMP AL,0
JB WrongInput
CMP AL,9
JA WrongInput
XOR AH,AH
ADD Z,EAX ;Receive last digit in number
JMP Initialize
WrongInput:
MOV AH,9
MOV DX,OFFSET WrongSTR
INT 21h
JMP TypeAgain
SignSave:
MOV NumSign,-1
JMP ReceiveNum
EnterKey:
XOR EAX,EAX
MOV EAX,Z
DIV Ten
MOV Z,EAX ;Z has number entered by user
Initialize:
MOV X,0
MOV I,0
MOV J,0
JMP CheckAnswerX ;Z will have number from user, NumSign will have -1 if number is negative (remain 1 if positive)
IncX:
XOR EAX,EAX
INC I ;To help with count of X
MOV EAX,I
MOV X,EAX
MUL X
MOV X,EAX ;X contains the value of X^2
CheckAnswerX:
XOR EAX,EAX
MOV Y,0
MOV J,0
CheckAnswerY:
XOR EAX,EAX
MOV EAX,J
MOV Y,EAX
MUL Y
MOV Y,EAX ;Y contains value of Y^2
XOR EAX,EAX
MOV EAX,X
SUB EAX,Y ;EAX - Y, keep value in EAX
CMP EAX,Z
JNE ContinueCheck
JMP Answer ;Meaning they're equal and we have the answer
ContinueCheck:
XOR EAX,EAX
MOV EAX,I
ADD EAX,J
CMP EAX,2002 ;Check if X and Y made their 1001 loop separately (sum of both is 2002)
JE NoAnswerStop
XOR EAX,EAX
MOV EAX,J
CMP EAX,1001 ;Check if Y made it's 0-1000 run
JE IncX ;Meaning Y needs to start from 0 again and add 1 to X
INC J ;To help with count of Y
JMP CheckAnswerY
Answer:
XOR EAX,EAX
MOV EAX,I
MOV X,EAX ;X contains it's original value of the answer (before the degree)
XOR EAX,EAX
MOV EAX,J
MOV Y,EAX ;Y contains it's original value of the answer (before the degree)
CMP NumSign,-1 ;If Z has a negative value
JE ExchangeXY
JMP Answer2 ;Else jump to Answer2 label
ExchangeXY: ;Exchange Y and X values so we receive correct negative Z
XOR EAX,EAX
MOV EAX,X
XCHG EAX,Y
MOV X,EAX
Answer2: ;Start inserting the values of Y, X and Z into the string
XOR CX,CX
MOV CX,4
XOR SI,SI
MOV SI,31
MOV EAX,Y
ReplaceAnswerY:
DIV Ten
ADD DL,'0' ;Convert from numeral value to Ascii value
MOV AnswerSTR[SI],DL
DEC SI
XOR EDX,EDX
LOOP ReplaceAnswerY
XOR CX,CX
MOV CX,4
XOR SI,SI
MOV SI,21
MOV EAX,X
ReplaceAnswerX:
DIV Ten
ADD DL,'0'
MOV AnswerSTR[SI],DL
DEC SI
XOR EDX,EDX
LOOP ReplaceAnswerX
JMP ReplaceAnswerContinueX
NoAnswerStop:
JMP NoAnswer
ReplaceAnswerContinueX:
XOR CX,CX
MOV CX,6
XOR SI,SI
MOV SI,11
MOV EAX,Z
ReplaceAnswerZ:
DIV Ten
ADD DL,'0'
MOV AnswerSTR[SI],DL
DEC SI
XOR EDX,EDX
LOOP ReplaceAnswerZ
CMP NumSign,-1
JE ChangeSignString
MOV AH,9
MOV DX,OFFSET AnswerSTR
INT 21h
JMP CodeEnd
ChangeSignString:
MOV AL,45
MOV AnswerSTR[5],AL
MOV AH,9
MOV DX,OFFSET AnswerSTR
INT 21h
JMP CodeEnd
NoAnswer: ;Insert value of Z into the string
XOR CX,CX
MOV CX,6
XOR SI,SI
MOV SI,7
MOV EAX,Z
ReplaceNoAnswerZ:
DIV Ten
ADD DL,'0'
MOV NoAnswerSTR[SI],DL
DEC SI
XOR EDX,EDX
LOOP ReplaceNoAnswerZ
MOV AH,9
MOV DX,OFFSET NoAnswerSTR
INT 21h
CodeEnd:
MOV AH,4Ch
INT 21h
END
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T17:57:02.577",
"Id": "406247",
"Score": "1",
"body": "Out of curiosity: why assembly? If it's for learning or a school project, fine. But these days, for any kind of serious application development, it's rare to see assembly - and even then, only in \"critical sections\" or while debugging."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T19:08:40.823",
"Id": "406253",
"Score": "1",
"body": "True but as you assumed, it's for a course I'm taking in college"
}
] | [
{
"body": "<p>Ooooh... MS-DOS Assembly programming! That was a long time ago for me, but here goes.</p>\n\n<p>There's a lack of error handling with the number entered, since a user can enter <code>99999</code> for Z and your program does not complain. The <code>SUB</code>, <code>CMP</code>, <code>JB</code> sequence can lose the <code>CMP</code> instruction since the flags will already be set by the subtraction. You can also get rid of the <code>JB</code> in this case, since the next check (<code>CMP AL,9</code>/<code>JA</code>) will detect all the wrong inputs.</p>\n\n<p>There are many places where you zero out a register with <code>XOR</code> when you don't need to zero it out at all. The sequence</p>\n\n<pre><code>XOR EAX,EAX\nMOV EAX,Z\n</code></pre>\n\n<p>The <code>XOR</code> is unnecessary since you immediately replace the register content with a new value.</p>\n\n<p>You need to zero out the <code>EDX</code> register before the <code>DIV Ten</code> instruction after the <code>EnterKey</code> label (or any of the other places you use <code>DIV</code>). You can also rewrite the code so that this isn't required: Multiply by ten before adding in the new digit, rather than before getting the next digit from input.</p>\n\n<p>In the <code>Initialize</code> section, you can zero out a register then store that value (which uses shorter instructions than storing a constant to memory).</p>\n\n<p>In <code>IncX</code>, the first <code>MOV X,EAX</code> is unnecessary since you replace it two instructions later. The same applies for <code>MOV Y,EAX</code> under <code>CheckAnswerY</code>.</p>\n\n<p>The <code>JNE ContinueCheck</code>/<code>JMP Answer</code>/<code>ContinueCheck:</code> sequence can be replaced with a simple <code>JE Answer</code>.</p>\n\n<p>You've hardcoded the offset to store the answer in (<code>MOV SI,31</code>). Your data declaration can be updated to include a label for this spot so you can store the address directly into <code>SI</code>. Similarly, you can get rid of the constant used in <code>ReplaceAnswerX</code>, and where the sign is stored in <code>ChangeSignString</code>, and the offset used in <code>NoAnswer</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T20:28:39.293",
"Id": "406259",
"Score": "0",
"body": "As for the restriction of Z, I couldn't really figure out how to do that with the whole number.. +1 for the info about the SUB and it's flag, as for the removing JB, there are chars below 0, won't that make them possible to enter? Thank you for the XOR and DIV tip as well! Didn't understand what you meant to do in Initialize section... in IncX, I do that since the value of X will be by degree of 2, so it needed a reboot to the value of I everytime. Thank you for the JNE tip. The comment about the offset lines, didn't understand this.. @1201ProgramAlarm"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T20:58:27.863",
"Id": "406270",
"Score": "1",
"body": "There is the `ja` (Jump above, unsigned comparison) and `jg` (Jump greater, signed comparison). `ja` will jump if the unsigned byte in `AL` is greater than 9. In initiialze: `XOR EAX,EAX`/`MOV X,EAX`/`MOV I,EAX`/`MOV J,EAX`. You don't need to define a complete string in one line. You can split it across multiple `db` lines and add labels wherever you need to reference the string."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T18:15:30.233",
"Id": "210177",
"ParentId": "210142",
"Score": "3"
}
},
{
"body": "<p>You can rearrange your equation:</p>\n\n<p><span class=\"math-container\">$$X^2 = Z + Y^2$$</span></p>\n\n<p>Since you are solving where <span class=\"math-container\">\\$Z \\ge 0\\$</span>, then <span class=\"math-container\">\\$ |X| \\ge |Y|\\$</span>, so you can stop your inner loop when Y reaches X, instead of continuing up to 1000.</p>\n\n<p>Alternately, loop for Y over the range 0..1000, calculate <span class=\"math-container\">\\$X^2\\$</span>, and do a binary search on the range Y..1000, looking for the X with the desired square. </p>\n\n<hr>\n\n<p>Instead of:</p>\n\n<pre><code>CMP AL,45 ;Ascii for minus\n</code></pre>\n\n<p>You should probably write:</p>\n\n<pre><code>CMP AL,'-' ;Is the number negative?\n</code></pre>\n\n<hr>\n\n<p>It looks like the user can type <code>-123</code> as <code>123-</code> or <code>1-23</code> or even <code>-1-2--3-</code>. You donโt restrict the minus sign to only being the first character. </p>\n\n<hr>\n\n<p>Since <code>NumSign</code> is initialized to <code>1</code> by loading the code image, the code is only guaranteed to run correctly once. Once a negative number has been entered, <code>NumSign</code> will be changed to <code>-1</code>, and will not be set back to <code>1</code> without reloading the program image.</p>\n\n<p>You should use <code>NumSign DD ?</code> and explicitly set <code>NumSign</code> to <code>1</code> at the beginning of you code <code>MOV NumSign,1</code>, to allow the code to be executed move than once.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T20:16:38.253",
"Id": "406257",
"Score": "0",
"body": "Sorry didn;t quite understand, but if I did then isn't it the same as I'm doing only need to change the inner loop for compare with X? Thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T20:32:35.327",
"Id": "406260",
"Score": "0",
"body": "Couldn't edit my previous comment, but same question goes for the CMP AL,45/'-', aren't they the same just different way of typing? Thank you! @AJNeufeld"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T20:42:42.793",
"Id": "406263",
"Score": "1",
"body": "The first two comments are aimed at improving your algorithm. As it stands, if no answer can be found, it will have taken 1,000,000 iterations. The first comment could reduce it to 500,000 and the second can reduce it to 8000."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T20:51:27.167",
"Id": "406266",
"Score": "1",
"body": "Yes, 45 and '-' are the same, I think, I havenโt checked. But why should I check when you could just write '-'. Why did you write `SUB AL,'0'` when you could write `SUB AL,48`? One is much, much clearer to the reader. Comments can help explain the code, but here you can let the assembler turn '-' into 45, and let the comment explain the why, instead of wasting the comment explaining that ASCII 45 is the minus sign."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T20:53:28.283",
"Id": "406267",
"Score": "0",
"body": "Sorry, this means I didn't understand you correctly, can you please explain a bit more? Beginning with the Z >= 0 please, did you write that because of the way I look at it and exchange X/Y if it's negative or something else? As for the '-' tip, thanks, very reasonable, will do that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T10:59:14.137",
"Id": "406297",
"Score": "1",
"body": "Yes, your original implementation takes the Z entered, saves the sign, solves the problem, and reverses the X/Y if the saved sign was negative. So, you are solving the sub-problem where Z >= 0. Now consider the inner loop when the outer loop has reached X=100. `100^2 = Z + Y^2`. Y=0 through Y=100 are all possible solutions. But once Y is incremented to larger the X, 100^2 = Z + 101^2 has no solution since Z is not negative."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T20:11:44.833",
"Id": "210183",
"ParentId": "210142",
"Score": "1"
}
},
{
"body": "<p>I see a number of things that may help you improve your program.</p>\n\n<h2>Factor out common code into subroutines</h2>\n\n<p>Several places use largely identical code which could be factored out into a routine instead. For example, you could use a subroutine for converting each number into its ASCII equivalent. Here's one way to do that:</p>\n\n<pre><code>;----------------------\n; StoreDec\n;\n; ENTRY: \n; es:di ==> *end* of target string\n; ax = number to convert to decimal string\n;\n; EXIT: \n; es:di ==> one before last written digit\n;\n; TRASHED: \n; ax, bx, dx, flags\n; \nStoreDec proc\n std ; move backward\n mov bx, 10 ; use base 10\nnextDigit:\n xor dx, dx ; zero top part\n div bx ; remainder:quotient in dx:ax\n xchg ax, dx ; \n add al, '0' ; convert quotient to ASCII digit\n stosb\n mov ax, dx ; recover remainder\n or ax, ax ; is it zero?\n jne nextDigit\n ret\nStoreDec endp\n</code></pre>\n\n<h2>Study the intruction set</h2>\n\n<p>A few cases in the current code have sequences like this one:</p>\n\n<pre><code>SUB AL,'0'\nCMP AL,0\nJB WrongInput\n</code></pre>\n\n<p>Because the <code>sub</code> instruction already sets the flags, the <code>cmp</code> instruction can simply be deleted.</p>\n\n<h2>Minimize register usage</h2>\n\n<p>With assembly language programming, minimizing the use of resources is often vital. One of the most precious resources is the processor's registers. Write comments to help you keep track of which registers are used for which purposes. It is possible to refactor this code so that none of the numeric variables are used and everything needed is stored in registers, given appropriate care.</p>\n\n<h2>Think of the user</h2>\n\n<p>I'd probably prefer to at least have the option of specifying the number <span class=\"math-container\">\\$Z\\$</span> on the command line. When the program begins, the command line argument(s), if any, are located in the DOS <a href=\"https://en.wikipedia.org/wiki/Program_Segment_Prefix\" rel=\"nofollow noreferrer\">PSP</a>. I'd suggest looking there first and then only issuing prompts if a command line argument is missing or invalid.</p>\n\n<h2>Fix the bug(s)</h2>\n\n<p>The stated input parameters are not enforced very well. For example, if the user enters 9000000 as the input value, the program falsely claims that:</p>\n\n<pre><code>000000 has no solution below 1000\n</code></pre>\n\n<p>First, the program should validate that the input is within the stated range and second, the program should inform the user of the faulty input rather than wasting many CPU cycles creating an incorrect answer.</p>\n\n<h2>Rethink the algorithm</h2>\n\n<p>The algorithm used in this code is extremely inefficient and can easily be improved to much much faster. First, let's look at the mathematics:</p>\n\n<p>The difference of two squares <span class=\"math-container\">\\$x^2 - y^2 = (x+y)(x-y)\\$</span>. So instead of doing two multiplication operations and a subtraction, we can do two addition/subtractions and one multiply. This is usually beneficial because adding and subtracting is very often faster than multiplication or division.</p>\n\n<p>Next, notice that we can keep the sum and difference and don't really need to recover the actual X and Y values until the end. For simplicity, in the alternative implementation I wrote, I keep <span class=\"math-container\">\\$x, sum\\$</span> and <span class=\"math-container\">\\$diff\\$</span>. </p>\n\n<p>You've already correctly observed that the only difference between, say -5 and +5 for <span class=\"math-container\">\\$z\\$</span> is that the values of the corresponding <span class=\"math-container\">\\$x, y\\$</span> pair are reversed. We can further exploit this fact by noting that if we only look for the absolute value of <span class=\"math-container\">\\$z\\$</span>, we can observe that if the value of <span class=\"math-container\">\\$x^2 - y^2 > |z|\\$</span>, there's no point in further incrementing the <span class=\"math-container\">\\$x\\$</span> value because that will only make the number even larger. We can then test for this and increment <span class=\"math-container\">\\$y\\$</span> if we observe this condition. </p>\n\n<p>Lastly, it is obvious that if <span class=\"math-container\">\\$x = y, x^2 - y^2 = 0\\$</span> and also that if we're only looking for a positive value, then <span class=\"math-container\">\\$x > y\\$</span>. </p>\n\n<p>Putting all of these observations together, the algorithm is:</p>\n\n<ol>\n<li>store <span class=\"math-container\">\\$|z|\\$</span> and sign separately. Hereafter we use <span class=\"math-container\">\\$z\\$</span> to mean <span class=\"math-container\">\\$|z|\\$</span>.</li>\n<li>set <span class=\"math-container\">\\$x = y = sum = diff = 0\\$</span></li>\n<li>compare <span class=\"math-container\">\\$(x+y)(x-y) , z\\$</span></li>\n<li>if <span class=\"math-container\">\\$(x+y)(x-y) = z\\$</span>, we're done</li>\n<li>if <span class=\"math-container\">\\$(x+y)(x-y) > z\\$</span>, go to step 9</li>\n<li>increment <span class=\"math-container\">\\$x, sum, diff\\$</span></li>\n<li>if <span class=\"math-container\">\\$x > 1000\\$</span>, there is no answer</li>\n<li>go to step 3</li>\n<li>increment <span class=\"math-container\">\\$y\\$</span></li>\n<li>if <span class=\"math-container\">\\$y > 1000\\$</span>, there is no answer</li>\n<li>set <span class=\"math-container\">\\$x = y+1\\$</span> and recalculate <span class=\"math-container\">\\$sum, diff\\$</span></li>\n<li>go to step 3</li>\n</ol>\n\n<p>When we print the result, the only difference is that if the original sign of <span class=\"math-container\">\\$z\\$</span> was negative, then swap <span class=\"math-container\">\\$x, y\\$</span></p>\n\n<h2>Be aware of real machines</h2>\n\n<p>It's unlikely you'll encounter anything less than a <code>.386</code> machine these days, but be aware that your use of 32-bit registers <code>EAX</code>, etc. means that this code will not run correctly on a real 8088 or 8086 machine. </p>\n\n<h2>Return an error code</h2>\n\n<p>When the program returns, it has the option of returning an error code. I'd suggest that a value of 0 would mean that suitable <span class=\"math-container\">\\$x, y\\$</span> values have been found, an error code of 1 would mean not found, and an error code of 2 could mean \"bad input.\" The return value goes into the <code>al</code> register when executing <code>int 21h, function 4ch</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T16:47:47.410",
"Id": "406343",
"Score": "0",
"body": "Thank you!! Question, I'm having real trouble restricting the input number, any tips on how I should do it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T16:51:54.480",
"Id": "406344",
"Score": "2",
"body": "One simple way to do that is to note that the absolute value of the allowable input numbers is 0 - 65535. That is *exactly* what fits in a 16-bit register (0000h to FFFFh), so as you add and multiply using 16-bit registers, just check the carry flag. If it's ever set after a `mul` or `add` instruction, the number is out of range."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T22:30:44.460",
"Id": "210189",
"ParentId": "210142",
"Score": "2"
}
},
{
"body": "<p>In pseudocode, your program looks roughly like this:</p>\n\n<pre><code>z = |z|\nfor x = 0..1000\n for y = 0..1000\n if xยฒ - yยฒ = z -> return true\nreturn false\n</code></pre>\n\n<p>It can be made faster by several orders of magnitude if you got rid of the nested loops:</p>\n\n<pre><code>x = y = 0\nz = |z|\nwhile x <= 1000:\n r = xยฒ - yยฒ - z\n if r = 0: return true\n if r < 0: x += 1\n if r > 0: y += 1\nreturn false\n</code></pre>\n\n<p>Alternatively, we can iterate down to zero, which better suits an assembly implementation.</p>\n\n<pre><code>x = y = 1000\nz = |z|\nwhile y >= 0:\n r = xยฒ - yยฒ - z\n if r = 0: return true\n if r < 0: y -= 1\n if r > 0: x -= 1\nreturn false\n</code></pre>\n\n<p>We still face the problem that intermediate results in <code>r = xยฒ - yยฒ - z</code> can be rather large, which is probably the reason you restricted <code>x</code> and <code>y</code> to values below 1000. Incremental updates to the residual are not only numerically superior, they are also faster and allow us to get away without a single multiplication:</p>\n\n<pre><code>x = y = 1000\nr = -|z|\nwhile y >= 0:\n if r = 0: return true\n if r < 0: y -= 1, r += 2y + 1\n if r > 0: x -= 1, r -= 2x + 1\nreturn false\n</code></pre>\n\n<p>In x86 assembly, this results in a fairly tight loop.</p>\n\n<pre><code>x = y = 1000\nr = -|z|\n\n cmp r, 0\n jl negative\n jmp success\n\npositive:\n dec x\n lea r [r - 2*x]\n dec r ; implicitly sets status flags\n jl negative ; most taken branch\n jg positive\n jmp success\n\nnegative:\n dec y ; implicitly sets status flags\n jl fail ; continue while y >= 0\n lea r [r + 2*y]\n inc r ; implicitly sets status flags\n jl negative ; most taken branch\n jg positive\n jmp success\n\nfail:\n ...\nsuccess:\n ...\n</code></pre>\n\n<p>As was suggested in the comments, a slightly modified implementation can handle both negative and positive values of <code>z</code> naturally:</p>\n\n<pre><code>x = y = 1000\n\n cmp z, 0\n jl negative\n jg positive\n jmp success\n\npositive:\n dec y ; implicitly sets status flags\n jl fail ; continue while y >= 0\n lea z [z - 2*y]\n dec z ; implicitly sets status flags\n jg positive\n jl negative\n jmp success\n\nnegative:\n dec x ; implicitly sets status flags\n jl fail ; continue while x >= 0\n lea z [z + 2*x]\n inc z ; implicitly sets status flags\n jl negative\n jg positive\n jmp success\n\nfail:\n ...\nsuccess:\n ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T16:46:08.707",
"Id": "406342",
"Score": "1",
"body": "Kind of feel bad none of these methods came to my mind while trying to solve it.. Thank you, great info!!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T18:18:29.283",
"Id": "406348",
"Score": "3",
"body": "The absolute value is now unnecessary with this algorithm . The x,y values will track by themselves to `x>y` if `z>0` and `x<y` if `z<0`. Eliminate the absolute value and there is no longer a need to swap the values at the end."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T15:43:39.630",
"Id": "210227",
"ParentId": "210142",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-21T23:24:04.640",
"Id": "210142",
"Score": "6",
"Tags": [
"assembly",
"x86"
],
"Title": "Find some X^2 - Y^2 equal to a given Z"
} | 210142 |
<p>I made an algorithm to train my skill in dynamic programming and I would like to have feed back on it. This algorithm takes a money system (<code>int</code>) and have a certain amount of money to render.</p>
<p>Do you see any problems in this code?</p>
<pre><code>public static int wayToRenderMemo(int[] array, int i, double cost, HashMap memo) {
if(i>=array.length) {
return 0;
}
else if(cost < 0) {
return 0;
}
else if(cost == 0) {
return 1;
}
else if(memo.containsKey(String.valueOf(i)+":"+String.valueOf(cost))) {
return (int) memo.get(String.valueOf(i)+":"+String.valueOf(cost));
}
else {
int res = 0;
for(int j = 0; j < array.length; j++) {
res += wayToRenderMemo(array, i+j, cost-array[j], memo);
}
memo.put(String.valueOf(i)+":"+String.valueOf(cost), res);
return res;
}
}
public static void main(String []args) {
int[] array = {1, 2, 5, 10, 20, 50, 100};
double amountOfMoneyToRender = 20;
System.out.println("Number of way to render "+amountOfMoneyToRender+"โฌ with the following system : "+Arrays.toString(array));
HashMap memo = new HashMap();
long t3 = System.currentTimeMillis();
System.out.println(wayToRenderMemo(array, 0, amountOfMoneyToRender, memo));
long t4 = System.currentTimeMillis();
double time2 = (t4-t3)/1000.0;
System.out.println("Result found in : "+time2+"seconds");
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T07:08:52.850",
"Id": "406206",
"Score": "0",
"body": "Welcome to Code Review! I find it highly commendable to explicitly state the purpose of coding something, especially with practice code. 2ยข: do so *in the code*."
}
] | [
{
"body": "<ol>\n<li>Java 1.5 was released in 2004, use generics for collections.</li>\n<li>Consider making <code>array</code> (terrible variable name BTW) and <code>memo</code> fields of object that does the computation instead of passing them as arguments every time</li>\n<li>Why is <code>amountOfMoneyToRender</code> a double instead of <code>int</code> or <code>long</code>?</li>\n<li>String.valueOf is unnecessary for <code>i + \"some literal\"</code></li>\n<li>Instead of using <code>containsKey</code> + <code>get</code> just do <code>get</code> and check for null.</li>\n<li>It might be good idea to change loop into <code>for(int j = i; j < array.length; j++)</code>, it will make easier to spot bug in your code (with amountOfMoneyToRender=10, the result should be 11, not 100) </li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-27T09:27:30.730",
"Id": "210410",
"ParentId": "210145",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T00:03:23.600",
"Id": "210145",
"Score": "2",
"Tags": [
"java",
"dynamic-programming",
"memoization"
],
"Title": "Number of way to render an amount of money"
} | 210145 |
<blockquote>
<p>Given a string print its words in decreasing order of frequency.</p>
<p>Example:</p>
<pre><code>i/p - "aa bbb ccc aa ddd aa ccc"
o/p - aa,ccc,ddd,bbb
</code></pre>
</blockquote>
<p>Scala:</p>
<pre><code>import collection.mutable.PriorityQueue
import collection.mutable.HashMap
object FindWordFreq extends App {
case class wordFreq(w: String, c: Int) extends Ordered[wordFreq] {
override def compare(that: wordFreq): Int = c compareTo(that.c)
}
val words = "aa bbb ccc aa ddd aa ccc" split " +"
val wordCount = HashMap[String, Int]()
for (word <- words) {
wordCount += (word -> (wordCount.getOrElse(word,0) + 1))
}
val myHeap = PriorityQueue[wordFreq]()
wordCount.toSeq foreach { case (w,c) => myHeap.enqueue(wordFreq(w,c)) }
println(myHeap.dequeueAll.map(_.w).mkString(","))
}
</code></pre>
<p>I do think that we can just do with Priority Queue (and get rid of map), but could not come up with very clean code with that.</p>
| [] | [
{
"body": "<p><strong>Using just a priority queue</strong></p>\n\n<p>Yes, it's possible, although you would need a special implementation of priority queue, which internally is a hash map + a heap. This trick is commonly used in Dijkstra's algorithm. See <a href=\"https://stackoverflow.com/a/17581306/1370445\">https://stackoverflow.com/a/17581306/1370445</a>.</p>\n\n<p>Unlike in Dijkstra's algorithm, in your task, you don't need to be able to alternately update values on the heap and remove the top element. So I would discourage you from using this data structure, and encourage to instead focus on achieving high code quality (including low code volume), using the data structures and operations available in Scala's standard library.</p>\n\n<p>Here are my recommendations regarding possible improvements to the code, some of them obsolete the others in the context of this specific piece of code, but I think it's worth to mention them anyway:</p>\n\n<p><strong>Use UpperCamelCase for class names</strong></p>\n\n<p>Scala has an official naming convention (<a href=\"https://docs.scala-lang.org/style/naming-conventions.html\" rel=\"nofollow noreferrer\">https://docs.scala-lang.org/style/naming-conventions.html</a>) which recommends to name classes with UpperCamelCase, so <code>wordFreq</code> should be <code>WordFreq</code>.</p>\n\n<p><strong>Use Scala syntax consistently</strong></p>\n\n<p>Scala let's you replace the dot and parentheses with a space in some case. <code>x method param</code> is equivalent to <code>x.method(param)</code>. In the snippet of code you've provided you sometimes use that feature (<code>\"aa bbb ccc aa ddd aa ccc\" split \" +\"</code>), sometimes use just part of it <code>c compareTo(that.c)</code> and sometimes you don't use it (<code>myHeap.enqueue(wordFreq(w,c))</code>). I would recommend you to decide which style of code you prefer (I prefer dots and parentheses) and use it consistently, at least within a single source file.</p>\n\n<p><strong>Embrace immutability</strong></p>\n\n<p>Scala provides two sets of collections, mutable and immutable. In most cases it's preferable to use immutable collection as they make reasoning easier and eliminate whole class of bugs. I won't dive deeper into that topic, as it is covered in detail by many articles on the internet, for example:</p>\n\n<ul>\n<li><a href=\"https://www.quora.com/What-are-the-advantages-and-disadvantages-of-immutable-data-structures\" rel=\"nofollow noreferrer\">https://www.quora.com/What-are-the-advantages-and-disadvantages-of-immutable-data-structures</a></li>\n<li><a href=\"https://www.yegor256.com/2014/06/09/objects-should-be-immutable.html\" rel=\"nofollow noreferrer\">https://www.yegor256.com/2014/06/09/objects-should-be-immutable.html</a></li>\n</ul>\n\n<p><strong>Prefer <code>Ordering</code> over <code>Ordered</code></strong></p>\n\n<p><code>Ordered</code> binds together the data structure and the way of ordering/comparing them. This is reasonable for thing which have some notion of \"natural order\" like Strings, or Integers. <code>Ordering</code> lets you deliver the way of ordering separately from the data structure declaration, resulting in more composable code.</p>\n\n<p>So instead of </p>\n\n<pre><code>case class wordFreq(w: String, c: Int) extends Ordered[wordFreq] {\n override def compare(that: wordFreq): Int = c compareTo(that.c)\n}\n</code></pre>\n\n<p>I would write</p>\n\n<pre><code>case class WordFreq(w: String, c: Int)\nval mostFrequentFirstWordFreqOrdering: Ordering[WordFreq] = \n (x: WordFreq, y: WordFreq) => y.c.compareTo(x.c)\n</code></pre>\n\n<p>you could make the <code>mostFrequentFirstWordFreqOrdering</code> implicit so that the compiler will pick it up automatic, but since there's more than one reasonable way to sort <code>WordFreq</code> I would prefer to stay explicit and pass the ordering by-hand.</p>\n\n<p><strong>Use sorted/sortBy instead of hand-crafting a heap sort</strong></p>\n\n<pre><code>val myHeap = PriorityQueue[wordFreq]()\nwordCount.toSeq foreach { case (w,c) => myHeap.enqueue(wordFreq(w,c)) }\nmyHeap.dequeueAll\n</code></pre>\n\n<p>Is basically a heap sort implementation. It could be replaced by the <code>sorted</code> or the <code>sortBy</code> methods of <code>SeqLike</code>. It could look like</p>\n\n<pre><code>wordCount.toSeq.sortBy{case (word, count) => -count}\n</code></pre>\n\n<p>or if you find the <code>-</code> and inelegant way of reversing the order, alternatives are:</p>\n\n<pre><code>wordCount.toSeq.sorted(Ordering.by[(String, Int), Int]{case (word, count) => count}.reverse)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>wordCount.toSeq.sortBy{case (word, count) => count}.reverse\n</code></pre>\n\n<p>the last one being less efficient in terms of allocations.</p>\n\n<p><strong>countBy</strong></p>\n\n<pre><code>val wordCount = HashMap[String, Int]()\nfor (word <- words) {\n wordCount += (word -> (wordCount.getOrElse(word,0) + 1))\n}\n</code></pre>\n\n<p>can be replaced with </p>\n\n<pre><code>words.groupBy(x => x).mapValues(_.length)\n</code></pre>\n\n<p>In fact I observe this pattern so often, that in some project I have an \"extension method\" <code>countBy</code> added to Traversable like this:</p>\n\n<pre><code>implicit class RichTraversable[+A](val traversable: Traversable[A]) extends AnyVal {\n def countBy[K, That](accessor: A => K): Map[K, Int] =\n traversable.groupBy(accessor).mapValues(_.length)\n}\n</code></pre>\n\n<p><strong>Separate calculations from making side effects</strong></p>\n\n<p>The line <code>println(myHeap.dequeueAll.map(_.w).mkString(\",\"))</code> does two things. It finishes the process of sorting the results <code>myHeap.dequeueAll.map(_.w)</code> and prints them in human readable format println(results.mkString(\",\")). Two things should be done in two lines, or better, two methods, or better functions (..., but functional IO is a longer topic).</p>\n\n<p><strong>Split by more than just spaces</strong>\nIn real-world text words may be separated by more than just spaces - new-lines, commas, semicolons, etc.. <code>\\W</code> is a regex pattern for \"non-word character\" (see <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html\" rel=\"nofollow noreferrer\">https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html</a>). Using <code>\"\\\\W+\"</code> would be better than <code>\" +\"</code>, although most likely there would still be some edge-cases where it would go wrong.</p>\n\n<p><strong>Final result</strong></p>\n\n<p>After all the suggested modifications the code could look like this:</p>\n\n<pre><code>object FindWordFreq extends App {\n val words = \"aa bbb ccc, aa ddd\\naa\\rccc\" split \"\\\\W+\"\n val wordCounts = words.groupBy(x => x).mapValues(_.length)\n val wordsByDescendingNumberOfOccurrences = wordCounts.toSeq.sortBy{case (_, count) => count}.reverse\n println(wordsByDescendingNumberOfOccurrences.mkString(\",\"))\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-28T20:25:52.690",
"Id": "406944",
"Score": "0",
"body": "Thanks. Your solution is for sure better than the one I came up. It looks more refined."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-27T18:19:57.967",
"Id": "210439",
"ParentId": "210147",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "210439",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T01:02:27.473",
"Id": "210147",
"Score": "0",
"Tags": [
"algorithm",
"strings",
"interview-questions",
"functional-programming",
"scala"
],
"Title": "Print words in decreasing order of frequency in Scala"
} | 210147 |
<p>I wanted your opinion on the first RPG game I made in C#. What things can I improve on with the code?</p>
<p>Events:</p>
<pre><code>static class Events
{
public static void SpawnWeapon(string weapon_name)
{
Console.WriteLine("\nAfter that fight you looted a weapon from the enemy party: {0}", weapon_name);
Player.EquipWeapon(weapon_name);
}
public static void LootHerbs(Player player)
{
Console.WriteLine("\nYou also managed to loot some herbs that you will use to cure you! You gained 3 HP.");
player.HP += 3;
}
public static void LootSpecialHerbs(Player player)
{
Console.WriteLine("\nYou also managed to loot some special herbs that you will use to cure you! You gained 5 HP.");
player.HP += 5;
}
public static void LootMedicine(Player player)
{
Console.WriteLine("\nYou looted some medicine that you will use to cure you! You gained 5 HP.");
player.HP += 5;
}
public static void LootHighGradeMedicine(Player player)
{
Console.WriteLine("\nAnd you also managed to loot some high grade medicine that you will use to cure you! You gained 7 HP.");
player.HP += 7;
}
public static void GodBlessing(Player player)
{
Console.WriteLine("\nAs you were walking towards the dragon nest, you suddenly hear a angelical voice behind you\n" +
"and your wounds magically heal. You were blessed by a god to finish your journey! You gained 12 HP.");
player.HP += 12;
}
}
</code></pre>
<p>Battle:</p>
<pre><code>static class Battle
{
public static int crit_chance = 16; // 1 in 15 attacks is a crit. ( Yes, 15 ).
public static int attack_timer = 1500;
public static bool isCrit()
{
Random rnd = new Random();
int crit = rnd.Next(1, crit_chance);
if (crit == 1)
{
return true;
}
return false;
}
public static bool isPlayerDead(Player player)
{
if (player.HP <= 0)
{
return true;
}
return false;
}
public static bool isMobDead(Mob mob)
{
if (mob.HP <= 0)
{
return true;
}
return false;
}
public static void PlayerAttack(Player player, Mob mob)
{
bool was_crit = false;
int DamageInflicted()
{
int damage = player.Attack() - mob.Defense();
if (damage <= 1)
{
damage = 1;
}
if (isCrit() == true)
{
was_crit = true;
damage += damage;
}
return damage;
}
mob.HP -= DamageInflicted();
if (was_crit == true)
{
Console.WriteLine("It was a critical hit! You dealt {0} damage.", DamageInflicted());
}
else
{
Console.WriteLine("You dealt {0} damage.", DamageInflicted());
}
Console.WriteLine("The enemy has {0} HP.", mob.HP);
}
public static void EnemyAttack(Player player, Mob mob)
{
bool was_crit = false;
int DamageInflicted()
{
int damage = mob.Attack() - player.Defense();
if (damage <= 0)
{
damage = 0;
}
if (isCrit() == true)
{
was_crit = true;
damage += damage;
}
return damage;
}
player.HP -= DamageInflicted();
if (was_crit == true)
{
Console.WriteLine("It was a critical hit! The enemy dealt {0} damage.", DamageInflicted());
}
else
{
Console.WriteLine("The enemy dealt {0} damage.", DamageInflicted());
}
Console.WriteLine("You have {0} HP.", player.HP);
}
public static void MakeBattle(Player player, Mob mob)
{
Console.WriteLine("You, {0}, will now fight the {1} {2}.", player.name, mob.specie, mob.name);
mob.Stats();
Console.WriteLine("Press Enter to begin the fight.");
Console.ReadLine();
Random rnd = new Random();
int move = rnd.Next(1, 3);
if (move == 1)
{
Console.WriteLine("You begin!");
while (true)
{
Console.WriteLine();
System.Threading.Thread.Sleep(attack_timer);
PlayerAttack(player, mob);
if (isMobDead(mob))
{
Console.WriteLine("You killed the {0}!", mob.specie);
Console.ReadLine();
Console.Clear();
break;
}
Console.WriteLine();
System.Threading.Thread.Sleep(attack_timer);
EnemyAttack(player, mob);
if (isPlayerDead(player))
{
Console.WriteLine("You died! Game Over!");
break;
}
}
}
else
{
Console.WriteLine("The enemy will begin!");
while (true)
{
Console.WriteLine();
System.Threading.Thread.Sleep(attack_timer);
EnemyAttack(player, mob);
if (isPlayerDead(player))
{
Console.WriteLine("You died! Game Over!");
break;
}
Console.WriteLine();
System.Threading.Thread.Sleep(attack_timer);
PlayerAttack(player, mob);
if (isMobDead(mob))
{
Console.WriteLine("You killed the {0}!", mob.specie);
Console.ReadLine();
Console.Clear();
break;
}
}
}
}
}
</code></pre>
<p>Mob:</p>
<pre><code>class Mob
{
public string specie;
public string name;
public int base_attack = 2;
public int base_defense = 1;
public int HP;
public int mob_defense;
public int mob_attack;
public Mob(string aSpecie, string aName, int aHP, int aAttack, int aDefense)
{
specie = aSpecie;
name = aName;
HP = aHP;
mob_attack = aAttack;
mob_defense = aDefense;
}
public int Attack()
{
return (base_attack + mob_attack);
}
public int Defense()
{
return (base_defense + mob_defense);
}
public void Stats()
{
Console.WriteLine("The {0} {1}'s Stats:", specie, name);
Console.WriteLine("HP: {0}", HP);
Console.WriteLine("Attack: {0}", Attack());
Console.WriteLine("Defense: {0}", Defense());
}
}
</code></pre>
<p>Story:</p>
<pre><code>static class Story
{
public static void S_1_Bandits(Player player)
{
Console.WriteLine("You are " + player.name + ", who's on his way to kill the dragons which are destroying the kingdom.");
Console.WriteLine("As you are on your way to the lairs of the dragons, you run into a couple of bandits.");
Console.WriteLine("And they don't seem so friendly...");
Console.ReadLine();
Console.Clear();
}
public static void S_2_Knights()
{
Console.WriteLine("The bandits weren't much of a match for you. Well Done! You continue on to the dragons lair!");
Console.WriteLine("However, a new movement has risen that wants to protect the dragons of the world.");
Console.WriteLine("Many people have joined this movement, including some knights.");
Console.WriteLine("And uh oh, 3 of them have found out about your quest...");
Console.WriteLine("Maybe they're friendly?");
Console.ReadLine();
Console.WriteLine("Nope.");
Console.ReadLine();
Console.Clear();
}
public static void S_3_Dragons()
{
Console.WriteLine("With the knights defeated you continue on your journey!");
Console.WriteLine("After a while you make it to the lair of dragons...");
Console.WriteLine("It's hot and little smokey in there. You put your sight on the pair of dragons in the center of it.");
Console.WriteLine("The time has come to end the dragons rampage!");
Console.ReadLine();
Console.Clear();
}
public static void S_End(Player player)
{
Console.WriteLine("You killed the dragons and saved the kingdom!");
Console.WriteLine("Your name will be remembered forever and legends will be told about the hero {0} that defeated the evil dragons!", player.name);
Console.WriteLine("Congrats!");
}
}
</code></pre>
<p>Weapon:</p>
<pre><code>class Weapon
{
public string name;
public int attack;
public int defense;
public static List<Weapon> weapon_list = new List<Weapon>();
public Weapon(string aName, int aAttack, int aDefense)
{
name = aName;
attack = aAttack;
defense = aDefense;
}
public static void CreateWeapon( string name, int attack, int defense)
{
Weapon weapon = new Weapon(name, attack, defense);
weapon_list.Add(weapon);
}
public static void CheckAllAvailableWeaponsStats()
{
Console.WriteLine("\nAll weapons in the game:");
foreach (Weapon weapon in Weapon.weapon_list)
{
Console.Write("Name: {0}\nAttack: {1}\nDefense: {2}\n", weapon.name, weapon.attack, weapon.defense);
Console.WriteLine("---------------------------");
}
}
public static void CheckWeaponStats(Weapon weapon)
{
Console.Write("\nName: {0}\nAttack: {1}\nDefense: {2}\n", weapon.name, weapon.attack, weapon.defense);
}
public static void CompareWeaponStats(Weapon other_weapon, Weapon your_weapon)
{
if (your_weapon == Player.equipped_weapon)
{
Console.Write("Name: {0} | Equipped Weapon Name: {1}\nAttack: {2} | Equipped Weapon Attack: {3} \nDefense: {4} |" +
" Equipped Weapon Defense: {5}\n", other_weapon.name, your_weapon.name, other_weapon.attack, your_weapon.attack, other_weapon.defense, your_weapon.defense);
}
else
{
Console.Write("Other Weapon Name: {0} | Your Weapon Name: {1}\nOther Weapon Attack: {2} | Your Weapon Attack: {3} \nOther Weapon Defense: {4} " +
"| Your Weapon Defense: {5}\n", other_weapon.name, your_weapon.name, other_weapon.attack, your_weapon.attack, other_weapon.defense, your_weapon.defense);
}
}
}
</code></pre>
<p>Player:</p>
<pre><code>class Player
{
public static Weapon initial_sword = new Weapon("Initial Sword", 8, 4);
public string name;
public int HP;
public int level = 0;
public static Weapon equipped_weapon = initial_sword;
public int base_attack = 4;
public int base_defense = 2;
public Player(string aName, int aHP)
{
name = aName;
HP = aHP;
}
public int Attack()
{
return (base_attack + equipped_weapon.attack);
}
public int Defense()
{
return (base_defense + equipped_weapon.defense);
}
public void Stats()
{
Console.WriteLine("\n{0}'s Stats:", name);
Console.WriteLine("HP: {0}", HP);
Console.WriteLine("Attack: {0} ({1})", Attack(), base_attack);
Console.WriteLine("Defense: {0} ({1})", Defense(), base_defense);
Console.WriteLine("Equipped Weapon: {0}; AT: {1}; DF: {2}", equipped_weapon.name, equipped_weapon.attack, equipped_weapon.defense);
}
public static bool QuestionPrompt()
{
string[] yes_list = { "yes", "", "sure", "y", "yeah", "why not", "yes.", "y." };
Console.Write("-->");
string input = Console.ReadLine();
string iinput = input.ToLower();
foreach (string value in yes_list)
{
if (value.Equals(iinput))
{
return true;
}
else
{
continue;
}
}
return false;
}
public static void ChangeWeaponByName(string new_weapon_name)
{
Weapon weapon_to_change = new Weapon("Test Weapon", 0, 0);
bool WeaponExists()
{
foreach (Weapon weapon in Weapon.weapon_list)
{
if (weapon.name.ToLower() == new_weapon_name.ToLower())
{
weapon_to_change = weapon;
return true;
}
else
{
continue;
}
}
return false;
}
if (WeaponExists() == true)
{
equipped_weapon = weapon_to_change;
}
}
public static void ChangeWeapon(Weapon new_weapon)
{
equipped_weapon = new_weapon;
}
public static void EquipWeapon(string weapon_name)
{
Weapon weapon_to_equip = new Weapon("Test Weapon", 0, 0);
bool WeaponExists()
{
foreach (Weapon weapon in Weapon.weapon_list)
{
if (weapon.name.ToLower() == weapon_name.ToLower())
{
weapon_to_equip = weapon;
return true;
}
else
{
continue;
}
}
return false;
}
if (WeaponExists())
{
Console.WriteLine("\nComparison of both weapons stats:");
Weapon.CompareWeaponStats(weapon_to_equip, Player.equipped_weapon);
Console.WriteLine("Are you sure you want to equip this weapon?");
if (QuestionPrompt() == true)
{
Console.WriteLine("You equipped the weapon!");
ChangeWeapon(weapon_to_equip);
}
else
{
Console.WriteLine("You will continue with the same weapon, the new one was discarded.");
}
}
else
{
Console.WriteLine("The weapon you want to equip doesn't exist!");
}
}
public static void CheckEquippedWeapon()
{
Console.WriteLine("Equipped Weapon:");
Weapon.CheckWeaponStats(equipped_weapon);
}
}
</code></pre>
<p>Main:</p>
<pre><code> static void Main()
{
Player player = new Player("", 30);
bool PlayerDied()
{
if (Battle.isPlayerDead(player) == true)
{
return true;
}
return false;
}
Weapon.CreateWeapon("Rusty Old Sword", 7, 3); // initial weapon
Weapon.CreateWeapon("Iron Sword", 10, 5); // to give the player after he fights the bandits
Weapon.CreateWeapon("Enchanted Silver Sword", 15, 7); // to give the player after he fights the knights
Player.ChangeWeaponByName("rusty old sword");
// the enemies
Mob[] bandits =
{
new Mob("Bandit", "Rob", 10, 6, 2),
new Mob("Bandit Leader", "Joe", 10, 7, 2)
};
Mob[] knights =
{
new Mob("Knight", "Rob", 12, 8, 4),
new Mob("Knight", "John", 12, 9, 3),
new Mob("Knight Captain", "Aaron", 14, 10, 4),
};
Mob[] dragons =
{
new Mob("Blue Dragon", "Jormungandr", 16, 10, 6),
new Mob("Dragon Leader", "Helios", 18, 11, 6),
};
Console.WriteLine("What's your name, adventurer?");
string response = Console.ReadLine();
player.name = response;
player.Stats();
Console.WriteLine("\nPress anything to begin the game.");
Console.ReadLine();
Console.Clear();
while (true)
{
Story.S_1_Bandits(player); // first part of the story
foreach (Mob mob in bandits)
{
Battle.MakeBattle(player, mob);
if (Battle.isPlayerDead(player) == true)
{
break;
}
}
if (PlayerDied() == true)
{
break;
}
Events.SpawnWeapon("Iron Sword");
if (player.HP <= 16)
{
Events.LootSpecialHerbs(player);
}
else
{
Events.LootHerbs(player);
}
player.Stats();
Console.WriteLine("\nPress Enter to continue.");
Console.ReadLine();
Console.Clear();
Story.S_2_Knights(); // second part of the story
foreach (Mob mob in knights)
{
Battle.MakeBattle(player, mob);
if (Battle.isPlayerDead(player) == true)
{
break;
}
}
if (PlayerDied() == true)
{
break;
}
Events.SpawnWeapon("Enchanted Silver Sword");
Events.LootMedicine(player);
if (player.HP >= 15)
{
Events.LootHighGradeMedicine(player);
}
else if (player.HP <= 13)
{
Events.GodBlessing(player);
}
else
{
Events.LootMedicine(player);
}
player.Stats();
Console.WriteLine("\nPress Enter to continue.");
Console.ReadLine();
Console.Clear();
Story.S_3_Dragons(); // third part of the story
foreach (Mob mob in dragons)
{
Battle.MakeBattle(player, mob);
if (Battle.isPlayerDead(player) == true)
{
break;
}
}
if (PlayerDied() == true)
{
break;
}
Console.Clear();
Story.S_End(player);
break;
}
Console.ReadLine();
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T08:53:26.373",
"Id": "406216",
"Score": "3",
"body": "Welcome to Code Review. That's a lot of code at once and therefore is hard to review, as reviewers are currently missing the big-picture. They only know that this is some kind of RPG, but it's not clear whether it's a text-based adventure or how to play it. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you. [Questions should include a description of what the code does](//codereview.meta.stackexchange.com/q/1226)"
}
] | [
{
"body": "<p><strong>Valley Girl coding</strong></p>\n\n<p>The valley girls say \"for sure, for sure\". so does this:</p>\n\n<pre><code>if (PlayerDied() == true)\n</code></pre>\n\n<p>Instead:</p>\n\n<pre><code>if(PlayerDied())\n</code></pre>\n\n<p>And, not this:</p>\n\n<pre><code>public static bool isMobDead(Mob mob)\n{\n if (mob.HP <= 0)\n {\n return true;\n }\n return false;\n}\n</code></pre>\n\n<p>instead:</p>\n\n<pre><code>public static bool isMobDead(Mob mob) { return mob.HP <= 0; }\n</code></pre>\n\n<p>and not this:</p>\n\n<pre><code>if ( weapon.name.ToLower() == weapon_name.ToLower() ) {\n return true;\n} else {\n continue;\n}\nreturn false;\n</code></pre>\n\n<p>instead:</p>\n\n<pre><code>return ( weapon.name.ToLower() == weapon_name.ToLower() ); \n</code></pre>\n\n<hr>\n\n<p><strong>Misplaced properties</strong></p>\n\n<pre><code>Battle.isPlayerDead(player)\n</code></pre>\n\n<p>isDead belongs in <code>Player</code> class, something like this:</p>\n\n<pre><code>public bool IsDead { get { return hitPoints <= 0; } }\n</code></pre>\n\n<p>If a class is \"calculating\" something about an object using only object-class's properties then it probably belongs in that class in the first place.</p>\n\n<p>Why does a <code>Weapon</code> have it's own weapons? If the idea is for a collection of all weapon types (and associated properties) that exist in the game then make a <code>Weapons</code> (plural) class. And a <code>Player</code> should have <code>Weapons</code> too.</p>\n\n<hr>\n\n<p><strong>Nmng cnvntns</strong></p>\n\n<p>You know these are bad names: <code>HP</code>, <code>isCrit()</code>, etc. Here's why: Names should be in descriptive terms of the problem domain and thus convey context and meaning. Names should help a code reader who is not you understand the program.</p>\n\n<p>Do not name things using implementation details. <code>List<Weapon> weapon_list</code>. Instead <code>List<Weapon> weapons</code>.</p>\n\n<hr>\n\n<p><strong>Make state variables</strong></p>\n\n<pre><code>while (true)\n</code></pre>\n\n<p>While what is true?</p>\n\n<p>Once you define what it means to keep going, let's say \"combatEffective\", then lots of imprecise and vague code is understandable:</p>\n\n<pre><code>while( combatEffective ) {\n . . .\n\n if( somePlayer.IsDead ) combatEffective = false;\n\n . . .\n}\n</code></pre>\n\n<p>Any number of things might cause an ineffective player and now the code unambiguously defines/declares these situations. Also the code is made more self document-y.</p>\n\n<p>MOST importantly rewrite so execution falls to the end of the <code>while</code> block and loops. As written, this code is very error prone when adding complexity.</p>\n\n<hr>\n\n<p><strong>Structure</strong></p>\n\n<p>The above change breaks the <code>while</code> code, you know that of course. But it would not given a structure instead of a single mass of linear code.</p>\n\n<pre><code>combatEffective = true;\nwhile( combatEffective) {\n if( !StoryOne() ) { combatEffective = false; }\n . . .\n if( !StoryTwo() ) { combatEffective = false; }\n . . .\n if( !StoryThree() ) { combatEffective = false; }\n}\n</code></pre>\n\n<p>Good structure creates appropriate level abstractions. That naturally makes code changealbe and understandable. Strive for appropriate abstractions at the <code>main()</code> level, class, method, and even individual control structure (if, while, switch, etc.) levels.</p>\n\n<hr>\n\n<p><strong>States are undefined</strong></p>\n\n<p>First, I assume <code>HP</code> means hit-points.... Where ever there is something like <code>player.HP <= 13</code> that must have some meaning otherwise you just felt like writing <code>13</code> at that moment; so why not 5, 256, -43? Define these states using enums or constants or something. I like enums. So \"13\" must be some kind of limit and being under 13 must be some kind of combat effectiveness state or something.</p>\n\n<hr>\n\n<p><strong>Confusing Player weapons</strong></p>\n\n<p>Why or how is <code>initial-sword</code> different from any other sword a player may have (or any other weapon for that matter)? I don't see why the weapon that a player object is instantiated with is special or different than any weapon he may get during the game.</p>\n\n<p><code>equiped_weapon</code> is confusing. I think you mean the weapon he is currently wielding. The things in a player's possession are the things he is \"equipt with.\" That is to say I am equipted with a sword whether it's in my hand or strapped to my back.</p>\n\n<p>If a player comes standard issue with a sword then give him a sword in the constructor, then explicitly put it in his hand for use - <em>just the way you'd do things every where else in the program</em></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T08:31:24.153",
"Id": "210159",
"ParentId": "210153",
"Score": "9"
}
}
] | {
"AcceptedAnswerId": "210159",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T04:19:37.513",
"Id": "210153",
"Score": "6",
"Tags": [
"c#",
"beginner",
"role-playing-game",
"battle-simulation"
],
"Title": "First C# RPG game and project as a beginner"
} | 210153 |
<p>I'm working on a game and I have developed A* path finding for certain enemies.
But I think I have some optimization issues.
If I put the player in an area that cannot be reached and put 3 or 4 enemies around him they are forced to use A* until there are no options left.
This causes a dramatic slowdown. </p>
<p>There are several limiting factors that limit the area that can be searched.
If the node is out of the attack range of the enemy, if the node falls out of the viewable screen, if the node fall out of the current "area", then the node will be ignored.
So in this case with the current enemy and it's range we should be checking about an 18x18 grid.
Things to consider, I'm using the map tiles themselves as the nodes, I'm using a priority queue for the open set, although I'm forced to remove an object from it if I have to update the parent or update the G value and re add it to preserve the proper order, and I'm using a hash set for the closed list. </p>
<p>Not sure if I shouldn't be using the actual map as the nodes.
Since the map tiles can be checked over and over I'm also forced to set the G value to maximum the first time I come across it for the current instance of the A* so that the calculated value will always be smaller.</p>
<p>This path finding occurs once every cycle of the game.
The code is ready for diagonal movement but so far I'm only taking advantage of horizontal and vertical movement.
I've also tried running it with other sections of code commented out to see if something else might be causing the slowdown, but it's definitely the A*.</p>
<p>I ran some tests and saw that the closed set had about 280 elements in it, and the open set had around 250 when it finished checking everything, not sure if those numbers make sense.
I would think one of those should be a lot smaller considering the limitations.
I'm probably doing a lot wrong here so any tips on how to make this code more efficient would be greatly appreciated. </p>
<p>This is a top down 2d game like original Zelda.
The map consists of tiles each with their own attributes.
The A* path finding algorithm tries to find a path from a starting tile to an end tile using only vertical or horizontal movements.
Hope that makes it more clear about what the game is like and how it functions. </p>
<p>Here is the class I use for A*</p>
<pre><code> package enemiesClass;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Set;
import Engine.Animator;
import Engine.MapMain;
public class Astar {
private MapMain nodeStart;//starting tile
private MapMain nodeEnd;//ending tile
private Enemies enemy;
private boolean diag;//can move diagonally
private boolean isPath;//true if there is a path and flase if there is not
private ArrayList<MapMain> pathToEnd = new ArrayList<MapMain>();
private int sightDistance;// = enemy.sightAttackRange*Animator.scale;//the maximum distance the enemy can see while attacking
private Point heroCent = Animator.getBoard().findCenter(Animator.getBoard().getHero().getRect());//center of hero rect
public Astar(MapMain nodeStart, MapMain nodeEnd, Enemies enemy, boolean diag){
this.nodeStart = nodeStart;
this.nodeEnd = nodeEnd;
this.enemy = enemy;
this.diag = diag;
sightDistance = enemy.sightAttackRange*Animator.scale;//the maximum distance the enemy can see while attacking
isPath = findPath();
}
private boolean findPath(){
Set<MapMain> closedSet = new HashSet<MapMain>();
Queue<MapMain> openSet = new PriorityQueue<MapMain>(11, nodeComparator);
nodeStart.setPathG(0);
nodeStart.setPathH(getDistance(nodeStart, nodeEnd));
nodeStart.setPathF(nodeStart.getPathH()+nodeStart.getPathF());
openSet.add(nodeStart);
while(!openSet.isEmpty()){
//MapMain[] maps = findNeighbors(openSet.peek());
MapMain currentNode = openSet.poll();
closedSet.add(currentNode);
if (currentNode.equals(nodeEnd)){
makePathToEnd();
return true;
}
//look through each neighbor
for(MapMain map: findNeighbors(currentNode)){
Point mapCent = Animator.getBoard().findMapTileCenter(map);//center point of map tile
//Line2D line = new Line2D.Double(mapCent, Animator.getBoard().findCenter(Animator.getBoard().getHero().getRect()));
if(closedSet.contains(map)){
continue;//if this map tile was already added to closedSet
}
if(Animator.getBoard().isRectInTile(map)){
continue;//if any tile in this map space has a rect in it
}
if(mapCent.x > enemy.mapAreaBR.getX()+Animator.scale || mapCent.x < enemy.mapAreaTL.getX() ||
mapCent.y > enemy.mapAreaBR.getY()+Animator.scale || mapCent.y < enemy.mapAreaTL.getY()){
continue;//if map tile is leaving the area the enemy is in
}
if(mapCent.x > Animator.screenW+Animator.scale || mapCent.x < -Animator.scale ||
mapCent.y > Animator.screenH+Animator.scale || mapCent.y < 0){
continue;//if map tile is outside of viewable screen
}
if(!checkRange(mapCent)){
continue;//hero is out of range from the center of this tile
}
if(!openSet.contains(map)){
map.setPathG(Integer.MAX_VALUE);//if this tile has not been added set the G to max value
map.setPathH(getDistance(map, nodeEnd));//find cost to to end node
}
//find cost to neighbor
int tempG = currentNode.getPathG()+getDistance(currentNode, map);
//if the new G cost to the neighbor is less then the old G cost to the neighbor
if(tempG < map.getPathG()){
if(openSet.contains(map)){//if this tile is already in open set
openSet.remove(map);//remove it to make changes so the order is preserved
}
map.setPathG(tempG);//apply new G cost
map.setPathF(map.getPathH()+map.getPathG());//calculate new F cost
map.setPathParent(currentNode);//add current node as parent
openSet.add(map);//add map to open set
}
}
}
return false;
}
//find neighbor nodes
private MapMain[] findNeighbors(MapMain node){
int neighborCount = 4;
if(diag) neighborCount = 8;
MapMain maps[] = new MapMain[neighborCount];
int index = 0;
for(MapMain map: Animator.getBoard().getMapMainArrayL1()){
int mapx = map.getMapPoint().x;
int mapy = map.getMapPoint().y;
int nodex = node.getMapPoint().x;
int nodey = node.getMapPoint().y;
//create loop for checking all neighbor nodes
for(int ix = -1; ix < 2; ix++){
for(int iy = -1; iy < 2; iy++){
if(ix == 0 && iy == 0) continue;//skip if it's the middle tile which is the current node
if(mapx == nodex+ix && mapy == nodey+iy){
if(ix == 0 || iy == 0){//if horizontal or vertical node always add neighbor
maps[index] = map;
index++;
}else if(diag){//if diagonal node only add when diag is true
maps[index] = map;
index++;
}
}
}
}
}
return maps;
}
private void makePathToEnd(){
MapMain nodeCurrent = nodeEnd;
pathToEnd.add(nodeCurrent);
while(!nodeCurrent.equals(nodeStart)){
nodeCurrent = nodeCurrent.getPathParent();
pathToEnd.add(nodeCurrent);
}
Collections.reverse(pathToEnd);
}
//checks to see if the hero is in range from given spot
private boolean checkRange(Point point){
if(heroCent.y > point.y-(sightDistance) && heroCent.y < point.y+(sightDistance) &&
heroCent.x > point.x-(sightDistance) && heroCent.x < point.x+(sightDistance)){
return true;
}
return false;
}
//get distance from one map tile to another
private int getDistance(MapMain map1, MapMain map2){
int distX = Math.abs(map1.getMapPoint().x-map2.getMapPoint().x);
int distY = Math.abs(map1.getMapPoint().y-map2.getMapPoint().y);
if(distX > distY)return 14*distY+10*(distX-distY);
return 14*distX+10*(distY-distX);
}
//comparator for priority queue
private Comparator<MapMain> nodeComparator = new Comparator<MapMain>(){
@Override
public int compare(MapMain a1, MapMain a2) {
return a1.getPathF() - a2.getPathF();
}
};
public boolean isPath() {
return isPath;
}
public ArrayList<MapMain> getPathToEnd() {
return pathToEnd;
}
}
</code></pre>
<p>And here is the section of code that calls it</p>
<pre><code>//do attack style 2 checks
private void doAttackStyle2(){
if(checkHeroAcross() || attacking){
setAttackDraw();
bullet3attack();
return;
}
if(!findAttackSpot2()){
stopAttack();
return;
}
attackPoint = heroPoint;
Astar astar = new Astar(findClosestTile(),Animator.getBoard().getMapFromPoint(attackPoint),this,false);
if(astar.isPath()){
if(attackPause < 29){
attackAlert();
return;
}
speed = attackSpeed;
faceHero();
dy=0;
dx=0;
moving = true;
astarPath = astar.getPathToEnd();
byte tileLoc = findRectLocationInMapTile(astarPath.get(0), Animator.getBoard().getRectCorners(rect));
byte nextLoc = 0;//next location to move to
if(astarPath.size() > 1){
nextLoc = getAttackNextTile();
moveAttackPath(tileLoc,nextLoc);
}else{
moveAttackPathFinal();
}
}else{
stopAttack();
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T11:39:18.583",
"Id": "406228",
"Score": "3",
"body": "Not quite enough for a full review, but: Why are you running full A* on every tick of your game? Usually you wouldn't need to do that. Most A* results will be at least useful for a few ticks or even seconds."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T17:26:44.130",
"Id": "406244",
"Score": "0",
"body": "Thanks! I was wondering if that was necessary. Never used A* before so I wasn't sure how it needs to work. I'll reduce the useage of it and see how it turns out."
}
] | [
{
"body": "<p>Calling <code>PriorityQueue.contains</code> is O(n) in the size of the priority queue and this ruins your performance.</p>\n\n<p>For example here:</p>\n\n<pre><code>if(!openSet.contains(map)){\n map.setPathG(Integer.MAX_VALUE);//if this tile has not been added set the G to max value \n map.setPathH(getDistance(map, nodeEnd));//find cost to to end node\n}\n</code></pre>\n\n<p>It is ok to have duplicates in the open set just check if the current node is in the closed set when you pull it out of the open set before continuing with it. Or if you don't like that, you can have a parallel open set to the open priority queue.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T09:32:39.760",
"Id": "406218",
"Score": "0",
"body": "Or [use a priority queue with O(1) contains!](https://github.com/BlueRaja/High-Speed-Priority-Queue-for-C-Sharp). That's for C# though - unfortunately I'm not aware of one for Java, but it is open source..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T17:31:41.393",
"Id": "406245",
"Score": "0",
"body": "One of the reasons I need to check if it's not in open set yet is because I'm using the actual map tiles as the nodes. It's very likely the tile has been used in the past and already has a G value set. The G value has to be reset so it can be compared. But this may be a flawed method. I'll look into creating separate nodes so this won't be needed. Once I see the performance increase I'll check this answer. Thanks for the tip!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T17:58:34.327",
"Id": "406248",
"Score": "1",
"body": "Storing ephemeral data pertaining to the path finding in the actual map tiles is a Bad Idea TM, for one you are preventing yourself from paralleling the A* search for the different agents for example. Also it's just the wrong place for this data."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T18:06:10.613",
"Id": "406249",
"Score": "0",
"body": "I was always worried about doing that. That's why I pointed it out. The game runs in a single thread so it wouldn't run parallel, but still it's bad practice. And I totally now see how I ruined the purpose of the priority queue by forcing the game to run through the entire queue each time. I'm pretty sure when I eliminate it I'll see a performance boost. Just didn't realize what I was doing at the time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T06:35:19.437",
"Id": "406387",
"Score": "0",
"body": "I've hit a wall. The priority queue comparable value can change during the coarse of the algorithm. Any attempt to remove an element and restructure the queue results in 0(n). I'm not sure what you mean by don't worry about duplicates? In order to check contains I have to compare objects, if openSet just got new objects added each time it would always add new objects to closed set. Maybe I misunderstood what you were trying to say? I know there are other heaps that can do 0(1) removal, but they don't come in stock java it doesn't look."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T09:19:18.817",
"Id": "406404",
"Score": "0",
"body": "@Sark If you use a node class with a reference to the tile and the G and F values in the node. Then you can have tiles in the closed set and nodes in the open set. Because the open set is ordered, you can just keep adding to the set when you find a better G values for neighbors, at any point only the shortest route (top of queue) is taken off the queue, you check the tile in the node to the closed set and skip that node if the check is positive. This way you don't need to update the nodes in the queue, just add new ones, the ordering and de-duping on pull takes care of it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T17:58:05.220",
"Id": "406432",
"Score": "0",
"body": "Problem is the G value has to change inside the node. If the node has been added to the queue and I change the G value the queue becomes corrupted. Even if I add it again to the queue, the first entry in the queue still references the node, and since it value has changed it is no longer on the right place in the heap. Adding and removing no longer allowes the heap to stay orginized and it can't keep the lowest value at the top. I might still be misunderstanding what you're trying to say?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T18:18:31.130",
"Id": "406441",
"Score": "0",
"body": "@Sark Don't change the G value in the node, add a new node with smaller G, it will be be processed before the old node and added to the closed set, when the old (outdated G value) b is pulled of the queue the tile is already in the closed set and thus you skip it. So you don't need to update anything in the queue, just add new nodes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T18:30:33.517",
"Id": "406445",
"Score": "0",
"body": "I think I get it. The key is that the closed set and open set hold two different kinds of objects, and the open set objects have a reference to the closed set objects for comparison. I'll work on that. I restructured the algorithm so there no longer are any contains methods being used and it's improved things significantly. But getting rid of the remove method will do even more I'm sure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T19:19:34.300",
"Id": "406450",
"Score": "0",
"body": "@Sark that is correct and it will also fix the problem of storing G and H in the map tile. Add yes, the remove also needs to go add it is also O(n)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T19:59:42.163",
"Id": "406456",
"Score": "0",
"body": "I tired it, but things got painfully slow. I'm sure I was doing something wrong with iterations, but the code with the remove works pretty good. Even with 4 enemies that cannot reach the player going through the entire A* algorithm there is no noticable slow down. I don't think the game will present any situation worse then that. I'll revisit trying to remove the \"remove\" method again later. Thanks for all the help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-26T17:51:57.667",
"Id": "406603",
"Score": "0",
"body": "I now use two objects, an AstarNode and an AstarQueueNode. The AstarNodes are created from the map and only relevant tiles are used. I put them in a multidimensional array so they can be found accroding to grid x and y coordinate without iteration. The \"remove\" for the priority queue is gone. Which all made a big difference. But the real culprit was a function that iterated over all layer 1 map tiles. I made a smaller sub set of only relevant tiles to iterate over and it made a huge impact. I can now have 20 enemies that cannot reach their destination tile and no visible slow down. Thanks agai"
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T09:28:51.130",
"Id": "210161",
"ParentId": "210156",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "210161",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T07:20:58.670",
"Id": "210156",
"Score": "3",
"Tags": [
"java",
"game",
"a-star"
],
"Title": "A* Pathfinding for a Game"
} | 210156 |
<h1>Preface</h1>
<p><a href="https://docs.python.org/3/library/functions.html#sorted" rel="nofollow noreferrer"><code>sorted</code> built-in function</a> has <code>key</code> keyword-only parameter. Most of the custom implementations like the following for <a href="https://en.wikipedia.org/wiki/Heapsort" rel="nofollow noreferrer"><em>heapsort</em> algorithm</a></p>
<pre><code>import heapq
import itertools
from typing import (Iterable,
TypeVar)
Domain = TypeVar('Domain')
def heapsort(iterable: Iterable[Domain]) -> Iterable[Domain]:
heap = []
for element in iterable:
heapq.heappush(heap, element)
for _ in itertools.repeat(None, len(heap)):
yield heapq.heappop(heap)
</code></pre>
<p>has no <code>key</code> parameter support. I thought of a decorator that will add <code>key</code> parameter support in the next fashion</p>
<pre><code>from functools import wraps
from operator import itemgetter
from typing import (Callable,
Iterable,
Optional,
TypeVar)
Domain = TypeVar('Domain')
Sortable = TypeVar('Sortable')
def with_key(plain: Callable[[Iterable[Sortable]], Iterable[Sortable]]
) -> Callable[..., Iterable[Domain]]:
@wraps(plain)
def implementation(iterable: Iterable[Domain],
*,
key: Optional[Callable[[Domain], Sortable]] = None
) -> Iterable[Domain]:
if key is None:
yield from plain(iterable)
return
yield from map(itemgetter(2),
plain((key(element), index, element)
for index, element in enumerate(iterable)))
return implementation
</code></pre>
<p>and after that used like</p>
<pre><code>>>> heapsort_with_key = with_key(heapsort)
>>> list(heapsort_with_key(range(10), key=lambda x: -x))
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
</code></pre>
<h1>Problem</h1>
<p>I wonder if there is a better way (e.g. in terms of memory efficiency) of adding <code>key</code> parameter? Does anyone know how it is implemented in <code>sorted</code>? </p>
| [] | [
{
"body": "<p>Python is open-source, and all the source code in the GitHub repository <a href=\"https://github.com/python/cpython\" rel=\"nofollow noreferrer\">python/cpython</a>. For a great deal of the built-ins, they can be found in <a href=\"https://github.com/python/cpython/blob/master/Python/bltinmodule.c\" rel=\"nofollow noreferrer\">cpython/Python/bltinmodule.c\n</a>. In the current revision, the beginning of the sorted function definitions is found at <a href=\"https://github.com/python/cpython/blob/8ac658114dec4964479baecfbc439fceb40eaa79/Python/bltinmodule.c#L2175\" rel=\"nofollow noreferrer\">line 2175</a>, and the actual function itself is found at <a href=\"https://github.com/python/cpython/blob/8ac658114dec4964479baecfbc439fceb40eaa79/Python/bltinmodule.c#L2201\" rel=\"nofollow noreferrer\">line 2201</a>.</p>\n\n<p>However, I'm not sure that knowing the implementation of sorted can help you too much with optimizing heapsort, because sorted uses <a href=\"https://en.wikipedia.org/wiki/Timsort\" rel=\"nofollow noreferrer\">Timsort</a>.</p>\n\n<p>I can make a suggestion: decorators will always add overhead, and particularly in a case like this, it's probably better to just make a new version of the function that integrates the key parameter with the original function, though this answer might miss the entire point of your question.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T14:51:39.693",
"Id": "406238",
"Score": "0",
"body": "I'm writing a library and part of it deals with sorting, so I've thought about an unique way for users to register their own sorting algorithms implementations and simply decorating them to have `key` parameter support \"for free\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T14:54:25.860",
"Id": "406239",
"Score": "0",
"body": "my answer about built-in `sorted` was how it deals with `key` parameter internally, I'm not so experienced with `CPython` (and `C` in general) and can't see anything in given source lines related to `key` parameter"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T13:30:02.617",
"Id": "210171",
"ParentId": "210160",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T08:54:44.863",
"Id": "210160",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"sorting",
"meta-programming"
],
"Title": "Decorator to add key parameter support to an existing sort function"
} | 210160 |
<p>So I was working on merge sort today, and was trying to speed it up. I would like your opinion on the implementation and if it's possible to make it faster. Besides that I was wondering if there are any mistakes that i am making code wise, things that are considered a bad practice. </p>
<p>I like making algorithms for fun, and then when i make them I always try to improve them. One thing that I have noticed which i couldn't wrap my head around was that when you give a reverse sorted array as input it works faster than when you don't.</p>
<pre><code>public static void mergeSort(int[] array) {
mergeDivider(array,0,array.length-1);
}
private static void mergeDivider(int[] array, int lowBound, int highBound) {
if(lowBound < highBound) {
int middle = (lowBound + highBound)/2;
if((highBound - lowBound) <= 43){
//Found online that insertion sort is faster for n <= 43
mergeSortInsertionSortSpeedUp(array,lowBound,highBound);
} else {
//Normal divide and conquer
mergeDivider(array, lowBound, middle);
mergeDivider(array, middle + 1, highBound);
if(array[middle] > array[middle + 1]){
mergeSortMerger(array, lowBound, middle, highBound);
}
}
}
}
//Merge method
private static void mergeSortMerger(int[] array, int lowBound, int middle, int highBound) {
//Doesn't make seperate copies for left and right only makes a temporary array
int left_index = lowBound, right_index = middle + 1,temp_index = 0;
int[] temp_holder = new int[highBound - lowBound + 1];
while(left_index <= middle && right_index <= highBound){
if(array[left_index] < array[right_index]){
temp_holder[temp_index++] = array[left_index++];
} else {
temp_holder[temp_index++] = array[right_index++];
}
}
while(left_index <= middle){
temp_holder[temp_index++] = array[left_index++];
}
while(right_index <= highBound){
temp_holder[temp_index++] = array[right_index++];
}
//Put everything in the original array
for(int x = lowBound, k = 0; x <=highBound;x++,k++){
array[x] = temp_holder[k];
}
}
private static void mergeSortInsertionSortSpeedUp(int[] array, int left, int right){
for(int x = left; x <= right;x++){
int temp = array[x];
int before = x - 1;
while(before >= left && array[before] > temp){
array[before+1] = array[before];
before--;
}
array[before+1] = temp;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T17:43:53.550",
"Id": "406246",
"Score": "0",
"body": "`was trying to speed [up merge-sort]` Advice: be explicit about the base-line, think about/design a benchmark, look around if there's something useful (framework, test-set(-generator), whole benchmark). If possible, set a performance goal. For tape sort, there used to be multi-way merge-sorts: care to argue relevance thereof?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T21:13:49.867",
"Id": "406271",
"Score": "0",
"body": "(*faster with reverse sorted input* is most probably due to branch prediction.)"
}
] | [
{
"body": "<ul>\n<li><p>Mandatory stability note: the sequence</p>\n\n<pre><code> if(array[left_index] < array[right_index]){\n temp_holder[temp_index++] = array[left_index++];\n } else {\n temp_holder[temp_index++] = array[right_index++];\n }\n</code></pre>\n\n<p>causes loss of stability (equal elements are merged in the wrong order).</p></li>\n<li><p>The code still does unnecessary copying (from <code>tmp</code> back to <code>array</code>). It is unnecessary because it can be avoided. Allocate a temporary array once, then</p>\n\n<pre><code> merge_sort subrange 0 of arr into corresponding subrange of tmp\n merge_sort subrange 1 of arr into corresponding subrange of tmp\n merge subranges from tmp to arr\n</code></pre></li>\n<li><p>The insertion sort implementation is suboptimal. Testing two conditions in</p>\n\n<pre><code> while(before >= left && array[before] > temp)\n</code></pre>\n\n<p>can be avoided. Take a look at the Alex Stepanov's <a href=\"https://github.com/psoberoi/stepanov-conversations-course/blob/master/languages/java/Quicksort64.java\" rel=\"nofollow noreferrer\">technique</a> (he is talking about quicksort, but the first 4 methods, which you are are only interested in, are equally applicable to your case).</p></li>\n<li><p>The algorithms of this kind generally look better at the semi-open ranges. Try to rewrite the code with the assumption that <code>highBound</code> <em>does not</em> belong to the range.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T15:06:44.853",
"Id": "406326",
"Score": "0",
"body": "Thank you for you response, I was wondering what you meant with your second point. I vaguely understand what you mean, but not completely. I get that I might be able to do it more efficiently, but everytime i have tried so far, it didn't really do anything."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T18:42:32.130",
"Id": "210179",
"ParentId": "210170",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T13:15:16.977",
"Id": "210170",
"Score": "2",
"Tags": [
"java",
"algorithm",
"sorting",
"mergesort"
],
"Title": "Merge sort implementation with various improvements"
} | 210170 |
<p>I'm working on an app that will be used for employee management and I'm using MySQL for the database. You can add employees, view/update/delete them, and on the dashboard I'm listing them in different tables depending on what's needed.</p>
<p>I was wondering if my insert and update code can be improved somehow. Because my update code I think it looks hard to maintain/edit. I was also wondering if there is a more simple way to do it. <strong>It's huge and I'm not even at the middle of adding all of the fields I need to edit/update info for.</strong></p>
<p>This is my insert code (for adding new employees to my db):</p>
<pre><code><?php
$server = "localhost";
$user = "root";
$pass = "";
$dbname = "employees";
// Create connection
$conn = mysqli_connect($server, $user, $pass, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$fname = mysqli_real_escape_string($conn, $_POST['fname']);
$lname = mysqli_real_escape_string($conn, $_POST['lname']);
$dob = mysqli_real_escape_string($conn, $_POST['dob']);
$embg = mysqli_real_escape_string($conn, $_POST['embg']);
$address = mysqli_real_escape_string($conn, $_POST['address']);
$city = mysqli_real_escape_string($conn, $_POST['city']);
$mobile = mysqli_real_escape_string($conn, $_POST['mobile']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$workplace = mysqli_real_escape_string($conn, $_POST['workplace']);
$workposition = mysqli_real_escape_string($conn, $_POST['workposition']);
$jobstartdate = mysqli_real_escape_string($conn, $_POST['jobstartdate']);
$contractfrom = mysqli_real_escape_string($conn, $_POST['contractfrom']);
$contractto = mysqli_real_escape_string($conn, $_POST['contractto']);
$healthbookfrom = mysqli_real_escape_string($conn, $_POST['healthbookfrom']);
$healthbookto = mysqli_real_escape_string($conn, $_POST['healthbookto']);
$bankaccount = mysqli_real_escape_string($conn, $_POST['bankaccount']);
$bank = mysqli_real_escape_string($conn, $_POST['bank']);
$workcode = mysqli_real_escape_string($conn, $_POST['workcode']);
$gender = mysqli_real_escape_string($conn, $_POST['gender']);
$bloodtype = mysqli_real_escape_string($conn, $_POST['bloodtype']);
$notes = mysqli_real_escape_string($conn, $_POST['notes']);
$contract_file = basename($_FILES['contractupload']['name']);
$contract_path = "files/contracts/$contract_file";
$contract_file = mysqli_real_escape_string($conn, $contract_file);
copy($_FILES['contractupload']['tmp_name'], $contract_path); // copy the file to the folder
$sql = "INSERT INTO addemployees (fname, lname, dob, embg, address, city, mobile, email, workplace, workposition, jobstartdate, contractfrom, contractto, healthbookfrom,
healthbookto, contractupload, bankaccount, bank, workcode, gender, bloodtype, notes)
VALUES ('$fname', '$lname', '$dob', '$embg', '$address', '$city', '$mobile', '$email', '$workplace', '$workposition', '$jobstartdate', '$contractfrom', '$contractto',
'$healthbookfrom', '$healthbookto', '$contract_file', '$bankaccount', '$bank', '$workcode', '$gender', '$bloodtype', '$notes')";
if (mysqli_query($conn, $sql)) {
header("location: employees.php");
// echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
//Close the connection
mysqli_close($conn);
?>
</code></pre>
<p>And this is my update user info code:</p>
<pre><code><?php
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$fname = $lname = $dob = $embg = $address = $city = $mobile = $email = $workplace =
$workposition = $jobstartdate = $contractfrom = "";
$fname_err = $lname_err = $dob_err = $embg_err = $address_err = $city_err = $mobile_err =
$email_err = $workplace_err = $workposition_err = $jobstartdate_err = $contractfrom_err = "";
// Processing form data when form is submitted
if(isset($_POST["id"]) && !empty($_POST["id"])){
// Get hidden input value
$id = $_POST["id"];
// Validate First Name ($fname)
$input_fname = trim($_POST["fname"]);
if(empty($input_fname)){
$lname_err = "Please enter your First Name.";
} else{
$fname = $input_fname;
}
// Validate Last Name ($lname)
$input_lname = trim($_POST["lname"]);
if(empty($input_lname)){
$lname_err = "Please enter your Last Name.";
} else{
$lname = $input_lname;
}
// Validate Date of Birth ($dob)
$input_dob = trim($_POST["dob"]);
if(empty($input_dob)){
$dob_err = "Please enter your Date of Birth.";
} else{
$dob = $input_dob;
}
// Validate EMBG ($embg)
$input_embg = trim($_POST["embg"]);
if(empty($input_embg)){
$embg_err = "Please enter your EMBG.";
} else{
$embg = $input_embg;
}
// Validate Address ($address)
$input_address = trim($_POST["address"]);
if(empty($input_address)){
$address_err = "Please enter an address.";
} else{
$address = $input_address;
}
// Validate City ($city)
$input_city = trim($_POST["city"]);
if(empty($input_city)){
$city_err = "Please enter your City.";
} else{
$city = $input_city;
}
// Validate Mobile Number ($mobile)
$input_mobile = trim($_POST["mobile"]);
if(empty($input_mobile)){
$mobile_err = "Please enter your Mobile.";
} else{
$mobile = $input_mobile;
}
// Validate E-mail ($email)
$input_email = trim($_POST["email"]);
if(empty($input_email)){
$email_err = "Please enter your E-mail.";
} else{
$email = $input_email;
}
// Validate WorkPlace ($workplace)
$input_workplace = trim($_POST["workplace"]);
if(empty($input_workplace)){
$workplace_err = "Please choose your Work Place.";
} else{
$workplace = $input_workplace;
}
// Validate Work Position ($workposition)
$input_workposition = trim($_POST["workposition"]);
if(empty($input_workposition)){
$workposition_err = "Please choose your Work Position.";
} else{
$workposition = $input_workposition;
}
// Validate Job Start Date ($jobstartdate)
$input_jobstartdate = trim($_POST["jobstartdate"]);
if(empty($input_jobstartdate)){
$jobstartdate_err = "Please enter your Date of Birth.";
} else{
$jobstartdate = $input_jobstartdate;
}
// Validate Contract From ($contractfrom)
$input_contractfrom = trim($_POST["contractfrom"]);
if(empty($input_contractfrom)){
$contractfrom_err = "Please enter your Date of Birth.";
} else{
$contractfrom = $input_contractfrom;
}
// Check input errors before inserting in database jobstartdate
if(empty($fname_err) && empty($lname_err) && empty($dob_err) && empty($embg_err) && empty($address_err) && empty($city_err) && empty($mobile_err) &&
empty($email_err) && empty($workplace_err) && empty($workposition_err) && empty($jobstartdate_err) && empty($contractfrom_err)){
// Prepare an update statement
$sql = "UPDATE addemployees SET fname=?, lname=?, dob=?, embg=?, address=?, city=?, mobile=?, email=?, workplace=?,
workposition=?, jobstartdate=?, contractfrom=? WHERE id=?";
if($stmt = $mysqli->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bind_param("ssssssssssssi", $param_fname, $param_lname, $param_dob, $param_embg, $param_address, $param_city, $param_mobile, $param_email,
$param_workplace, $param_workposition, $param_jobstartdate, $param_contractfrom, $param_id);
// Set parameters
$param_id = $id;
$param_fname = $fname;
$param_lname = $lname;
$param_dob = $dob;
$param_embg = $embg;
$param_address = $address;
$param_city = $city;
$param_mobile = $mobile;
$param_email = $email;
$param_workplace = $workplace;
$param_workposition = $workposition;
$param_jobstartdate = $jobstartdate;
$param_contractfrom = $contractfrom;
// Attempt to execute the prepared statement
if($stmt->execute()){
// Records updated successfully. Redirect to landing page
header("location: employees.php");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
}
// Close statement
$stmt->close();
}
// Close connection
$mysqli->close();
} else{
// Check existence of id parameter before processing further
if(isset($_GET["id"]) && !empty(trim($_GET["id"]))){
// Get URL parameter
$id = trim($_GET["id"]);
// Prepare a select statement
$sql = "SELECT * FROM addemployees WHERE id = ?";
if($stmt = $mysqli->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bind_param("i", $param_id);
// Set parameters
$param_id = $id;
// Attempt to execute the prepared statement
if($stmt->execute()){
$result = $stmt->get_result();
if($result->num_rows == 1){
/* Fetch result row as an associative array. Since the result set contains only one row, we don't need to use while loop */
$row = $result->fetch_array(MYSQLI_ASSOC);
// Retrieve individual field value
$fname = $row["fname"];
$lname = $row["lname"];
$dob = $row["dob"];
$embg = $row["embg"];
$address = $row["address"];
$city = $row["city"];
$mobile = $row["mobile"];
$email = $row["email"];
$workplace = $row["workplace"];
$workposition = $row["workposition"];
$jobstartdate = $row["jobstartdate"];
$contractfrom = $row["contractfrom"];
} else{
// URL doesn't contain valid id. Redirect to error page
header("location: error.php");
exit();
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
$stmt->close();
// Close connection
$mysqli->close();
} else{
// URL doesn't contain id parameter. Redirect to error page
header("location: error.php");
exit();
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Update Record</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
.wrapper{
width: 500px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="page-header">
<h2>ะะทะผะตะฝะธ ะะพะดะฐัะพัะธ</h2>
</div>
<form action="<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>" method="post">
<div class="form-group <?php echo (!empty($fname_err)) ? 'has-error' : ''; ?>">
<label>ะะผะต</label>
<input type="text" id="fname" name="fname" class="form-control" value="<?php echo $fname; ?>">
<span class="help-block"><?php echo $fname_err;?></span>
</div>
<div class="form-group <?php echo (!empty($lname_err)) ? 'has-error' : ''; ?>">
<label>ะัะตะทะธะผะต</label>
<input type="text" name="lname" id="lname" class="form-control" value="<?php echo $lname; ?>">
<span class="help-block"><?php echo $lname_err;?></span>
</div>
<div class="form-group <?php echo (!empty($dob_err)) ? 'has-error' : ''; ?>">
<label>ะะฐัะฐ ะฝะฐ ะ ะฐัะฐัะต</label>
<input type="date" name="dob" id="dob" class="form-control" value="<?php echo $dob; ?>">
<span class="help-block"><?php echo $dob_err;?></span>
</div>
<div class="form-group <?php echo (!empty($embg_err)) ? 'has-error' : ''; ?>">
<label>ะะะะ</label>
<input type="text" name="embg" id="embg" class="form-control" maxlength="13" value="<?php echo $embg; ?>">
<span class="help-block"><?php echo $embg_err;?></span>
</div>
<div class="form-group <?php echo (!empty($address_err)) ? 'has-error' : ''; ?>">
<label>ะะดัะตัะฐ</label>
<input type="text" id="address" name="address" class="form-control" value="<?php echo $address; ?>">
<span class="help-block"><?php echo $address_err;?></span>
</div>
<div class="form-group <?php echo (!empty($city_err)) ? 'has-error' : ''; ?>">
<label>ะัะฐะด</label>
<input type="text" name="city" id="city" class="form-control" value="<?php echo $city; ?>">
<span class="help-block"><?php echo $city_err;?></span>
</div>
<div class="form-group <?php echo (!empty($mobile_err)) ? 'has-error' : ''; ?>">
<label>ะะพะฑะธะปะตะฝ</label>
<input type="text" name="mobile" id="mobile" class="form-control" maxlength="9" value="<?php echo $mobile; ?>">
<span class="help-block"><?php echo $mobile_err;?></span>
</div>
<div class="form-group <?php echo (!empty($email_err)) ? 'has-error' : ''; ?>">
<label>ะ-ะผะฐะธะป</label>
<input type="text" name="email" id="email" class="form-control" value="<?php echo $email; ?>">
<span class="help-block"><?php echo $email_err;?></span>
</div>
<div class="form-group <?php echo (!empty($workplace_err)) ? 'has-error' : ''; ?>">
<label>ะ ะฐะฑะพัะฝะพ ะะตััะพ <span style="font-size: 15px; color: rgb(255, 0, 0); margin-right: 15px;">(ะะ ะะะะ ะ)</span></label>
<select type="text" name="workplace" id="workplace" class="form-control" value="<?php echo $workplace; ?>">
<option value="ะะฐัะธั ะะข-1 - ะจะธัะพะบ ะกะพะบะฐะบ ะฑั. 55">ะะฐัะธั ะะข-1 - ะจะธัะพะบ ะกะพะบะฐะบ ะฑั. 55</option>
<option value="ะะฐัะธั ะะข-2 - ะจะธัะพะบ ะกะพะบะฐะบ ะฑั. 94">ะะฐัะธั ะะข-2 - ะจะธัะพะบ ะกะพะบะฐะบ ะฑั. 94</option>
<option value="ะะฐะฝั ะะฐั ะะข - ะจะธัะพะบ ะกะพะบะฐะบ ะฑั. 55">ะะฐะฝั ะะฐั ะะข - ะจะธัะพะบ ะกะพะบะฐะบ ะฑั. 55</option>
<option value="ะะปะฐะฒะตะฝ ะะฐะณะฐัะธะฝ - ะะพัะธะผะตัะบะฐ">ะะปะฐะฒะตะฝ ะะฐะณะฐัะธะฝ - ะะพัะธะผะตัะบะฐ</option>
</select>
<span class="help-block"><?php echo $workplace_err;?></span>
</div>
<div class="form-group <?php echo (!empty($workposition_err)) ? 'has-error' : ''; ?>">
<label>ะ ะฐะฑะพัะฝะฐ ะะพะทะธัะธัะฐ <span style="font-size: 15px; color: rgb(255, 0, 0); margin-right: 15px;">(ะะ ะะะะ ะ)</span></label>
<select type="text" name="workposition" id="workposition" class="form-control" value="<?php echo $workposition; ?>">
<option value="ะะตะปะฝะตั">ะะตะปะฝะตั</option>
<option value="ะจะฐะฝะบะตั">ะจะฐะฝะบะตั</option>
<option value="ะะพะปะฐัะธ">ะะพะปะฐัะธ</option>
<option value="ะกะปะฐะดะพะปะตะด">ะกะปะฐะดะพะปะตะด</option>
<option value="ะัะพะธะทะฒะพะดััะฒะพ ะกะปะฐะดะพะปะตะด">ะัะพะธะทะฒะพะดััะฒะพ ะกะปะฐะดะพะปะตะด</option>
<option value="ะัะพะธะทะฒะพะดััะฒะพ ะขะพััะธ">ะัะพะธะทะฒะพะดััะฒะพ ะขะพััะธ</option>
<option value="ะัะฒะฐั">ะัะฒะฐั</option>
<option value="ะะพะผะพัะฝะธะบ ะัะฒะฐั">ะะพะผะพัะฝะธะบ ะัะฒะฐั</option>
<option value="ะกะฐะปะฐัะตั">ะกะฐะปะฐัะตั</option>
<option value="ะะธัะตั">ะะธัะตั</option>
<option value="ะะตะฝะฐัะตั">ะะตะฝะฐัะตั</option>
<option value="ะะฝะธะณะพะฒะพะดะธัะตะป">ะะฝะธะณะพะฒะพะดะธัะตะป</option>
<option value="ะฅะธะณะธะตะฝะธัะฐั">ะฅะธะณะธะตะฝะธัะฐั</option>
<option value="ะกััะฐะถะฐั">ะกััะฐะถะฐั</option>
<option value="ะะฐะณะฐัะธะพะฝะตั">ะะฐะณะฐัะธะพะฝะตั</option>
<option value="ะจะพัะตั">ะจะพัะตั</option>
<option value="ะะธัััะธะฑััะตั">ะะธัััะธะฑััะตั</option>
</select>
<span class="help-block"><?php echo $workposition_err;?></span>
</div>
<div class="form-group <?php echo (!empty($jobstartdate_err)) ? 'has-error' : ''; ?>">
<label>ะะฐัะฐ ะฝะฐ ะะพัะฝัะฒะฐัะต ะฝะฐ ะ ะฐะฑะพัะฐ <span style="font-size: 15px; color: rgb(255, 0, 0); margin-right: 15px;">(ะะตัะตั/ะะตะฝ/ะะพะดะธะฝะฐ)</span></label>
<input type="date" name="jobstartdate" id="jobstartdate" class="form-control" value="<?php echo $jobstartdate; ?>">
<span class="help-block"><?php echo $jobstartdate_err;?></span>
</div>
<div class="form-group <?php echo (!empty($contractfrom_err)) ? 'has-error' : ''; ?>">
<label>ะะพะณะพะฒะพั ะทะฐ ัะฐะฑะพัะฐ ะพะด <span style="font-size: 15px; color: rgb(255, 0, 0); margin-right: 15px;">(ะะตัะตั/ะะตะฝ/ะะพะดะธะฝะฐ)</span></label>
<input type="date" name="contractfrom" id="contractfrom" class="form-control" value="<?php echo $contractfrom; ?>">
<span class="help-block"><?php echo $contractfrom_err;?></span>
</div>
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<input type="submit" class="btn btn-primary" value="Submit">
<a href="employees.php" class="btn btn-default">Cancel</a>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T07:05:44.493",
"Id": "406390",
"Score": "0",
"body": "The answer below doesn't answer your main question, how to keep the code size at bay. To answer this one you should rewrite it from 1990-x style to 2010-x style namely using a framework. Laravel would be a good choice for you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-27T10:51:10.673",
"Id": "406681",
"Score": "0",
"body": "\"_I was wondering if my insert and update code can be improved somehow._\" Both answers attempt to do this very thing. If you have advice on how to improve the code, then you should post your advice as an answer, not a comment. Your comment does not seek additional clarity/details so it is not suitable as a comment. Rather than put down others, put your expertise to good use and post constructive content in the places designed for it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-27T14:55:43.743",
"Id": "406723",
"Score": "0",
"body": "Laravel is a good framework, but we can't recommend using Laravel as a remedy for everything. In fact using a framework for such a small thing doesn't guarantee the project will have smaller code base. Half of this code is HTML which one way or another is still necessary. The other half are validation messages, which of course could be designed better but are also needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-28T09:10:27.793",
"Id": "406836",
"Score": "0",
"body": "@Dharman \"we can't recommend using Laravel as a remedy for everything\" is a correct statement by itself, but nowhere did I offer if for this purpose. I proposed to use Laravel to solve a certain problem for which it will be excellent, preventing the code from bloating when new fields are added. Both HTML and validation parts will shrunk catastrophically. You may want to try it to see for yourself."
}
] | [
{
"body": "<p>In your INSERT script:</p>\n\n<ul>\n<li>Use your config.php file everywhere instead of hardcoding your connection credentials.</li>\n<li>You should be checking that the POST elements actually exist before trying to access their values as a matter of best practice. I'd probably use a null coalescing operator or perhaps one giant <code>isset()</code> conditional (<code>isset()</code> can handle multiple arguments).</li>\n<li>If this was my script, I'd probably incorporate stronger validation checks on each incoming value so that the database is kept clean and meaningful. Rather than tell the user when something is missing, ratchet up the value requirements and inform the user that an expected value didn't have the expected format and describe in detail what is expected (dob format, email, bloodtype, gender etc).</li>\n<li>I'll recommend object-oriented mysqli syntax because it is more concise and in my opinion easier to read and maintain.</li>\n<li>Using a prepared statement will avoid all of that bloat with value escaping.</li>\n<li>You must never provide the actual mysql error when your application is public.</li>\n</ul>\n\n<p>In your UPDATE script:</p>\n\n<ul>\n<li>I don't know that I like the chained declaration of default empty strings for so many values -- it has a negative impact on readability and maintainability for a slight (unnecessary) benefit in script length.</li>\n<li>You should be checking that the POST elements actually exist before trying to access/<code>trim()</code> their values as a matter of best practice. I'd probably write the <code>trim()</code> call in the else portion of the condition block.</li>\n<li><code>isset($_POST[\"id\"]) && !empty($_POST[\"id\"])</code> is a redundant check, just remove the <code>isset()</code> condition because <code>!empty()</code> will accomplish the same thing.</li>\n<li>Rather than using lots of similar yet separate <code>_err</code> variables, just create an <code>$error</code> array and if there are any invalid values passed, just push them into the array. When deciding to proceed with the update query, just check the size of the error array. If <code>!sizeof($errors)</code>, then perform the update, else display all of the invalid values.</li>\n<li>Rather than trimming <code>$id</code>, just cast it as an integer with <code>(int)</code>.</li>\n<li>Jamming a value attribute like <code>value=\"<?php echo $workposition; ?>\"</code> is not going to work in your <code><select></code> fields.</li>\n</ul>\n\n<p>As a matter of personal preference, I tend to write all my negative/failure/error outcomes before my successful outcomes in my condition blocks. By writing the SELECT statement last, you can move directly into your html form portion which should make things easier to associate and debug.</p>\n\n<p>Try to avoid single-use variable declarations. If they improve the readability of your code, that can be a sound justification. However, generally your code will be easier to maintain if you have fewer variables in your global scope.</p>\n\n<p>Finally, because you are processing multibyte characters, be sure to do <a href=\"https://stackoverflow.com/q/279170/2943403\">UTF-8 All The Way Through</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T00:02:50.663",
"Id": "406373",
"Score": "1",
"body": "First of all thank you very much for having the time to read my post and go through my code (i know it's huge and i'll work on it). \nThank you very much for all of your suggestion. I'll go through all of them individually and 'fix' my code. \n\nAgain thanks a lot man."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T00:05:05.597",
"Id": "406374",
"Score": "0",
"body": "There are probably more refinements to make. Be sure to check back for other volunteers' reviews that may come later."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-26T23:34:06.240",
"Id": "406621",
"Score": "0",
"body": "Why should they put `trim` in the else part of the condition? Isn't it better to get rid of spaces before checking if the input is empty? What if the user accidentally entered a space? Without trimming, your application will accept the space as valid input and then trim it producing empty value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-26T23:35:37.807",
"Id": "406622",
"Score": "0",
"body": "Why is it better to check the size with `!sizeof($errors)` of the array instead of plain `if(!$errors)`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-26T23:46:18.617",
"Id": "406626",
"Score": "0",
"body": "Okay, `if(!$errors)` spares a function call -- uae that. You can call `trim()` after an `isset()` call to avoid generating Notices. If you are concerned with invalid input, you should perform a stronger check than just deflecting a space."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-27T07:25:38.747",
"Id": "406659",
"Score": "0",
"body": "@Dharman using isset for the POST form is a questionable practice. If a regular field is not set, it doesn't mean that a user didin't fill it up but that your form is incorrect or was tampered with. You aren't supposed to silently let it go as it will be with isset(). So unless your field is checkbox or radio, do not use isset() but instead let the error be. This is what error messages are for. Despite that most PHP users think, \"Undefined variable\" notice doesn't exist to only nag them and to make them devise ways to circumvent this error. It is for the good."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-27T08:22:39.867",
"Id": "406667",
"Score": "1",
"body": "@Dharman I am talking about Notices not Errors. Using `!isset()` or `empty()` is a good way to process submissions that are incomplete/fooled-with. At no point am I endorsing \"letting it go\", rather I recommend handling the unexpected occurrence directly/sensibly."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T23:36:22.360",
"Id": "210248",
"ParentId": "210173",
"Score": "4"
}
},
{
"body": "<p>Here are my ideas.<br>\nFor the insert script I have the same recommendations as @mickmackusa. Stay consistent and use object-oriented syntax for mysqli and prepared statements. You might find it easier to use PDO instead of mysqli, but it is probably too late at this stage unless your project is still small and you are willing to swap.</p>\n\n<p>Update script:</p>\n\n<ol>\n<li><p>Don't create so many aliases on your variables. There is no reason for it if you are not modifying their value. If 2 variables hold the same value, but have different name your code gets harder to understand.</p></li>\n<li><p>Don't declare empty strings explicitly. Try out my nifty trick of using trim with null-coalesce operator*: <code>trim($_POST['fname'] ?? '');</code> It doesn't trigger a notice and also defaults to an empty string if the variable doesn't exist. Personally I don't agree here with @mickmackusa statements that your should call <code>isset</code> before <code>trim</code>, I see no benefit in doing so, and much more prefer defaulting it to a null or empty string.</p></li>\n<li><p>Use <code>isset</code> or <code>empty</code>. There is no need to call them both. Try: <code>if (!empty($_POST['id'])) {</code></p></li>\n<li><p>Your <code>id</code> should be an integer so you should enforce that. A short way of doing so would be <code>$id = (int) ($_POST['id'] ?? null);</code>, but keep in mind that your should do more data validation than this!</p></li>\n<li><p>Use an associative array for your validation errors. This makes the syntax simpler (see answer by @mickmackusa), and still allows you to separate the messages. An empty array is falsish value so you can just check <code>if(!$errors)</code> to see if the validations passed.<br>\nIn your HTML form you can then check if the key exists and display the message. Here again you could use null-coalesce operator*: <code><?php echo $validation_errors['embg'] ?? '';?></code> to get rid of the pesky notices, or you could redesign your HTML to display the <code><span></code> only if the message exists.</p></li>\n<li><p>Close your mysqli statement in the same code block it was created or not at all, PHP will do it for you anyway. If the prepare call fails it will return FALSE and your can't call <code>FALSE->close()</code>. Close the statement only if prepare was successful.</p></li>\n<li><p>Exit with a header. Exit can take an argument in the form of a string and header returns nothing which makes it a perfect pair to put together: <code>exit(header('location: employees.php'));</code>. Saves you one line at least.</p></li>\n<li><p>No need for an else statement after the <code>exit</code>. Exit will terminate the script so else part will never be reached. </p></li>\n<li><p>You should close mysqli connection either in the same block of code it was created or not at all. When PHP script terminated it will close the connection for you automatically. If you really need to close it yourself don't put it inside an if statement.</p></li>\n<li><p>The only statement in the else part is an if statement. Use <code>elseif</code> instead. In your case the statement can be <code>if/elseif/else</code> instead of <code>if{if/else}</code></p></li>\n<li><p><strong>Prevent XSS!</strong> Never output raw data regardless of where it came from. Use <code>htmlspecialchars($str, ENT_QUOTES | ENT_HTML5, 'UTF-8');</code> on any data displayed into HTML. I have created a wrapper function to make it simpler to call this. </p></li>\n<li><p><a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select\" rel=\"nofollow noreferrer\">HMTL select tag</a> doesn't have <code>type</code> or <code>value</code> attributes. </p></li>\n</ol>\n\n<p>* If you are not yet on >=PHP 7, then instead of null coalesce operator you need to use a longer syntax with an <code>isset</code> or create a shim.</p>\n\n<pre><code><?php\n// Include config file\nrequire_once 'config.php';\n\n// Processing form data when form is submitted\nif (!empty($_POST['id'])) {\n // Get hidden input value\n $id = (int) ($_POST['id'] ?? null);\n\n // define an empty array for validation errors to be displayed in HTML form\n $validation_errors = [];\n\n // Validate First Name ($fname)\n $fname = trim($_POST['fname'] ?? '');\n if (empty($fname)) {\n $validation_errors['fname'] = 'Please enter your First Name.';\n }\n\n // Validate Last Name ($lname)\n $lname = trim($_POST['lname'] ?? '');\n if (empty($lname)) {\n $validation_errors['lname'] = 'Please enter your Last Name.';\n }\n\n // Validate Date of Birth ($dob)\n $dob = trim($_POST['dob'] ?? '');\n if (empty($dob)) {\n $validation_errors['dob'] = 'Please enter your Date of Birth.';\n }\n\n // Validate EMBG ($embg)\n $embg = trim($_POST['embg'] ?? '');\n if (empty($embg)) {\n $validation_errors['embg'] = 'Please enter your EMBG.';\n }\n\n // Validate Address ($address)\n $address = trim($_POST['address'] ?? '');\n if (empty($address)) {\n $validation_errors['address'] = 'Please enter an address.';\n }\n\n // Validate City ($city)\n $city = trim($_POST['city'] ?? '');\n if (empty($city)) {\n $validation_errors['city'] = 'Please enter your City.';\n }\n\n // Validate Mobile Number ($mobile)\n $mobile = trim($_POST['mobile'] ?? '');\n if (empty($mobile)) {\n $validation_errors['mobile'] = 'Please enter your Mobile.';\n }\n\n // Validate E-mail ($email)\n $email = trim($_POST['email'] ?? '');\n if (empty($email)) {\n $validation_errors['email'] = 'Please enter your E-mail.';\n }\n\n // Validate WorkPlace ($workplace)\n $workplace = trim($_POST['workplace'] ?? '');\n if (empty($workplace)) {\n $validation_errors['workplace'] = 'Please choose your Work Place.';\n }\n\n // Validate Work Position ($workposition)\n $workposition = trim($_POST['workposition'] ?? '');\n if (empty($workposition)) {\n $validation_errors['workposition'] = 'Please choose your Work Position.';\n }\n\n // Validate Job Start Date ($jobstartdate)\n $jobstartdate = trim($_POST['jobstartdate'] ?? '');\n if (empty($jobstartdate)) {\n $validation_errors['jobstartdate'] = 'Please enter your Date of Birth.';\n }\n\n // Validate Contract From ($contractfrom)\n $contractfrom = trim($_POST['contractfrom'] ?? '');\n if (empty($contractfrom)) {\n $validation_errors['contractfrom'] = 'Please enter your Date of Birth.';\n }\n\n\n // Check input errors before inserting in database jobstartdate\n if (!$validation_errors) {\n // Prepare an update statement\n $sql = 'UPDATE addemployees SET fname=?, lname=?, dob=?, embg=?, address=?, city=?, mobile=?, email=?, workplace=?,\n workposition=?, jobstartdate=?, contractfrom=? WHERE id=?';\n\n if ($stmt = $mysqli->prepare($sql)) {\n // Bind variables to the prepared statement as parameters\n $stmt->bind_param(\n 'ssssssssssssi',\n $fname,\n $lname,\n $dob,\n $embg,\n $address,\n $city,\n $mobile,\n $email,\n $workplace,\n $workposition,\n $jobstartdate,\n $contractfrom,\n $id\n );\n\n // Attempt to execute the prepared statement\n if ($stmt->execute()) {\n // Records updated successfully. Redirect to landing page\n exit(header('location: employees.php')); // exit with a header\n }\n echo 'Something went wrong. Please try again later.';\n\n // Close statement\n // $stmt->close(); // it's redundant in this context\n }\n }\n} elseif ($id = (int)$_GET['id']) {\n // Check existence of id parameter before processing further\n\n // Prepare a select statement\n $sql = 'SELECT * FROM addemployees WHERE id = ?';\n\n if ($stmt = $mysqli->prepare($sql)) {\n // Bind variables to the prepared statement as parameters\n $stmt->bind_param('i', $id);\n\n // Attempt to execute the prepared statement\n if ($stmt->execute()) {\n $result = $stmt->get_result();\n if ($result->num_rows) {\n // Fetch result row as an associative array. Since the result set contains only one row, we don't need to use while loop\n $row = $result->fetch_array(MYSQLI_ASSOC);\n\n // Retrieve individual field value\n $fname = $row['fname'];\n $lname = $row['lname'];\n $dob = $row['dob'];\n $embg = $row['embg'];\n $address = $row['address'];\n $city = $row['city'];\n $mobile = $row['mobile'];\n $email = $row['email'];\n $workplace = $row['workplace'];\n $workposition = $row['workposition'];\n $jobstartdate = $row['jobstartdate'];\n $contractfrom = $row['contractfrom'];\n } else {\n // URL doesn't contain valid id. Redirect to error page\n exit(header('location: error.php')); // exit with a header\n }\n } else {\n echo 'Oops! Something went wrong. Please try again later.';\n }\n\n // Close statement\n // $stmt->close(); // it's redundant in this context\n }\n} else {\n // URL doesn't contain id parameter. Redirect to error page\n exit(header('location: error.php')); // exit with a header\n}\n\n\n// Close connection\n// $mysqli->close(); // it's redundant in this context\n\n\nfunction clean_HTML(string $str): string\n{\n return htmlspecialchars($str, ENT_QUOTES | ENT_HTML5, 'UTF-8');\n}\n\n?>\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <title>Update Record</title>\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css\">\n <style type=\"text/css\">\n .wrapper{\n width: 500px;\n margin: 0 auto;\n }\n </style>\n</head>\n<body>\n <div class=\"wrapper\">\n <div class=\"container-fluid\">\n <div class=\"row\">\n <div class=\"col-md-12\">\n <div class=\"page-header\">\n <h2>ะะทะผะตะฝะธ ะะพะดะฐัะพัะธ</h2>\n </div>\n <form action=\"<?php echo htmlspecialchars(basename($_SERVER['REQUEST_URI'])); ?>\" method=\"post\">\n\n <div class=\"form-group <?php echo isset($validation_errors['fname']) ? 'has-error' : ''; ?>\">\n <label>ะะผะต</label>\n <input type=\"text\" id=\"fname\" name=\"fname\" class=\"form-control\" value=\"<?php echo clean_HTML($fname); ?>\">\n <span class=\"help-block\"><?php echo $validation_errors['fname'] ?? '';?></span>\n </div>\n\n <div class=\"form-group <?php echo isset($validation_errors['lname']) ? 'has-error' : ''; ?>\">\n <label>ะัะตะทะธะผะต</label>\n <input type=\"text\" name=\"lname\" id=\"lname\" class=\"form-control\" value=\"<?php echo clean_HTML($lname); ?>\">\n <span class=\"help-block\"><?php echo $validation_errors['lname'] ?? '';?></span>\n </div>\n\n <div class=\"form-group <?php echo isset($validation_errors['dob']) ? 'has-error' : ''; ?>\">\n <label>ะะฐัะฐ ะฝะฐ ะ ะฐัะฐัะต</label>\n <input type=\"date\" name=\"dob\" id=\"dob\" class=\"form-control\" value=\"<?php echo clean_HTML($dob); ?>\">\n <span class=\"help-block\"><?php echo $validation_errors['dob'] ?? '';?></span>\n </div>\n\n <div class=\"form-group <?php echo isset($validation_errors['embg']) ? 'has-error' : ''; ?>\">\n <label>ะะะะ</label>\n <input type=\"text\" name=\"embg\" id=\"embg\" class=\"form-control\" maxlength=\"13\" value=\"<?php echo clean_HTML($embg); ?>\">\n <span class=\"help-block\"><?php echo $validation_errors['embg'] ?? '';?></span>\n </div>\n\n <div class=\"form-group <?php echo isset($validation_errors['address']) ? 'has-error' : ''; ?>\">\n <label>ะะดัะตัะฐ</label>\n <input type=\"text\" id=\"address\" name=\"address\" class=\"form-control\" value=\"<?php echo clean_HTML($address); ?>\">\n <span class=\"help-block\"><?php echo $validation_errors['address'] ?? '';?></span>\n </div>\n\n <div class=\"form-group <?php echo isset($validation_errors['city']) ? 'has-error' : ''; ?>\">\n <label>ะัะฐะด</label>\n <input type=\"text\" name=\"city\" id=\"city\" class=\"form-control\" value=\"<?php echo clean_HTML($city); ?>\">\n <span class=\"help-block\"><?php echo $validation_errors['city'] ?? '';?></span>\n </div>\n\n <div class=\"form-group <?php echo isset($validation_errors['mobile']) ? 'has-error' : ''; ?>\">\n <label>ะะพะฑะธะปะตะฝ</label>\n <input type=\"text\" name=\"mobile\" id=\"mobile\" class=\"form-control\" maxlength=\"9\" value=\"<?php echo clean_HTML($mobile); ?>\">\n <span class=\"help-block\"><?php echo $validation_errors['mobile'] ?? '';?></span>\n </div>\n\n <div class=\"form-group <?php echo isset($validation_errors['email']) ? 'has-error' : ''; ?>\">\n <label>ะ-ะผะฐะธะป</label>\n <input type=\"text\" name=\"email\" id=\"email\" class=\"form-control\" value=\"<?php echo clean_HTML($email); ?>\">\n <span class=\"help-block\"><?php echo $validation_errors['email'] ?? '';?></span>\n </div>\n\n <div class=\"form-group <?php echo isset($validation_errors['workplace']) ? 'has-error' : ''; ?>\">\n <label>ะ ะฐะฑะพัะฝะพ ะะตััะพ <span style=\"font-size: 15px; color: rgb(255, 0, 0); margin-right: 15px;\">(ะะ ะะะะ ะ)</span></label>\n <select name=\"workplace\" id=\"workplace\" class=\"form-control\" >\n <option value=\"ะะฐัะธั ะะข-1 - ะจะธัะพะบ ะกะพะบะฐะบ ะฑั. 55\">ะะฐัะธั ะะข-1 - ะจะธัะพะบ ะกะพะบะฐะบ ะฑั. 55</option>\n <option value=\"ะะฐัะธั ะะข-2 - ะจะธัะพะบ ะกะพะบะฐะบ ะฑั. 94\">ะะฐัะธั ะะข-2 - ะจะธัะพะบ ะกะพะบะฐะบ ะฑั. 94</option>\n <option value=\"ะะฐะฝั ะะฐั ะะข - ะจะธัะพะบ ะกะพะบะฐะบ ะฑั. 55\">ะะฐะฝั ะะฐั ะะข - ะจะธัะพะบ ะกะพะบะฐะบ ะฑั. 55</option>\n <option value=\"ะะปะฐะฒะตะฝ ะะฐะณะฐัะธะฝ - ะะพัะธะผะตัะบะฐ\">ะะปะฐะฒะตะฝ ะะฐะณะฐัะธะฝ - ะะพัะธะผะตัะบะฐ</option>\n </select>\n <span class=\"help-block\"><?php echo $validation_errors['workplace'] ?? '';?></span>\n </div>\n\n <div class=\"form-group <?php echo isset($validation_errors['workposition']) ? 'has-error' : ''; ?>\">\n <label>ะ ะฐะฑะพัะฝะฐ ะะพะทะธัะธัะฐ <span style=\"font-size: 15px; color: rgb(255, 0, 0); margin-right: 15px;\">(ะะ ะะะะ ะ)</span></label>\n <select name=\"workposition\" id=\"workposition\" class=\"form-control\" >\n <option value=\"ะะตะปะฝะตั\">ะะตะปะฝะตั</option>\n <option value=\"ะจะฐะฝะบะตั\">ะจะฐะฝะบะตั</option>\n <option value=\"ะะพะปะฐัะธ\">ะะพะปะฐัะธ</option>\n <option value=\"ะกะปะฐะดะพะปะตะด\">ะกะปะฐะดะพะปะตะด</option>\n <option value=\"ะัะพะธะทะฒะพะดััะฒะพ ะกะปะฐะดะพะปะตะด\">ะัะพะธะทะฒะพะดััะฒะพ ะกะปะฐะดะพะปะตะด</option>\n <option value=\"ะัะพะธะทะฒะพะดััะฒะพ ะขะพััะธ\">ะัะพะธะทะฒะพะดััะฒะพ ะขะพััะธ</option>\n <option value=\"ะัะฒะฐั\">ะัะฒะฐั</option>\n <option value=\"ะะพะผะพัะฝะธะบ ะัะฒะฐั\">ะะพะผะพัะฝะธะบ ะัะฒะฐั</option>\n <option value=\"ะกะฐะปะฐัะตั\">ะกะฐะปะฐัะตั</option>\n <option value=\"ะะธัะตั\">ะะธัะตั</option>\n <option value=\"ะะตะฝะฐัะตั\">ะะตะฝะฐัะตั</option>\n <option value=\"ะะฝะธะณะพะฒะพะดะธัะตะป\">ะะฝะธะณะพะฒะพะดะธัะตะป</option>\n <option value=\"ะฅะธะณะธะตะฝะธัะฐั\">ะฅะธะณะธะตะฝะธัะฐั</option>\n <option value=\"ะกััะฐะถะฐั\">ะกััะฐะถะฐั</option>\n <option value=\"ะะฐะณะฐัะธะพะฝะตั\">ะะฐะณะฐัะธะพะฝะตั</option>\n <option value=\"ะจะพัะตั\">ะจะพัะตั</option>\n <option value=\"ะะธัััะธะฑััะตั\">ะะธัััะธะฑััะตั</option>\n </select>\n <span class=\"help-block\"><?php echo $validation_errors['workposition'] ?? '';?></span>\n </div>\n\n <div class=\"form-group <?php echo isset($validation_errors['jobstartdate']) ? 'has-error' : ''; ?>\">\n <label>ะะฐัะฐ ะฝะฐ ะะพัะฝัะฒะฐัะต ะฝะฐ ะ ะฐะฑะพัะฐ <span style=\"font-size: 15px; color: rgb(255, 0, 0); margin-right: 15px;\">(ะะตัะตั/ะะตะฝ/ะะพะดะธะฝะฐ)</span></label>\n <input type=\"date\" name=\"jobstartdate\" id=\"jobstartdate\" class=\"form-control\" value=\"<?php echo clean_HTML($jobstartdate); ?>\">\n <span class=\"help-block\"><?php echo $validation_errors['jobstartdate'] ?? '';?></span>\n </div>\n\n <div class=\"form-group <?php echo isset($validation_errors['contractfrom']) ? 'has-error' : ''; ?>\">\n <label>ะะพะณะพะฒะพั ะทะฐ ัะฐะฑะพัะฐ ะพะด <span style=\"font-size: 15px; color: rgb(255, 0, 0); margin-right: 15px;\">(ะะตัะตั/ะะตะฝ/ะะพะดะธะฝะฐ)</span></label>\n <input type=\"date\" name=\"contractfrom\" id=\"contractfrom\" class=\"form-control\" value=\"<?php echo clean_HTML($contractfrom); ?>\">\n <span class=\"help-block\"><?php echo $validation_errors['contractfrom'] ?? '';?></span>\n </div>\n\n\n <input type=\"hidden\" name=\"id\" value=\"<?php echo $id; ?>\"/>\n <input type=\"submit\" class=\"btn btn-primary\" value=\"Submit\">\n <a href=\"employees.php\" class=\"btn btn-default\">Cancel</a>\n </form>\n </div>\n </div>\n </div>\n </div>\n</body>\n</html>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-27T14:33:08.367",
"Id": "406714",
"Score": "0",
"body": "\"Otherwise ?id=abc would trigger mysqli error. \" - here you are wrong again :) PHP and mysql are famous for being very permissive about input types. Neither Mysql nor PHP would complain if you bind a string to a prepared statement that expects an int. it will be silently converted"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-27T14:35:43.817",
"Id": "406715",
"Score": "0",
"body": "So your recommendation is to throw at mysql whatever you get and hope for the best? If you know the type then check that the parameter is of that type before you execute the query."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-27T14:41:24.437",
"Id": "406716",
"Score": "0",
"body": "Yes, that's my recommendation. A suggestion should be reasonable, it should have an explanation. It shouldn't be just an order \"do like I said!\". It will create a very bad kind of programmer - a cargo cult programmer who have no idea what they do and why. So you had an explanation, but it turned to be not true. Therefore you should either find another explanation or withdraw the suggestion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-27T16:18:20.157",
"Id": "406737",
"Score": "0",
"body": "Mod Note: I removed quite a bunch of comments here. I highly recommend perusing [chat] for extended discussions around posts. Thanks!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-27T01:36:07.540",
"Id": "210393",
"ParentId": "210173",
"Score": "4"
}
},
{
"body": "<p>Let me introduce you to loops.</p>\n\n<p>A loop is a very important element of a program, it can relieve us from most fatiguing jobs. However important it is, at the same time it is very easy to implement. Frankly, every time you see repeated blocks in your code, you can tell for sure that they can be replaced with a loop.</p>\n\n<p>So, first of all we must define such blocks in your code. As we can see, it's data validation and form output. Let's see, if we can define variable parts in your repeated code blocks and put them in arrays, and then use these arrays to populate just a single code block in a loop:</p>\n\n<pre><code><?php\n// Include config file\nrequire_once \"config.php\";\n\n// Define all inputs\n$config = [\n 'fname' => 'ะะผะต',\n 'lname' => 'ะัะตะทะธะผะต',\n 'dob' => 'ะะฐัะฐ ะฝะฐ ะ ะฐัะฐัะต',\n 'embg' => 'ะะะะ',\n 'address' => 'ะะดัะตัะฐ',\n 'city' => 'ะัะฐะด',\n 'mobile' => 'ะะพะฑะธะปะตะฝ',\n 'email' => 'ะ-ะผะฐะธะป',\n 'workplace' => 'ะ ะฐะฑะพัะฝะพ ะะตััะพ',\n 'workposition' => 'ะ ะฐะฑะพัะฝะฐ ะะพะทะธัะธัะฐ',\n 'jobstartdate' => 'ะะฐัะฐ ะฝะฐ ะะพัะฝัะฒะฐัะต ะฝะฐ ะ ะฐะฑะพัะฐ',\n 'contractfrom' => 'ะะพะณะพะฒะพั ะทะฐ ัะฐะฑะพัะฐ ะพะด',\n];\n// take all field names\n$fields = array_keys($config);\n\nif ($_POST) {\n\n // Define an array for errors\n $errors = [];\n\n // Let's collect all values here\n $input = [];\n\n // And let's validate all fields in one simple loop!\n foreach ($fields as $field) {\n $input[$field] = trim($_POST[$field]);\n if (!$input[$field]) {\n $errors[$field] = true;\n }\n }\n\n if (!$errors) {\n\n if (!empty($_POST['id'])) {\n $input['id'] = $_POST['id'];\n $sql = \"UPDATE addemployees SET fname=?, lname=?, dob=?, embg=?, address=?, city=?, mobile=?, email=?, workplace=?,\n workposition=?, jobstartdate=?, contractfrom=? WHERE id=?\";\n $stmt = $mysqli->prepare($sql);\n $stmt->bind_param(\"ssssssssssssi\", ...array_values($input));\n $stmt->execute();\n } else {\n $sql = \"INSERT INTO addemployees SET fname=?, lname=?, dob=?, embg=?, address=?, city=?, mobile=?, email=?, workplace=?,\n workposition=?, jobstartdate=?, contractfrom=?\";\n $stmt = $mysqli->prepare($sql);\n $stmt->bind_param(\"ssssssssssss\", ...array_values($input));\n $stmt->execute();\n }\n header(\"location: employees.php\");\n exit();\n }\n} elseif(!empty($_GET[\"id\"])) {\n\n $sql = \"SELECT * FROM addemployees WHERE id = ?\";\n $stmt = $mysqli->prepare($sql);\n $stmt->bind_param(\"i\", $_GET[\"id\"]);\n $stmt->execute();\n $input = $stmt->get_result()->fetch_assoc();\n\n if (!$input) {\n exit(\"Record not found\");\n }\n} else {\n // Let's fill all fields with empty strings \n foreach ($fields as $field) {\n $input[$field] = \"\";\n }\n}\n// a shorthand function for htmlspecialchars()\nfunction e($str)\n{\n return htmlspecialchars($str, ENT_QUOTES, 'utf-8');\n}\n?>\n\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <title>Update Record</title>\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css\">\n <style type=\"text/css\">\n .wrapper{\n width: 500px;\n margin: 0 auto;\n }\n </style>\n</head>\n<body>\n<div class=\"wrapper\">\n <div class=\"container-fluid\">\n <div class=\"row\">\n <div class=\"col-md-12\">\n <div class=\"page-header\">\n <h2>ะะทะผะตะฝะธ ะะพะดะฐัะพัะธ</h2>\n </div>\n <form action=\"\" method=\"post\">\n <?php foreach (['fname', 'lname', 'dob', 'embg', 'address', 'city', 'mobile', 'email'] as $field ): ?>\n <div class=\"form-group <?= (!empty($errors[$field])) ? 'has-error' : ''; ?>\">\n <label><?=$config[$field]?></label>\n <input type=\"text\" id=\"<?=$field?>\" name=\"<?=$field?>\" class=\"form-control\" value=\"<?= e($input[$field]) ?>\">\n <span class=\"help-block\">Please enter your <?=$config[$field]?></span>\n </div>\n <?php endforeach ?>\n <div class=\"form-group <?= (!empty($errors['workplace'])) ? 'has-error' : ''; ?>\">\n <label>ะ ะฐะฑะพัะฝะพ ะะตััะพ <span style=\"font-size: 15px; color: rgb(255, 0, 0); margin-right: 15px;\">(ะะ ะะะะ ะ)</span></label>\n <select type=\"text\" name=\"workplace\" id=\"workplace\" class=\"form-control\" value=\"<?= e($input['workplace']) ?>\">\n <option value=\"ะะฐัะธั ะะข-1 - ะจะธัะพะบ ะกะพะบะฐะบ ะฑั. 55\">ะะฐัะธั ะะข-1 - ะจะธัะพะบ ะกะพะบะฐะบ ะฑั. 55</option>\n <option value=\"ะะฐัะธั ะะข-2 - ะจะธัะพะบ ะกะพะบะฐะบ ะฑั. 94\">ะะฐัะธั ะะข-2 - ะจะธัะพะบ ะกะพะบะฐะบ ะฑั. 94</option>\n <option value=\"ะะฐะฝั ะะฐั ะะข - ะจะธัะพะบ ะกะพะบะฐะบ ะฑั. 55\">ะะฐะฝั ะะฐั ะะข - ะจะธัะพะบ ะกะพะบะฐะบ ะฑั. 55</option>\n <option value=\"ะะปะฐะฒะตะฝ ะะฐะณะฐัะธะฝ - ะะพัะธะผะตัะบะฐ\">ะะปะฐะฒะตะฝ ะะฐะณะฐัะธะฝ - ะะพัะธะผะตัะบะฐ</option>\n </select>\n <span class=\"help-block\">Please enter your ะ ะฐะฑะพัะฝะพ ะะตััะพ</span>\n </div>\n\n <div class=\"form-group <?= (!empty($errors['workposition'])) ? 'has-error' : ''; ?>\">\n <label>ะ ะฐะฑะพัะฝะฐ ะะพะทะธัะธัะฐ <span style=\"font-size: 15px; color: rgb(255, 0, 0); margin-right: 15px;\">(ะะ ะะะะ ะ)</span></label>\n <select type=\"text\" name=\"workposition\" id=\"workposition\" class=\"form-control\" value=\"<?= e($input['workposition']) ?>\">\n <option value=\"ะะตะปะฝะตั\">ะะตะปะฝะตั</option>\n <option value=\"ะจะฐะฝะบะตั\">ะจะฐะฝะบะตั</option>\n <option value=\"ะะพะปะฐัะธ\">ะะพะปะฐัะธ</option>\n <option value=\"ะกะปะฐะดะพะปะตะด\">ะกะปะฐะดะพะปะตะด</option>\n <option value=\"ะัะพะธะทะฒะพะดััะฒะพ ะกะปะฐะดะพะปะตะด\">ะัะพะธะทะฒะพะดััะฒะพ ะกะปะฐะดะพะปะตะด</option>\n <option value=\"ะัะพะธะทะฒะพะดััะฒะพ ะขะพััะธ\">ะัะพะธะทะฒะพะดััะฒะพ ะขะพััะธ</option>\n <option value=\"ะัะฒะฐั\">ะัะฒะฐั</option>\n <option value=\"ะะพะผะพัะฝะธะบ ะัะฒะฐั\">ะะพะผะพัะฝะธะบ ะัะฒะฐั</option>\n <option value=\"ะกะฐะปะฐัะตั\">ะกะฐะปะฐัะตั</option>\n <option value=\"ะะธัะตั\">ะะธัะตั</option>\n <option value=\"ะะตะฝะฐัะตั\">ะะตะฝะฐัะตั</option>\n <option value=\"ะะฝะธะณะพะฒะพะดะธัะตะป\">ะะฝะธะณะพะฒะพะดะธัะตะป</option>\n <option value=\"ะฅะธะณะธะตะฝะธัะฐั\">ะฅะธะณะธะตะฝะธัะฐั</option>\n <option value=\"ะกััะฐะถะฐั\">ะกััะฐะถะฐั</option>\n <option value=\"ะะฐะณะฐัะธะพะฝะตั\">ะะฐะณะฐัะธะพะฝะตั</option>\n <option value=\"ะจะพัะตั\">ะจะพัะตั</option>\n <option value=\"ะะธัััะธะฑััะตั\">ะะธัััะธะฑััะตั</option>\n </select>\n <span class=\"help-block\">Please enter your ะ ะฐะฑะพัะฝะฐ ะะพะทะธัะธัะฐ</span>\n </div>\n <?php foreach (['jobstartdate','contractfrom'] as $field ): ?>\n <div class=\"form-group <?= (!empty($errors[$field])) ? 'has-error' : ''; ?>\">\n <label><?=$config[$field]?></label>\n <input type=\"text\" id=\"<?=$field?>\" name=\"<?=$field?>\" class=\"form-control\" value=\"<?= e($input[$field]) ?>\">\n <span class=\"help-block\">Please enter your <?=$config[$field]?></span>\n </div>\n <?php endforeach ?>\n <?php if (isset($input['id'])): ?>\n <input type=\"hidden\" name=\"id\" value=\"<?php echo $input['id']; ?>\"/>\n <?php endif ?>\n <input type=\"submit\" class=\"btn btn-primary\" value=\"Submit\">\n <a href=\"employees.php\" class=\"btn btn-default\">Cancel</a>\n </form>\n </div>\n </div>\n </div>\n</div>\n</body>\n</html>\n</code></pre>\n\n<p>As you can see, this code, although covering both insert and update cases, is almost <strong>three times shorter than your initial code</strong>.</p>\n\n<p>Moreover, adding a regular field would make it bigger by one single line - a new member in <code>$config</code> variable. Which, I believe, does answer your main question, how to make this code easier to maintain.</p>\n\n<p>Please be advised though: this code is essentially 2000s' PHP at best. It is better than your 1990s' code, but it is still considered outdated nowadays. In 2018 you are supposed to use a <em>framework</em> for such a task. And or a reason:</p>\n\n<p>Your code is oversimplified. In reality you will need different validations, different HTML in different form fields and so on. when you will try to implement all this in raw PHP, your code will start to bloat again. But, given such a task of adding / editing a record in the database is so common, that all popular frameworks offer very sleek solutions, including configurable validations, form generation, SQL automation and many, many more other things that will make even a customized code concise and maintainable. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-28T15:01:47.823",
"Id": "210496",
"ParentId": "210173",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "210248",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T17:02:39.813",
"Id": "210173",
"Score": "4",
"Tags": [
"php",
"html",
"mysql",
"mysqli"
],
"Title": "Adding / updating user info into MySQL database"
} | 210173 |
<p>I built a chess game in C++. My main concern is the design. For example, in the board class it has a 2D array of pieces. This array represents the positions of the pieces, but the piece class also has a variable to store its position (used to check the validity of the move sense each piece has a different move capabilities).</p>
<p><strong>main.cpp</strong></p>
<pre><code>#include <iostream>
#include "board.h"
#include "Piece.h"
#include "Presenter.h"
#include "utilities.h"
int main()
{
Board board;
Presenter presenter(&board);
presenter.draw();
std::cout <<endl<< "make a move by writing old then new coordinates of the piece you want to move ex: (0,1) -> (0,5)" << endl;
int oldX, oldY, newX, newY;
while (1)
{
cin >> oldX >> oldY >> newX >> newY;
// making sure the numbers are within the board
if (oldX > 8 || oldY > 8 || newX > 8 || newY > 8)
{
cout << "one or more number is larger than 8" << endl;
continue;
}
oldX--; oldY--; newX--; newY--;
//making sure the move is valid
if (board.move({ oldX, oldY }, { newX, newY }) == invalid)
{
cout << "error: you can't move pieces from the other player " <<
endl;
}
presenter.draw();
}
}
</code></pre>
<p><strong>Board.cpp</strong></p>
<pre><code>#include "board.h"
#include <utility>
#include <algorithm>
using namespace std;
Board::Board()
{
active_player = player1;
// initializing pieces array
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++) {
if (i < 2) pieces[i][j] = new Piece({ i, j }, player1); //the first two rows for player1
else if (i>5) pieces[i][j] = new Piece({ i, j }, player2); //the last two rows for player2
else pieces[i][j] = new Piece({ i, j }, empty); //all other rows are empty
}
}
}
// changes the position of the piece if its a valid move
move_state Board::move(Coord old_pos, Coord new_pos)
{
if (pieces[old_pos.x][old_pos.y]->get_owner() != active_player)
return invalid;
else if (pieces[old_pos.x][old_pos.y]->change_position(new_pos) == valid)
{
std::swap(pieces[new_pos.x][new_pos.y], pieces[old_pos.x][old_pos.y]);
active_player = (active_player == player1) ? player2 : player1; // toggle active_player after each valid move
return valid;
}
else return invalid;
}
Board::~Board()
{
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++) {
free(pieces[i][j]);
}
}
}
</code></pre>
<p><strong>board.h</strong></p>
<pre><code>#pragma once
#include "Piece.h"
#include "utilities.h"
#include <vector>
using namespace std;
class Board{
Player active_player;
Piece *pieces[8][8];
public:
Board();
~Board();
move_state move(Coord old_pos, Coord new_pos);
Player get_player(Coord pos)
{
if (pieces[pos.x][pos.y] != nullptr) return pieces[pos.x][pos.y]->get_owner();
else return empty;
}
};
</code></pre>
<p><strong>piece.h</strong></p>
<pre><code>#pragma once
#include "utilities.h"
class Piece{
Player owner;
Coord position;
public :
Piece(Coord pos, Player _owner) :
owner(_owner),
position(pos)
{
}
Player get_owner(){ return owner; }
move_state change_position(Coord pos)
{
position.x = pos.x;
position.y = pos.y;
return valid; // checking is not supported all moves are valid
}
};
</code></pre>
<p><strong>presenter.cpp</strong></p>
<pre><code>#include "Presenter.h"
#include <iostream>
using namespace std;
Presenter::~Presenter()
{
}
void Presenter::draw()
{
cout << " 1 2 3 4 5 6 7 8 ";
cout << endl << " | ";
for (int i = 0; i < 8; i++){
for (int j = 0; j < 8; j++){
if (board->get_player({ i, j }) == player1) cout << "A" << " ";
if (board->get_player({ i, j }) == player2) cout << "B" << " ";
if (board->get_player({ i, j }) == empty) cout << "O" << " ";
}
cout << "| "<< i+1 << endl<<" | ";
}
}
</code></pre>
<p><strong>presenter.h</strong></p>
<pre><code>#pragma once
#include "board.h"
class Presenter
{
Board * board;
public:
Presenter(Board* b){
board = b;
};
void draw();
~Presenter();
};
</code></pre>
<p><strong>utilities.h</strong></p>
<pre><code>#pragma once
enum Player
{
player1,
player2,
empty
};
struct Coord
{
unsigned char x;
unsigned char y;
};
enum move_state{
valid,
invalid
};
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T22:02:19.683",
"Id": "406275",
"Score": "7",
"body": "This doesnโt answer your question, but the #1 advice I can give is to turn `Piece *pieces[8][8];` into `Piece pieces[8][8];`, and remove all references to operator `new`. A Piece is small, it doesnโt need dynamic allocation. If it were larger or needed dynamic allocation for another reason, you should use a `std::unique_ptr` to own each piece. Donโt use `new` unless there are no alternatives."
}
] | [
{
"body": "<p>@CrisLuengo's advice is valid. Past that, even if you were to keep your usage of <code>new</code>, there's a very important rule to follow: never mix C and C++ dynamic memory allocation. You've used <code>new</code> and then <code>free</code>, when you should be using <code>new</code> and then <code>delete</code>. Depending on your C libraries, compiler and system, this kind of mixing can do very bad things, potentially stack smashing, etc.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T02:14:38.680",
"Id": "210199",
"ParentId": "210176",
"Score": "3"
}
},
{
"body": "<ul>\n<li>Consistency helps other people read, understand, and trust your code. This includes:\n\n<ul>\n<li>consistent whitespace (e.g. leaving an empty line after <code>#include</code>s),</li>\n<li>capitalization of file names (<code>board.h</code> vs <code>Presenter.h</code>),</li>\n<li>variable and type naming style (<code>Coord</code> vs <code>move_state</code>),</li>\n<li>putting all function definitions in the .cpp files, instead of just some of them.</li>\n</ul></li>\n<li><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">Don't use <code>using namespace std;</code></a>.</li>\n<li><a href=\"https://stackoverflow.com/a/18335862/673679\">Use <code>enum class</code> instead of plain <code>enum</code> for type-safety.</a></li>\n</ul>\n\n<hr>\n\n<ul>\n<li>Variables should be declared as close to the point of use as practical (<code>oldX</code>, <code>oldY</code>, <code>newX</code>, <code>newY</code> should be inside the loop in <code>main</code>).</li>\n<li><p>Validate input thoroughly. There's no guarantee that what the user enters is an int, so we have to check that reading from <code>cin</code> worked each time. If it didn't we then have to clear the error flags on the stream, and ignore the invalid input:</p>\n\n<pre><code>if (std::cin.fail())\n{\n std::cin.clear();\n std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\\n');\n}\n</code></pre>\n\n<p>It would therefore be better to abstract the request for user input to a separate function with a signature like: <code>bool readCoord(Coord& value);</code></p></li>\n<li><p>While we check that the input values are not too high (e.g. <code>oldX < 8</code>), we also have to check that they are not too low (if the user enters <code>-1</code>). Which leads on to...</p></li>\n<li>Use unsigned types where numbers should not be negative (e.g. for indexing into arrays).</li>\n<li>We could make this neater by using the <code>Coord</code> class and adding a new function to the board: <code>if (!(board.InBounds(old) && board.InBounds(new))) ...</code>.</li>\n<li>This line <code>oldX--; oldY--; newX--; newY--;</code> indicates that we're using 1-based indexing, but the <code>\"...of the piece you want to move ex: (0,1) -> (0,5)\"</code> implies 0-based indexing. Note that for 1-based indexing, we also need to check that we don't have an index of 0, even if we're using an unsigned index type.</li>\n<li>Nitpick: use <code>while (true)</code> instead of <code>while (1)</code>. It's a more direct statement of intent, since the latter is shorthand for <code>while (1 != 0)</code>.</li>\n</ul>\n\n<hr>\n\n<ul>\n<li><p>Don't duplicate the position inside the <code>Piece</code> class. Checking that the move is valid should be done by the board (or better by a separate <code>Rules</code> class).</p></li>\n<li><p>The dynamic allocation of pieces might be understandable if we were using a <code>nullptr</code> for empty squares, but without that there's no advantage over storing all the pieces by value (and all the disadvantages pointed out by Reinderien).</p></li>\n<li><p>It might be better to store pieces in an array of <code>std::optional<Piece></code>, instead of having a special <code>empty</code> value in your <code>Player</code> enum for pieces that don't actually exist.</p></li>\n<li><p><code>Presenter</code> should probably store a <code>const Board&</code> instead of a <code>Board*</code>. This means <code>Presenter</code> can never be given a <code>nullptr</code>, and it shows that <code>Presenter</code> never changes the board.</p></li>\n<li><p><code>Board::get_player</code> can then be a const function: <code>Player get_player(Coord pos) const;</code>, since it doesn't alter the data members of the board class.</p></li>\n<li><p><code>Presenter</code> can use the member initializer list to initialize the <code>board</code> variable (like the <code>Board</code> class does). Note that initializer lists specifically allow using the same name for function arguments as used for the member variable.</p></li>\n<li><p>Since the <code>Presenter</code> destructor does nothing, we don't need to define it ourselves.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T10:31:38.410",
"Id": "210210",
"ParentId": "210176",
"Score": "3"
}
},
{
"body": "<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. It is particularly bad to put it into a header file, so please don't do that.</p>\n\n<h2>Use the approprate data types</h2>\n\n<p>If the <code>Coord</code> values are <code>unsigned char</code>, then the loops that generate coordinates should use that instead. For convenience, and to allow for flexibility, I'd suggest either something like this:</p>\n\n<pre><code>using CoordInt = unsigned char;\nstruct Coord\n{\n CoordInt x;\n CoordInt y;\n};\n</code></pre>\n\n<p>or perhaps better, make <code>Coord</code> a class and do validation of the coordinates in the constructor so that it is not possible to create invalid coordinates.</p>\n\n<h2>Do better error checking</h2>\n\n<p>If the coordinates passed to <code>Board::move</code> are invalid (i.e. not actually on the board, the program will not work as intended due to <em>undefined behavior</em>. Eliminate that either by doing validation of the coordinates where needed or, as per the previous suggestion, make it impossible for invalid coordinates to be constructed.</p>\n\n<h2>Don't mislead the user</h2>\n\n<p>The user is told \"make a move by writing old then new coordinates of the piece you want to move ex: (0,1) -> (0,5)\" but if the user actually enters those <strong>zero-based</strong> coordinates, the program crashes, because what the program <em>actually</em> expects are 1-based coordinates without commas or parentheses or any other punctuation. This leads directly to the next suggestion.</p>\n\n<h2>Use standard nomenclature where it applies</h2>\n\n<p>In chess, the <a href=\"https://en.wikipedia.org/wiki/Algebraic_notation_(chess)\" rel=\"nofollow noreferrer\">standard algebraic notation</a> has been widely used for decades. Experienced chess players will already know that notation, and it won't matter to players who aren't already familiar. Use that notation instead of the number pairs the program currently used.</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>Use <code>delete</code> instead of <code>free</code> in C++</h2>\n\n<p>The <code>Board</code> destructor uses <code>free</code> instead of <code>delete</code> which is an error. C++ uses <code>new</code> and <code>delete</code>. The other suggestions say you shouldn't use <code>free</code> and <code>delete</code> at all, but I understand that your intent is to have <code>Piece</code> be a base class, so this usage is appropriate once you fix this error.</p>\n\n<h2>Use const where practical</h2>\n\n<p>The current <code>Piece::get_owner()</code> routine does not (and should not) modify the underlying object, and so it should be declared <code>const</code>:</p>\n\n<pre><code>Player get_owner() const { return owner; }\n</code></pre>\n\n<p>The same is true of <code>Presenter::draw()</code>.</p>\n\n<h2>Reduce the use of raw pointers where practical</h2>\n\n<p>There is no useful thing that a <code>Presenter</code> can do with a <code>Board</code> pointer that is <code>nullptr</code>, so I'd strongly recommend using a <code>std::shared_ptr</code> instead or by having the <code>Board</code> object be a member of the <code>Presenter</code> class.</p>\n\n<h2>Let the compiler create default destructor</h2>\n\n<p>The compiler will create a destructor by default which is essentially identical to what you've got for the <code>Presenter</code> class, so you can simply omit both the declaration and implementation from your code.</p>\n\n<h2>Use consistent file names</h2>\n\n<p>Is it <code>board.h</code> or <code>Board.h</code>? <code>Presenter.h</code> or <code>presenter.h</code>? It's important to be consistent because consistency aids reader comprehension.</p>\n\n<h2>Rethink the class design</h2>\n\n<p>If we think about a future version of this program that actually has rooks, knights, etc. What will each piece need to determine whether a move is valid? The current interface only passes the proposed new coordinates to <code>change_position</code>. However, this is not enough information. A bishop, for instance, cannot jump over other pieces, so determining a valid move will require examining all of the points between the current and proposed position as well. This information more properly belongs to the <code>Board</code> class, so I would recommend passing a <code>Board</code> reference to the <code>Piece</code> to allow it to check for move validity. Also, for some moves, such as castling, or capturing a pawn <em>en passant</em>, two pieces are involved and not only their positions but something about their history must be known. For all of these reasons, I'd suggest that only the <code>Board</code> should know about positions, and to eliminate the <code>Coord</code> member from each <code>Piece</code> and that any move validity checking should pass not only the proposed <code>Coord</code> but the <code>Board</code> and current <code>Coord</code> as well.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-27T07:01:23.497",
"Id": "455364",
"Score": "0",
"body": "One question - if we have a class for the Game , should it own actual players or references to players. If it owns actual ones, destroying game would free up the players, otherwise it can be reference or pointers and we will need to ensure, caller frees up the memory etc. My main point is thinking OOP principles which is preferred? Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-27T13:36:14.157",
"Id": "455409",
"Score": "1",
"body": "It would depend on the context. If it's simply done as a two-player single game, I'd probably have the board own the `Player` objects, if `Player` objects are even needed. If it's intended to be part of a tournament, then the players would need to exist outside the context of a single game, so references would make more sense."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-27T18:07:15.847",
"Id": "455464",
"Score": "0",
"body": "Thanks a lot for confirming :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T17:43:48.417",
"Id": "210233",
"ParentId": "210176",
"Score": "6"
}
},
{
"body": "<h2>Pass by reference?</h2>\n\n<p>Not everyone agrees, however, references ain't allowed to be nullptr. If you don't expect a nullptr, pass by reference instead of pointer.</p>\n\n<pre><code>Presenter presenter(board);\n</code></pre>\n\n<h2>Initialize your variables</h2>\n\n<p>It's always a good idea to initialize your variables, even when replacing the values with cin.\nCin leaves the value unmodified, when entering invalid data. So you have undefined behavior in your program.</p>\n\n<p>So either initialize your values to an invalid value OR</p>\n\n<h2>Check on input failure</h2>\n\n<pre><code>if (!cin >> oldX)\n // Handle error\n</code></pre>\n\n<h2>Check boundaries</h2>\n\n<p>As indicated entering <code>a b c d</code> causes problems, entering <code>0 1 2 3</code> does as well as it will result in out of bounds access.</p>\n\n<h2>Use compound initialization</h2>\n\n<p>If things are good they deserve a mention as well. Calling the move with pairs clearly indicates for the caller how it's grouped:</p>\n\n<pre><code>if (board.move({ oldX, oldY }, { newX, newY })\n</code></pre>\n\n<h2>Use standard types</h2>\n\n<pre><code> if (board.move({ oldX, oldY }, { newX, newY }) == invalid)\n</code></pre>\n\n<p>Why return a special value, when you only check on failure? A bool will work as well.</p>\n\n<h2>std::unique_ptr</h2>\n\n<pre><code> if (i < 2) pieces[i][j] = new Piece({ i, j }, player1);\n</code></pre>\n\n<p>From C++14 on, using <code>std::make_unique<Piece>(...)</code> is recommended. Storing the value in a unique_ptr indicates ownership clearly, while preventing memory-leak.</p>\n\n<h2>Constants</h2>\n\n<pre><code> for (int i = 0; i < 8; i++)\n</code></pre>\n\n<p>8 is a really nice number, putting it in a constant allows you to give it a name.</p>\n\n<h2>Check on pointers</h2>\n\n<pre><code> if (pieces[old_pos.x][old_pos.y]->get_owner() != active_player)\n</code></pre>\n\n<p>You haven't checked your pointer on null. Again you assume valid input.</p>\n\n<h2>Const?</h2>\n\n<p>If you don't expect changes to an instance, make it const. If catches simple mistakes and clearly sets expectations.</p>\n\n<pre><code> Player get_player(Coord pos) const\n</code></pre>\n\n<h2>Initializer list</h2>\n\n<pre><code>Presenter(Board& b) : board(b) {\n board = b;\n };\n</code></pre>\n\n<h2>Scoped enumerations</h2>\n\n<pre><code>enum class Player { ... };\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-28T21:28:57.253",
"Id": "210524",
"ParentId": "210176",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "210233",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T18:13:18.457",
"Id": "210176",
"Score": "6",
"Tags": [
"c++",
"object-oriented",
"chess"
],
"Title": "Chess game design in C++"
} | 210176 |
<blockquote>
<p>User has three attempts (locks you out for 10 seconds if you fail) to log in to send an email. Afterwards, you need to insert your username and password to send your message to someone of your will.</p>
</blockquote>
<p>Any improvements that I can make? </p>
<pre><code>import smtplib
import time
def send_mail() :
try :
content = input("Type in your content :")
mail = smtplib.SMTP('smtp.gmail.com', 587)
mail.ehlo()
mail.starttls()
username = input("Username :")
password = input("Password :")
mail.login(username,password)
receiver = input("Receiver : ")
mail.sendmail(username, receiver, content)
mail.close()
except smtplib.SMTPException :
print("Error. Mail was not sent.")
else :
print("Success. Mail sent.")
if __name__ == '__main__' :
password = "password123"
num_of_tries = 3
input_password = input("Enter password")
'3 attempts before locking you out for 10 seconds.'
while password != input_password :
num_of_tries -= 1
if num_of_tries == 0 :
print("Try again in 10 seconds")
time.sleep(10)
num_of_tries = 3
input_password = input(str(num_of_tries) + " Attempts Remaining. Password : ")
if password == input_password :
print("Success.")
send_mail()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T20:41:19.390",
"Id": "406262",
"Score": "0",
"body": "Indentation seems to be off. Please fix."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T20:50:10.363",
"Id": "406265",
"Score": "0",
"body": "I don't get it. I used code block, yet the indentation won't be fixed...My indentation seems fine on my IDE."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T20:54:37.193",
"Id": "406268",
"Score": "1",
"body": "I took a liberty to edit. Is everything OK?"
}
] | [
{
"body": "<pre><code>def send_mail() :\n</code></pre>\n\n<p>Per PEP8, you wouldn't typically include a space before those colons. You should run your code through a linter.</p>\n\n<pre><code>password = input(\"Password :\")\n</code></pre>\n\n<p>This is a big no-no. Never expose a user's password content on the screen if you can avoid it. Instead, use the built-in <code>getpass</code> which attempts to mask your input.</p>\n\n<pre><code>mail.close()\n</code></pre>\n\n<p>You should avoid doing this explicitly, and instead use <code>mail</code> in a <code>with</code> statement.</p>\n\n<pre><code>'3 attempts before locking you out for 10 seconds.'\n</code></pre>\n\n<p>This line has no effect. Perhaps you meant to write <code>print</code> here. Also, don't hard-code the <code>3</code> in the string; use <code>num_of_tries</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T02:03:45.780",
"Id": "210198",
"ParentId": "210181",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T19:33:35.883",
"Id": "210181",
"Score": "1",
"Tags": [
"python"
],
"Title": "User needs to type in the password to send an email"
} | 210181 |
<p>I have a text file like this example:</p>
<pre><code>>chr12:86512-86521
CGGCCAAAG
>chr16:96990-96999
CTTTCATTT
>chr16:97016-97025
TTTTGATTA
>chr16:97068-97077
ATTTAGGGA
</code></pre>
<p>This file is divided into different parts, and every part has 2 lines. The line which starts with <code>></code> is ID and the 2nd line is a sequence of letters and the letters are <code>A, T, C or G</code> and also the length of each sequence is 9 so, for every sequence of letters there are 9 positions. I want to get the frequency of the 4 mentioned letters in every position (we have 9 positions).</p>
<p>Here is the expected output for the small example:</p>
<pre><code>one = {'T': 1, 'A': 1, 'C': 2, 'G': 0}
two = {'T': 3, 'A': 0, 'C': 0, 'G': 1}
three = {'T': 3, 'A': 0, 'C': 0, 'G': 1}
four = {'T': 3, 'A': 0, 'C': 1, 'G': 0}
five = {'T': 0, 'A': 1, 'C': 2, 'G': 1}
six = {'T': 0, 'A': 3, 'C': 0, 'G': 1}
seven = {'T': 2, 'A': 1, 'C': 0, 'G': 1}
eight = {'T': 2, 'A': 1, 'C': 0, 'G': 1}
nine = {'T': 1, 'A': 2, 'C': 0, 'G': 1}
</code></pre>
<p>I am doing that in Python using the following command. This command has 3 steps. Steps 1 and 2 work fine, but would you help me to improve step 3, which made this pipeline so slow for big files?</p>
<h1>Step 1: to parse the file into a comma-separated file</h1>
<pre><code>def fasta_to_textfile(filename, outfile):
with open(filename) as f, open(outfile, 'w') as outfile:
header = sequence = None
out = csv.writer(outfile, delimiter=',')
for line in f:
if line.startswith('>'):
if header:
entry = header + [''.join(sequence)]
out.writerow(entry)
header = line.strip('>\n').split('|')
sequence = []
else:
sequence.append(line.strip())
if header:
entry = header + [''.join(sequence)]
out.writerow(entry)
</code></pre>
<h1>Step 2: comma-separated file to a Python dictionary</h1>
<pre><code>def file_to_dict(filename):
f = open(filename, 'r')
answer = {}
for line in f:
k, v = line.strip().split(',')
answer[k.strip()] = v.strip()
return answer
</code></pre>
<h1>To print functions from steps 1 and 2:</h1>
<pre><code>a = fasta_to_textfile('infile.txt', 'out.txt')
d = file_to_dict('out.txt')
</code></pre>
<h1>Step 3: to get the frequency</h1>
<pre><code>one=[]
two=[]
three=[]
four=[]
five=[]
six=[]
seven=[]
eight=[]
nine=[]
mylist = d.values()
for seq in mylist:
one.append(seq[0])
two.append(seq[1])
se.append(seq[2])
four.append(seq[3])
five.append(seq[4])
six.append(seq[5])
seven.append(seq[6])
eight.append(seq[7])
nine.append(seq[8])
from collections import Counter
one=Counter(one)
two=Counter(two)
three=Counter(three)
four=Counter(four)
five=Counter(five)
</code></pre>
| [] | [
{
"body": "<p>You forgot to add <code>import csv</code> and <code>from collections import Counter</code>. Probably missed it while copy pasting. Also, your <code>=</code> signs are inconsistent in step 3. Try to follow <strong>PEP8</strong>. Also, <code>a</code> is useless in this line:</p>\n\n<pre><code>a = fasta_to_textfile('infile.txt', 'out.txt')\n</code></pre>\n\n<p>Since you've programmed a void function, <code>a = None</code> because it returns nothing.</p>\n\n<p>Is the conversion to the CSV file really necessary? This would be an example of the pipeline:</p>\n\n<ol>\n<li>Read the file.</li>\n<li>Extract the sequence and load it into a N*9 table, where N is the number of sequences</li>\n<li>Swap the rows and columns (<code>numpy</code> can help you out here)</li>\n<li>A simple <code>for</code> loop that uses the <code>Counter</code> function on each row (but really column), refactored into less lines. Sadly I don't have time right to rewrite bits of your code right now.</li>\n</ol>\n\n<p>One last thing - are you sure your example is correct? I tried loading it but got: <code>ValueError: not enough values to unpack (expected 2, got 1)</code>...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T00:17:29.873",
"Id": "210193",
"ParentId": "210184",
"Score": "1"
}
},
{
"body": "<p>That's a crazy amount of code for such a simple task. There's no need to generate any intermediate files. There's no need to create nine separate variables for the nine columns.</p>\n\n<p>To process an input file (whether from <code>sys.stdin</code> or as a named argument on the command line), use <a href=\"https://docs.python.org/3/library/fileinput.html\" rel=\"nofollow noreferrer\"><code>fileinput</code></a>. That way, you don't have to hard-code <code>'infile.txt'</code>. Then, simply ignore the lines that start with <code>></code> and strip off the newlines.</p>\n\n<p>To work on columns rather than rows, use <a href=\"https://docs.python.org/3/library/functions.html#zip\" rel=\"nofollow noreferrer\"><code>zip()</code></a>.</p>\n\n<h2>Suggested solution</h2>\n\n<p>These seven lines could replace your entire code.</p>\n\n<pre><code>import fileinput\nfrom collections import Counter\n\ndef nucleotide_lines(f):\n for line in f:\n if not line.startswith('>'):\n yield line.rstrip()\n\nprint([Counter(col) for col in zip(*nucleotide_lines(fileinput.input()))])\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T09:37:18.823",
"Id": "213646",
"ParentId": "210184",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T20:20:40.023",
"Id": "210184",
"Score": "1",
"Tags": [
"python",
"bioinformatics"
],
"Title": "Getting the frequency of letters in each position"
} | 210184 |
<p>Building out a React component that is supposed to hold the following information and display it in a feed-like page. The idea is to later map over the individual entries in an array.</p>
<ul>
<li>Author</li>
<li>Timestamp</li>
<li>Message Title</li>
<li>Message body</li>
</ul>
<p>Currently, I have the following code in one file (BuildingUpdateBox.js):</p>
<pre><code>import React from 'react';
import "./BuildingUpdateBox.css"
const BuildingUpdateBoxHeader = (props) => {
const author = props.author ? `Author: ${props.author}` : 'No Author'
return (
<div className="building-update-box-header">
<span className="building-update-box-header-item">{author}</span>
<span className="building-update-box-header-item">Timestamp: {props.timestamp}</span>
</div>
)
}
const BuildingUpdateBoxBody = (props) => {
return (
<div className="building-update-box-body">
<div className="building-update-box-body-title"><h2>{props.title}</h2></div>
<div className="building-update-box-body-message"><p>{props.message}</p></div>
</div>
)
}
const BuildingUpdateBox = (props) => {
return (
<div className="wrapper">
<div className="building-update-box">
<BuildingUpdateBoxHeader
author={props.content.author}
timestamp={props.content.timestamp}
/>
<BuildingUpdateBoxBody
title={props.content.title}
message={props.content.message}
/>
</div>
</div>
)
}
export default BuildingUpdateBox;
</code></pre>
<p>And in App.js (I currently use create-react-app):</p>
<pre><code>const message = {
author: 'Joe Smith',
timestamp: '2018/12/22',
title: 'Broken Heater',
message: 'Dear tenants, we will have a plumber onsite tomorrow, who will replace the broken boiler. We apologize for the inconvenience. If you have any questions, please feel free to reach out to 123-456-7890.'
};
class App extends Component {
render() {
return (
<div>
<BuildingUpdateBox content={message} />
</div>
);
}
}
</code></pre>
<p>I'm looking to hear if I should:</p>
<ul>
<li>Place the functional components into their own files (with reasoning)</li>
<li>Even use 3 separate functions, since I don't ever see the Header or Body being used without the Box and vice versa</li>
<li>Do anything with the way I import the CSS</li>
</ul>
| [] | [
{
"body": "<p>Generally if you want a more in depth review you should provide more code and a potential specifics you want to improve on; your code is very thin, and so it's a little difficult to help you expand on it, however, I would say that there's a few different things you can do to this to improve or follow a different direction forward.</p>\n\n<p>Your use of pure components is good for <code>BuildingUpdateBoxHeader</code> and <code>BuildingUpdateBoxBody</code> as using primitive props is better for performance. However, using a <code>content</code> object inside your props for <code>BuildingUpdateBox</code> means React cannot shallow compare your props and is unable to determine when not to rerender the component, causing potentially wasted rerenders.</p>\n\n<p>I would recommend trying JSS (css in js) to embed your styles directly in your application for an alternate solution to specifying <code>className</code> manually. This couples your css with its implementation rather than needing to update both the css & js when you modify them.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-25T13:02:27.510",
"Id": "210310",
"ParentId": "210186",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T21:01:05.407",
"Id": "210186",
"Score": "4",
"Tags": [
"javascript",
"ecmascript-6",
"react.js"
],
"Title": "React Component Design"
} | 210186 |
<p>Assume you have the following data in the form of a <code>csv</code>-file. The content looks something like this:</p>
<pre class="lang-none prettyprint-override"><code>,Action,Comedy,Horror
1,650,819,
,76,63,
2,,462,19
,,18,96
3,652,457,18
,75,36,89
</code></pre>
<p>which can be interpreted as a table of the form:</p>
<pre class="lang-none prettyprint-override"><code> Action Comedy Horror
1 650 819
76 63
2 462 19
18 96
3 652 457 18
75 36 89
</code></pre>
<p>The goal was to write a function that takes a <code>lst</code> with genre names as elements in form of a <code>str</code> and returns a scatter plot of the data, where the data that should appear on the scatter plot is in the second row of every index (<code>76, 63 ,</code> and <code>, 18, 96</code> and <code>75, 36, 89</code>). The function should be able to distinguish between two-dimensional and three-dimensional scatter plots depending on the input.</p>
<pre class="lang-pye prettyprint-override"><code>from pandas import DataFrame
from csv import reader
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def genre_scatter(lst):
"""
Creates an scatter plot using the data from genre_scores.csv.
:param lst: a list with names of the genres considered
:return: saves a pdf-file to the folder Fig with the name gen_1_ge_2.pdf
"""
# First we need to determine the right columns of genre_scores.
first_row = [row for row in reader(open('genre_scores.csv', 'r'))][0]
index = [first_row.index(x) for x in lst]
# Get the relevant data in the form of a DataFrame.
# Please note that the first row of data for every index is not necessary for this task.
data = DataFrame.from_csv('genre_scores.csv')
gen_scores = [data.dropna().iloc[1::2, ind - 1].transpose() for ind in index]
# rewrite the values in an flattened array for plotting
coordinates = [gen.as_matrix().flatten() for gen in gen_scores]
# Plot the results
fig = plt.figure()
if len(coordinates) == 2:
plt.scatter(*coordinates)
plt.text(70, 110, "pearson={}".format(round(pearson_coeff(coordinates[0], coordinates[1]), 3)))
plt.xlabel(lst[0])
plt.ylabel(lst[1])
plt.savefig("Fig/{}_{}.pdf".format(*lst))
else:
ax = fig.add_subplot(111, projection='3d')
ax.scatter(*coordinates)
ax.update({'xlabel': lst[0], 'ylabel': lst[1], 'zlabel': lst[2]})
plt.savefig("Fig/{}_{}_{}.pdf".format(*lst))
plt.show()
plt.close("all")
if __name__ == "__main__":
genre_scatter(['Action', 'Horror', 'Comedy'])
</code></pre>
<p>The code works and I'm happy with the output but there are a few things that bug me and I'm not sure if I used them right. </p>
<ol>
<li>I'm not incredibly familiar with list comprehension (I think that is what you call expressions of the form <code>[x for x in list]</code>, please correct me if I'm wrong) and haven't used them very often, so I'm not quite sure if this here was the right approach for the problem. My biggest concern is the first use of this kind of expression, where I basically need the first row of the CSV file but create a list with all the rows only to use the first. Is there a smarter way to do this?</li>
<li>Is there a better way to label the axes? Ideally some function where I just could pass the <code>*lst</code> argument?</li>
</ol>
<p>Please forget the <code>pearson_coeff()</code> part in the code, it's not really relevant for this.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T01:46:04.080",
"Id": "406286",
"Score": "0",
"body": "Are you sure that this code runs? You appear to use `csv.reader` but don't import it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T01:48:59.490",
"Id": "406287",
"Score": "0",
"body": "@Reinderien Thanks for pointing that out, copied this out of a larger code and forgot to check every import..."
}
] | [
{
"body": "<p>This really isn't bad, in terms of base Python. The only thing that stands out to me is this:</p>\n\n<pre><code>first_row = [row for row in reader(open('genre_scores.csv', 'r'))][0]\n</code></pre>\n\n<p>Firstly, you aren't closing the file. Always close the file after you're done.</p>\n\n<p><code>'r'</code> is implicit, so you don't need to write it in the arguments to <code>open</code>.</p>\n\n<p>Also, you're building up an entire list in memory from the CSV file, and then throwing it all away only to use the first row. Instead, you should use something like:</p>\n\n<pre><code>with open('genre_scores.csv') as f:\n csv_reader = reader(f)\n first_row = next(csv_reader)\n</code></pre>\n\n<p>You also ask:</p>\n\n<blockquote>\n <p>I'd like to implement something that makes sure that lst isn't longer than three elements (since four dimensional plots aren't really a thing). The only way I know to do this is <code>assert len(lst) <=3</code>, which gets the job done but it would be nice if it also could raise a useful error message. </p>\n</blockquote>\n\n<p>Fairly straightforward, and I'll also assume that the minimum is 2:</p>\n\n<pre><code>if not (2 <= len(lst) <= 3):\n raise ValueError(f'Invalid lst length of {len(lst)}')\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T01:49:29.980",
"Id": "210195",
"ParentId": "210188",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "210195",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-22T22:15:16.137",
"Id": "210188",
"Score": "2",
"Tags": [
"python",
"beginner",
"python-3.x",
"pandas",
"matplotlib"
],
"Title": "Generating scatter plot from a CSV file"
} | 210188 |
<p>I have a file with word frequency logs from a very messy corpus of scraped Polish text that I am trying to clean to get accurate word frequencies. Since this is a big text file, I divided it into batches.</p>
<p>Here is a snippet from the original file:</p>
<blockquote>
<pre><code> 1 ลrodka(byลe
1 ลrodka.byลo
1 ลrodkacccxli.
1 (ลrodkach)
1 โลrodkachโ
1 ลrodยญkach
1 ลrodkach...
1 ลrodkach.",
1 ลrodkach"
1 ลrodkach".
1 ลrodkachwzorem
1 ลrodkach.ลผycie
1 ลrodkajak
1 "ลrodkami"
1 (ลrodkami)
1 โลrodkamiโ)
1 ลrodkami!"
1 ลrodkamiโ
1 ลrodkami)?
1 ลrodkamiห.
</code></pre>
</blockquote>
<p>My goal is to clean true word labels and remove noisy word labels (e.g. collocations of words concatenated through punctuation). This is what is achieved by the first part of the script. As you can see in the data sample above, several noisy entries belong to the same true label. Once cleaned, their frequencies should be added. This is what I try to achieve in the second part of my script.</p>
<p>Here is the code in one piece with fixed indentation, in case you are able to reproduce my issues on your end:</p>
<pre><code># -*- coding: utf-8 -*-
import io
import pandas as pd
import numpy as np
num_batches = 54
for i in range(1 ,num_batches +1):
infile_path = r'input_batch_' + str(i) + r'.txt'
outfile_path = r'output_batch_' + str(i) + r'.txt'
with io.open(infile_path, 'r', encoding = 'utf8') as infile, \
io.open(outfile_path, 'w', encoding='utf8') as outfile:
entries_raw = infile.readlines()
entries_single = [x.strip() for x in entries_raw]
entries = [x.split('\t') for x in entries_single]
data = pd.DataFrame({"word": [], "freq": []})
for j in range(len(entries)):
data.loc[j] = entries[j][1], entries[j][0]
freq_dict = dict()
keys = np.unique(data['word'])
for key in keys:
for x in range(len(data)):
if data['word'][x] == key:
if key in freq_dict:
prior_freq = freq_dict.get(key)
freq_dict[key] = prior_freq + data['freq'][x]
else:
freq_dict[key] = data['freq'][x]
for key in freq_dict.keys():
outfile.write("%s,%s\n" % (key, freq_dict[key]))
</code></pre>
<p>The problem with this code is that it is either buggy, running into an infinite loop or sth, or is very slow, even for processing a single batch, to the point of being impractical. Are there ways to streamline this code to make it computationally tractable? In particular, can I achieve the same goal without using <code>for</code> loops? Or by using a different data structure for word-frequency lookup than a dictionary?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T00:22:12.503",
"Id": "406283",
"Score": "1",
"body": "I've added the fixed code in one piece below. Thank you!"
}
] | [
{
"body": "<pre><code>for i in range(1 ,num_batches +1):\n</code></pre>\n\n<p>Your inter-token spacing here is a little wonky. I suggest running this code through a linter to get it to be PEP8-compliant.</p>\n\n<p>This string:</p>\n\n<pre><code>r'input_batch_' + str(i) + r'.txt'\n</code></pre>\n\n<p>can be:</p>\n\n<pre><code>f'input_batch_{i}.txt'\n</code></pre>\n\n<p>This code:</p>\n\n<pre><code>entries_raw = infile.readlines()\nentries_single = [x.strip() for x in entries_raw]\nentries = [x.split('\\t') for x in entries_single]\n</code></pre>\n\n<p>can also be simplified, to:</p>\n\n<pre><code>entries = [line.rstrip().split('\\t') for line in infile]\n</code></pre>\n\n<p>Note a few things. You don't need to call <code>readlines()</code>; you can treat the file object itself as an iterator. Also, avoid calling a variable <code>x</code> even if it's an intermediate variable; you need meaningful names.</p>\n\n<p>This is an antipattern inherited from C:</p>\n\n<pre><code>for j in range(len(entries)):\n data.loc[j] = entries[j][1], entries[j][0]\n</code></pre>\n\n<p>You should instead do:</p>\n\n<pre><code>for j, entry in enumerate(entries):\n data.loc[j] = entry[1], entry[0]\n</code></pre>\n\n<p>That also applies to your <code>for x in range(len(data)):</code>.</p>\n\n<p>This:</p>\n\n<pre><code>freq_dict = dict()\n</code></pre>\n\n<p>should be:</p>\n\n<pre><code>freq_dict = {}\n</code></pre>\n\n<p>This:</p>\n\n<pre><code>if key in freq_dict:\n prior_freq = freq_dict.get(key)\n freq_dict[key] = prior_freq + data['freq'][x]\nelse:\n freq_dict[key] = data['freq'][x]\n</code></pre>\n\n<p>can be simplified to:</p>\n\n<pre><code>prior_freq = freq_dict.get(key)\nfreq_dict[key] = data['freq'][x]\nif prior_freq is not None:\n freq_dict[key] += prior_freq\n</code></pre>\n\n<p>or even (courtesy @AlexHall):</p>\n\n<pre><code>freq_dict[key] = data['freq'][x] + freq_dict.get(key, 0)\n</code></pre>\n\n<p>Note a few things. First of all, you were inappropriately using <code>get</code> - either check for key presence and then use <code>[]</code>, or use <code>get</code> and then check the return value (which is preferred, as it requires fewer key lookups).</p>\n\n<p>This loop:</p>\n\n<pre><code>for key in freq_dict.keys():\noutfile.write(\"%s,%s\\n\" % (key, freq_dict[key]))\n</code></pre>\n\n<p>needs adjustment in a few ways. Firstly, it won't run at all because its indentation is wrong. Also, rather that only iterating over <code>keys</code>, you should be iterating over <code>items</code>:</p>\n\n<pre><code>for key, freq in freq_dict.items():\n outfile.write(f'{key},{freq}\\n')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T19:07:50.697",
"Id": "406353",
"Score": "1",
"body": "The `freq_dict` code is wrong because it calls `.get` after assigning to that key. In any case it can be simplified more to `freq_dict[key] = data['freq'][x] + freq_dict.get(key, 0)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T01:04:01.513",
"Id": "406378",
"Score": "0",
"body": "@AlexHall Good eyes. Edited."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T01:35:27.943",
"Id": "210194",
"ParentId": "210192",
"Score": "5"
}
},
{
"body": "<p>Reinderien covered most of the other issues with your code. But you should know there's a built-in class for simplifying the task of tallying word frequencies:</p>\n\n<pre><code>from collections import Counter\n\nyourListOfWords = [...]\n\nfrequencyOfEachWord = Counter(yourListOfWords)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T01:58:14.107",
"Id": "210196",
"ParentId": "210192",
"Score": "3"
}
},
{
"body": "<p>To expand on <a href=\"https://codereview.stackexchange.com/a/210196/98493\">the answer</a> by <a href=\"https://codereview.stackexchange.com/users/126348/aleksandrh\">@AleksandrH</a>, this is how I would write it using <code>collections.Counter</code>:</p>\n\n<pre><code>import io\nfrom collections import Counter\nimport regex as re # the normal re module does not support \\p{P}...\n\ndef read_file(file_name):\n \"\"\"Reads a file into a Counter object.\n\n File contains rows with counts and words.\n Words can be multiple words separated by punctuation or whitespace.\n If that is the case, separate them.\n \"\"\"\n counter = Counter()\n with io.open(file_name, 'r', encoding = 'utf8') as infile:\n for line in infile:\n if not line:\n continue\n freq, words = line.strip().split('\\t') # need to omit '\\t' when testing, because SO replaces tabs with whitespace\n # split on punctuation and whitespace\n words = re.split(r'\\p{P}|\\s', words)\n # update all words\n for word in filter(None, words): # filter out empty strings\n counter[word] += int(freq)\n return counter\n\ndef write_file(file_name, counter):\n with io.open(file_name, 'w', encoding='utf8') as outfile:\n outfile.writelines(f'{word},{freq}\\n' for word, freq in counter.most_common()) # use `items` if order does not matter\n\n\nif __name__ == \"__main__\":\n num_batches = 54\n for i in range(1, num_batches + 1):\n counter = read_file(f\"input_batch_{i}.txt\")\n write_file(f\"output_batch_{i}.txt\", counter)\n</code></pre>\n\n<p>This also has (the start of) a <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\"><code>docstring</code></a> describing what the <code>read_file</code> function does, functions in the first place in order to separate concerns, and a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a> to allow importing from this script without the main code running.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T11:12:34.350",
"Id": "210211",
"ParentId": "210192",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "210194",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T00:05:16.587",
"Id": "210192",
"Score": "3",
"Tags": [
"python",
"performance",
"hash-map",
"lookup"
],
"Title": "Word frequencies from large body of scraped text"
} | 210192 |
<p>I write this solution to the popular <a href="https://en.wikipedia.org/wiki/Eight_queens_puzzle" rel="nofollow noreferrer">N Queens</a> problem using backtracking algorithm. I am relatively new to Python. I would like to know what are the ways to refactor this code and also code style of Python in general.</p>
<pre><code>def isSafe (board, row, col):
# check left row
for y in range(col):
if board[row][y] == 1:
return False
# check diagonal left top
for x, y in zip(range(row, -1, -1), range(col, -1, -1)):
if board[x][y] == 1:
return False
# check diagonal left bottom
for x, y in zip(range(row, N, 1), range(col, -1, -1)):
if board[x][y] == 1:
return False
return True
def generateSolution(board, col):
# terminating condition
# all columns covered
global N
if col >= N:
return True
# loop over all the rows
for i in range(N):
if isSafe(board, i, col) == True:
board[i][col] = 1
# recursively place other queens
if generateSolution(board, col + 1) == True:
return True
# unmark queen spot
board[i][col] = 0
# backtrack
return False
N = int(input())
startCol = 0
board = [[0 for i in range(N)] for j in range(N)]
# print(board)
if generateSolution(board, startCol) == False:
print("No Solution Exists")
else:
print("Solution exists")
print(board)
</code></pre>
| [] | [
{
"body": "<h1>PEP 8</h1>\n\n<p>There is a generally accepted style for Python known as <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a>. Most notably <code>camelCase</code> functions/methods should become <code>snake_case</code>. There are some other issues with stylistic conventions, I would give the document I linked to an overview.</p>\n\n<h1>Main Function</h1>\n\n<p>I would advise you add <a href=\"https://stackoverflow.com/a/20158605/667648\">a main function to your program.</a> The main reason being: If I want to use the functions from your script, when I import your script I probably don't want to actually run your program, just use <code>generateSolution</code> and <code>isSafe</code>. So:</p>\n\n<pre><code>N = int(input())\nstartCol = 0\nboard = [[0 for i in range(N)] for j in range(N)]\n# print(board)\n\nif generateSolution(board, startCol) == False:\n print(\"No Solution Exists\")\nelse:\n print(\"Solution exists\")\n print(board)\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>def main():\n N = int(input())\n startCol = 0\n board = [[0 for i in range(N)] for j in range(N)]\n\n if generateSolution(board, startCol) == False:\n print(\"No Solution Exists\")\n else:\n print(\"Solution exists\")\n print(board)\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<h1>Avoid global</h1>\n\n<p>You should almost always not use the <code>global</code> keyword. In this case: just pass <code>N</code> into your <code>generateSolution</code> function, i.e. <code>generate_solution(board, col, N)</code>.</p>\n\n<h1>Naming</h1>\n\n<p>I am not entirely sure how your code works (I am, ashamedly, unfamiliar with the N-Queen problem). I assume <code>N</code> refers to the number of queens? I would recommend that you call it <code>queen_count</code> or something of the sort. In addition, <code>generate_solution</code> is rather unspecific. I would call it (possibly) <code>n_queen_solvable</code>.</p>\n\n<h1>Does <code>generate_solution</code> actually do that?</h1>\n\n<p>I mentioned changing it to the name <code>n_queen_solvable</code> because you have return a truth value. I would expect a function like that to actually give me a configuration, not answer whether a solution exists or not. You may want to refactor this into two functions: <code>n_queen_solvable</code> and <code>gen_queen_config</code> or something of the sort.</p>\n\n<h1>Default parameters</h1>\n\n<p>You seem to want to start at the zeroith column. Makes sense. Instead of explicitly passing the <code>startCol</code> explicitly, I would just make <code>col</code> <a href=\"https://docs.python.org/3/tutorial/controlflow.html#default-argument-values\" rel=\"nofollow noreferrer\">default to 0</a>. This is done by changing:</p>\n\n<pre><code>def generateSolution(board, col):\n</code></pre>\n\n<p>to </p>\n\n<pre><code>def generateSolution(board, col=0):\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T08:26:21.910",
"Id": "406291",
"Score": "1",
"body": "Thereโs also the `generate` special meaning given Pythonโs generator objects, yet the method is not yielding anything."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T05:55:50.240",
"Id": "210204",
"ParentId": "210202",
"Score": "4"
}
},
{
"body": "<p>+1 to @Dair's suggestions. Also, your <code>isSafe</code> (which should be called <code>is_safe</code> - snake_case is standard in Python) can be simplified, although I'm a little shaky on what you're trying to accomplish with your logic.</p>\n\n<p>First, I'll suggest that you rename your arguments to <code>row_index</code> and <code>col_index</code>.</p>\n\n<p>I had started re-writing your <code>for</code> loops as list comprehensions using <code>any</code> (which you should still do), but I ran into some questionable logic.</p>\n\n<p>You say \"check left row\", by which I think you actually mean \"check the left-hand side of the row containing (row_index, col_index)\". If that's true, why are you iterating with <code>y</code>? Isn't that <code>x</code>?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T16:05:21.887",
"Id": "210229",
"ParentId": "210202",
"Score": "1"
}
},
{
"body": "<p>@Dair's answer is good, but there was something else that hasn't been mentioned:</p>\n\n<h1>Don't compare to Boolean values</h1>\n\n<ul>\n<li>Instead of <code>if foo == True</code>, write <code>if foo</code></li>\n<li>Instead of <code>if foo == False</code>, write <code>if not foo</code></li>\n</ul>\n\n<p>Comparing to Boolean values is always unnecessary because the values will already be coerced into Boolean values in the appropriate contexts. While the <a href=\"https://www.python.org/dev/peps/pep-0020/\" rel=\"nofollow noreferrer\">Zen of Python</a> does say \"Explicit is better than implicit\", Boolean comparison looks like nonstandard Python code, and is a bit of a code smell for me.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T17:59:30.987",
"Id": "210235",
"ParentId": "210202",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "210204",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T02:34:55.030",
"Id": "210202",
"Score": "4",
"Tags": [
"python",
"algorithm",
"python-3.x",
"backtracking",
"n-queens"
],
"Title": "N Queens in Python using backtracking"
} | 210202 |
<p>I've made a python script to get some statistics from a server log. I would like some guidelines to improve my code: make it run faster, be more pythonic, etc. I don't write python professionally (embedded developer) so please go easy on me.</p>
<p>Here's the code:</p>
<pre><code>'''
Find the number of 'exceptions' and 'added' event's in the exception log
with respect to the device ID.
author: clmno
date: Dec 23 2018
'''
from time import time
import re
def timer(fn):
''' Used to time a function's execution'''
def f(*args, **kwargs):
before = time()
rv = fn(*args, **kwargs)
after = time()
print("elapsed", after - before)
return rv
return f
def find_sql_guid(txt):
''' From the passed in txt, find the SQL guid using re'''
re1 = '.*?'
# SQL GUID 1
re2='([A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12})'
rg = re.compile(re1+re2, re.IGNORECASE|re.DOTALL)
m = rg.search(txt)
if m:
guid1 = m.group(1)
return guid1
else:
print("ERROR: No SQL guid in line. Check the code")
exit(-1)
def find_device_IDs(path, element):
""" Find the element (type: str) within the file (file path is
provide as arg). Then find the SQL guid from the line at hand.
(Each line has a SQL guid)
Return a dict of {element: [<list of SQL guids>]}
"""
lines = dict()
lines[element] = []
with open(path) as f:
for line in f:
if str(element) in line:
#find the sql-guid from the line-str & append
lines[element].append(find_sql_guid(line))
return lines
# @timer
def find_num_occurences(path, key, search_val, unique_values):
""" Find and append SQL guids that are in a line that contains a string
that's in search_val into 'exception' and 'added'
Return a dict of {'exception':set(<set of SQL guids>),
'added': set(<set of SQL guids>)}
"""
lines = {'exception':set(), 'added': set()}
with open(path) as f:
for line in f:
for value in unique_values:
if value in line:
if search_val[0] in line:
lines['exception'].add(value)
elif search_val[1] in line:
lines['added'].add(value)
return lines
def print_stats(num_exceptions_dict):
for key in num_exceptions_dict.keys():
print("{} added ".format(key) +
str(len(list(num_exceptions_dict[key]["added"]))))
print("{} exceptions ".format(key) +
str(len(list(num_exceptions_dict[key]["exception"]))))
if __name__ == "__main__":
path = 'log/server.log'
search_list = ['3BAA5C42', '3BAA5B84', '3BAA5C57', '3BAA5B67']
#find every occurance of device ID and find their corresponding SQL
# guids (unique ID)
unique_ids_dict = dict()
for element in search_list:
unique_ids_dict[element] = find_device_IDs(path, element)
#Now for each unique ID find if string ["Exception occurred",
# "Packet record has been added"] is found in it's SQL guid list.
search_with_in_deviceID = ["Exception occurred",
"Packet record has been added"]
num_exceptions_dict = dict()
for elem in search_list:
num_exceptions_dict[elem] = find_num_occurences(path, elem,
search_with_in_deviceID, list(unique_ids_dict[elem].values())[0])
print_stats(num_exceptions_dict)
</code></pre>
<p>and <a href="https://pastebin.com/puqaUkzi" rel="nofollow noreferrer">here's</a> a small server log for you to experiment on.<br/>
This code works but the time elapsed to run through a log file of 55000 lines is 42 seconds</p>
<pre><code>$ time python findUniqueVal_log.py
real 0m42.343s
user 0m42.245s
sys 0m0.100s
</code></pre>
<p><strong>I would like guidelines on:</strong><br/></p>
<ul>
<li>Optimizing in both coding and performance efficiency</li>
<li>Any better approach to this problem</li>
<li>I keep opening the file and closing it. Is that IO delay causing any noticeable delay? </li>
</ul>
| [] | [
{
"body": "<p>Your <code>timer</code> function should probably go away, to use the built-in <code>timeit</code> instead; or at least <code>timer</code> should wrap <code>timeit</code>.</p>\n\n<p>I'm unclear on why <code>re1</code> and <code>re2</code> are separate. Just have them in the same string. If you want to make it clear that they're separate parts of the regex, you could show the construction of the regex as a concatenation, i.e.</p>\n\n<pre><code>rg = re.compile('.*?' # Prefix to do foo\n # This is a SQL GUID\n '([A-Z0-9]{8}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{12})',\n re.IGNORECASE | re.DOTALL)\n</code></pre>\n\n<p>Also, you should not have an outer group on that regex.</p>\n\n<p>Your <code>else</code> after <code>return guid1</code> is redundant, since the previous block has already returned.</p>\n\n<p><code>lines = dict()</code> should be <code>lines = {}</code>. There's a reason for this: generally, shorter code is considered more \"Pythonic\" (as long as it doesn't become arcane or difficult to understand). A dictionary literal is short, simple, and easy to understand.</p>\n\n<p>Here:</p>\n\n<pre><code>if str(element) in line:\n</code></pre>\n\n<p>You've already stated in the function doc that <code>element</code> is assumed to be a string, so you don't need to convert it using <code>str</code>.</p>\n\n<p>Here:</p>\n\n<pre><code>unique_ids_dict[element] = find_device_IDs(path, element)\n</code></pre>\n\n<p>Your data structure use is a little strange. You're constructing a dictionary by element of single-key dictionaries by element of GUIDs. It would probably make more sense to change <code>find_device_IDs</code> such that it doesn't return a dictionary, and instead just returns a set.</p>\n\n<p>Speed tips:</p>\n\n<ul>\n<li>Sort out your data structure strategy, mentioned above</li>\n<li>Don't re-compile your regex every time an inner function is called. Compile your regex once, at the global level</li>\n</ul>\n\n<p>This:</p>\n\n<pre><code>num_exceptions_dict = dict()\n for elem in search_list:\n num_exceptions_dict[elem] = find_num_occurences(path, elem, \n search_with_in_deviceID, list(unique_ids_dict[elem].values())[0])\n</code></pre>\n\n<p>should probably be reduced to something like</p>\n\n<pre><code>num_exceptions_dict = {\n elem: find_num_occurences(path, elem, search_with_in_deviceID,\n unique_ids_dict[elem].values())\n for elem in search_list\n}\n</code></pre>\n\n<p>The performance-affecting change is to avoid re-constructing an inner list. But there's something more sinister going on there. A dictionary is <em>unordered</em>, but you're taking element <code>[0]</code> of an arbitrarily ordered list of <code>values()</code>. If you actually do intend to pull a non-deterministic value from the dictionary, then fine; but this is probably not your intention.</p>\n\n<p>This:</p>\n\n<pre><code>search_with_in_deviceID = [\"Exception occurred\", \"Packet record has been added\"]\n</code></pre>\n\n<p>should be a tuple instead of a list, since you aren't changing it; so:</p>\n\n<pre><code>search_within_device_ID = ('Exception occurred', 'Packet record has been added')\n</code></pre>\n\n<p>I'm going to suggest that you attempt to address the issues that I've raised, above, in particular with respect to the structure of your dictionary and the non-deterministic behaviour of your <code>values</code> call; and then submit a new question so that further performance issues may be addressed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T15:44:23.633",
"Id": "406330",
"Score": "0",
"body": "Yes, about the last suggestion. That was something I missed. And about `str(element)`, yes this too should have been updated. But about `lines = {}` instead of `lines = dict()` . I decided to use this because I thought it provided more clarity when one `speed reads`. Could you let me know how your's would be better. Same goes for `re1` and `re2`. Better when speed reading. Thank you for suggesting `timeit`.\n\nAlso, how can I make this run faster?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T15:46:29.907",
"Id": "406331",
"Score": "1",
"body": "Even if `re1` and `re2` were to stay separate for the purposes of legibility, they have bad names, and you should rename them to something like `re_prefix` and `re_guid` - otherwise, legibility doesn't increase."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T15:49:58.077",
"Id": "406333",
"Score": "0",
"body": "Got it! Makes sense. Thank you. How about `dict()`? I'm guessing they are almost the same level of legibility. Again, any suggestion to make it go faster?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T16:28:48.987",
"Id": "406341",
"Score": "0",
"body": "Please see edits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-27T06:20:58.807",
"Id": "406652",
"Score": "1",
"body": "I've made improvements and reposted here https://codereview.stackexchange.com/questions/21040."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-27T14:23:35.323",
"Id": "406710",
"Score": "0",
"body": "@clmno Are you sure that's the right link?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-27T15:40:30.013",
"Id": "406732",
"Score": "0",
"body": "https://codereview.stackexchange.com/questions/210405. Missed a digit."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T15:22:23.737",
"Id": "210226",
"ParentId": "210207",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "210226",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T10:15:43.337",
"Id": "210207",
"Score": "3",
"Tags": [
"python"
],
"Title": "Counting SQL guids from a server log and printing stats"
} | 210207 |
<p>I have read your rules and in particular the part about bite-sized portions, so I am apprehensive about posting this but want to do it anyway. I have recently begun getting into C and in particular ncurses with the desire to make some games for the sake of historical appreciation (at least a Rogue clone, probably more). Python is the language I've messed with most extensively to this point and I'm far from an expert in that.</p>
<p>If anyone has the time and the desire, here is 715 lines of a complete and working Tic Tac Toe game that I wrote on my Ubuntu Laptop. The AI is no genius and I could definitely make it better but that was not my focus here... my concern was in writing structurally sound code and a portable, good-looking ncurses display. To that end I think I did alright. What I would like to hear are any and all ways that I could improve my coding style to better take advantage of the C language and the ncurses library while making future games. Don't hold back! Every little thing will help me write better games in the near future. I don't need anybody to go over the entire thing unless they really want to, simply giving me style tips is more than helpful.</p>
<pre><code>// The mandatory tic tac toe game to practice ncurses stuff.
// Date Started: 21 DEC 2018
#include <ncurses.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
// Global Variables
time_t t;
int row, col, x, y, px, py, slen, sx;
// constants to use with the COLOR_PAIR() attribute for easier remembering
const int Xs = 1;
const int Os = 2;
const int BG = 3;
/*
Board (7 x 7 character cells):
Line 1 = ------- (7 hyphens)
Line 2 = | | | | Spaces: 1=(1, 1) 2=(1, 3) 3=(1, 5)
Line 3 = -------
Line 4 = | | | | 4=(3, 1) 5=(3, 3) 6=(3, 5)
Line 5 = -------
Line 6 = | | | | 7=(5, 1) 8=(5, 3) 9=(5, 5)
Line 7 = -------
*/
const int line_len = 7; // constant int for the length of a board line
char break_lines[] = "-------"; // Strings representing the board lines, minus the pieces
char play_lines[] = "| | | |";
/*
These spaces are abstractions, since the board itself will need to vary based on the current size of the terminal.
They represent the current values of the "playable" spaces.
*/
char space_1 = ' ';
char space_2 = ' ';
char space_3 = ' ';
char space_4 = ' ';
char space_5 = ' ';
char space_6 = ' ';
char space_7 = ' ';
char space_8 = ' ';
char space_9 = ' ';
int space_1y, space_1x;
int space_2y, space_2x;
int space_3y, space_3x;
int space_4y, space_4x;
int space_5y, space_5x;
int space_6y, space_6x;
int space_7y, space_7x;
int space_8y, space_8x;
int space_9y, space_9x;
char *space_ptr = NULL; // Pointer to one of the playable spaces
// Player's side ('X' or 'O')
char side;
int running = 1; // Main menu control variable
int playing = 1; // Game loop control variable
int turn = 1; // Turn number
int game_over = 0;
// Function Declarations
void f_intro(); // Print elaborate "animated" intro splash
char f_setup(); // Prompt player to pick a side or pick random selection, returns char
void f_paint(); // Paint the board state on a given turn
void f_turn_input(); // Take player input and determine AI action (includes sub-functions probably)
void f_player_turn(); // Take player input and place the appropriate mark on the board
void f_AI_turn(); // Logic (such as it is) and Placement for AI turn
void f_evaluate_turn(); // Check for endgame state and either advance the turn or end the game (with sub-functions probably)
int f_AI_picker(); // Picks random spots until it finds an empty one or tries them all
void f_declare_winner(char symbol); // Takes the winning character and creates a splash screen declaring victory ('X', 'O', or 'T' for Tie)
// Main Function
int main(){
srand((unsigned) time(&t));
initscr();
clear();
cbreak();
keypad(stdscr, 1);
curs_set(0);
noecho();
start_color();
init_pair(Xs, COLOR_CYAN, COLOR_BLACK);
init_pair(Os, COLOR_RED, COLOR_BLACK);
init_pair(BG, COLOR_YELLOW, COLOR_BLACK);
f_intro(); // Print intro splash
getch();
while(running){
clear();
side = f_setup(); // Choose X's, O's, or RANDOM SIDE
playing = 1;
while(playing){
f_paint(); // Paint the board as it is that turn
f_turn_input(); // Take player input and if valid determine AI move + sub-functions
turn++;
}
// To-Do, a reset function
}
endwin();
return 0;
}
// Function Definitions
void f_intro(){
// Print elaborate "animated" intro splash
int which;
clear();
getmaxyx(stdscr, row, col);
// Print the background
for(y=0;y<=row;y++){
for(x=0;x<=col;x++){
which = rand() % 3;
if(which == 0){
// Print an "X" in the cell
attron(COLOR_PAIR(Xs));
mvprintw(y, x, "X");
attroff(COLOR_PAIR(Xs));
}else if(which == 1){
// Print an "O" in the cell
attron(COLOR_PAIR(Os));
mvprintw(y, x, "O");
attroff(COLOR_PAIR(Os));
}else if(which == 2){
// Print a blank black space in the cell
attron(COLOR_PAIR(BG));
mvprintw(y, x, " ");
attroff(COLOR_PAIR(BG));
}
}
}
// Print the Title
y = row / 2 - 1;
char intro_str[] = " NCURSES Tic Tac Toe! ";
char intro_str_padding[] = " ";
char intro_str2[] = " any key to continue ";
slen = strlen(intro_str);
x = col / 2 - slen / 2;
mvprintw(y++, x, intro_str_padding);
mvprintw(y++, x, intro_str);
mvprintw(y++, x, intro_str2);
mvprintw(y, x, intro_str_padding);
refresh();
}
char f_setup(){
// Prompt player to pick a side or pick random selection, returns char
int input;
clear();
getmaxyx(stdscr, row, col);
char setup_str1[] = "Pick a side!";
char setup_str2[] = "Press 'X', 'O', or 'R' for Random!";
char *chose_x = "You chose X's! Any key to continue...";
char *chose_y = "You chose O's! Any key to continue...";
char *choice_ptr = NULL;
y = row / 2 - 1;
slen = strlen(setup_str1);
x = col / 2 - slen / 2;
mvprintw(y++, x, setup_str1);
slen = strlen(setup_str2);
x = col / 2 - slen / 2;
mvprintw(y++, x, setup_str2);
y++;
refresh();
input = getch();
if(input == 'X' || input == 'x'){
choice_ptr = chose_x;
slen = strlen(choice_ptr);
x = col / 2 - slen / 2;
mvprintw(y, x, choice_ptr);
refresh();
getch();
return 'X';
}else if(input == 'O' || input == 'o'){
choice_ptr = chose_y;
slen = strlen(choice_ptr);
x = col / 2 - slen / 2;
mvprintw(y, x, choice_ptr);
refresh();
getch();
return 'O';
}else if(input == 'R' || input == 'r'){
int r;
r = rand() % 2;
if(r == 0){
// Pick 'X'
choice_ptr = chose_x;
slen = strlen(choice_ptr);
x = col / 2 - slen / 2;
mvprintw(y, x, choice_ptr);
refresh();
getch();
return 'X';
}else if(r == 1){
// Pick 'O'
choice_ptr = chose_y;
slen = strlen(choice_ptr);
x = col / 2 - slen / 2;
mvprintw(y, x, choice_ptr);
refresh();
getch();
return 'O';
}
}else{
char err_str[] = "Input error! Any key to continue...";
slen = strlen(err_str);
x = col / 2 - slen / 2;
mvprintw(y, x, err_str);
refresh();
getch();
f_setup();
}
}
void f_paint(){
// Paint the board state on a given turn
/*
1. Clear screen.
2. Paint blank board.
3. Paint the contents of each playable cell.
4. Refresh screen
*/
clear(); // Clear screen
getmaxyx(stdscr, row, col); // Get current size of terminal
y = row / 2 - 3; // Board is 7x7 characters, so (y / 2 - 3) is a decent top edge
x = col / 2 - 3; // Ditto for (x / 2 - 3) being a decent left edge.
// Determine the locations of the 9 "playable" cells:
space_1y = y + 1; space_1x = x + 1;
space_2y = y + 1; space_2x = x + 3;
space_3y = y + 1; space_3x = x + 5;
space_4y = y + 3; space_4x = x + 1;
space_5y = y + 3; space_5x = x + 3;
space_6y = y + 3; space_6x = x + 5;
space_7y = y + 5; space_7x = x + 1;
space_8y = y + 5; space_8x = x + 3;
space_9y = y + 5; space_9x = x + 5;
// Paint the board roughly centered:
int yy, xx;
attron(COLOR_PAIR(BG));
for(yy = 0; yy < line_len; yy++){
if(yy == 0 || yy % 2 == 0){
mvprintw(y + yy, x, break_lines);
}else{
mvprintw(y + yy, x, play_lines);
}
}
attroff(COLOR_PAIR(BG));
// Insert appropriate characters into the "playable" cells:
if(space_1 == 'X'){
attron(COLOR_PAIR(Xs));
}else if(space_1 == 'O'){
attron(COLOR_PAIR(Os));
}
mvaddch(space_1y, space_1x, space_1);
if(space_2 == 'X'){
attron(COLOR_PAIR(Xs));
}else if(space_2 == 'O'){
attron(COLOR_PAIR(Os));
}
mvaddch(space_2y, space_2x, space_2);
if(space_3 == 'X'){
attron(COLOR_PAIR(Xs));
}else if(space_3 == 'O'){
attron(COLOR_PAIR(Os));
}
mvaddch(space_3y, space_3x, space_3);
if(space_4 == 'X'){
attron(COLOR_PAIR(Xs));
}else if(space_4 == 'O'){
attron(COLOR_PAIR(Os));
}
mvaddch(space_4y, space_4x, space_4);
if(space_5 == 'X'){
attron(COLOR_PAIR(Xs));
}else if(space_5 == 'O'){
attron(COLOR_PAIR(Os));
}
mvaddch(space_5y, space_5x, space_5);
if(space_6 == 'X'){
attron(COLOR_PAIR(Xs));
}else if(space_6 == 'O'){
attron(COLOR_PAIR(Os));
}
mvaddch(space_6y, space_6x, space_6);
if(space_7 == 'X'){
attron(COLOR_PAIR(Xs));
}else if(space_7 == 'O'){
attron(COLOR_PAIR(Os));
}
mvaddch(space_7y, space_7x, space_7);
if(space_8 == 'X'){
attron(COLOR_PAIR(Xs));
}else if(space_8 == 'O'){
attron(COLOR_PAIR(Os));
}
mvaddch(space_8y, space_8x, space_8);
if(space_9 == 'X'){
attron(COLOR_PAIR(Xs));
}else if(space_9 == 'O'){
attron(COLOR_PAIR(Os));
}
mvaddch(space_9y, space_9x, space_9);
attroff(COLOR_PAIR(Xs));
attroff(COLOR_PAIR(Os));
refresh();
}
void f_turn_input(){
// Take player input and determine AI action (includes sub-functions probably)
/*
1. Determine who goes first.
- Using if/else to divide the function into two halves for each possibility.
2. Player/AI Takes turn. -> Refresh
3. Player/AI takes turn. -> Refresh
Note on AI: No real logic for this version. Just going to randomly pick from the available spaces.
*/
if(side == 'X'){
// if player is 'X':
f_player_turn();
f_evaluate_turn();
if(game_over == 0){
f_AI_turn();
f_evaluate_turn();
}
}else if(side == 'O'){
// If player is 'O':
f_AI_turn();
f_evaluate_turn();
if(game_over == 0){
f_player_turn();
f_evaluate_turn();
}
}
refresh();
}
void f_player_turn(){
// Take player input and place the appropriate mark on the board
int info_line = y + 10; // Determine the line that the info splash will show up on.
char move_splash[] = "Use arrow keys and press 'P' to place your piece!";
char done_splash[] = "Good move!";
char move_err_splash[] = "You can't move that way!";
char input_err_splash[] = "Invalid input!";
char full_err_splash[] = "Spot already claimed!";
slen = strlen(move_splash);
sx = col / 2 - slen / 2; // Center the info splash
mvprintw(info_line, sx, move_splash);
curs_set(1); // Enable the cursor for the player
int pos_y = space_1y; // Y position of the cursor
int pos_x = space_1x; // X position of the cursor
move(pos_y, pos_x); // Move it to space 1
refresh();
int inputting = 1;
while(inputting){
int input;
char spot;
int cx;
input = getch();
if(input == KEY_LEFT){
if(!(pos_x == space_1x)){
// If not on the left playable edge
pos_x -= 2;
move(pos_y, pos_x);
}else{
for(cx = sx; cx <= col; cx++){
// Clear the info line
mvaddch(info_line, cx, ' ');
}
slen = strlen(move_err_splash);
sx = col / 2 - slen / 2;
mvprintw(info_line, sx, move_err_splash);
move(pos_y, pos_x);
}
}else if(input == KEY_RIGHT){
if(!(pos_x == space_3x)){
// If not on the right playable edge
pos_x += 2;
move(pos_y, pos_x);
}else{
for(cx = sx; cx <= col; cx++){
// Clear the info line
mvaddch(info_line, cx, ' ');
}
slen = strlen(move_err_splash);
sx = col / 2 - slen / 2;
mvprintw(info_line, sx, move_err_splash);
move(pos_y, pos_x);
}
}else if(input == KEY_UP){
if(!(pos_y == space_1y)){
// If not on the top playable edge
pos_y -= 2;
move(pos_y, pos_x);
}else{
for(cx = sx; cx <= col; cx++){
// Clear the info line
mvaddch(info_line, cx, ' ');
}
slen = strlen(move_err_splash);
sx = col / 2 - slen / 2;
mvprintw(info_line, sx, move_err_splash);
move(pos_y, pos_x);
}
}else if(input == KEY_DOWN){
if(!(pos_y == space_9y)){
// If not on the bottom playable edge
pos_y += 2;
move(pos_y, pos_x);
}else{
for(cx = sx; cx <= col; cx++){
// Clear the info line
mvaddch(info_line, cx, ' ');
}
slen = strlen(move_err_splash);
sx = col / 2 - slen / 2;
mvprintw(info_line, sx, move_err_splash);
move(pos_y, pos_x);
}
}else if(input == 'P' || input == 'p'){
/*
1. Read contents of space.
2. If Empty -> Place player's symbol
3. Else, try again
*/
if(pos_y == space_1y && pos_x == space_1x){
space_ptr = &space_1;
}else if(pos_y == space_2y && pos_x == space_2x){
space_ptr = &space_2;
}else if(pos_y == space_3y && pos_x == space_3x){
space_ptr = &space_3;
}else if(pos_y == space_4y && pos_x == space_4x){
space_ptr = &space_4;
}else if(pos_y == space_5y && pos_x == space_5x){
space_ptr = &space_5;
}else if(pos_y == space_6y && pos_x == space_6x){
space_ptr = &space_6;
}else if(pos_y == space_7y && pos_x == space_7x){
space_ptr = &space_7;
}else if(pos_y == space_8y && pos_x == space_8x){
space_ptr = &space_8;
}else if(pos_y == space_9y && pos_x == space_9x){
space_ptr = &space_9;
}
if(*space_ptr == ' '){
if(side == 'X'){
*space_ptr = 'X';
}else{
*space_ptr = 'O';
}
for(cx = sx; cx <= col; cx++){
// Clear the info line
mvaddch(info_line, cx, ' ');
}
slen = strlen(done_splash);
sx = col / 2 - slen / 2;
mvprintw(info_line, sx, done_splash);
move(pos_y, pos_x);
refresh();
inputting = 0;
}else{
for(cx = sx; cx <= col; cx++){
// Clear the info line
mvaddch(info_line, cx, ' ');
}
slen = strlen(full_err_splash);
sx = col / 2 - slen / 2;
mvprintw(info_line, sx, full_err_splash);
move(pos_y, pos_x);
}
}else{
// If the user presses any other button
for(cx = sx; cx <= col; cx++){
// Clear the info line
mvaddch(info_line, cx, ' ');
}
slen = strlen(input_err_splash);
sx = col / 2 - slen / 2;
mvprintw(info_line, sx, input_err_splash);
move(pos_y, pos_x);
}
}
}
int f_AI_picker(){
/*
1. Pick a number between 1 and 9
2. Randomly decide whether to check spaces from 1 to 9 or 9 to 1 for the sake of variety
3. Check them in the determined order until an open space is found.
4. Return number of open space.
Note: This version has no real strategic logic and will be easily beaten by any player.
Although a quick fix for some added challenge is to make it prioritize the center tile.
*/
int pick;
pick = rand() % 9 + 1;
int order; // 1 = Ascending, 2 = Descending
order = rand() % 2 + 1;
if(space_5 == ' '){
return 5;
}else{
if(order == 1){
if(space_1 == ' '){
return 1;
}else if(space_2 == ' '){
return 2;
}else if(space_3 == ' '){
return 3;
}else if(space_4 == ' '){
return 4;
}else if(space_6 == ' '){
return 6;
}else if(space_7 == ' '){
return 7;
}else if(space_8 == ' '){
return 8;
}else if(space_9 == ' '){
return 9;
}
}else if(order == 2){
if(space_9 == ' '){
return 9;
}else if(space_8 == ' '){
return 8;
}else if(space_7 == ' '){
return 7;
}else if(space_6 == ' '){
return 6;
}else if(space_4 == ' '){
return 4;
}else if(space_3 == ' '){
return 3;
}else if(space_2 == ' '){
return 2;
}else if(space_1 == ' '){
return 1;
}
}
}
}
void f_AI_turn(){
// Logic (such as it is) and Placement for AI turn
char AI_char;
if(side == 'X'){
AI_char = 'O';
}else{
AI_char = 'X';
}
int space_to_place;
space_to_place = f_AI_picker();
if(space_to_place == 1){
space_1 = AI_char;
}else if(space_to_place == 2){
space_2 = AI_char;
}else if(space_to_place == 3){
space_3 = AI_char;
}else if(space_to_place == 4){
space_4 = AI_char;
}else if(space_to_place == 5){
space_5 = AI_char;
}else if(space_to_place == 6){
space_6 = AI_char;
}else if(space_to_place == 7){
space_7 = AI_char;
}else if(space_to_place == 8){
space_8 = AI_char;
}else if(space_to_place == 9){
space_9 = AI_char;
}
f_paint();
refresh();
}
void f_declare_winner(char symbol){
// Takes the winning character and creates a splash screen declaring victory ('X', 'O', or 'T' for Tie)
char *x_wins = " X is the winner! ";
char *o_wins = " O is the winner! ";
char *tie_game = " The game is a tie! ";
char padding[] = " ";
char *win_splash_ptr = NULL;
// Paint background for victory splash:
if(symbol == 'X'){
win_splash_ptr = x_wins;
attron(COLOR_PAIR(Xs));
for(y = 0; y <= row; y++){
for(x = 0; x <= col; x++){
if(x == 0 || x % 2 == 0){
mvaddch(y, x, 'X');
}else{
mvaddch(y, x, ' ');
}
}
}
attroff(COLOR_PAIR(Xs));
}else if(symbol == 'O'){
win_splash_ptr = o_wins;
attron(COLOR_PAIR(Os));
for(y = 0; y <= row; y++){
for(x = 0; x <= col; x++){
if(x == 0 || x % 2 == 0){
mvaddch(y, x, 'O');
}else{
mvaddch(y, x, ' ');
}
}
}
attroff(COLOR_PAIR(Os));
}else if(symbol == 'T'){
win_splash_ptr = tie_game;
for(y = 0; y <= row; y++){
for(x = 0; x <= col; x++){
if(x == 0 || x % 2 == 0){
attron(COLOR_PAIR(Xs));
mvaddch(y, x, 'X');
attroff(COLOR_PAIR(Xs));
}else{
attron(COLOR_PAIR(Os));
mvaddch(y, x, 'O');
attroff(COLOR_PAIR(Os));
}
}
}
}
//Paint the prompt
y = row / 2 - 2;
slen = strlen(win_splash_ptr);
x = col / 2 - slen / 2;
mvprintw(y++, x, padding);
mvprintw(y++, x, win_splash_ptr);
mvprintw(y, x, padding);
curs_set(0);
refresh();
getch();
running = 0;
playing = 0;
}
void f_evaluate_turn(){
// Check for endgame state and either advance the turn or end the game (with sub-functions probably)
/*
1. Check for each possible victory condition. -> If so, declare appropriate victory.
2. Check if turn number is high enough to indicate a tie -> If so, declare a tie.
3. Else, continue.
*/
int winner;
winner = 'N'; // For none
if(space_1 == 'O' && space_2 == 'O' && space_3 == 'O'){
winner = 'O';
game_over++;
}else if(space_4 == 'O' && space_5 == 'O' && space_6 == 'O'){
winner = 'O';
game_over++;
}else if(space_7 == 'O' && space_8 == 'O' && space_9 == 'O'){
winner = 'O';
game_over++;
}else if(space_1 == 'O' && space_4 == 'O' && space_7 == 'O'){
winner = 'O';
game_over++;
}else if(space_2 == 'O' && space_5 == 'O' && space_8 == 'O'){
winner = 'O';
game_over++;
}else if(space_3 == 'O' && space_6 == 'O' && space_9 == 'O'){
winner = 'O';
game_over++;
}else if(space_1 == 'O' && space_5 == 'O' && space_9 == 'O'){
winner = 'O';
game_over++;
}else if(space_3 == 'O' && space_5 == 'O' && space_7 == 'O'){
winner = 'O';
game_over++;
}else if(space_1 == 'X' && space_2 == 'X' && space_3 == 'X'){
winner = 'X';
game_over++;
}else if(space_4 == 'X' && space_5 == 'X' && space_6 == 'X'){
winner = 'X';
game_over++;
}else if(space_7 == 'X' && space_8 == 'X' && space_9 == 'X'){
winner = 'X';
game_over++;
}else if(space_1 == 'X' && space_4 == 'X' && space_7 == 'X'){
winner = 'X';
game_over++;
}else if(space_2 == 'X' && space_5 == 'X' && space_8 == 'X'){
winner = 'X';
game_over++;
}else if(space_3 == 'X' && space_6 == 'X' && space_9 == 'X'){
winner = 'X';
game_over++;
}else if(space_1 == 'X' && space_5 == 'X' && space_9 == 'X'){
winner = 'X';
game_over++;
}else if(space_3 == 'X' && space_5 == 'X' && space_7 == 'X'){
winner = 'X';
game_over++;
}else if(turn >= 5){
winner = 'T';
game_over++;
}
if(winner != 'N'){
f_declare_winner(winner);
}
}
</code></pre>
<p>And of course it goes without saying but any fellow linux users who want to throw this in their home directory and play it themselves are more than welcome to do so! Just be aware that without more strategic thinking the AI is a total pushover. I only went so far as making it prioritize the center square.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T12:42:27.310",
"Id": "406308",
"Score": "1",
"body": "Long questions are fine: they just tend to lend themselves to less comprehensive reviews (which is not necessarily a bad thing), and more rounds of review if you revise your code using the suggestions given. You can really learn a great deal from improving a larger program. And if you revise your code, it may turn out to need less than 715 lines!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T12:44:06.003",
"Id": "406309",
"Score": "1",
"body": "I don't really want to do too much more with this. Maybe improve the AI a little bit. Mostly I'm interested in tips that will lend themselves to making better games in the future. Also any ways in which I have obviously mis-used the language or the ncurses library (as I'm sure there are a few).\n\nI made this in two marathon sessions and although I'm very proud of it I'm sure it's just full of stylistically bad choices."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T12:55:09.543",
"Id": "406310",
"Score": "0",
"body": "Even if you don't revise this, you'll still get some very useful advice for future projects. The benefit of trying to revise it is that you can work your way through the hiccups of revision and the creation process with a familiar piece of code instead of some code that's not fully-formed (and revision will probably take much less time than composition). But it's your time, and you should choose how to spend it. Also note that this is getting a bit chatty, so a moderator may come and clear this out later, because the main point of comments is to ask clarifying questions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T13:12:07.217",
"Id": "406311",
"Score": "0",
"body": "Noted! Well I'm all for advice on how to make it shorter as well. In particular I was not sure if it would be appropriate using switch statements instead of if-else chains as it's my understanding that switch statements with variables that change in run-time can be troublesome. That's definitely a clarification I'm after."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T21:59:47.917",
"Id": "406367",
"Score": "1",
"body": "Using the number pad for move entry is nice. You only ever have to hit one key to play, and the key layout matches the on-screen board. A simple way to create a good AI is to try a move in a copy of the game state, then recurses to see if that leads to a forced win or a possible forced loss. If there's a forced win, play that. Otherwise select randomly from all the moves that don't let the opponent force a win (i.e. lead to a draw). That's what I did for a first-year CS assignment to write a tic-tac-toe game. (But apparently I was the only one in the class to do that. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T22:40:14.033",
"Id": "406370",
"Score": "0",
"body": "That is a darn good idea. One problem I had with the ncurses key entry is I tried to use KEY_ENTER instead of 'P' and it wouldn't work. Any idea why?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T03:31:42.103",
"Id": "406384",
"Score": "0",
"body": "@some_guy632: no idea, I haven't done anything with ncurses before."
}
] | [
{
"body": "<p>These:</p>\n\n<pre><code>char space_1 = ' ';\nchar space_2 = ' ';\nchar space_3 = ' ';\nchar space_4 = ' ';\nchar space_5 = ' ';\nchar space_6 = ' ';\nchar space_7 = ' ';\nchar space_8 = ' ';\nchar space_9 = ' ';\nint space_1y, space_1x;\nint space_2y, space_2x;\nint space_3y, space_3x;\nint space_4y, space_4x;\nint space_5y, space_5x;\nint space_6y, space_6x;\nint space_7y, space_7x;\nint space_8y, space_8x;\nint space_9y, space_9x;\n</code></pre>\n\n<p>should certainly be refactored into three arrays. That will allow you to write sane loops and decrease the repetition in your code.</p>\n\n<p>For all of your global variables, as well as all of your functions except <code>main</code>, they should be declared <code>static</code> because they aren't being exported to any other modules.</p>\n\n<p>Your <code>running</code> and <code>playing</code> variables are actually booleans, so you should be using <code><stdbool.h></code>.</p>\n\n<p>Having <code>x</code> and <code>y</code> as globals seems ill-advised, especially where you have them being used in loops like this:</p>\n\n<pre><code>for(y=0;y<=row;y++){\n for(x=0;x<=col;x++){\n</code></pre>\n\n<p>They should probably be kept as locals, and in this case, instantiated in the loop declaration.</p>\n\n<p>Your <code>if(which == 0){</code> can be replaced by a switch, since you're comparing it three times.</p>\n\n<p><code>char *chose_x</code> and any other string that doesn't change should be declared <code>const</code>.</p>\n\n<p>This:</p>\n\n<pre><code>if(input == 'O' || input == 'o')\n</code></pre>\n\n<p>should be:</p>\n\n<pre><code>if (tolower(input) == 'o')\n</code></pre>\n\n<p>and similarly for similar cases.</p>\n\n<p>This:</p>\n\n<pre><code>x = col / 2 - slen / 2;\n</code></pre>\n\n<p>can be:</p>\n\n<pre><code>x = (col - slen) / 2;\n</code></pre>\n\n<p>though, as @PeterCordes correctly notes, you need to be careful about applying this rule generally if working with signed integers. And yes, it is best practice to make variables <code>unsigned</code> if you know that the data will not be negative.</p>\n\n<p>This:</p>\n\n<pre><code> if(yy == 0 || yy % 2 == 0){\n mvprintw(y + yy, x, break_lines);\n }else{\n mvprintw(y + yy, x, play_lines);\n }\n</code></pre>\n\n<p>should use an intermediate variable for simplicity, and the first <code>== 0</code> is redundant:</p>\n\n<pre><code>char *lines;\nif (!(yy % 2))\n lines = break_lines;\nelse\n lines = play_lines;\nmvprintw(y + yy, x, lines);\n</code></pre>\n\n<p>Do a similar temporary variable strategy in your code for <code>Print an \"X\" in the cell</code>. This is in the name of DRY (\"don't repeat yourself\").</p>\n\n<p>Since you won't be modifying this:</p>\n\n<pre><code>char done_splash[] = \"Good move!\";\n</code></pre>\n\n<p>You should instead declare it as a <code>const char*</code> rather than an array.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T21:52:10.600",
"Id": "406366",
"Score": "4",
"body": "It's maybe worth mentioning that `(col - slen) / 2` is *not* exactly equivalent to `col / 2 - slen / 2`. The variables are signed, and `(1 - (-1) ) /2 = 2/2 = 1`, but `1/2` and `-1/2` are both 0 (truncation), and `0 - 0 = 0`. It's a safe optimization in *this* case because neither variable will ever hold a negative number. It might also be better to make both of them `unsigned`, so the compiler doesn't have to implement signed-division semantics and can just use a right shift."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T23:59:59.147",
"Id": "406372",
"Score": "0",
"body": "It did not occur to me to use unsigned. Is that a best practice in C for integers that will never be negative?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T00:54:01.027",
"Id": "406377",
"Score": "0",
"body": "@PeterCordes You're right; I've noted as much in an edit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T01:06:14.787",
"Id": "406379",
"Score": "2",
"body": "@some_guy632: it has some advantages and disadvantages. If you do `col - 2 < n`, you will get the \"unexpected\" result that col from 0..1 wraps to UINT_MAX-1..0, so the compare is false. Signed overflow being undefined behaviour also allows compilers to optimize more aggressively in some cases vs. using an unsigned type that's narrower than a pointer. (Which is the case for `unsigned` on 64-bit machines). See http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html. But yes, division by compile-time constants is cheaper for unsigned numbers than signed, power of 2 or not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T14:35:56.360",
"Id": "406419",
"Score": "1",
"body": "@Peter I wouldn't claim that using unsigned ints for numbers you expect to never be negative is a best practice in C though. The exceedingly minor performance advantage in some situations vs. the additional complexities is not that straight forward. Google explicitly says to not use unsigned numbers for \"this number should not be negative\"."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T15:07:59.563",
"Id": "210223",
"ParentId": "210217",
"Score": "4"
}
},
{
"body": "<h3>Avoid numbered variables</h3>\n\n<blockquote>\n<pre><code>char space_1 = ' ';\nchar space_2 = ' ';\nchar space_3 = ' ';\nchar space_4 = ' ';\nchar space_5 = ' ';\nchar space_6 = ' ';\nchar space_7 = ' ';\nchar space_8 = ' ';\nchar space_9 = ' ';\nint space_1y, space_1x;\nint space_2y, space_2x;\nint space_3y, space_3x;\nint space_4y, space_4x;\nint space_5y, space_5x;\nint space_6y, space_6x;\nint space_7y, space_7x;\nint space_8y, space_8x;\nint space_9y, space_9x;\n</code></pre>\n</blockquote>\n\n<p>If you find yourself using numbered variables, you almost always should be using an array instead. E.g. </p>\n\n<pre><code>const int CELL_COUNT = 9;\n\ntypedef struct {\n int y;\n int x;\n} Location;\n\nchar cells[CELL_COUNT] = \" \";\nLocation cell_locations[CELL_COUNT];\n</code></pre>\n\n<p>Even with the constant and type declaration, this is still shorter than your original. And now you can refer to, e.g. <code>cell_locations[0].x</code> which is more self-documenting. Instead of a naming convention, we have an enforceable type pattern. A <code>Location</code> must have a <code>y</code> and an <code>x</code>. There must be <code>CELL_COUNT</code> (9) <code>cell_locations</code>. </p>\n\n<p>You can move <code>Location</code> into a header file that you can reuse. </p>\n\n<p>Later, instead of </p>\n\n<blockquote>\n<pre><code> space_1y = y + 1; space_1x = x + 1;\n space_2y = y + 1; space_2x = x + 3;\n space_3y = y + 1; space_3x = x + 5;\n space_4y = y + 3; space_4x = x + 1;\n space_5y = y + 3; space_5x = x + 3;\n space_6y = y + 3; space_6x = x + 5;\n space_7y = y + 5; space_7x = x + 1;\n space_8y = y + 5; space_8x = x + 3;\n space_9y = y + 5; space_9x = x + 5;\n</code></pre>\n</blockquote>\n\n<p>We can say something like </p>\n\n<pre><code> int i = 0;\n for (int current_y = y + 1, n = y + line_len; current_y < n; current_y += 2) {\n for (int current_x = x + 1, m = x + line_len; current_x < m; x += 2) {\n cell_locations[i].y = current_y;\n cell_locations[i].x = current_x;\n i++;\n }\n }\n</code></pre>\n\n<p>And instead of nine </p>\n\n<blockquote>\n<pre><code> if(space_1 == 'X'){\n attron(COLOR_PAIR(Xs));\n }else if(space_1 == 'O'){\n attron(COLOR_PAIR(Os));\n }\n mvaddch(space_1y, space_1x, space_1);\n</code></pre>\n</blockquote>\n\n<p>We can say something like </p>\n\n<pre><code>int determine_color_pair(char mark) {\n if (mark == 'X') {\n return Xs;\n }\n\n if (mark == 'O') {\n return Os;\n }\n\n return BG;\n} \n</code></pre>\n\n<p>and </p>\n\n<pre><code> for (int j = 0; j < CELL_COUNT; j++) {\n attron(COLOR_PAIR(determine_color_pair(cells[j])));\n mvaddch(cell_locations[j].y, cell_locations[j].x, cells[j]);\n }\n</code></pre>\n\n<h3>Prefer descriptive names to comments</h3>\n\n<blockquote>\n<pre><code>void f_intro(); // Print elaborate \"animated\" intro splash\n</code></pre>\n</blockquote>\n\n<p>With proper naming, you won't need comments for things like this. </p>\n\n<pre><code>void display_intro();\n</code></pre>\n\n<p>or even </p>\n\n<pre><code>void display_elaborate_pseudo_animated_intro_splash();\n</code></pre>\n\n<p>Although I think that's overkill. But for a function that you only call once, that kind of name is possible. </p>\n\n<p>I'm not crazy about using an <code>f_</code> prefix to indicate a function. Functions should generally have verb names, because they do things. Variables have noun names, because they represent things. It is more common to use prefixes to separate your code from other code that may be linked, e.g. <code>ttt_display_intro</code>. Then if you link your Tic-Tac-Toe game with a text-based RPG (e.g. Zork or Rogue), you can have <code>display_intro</code> functions in both. </p>\n\n<p>In code examples, they often put comments on every variable for didactic purposes. I find this unfortunate, as it gives people an unrealistic view of how comments should be used. Comments should be used to explain <em>why</em> code does things rather than what the code is doing. The code itself should mostly suffice for telling people what the code is doing. </p>\n\n<p>I find the practice of comments after code on the same line obnoxious. I would much rather see </p>\n\n<pre><code>// Takes the winning character and creates a splash screen declaring victory ('X', 'O', or 'T' for Tie)\nvoid f_declare_winner(char symbol);\n</code></pre>\n\n<p>Note how that gets rid of the scroll bar. </p>\n\n<p>If the comment is not needed to appear in the left column, then you are probably better off without it. </p>\n\n<h3>Simplification</h3>\n\n<blockquote>\n<pre><code> }else if(input == 'R' || input == 'r'){\n int r;\n r = rand() % 2;\n if(r == 0){\n // Pick 'X'\n choice_ptr = chose_x;\n slen = strlen(choice_ptr);\n x = col / 2 - slen / 2;\n mvprintw(y, x, choice_ptr);\n refresh();\n getch();\n return 'X';\n }else if(r == 1){\n // Pick 'O'\n choice_ptr = chose_y;\n slen = strlen(choice_ptr);\n x = col / 2 - slen / 2;\n mvprintw(y, x, choice_ptr);\n refresh();\n getch();\n return 'O';\n }\n</code></pre>\n</blockquote>\n\n<p>This whole block can be removed.</p>\n\n<p>Replace </p>\n\n<blockquote>\n<pre><code> input = getch();\n if(input == 'X' || input == 'x'){\n</code></pre>\n</blockquote>\n\n<p>with </p>\n\n<pre><code> input = toupper(getch());\n if (input == 'R') {\n int r = rand() % 2;\n input = (r == 0) ? 'X' : 'O';\n }\n\n if (input == 'X') {\n</code></pre>\n\n<p>Now you don't have to duplicate the code. </p>\n\n<p>At the end of the function, </p>\n\n<blockquote>\n<pre><code> f_setup();\n</code></pre>\n</blockquote>\n\n<p>should probably be </p>\n\n<pre><code> return f_setup();\n</code></pre>\n\n<p>Or change things to use an infinite loop rather than a recursive call. </p>\n\n<pre><code>void display_prompt_and_wait_for_input(const char *choice_ptr) {\n int slen = strlen(choice_ptr);\n x = col / 2 - slen / 2;\n mvprintw(y, x, choice_ptr);\n refresh();\n getch();\n}\n\n// Prompt player to pick a side or pick random selection, returns char\nchar f_setup() {\n const char setup_str1[] = \"Pick a side!\";\n const char setup_str2[] = \"Press 'X', 'O', or 'R' for Random!\";\n char *chose_x = \"You chose X's! Any key to continue...\";\n char *chose_y = \"You chose O's! Any key to continue...\";\n\n for (;;) {\n clear();\n getmaxyx(stdscr, row, col);\n y = row / 2 - 1;\n int slen = strlen(setup_str1);\n x = col / 2 - slen / 2;\n mvprintw(y++, x, setup_str1);\n slen = strlen(setup_str2);\n x = col / 2 - slen / 2;\n mvprintw(y++, x, setup_str2);\n y++;\n refresh();\n\n int input = toupper(getch());\n if (input == 'R') {\n int r = rand() % 2;\n input = (r == 0) ? 'X' : 'O';\n }\n\n switch (input) {\n case 'X':\n display_prompt_and_wait_for_input(chose_x);\n return 'X';\n case 'O':\n display_prompt_and_wait_for_input(chose_y);\n return 'O';\n default:\n char *err_str = \"Input error! Any key to continue...\";\n display_prompt_and_wait_for_input(err_str);\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T22:37:18.403",
"Id": "406369",
"Score": "0",
"body": "Thanks! I wish I could mark all of these as answers. I will be using all of these tips for my next project shortly."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T16:04:23.167",
"Id": "210228",
"ParentId": "210217",
"Score": "13"
}
},
{
"body": "<p>Here are a number of things that may help you improve your program.</p>\n\n<h2>Eliminate global variables where practical</h2>\n\n<p>Having routines dependent on global variables makes it that much more difficult to understand the logic and introduces many opportunities for error. For this program, it would be easy and natural to wrap nearly all of the global variables in a <code>struct</code> to make it clear which things go together. Then all you need is to pass around a pointer to that <code>struct</code>. In some case, such as <code>x</code>, it could simply be put as a local variable into functions that uses that variable. Even better, in the case of <code>t</code>, it can be eliminated entirely because <code>time(NULL)</code> will do what you need.</p>\n\n<h2>Eliminate unused variables</h2>\n\n<p>This code declares variables <code>px</code> and <code>py</code> but then does nothing with them. Your compiler is smart enough to help you find this kind of problem if you know how to ask it to do so.</p>\n\n<h2>Use more whitespace to enhance readability of the code</h2>\n\n<p>Instead of crowding things together like this:</p>\n\n<pre><code>for(y=0;y<=row;y++){\n for(x=0;x<=col;x++){\n</code></pre>\n\n<p>most people find it more easily readable if you use more space:</p>\n\n<pre><code>for(y = 0; y <= row; y++) {\n for(x = 0;x <= col; x++) {\n</code></pre>\n\n<h2>Don't Repeat Yourself (DRY)</h2>\n\n<p>There is a <em>lot</em> of repetitive code in this and some peculiar variables such as <code>space_1</code> through <code>space_9</code>. This could be greatly improved by simply using an array <code>space[9]</code> and using index variables to step through those spaces. A similar thing could be done with the overly long <code>f_evaluate_turn()</code> function.</p>\n\n<h2>Return something useful from functions</h2>\n\n<p>The way the functions are currently written, most return <code>void</code> but this prevents simplifying the code. For example, instead of this:</p>\n\n<pre><code>f_player_turn();\nf_evaluate_turn();\nif(game_over == 0){\n f_AI_turn();\n f_evaluate_turn();\n}\n</code></pre>\n\n<p>You could write this if each turn evaluated itself and returned <code>true</code> if the game is not yet over:</p>\n\n<pre><code>if (f_player_turn()) {\n f_AI_turn();\n}\n</code></pre>\n\n<h2>Use better naming</h2>\n\n<p>Some of the names, such as <code>game_over</code> and <code>running</code> are good because they are descriptive, but others, such as <code>sx</code> don't give much hint as to what they might mean. Also, using the <code>f_</code> prefix for all functions is simply annoying and clutters up the code.</p>\n\n<h2>Use a better random number generator</h2>\n\n<p>You are currently using </p>\n\n<pre><code>which = rand() % 3;\n</code></pre>\n\n<p>There are a number of problems with this approach. This will generate lower numbers more often than higher ones -- it's not a uniform distribution. Another problem is that the low order bits of the random number generator are not particularly random, so neither is the result. On my machine, there's a slight but measurable bias toward 0 with that. See <a href=\"http://stackoverflow.com/questions/2999075/generate-a-random-number-within-range/2999130#2999130\">this answer</a> for details, but I'd recommend changing that to something like those shown in the link. It doesn't matter a great deal in this particular application, but it's good to know generally.</p>\n\n<h2>Create and use smaller functions</h2>\n\n<p>This code could be much shorter and easier to read, understand and modify if it used smaller functions. For example, using a function like this consistently would greatly improve the readability of the code:</p>\n\n<pre><code>void place(int x, int y, char ch) {\n switch (ch) {\n case ' ':\n attron(COLOR_PAIR(BG));\n mvprintw(y, x, \" \");\n attroff(COLOR_PAIR(BG));\n break;\n case 'X':\n attron(COLOR_PAIR(Xs));\n mvprintw(y, x, \"X\");\n attroff(COLOR_PAIR(Xs));\n break;\n case 'O':\n attron(COLOR_PAIR(Os));\n mvprintw(y, x, \"O\");\n attroff(COLOR_PAIR(Os));\n break;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T00:53:51.057",
"Id": "406376",
"Score": "0",
"body": "Aren't you missing a loop around `which = rand() / (RAND_MAX / 3);` for it to be correct? (well less biased, although admittedly `rand` is generally so horrible that you can't save it even if you try."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T01:44:00.003",
"Id": "406381",
"Score": "0",
"body": "@Voo yes, a loop as in the linked answer is the best way to do it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T03:05:27.733",
"Id": "406382",
"Score": "1",
"body": "Both `which = rand() % 3;` and `which = rand() / (RAND_MAX / 3);` form a similarly slightly skewed distribution. Recommend the 2nd does not add distribution benefit. At least `rand() % 3` is clear."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T03:08:58.037",
"Id": "406383",
"Score": "0",
"body": "\"the low order bits of the random number generator are not particularly random\" comes from where? Certainly a quality of implementation issue and not a C specification."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T12:48:51.107",
"Id": "406411",
"Score": "0",
"body": "@chux: You're correct in your observations. My comment about low order bits comes from the poor quality of implementations (often linear congruential algorithms), but the standard, too, is at fault for not specifying any requirements on the quality of the random numbers from `rand()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T13:00:25.180",
"Id": "406414",
"Score": "0",
"body": "Even if the \"low order bits of the random number generator are not particularly random\" is true - let us even assume the lower byte is 0, `rand() / (RAND_MAX / 3)` affords no benefit over `rand() % 3`. `rand() % 3` depends on all the bits. Perhaps you were seeing it as `rand() % 4`? `rand()` like many computational functions in C, all lack quality requirements. It isn't that `rand()` is bad, it is that various implementations of it are weak - and folks tolerate it. All in all, a _good_ review aside from PRNG part."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T13:04:54.113",
"Id": "406416",
"Score": "0",
"body": "@chux: You're right, thanks. The intent of my comments on `rand()` was to get the reader to follow the link to the fuller discussion of what's wrong with `rand()` and how to address the flaws. My suggestion is only *part* of a better implementation. As a practical matter, this program is only using it for making a pretty display and not cryptography, so it probably doesn't matter much no matter which variation is used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T13:08:11.630",
"Id": "406417",
"Score": "0",
"body": "I've updated my answer to just point to the PRNG answer and omit the code. Thanks, all for the helpful comments!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-28T22:39:59.403",
"Id": "406961",
"Score": "0",
"body": "I have implemented a lot of these improvements and am almost done with a better version. I managed to get rid if global variables almost entirely (which required using a lot more parameters in my functions) and all I've got left is the AI which I'm putting more effort into. Is it common practice to post the improved version? Is anyone interested in reviewing it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-28T22:42:19.597",
"Id": "406963",
"Score": "2",
"body": "If youโd like a review of the new code, post it as a new question and link to this one. Iโm sure people will review it."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T16:33:04.390",
"Id": "210231",
"ParentId": "210217",
"Score": "12"
}
}
] | {
"AcceptedAnswerId": "210228",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T12:26:15.043",
"Id": "210217",
"Score": "15",
"Tags": [
"beginner",
"c",
"tic-tac-toe",
"ai",
"curses"
],
"Title": "Ncurses Tic Tac Toe with simplistic AI"
} | 210217 |
<p>I'm using react native to build an iOS app, but have little to no experience in obj C or iOS development. The app I'm building has a bunch of content files that aren't user specific, will be downloaded from some CDN, and will (mostly) be behind a paywall. As I understand it, the best place for this would be somewhere within Application Support (the Cache dir doesn't seem to fit the bill because this is more about allowing users to download content for offline use than caching per se. Also, I think there's no guarantees about the lifetime of files in the Cache dir(?).). Also, I want to make sure that those content files aren't backed up to iCloud or anywhere else; and that they're not accessible by the user or other apps.</p>
<p>I have two questions:</p>
<ol>
<li><p>Does that placement for the content fit with iOS recommendations/best practices?</p></li>
<li><p>Because I have little obj c/iOS experience, I'd be super grateful if you lovely people could cast your eyes over the code and review it?</p></li>
</ol>
<pre><code>// *** blah.h
#import <React/RCTBridgeModule.h>
@interface Blah : NSObject <RCTBridgeModule>
@end
// *** blah.m
#import "Blah.h"
@implementation Blah
RCT_EXPORT_MODULE();
RCT_EXPORT_METHOD(createAppDataPath:(NSString *)namespace findEventsWithResolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject){
NSUInteger length = [namespace length];
if (length < 1) {
reject(@"namespace_invalid", @"Namespace param should be non-empty string", nil);
return;
}
// ref: https://stackoverflow.com/a/17430820/1937302
@try {
NSString *appSupportDir = [NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES) lastObject];
NSString *cacheDir = [appSupportDir stringByAppendingString: [NSString stringWithFormat:@"/%@", namespace]];
// check for existence of directory:
BOOL isDir;
BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:cacheDir isDirectory:&isDir];
if (!exists) {
NSError *error = nil;
// if not present, create it:
BOOL result = [[NSFileManager defaultManager] createDirectoryAtPath:cacheDir withIntermediateDirectories:YES attributes:nil error:&error];
if (!result) {
reject(@"cant_create", @"Can't create directory", error);
return;
}
} else if (!isDir) {
reject(@"non_directory_path_exists", @"Path already exists as a non-directory", nil);
return;
}
// now mark the directory as excluded from iCloud backups:
NSURL *url = [NSURL fileURLWithPath:cacheDir];
NSError *error = nil;
BOOL result = [url setResourceValue:@YES forKey:NSURLIsExcludedFromBackupKey error:&error];
if (!result) {
reject(@"cant_exclude_from_backups", @"Can't exclude from backups", error);
return;
}
resolve(cacheDir);
}
@catch(NSException *exception) {
// TODO: capture information from exception and pass to rejection?
// ref: https://stackoverflow.com/questions/43561531/how-to-convert-an-exception-into-an-nserror-object\
// ref: https://stackoverflow.com/a/4654759/1937302
// ref: https://developer.apple.com/documentation/foundation/nsexception
reject(@"exception", @"An exception has occurred", nil);
}
}
@end
</code></pre>
| [] | [
{
"body": "<p><a href=\"https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/FileSystemOverview/FileSystemOverview.html#//apple_ref/doc/uid/TP40010672-CH2-SW12\" rel=\"nofollow noreferrer\">File System Basics</a> tells us:</p>\n\n<blockquote>\n <p>The contents of the <code>Library</code> directory (with the exception of the <code>Caches</code> subdirectory) are backed up by iTunes and iCloud.</p>\n</blockquote>\n\n<p>And</p>\n\n<blockquote>\n <p>Put data cache files in the <code>Library/Caches/</code> directory. Cache data can be used for any data that needs to persist longer than temporary data, but not as long as a support file. Generally speaking, the application does not require cache data to operate properly, but it can use cache data to improve performance. Examples of cache data include (but are not limited to) database cache files and transient, downloadable content. Note that the system may delete the <code>Caches/</code> directory to free up disk space, so your app must be able to re-create or download these files as needed.</p>\n</blockquote>\n\n<p>If this content is readily re-downloadable, <code>Caches</code> might actually be a reasonable idea. It makes your app a โgood citizenโ. If the user is running low on storage, it might be better to allow re-downloadable content to be removed rather than tempting the user, looking at their storage taken up by various apps, to contemplate removing your app because itโs taking up a lot of unreclaimable space.</p>\n\n<p>If you want to ensure the content will never be deleted when the device runs low on space, then go ahead and put it in the <code>Application Support</code> directory, but manually exclude it from backups, like you have done.</p>\n\n<p>Feel free to refer the <a href=\"https://developer.apple.com/videos/play/tech-talks/204/\" rel=\"nofollow noreferrer\">iOS Storage Best Practices</a> video (and that page has useful links).</p>\n\n<hr>\n\n<p>You said:</p>\n\n<blockquote>\n <p>I think there's no guarantees about the lifetime of files in the Cache dir</p>\n</blockquote>\n\n<p>Correct. In practice, when (a) the device runs low on space; and (b) your app is not running, the OS can purge this directory. It starts with apps that have been use less recently.</p>\n\n<blockquote>\n <p>Also, I want to make sure that those content files aren't backed up to iCloud or anywhere else; and that they're not accessible by the user or other apps.</p>\n</blockquote>\n\n<p>By the way, whether itโs backed-up or not and whether itโs accessible by the user are two different questions. E.g., files in the <code>Application Support</code> directory are backed-up (other than, obviously, content of the <code>Caches</code> folder or those files explicitly designated to not be backed-up). But the contents are not visible to the user. Only user documents stored in <code>Documents</code> folder or iCloud Drive are visible to the end-user.</p>\n\n<p>So, if your content is not readily re-downloadable, but you donโt want to expose them to the individual files, <code>Application Support</code> (without specifying <code>NSURLIsExcludedFromBackupKey</code>) might be prudent. Itโs your call.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-01T21:49:24.247",
"Id": "214572",
"ParentId": "210220",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T12:48:53.277",
"Id": "210220",
"Score": "4",
"Tags": [
"objective-c",
"ios",
"react-native"
],
"Title": "Creating directory within Application Support, and preventing iCloud backup"
} | 210220 |
<p>I am trying to solve <a href="https://oj.leetcode.com/problems/two-sum/" rel="nofollow noreferrer">this problem</a>:</p>
<blockquote>
<p>Given an array of integers, return indices of the two numbers such that they add up to a specific target.</p>
</blockquote>
<p>and this is my implementation:</p>
<pre><code>public int[] twoSum(int[] numbers, int target) {
Map<Integer, Integer> numbersMap = new HashMap<Integer, Integer>();
int[] requiredNumbers = null;
int index = 0;
for (int number : numbers) {
if (numbersMap.containsKey(target - number)) {
requiredNumbers = new int[2];
requiredNumbers[0] = numbersMap.get(target - number);
requiredNumbers[1] = index;
return requiredNumbers;
} else {
numbersMap.put(number, index);
index++;
}
}
return requiredNumbers;
}
</code></pre>
<p>How can I improve its execution time?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T18:24:05.123",
"Id": "406350",
"Score": "1",
"body": "you could have used indexed for loop as you are anyway keeping the track of the index"
}
] | [
{
"body": "<p>If the size of your input array can be <strong>large</strong>, you can get a speed-up by preallocating the capacity of your <code>HashMap</code>:</p>\n\n<pre><code>Map<Integer, Integer> numbersMap = new HashMap<Integer, Integer>(numbers.length * 2);\n</code></pre>\n\n<p>As the algorithm runs, data will be added to the <code>HashMap</code>. When number of entries exceeds the <code>capacity * load_factor</code>, the hashmap's capacity is doubled, and the elements are re-binned for the larger capacity. This capacity doubling and rebinning takes time. It doesn't happen often, <span class=\"math-container\">\\$O(\\log N)\\$</span> times, but it can be eliminated by starting with a hashmap of sufficient capacity.</p>\n\n<p>The <code>load_factor</code> defaults to 0.75, so an initial capacity larger than <code>numbers.length * 4/3</code> is required. <code>numbers.length * 2</code> is a simple expression that satisfies that requirement.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T19:55:20.360",
"Id": "210239",
"ParentId": "210225",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T15:12:30.017",
"Id": "210225",
"Score": "3",
"Tags": [
"java",
"performance",
"programming-challenge"
],
"Title": "Find two numbers that add up to target"
} | 210225 |
<p>I, <a href="https://codereview.stackexchange.com/q/157875/15315">also</a>, need to know whether this is a valid implementation of the factory pattern.</p>
<p>The <a href="https://github.com/THUFIR/com.toscrape.books.selenium/tree/f206050e7f68ca3caf446d09d78c7a6bf3e72fb4" rel="nofollow noreferrer">amount of effort which goes into</a> configuring <code>DriverFactory</code> to simply get a <code>WebDriver</code> instance seems disproportionate to the point where I ask: "is there not a better way?"</p>
<p>The main class code:</p>
<pre><code>package dur.bounceme.net.SeleniumBase;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Logger;
import org.openqa.selenium.WebDriver;
public class App {
private static final Logger LOG = Logger.getLogger(App.class.getName());
private Properties properties = new Properties();
public static void main(String[] args) throws IOException {
new App().initSelenium();
}
private void initSelenium() throws IOException {
properties.loadFromXML(App.class.getResourceAsStream("/selenium.xml"));
WebDriver webDriver = DriverFactory.getWebDriver(properties); //is this factory and usage correct?
HomePage homePage = new HomePage(webDriver);
homePage.populateCatalogue();
}
}
</code></pre>
<p>And my factory: </p>
<pre><code>package dur.bounceme.net.SeleniumBase;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
public class DriverFactory {
private static final Logger LOG = Logger.getLogger(DriverFactory.class.getName());
private Properties properties = new Properties();
private FirefoxBinary firefoxBinary = null;
private FirefoxOptions firefoxOptions = null;
private WebDriver webDriver = null;
private URL url = null;
private String driver = null;
private String gecko = null;
private final List<String> commandLineOptions = new ArrayList<>();
private DriverFactory() {
}
private DriverFactory(Properties properties) throws MalformedURLException {
this.properties = properties;
loadProps();
init();
}
static WebDriver getWebDriver(Properties properties) throws MalformedURLException {
DriverFactory driverFactory = new DriverFactory(properties);
return driverFactory.webDriver;
}
private void loadProps() throws MalformedURLException {
LOG.fine(properties.toString());
url = new URL(properties.getProperty("url"));
driver = properties.getProperty("driver");
gecko = properties.getProperty("gecko");
String commandLineOption = properties.getProperty("option01");
commandLineOptions.add(commandLineOption);
}
private void init() throws MalformedURLException {
firefoxBinary = new FirefoxBinary();
commandLineOptions.forEach((commandLineOption) -> {
LOG.fine(commandLineOption.toString());
firefoxBinary.addCommandLineOptions(commandLineOption);
});
System.setProperty(driver, gecko);
firefoxOptions = new FirefoxOptions();
firefoxOptions.setBinary(firefoxBinary);
webDriver = new FirefoxDriver(firefoxOptions);
webDriver.get(url.toString());
LOG.fine(webDriver.getTitle());
LOG.fine(webDriver.getCurrentUrl().toLowerCase());
}
void close() {
webDriver.close();
}
}
</code></pre>
<p>There seems no nice way to get around loading configuration from a file, which is then loaded. But, it strikes me that I'm re-inventing the wheel of loading a props file for the purpose of configuring a Selenium <code>WebDriver</code> when I expect there's a tried-and-true approach.</p>
<p>Or, at least, more re-usable.</p>
<p>Although, what possible use there would be for multiple <code>WebDriver</code> instances is beyond me. It would seem Selenium Grid would handle that question quite differently.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T18:35:12.377",
"Id": "406351",
"Score": "1",
"body": "Looks like this factory will only create drives for FireFox. What about other browsers such as Chrome or IE? The factory should create more than one item of the same kind."
}
] | [
{
"body": "<h3>Quick Simplifications</h3>\n\n<ul>\n<li>The 0-args constructor is not used. Remove it.</li>\n<li><code>close()</code> <em>can not</em> be called in a meaningful way. Nobody can obtain an instance of <code>DriverFactory</code>, so making that an instance method is not useful in any way.</li>\n<li>You're misusing fields as variables. Everything you're doing can be put into the factory method itself. There's no need for any instance data, you're not accessing it anywhere.</li>\n</ul>\n\n<p>Let's consider instead:</p>\n\n<pre><code>static WebDriver getWebDriver(Properties properties) throws MalformedURLException {\n LOG.fine(properties.toString);\n final URL url = new URL(properties.getProperty(\"url\"));\n final String driver = properties.getProperty(\"driver\");\n final String gecko = properties.getProperty(\"gecko\");\n final List<String> commandLineOptions = new ArrayList<>();\n commandLineOptions.add(properties.getProperty(\"option01\"));\n\n final FirefoxBinary ffBinary = new FirefoxBinary();\n commandLineOptions.forEach((commandLineOption) -> {\n LOG.fine(commandLineOption);\n ffBinary.addCommandLineOptions(commandLineOption);\n });\n System.setProperty(driver, gecko);\n\n final FirefoxOptions ffOptions = new FirefoxOptions();\n ffOptions.setBinary(ffBinary);\n\n WebDriver result = new FirefoxDriver(ffOptions);\n result.get(url.toString()); \n LOG.fine(webDriver.getTitle());\n LOG.fine(webDriver.getCurrentUrl().toLowerCase());\n return result;\n}\n</code></pre>\n\n<p>This does mostly the same as the code you presented. We can see here that opening yourself up to <code>MalformedURLException</code> is <strong>not</strong> necessary. You're reading the String from properties into a URL and then call <code>.toString()</code> on it.</p>\n\n<p>What we can see pretty easily now is that you're reading the contents of the passed Properties into variables to just use them once. It might be easier to reimagine the code as something like the following:</p>\n\n<pre><code>public static WebDriver getWebDriver(Properties properties) {\n final FirefoxBinary ffBinary = discoverBinary(properties);\n setSystemProperties(properties);\n final FirefoxOptions ffOptions = buildOptions(ffBinary);\n return createWebDriver(ffOptions, properties);\n}\n</code></pre>\n\n<p>This makes the code comparatively abstract and easy to follow. You can grasp what happens without needing a deeper understanding of Selenium itself (not that the original code required a lot of it).</p>\n\n<p>This abstraction just makes it easier to understand what's going on. The methods themselves are pretty trivial :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T19:08:00.607",
"Id": "406354",
"Score": "0",
"body": "My thinking was that this method could end up many lines long so to put as much as possible into other classes. No?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T19:09:44.990",
"Id": "406355",
"Score": "1",
"body": "But that needs to provide abstraction. Don't just hide away lines, that's only moving the problem. Hide complexity"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T19:03:46.800",
"Id": "210238",
"ParentId": "210234",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T17:56:47.557",
"Id": "210234",
"Score": "0",
"Tags": [
"java",
"object-oriented",
"factory-method",
"selenium",
"properties"
],
"Title": "Factory to instantiate and configure Selenium WebDriver"
} | 210234 |
<p>The program uses a very simple algorithm to calculate the supporting forces of a simply supported beam. </p>
<p>I'd like to know if thorwables are good practice to handle semantic errors and if one should always use "getters" and "setters" or if it is ok to access fields in data model objects directly (the load Class). </p>
<p>How do you judge the readibility. Any tips/ hints?</p>
<p>This Class creates a beam:</p>
<pre><code>/**
* A simply supported beam.
*
* @author Berthold
*
*/
import java.util.ArrayList;
import java.util.List;
public class Beam {
private double length;
private List <Load> stress;
/*
* Create a beam
*/
public Beam(double length){
this.length=length;
stress=new ArrayList<Load> ();
}
/*
* Add load
*/
public void addLoad(Load load) throws BeamError {
if (load.x>=0 && load.x<=length && load.x+load.length<=length) stress.add(load);
else throw new BeamError ("Load not withing girder length!",stress.size()+1);
}
/*
* Get load
*/
public Load getLoad(int atIndex){
return stress.get(atIndex);
}
/*
* Get length
*/
public double getLength(){
return length;
}
/*
* Return # of loads acting
*/
public int numberOfLoads(){
return stress.size();
}
}
</code></pre>
<p>This Class adds a load:</p>
<pre><code>/**
* Load
*
* Load acting downwards -
* Load acting upwards +
*
* Single load: length=0
* line load: x=distance from bearing A. Length= length of line load
*
* @author Berthold
*
*/
public class Load {
public double force; // Force
public double x; // x= length from beginning of the girder to the force acting
public double length;// If not 0 => force is a line load. Starts at x, ends at x+l
/*
* Create a single force or a line load.
*/
public Load (double force,double x,double length){
this.force=force;
this.x=x;
this.length=length;
}
}
</code></pre>
<p>This class claculates the beams supporting forces:</p>
<pre><code>/**
* Solves a simply supported beam with single and/ or line loads.
*
* Beam is not cantilevered (two bearings, one at the beginning, one at the end).
* Beam has a statically determined support configuration.
*
* Force, leading sign:
* + Force acts upwards
* - Force acts downwards
*
* Torque, leading sing
* + Clockwise
* - Anti- clockwise
*
* Bearings
* A is left, B is right
* A is pinned
* B is a roller
*
* Length
* Starts at A (0) and ends at B(l)
*
* Result:
* Resulting forces at the bearings can point up- or downwards. A negative result means
* that the force points in the opposite direction of the acting force. So, - means
* "upwards" regarding the result.
*
* |---> F1 F2 Fn
* o-------------------------------o
* A B
* |---------x1----x2---xn
* |
* |--------------- l -------------|
*
* x=0 x=l
*
* Solver calculates from left to right by solving the following equation
* (Result is resulting force at bearing A):
* Sum M=0=FA x l - F1 x (l-x1) - F2(l-x2) x ..... x Fn(l-xn)
*
* Resulting force at bearing B is calculated by solving this equation:
* Sum V=0=FA-F1-F2-....-Fn+FB
*
* @author Berthold
*
*/
public class Solve {
/*
* Get result
*/
public static Result getResults(Beam beam){
Result r=new Result();
double torqueSum=0;
double loadSum=0;
Load load;
for (int i=0;i<=beam.numberOfLoads()-1;i++){
load=beam.getLoad(i);
// Check if load is a single load
if (load.length==0){
loadSum=loadSum+load.force;
torqueSum=torqueSum+load.force*(beam.getLength()-load.x);
// Line load
} else{
double xx=(beam.getLength()-load.x)-load.length/2;
double ff=load.force*load.length;
loadSum=loadSum+ff;
torqueSum=torqueSum+loadSum*xx;
}
}
// We multiply by -1 to get the right direction of the force at the bearing.
// Remember: Per our convention - means the force points downward (globally).
// For the result - means it points in the opposite direction of the acting forces,
// so it points upwards.....
// FA=(Sum Fn x xn)/l
r.bearingA=-1*torqueSum/beam.getLength();
// FB=Sum F - FA
r.bearingB=-1*loadSum-r.bearingA;
return r;
}
}
</code></pre>
<p>Error handling:</p>
<pre><code>/**
* BeamError
*
* Describes an error occured while creating a new beam or
* setting it's properties.
*
* @author Berthold
*
*/
public class BeamError extends Throwable{
String errorDescription;
int loadNumberCausedError;
public BeamError(String errorDescription,int loadNumberCausedError){
this.errorDescription=errorDescription;
this.loadNumberCausedError=loadNumberCausedError;
}
}
</code></pre>
<p>Main Class, shows how to use the package:</p>
<pre><code>/**
* A simple driver
*
* Create a beam, add loads, solve.....
*
*/
public class MainBeamCalculator {
public static void main(String [] args){
// A girder, length=10 m
Beam myBeam=new Beam (15);
// Add some stress
try{
myBeam.addLoad(new Load(-5.5,1,0));
myBeam.addLoad(new Load(-2,4,0));
myBeam.addLoad(new Load(-3,8,0));
// Get results
System.out.println("Beam. Loads:"+myBeam.numberOfLoads());
Result r=Solve.getResults(myBeam);
System.out.println("Bearing A:"+r.bearingA+" B:"+r.bearingB);
}catch (BeamError e){
System.out.println ("Error while creating beam:"+e.errorDescription);
System.out.println("Load #"+e.loadNumberCausedError+" wrong!");
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-28T22:10:44.643",
"Id": "406954",
"Score": "2",
"body": "You should not change the question based on the reviews. This may confuse future readers...."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-28T22:29:45.430",
"Id": "406957",
"Score": "0",
"body": "Got your point. So, better repost the old code? Is there any good practice to post improved code based on an answer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-28T22:34:38.760",
"Id": "406960",
"Score": "1",
"body": "Yes, revert to the original code please. This site is not really meant to do \"online improvement\" If you feel the suggestions raise some confusion create a new question, maybe referencing this one."
}
] | [
{
"body": "<p>Thanks for sharing your code.</p>\n\n<h1>thorwables are good practice to handle semantic errors?</h1>\n\n<p>There is an argument running in the community when exactly exceptions should be used and when not. You might get different answers depending on who you ask.\nThe common ground here ist that exceptions should not be misused to control the program flow.</p>\n\n<p>IMHO your use of the exception is ok since the detected situation needs user interaction to be solved. The there is no way the program can recover from that on its own.</p>\n\n<h1>one should always use \"getters\" and \"setters\"?</h1>\n\n<p>Yes.</p>\n\n<p>The reason is that your <code>Load</code> class may develop and get Extentions (specialized Loads that extend your currrent <code>Load</code> class). Or you decide to change the way your <code>Load</code> class stores its properties. accessing the properties via getter and setter yould enable you to change that without affecting the calling code.</p>\n\n<p>Some may argue that this is overkill for such a small problem, but you should get used to do so \"in principle\". </p>\n\n<p><strong>BUT</strong>\nThis holds only true for <em>Data Transfer Objects</em> or <em>Value Objects</em>, anything that can be considered being the \"Data Model\".</p>\n\n<p>Classes holding <em>business logic</em> <strong>should not</strong> have getters or setters. </p>\n\n<h1>How do you judge the readibility.</h1>\n\n<h2>Comments</h2>\n\n<p>Your code has a lot of comments.</p>\n\n<p>Some decades ago this was concidered a good thing but currently the we agree that <em>less is more</em>. \nComments should explain <strong>why</strong> the code is like it is. Your identifiers (names of methods and variables) should explain how it works.</p>\n\n<p>The reason is that comments thend to erode. \nWhile your program develops you change the code but not the comments for various resons: no time, to concentrated or something along that.\nYou intent to change the comment later but that never happens usually for the same reasons you did noch change it immediately.</p>\n\n<p>This way youir comments turn into lies while the code they used to describe changes.</p>\n\n<h3>good comments</h3>\n\n<p>Yes, your code also has good comments. ;o)</p>\n\n<p>The header comment of class <code>Solution</code> is a good one. \nIt describes what the code is <em>supposed</em> to do.</p>\n\n<h3>bad comments</h3>\n\nvariable explanations\n\n<ol>\n<li><p>repetition</p>\n\n<pre><code>public double force; // Force\n</code></pre>\n\n<p>This is just a repetition of the name. \nIt adds no value for the reader.</p></li>\n<li><p>single character names / explained variables</p>\n\n<p>In Java the length of identifiers is virtually unbounded. \nThere is no need to be stingy with characters. \nInstead of that explanation in class <code>Load</code></p>\n\n<pre><code>public double x; // x= length from beginning of the girder to the force acting\n</code></pre>\n\n<p>the variable could be named like this</p>\n\n<pre><code>public double distanceFromMount;\n</code></pre>\n\n<p>the same applies to variable <code>length</code></p>\n\n<pre><code> public double lineLoadLegth;\n</code></pre></li>\n</ol>\n\n<p>BTW: when dealing with physical values it is a good idea to add <em>units</em> to identifier names. </p>\n\n<p>Remember the failed Mars missions <em>Mars Climate Orbiter</em> and <em>Mars Polar Lander</em>?\nThey failed because the main computer was build by NASA and as usual in science they handled physical values in SI units (km, km/h, kg) while the lander engine was build by <em>General Electrics</em> aviation department where engineers traditionally use imperial units (miles, knots, pounds) Since they did not had units in their identifiers this problem could not be detected by code reviews or the engineers while coding.</p>\n\n<p>So even when not coding space mission control software you should consider adding units to variables (and method) dealing with physical values as the properties in your <code>Load</code> class do:</p>\n\n<pre><code>public double forceInNewton;\npublic double distanceFromMountInMeter;\npublic double loadLengthInMeter;\n</code></pre>\n\n<p>I'd even consider this being a valid reason to violate the <a href=\"https://www.oracle.com/technetwork/java/codeconventions-135099.html\" rel=\"nofollow noreferrer\">Naming Conventions</a> and write it like this:</p>\n\n<pre><code>public double force_N;\npublic double distanceFromMount_m;\npublic double loadLength_ft;\n</code></pre>\n\n<h2>code formatting</h2>\n\n<p>Put each instruction on a separate line.\nSo the method <code>addLoad</code> in class <code>Beam</code> should look like this:</p>\n\n<pre><code>public void addLoad(Load load) throws BeamError {\n if (load.x>=0 && load.x<=length && load.x+load.length<=length)\n stress.add(load);\n else \n throw new BeamError (\"Load not withing girder length!\",stress.size()+1);\n}\n</code></pre>\n\n<p>You may consider to use your IDEs *auto formatter\" feature to always have proper line breaks and indentation.</p>\n\n<h2>use private methods</h2>\n\n<p>The method <code>addLoad</code> in class <code>Beam</code> has some more readability issue. \nIt is not obvious what the condition is. \nSo it might be a good idea to move that into a method of its own:</p>\n\n<pre><code>private boolean isInside(Load load) throws BeamError {\n return load.x>=0 && load.x<=length && load.x+load.length<=length;\n}\n\npublic void addLoad(Load load) throws BeamError {\n if (isInside(load))\n stress.add(load);\n else \n throw new BeamError (\"Load not withing girder length!\",stress.size()+1);\n}\n</code></pre>\n\n<h2>separation of concerns (from readability point of view)</h2>\n\n<p>Being inside class <code>Beam</code> the line </p>\n\n<pre><code>if (isInside(load))\n</code></pre>\n\n<p>still reads a bit \"bumpy\", whereas </p>\n\n<pre><code>public void addLoad(Load load) throws BeamError {\n if (load.isInside(length_m))\n stress.add(load);\n else \n throw new BeamError (\"Load not withing girder length!\",stress.size()+1);\n}\n</code></pre>\n\n<p>is much more expressive (IMHO).</p>\n\n<p>This could be an indication that <code>isInside()</code> belongs to class <code>Load</code> rather than to class <code>Beam</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-28T21:58:51.707",
"Id": "406953",
"Score": "0",
"body": "Hi, thank you for your answer! Verry usefull and a warm welcome to the comunity :-) I updated my code accordingly."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-26T16:12:11.920",
"Id": "210367",
"ParentId": "210241",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T20:46:29.683",
"Id": "210241",
"Score": "2",
"Tags": [
"java",
"physics"
],
"Title": "Calculate supporting forces of a simply supported beam"
} | 210241 |
<p>This post is based on the <a href="https://en.wikipedia.org/wiki/Knapsack_problem#Definition" rel="nofollow noreferrer">0-1 Knapsack problem</a>. I came across this problem in <strong>Assignment #4</strong> of Professor Tim Roughgarden's course <em>Greedy Algorithms, Minimum Spanning Trees, and Dynamic Programming</em> on Coursera. </p>
<p><strong>Question 1:</strong></p>
<blockquote>
<p>In this programming problem and the next you'll code up the knapsack
algorithm from lecture.</p>
<p>Let's start with a warm-up. Download the text file below.</p>
<p><a href="https://d3c33hcgiwev3.cloudfront.net/_6dfda29c18c77fd14511ba8964c2e265_knapsack1.txt?Expires=1545696000&Signature=MBY14xIUphAPAB7Yfbk4jsI1uYGSYa3CeqazBVkIJC0KLQ4vSjT8C6MS-BLnay~eS7oVkaspGl70kcCaW2eDfhCVAvmaOTsNiEWJOVV-jkfL~v75E0lKHcf6fr2bEcGJ2-K5JrfY1H6ImlZN3XzTKAMhlEKrDXdp9nJx3WsJFZM_&Key-Pair-Id=APKAJLTNE6QMUY6HBC5A" rel="nofollow noreferrer">knapsack.txt</a></p>
<p>This file describes a knapsack instance, and it has the following
format:</p>
<p>[knapsack_size][number_of_items]</p>
<p>[value_1] [weight_1]</p>
<p>[value_2] [weight_2]</p>
<p>...</p>
<p>For example, the third line of the file is "50074 659", indicating
that the second item has value 50074 and size 659, respectively.</p>
<p>You can assume that all numbers are positive. You should assume that
item weights and the knapsack capacity are integers.</p>
<p>In the box below, type in the value of the optimal solution.</p>
</blockquote>
<p><strong>My program:</strong></p>
<pre><code>def knapSack(W , wt , val , n):
# Base Case
if n == 0 or W == 0 :
return 0
# If weight of the nth item is more than Knapsack of capacity
# W, then this item cannot be included in the optimal solution
if (wt[n-1] > W):
return knapSack(W , wt , val , n-1)
# Check for required value in lookup table first
if (lookup[n][W]!=-1):
return lookup[n][W]
# Add to lookup table and return the maximum of two cases:
# (1) nth item included
# (2) not included
else:
x = max(val[n-1] + knapSack(W-wt[n-1] , wt , val , n-1), knapSack(W , wt , val , n-1))
lookup[n][W] = x
return x
#End of function knapSack
#To test above function
val = []
wt = []
with open("knapsack.txt") as f:
first_line = f.readline().split()
W = int(first_line[0])
n = int(first_line[1])
for line in f:
words = line.split()
val.append(int(words[0]))
wt.append(int(words[1]))
lookup = [[-1 for i in range(W+1)] for j in range(n+1)]
print knapSack(W, wt, val, n)
</code></pre>
<p>This program gave me the output as 2493893, which matches with the official solution. So I presume that my code is correct. So far so good. The next question in the same assignment is as follows.</p>
<p><strong>Question 2:</strong></p>
<blockquote>
<p>This problem also asks you to solve a knapsack instance, but a much
bigger one.</p>
<p>Download the text file below.</p>
<p><a href="https://d3c33hcgiwev3.cloudfront.net/_6dfda29c18c77fd14511ba8964c2e265_knapsack_big.txt?Expires=1545696000&Signature=DzUrI7GKCMX-9MUJQo~hweafZElsQdMWF8XlKcKtzTZFSAPCjzOlj5b64usI~6JgEMMRn6p5meFsMKds3QsoNoEadTLd4XCL3w~6w7OkcKqzv5xzkqUSfa68phtWm1uZlJ2PaCV8sWHwGiM3Bxti1AIrHy7GZRzX9nwiGGpG3J0_&Key-Pair-Id=APKAJLTNE6QMUY6HBC5A" rel="nofollow noreferrer">knapsack_big.txt</a> </p>
<p>This file describes a knapsack instance, and it has the following
format:</p>
<p>[knapsack_size][number_of_items]</p>
<p>[value_1] [weight_1]</p>
<p>[value_2] [weight_2]</p>
<p>...</p>
<p>For example, the third line of the file is "50074 834558", indicating
that the second item has value 50074 and size 834558, respectively. As
before, you should assume that item weights and the knapsack capacity
are integers.</p>
<p>This instance is so big that the straightforward iterative
implemetation uses an infeasible amount of time and space. So you will
have to be creative to compute an optimal solution. One idea is to go
back to a recursive implementation, solving subproblems --- and, of
course, caching the results to avoid redundant work --- only on an "as
needed" basis. Also, be sure to think about appropriate data
structures for storing and looking up solutions to subproblems.</p>
<p>In the box below, type in the value of the optimal solution.</p>
</blockquote>
<p><strong>My program (same as before):</strong></p>
<pre><code>def knapSack(W , wt , val , n):
# Base Case
if n == 0 or W == 0 :
return 0
# If weight of the nth item is more than Knapsack of capacity
# W, then this item cannot be included in the optimal solution
if (wt[n-1] > W):
return knapSack(W , wt , val , n-1)
# Check for required value in lookup table first
if (lookup[n][W]!=-1):
return lookup[n][W]
# Add to lookup table and return the maximum of two cases:
# (1) nth item included
# (2) not included
else:
x = max(val[n-1] + knapSack(W-wt[n-1] , wt , val , n-1), knapSack(W , wt , val , n-1))
lookup[n][W] = x
return x
#End of function knapSack
#To test above function
val = []
wt = []
with open("knapsack_big.txt") as f:
first_line = f.readline().split()
W = int(first_line[0])
n = int(first_line[1])
for line in f:
words = line.split()
val.append(int(words[0]))
wt.append(int(words[1]))
lookup = [[-1 for i in range(W+1)] for j in range(n+1)]
print knapSack(W, wt, val, n)
</code></pre>
<p>The second question had mentioned that the ordinary iterative approach would not suffice and that we'd have to get back to the recursive approach and use appropriate caching. Fair enough. I had already used the recursive approach in my initial program and also implemented a lookup table for <a href="https://en.wikipedia.org/wiki/Memoization" rel="nofollow noreferrer">memoization</a> purposes. </p>
<p>It worked perfectly fine on the smaller data set i.e. <code>knapsack.txt</code> and took less than a second to execute. However, when I execute the program on the second file <code>knapsack_big.txt</code> (which is considerably larger than <code>knapsack.txt</code>) it takes forever to execute and in most cases ends up getting <a href="https://stackoverflow.com/questions/19189522/what-does-killed-mean">killed</a>.</p>
<p>So, any idea how to speed up the program so that it can be executed on larger data sets? I suspect that there might be more efficient data structures (than a simple 2D list) for this problem, but not sure which. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T01:07:02.940",
"Id": "406380",
"Score": "0",
"body": "I'd propose that, for posterity, you also include in-text the contents of `knapsack.txt` as it's relatively short."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T08:01:59.537",
"Id": "406395",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T08:07:43.833",
"Id": "406397",
"Score": "0",
"body": "For your speed-up problem, have you tried what happened if, instead of keeping a list `val` and `wt`, you keep a list of tuples containing `(val, wt)`? It appears you only use them for same-index values, so it might be faster on both the append and the look-up."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T08:17:29.590",
"Id": "406399",
"Score": "0",
"body": "@Mast Thanks, I will try that out but not sure if that will be a substantial improvement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T08:32:46.210",
"Id": "406401",
"Score": "1",
"body": "Neither am I, hence a comment instead of an answer, but I'd say it's worth a try. Something even more important you should try, is [profiling your code](https://codereview.meta.stackexchange.com/a/5284/52915) to see where the bottlenecks are. It takes some getting used to, but being able to profile is an essential skill in debugging performance."
}
] | [
{
"body": "<pre><code>def knapSack(W , wt , val , n): \n</code></pre>\n\n<p>This is not PEP8-compliant. You should run this code through a linter. For that particular line, it would instead be</p>\n\n<pre><code>def knapsack(W, wt, val, n):\n</code></pre>\n\n<p>You have several lines like this:</p>\n\n<pre><code>if (wt[n-1] > W):\n</code></pre>\n\n<p>with parens around the <code>if</code> condition. These parens are not needed.</p>\n\n<p>This:</p>\n\n<pre><code>print knapSack(W, wt, val, n) \n</code></pre>\n\n<p>uses Python 2-style <code>print</code>. In most cases, using Python 3-style <code>print</code> is compatible with Python 2, and this is such a case; so for forward compatibility you should instead write</p>\n\n<pre><code>print(knapSack(W, wt, val, n))\n</code></pre>\n\n<p>This:</p>\n\n<pre><code>if (lookup[n][W]!=-1):\n return lookup[n][W] \nelse: \n</code></pre>\n\n<p>doesn't need the <code>else</code>, since the previous block would have already returned.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T06:24:03.143",
"Id": "406386",
"Score": "1",
"body": "Thanks for the answer! This doesnโt address the speedup issue though (which is the main problem Iโm facing)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T03:59:03.323",
"Id": "210253",
"ParentId": "210242",
"Score": "2"
}
},
{
"body": "<p>This isn't an answer but more of an <a href=\"https://codereview.meta.stackexchange.com/a/1765\">update</a>. I ran the code through a linter - <a href=\"https://www.pylint.org/\" rel=\"nofollow noreferrer\">Pylint</a>, as suggested by <a href=\"https://codereview.stackexchange.com/a/210253/188780\">@Reinderien</a>. These are the current versions:</p>\n\n<hr>\n\n<pre><code>'''Programming Assignment #4: Question 1'''\ndef knapsack(max_weight, weights, values, max_value):\n '''Recursive method for the knapsack problem (with memoization)'''\n # Base Case\n if max_value == 0 or max_weight == 0:\n return 0\n # If weight of the nth item is more than Knapsack of capacity\n # W, then this item cannot be included in the optimal solution\n if weights[max_value-1] > max_weight:\n return knapsack(max_weight, weights, values, max_value-1)\n # Check for required value in lookup table first\n if LOOKUP[max_value][max_weight] != -1:\n return LOOKUP[max_value][max_weight]\n # Add to lookup table and return the maximum of two cases:\n # (1) nth item included\n # (2) not included\n val1 = knapsack(max_weight-WEIGHTS[max_value-1], weights, values, max_value-1)\n val1 += VALUES[max_value-1]\n # val1 stores the maximum possible profit when the last item is included\n val2 = knapsack(max_weight, weights, values, max_value-1)\n # val2 stores the maximum possible profit when the last item is excluded\n temp = max(val1, val2)\n LOOKUP[max_value][max_weight] = temp\n return temp\n#End of function knapsack\n#To test above function\nVALUES = []\nWEIGHTS = []\n#Reading the data file\nwith open(\"knapsack.txt\") as f:\n FIRST_LINE = f.readline().split()\n MAX_WEIGHT = int(FIRST_LINE[0])\n MAX_VALUE = int(FIRST_LINE[1])\n for line in f:\n words = line.split()\n VALUES.append(int(words[0]))\n WEIGHTS.append(int(words[1]))\n#Declaring and initializing the lookup table\nLOOKUP = [[-1 for i in range(MAX_WEIGHT+1)] for j in range(MAX_VALUE+1)]\n#Function knapsack is invoked\nprint knapsack(MAX_WEIGHT, WEIGHTS, VALUES, MAX_VALUE)\n</code></pre>\n\n<hr>\n\n<pre><code>'''Programming Assignment #4: Question 2'''\ndef knapsack(max_weight, weights, values, max_value):\n '''Recursive method for the knapsack problem (with memoization)'''\n # Base Case\n if max_value == 0 or max_weight == 0:\n return 0\n # If weight of the nth item is more than Knapsack of capacity\n # W, then this item cannot be included in the optimal solution\n if weights[max_value-1] > max_weight:\n return knapsack(max_weight, weights, values, max_value-1)\n # Check for required value in lookup table first\n if LOOKUP[max_value][max_weight] != -1:\n return LOOKUP[max_value][max_weight]\n # Add to lookup table and return the maximum of two cases:\n # (1) nth item included\n # (2) not included\n val1 = knapsack(max_weight-WEIGHTS[max_value-1], weights, values, max_value-1)\n val1 += VALUES[max_value-1]\n # val1 stores the maximum possible profit when the last item is included\n val2 = knapsack(max_weight, weights, values, max_value-1)\n # val2 stores the maximum possible profit when the last item is excluded\n temp = max(val1, val2)\n LOOKUP[max_value][max_weight] = temp\n return temp\n#End of function knapsack\n#To test above function\nVALUES = []\nWEIGHTS = []\n#Reading the data file\nwith open(\"knapsack_big.txt\") as f:\n FIRST_LINE = f.readline().split()\n MAX_WEIGHT = int(FIRST_LINE[0])\n MAX_VALUE = int(FIRST_LINE[1])\n for line in f:\n words = line.split()\n VALUES.append(int(words[0]))\n WEIGHTS.append(int(words[1]))\n#Declaring and initializing the lookup table\nLOOKUP = [[-1 for i in range(MAX_WEIGHT+1)] for j in range(MAX_VALUE+1)]\n#Function knapsack is invoked\nprint knapsack(MAX_WEIGHT, WEIGHTS, VALUES, MAX_VALUE)\n</code></pre>\n\n<hr>\n\n<p>The above programs should be fine syntactically now. They returned a 10/10 score on being run through Pylint. However, as mentioned in the original question, the code still gets killed whenever it is executed on large data files like <code>knapsack_big.txt</code>. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T14:51:39.907",
"Id": "406420",
"Score": "3",
"body": "Typically capitalized values are only seen on globals. I think the reason they appear in your program is that you have a bunch of global code. You should attempt to put all of your global-scope code into a `main` function; then pylint will probably change its suggestions to de-capitalize those variables."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T08:14:33.717",
"Id": "210262",
"ParentId": "210242",
"Score": "2"
}
},
{
"body": "<p>Not sure if the question is still relevant. But this line is creating a list that is too big that exceeds most memory limits:</p>\n<blockquote>\n<pre><code>LOOKUP = [[-1 for i in range(MAX_WEIGHT+1)] for j in range(MAX_VALUE+1)]\n</code></pre>\n</blockquote>\n<p>Instead of creating the <code>LOOKUP</code> table upfront, it may be better to save the sub-problems in a hash table or a search tree as you solve them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T07:10:13.990",
"Id": "524947",
"Score": "0",
"body": "Welcome to Code Review! Is this an observation about the code in [the answer by JD](https://codereview.stackexchange.com/a/210262/120114)? The main objective is to review the OPs code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T05:49:45.690",
"Id": "265757",
"ParentId": "210242",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "210253",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T21:11:03.730",
"Id": "210242",
"Score": "4",
"Tags": [
"python",
"recursion",
"time-limit-exceeded",
"memoization",
"knapsack-problem"
],
"Title": "Knapsack problem - recursive approach with memoization"
} | 210242 |
<p>Looking for a critique of this simple logger class I'm working on in my transition to TypeScript.</p>
<p>The purpose of the logging class is to just print to a console either info, warn or error messages.</p>
<p>The main things I'm after feedback on are my usage of the TypeScript type system. I.e interfaces/types/whatever else could be done different or better.</p>
<pre><code>interface LoggerConfig {
prefix?: string;
prefixColor?: TextColor.White;
displayConsole?: boolean;
outputExternal?: boolean;
}
type LogFn = (msg: string) => void;
interface Log {
config: LoggerConfig;
log: (msg: string, logColor: TextColor, override?: LoggerConfig) => void;
info: LogFn;
warn: LogFn;
error: LogFn;
}
class Logger implements Log {
config: LoggerConfig = {
prefix: 'console :: ',
prefixColor: TextColor.Green,
displayConsole: false,
outputExternal: false,
};
constructor(userConfig: LoggerConfig = {}) {
this.config = {...this.config, ...userConfig};
}
log(msg: string, logColor: TextColor, override?: LoggerConfig) {
const config = override ? {...this.config, ...override} : this.config;
const {displayConsole, outputExternal, prefix, prefixColor} = config;
if (displayConsole) {
showConsole();
}
if (outputExternal) {
external.printToConsole(`${prefix} ${msg}`);
}
print(prefixColor + prefix + logColor + ' ' + msg);
}
info(msg: string) {
this.log(msg, TextColor.White);
}
warn(msg: string) {
this.log(msg, TextColor.Yellow, {displayConsole: true});
}
error(msg: string) {
this.log(msg, TextColor.Red, {displayConsole: true, outputExternal: true});
}
}
const logger = new Logger({prefix: 'testLogger :: '})
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-31T04:06:59.717",
"Id": "407166",
"Score": "0",
"body": "It would help to see the definitions of `showConsole`, `external.printToConsole` and `print`. Right now it's difficult to say what the behavior of the logger will be."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T21:45:10.090",
"Id": "210243",
"Score": "2",
"Tags": [
"logging",
"typescript"
],
"Title": "Typescript logger class"
} | 210243 |
<p><strong>Problem statement</strong></p>
<p>I have entities whose relations form a graph. As an example, let's imagine <code>User</code>s and <code>Group</code>s. Each user has a <code>Set</code> of groups s*he belongs to; each <code>Group</code> has a <code>Set</code> of <code>User</code>s, representing its members. When constructing objects of those types, there is no clear hierachy. One could start by constructing a <code>Group</code> and add <code>User</code>s to the group, as well as start with constructing an <code>User</code> and add <code>Group</code>s to that user.</p>
<p>To ease construction, I want to have a fluent API for constructing those objects. Looking online, the most advanced solutions I have found assume a hieracical (i.e. tree-like) relation model, e.g.:</p>
<ul>
<li>An <code>Order</code> has <code>OrderItem</code>s</li>
<li><code>OrderItems</code> have an <code>OrderDescription</code></li>
<li>....</li>
</ul>
<p>Implementing this kind of fluent builder is easy enough, since an <code>OrderItemBuilder</code> always needs some kind of callback to an <code>Order</code>, and an Order always needs to have a <code>build()</code> method.</p>
<p>With the <code>User</code>-<code>Group</code>-example, the separation is not as clear. When starting construction a <code>User</code>-objects, a <code>build()</code>-method must be present. Starting a (recursive) <code>Group</code>-construction, the builder must not provide <code>build()</code>, but <code>and()</code> (or some other callback-method) instead. Here is an example usage:</p>
<pre><code>Group root = groupBuilder // may be injected through some means
.withName("root")
.withUser()
.name("John Doe")
.email("john@doe.com")
// must not compile:
// .build()
.and()
// must not compile:
//.and()
.build();
User jane = userBuilder // may be injected thorugh some means
.withName("Jane Doe")
.withGroup()
.name("default")
// must not compile:
// .build()
.and()
.withEmail("jane@doe.com")
// must not compile:
// .and()
.build()
</code></pre>
<p><strong>My solution</strong> </p>
<p>follows the following concept:</p>
<ul>
<li>One <code>UserBuilder</code> for "root"-consturction having a <code>User build()</code>-method, </li>
<li>One <code>UserBuilderNested</code>, if a <code>User</code> is constructed within the construction of another object, thus providing an <code>and()</code>-method, which internally calls some callback-function, passing the constructed user to the enclosing builder</li>
<li>both versions for the <code>Group</code>-object.</li>
</ul>
<p>To avoid <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself#DRY_vs_WET_solutions" rel="nofollow noreferrer">WET-programming</a>, I created two interfaces <code>UserBuilderCore</code> and <code>GroupBuilderCore</code>, containing only the <code>with...(...)</code> methods for the respective builder. <code>UserBuilder</code> and <code>UserBuilderNested</code> implement <code>UserBuilderCore</code>; <code>GroupBuilder</code> and <code>GroupBuilderNested</code> implement <code>GroupBuilderCore</code>. The code for <code>User</code> and its builders is shown at the end of the question, the code for <code>Group</code> and its builders is analogue. The whole code can be found on <a href="https://bitbucket.org/turing85/builderfun/src/master/" rel="nofollow noreferrer">bitbucket</a>.</p>
<p><strong>Pros</strong></p>
<ul>
<li>The interfaces are fully functional and type-safe.</li>
</ul>
<p><strong>Cons</strong></p>
<ul>
<li>For every relation in a class (e.g., lets assume each <code>User</code> gets an additional <code>Set<Post> posts</code> of written posts), one additional generic parameter has to be introduced. </li>
<li>As of now, <code>UserImpl</code> and <code>GroupImpl</code> are tightly coupled. I have not yet found a possibility to modify the generic parameters in such a way that I could e.g. inject some <code>UserBuilderNested</code> in <code>GroupImplBuilder</code>.</li>
<li>Furhtermore, adding a new <code>User</code>-implementation requires the correct generic wiring, as shown in the example implementation.</li>
</ul>
<p><strong>Request</strong></p>
<p>I am looking for ways to improve the code in the following way:</p>
<ul>
<li>Avoid adding additional generic parameters for new relationships (if possible).</li>
<li>Simplify the current design to allow easier extensability.</li>
<li>Decouple the <code>UserBuilder</code>- and <code>GroupBuilder</code>-implementations.</li>
<li>Any other remarks are of course welcome, but I know that the question is already pretty comprehensive. The points above are my main concern.</li>
</ul>
<p><strong>Remarks on the provided code</strong></p>
<p>The code is only a mockup, with no validation or referencial integrity measurements (e.g., when constructing a <code>Group</code> within a <code>User</code>, the <code>User</code> is not added to the constructed <code>Group</code>). This is on purpose.</p>
<p><strong>Source code</strong></p>
<p><code>User.java</code>:</p>
<pre><code>package com.turing.builder;
import java.util.Set;
public interface User {
String getName();
String getEmail();
Set<Group> getGroups();
void addGroup(Group group);
}
// UserBuilderCore.java
package com.turing.builder;
public interface UserBuilderCore< // @formatter:off
S extends UserBuilderCore<S, C>,
C extends GroupBuilderNested<C, ?, S>> { // @formatter:on
S withName(String name);
S withEmail(String email);
S withGroup(Group group);
C withGroup();
}
</code></pre>
<p><code>UserBuilder.java</code>:</p>
<pre><code>package com.turing.builder;
public interface UserBuilder< // @formatter:off
S extends UserBuilder<S, C>,
C extends GroupBuilderNested<C, ?, S>> // @formatter:on
extends UserBuilderCore<S, C> {
User build();
}
</code></pre>
<p><code>UserBuilderNested.java</code>:</p>
<pre><code>package com.turing.builder;
public interface UserBuilderNested< // @formatter:off
S extends UserBuilderNested<S, C, P>,
C extends GroupBuilderNested<C, ?, S>,
P extends GroupBuilderCore<P, ?>> // @formatter:on
extends UserBuilderCore<S, C> {
P and();
}
</code></pre>
<p><code>UserImpl.java</code>:</p>
<pre><code>package com.turing.builder.impl;
import com.turing.builder.Group;
import com.turing.builder.User;
import com.turing.builder.UserBuilder;
import com.turing.builder.UserBuilderCore;
import com.turing.builder.UserBuilderNested;
import com.turing.builder.impl.GroupImpl.GroupImplBuilderCore;
import com.turing.builder.impl.GroupImpl.GroupImplBuilderNested;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
public class UserImpl implements User {
private String name;
private String email;
private Set<Group> groups = new HashSet<>();
@Override
public String getName() {
return name;
}
private void setName(String name) {
this.name = name;
}
@Override
public String getEmail() {
return email;
}
private void setEmail(String email) {
this.email = email;
}
@Override
public Set<Group> getGroups() {
return groups;
}
private void setGroups(Set<Group> groups) {
this.groups = groups;
}
@Override
public void addGroup(Group group) {
this.groups.add(group);
}
@Override
public String toString() {
return String.format("User %s=%s",
getName(),
getGroups().stream()
.map(Group::getName)
.collect(Collectors.toList()));
}
protected abstract static class UserImplBuilderCore< // @formatter:off
S extends UserImplBuilderCore<S>>
implements UserBuilderCore<
/* S = */ S,
/* C = */ GroupImplBuilderNested<S>> { // @formatter:on
private UserImpl managed = new UserImpl();
@Override
@SuppressWarnings("unchecked")
public S withName(String name) {
managed.setName(name);
return ((S) this);
}
@Override
@SuppressWarnings("unchecked")
public S withEmail(String email) {
managed.setEmail(email);
return ((S) this);
}
@Override
@SuppressWarnings("unchecked")
public S withGroup(Group group) {
managed.addGroup(group);
return ((S) this);
}
@Override
public GroupImplBuilderNested<S> withGroup() {
return new GroupImplBuilderNested<>(this::withGroup);
}
protected User construct() {
User constructed = this.managed;
this.managed = new UserImpl();
return constructed;
}
}
public static class UserImplBuilder extends UserImplBuilderCore<UserImplBuilder>
implements UserBuilder< // @formatter:off
/* S = */ UserImplBuilder,
/* C = */ GroupImplBuilderNested<UserImplBuilder>> { // @formatter:on
public User build() {
return construct();
}
}
public static class UserImplBuilderNested<T extends GroupImplBuilderCore<T>>
extends UserImplBuilderCore<UserImplBuilderNested<T>>
implements UserBuilderNested< // @formatter:off
/* S = */ UserImplBuilderNested<T>,
/* C = */ GroupImplBuilderNested<UserImplBuilderNested<T>>,
/* P = */ T> { // @formatter:on
private final Function<User, T> callback;
public UserImplBuilderNested(Function<User, T> callback) {
this.callback = callback;
}
public T and() {
return callback.apply(construct());
}
}
}
</code></pre>
| [] | [
{
"body": "<p>Drop nested builders and use separate builders for each type of object to be created (<code>GroupBuilder</code>, <code>UserBuilder</code>, <code>WhateverBuilder</code>).</p>\n\n<p>Then you may use the builders like so:</p>\n\n<pre><code>Group root = GroupBuilder\n .withName(\"root\")\n .withUser(UserBuilder.\n .withName(\"John Doe\")\n .withEmail(\"john@doe.com\")\n // ...\n .build())\n .withUser(UserBuilder.\n .withName(\"Jane Doe\")\n .withEmail(\"jane@doe.com\")\n .build())\n .build();\n</code></pre>\n\n<p>This is easier to implement and probably easier to understand for users.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T23:28:50.857",
"Id": "406371",
"Score": "0",
"body": "I am aware of this solution and it is already implemented in my solution."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T22:50:42.730",
"Id": "210246",
"ParentId": "210244",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T21:47:33.673",
"Id": "210244",
"Score": "0",
"Tags": [
"java",
"generics",
"fluent-interface"
],
"Title": "Recursive fluent builder"
} | 210244 |
<p>I am trying to solve <a href="https://leetcode.com/problems/search-insert-position/" rel="nofollow noreferrer">this problem</a>:</p>
<blockquote>
<p>Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.</p>
</blockquote>
<p>and this is my implementation:</p>
<pre><code>public int searchInsert(int[] numbers, int target) {
int startIndex = 0;
int endIndex = numbers.length - 1;
int midIndex;
while (startIndex <= endIndex) {
midIndex = (endIndex - startIndex) / 2 + startIndex;
if(numbers[midIndex] == target)
return midIndex;
else {
if(numbers[midIndex] > target) {
if(midIndex <= 0 || numbers[midIndex - 1] < target) {
return midIndex;
}
endIndex = midIndex - 1;
}
else {
if(midIndex >= numbers.length - 1 || numbers[midIndex + 1] > target) {
return midIndex + 1;
}
startIndex = midIndex + 1;
}
}
}
return -1;
}
</code></pre>
<p>How can I make it more efficient?</p>
| [] | [
{
"body": "<p>In Java, the most efficient implementation of this will likely be </p>\n\n<pre><code>public int searchInsert(int[] numbers, int target) {\n int index = Arrays.binarySearch(numbers, target);\n\n if (index < 0) {\n index = -index - 1;\n }\n\n return index;\n}\n</code></pre>\n\n<p>With that said, the place where I'd look first are your special cases. Under what circumstances would <code>midIndex</code> be less than 0 or more than <code>numbers.length - 1</code>? Never (if it was, <code>numbers[midIndex]</code> would throw an out of bounds exception). And when will it be equal? When we've found the edge, when <code>endIndex</code> will be less than <code>startIndex</code>. </p>\n\n<p>So simplify </p>\n\n<pre><code> while (startIndex < endIndex) {\n midIndex = (endIndex - startIndex) / 2 + startIndex;\n if (numbers[midIndex] == target) {\n return midIndex;\n }\n\n if (numbers[midIndex] < target) {\n startIndex = midIndex + 1;\n }\n else {\n endIndex = midIndex - 1;\n }\n }\n\n return startIndex;\n</code></pre>\n\n<p>This will do one extra assignment and outer loop comparison but save two comparisons on every iteration. Since the assignment only involves registers and math, it should be quick (possibly quicker than the comparisons, which have to load the registers from cache if not memory). </p>\n\n<p>Without the extra checks, the code will update either <code>startIndex</code> or <code>endIndex</code> and make the same return. Because <code>startIndex</code> will equal either <code>midIndex</code> or <code>midIndex + 1</code>, the same as was returned in the original code. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T01:05:19.310",
"Id": "210252",
"ParentId": "210245",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "210252",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T22:14:30.327",
"Id": "210245",
"Score": "0",
"Tags": [
"java",
"performance",
"programming-challenge",
"binary-search"
],
"Title": "Search insert position"
} | 210245 |
<p>There is a Graph implementation. I'm using Set to store unique Edges and Map to store Vertices and their associated edges. Assume Vertex and Edge class has been defined somewhere else implementing hashcode() and equals() working fine. </p>
<pre><code>public class Graph
{
static class Vertex {}
static class Edge {}
private Map<Vertex, Set<Edge>> vertexSetMap;
private Set<Edge> edgeSet;
public Graph()
{
edgeSet = new LinkedHashSet<>();
vertexSetMap = new LinkedHashMap<>();
}
public boolean addVertex(Vertex vertex)
{
if(!vertexSetMap.containsKey(vertex))
{
vertexSetMap.put(vertex, new LinkedHashSet <>());
return true;
}
return false;
}
public boolean addEdge(Vertex v1, Vertex v2, Edge edge)
{
if(edgeSet.add(edge))
{
vertexSetMap.get(v1).add(edge);
vertexSetMap.get(v2).add(edge);
return true;
}
return false;
}
public Set<Edge> getEdges(Vertex vertex)
{
return vertexSetMap.get(vertex);
}
public Set<Vertex> getNeighborsOf(Vertex vertex)
{
Set<Vertex> neighbors = new LinkedHashSet <>();
for(Edge edge : vertexSetMap.get(vertex))
{
Vertex v1 = edge.getVertex1();
Vertex v2 = edge.getVertex2();
if(v1.equals(vertex)) neighbors.add(v2);
else neighbors.add(v1);
}
return neighbors;
}
public void removeVertex(Vertex vertex)
{
Set<Edge> deleteEdges = getEdges(vertex);
vertexSetMap.remove(vertex);
edgeSet.removeAll(deleteEdges);
vertexSetMap.keySet().forEach(vertex1 ->
vertexSetMap.get(vertex1).removeAll(deleteEdges));
}
public void removeEdge(Edge edge)
{
edgeSet.remove(edge);
Vertex v1 = edge.getVertex1();
Vertex v2 = edge.getVertex2();
vertexSetMap.get(v1).remove(edge);
vertexSetMap.get(v2).remove(edge);
}
public boolean containsVertex(Vertex vertex)
{
return vertexSetMap.containsKey(vertex);
}
public boolean containsEdge(Vertex v1, Vertex v2, Edge edge)
{
return (edgeSet.contains(edge) && vertexSetMap.get(v1).contains(edge)
&& vertexSetMap.get(v2).contains(edge));
}
public boolean containsEdge(Vertex v1, Vertex v2)
{
for(Edge e : vertexSetMap.get(v1))
if(vertexSetMap.get(v2).contains(e)) return true;
return false;
}
public int totalVertices()
{
return vertexSetMap.keySet().size();
}
public int totalEdges()
{
return edgeSet.size();
}
public Set<Vertex> getAllVertices()
{
return new LinkedHashSet <>(vertexSetMap.keySet());
}
public Set<Edge> getAllEdges()
{
return edgeSet;
}
public void clear()
{
edgeSet = null;
edgeSet = new LinkedHashSet <>();
vertexSetMap = null;
vertexSetMap = new LinkedHashMap <>();
}
}
</code></pre>
| [] | [
{
"body": "<p>As of now, you only use <code>LinkedHashSet</code> and <code>LinkedHashMap</code>, thus declaring <code>edgeSet</code> and <code>vertexMap</code> as <code>HashSet</code> and <code>HashMap</code> is pointless. You could deploy <a href=\"https://en.wikipedia.org/wiki/Inversion_of_control\" rel=\"nofollow noreferrer\">Inversion of Control</a> in order to demand some <code>Set</code> and <code>Map</code> at construction.</p>\n\n<hr>\n\n<p>Method <code>getEdges(...)</code> could possibly return <code>null</code>, so you may want to wrap the return value in an <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Optional.html\" rel=\"nofollow noreferrer\"><code>Optional</code></a>. Using <code>Optional</code>, you can also unify the behaviour of <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Map.html#get(java.lang.Object)\" rel=\"nofollow noreferrer\"><code>Map#get(Object)</code> (which may or may not throw a <code>NPE</code> if a <code>null</code> is passed as argument)</a>:</p>\n\n<pre><code>public Optional<Set<Edge>> getEdges(Vertex vertex)\n{\n Optional<Set<Edge>> result = Optional.empty();\n try \n {\n result = Optional.ofNullable(vertex);\n }\n catch (NullPointerException e)\n {\n // No action needed, we return an empty Optional\n }\n return result;\n}\n</code></pre>\n\n<hr>\n\n<p>Your <code>remove...(...)</code>-methods throw a <code>NPE</code> if the <code>Vertex</code>/<code>Edge</code> provided is not contained within the graph or is <code>null</code>. As with <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Map.html#get(java.lang.Object)\" rel=\"nofollow noreferrer\"><code>Map#get(Object)</code></a>, <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Set.html#remove(java.lang.Object)\" rel=\"nofollow noreferrer\"><code>Set#remove(Object)</code></a> may or may not throw a <code>NPE</code>. You can rewrite them to not throw:</p>\n\n<pre><code>public void removeVertex(Vertex vertex)\n{\n Optional<Set<Edge>> deleteEdges = getEdges(vertex);\n if (deleteEdges.isPresent())\n {\n vertexSetMap.remove(vertex);\n edgeSet.removeAll(deleteEdges.get());\n vertexSetMap.keySet().forEach(vertex1 ->\n vertexSetMap.get(vertex1).removeAll(deleteEdges.get()));\n }\n}\n\npublic void removeEdge(Edge edge)\n{\n try\n {\n if (edgeSet.remove(edge))\n {\n Vertex v1 = edge.getVertex1();\n Vertex v2 = edge.getVertex2();\n vertexSetMap.get(v1).remove(edge);\n vertexSetMap.get(v2).remove(edge);\n }\n }\n catch (NullPoionterException e)\n {\n // No action needed, there is nothing to remove.\n }\n}\n</code></pre>\n\n<hr>\n\n<p>When you add methods</p>\n\n<pre><code>public boolean containsVertex(Vertex vertex)\npublic boolean getOther(Vertex vertex)\n</code></pre>\n\n<p>To your <code>Edge</code>-class, you can rewrite <code>getNeighborsOf(...)</code> to use <code>Stream</code>s</p>\n\n<pre><code>public Set<Vertex> getNeighborsOf(Vertex vertex) {\n return vertexSetMap.get(vertex).stream()\n .filter(edge -> edge.contains(vertex))\n .map(edge -> edge.getOther(vertex))\n .collect(Collectors.toSet());\n}\n</code></pre>\n\n<hr>\n\n<p>What is missing is a <code>Set<Vertex> getVertices()</code> method (you have one for <code>Edge</code>s, so I would expect one for <code>Vertex</code>s as well). This would probably require creating an additional field <code>Set<Vertex> vertices</code> in your <code>Graph</code> class.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-01-23T13:51:34.383",
"Id": "410043",
"Score": "0",
"body": "Unless one needs to distinguish between an empty set and no set at all - which is not the case here - `Optional<Set<X>>` just adds an unnecessary level of complexity. Instead of returning `null` it would be better to have `getEdges` just return an empty set which can be done, for example, with: `return vertexSetMap.getOrDefault(vertex, Collections.emptySet());`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-18T10:22:34.810",
"Id": "461703",
"Score": "1",
"body": "What would be the benefit of IoC? A mere \"you could use\" is not helpful without any purpose."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-18T10:25:30.873",
"Id": "461704",
"Score": "1",
"body": "Applying your suggestions would bloat the code for no benefit. There are much cleaner ways that don't use `Optional`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-01-18T10:33:01.473",
"Id": "461707",
"Score": "1",
"body": "Regarding \"What is missing\", did you overlook `getAllVertices`?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T00:24:09.290",
"Id": "210250",
"ParentId": "210249",
"Score": "-1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-23T23:39:06.083",
"Id": "210249",
"Score": "2",
"Tags": [
"java",
"graph"
],
"Title": "Graph Implementation in Java using Set and Map"
} | 210249 |
<p>The program below is meant to find all of the fare prime numbers under a user specified value. A fare prime being a number that when its digits are rotated, each combination makes a prime number. An example being 113 because 113, 311, and 131 are all prime numbers. My current problem is that the program takes a very long time to process very large numbers so I need a way of making it run quicker. I've tried to explain the code with the comments but if any part doesn't make sense I'll do my best to explain. </p>
<pre><code>#get user input for the number range
n = int(input("number"))
primes = []
#find all the prime numbers up to the specified value and append them to a list
for num in range(2, n+1):
for i in range(2, num):
if num % i == 0:
break
else:
primes.append(num)
#find out if the prime number is a fare prime
for i in primes:
length = len(str(i))
#if the number has one digit it is automatically a fare prime
if length == 1:
print(i)
#if the number is longer, rotate the digits to see if it is a fare prime
if length >= 2:
number = i
fare_primes = []
#rotate the number to figure out if all combinations are prime
for j in range(length):
#turns # into a list of digits
digit_list = list(str(number))
#rearranges
number = [*digit_list[1::], digit_list[0]]
part = ""
#turns it back into an int value
number = part.join(number)
int_num = int(number)
#check if # is prime
for divider in range(2,int_num):
if int_num % divider == 0:
break
else:
fare_primes.append(number)
#if all combinations of the digits are prime the original # is printed
if len(fare_primes) == length:
print(fare_primes[-1])
</code></pre>
| [] | [
{
"body": "<p>A 2+ digit fare prime number can never have an even digit, or a 5 digit in its set of digits, because a rotation which moves an even digit or a 5 to the last digit will be divisible by 2 or 5. You could use that as a filter for your possible fare primes from the list of primes you calculate. </p>\n\n<p>When calculating primes, you can stop at <code>sqrt(num)</code>. Any number greater than <code>sqrt(num)</code> that evenly divides <code>num</code> will have a compliment number less than <code>sqrt(num)</code> that you have already tested. </p>\n\n<p>Speaking of primes that youโve calculated, why donโt you use those for your subsequent prime test? Why try dividing by every number from 2 up to <code>int_num</code> when you could just try the numbers in <code>primes</code> upto <code>int_num</code>.</p>\n\n<p>... or just ask if <code>int_num in primes</code>. Speed tip: turn <code>primes</code> into a <code>set()</code> first for faster inclusion testing.</p>\n\n<p>Your <code>digit_list</code> code is very inefficient. For any number, once youโve split the number into digits, you donโt need to resplit it into digits again for each rotation. Actually, you donโt even need to split it into individual digits. This will give you the rotated values:</p>\n\n<pre><code>digits = str(i)\nfor j in range(1, length):\n int_num = int( digits[j:] + digits[:j])\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T06:13:22.607",
"Id": "210256",
"ParentId": "210254",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "210256",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T04:31:10.353",
"Id": "210254",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"time-limit-exceeded",
"primes"
],
"Title": "Find primes that are also primes when its digits are rotated"
} | 210254 |
<p>UICollectionViewCell's content misbehaves ,
the layout animates,
when UICollectionView scrolls to the top of the screen.</p>
<p>I am asking here, because it looks like an apple's bug.</p>
<p>looks like squeezed in the following gif, the cell's label laid down.</p>
<p><a href="https://i.stack.imgur.com/rKlVq.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rKlVq.gif" alt="one"></a></p>
<p>I solved it by </p>
<pre><code>- (void)viewDidLoad {
[super viewDidLoad];
// comment the following line
// self.collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
</code></pre>
<p>I use <code>UIScrollViewContentInsetAdjustmentNever</code>, to avoid the collectionView's content insets. </p>
<p>Like the following image</p>
<p><a href="https://i.stack.imgur.com/9PSNR.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9PSNR.jpg" alt="two"></a></p>
<p>In order to keep both, I add one line <code>_collectionView.contentInset = UIEdgeInsetsMake(-20, 0, 0, 0);</code></p>
<p>Tested on iPhones: iPhone 7 ( 11.4.1 ), iPhone XS Max ( 12.1 )</p>
<p>Any other ideas?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T07:40:31.913",
"Id": "210260",
"Score": "1",
"Tags": [
"objective-c",
"ios",
"uikit"
],
"Title": "UICollectionViewCell's content layout misbehaves when UICollectionView scrolls to the top of the screen"
} | 210260 |
<p>I solved <a href="https://github.com/donnemartin/system-design-primer/blob/master/solutions/object_oriented_design/parking_lot/parking_lot.ipynb" rel="nofollow noreferrer">this</a> system design interview question. </p>
<p><strong>The problem description</strong></p>
<blockquote>
<p>Design a parking lot</p>
<p>Constraints and assumptions</p>
<ul>
<li>What types of vehicles should we support?
<ul>
<li>Motorcycle, Car, Bus</li>
</ul></li>
<li>Does each vehicle type take up a different amount of parking spots?
<ul>
<li>Yes</li>
<li>Motorcycle spot -> Motorcycle</li>
<li>Compact spot -> Motorcycle, Car</li>
<li>Large spot -> Motorcycle, Car</li>
<li>Bus can park if we have 5 consecutive "large" spots</li>
</ul></li>
<li>Does the parking lot have multiple levels?
<ul>
<li>Yes</li>
</ul></li>
</ul>
</blockquote>
<p>Operations I assumed and implemented for the ParkingLot.</p>
<ul>
<li><code>ParkVehicle</code> is when a person wants to park their vehicle in the spots they wish too. The spot chosen is assumed to be free always. </li>
<li><code>UnParkVechicle</code> is when a person want's to unpark their vehicle without having to explicitly mention the spot in which they parked. </li>
<li><code>GetOptimalParkingSpot</code> is when a person wishes to know which is the parking spot that is nearest to them for their vehicle. This implementation compares the spots by the floor, row and position they are on.</li>
<li><code>GetParkingSpotStatus</code> returns whether the requested parking spot range is occupied or vacant. </li>
<li><code>IParkingSpaceMapper.GetSmallestParkingSpaceRequired</code> returns the least required parking spots for a particular vehicle. </li>
</ul>
<p>Implementation Details. </p>
<ul>
<li>To make the solution more adaptable to future business rules I decided to represent the parking space required for each vehicle type as a continuous set of parking spots.</li>
<li>To keep track of the continuous set of parking spots and their types I used a sorted set to find a particular range of parking spots and also to merge with continuous ranges to it's left and right during freeing a particular range of parking spots. </li>
</ul>
<p><strong>The main interfaces</strong></p>
<pre><code>public interface IParkingLot
{
int FreeSpots { get; }
bool ParkVehicle(Vehicle vehicle, ParkingSpot parkingSpot);
bool UnParkvehicle(Vehicle vehicle);
ParkingSpot GetOptimalParkingSpot(Vehicle vehicle);
ParkingSpotStatus GetParkingSpotStatus(ParkingSpot spot);
}
public interface IParkingSpaceMapper
{
ParkingSpaceRequirment GetSmallestParkingSpaceRequired(Vehicle vehicle);
}
</code></pre>
<p><strong>Concrete Implementation of Interfaces (Business Logic)</strong></p>
<pre><code>public class ParkingLotCore : IParkingLot
{
private ImmutableSortedSet<ParkingSpot> freeParkingSpots;
private ConcurrentDictionary<string, ParkingSpot> parkedVehicles;
private readonly IEnumerable<List<List<ParkingSpot>>> parkingLotLayout;
private readonly IParkingSpaceMapper parkingSpaceMapper;
private int _freeSpots = 0;
public int FreeSpots => _freeSpots;
private int _totalSpots = 0;
public int TotalSpots => _totalSpots;
public ParkingLotCore(IEnumerable<List<List<ParkingSpot>>> parkingLotLayout, IParkingSpaceMapper parkingSpaceMapper)
{
var comparer = Comparer<ParkingSpot>.Create((x, y) =>
x.Floor == y.Floor ?
x.Row == y.Row ?
x.StartPosition.CompareTo(y.StartPosition)
: x.Row.CompareTo(y.Row)
: x.Floor.CompareTo(y.Floor)
);
freeParkingSpots = ImmutableSortedSet.Create<ParkingSpot>(comparer);
parkedVehicles = new ConcurrentDictionary<string, ParkingSpot>();
this.parkingLotLayout = parkingLotLayout;
this.parkingSpaceMapper = parkingSpaceMapper;
InitializeParkingLot();
}
private void InitializeParkingLot()
{
foreach (var floor in parkingLotLayout)
{
foreach (var row in floor)
{
foreach (var spot in row)
{
freeParkingSpots = freeParkingSpots.Add(spot);
Interlocked.Add(ref _totalSpots, spot.SpotCount);
Interlocked.Add(ref _freeSpots, spot.SpotCount);
}
}
}
}
public ParkingSpot GetOptimalParkingSpot(Vehicle vehicle)
{
ParkingSpaceRequirment requiredSpace = parkingSpaceMapper.GetSmallestParkingSpaceRequired(vehicle);
var vacantSpot = freeParkingSpots.FirstOrDefault(m => m.ParkingSpotTypes >= requiredSpace.ParkingSpot
&& m.SpotCount >= requiredSpace.ParkingSpotsCount
);
if (vacantSpot != null)
{
vacantSpot.SpotCount = Math.Min(vacantSpot.SpotCount, requiredSpace.ParkingSpotsCount);
}
return vacantSpot;
}
public bool ParkVehicle(Vehicle vehicle, ParkingSpot parkingSpot)
{
if (parkedVehicles.ContainsKey(vehicle.VehicleNumber))
{
throw new InvalidOperationException($"Vehicle with number {vehicle.VehicleNumber} is already parked");
}
ParkingSpot vacantSpot = freeParkingSpots.FirstOrDefault(spot => spot.Floor == parkingSpot.Floor
&& spot.Row == parkingSpot.Row
&& spot.ParkingSpotTypes == parkingSpot.ParkingSpotTypes
&& spot.StartPosition <= parkingSpot.StartPosition
&& spot.SpotCount >= parkingSpot.SpotCount
);
if (vacantSpot == null)
throw new KeyNotFoundException("The spot could not be found");
freeParkingSpots = freeParkingSpots.Remove(vacantSpot);
parkedVehicles.TryAdd(vehicle.VehicleNumber, parkingSpot);
if (parkingSpot.StartPosition > vacantSpot.StartPosition)
{
var newSpot = new ParkingSpot() { Floor = vacantSpot.Floor, ParkingSpotTypes = vacantSpot.ParkingSpotTypes, Row = vacantSpot.Row, StartPosition = vacantSpot.StartPosition};
newSpot.SpotCount = parkingSpot.StartPosition - vacantSpot.StartPosition;
freeParkingSpots = freeParkingSpots.Add(newSpot);
}
if (vacantSpot.SpotCount > parkingSpot.SpotCount)
{
var newSpot = new ParkingSpot() { Floor = vacantSpot.Floor, ParkingSpotTypes = vacantSpot.ParkingSpotTypes, Row = vacantSpot.Row};
newSpot.StartPosition = parkingSpot.StartPosition + parkingSpot.SpotCount;
newSpot.SpotCount = vacantSpot.SpotCount - newSpot.StartPosition + 1;
freeParkingSpots = freeParkingSpots.Add(newSpot);
}
Interlocked.Add(ref _freeSpots, parkingSpot.SpotCount * -1);
return true;
}
public bool UnParkvehicle(Vehicle vehicle)
{
parkedVehicles.TryRemove(vehicle.VehicleNumber, out ParkingSpot currentSpot);
if (currentSpot == null)
throw new ArgumentException($"vehicle {vehicle.VehicleNumber} is not parked");
var leftSpot = freeParkingSpots.FirstOrDefault(spot => spot.Floor == currentSpot.Floor
&& spot.Row == currentSpot.Row
&& spot.ParkingSpotTypes == currentSpot.ParkingSpotTypes
&& spot.StartPosition + spot.SpotCount == currentSpot.StartPosition
);
ParkingSpot newSpotToUpdate = new ParkingSpot() { Floor = currentSpot.Floor, ParkingSpotTypes = currentSpot.ParkingSpotTypes, Row = currentSpot.Row, StartPosition = currentSpot.StartPosition, SpotCount = currentSpot.SpotCount };
if (leftSpot != null)
{
newSpotToUpdate.StartPosition = leftSpot.StartPosition;
newSpotToUpdate.SpotCount = currentSpot.SpotCount + leftSpot.SpotCount;
freeParkingSpots = freeParkingSpots.Remove(leftSpot);
}
var rightSpot = freeParkingSpots.FirstOrDefault(spot => spot.Floor == currentSpot.Floor
&& spot.Row == currentSpot.Row
&& spot.ParkingSpotTypes == currentSpot.ParkingSpotTypes
&& spot.StartPosition == currentSpot.StartPosition + currentSpot.SpotCount
);
if (rightSpot != null)
{
newSpotToUpdate.SpotCount = newSpotToUpdate.SpotCount + rightSpot.SpotCount;
freeParkingSpots = freeParkingSpots.Remove(rightSpot);
}
freeParkingSpots = freeParkingSpots.Add(newSpotToUpdate);
return true;
}
public ParkingSpotStatus GetParkingSpotStatus(ParkingSpot parkingSpot)
{
var rightSpot = freeParkingSpots.FirstOrDefault(spot => spot.Floor == parkingSpot.Floor
&& spot.Row == parkingSpot.Row
&& spot.ParkingSpotTypes == parkingSpot.ParkingSpotTypes
&& spot.StartPosition <= parkingSpot.StartPosition
&& spot.StartPosition + spot.SpotCount >= parkingSpot.SpotCount + parkingSpot.StartPosition
);
if (rightSpot != null)
{
return ParkingSpotStatus.Vacant;
}
return ParkingSpotStatus.Occupied;
}
}
public class ParkingSpaceMapper : IParkingSpaceMapper
{
public ParkingSpaceRequirment GetSmallestParkingSpaceRequired(Vehicle vehicle)
{
switch (vehicle.vehicleType)
{
case VehicleTypes.MotorCycle:
return new ParkingSpaceRequirment() { ParkingSpot = ParkingSpotTypes.Motorcycle, ParkingSpotsCount = 1 };
case VehicleTypes.Car:
return new ParkingSpaceRequirment() { ParkingSpot = ParkingSpotTypes.Compact, ParkingSpotsCount = 1 };
case VehicleTypes.Bus:
return new ParkingSpaceRequirment() { ParkingSpot = ParkingSpotTypes.Large, ParkingSpotsCount = 5 };
default:
throw new ArgumentException($"vehicleType {vehicle.vehicleType} is invalid.");
}
}
}
</code></pre>
<p><strong>The enum's used</strong> </p>
<pre><code>public enum ParkingSpotStatus
{
Occupied = 0,
Vacant = 1
}
public enum ParkingSpotTypes
{
Motorcycle = 0,
Compact = 1,
Large = 2
}
public enum VehicleTypes
{
MotorCycle = 0,
Car = 1,
Bus = 2
}
</code></pre>
<p><strong>The data transfer objects used</strong> </p>
<pre><code>public class ParkingLotStatus
{
public int TotalParkingSpots { get; set; }
public int OccupiedSpots { get; set; }
public int FreeSpots { get; set; }
}
public class ParkingSpaceRequirment
{
public ParkingSpotTypes ParkingSpot { get; set; }
public int ParkingSpotsCount { get; set; }
}
public class ParkingSpot
{
public int Floor { get; set; }
public int Row { get; set; }
public int StartPosition { get; set; }
public int SpotCount { get; set; }
public ParkingSpotTypes ParkingSpotTypes { get; set; }
}
public class Vehicle
{
public string VehicleNumber { get; set; }
public VehicleTypes vehicleType { get; set; }
}
</code></pre>
<p>The code along with the unit tests are available at GitHub to make it easier to read. <a href="https://github.com/benneyman/oop-parkingLot" rel="nofollow noreferrer">https://github.com/benneyman/oop-parkingLot</a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-25T02:39:55.387",
"Id": "406464",
"Score": "1",
"body": "Other than the constraints and assumptions that you listed, was the only instruction \"Design a parking lot\"? That seems rather vague; I would expect to be told something about the kind of operations that need to be done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-25T02:41:56.190",
"Id": "406465",
"Score": "0",
"body": "@blackwood yes you're right. I pretty much had to think of the operations that would be expected of a parking lot. I'll edit those into the descriptions as well."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T07:46:34.697",
"Id": "210261",
"Score": "4",
"Tags": [
"c#",
"algorithm",
"object-oriented",
"programming-challenge"
],
"Title": "Design an object oriented parking lot"
} | 210261 |
<p>This is my first attempt at python game in pygame. It's a maze game where the maze is randomly generated using Prim's Algorithm.</p>
<pre><code>import pygame
import random
import time
pygame.init()
# all fonts used
font1 = pygame.font.SysFont("comicsansms", 49, True)
font2 = pygame.font.SysFont("comicsansms", 150, True)
font3 = pygame.font.SysFont("comicsansms", 28, True)
# creates the string that displays time
def get_time(hours,minutes,seconds):
if len(str(hours)) > 1:
a = str(hours)
else:
a = "0" + str(hours)
if len(str(minutes)) > 1:
b = str(minutes)
else:
b = "0" + str(minutes)
if len(str(seconds)) > 1:
c = str(seconds)
else:
c = "0" + str(seconds)
return a + ":" + b + ":" + c
# creates the time counter
def draw_time(start_time,pause_time):
hours = 0
minutes = 0
seconds = 0
current_time = time.time() - pause_time - start_time
if current_time > 3600:
while True:
if current_time - 3600 > 0:
hours += 1
current_time -= 3600
else:
while True:
if current_time - 60 > 0:
minutes += 1
current_time -= 60
else:
seconds += int(current_time)
break
break
else:
while True:
if current_time - 60 > 0:
minutes += 1
current_time -= 60
else:
seconds += int(current_time)
break
return [font1.render(get_time(hours, minutes, seconds), True, (0, 0, 0), (255, 255, 255)), get_time(hours, minutes, seconds)]
class cell:
def __init__(self,up,down,left,right):
self.visited = False
self.walls = [up,down,left,right]
class labyrinth:
# generates the maze
def __init__(self,id):
self.id = id
self.walls = []
self.maze_walls = []
self.cells = []
x = 0
t = 0
# creates all cell within the maze
for f in range(22):
for s in range(28):
# if command makes sure no cellls are created where the clock is supposed to be
if not (f in (0,1,2) and s > 20):
self.cells.append(cell((x + 8, t, 25, 8), (x + 8, t + 33, 25, 8), (x, t + 8, 8, 25), (x + 33, t + 8, 8, 25)))
x += 33
x = 0
t += 33
# generates maze using prim's algorithm
for v in self.cells[0].walls:
self.maze_walls.append(v)
self.walls.append(v)
self.cells[0].visited = True
while len(self.walls) > 0:
wall = random.choice(self.walls)
# checks which cells are divided by the wall
divided_cells = []
for u in self.cells:
if wall in u.walls:
divided_cells.append(u)
if len(divided_cells) > 1 and (not ((divided_cells[0].visited and divided_cells[1].visited) or ((not divided_cells[0].visited) and (not divided_cells[1].visited)))):
# checks which cells have been visited
for k in divided_cells:
k.walls.remove(wall)
if k.visited == False:
k.visited = True
for q in k.walls:
if not q in self.walls:
self.walls.append(q)
if not q in self.maze_walls:
self.maze_walls.append(q)
if wall in self.maze_walls:
self.maze_walls.remove(wall)
self.walls.remove(wall)
for j in range(0,736,33):
for i in range(0,951,33):
self.maze_walls.append((i, j, 8, 8))
# draws the maze
def draw(self, goal):
screen.fill((0, 0, 0))
for k in self.maze_walls:
pygame.draw.rect(screen, color, pygame.Rect(k[0],k[1],k[2],k[3]))
pygame.draw.rect(screen, color, pygame.Rect(695, 0, 300, 105)) # clock background
pygame.draw.rect(screen, (0, 255, 0), goal) # finish
id = 0
running = True
while running:
screen = pygame.display.set_mode((930, 733))
done = False
color = (0, 128, 255) # color of the walls
x = 16
y = 16
clock = pygame.time.Clock()
start = time.time()
id += 1
maze = labyrinth(id)
goal = pygame.Rect(899,701,25,25)
victory = False
speed = 4 # movement speed
pause = False
pause_time = 0 # time spent in pause menue
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE or event.key == pygame.K_p:
if pause:
pause = False
pause_time += time.time() - pause_time_start
else:
pause = True
pause_time_start = time.time()
if event.key == pygame.K_RETURN:
done = True
if pause:
screen.fill((0, 0, 0))
pause_text = font2.render("PAUSE",True,(255,255,255))
screen.blit(pause_text, (468 - (pause_text.get_width() // 2), 368 - (pause_text.get_height() // 2)))
# the actual game
if not victory and not pause:
move_up = True
move_down = True
move_left = True
move_right = True
pressed = pygame.key.get_pressed()
# movment
if pressed[pygame.K_w] or pressed[pygame.K_UP]:
# checks if their is a overlap with the wall
for m in maze.maze_walls:
player = pygame.Rect(x, y - speed, 10, 10)
if player.colliderect(pygame.Rect(m[0],m[1],m[2],m[3])):
move_up = False
break
if move_up:
y -= speed
if pressed[pygame.K_s] or pressed[pygame.K_DOWN]:
player = pygame.Rect(x, y + speed, 10, 10)
for m in maze.maze_walls:
if player.colliderect(pygame.Rect(m[0],m[1],m[2],m[3])):
move_down = False
break
if move_down:
y += speed
if pressed[pygame.K_a] or pressed[pygame.K_LEFT]:
player = pygame.Rect(x - speed, y, 10, 10)
for m in maze.maze_walls:
if player.colliderect(pygame.Rect(m[0],m[1],m[2],m[3])):
move_left = False
break
if move_left:
x -= speed
if pressed[pygame.K_d] or pressed[pygame.K_RIGHT]:
player = pygame.Rect(x + speed, y, 10, 10)
for m in maze.maze_walls:
if player.colliderect(pygame.Rect(m[0],m[1],m[2],m[3])):
move_right = False
break
if move_right:
x += speed
# checks if player has reached the goal
if goal.colliderect((x, y, 10, 10)):
victory = True
# draws the screen
maze.draw(goal)
text = draw_time(start, pause_time)
pygame.draw.rect(screen, (255, 100, 0), pygame.Rect(x,y,10,10))
screen.blit(text[0], (700, 15))
# victory screen
if victory:
screen.fill((0, 0, 0))
time_text = font1.render("Time Taken: " + text[1],True,(255,255,255))
victory_text = font2.render("VICTORY!",True,(255,255,255))
reset = font3.render("(Press Enter to Start New Game)",True,(255,255,255))
screen.blit(victory_text,(468 - (victory_text.get_width() // 2), 328 - (victory_text.get_height() // 2)))
screen.blit(time_text, (468 - (time_text.get_width() // 2), (248 - (time_text.get_height() // 2)) + victory_text.get_height()))
screen.blit(reset, (468 - (reset.get_width() // 2), (248 - (reset.get_height() // 2)) + victory_text.get_height() + time_text.get_height()))
clock.tick(60)
pygame.display.flip()
</code></pre>
| [] | [
{
"body": "<h2>Time Handling</h2>\n\n<p>Most of your time handling code needs to be rewritten. Read more about time in Python here:</p>\n\n<p><a href=\"https://docs.python.org/3/library/time.html\" rel=\"nofollow noreferrer\">https://docs.python.org/3/library/time.html</a></p>\n\n<p><a href=\"https://docs.python.org/3/library/datetime.html\" rel=\"nofollow noreferrer\">https://docs.python.org/3/library/datetime.html</a></p>\n\n<p>Specifically,</p>\n\n<ul>\n<li>The entire <code>get_time</code> method needs to be replaced with a call to <code>strftime</code></li>\n<li>Stop passing around hours, minutes and seconds separately. Just pass around a <code>datetime.time</code>.</li>\n<li>Most of your <code>draw_time</code> method needs to go away. Keep the call to <code>render</code>, but the call to <code>get_time</code> should be replaced with a call to <code>strftime</code>.</li>\n</ul>\n\n<h2>Formatting</h2>\n\n<p>Your code is not PEP8-compliant. In particular, your class names need to be capitalized. Running your code through a linter will help this.</p>\n\n<h2>Magic numbers</h2>\n\n<p>What do 22, 28, 736, 695, 930, etc. mean? These need to be replaced with constant variables. Where possible, calculate them from other constants.</p>\n\n<h2>DRY (don't repeat yourself)</h2>\n\n<p>This block:</p>\n\n<pre><code> if pressed[pygame.K_w] or pressed[pygame.K_UP]:\n # checks if their is a overlap with the wall\n for m in maze.maze_walls:\n player = pygame.Rect(x, y - speed, 10, 10)\n if player.colliderect(pygame.Rect(m[0],m[1],m[2],m[3])):\n move_up = False\n break\n if move_up:\n y -= speed\n</code></pre>\n\n<p>is repeated four times with very little modification. Consider moving it to a function, and accepting arguments for anything that varies (the two key values, and a 2-tuple of ints to add to the coordinates).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T15:33:59.410",
"Id": "210273",
"ParentId": "210265",
"Score": "1"
}
},
{
"body": "\n\n<ul>\n<li>One of your goals should be to avoid repetitive code. This is called the <a href=\"https://en.wikipedia.org/wiki/Don't_repeat_yourself\" rel=\"nofollow noreferrer\">DRY principle</a>. If you have identical code (e.g. functions that call almost the same parameters, blocks of code that are almost identical except for one word), the repetition can almost certainly be reduced by creating more functions or looking into other structures.</li>\n<li><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> is the style guide that Python programmers commonly use. It makes your code easier for others to read, and also helps you to define standardized interfaces whose calling conventions will be easy to remember. I reading through it and starting to learn the conventions. There also automated checkers that you can run your code through to point out improvements to you: I use <a href=\"https://www.pylint.org/\" rel=\"nofollow noreferrer\"><code>pylint</code></a> for this. There's one thing I immediately notice in your code that does not follow PEP 8:\n\n<ul>\n<li>Classes should be named following the <code>CapWords</code> convention (<a href=\"https://www.python.org/dev/peps/pep-0008/#class-names\" rel=\"nofollow noreferrer\">source</a>):\n\n<ul>\n<li><code>labyrinth</code> should be <code>Labyrinth</code></li>\n</ul></li>\n</ul></li>\n<li>When creating strings that have a pattern <a href=\"https://docs.python.org/library/string.html#format-string-syntax\" rel=\"nofollow noreferrer\"><code>str.format()</code></a> and <a href=\"https://docs.python.org/reference/lexical_analysis.html#formatted-string-literals\" rel=\"nofollow noreferrer\">formatted string literals</a> come in handy.</li>\n</ul>\n\n<h2>There are easier ways to format strings</h2>\n\n<p>Take this function:</p>\n\n<pre><code>def get_time(hours,minutes,seconds):\n if len(str(hours)) > 1:\n a = str(hours)\n else:\n a = \"0\" + str(hours)\n\n if len(str(minutes)) > 1:\n b = str(minutes)\n else:\n b = \"0\" + str(minutes)\n\n if len(str(seconds)) > 1:\n c = str(seconds)\n else:\n c = \"0\" + str(seconds)\n\n return a + \":\" + b + \":\" + c\n</code></pre>\n\n<p>The three conditionals are not necessary; Python already has three ways to pad strings to two digits. My personal favorite is formatted string literals. Instead of: </p>\n\n<pre><code> if len(str(hours)) > 1:\n a = str(hours)\n else:\n a = \"0\" + str(hours)\n</code></pre>\n\n<p>You can just do:</p>\n\n<pre><code> a = f\"{a:0>2}\"\n</code></pre>\n\n<p>Here's how it works (see <a href=\"https://docs.python.org/library/string.html#format-specification-mini-language\" rel=\"nofollow noreferrer\">here</a> for more details):</p>\n\n<pre><code>f string prefix thats starts a formatted string literal\n \"\n { starts a variable reference\n a variable name\n : start formatting section\n 0 padding character\n > right align\n 2 number of characters to pad to\n } end variable reference\n \"\n</code></pre>\n\n<p>And from there you could do:</p>\n\n<pre><code>def get_time(hours,minutes,seconds):\n return \":\".join(f\"{part:0>2}\" for part in [a, b, c])\n</code></pre>\n\n<p>But as @Reinderien mentions, it's better to use <code>strftime</code> here. I also recommend reading his answer for more suggestions.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T15:55:21.957",
"Id": "210274",
"ParentId": "210265",
"Score": "0"
}
},
{
"body": "<p><code>get_time</code> has a fair amount of repetition. I'd move the \"padding\" check to a new function, and just map it over a list holding the three pieces of time data:</p>\n\n<pre><code>def zero_pad_format(n):\n if n < 10:\n return \"0\" + str(n)\n else:\n return str(n)\n\ndef get_time(hours, minutes, seconds):\n padded = [zero_pad_format(t) for t in [hours, minutes, seconds]]\n\n return \":\".join(padded)\n\n>>> get_time(5, 7, 43)\n'05:07:43'\n</code></pre>\n\n<p>Really, it's unnecessary to turn the number into a string just to check if it needs to be padded. If the stringified number has a string length of greater than 1, that also means it's <code>>= 10</code>. You can just check if the number is less than or equal to 9 to see if you should pad it. That's what I'm doing in the first function. Instead of writing the same code three times, I moved it to its own function so the single function can be used three times.</p>\n\n<pre><code>padded = [zero_pad_format(t) for t in [hours, minutes, seconds]]\n</code></pre>\n\n<p>This puts the three time data into a list, and maps <code>zero_pad_format</code> over it, and returns a list <code>padded</code> containing the padded data. The line below it </p>\n\n<pre><code>return \":\".join(padded)\n</code></pre>\n\n<p>Takes the padded data, and \"joins\" the data together with <code>\":\"</code>. I recommend getting very familiar with <code>join</code>. It's a very useful function.</p>\n\n<hr>\n\n<p>The looping bit at the top of <code>draw_time</code> to get hours, minutes, and seconds from a raw seconds number is quite messy and inefficient. You're looping where straight math can be used:</p>\n\n<pre><code>def time_from_seconds(elapsed_seconds):\n current_time = elapsed_seconds\n\n hours = current_time // 3600\n current_time -= 3600 * hours\n\n minutes = current_time // 60\n current_time -= 60 * minutes\n\n return hours, minutes, current_time\n\n>>> time_from_seconds(5000)\n(1, 23, 20)\n\n>>> time_from_seconds(5001)\n(1, 23, 21)\n\n>>> time_from_seconds(3600)\n(1, 0, 0)\n\n>>> time_from_seconds(1234567890) 3 How long would this take if using loops?\n(342935, 31, 30)\n</code></pre>\n\n<p>Use division to figure out how many hours you can get out of the <code>current_time</code>, store the number in <code>hours</code>, then multiply that by 3600 to figure how much needs to be subtracted from <code>current_time</code>. Then you do the same for minutes.</p>\n\n<p>There's some repetition here that could be ironically be solved by using some loops, but I feel that wouldn't be quite as clear.</p>\n\n<p>That gets rid of the majority of the code in <code>draw_time</code> though, which is a hint that that code shouldn't have been directly in <code>draw_time</code> in the first place. That chunk of code has nothing to do with drawing the time. It's just figuring out what to draw. You might want a set-up closer to this:</p>\n\n<pre><code>def draw_time(hours, minutes, seconds):\n return (font1.render(get_time(hours, minutes, seconds),\n True,\n (0, 0, 0), (255, 255, 255)),\n get_time(hours, minutes, seconds))\n\n# An awful name, and this still isn't an ideal setup. It's mildy better though.\ndef draw_time_from_start_pause(start_time, pause_time):\n current_time = time.time() - pause_time - start_time\n\n h, m, s = time_from_seconds(current_time)\n return draw_time(h, m, s)\n\n # or\n\n #data = time_from_seconds(current_time)\n #return draw_time(*data) # Spread the data into the arguments\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-25T02:06:57.507",
"Id": "210294",
"ParentId": "210265",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "210274",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T09:38:31.893",
"Id": "210265",
"Score": "2",
"Tags": [
"python",
"beginner",
"algorithm",
"python-3.x",
"pygame"
],
"Title": "Pygame maze game"
} | 210265 |
<p>A 'slow sort' is probably the slowest practical sort. It compares each element with the elements after it, and swaps immediately if one is greater than the other, and goes back to the start of the array.</p>
<p>For example:</p>
<blockquote>
<p>CBAD -> BCAD -> ACBD -> ABCD</p>
</blockquote>
<p>My code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function go() {
var arrLen=Math.floor(Math.random()*20)+30;
var arr=Array.from({length:arrLen}).map(()=>Math.floor(Math.random()*20)); // make random array
txtIn.textContent=arr; //display
//txtOut1.textContent=arr.sort(function(a,b) {return -(a<b);}); // native sort
txtOut1.textContent=arr.sort((a,b)=>a-b); // native sort
var srcPos=0,dstPos,tmp; // declare variables
while (srcPos<arrLen-1) {
dstPos=srcPos+1;
while (dstPos<arrLen) { // three swap routines
if (arr[srcPos]>arr[dstPos]) {tmp=arr[srcPos];arr[srcPos]=arr[dstPos];arr[dstPos]=tmp;srcPos=0;break}
//if (arr[srcPos]>arr[dstPos]) {arr[srcPos]^=arr[dstPos];arr[dstPos]^=arr[srcPos];arr[srcPos]^=arr[dstPos];srcPos=0;break}
//if (arr[srcPos]>arr[dstPos]) {arr[srcPos]+=arr[dstPos];arr[dstPos]=arr[srcPos]-arr[srcPos];arr[srcPos]+=arr[dstPos];srcPos=0;break}
srcPos++;
dstPos++;
}
}
txtOut2.textContent=arr; //display
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><span id='txtIn' style='display:overflow; width:200px; border:2px grey solid'></span><label>data</label><br>
<span id='txtOut1' style='display:overflow; width:200px; border:2px red solid'></span><label>native sort</label><br>
<span id='txtOut2' style='display:overflow; width:200px; border:2px red solid'></span><label>slowsort</label><br>
<button onclick='go();'>go</button></code></pre>
</div>
</div>
</p>
<p>I have included three swap types, tmp, XOR and add, and commented out two of them. The native sort includes a EMCA2015 arrow function version.</p>
<p>It seems to work okay - admittedly I haven't tested it for other data types, but any feedback would be appreciated.</p>
| [] | [
{
"body": "<p>There are a few terms one can use to grade code. <strong>Correctness</strong>, <strong>efficiency</strong>, <strong>readabilty</strong>, <strong>reuse</strong> <strong>testability</strong> and few other <em>objectively</em> measurable metrics come to mind.</p>\n\n<p>Efficiency isn't really a concern here, and due to the simplicity of the algorithm, neither is correctness. However, it was hard to check whether the code is correct because it's nearly not readable. Also, it's not reusable, at all, as the sorting method is embedded inline and therefore not testable.</p>\n\n<p>With this small overview in mind, let's review the code in detail.</p>\n\n<h1>Correctness</h1>\n\n<p>The outer <code>while</code> loop will only exit when <code>srcPos == arrLen - 1</code>. This may only happen if <code>srcPos</code> does not get set to <code>0</code>, which again only happens if two elements weren't in order. Therefore when we have <code>srcPos == arrLen - 1</code>, all elements where lesser or equal to their predecessors and the array is sorted.</p>\n\n<h1>Efficiency</h1>\n\n<p>This was an inverse goal. While it's already slow, I accidentally misread the code (see the next section) and read:</p>\n\n<pre><code>...\n var srcPos=0,dstPos,tmp; // declare variables\n while (srcPos<arrLen-1) {\n dstPos=srcPos+1;\n while (dstPos<arrLen) { // three swap routines\n if (arr[srcPos]>arr[dstPos]) {tmp=arr[srcPos];arr[srcPos]=arr[dstPos];arr[dstPos]=tmp;srcPos=0;break}\n //if (arr[srcPos]>arr[dstPos]) {arr[srcPos]^=arr[dstPos];arr[dstPos]^=arr[srcPos];arr[srcPos]^=arr[dstPos];srcPos=0;break}\n //if (arr[srcPos]>arr[dstPos]) {arr[srcPos]+=arr[dstPos];arr[dstPos]=arr[srcPos]-arr[srcPos];arr[srcPos]+=arr[dstPos];srcPos=0;break}\n\n dstPos++;\n }\n srcPos++; // whoops!\n }\n ...\n</code></pre>\n\n<p>That's even worse, since we end up with a lot of unnecessary comparisons. See \"But this can be made worse\" below.</p>\n\n<h2>It's already slow...</h2>\n\n<p>Your code restarts for every inversion and end up with <span class=\"math-container\">\\$\\mathcal O(n^3)\\$</span>. That's already bad, but you can do worse.</p>\n\n<h2>But this can be made worse</h2>\n\n<p>Just increase <code>src</code> <strong>only</strong> in the outer <code>while</code>. Here's the analysis for the case:\nThe worst runtime we can get is for an inverse array, e.g. <code>[5,4,3,2,1]</code>:</p>\n\n<pre><code>[5,4,3,2,1]\n[4,5,3,2,1]\n[3,5,4,2,1]\n[2,5,4,3,1]\n[1,5,4,3,2]\n...\n</code></pre>\n\n<p>For <span class=\"math-container\">\\$n\\$</span> elements, we need <span class=\"math-container\">\\$1\\$</span> comparison to move the largest element to the second position, <span class=\"math-container\">\\$2\\$</span> elements to move the second largest to the third, and so on. In summary, we have <span class=\"math-container\">$$1 + 2 + \\ldots + (n-2) + (n - 1) = \\frac{n(n-1)}{2}$$</span> comparisons to get the smallest value to the front. However, contrary to bubble sort, we always reset <code>srcPos</code> to zero. Therefore, the second smallest value won't take less time to get to the front:</p>\n\n<pre><code>[1,4,5,3,2] -- 4 comparisons for 1, 1 comparison for 5-4\n[1,3,5,4,2] -- 4 comparisons for 1, 2 comparisons for 4-5, 4-3\n[1,2,5,4,3] -- 4 comparisons for 1, 3 comparisons for 3-5, 3-4, 3-2\n</code></pre>\n\n<p>Although we should be able to only look at the subarray starting at index one, we <em>always</em> have the initial 4 comparisons. So for the second element, we have</p>\n\n<p><span class=\"math-container\">$$((n-1)+1) + ((n-1)+2) + \\ldots + ((n-1)+(n-3)) + ((n - 1)+(n-2))\n = (n-1)(n-2) + \\frac{(n-1)(n-2)}{2}$$</span>\ncomparisons. It's similar for the rest:</p>\n\n<pre><code>[1,2,5,4,3]\n[1,2,4,5,3] -- 4 comparisons for 1, 3 comparisons 2, 1 comparison for 5-4\n[1,2,3,5,4] -- 4 comparisons for 1, 3 comparisons 2, 2 comparison for 4-5, 4-3\n</code></pre>\n\n<p>If we complete the induction, we get</p>\n\n<p><span class=\"math-container\">$$ \\sum_{i=0}^n \\frac{(n-i)(n-i-1)}{2} + (n-i-1)\\sum_{j=1}^i (n-j) $$</span>\nwhich is inefficient enough. Good job there :).\n</p>\n\n<h1>Readability, reuse and testability</h1>\n\n<p>Readability <em>really</em> suffers since the swap logic is put into a single line. Also, there are several values with short names that are not related to your algorithm at all.</p>\n\n<p>Furthermore, we cannot use the sort outside of that snippet. That prevents</p>\n\n<ul>\n<li>sorting more than one array</li>\n<li>custom sort (for example reverse, lexicographic, etc.)</li>\n<li>testing</li>\n</ul>\n\n<p>So first of all let's make a function:</p>\n\n<pre><code>function slowSort(arr) {\n var src = 0;\n var dest;\n var tmp;\n\n while(src < arr.length - 1) {\n dest = src + 1;\n while(dest < arr.length) {\n if(arr[src] > arr[dest]) {\n temp = arr[dest];\n arr[dest] = arr[src];\n arr[src] = temp;\n src = 0;\n break;\n }\n dest++;\n src++; // place this one in the outer to make it worse, but\n // keep in mind to set `src = -1` instead.\n }\n }\n}\n</code></pre>\n\n<p>That's a lot easier to read. Also, we can now</p>\n\n<ul>\n<li>sort multiple times</li>\n<li>get improvements/speed regressions for every call site</li>\n<li><p>add additional comparison methods, e.g.</p>\n\n<pre><code>function slowSort(arr, comp) { ... }\n</code></pre></li>\n<li><strong>test</strong> the function</li>\n</ul>\n\n<h1>Bottom line</h1>\n\n<p>Always try to make your code reusable, testable and readable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T13:16:16.960",
"Id": "210270",
"ParentId": "210267",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T10:17:59.563",
"Id": "210267",
"Score": "1",
"Tags": [
"javascript",
"array",
"sorting"
],
"Title": "A 'slow sort': repeatedly swap the first misordered pair"
} | 210267 |
<p>I'm trying to get the changes that were made in a string and apply them to similar strings.</p>
<p><strong>string are similar if they are equal from 0 to index of change.</strong></p>
<p>let's say I have this strings:</p>
<pre><code>let a = "123.1/1";
let b = "123.1/2";
let c = "124.1/1";
</code></pre>
<p>now we make these changes:</p>
<pre><code>let newA = "123.22/1"; // was "123.1/1", indexOfChange = 3 in this case.
</code></pre>
<p>then when we want to apply changes to similar strings I want the changes to apply only to similar strings:</p>
<pre><code>a = "123.22/1";
b = "123.22/2";
c = "124.1/1";
</code></pre>
<p><strong>The way I tackled it is by taking these steps:</strong></p>
<ol>
<li><p>get the index of change by comparing old <code>a</code> with the new value.</p>
<pre><code>let len = max(a.length, newA.length);
let changeStartsAt = 0;
for(let i = 0; i < len; i++){
if(a[i] != newA[i]){
changeStartsAt = i;
break;
}
}
</code></pre></li>
<li><p>get the "suffix" (couldn't find a better name for it) and where it starts in <code>a</code>.</p>
<pre><code>let changeOldEndsAt= 0;
let changeNewEndsAt = 0;
let k = a.length - 1;
let j = newA.length - 1;
while(k >= 0 && j >= 0){
if(a[k] != newA[j]){
changeOldEndsAt = k;
changeNewEndsAt = j;
break;
}
k--;j--;
}
</code></pre></li>
<li><p>get the similar string (as defined above) and apply the changes.</p>
<pre><code>let arr = [a,b,c];
let rep = a.substring(0, changeStartsAt + 1);
for(let str of arr){
// this is how I defined 'similar'
if(str.length != str.replace(rep, '').length){
console.log(
str.substring(0, changeStartsAt) +
newA.substring(changeStartsAt, changeNewEndsAt + 1) +
str.substring(changeOldEndsAt, str.length)
)
}
}
</code></pre></li>
</ol>
<p>Is there a more efficient/"good practice" to achieve this?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T10:41:17.540",
"Id": "210268",
"Score": "1",
"Tags": [
"javascript",
"strings"
],
"Title": "change a string and apply changes to other similar strings"
} | 210268 |
<p>So, I just wanted to post something on <a href="http://www.rosettacode.org/wiki/Rosetta_Code" rel="noreferrer">Rosetta Code</a>, and I found this task of generating and plotting a <a href="https://en.wikipedia.org/wiki/Julia_set" rel="noreferrer">Julia set</a>: <a href="http://www.rosettacode.org/wiki/Julia_set" rel="noreferrer">http://www.rosettacode.org/wiki/Julia_set</a>. There was already one solution but it was quite inefficient and not Pythonic. Here is my attempt on this:</p>
<pre><code>"""
This solution is an improved version of an efficient Julia set solver
from:
'Bauckhage C. NumPy/SciPy Recipes for Image Processing:
Creating Fractal Images. researchgate. net, Feb. 2015.'
"""
import itertools
from functools import partial
from numbers import Complex
from typing import Callable
import matplotlib.pyplot as plt
import numpy as np
def douady_hubbard_polynomial(z: Complex,
*,
c: Complex):
"""
Monic and centered quadratic complex polynomial
https://en.wikipedia.org/wiki/Complex_quadratic_polynomial#Map
"""
return z ** 2 + c
def julia_set(*,
mapping: Callable[[Complex], Complex],
min_coordinate: Complex,
max_coordinate: Complex,
width: int,
height: int,
iterations_count: int = 256,
threshold: float = 2.) -> np.ndarray:
"""
As described in https://en.wikipedia.org/wiki/Julia_set
:param mapping: function defining Julia set
:param min_coordinate: bottom-left complex plane coordinate
:param max_coordinate: upper-right complex plane coordinate
:param height: pixels in vertical axis
:param width: pixels in horizontal axis
:param iterations_count: number of iterations
:param threshold: if the magnitude of z becomes greater
than the threshold we assume that it will diverge to infinity
:return: 2D pixels array of intensities
"""
imaginary_axis, real_axis = np.ogrid[
min_coordinate.imag: max_coordinate.imag: height * 1j,
min_coordinate.real: max_coordinate.real: width * 1j]
complex_plane = real_axis + 1j * imaginary_axis
result = np.ones(complex_plane.shape)
for _ in itertools.repeat(None, iterations_count):
mask = np.abs(complex_plane) <= threshold
if not mask.any():
break
complex_plane[mask] = mapping(complex_plane[mask])
result[~mask] += 1
return result
if __name__ == '__main__':
mapping = partial(douady_hubbard_polynomial,
c=-0.7 + 0.27015j) # type: Callable[[Complex], Complex]
image = julia_set(mapping=mapping,
min_coordinate=-1.5 - 1j,
max_coordinate=1.5 + 1j,
width=800,
height=600)
plt.axis('off')
plt.imshow(image,
cmap='nipy_spectral',
origin='lower')
plt.show()
</code></pre>
<p>I think it looks good, and it is definitely more efficient. There was just one thing that I was not sure about. I was thinking to take out creating a <code>complex_plane</code> to a separate function and pass it as a parameter to <code>julia_set</code>. But in this case the <code>julia_set</code> wouldn't be a pure function as it would mutate the <code>complex_plane</code>. And I prefer my functions not to have any side effects. So I decided to leave it as is. </p>
<p>Any comments on this matter or anything else are welcome.</p>
<p>Here are some examples of output:</p>
<p><img src="https://i.stack.imgur.com/kAqld.png" width="300">
<img src="https://i.stack.imgur.com/ol0Qy.png" width="300"></p>
| [] | [
{
"body": "<p>For <code>douady_hubbard_polynomial</code>, you're missing a return type.</p>\n\n<p>This:</p>\n\n<pre><code>for _ in itertools.repeat(None, iterations_count):\n</code></pre>\n\n<p>can just be</p>\n\n<pre><code>for _ in range(iterations_count):\n</code></pre>\n\n<p>I don't see any other obvious issues.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T15:37:47.603",
"Id": "406421",
"Score": "3",
"body": "`itertools.repeat(None, iterations_count)` is much faster for big `int`s since it doesn't require creating redundant objects, you can look at [this answer](https://stackoverflow.com/a/9098860/5997596)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T15:44:23.157",
"Id": "406423",
"Score": "0",
"body": "That's pretty cool; I didn't know that. I'd still suggest that it's premature optimization and highly unlikely to be a bottleneck of any significance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T16:22:03.013",
"Id": "406427",
"Score": "1",
"body": "I did some timings, and it looks like `itertools.repeat` won't be of any help due to breaking out of a loop when the `mask` becomes empty, so it won't reach big `int`s where the difference will be significant. I'm gonna change it to `range`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T16:35:40.573",
"Id": "406429",
"Score": "0",
"body": "About using the asterisk. I think it is a good practice to [force a user to use keyword arguments](https://stackoverflow.com/questions/2965271/forced-naming-of-parameters-in-python). When you said about *arbitrary arguments*, I think, you referred to [another thing](https://stackoverflow.com/questions/13125218/arbitrary-number-of-arguments-in-a-python-function) which is not my case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T18:01:57.643",
"Id": "406434",
"Score": "0",
"body": "@Georgy I removed my asterisk feedback from the answer. That said, this is a style decision, and one I disagree with. It should be left to the caller to determine whether adding explicit kwarg names makes the call more clear, or whether the parameters being passed are obvious and the code can be made more terse."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T14:58:02.440",
"Id": "210272",
"ParentId": "210271",
"Score": "3"
}
},
{
"body": "<h3>1. Review</h3>\n\n<ol>\n<li><p>Some of the variable names could be improved:</p>\n\n<p><code>complex_plane</code> is an array of <span class=\"math-container\">\\$z\\$</span> values for each pixel in the image, so naming it <code>z</code> would help the reader relate it to the <code>z</code> in <code>douady_hubbard_polynomial</code>. </p>\n\n<p><code>imaginary_axis</code> and <code>real_axis</code> are only used once in the very next line, so there is no need for them to have long and memorable names. I would use something short like <code>im</code> and <code>re</code>.</p>\n\n<p><code>result</code> is an array of iteration counts, so it could be named something like <code>iterations</code>.</p>\n\n<p><code>mask</code> is a Boolean array selecting pixels that have not yet diverged to infinity, so something like <code>not_diverged</code> or <code>live</code> would convey this better.</p></li>\n<li><p>On each iteration, the iteration counts of the escaped pixels are incremented. This means that some pixels get incremented many times, for example a pixel that escapes on the first iteration gets its count incremented 256 times. It would be more efficient to set the iteration count for each pixel just once. A convenient time to do this is when it escapes.</p></li>\n<li><p>As the number of iterations goes up, the number of pixels that have not escaped to infinity gets smaller and smaller. But the masking operations are always on the whole array. It would be more efficient to keep track of the <em>indexes</em> of the pixels that have not escaped, so that subsequent operations are on smaller and smaller arrays.</p></li>\n</ol>\n\n<h3>2. Revised code</h3>\n\n<pre><code>im, re = np.ogrid[min_coordinate.imag: max_coordinate.imag: height * 1j,\n min_coordinate.real: max_coordinate.real: width * 1j]\nz = (re + 1j * im).flatten()\nlive, = np.indices(z.shape) # indexes of pixels that have not escaped\niterations = np.empty_like(z, dtype=int)\nfor i in range(iterations_count):\n z_live = z[live] = mapping(z[live])\n escaped = abs(z_live) > threshold\n iterations[live[escaped]] = i\n live = live[~escaped]\niterations[live] = iterations_count - 1\nreturn (iterations_count - iterations).reshape((height, width))\n</code></pre>\n\n<p>Notes</p>\n\n<ol>\n<li><p>This is about three times as fast as the code in the post.</p></li>\n<li><p>Because we are maintaining an array of indexes, it is convenient to flatten the <code>z</code> array and then reshape <code>iterations</code> to two dimensions before returning it. If we left the array two-dimensional, there would need to be two arrays of indexes, <code>live_i</code> and <code>live_j</code>.</p></li>\n<li><p>Pixels that don't escape are given the value <code>iterations_count - 1</code> in order to match the code in the post. It would make more sense to use <code>iterations_count</code> or a larger value here.</p></li>\n<li><p>The subtraction <code>iterations_count - iterations</code> is only there so that the returned values match the code in the post. The subtraction could be omitted if you <a href=\"https://matplotlib.org/api/_as_gen/matplotlib.colors.Colormap.html#matplotlib.colors.Colormap.reversed\" rel=\"noreferrer\">reverse the colour map</a>.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-27T19:00:30.647",
"Id": "210445",
"ParentId": "210271",
"Score": "5"
}
},
{
"body": "<p>This is a minor change, with a 50% improvement to @gareth's answer. Changing </p>\n\n<p><code>escaped = abs(z_live) > threshold</code> to </p>\n\n<p><code>escaped = z_live.real**2 + z_live.imag**2>threshold**2</code></p>\n\n<p>while less nice looking is about 50% faster because it saves a square-root of all the elements.</p>\n\n<p>To time it, I used</p>\n\n<pre><code>t1 = time()\nimage = julia_set(mapping=mapping,\n min_coordinate=-1.5 - 1j,\n max_coordinate=1.5 + 1j,\n iterations_count = 255,\n width=1920,\n height=1080)\nprint(time() - t1)\n</code></pre>\n\n<p>Before: 3.16s\nAfter 2.21s</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-17T15:12:03.780",
"Id": "435186",
"Score": "0",
"body": "Thanks for the feedback! Did you measure the times for this specific line or for the full script? Because I don't see any performance gain when measuring times of running the `julia_set` function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-17T15:18:55.143",
"Id": "435189",
"Score": "0",
"body": "Timing info added, my guess is that you timed image showing or something."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-17T15:25:08.493",
"Id": "435190",
"Score": "0",
"body": "Sorry, maybe I don't understand something, but 3.21s is more than 3.16s, and I don't see the 50% improvement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-17T15:27:20.097",
"Id": "435191",
"Score": "0",
"body": "yes, that's because I mistyped 2 as 3"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-17T15:42:44.940",
"Id": "435192",
"Score": "0",
"body": "Well, that's weird, I get 10% longer times with your suggestion. I guess I'm doing something wrong..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-17T15:44:52.387",
"Id": "435193",
"Score": "0",
"body": "Are you running the revised code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-17T16:00:28.463",
"Id": "435196",
"Score": "0",
"body": "Yes, double-checked, it runs slower for me. With your setup the revised code as in the Gareth's answer takes around 5.7s for me, and with your suggestion it takes around 6.3s. Are you using the same `mapping` as in the question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-17T16:38:27.547",
"Id": "435200",
"Score": "0",
"body": "yes. What version of python are you using? Also what OS? I'm 3.7 on linux"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-17T18:25:17.263",
"Id": "435211",
"Score": "0",
"body": "Huh! So, now I tried it on my home laptop, and now I see the difference: 2.89s vs 2.06s. (Linux, Python 3.7.0, NumPy 1.16.3) It's weird to see that it's faster than PC in my office... I don't remember the versions there, will add it tomorrow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-17T18:29:12.877",
"Id": "435212",
"Score": "0",
"body": "My guess is you're office has a version of numpy where real and imag copy rather than alias. For this to be better, it needs to not allocate a ton of memory."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-29T15:00:38.490",
"Id": "436958",
"Score": "0",
"body": "Better late than never. My office PC has the following setup: Windows 8.1, Python 3.7.3, NumPy 1.16.4"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-29T15:17:06.703",
"Id": "436965",
"Score": "1",
"body": "Consider me stumped then."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-17T15:01:55.013",
"Id": "224349",
"ParentId": "210271",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "210445",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T14:09:52.417",
"Id": "210271",
"Score": "15",
"Tags": [
"python",
"numpy",
"fractals"
],
"Title": "Generating Julia set"
} | 210271 |
<p>I am developing a framework that allows to specify a machine learning model via a <code>yaml</code> file with different parameters nested so the configuration files are easy to read for humans.</p>
<p>I would like to give users the option of instead of specifying a parameter giving a range of options to try via a list.</p>
<p>Then I have to take this and generate all the possible valid combinations for the parameters the user has given multiple values for.</p>
<p>To mark which parameters are in fact lists and which ones are multiple values, I have opted to choose that combination values begin with 'multi_' (though if you have a different take I would be interested to hear it!).</p>
<p>So for example an user could write:</p>
<pre><code>config = {
'train_config': {'param1': 1, 'param2': [1,2,3], 'multi_param3':[2,3,4]},
'model_config': {'cnn_layers': [{'units':3},{'units':4}], 'multi_param4': [[1,2], [3,4]]}
}
</code></pre>
<p>Indicating that 6 configuration files must be generated, where the values of 'param3' and 'param4' take all the possible combinations.</p>
<p>I have written a generator function to do this:</p>
<pre><code>from pandas.io.json.normalize import nested_to_record
import itertools
import operator
from functools import reduce
from collections import MutableMapping
from contextlib import suppress
def generate_multi_conf(config):
flat = nested_to_record(config)
flat = { tuple(key.split('.')): value for key, value in flat.items()}
multi_config_flat = { key[:-1] + (key[-1][6:],) : value for key, value in flat.items() if key[-1][:5]=='multi'}
if len(multi_config_flat) == 0: return # if there are no multi params this generator is empty
keys, values = zip(*multi_config_flat.items())
# delete the multi_params
# taken from https://stackoverflow.com/a/49723101/4841832
def delete_keys_from_dict(dictionary, keys):
for key in keys:
with suppress(KeyError):
del dictionary[key]
for value in dictionary.values():
if isinstance(value, MutableMapping):
delete_keys_from_dict(value, keys)
to_delete = ['multi_' + key[-1] for key, _ in multi_config_flat.items()]
delete_keys_from_dict(config, to_delete)
for values in itertools.product(*values):
experiment = dict(zip(keys, values))
for setting, value in experiment.items():
reduce(operator.getitem, setting[:-1], config)[setting[-1]] = value
yield config
</code></pre>
<p>Iterating over this with the example above gives:</p>
<pre><code>{'train_config': {'param1': 1, 'param2': [1, 2, 3], 'param3': 2}, 'model_config': {'cnn_layers': [{'units': 3}, {'units': 4}], 'param4': [1, 2]}}
{'train_config': {'param1': 1, 'param2': [1, 2, 3], 'param3': 2}, 'model_config': {'cnn_layers': [{'units': 3}, {'units': 4}], 'param4': [3, 4]}}
{'train_config': {'param1': 1, 'param2': [1, 2, 3], 'param3': 3}, 'model_config': {'cnn_layers': [{'units': 3}, {'units': 4}], 'param4': [1, 2]}}
{'train_config': {'param1': 1, 'param2': [1, 2, 3], 'param3': 3}, 'model_config': {'cnn_layers': [{'units': 3}, {'units': 4}], 'param4': [3, 4]}}
{'train_config': {'param1': 1, 'param2': [1, 2, 3], 'param3': 4}, 'model_config': {'cnn_layers': [{'units': 3}, {'units': 4}], 'param4': [1, 2]}}
{'train_config': {'param1': 1, 'param2': [1, 2, 3], 'param3': 4}, 'model_config': {'cnn_layers': [{'units': 3}, {'units': 4}], 'param4': [3, 4]}}
</code></pre>
<p>Which is the result expected.</p>
<p>Any feedback on how to make this code more readable would be very much appreciated!</p>
| [] | [
{
"body": "<p>For non-trivial list comprehensions such as</p>\n\n<pre><code>multi_config_flat = { key[:-1] + (key[-1][6:],) : value for key, value in flat.items() if key[-1][:5]=='multi'}\n</code></pre>\n\n<p>You should split it onto multiple lines, i.e.</p>\n\n<pre><code>multi_config_flat = {key[:-1] + (key[-1][6:],): value\n for key, value in flat.items()\n if key[-1][:5]=='multi'}\n</code></pre>\n\n<p>This:</p>\n\n<pre><code>key[-1][:5]=='multi'\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>key[-1].startswith('multi')\n</code></pre>\n\n<p>This:</p>\n\n<pre><code>if len(multi_config_flat) == 0: return\n</code></pre>\n\n<p>is equivalent (more or less) to</p>\n\n<pre><code>if not multi_config_flat:\n return\n</code></pre>\n\n<p>The latter also catches the case of <code>multi_config_flat</code> being <code>None</code>, but that won't be possible in this context.</p>\n\n<p>This:</p>\n\n<pre><code>for key, _ in multi_config_flat.items():\n</code></pre>\n\n<p>is not necessary; simply iterate over <code>keys</code>:</p>\n\n<pre><code>for key in multi_config_flat:\n</code></pre>\n\n<p>This is fairly opaque:</p>\n\n<pre><code>reduce(operator.getitem, setting[:-1], config)[setting[-1]] = value\n</code></pre>\n\n<p>Probably you should assign the output of <code>reduce</code> to a meaningfully named variable, so that your code is more clear.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T21:30:08.643",
"Id": "406458",
"Score": "1",
"body": "`for key in multi_config_flag.keys()` can simply be `for key in multi_config_flag` as the default iterator is `keys()`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T20:08:42.277",
"Id": "210283",
"ParentId": "210275",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "210283",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T16:26:53.427",
"Id": "210275",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"generator"
],
"Title": "Generating combinations of specific values of a nested dict"
} | 210275 |
<p>I'm studying C with a Deitel's book. The book asks me to write a program that simulates a virtual PC (with virtual memory in an array called <code>memory[100]</code>).
Then the book asks me to write a program that sums 10 numbers. I did it but I had to initialize some variables (<code>memory[20]</code>, <code>memory[21]</code>, <code>memory[22]</code>) before running the program.
There is any way to make this program without initially storing the variables
and using the same number of instructions?</p>
<p>These are valid instructions:</p>
<pre><code>#define READ 10;
#define WRITE 11;
#define LOAD 20;
#define STORE 21;
#define ADD 30;
#define SUBTRACT 31;
#define DIVIDE 32;
#define MULTIPLY 33;
#define BRANCH 40;
#define BRANCHANG 41;
#define BRANCHZERO 42;
#define HALT 43;
</code></pre>
<p>And the code:</p>
<pre><code>int main(){
int memory[100] = {2022,1022,3022,2122,2021,3120,2121,4209,4000,1122,4300}; // my set of instruction for sum 10 numbers
memory[99] = -99999;
memory[20] = 1; // the variables initializations that i want to remove
memory[21] = 10;
memory[22] = 0;
int accumulator = 0000;
int instCounter = 00;
int instRegistrer = 0000;
int operationCode = 00;
int operand = 00;
while(memory[instCounter] >= 0){
printf("\n**%d** ", instCounter);
instRegistrer = memory[instCounter];
operationCode = instRegistrer / 100;
operand = instRegistrer % 100;
switch(operationCode){
case READ:
printf("READ ");
scanf("%d", &memory[operand]);
instCounter++;
break;
case WRITE:
printf("WRITE ");
printf("%d", memory[operand]);
instCounter++;
break;
case LOAD:
printf("LOAD ");
accumulator = memory[operand];
instCounter++;
break;
case STORE:
printf("STORE ");
memory[operand] = accumulator;
instCounter++;
break;
case ADD:
printf("ADD ");
accumulator += memory[operand];
instCounter++;
break;
case SUBTRACT:
printf("SUBTRACT ");
accumulator -= memory[operand];
instCounter++;
break;
case DIVIDE:
printf("DIVIDE ");
accumulator /= memory[operand];
instCounter++;
break;
case MULTIPLY:
printf("MULTIPLY ");
accumulator *= memory[operand];
instCounter++;
break;
case BRANCH:
printf("BRANCH ");
instCounter = operand;
break;
case BRANCHANG:
printf("BRANCHANG ");
if(accumulator < 0)instCounter = operand;
else instCounter++;
break;
case BRANCHZERO:
printf("BRANCHZERO ");
if(accumulator == 0)instCounter = operand;
else instCounter++;
break;
case HALT:
printf("HALT ");
instCounter = 99;
break;
}
}
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T18:00:35.200",
"Id": "406433",
"Score": "0",
"body": "The code, as presented, does not compile."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T18:05:02.680",
"Id": "406435",
"Score": "2",
"body": "@1201ProgramAlarm Can you illuminate us? What's the error?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T18:11:18.700",
"Id": "406438",
"Score": "0",
"body": "@1201ProgramAlarm What is the error?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-25T00:42:56.690",
"Id": "406461",
"Score": "4",
"body": "@Reinderien As you mention in your answer, all those semicolons in the `#define` macros, which will expand to `case 10;:` etc. which won't compile."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-25T07:42:23.047",
"Id": "406471",
"Score": "1",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. Feel free to post a follow-up question linking back to this one instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-25T16:03:11.747",
"Id": "406489",
"Score": "3",
"body": "Closing this question as broken, since the code does not compile. Please refrain from changing the code after receiving answers as outlined in the policy above."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-25T23:20:03.367",
"Id": "406510",
"Score": "2",
"body": "Note that this answer is currently being [discussed on meta](https://codereview.meta.stackexchange.com/q/9050/37660)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-28T12:13:23.807",
"Id": "406859",
"Score": "1",
"body": "@Vogel612 As per [this policy](https://codereview.meta.stackexchange.com/q/7051) you can edit an off-topic question with answers to make it on-topic. If that's what has been done here can we just fix and re-open the question?"
}
] | [
{
"body": "<p>Your instruction list:</p>\n\n<pre><code>#define READ 10;\n#define WRITE 11;\n#define LOAD 20;\n#define STORE 21;\n#define ADD 30;\n#define SUBTRACT 31;\n#define DIVIDE 32;\n#define MULTIPLY 33;\n#define BRANCH 40;\n#define BRANCHANG 41;\n#define BRANCHZERO 42;\n#define HALT 43;\n</code></pre>\n\n<p>has a few issues. First of all, you shouldn't add semicolons after those defines. Also, this would be better represented as an <code>enum</code>, since op codes are mutually exclusive.</p>\n\n<p>Your memory initialization:</p>\n\n<pre><code>int memory[100] = {2022,1022,3022,2122,2021,3120,2121,4209,4000,1122,4300}; // my set of instruction for sum 10 numbers\n</code></pre>\n\n<p>also needs a few adjustments. Since none of these values will exceed 9999, you should be storing them as <code>int16_t</code>, not int. Furthermore, you shouldn't be writing raw machine code in that array. You should be constructing those values like</p>\n\n<pre><code>{\n 100*LOAD + 22,\n 100*READ + 22,\n // ...\n}\n</code></pre>\n\n<p>Also, it seems like you store -99999 as a magic value to indicate program termination, when this is technically not necessary. I don't have the specifications for your VM, but it would make more sense to</p>\n\n<ul>\n<li>have all of the memory contents be of type <code>int16_t</code></li>\n<li>on <code>HALT</code>, simply terminate the program</li>\n</ul>\n\n<p>rather than</p>\n\n<ul>\n<li>on <code>HALT</code>, jump to the end of memory</li>\n<li>at the end of memory, have a magic negative value.</li>\n</ul>\n\n<p>There's a typo in <code>instRegistrer</code>. It's \"register\", not \"registrer\".</p>\n\n<p>I propose that, instead of having to manually write a different <code>printf</code> string for each instruction, </p>\n\n<ol>\n<li>declare an array of 44 character pointers</li>\n<li>define a macro that indexes into the array based on the opcode value, and initializes that element to a stringized (<code>#</code>) version of the opcode</li>\n<li>call the macro for every opcode that you have</li>\n</ol>\n\n<p>You could take this strategy further and store a struct at each element of the array, containing a string name and an operation function pointer. This would nicely generalize your code and make execution of long programs faster. </p>\n\n<p>You're also keen on avoiding separate assignment of memory contents for use by variables. This can be done by shifting your \"data\" memory to the address right after your \"program\" memory, and then doing the initialization in your array literal.</p>\n\n<p>The following incorporates all of the above. It seems you're still learning basic C, so some of these concepts may require explanation - please let me know in the comments.</p>\n\n<pre><code>#include <stdio.h>\n#include <stdint.h>\n#include <stdlib.h>\n\ntypedef enum\n{\n READ = 10,\n WRIT = 11,\n LOAD = 20,\n STOR = 21,\n ADD = 30,\n SUB = 31,\n DIV = 32,\n MUL = 33,\n BRA = 40,\n BRNG = 41,\n BRZR = 42,\n HALT = 43\n} OpCode;\n\ntypedef struct\n{\n int16_t mem[100], acc;\n uint8_t counter;\n} VM;\n\ntypedef struct\n{\n const char *name;\n void (*execute)(VM *vm, uint8_t addr);\n} Operation;\n\nstatic uint16_t makeOp(OpCode code, uint8_t addr)\n{\n return 100*code + addr;\n}\n\n#define DEFOP(op) ops[op] = (Operation){.name=#op, .execute=exc_##op}\n\nstatic void exc_READ(VM *vm, uint8_t addr) {\n int32_t x;\n if (scanf(\"%d\", &x) != 1)\n {\n perror(\"Failed to read integer\");\n exit(1);\n }\n if (x >= 10000 || x <= -10000)\n {\n fprintf(stderr, \"Invalid value %d\", x);\n exit(1);\n }\n vm->mem[addr] = x;\n vm->counter++;\n}\nstatic void exc_WRIT(VM *vm, uint8_t addr) {\n printf(\"%d\\n\", vm->mem[addr]);\n vm->counter++;\n}\nstatic void exc_LOAD(VM *vm, uint8_t addr) {\n vm->acc = vm->mem[addr];\n vm->counter++;\n}\nstatic void exc_STOR(VM *vm, uint8_t addr) {\n vm->mem[addr] = vm->acc;\n vm->counter++;\n}\nstatic void exc_ADD(VM *vm, uint8_t addr) {\n vm->acc += vm->mem[addr];\n vm->counter++;\n}\nstatic void exc_SUB(VM *vm, uint8_t addr) {\n vm->acc -= vm->mem[addr];\n vm->counter++;\n}\nstatic void exc_DIV(VM *vm, uint8_t addr) {\n vm->acc /= vm->mem[addr];\n vm->counter++;\n}\nstatic void exc_MUL(VM *vm, uint8_t addr) {\n vm->acc *= vm->mem[addr];\n vm->counter++;\n}\nstatic void exc_BRA(VM *vm, uint8_t addr) {\n vm->counter = addr;\n}\nstatic void exc_BRNG(VM *vm, uint8_t addr) {\n if (vm->acc < 0)\n vm->counter = addr;\n else\n vm->counter++;\n}\nstatic void exc_BRZR(VM *vm, uint8_t addr) {\n if (!vm->acc)\n vm->counter = addr;\n else\n vm->counter++;\n}\nstatic void exc_HALT(VM *vm, uint8_t addr) {\n exit(0);\n}\n\nint main()\n{\n const uint8_t X = 13, I = 12, DELTA = 11;\n\n Operation ops[HALT+1];\n DEFOP(READ);\n DEFOP(WRIT);\n DEFOP(LOAD);\n DEFOP(STOR);\n DEFOP(ADD);\n DEFOP(SUB);\n DEFOP(DIV);\n DEFOP(MUL);\n DEFOP(BRA);\n DEFOP(BRNG);\n DEFOP(BRZR);\n DEFOP(HALT);\n\n VM vm = {.counter = 0,\n .acc = 0,\n .mem = {\n makeOp(LOAD, X), // 0: beginning\n makeOp(READ, X),\n makeOp( ADD, X),\n makeOp(STOR, X),\n makeOp(LOAD, I),\n makeOp( SUB, DELTA),\n makeOp(STOR, I),\n makeOp(BRZR, 9),\n makeOp( BRA, 0),\n makeOp(WRIT, X), // 9: exit loop\n makeOp(HALT, 0),\n 1, // 11: DELTA\n 10, // 12: I\n 0 // 13: X\n }};\n\n for (;;) {\n int16_t current = vm.mem[vm.counter];\n uint8_t code = current/100,\n addr = current%100;\n const Operation *op = ops + code;\n printf(\"%02u: %4s %02u\\n\", vm.counter, op->name, addr);\n op->execute(&vm, addr);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T18:32:59.383",
"Id": "406447",
"Score": "0",
"body": "In the original code there was no semicolon after definies. I'm studying C and i am actually on the pointer chapter, i dont know what enum is. uint16_t is a good idea but It Is only an exercise, i dont mind about efficence. The instruction must be an integer of 4 digits. My question was there Is any way to sum 10 numbers without initialize variables in Memory."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T19:40:23.673",
"Id": "406451",
"Score": "1",
"body": "An `enum` is basically an integer, but its values are constrained to a certain named list. Be careful about your 4-digit notation, because it sometimes doesn't do what you expect: for instance, 0244 is interpreted as *octal* instead of decimal."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T19:41:41.350",
"Id": "406452",
"Score": "0",
"body": "There is a way to simplify your memory variable initialization. If you're allowed to use different addresses than 20/21/22, then you can include them at the end of the literal array initializer (but you'll have to adjust your addresses)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T19:50:18.403",
"Id": "406454",
"Score": "0",
"body": "I never worked with typedef, struct, static functions and i dont know what is ->(it looks like an operator). To develop the program i followed the instruction on the book. The instruction said to use #define for READ,WRITE.... and to use a switch for operationCode"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T19:54:56.787",
"Id": "406455",
"Score": "5",
"body": "It seems like you have some reading to do :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-25T07:46:37.687",
"Id": "406473",
"Score": "5",
"body": "In the future, please refrain from answering off-topic questions. The code in the question was broken (did not compile, so couldn't have produced the correct result). Instead, flag/vote to close the question instead so it can be fixed by the author (and afterwards be reopened/reviewed). Thank you for your contributions!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-25T17:07:28.020",
"Id": "406490",
"Score": "0",
"body": "@Mast Quite true; I got ahead of myself."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T18:19:48.913",
"Id": "210280",
"ParentId": "210276",
"Score": "9"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T16:36:09.663",
"Id": "210276",
"Score": "3",
"Tags": [
"c",
"virtual-machine"
],
"Title": "Simpletron in C without initial storing"
} | 210276 |
<p>I solved <a href="https://leetcode.com/problems/remove-element/" rel="nofollow noreferrer">this problem</a>:</p>
<blockquote>
<p>Given an array <code>nums</code> and a value <code>val</code>, remove all instances of that value in-place and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.</p>
</blockquote>
<p>How can I improve its execution time and also, if there is any better way of doing it?</p>
<pre><code>public int removeElement(int[] numbers, int value) {
int index = 0;
for(; index < numbers.length; index++) {
if(numbers[index] == value) {
boolean otherNumberPresent = false;
int j = index + 1;
for(; j < numbers.length; j++ ){
if(numbers[j] != value) {
otherNumberPresent = true;
break;
}
}
if(otherNumberPresent) {
int temp = numbers[j];
numbers[j] = numbers[index];
numbers[index] = temp;
} else {
return index;
}
}
}
return index;
}
</code></pre>
| [] | [
{
"body": "<p>A much simpler solution is to have an \"input pointer\" <code>i</code> and an \"output pointer\" <code>o</code>.</p>\n\n<pre><code>public int removeElement(int[] numbers, int value) {\n int o = 0;\n for (int i = 0; i < numbers.length; i++) {\n if (numbers[i] != value) {\n numbers[o++] = numbers[i];\n }\n }\n return o;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T20:13:17.450",
"Id": "210284",
"ParentId": "210282",
"Score": "6"
}
},
{
"body": "<p>The fundamental issue with your code is that it has two loops in it. As a rule of thumb, that suggests it is a quadratic algorithm: if you double the size of the input, the runtime could be four times worse.</p>\n\n<p>In practice that should (depending on the input profile) happen rarely, so long as the array doesn't have the first half full of the target number and the second full of other stuff. But even with a more random distribution, this will be slower than needed because it keeps dumping the values to remove back into the bit of the array it is about to search!</p>\n\n<p>The answer by 200_success works well enough, but also has a higher than necessary cost because it writes something in almost every step of the loop.</p>\n\n<p>There is another solution, hinted at in the question with the order doesn't matter clause: when you need to delete something, move the replacement from the end. Because the end is discarded anyway, you don't even need to swap out the old value with the one you want to delete. </p>\n\n<p>Although it is dangerous to predict without profiling, that will probably prove a more efficient approach. The heuristic is that most steps in the loop will just be a read and equality comparison before moving on to the next step. (This should also be friendly to a bunch of low level details such as the cache coherence and branch predictor, but that is very detailed and really needs profiling.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-25T00:07:02.497",
"Id": "210292",
"ParentId": "210282",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "210284",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T19:46:30.400",
"Id": "210282",
"Score": "3",
"Tags": [
"java",
"performance",
"programming-challenge"
],
"Title": "Remove all occurrences of an element from an array, in place"
} | 210282 |
<blockquote>
<p><strong>Function</strong> : User enters a word in korean and the program translates (defines) it in english. </p>
<p>What improvements can I make? </p>
<p><strong>Extra</strong> : What other challenges would you recommend that incorporates both JSON and python?</p>
</blockquote>
<p><strong>KoreanDictionary.py</strong></p>
<pre><code>import json
from difflib import get_close_matches
korean_data = json.load(open("korean_vocabulary.json"))
def my_translator(word):
if word in korean_data.keys():
return korean_data[word]
elif len(get_close_matches(word,korean_data.keys(),n=1,cutoff=.69)) > 0:
word = get_close_matches(word,korean_data.keys(),n=1,cutoff=.69)[0]
return korean_data[word]
else:
return "Word does not exist."
if __name__ == '__main__':
user_input = input("Define:")
definition = str(my_translator(user_input)).replace('[','').replace(']','').replace("'",'')
print(user_input + ": " + definition)
</code></pre>
<p><strong>korean_vocabulary.json</strong></p>
<pre><code>{"์๋
ํ์ธ์": ["hello"],"์ฃฝ์ด๋ฒ๋ ค": ["GO DIE"],"์ํฉ": ["situation"],"์ด๋ ค์": ["hard; difficult"],
"๋ชจ๋ฅด๊ฒ ๋ค": ["I don't know."],"์กฐ๊ฑด": ["condition"],"์ ๊ท์ง ์ง์
": ["full-time job"],
"ํ๋ฝ": ["eliminate; out"], "๋์น": ["quick to catch; tactfulness"],"์ฌํ": ["sad"],
"๋ณต์กํ": ["complicated"],"์์ ": ["completely"],"๋ฐ๋": ["opposite"],"๋๋ฐ": ["jackpot; awesome"],
"์ด๊บ ": ["shoulders"],"์ผ๊ตด": ["face"]}
</code></pre>
| [] | [
{
"body": "<pre><code>if word in korean_data.keys():\n return korean_data[word]\n</code></pre>\n\n<p>This is better written as:</p>\n\n<pre><code>trans = korean_data.get(word)\nif trans:\n return trans\n</code></pre>\n\n<p>This:</p>\n\n<pre><code>elif len(get_close_matches(word,korean_data.keys(),n=1,cutoff=.69)) > 0:\n word = get_close_matches(word,korean_data.keys(),n=1,cutoff=.69)[0]\n return korean_data[word]\n</code></pre>\n\n<p>calls for a few changes. Firstly, you don't need an <code>elif</code>, simply an <code>if</code> - because the previous block returned. Also, you should avoid re-issuing that entire <code>get_close_matches</code> call, and instead write a temporary variable:</p>\n\n<pre><code>words = get_close_matches(word,korean_data.keys(),n=1,cutoff=.69)\nif words:\n return korean_data[words[0]]\n</code></pre>\n\n<p>This:</p>\n\n<pre><code>return \"Word does not exist.\"\n</code></pre>\n\n<p>is not really good practice. It's \"in-band error information\", i.e. you're mixing valid data with an error message. Instead, you should be <code>raise</code>-ing an exception, catching it in your calling code, and outputting an error message there.</p>\n\n<blockquote>\n <p>What other challenges would you recommend that incorporates both JSON and python?</p>\n</blockquote>\n\n<p>Download or scrape a real Korean-English dictionary dataset, either incorporating it into your application or setting up a REST client to contact a translation server somewhere. If local, save it as a format more efficient than JSON - perhaps compressed pickle, or SQLite. There are many ways to store a local database, and each has its advantages and disadvantages, but that's a topic for another question.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-25T05:56:45.330",
"Id": "406467",
"Score": "0",
"body": "I would never recommend to use pickle, especially to someone not so experienced with it, it makes code vulnerable & dictionary file hardly manageable, can't see any pros in doing that, maybe using some sort of database (SQLite for beginning) can be a better idea"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-25T17:13:22.003",
"Id": "406491",
"Score": "0",
"body": "@AzatIbrakov It's only one of many alternatives, and it is appropriate for some cases (otherwise, why would it be included in Python?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-25T17:15:51.977",
"Id": "406492",
"Score": "0",
"body": "it is used internally, mainly in `multiprocessing` stdlib module, even [docs](https://docs.python.org/3/library/pickle.html) warns us that `pickle` is not secure"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-25T17:17:28.247",
"Id": "406493",
"Score": "0",
"body": "It's not secure against *maliciously constructed data*. In this use case (a translation dictionary), the data are not being supplied by the user, so the risk is lower."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-25T17:21:17.297",
"Id": "406494",
"Score": "0",
"body": "why to use insecure, Python-specific, hardly-manageable solution, when there are tons of alternatives that better suite for purposes of persistence?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-25T19:19:09.523",
"Id": "406499",
"Score": "0",
"body": "So like this: \"raise Exception(\"Word does not exist.\")\" ???"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-25T20:48:35.737",
"Id": "406503",
"Score": "2",
"body": "An example why in-band error information is bad: https://boingboing.net/2008/07/15/chinese-restaurant-c.html"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-25T21:15:37.550",
"Id": "406504",
"Score": "0",
"body": "@austingae More or less. You'd probably want to use something more specific than `Exception` - perhaps `ValueError`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-25T21:21:16.643",
"Id": "406505",
"Score": "0",
"body": "I see. Better to be specific than to be vague ofc. Thanks."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T23:00:39.073",
"Id": "210288",
"ParentId": "210286",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "210288",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-12-24T21:15:15.990",
"Id": "210286",
"Score": "5",
"Tags": [
"python",
"json"
],
"Title": "A Korean (Language) Dictionary"
} | 210286 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.