body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I'm recording which keys are being pressed. After pressing two keys, the first link that matches the two characters will be highlighted. After pressing one more key, the link that corresponds to those three characters will be clicked.</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>let keys = []
document.addEventListener('keypress', event => {
if (event.key === ' ') return
keys.push(event.key)
const selector = 'a'
let text = keys.join('')
let element = [...document.querySelectorAll(selector)]
.find(elements => elements.textContent.includes(text))
if (keys.length === 2) {
if (!element) {
keys = []
return
}
const highlightColor = '#f2e1c2'
element.style.borderBottom = `2px solid ${highlightColor}`
element.scrollIntoView({
block: "center"
})
}
if (keys.length === 3) {
if (!element) {
keys = []
return
}
element.click()
keys = []
}
})</code></pre>
</div>
</div>
</p>
<p>As you can see, there are a lot of if statements. <a href="https://github.com/ryanmcdermott/clean-code-javascript#avoid-conditionals" rel="nofollow noreferrer">Some people</a> suggest that you should avoid conditionals. Should I follow that advice here? If so, how should I remove them the conditionals?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T07:54:16.480",
"Id": "525023",
"Score": "0",
"body": "@TobySpeight Is the title fine now?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T07:59:21.400",
"Id": "525025",
"Score": "2",
"body": "Looks much better - thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T00:00:40.363",
"Id": "525082",
"Score": "1",
"body": "It'd be cool to be able to run this on some sample HTML in the snippet to see the behavior."
}
] |
[
{
"body": "<h2>Warning <code>keypress</code></h2>\n<p>The <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document/keypress_event\" rel=\"nofollow noreferrer\" title=\"MDN Web API's Document keypress event\">keypress</a> event has been depreciated. Using it means that your code can just stop working at any time without warning.</p>\n<p>See <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document/keypress_event\" rel=\"nofollow noreferrer\" title=\"MDN Web API's Document keypress event\">keypress</a> page for alternatives. I will assume you use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document/keydown_event\" rel=\"nofollow noreferrer\" title=\"MDN Web API's Document keydown event\">keydown</a></p>\n<h2>Style</h2>\n<p>First some optional style points that will help reduce the chance of bugs</p>\n<ul>\n<li>Delimit all code blocks. Eg <code>if (event.key === ' ') return</code> should be <code>if (event.key === ' ') { return }</code></li>\n<li>Use semicolon to end all ambiguous lines. See rewrite.</li>\n<li>Use constants for variables that do not change. See rewrite.</li>\n</ul>\n<p>General style points</p>\n<ul>\n<li>Empty arrays rather than reassign arrays. See rewrite.</li>\n<li>Don't repeat code. You empty the key array in 3 places, only needs to be done once.</li>\n<li>Use class name to change style rather than assign directly to the style property.</li>\n</ul>\n<h2>UI Problems</h2>\n<p>This code is very user unfriendly.</p>\n<p>A list of problems</p>\n<ul>\n<li><p>You use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key\" rel=\"nofollow noreferrer\" title=\"MDN Web API's KeyboardEvent key\">KeyboardEvent.key</a> property to define the search term. However many keys will be named keys rather than a character. eg <code>Tab</code>, <code>Shift</code></p>\n<p>Hitting any of the non character keys will create a non intuitive search.</p>\n</li>\n<li><p>You highlight anchor elements that match. However if the match does not complete the highlight is left in place.</p>\n<p>You need to remove the highlight from anchors that don't complete the matched keys.</p>\n</li>\n<li><p>(ignoring above point) You only highlight one anchor even if the search would match more than one.</p>\n<p>The user will see the functionality as broken if you don't highlight all matching anchors.</p>\n<p>If you highlight all matches you also need to proved a way to toggle the current focused highlighted option. EG use the Tab key to cycle matches</p>\n</li>\n<li><p>It is possible to accidentally hit keys (Cat on the keyboard).</p>\n<p>With only 3 keys required you redirect the user's page too easily. This is very poor UI practice.</p>\n<p>Better to wait for confirmation (eg user hits "enter") before navigating</p>\n</li>\n<li><p>Don't limit the search to 3 keys strokes. Let the user enter as many keys as needed to make the search term unique.</p>\n<p>Automatically reset the search term only when there are no matches.</p>\n</li>\n<li><p>There is no way to cancel the search (apart from adding a 3 characters that do not match an anchors text.</p>\n<p>Give the user a way to cancel (eg clear the search on the Escape key)</p>\n</li>\n<li><p>The match is maintained indefinitely.</p>\n<p>If the page has a highlighted match the user can come back in hours and if a key is hit that matches the anchor it will navigate.</p>\n<p>Add a search timeout that resets the search term after some timeout</p>\n</li>\n</ul>\n<p>There are more behavioral problems but they should become non issues if you address the points above.</p>\n<p>I will say that your code is unfit and should never be released into the wild.</p>\n<h2>Rewrite</h2>\n<p>The rewrite keeps the same functionality and is only an example of a cleaner style. It is <strong>NOT</strong> an example of how to implement this type of feature.</p>\n<p>I would never use this code due to the many UI problems (as pointed out above)</p>\n<p><strong>Note</strong> this function assumes that the CSS class <code>highlightAnchor</code> has been defined</p>\n<p><strong>Note</strong> A slight behavior change is that a 3 character string match will also highlight and scroll into view.</p>\n<p><strong>Note</strong> If the page contains 100s of anchors you should consider moving the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Array join\">Array.join</a> out of the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Array find\">Array.find</a> callback</p>\n<pre><code>;(()=> {\n const keys = []\n const anchors = [...document.querySelectorAll("a")];\n anchors.length && document.addEventListener('keydown', event => {\n if (event.key !== ' ') { \n keys.length = keys.length >= 3 ? 0 : keys.length;\n keys.push(event.key);\n const match = anchors.find(a => a.textContent.includes(keys.join(''))); \n if (match && keys.length >= 2) {\n match.classList.add("highlightAnchor");\n match.scrollIntoView({block: "center"})\n search.length === 3 && match.click();\n }\n }\n });\n})();\n</code></pre>\n<h2>If statements</h2>\n<p>Code without conditional branching does not need a computer to run it.</p>\n<p>There is nothing wrong with <code>if</code> (and like branching instructions, <code>if</code>, <code>else</code>, <code>switch case</code>, <code>while</code>, ...). They can not be avoided, they can only be hidden via syntax tricks / hacks.</p>\n<p>OMDG The linked example you give of <a href=\"https://github.com/ryanmcdermott/clean-code-javascript#avoid-conditionals\" rel=\"nofollow noreferrer\">bad practice</a> should be read with a pinch of salt (oceans worth if you ask me) The "bad" V "good" example are completely unrelated and it is quite laughable.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T01:54:54.343",
"Id": "265868",
"ParentId": "265812",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T07:28:32.647",
"Id": "265812",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Recording keypress and clicking the link that corresponds to the pressed characters"
}
|
265812
|
<p>This is a simple Python multi-connection downloader primarily using requests, mmap and threads, it downloads a single file using 32 concurrent connections, slices the download using range parameter, and write the slices to a <code>mmap</code> object.</p>
<p>The code:</p>
<pre class="lang-py prettyprint-override"><code>import re
import requests
import sys
import time
from collections import deque
from datetime import datetime, timedelta
from math import inf
from mmap import mmap
from pathlib import Path
from reprint import output
from threading import Thread
def timestring(sec):
sec = int(sec)
a = str(int(sec // 3600)).zfill(2)
sec = sec % 3600
b = str(int(sec // 60)).zfill(2)
c = str(int(sec % 60)).zfill(2)
return '{0}:{1}:{2}'.format(a, b, c)
class downloader:
def __init__(self, url, filepath, num_connections=32, overwrite=False):
self.mm = None
self.count = 0
self.recent = deque([0] * 20, maxlen=20)
self.download(url, filepath, num_connections, overwrite)
def multidown(self, url, start, end):
r = requests.get(url, headers={'range': 'bytes={0}-{1}'.format(start, end-1)}, stream=True)
i = start
for chunk in r.iter_content(1048576):
if chunk:
self.mm[i: i+len(chunk)] = chunk
self.count += len(chunk)
i += len(chunk)
def singledown(self, url, path):
with requests.get(url, stream=True) as r:
with path.open('wb') as file:
for chunk in r.iter_content(1048576):
if chunk:
self.count += len(chunk)
file.write(chunk)
def download(self, url, filepath, num_connections=32, overwrite=False):
singlethread = False
threads = []
bcontinue = False
filepath = filepath.replace('\\', '/')
if (not re.match('^[a-zA-Z]:/(((?![<>:"/|?*]).)+((?<![ .])/)?)*$', filepath) or
not Path(filepath[:3]).exists()):
print('Invalid windows file path has been inputted, process will now stop.')
return
path = Path(filepath)
if not path.exists():
bcontinue = True
else:
if path.is_file():
if overwrite:
bcontinue = True
else:
while True:
answer = input(f'`{filepath}` already exists, do you want to overwrite it? \n(Yes, No):').lower()
if answer in ['y', 'yes', 'n', 'no']:
if answer.startswith('y'):
bcontinue = True
break
else:
print('Invalid input detected, retaking input.')
if not bcontinue:
print(f'Overwritting {filepath} has been aborted, process will now stop.')
return
bcontinue = False
head = requests.head(url)
if head.status_code == 200:
bcontinue = True
else:
for i in range(5):
print(f'Failed to connect server, retrying {i + 1} out of 5')
head = requests.head(url)
if head.status_code == 200:
print(f'Connection successful on retry {i + 1}, process will now continue.')
bcontinue = True
break
else:
print(f'Retry {i + 1} out of 5 failed to connect, reattempting in 1 second.')
time.sleep(1)
if not bcontinue:
print("Connection can't be established, can't download target file, process will now stop.")
return
folder = '/'.join(filepath.split('/')[:-1])
Path(folder).mkdir(parents=True, exist_ok=True)
headers = head.headers
total = headers.get('content-length')
if not total:
print(f'Cannot find the total length of the content of {url}, the file will be downloaded using a single thread.')
started = datetime.now()
print('Task started on %s.' % started.strftime('%Y-%m-%d %H:%M:%S'))
th = Thread(target=self.singledown, args=(url, path))
threads.append(th)
th.start()
total = inf
singlethread = True
else:
total = int(total)
code = requests.head(url, headers={'range':'bytes=0-100'}).status_code
if code != 206:
print('Server does not support the `range` parameter, the file will be downloaded using a single thread.')
started = datetime.now()
print('Task started on %s.' % started.strftime('%Y-%m-%d %H:%M:%S'))
th = Thread(target=self.singledown, args=(url, path))
threads.append(th)
th.start()
singlethread = True
else:
path.touch()
file = path.open(mode='wb')
file.seek(total - 1)
file.write(b'\0')
file.close()
file = path.open(mode='r+b')
self.mm = mmap(file.fileno(), 0)
segment = total / num_connections
started = datetime.now()
print('Task started on %s.' % started.strftime('%Y-%m-%d %H:%M:%S'))
for i in range(num_connections):
th = Thread(target=self.multidown, args=(url, int(segment * i), int(segment * (i + 1))))
threads.append(th)
th.start()
downloaded = 0
totalMiB = total / 1048576
speeds = []
interval = 0.025
with output(initial_len=4, interval=0) as dynamic_print:
while True:
status = sum([i.is_alive() for i in threads])
downloaded = self.count
self.recent.append(downloaded)
done = int(100 * downloaded / total)
doneMiB = downloaded / 1048576
gt0 = len([i for i in self.recent if i])
if not gt0:
speed = 0
else:
recent = list(self.recent)[20 - gt0:]
if len(recent) == 1:
speed = recent[0] / 1048576 / interval
else:
diff = [b - a for a, b in zip(recent, recent[1:])]
speed = sum(diff) / len(diff) / 1048576 / interval
speeds.append(speed)
nzspeeds = [i for i in speeds if i]
if nzspeeds:
minspeed = min(nzspeeds)
else:
minspeed = 0
maxspeed = max(speeds)
meanspeed = sum(speeds) / len(speeds)
remaining = totalMiB - doneMiB
dynamic_print[0] = '[{0}{1}] {2}'.format(
'\u2588' * done, '\u00b7' * (100-done), str(done)) + '% completed'
dynamic_print[1] = '{0:.2f} MiB downloaded, {1:.2f} MiB total, {2:.2f} MiB remaining, download speed: {3:.2f} MiB/s'.format(
doneMiB, totalMiB, remaining, speed)
now = datetime.now()
elapsed = timestring((now - started).seconds)
if meanspeed and total != inf:
eta = timestring(remaining / meanspeed)
else:
eta = '99:59:59'
dynamic_print[2] = 'Minimum speed: {0:.2f} MiB/s, average speed: {1:.2f} MiB/s, maximum speed: {2:.2f} MiB/s'.format(minspeed, meanspeed, maxspeed)
dynamic_print[3] = 'Task started on {0}, {1} elapsed, ETA: {2}'.format(
started.strftime('%Y-%m-%d %H:%M:%S'), elapsed, eta)
if status == 0:
ended = datetime.now()
if not singlethread:
self.mm.close()
break
time.sleep(interval)
time_spent = (ended - started).seconds
meanspeed = sum(speeds) / len(speeds)
print('Task completed on {0}, total time elapsed: {1}, average speed: {2:.2f} MiB/s'.format(
ended.strftime('%Y-%m-%d %H:%M:%S'), timestring(time_spent), meanspeed))
if __name__ == '__main__':
d = downloader(*sys.argv[1:])
</code></pre>
<p>Example usage:</p>
<pre><code>PS C:\Windows\System32> downloader (getdownlink 19711382) "D:/Music/Vox Angeli/Irlande/Vox Angeli - New Soul.mp3"
D:/Music/Vox Angeli/Irlande/Vox Angeli - New Soul.mp3 already exists, do you want to overwrite it?
(Yes, No):y
Task started on 2021-08-07 15:17:18.
[████████████████████████████████████████████████████████████████████████████████████████████████████] 100% completed
3.85 MiB downloaded, 3.85 MiB total, 0.00 MiB remaining, download speed: 2.32 MiB/s
Minimum speed: 0.00 MiB/s, mean speed: 14.01 MiB/s, maximum speed: 52.98 MiB/s
Task started on 2021-08-07 15:17:18, 00:00:00 elapsed, ETA: 00:00:00
Task completed on 2021-08-07 15:17:19, total time elapsed: 00:00:00, mean speed: 14.01 MiB/s
</code></pre>
<p>(<code>getdownlink</code> is a Python file that is out of the scope of this review)</p>
<p>The speeds are really high, are the numbers valid? I am using a 100Mbps broadband connection which roughly translates to 11.92MiB/s max download speed, I am not sure if I should trust the numbers, but what is written in the code tells me it is correct.</p>
<p>I want to know whether my code is performant or not, how it can be faster, is 32 connections per download a good practice (I used the limit I have found in most downloaders), and most importantly, I use <code>mmap</code> in this script, I wonder if mmap uses 1MiB physical primary memory for 1MiB of file, in other words, I have 16GiB physical RAM, can I use the same method to download a single file larger than 16GiB?</p>
<p>And I wonder, how can I implement a pause and resume feature, how can I use multithreading to download n (say 4) files simultaneously over a list of files, and how can I display download information for each download?</p>
<hr />
<p>Update:</p>
<p>I have modified my code to allow it download large files, and I have determined that mmap doesn't use 1MiB physical memory per 1MiB file, as evident by my testing.</p>
<p>The following demonstrates usage (I don't know how to pass default parameters to script yet, and the link might become expired):</p>
<pre><code>PS C:\Windows\System32> downloader "http://51.195.5.190/Oceanofgames.com/Running_With_Rifles_Edelweiss_PLAZA.zip?md5=i-0EWKAFXjhhWvF17S8j3A&expires=1630915755" 'D:\Downloads\Running with rifles.zip'
D:/Downloads/Running with rifles.zip already exists, do you want to overwrite it?
(Yes, No):y
Task started on 2021-08-07 16:55:57.
[████████████████████████████████████████████████████████████████████████████████████████████████████] 100% completed
1489.83 MiB downloaded, 1489.83 MiB total, 0.00 MiB remaining, download speed: 22.29 MiB/s
Minimum speed: 0.00 MiB/s, mean speed: 11.66 MiB/s, maximum speed: 160.00 MiB/s
Task started on 2021-08-07 16:55:57, 00:03:04 elapsed, ETA: 00:00:00
Task completed on 2021-08-07 16:59:02, total time elapsed: 00:03:04, mean speed: 11.66 MiB/s
</code></pre>
<p>While it is downloading, the download speed constantly shifts between 0 and a non-zero number, how can I get current download speed?</p>
<hr />
<p>Minor update: made several small improvements, and made the dummy ETA more logical.</p>
<hr />
<p>Major update: used a fixed size deque to keep track of recent sizes within 0.5 second time frame, and use that data to calculate current download speed.</p>
<hr />
<p>Minor update: Updated the minimum speed logic so that if there are non zero speeds the minimum speed will be the minimum of non-zero speeds instead of 0.</p>
<hr />
<p>Final update:</p>
<p>Updated the code so that single thread downloads will also show additional information, and limit the RAM single thread downloading can use.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T13:12:17.757",
"Id": "525106",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] |
[
{
"body": "<p>Here are a few comments on your question and your code, in no particular order:</p>\n<ul>\n<li><p>There is no need to reinvent the wheel when formatting a time (<code>timestring</code> function). Have a look at <a href=\"https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior\" rel=\"nofollow noreferrer\">datetime.date#strftime</a>.</p>\n</li>\n<li><p>Instead of handling the threads yourself, you could probably use a <a href=\"https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.ThreadPool\" rel=\"nofollow noreferrer\">ThreadPool</a> and let it handle the actual thread management.</p>\n</li>\n<li><p>A constructor is expected to only create an instance of a class. Having the constructor of <code>downloader</code> do the actual download is a bit obscure and nasty. An instance should first be created, and the explicitly call a download method.</p>\n</li>\n<li><p>The <a href=\"https://en.m.wikipedia.org/wiki/Cyclomatic_complexity\" rel=\"nofollow noreferrer\">cyclomatic complexity</a> of your <code>download</code> function is about 35. Although the <a href=\"https://softwareengineering.stackexchange.com/questions/194061/cyclomatic-complexity-ranges\">recommended cyclomatic complexity</a> of a method is subject to opinion, I'd say if it's over 10, ot should probably be refactored.</p>\n</li>\n</ul>\n<p>This only means you should separate concerns and levels of abstraction. For example, this piece of code could go into its own method:</p>\n<pre class=\"lang-py prettyprint-override\"><code>filepath = filepath.replace('\\\\', '/')\nif (not re.match('^[a-zA-Z]:/(((?![<>:"/|?*]).)+((?<![ .])/)?)*$', filepath) \n or not Path(filepath[:3]).exists()):\n print('Invalid windows file path has been inputted, process will now stop.')\n return\npath = Path(filepath)\n</code></pre>\n<ul>\n<li><p>If you haven't yet, have a look at <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a>, a general style guide for python code widely followed by the community. For example, class names should start with a capital letter: <code>Downloader</code> instead of <code>downloader</code>.</p>\n</li>\n<li><p>You should consider using <a href=\"https://www.python.org/dev/peps/pep-0484/\" rel=\"nofollow noreferrer\">type hints</a> in your methods, to make them easier to understand. For example:</p>\n</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>def timestring(sec: int) -> str:\n ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T14:08:37.377",
"Id": "525044",
"Score": "0",
"body": "I wrote timestring because timedelta doesn't have strftime method. And the calculated seconds are floats instead of ints, so explicitly set type hint to int will cause the function to raise errors if I don't cast to int before function call, and I don't want to do it outside of function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T16:30:07.793",
"Id": "525048",
"Score": "1",
"body": "Then, if you read the [timedelta documetation](https://docs.python.org/3/library/datetime.html#datetime.timedelta), you'll see their string representation (`str()`) might be exactly what you need. Also, type hints are ignored at runtime, so they will not raise an error. They are used for static analysis and to give the developers a hint on data types"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T05:06:30.730",
"Id": "525092",
"Score": "0",
"body": "I actually first used `str()` representation of `timedelta`, but the result has decimal places after seconds and I don't like it, if you haven't figured out from my code yet, I want integer seconds without decimals, and it simply can't be done with only one `str` conversion."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T13:45:25.677",
"Id": "265828",
"ParentId": "265814",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T07:44:34.200",
"Id": "265814",
"Score": "4",
"Tags": [
"python",
"performance",
"python-3.x",
"multithreading"
],
"Title": "Python multi-connection downloader"
}
|
265814
|
<p>In a recent coding interview I was asked to write a program which takes as input two text lines:</p>
<ul>
<li>The first one represents a graph, formatted as a sequence of undirected edges like <code>[A,B,10] [B,C,4]</code></li>
<li>The second one represents two nodes, between which the shortes path is to be found, and the maximum acceptable distance, formatted like <code>A->C,20</code>.</li>
</ul>
<p>the output is a representation of this shortest path, like <code>A->C</code>.</p>
<pre><code>/*************************
* BEGIN default includes
*************************/
#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <unordered_map>
/*************************
* END default includes
*************************/
#include <unordered_set>
#define DEBUG_QUIET 0
#define DEBUG_INFO 1
#define DEBUG_VERBOSE 2
#define DEBUG DEBUG_QUIET // Edit to change debug output level
#if DEBUG >= DEBUG_VERBOSE
#define PRINT_VERBOSE(x) x
#else
#define PRINT_VERBOSE(x)
#endif
#if DEBUG >= DEBUG_INFO
#define PRINT_INFO(x) x
#else
#define PRINT_INFO(x)
#endif
using namespace std;
class E1 : exception {};
class E2 : exception {};
class E3 : exception {};
class Graph {
public:
/**
* @brief Constructs a graph from a string.
* @param s The first line of input
*/
Graph(const string s) {
string::const_iterator it = s.begin();
bool done = false;
while (!done) {
expect(it,'[');
char n1 = *(it++);
expect(it,',');
char n2 = *(it++);
expect(it,',');
unsigned weight = extractNumber(it, s.end());
expect(it,']');
if (it==s.end()) done = true;
if (!done) expect(it,' ');
PRINT_VERBOSE(cout << "New edge: ["<< n1 << "," << n2 << "," << weight << "] " << endl; )
m_graphMap.insert(make_pair(n1,NeighborSet_t()));
NeighborSet_t* ns1 = &m_graphMap.find(n1)->second;
if (ns1->find(Node_t(n2))!=ns1->end()) { throw E2(); }
ns1->insert(Node_t(n2,weight));
m_graphMap.insert(make_pair(n2,NeighborSet_t()));
NeighborSet_t* ns2 = &m_graphMap.find(n2)->second;
if (ns2->find(Node_t(n1))!=ns2->end()) { throw E2(); }
ns2->insert(Node_t(n1,weight));
}
PRINT_VERBOSE(cout << "Parsing graph string complete" << endl);
}
/**
* @brief Computes the Shortest Path from two points.
* @param s The second line of input
* @return A representation of the Shortest Path according to the specification
*/
string sp(const string s) const {
char start_node, end_node;
unsigned maxdist;
parseSPTstring(s, start_node, end_node, maxdist);
PRINT_INFO(cout << "Searching for path from " << start_node << " to " << end_node << " (maxdist: " << maxdist << ")" << endl);
if (m_graphMap.find(start_node) == m_graphMap.end() || m_graphMap.find(end_node) == m_graphMap.end() )
throw E2(); // Not in graph!
GraphMap_t spt;
MinHeap_t minHeap; // Stores a set of nodes, ordered by distance
minHeap.insert(Node_t(start_node,0)); // Will insert again, but next insert will be ignored
PRINT_INFO( cout << "Initializing minHeap" << endl; )
Visited_t visited;
initMinHeap(start_node, visited, minHeap);
PRINT_INFO( cout << "Computing SPT" << endl; )
buildSPT(minHeap, spt);
PRINT_VERBOSE( visited = Visited_t(); printGraph(start_node,visited,spt); )
PRINT_VERBOSE( cout << "Generating SPT string" << endl; )
visited = Visited_t(); // Reset
return generateSPString(start_node,end_node,visited,spt,maxdist);
}
private:
/**********
* Types
**********/
typedef unordered_set<char> Visited_t;
class Node_t {
public:
const char name;
const unsigned distance;
bool operator== (const Node_t& other) const { return this-> name == other.name; }
bool operator< (const Node_t& other) const {
if (*this==other)
return false; // Same node, reflexively false
else
{
if (this->distance == other.distance)
return this->name < other.name; // Don't care, sort by name
else
return this->distance < other.distance;
}
}
Node_t(char n, unsigned d = UINT_MAX) : name(n), distance(d) {};
};
typedef set<Node_t> NeighborSet_t; // Can't use unordered_set because it needs to be hashable
typedef set<Node_t> MinHeap_t;
typedef unordered_map<char, NeighborSet_t> GraphMap_t;
/*********************************************
* Helper functions for parsing / debugging
*********************************************/
/**
* @brief Throws an exception if it finds unexpected characters.
* @param it An iterator over the input string
* @param c The expected character
*/
static void expect(string::const_iterator& it,char c){
PRINT_VERBOSE( cout << "Expecting '" << c << "', found '" << *it << "' "; )
if (!(c==*it)) throw E1(); // Invalid formatting of the input string
it++;
return;
}
/**
* @brief Useful to extract numbers of arbitraty digits.
* @param start Beginning of digits
* @param end End of the string
* @return The index of the last digit of this number
*/
static unsigned extractNumber(string::const_iterator& start, const string::const_iterator& end) {
string::const_iterator weight_end = find_if(start, end, not1(ptr_fun<int, int>(isdigit)));
unsigned weight;
try {
weight = stoi(string(start,weight_end));
} catch (invalid_argument) {
throw E1(); // Garbage in the input string
}
start = weight_end;
return weight;
}
/**
* @brief Parse path specification.
* @param s The second line of input
* @param start_node Will be overwritten with the start node name
* @param end_node Will be overwritten with the end node name
*/
static void parseSPTstring(const string s, char& start_node, char& end_node, unsigned& maxdist) {
string::const_iterator it = s.begin();
start_node = *(it++);
expect(it, '-');
expect(it, '>');
end_node = *(it++);
expect(it, ',');
maxdist = extractNumber(it, s.end());
if (!(s.end()==it)) throw E1(); // Trailing characters
}
/**
* @brief DFS recursive function to print a graph. For debugging.
* @param node The current root node
* @param visited Unordered set of visited node names
* @param g The graph
*/
static void printGraph(char node, Visited_t& visited, const GraphMap_t& g) {
if (visited.find(node)!=visited.end()){
PRINT_VERBOSE( cout << "Not visiting " << node << " again. "; )
return;
}
PRINT_VERBOSE( cout << "Visit " << node << ". ");
visited.insert(node);
const NeighborSet_t neighborSet = g.at(node);
for ( Node_t n : neighborSet) {
cout << "[" << node << "," << n.name << "," << n.distance << "] ";
printGraph(n.name, visited, g);
}
PRINT_VERBOSE( cout << "Step out " << node << ". " << endl);
}
/**
* @brief Function to print the minHeap. For debugging.
* @param minHeap The minHeap
*/
static void printMinHeap(const MinHeap_t& minHeap) {
for (MinHeap_t::iterator it = minHeap.begin(); it!=minHeap.end(); it++) {
cout << (*it).name << ":" << (*it).distance << "; ";
};
}
/**
* @brief Recursive function to generate a string representing the SP according to the specification.
* @param start_node Char name of the start of the path node
* @param end_node Char name of the end of the path node
* @param visited Unordered set of visited node names. SPT is an ADG, but may still print the same node multiple times
* @param spt Acyclic, directed graph representing the Shortest Path Tree
* @param maxdist Maximum allowed distance from the start node
* @return The string representation of the SP
*/
static string generateSPString(const char start_node, const char end_node, Visited_t& visited, GraphMap_t& spt, const unsigned maxdist){
if (visited.find(start_node)!=visited.end()){
PRINT_VERBOSE( cout << "Not visiting " << start_node << " again. "; )
return "";
}
PRINT_VERBOSE( cout << "Visit " << start_node << ". "; )
visited.insert(start_node);
stringstream ss;
if (start_node==end_node) {
ss << end_node;
return ss.str();
}
const NeighborSet_t neighborSet = spt.at(start_node);
if (neighborSet.empty()) return "";
for ( Node_t n : neighborSet) {
if (n.name==end_node) {
if (n.distance>maxdist)
throw E3();
}
ss << generateSPString(n.name, end_node, visited, spt, maxdist);
}
PRINT_VERBOSE( cout << "Step outside " << start_node << ". "; )
stringstream ss2;
if (!ss.str().empty())
ss2 << start_node << "->" << ss.str();
else
ss2 << ss.str();
PRINT_VERBOSE( cout << "Returning '" << ss2.str() << "'. "; )
return ss2.str();
}
/*************************
* Dijkstra Implementation
*************************/
/**
* @brief Recursive DFS to populate the minHeap.
* @param node Current root note
* @param visited Unordered set of already visited node names, to avoid loops since the graph is undirected
* @param minHeap The minHeap to be generated
*/
void initMinHeap(const char node, Visited_t& visited, MinHeap_t& minHeap) const{
if (visited.find(node)!=visited.end()){
PRINT_VERBOSE(cout << "Not visiting " << node << " again. ");
return;
}
PRINT_VERBOSE( cout << "Visit " << node << ". ");
visited.insert(node);
PRINT_VERBOSE( cout << "Add " << node << " to minHeap. ");
minHeap.insert(Node_t(node,UINT_MAX));
NeighborSet_t neighborSet = m_graphMap.at(node);
for ( Node_t n : neighborSet) {
initMinHeap(n.name, visited, minHeap);
}
PRINT_VERBOSE(cout << "Step out " << node << ". " << endl);
}
/**
* @brief Computes the SPT from the minHeap.
* @param minHeap The minHeap
* @param spt The SPT
*/
void buildSPT(MinHeap_t& minHeap, GraphMap_t& spt) const{
while (!minHeap.empty()) {
Node_t minNode = *(minHeap.begin());
PRINT_VERBOSE( cout << "Closest neighbor is " << minNode.name << ", dist: " << minNode.distance << ", deleting from minHeap. "; cout << endl; )
minHeap.erase(minHeap.find(minNode));
PRINT_VERBOSE( cout << "MinHeap: "; printMinHeap(minHeap); )
spt.insert(make_pair(minNode.name,NeighborSet_t()));
for (Node_t n : m_graphMap.at(minNode.name)) {
PRINT_VERBOSE( cout << "Find node " << n.name << "... "; )
MinHeap_t::iterator i = minHeap.find(Node_t(n.name));
if (i==minHeap.end()) {
PRINT_VERBOSE( cout << "not in minHeap, skipping. "; )
continue;
}
unsigned newDist = minNode.distance+n.distance;
if (newDist>(*i).distance){
PRINT_VERBOSE( cout << "New distance (" << newDist << ") is greater than the current one (" << (*i).distance << "). Continue."; )
continue;
}
PRINT_VERBOSE(cout << "Delete node " << (*i).name << ", distance " << (*i).distance << ". "; )
minHeap.erase(i);
PRINT_VERBOSE( cout << "MinHeap after erase: "; printMinHeap(minHeap); cout; )
PRINT_VERBOSE( cout << "Insert node " << n.name << ", distance " << newDist << ". "; )
minHeap.insert(Node_t(n.name,newDist));
PRINT_VERBOSE( cout << "MinHeap after insert: "; printMinHeap(minHeap); )
spt[minNode.name].insert(Node_t(i->name,newDist)); // Store the distance in the dual graph
}
PRINT_VERBOSE( cout << endl; )
}
PRINT_VERBOSE(cout << "SPT done." << endl; )
}
/*
* Members
*/
GraphMap_t m_graphMap = GraphMap_t();
};
int main() {
string edgeString;
getline(cin,edgeString);
string pathString;
getline(cin,pathString);
PRINT_INFO( cout << edgeString << endl << pathString << endl; )
try {
const Graph g = Graph(edgeString);
string spt = g.sp(pathString);
if (spt.empty()) {
cout << "E3";
return 0;
}
cout << spt << endl;
} catch (E1) {
cout << "E1" << endl;
return 0;
} catch (E2) {
cout << "E2" << endl;
return 0;
} catch (E3) {
cout << "E3" << endl;
return 0;
}
return 0;
}
</code></pre>
<p>My code was an implementation of the Dijkstra algorithm with min heap, which I thought was the most efficient algorithm for this problem, and I was passing all tests; nevertheless, I failed the interview.</p>
<p>How does my code look?</p>
|
[] |
[
{
"body": "<p>Do you <em>really</em> use all these?:</p>\n<blockquote>\n<pre><code>#include <map>\n#include <set>\n#include <list>\n#include <cmath>\n#include <ctime>\n#include <deque>\n#include <queue>\n#include <stack>\n#include <string>\n#include <bitset>\n#include <cstdio>\n#include <limits>\n#include <vector>\n#include <climits>\n#include <cstring>\n#include <cstdlib>\n#include <fstream>\n#include <numeric>\n#include <sstream>\n#include <iostream>\n#include <algorithm>\n#include <unordered_map>\n</code></pre>\n</blockquote>\n<p>Such a large list of includes can often be a sign of too many different responsibilities for a single translation unit. Or of a developer too lazy to actually consider what's required.</p>\n<hr />\n<blockquote>\n<pre><code>using namespace std;\n</code></pre>\n</blockquote>\n<p>Throwing away all the benefits of namespaces and piling the whole of <code>std</code> into the global namespace is an instant review fail in many (most?) development teams.</p>\n<hr />\n<pre><code>#define DEBUG DEBUG_QUIET // Edit to change debug output level\n\n#if DEBUG >= DEBUG_VERBOSE\n#define PRINT_VERBOSE(x) x\n#else \n#define PRINT_VERBOSE(x)\n#endif\n#if DEBUG >= DEBUG_INFO\n#define PRINT_INFO(x) x\n#else \n#define PRINT_INFO(x)\n#endif\n</code></pre>\n<p>I have to <em>recompile</em> just to change the debugging level??</p>\n<p>And you're introducing macros that can't be used like functions - avoid that unless there's no alternative.</p>\n<hr />\n<blockquote>\n<pre><code>class E1 : exception {};\nclass E2 : exception {};\nclass E3 : exception {};\n</code></pre>\n</blockquote>\n<p>Those are the least informative class names I've seen for some time. And why the <em>private</em> inheritance?</p>\n<hr />\n<p>At this point I'd seen enough, and didn't bother reading the rest.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T19:58:59.537",
"Id": "525061",
"Score": "0",
"body": "1. These where the default includes, I didn't remove them.\n\n2. Same, that code was already there.\n\n3. I thought it would be good to opt out of that code and not compile it if not required\n\n4. I didn't choose those; these where in the specification, and tests would check against those names.\n\nThank you for your answer, but 3 out of 4 points where not my choice. Maybe I was expected to remove that code and I didn't."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T10:25:51.627",
"Id": "265819",
"ParentId": "265816",
"Score": "3"
}
},
{
"body": "<p>Intro code:</p>\n<p>There's a lot of "instant fail"s here:</p>\n<ul>\n<li><p>Include only the headers you need!</p>\n</li>\n<li><p>Debugging macros are probably not acceptable for something like this. We can step through in a debugger if we need to manually check what's happening in the code. If we want to "prove" that the code is working correctly, we should use unit tests.</p>\n<p>The macros make the code a <em>lot</em> harder to read and maintain.</p>\n</li>\n<li><p><code>using namespace std;</code> This leads to namespace collisions. Don't do it.</p>\n</li>\n<li><p><code>class E1 : exception {};</code> Not a helpful name. Try <code>InvalidInputException</code> or something similar.</p>\n</li>\n</ul>\n<hr />\n<p>Graph class constructor:</p>\n<ul>\n<li><p><code>Graph(const string s)</code> That's an unnecessary string copy. We should pass a <code>const std::string&</code>.</p>\n</li>\n<li><p>The parsing code shouldn't be part of the <code>Graph</code> class. If we want to add a different text format later, we shouldn't have to change the <code>Graph</code> class.</p>\n<p>The <code>Graph</code> could be a simple <code>struct</code> containing only data. The parsing could be done by a set of free (non-member) functions.</p>\n</li>\n<li><p><code>expect(it,'[');</code> If <code>it</code> is at the <code>end()</code> of the string, dereferencing it will cause undefined behavior.</p>\n</li>\n<li>\n<pre><code> m_graphMap.insert(make_pair(n1,NeighborSet_t()));\n NeighborSet_t* ns1 = &m_graphMap.find(n1)->second;\n if (ns1->find(Node_t(n2))!=ns1->end()) { throw E2(); }\n ns1->insert(Node_t(n2,weight));\n</code></pre>\n<p><code>insert</code> returns an iterator to the inserted element (or the one that prevented insertion), so we shouldn't need to find it again straight afterwards.</p>\n<p>Consider using <code>operator[]</code> instead. With a few minor changes the above might be condensed to: <code>m_graphMap[n1][n2].distance = weight;</code></p>\n</li>\n<li><p>Is there actually a reason to store the neighbours as a <code>set</code>, instead of a <code>std::vector<std::pair<char, unsigned int>></code>?</p>\n</li>\n</ul>\n<hr />\n<p>Dijkstra implementation:</p>\n<ul>\n<li><p><code>sp()</code> should be called <code>findShortestPath()</code> or something equally meaningful.</p>\n</li>\n<li><p><code>string sp(const string s) const</code>. Again, an unnecessary string copy.</p>\n</li>\n<li><p>Again, the parsing of the user input should be done separately, and not in the graph class, or in the <code>findShortestPath</code> function.</p>\n</li>\n<li><p>Note that the <code>findShortestPath</code> function should also be separate from the <code>Graph</code> class. (It's good that you're not storing any data from the path finding inside the <code>Graph</code> class as members, but we could separate the function (and typedefs) entirely).</p>\n</li>\n<li><p><code>void initMinHeap(const char node, Visited_t& visited, MinHeap_t& minHeap)</code> It looks like this recursively adds every node in the graph onto the min heap. We don't need to do that!</p>\n<p>Since we have a fixed destination node, we shouldn't process the entire graph. We want to pick the closest node off the queue and check if it's the one we're looking for. If not, we add its neighbours to the queue and then check the next closest node.</p>\n</li>\n<li>\n<pre><code> NeighborSet_t neighborSet = m_graphMap.at(node);\n</code></pre>\n<p>This copies an entire <code>std::set</code> unnecessarily.</p>\n</li>\n<li>\n<pre><code> Node_t minNode = *(minHeap.begin());\n minHeap.erase(minHeap.find(minNode));\n</code></pre>\n<p>We already know where the element we want to remove is, so we shouldn't have to call <code>find</code>.</p>\n</li>\n</ul>\n<hr />\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T20:05:05.597",
"Id": "525063",
"Score": "0",
"body": "Thank you very much for your very thorough answer! The headers where already there; I didn't remove them. Same as `using namespace std`. Maybe I was expected to figure it out? Exception names where used by the unit tests, so I didn't have a saying in those."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T11:41:32.850",
"Id": "265824",
"ParentId": "265816",
"Score": "7"
}
},
{
"body": "<p>In addition to user673679 and Toby Speight's answers, here are a few more issues:</p>\n<h1>Use a consistent code style</h1>\n<p>Sometimes I see spaces around commas, sometimes not, the body of <code>if</code> statements is sometimes on the same line, sometimes on separate lines. It makes the code messy to look at. The least you can do is run it through some automated code formatting; either your editor can do it, or you can use an external tool like <a href=\"http://astyle.sourceforge.net/\" rel=\"nofollow noreferrer\">Artistic Style</a> or <a href=\"https://clang.llvm.org/docs/ClangFormat.html\" rel=\"nofollow noreferrer\">ClangFormat</a>.</p>\n<p>In particular, make sure every statement is on a separate line, add spaces around operators and after commas, and don't be afraid to separate segments of code with empty lines.</p>\n<h1>Improve the Doxygen documentation</h1>\n<p>It's great that you documented the code using Doxygen! There are a few slight improvements you could make though:</p>\n<p>If you pass something by non-const reference or non-const pointer, be sure to add <code>[in]</code>, <code>[out]</code> or <code>[in,out]</code> annotations to the parameters in the Doxygen comments.</p>\n<p>Also ensure you add a Doxygen header for each <code>class</code> itself, not just for its member variabels and functions. Describe what the class is meant to represent.</p>\n<h1>Use <code>emplace()</code> where appropriate</h1>\n<p>If you use <code>emplace()</code> instead of <code>insert()</code>, you don't have to call <code>make_pair()</code> or explicitly construct a type:</p>\n<pre><code>m_graphMap.emplace(n1, NeighborSet_t());\n...\nns1->emplace(n2,weight);\n</code></pre>\n<h1>Avoid useless braces, parentheses, etc.</h1>\n<p>There are a few uses of unnecessary syntax that makes the code just harder to read. For example:</p>\n<ul>\n<li><code>*(it++)</code> -> <code>*it++</code></li>\n<li><code>!(c==*it)</code> -> <code>c != *it</code></li>\n<li><code>(*i).distance</code> -> <code>i->distance</code></li>\n</ul>\n<p>Your use of <code>this-></code> is unnecessary, but in the case of the binary operator overloads, it's actually a nice way to keep expressions symmetric and clearly indicate which side's member variable you are using.</p>\n<h1>Missed opportunities for using range-<code>for</code> loops</h1>\n<p>In <code>printMinHeap</code>, you could write:</p>\n<pre><code>for (auto &item: minHeap)\n std::cout << item.name << ": " << item.distance << "; ";\n</code></pre>\n<h1>Make <code>Node_t</code> hashable</h1>\n<p>You wrote you couldn't use a <code>std::unordered_set</code> for <code>NeighborSet_t</code> because "it needs to be hashable". So why not make it hashable? You already had to overload <code>operator<</code> to make it comparable so it could be used in a <code>std::set</code>. There's two ways to approach this:</p>\n<ol>\n<li>Pass a hash function as a parameter to <a href=\"https://en.cppreference.com/w/cpp/container/unordered_set\" rel=\"nofollow noreferrer\"><code>std::unordered_set</code></a>.</li>\n<li>Overload <a href=\"https://en.cppreference.com/w/cpp/utility/hash\" rel=\"nofollow noreferrer\"><code>std::hash</code></a> to be able to produce a hash for <code>Node_t</code>.</li>\n</ol>\n<h1>Use of <code>stringstream</code>s</h1>\n<p>A <code>std::stringstream</code> is helpful if you are adding a lot of data to it, but if you convert to and from <code>std::string</code>s a lot, any performance benefit is lost. This is exactly what you do in <code>generateSPString()</code>. Better would be to pass if you pass it an <code>std::stringstream</code> by reference, and have it add to that, but that requires you being able to write everything sequentially, but currently you also want to prepend things to the string. In that case, maybe just use <code>std::string</code> for everything.</p>\n<h1>Better printing functions</h1>\n<p>You have functions like <code>printGraph()</code> that are hardcoded to print to <code>std::cout</code>. Better would be to pass a <code>std::ostream</code> reference to the functions, so they can print to that:</p>\n<pre><code>static void printGraph(std::ostream &out, ...) {\n ...\n out << "[" << ...;\n ...\n}\n</code></pre>\n<p>You can also create an overload for <code>operator<<</code> (see <a href=\"https://www.learncpp.com/cpp-tutorial/overloading-the-io-operators/\" rel=\"nofollow noreferrer\">this tutorial</a>) so you can write this:</p>\n<pre><code>Graph g(...);\nstd::cout << g;\n</code></pre>\n<h1>Use <code>'\\n'</code> instead of <code>std::endl</code></h1>\n<p>Prefer using <a href=\"https://stackoverflow.com/questions/213907/stdendl-vs-n\"><code>'\\n'</code> instead of <code>std::endl</code></a>; the latter is equivalent to the former, but also forces the output to be flushed. That is usually not necessary, and comes with a performance overhead.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T20:08:29.143",
"Id": "525064",
"Score": "0",
"body": "Thank you, very useful remarks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T13:18:53.560",
"Id": "265826",
"ParentId": "265816",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T09:15:43.590",
"Id": "265816",
"Score": "4",
"Tags": [
"c++",
"interview-questions",
"graph",
"c++14",
"pathfinding"
],
"Title": "Compute shortest path in undirected graph"
}
|
265816
|
<p>I've been looking at the way the native queries are written in my project and it just seems overengineered in my perspective. Writing a native query should be simple. Can someone suggest the right/simple way to write native queries? Here is how it is written as of now:</p>
<p><strong>Repository</strong></p>
<pre><code>package com.fsap.aap.aml.external.actone.repository;
import com.fsap.aap.aml.external.actone.domain.dto.ActOneDetailsDto;
import com.fsap.aap.aml.external.actone.domain.entity.ActOneDetailsEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.math.BigInteger;
import java.util.List;
import java.util.Set;
/**
* Represents actone details repository
*
* Created by Saransh Bansal on 29/05/2021.
*/
public interface ActOneDetailsRepository extends JpaRepository<ActOneDetailsEntity, BigInteger>, JpaSpecificationExecutor<ActOneDetailsEntity> {
/**
* Searches customer's actone details.
*
* @param cins list of target customer ids
* @return {@link List} of {@link ActOneDetailsDto}
*/
@Query(nativeQuery = true)
List<ActOneDetailsDto> findCustomerActOneDetailsByCins(@Param("cins") Set<String> cins);
}
</code></pre>
<p><strong>Entity</strong></p>
<pre><code>package com.fsap.aap.aml.external.actone.domain.entity;
import com.fsap.aap.aml.external.actone.domain.dto.ActOneDetailsDto;
import javax.persistence.*;
import java.io.Serializable;
import java.math.BigInteger;
import static com.fsap.aap.aml.external.actone.repository.NativeQuery.FIND_ACTONE_DETAILS_BY_CINS;
/**
* Represent actone related metadata for a customer
*
* Created by Saransh Bansal on 01/04/2021.
*/
@Entity
@SqlResultSetMapping(
name = "customerActOneDetailsByCinsDateMapping",
classes = {
@ConstructorResult(
targetClass = ActOneDetailsDto.class,
columns = {
@ColumnResult(name = "cin", type = String.class),
@ColumnResult(name = "alertType", type = String.class),
@ColumnResult(name = "alertSubtype", type = String.class),
@ColumnResult(name = "alertLegislationType", type = String.class),
@ColumnResult(name = "isSarAlert", type = Boolean.class),
@ColumnResult(name = "isSarDisclosed", type = Boolean.class)
}
)
}
)
@NamedNativeQuery(
name = "ActOneDetailsEntity.findCustomerActOneDetailsByCins",
query = FIND_ACTONE_DETAILS_BY_CINS,
resultSetMapping = "customerActOneDetailsByCinsDateMapping"
)
public class ActOneDetailsEntity implements Serializable {
private static final long serialVersionUID = 3849856394509637108L;
@Id
private BigInteger id;
}
</code></pre>
<p><strong>NativeQuery class</strong></p>
<pre><code>package com.fsap.aap.aml.external.actone.repository;
/**
* Static native queries for actone
*
* Created by Saransh Bansal on 29/05/2021.
*/
public final class NativeQuery {
public static final String FIND_ACTONE_DETAILS_BY_CINS = "SELECT DISTINCT" +
" pers.p16 AS cin," +
" al.p37 AS alertType," +
" al.p35 AS alertSubtype," +
" al.p34 AS alertLegislationType," +
" CASE WHEN form_identifier IS NOT NULL THEN 1 ELSE 0" +
" END AS isSarAlert," +
" CASE WHEN forms.date_filing IS NOT NULL THEN 1 ELSE 0" +
" END AS isSarDisclosed" +
"FROM" +
" actone_owner.v_acm_items pers" +
" LEFT OUTER JOIN actone_owner.v_acm_relations rel ON rel.child_join_id = pers.item_join_id" +
" LEFT OUTER JOIN actone_owner.v_acm_items al ON rel.parent_join_id = al.item_join_id" +
" LEFT OUTER JOIN impl_owner.impl_relation_entity2alert asso ON asso.alert_id = al.item_id" +
" AND asso.customer_key = pers.item_id " +
" LEFT OUTER JOIN actone_owner.v_acm_business_units2 bus ON bus.bu_join_id = al.bu_join_id" +
" LEFT OUTER JOIN actone_owner.v_acm_relations ca_al ON al.item_join_id = ca_al.child_join_id" +
" LEFT OUTER JOIN actone_owner.v_acm_items cases ON ca_al.parent_join_id = cases.item_join_id" +
" LEFT OUTER JOIN actone_owner.acm_forms forms ON forms.alert_internal_id = cases.item_join_id" +
" LEFT OUTER JOIN actone_owner.acm_form_custom_attributes forms_cus ON forms.form_internal_id = forms_cus.form_internal_id" +
" LEFT OUTER JOIN actone_owner.v_acm_item_attachments_content docs ON docs.item_join_id = cases.item_join_id " +
"WHERE" +
" al.item_date >= add_months(sysdate, -24) AND UPPER(pers.item_id) LIKE 'PERS%' AND al.item_id IS NOT NULL " +
" AND pers.p16 IN :cins " +
"GROUP BY cin";
private NativeQuery() {
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T20:01:34.080",
"Id": "525476",
"Score": "0",
"body": "I would have done at Repository level. It's closer to @Query , easily visible . If entity grows and so does querying methods , over the period of time it became cumbersome to easily maintain Repository Layer."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T10:07:41.627",
"Id": "265817",
"Score": "0",
"Tags": [
"java",
"hibernate",
"jpa"
],
"Title": "What is the right way to write a native query in Spring JPA?"
}
|
265817
|
<p>Some background: JavaScript is not my primary language, so I'm looking to get some constructive criticism here.</p>
<p>I built a tiny single page HTML app that pretty prints JSON text. It's very useful when I am looking a process logs that dump JSON without pretty printing.</p>
<p>In my tool, I added a checkbox to optionally sort the keys for all JSON objects.</p>
<p>To be clear, I am only targetting the most modern browsers, so please assume the latest and greatest of JavaScript is available.</p>
<pre><code>function _sort_keys_deeply(json_thing)
{
if (false === _is_sortable(json_thing))
{
return json_thing;
}
if (Array.isArray(json_thing))
{
for (var i = 0; i < json_thing.length; ++i)
{
const val = json_thing[i];
if (_is_sortable(val))
{
const val2 = _sort_keys_deeply(val);
json_thing[i] = val2;
}
}
return json_thing;
}
// else: object
const sorted_obj = _sort_object_keys(json_thing);
const key_arr = Object.keys(sorted_obj);
for (var i = 0; i < key_arr.length; ++i)
{
const key = key_arr[i];
const val = sorted_obj[key];
if (_is_sortable(val))
{
const val2 = _sort_keys_deeply(val);
sorted_obj[key] = val2;
}
}
return sorted_obj;
}
function _is_sortable(z)
{
// Beware: null is type object, but is not sortable.
const x = (null !== z) && ('object' === typeof(z) || Array.isArray(z));
return x;
}
// Ref: https://stackoverflow.com/a/31102605/257299
function _sort_object_keys(obj)
{
const key_arr = Object.keys(obj);
// In-place array sort
key_arr.sort();
// Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
const f =
function(new_obj2, key/*, index, array*/)
{
new_obj2[key] = obj[key];
return new_obj2;
};
const new_obj = {};
key_arr.reduce(f, new_obj);
return new_obj;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T16:48:57.823",
"Id": "525049",
"Score": "1",
"body": "`Array.sort()` can sort `null` if done so explicitly in a `compareFunction` passed into `sort()`. [See MDN documentation.](https://developer.mozilla.org/en-US/docs/web/javascript/reference/global_objects/array/sort)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T17:14:40.720",
"Id": "525053",
"Score": "1",
"body": "`false === _is_sortable(json_thing)` -> left-handed boolean comparison! ... 15 yr dormant PTSD nightmares returning! A former C programmer? Nostalgia? Seriously, just curious why. Has ES5 or beyond not fixed the need for this? The world wonders"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T12:05:50.887",
"Id": "525154",
"Score": "0",
"body": "@radarbob Fair question. Previously, I worked with finance quants. In a shared code-base, we stopped using the not operator (!) because it was too easy to miss in very dense formulas. Instead, we switched to explicit left-side boolean testing which was (is!) horribly ugly, but much harder to miss. Over the long term, I found it helped to reduce boolean logic bugs, so I kept doing it in other situations."
}
] |
[
{
"body": "<p>This code was well-commented and easy enough to figure out. Well done on that front.</p>\n<p>Stylistic notes:</p>\n<ul>\n<li>In JS it's idiomatic to use <code>camelCase</code>, not <code>snake_case</code>.</li>\n<li>This code is formatted like C# code. In JS, open brace on same line is more common.</li>\n<li>Feel free to leave out the semi-colons.</li>\n</ul>\n<p>Design notes:</p>\n<ul>\n<li>You can make the small helper functions one-liners and define them <em>within</em> the main function. This way, conceptually, you'll be writing a single function to solve a single problem.</li>\n<li>In my rewrite below, I've left off the braces on the single-statement <code>if</code>s. That's a personal preference but makes some people uneasy. Feel free to add them back.</li>\n</ul>\n<p>Here is my attempt at a rewrite based on these notes. Let me know if I've unwittingly changed any behavior:</p>\n<pre><code>function sorted(o) {\n const isObj = x => typeof(x) === 'object'\n const isArr = Array.isArray\n\n // Beware: null is type object, but is not sortable.\n const isSortable = x => (x !== null) && (isObj(x) || isArr(x))\n\n if (!isSortable(o))\n return o\n\n if (isArr(o))\n return o.map(sorted)\n\n if (isObj(o))\n return Object.keys(o).sort().reduce(\n (m, x) => (m[x] = isSortable(o[x]) ? sorted(o[x]) : o[x], m),\n {}\n )\n}\n</code></pre>\n<p><a href=\"https://tio.run/##XVDLboMwELzzFZNLYksEqenNEq36BTn0GOVgg1NBACNjKhDh2@kakgblYu9jdnZncvkrm8RmtdsrqXSxr0yqp@nSVonLTIXGWKdTZjiGAEhM1ThkzVHliNEh/oDra20urOOI4xg7o3KduN0K@2UtYemVfTRnsl91v4lfqkI/6FiHDfFUbVFwbLdg8zJPf7stZBTzgBiyC9jmSUAncqoCVrvWVjAPzDL02o1KWbNFHH8i/aoX5HEWFF1131Ar8iOMR1anbaLZDARYGcIbQOeXp@5MWtZ3UYXj89/JORXwf4iSh3eOYZwDHoxBQE5ggBKHEFK8hUgEBqUEKJRSHMYQqcCJsuFeFPDF9/MYeF9NoaPC/Nzleb@m6Q8\" rel=\"nofollow noreferrer\" title=\"JavaScript (Babel Node) – Try It Online\">Try it online!</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T12:08:32.883",
"Id": "525155",
"Score": "0",
"body": "Wow, this is an amazing refactoring. Very elegant. Thank you to teach. My only concern is the assignment + test in the same expression: `(m, x) => (m[x] = isSortable(o[x]) ? ...` Those are a bit dangerous in my experience!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T13:57:21.793",
"Id": "525162",
"Score": "1",
"body": "Thanks. I know some people don't like ternaries, but my rule is that as long as they aren't nested, each branch is a simple expression, and they fit comfortably on one line, they are a good thing. That said, if you don't agree you can rewrite like so: (cont)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T13:57:27.013",
"Id": "525164",
"Score": "1",
"body": "[Try it online!](https://tio.run/##ZVHLboMwELzzFZNLYksEqenNEpH6BTn0GOVgg1ORGhwZU4EI307XQB5qfbDWM@Px7vgif2SdueLqt0oqbbaVzfU4npsq84WtUFvndc4sRx8Bma1qj6I@qAtStEj38N1V2zNrOdI0xcaqi8785kX74RxpaZddMp1k98J@kr9URt/tWIsV@VSNMRzrNdj0WLC/3WYzqnlEDsUZbPU0oBY5oYDTvnEV7F0zX/rLJqW8snk4/lSGp/4oD9NAybfuaqKScIXxxOm8yTSbhAArY4QA9lNI85oNn90d29NiPK@SABr6nm@gH6w2tf4vDZoHunRXLsAQL0U/TAWPhiiiQNFDiV0MKd5iZAK9UgJUSil2Q4xc4EinfgEFAvh@GqLwPdboxNivJaUQ@zj@Ag \"JavaScript (Babel Node) – Try It Online\")"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T13:59:59.463",
"Id": "525165",
"Score": "1",
"body": "Thanks, I checked your second link: Wow, the ternary really makes a difference! I guess I will keep it and add a comment to the code \"beware\". :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T18:48:00.047",
"Id": "525185",
"Score": "0",
"body": "*... formatted like C#* :: Line breaking a JS statement with a \"dangling operator\" (opening brace, boolean operator, etc.) prevents possible JS mis-interpretation. [And no one seems to use explicit \" ; \" anymore](https://www.freecodecamp.org/news/codebyte-why-are-explicit-semicolons-important-in-javascript-49550bea0b82/). I've been bitten by these at one time or another."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T19:23:21.300",
"Id": "525186",
"Score": "0",
"body": "I was referring to the open brace on own line with the C# comment. As for semi-colons, the examples in that article are silly imo. The 2nd example is something you wouldn't ever write, and the 1st is something very few people would ever do by mistake. It's [perfectly fine](https://www.youtube.com/watch?v=Qlr-FGbhKaI&t=13s) to leave them out, and I recommend doing so."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T19:28:32.587",
"Id": "525187",
"Score": "1",
"body": "up-ed for formatting and ternary use. Here, testing exceptional cases up front erases complexity such that code reading and understanding shines from good formatting. Surrounding control blocks with whitespace is essential IMO. Brace-less one liner `if`s are elegant *and definitely aid quick understanding*. The ternary's beauty is it's counterintuitive understandability. With *disciplined formatting*, control logic is spatial expressed and even nesting, 1 deep anyway, can manifest this property. Nothing here is absolute."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T20:22:32.703",
"Id": "265835",
"ParentId": "265820",
"Score": "4"
}
},
{
"body": "<h2>JSON</h2>\n<p>JSON is a not a thing, it is a transport file format, held in memory as a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. String\">String</a>\nIn JavaScript it is parsed using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse\" rel=\"nofollow noreferrer\" title=\"MDN Web API's JSON parse\">JSON.parse</a> and the result is an <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Object\">Object</a>.\nTo refer to an object as a <code>json_thing</code> is incorrect (yes its a "thing") but it's not a string or blob formatted to as JSON.</p>\n<p>The only thing that makes an object unique when created from a JSON string is that you are guaranteed not to have cyclic references.</p>\n<h2>General notes.</h2>\n<p>There is a lot of code noise in your code. Code noise is anything that does not contribute to the algorithm process</p>\n<p>You modify the array in place, but you copy objects. Best if you treat arrays and objects the same, either in place or as a copy. The rewrites give examples of both</p>\n<h2>Call stack overflow</h2>\n<p>JavaScript uses a call stack (as do most languages) unfortunately almost all JavaScript implementations do not recognize tail calls (even though its part of the ECMAScript6 standard) meaning that recursion is dangerous.</p>\n<p>There is no way to know how deep the call stack is, nor how deep you must go to complete the task. Always be wary of this when creating recursive code.</p>\n<p>The rewrites gives an example of a non recursive solution that can process a much deeper object than a recursive function can.</p>\n<h2>Code style</h2>\n<ul>\n<li><p>Declare variable at top of function as this is where variables declared as <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. var\">var</a> are created. Function declaration (eg <code>function name(){}</code>) are also hoisted to the top of their scope in JavaScript.</p>\n<p><strong>Note</strong> that <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. let\">let</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. const\">const</a> are block scope <code>{/*block*/}</code> and are not hoisted to the top of their scope. You can not use them before they are declared.</p>\n</li>\n<li><p>If you don't need the index use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. for...of\">for...of</a> of loop rather than a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. for\">for</a> loop.</p>\n<p><strong>Note</strong> Using callback iterators can add overhead to processing and are generals slower than for loops.</p>\n</li>\n<li><p>Avoid single use variables unless they help keep the code clean.</p>\n</li>\n<li><p>JavaScript logical operators always execute in the same order (unlike C/C++) and can thus be used to reduce code noise via short circuit syntax style. Eg <code>if (foo) { foo = 0 }</code> can be <code>foo && (foo = 0);</code></p>\n<p><strong>Note</strong> that the <code>()</code> around the second (3rd etc...) logical clause is required if there is an assignment operator within a short circuit expression.</p>\n<p><strong>Note</strong> you can not short circuit flow control eg <code>foo && return</code> is illegal. Same for <code>break</code>, <code>continue</code>, <code>if</code>, <code>for</code> etc...</p>\n<p>As the order of logical and grouped expressions / statements is always the same you can optimize them using most likely outcome. eg testing <code>z !== null && typeof z === "object"</code> can be optimized as <code>typeof z === "object" && z !== null</code> as it is far more likely that z is not an object than it being <code>null</code></p>\n</li>\n<li><p>Use the short form/style when you can. Eg <code>if (false === isSortable(obj)) {</code> can be <code>if (!isSortable(obj)) {</code></p>\n</li>\n<li><p>Function arguments are function scoped and writeable (almost identical to <code>var</code>). Reuse them if it helps reduce code noise.</p>\n</li>\n<li><p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Object keys\">Object.keys</a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Object entries\">Object.entries</a> <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Object values\">Object.values</a> works on <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Array\">Array</a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Object\">Object</a>, and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. String\">String</a> thus you do not need to treat object and array separately.</p>\n</li>\n<li><p>Array is a <code>typeof</code> <code>"object"</code>. The <code>Array.isArray</code> in <code>isSortable</code> is redundant.</p>\n<p>Note that <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. typeof\">typeof</a> is a JavaScript operator and not a function. <code>typeof(z)</code> is the same as <code>typeof z</code> the grouping operator has no effect in this case</p>\n</li>\n<li><p>You can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Object fromEntries\">Object.fromEntries</a> to create an object from an array of key, name pairs. <code>Object.fromEntries([["A", 1], ["B", 2]])</code> will define an object <code>{A:1, B:1}</code></p>\n</li>\n</ul>\n<h2>Rewrite</h2>\n<p>Rewrite removes the code noise and redundant code.</p>\n<p>I have provided three versions.</p>\n<ol>\n<li><p>uses recursion and creates a copy of objects that are sorted. This rewrite is the only one the matches you function`s behavior</p>\n</li>\n<li><p>uses a stack and sorts object keys in place. Only arrays and object are pushed to the stack.</p>\n</li>\n<li><p>Same as 2 but checks for cyclic references and as such is the only rewrite safe to use.</p>\n</li>\n</ol>\n<p><strong>NOTE</strong> ONLY use the first two on objects that do not have cyclic references. The recursive example will throw an error very quickly, the second will need to use up memory before it has a problem (this will lock the page as it chews up memory), and then depending on the engine could crash the page/thread or throw an error.</p>\n<h3>Recursive</h3>\n<pre><code>function sortKeysDeeply(obj) {\n if (isObj(obj)) {\n !Array.isArray(obj) && (obj = sortObjectKeys(obj));\n for (const [key, val] of Object.entries(sorted)) {\n isObj(val) && (obj[key] = sortKeysDeeply(val));\n }\n }\n return obj;\n}\n</code></pre>\n<h3>Using a stack</h3>\n<pre><code>function sortKeysDeeply(obj) {\n const stack = [];\n if (isObj(obj)) {\n stack.push(obj);\n while (stack.length) {\n let o = stack.pop();\n o = !Array.isArray(o) && sortInPlaceObjectKeys(o);\n for (const val of Object.values(o)) { isObj(val) && stack.push(val) }\n }\n }\n return obj;\n}\n</code></pre>\n<h3>Cyclic safe stack</h3>\n<p>This uses a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. WeakSet\">WeakSet</a> to track which object references have been encountered.</p>\n<p>A week set only holds the generated hash rather than the object and thus uses a little less memory than <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Set\">Set</a> and reduces the GC workload.</p>\n<p>You can use this in the recursive code as well.</p>\n<pre><code>function sortKeysDeeply(obj) {\n const stack = [], checked = new WeakSet();\n if (isObj(obj)) {\n stack.push(obj);\n while (stack.length) {\n let o = stack.pop();\n checked.add(o);\n o = !Array.isArray(o) && sortInPlaceObjectKeys(o);\n for (const val of Object.values(o)) { \n isObj(val) && !checked.has(val) && stack.push(val);\n }\n }\n }\n return obj;\n}\n</code></pre>\n<h3>Helper functions</h3>\n<p>Function required by above rewrites.</p>\n<pre><code>const strSorter = (a, b) => a > b ? 1 : a < b ? -1 : 0;\nconst isObj = obj => 'object' === typeof(obj) && null !== obj;\nconst sortObjectKeys = obj => \n Object.fromEntries(Object.entries(obj).sort((a, b) => strSorter(a[0], b[0])));\n \nconst sortInPlaceObjectKeys = obj => {\n const sorted = Object.entries(obj).sort((a, b) => strSorter(a[0], b[0]));\n for (const [key] of sorted) { delete obj[key] }\n return Object.assign(obj, Object.fromEntries(sorted));\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T22:06:03.290",
"Id": "265890",
"ParentId": "265820",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T10:55:30.317",
"Id": "265820",
"Score": "2",
"Tags": [
"javascript",
"sorting",
"json"
],
"Title": "Using JavaScript, given a JSON value, recursively find all JSON objects, then sort keys in-place"
}
|
265820
|
<h1>What is Vyxal</h1>
<p><a href="https://esolangs.org/wiki/Vyxal" rel="nofollow noreferrer">Vyxal</a> is a golfing language with a unique design philosophy: make things as short as possible but retain elegance while doing so. In very simple terms, this means keeping aspects of traditional programming languages that most developers are familiar with, while still providing commands that allow golfers to actually win challenges.</p>
<p>Vyxal is not a language that forces users to mash random characters together until something works. Nor is it a language that needs to be verbose. Vyxal is terse when it needs to be, and readable/stylish when it wants to be.</p>
<h2>Resources</h2>
<ul>
<li><a href="https://github.com/Vyxal/Vyxal" rel="nofollow noreferrer">Github repository</a></li>
<li><a href="https://github.com/Vyxal" rel="nofollow noreferrer">Github organisation</a></li>
<li><a href="https://lyxal.pythonanywhere.com/" rel="nofollow noreferrer">Offical online interpreter</a></li>
<li><a href="https://vyxapedia.hyper-neutrino.xyz/tio" rel="nofollow noreferrer">Alternate online interpreter</a></li>
<li><a href="https://github.com/Vyxal/Vyxal/blob/master/docs/Tutorial.md" rel="nofollow noreferrer">Official tutorial</a></li>
<li><a href="https://vyxapedia.hyper-neutrino.xyz/beginners" rel="nofollow noreferrer">Alternate tutorial</a></li>
<li><a href="https://github.com/Vyxal/Vyxal/blob/master/docs/elements.txt" rel="nofollow noreferrer">Full list of commands</a></li>
<li><a href="https://chat.stackexchange.com/rooms/106764/vyxal">Chat room</a></li>
</ul>
<p>Note that even though the Vyxal source code is currently being refactored, the regulars in the chat room are happy to answer any questions.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T11:36:42.160",
"Id": "265822",
"Score": "0",
"Tags": null,
"Title": null
}
|
265822
|
Vyxal is a golfing language made by CGSE user lyxal. But unlike other golfing languages you might have seen, Vyxal has a special focus on readability and elegancy - it has features such as arbitrary variable names and defined functions that other golflangs don't have. Questions using the vyxal tag are not for advice on making programs shorter - they should be on-topic for Code Review. Golfing tips should be directed to Code Golf Stack Exchange.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T11:36:42.160",
"Id": "265823",
"Score": "0",
"Tags": null,
"Title": null
}
|
265823
|
<p>I've created this code in the golfing language <a href="https://github.com/vyxal/vyxal" rel="nofollow noreferrer">Vyxal</a> to do FizzBuzz:</p>
<pre class="lang-js prettyprint-override"><code>100 ( n 1 + →currentvalue
←currentvalue 15 % 0 = [
`FizzBuzz`,
| ←currentvalue 5 % 0 = [
`Buzz`,
| ←currentvalue 3 % 0 = [
`Fizz`,
| ←currentvalue ,
</code></pre>
<p><a href="https://lyxal.pythonanywhere.com?flags=&code=100%20%28%20n%201%20%2B%20%E2%86%92currentvalue%0A%E2%86%90currentvalue%2015%20%25%200%20%3D%20%5B%0A%20%20%60FizzBuzz%60%2C%0A%20%20%7C%20%E2%86%90currentvalue%205%20%25%200%20%3D%20%5B%0A%20%20%20%20%60Buzz%60%2C%0A%20%20%20%20%7C%20%E2%86%90currentvalue%203%20%25%200%20%3D%20%5B%0A%20%20%20%20%20%20%60Fizz%60%2C%0A%20%20%20%20%20%20%7C%20%E2%86%90currentvalue%20%2C&inputs=&header=&footer=" rel="nofollow noreferrer">Try it Online!</a></p>
<p>We loop 100 times. <code>n</code> is the 0-indexed iteration number, but we want the 1-indexed iteration number, so we add 1 and store it to the variable <code>currentvalue</code>. Then, we check if this is divisible by 15, 5, or 3 and print the corresponding text, otherwise printing <code>currentvalue</code>.</p>
<p>This is mostly equivalent to the following pseudocode:</p>
<pre><code>100 times
currentvalue = iterationnumber + 1
if currentvalue % 15 == 0
print 'FizzBuzz'
else if currentvalue % 5 == 0
print 'Buzz'
else if currentvalue % 3 == 0
print 'Fizz'
else
print currentvalue
</code></pre>
<p>I'm a bit dissatisfied with the need for three nested conditionals, and I feel like the code would be nicer if I didn't have to use the <code>currentvalue</code> variable.</p>
<p>I'm looking for tips on making this more readable and idiomatic, not shorter, unless it helps with the other two points.</p>
<p>Thanks for helping!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T22:09:15.837",
"Id": "525071",
"Score": "0",
"body": "This is a comment because I don't have much to say, but I'd recommend closing your loops and other structures. It's like having a Java class where you write `class Foo { public void bar() {`. without any `}}` at the end."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T22:09:35.800",
"Id": "525072",
"Score": "0",
"body": "Well, for one, you don't need to use a variable if you just duplicate your value three times before the first `[` block."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T22:10:52.737",
"Id": "525073",
"Score": "0",
"body": "@hyper-neutrino Oh true. Maybe make an answer?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T22:12:48.793",
"Id": "525074",
"Score": "0",
"body": "I will once I have some more details to contribute; I don't have time right now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T22:13:07.273",
"Id": "525075",
"Score": "0",
"body": "You can also put the `,` outside the if statement if you close it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T22:14:24.503",
"Id": "525076",
"Score": "0",
"body": "@user True, to both."
}
] |
[
{
"body": "<p>Firstly, it doesn't really make sense to push <code>100</code>, run a <code>(</code> block, and then do <code>n 1 +</code> when you could instead just use <code>ɾ</code> to get the range <code>1, 2, ..., 100</code>: <code>100 ɾ (</code>. Now, you are looping from 1 to 100, which makes a lot more sense. In fact, in the comments, I mentioned how by duplicating the computed <code>currentvalue</code> thrice, you could just pop off the stack instead of using <code>←currentvalue</code>, but this way, <code>n</code> will be the correct value (or you could save it in the for loop using <code>(x|...)</code>.</p>\n<p>Also, as pointed out by exedraj/lyxal (the creator of this language), it is better to use a map lambda as this creates the list and lets you manipulate it later, rather than just outputting within the for loop.</p>\n<p>Thus, we can do this:</p>\n<pre><code>100 ɾ ƛ\n n 15 % 0 = [\n `FizzBuzz` |\n n 3 % 0 = [\n `Fizz` |\n n 5 % 0 = [\n `Buzz` |\n n\n ]]]\n; ⁋\n</code></pre>\n<p>(Also, just stylistically, I like to put the <code>%3</code> first and <code>%5</code> second because it's called <em>FizzBuzz</em> after all, not <em>BuzzFizz</em>. Though this doesn't matter. Also, you should close your structures if you want it to be more idiomatic and readable rather than golfed.)</p>\n<p>Then, IMO it actually makes more sense to nest the <code>%3</code> and <code>%5</code> checks within each other rather than using <code>%15</code> - this makes it clearer that <code>FizzBuzz</code> is output when it is divisible by both (which is equivalent to being divisible by 15 (or generally the LCM) here but this is more explicit).</p>\n<p>Also, there's a built-in for checking divisibility. I don't think <code>% 0 =</code> is actually any better. It's probably more readable for someone who doesn't know what Vyxal's built-ins are, but idiomatically, you should be using <code>Ḋ</code> instead.</p>\n<pre><code>100 ɾ ƛ\n n 3 Ḋ [\n n 5 Ḋ [ `FizzBuzz` | `Fizz` ] |\n n 5 Ḋ [ `Buzz` | n ]\n ]\n; ⁋\n</code></pre>\n<p>(You could store <code>n 5 Ḋ</code> into a variable but there's honestly no point because those two expressions can't both be run, so you wouldn't actually be introducing any optimizations.)</p>\n<p>Finally, my personal preference for the FizzBuzz problem has always been to just build a string by combining the relevant components, and if that string is empty, returning <code>n</code> itself. Firstly, this makes it clearer what's going on (to me), where basically you say "if it's divisible by 3, output Fizz, if it's divisible by 5, output Buzz", and thus if it's divisible by both, both Fizz and Buzz are output. Secondly, this makes it more extendable.</p>\n<pre><code>100 ɾ ƛ ⟨3 | 5⟩ Ḋ ⟨`Fizz` | `Buzz`⟩ * ∑ n ∨ ; ⁋\n</code></pre>\n<p>Here, we take <code>n</code>, check divisibility by <code>3</code> and <code>5</code> in parallel (<code>₍₃₅</code> is shorter but that isn't as clear), and then replicate by <code>["Fizz", "Buzz"]</code> using <code>*</code> and then sum the strings together. Finally, we take logical or with <code>n</code> in case of empty string (note that <code>∨</code> is logical OR, not a lowercase letter <code>v</code>). Finally, we output each line.</p>\n<p>It's mostly up to preference which one to use, and Vyxal doesn't have an established set of best practices anyway, but the main takeaway is to use the proper looping values; if you have to alter your loop value and save to a variable, you probably should've done that outside the loop so you can just use <code>n</code> and have it be the proper correct value.</p>\n<p>The other reason I like the last one is this:</p>\n<pre><code>2 3 5 W →factors\n`Yeet` `Fizz` `Buzz` W →strings\n\n100 ɾ ƛ\n n ←factors Ḋ ←strings * ∑ n ∨\n; ⁋\n</code></pre>\n<p><a href=\"https://vyxapedia.hyper-neutrino.xyz/tio#WyIiLCIyIDMgNSBXIOKGkmZhY3RvcnNcbmBZZWV0YCBgRml6emAgYEJ1enpgIFcg4oaSc3RyaW5nc1xuXG4xMDAgyb4gxptcbiAgICBuIOKGkGZhY3RvcnMg4biKIOKGkHN0cmluZ3MgKiDiiJEgbiDiiKhcbjsg4oGLIiwiIiwiIiwiIl0=\" rel=\"nofollow noreferrer\">Try It Online!</a></p>\n<p>It's easy to extend.</p>\n<p>(<code>⁋</code> means "join on newline"; you can also use <code>¶ j</code> or <code>`\\n` j</code> for more clarity. Or, of course, just use the <code>j</code> flag.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T00:40:15.477",
"Id": "525085",
"Score": "0",
"body": "Just two little things I'd add: a) `∴` (dyadic maximum) can be used in place of `∨` in this case and b) wrapping everything in `ƛ` and joining on newlines (using `⁋`, `¶j` or `\\`\\n\\`j`) is, imo, more idiomatic - it allows implicit reuse of the context variable, and returns a list instead of printing each item on its own."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T02:37:52.563",
"Id": "525091",
"Score": "0",
"body": "@exedraj I know about dyadic maximum from your golfed answer on the code golf post, but is it actually better? I still feel like dyadic OR makes it clearer that it's substituting an empty string for that, whereas dyadic maximum depends on the ordering of different types and that's not immediately obvious/intuitive. I agree with using map lambda though."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T23:09:47.793",
"Id": "265840",
"ParentId": "265838",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "265840",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T22:02:10.990",
"Id": "265838",
"Score": "4",
"Tags": [
"fizzbuzz",
"vyxal"
],
"Title": "FizzBuzz in Vyxal"
}
|
265838
|
<p>I need to go from this dataframe:</p>
<pre><code>> dat
Code Project Status
1 A01 Pr1 In progress
2 A02 Pr1 Complete
3 A03 Pr2 Complete
4 A04 Pr1 Complete
5 A05 Pr1 In progress
6 A06 Pr3 Complete
7 A07 Pr3 In progress
8 A08 Pr3 Complete
9 A09 Pr2 Complete
10 A10 Pr2 In progress
</code></pre>
<p>to this JSON object:</p>
<pre><code>[
{
"key": "Complete",
"values": [
{
"label": "Pr1",
"value": 2
},
{
"label": "Pr2",
"value": 2
},
{
"label": "Pr3",
"value": 2
}
],
"color": "#440154FF"
},
{
"key": "In progress",
"values": [
{
"label": "Pr1",
"value": 2
},
{
"label": "Pr2",
"value": 1
},
{
"label": "Pr3",
"value": 1
}
],
"color": "#FDE725FF"
}
]
</code></pre>
<p>In this JSON object, <code>value</code> is a count, and <code>color</code> is a color for each level of <code>Status</code>; the colors must be distinct.</p>
<p>I have a solution with <code>data.table</code>:</p>
<pre><code>dat <- read.table(
text = "Code,Project,Status
A01,Pr1,In progress
A02,Pr1,Complete
A03,Pr2,Complete
A04,Pr1,Complete
A05,Pr1,In progress
A06,Pr3,Complete
A07,Pr3,In progress
A08,Pr3,Complete
A09,Pr2,Complete
A10,Pr2,In progress", sep = ",", header = TRUE
)
originalNames <- names(dat)
xName <- "Project"
byName <- "Status"
names(dat)[match(xName, originalNames)] <- "...X"
library(data.table)
library(viridisLite)
DT0 <- as.data.table(dat)
DT1 <- DT0[, .(count = .N), keyby = c("...X", byName)]
DT2 <- DT1[
, .(values = list(data.table(label = `...X`, value = `count`))), by = byName
]
names(DT2)[1L] <- "key"
DT2[, `:=`(color = viridis(nrow(DT2)))]
jsonlite::toJSON(DT2, pretty = TRUE)
</code></pre>
<p>Does it sound good and would you have something better to propose?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T07:19:19.593",
"Id": "265844",
"Score": "2",
"Tags": [
"json",
"r"
],
"Title": "Transform dataframe to a certain JSON format"
}
|
265844
|
<p>The code works, at least against the unit tests. But I would like input on how to refactor it. Or also maybe a way to do this without using temporary lists? I also have some special checks, like if the string is empty or if the brackets are unbalanced; is there a way to incorporate these special checks into the main body? It has been my problem with coding; I cannot refactor special cases into the general algorithm.</p>
<pre><code>using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public static class MatchingBrackets
{
public static bool IsPaired(string input)
{
string opening = "{[(";
string closing = "}])";
// Temporary lists to hold currently unmatched opening-closing brackets
List<char> opening_brackets = new List<char>{};
List<char> closing_brackets = new List<char>{};
// If input is empty string then return true
if (input.Count() == 0) { return true;}
// Loop through each character
foreach (char i in input)
{
// If the character is in the set of opening and closing brackets
if ((opening + closing).Contains(i))
// If it is an opening bracket, append to opening brackets temp list
if (opening.Contains(i) is true) { opening_brackets.Add(i); }
else
{
// Append closing bracket to closing brackets temp list
closing_brackets.Add(i);
// If there are no (more) temp opening brackets but we are in this else statement,
// then we fail already
if (opening_brackets.Count == 0) { return false;}
// Find the opening bracket that corresponds to the currently closing bracket
char required_prev_opening = opening.ElementAt(closing.LastIndexOf(i));
// If the corresponding opening bracket is not the same to the last
// opening bracket, we fail already
if (required_prev_opening != (char)opening_brackets.Last()) { return false;}
// The current closing bracket has a correct corresponding opening bracket. Remove them from
// their respective temporary list
opening_brackets.RemoveAt(opening_brackets.Count-1);
closing_brackets.RemoveAt(closing_brackets.Count-1);
}
}
// Check if there are still unmatched opening or closing brackets. If so then we fail.
if (opening_brackets.Count != 0 || closing_brackets.Count != 0)
{
return false;
}
return true;
}
}
</code></pre>
<p>The unit tests are:</p>
<pre><code>// This file was auto-generated based on version 2.0.0 of the canonical data.
using Xunit;
public class MatchingBracketsTests
{
[Fact]
public void Paired_square_brackets()
{
var value = "[]";
Assert.True(MatchingBrackets.IsPaired(value));
}
[Fact]
public void Empty_string()
{
var value = "";
Assert.True(MatchingBrackets.IsPaired(value));
}
[Fact]
public void Unpaired_brackets()
{
var value = "[[";
Assert.False(MatchingBrackets.IsPaired(value));
}
[Fact]
public void Wrong_ordered_brackets()
{
var value = "}{";
Assert.False(MatchingBrackets.IsPaired(value));
}
[Fact]
public void Wrong_closing_bracket()
{
var value = "{]";
Assert.False(MatchingBrackets.IsPaired(value));
}
[Fact]
public void Paired_with_whitespace()
{
var value = "{ }";
Assert.True(MatchingBrackets.IsPaired(value));
}
[Fact]
public void Partially_paired_brackets()
{
var value = "{[])";
Assert.False(MatchingBrackets.IsPaired(value));
}
[Fact]
public void Simple_nested_brackets()
{
var value = "{[]}";
Assert.True(MatchingBrackets.IsPaired(value));
}
[Fact]
public void Several_paired_brackets()
{
var value = "{}[]";
Assert.True(MatchingBrackets.IsPaired(value));
}
[Fact]
public void Paired_and_nested_brackets()
{
var value = "([{}({}[])])";
Assert.True(MatchingBrackets.IsPaired(value));
}
[Fact]
public void Unopened_closing_brackets()
{
var value = "{[)][]}";
Assert.False(MatchingBrackets.IsPaired(value));
}
[Fact]
public void Unpaired_and_nested_brackets()
{
var value = "([{])";
Assert.False(MatchingBrackets.IsPaired(value));
}
[Fact]
public void Paired_and_wrong_nested_brackets()
{
var value = "[({]})";
Assert.False(MatchingBrackets.IsPaired(value));
}
[Fact]
public void Paired_and_incomplete_brackets()
{
var value = "{}[";
Assert.False(MatchingBrackets.IsPaired(value));
}
[Fact]
public void Too_many_closing_brackets()
{
var value = "[]]";
Assert.False(MatchingBrackets.IsPaired(value));
}
[Fact]
public void Math_expression()
{
var value = "(((185 + 223.85) * 15) - 543)/2";
Assert.True(MatchingBrackets.IsPaired(value));
}
[Fact]
public void Complex_latex_expression()
{
var value = "\\left(\\begin{array}{cc} \\frac{1}{3} & x\\\\ \\mathrm{e}^{x} &... x^2 \\end{array}\\right)";
Assert.True(MatchingBrackets.IsPaired(value));
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T13:02:08.983",
"Id": "525104",
"Score": "1",
"body": "For a simple balanced pair check without temporary lists, you can (1) move up from last known Left index until you find an opening bracket, (2) determine the required closing bracket, and (3) from last known Right index move down looking for ANY closing bracket. If that bracket is not found or is not the required closing bracket, you may return false and stop processing. You also stop when the last known Left index is no longer less than the Right index."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T15:45:10.367",
"Id": "525117",
"Score": "0",
"body": "FYI Your code doesn't follow the naming guidelines: https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/naming-guidelines"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T16:12:12.437",
"Id": "525119",
"Score": "0",
"body": "@RickDavin But then with your algortihm, wouldn't ({[)}] be a valid answer, while it is actually not?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T11:33:30.797",
"Id": "525151",
"Score": "0",
"body": "No. Re-read: move down looking for *ANY* closing bracket. If that bracket is not found or is *not the required closing bracket*, you may return false."
}
] |
[
{
"body": "<p>Nice code. But you can use one stack instead two lists. Try to refactor your code.\nPush the opening bracket to the stack.\nPop the last bracket. In case there is wrong bracket return false.</p>\n<p>At the end you should get empty stack in case the brackets are paired</p>\n<pre><code>public static class MatchingBrackets\n{\n private static Dictionary<char, char> _pairs = new Dictionary<char, char> \n {\n { '(', ')' },\n { '[', ']' },\n { '{', '}' },\n };\n public static bool IsPaired(string input)\n {\n\n // If input is empty string then return true\n if (input.Count() == 0) { return true;}\n\n Stack<char> brackets = new Stack<char>();\n\n // Loop through each character\n foreach (char i in input)\n {\n // If it is an opening bracket, push it to the stack\n if(_pairs.ContainsKey(i)){\n brackets.Push(i);\n }\n // If it is an closing bracket, pop it\n else if(_pairs.Values.Contains(i))\n {\n if(brackets.Count == 0) return false;\n\n var openingBracket = brackets.Pop();\n // If it isn't pair of the last opening bracket return false\n if(_pairs[openingBracket] != i) \n {\n return false;\n }\n }\n }\n // The stack should be empty in case all brackets are closed\n return brackets.Count == 0;\n }\n}\n</code></pre>\n<p><a href=\"https://dotnetfiddle.net/D6EsVm\" rel=\"nofollow noreferrer\">Try it out yourself.</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T16:10:13.523",
"Id": "525118",
"Score": "0",
"body": "Wow yeah a dictionary is more suitable since the brackets can be thought of as a key-pair . Thanks for the reply!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T18:34:08.873",
"Id": "525122",
"Score": "2",
"body": "When the input contains excess closing bracket, this code crashes because pop from empty stack."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T08:44:48.650",
"Id": "525144",
"Score": "0",
"body": "@BobbyJ, you right! My mistake. Thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T14:49:47.490",
"Id": "525245",
"Score": "1",
"body": "The variable `i` makes this very confusing to read. The variable should have a better name, or at least on that isn't associated with the index of a `for` loop. Also the formatting is very inconsistent. There are 5 `if` statements and the use of braces in line breaks is different for all of them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T14:58:40.660",
"Id": "525247",
"Score": "0",
"body": "Also, while the algorithm is good, this answer doesn't give any feedback about OPs original code."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T12:57:57.580",
"Id": "265853",
"ParentId": "265845",
"Score": "8"
}
},
{
"body": "<h1>Too many comments</h1>\n<p>Comments should only be used when absolutelly necessary to explain why something is done. What is done doesn't belong in comments, as this should be clear from reading the code.</p>\n<pre><code>// If input is empty string then return true\nif (input.Count() == 0) { return true;}\n</code></pre>\n<p>This comment for example doesn't add anything and just makes it harder to read the code.</p>\n<h1>Naming</h1>\n<p>Be consistent! <code>IsPaired</code> uses PascalCase while the methods in the unit test use Snake_case.</p>\n<p>Also use descriptive names. Most of your names are very good but the <code>i</code> in the loop shoud get a better name. <code>i</code> is associated with the index variable in <code>for</code> loops and should only be used there. When ready the code I actually go confused once about where the index in coming from.</p>\n<h1>Use of braces</h1>\n<p>There should be braces after <code>if ((opening + closing).Contains(i))</code>. Especially as ther is a lot of code.<br />\nAlso there should be a space before the closing braces in the single line <code>if</code>s.</p>\n<h1><code>closing_brackets</code> is uncessary</h1>\n<p>After adding items to this list the method either returns or removes the just added item. So this list does nothing.</p>\n<h1><code>input.Count()</code> is problematic on many levels</h1>\n<p>You don't have a unit test with a <code>null</code> string as input. This case will fail with a <code>NullReferenceException</code> at <code>input.Count()</code>.<br />\nAlso <code>.Count()</code> is not a member of the <code>string</code> type. But an extensions method from Linq. It would be better to use the <code>Length</code> property instead.</p>\n<p>But I think it would be best to change the condition to</p>\n<pre><code>if(string.IsNullOrEmpty(input))\n</code></pre>\n<h1>Directly use the <code>bool</code> result of methods</h1>\n<p>The <code>is true</code> in <code>if (opening.Contains(i) is true)</code> is unnecessary.</p>\n<h1>The nested <code>if</code>s in the loop are unncessary</h1>\n<p>Generally avoid unecessary nesting. You mostly do this by exiting early from the loop.</p>\n<p>This code</p>\n<pre><code>if ((opening + closing).Contains(i))\n if (opening.Contains(i) is true) { opening_brackets.Add(i); }\n else\n {\n</code></pre>\n<p>can be changed to</p>\n<pre><code>if (opening.Contains(i))\n{\n opening_brackets.Add(i);\n}\nelse if (closing.Contains(i))\n{\n</code></pre>\n<h1>You can directly return the result of boolean operations</h1>\n<p>The last if can be replaced by a return statement, especially if you get rid of the <code>closing_brackets</code> list.</p>\n<pre><code>return opening_brackets.Count == 0;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T16:02:14.400",
"Id": "265918",
"ParentId": "265845",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "265853",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T09:30:59.897",
"Id": "265845",
"Score": "5",
"Tags": [
"c#",
"balanced-delimiters"
],
"Title": "C# code to check balanced brackets in a string"
}
|
265845
|
<p>I'm building a full stack exercise app and some of my objects include routines, exercises, exercise sets etc. Instead of writing out specific get, post, put and delete requests for each resource, I was wondering if there's a more dynamic way to make requests using a custom React hook. I've seen many examples of a useFetch hook, but not much for other request types. I've already built a custom hook, and created a strategy for making requests in my components. It seems to work, but I was hoping to get some feedback from some more experienced developers out there if they are willing, or if they can show some examples of what I'm trying to achieve. Thanks!</p>
<p><strong>Type Defs</strong></p>
<pre><code>import { AxiosError, AxiosResponse } from 'axios'
import React from 'react'
export type StatusType = "fetching" | "creating" | "updating" | "deleting" | "done"
export interface DataReturnType {
response: AxiosResponse | undefined
status: StatusType
error: AxiosError | undefined
}
// Every time there's a new resource added to my back end, all I have to do is add a
// new endpoint string here and I automatically get all the requests.
export type ResourceEndpointType = "routines" | "routines/routine" | "routines/weeks" | "set-groups" | "exercise-sets" | "exercises" | "users"
// Below essentially tells you how the request is built every time you need it.
// TypeScript makes it easy to implement because you never have to remember what the endpoint is,
// it just pops up as you're typing. Furthermore, this approach imposes more consistent structure to requests.
export type RequestObjType = {
resourceEndPoint: ResourceEndpointType
parameter?: string
query?: string
request: "get" | "post" | "put" | "delete"
body?: object
trigger:boolean
setTrigger: React.Dispatch<React.SetStateAction<boolean>>
}
</code></pre>
<p><strong>The Hook</strong></p>
<pre><code>import { useEffect, useState } from "react";
import { AxiosError, AxiosResponse } from "axios";
import axiosWithAuth from "../utils/axiosWithAuth"; // an instance of axios with baseUrl and appropriate headers
import { DataReturnType, RequestObjType, StatusType } from "./apiTypes";
enum Statuses {
get = "fetching",
post = "creating",
put = "updating",
delete = "deleting",
done = "done",
}
const useRequest = (requestObj: RequestObjType): DataReturnType => {
const [response, responseSet] = useState<AxiosResponse | undefined>(
undefined
);
const [status, statusSet] = useState<StatusType>(Statuses.done);
const [error, errorSet] = useState<AxiosError | undefined>(undefined);
let url = requestObj.resourceEndPoint;
if (requestObj.parameter) url += "/" + requestObj.parameter;
if (requestObj.query) url += "?" + requestObj.query;
useEffect(() => {
if (requestObj.trigger) { // trigger and setTrigger are passed in by the component
console.log(`Requesting ${requestObj.request.toUpperCase()}...`);
statusSet(Statuses[requestObj.request]);
axiosWithAuth()
[requestObj.request](url, requestObj.body)
.then((response: AxiosResponse) => {
requestObj.setTrigger(false);
responseSet(response);
statusSet("done");
})
.catch((error: AxiosError) => {
console.log(error);
errorSet(error);
statusSet("done");
requestObj.setTrigger(false);
});
}
// resetting response and error every time will allow for conditional checks in the component
responseSet(undefined);
errorSet(undefined);
requestObj.setTrigger(false);
}, [url, requestObj]);
return {
response,
status,
error,
};
};
export default useRequest;
</code></pre>
<p><strong>Using the hook for GET in a search bar component</strong></p>
<pre><code> const [search, setSearch] = useState("");
const { loadExercises, paginationSet } = useExerciseContext(); // custom hook built from useContext
const [trigger, shouldFetch] = useState(false);
const { response, status } = useRequest({
request: "get",
query: `name=${search}`,
resourceEndPoint: "exercises",
trigger,
setTrigger: shouldFetch,
});
// watching for changes in the response
useEffect(() => {
if (response) {
loadExercises(response.data.data);
paginationSet(response.data.pagination)
}
}, [loadExercises, response, status, paginationSet]);
...
<Button
onClick={() => shouldFetch(true)} // triggering the request
className={classes.submitBtn}
variant="outlined"
>
Submit
</Button>
</code></pre>
<p><strong>Using the hook for PUT in another component</strong></p>
<pre><code> const { changeRoutineColor, routineColorMap, replaceRoutine } =
useRoutinesContext();
const routineColor = routineColorMap[routine._id];
const classes = useItemStyles({ routineColor });
const [shouldUpdate, setShouldUpdate] = useState(false); // you can make the triggers more semantic
const { response, status, error } = useUpdate({ // being more semantic with the useResource import
resourceEndPoint: "routines/routine",
parameter: routine._id,
query: "select=color", // I don't need the entire object back from the backend (MongoDB/Node/Mongoose) so I can add a select to the query
request: "put",
trigger: shouldUpdate,
setTrigger: setShouldUpdate,
body: { color: routineColor },
});
// handling the response
useEffect(() => {
if (response && response.data) {
replaceRoutine({ ...routine, color: response.data.data.color });
}
}, [replaceRoutine, response, routine, error]);
const onChange = (newColor: string) => {
changeRoutineColor(routine._id, newColor);
};
//
const handleClose = () => {
popupState.close();
setShouldUpdate(true); // triggering the request
};
</code></pre>
|
[] |
[
{
"body": "<p>The biggest part is that the code works and it looks okay.</p>\n<p>I only have a few concerns about unnecessary rerenders and inconsistent UI because of inaccurate status state.</p>\n<p>Below are a few minor things I'd recommend and consider.</p>\n<h3>Naming</h3>\n<p>Code naming should be consistent and verbose.</p>\n<ul>\n<li><p>I'd recommend changing the name of <code>trigger</code> to <code>refetch</code> and <code>setTrigger</code> to something more descriptive to what's the code is doing - I'd recommend using the same name for the component - <code>shouldFetch</code>.</p>\n</li>\n<li><p>The set state variable assignments are not named consistently - i.e. <code>paginationSet</code> and <code>setSearch</code>. I'd recommend following the standard of the word <code>set</code> followed by a descriptive state word.</p>\n</li>\n</ul>\n<p>Below are two examples:</p>\n<ul>\n<li>rename pagninationSet to setPagination</li>\n<li>rename statusSet to setStatus</li>\n</ul>\n<p>Status enums are not consistently used (you manually type 'done') - but I think this can be removed all together - see state.</p>\n<p>The promise code can be simplified by using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/finally\" rel=\"nofollow noreferrer\">finally</a>.</p>\n<hr />\n<h3>State</h3>\n<p>Objectively speaking you only have four states - No data, loading, error, and data.</p>\n<p>Since you are using the hook in the components that are fetching the data you know what the UI would show in the place you're using the hook - the actual status strings of <code>deleting</code>, <code>creating</code> etc. are unnecessary for the universal fetch hook.</p>\n<p>Here are some things I'd do</p>\n<ul>\n<li><p>Remove the added complexity with the <code>setStatus</code> and change it to <code>loading</code>.</p>\n</li>\n<li><p>I would replace <code>status</code> with <code>loading</code> and remove the <code>status</code> enum and <code>status</code> logic as it is not necessary to achieve the goal of the hook and UI.<br />\nThis would also solve the issue of inaccurate default status of <code>done</code>;</p>\n</li>\n<li><p>Set the error state to either Boolean or the message.</p>\n</li>\n<li><p>I don't like undefined values for state, use either string (or empty one), null, a Boolean - something more representative of the actual set state.</p>\n</li>\n<li><p>I prefer string literals over string concatenation since I think they are more concise, so I'd change how the <code>URL</code> is generated.</p>\n</li>\n<li><p>I prefer destructuring too.</p>\n</li>\n<li><p>Move the <code>setState</code> into the <code>if</code> condition because you only set state values after when fetching. It will make sure you always reflect the current state to the components using the hook</p>\n</li>\n<li><p>Move the url inside the effect hook to reduce the unnecessary generation and effect hook dependency of <code>url</code> if the condition is not met.</p>\n</li>\n</ul>\n<h3>Small refactor of the main hook</h3>\n<pre class=\"lang-js prettyprint-override\"><code>const useRequest = (request)=> {\n const [response, setResponse] = useState(null);\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState(false);\n\n useEffect(() => {\n const { \n body, resourceEndPoint, parameter, query, refetch, request, shouldFetch\n } = request;\n if (refetch) {\n const url = `${resourceEndPoint}${parameter ?`/${parameter}` :''}${query ?`?${query}` :''}`;\n setLoading(true);\n setError(false)\n axiosWithAuth()\n [request](url, body)\n .then(setResponse)\n .catch(()=> {\n setError(true)\n })\n .finally(() => setLoading(false));\n }\n shouldFetch(false); // can only be false - don't need to place in `if` statement\n }, [request]);\n\n return { error, loading, response };\n};\n</code></pre>\n<p>Lastly, make the other components states match the names here.</p>\n<p><em>Note: I wrote this in the stack editor so there might be a typo in the names. I also removed the types to make it easier to follow on here and I can't verify they are correct - they need to updated to reflect the changes.</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T10:55:35.493",
"Id": "525149",
"Score": "1",
"body": "Man, thanks so much! That's really helpful feedback."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T23:32:44.620",
"Id": "265865",
"ParentId": "265849",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "265865",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T10:47:59.763",
"Id": "265849",
"Score": "3",
"Tags": [
"react.js",
"typescript",
"mongoose",
"axios"
],
"Title": "A React - Typescript custom hook for any request (GET, POST, PUT, DELETE) to my back end"
}
|
265849
|
<p><strong>Edit</strong>: cross-posted this question on <a href="https://stackoverflow.com/questions/68774523/best-way-of-cleaning-up-resources-with-completablefuture">Stackoverflow</a>.</p>
<p>Suppose I have a function that takes a <code>FileInputStream</code>, performs some operation using the file data in the background, and returns a <code>CompletableFuture<Void</code> that will be completed when the background operation finishes:</p>
<pre class="lang-java prettyprint-override"><code>CompletableFuture<Void> asyncFileOperation(FileInputStream in) {
var cf = new CompletableFuture<Void>();
// ...
return cf;
}
</code></pre>
<p><code>FileInputStream</code> is a resource that has to be closed when not needed anymore. With synchronous code, we would use <code>finally</code> or <code>try-with-resources</code>. But with <code>CompletableFuture</code>, it's a bit more complicated. I can think of four ways, with pros and cons:</p>
<ol>
<li>Simply using <code>whenComplete</code>:</li>
</ol>
<pre class="lang-java prettyprint-override"><code>FileInputStream in = openFile("data.txt");
asyncFileOperation(in)
.whenComplete((r, x) -> in.close());
</code></pre>
<p>This effectively closes the stream when <code>asyncFileOperation</code> completes, regardless whether it succeeds or fails. Except, when <code>asyncFileOperation</code> throws a synchronous RuntimeException before even returning the <code>CompletableFuture</code>, <code>whenComplete</code> will not be called, so neither will <code>close</code>.</p>
<p>We could write this off as "never happens", but unexpected exceptions are the very reason we use <code>finally</code> and <code>try-with-resources</code> in the synchronous case, so we need to expect the unexpected.</p>
<ol start="2">
<li>Calling <code>asyncFileOperation</code> inside <code>thenCompose</code>:</li>
</ol>
<pre class="lang-java prettyprint-override"><code>CompletableFuture.completedFuture(openFile("data.txt");)
.thenCompose(this::asyncFileOperation)
.whenComplete((r, x) -> in.close());
</code></pre>
<p>This solves the problem of solution 1 by executing <code>asyncFileOperation</code> in the context of an existing CompletableFuture, so any exception gets caught and <code>whenComplete</code> is always executed. The problem with this is that we swallow the exception, which is particularly bad for unexpected ones such as NullPointerException.</p>
<ol start="3">
<li>Using both <code>try-catch</code> and <code>whenComplete</code>:</li>
</ol>
<pre class="lang-java prettyprint-override"><code>FileInputStream in = openFile("data.txt");
try {
asyncFileOperation(in)
.whenComplete((r, x) -> in.close());
} catch (RuntimeException exc) {
in.close();
throw exc;
}
</code></pre>
<p>This solves all of the above problems, and doesn't really introduce new ones, except that it's ugly and repetitive.</p>
<ol start="4">
<li>Doing it inside <code>asyncFileOperation</code>:</li>
</ol>
<pre class="lang-java prettyprint-override"><code>CompletableFuture<Void> asyncFileOperation(FileInputStream in) {
var cf = new CompletableFuture<Void>();
// ...
return cf.whenComplete((r, x) -> in.close());
}
asyncFileOperation(openFile("data.txt"));
</code></pre>
<p>Here, <code>asyncFileOperation</code> closes the stream itself ones it completes. Depending on the implementation, it might be obvious that there can be no RuntimeException, so we could eliminate some cases. If not, we need to use one of the approaches above to handle this, but we can handle it once and for all rather for every call.
Still, I don't like this because maybe we want to continue to use the stream for some other operations, and its always nice when resources are created and cleaned up in the same place.</p>
<p>So what are your thoughts on these options? Do you have other ones?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T06:40:26.300",
"Id": "525214",
"Score": "0",
"body": "Hello at CodeReview@SE - SE's site *for open-ended feedback on **working** source code from your project, including **application** of best practices* (along [What topics can I ask about here?](https://codereview.stackexchange.com/help/on-topic)). I think your question off topic: Check [stack**overflow**](https://stackoverflow.com/help/on-topic)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T07:26:56.713",
"Id": "525216",
"Score": "0",
"body": "Yeah, I wasn't sure whether to post in on Stackoverflow, Software Engineering, or here, so thanks! Should I just copy it into Stackoverflow?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T07:31:17.213",
"Id": "525218",
"Score": "0",
"body": "(Please consult the help pages - far as I remember, the canonical procedure is to ask for a moderator to move the post. Whenever you feel justified to cross-post, by all means cross-link the posts, too.)"
}
] |
[
{
"body": "<p>I can think of a different approach in which it would be the asynchronous' call responsibility to create the resource and close it:</p>\n<p>If you want to let the responsibility of knowing how to create the resource to the caller, you could use a <a href=\"https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/util/function/Supplier.html\" rel=\"nofollow noreferrer\">Provider</a>:</p>\n<pre class=\"lang-java prettyprint-override\"><code>CompletableFuture<Void> asyncFileOperation(Provider<FileInputStream> inProvider) {\n // This try-with-resources would actually be used in the background task, but you get the idea\n try (var in = inProvider.get()) {\n var cf = new CompletableFuture<Void>();\n // ...\n return cf;\n }\n}\n\nasyncFileOperation(() -> openFile("data.txt"))\n</code></pre>\n<p>If you want to leave the responsibility of knowing how to create the resource to <code>asyncFileOperation</code>, then just pass a filepath to the method.</p>\n<p>The trade off with this solution is you'd have to create the resource again if you want to use it somewhere else.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T13:57:24.563",
"Id": "525163",
"Score": "0",
"body": "It's certainly a nice idea I didn't think of, thanks! It gives me another, somewhat opposite idea: We could pass the async operation to the method that opens the file, like `useFileAsync(\"data.txt\", this::asyncFileOperation)`, so it would have the signature `useFileAsync(String, Function<FileInputStream, CompletableFuture<Void>)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T14:03:40.190",
"Id": "525166",
"Score": "0",
"body": "Still, I would be interested in a more general solution, not only for files, but any kind of cleanup to be executed when a CompletableFuture completes, and I don't think this would work in the general case. But maybe even option 1 with just `whenComplete` already works fine and I'm just being paranoid ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T17:41:05.777",
"Id": "525179",
"Score": "0",
"body": "To make it more generic, you could use make a class that takes a `Provider<T extends Autoclosable>` and applies it to a `Consumer<Provider<T extends Autoclosable>>`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T05:50:10.060",
"Id": "525209",
"Score": "0",
"body": "I wasn't talking about the type, mroe about the approach. I'm not sure it's always possible to open the resource only in the background task.\nFor example, you might have an existing DB connection that you jused used for synchronous work and you want to reuse it for the background task, but you need to close it afterwards. This is a pattern that appears quite often in our codebase. But maybe it's an anti-pattern and this should also follow your approach?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T12:57:01.723",
"Id": "525236",
"Score": "1",
"body": "Reading [this](https://www.baeldung.com/java-sql-connection-thread-safety) Baelding article and [this](https://stackoverflow.com/questions/4111594/why-always-close-database-connection) answer, you should probably let each thread/process request their own database connection using a connection pool. Still, if we are talking about database connections, you probably have that logic centralised, so maybe the is no need to use any kind of provider, and just let the corresponding thread request a connection"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T11:01:42.133",
"Id": "265876",
"ParentId": "265850",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "265876",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T11:04:47.370",
"Id": "265850",
"Score": "2",
"Tags": [
"java",
"asynchronous"
],
"Title": "Best way of cleaning up resources with CompletableFuture"
}
|
265850
|
<p>I'm implementing <code>apply_each</code> for tuple-like object as a general function which may be a combined version of <code>for_each</code> and <code>tuple_transform</code> in some implementations for tuple iteration.</p>
<p>As the name suggests, the first argument which is invocable will <strong>apply each</strong> element of the tuple.</p>
<hr />
<h3>Function Prototype of <code>apply_each</code>:</h3>
<pre class="lang-cpp prettyprint-override"><code>template <typename F, typename... Tuples>
constexpr decltype(auto) apply_each(F&& f, Tuples&&... ts);
</code></pre>
<hr />
<h3>As usual, you can iterate over the tuple</h3>
<pre class="lang-cpp prettyprint-override"><code>std::tuple tup_1 {1, 2.5, "three", 'F'};
gold::apply_each([](const auto& elem) {
std::cout << elem << ' ';
}, tup_1);
</code></pre>
<p>Output:</p>
<pre><code>1 2.5 three F
</code></pre>
<hr />
<h3>Tuple-like object can also be used</h3>
<pre class="lang-cpp prettyprint-override"><code>gold::apply_each([](const auto& elem) {
std::cout << elem << ' ';
}, std::array{1, 2, 3, 4});
</code></pre>
<p>Output:</p>
<pre><code>1 2 3 4
</code></pre>
<hr />
<h3>How about two or more tuples? Sure! No problem</h3>
<p>The function <code>apply_each</code> takes the first parameter that is callable and the arity should match with the number of elements from the tuple. There is internally a <code>zipper</code> function that zips the function so that the tuples that are zipped can be traversed together.</p>
<p>You don't need to worry about the length of every tuple because it automatically selects the minimum size of the tuples and truncates it.</p>
<pre class="lang-cpp prettyprint-override"><code>std::tuple tup_1 {1, 2, 3, 4};
std::tuple tup_2 {1, 2, 3, 4, 5};
std::tuple tup_3 {1, 2, 3};
gold::apply_each([i = 1](const auto&... args) mutable {
if (i == 1) std::cout << "Taking the sum of each element..." << '\n';
std::cout << "Iteration " << i++ << ": " << (args + ...) << '\n';
}, tup_1, tup_2, tup_3);
</code></pre>
<p>Output:</p>
<pre><code>Taking the sum of each element...
Iteration 1: 3
Iteration 2: 6
Iteration 3: 9
</code></pre>
<p>Well you can still use the parameter list: <code>const auto& arg1, const auto& arg2, const auto& arg3</code>.</p>
<hr />
<h3>What about the return type? Sure!</h3>
<pre class="lang-cpp prettyprint-override"><code>std::tuple tup_1 {1, 2, 3, 4};
std::tuple tup_2 {1, 2, 3, 4, 5};
std::tuple tup_3 {1, 2, 3};
auto sum_tuple = gold::apply_each([](const auto&... args) mutable {
return (args + ...);
}, tup_1, tup_2, tup_3);
static_assert(std::is_same_v<std::tuple<int, int, int>, decltype(sum_tuple)>); // passed!
gold::apply_each([i = 1](const auto& elem) mutable {
std::cout << "Sum " << i++ << ": " << elem << '\n';
}, sum_tuple);
</code></pre>
<p>Output:</p>
<pre><code>Sum 1: 3
Sum 2: 6
Sum 3: 9
</code></pre>
<hr />
<h3>What about mutating them? Hmmm...</h3>
<p>Well...</p>
<pre class="lang-cpp prettyprint-override"><code>std::tuple<int, double> tup_1;
gold::apply_each([](auto& elem){
if constexpr (std::is_integral_v<std::decay_t<decltype(elem)>>) {
elem = 3;
} else {
elem = 3.14159;
}
}, tup_1);
gold::apply_each([](const auto& elem){
std::cout << elem << ' ';
}, tup_1);
</code></pre>
<p>It seems to be compiled, but! The tuple doesn't change...</p>
<pre class="lang-cpp prettyprint-override"><code>0 0
</code></pre>
<p>Why? Well, it's difficult for me to make communicate with references when that invocable object is passed, and I can't figure out easily the argument type of the function because it may be a template or not. So... I used a <code>reference_wrapper</code>!, because that's the only one who saved me.</p>
<p>Let's see...</p>
<pre class="lang-cpp prettyprint-override"><code>gold::apply_each([](auto& elem){
if constexpr (std::is_integral_v<std::decay_t<decltype(elem)>>) {
elem = 3;
} else {
elem = 3.14159;
}
}, std::ref(tup_1));
</code></pre>
<p>Oops!! It seems the compiler is very angry. Well, the <code>elem</code> is still actually a <code>reference_wrapper</code> so the error is about <code>operator=</code> mismatch, and is not converted into primitive reference because it is a generic lambda.</p>
<p>So, I find another solution and <code>overload</code> is the key!</p>
<pre class="lang-cpp prettyprint-override"><code>gold::apply_each(gold::overload(
[](int& elem){ elem = 3; },
[](double& elem) { elem = 3.14159; }
), std::ref(tup_1));
</code></pre>
<p>The compiler seems very happy now <code>:)</code></p>
<p>A reference wrapper is implicitly converted into reference type because the argument type is known which is <code>int&</code> and <code>double&</code></p>
<p>What is the other way for passing a generic lambda? So I created a struct <code>overload_unref</code>!</p>
<pre class="lang-cpp prettyprint-override"><code>gold::apply_each(gold::overload_unref(
[](auto& elem) {
if constexpr (std::is_integral_v<std::decay_t<decltype(elem)>>) {
elem = 3;
} else {
elem = 3.14159;
}
}
), std::ref(tup_1));
</code></pre>
<p>The mechanics of <code>overload_unref</code> is that it will unwrap the argument if the type is <code>reference_wrapper</code>.</p>
<p>Here is the full implementation of <code>apply_each</code> together with the helper <code>tuple_zip</code> function:</p>
<pre class="lang-cpp prettyprint-override"><code>namespace gold {
namespace detail {
template <typename>
struct is_ref_wrapper_ : std::false_type {};
template <typename T>
struct is_ref_wrapper_<std::reference_wrapper<T>> : std::true_type {};
template <typename T>
inline constexpr bool is_ref_wrapper_v_ = is_ref_wrapper_<T>::value;
template <typename T>
struct maybe_unwrap_ref_wrapper_ {
using type = std::conditional_t<is_ref_wrapper_v_<T>, std::unwrap_reference_t<T>, T>;
};
template <typename T>
using maybe_unwrap_ref_wrapper_t_ = typename maybe_unwrap_ref_wrapper_<T>::type;
template <typename T>
using get_ref_wrap_type_t_ = typename T::type;
template <std::size_t I, typename... Tuple>
using zip_tuple_at_index_t_ = std::tuple<
std::conditional_t<
is_ref_wrapper_v_<std::decay_t<Tuple>>,
std::reference_wrapper<
std::conditional_t<
std::is_const_v<std::experimental::detected_or_t<Tuple, get_ref_wrap_type_t_, Tuple>>,
const std::tuple_element_t<I, std::decay_t<maybe_unwrap_ref_wrapper_t_<Tuple>>>,
std::tuple_element_t<I, std::decay_t<maybe_unwrap_ref_wrapper_t_<Tuple>>>
>
>,
std::tuple_element_t<I, std::decay_t<maybe_unwrap_ref_wrapper_t_<Tuple>>>
>...
>;
template <std::size_t I, typename... Tuple>
constexpr zip_tuple_at_index_t_<I, Tuple...> zip_tuple_at_index_(Tuple&&... ts) {
return { []<typename T>(T&& t) {
if constexpr (is_ref_wrapper_v_<std::remove_cvref_t<T>>) {
using type_ = std::remove_reference_t<typename T::type>; // reference_wrapper<T>::type
if constexpr (std::is_const_v<type_>)
return std::cref(std::get<I>(std::forward<T>(t).get()));
else
return std::ref(std::get<I>(std::forward<T>(t).get()));
} else
return std::get<I>(std::forward<T>(t));
}(std::forward<Tuple>(ts)) ... };
}
template <typename... Tuple, std::size_t... Is>
constexpr std::tuple<zip_tuple_at_index_t_<Is, Tuple...>...>
tuple_zip_impl_(std::index_sequence<Is...>, Tuple&&... ts) {
return { zip_tuple_at_index_<Is>(std::forward<Tuple>(ts)...)... };
}
} // namespace detail
// tuple_zip
template <typename... Tuple> requires (sizeof...(Tuple) > 0)
constexpr decltype(auto) tuple_zip(Tuple&&... ts) {
constexpr auto min_size_ = std::ranges::min({
std::tuple_size_v<std::decay_t<detail::maybe_unwrap_ref_wrapper_t_<Tuple>>>...
});
return detail::tuple_zip_impl_(
std::make_index_sequence<min_size_>{},
std::forward<Tuple>(ts)...
);
}
namespace detail {
template <typename F, typename... Tuple, std::size_t... Is> requires (sizeof...(Tuple) > 0)
constexpr decltype(auto) apply_each_impl_(std::index_sequence<Is...>, F&& f, Tuple&&... ts) {
decltype(auto) zipped_ = tuple_zip(std::forward<Tuple>(ts)...);
using result_t_ = decltype([&]{
return (std::apply(std::forward<F>(f), std::get<Is>(zipped_)), ...);
}());
if constexpr (std::is_void_v<result_t_>) {
return (
std::apply(std::forward<F>(f), std::get<Is>(zipped_)), ...
);
} else {
return std::make_tuple(
std::apply(
std::forward<F>(f), std::get<Is>(zipped_)
)...
);
}
}
} // namespace detail
// apply_each
template <typename F, typename... Tuple>
constexpr decltype(auto) apply_each(F&& f, Tuple&&... ts) {
using indices_ = std::make_index_sequence<std::ranges::min({
std::tuple_size_v<std::decay_t<detail::maybe_unwrap_ref_wrapper_t_<Tuple>>>...
})>;
return detail::apply_each_impl_(indices_{}, std::forward<F>(f), std::forward<Tuple>(ts)...);
}
// unref
template <typename T>
constexpr T&& unref(T&& t) {
return std::forward<T>(t);
}
template <typename T>
constexpr T& unref(std::reference_wrapper<T> t) {
return t.get();
}
// overload
template <typename... Fs>
struct overload : Fs... {
using Fs::operator()...;
};
// I have to provide this, otherwise, I would get a compilation error that I can't explain further...
template <typename... Fs>
overload(Fs...) -> overload<Fs...>;
namespace requirements {
template <typename... Ts>
concept has_at_least_ref_wrapper_ = (detail::is_ref_wrapper_v_<std::remove_cvref_t<Ts>> || ...);
} // namespace requirements
// overload_unref
template <typename... Fs>
struct overload_unref : overload<Fs...> {
overload_unref(Fs&&... fs)
: overload<Fs...>{ std::forward<Fs>(fs) ... } {}
using overload<Fs...>::operator();
template <typename... Ts>
requires requirements::has_at_least_ref_wrapper_<Ts...>
constexpr auto operator()(Ts&&... args) {
return (*this)(unref(std::forward<Ts>(args))...);
}
};
} // namespace gold
</code></pre>
<p>Current problems:</p>
<ul>
<li>The definition of alias <code>zip_tuple_at_index_t_</code> is over complicated even though I'm the one who wrote this but I can't further simplify this one.</li>
<li>Same to <code>zip_tuple_at_index_</code>.</li>
<li>I don't know if it's safe to use <code>std::experimental::detected_or_t</code> even if it's <strong>experimental</strong>.</li>
<li>I'm writing <code>decltype(auto)</code> for no reason but I don't know if that affects the value category of the type.</li>
<li>There will be a potential compiler error for GCC 11 maybe.</li>
</ul>
<p>Demo: <a href="https://gcc.godbolt.org/z/hz94faWad" rel="nofollow noreferrer">https://gcc.godbolt.org/z/hz94faWad</a></p>
<ul>
<li>Another problem is that, the code will be compiled fine in GCC 10.3, but not in GCC 11 higher.</li>
</ul>
|
[] |
[
{
"body": "<p>I see two main issues with the design.</p>\n<ol>\n<li>That you need to use <code>std::ref</code> to operate on the tuples themselves and not their copies. This isn't good. It is used this way in <code>thread</code> and similar cases but there it creates an object and knowledge whether a copy is needed to be a kept or a reference is extremely important. Here you invoke it immediately - so why copy at all?</li>\n</ol>\n<p>I remember implementing similar code and it was a straight forward recursion - it was called <code>visit</code>.</p>\n<pre><code>namespace details\n{\n template<size_t puIndex=0, typename PTuple, typename... PTuples, typename PFunc, \n std::enable_if_t<puIndex == std::tuple_size_v<std::remove_reference_t<std::remove_const_t<PTuple>>>,int> = 0>\n void visit(PFunc&& func, PTuple&& tuple, PTuples&&... tuples)\n {}\n\n template<size_t puIndex=0, typename PTuple, typename... PTuples, typename PFunc, \n std::enable_if_t<puIndex != std::tuple_size_v<std::remove_reference_t<std::remove_const_t<PTuple>>>,int> = 0>\n void visit(PFunc&& func, PTuple&& tuple, PTuples&&... tuples)\n {\n func(std::get<puIndex>(tuple), std::get<puIndex>(tuples)...);\n visit<puIndex+1>(std::forward<PFunc>(func), std::forward<PTuple>(tuple), std::forward<PTuples>(tuples)...);\n }\n}\n\ntemplate<typename PFunc, typename PTuple, typename... PTuples>\nvoid visit(PFunc&& func, PTuple&& tuple, PTuples&&... tuples)\n{\n details::visit(std::forward<PFunc>(func), std::forward<PTuple>(tuple), std::forward<PTuples>(tuples)...);\n}\n</code></pre>\n<p>I didn't bother making it safe for various sizes nor I needed to deal with return types... which brings me to the second point:</p>\n<ol start=\"2\">\n<li>I don't think this is a good idea to restrict the application to the minimal size of the tuples.</li>\n</ol>\n<p>Imagine user wanted to simply work with tuples of the same size and by mistake put a tuple with smaller size. It will cause runtime errors that he will have hard time finding with all the template complexity.</p>\n<p>Instead, the default <code>apply_each</code> should require all tuples to be of the same size and have a special version of <code>apply_each</code> for the case when the tuples are of varied sizes.</p>\n<p>Besides, even in one of cases you've shown some would argue that it should've called the function for the maximal size of the tuples.</p>\n<hr />\n<p>About return types... do you really want to deal with that? What if the tuples are in fact arrays and you return a tuple while user wanted an array as output? What to do when some calls return void? It's a mess.</p>\n<p>User should just pass an additional tuple to the call as an output parameter and fill it. I don't think overcomplicating the function is worthwhile if the work around is better and quite straightforward.</p>\n<p>But if you really need it I'd recommend you write function with a slightly different name to avoid any possible ambiguity. When I think about it - it isn't much more complicated to implement than the <code>visit</code> above... here is an example:</p>\n<pre><code>namespace details\n{\n template<size_t I, typename Func, typename Tuple, typename... Tuples>\n auto call_i(Func&& f, Tuple&& tpl, Tuples&&... tuples)\n {\n return f(std::get<I>(tpl), std::get<I>(tuples)...);\n }\n \n template<typename Func, typename Tuple, typename... Tuples, size_t... I>\n auto apply_each_impl(std::index_sequence<I...>, Func&& f, Tuple&& tpl, Tuples&&... tuples)\n {\n return std::make_tuple(call_i<I>(std::forward<Func>(f), std::forward<Tuple>(tpl), std::forward<Tuples>(tuples)...)...);\n }\n\n}\n\ntemplate<typename Func, typename Tuple, typename... Tuples>\nauto apply_each(Func&& f, Tuple&& tpl, Tuples&&... tuples)\n{\n return details::apply_each_impl(std::make_index_sequence<std::tuple_size_v<std::remove_reference_t<std::remove_const_t<Tuple>>>>{}, std::forward<Func>(f), std::forward<Tuple>(tpl), std::forward<Tuples>(tuples)...);\n}\n</code></pre>\n<p>But this doesn't work when some of the return types are <code>void</code> - as one cannot create <code>tuple</code> with <code>void</code> template arguments. As @G.Sliepen noticed the call order is not properly defined per C++ standard and GCC calls them in reverse order.</p>\n<p>So I believe the only reasonable way to get output without randomized call-order is to literally apply the work-around I proposed earlier but do so automatically. First deduce the output arguments and create the tuple, then apply the <code>visit</code> with lambda function that calls <code>f</code> and sets the output values into the output tuple and then return the output tuple. Something like this:</p>\n<pre><code>template<typename Func, typename Tuple, typename... Tuples>\nauto apply_each_ord(Func&& f, Tuple&& tpl, Tuples&&... tuples)\n{\n using outputTuple = decltype(apply_each(std::forward<Func>(f), std::forward<Tuple>(tpl), std::forward<Tuples>(tuples)...));\n \n outputTuple out;\n \n visit([&f](auto& outV, auto&&... args)\n {\n outV = f(args...);\n }, out, std::forward<Tuple>(tpl), std::forward<Tuples>(tuples)...);\n \n return out;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-11T10:27:33.767",
"Id": "528236",
"Score": "0",
"body": "But how would you implement `tuple_zip` using recursion?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-11T11:02:37.913",
"Id": "528239",
"Score": "1",
"body": "@G.Sliepen I wouldn't be implementing `tuple_zip` at all - it is just a helper to `apply_each` and not part of the main functionality. If you refer to implementation of the case when variables are returned - I wouldn't implement it with recursion. I have added example of an implementation..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-11T12:06:29.383",
"Id": "528242",
"Score": "1",
"body": "Looks good, although it seems to call the function in reverse order on the tuple elements when using GCC (see https://godbolt.org/z/Wx1Kcn77r)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-11T12:44:44.673",
"Id": "528243",
"Score": "0",
"body": "@G.Sliepen oh... that's not good. I don't see a decent way to deal with this lack of control - I begin to understand why `for...` was not accepted into `C++` standard. Then I believe the only reasonable way to get output without randomized call-order is to literally apply the work-around I proposed earlier but do so automatically. First deduce the output arguments and create the tuple, then apply the `visit` with lambda function that calls `f` and sets the output values into the output tuple and then return the output tuple."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-11T13:07:51.010",
"Id": "528245",
"Score": "1",
"body": "@G.Sliepen added `apply_each_ord` implementation that uses `apply_each` for type deduction and `visit` for the call."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-10T21:04:05.290",
"Id": "267874",
"ParentId": "265854",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "267874",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T14:20:04.170",
"Id": "265854",
"Score": "5",
"Tags": [
"c++",
"template-meta-programming",
"c++20"
],
"Title": "Implementing apply_each for tuple c++"
}
|
265854
|
<p>First of all: Hi, my name is Henrik and I am a mechanical engineer, who loves to code in his free time.
To get better in programming I wrote a genetic algorithm compined with a list planning algorithm (giffler thompsoon algorithm) to solve the fjssp (i have encountered this problem in my master thesis 2 years ago).</p>
<p>Although i would like to have help / reviews about the whole program, i think the biggest potential for improvement is in the class "Individuum". Especially the methods "calculateStartingTimeMatrix" and "decodierung" (decoding) seem to me somehow cumbersome, inefficient and confusing (the latter is certainly also due to the length of the methods).</p>
<p>To the programm:
After reading a production process out of an excel file and creating a population with random individuals i create permissible productionsplans for each individual ("Individuum"). To be able to do that i use the giffler thompson algorithm to decode the individuals. This happens in the "decodierung" method. For the giffler thompson algorithm i need to calculate the starting times at the beginning and every time i add a operation to the production schedule. This happens in the calculateStartingTimeMatrix methode.</p>
<pre><code>package planningalgorithm;
import java.util.Random;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Individuum {
int number;
int birthGeneration;
int nOp;
int nMa;
int[] indiAllocation; // Allocation of this Individual
int[] indiSequence; // Sequenz of this Individual
int[][] predecessorWorkingTimes; // Do i need this?
int[][] startingTimeMatrix; // Do i need this?
int[] timesProduction;
float timeFitness;
int susRank;
int tournamentWins;
List<Machine> indiMachines; // Machines of this Individual
List<Operationen> indiProcess; // Process of this Individual
int[] arrayA;
int[] arrayB;
int operationDash;
int operationDashDash;
int operationStar;
//Konstruktor
Individuum(int num, int startgen, int nOp, int nMa){
number=num;
this.nOp = nOp;
this.nMa = nMa;
birthGeneration=startgen;
indiAllocation = new int[nOp];
indiSequence = new int[nOp];
predecessorWorkingTimes = new int[nOp][nOp];
startingTimeMatrix = new int[nOp][nOp+1];
timesProduction = new int[nOp];
// Liste der Maschinen erstellen
indiMachines = new ArrayList<>(nMa);
for (int i=0;i<nMa;i++) {
Machine newMachine = new Machine(i,0);
indiMachines .add(newMachine);
}
// Liste der Prozesse erstellen
indiProcess = new ArrayList<>(nOp);
for (int i=0;i<nOp;i++) {
Operationen newOperation = new Operationen(nOp,nMa);
indiProcess.add(newOperation);
}
arrayA = new int[nOp];
arrayB = new int[nOp];
}
// Zufallszahl
private double randomNumber(){
double ranNum;
Random zufallszahl = new Random();
ranNum = zufallszahl.nextDouble();
return ranNum;
}
private double round(double value, int decimalPoints) {
double d = Math.pow(10, decimalPoints);
return Math.round(value * d) / d;
}
private int max(int[] fooArr) {
int maximum = -100;
for (int i=0;i<fooArr.length;i++) {
if (fooArr[i] > maximum) {
maximum = fooArr[i];
}
}
return maximum;
}
public void copyArr (int[] arr, int[] dest){
for (int i=0;i<arr.length;i++){
dest[i] = arr[i];
}
}
public int[] copyArraySection (int[] originArr, int startPointerArr, int[] destArr, int startPointerDest, int lenghtCopy){
for (int i=0;i<lenghtCopy;i++){
destArr[startPointerDest+i] = originArr[startPointerArr+i];
}
return destArr;
}
public int[] addOneToArray (int[] arr, int what){
// Case 1: Array is empty
if (arr == null){
int[] newArr = new int[1];
newArr[0] = what;
return newArr;
}
// Case 2: Array isnt empty
else {
int[] newArr = new int[arr.length + 1];
for (int i=0;i<arr.length;i++){
newArr[i] = arr[i];
}
newArr[arr.length] = what;
return newArr;
}
}
public int[] oneValue(int[] barArr, int value){
int[] oneValueArr = new int[barArr.length];
for (int i=0;i<barArr.length;i++){
oneValueArr[i] = value;
}
return oneValueArr;
}
public int[] changeValue (int[] arrArr, int oldValue, int newValue){
int[] newArrArr = new int[arrArr.length];
for (int i=0;i<arrArr.length;i++){
if (arrArr[i] == oldValue){
arrArr[i] = newValue;
}
}
return newArrArr;
}
public int count (int[] countArr, int value){
int countDoku = 0;
for (int i=0;i<countArr.length;i++){
if (countArr[i]==value){
countDoku++;
}
}
return countDoku;
}
public int[][] copyMatrix (int[][] arr) {
int[][] copy = new int[arr.length][arr[0].length];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++) {
copy[i][j] = arr[i][j];
}
}
return copy;
}
void calculateStartingTimeMatrix(){
//Reset startingTimeMatrix except the last column nOp which includes the occupation times
for (int r=0;r<nOp;r++){
for (int c=0;c<nOp;c++){
startingTimeMatrix[r][c] = 0;
}
}
// Reset the status in every operation
for (int i=0;i<nOp;i++){
indiProcess.get(i).operationDone = false;
indiProcess.get(i).operationNotReady = true;
indiProcess.get(i).operationReadyToStart = false;
}
// Reset the remainingPredessors
for (int i=0;i<nOp;i++){
copyArr(indiProcess.get(i).predecessor,indiProcess.get(i).remainingPredecessors);
}
// Update StartingTimeMatrix with Operation, that are already planned
for (int i=0;i<nOp;i++){
if (arrayA[i] == -1){
indiProcess.get(i).operationDone = true;
indiProcess.get(i).operationNotReady = false;
indiProcess.get(i).operationReadyToStart = false;
for (int z2=0;z2<nOp;z2++){
if (indiProcess.get(z2).predecessor[i] == 1){
startingTimeMatrix[z2][i] = indiProcess.get(i).timeEnd;
indiProcess.get(z2).remainingPredecessors[i] = 0;
}
}
}
}
for (int i=0;i<nOp;i++){
if (arrayA[i] == 1){
indiProcess.get(i).operationDone = false;
indiProcess.get(i).operationNotReady = false;
indiProcess.get(i).operationReadyToStart = true;
}
}
int operationsDone = 0;
while (operationsDone < nOp){
for (int z=0;z<nOp;z++){
int foundOp = 0;
// Search for starting Operation
if (indiProcess.get(z).operationReadyToStart == true){
foundOp = z;
for (int z2=0;z2<nOp;z2++){
if (indiProcess.get(z2).predecessor[foundOp] == 1){
startingTimeMatrix[z2][foundOp] = max(startingTimeMatrix[foundOp]) + predecessorWorkingTimes[z2][foundOp]; //t_Op = t_PredecessorStart(from startingTimeMatrix) + t_PredecessorProcess(from predecessorTimes)
}
}
// Mark the found operation as done
for (int z3=0;z3<nOp;z3++){
if (indiProcess.get(z3).remainingPredecessors[foundOp] == 1){
indiProcess.get(z3).remainingPredecessors[foundOp] = 0; // FoundOp is done and is now no longer a predecessor on which other operations have to wait for
}
}
indiProcess.get(foundOp).operationDone = true;
}
}
//Calculate new Starting Operations
for (int z=0;z<nOp;z++){
// Operation has no remaining Predecessor and wasnt done yet: Ready to Start
if (max(indiProcess.get(z).remainingPredecessors)==0 && indiProcess.get(z).operationDone == false){
indiProcess.get(z).operationReadyToStart = true;
indiProcess.get(z).operationNotReady = false;
}
// Operation has no remaining Predecessor, but is already done
if (max(indiProcess.get(z).remainingPredecessors)==0 && indiProcess.get(z).operationDone == true){
indiProcess.get(z).operationReadyToStart = false;
indiProcess.get(z).operationNotReady = false;
}
// Operation still has remaining Predecessors
if (max(indiProcess.get(z).remainingPredecessors)!=0){
indiProcess.get(z).operationNotReady = true;
indiProcess.get(z).operationReadyToStart = false;
indiProcess.get(z).operationDone = false;
}
}
//Abbruchbedingungen ermitteln
operationsDone = 0;
for (int z=0;z<nOp;z++){
if(indiProcess.get(z).operationDone == true){
operationsDone++;
}
}
}
//Fertigungszeiten berechnen
for (int z=0;z<nOp;z++){
timesProduction[z] = max(startingTimeMatrix[z]) + indiProcess.get(z).timeWorking;
}
}
void correctingAllocation (List<Operationen> operationsList){
// Liste der Maschinen erstellen
for (int i=0;i<nOp;i++){
indiProcess.get(i).availableMachines = new int[nMa];
copyArr(operationsList.get(i).availableMachines,indiProcess.get(i).availableMachines);
}
for (int i=0;i<nOp;i++){
int requestedMachine = indiAllocation[i];
if (indiProcess.get(i).availableMachines[requestedMachine] == 0){
// Requested Machine cant execute the operation
// Find available Machines
List<Integer> numbersAvailableMachines = new ArrayList<>();
for (int j=0;j<nMa;j++){
if (indiProcess.get(i).availableMachines[j] == 1){
numbersAvailableMachines.add(j);
}
}
// Pick random Machine of the available machines
double randomMachine = round((numbersAvailableMachines.size()-1) * randomNumber(),0);
int newMachine = (int) randomMachine;
//Put new Machine in Allocation
indiAllocation[i] = numbersAvailableMachines.get(newMachine);
}
}
}
// Decodierung
void decodierung(int[][] Vorrangmatrix, int[][] Maschinenzeiten){
// VORBEREITUNG
//Prozesszeitenmatrix bestimmen aus Zuordnung und Maschinenzeiten und Maschinenzeit in Matrix der Vorgänger-Prozess-Zeiten eintragen
for (int z=0;z<nOp;z++){
indiProcess.get(z).workingMachine = indiAllocation[z];
indiProcess.get(z).timeWorking = Maschinenzeiten[z][indiProcess.get(z).workingMachine];
}
// z=zeile/row
// s=spalte/column
for (int z=0;z<nOp;z++){
for (int s=0;s<nOp;s++){
if (Vorrangmatrix[z][s]==1){
predecessorWorkingTimes[z][s] = indiProcess.get(s).timeWorking;
}
else{
predecessorWorkingTimes[z][s] = 0;
}
}
}
// Get the predecessors of every Operation and save them under Process.get(x).Predecessors
for (int i=0;i<nOp;i++){
copyArr(Vorrangmatrix[i],indiProcess.get(i).predecessor);
}
int[][] arrayV = copyMatrix(Vorrangmatrix);
for (int z=0;z<nOp;z++){
if (max(Vorrangmatrix[z]) < 0.1)
arrayA[z] = 1;
else{
arrayA[z] = 0;
}
}
calculateStartingTimeMatrix();
// Beginn Giffler-Thompson Algorithmus
int gtaBreakingCondition = 0;
while (gtaBreakingCondition < nOp){
operationDash = 0;
operationDashDash = 0;
operationStar = 0;
// GT - Step 2.H1: Get O' (Operation with earliest Productiontime, finsihed first)
int earliestProductiontime = 1000;
for (int z=0;z<nOp;z++){
if (arrayA[z] == 1 && timesProduction[z]< earliestProductiontime){
operationDash = z;
earliestProductiontime = timesProduction[z];
}
}
// GT - Step 2.H2: Get B, all Operations of A on the same Machine as O'
int currentMachine = indiAllocation[operationDash];
for (int z=0;z<nOp;z++){
if (arrayA[z]==1 && indiAllocation[z]==currentMachine){
arrayB[z]=1;
}
else{
arrayB[z] = 0;
}
}
// GT - Step 2.H3: Get O'' (Operation of B with ealiest starting Time)
int earliestStartingtime = 1000;
for (int z=0;z<nOp;z++){
if (arrayB[z]==1 && max(startingTimeMatrix[z])<earliestStartingtime){
operationDashDash = z;
earliestStartingtime = max(startingTimeMatrix[z]);
}
}
// GT - Step 2.H4: Delete operations outside of the sigma window
//Check if earliest starttime is smaller then occupation
int starttime;
if (max(startingTimeMatrix[operationDashDash]) < indiMachines.get(currentMachine).timeOccupation){
starttime = indiMachines.get(currentMachine).timeOccupation;
}
else{
starttime = max(startingTimeMatrix[operationDashDash]);
}
double sigma = 0.5;
// Delete Operations outside
for (int z=0;z<nOp;z++){
if (arrayB[z]==1 && max(startingTimeMatrix[z]) > (starttime + sigma * (timesProduction[operationDash] - starttime))){
arrayB[z] = 0;
}
}
//GT - Step 2.H5: Get O*
int permutation = 1000;
for (int z=0;z<nOp;z++){
if (arrayB[z]==1 && indiSequence[z]<permutation){
permutation = indiSequence[z];
operationStar = z;
}
}
// Mark OperationStern as done
arrayA[operationStar] = -1; // OperationStar is done, mark with -1 in A
for (int z=0;z<nOp;z++){
if (arrayA[z] != -1){
arrayV[z][operationStar] = 0; // OperationStar is no longer predecessor of other operations
}
}
arrayV[operationStar] = oneValue(arrayV[operationStar], -1); // OperationStar is done, mark with -1 in V
// Set the starting time of operationStar
if (max(startingTimeMatrix[operationStar]) < indiMachines.get(currentMachine).timeOccupation){
indiProcess.get(operationStar).timeStart = indiMachines.get(currentMachine).timeOccupation;
}
if (max(startingTimeMatrix[operationStar]) >= indiMachines.get(currentMachine).timeOccupation){
indiProcess.get(operationStar).timeStart = max(startingTimeMatrix[operationStar]);
}
// Set the ending time of operationStar
indiProcess.get(operationStar).timeEnd = indiProcess.get(operationStar).timeStart + indiProcess.get(operationStar).timeWorking;
// Set new occupation time of the current machine
indiMachines.get(currentMachine).timeOccupation = indiProcess.get(operationStar).timeEnd;
// GT - Schritt 4: Add successors of O* to A
for (int z=0;z<nOp;z++){
if (max(arrayV[z]) == 0){
arrayA[z] = 1;
}
if (max(arrayV[z]) == -1){
arrayA[z] = -1;
}
if (max(arrayV[z]) == 1){
arrayA[z] = 0;
}
}
//GT - Step 5: Update occupation time of the current machine to every operation which is also done on that machine
for (int z=0;z<nOp;z++){
if (arrayA[z] != -1 && indiAllocation[z] == currentMachine){
startingTimeMatrix[z][nOp] = indiProcess.get(operationStar).timeEnd;
}
}
//Update startingTimeMatrix, because the occupation time in startingTimeMatrix[z][nOp] was updated
calculateStartingTimeMatrix();
//Give the working Machine some Information about the Operation: Needed for the BarChart
indiMachines.get(currentMachine).plannedOperations = addOneToArray(indiMachines.get(currentMachine).plannedOperations, operationStar);
indiMachines.get(currentMachine).startingTimesOps = addOneToArray(indiMachines.get(currentMachine).startingTimesOps, indiProcess.get(operationStar).timeStart);
indiMachines.get(currentMachine).endingTimesOps = addOneToArray(indiMachines.get(currentMachine).endingTimesOps, indiProcess.get(operationStar).timeEnd);
// Calculate Breaking Condition
gtaBreakingCondition = count(arrayA, -1);
}
}
// 1-Bit-Mutation
void einbitmutation(int nOp, double mutProbability){
for (int i = 0; i<nOp; i++) {
double random = randomNumber();
if (random<mutProbability){
if (indiAllocation[i]==1){
indiAllocation[i]=0;
}
else {
indiAllocation[i]=1;
}
}
}
}
//Mixed Mutation
void mixedmutation(int nOp, float mixMutProbability, int typeCoding){
double random = randomNumber();
if(random > mixMutProbability){
int sectionStart = (int) round(randomNumber()*nOp,0);
int sectionEnd = (int) round(randomNumber()*nOp,0);
while (sectionEnd == sectionStart){
sectionEnd = (int) round(randomNumber()*nOp,0);
}
if (sectionEnd < sectionStart){
int temp = sectionStart;
sectionStart = sectionEnd;
sectionEnd = temp;
}
int[] tempArr = new int[sectionEnd-sectionStart];
if (typeCoding == 0){
tempArr = copyArraySection(indiAllocation, sectionStart, tempArr, 0, sectionEnd-sectionStart);
List<Integer> tempList = new ArrayList<>();
for (int k=0;k<tempArr.length;k++){
tempList.add(tempArr[k]);
}
Collections.shuffle(tempList);
int[] mixedArr = tempList.stream().mapToInt(i->i).toArray();
indiAllocation = copyArraySection(mixedArr, 0, indiAllocation, sectionStart, sectionEnd-sectionStart);
}
else if (typeCoding == 1){
tempArr = copyArraySection(indiSequence, sectionStart, tempArr, 0, sectionEnd-sectionStart);
List<Integer> tempList = new ArrayList<>();
for (int k=0;k<tempArr.length;k++){
tempList.add(tempArr[k]);
}
Collections.shuffle(tempList);
int[] mixedArr = tempList.stream().mapToInt(i->i).toArray();
indiSequence = copyArraySection(mixedArr, 0, indiSequence, sectionStart, sectionEnd-sectionStart);
}
else{
System.out.println("Wrong Input for Coding Type of Mixed Mutation");
}
}
}
// Swap-Mutation
void swapmutation(int nOp, float mutProbability){
for (int i = 0; i<nOp; i++) {
double random = randomNumber();
if (random<mutProbability) {
double random2 = round(randomNumber()*(nOp-1),0);
int randomposition = (int)random2;
int saveNumber = indiSequence[randomposition];
indiSequence[randomposition] = indiSequence[i];
indiSequence[i] = saveNumber;
}
}
}
}
</code></pre>
<p>I would like to describe the programm even a bit more, but i already wrote a lot. You can fine the whole program with more explanations, pictures and examples here:
<a href="https://github.com/enruk/Productionplaner" rel="nofollow noreferrer">https://github.com/enruk/Productionplaner</a></p>
<p>I know its not allowed to link to third party website but i really hesitate to copy every class in here. I don't think this helps clarity and understanding.</p>
<p>Why I post it here?
My problem is that in self-taught programming, I only work up to the point where the program works. I miss a kind of mentor who tells me: Yes, this works, but it can be done better (which is i guess the point of this website).</p>
<p>As already mentioned, I am also happy to receive feedback on the remaining classes of the program or the entire program (but i know that this is not the purpose of this website). I know the program is quiet big to give a detailed feedback. What I look for are more general tips / advices. I appreciate the smallest advices.
What can i do better / on which topics should I work / research more?</p>
<ul>
<li>Structure of the program</li>
<li>Basic algorithms</li>
<li>Structure and use of methods</li>
<li>Use of data structures</li>
</ul>
<p>Thank you very much already!
I know there are some german comments / varaibles names. Apologies. I will fix that asap.</p>
<p>Also I am happy about good recommendations for online courses.
I am currently doing this one:
<a href="https://www.udemy.com/course/java-training-ullenboom/" rel="nofollow noreferrer">https://www.udemy.com/course/java-training-ullenboom/</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T13:49:08.910",
"Id": "525673",
"Score": "1",
"body": "First thing I notice is that your variable names are not always self-descriptive. Things like `nOp` or `susRank` make it hard to follow along."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T13:50:46.100",
"Id": "525675",
"Score": "1",
"body": "Also utility methods like `randomNumber()`, `addOneToArray()` and so on should be outsourced to some sort of helper class. Right now it's hard to find out what your class is supposed to do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T13:56:43.057",
"Id": "525678",
"Score": "1",
"body": "What I also noticed is that most of your methods return `void`. When doing any form of calculations (and it seems you do) it's better to follow an input/output style IMHO. This makes your code a lot more testable (defined input results in expected output)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-24T08:38:32.533",
"Id": "526147",
"Score": "0",
"body": "@slauth thank you so much for you feedback. Really appreciate it. My Answer is a bit late, bc i was in vacation. Now that i think about it, your third comment in particular makes sense for maintenance and troubleshooting purposes. Also first and second comment are absolutly clear. I try to change this asap"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-24T08:50:23.793",
"Id": "526148",
"Score": "0",
"body": "@slauth Regarding your question about the purpose of the class: Each class \"Individuum\" is a production schedule. The main attributes are the sequence and the allocation. Each position i in the two arrays gives operation i of the production process a number in the sequence and an allocation to a machine. In the method \"decodierung\" i create an admissible productions schedule from these two vectors using the giffler thompson algorithm. I hope that helps a bit."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T15:50:22.360",
"Id": "265855",
"Score": "2",
"Tags": [
"java",
"beginner",
"genetic-algorithm"
],
"Title": "Giffler Thompson Algorithm for decoding individuals of a Genetic Algorithm"
}
|
265855
|
<p>I'm a new developer just starting out learning HTML5, CSS3 and JavaScript. Below is my attempt at building a portfolio website.</p>
<p>I am finding it difficult getting my site to respond better when adjusting the screen size. Text and images are just going all over the place when resizing the browsers window or viewing on mobile devices.</p>
<p>Any advice or criticism is appreciated. I have also linked my GitHub and pages below. Thanks</p>
<p><a href="https://github.com/JackDef10/Second-portfolio-draft" rel="nofollow noreferrer">GitHub</a>
<a href="https://jackdef10.github.io/Second-portfolio-draft/" rel="nofollow noreferrer">Portfolio</a></p>
<h1>HTML</h1>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./resources/css/index.css">
<title>Jack Defroand | Web Developer</title>
</head>
<body>
<div id="wrapper">
<div class="container">
<header class="main-page" id="main-page">
<nav class="navbar">
<a href="#main-page" class="nav-item">HOME</a>
<a href="#about-me" class="nav-item">ABOUT</a>
<a href="#projects" class="nav-item">PROJECTS</a>
<a href="#skills" class="nav-item">SKILLS</a>
<a href="#contact" class="nav-item">CONTACT</a>
</nav>
<div class="title-containter">
<div class="main-title">
<h1>JACK DEFROAND</h1><span id="text2"><span id="web-text">FRONT END</span> DEVELOPER</span>
<a href="#contact"><p>CONTACT ME</p></a>
</div>
</div>
<div class="socials">
<a href="https://github.com/JackDef10">
<img src="resources/images/GitHub-Logos/GitHub_Logo_White.png" alt="GitHub logo" id="github">
</a>
<a href="https://www.linkedin.com/in/jack-defroand/">
<img src="resources/images/LinkedIn-Logos/LI-In-Bug.png" alt="LinkedIn logo" id="linkedIn">
</a>
</div>
</header>
<main class="content">
<section class="section-style" id="about-me">
<div class="about-me">
<article>
<h1><span class="section-title">ABOUT ME</span></h1>
<aside id="about-text">
<p>In October I began my journey in to full stack development through an award winning training
provider and recruiter "IT Career Switch". Teaching the fundamentals of Software Development
through hundreds of hours of coding and course materials on the web such as Code academy and
w3schools.</p>
<p>Over 40 weeks, I learned how to create full-stack web applications from scratch using various
languages, libraries and frameworks including JavaScript, React, Java, Node.js, Python, HTML,
CSS, Bootstrap & SQL.</p>
<p>Please feel free to contact me if you have any questions by sending a message bellow or email at
Jackdefroand@gmail.com.</p>
</aside>
<div class="profile-img">
<img src="./resources/svg/Coding.svg" alt="My name is Jack Defroand">
</div>
</article>
</div>
</section>
<section class="section-style" id="projects">
<div class="projects">
<h1><span class="section-title">PROJECTS</span></h1>
<div class="container-pro">
<div id="gallery"></div>
</div>
</div>
<div id="popup">
<img src="" alt="" id="selectedImage">
</div>
</section>
<section class="section-style" id="skills">
<div class="skills">
<h1><span class="section-title">SKILLS</span></h1>
<div class="skills-svg">
<img src="resources/svg/Skills svg.svg" alt="My skills diagram">
</div>
</div>
</section>
<section class="section-style" id="contact">
<div class="contact">
<h1><span class="section-title">CONTACT</span></h1>
<p>Have a question or want to work together?</p>
<div class="email-form">
<div id="input-name">
<label for="name"></label>
<input type="text" id="name" name="name" placeholder="Name" required class="inputBox">
</div>
<div id="input-email">
<label for="email"></label>
<input type="email" id="email" name="email" placeholder="Email" required class="inputBox">
</div>
<div id="input-subject">
<label for="subject"></label>
<input type="text" id="subject" name="subject" placeholder="Subject" required class="inputBox">
</div>
<div id="input-message">
<textarea id="message" rows="10" cols="50" name="message" placeholder="Message" class="inputBox">
</textarea>
</div>
<input id="submit" type="submit" value="Send Message">
</div>
<div class="contact-svg">
<img src="resources/svg/Email svg.svg">
</div>
</div>
</section>
</main>
</div>
</div>
<script src="./resources/javascript/Navbar.js"></script>
<script src="./resources/javascript/Image-gallery.js"></script>
</body>
</html>
</code></pre>
<h1>CSS</h1>
<pre><code>* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: Arial, Helvetica, sans-serif;
scroll-behavior: smooth;
}
html{
font-size:16px;
}
body {
margin: 0 auto;
width:100%;
height:100%;
}
#wrapper{
width: 100%;
height: 100%;
}
.container{
scroll-snap-type: y mandatory;
overflow-y: scroll;
height: 100vh;
width: 100%;
}
/* Different page sections*/
section{
height: 100vh;
display: flex;
align-items: center;
width:100%;
scroll-snap-align: start;
}
.main-page{
background-image: url("../images/main-background.jpg");
background-repeat:no-repeat;
background-position: center;
background-size: cover;
width: 100%;
display:flex;
position:relative;
height: 100vh;
justify-content: center;
align-items: flex-start;
scroll-snap-align: start;
}
.about-me{
background-color: #4158D0;
background-image: linear-gradient(43deg, #4158D0 0%, #C850C0 46%, #FFCC70 100%);
margin: 0 auto;
position:relative;
display: block;
height: 85%;
width:85%;
}
.projects{
background-image: linear-gradient( 135deg, #43CBFF 10%, #9708CC 100%);
margin: 0 auto;
position:relative;
display: block;
height: 85%;
width:85%;
}
.skills{
background-color: #FA8BFF;
background-image: linear-gradient(45deg, #FA8BFF 0%, #2BD2FF 52%, #2BFF88 90%);
margin: 0 auto;
position:relative;
display: block;
height: 85%;
width:85%;
}
.contact{
background-color: #FF3CAC;
background-image: linear-gradient(225deg, #FF3CAC 0%, #784BA0 50%, #2B86C5 100%);
margin: 0 auto;
position:relative;
display: block;
height: 85%;
width:85%;
}
.section-title{
color:whitesmoke;
font-size: 4.5em;
font-weight:600;
border: 3px solid white;
position: relative;
top: 100px;
padding: 20px;
margin: 0 auto;
width: 700px;
display:block;
text-align: center;
}
.section-style{
background-color: seashell;
width:100%;
position: relative;
}
.main-title a p {
font-size: 0.35em;
position: relative;
text-align: center;
padding: 20px;
letter-spacing: 0.2em;
width: 250px;
margin: 20px auto;
border: 2px solid white;
color: white;
text-decoration: none;
}
.main-title a p:hover {
border: 2px solid tomato;
color: tomato;
transition: 0.6s;
}
.main-title h1{
width: 100%;
font-size: 1.5em;
letter-spacing: 0.3em;
text-align: center;
padding: 10px 0;
}
.title-containter{
background-color: rgba(39, 39, 39, 0.55);
width:50%;
top:300px;
position: relative;
margin: 0 auto;
display: inline;
padding: 30px;
font-size: 3.5em;
color:whitesmoke;
}
#text2{
color:tomato;
font-size: 1.2em;
text-align: center;
display: block;
position: relative;
letter-spacing: 0.5em;
padding-bottom: 20px;
}
#web-text{
text-align: center;
position: relative;
font-size:0.8em;
color:turquoise;
display:block;
letter-spacing: 0.5em;
padding: 30px 0;
}
.socials{
position: absolute;
top: 800px;
}
.socials img{
width: 125px;
height: auto;
margin: 40px;
}
#linkedIn{
width:50px;
height:auto;
align-items: baseline;
}
#linkedIn:hover{
content: url("../images/LinkedIn-Logos/LI-In-Bug-tomato.png");
}
#github:hover{
content: url("../images/GitHub-Logos/GitHub_Logo_tomato.png");
}
.navbar {
display: inline;
overflow: hidden;
background-color: #fff;
padding: 40px 90px;
border-radius: 60px;
box-shadow: 0 10px 40px rgba(159, 162, 177, .8);
position: fixed;
margin-top: 2em;
z-index: 1;
transition: 0.7s;
}
.nav-item {
color: #83818c;
padding: 20px;
text-decoration: none;
transition: 0.3s;
margin: 0 6px;
z-index: 1;
font-family: 'Roboto Condensed', sans-serif;
font-weight: 600S;
position: relative;
font-size: 1.5em;
}
.nav-item:before {
content: "";
position: absolute;
bottom: -6px;
left: 0;
width: 100%;
height: 5px;
background-color:tomato;
border-radius: 8px 8px 0 0;
opacity: 0;
transition: 0.3s;
}
.nav-item:not(.is-active):hover:before {
opacity: 1;
bottom: 0;
}
.nav-item:not(.is-active):hover {
color: tomato;
}
/* About Me Section */
#about-text{
color: white;
font-size: 1.3em;
line-height: 1.5em;
max-width: 65%;
float: left;
margin: 5rem;
display: grid;
grid-auto-flow: row;
gap:2em;
position: relative;
top: 100px;
border-right: 2px solid white;
}
#about-text p{
padding-right: 30px;
letter-spacing: 0.2em;
}
.profile-img img{
width: 417px;
height: 625px;
position: relative;
display: inline;
object-fit: cover;
border: 10px solid white;
box-shadow: 3px 3px 20px black;
}
/* projects */
.container-pro{
margin: 0 auto;
width: 90%;
height: 40%;
padding: 50px 20px;
position: relative;
top: 150px;
}
.galleryImg {
max-width: 100%;
height: 300px;
width: 300px;
position: relative;
transition: transform 250ms;
cursor: pointer;
object-fit: cover;
}
#gallery{
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
}
.galleryImg:hover{
transform: translateY(-2px);
box-shadow: 3px 3px 10px black;
transform: scale(1.2);
}
#popup{
position:fixed;
top: 0;
left:0;
right: 0;
bottom:0;
background-color: rgba(0, 0, 0, 0.8);
display: flex;
justify-content: center;
align-items: center;
transform: translateY(-100%);
transition: 200ms transform;
padding: 50px;
}
#selectedImage{
max-height:100%;
}
/* projects */
.skills-svg{
position: relative;
top: 200px;
float: right;
}
/* contact form */
.email-form{
position:relative;
top: 200px;
left: 100px;
}
.inputBox{
background-color: seashell;
color: black;
font-family:Arial, Helvetica, sans-serif;
border: 0px;
box-shadow: 0 0 15px 4px rgba(159, 162, 177, .5);
margin: 10px;
padding: 20px;
border-radius: 2em;
font-size:1;
font-weight: bold;
}
#name{
position:relative;
float: left;
}
#email {
position:relative;
display:inline-block;
}
#subject{
width: 625px;
}
#message{
max-width: 625px;
min-width: 625px;
width: 625px;
max-height: 800px;
}
#submit{
padding: 15px;
width: 250px;
background-color:seashell;
color: rgb(89, 93, 110);
border-width: 2px;
border-color:seashell;
font-size: 1em;
border-radius: 2em;
border-style: solid;
font-weight: 700;
position: relative;
margin: 10px;
left:375px;
}
#submit:hover{
color: seashell;
background-color: rgba(159, 162, 177, .1);
border-color: seashell;
padding: 1em;
transition: 0.3s;
}
.contact-svg img{
display: inline;
position: relative;
width: 40%;
height: 20%;
object-fit: cover;
float: right;
bottom: 250px;
right: 100px;
}
.contact p {
color: white;
letter-spacing: 0.3em;
display: inline;
position: relative;
top: 160px;
margin-left: 7em;
}
@media only screen and (max-width: 1200px) and (min-width: 320px){
#about-text{
font-size: 1.2em;
}
}
/* Tablets */
@media only screen and (max-width: 800px) and (min-width: 300px){
.navbar{
width: 370px;
font-size: 0.6em;
margin: 0 auto;
display:flex;
padding:10px;
top: 20px;
}
.nav-item{
padding: 0px;
}
.nav-item:before {
height:2px;
}
.title-containter{
top: 150px;
font-size: 0.95em;
width: 350px;
}
.socials{
top:500px;
}
.main-title a p{
font-size: 0.85em;
}
.section-title{
font-size:1em;
width: 200px;
}
#about-text{
font-size: 0.8em;
}
}
@media only screen and (max-width: 1300px) and (min-width: 900px){
.title-containter{
top: 400px;
font-size: 3em;
width: 800px;
}
.socials{
top:1000px;
}
.main-title a p{
font-size: 0.5em;
}
.section-title{
font-size:4em;
width: 500px;
}
.nav-item:before {
height:8px;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T13:27:55.087",
"Id": "525301",
"Score": "1",
"body": "You might be interested in learning about [**flexbox**](https://css-tricks.com/snippets/css/a-guide-to-flexbox/) for greatly simplifying not only the CSS, but also the HTML by removing the need for elements strictly for styling purposes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T20:00:20.567",
"Id": "525355",
"Score": "0",
"body": "Yeah I need to go more in depth with flexbox and grid. Which of the two do you think would be more effective for this type of layout and more intuitive to use. @morbusg"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T15:00:31.930",
"Id": "525463",
"Score": "0",
"body": "I've no experience on grid, but flexbox I can definitely recommend."
}
] |
[
{
"body": "<p>Sick portfolio Jack. So instead of giving img a fixed size, you should give it a relative value (i.e percentage). For example:</p>\n<pre><code>.socials img{\n width: 125px; => 75%\n height: auto; \n margin: 40px;\n}\n</code></pre>\n<p>To make your site responsive, the next time you may consider adding bootstrap to it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T01:54:58.130",
"Id": "265869",
"ParentId": "265856",
"Score": "2"
}
},
{
"body": "<pre><code>section{\n /**/\n}\n</code></pre>\n<p>Dont assign styles by tag name, use classes instead. It could be multiple <code>section</code>s on the page.</p>\n<pre><code>.main-title a p {\n</code></pre>\n<p>The same.</p>\n<pre><code>#text2{\n</code></pre>\n<p>What does it means? And where is <code>text1</code>?</p>\n<pre><code>#web-text{\n</code></pre>\n<p>Now I know, that its web-site... (sarcasm).</p>\n<pre><code>.container-pro{\n</code></pre>\n<p>Professional?</p>\n<pre><code>.galleryImg {\n</code></pre>\n<p>Why not <code>.gallery-img</code>?</p>\n<pre><code><img src="resources/svg/Email svg.svg">\n</code></pre>\n<p>Spaces in filenames is a bad practice.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T11:03:43.510",
"Id": "265948",
"ParentId": "265856",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T16:50:52.173",
"Id": "265856",
"Score": "0",
"Tags": [
"javascript",
"beginner",
"html",
"css",
"mobile"
],
"Title": "Portfolio Website Responsive Design"
}
|
265856
|
<p>I'm learning C# and have written the below class to encapsulate the game state of Conway's Game of Life and its update methods. I'm also learning about implementing light automated unit tests for this project from the beginning. My overall goal is to build an Android app implementation of the game (using Xamarin) where this class is a component.</p>
<pre><code>// This code is intended to be a component in an Android app implementation of Conway's Game of Life,
// built with C# and Xamarin.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConwayStateExplorer
{
// This exception type is used within the ConwayStateVector class to indicate either that live cells have reached
// the boundary of game space during a state update, or that a caller has passed invalid coordinates to
// ConwayStateVector.CellState or ConwayStateVector.NextCellStateUpdate.
public class GameStateUpdateOutOfBoundsException : Exception
{
public GameStateUpdateOutOfBoundsException()
{
}
public GameStateUpdateOutOfBoundsException(string message)
: base(message)
{
}
public GameStateUpdateOutOfBoundsException(string message, Exception inner)
: base(message, inner)
{
}
}
// This class encapsulates the game state and the methods used to update it.
public class ConwayStateVector
{
// The game state is held as an byte[,] in _currentState, where 1 represents a live cell and 0 a dead cell.
// _stateSnapshot is used by UpdateState to store a version of the game state that stays constant during a
// game state update computation. Callers interact with CurrentIndex, CellState and NextCellStateUpdate using
// array centred origin coordinates (variables prefixed with centre) while the game state is handled internally
// using 0 based array coordinates (variables prefixed with array). The CentreToArrayCoordinates and
// ArrayToCentreCoordinates methods are used to convert between these two coordinate systems.
private byte[,] _currentState, _stateSnapshot;
private (int i, int j) _currentIndex, _centreCell, _centreMin, _centreMax;
public readonly int ArrayLimitI, ArrayLimitJ;
public readonly (int i, int j) CentreMinLimit, CentreMaxLimit;
public ConwayStateVector(int sizeI, int sizeJ)
{
_currentState = new byte[sizeI, sizeJ];
_stateSnapshot = new byte[sizeI, sizeJ];
ArrayLimitI = sizeI - 1;
ArrayLimitJ = sizeJ - 1;
_centreCell.i = sizeI / 2 - 1;
_centreCell.j = sizeJ / 2 - 1;
CentreMinLimit = ArrayToCentreCoordinates(0, 0);
CentreMaxLimit = ArrayToCentreCoordinates(ArrayLimitI, ArrayLimitJ);
}
// The CurrentIndex property is used to set the index in _currentState that will be read the next time
// the CellState property is called.
public (int centreI, int centreJ) CurrentIndex
{
set
{
(int, int) newArrayIndex;
if (value.centreI < CentreMinLimit.i || value.centreI > CentreMaxLimit.i
|| value.centreJ < CentreMinLimit.j || value.centreJ > CentreMaxLimit.j)
{
throw new GameStateUpdateOutOfBoundsException
("CurrentIndex: Attempt to set next game state read index outside bounds of game space.");
}
newArrayIndex = CentreToArrayCoordinates(value.centreI, value.centreJ);
_currentIndex = newArrayIndex;
}
}
public int CellState
{
get { return _currentState[_currentIndex.i, _currentIndex.j]; }
}
// This property is used to flip the state of a specified index in _currentState from 0 to 1 or vice versa.
public (int centreI, int centreJ) NextCellStateUpdate
{
set
{
(int i, int j) arrayIndex;
if (value.centreI < CentreMinLimit.i || value.centreI > CentreMaxLimit.i
|| value.centreJ < CentreMinLimit.j || value.centreJ > CentreMaxLimit.j)
{
throw new GameStateUpdateOutOfBoundsException
("SetCellState: Attempt to set cell state outside bounds of game space.");
}
arrayIndex = CentreToArrayCoordinates(value.centreI, value.centreJ);
if (_currentState[arrayIndex.i, arrayIndex.j] == 0)
{
_currentState[arrayIndex.i, arrayIndex.j] = 1;
}
else
{
_currentState[arrayIndex.i, arrayIndex.j] = 0;
}
if (value.centreI - 1 < _centreMin.i) { _centreMin.i = value.centreI - 1; }
if (value.centreI + 1 > _centreMax.i) { _centreMax.i = value.centreI + 1; }
if (value.centreJ - 1 < _centreMin.j) { _centreMin.j = value.centreJ - 1; }
if (value.centreJ + 1 > _centreMax.j) { _centreMax.j = value.centreJ + 1; }
}
}
// These two methods are used to transform from centre to array coordinates and vice versa, respectively.
private (int, int) CentreToArrayCoordinates(int i, int j)
{
return (_centreCell.i + i, _centreCell.j + j);
}
private (int, int) ArrayToCentreCoordinates(int i, int j)
{
return (i - _centreCell.i, j - _centreCell.j);
}
// This method is used to update the game state at each game logic tick according to the rules of the game.
public void UpdateState()
{
int i, j;
(int i, int j) arrayMin, arrayMax, newCentreMin = (0, 0), newCentreMax = (0, 0), centrePos;
int baseValue, posIZeroJValue, posINegJValue, zeroINegJValue, negINegJValue, negIZeroJValue, negIPosJValue;
int zeroIPosJValue, posIPosJValue, localPopulation;
bool lifeFlag;
if (_centreMin.i <= CentreMinLimit.i || _centreMax.i >= CentreMaxLimit.i || _centreMin.j <= CentreMinLimit.j
|| _centreMax.j >= CentreMaxLimit.j)
{
throw new GameStateUpdateOutOfBoundsException("UpdateState: The boundary of game space has been reached.");
}
arrayMin = CentreToArrayCoordinates(_centreMin.i, _centreMin.j);
arrayMax = CentreToArrayCoordinates(_centreMax.i, _centreMax.j);
Array.Copy(_currentState, 0, _stateSnapshot, 0, (ArrayLimitI + 1) * (ArrayLimitJ + 1));
for (i = arrayMin.i; i <= arrayMax.i; i++)
{
for (j = arrayMin.j; j <= arrayMax.j; j++)
{
centrePos = ArrayToCentreCoordinates(i, j);
baseValue = _stateSnapshot[i, j];
posIZeroJValue = _stateSnapshot[i + 1, j];
posINegJValue = _stateSnapshot[i + 1, j - 1];
zeroINegJValue = _stateSnapshot[i, j - 1];
negINegJValue = _stateSnapshot[i - 1, j - 1];
negIZeroJValue = _stateSnapshot[i - 1, j];
negIPosJValue = _stateSnapshot[i - 1, j + 1];
zeroIPosJValue = _stateSnapshot[i, j + 1];
posIPosJValue = _stateSnapshot[i + 1, j + 1];
localPopulation = posIZeroJValue + posINegJValue + zeroINegJValue + negINegJValue
+ negIZeroJValue + negIPosJValue + zeroIPosJValue + posIPosJValue;
if (baseValue == 1)
{
if (localPopulation == 2 || localPopulation == 3)
{
lifeFlag = true;
}
else
{
_currentState[i, j] = 0;
lifeFlag = false;
}
}
else
{
if (localPopulation == 3)
{
_currentState[i, j] = 1;
lifeFlag = true;
}
else { lifeFlag = false; }
}
if (lifeFlag == true)
{
if (centrePos.i < newCentreMin.i) { newCentreMin.i = centrePos.i; }
else if (centrePos.i > newCentreMax.i) { newCentreMax.i = centrePos.i; }
else if (centrePos.j < newCentreMin.j) { newCentreMin.j = centrePos.j; }
else if (centrePos.j > newCentreMax.j) { newCentreMax.j = centrePos.j; }
}
}
}
_centreMin = newCentreMin;
_centreMax = newCentreMax;
}
// This method is intended to allow the unit tests to access _currentState.
public byte[,] TestState()
{
return _currentState;
}
}
class Program
{
static void Main(string[] args)
{
string command, position, runStatus = "run", stateText;
string[] components;
int componentI, componentJ;
ConwayStateVector gameState = new ConwayStateVector(8, 8);
byte[,] initialState1 = { { 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 1, 0, 0, 0, 0, 0, 0 },
{ 0, 1, 0, 0, 0, 0, 0, 0 },
{ 0, 1, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 } };
do
{
Console.WriteLine("\nEnter command: ");
command = Console.ReadLine();
if (command == "set")
{
Console.WriteLine("\nEnter position: ");
position = Console.ReadLine();
components = position.Split(',');
componentI = Convert.ToInt32(components[0]);
componentJ = Convert.ToInt32(components[1]);
gameState.NextCellStateUpdate = (componentI, componentJ);
stateText = ShowState(gameState);
Console.WriteLine(stateText);
}
else if (command == "u")
{
gameState.UpdateState();
stateText = ShowState(gameState);
Console.WriteLine(stateText);
}
else { runStatus = "Stop"; }
} while (runStatus == "run");
}
// This function transforms the game state to a text representation so this can be output in the console.
static string ShowState(ConwayStateVector gameState)
{
int i, j, state;
string outputString = "";
for (i = -3; i <= 4; i++)
{
for (j = -3; j <= 4; j++)
{
gameState.CurrentIndex = (i, j);
state = gameState.CellState;
outputString = outputString + Convert.ToString(state) + " ";
}
outputString = outputString + "\n";
}
return outputString;
}
}
}
</code></pre>
<p>These are the test methods.</p>
<pre><code>using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Linq;
using ConwayStateExplorer;
namespace ConwayStateTests
{
[TestClass]
public class StateUpdateTests
{
[TestMethod]
// This method is used to test whether ConwayStateVector.UpdateState correctly updates the game state when
// given a set of example states.
public void UpdateState_CorrectStateUpdate()
{
ConwayStateVector gameState;
byte[,] nextState;
// This tests live cells with 0 live neighbours and dead cells with 0 or 1 live neighbours.
byte[,] initialState1 = { { 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 0, 0, 1, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 0, 0, 1, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 } };
// This tests live cells with 1 live neighbour and dead cells with 0, 1 or 2 live neighbours.
byte[,] initialState2 = { { 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 } };
// This tests live cells with 1 or 2 live neighbours and dead cells with 0, 1, 2 or 3 live neighbours.
byte[,] initialState3 = { { 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 1, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 } };
// This tests live cells with 3 live neighbours and dead cells with 0, 1 or 2 live neighbours.
byte[,] initialState4 = { { 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 } };
// This tests live cells with 2, 3 or 4 live neighbours and dead cells with 0, 1, 2 or 3 live neighbours.
byte[,] initialState5 = { { 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 1, 1, 0, 0, 0 },
{ 0, 0, 1, 1, 1, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 } };
// This tests live cells with 2 or 4 live neighbours and dead cells with 0, 1, 2, 3 or 8 live neighbours.
byte[,] initialState6 = { { 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 1, 0, 0, 0 },
{ 0, 0, 1, 0, 1, 0, 0, 0 },
{ 0, 0, 1, 1, 1, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 } };
byte[,] predictedState1 = { { 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 } };
byte[,] predictedState2 = { { 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 } };
byte[,] predictedState3 = { { 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 1, 0, 0, 0, 0 },
{ 0, 0, 0, 1, 0, 0, 0, 0 },
{ 0, 0, 0, 1, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 } };
byte[,] predictedState4 = { { 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 0, 0, 0, 0 },
{ 0, 0, 1, 1, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 } };
byte[,] predictedState5 = { { 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 0, 1, 0, 0, 0 },
{ 0, 0, 1, 0, 1, 0, 0, 0 },
{ 0, 0, 0, 1, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 } };
byte[,] predictedState6 = { { 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 1, 0, 0, 0, 0 },
{ 0, 0, 1, 0, 1, 0, 0, 0 },
{ 0, 1, 0, 0, 0, 1, 0, 0 },
{ 0, 0, 1, 0, 1, 0, 0, 0 },
{ 0, 0, 0, 1, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 } };
gameState = new ConwayStateVector(8, 8);
SetInitialState(gameState, initialState1);
gameState.UpdateState();
nextState = gameState.TestState();
Assert.IsTrue(CompareStates(predictedState1, nextState), "UpdateState test 1 failed.");
gameState = new ConwayStateVector(8, 8);
SetInitialState(gameState, initialState2);
gameState.UpdateState();
nextState = gameState.TestState();
Assert.IsTrue(CompareStates(predictedState2, nextState), "UpdateState test 2 failed.");
gameState = new ConwayStateVector(8, 8);
SetInitialState(gameState, initialState3);
gameState.UpdateState();
nextState = gameState.TestState();
Assert.IsTrue(CompareStates(predictedState3, nextState), "UpdateState test 3 failed.");
gameState = new ConwayStateVector(8, 8);
SetInitialState(gameState, initialState4);
gameState.UpdateState();
nextState = gameState.TestState();
Assert.IsTrue(CompareStates(predictedState4, nextState), "UpdateState test 4 failed.");
gameState = new ConwayStateVector(8, 8);
SetInitialState(gameState, initialState5);
gameState.UpdateState();
nextState = gameState.TestState();
Assert.IsTrue(CompareStates(predictedState5, nextState), "UpdateState test 5 failed.");
gameState = new ConwayStateVector(8, 8);
SetInitialState(gameState, initialState6);
gameState.UpdateState();
nextState = gameState.TestState();
Assert.IsTrue(CompareStates(predictedState6, nextState), "UpdateState test 6 failed.");
}
[TestMethod]
// This method is used to test if ConwayStateVector.UpdateState correctly detects that the boundary of
// game space has been reached and throws the appropriate exception.
public void UpdateState_InvalidStateUpdate()
{
ConwayStateVector gameState = new ConwayStateVector(8, 8);
byte[,] initialState1 = { { 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 1, 0, 0, 0, 0, 0, 0 },
{ 0, 1, 0, 0, 0, 0, 0, 0 },
{ 0, 1, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 } };
SetInitialState(gameState, initialState1);
Assert.ThrowsException<GameStateUpdateOutOfBoundsException>(() => gameState.UpdateState());
}
[TestMethod]
// This method is used to test if ConwayStateVector.NextCellStateUpdate correctly updates the game state,
// with 0 to 1 and 1 to 0 cell flips tested.
public void NextCellStateUpdate_ValidUpdate()
{
ConwayStateVector gameState = new ConwayStateVector(8, 8);
byte[,] nextState;
byte[,] predictedState1 = { { 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 1, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 } };
byte[,] predictedState2 = { { 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 } };
gameState.NextCellStateUpdate = (1, 2);
nextState = gameState.TestState();
Assert.IsTrue(CompareStates(predictedState1, nextState), "NextCellStateUpdate test 1 failed.");
gameState.NextCellStateUpdate = (1, 2);
Assert.IsTrue(CompareStates(predictedState2, nextState), "NextCellStateUpdate test 2 failed.");
}
[TestMethod]
// This method is used to test if ConwayStateVector.NextCellStateUpdate correctly detects that the centred
// origin coordinates passed are outside of game space and throws the appropriate exception.
public void NextCellStateUpdate_InvalidUpdate()
{
ConwayStateVector gameState = new ConwayStateVector(8, 8);
Assert.ThrowsException<GameStateUpdateOutOfBoundsException>(() => gameState.NextCellStateUpdate = (-4, 3));
}
[TestMethod]
// This method is used to test if ConwayStateVector.CurrentIndex and ConwayStateVector.CellState correctly
// read the game state.
public void CurrentIndexPlusCellState_ValidIndex()
{
ConwayStateVector gameState = new ConwayStateVector(8, 8);
byte[,] initialState = { { 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 1, 0, 1, 0, 0, 0 },
{ 0, 0, 1, 0, 1, 0, 0, 0 },
{ 0, 0, 0, 1, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0 } };
SetInitialState(gameState, initialState);
gameState.CurrentIndex = (1, 0);
Assert.IsTrue(gameState.CellState == 1, "CurrentIndexPlusCellState test 1 failed.");
gameState.CurrentIndex = (3, -1);
Assert.IsTrue(gameState.CellState == 0, "CurrentIndexPlusCellState test 2 failed.");
}
[TestMethod]
// This method is used to test if ConwayStateVector.CurrentIndex correctly detects that the centred origin
// coordinates passed are outside of game space and throws the appropriate exception.
public void CurrentIndexPlusCellState_InvalidIndex()
{
ConwayStateVector gameState = new ConwayStateVector(8, 8);
Assert.ThrowsException<GameStateUpdateOutOfBoundsException>(() => gameState.CurrentIndex = (2, 5));
}
// This method compares the predicted next state of the ConwayStateVector object with its actual state
// to check if the game logic has worked correctly.
private bool CompareStates(byte[,] predictedState, byte[,] actualState)
{
int i, j;
for (i = 0; i < 7; i++)
{
for (j = 0; j < 7; j++)
{
if (predictedState[i, j] == actualState[i, j]) { }
else { return false; }
}
}
return true;
}
// This method is used to automate the testing of ConwayStateVector.UpdateState by setting the initial state of
// gameState based on one of the initialState patterns.
private void SetInitialState(ConwayStateVector gameState, byte[,] newState)
{
int i, j;
for (i = 0; i <= 7; i++)
{
for (j = 0; j <= 7; j++)
{
if (newState[i, j] == 1) { gameState.NextCellStateUpdate = (i - 3, j - 3); }
}
}
}
}
}
</code></pre>
<p>Could anyone provide feedback on the use of language features, if you think this is factored sensibly and / or the test methods? Any help would be appreciated. Thanks.</p>
|
[] |
[
{
"body": "<p>You've implemented the "game of life" as an actual game where you have to enter coordinates. That's really weird to me; it's a zero-player game - the living cells play the game.</p>\n<p>I've got no clue when I started to read into the code why there are two coordinate systems and two naming conventions. To me this just confuses matters.</p>\n<h2>GameStateUpdateOutOfBoundsException</h2>\n<pre><code>public class GameStateUpdateOutOfBoundsException : Exception\n</code></pre>\n<p>It seems to me that you describe that the exception is used for two different purposes. That's not a good idea, even if it shortens code. However, you can shorten the exception by only haven an <code>XxxException(String)</code> method as you don't use it within a <code>catch</code> and always provide a message.</p>\n<h2>ConwayStateVector</h2>\n<p><strong>Fields</strong></p>\n<pre><code>private (int i, int j) _currentIndex, _centreCell, _centreMin, _centreMax;\n</code></pre>\n<p>Coordinates are almost always displayed using <code>x</code> and <code>y</code>. <code>i</code> and <code>j</code> are almost always used for indexing instead. So if you ever want to have a for / next loop for anything other than the coordinates, you'll run into name clashes; not a good idea. I'd use <code>Width</code> and <code>Height</code> for the sizes and <code>x</code> and <code>y</code> for the individual coordinates though.</p>\n<p>Only <code>_centreCell</code> is currently initialized, and that means that other coordinates are in a <code>null</code> / invalid state.</p>\n<pre><code>private byte[,] _currentState, _stateSnapshot;\n</code></pre>\n<p>If you store a state, you'd store it in a <code>State</code> specific class. This class doesn't hold one state, it stores two. Even worse, it keeps track of a current position, which is something that doesn't need to be exposed. It would e.g. preclude a solution that uses multiple threads to create the next state. <strong>Always</strong> keep state to the minimal amount required.</p>\n<p>Instead of using <code>_</code> prefixes, it is common to simply keep the normal name without <code>_</code>; if you must you can use <code>this.<fieldname></code> if confusion arises. It is not actively harmful to use underscores for internal fields; however if you do so then all internal fields should start with a hash, not just a few.</p>\n<pre><code>public readonly int ArrayLimitI, ArrayLimitJ;\n</code></pre>\n<p>First of all, it is much easier to just create a getter and return the size of the arrays. Furthermore, you now make an implementation detail of your class visible: that you use arrays. That's generally not done, as it means you cannot rewrite it to use other constructions later.</p>\n<p>I'd be more comfortable with names like <code>BoardWidth</code> and <code>BoardHeight</code>, for instance. Games are played on a board (the board is the "game space", so actually you've hinted at this yourself). Storing them as <code>Max</code> and <code>Min</code> doesn't work either: the only time you use them is when you actually need to increase their size by 1 again.</p>\n<p><strong>ConwayStateVector</strong></p>\n<pre><code>public ConwayStateVector(int sizeI, int sizeJ)\n</code></pre>\n<p>To me a good start would be a board with any width, and where each array has the same "height".</p>\n<p><strong>CurrentIndex</strong></p>\n<pre><code>public (int centreI, int centreJ) CurrentIndex\n</code></pre>\n<p>This is possibly a current <em>position</em> indicated by <em>two coordinates</em>. An index is not generally thought of as having two values. Even if you would keep to using the word index then <code>i</code> and <code>j</code> would be <em>two indices</em> just like you have <em>two coordinates</em>; they'd probably still together would indicate one position (or possibly one location) though.</p>\n<p>Later in the main method you have <code>Console.WriteLine("\\nEnter position: ")</code>. That should have provided a hint. I see a lot of people trying to be too smart when it comes to naming variables. There is a board. There is a position on a board consisting of two coordinates. That's it.</p>\n<pre><code>(int, int) newArrayIndex;\n</code></pre>\n<p>You don't need a local variable here, you can directly assign to the field.</p>\n<p><strong>UpdateState</strong></p>\n<p>This method is <em>much</em> to complex. The number of variables is a very clear indication of it. Some purists would just use up to 7 lines, but that's going a bit too deep. Having 18 local variables to keep track of is however a very clear indication that you've put too much in a single method.</p>\n<p>In languages such as C# you only declare variables just before you assign a value to them. That will at least limit the scope of the variables <em>especially</em> for the reader.</p>\n<pre><code>if (_centreMin.i <= CentreMinLimit.i || _centreMax.i >= CentreMaxLimit.i || _centreMin.j <= CentreMinLimit.j\n || _centreMax.j >= CentreMaxLimit.j)\n{\n throw new GameStateUpdateOutOfBoundsException("UpdateState: The boundary of game space has been reached.");\n}\n</code></pre>\n<p>I see many of these tests. If you just loop over <code>y</code> and loop over <code>x</code> within the <code>y</code> loop then you'd only have to check if one of the neighboring cells exist, e.g. <code>if (exists(position) && isalive(position)) then neighboringCellCount++</code>. See, no exceptions necessary (and if you program this badly then you will get an <code>IndexOutOfBoundsException</code> anyway.</p>\n<pre><code>posIZeroJValue = _stateSnapshot[i + 1, j];\n</code></pre>\n<p>Have you watched "Ender's game"? You start by defining directions. What about <code>n</code>, <code>ne</code>, <code>e</code>, <code>se</code>, <code>s</code>, <code>sw</code>, <code>w</code> and <code>nw</code>? A lot shorter than these descriptions, right? Although it is questionable if you need those if you just loop over <code>y</code> and <code>x</code> for getting the neighbors.</p>\n<p>You could also create a readonly tuple I suppose <code>private readonly (int, int) NORTH = (0, -1)</code>, for instance. Generally we use <code>x=0, y=0</code> to be the northwest, and then travel east by increasing <code>x</code> and south by increasing <code>y</code>) as most computer screens are created that way.</p>\n<h2>Program</h2>\n<p><strong>Main</strong></p>\n<pre><code> byte[,] initialState1 = { { 0, 0, 0, 0, 0, 0, 0, 0 },\n { 0, 1, 0, 0, 0, 0, 0, 0 },\n { 0, 1, 0, 0, 0, 0, 0, 0 },\n { 0, 1, 0, 0, 0, 0, 0, 0 },\n { 0, 0, 0, 0, 0, 0, 0, 0 },\n { 0, 0, 0, 0, 0, 0, 0, 0 },\n { 0, 0, 0, 0, 0, 0, 0, 0 },\n { 0, 0, 0, 0, 0, 0, 0, 0 } };\n</code></pre>\n<p>Alright, but what about using resources here instead of literals? And why is the game state never set to this <code>initialState1</code>?</p>\n<pre><code>components = position.Split(',');\ncomponentI = Convert.ToInt32(components[0]);\ncomponentJ = Convert.ToInt32(components[1])\n</code></pre>\n<p>Although you should not need internal exceptions when required, you should definitely sanitize your input. You should for instance test if the string consists of two numbers separated by a comma (and maybe whitespace) and check if the <code>x</code> and <code>y</code> are in the right position.</p>\n<pre><code>else { runStatus = "Stop"; }\n</code></pre>\n<p>Any type error and you stop? That's rude. Just create a <code>stop</code> command please.</p>\n<pre><code>for (i = -3; i <= 4; i++)\n{\n for (j = -3; j <= 4; j++)\n</code></pre>\n<p>All that work for creating max and min values, and now you just use literals.</p>\n<h2>StateUpdateTests</h2>\n<p><strong>UpdateState_CorrectStateUpdate</strong></p>\n<p>Why not keep the tests with their initial state and predicated state separate from each other? You're again trying too much at once. Furthermore, if you are doing the counting instead of the computer, usually something is amiss.</p>\n<p><strong>CurrentIndexPlusCellState_ValidIndex</strong></p>\n<pre><code>// This method is used to test if ConwayStateVector.CurrentIndex and ConwayStateVector.CellState correctly\n// read the game state.\n\ngameState.CurrentIndex = (1, 0);\nAssert.IsTrue(gameState.CellState == 1, "CurrentIndexPlusCellState test 1 failed.");\ngameState.CurrentIndex = (3, -1);\nAssert.IsTrue(gameState.CellState == 0, "CurrentIndexPlusCellState test 2 failed.");\n</code></pre>\n<p>At this point you've completely lost me. I presume that <code>3, -1</code> is an invalid cell state? Why would it be <code>0</code> in that case? Isn't <code>0</code> mean that it is dead?</p>\n<p>At this point, I may need training; which is weird because I'm pretty sure I've known about the game of life for about 30 years.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T09:38:20.803",
"Id": "525147",
"Score": "0",
"body": "OK, thanks for your detailed feedback. To answer your first implied question about why the user can set the game state with the console, in any implementation the player (in the 0 player game) needs to be able to set the initial state. This class is intended to be a component in a larger implementation of the game, as mentioned in the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T13:10:43.943",
"Id": "525159",
"Score": "0",
"body": "Alright. Do you have any specific goals set for this implementation? The game of life is well known because of its elegance - just a few rules create this huge complexity, much like e.g. Mandelbrot does for fractal geometry. To be honest, the code doesn't currently reflect that but maybe that's because I might not know the goals. I do like that the game itself seems decoupled from any GUI elements though; that's a very common mistake."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T10:51:47.367",
"Id": "525229",
"Score": "0",
"body": "The core of the app is intended to present the user with a view of the board and the choice to set an initial state by screen tapping the initial live cells, or choosing from some preset patterns."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T11:15:23.043",
"Id": "525230",
"Score": "0",
"body": "The app is intended to present the user with a scaleable view of the board, where they can set an initial state by tapping the initial live cells and then run the game. As for the two coordinate systems the board used in the app will be larger (up to 2048 * 2048) and for efficiency I wanted to avoid applying the game logic to every cell on every tick. The application area is limited to a rectangle that dynamically grows away from the centre of the board, or shrinks towards it as necessary. Having two coordinate systems seems to make some of the code to implement that scaling logic simpler."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T17:06:19.417",
"Id": "525258",
"Score": "0",
"body": "OK, having the possibility to expand into the negative values of an axis is a great design. But even then I would stick to this one centered coordinate system and hide anything below it from the user."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T00:14:03.577",
"Id": "265866",
"ParentId": "265857",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T16:50:55.430",
"Id": "265857",
"Score": "2",
"Tags": [
"c#",
"unit-testing",
"game-of-life"
],
"Title": "Conway's Game of Life in a C# class. Is this sensibly factored and well tested?"
}
|
265857
|
<p>I want to know if I can use shared memory to optimize my code and get better performance. I will explain how my code works:</p>
<p>The inputs to my kernel are a matrix <code>d_e</code> of size [75x19], array <code>d_l</code> and <code>d_f</code> both of size [75x1]. In my kernel I don't always use the the whole matrix <code>d_e</code> in the computation, rather it is done as follows:</p>
<ol>
<li>nc = 2^19 = 524288, I need to do the computation 524288 times, so
I need a total of 524288 threads.</li>
<li>In my kernel I create a binary array <code>lbo</code> of 19 digits, the array
represents the computation number in binary, so if it is computation
1 = 1000000000000000000, if its 3 then 1100000000000000000, if its
5242888 then 1111111111111111111 and so on</li>
<li>Based on that vector I choose the corresponding columns from the
matrix <code>d_e</code>, put them in a new matrix <code>f2</code>, then compute its transpose
in <code>ft2</code></li>
<li>for example if the binary vector is 5 = 1010000000000000000 , I take column 1 and 3 from matrix <code>d_e</code>, put them in <code>f2</code> and compute the transpose in <code>ft2</code></li>
<li>Do some other calculations</li>
<li>So each thread of the 524288 threads executed uses a different dimension of the matrix <code>d_e</code> according to the corresponding binary number.</li>
</ol>
<p>Currently I implement this procedure in a for loop, which I didn't include here because I believe it is straighforward(I can include it if someone wants to), what I am thinking of is the following:</p>
<p>if the computation is 7 = 1110000000000000000 , then I need column 1,2 and 3, but since thread 5 used column 1 and 3 in the computation, can I use shared memory to get columns 1 and 3, put them in <code>f2</code> which thread 7 uses and add column 2 to it or not? more importantly if this is achievable, is it going to be more efficient than a for loop?</p>
<p>Kernel</p>
<pre><code> __global__ void fun(double* l, double* f, double* e, int na, int nb, int nc)
{
bool* lbo = new bool[na];
int index = blockIdx.x * blockDim.x + threadIdx.x;
int stride = blockDim.x * gridDim.x;
for (int idx = index; idx < nc; idx += stride)
{
DB(idx, lbo, na);
bool bin = 1;
int count = 0;
for (int i = 0; i < na; i++)
{
if (lbo[i] == bin)
{
count++;
}
}
double* f2 = new double[nb * count];
double* ft2 = new double[nb * count];
// Do some computation
}
}
</code></pre>
<p>Main</p>
<pre><code>int main()
{
int na = 19;
int nb = 75;
int nc = 1 << na;
double* h_f = new double[nb];
double* h_l = new double[nb];
double** h_e = new double* [nb];
for (int i = 0; i < nb; i++)
{
h_e[i] = new double[na];
}
//Allocate d_l, d_f, d_e
size_t a = 2048;
cudaDeviceSetLimit(cudaLimitMallocHeapSize, a * 1024 * 1024);
int blockSize = 128;
int numBlocks = (nc + blockSize - 1) / blockSize;
fun << <numBlocks, blockSize >> > (d_l, d_f, d_e, na, nb, nc);
cudaDeviceSynchronize();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T14:36:51.067",
"Id": "525168",
"Score": "1",
"body": "Welcome to the Code Review Community. What we do here is review working code that you have written and make suggestions on how to improve that code. Do you have this code working using shared memory? Please read [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T19:01:16.177",
"Id": "265859",
"Score": "0",
"Tags": [
"c++",
"cuda"
],
"Title": "Using shared memory in cuda kernel to populate arrays of different dimensions"
}
|
265859
|
<p>I have implemented the following question and looking forward for the reviews.</p>
<p>Question Explanation :
We have a two-dimensional board game involving snakes. The board has two types of squares on it: +'s represent impassable squares where snakes cannot go, and 0's represent squares through which snakes can move. Snakes can only enter on the edges of the board, and each snake can move in only one direction. We'd like to find the places where a snake can pass through the entire board, moving in a straight line.</p>
<p>Here is an example board:</p>
<pre><code>col--> 0 1 2 3 4 5 6
+----------------------
row 0 | + + + 0 + 0 0
| 1 | 0 0 0 0 0 0 0
| 2 | 0 0 + 0 0 0 0
v 3 | 0 0 0 0 + 0 0
4 | + + + 0 0 0 +
</code></pre>
<p>Write a function that takes a rectangular board with only +'s and 0's, and returns two collections:</p>
<ul>
<li>one containing all of the row numbers whose row is completely passable by snakes, and</li>
<li>the other containing all of the column numbers where the column is completely passable by snakes.</li>
</ul>
<p>Complexity Analysis:</p>
<p>r: number of rows in the board
c: number of columns in the board</p>
<pre><code>straightBoard1 = [['+', '+', '+', '0', '+', '0', '0'],
['0', '0', '0', '0', '0', '0', '0'],
['0', '0', '+', '0', '0', '0', '0'],
['0', '0', '0', '0', '+', '0', '0'],
['+', '+', '+', '0', '0', '0', '+']]
findPassableLanes(straightBoard1) // = Rows: [1], Columns: [3, 5]
straightBoard2 = [['+', '+', '+', '0', '+', '0', '0'],
['0', '0', '0', '0', '0', '+', '0'],
['0', '0', '+', '0', '0', '0', '0'],
['0', '0', '0', '0', '+', '0', '0'],
['+', '+', '+', '0', '0', '0', '+']]
findPassableLanes(straightBoard2) // = Rows: [], Columns: [3]
straightBoard3 = [['+', '+', '+', '0', '+', '0', '0'],
['0', '0', '0', '0', '0', '0', '0'],
['0', '0', '+', '+', '0', '+', '0'],
['0', '0', '0', '0', '+', '0', '0'],
['+', '+', '+', '0', '0', '0', '+']]
findPassableLanes(straightBoard3) // = Rows: [1], Columns: []
straightBoard4 = [['+']]
findPassableLanes(straightBoard4) // = Rows: [], Columns: []
</code></pre>
<p>Solution Class</p>
<pre><code>import java.util.ArrayList;
public class MazePathFinder {
public static void main(String[] argv) {
char[][] straightBoard1 = {{'+', '+', '+', '0', '+', '0', '0'},
{'0', '0', '0', '0', '0', '0', '0'},
{'0', '0', '+', '0', '0', '0', '0'},
{'0', '0', '0', '0', '+', '0', '0'},
{'+', '+', '+', '0', '0', '0', '+'}};
char[][] straightBoard2 = {{'+', '+', '+', '0', '+', '0', '0'},
{'0', '0', '0', '0', '0', '+', '0'},
{'0', '0', '+', '0', '0', '0', '0'},
{'0', '0', '0', '0', '+', '0', '0'},
{'+', '+', '+', '0', '0', '0', '+'}};
char[][] straightBoard3 = {{'+', '+', '+', '0', '+', '0', '0'},
{'0', '0', '0', '0', '0', '0', '0'},
{'0', '0', '+', '+', '0', '+', '0'},
{'0', '0', '0', '0', '+', '0', '0'},
{'+', '+', '+', '0', '0', '0', '+'}};
char[][] straightBoard4 = {{'+'}};
ArrayList<ArrayList<Integer>> lists1 = findPassableLanes(straightBoard1);
System.out.println("Rows: " + lists1.get(0) + ", Columns: " + lists1.get(1));
ArrayList<ArrayList<Integer>> lists2 = findPassableLanes(straightBoard2);
System.out.println("Rows: " + lists2.get(0) + ", Columns: " + lists2.get(1));
ArrayList<ArrayList<Integer>> lists3 = findPassableLanes(straightBoard3);
System.out.println("Rows: " + lists3.get(0) + ", Columns: " + lists3.get(1));
ArrayList<ArrayList<Integer>> lists4 = findPassableLanes(straightBoard4);
System.out.println("Rows: " + lists4.get(0) + ", Columns: " + lists4.get(1));
}
public static ArrayList<ArrayList<Integer>> findPassableLanes(char[][] matrix) {
ArrayList<Integer> rowList = new ArrayList<>();
ArrayList<Integer> columnList = new ArrayList<>();
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
for (int row = 0; row < matrix.length - 1; row++) {
if (matrix[row][0] == '0' && dfs(matrix, row, 0, 1)) {
rowList.add(row);
}
}
for (int column = 0; column < matrix[0].length - 1; column++) {
if (matrix[0][column] == '0' && dfs(matrix, 0, column, 0)) {
columnList.add(column);
}
}
result.add(rowList);
result.add(columnList);
return result;
}
public static boolean dfs(char[][] matrix, int row, int column, int flag) {
if (flag == 1 && column == matrix[0].length - 1 && matrix[row][matrix[0].length - 1] == '0') return true;
if (flag == 0 && row == matrix.length - 1 && matrix[matrix.length - 1][column] == '0') return true;
if (row < 0 || column < 0 || row > matrix.length - 1 || column > matrix.length || matrix[row][column] != '0')
return false;
boolean result;
if (flag == 1) {
result = dfs(matrix, row, column + 1, 1);
} else {
result = dfs(matrix, row + 1, column, 0);
}
return result;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T07:29:16.490",
"Id": "525138",
"Score": "1",
"body": "This is the third question involving depth first search you have posted in a short time. You may have fallen into the good old \"hammer trap.\" I.e. thinking that all problems look like \"nails\" if you only have a \"hammer\" as a tool. This problem is literally: checking if a one dimensional array consists of only zeros. You don't need DFS for that. Did you get tricked by your professor?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T07:32:03.680",
"Id": "525139",
"Score": "0",
"body": "This is just the second question and only intersection of this algorithms are borh of the operations on maze. So this is totaly fine"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T07:38:21.657",
"Id": "525142",
"Score": "0",
"body": "Sorry, your problem description was misleading. You are just asking the same question about path finding using DFS again and again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T05:05:43.430",
"Id": "525206",
"Score": "0",
"body": "All you need to do is convert the pluses to ones, and then get the column sums and row sums, and find which of those sums are 0."
}
] |
[
{
"body": "<p>The one big thing worth saying has already been said: This isn't a problem where DFS is needed. This could and should be checked using nested <code>for</code>-loops, iteratively checking all rows and columns. Recursion is probably slower, certainly heavier on memory and doesn't make much sense here.</p>\n<p>Regarding the <code>dfs</code> function:</p>\n<ul>\n<li>Use curly brackets for the three long <code>if</code>s and put the <code>return</code> on a new line. It improves readability and prevents bugs. (hence it's considered a good practice to do so).</li>\n<li>The last <code>if</code> is useless. You only increment <code>row</code> and <code>column</code> by one, so the third and fourth conditions will always be caught by the <code>if</code>s before them since <code>row == matrix.length - 1</code> will always be hit before <code>row > matrix.length - 1</code>. The first and second tests won't happen since you start the two values at <code>0</code> and only ever increment them. The last one just doesn't make sense. It's probably a leftover from a DFT maze path search where this field is the exit.</li>\n<li><code>int flag</code> is poorly named and the type doesnt make much sense. It should be changed to <code>boolean doRows</code> or <code>boolean doCols</code> with the rest of the code changed accordingly. As is, the reader is left to wonder what this flag is for.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T07:45:37.370",
"Id": "265980",
"ParentId": "265860",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T19:15:17.580",
"Id": "265860",
"Score": "-1",
"Tags": [
"java",
"matrix",
"depth-first-search"
],
"Title": "Find Passable Lanes in Rows and Columns"
}
|
265860
|
<p>I would like the array elements to minimize by preserving their orders. For example:</p>
<ul>
<li><code>3,7,9,7</code> is given <code>1,2,3,2</code> is yielded</li>
<li><code>1,99,90,95,99</code> is given <code>1,4,2,3,4</code> is yielded.</li>
</ul>
<p>Think array can be ranged btw 0 to 100, exclusively. My try’s time complexity is <span class="math-container">\$O(n^3 + n)\$</span>.</p>
<p>Can there be more efficient way to solve this?</p>
<pre><code>int[] arr = new int[] {2,5,3,5}; // example input
var copy = (int[])arr.Clone();
var num = 101;
foreach(var x in arr)
{
var min = copy.Min();
for(int i = 0 ; i < arr.Length; i++)
if(min == arr[i])
{
copy[i] = num;
}
num++;
}
for (int i = 0; i < copy.Length; i++)
{
copy[i] = copy[i] % 100;
}
</code></pre>
|
[] |
[
{
"body": "<h3>Indents</h3>\n<p>I've spent a minute struggling to understand that <code>copy[i] = num;</code> happens inside the second <code>for</code> loop. Please, indent the code to make it readable - you will gain from it in the first place.</p>\n<h3>Your algorithm is <span class=\"math-container\">\\$O(n^2)\\$</span></h3>\n<p>First, <span class=\"math-container\">\\$O(n^3+n) = O(n^3)\\$</span>. <span class=\"math-container\">\\$O(n)\\$</span> can be neglected because it is small compared to <span class=\"math-container\">\\$O(n^3)\\$</span>. Second, I don't see any third loop inside the second.</p>\n<h3>Better algo</h3>\n<ol>\n<li>Sort the copy of the array, <span class=\"math-container\">\\$O(n*log(n))\\$</span>.</li>\n<li>Make some search structure to convert a number in a sorted array into its index (map or another array), <span class=\"math-container\">\\$O(n)\\$</span>.</li>\n<li>Change all numbers in the first array to their indexes in sorted array, <span class=\"math-container\">\\$O(n)\\$</span>.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T06:56:08.680",
"Id": "265874",
"ParentId": "265862",
"Score": "5"
}
},
{
"body": "<p>This is zero based index and the example is one based index, can add one if need to match. I didn't do timing test to see if this is faster or even look at memory consumptions. To me this reads and makes it easier to maintain. I prefer maintenance over performance unless it's needs to be performance skewed for the area of code it's in.</p>\n<p><a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.sortedlist-2?view=net-5.0\" rel=\"nofollow noreferrer\">SortedList</a> takes two values but we don't care about the value so just toss in a bool to make it happy. Then using the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.sortedlist-2.indexofkey?view=net-5.0\" rel=\"nofollow noreferrer\">IndexOfKey</a> method that uses a binary search. Which under the covers uses <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.array.binarysearch?view=net-5.0\" rel=\"nofollow noreferrer\">Array.BinarySearch</a>. Could take SortedList out of the picture and use Array.BinarySearch to do similar to what SortListed is doing if having the bool value that isn't used is a deal breaker for you.</p>\n<pre><code>public static int[] Positions(params int[] items)\n{\n var sortedList = new SortedList<int, bool>(items.Length);\n for (var i = 0; i < items.Length; i++)\n {\n sortedList.TryAdd(items[i], false);\n }\n\n var result = new int[items.Length];\n for (var i = 0; i< items.Length; i++)\n {\n result[i] = sortedList.IndexOfKey(items[i]);\n }\n\n return result;\n}\n</code></pre>\n<p>EDIT: If you want to avoid SortedList you can do what it's doing pretty simple.</p>\n<pre><code>public static IEnumerable<int> Position(params int[] items)\n{\n var distinct = new HashSet<int>(items);\n var clone = new int[distinct.Count];\n distinct.CopyTo(clone);\n Array.Sort(clone);\n for (var i = 0; i < items.Length; i++)\n {\n yield return Array.BinarySearch(clone, items[i]) + 1;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T16:48:01.333",
"Id": "525173",
"Score": "0",
"body": "Interesting solution, `Positions(arr).Select(x => x+1)` fixes the final result."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T16:58:14.373",
"Id": "525174",
"Score": "1",
"body": "You can just do 'result[i] = sortedList.IndexOfKey(items[i]) + 1;' instead of looping through again. I assumed you wanted an array back. if wanting an ienumerable you can just yield return that statement and change the method signature"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T16:58:51.750",
"Id": "525175",
"Score": "0",
"body": "While `SortedList` (being key/value) is alienating given SortedDictionary: why not just use SortedSet?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T17:00:44.873",
"Id": "525176",
"Score": "1",
"body": "@greybeard SortedSet/SortedDictionary doesn't contain IndexOfKey"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T17:02:40.027",
"Id": "525177",
"Score": "0",
"body": "@CharlesNRice it is an elegant solution. Thank you sir."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T15:04:30.923",
"Id": "265882",
"ParentId": "265862",
"Score": "1"
}
},
{
"body": "<blockquote>\n<p>Can there be more efficient way to [canonicalise values between minV and maxV in an array preserving rank]?</p>\n</blockquote>\n<p>Yes. Let me suggest another mechanism in-stead of <em>sorting</em> / <em>ordering</em> (the latter being what most procedures with a name derived from <em>sort</em> do):<br />\nWhen the range of values maxV - minV is small, use an array about that size to</p>\n<ol>\n<li>find which values do appear<br />\n(When keeping count of value frequencies, this can be used for <em>ordering using value counts</em>: <a href=\"https://en.m.wikipedia.org/wiki/Counting_sort#Pseudocode\" rel=\"nofollow noreferrer\">counting sort</a>.)</li>\n<li>assign canonical values</li>\n<li>map input values to canonical values</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T07:33:37.223",
"Id": "265903",
"ParentId": "265862",
"Score": "0"
}
},
{
"body": "<p>You can improve the complexity to <code>O(N.Log(N))</code> (on average) at the expense of space by introducing an adjunct array containing the numbers 0..N-1 and sorting it at the same time as the original array.</p>\n<p>This will yield a set of indices that you can use to populate a results array like so:</p>\n<pre><code>int[] arr = { 1, 99, 90, 95, 99 };\nint[] tmp = Enumerable.Range(0, arr.Length).ToArray();\nint[] res = new int[arr.Length];\n\nArray.Sort(arr, tmp);\nint ind = 0;\n\nfor (int i = 0; i < arr.Length; ++i)\n{\n if (i == 0 || arr[i] != arr[i-1])\n ++ind;\n\n res[tmp[i]] = ind;\n}\n\nConsole.WriteLine(string.Join(", ", res)); // 1, 4, 2, 3, 4\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T09:15:20.733",
"Id": "265982",
"ParentId": "265862",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T22:19:07.100",
"Id": "265862",
"Score": "4",
"Tags": [
"c#",
"algorithm",
"array"
],
"Title": "Better way to minimize array elements"
}
|
265862
|
<p>I know this is a weird program but I am trying to learn how to write Python programs. This program will accept user input, starting by having the user specify a file path then continuously looping through a set of option which the user will choose.</p>
<p>The options are basic Pandas methods, get mean, variance, and standard deviation of a certain row, group certain columns, get info on csv file path. My biggest question is how could I better structure this file, how can it be more pythonic?</p>
<p>Suggestions on how I can use method overloads better are welcome. For example, my <code>GroupCols</code> method, is that the best way to allow for method overloading? Should I have <code>if __name__ "__main__":</code> at the very bottom of the program? Would it be better to have all of my methods as return functions and then <code>print()</code> the results after calling each function? Or the function just <code>print()</code>?</p>
<pre><code>import pandas as pd
class Data:
def __init__(self):
self.df = None
def OpenFile(self, filePath: str):
try:
self.df = pd.read_csv(filePath)
except Exception as ex:
print(str(ex))
print("Reenter file path before proceeding...\n")
return
def Head(self, coun: int = 0):
if coun == 0:
print(self.df.head())
return
print(self.df.head(coun))
def Info(self):
print(self.df.info())
def GroupCols(self, col1: str, col2: str = "", col3: str = ""):
try:
if not col2 and not col3:
grouped = self.df.groupby([col1])
self.GetStats(grouped)
elif col2 and not col3:
grouped = self.df.groupby([col1, col2])
self.GetStats(grouped)
elif col2 and col3:
grouped = self.df.groupby([col1, col2, col3])
self.GetStats(grouped)
elif not col2 and col3:
grouped = self.df.groupby([col1, col3])
self.GetStats(grouped)
except Exception as ex:
print(str(ex))
return
def GetCount(self, col: str) -> int:
if col:
return self.df[col].value_counts()
return 0
def GetStats(self, dfStats):
print("Mean : %r" %(dfStats.mean()))
print("Variance: %r" % (dfStats.var()))
print("Std Dev: %r" % (dfStats.std()))
</code></pre>
<pre><code>def main():
d = Data()
while True:
option = input("Choose an option:\n1 - Open New File\n2 - Get Head of file\n"+
"3 - Get Info on file\n4 - Group between 1 and 3 column\n"+
"5 - Get count of specified column\n6 - Exit\n")
if option == "1":
file = input('Enter the file path of the csv file:\n')
d.OpenFile(file)
continue
elif option == "2":
count = input("Enter number of rows to retrieve or enter 0\n")
d.Head(int(count))
continue
elif option == "3":
d.Info()
elif option == "4":
cols = input("Enter between 1 and 3 columns separated by a comma\n")
group = cols.split(',')
if len(group) == 1:
d.GroupCols(group[0])
elif len(group) < 3:
d.GroupCols(group[0], group[1])
else:
d.GroupCols(group[0], group[1], group[2])
elif option == "5":
col = input("Enter column name to get count of\n")
print(d.GetCount(col))
elif option == "6":
exit()
else:
print("Could not understand option. Enter numeric value\n")
if __name__ == "__main__":
main()
</code></pre>
|
[] |
[
{
"body": "<h2>Starting from your questions:</h2>\n<ul>\n<li><strong>...<code>GroupCols</code> method, is that the best way to allow for method overloading?</strong> I guess if what you mean is whether the way the function is defined does a function overload depending on the number of parameters you provide, then it technically does it. But it is not really the best way to deal with what you aim for there. Also, as you check for <code>not col2 and not col3</code> I think the type and default in the function definition should be more like <code>col2: Optional[str] = None</code>, if you want to make sure that checking on the parameters being provided works as expected.</li>\n<li><strong>Should I have <code>if __name__ "__main__":</code> at the very bottom of the program?</strong> Yes. This is ok as you have it.</li>\n<li><strong>Would it be better to have all of my methods as return functions and then <code>print()</code> the results after calling each function? Or the function just <code>print()</code>?</strong> My recommendation would be that, unless the function name conceptually states that it will print (such as the <code>display</code> function), it would be better for it to return a value to be printed. Also, if you opt for returning nothing, it should be typed in the function description (<code>def Info(self) -> None:</code>)</li>\n</ul>\n<h2>As other quick notes:</h2>\n<ul>\n<li>You are consistently checking in several functions (<code>GroupCols</code> and <code>GetCount</code>) <code>str=""</code> as if this would be <code>False</code> or <code>None</code>, and that is not the case. if <code>str="" -> bool(str)==True</code>. So be mindful of that, empty string is a value of string.</li>\n<li>Considering the type of functions you created, I am not 100% sure there is any benefit from you making them as methods of a class. It would make much more sense for them to just be functions to which a dataframe is provided.</li>\n<li>To be honest, you barely need any function, as all your calls can be directly processed by DataFrame methods, but as you say that this is a learning exercise I will not go into that.</li>\n<li>Naming convention in python would dictate that the functions would be named as lowercase, underscored, not camelcase. Then <code>GroupCols</code> -> <code>group_cols</code> and so on.</li>\n<li>for <code>GroupCols</code> and <code>GetCount</code> it would be good to check if the provided columns exist in the dataframe. On the first one you have controlled the error that it will produce if not, but that is not the case on the second function.</li>\n</ul>\n<h2>On code simplification:</h2>\n<p><code>pandas</code> head method already takes dataframe size 0 into account:</p>\n<pre><code> def Head(self, coun: int = 0) -> None:\n print(self.df.head(coun))\n</code></pre>\n<p>The <code>GroupCols</code> function should probably deal with an iterable as input. It would make it much more flexible and easier to read/understand (you'll need to <code>from typing import Iterable</code>).</p>\n<pre><code> def GroupCols(self, cols: Iterable[str]) -> None:\n try:\n grouped = self.df.groupby(cols)\n self.GetStats(grouped)\n except Exception as ex:\n print(str(ex))\n return\n</code></pre>\n<p>You'll just need to make sure to call it in you main loop as <code>d.GroupCols(group)</code> and it will work for any number of columns.</p>\n<p>Hope this helps!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T04:49:09.777",
"Id": "525204",
"Score": "0",
"body": "thanks I will use this advice. I think the method overloading I was wondering the best way to use it and did not think `None` being newer to python"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T11:59:41.090",
"Id": "265878",
"ParentId": "265871",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T03:18:22.387",
"Id": "265871",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"pandas"
],
"Title": "Python program to accept user input for Pandas methods"
}
|
265871
|
<p>I need people who have experience with React to review my code.</p>
<p>I want to make a debounce using Lodash.</p>
<pre><code>import debounce from 'lodash/debounce'
</code></pre>
<pre><code>const [name, setName] = React.useState<string | undefined>(undefined)
const [displayedName, setDisplayedName] = React.useState<string | undefined>(undefined)
const changeName = debounce((e: domProperty) => {
setName(e.target.value)
}, 1000)
React.useEffect(() => {
// call API
}, [name])
</code></pre>
<pre><code>return (
<Input
placeholder="Player name"
prefix={<UserOutlined />}
value={displayedName}
onChange={(e) => {
changeName(e);
setDisplayedName(e.target.value);
}}
/>
)
</code></pre>
<p>Is it good? or is there anything wrong there?</p>
<p>So here I use <code>displayedName</code> because when I type something in <code>Input</code>, the <code>name</code> state doesn't change as it might be blocked by a <code>debounce</code>.</p>
<p>For example: when I type "alex" at the beginning (it works), then when I want to add the letter "i" (it doesnt, so I can't add or remove any letter it always "alex"), the <code>name</code> state is still the same as "alex". Therefore I add <code>displayedName</code>.</p>
|
[] |
[
{
"body": "<ol>\n<li>Code you provided can't work properly in some cases. Thing is that <code>debounce</code> returns a completely new function with a separate queue on each new render.\n<ul>\n<li>So, in case if rerender happens, <code>changeName</code> will be completely new & will apply changes immediately</li>\n<li>There is an even worse possibility. As the old debounced function is not destroyed, it can overwrite the value written by the new <code>changeName</code>.</li>\n<li>In order to fix that, you need to wrap it into <code>React.useMemo</code>. Like <code>React.useMemo(debounce(e => { … }, 1000), [])</code></li>\n</ul>\n</li>\n<li>Consider using a special hook <a href=\"https://usehooks.com/useDebounce/\" rel=\"nofollow noreferrer\">https://usehooks.com/useDebounce/</a></li>\n</ol>\n<h1>useDebounce</h1>\n<p>I will take code here of useDebounce function from cited article:</p>\n<pre><code>function useDebounce(value, delay) {\n const [debouncedValue, setDebouncedValue] = useState(value);\n\n useEffect(\n () => {\n const handler = setTimeout(() => setDebouncedValue(value), delay);\n\n return () => clearTimeout(handler);\n },\n [value, delay]\n );\n \n return debouncedValue;\n}\n</code></pre>\n<p>And in your code usage is going to look like:</p>\n<pre><code>const [name, setName] = React.useState<string | undefined>(undefined);\nconst debouncedName = useDebounce(name, 1000);\n\nconst changeName = ((e: domProperty) => {\n setName(e.target.value)\n};\n\nReact.useEffect(() => {\n // call API\n}, [debouncedName])\n\nreturn (\n <Input\n placeholder="Player name"\n prefix={<UserOutlined />}\n value={displayedName}\n onChange={(e) => {\n changeName(e);\n }}\n />\n)\n</code></pre>\n<p>This is more beautiful because you don't need to write the value into two state variables.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T10:09:57.990",
"Id": "265944",
"ParentId": "265873",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T04:39:15.793",
"Id": "265873",
"Score": "0",
"Tags": [
"javascript",
"react.js",
"lodash.js"
],
"Title": "React debounce using Lodash"
}
|
265873
|
<p>I'm a beginner and self taught and just want to see if there are neater ways of doing what I am doing, or whether there are bits of code that are poorly written. I think Lines 100-204 are the most crudely written. Below I've also determined who is bowling first and therefore assigning a dictionary to that team for there bowling extras. I feel there must be a better way using True and False statements</p>
<pre><code># Determining who lost the toss and who is batting first
if info['home team'] == info['toss_winner']:
toss_loser = info['away team']
elif info['home team'] != info['toss_winner']:
toss_loser = info['home team']
if info['toss_decision'] == 'field':
first_innings: object = toss_loser
elif info['toss_decision'] != 'field':
first_innings = info['toss_winner']
# Determining which team the extras belong to for each innings
if first_innings == info['toss_winner']:
first_innings_extras = {'bowling team': f"{toss_loser}", 'total': 0, 'wides': 0, 'no-balls': 0,
'byes': 0, 'leg-byes': 0, 'penalty': 0}
second_innings_extras = {'bowling team': f"{info['toss_winner']}", 'total': 0, 'wides': 0,
'no-balls': 0, 'byes': 0, 'leg-byes': 0, 'penalty': 0}
elif first_innings != info['toss_winner']:
first_innings_extras = {'bowling team': f"{info['toss_winner']}", 'total': 0, 'wides': 0,
'no-balls': 0, 'byes': 0, 'leg-byes': 0, 'penalty': 0}
second_innings_extras = {'bowling team': f"{toss_loser}", 'total': 0, 'wides': 0, 'no-balls': 0,
'byes': 0, 'leg-byes': 0, 'penalty': 0}
</code></pre>
<p>Any advice would be hugely appreciated!</p>
<p>Link to code: <a href="https://github.com/hanners999/Natwest-T20-Blast/blob/main/cricket_data.py" rel="nofollow noreferrer">https://github.com/hanners999/Natwest-T20-Blast/blob/main/cricket_data.py</a></p>
<p>Link to CSV files (towards bottom of page - look for T20 Blast (CSV new) : <a href="https://cricsheet.org/downloads/" rel="nofollow noreferrer">https://cricsheet.org/downloads/</a></p>
|
[] |
[
{
"body": "<p>Disclaimer: I know nothing whatsoever about the rules of cricket.</p>\n<p><strong>Useless check</strong></p>\n<p>Because either <code>info['toss_decision']</code> equals <code>'field'</code> or it does not, you do not need to check things twice in:</p>\n<pre><code>if info['toss_decision'] == 'field':\n first_innings: object = toss_loser\nelif info['toss_decision'] != 'field':\n first_innings = info['toss_winner']\n</code></pre>\n<p>which could be written as:</p>\n<pre><code>if info['toss_decision'] == 'field':\n first_innings: object = toss_loser\nelse:\n first_innings = info['toss_winner']\n</code></pre>\n<p>Not that it really changes anything but you could also write this using the ternary operator:</p>\n<pre><code>first_innings = toss_loser if info['toss_decision'] == 'field' else info['toss_winner']\n</code></pre>\n<p>Similarly, either <code>info['home team']</code> and <code>info['toss_winner']</code> are equal or they are not. We could write:</p>\n<pre><code>if info['home team'] == info['toss_winner']:\n toss_loser = info['away team']\nelse:\n toss_loser = info['home team']\n</code></pre>\n<p>or even:</p>\n<pre><code>toss_loser = info['away team'] if info['home team'] == info['toss_winner'] else info['home team']\n</code></pre>\n<p>Going further, one could also imagine writing the retrieval from the structure slightly differently:</p>\n<pre><code>toss_loser = info['away team' if (info['home team'] == info['toss_winner']) else 'home team']\n</code></pre>\n<p>Finally, the same argument applies to the last part of the code as well.</p>\n<p><strong>Duplicated logic</strong></p>\n<p>In the final part of the code, we are creating dictionnaries in a pretty similar way. It could help to try to see which parts are actually the same and which parts are different.</p>\n<p>We'd get something like:</p>\n<pre><code>if first_innings == info['toss_winner']:\n bowling_first = toss_loser\n bowling_second = info["toss_winner"\nelse:\n bowling_first = info["toss_winner"]\n bowling_second = toss_loser\n\nfirst_innings_extras = {'bowling team': f"{bowling_first}", 'total': 0, 'wides': 0,\n 'no-balls': 0, 'byes': 0, 'leg-byes': 0, 'penalty': 0} \nsecond_innings_extras = {'bowling team': f"{bowling_second}", 'total': 0, 'wides': 0,\n 'no-balls': 0, 'byes': 0, 'leg-byes': 0, 'penalty': 0}\n</code></pre>\n<p><strong>Introducing more variables</strong></p>\n<p>The value <code>info["toss_winner"]</code> is heavily used through the code and we have a <code>toss_loser</code> variable. Maybe it'd make things clearer and more consistent to define a variable for it.</p>\n<p><strong>Getting rid of the intermediate variables</strong></p>\n<p>On the other side, it looks like we check the toss decision to determine the first innings and then check the first inning to determine who is bowling first and who is bowling second. We could probably get rid of the intermediate logic about innings.</p>\n<p>At this point, we'd get something like:</p>\n<pre><code>toss_winner = info['toss_winner']\ntoss_loser = info['away team' if (info['home team'] == toss_winner) else 'home team']\n\n# Determining which team the extras belong to for each innings\nif info['toss_decision'] != 'field':\n bowling_first = toss_winner\n bowling_second = toss_loser\nelse:\n bowling_first = toss_loser\n bowling_second = toss_winner\n\nfirst_innings_extras = {'bowling team': f"{bowling_first}", 'total': 0, 'wides': 0,\n 'no-balls': 0, 'byes': 0, 'leg-byes': 0, 'penalty': 0} \nsecond_innings_extras = {'bowling team': f"{bowling_second}", 'total': 0, 'wides': 0,\n 'no-balls': 0, 'byes': 0, 'leg-byes': 0, 'penalty': 0}\n</code></pre>\n<p><strong>Additional notes about the different innings</strong></p>\n<p>I am not sure this is 100% relevant to what you are trying to achieve but I'd like to show a few other things that could be done.</p>\n<p>Python allows to write multiple assignment which in your case could mean something like:</p>\n<pre><code>if info['toss_decision'] == 'field':\n bowling_first, bowling_second = toss_loser, toss_winner\nelse:\n bowling_first, bowling_second = toss_winner, toss_loser\n</code></pre>\n<p>This could again be written with a ternary operator but it probably makes it more complicated than it needs to be.</p>\n<p>Another possible improvement is to notice that <code>bowling_first</code> and <code>bowling_second</code> will be handled in much the same way. Instead of having 2 variables for these, we could try to use a relevant data structure: a tuple or a list for instance.</p>\n<pre><code># Determining which team the extras belong to for each innings\nif info['toss_decision'] == 'field':\n bowling_order = toss_loser, toss_winner\nelse:\n bowling_order = toss_winner, toss_loser\n\nfirst_innings_extras = {'bowling team': f"{bowling_order[0]}", 'total': 0, 'wides': 0,\n 'no-balls': 0, 'byes': 0, 'leg-byes': 0, 'penalty': 0}\nsecond_innings_extras = {'bowling team': f"{bowling_order[1]}", 'total': 0, 'wides': 0,\n 'no-balls': 0, 'byes': 0, 'leg-byes': 0, 'penalty': 0}\n</code></pre>\n<p>But then, the same logic applies to the innings: maybe we do not really need 2 variables for this.</p>\n<pre><code># Determining which team the extras belong to for each innings\nbowling_order = (\n (toss_loser, toss_winner)\n if (info["toss_decision"] == "field")\n else (toss_winner, toss_loser)\n)\n\ninnings = (\n {\n "bowling team": f"{team}",\n "total": 0,\n "wides": 0,\n "no-balls": 0,\n "byes": 0,\n "leg-byes": 0,\n "penalty": 0,\n }\n for team in bowling_order\n)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T12:20:17.710",
"Id": "265880",
"ParentId": "265877",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "265880",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T11:11:57.787",
"Id": "265877",
"Score": "3",
"Tags": [
"python",
"beginner",
"csv",
"database"
],
"Title": "Reducing the amount of duplicated code (python) - cricket matches"
}
|
265877
|
<p>I wanted to create a simple method that creates two random teams for football/soccer match from a list of players with a requirement that the goalkeepers should be in different teams (so that one team should have at least one goalkeeper). It's a simple task and I wanted this method to be as clean as possible, let me know what do you think.
cheers!</p>
<pre><code>fun shuffleTeams() {
val availablePlayers = playersList.toMutableList()
val teamA = mutableListOf<Player>()
val teamB = mutableListOf<Player>()
val goalkeepers = availablePlayers.groupBy { player -> player.isGoalkeeper }.values.first { playersLists ->
playersLists.all { player -> player.isGoalkeeper }
}
if (goalkeepers.size >= 2) { availablePlayers.removeAll(goalkeepers.take(2)) }
availablePlayers.shuffle()
val teams = availablePlayers.chunked(if (availablePlayers.size % 2 == 0) (availablePlayers.size / 2) else (availablePlayers.size / 2) + 1)
if (goalkeepers.size >= 2) {
teamA.add(goalkeepers[0])
teamB.add(goalkeepers[1])
}
teamA.addAll(teams[0])
teamB.addAll(teams[1])
teamA.forEach { println("teamA - ${it.name}, ${it.isGoalkeeper}") }
teamB.forEach { println("teamB - ${it.name}, ${it.isGoalkeeper}") }
}
private val playersList = listOf(Player("A", true), Player("B"), Player("C"), Player("D"), Player("E"), Player("F"),
Player("G"), Player("H", true), Player("I", true), Player("J"), Player("K"), Player("L"), Player("M"))
data class Player(
val name: String,
val isGoalkeeper: Boolean = false
)
</code></pre>
|
[] |
[
{
"body": "<p><code>{ player -> player.isGoalkeeper }</code> can be replaced with <code>(Player::isGoalkeeper)</code> in all the places you're using it. This is recommended syntax from Jetbrains because it's self-documenting...no extra variable name introduced so it's simpler to read and know what the types are.</p>\n<p>Your one-line if-statement I think most programmers would avoid. It's more readable to break out the conditional contents into their own line(s).</p>\n<p>Your way of getting a list of all goalkeepers is quite convoluted. You could simply use <code>filter()</code>, or <code>partition()</code> if you needed the list of non-goalkeeers (which you aren't using).</p>\n<p>Otherwise, I don't see any other cleanliness issues.</p>\n<p>I think this algorithm could be simpler though. I think it tends to be cleaner not to have to add and subtract from collections multiple times. I find your code a little bit hard to follow.</p>\n<pre><code>fun shuffleTeams() {\n val goalkeepers = playersList.filter(Player::isGoalkeeper).shuffled().take(2)\n require(goalkeepers.size >= 2) { "Not enough goal keepers!" }\n val others = (playersList - goalkeepers).shuffled()\n val teamA = others.take(others.size / 2) + goalkeepers[0]\n val teamB = others.drop(others.size / 2) + goalkeepers[1]\n\n teamA.forEach { println("teamA - ${it.name}, ${it.isGoalkeeper}") }\n teamB.forEach { println("teamB - ${it.name}, ${it.isGoalkeeper}") }\n}\n</code></pre>\n<p>However, I think it would usually be desirable evenly divide people who can goalkeep between teams so players can sub out. To do it that way I would use:</p>\n<pre><code>fun shuffleTeams() {\n val (goalkeepers, others) = playersList.shuffled().partition(Player::isGoalkeeper)\n require(goalkeepers.size >= 2) { "Not enough goal keepers!" }\n val teamA = goalkeepers.take(goalkeepers.size / 2) + others.drop(others.size / 2)\n val teamB = goalkeepers.drop(goalkeepers.size / 2) + others.take(others.size / 2)\n\n teamA.forEach { println("teamA - ${it.name}, ${it.isGoalkeeper}") }\n teamB.forEach { println("teamB - ${it.name}, ${it.isGoalkeeper}") }\n}\n</code></pre>\n<p>Note that I stagger the use of take and drop between the two teams. This is so if there is both an odd number of goalkeepers and an odd number of non-goalkeepers, neither team will receive both rounding errors in their favor and end up with two more players than the other.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T07:27:41.397",
"Id": "525217",
"Score": "0",
"body": "Thanks for the feedback! `Player::isGoalkeeper` looks awesome, I will start using it more frequently. Good to know there is `require` aswell. You gave me a lot of useful information, I will try to use it daily. Thanks again!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T16:35:15.233",
"Id": "265885",
"ParentId": "265881",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "265885",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T12:31:42.750",
"Id": "265881",
"Score": "3",
"Tags": [
"kotlin"
],
"Title": "Create two teams from a list of players with minimum of one goalkeeper per team"
}
|
265881
|
<p>I don't know how to use classes and i think its meant to be used here to avoid repetition of functions but i can be completely wrong, i am a student who keeps learning bit by bit. Please can you take a look into my code? i truly appreciate it :)</p>
<pre><code>import nmap
import re
from sys import argv, version
#Open the file then read the content and print it
f= open("texttop.txt", "r")
file_contents= f.read()
print(file_contents)
sperate= "--------------------------------------------------------------------------------------------------------"
#shorten the function with a variable
scanner = nmap.PortScanner()
#Get the target ip address and the port range from the terminal
args = argv[1:]
if len(argv)==4:
target_ip=args[0]
port_range=args[1]
scan_type=args[2]
else:
print("Your supposed to enter the Target IP address then the port range and the attack type, enter them again.")
target_ip= str(input("Enter the target IP address:\n"))
port_range= str(input("Enter the port range please:\n "))
scan_type=str(input("Enter attack type"))
port_range.lower()
#Function for scan 1
def start_scan1():
#print the nmap version to the user
nversion = "NMAP.Version:" + str(scanner.nmap_version())
#Print nmap version without any special characters
string = re.sub(r"[() ]","",nversion)
#start scanning
print(string+"\nScanning...")
scanner.scan(target_ip,port_range,"-v -sA -O -sV")
#Save the scan info into a variable
print("This a list of the scan info. Please ignore if not wanted: " + str(scanner.scaninfo()))
#For every host in the target aquired we check its status
for host in scanner.all_hosts():
print(sperate)
#print the status of the target
print('Host : %s (%s) \t State : %s \n ' % (host, scanner[host].hostname(),scanner[host].state()))
#Check the protocol for every host
for proto in scanner[host].all_protocols():
print("Protocol: %s" % (proto))
#Make a variable to get the ports from the protocol
lport = scanner[host][proto].keys()
#Check port status
for port in lport:
print("Port: %s \t State: %s \t Service: %s \t Version: %s" % (port, scanner[host][proto][port]['state'],scanner[host][proto][port]['name'],scanner[host][proto][port]["version"]))
print("--------------------------------------------------------------------------------------------------------")
print("\n Finished scan.")
#Function for scan 2
def start_scan2():
#print the nmap version to the user
nversion = "NMAP.Version:" + str(scanner.nmap_version())
#Print nmap version without any special characters
string = re.sub(r"[() ]","",nversion)
#start scanning
print(string+"\nScanning...")
scanner.scan(target_ip,port_range,"-sS -T0")
#Save the scan info into a variable
print("This a list of the scan info. Please ignore if not wanted: " + str(scanner.scaninfo()))
#For every host in the target aquired we check its status
for host in scanner.all_hosts():
print(sperate)
#print the status of the target
print('Host : %s (%s) \t State : %s \n ' % (host, scanner[host].hostname(),scanner[host].state()))
#Check the protocol for every host
for proto in scanner[host].all_protocols():
print("Protocol: %s" % (proto))
#Make a variable to get the ports from the protocol
lport = scanner[host][proto].keys()
#Check port status
for port in lport:
print("Port: %s \t State: %s \t Service: %s \t Version: %s" % (port, scanner[host][proto][port]['state'],scanner[host][proto][port]['name'],scanner[host][proto][port]["version"]))
print("--------------------------------------------------------------------------------------------------------")
print("\n Finished scan.")
#if statement to check which scan combination the user want to use.
if scan_type==1:
start_scan1()
elif scan_type==2:
start_scan2()
else:
start_scan1()
</code></pre>
|
[] |
[
{
"body": "<p>This is by no means a thorough review but I see things you can improve in no particular order:</p>\n<ul>\n<li>add <strong>line spacing</strong>, especially between functions - that will make the code easier to read. Everything is glued together here, it's not obvious in the blink of an eye where a function start and where it ends</li>\n<li>for command line arguments, you should be using the argparse module that is less clumsy and allows you to accept named parameters without a preset order. A short example <a href=\"https://codereview.stackexchange.com/a/249765/219060\">here</a></li>\n<li>it's not clear what file you are reading on top of your code. If it is a bunch of instructions then maybe it would be more elegant to put all that in a separate .py file and import it. If it is help text, then read above about argparse.</li>\n<li>you are not validating the parameters, so your program can easily misbehave in case of typos, the obvious way would be to use <strong>regular expressions</strong> to validate IP address etc. You are already using the re module for something else.</li>\n<li>the validation can be baked in with argparse, here's another more sophisticated <a href=\"https://codereview.stackexchange.com/a/242865/219060\">example</a> (quoting myself again)</li>\n<li>unnecessary <strong>repetition</strong>: start_scan1 and start_scan2 are obviously nearly identical. The only thing that that is different is the scan parameters. So you could just create a single function with scan options as arguments. Just doing that will decrease your code base by 30%.</li>\n<li>but these functions are poorly <strong>named</strong>, the purpose should be intuitive from the function name so they could be named scan_paranoid and scan_aggressive respectively. You can write simple, one-liner functions with these descriptive names, that will call a more generic scan routine with the desired parameters.</li>\n<li>you should use the <strong>logging</strong> module to send output to both console and file. A basic example <a href=\"https://codereview.stackexchange.com/a/238459/219060\">here</a>. The reason is obvious: it's easier to review results in a file, especially if the results are properly formatted (you could even output as CSV). The other reason is that the console buffer size is limited and you may lose output after spitting out a few hundreds or thousands of rows, which would occur in a large scan.</li>\n<li>instead of %s formatting, you could use F-strings (requires Python 3.6). If you are on a recent version of Python3 I would recommend you to upgrade the coding style in this regard</li>\n</ul>\n<h2>Code</h2>\n<p>At line #22:</p>\n<pre><code>port_range.lower()\n</code></pre>\n<p>This does nothing, this is not a variable assignment</p>\n<p>sperate is a typo. Besides, it could be used on line #47, rather than repeating those hyphens. It's no hugely useful anyway.</p>\n<h2>Coding style</h2>\n<p>Review PEP8 for coding style, for example there should be a space after every comma between function arguments and that convention should be consistently respected throughout your code, which is not the case here:</p>\n<pre><code> print('Host : %s (%s) \\t State : %s \\n ' % (host, scanner[host].hostname(),scanner[host].state()))\n</code></pre>\n<p>A good IDE with linter (eg flake8) can definitely pinpoint the problematic patterns and help enforce good habits.</p>\n<p>Some lines are way too long (eg #46, 72). They should be broken down to multiline declaration for better readibility. Your screen is quite likely larger than mine and you may not have to scroll. But chunks of code overly large should be avoided nonetheless - they are not pleasant to review.\nPEP8 actually recommends 79 characters width - I don't respect this rule strictly but remain reasonable.</p>\n<h2>Misc</h2>\n<p>I am quite familiar with nmap but never used the corresponding Python module. You might also be interested in <a href=\"https://scapy.net/\" rel=\"nofollow noreferrer\">Scapy</a>, that does a different job actually, in the sense that it does not interprets results for you, but returns raw packet responses instead. It may be interesting if one day you need to dig deeper into the responses than nmap allows.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T17:05:29.930",
"Id": "525257",
"Score": "0",
"body": "Truly this is quite useful and i appreciate every bit of information you handed me, i chose nmap rather than Scapy because i am not quite qualified for it yet, its a bit hard but i appreciate your help again i truly do."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T19:49:03.810",
"Id": "265888",
"ParentId": "265887",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "265888",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T18:47:51.237",
"Id": "265887",
"Score": "0",
"Tags": [
"python"
],
"Title": "A port scanner made in python"
}
|
265887
|
<p>Hello everyone I was told to post this here instead of StackOverFlow.</p>
<p>I am using PyAutoGUI currently as this was the best tools I could manage to find to use a piece of software that has no native Python function. I am using the mouse and keyboard control to design maps for Dungeons and Dragons using the software Dungeon Painter Studio. It is working as intended and I have figured out a way to actually use my script to create maps on it however, since PyAutoGUI is based on mouse location and pixels it has been quite a manual process.</p>
<p>EDIT:</p>
<p>Here is a picture of the software with nothing in it just opened up:
<a href="https://i.stack.imgur.com/80A6M.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/80A6M.png" alt="enter image description here" /></a></p>
<p>Here is a picture after the code has been ran:
<a href="https://i.stack.imgur.com/9891z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9891z.png" alt="enter image description here" /></a></p>
<p>My reason for creating this script is so that I can eventually randomize it to create a random generated map for my D&D campaign that is somewhat original compared to just taking a map off the internet.</p>
<p>I am inputting a starting location for the mouse and have it click and moved based on relative location to that starting position. Here is a piece of what it currently looks like:</p>
<pre><code>#Switch to dps, maximize window, select the tile hotkey
pyautogui.keyDown('altleft'); pyautogui.press('tab'); pyautogui.keyUp('altleft')
fw = pyautogui.getActiveWindow()
fw.maximize()
pyautogui.keyDown('enter')
#Select the background tile
pyautogui.click('dirt_k.png')
#Create background
pyautogui.moveTo(9,189)
pyautogui.mouseDown(9,189)
pyautogui.moveTo(748,808)
pyautogui.mouseUp(252,436)
#Select the dugeon tile
pyautogui.click('dirt_d.png')
#Create dungeon floor
pyautogui.moveTo(329,807)
pyautogui.mouseDown(329,807)
pyautogui.moveRel(100,-75)
pyautogui.mouseUp()
pyautogui.moveRel(-25,0)
pyautogui.mouseDown()
pyautogui.moveRel(-50,-50)
pyautogui.mouseUp()
pyautogui.moveRel(-100,0)
pyautogui.mouseDown()
pyautogui.moveRel(250,-125)
pyautogui.mouseUp()
pyautogui.moveRel(0,100)
pyautogui.mouseDown()
pyautogui.moveRel(50,25)
pyautogui.mouseUp()
pyautogui.moveRel(0,100)
pyautogui.mouseDown()
pyautogui.moveRel(100,-125)
pyautogui.mouseUp()
pyautogui.moveRel(0,0)
pyautogui.mouseDown()
pyautogui.moveRel(-25,-50)
pyautogui.mouseUp()
pyautogui.moveRel(-75,0)
pyautogui.mouseDown()
pyautogui.moveRel(175,-100)
pyautogui.mouseUp()
pyautogui.mouseDown()
pyautogui.moveRel(-25,-50)
pyautogui.mouseUp()
pyautogui.moveRel(25,0)
pyautogui.mouseDown()
pyautogui.moveRel(-225,-125)
pyautogui.mouseUp()
</code></pre>
<p>It basically continues on like that for hundreds of lines to create a sample map. I was just seeing if anyone else is familiar enough with PyAutoGUI (or any other tools) that would help automated this process a bit more.</p>
<p>I have the amount of pixels per square which is roughly 25px so it isn't too hard to calculate. Moving right is +25 left is -25 down is +25 up is -25. So using those measurements I have been able to calculate relative location where the mouse starts and move it around from there.</p>
<p>Any advice or help is greatly appreciated, thank you!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T21:08:26.723",
"Id": "525195",
"Score": "0",
"body": "We are missing some information here. Can you include a screenshot of the program you're scripting, and explain why you're scripting it (instead of doing it once by hand?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T21:37:08.890",
"Id": "525196",
"Score": "0",
"body": "Just added an edit with some screenshots so you can see it. The reason I am running this and want to optimize it is so that eventually I can randomly generate these maps to add to my D&D game."
}
] |
[
{
"body": "<blockquote>\n<p>My reason for creating this script is so that I can eventually randomize it to create a random generated map for my D&D campaign that is somewhat original compared to just taking a map off the internet.</p>\n</blockquote>\n<p>Given that you want to eventually make a random map, your current approach won't work. You're just using hardcoded values, and there is no way to "randomize" it without fundamentally re-writing it.</p>\n<ul>\n<li>The first change I would recommend is separate the data out. This makes the program shorter, clearer, and easier to change to add something like randomness</li>\n</ul>\n<pre><code>#Create dungeon floor\npyautogui.moveTo(329,807)\npyautogui.mouseDown(329,807)\npyautogui.moveRel(100,-75)\npyautogui.mouseUp()\n\nlines = [\n ((-25, 0), (-50, 50)),\n ((-100,0), (250,-125))\n ((0,100), (50,25)),\n ((0,100), (100,-125)),\n ((0,0), (-25,-50)),\n ((-75,0), (175,-100)),\n ((0,0), (-25,-50)),\n ((25,0), (-225,-125)),\n]\n\nfor down, up in lines:\n pyautogui.moveRel(*down)\n pyautogui.mouseDown()\n pyautogui.moveRel(*up)\n pyautogui.mouseUp()\n</code></pre>\n<ul>\n<li>Work in absolute coordinates, not relative ones. It will make things easier for random dungeons.</li>\n<li>Add comments. Does a particular mouse movement draw a room? Does it draw a line bordering a room? I have literally no idea. In this case, move movement is so opaque it will be useful for you as well, not just other readers.</li>\n<li>As a warning, the whole idea of scripting a dungeon generation program may not be worth it. What happens if you want a map that's bigger than your screen resolution? If you just output your own image directly, it will be easier than scripting in some ways.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T23:17:20.757",
"Id": "525199",
"Score": "0",
"body": "Yes this is perfect and what I was looking for something along these lines (pun intended)! In a all seriousness though I do recognize the limitations of working with a limited amount of screen space right now and was heading in the direction you just explained. Adding the lines like that should really help. As for the limited map spacing, I was planning on just creating multiple that could possibly connected if I wrote in some kind of connection point to be in that would carry over into the next map. This is a great start for me though and I really do appreciate the time you took to answer"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T23:07:19.260",
"Id": "265891",
"ParentId": "265889",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T20:51:02.693",
"Id": "265889",
"Score": "2",
"Tags": [
"python"
],
"Title": "Maze generator for Dungeons and Dragons"
}
|
265889
|
<p>This is my first Stack Exchange question, so please bare with me. I'm following this tutorial on youtube by <a href="https://www.youtube.com/watch?v=GFYT7Lqt1h8&list=PLlrATfBNZ98eOOCk2fOFg7Qg5yoQfFAdf&index=2" rel="nofollow noreferrer">The Cherno</a>, Im only up to episode 16 and I have done this on another laptop before and had 3000 FPS. On my new <a href="https://www.bestbuy.com/site/asus-rog-zephyrus-15-6-qhd-gaming-laptop-amd-ryzen-9-16gb-memory-nvidia-geforce-rtx-3070-1tb-ssd-eclipse-grey-eclipse-grey/6448848.p?skuId=6448848" rel="nofollow noreferrer">laptop</a>, im only getting 600 FPS. I dont think it is the code but everything I have looked up has just led me to minecraft issuse with FPS. A lot of things I have read said I should make sure its using the correct GPU and change my setting in the NVidia Control panel. Everything I have tried hasnt helped sadly. Any tips or suggestions would be greatly appreciated.
Please let me know if any more information is needed</p>
<hr />
<p><strong>Below is my main class which holds the game loop, widow initialization, and rendering methods</strong></p>
<hr />
<pre><code>package com.SaltineCracker.rain;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import javax.swing.JFrame;
import com.SaltineCracker.rain.graphics.Screen;
/*
Holds the game loop
Initializes the Threads
Has the start and stop functions
Creates the screen ad has the Render and Update Methods
*/
public class Game extends Canvas implements Runnable{
private static final long serialVersionUID = 1L;
// Sets the screen width and height
public static int width = 300;
// Creates the height with a 16/9 aspect ratio based off width
public static int height = width / 16 * 9;
public static int scale = 3;
public static String title = "Rain";
// Creates a new thread
private Thread thread;
// Uses JFrame to create the window
private JFrame frame;
// Game loop variable
private boolean running = false;
// Gets the screen class from the graphics folder and makes it available for use
private Screen screen;
// Creates the image
private BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// Allows the game to have access to each pixel and the ability to change them
private int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
public Game()
{
Dimension size = new Dimension(width * scale, height * scale);
// Sets the window size using a method in canvas because the game is extending it
setPreferredSize(size);
// Creates a new instance of the screen class
screen = new Screen(width, height);
// Creates new instance of JFrame
frame = new JFrame();
}
// synchronized allows the threads to run together
public synchronized void start()
{
// Starts game loop
running = true;
// Creates a new thread object and then starts it
thread = new Thread(this, "Display");
// Once run, it initializes and starts the run function
thread.start();
}
// Try's to properly join the threads and then force closes them
public synchronized void stop()
{
// Stops game loop
running = false;
try
{
thread.join();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
// Game loop gets called automatically because the game implements Runnable
public void run()
{
// Gets the time right when the program is started
long lastTime = System.nanoTime();
long timer = System.currentTimeMillis();
final double ns = 1000000000.0 / 60.0;
double delta = 0;
int frames = 0;
int updates = 0;
while (running)
{
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
// Makse's sure that the program runs only 60 times a second
while (delta >= 1)
{
update();
// Counting all the amount of times it updates
updates++;
// Resets the delta variable back to 0
delta--;
}
render();
// COunts the amount of frames run a second
frames++;
// Happens once per second
if (System.currentTimeMillis() - timer > 1000)
{
timer += 1000;
// Displays the FPS and UPDATES in the tile bar
frame.setTitle(title + " | " + updates + " ups, " + frames + " fps");
updates = 0;
frames = 0;
}
}
stop();
}
public void update()
{
}
public void render()
{
// <pre>-loading data to be rendered, usually pixel information
BufferStrategy bs = getBufferStrategy();
if (bs == null)
{
createBufferStrategy(3);
return;
}
// Clears the screen
screen.clear();
// Calls the screen rending method
screen.render();
// Sets the new buffered image to what ever the Screen class is rendering
for (int i = 0; i < pixels.length; i++)
{
pixels[i] = screen.pixels[i];
}
// Links the graphics element with the buffer strategy
Graphics g = bs.getDrawGraphics();
// Draws the buffered image at 0, 0 with the height and width
g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
// Removes old graphics
g.dispose();
// Shows the next buffer strategy
bs.show();
}
public static void main(String[] args)
{
// Creates a new instance of the game
Game game = new Game();
// --- Canvas Frame Customization ---
// Removes the ability to resize
game.frame.setResizable(false);
game.frame.setTitle(Game.title);
// Adds the game object as a component
game.frame.add(game);
// Sizes the game
game.frame.pack();
// Closes the program and not just the window
game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.frame.setLocationRelativeTo(null);
// Shows the window
game.frame.setVisible(true);
// Uses the start method and starts the game
game.start();
}
}
</code></pre>
<hr />
<p><strong>This is my second class called Screen</strong></p>
<hr />
<pre><code>package com.SaltineCracker.rain.graphics;
import java.util.Random;
/*
Gets initialized in the Game class, Game Function
This Class handles rendering the screen data
*/
public class Screen {
private int width, height;
public int[] pixels;
public int[] tiles = new int[64 * 64];
private Random random = new Random();
public Screen(int width, int height)
{
this.width = width;
this.height = height;
// Creates an integer for each pixel on the screen
pixels = new int[width * height];
for (int i = 0; i < 64 * 64; i++)
{
tiles[i] = random.nextInt(0xffffff);
}
}
// Sets all pixels in pixels array to black to clear the screen
public void clear()
{
for (int i = 0; i < pixels.length; i++)
{
pixels[i] = 0;
}
}
// Runs through every pixel
public void render()
{
// Loops through Y pixels
for (int y = 0; y < height; y++)
{
// Temporary variable to not mess with Y
int yy = y;
// If the object is out of bounds of array, it wont crash
if (yy < 0 || yy >= height ) break;
// Loops through X pixels
for (int x = 0; x < width; x++)
{
// Temporary variable to not mess with X
int xx = x;
// If the object is out of bounds of array, it wont crash
if (xx < 0 || xx >= width ) break;
// Gets the tile by the pixel amount, 4 is the square root of the pixel length
int tileIndex = ((x >> 4) & 63) + ((y >> 4) & 63) * 64;
// Gets the pixel index and sets it to a color
pixels[x + y * width] = tiles[tileIndex];
}
}
}
}
</code></pre>
<hr />
<p><strong>This image shows what GPU it is using</strong></p>
<hr />
<p><a href="https://i.stack.imgur.com/D7vZq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/D7vZq.png" alt="enter image description here" /></a></p>
<hr />
<p><strong>This image shows what GPU 0 is listed as</strong></p>
<hr />
<p><a href="https://i.stack.imgur.com/V7vSs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/V7vSs.png" alt="enter image description here" /></a></p>
<hr />
<p><strong>This image shows what my NVidia Control Global settings are</strong></p>
<hr />
<p><a href="https://i.stack.imgur.com/uMrcz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uMrcz.png" alt="enter image description here" /></a></p>
<hr />
<p><strong>This image shows what my NVidia Control settings are for Javaw.exe</strong></p>
<hr />
<p><a href="https://i.stack.imgur.com/5c9De.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5c9De.png" alt="enter image description here" /></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T06:38:11.753",
"Id": "525213",
"Score": "3",
"body": "There's not much to review here as you are under the wrong assumption, that you can make a game engine using normal user interface code like swing/awt. To achive performance, you'll have to program your graphics hardware more or less directly, e.g. using OpenGL (for java see https://jogamp.org/jogl/www/) which will be a long journey in itself. Frankly, my advice for the beginning programmer is finding a different project first. 3d engines are probably the most complicated thing you can aim for using the most convoluted programming interface imaginable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T21:37:47.353",
"Id": "525273",
"Score": "0",
"body": "I do agree with the fact that making a 3D game engine is a very hard task, that's why I'm purely doing a 2D game engine. I do plan on learning OpenGL for which the Cherno also has a series to explain it and how to implement it. I've also have done a decent amount of messing with Unity, same with just programing different projects. I purely just wanted to go for what seems to be a decently long and difficult project to occupy any downtime and to learn a decent amount from it. The main question I guess for this was any suggestions for my computer settings on how to fix an underperforming GPU."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T07:42:06.903",
"Id": "525639",
"Score": "0",
"body": "Could you share what CPUs you have in both of your laptops? I'm starting to think that `Screen.render()` might be the problem here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T11:04:40.917",
"Id": "525661",
"Score": "0",
"body": "@mindoverflow My old computer had an Intel 5 Core i5 9th gen and my new one has an AMD Ryzen 9 5900HS"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T06:53:13.860",
"Id": "525726",
"Score": "0",
"body": "They seem rather similar. Do you have access to both computers? Might be worth a try to benchmark the parts I suspect."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T07:14:25.363",
"Id": "525729",
"Score": "0",
"body": "I looked again, you'd need to benchmark the `screen.clear()`, `screen.render()` and the `for` loop after these two inside of `Game.render()`. Some simple timing using `System.nanoTime()` should suffice. Don't print the time take on every frame (slow, instead sum the times ad divide through the frames rendered) and run the game for at least 30s (JVM is slow on startup)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T23:05:04.980",
"Id": "525809",
"Score": "0",
"body": "@mindoverflow, So I did the timings benchmark and this is what I got. This is in nanoseconds, 4_500 for screen.clear(), 42_000 for system.render(), 5_000 for the for loop. I then checked g.drawimage and it's getting about 100_000, and bs.show is getting about 1_500_000. As a whole, it's about 2_000_000, sadly I'm new at using Buffered Strategy so I don't fully understand how to optimize this process."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-19T05:52:33.260",
"Id": "525830",
"Score": "0",
"body": "Well, I'm at my wit's end here ^^;. Perhaps it's just Java not playing nice with your hardware for some reason, you could try asking about this on stackoverflow. Lastly, while I don't recommend learning a library AND Java at the same time, you could check out LibGDX. There are some good tutorials, I can recommend Brent Aureli's videos."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-19T20:49:18.600",
"Id": "525893",
"Score": "0",
"body": "@mindoverflow definitely thank you for the help and I will definitely be looking up LibGDX for help and try to post this on Stackoverflow"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-12-04T17:17:09.570",
"Id": "534662",
"Score": "0",
"body": "`please bare with me` I might come back to that later."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T23:09:01.293",
"Id": "265892",
"Score": "1",
"Tags": [
"java",
"performance",
"game",
"eclipse"
],
"Title": "I'm making a 2D game engine with JAVA Eclipse 2021-06 but it is underperforming in FPS for my NVidia RTX 3070"
}
|
265892
|
<p>Is the code properly documented/commented?
does the code handle errors properly? any suggestions to improve the code
Help outline the object-oriented principles shown in the code.</p>
<pre><code>using System;
public class testScore
{
public static void Main()
{
string str1;
double dbl1;
Console.WriteLine("Welcome to the Acme Student Test Score comenter");
Console.WriteLine("Enter your name");
str1 = Console.ReadLine();
Console.WriteLine("Enter the test score");
dbl1 = Double.Parse(Console.ReadLine());
Console.WriteLine("Hello {0}", str1);
Console.WriteLine("You scored {0}", dbl1);
if(dbl1 < 40)
{
if (dbl1 > 0)
{
Console.WriteLine("This a FAIL score");
}
}
if ((dbl1 >= 40) && (dbl1 <= 100))
{
Console.WriteLine("This is a PASS score");
if (dbl1 >= 75)
Console.WriteLine("You did very well!");
}
else
{
Console.WriteLine("Oh dear - you have put in a wrong test score");
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T00:31:52.420",
"Id": "525203",
"Score": "0",
"body": "`Double.Parse(Console.ReadLine())` will throw an exception on invalid input. Use [Double.TryParse](https://docs.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-5.0#System_Double_TryParse_System_String_System_Double__) instead. As of comments: you don't have a single one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T05:54:42.100",
"Id": "525210",
"Score": "3",
"body": "Welcome to Code Review! We need to know *what the code is intended to achieve*. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](//meta.codereview.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](//meta.codereview.stackexchange.com/q/2436), rather than your concerns about the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T06:28:28.537",
"Id": "525212",
"Score": "1",
"body": "You ask about `documented/commented`, I find no *documentation* or *code comments* in the code presented. I don't dare to try and imagine how program source code could conceivably *show object-oriented principles*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T07:36:20.663",
"Id": "525221",
"Score": "0",
"body": "Because C# is a procedural programming language (mostly) that's why your code (alone without comments) should be able to use to answer to the **What** and **How** questions. On the other hand your code will not capture the **why**s and **why not**s. So, your comments should capture your decisions: why did you choose path A over path B; why did you exclude path C and path D ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T15:14:12.773",
"Id": "525587",
"Score": "1",
"body": "@alex if [zareb](https://codereview.stackexchange.com/users/247166/zareb) is your registered account and you would like them to be merged, then you can click the [contact link](https://codereview.stackexchange.com/contact) in the lower left corner of the page and request your accounts to be merged."
}
] |
[
{
"body": "<p><strong>Variables</strong></p>\n<p>You've defined <code>str1</code> and <code>dbl1</code> as variable names, but the names themselves aren't descriptive of their use. Better names for them would be:</p>\n<pre><code>string name;\ndouble score;\n</code></pre>\n<p>Along with this, there's no reason why you can't instantiate the variable at the same time as the declaration:</p>\n<pre><code>string name = Console.ReadLine();\n</code></pre>\n<p><strong>Error Handling</strong></p>\n<p>As it currently stands, there's one place where a runtime exception can occur, which is <code>Double.Parse(Console.ReadLine())</code>. If a user decides to enter <code>ten</code> as the score input, an error will occur. We can use <code>Double.TryParse</code> instead, and we can add retry logic if an invalid input was entered. We can also add logic to retry if an invalid number was entered (e.g. 200). Something like:</p>\n<pre><code>Console.WriteLine("Enter the test score");\nbool successfulInput = false;\ndo\n{\n successfulInput = Double.TryParse(Console.ReadLine(), out score);\n\n if (!successfulInput)\n {\n Console.WriteLine("Score must be a number"); \n }\n else if (score < 0 || score > 100)\n {\n Console.WriteLine("Oh dear - you have put in a wrong test score");\n successfulInput = false;\n }\n} while (!successfulInput);\n</code></pre>\n<p><strong>Methods</strong></p>\n<p>Split up behaviour into Methods for better cohesion and readability. We can extract the logic to determine the grade into a method like:</p>\n<pre><code>static void DisplayGrade(string name, double score)\n{\n Console.WriteLine("Hello {0}", name);\n Console.WriteLine("You scored {0}", score);\n\n if ((score >= 40) && (score <= 100))\n {\n Console.WriteLine("This is a PASS score");\n\n if (score >= 75)\n {\n Console.WriteLine("You did very well!");\n }\n }\n else\n { \n Console.WriteLine("This a FAIL score");\n }\n}\n</code></pre>\n<p>We can do this for all the different behaviours we want to capture (which I will show at the end).</p>\n<p><strong>Magic Numbers</strong></p>\n<p>There are numbers such as 40, 100, and 75 which is not very descriptive of their intent alone. These numbers can be replaced with by <code>const</code> variables:</p>\n<pre><code>const int PASS_MARK = 40;\nconst int TOP_MARK = 100;\nconst int GOOD_MARK = 75;\n</code></pre>\n<p>This would look something like:</p>\n<pre><code>static void DisplayGrade(string name, double score)\n{\n Console.WriteLine("Hello {0}", name);\n Console.WriteLine("You scored {0}", score);\n\n if ((score >= PASS_MARK) && (score <= TOP_MARK))\n {\n Console.WriteLine("This is a PASS score");\n\n if (score >= GOOD_MARK)\n {\n Console.WriteLine("You did very well!");\n }\n }\n else\n { \n Console.WriteLine("This a FAIL score");\n }\n}\n</code></pre>\n<p><strong>Final Results</strong></p>\n<p>If we apply these techniques, we'd get something along the lines of:</p>\n<pre><code>using System;\n\npublic class testScore\n{\n const int PASS_MARK = 40;\n const int TOP_MARK = 100;\n const int GOOD_MARK = 75;\n const int MIN_MARK = 0;\n \n public static void Main()\n {\n DisplayWelcomeMessage();\n\n string name = GetNameInput();\n double score = GetScoreInput();\n\n DisplayGrade(name, score);\n } \n \n static void DisplayWelcomeMessage()\n {\n Console.WriteLine("Welcome to the Acme Student Test Score comenter");\n }\n \n static string GetNameInput()\n {\n Console.WriteLine("Enter your name");\n return Console.ReadLine();\n }\n \n static double GetScoreInput()\n {\n Console.WriteLine("Enter the test score");\n \n double score;\n bool successfulInput = false;\n do\n {\n successfulInput = Double.TryParse(Console.ReadLine(), out score);\n if (!successfulInput)\n {\n Console.WriteLine("Score must be a number"); \n }\n else if (score < MIN_MARK || score > TOP_MARK)\n {\n Console.WriteLine("Oh dear - you have put in a wrong test score");\n successfulInput = false;\n }\n } while (!successfulInput); \n \n return score;\n }\n \n static void DisplayGrade(string name, double score)\n {\n Console.WriteLine("Hello {0}", name);\n Console.WriteLine("You scored {0}", score);\n\n if ((score >= PASS_MARK) && (score <= TOP_MARK))\n {\n Console.WriteLine("This is a PASS score");\n\n if (score >= GOOD_MARK)\n {\n Console.WriteLine("You did very well!");\n }\n }\n else\n { \n Console.WriteLine("This a FAIL score");\n }\n }\n}\n</code></pre>\n<p><strong>A Note on comments</strong></p>\n<p>While your original question did ask if the code was properly commented (which there were no comments), I'm of the belief that unless it's a public API, then comments don't have real value if your code is easy to read. The steps taken here are to ensure that the code is highly readable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T09:24:32.860",
"Id": "525223",
"Score": "0",
"body": "agree with last point, comments are completely redundent except for maybe cases with magic numbers (like hex memory addresses) or more complex alghorytms (like reading backwards from a hex file to ensure little-endianess)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T00:35:11.827",
"Id": "265894",
"ParentId": "265893",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T23:45:31.417",
"Id": "265893",
"Score": "1",
"Tags": [
"c#"
],
"Title": "Is the code properly documented/commented and does the code handle errors properly?"
}
|
265893
|
<p>I've recently reached a milestone for my Othello clone. This is my first python project and the farthest I've come to a full program beyond small scripts and little automations.</p>
<p>I'd love for those smarter than I to critique and help me to write better code.</p>
<p>Link:
<a href="https://github.com/Mcclujdd/othello" rel="nofollow noreferrer">https://github.com/Mcclujdd/othello</a></p>
<p>Most of my code here: board.py</p>
<pre><code>import tkinter as tkr
master = tkr.Tk()
master.geometry("800x800")
frame = tkr.Frame(master)
frame.pack()
canvas = tkr.Canvas(master, width=800, height=800)
canvas.pack(expand=tkr.YES, fill=tkr.BOTH)
class Tile:
is_empty = True
def __init__(self, coordinate, is_black, tkr_coordinates):
self.coordinate = coordinate
self.color = 'grey'
self.tkr_coordinates = tkr_coordinates
# self.tkr_coordinates = [40, 40, 130, 130] #pixel coordinates for x1, y1, x2, y2
board_matrix = [0,1,2,3,4,5,6,7,
8,9,10,11,12,13,14,15,
16,17,18,19,20,21,22,23,
24,25,26,27,28,29,30,31,
32,33,34,35,36,37,38,39,
40,41,42,43,44,45,46,47,
48,49,50,51,52,53,54,55,
56,57,58,59,60,61,62,63]
def create_tkr_coordinates(coordinates): # coordinates must be [x1, y1, x2, y2] format
y1 = coordinates[1]
y2 = coordinates[3]
tkr_values = []
for row in range(8):
x1 = coordinates[0]
x2 = coordinates[2]
for col in range(8):
tkr_values.append([x1, y1, x2, y2])
x1 += 90
x2 += 90
y1 += 90
y2 += 90
return tkr_values
def generateBoardValues():
board_height = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
board_width = ('1', '2', '3', '4', '5', '6', '7', '8')
board_matrix_assignments = {} # a1 - h8 to be assigned to tile objects
index = 0
tkr_values = create_tkr_coordinates([40, 40, 130, 130])
for letter in board_height:
for number in board_width:
board_matrix_assignments[board_matrix[index]] = Tile(f'{letter+number}', False, tkr_values[index])
index +=1
return board_matrix_assignments
def modifyColor(tile, color):
canvas.itemconfig(tile, fill=color)
def onClick(event):
tile = canvas.find_closest(event.x, event.y)
current_color = canvas.itemcget(tile, 'fill')
if current_color == 'grey':
color = 'red'
elif current_color == 'red':
color = 'blue'
else:
color = 'grey'
modifyColor(tile, color)
def drawBoard(board):
for tile in board:
x1 = board.get(tile).tkr_coordinates[0]
y1 = board.get(tile).tkr_coordinates[1]
x2 = board.get(tile).tkr_coordinates[2]
y2 = board.get(tile).tkr_coordinates[3]
canvas.create_rectangle(x1, y1, x2, y2, fill=board.get(tile).color)
canvas.bind('<Button-1>', onClick)
tkr.mainloop()
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T00:38:59.960",
"Id": "265895",
"Score": "3",
"Tags": [
"beginner",
"python-3.x",
"object-oriented",
"design-patterns"
],
"Title": "Othello game in Tk"
}
|
265895
|
<h1><strong>Overview</strong></h1>
<p>This is a program that encrypts and decrypts messages and texts using two simple algorithms. Please note, the algorithms used in this project are not suitable for production use. I used them to help deepen my understanding [beginner] of the general ideas behind Java, encryption, working with files, and interacting with the command line.</p>
<h1><strong>Code</strong></h1>
<p><strong>App.java</strong></p>
<pre><code>package encrypt.decrypt;
import java.io.File;
import java.io.IOException;
public class App {
public static void main(String[] args) throws IOException {
/*
* This program has six arguments:
* -mode: determines the program’s mode (enc for encryption, dec for decryption).
* -key: an integer key to modify the message.
* -data: is a text or ciphertext to encrypt or decrypt.
* -alg: two different algorithms. The first one would be shifting algorithm (it shifts each letter by the
* specified number according to its order in the alphabet in circle). The second one would be based on
* Unicode table, like in the previous stage.
* -in: read data in from a txt file
* -out: write data to a txt file
*/
String mode = "enc";
int key = 0;
String data = "";
String alg = "shift";
boolean isDataProvided = false;
boolean isInProvided = false;
File inputFile = null;
File outputFilePath = null;
String workingDirectory = System.getProperty("user.dir");
for (int i = 0; i < args.length; i++) {
switch (args[i]) {
case "-alg" -> alg = args[i + 1];
case "-mode" -> mode = args[i + 1];
case "-key" -> key = Integer.parseInt(args[i + 1]);
case "-data" -> {
isDataProvided = true;
data = args[i + 1];
}
case "-in" -> {
isInProvided = true;
inputFile = new File(workingDirectory + "\\" + args[i + 1]);
}
case "-out" -> outputFilePath = new File(workingDirectory + "\\" + args[i + 1]);
}
}
switch (mode) {
case "enc":
if (alg.equals("unicode")) {
if (inputFile == null && outputFilePath == null) {
System.out.println(EncryptDecrypt.encrypt(data, key));
} else if (isDataProvided && isInProvided) {
System.out.println(EncryptDecrypt.encrypt(data, key));
} else {
EncryptDecrypt.writeCipherTextFile(inputFile, outputFilePath, key, alg, mode);
}
break;
} else if (alg.equals("shift")) {
if (inputFile == null && outputFilePath == null) {
System.out.println(EncryptDecrypt.alphabetIndexPositions(data, key, mode, alg));
} else if (isDataProvided && isInProvided) {
System.out.println(EncryptDecrypt.alphabetIndexPositions(data, key, mode, alg));
} else {
EncryptDecrypt.writeCipherTextFile(inputFile, outputFilePath, key, alg, mode);
}
break;
}
case "dec":
if (inputFile == null && outputFilePath == null) {
System.out.println(EncryptDecrypt.alphabetIndexPositions(data, key, mode, alg));
} else if (isDataProvided && isInProvided) {
System.out.println(EncryptDecrypt.alphabetIndexPositions(data, key, mode, alg));
} else {
EncryptDecrypt.readCipherTextFile(inputFile, outputFilePath, key, alg, mode);
}
break;
}
}
}
</code></pre>
<p><strong>EncryptDecrypt.java</strong></p>
<pre><code>package encrypt.decrypt;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
public class EncryptDecrypt {
public static final String[] ALPHABET = {
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
"k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
"u", "v", "w", "x", "y", "z"
};
public static String alphabetIndexPositions(String inputMessage, int inputKey, String mode, String alg) {
String[] inputMessageArray = inputMessage.split("");
int alphabetCount = 0;
StringBuilder alphabetIndex = new StringBuilder();
StringBuilder isUpperCase = new StringBuilder();
for (String inputMessageLetter : inputMessageArray) {
for (String alphabetLetter : ALPHABET) {
if (inputMessageLetter.equals(alphabetLetter)) {
isUpperCase.append(false).append(" ");
break;
} else if (inputMessageLetter.equals(alphabetLetter.toUpperCase())) {
isUpperCase.append(true).append(" ");
break;
} else if (inputMessageLetter.matches("[a-zA-Z]")) {
alphabetCount++;
}
}
if (alphabetCount == 0 && inputMessageLetter.matches("a")) {
alphabetIndex.append(0).append(" ");
} else if (alphabetCount == 0 && !inputMessageLetter.matches("[a-zA-Z]") && !inputMessageLetter.equals(" ")) {
alphabetIndex.append(inputMessageLetter).append(" ");
isUpperCase.append("false").append(" ");
} else {
if (inputMessageLetter.equals(" ")) {
alphabetIndex.append(inputMessageLetter);
isUpperCase.append("false").append(" ");
} else {
alphabetIndex.append(alphabetCount).append(" ");
}
}
alphabetCount = 0;
}
if (mode.equals("enc")) {
return indexWithKey(alphabetIndex, inputKey, isUpperCase);
} else if (mode.equals("dec")) {
if (alg.equals("shift")) {
return decryptShiftIndexes(alphabetIndex, inputKey, isUpperCase);
} else if (alg.equals("unicode")) {
return decrypt(inputMessage, inputKey);
} else {
return "Algorithm must be shift or unicode!";
}
} else {
return "Mode must be enc or dec!";
}
}
public static String indexWithKey(StringBuilder alphabetIndex, int inputKey, StringBuilder isUpperCase) {
String[] indexArray = alphabetIndex.toString().split(" ");
StringBuilder indexArrayKey = new StringBuilder();
int lengthOfAlphabet = 25;
for (String index :
indexArray) {
int indexWithKeyCount;
if (index.matches("\\d+")) {
indexWithKeyCount = Integer.parseInt(index) + inputKey;
if (indexWithKeyCount > lengthOfAlphabet) {
indexWithKeyCount = Math.abs(lengthOfAlphabet - indexWithKeyCount);
indexArrayKey.append(indexWithKeyCount - 1).append(" ");
} else {
indexArrayKey.append(indexWithKeyCount).append(" ");
}
} else {
indexArrayKey.append(index).append(" ");
}
}
return replaceIndexWithLetters(indexArrayKey, isUpperCase);
}
public static String replaceIndexWithLetters(StringBuilder indexArrayKey, StringBuilder isUpperCase) {
String[] isUpperCaseArray = isUpperCase.toString().split(" ");
String[] alphabetIndexArray = indexArrayKey.toString().split(" ");
StringBuilder outputCipher = new StringBuilder();
int indexCount = 0;
int count = 0;
for (String letterIndexPosition : alphabetIndexArray) {
for (String s : ALPHABET) {
if (!letterIndexPosition.matches("\\d+")) {
if (alphabetIndexArray[indexCount].equals("")) {
outputCipher.append(letterIndexPosition).append(" ");
} else {
outputCipher.append(letterIndexPosition);
}
break;
} else if (count == Integer.parseInt(letterIndexPosition)) {
if (isUpperCaseArray[indexCount].equals("true")) {
outputCipher.append(s.toUpperCase());
} else {
outputCipher.append(s);
}
break;
}
count++;
}
indexCount++;
count = 0;
}
return outputCipher.toString();
}
public static String decryptShiftIndexes(StringBuilder alphabetIndex, int inputKey, StringBuilder isUpperCase) {
String[] alphabetIndexArray = alphabetIndex.toString().split(" ");
StringBuilder output = new StringBuilder();
for (String index :
alphabetIndexArray) {
if (index.matches("\\d+")) {
if (Integer.parseInt(index) - inputKey < 0) {
output.append(Integer.valueOf(26 - Math.abs(Integer.parseInt(index) - inputKey))).append(" ");
} else {
output.append(Integer.parseInt(index) - inputKey).append(" ");
}
} else {
output.append(index).append(" ");
}
}
return decryptShift(output, isUpperCase);
}
public static String decryptShift(StringBuilder output, StringBuilder isUpperCase) {
String[] isUpperCaseArray = isUpperCase.toString().split(" ");
String[] outputFinal = output.toString().split(" ");
StringBuilder outputFinal2 = new StringBuilder();
for (int indexCount = 0; indexCount < outputFinal.length; indexCount++) {
for (String index :
outputFinal) {
if (index.matches("\\d+")) {
if (isUpperCaseArray[indexCount].equals("true")) {
outputFinal2.append(ALPHABET[Integer.parseInt(index)].toUpperCase());
} else {
outputFinal2.append(ALPHABET[Integer.parseInt(index)]);
}
} else {
if (index.equals("")) {
outputFinal2.append(index).append(" ");
} else {
outputFinal2.append(index);
}
}
}
}
return String.valueOf(outputFinal2);
}
public static String encrypt(String inputMessage, int inputKey) {
char[] encryptCharArray = inputMessage.toCharArray();
char[] charArray2 = new char[encryptCharArray.length];
for (int i = 0; i < charArray2.length; i++) {
charArray2[i] = encryptCharArray[i] += inputKey;
}
return new String(charArray2);
}
public static String decrypt(String inputMessage, int inputKey) {
char[] decryptCharArray = inputMessage.toCharArray();
char[] charArray2 = new char[decryptCharArray.length];
for (int i = 0; i < charArray2.length; i++) {
charArray2[i] = decryptCharArray[i] -= inputKey;
}
return new String(charArray2);
}
public static void writeCipherTextFile(File inputFile, File outputFilePath, int key, String alg, String mode) throws IOException {
Path reader = Path.of(String.valueOf(inputFile));
List<String> allLines = Files.readAllLines(reader);
String allLinesString = allLines.toString();
// Remove the List<String> brackets
String allLinesStringWithoutBrackets = allLinesString.substring(1, allLinesString.length() - 1);
if (alg.equals("unicode")) {
Files.writeString(Paths.get(outputFilePath.toString()), encrypt(allLinesStringWithoutBrackets, key));
} else if (alg.equals("shift")) {
Files.writeString(Paths.get(outputFilePath.toString()), alphabetIndexPositions(allLinesStringWithoutBrackets, key, mode, alg));
}
}
public static void readCipherTextFile(File inputFile, File outputFilePath, int key, String alg, String mode) throws IOException {
Path reader = Path.of(String.valueOf(inputFile));
List<String> allLines = Files.readAllLines(reader);
String allLinesString = allLines.toString();
// Remove the List<String> brackets
String allLinesStringWithoutBrackets = allLinesString.substring(1, allLinesString.length() - 1);
if (alg.equals("unicode")) {
Files.writeString(Paths.get(outputFilePath.toString()), decrypt(allLinesStringWithoutBrackets, key));
} else if (alg.equals("shift")) {
Files.writeString(Paths.get(outputFilePath.toString()), alphabetIndexPositions(allLinesStringWithoutBrackets, key, mode, alg));
}
}
}
</code></pre>
<h1><strong>Example Usage</strong></h1>
<pre><code>Example 1
java Main -mode enc -in road_to_treasure.txt -out protected.txt -key 5 -alg unicode
This command must get data from the file road_to_treasure.txt, encrypt the data with the key 5, create a file called protected.txt and write ciphertext to it.
Example 2
Input:
java Main -mode enc -key 5 -data "Welcome to hyperskill!" -alg unicode
Output:
\jqhtrj%yt%m~ujwxpnqq&
Example 3
Input:
java Main -key 5 -alg unicode -data "\jqhtrj%yt%m~ujwxpnqq&" -mode dec
Output:
Welcome to hyperskill!
Example 4:
Input:
java Main -key 5 -alg shift -data "Welcome to hyperskill!" -mode enc
Output:
Bjqhtrj yt mdujwxpnqq!
Example 5:
Input:
java Main -key 5 -alg shift -data "Bjqhtrj yt mdujwxpnqq!" -mode dec
Output:
Welcome to hyperskill!
</code></pre>
<p><strong>GitHub</strong></p>
<p><a href="https://github.com/iamericfletcher/Encrypt-Decrypt-GH" rel="nofollow noreferrer">https://github.com/iamericfletcher/Encrypt-Decrypt-GH</a></p>
|
[] |
[
{
"body": "<p>Here's what I found in no particular order, I hope it helps:</p>\n<h2>Command line parsing</h2>\n<p>The parser will throw an <code>OutOfBoundsException</code> or will use garbage if the user doesn't provide a value after an argument flag. If you pass only an input file but no output file, the parser also fails. It works well with good input though. Consider trying out a library like <a href=\"http://www.martiansoftware.com/jsap/\" rel=\"nofollow noreferrer\">JSAP</a> or <a href=\"https://commons.apache.org/proper/commons-cli/\" rel=\"nofollow noreferrer\">Commons-CLI</a>, these should catch all the edge cases for you. Also, a help page using the <code>-h/--help</code> arg would be very helpful.</p>\n<h2>Java 14 switch cases</h2>\n<p>Maybe I'm just not used to the syntax yet, but I wouldn't use arrows in a <code>switch</code> where some of the cases need multiple lines. Using standard <code>break</code>s looks a bit more uniform here, but that's mostly my opinion.</p>\n<h2>Exception handling</h2>\n<p>Having <code>main</code> throw an <code>IOException</code> is fine for quick scripts, but for anything bigger please use <code>try/catch</code> to properly handle exceptions where they occur. A stack trace isn't very helpful to the user, instead catch the exception(s) and print a "human-readable" error message.</p>\n<h2>BUG: Decrypting doesn't preserve newlines</h2>\n<p>Encrypting and then decrypting replaces newlines with <code>, </code>, ruining the input file. While doing a <code>toString()</code> on the <code>List<String></code> seems convenient, I'd loop over the entries and handle the line breaks manually. Another way is to read the entire file as one string and encrypt that. You might get some unprintable characters when encrypting the linebreaks though.</p>\n<h2>Comments</h2>\n<p>Please add some comments! I'm having a hard time understanding which function does what, why and how. Add a couple lines of comments before a method to briefly describe what it does and add a line whereever you do more complicated things. It helps us understand your code and it will help you if you decide to work on it after half a year.</p>\n<h2>Variable names</h2>\n<h4>Too long</h4>\n<p><code>allLinesStringWithoutBracket</code> is too long of a name. Long names will make all lines longer and introduce line breaks in the middle of statements, making the code harder to read. This is mostly caused by...</p>\n<h4>...Bad var names</h4>\n<p>Good names tell the reader not the content/type of the variable, but what the variable is supposed to represent. A made-up example would be this:<br />\nSay you split an input string <code>inputString</code> by spaces. You could name it <code>inputStringArray</code>, but that doesn't help the reader and is already rather long. Ask yourself: What <em>is</em> this array? Depending on the context, it could be called <code>words</code> (<code>inputString</code> is a line of text), <code>args</code> (command line), <code>tokens</code> (some sort of script), etc. Note: Shorter name, but helps the reader to understand the program.</p>\n<p>You also have some vars ending in <code>...2</code>. In these cases, they are used to store some sort of result, so they should be named accordingly.</p>\n<h4>Inconsistent naming</h4>\n<p>Both <code>inputFile</code> and <code>outputFilePath</code> are <code>File</code>s. Going by the name, I'd expect the latter to be either a <code>Path</code> or a <code>String</code> though.</p>\n<h4>Java naming conventions</h4>\n<p>Anything starting with <code>is</code> is usually a <code>boolean</code>. Here you have a <code>StringBuilder isUpperCase</code>, which is confusing.</p>\n<p>=====</p>\n<p>I get identical output for both of your encryption schemes (<code>unicode</code> and <code>shift</code>). Is that a bug, intended or am I using the program wrong?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T20:22:03.747",
"Id": "265924",
"ParentId": "265896",
"Score": "1"
}
},
{
"body": "<p><strong>Conditions</strong></p>\n<p>Sometimes you use "switch", sometimes you use "if..else if..." . This inconsistency doesn't help readability.</p>\n<p><strong>Data types</strong></p>\n<ul>\n<li>You use String for char values</li>\n<li>You use a space-delimited String for what should be boolean arrays, and also for integer arrays</li>\n</ul>\n<p><strong>Maths</strong></p>\n<ul>\n<li>You use "+=" and "-=" in contexts where changing the value you're adding to doesn't seem to make sense.</li>\n</ul>\n<p><strong>Algorithm Implementation</strong></p>\n<p>It would help us critique your code better if we had a clear expression of the encryption and decryption algorithms in use. I'm convinced they could be more elegantly implemented, but I haven't got the patience to reverse engineer them from your code and then do the rewrite.</p>\n<p>Update: This seems to be a simple Caesar (ROT-n) cipher, in which case you have made it incredibly complicated, with an unreasonable number of passes through your input data.</p>\n<p><strong>Decisions</strong></p>\n<p>You seem to need to make decisions too many times. Once you know you are encoding, that should be it; similarly, once you know you are using the "shift" algorithm, that should be it. You shouldn't need to pass the mode and algorithm around.</p>\n<p>This is because you haven't done anything sensible about object-orientation and encapsulation.</p>\n<p>The encrypter/decrypter class shouldn't care where its input comes from and you shouldn't have a single encrypter/decrypter class. That's not the Java way...</p>\n<p>If I were doing this, I'd start with an interface - let's call it "Algorithm" - which provides an encode and decode method, each taking a Reader and a Writer as arguments.</p>\n<pre><code>import java.io.IOException;\nimport java.io.Reader;\nimport java.io.Writer;\n\npublic interface Algorithm {\n public void encode(Reader in, Writer out) throws IOException;\n public void decode(Reader in, Writer out) throws IOException;\n}\n</code></pre>\n<p>Then you would have classes to implement that interface - say ShiftAlgorithm and UnicodeAlgorithm, for lack of better names. The method implementations would simply read characters from their input, apply the appropriate transformation and write the transformed data to their output.</p>\n<p>You can produce appropriate Readers and Writer for files, System.in/System.out and Strings easily enough, and none of that should be the business of the Algorithm implementation.</p>\n<p>Here's a example doing just "encoding" with a dummy (no-op) Algorithm implementation and a String as input. You should be able to see how this could be extended for your variations.</p>\n<pre><code>import java.io.CharArrayReader;\nimport java.io.CharArrayWriter;\nimport java.io.IOException;\nimport java.io.Reader;\nimport java.io.Writer;\n\npublic class EncDec {\n\n public static void main(String[] args) throws IOException {\n Algorithm algImp = new DummyAlgorithm();\n\n String testInput = "My Dog Has Fleas";\n Reader encodeInput = new CharArrayReader(testInput.toCharArray());\n Writer encodeOutput = new CharArrayWriter();\n\n algImp.encode(encodeInput, encodeOutput);\n System.out.format("Encoded data = {%s}%n", encodeOutput.toString());\n\n }\n\n static final class DummyAlgorithm implements Algorithm {\n\n @Override\n public void encode(Reader in, Writer out) throws IOException {\n cat(in, out);\n }\n\n @Override\n public void decode(Reader in, Writer out) throws IOException {\n cat(in, out);\n }\n\n private void cat(Reader in, Writer out) throws IOException {\n int inChar;\n while ((inChar = in.read()) != -1) {\n out.write(inChar);\n }\n }\n }\n}\n</code></pre>\n<p>Here's a simple implementation of the ROT cipher using this Interface approach:</p>\n<pre><code> static final class RotAlgorithm implements Algorithm {\n\n int rotationDegree;\n\n RotAlgorithm(int degree) {\n rotationDegree = degree;\n }\n\n @Override\n public void encode(Reader in, Writer out) throws IOException {\n int inChar;\n while ((inChar = in.read()) != -1) {\n out.write(rotateChar(inChar, rotationDegree));\n }\n }\n\n @Override\n public void decode(Reader in, Writer out) throws IOException {\n int inChar;\n while ((inChar = in.read()) != -1) {\n out.write(rotateChar(inChar, -rotationDegree));\n }\n }\n\n private int rotateChar(int inChar, int degree) {\n if ((inChar >= 'a') && (inChar <= 'z')) {\n return rotateChar(inChar, 'a', 'z', degree);\n }\n if ((inChar >= 'A') && (inChar <= 'Z')) {\n return rotateChar(inChar, 'A', 'Z', degree);\n }\n return inChar;\n }\n\n private int rotateChar(int inChar, char start, char end, int degree) {\n int newChar = inChar + degree;\n if (newChar > end) {\n newChar = start + ((newChar - end) - 1);\n }\n else if (newChar < start) {\n newChar = end - ((start - newChar) - 1);\n }\n return newChar;\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T08:24:12.630",
"Id": "265981",
"ParentId": "265896",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "265981",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T01:02:17.993",
"Id": "265896",
"Score": "2",
"Tags": [
"java",
"beginner"
],
"Title": "Program that encrypts and decrypts messages and texts"
}
|
265896
|
<p>Well, there are many game of life's already, but after posting an answer on it in C#, I thought I might as well check if I did any better and if there is anything new to learn - there always is.</p>
<p>Design:</p>
<ul>
<li>main object is a <code>Board</code> which represents a board including the living cells;</li>
<li>both the initial board and the subsequent boards are created using a builder and are otherwise immutable</li>
<li>the actual state of the board is kept in an array of 64 bit words, this is not a two dimensional array but a single array consisting of the subsequent rows</li>
<li>the actual game is run in <code>Game</code> of course, using the deliberately simple <code>next</code> method</li>
<li>the <code>Direction</code> enum can be used to identify the neighboring cells</li>
<li>the <code>Position</code> class is too boring to explain, it's immutable as well but can be used to calculate other positions using <code>relativePosition</code>.</li>
</ul>
<p>I've left out any JavaDoc for conciseness, the code should be mostly self explaining (please indicate if you think it doesn't). <code>GameMain</code> is just there for demonstration purposed, I've left out any UI work; I am not looking for UI advice. Also, the exceptions are deliberately left out; they are there but known to be dumbed down.</p>
<p>Finally, in <code>Board.Builder</code> you will find a seemingly unused method called <code>applyPattern</code> which can be used to apply patterns as a kind of "stamp". The code for that is slightly too expansive to post directly (I've designed a file format for boards and patterns for good measure).</p>
<p>Anything you would have done differently w.r.t. design? Coding practices or conciseness? Please let me know.</p>
<p><strong>Board</strong></p>
<pre><code>package nl.owlstead.gameoflife;
import java.util.Arrays;
public class Board {
private final int width;
private final int height;
private final long[] state;
private final int stateWidth;
private Board(int width, int height, long[] state) {
this.width = width;
this.height = height;
this.state = state;
this.stateWidth = state.length / height;
}
public boolean isAlive(Position pos) {
if (!isValid(width, height, pos)) {
throw new IllegalArgumentException("Position " + pos + " is not on the board.");
}
int x = pos.getX();
int y = pos.getY();
int cellsInState = calculateLocationInState(stateWidth, x, y);
long cells = state[cellsInState];
int cellInCells = calculateLocationInLong(x);
return (cells & (1L << cellInCells)) != 0;
}
public boolean isValid(Position pos) {
return isValid(width, height, pos);
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Board)) {
return false;
}
var that = (Board) obj;
// check dimensions
if ((this.width != that.width) || (this.height != that.height)) {
return false;
}
// simple array compare
return Arrays.compare(this.state, that.state) == 0;
}
public String toString() {
if (width * height > 6400) {
return "Board too large";
}
// includes carriage return
var sb = new StringBuilder((width + 1) * height);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
sb.append(isAlive(new Position(x, y)) ? "\u25CF" : " "); // "\u25A1" is white square
}
sb.append("\n");
}
return sb.toString();
}
private static boolean isValid(int width, int height, Position pos) {
int x = pos.getX();
int y = pos.getY();
return (x >= 0) && (x < width) && (y >= 0) && (y < height);
}
private static int calculateLocationInState(int stateWidth, int x, int y) {
return y * stateWidth + x / Long.SIZE;
}
private static int calculateLocationInLong(int x) {
return x % Long.SIZE;
}
private static int calculateStateWidth(int width) {
return (width + Long.SIZE - 1) / Long.SIZE;
}
private static int calculateStateSize(int width, int height) {
return calculateStateWidth(width) * height;
}
public static class Builder {
private final int width;
private final int height;
private final long[] state;
private int stateWidth;
public Builder(int width, int height) {
this.width = width;
this.height = height;
this.state = new long[calculateStateSize(width, height)];
this.stateWidth = calculateStateWidth(width);
}
public void makeAlive(Position pos) {
// NOTE could be made assertion
if (!isValid(width, height, pos)) {
throw new IllegalArgumentException("Position is not valid for this board " + pos);
}
int x = pos.getX();
int y = pos.getY();
int cellsInState = calculateLocationInState(stateWidth, x, y);
int cellInCells = calculateLocationInLong(x);
long mask = 1L << cellInCells;
this.state[cellsInState] |= mask;
}
public void applyPattern(Position position, GolPattern pattern) {
var alivePositions = pattern.getAlivePositions();
for (var alivePosition : alivePositions) {
var alivePositionOnBoard = alivePosition.relativePosition(position.getX(), position.getY());
makeAlive(alivePositionOnBoard);
}
}
public Board build() {
return new Board(width, height, state);
}
}
}
</code></pre>
<p><strong>Position</strong></p>
<pre><code>package nl.owlstead.gameoflife;
public final class Position {
private final int x;
private final int y;
public Position(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public Position relativePosition(int deltaX, int deltaY) {
return new Position(x + deltaX, y + deltaY);
}
@Override
public int hashCode() {
return x + y * 0x10001;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Position)) {
return false;
}
var that = (Position) obj;
return (this.x == that.x && this.y == that.y);
}
@Override
public String toString() {
return String.format("(%d, %d)", x, y);
}
}
</code></pre>
<p><strong>Game</strong></p>
<pre><code>package nl.owlstead.gameoflife;
public class Game {
// could be extended to detect cycles
public enum Freshness {
FRESH,
// NOTE for future use
CYCLING,
STALE;
}
private Freshness freshness = Freshness.FRESH;
private Board current;
public Game(Board start) {
this.current = start;
}
private int getNeighborCount(Position pos) {
int count = 0;
for (var direction : Direction.ALL_DIRECTIONS) {
var candidate = pos.relativePosition(direction.getDeltaX(), direction.getDeltaY());
if (current.isValid(candidate) && current.isAlive(candidate)) {
count++;
}
}
return count;
}
private boolean becomesOrStaysAlive(Position pos) {
boolean isAlive = current.isAlive(pos);
int neighborCount = getNeighborCount(pos);
// condensed rules for game of life
if (isAlive) {
return neighborCount == 2 || neighborCount == 3;
} else {
return neighborCount == 3;
}
}
private Board calculateNextBoardState() {
int width = current.getWidth();
int height = current.getHeight();
var builder = new Board.Builder(width, height);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
Position pos = new Position(x, y);
if (becomesOrStaysAlive(pos)) {
builder.makeAlive(pos);
}
}
}
return builder.build();
}
public boolean next() {
var next = calculateNextBoardState();
if (next.equals(current)) {
this.freshness = Freshness.STALE;
return false;
} else {
this.current = next;
return true;
}
}
public Board getCurrent() {
return current;
}
public Freshness getFreshness() {
return freshness;
}
}
</code></pre>
<p><strong>Direction</strong></p>
<pre><code>package nl.owlstead.gameoflife;
import java.util.EnumSet;
import java.util.Set;
public enum Direction {
N(0, -1),
NE(1, -1),
E(1, 0),
SE(1, 1),
S(0, 1),
SW(-1, 1),
W(-1, 0),
NW(-1, -1);
public static final Set<Direction> ALL_DIRECTIONS = EnumSet.allOf(Direction.class);
private final int deltaX;
private final int deltaY;
private Direction(int deltaX, int deltaY) {
this.deltaX = deltaX;
this.deltaY = deltaY;
}
public int getDeltaX() {
return deltaX;
}
public int getDeltaY() {
return deltaY;
}
}
</code></pre>
<p><strong>GameMain</strong></p>
<pre><code>package nl.owlstead.gameoflife;
import java.util.regex.Pattern;
public class GameMain {
private static final Pattern POSITION_FINDER_PATTERN = Pattern.compile("[(](\\d+),(\\d+)[)]");
public static void main(String[] args) {
var builder = new Board.Builder(8, 8);
String gliderStartState = "(1,0)(2,1)(0,2)(1,2)(2,2)";
var m = POSITION_FINDER_PATTERN.matcher(gliderStartState);
while (m.lookingAt()) {
int x = Integer.parseInt(m.group(1));
int y = Integer.parseInt(m.group(2));
Position pos = new Position(x, y);
builder.makeAlive(pos);
m.region(m.end(), m.regionEnd());
}
if (!m.hitEnd()) {
throw new RuntimeException();
}
var start = builder.build();
var game = new Game(start);
do {
System.out.println(game.getCurrent());
} while (game.next());
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Not bad at all, therefore here's only a few things that rub me the wrong way:</p>\n<ul>\n<li>Encoding the state in a long. Why? We are talking about saving a few hundred bytes at most, and we are in an age where this will not even make a difference on a mobile phone. This had been a good idea in 1970, but today you're better off when you simply use an array which you can index.</li>\n<li>Even if you <em>absolutely want</em> to save space by encoding more values in a single long, use java.util.BitSet instead of rolling your own.</li>\n<li>Half of the methods in the Board class are static, probably because you use them in the Builder, too. This makes the class a mixup of object oriented encapsulation and a utility class. I don't like that.</li>\n<li>"var" was a patently bad idea in my opinion, and it is banned from all projects where I can influence the coding guidelines.</li>\n<li>Making classes final (your Position class) normally does not make sense. How can you tell today, that there won't be a good reason to extend the class a year down the road.</li>\n<li>The ALL_DIRECTIONS set in Direction is (a) not necessary, as an enum has the <code>values()</code> method, and (b) mutable. The <code>final</code> only makes the <em>reference</em> final, but you could still call <code>Direction.ALL_DIRECTIONS.clear()</code> from outside. You have to wrap it in <code>Collections.immutableSet()</code> to achive your goal.</li>\n<li>Having the Board encode the visual output is a mixup of concerns. OK for debugging, but not beyond that.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T14:12:24.920",
"Id": "525243",
"Score": "0",
"body": "Interesting part about the memory management; I thought this was the best way to create a single compact & aligned piece of memory though. If you know a good way of creating a builder without the static methods then I'm all ears; I rewrote the original methods when I found out that the builder needed them as well, and I think extending the object with a builder may not be the best thing to do (but maybe I was wrong about that)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T17:06:52.910",
"Id": "525259",
"Score": "0",
"body": "I recreated one where the builder extends the original class and it seems to work; some private static methods still required as you can only call the `super` constructor directly though. One possible issue with that is that some of the none-builder methods may not work in an invalid state during building; you might want to go over those and override them throwing an `OperationNotSupportedException`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T17:08:25.720",
"Id": "525260",
"Score": "0",
"body": "Worse though, you could now use the builder class as stand in for the original class, at which point I have to call defeat."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T17:27:21.233",
"Id": "525261",
"Score": "0",
"body": "The options I can immediately think of are a static utility class to encapsulate the common methods, or a common base class. Both have their drawbacks. Personally, I'd go for the utility class, as I'd rather pay the price for a silly utility than for a bad abstraction."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T06:18:24.813",
"Id": "265901",
"ParentId": "265897",
"Score": "5"
}
},
{
"body": "<p>The Game of Life board is a sparse data structure. Replacing the array with a <code>Map<Position,Freshness></code> would relieve you from allocating space for unused positions. You would iterate over actual existing cells, not empty locations. It would allow for dynamically expanding and "infinite" board size and it would make range checks mostly unnecessary.</p>\n<p><code>Game</code> is not immutable and I don't see a reason why it shouldn't be. It represents game state and one of the objectives was to make the game state immutable. If we define <code>Board</code> to be a dumb data object the <code>Game</code> class would represent a generation within the game and it should be renamed. In my vocabulary, "game" represents the whole program and I find it too generic in this case. A generation does not change once it has been created. A generation can be dead if does not contain any living cells or stable if it is identical to it's previous generation. The class should provide this information so that the user interface code can end the program when there is no point in continuing.</p>\n<p>Expandin on mtj's opinion on var. <em>It is a patently bad idea and should not be used.</em> There is an argument for it that it reduces clutter when the type can be inferred from the statement (e.g. <code>var value = new String(...)</code>), but you use it in many places where a var is assigned a value that is returned from a method call and figuring out the type then requires inspecting the method signature. Because it is so easily misused and the misuses make the code so much harder to follow, it should not be used at all. Ever.</p>\n<p><code>Direction</code> seems a bit unnecessary class and it adds clutter as you have to manually add the delta to a <code>Position</code>. Instead just add a <code>Position add(Position)</code> method to the <code>Position</code> class and define the directions as <code>Position</code>s. And that's enough tautology for this paragraph. :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T12:55:39.030",
"Id": "525298",
"Score": "0",
"body": "Thanks for the view. I do think you got a few things wrong, possibly due to my naming. Freshness is used **in the game** to indicate if it is stale or not. The board is really the state of the board (I named it `BoardState` initially but thought that was a bit wordy and could call it `Generation` instead). That makes the argument to rename `Game` (which encapsulates the rules of a changing game) moot, I think. I don't like to mix uses for position to capture both coordinates and delta coordinates, but yeah, I get your point."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T04:37:02.027",
"Id": "525377",
"Score": "0",
"body": "@MaartenBodewes Correct, it all comes to how the responsibilities are divided. I think my preference would be having the Board or Generation as you have it, then place the evolutionary rules into a separate class (defined by an interface so that it can be changed easily) and the control structure that runs the process into a third class."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T05:58:57.950",
"Id": "265937",
"ParentId": "265897",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "265901",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T02:29:12.927",
"Id": "265897",
"Score": "6",
"Tags": [
"java",
"game",
"design-patterns",
"game-of-life",
"coordinate-system"
],
"Title": "Conway's game of life as Java OO with underlaying array"
}
|
265897
|
<p>I'm solving the classic problem of finding two numbers from an array that sum to a given value.</p>
<p>Can anybody please check whether my analysis of time and space complexity is correct on this one?</p>
<pre><code># O(n) time | O(1) space
def twoNumberSum(array, targetSum):
for x in array:
y = targetSum - x
if y!=x and y in array:
return [x, y]
return []
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T06:26:59.593",
"Id": "525211",
"Score": "2",
"body": "It is nearly impossible to solve this problem with O(n) time and O(1) space."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T14:51:58.053",
"Id": "525246",
"Score": "0",
"body": "Executing `y in array` already takes linear (O(n)) time. This is inside the `for x in array` loop, so this O(n) has to be multiplied by n (the number of elements you loop over). Hence quadratic (O(n²)) time, not linear. Also note `y != x` has nothing to do with the problem and should be removed for the code to give correct results, leaving only `if y in array:`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T15:04:39.900",
"Id": "525248",
"Score": "2",
"body": "I think the `y!=x` should actually be checking indices. As things are, `twoNumberSum([2,2],4)` will be false. If you remove it as Stef suggests, `twoNumberSum([1,2],4)` will be true."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T04:00:40.477",
"Id": "525280",
"Score": "0",
"body": "@leaf_yakitori If the list is sorted, we can solve it with two pointers approach in linear time."
}
] |
[
{
"body": "<p>This code fails given <code>[0, 1, 1]</code> and <code>2</code> as inputs: it should return <code>[1,1]</code> but fails because the two numbers are identical. So it fails review, without any further analysis.</p>\n<p>Scaling is poorer than you believe, if <code>array</code> is a list, since <code>in</code> is generally linear in the list length. Since <code>in</code> is used inside the <code>for</code> loop, time taken is proportional to O(n²).</p>\n<p>When no result is present, I would probably choose to return <code>None</code> rather than an empty list.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T05:58:23.563",
"Id": "265899",
"ParentId": "265898",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T04:49:39.817",
"Id": "265898",
"Score": "2",
"Tags": [
"python"
],
"Title": "Python - Two Number Sum (time and space complexity)"
}
|
265898
|
<p>Taking forward the code written for the math library previously mentioned here. <a href="https://github.com/suryasis-hub/MathLibrary" rel="nofollow noreferrer">link</a>. Wrote templatized functions for mode and standard deviations. (Some of the changes to the previous reviews were not made yet.
Please review the same.</p>
<p><strong>NB</strong>: I get certain comments regarding the inclusion of headers. This is a part of a visual studio project and some of the headers are moved to pch.h.</p>
<p><strong>CODE</strong></p>
<pre><code>#include <vector>
#include <numeric>
#include <string>
#include <functional>
#include <unordered_map>
namespace Statistics
{
template <typename T>
T average(const std::vector<T> &distributionVector)
{
if (distributionVector.size() == 0)
{
throw std::invalid_argument("Statistics::average - The distribution provided is empty");
}
return std::accumulate(distributionVector.begin(), distributionVector.end(), T())
/ (distributionVector.size());
}
template <typename T>
T variance(const std::vector<T> &distributionVector)
{
if (distributionVector.size() == 0)
{
throw std::invalid_argument("Statistics::expectation - The distribution provided is empty");
}
T meanOfSquare = average(distributionVector);
return (std::accumulate(distributionVector.begin(), distributionVector.end(), T(), [=](T a,T b) { return a + (b - meanOfSquare )*(b - meanOfSquare); })/distributionVector.size());
}
template <typename T>
T standardDeviation(const std::vector<T>& distributionVector)
{
return pow(variance(distributionVector), 0.5);
}
template<typename T>
T mode(const std::vector<T>& distributionVector)
{
std::unordered_map<T, int> frequencyMap;
std::for_each(distributionVector.begin(), distributionVector.end(), [&](T a) { frequencyMap[a]++; });
int maxCount = 0;
std::for_each(frequencyMap.begin(), frequencyMap.end(), [&](auto a) { maxCount = std::max(maxCount, a.second); });
T answer;
std::for_each(frequencyMap.begin(), frequencyMap.end(), [&](auto a) { if (maxCount == a.second) { answer = a.first; } });
return answer;
}
}
</code></pre>
<p><strong>Test code</strong></p>
<pre><code>#include "pch.h"
#include <vector>
#include "../MathLibrary/Combinatorics.h"
#include "../MathLibrary/Statistics.h"
void compareDoubles(double a, double b)
{
const double THRESHOLD = 0.01;
ASSERT_TRUE(abs(a - b) < THRESHOLD);
}
TEST(Combinatorial_Factorial, small_ints)
{
EXPECT_EQ(Combinatorics::factorial(0), 1);
EXPECT_EQ(Combinatorics::factorial(1), 1);
EXPECT_EQ(Combinatorics::factorial(5), 120);
EXPECT_EQ(Combinatorics::factorial(20), 2432902008176640000);
}
TEST(Combinatorial_Factorial, too_big)
{
EXPECT_THROW(Combinatorics::factorial(500), std::invalid_argument);
}
TEST(Combinatorial_Combinations, small_ints)
{
EXPECT_EQ(Combinatorics::combinations(5,5), 1);
EXPECT_EQ(Combinatorics::combinations(5, 0), 1);
EXPECT_EQ(Combinatorics::combinations(5, 1), 5);
EXPECT_EQ(Combinatorics::combinations(20,10),184756);
EXPECT_EQ(Combinatorics::combinations(40, 35),658008);
}
TEST(Combinatorial_Combinations, negative_n)
{
EXPECT_THROW(Combinatorics::combinations(-5, 5), std::invalid_argument);
}
TEST(Combinatorial_Combinations, r_greater_than_n)
{
EXPECT_THROW(Combinatorics::combinations(4, 5), std::invalid_argument);
}
TEST(Combinatorial_Combinations, overflow)
{
EXPECT_THROW(Combinatorics::combinations(100, 50), std::invalid_argument);
}
TEST(Combinatorial_Permutations, small_ints)
{
EXPECT_EQ(Combinatorics::permutations(5, 5), 120);
EXPECT_EQ(Combinatorics::permutations(5, 0), 1);
EXPECT_EQ(Combinatorics::permutations(5, 2), 20);
EXPECT_EQ(Combinatorics::permutations(10, 2), 90);
EXPECT_EQ(Combinatorics::permutations(40, 3), 59280);
EXPECT_EQ(Combinatorics::permutations(40, 7), 93963542400);
EXPECT_EQ(Combinatorics::permutations(50, 4), 5527200);
}
TEST(Combinatorial_Permutations, r_negative)
{
EXPECT_THROW(Combinatorics::permutations(5, -5), std::invalid_argument);
}
TEST(Combinatorial_Permutations, n_negative)
{
EXPECT_THROW(Combinatorics::permutations(-5, 5), std::invalid_argument);
}
TEST(Combinatorial_Permutations,r_greater)
{
EXPECT_THROW(Combinatorics::permutations(5, 6), std::invalid_argument);
}
TEST(Combinatorial_Permutations,overflow)
{
EXPECT_THROW(Combinatorics::permutations(50,46), std::invalid_argument);
}
TEST(Statistics_mean, small_distributions)
{
std::vector<int> testVector = { -2,-1,0,1,2 };
EXPECT_EQ(Statistics::average(testVector), 0);
std::vector<double> testVectorDouble = {5,5,6,6};
compareDoubles(Statistics::average(testVectorDouble), 5.5);
}
TEST(Statistics_mean, empty_distribution)
{
std::vector<int> testVector;
EXPECT_THROW(Statistics::average(testVector), std::invalid_argument);
}
TEST(Statistics_variance, small_distribution)
{
std::vector<double> testVector = { 0,0 };
compareDoubles(Statistics::variance(testVector), 0);
std::vector<double> testVector2 = {1,2,3,4};
compareDoubles(Statistics::variance(testVector2), 1.25);
std::vector<double> testVectorRandom = { 1,2,3,4,6,8,9,34,45,78,89 };
compareDoubles(Statistics::variance(testVectorRandom), 938.2314);
}
TEST(Statistics_standarddev, small_distribution)
{
std::vector<double> testVector = { 0,0 };
compareDoubles(Statistics::standardDeviation(testVector), 0);
std::vector<double> testVector2 = { 1,2,3,4 };
compareDoubles(Statistics::standardDeviation(testVector2), 1.11803);
std::vector<double> testVectorRandom = { 1,2,3,4,6,8,9,34,45,78,89 };
compareDoubles(Statistics::standardDeviation(testVectorRandom), 30.6305);
}
TEST(Statistics_mode, small_distribution)
{
std::vector<int> testVector = { 32,32, 45, 12,32};
EXPECT_EQ(Statistics::mode(testVector), 32);
std::vector<int> testVector1 = { 32,32,32 };
EXPECT_EQ(Statistics::mode(testVector1), 32);
std::vector<int> testVector2 = {0};
EXPECT_EQ(Statistics::mode(testVector2), 0);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T07:18:47.183",
"Id": "525215",
"Score": "2",
"body": "The test code seems to be a repeat of the functions. I guess it's a copy-paste error?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T07:36:06.420",
"Id": "525220",
"Score": "1",
"body": "Made the changes. Thanks for spotting that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T13:54:36.780",
"Id": "525240",
"Score": "0",
"body": "What jumps out are the same issues as before. `size()==0`, specific to (whole) vectors,"
}
] |
[
{
"body": "<blockquote>\n<pre><code> throw std::invalid_argument("Statistics::average - The distribution provided is empty");\n</code></pre>\n</blockquote>\n<p>Oops - we didn't include <code><stdexcept></code>.</p>\n<blockquote>\n<pre><code> return pow(variance(distributionVector), 0.5);\n</code></pre>\n</blockquote>\n<p>What's <code>pow()</code>? If we meant <code>std::pow()</code>, we need to include <code><cmath></code>. And <code>std::sqrt()</code> would be clearer and more idiomatic than <code>std::pow( , 0.5)</code>.</p>\n<hr />\n<p>Now we have the code compiling, let's have a proper look inside.</p>\n<blockquote>\n<pre><code>template <typename T>\nT average(const std::vector<T> &distributionVector)\n</code></pre>\n</blockquote>\n<p>I think a previous review advised that <code>T</code> might be a poor choice of return type. For example, we probably want a <code>double</code> for the mean of a vector of <code>int</code>. And accepting only vectors, rather than any range, is too inflexible for many users.</p>\n<hr />\n<blockquote>\n<pre><code> int maxCount = 0;\n std::for_each(frequencyMap.begin(), frequencyMap.end(), [&](auto a) { maxCount = std::max(maxCount, a.second); });\n T answer;\n std::for_each(frequencyMap.begin(), frequencyMap.end(), [&](auto a) { if (maxCount == a.second) { answer = a.first; } });\n</code></pre>\n</blockquote>\n<p>Here, we're traversing the vector twice. We should just use <code>std::max_element()</code> to traverse the list once, then return the value from that element.</p>\n<hr />\n<p>What's the mode of an empty list? It's surprising and inconsistent that this function doesn't throw when the list is empty, given that the other functions do.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T10:23:58.857",
"Id": "265909",
"ParentId": "265900",
"Score": "2"
}
},
{
"body": "<pre><code> std::for_each(distributionVector.begin(), distributionVector.end(), [&](T a) { frequencyMap[a]++; });\n</code></pre>\n<p>Use prefix <code>++</code> not postfix. If <code>T</code> is not an elementary integer type, the general implementation of postfix is to <em>copy</em> the argument and call the prefix version then return the argument. Get in the habit of using <code>++x</code> not <code>x++</code> in general.</p>\n<pre><code> int maxCount = 0;\n std::for_each(frequencyMap.begin(), frequencyMap.end(), [&](auto a) { maxCount = std::max(maxCount, a.second); });\n T answer;\n std::for_each(frequencyMap.begin(), frequencyMap.end(), [&](auto a) { if (maxCount == a.second) { answer = a.first; } });\n</code></pre>\n<p>You make two passes why? The first finds the largest count, and the second then finds the last element having that count. You could simply remember the max <em>and</em> the associated value in the first loop. Another flaw of the second loop is not returning as soon as it finds the match, but runs through the whole collection anyway.</p>\n<p>You can just use the <code>max_element</code> passing in a lambda for the comparison that compares the <code>.second</code>. It returns the entire pair, of which you return the <code>.first</code>.</p>\n<p>More generally, the built-in range-based <code>for</code> loop is simpler and more flexible than the (original, begin/end iterator based) <code>for_each</code> algorithm.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T14:06:56.953",
"Id": "265915",
"ParentId": "265900",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T06:14:23.327",
"Id": "265900",
"Score": "4",
"Tags": [
"c++",
"beginner"
],
"Title": "Mode and standard deviation for Math Library"
}
|
265900
|
<p>From the PEP8 "Function names should be lowercase, with words separated by underscores as necessary to improve readability."</p>
<p>Then we have popular libraries like matplotlib with arguments i.e. <code>linewidth</code> and <code>markersize</code>, which is apparently doesn't follow the convention. The question is when
you have arguments with the exact same meaning, should you follow the PEP8 or library naming.
I.e. what is generally more acceptable</p>
<pre class="lang-py prettyprint-override"><code>def show(x, y, line_width, marker_size):
plt.plot(x, y, linewidth=line_width, markersize=marker_size, marker='o')
plt.show()
</code></pre>
<p>or</p>
<pre class="lang-py prettyprint-override"><code>def show(x, y, linewidth, markersize):
plt.plot(x, y, linewidth=linewidth, markersize=markersize, marker='o')
plt.show()
</code></pre>
|
[] |
[
{
"body": "<p>I'd say it depends on who your code is for. If your library is designed for coders who are familiar with matplotlib and the arguments its functions take (they know what <code>linewidth</code> and <code>markersize</code> are in the context of matplotlib), use the matplotlib naming. Otherwise use the more standard python naming (snake case). If the rest of your library API uses snake case, then I think it would be more consistent to follow that and "smooth over" the matplotlib naming. From PEP 8:</p>\n<blockquote>\n<p>Consistency with this style guide is important. Consistency within a project is more important. Consistency within one module or function is the most important.</p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T09:23:20.753",
"Id": "265905",
"ParentId": "265904",
"Score": "4"
}
},
{
"body": "<p>First is better - it's making a bridge from PEP8 style code into old style code, not drawing old style into the new code.</p>\n<p>PEP8 says:</p>\n<blockquote>\n<p>In particular: do not break backwards compatibility just to comply with this PEP!</p>\n<p>Some other good reasons to ignore a particular guideline:</p>\n<ol>\n<li>When applying the guideline would make the code less readable, even for someone who is used to reading code that follows this PEP.</li>\n<li>To be consistent with surrounding code that also breaks it (maybe for historic reasons) -- although this is also an opportunity to clean up someone else's mess (in true XP style).</li>\n<li>Because the code in question predates the introduction of the guideline and there is no other reason to be modifying that code.</li>\n<li>When the code needs to remain compatible with older versions of Python that don't support the feature recommended by the style guide.</li>\n</ol>\n</blockquote>\n<p>I don't think <code>linewidth=line_width</code> is less readable then <code>linewidth=linewidth</code>, and there's no other needs to do the second.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T09:25:58.477",
"Id": "525224",
"Score": "2",
"body": "My only reservation is if the user of the code knows the function is a wrapper for matplotlib, they may be more familiar with matplotlib naming."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T10:23:03.273",
"Id": "525227",
"Score": "0",
"body": "I think it's still clear enough."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T09:24:03.870",
"Id": "265906",
"ParentId": "265904",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "265906",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T08:31:44.057",
"Id": "265904",
"Score": "-1",
"Tags": [
"python"
],
"Title": "Should you follow the style convention in python with old libraries?"
}
|
265904
|
<p>I wrote a 2-layer neural net with just Python & NumPy to implement the XOR Gate, here is the code</p>
<pre><code>import time
start_time = time.time()
import numpy as np
def sigmoid(z):
return 1 / (1 + np.exp(-z))
class MLPClassifier:
def __init__(self, eta=.05, n_epoch=10, n_0=2, n_1=2, n_2=1,
model_w1=[], model_b1=[], model_w2=[], model_b2=[]):
self.eta = eta
self.n_epoch = n_epoch
self.model_w1 = model_w1
self.model_b1 = model_b1
self.model_w2 = model_w2
self.model_b2 = model_b2
self.n_1 = n_1
self.n_2 = n_2
def initialize_params(self, n_0, n_1, n_2):
if len(self.model_w1) == 0:
self.model_w1 = np.full((n_0, n_1), .5)
if len(self.model_w2) == 0:
self.model_w2 = np.random.uniform(size=(n_1, n_2))
if len(self.model_b1) == 0:
self.model_b1 = np.random.uniform(size=(1, n_1))
if len(self.model_b2) == 0:
self.model_b2 = np.random.uniform(size=(1, n_2))
def predict(self, x):
_, a2 = self.forward_propagation(x)
yhat = a2 >= 0.5
return 1*yhat
def forward_propagation(self, x):
z1 = np.dot(x, self.model_w1) + self.model_b1
a1 = sigmoid(z1)
z2 = np.dot(a1, self.model_w2) + self.model_b2
a2 = sigmoid(z2)
return a1, a2
def backward_propagation(self, x, y, a1, a2):
m = len(x)
n_1 = self.n_1
n_2 = self.n_2
a1 = a1.reshape(m, -1)
dz2 = a2 - y
dw2 = np.dot(a1.T, dz2)/m
dw2 = dw2.reshape(n_1, n_2)
db2 = np.mean(dz2, keepdims = True)
dz1 = np.dot(dz2, self.model_w2.T) * (a1*(1-a1))
dw1 = np.dot(x.T, dz1)/m
db1 = np.mean(dz1, axis=0)
return dw2, db2, dw1, db1
def update_params(self, dw2, db2, dw1, db1):
self.model_w2 -= self.eta * dw2
self.model_b2 -= self.eta * db2
self.model_w1 -= self.eta * dw1
self.model_b1 -= self.eta * db1
def fit(self, x, y, verbose=False):
n_0 = x.shape[-1]
n_1 = self.n_1
n_2 = self.n_2
self.initialize_params(n_0, n_1, n_2)
for i in range(self.n_epoch):
a1, a2 = self.forward_propagation(x)
dw2, db2, dw1, db1 = self.backward_propagation(x, y, a1, a2)
self.update_params(dw2, db2, dw1, db1)
x_train = np.array([[0,0],[0,1],[1,0],[1,1]])
y_train = np.array([0,1,1,0]).reshape(4,1)
print('preparation took {:.5f} s'.format(time.time() - start_time))
classifier = MLPClassifier(.1, 10000)
classifier.fit(x_train, y_train, verbose=True)
print('training took {:.5f} s'.format(time.time() - start_time))
acc = np.count_nonzero(np.squeeze(classifier.predict(x_train)) == np.squeeze(y_train))
print('train accuracy {:.5f}'.format(acc/len(y_train)))
print(*classifier.predict(x_train))
print('the whole app took {:.5f} s'.format(time.time() - start_time))
</code></pre>
<p>The code works as expected.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T10:03:21.737",
"Id": "265908",
"Score": "0",
"Tags": [
"python",
"machine-learning"
],
"Title": "Implement the XOR Gate using a 2-layer neural net with just Python & NumPy"
}
|
265908
|
<p>Python Beginner building an automation irrigation system in Raspberry Pi.</p>
<p>The Python has two functions:</p>
<ol>
<li>Single wire temperature sensor (DS18B20) that prints/monitors temperature</li>
<li>Turn on LED (will be relay switch)</li>
</ol>
<p>The idea is when the temperature gets too hot, it will turn on the switch/Led that will turn on the air conditioning.</p>
<p>Looking on advice in two capacities:</p>
<ol>
<li>To make it cleaner/better code and more efficient</li>
<li>How can I use "Temperature" as a global variable so I can use it on other things like a screen/LCD</li>
</ol>
<pre><code>#import modules
import time
import board
import busio
import digitalio
from board import *
from datetime import date
#DigitalIO and Pin setup
tempLed = digitalio.DigitalInOut(D17) #PIN LED for too hot sensor.
tempLed.direction = digitalio.Direction.OUTPUT
tempSensor = digitalio.DigitalInOut(D14) #Temp sensor DS18B20 as configured in terminal
tempSensor.switch_to_input(pull=digitalio.Pull.UP)
tempSensor.pull = digitalio.Pull.UP
#main loop
try:
while True:
tempStore = open("/sys/bus/w1/devices/28-3cffe076cfcf/w1_slave") #change this number to the Device ID of your sensor
data = tempStore.read()
tempStore.close()
tempData = data.split("\n")[1].split(" ")[9]
temperature = float(tempData[2:])
temperature = temperature/1000
print(temperature)
if temperature > 24: #change this value to adjust the 'too hot' threshold
tempLed.value = True
else:
tempLed.value = False
time.sleep(1)
except KeyboardInterrupt:
digitalio.cleanup()
print ("Program Exited Cleanly")
</code></pre>
<p>Sample data:</p>
<pre class="lang-none prettyprint-override"><code>70 01 55 05 7f a5 81 66 3d : crc=3d YES
70 01 55 05 7f a5 81 66 3d t=23000
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T15:08:18.167",
"Id": "525249",
"Score": "2",
"body": "Your `data.split(\"\\n\")[1].split(\" \")[9]` operation extracts the 10th space-separated word from the second line of `data`. We can't tell how robust that extraction process is without seeing what the sensor returns. Could you provide a sample of the actual data that gets returned from the sensor?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T14:20:24.947",
"Id": "525313",
"Score": "0",
"body": "@AJNeufeld - thanks for info; this is data extracted for temperature = 23. First example is data = `70 01 55 05 7f a5 81 66 3d : crc=3d YES\n70 01 55 05 7f a5 81 66 3d t=23000\n` and this is tempData \n`t=23000`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T01:19:27.617",
"Id": "525373",
"Score": "0",
"body": "I’ve added the sample data to the question post. Please confirm it was formatted properly, by editing it if it was not."
}
] |
[
{
"body": "<p>I'm going to assume that your device has a <code>sysfs</code> interface identical to that described in <a href=\"https://albertherd.com/2019/01/20/using-c-to-monitor-temperatures-through-your-ds18b20-thermal-sensor-raspberry-pi-temperature-monitoring-part-3/\" rel=\"noreferrer\">this guide</a>, which based on your code is likely the case.</p>\n<blockquote>\n<p>How can I use "Temperature" as a global variable</p>\n</blockquote>\n<p>is the opposite direction to what you should do. Currently <em>all</em> of your code is global, but you should put some effort into making it re-entrant.</p>\n<p>Other than your global code, one thing that stands out is the non-guaranteed <code>close</code> call, which should be replaced by a <code>with</code> statement.</p>\n<p>You should not need to <code>read()</code> the entire file. Instead, read line-by-line until you find a match.</p>\n<pre><code> if temperature > 24: #change this value to adjust the 'too hot' threshold\n tempLed.value = True\n else: \n tempLed.value = False\n</code></pre>\n<p>should be reduced to</p>\n<pre><code>temp_led.value = temperature > threshold\n</code></pre>\n<p>where <code>threshold</code> is a parameter instead of being hard-coded, and the variable names are PEP8-compliant.</p>\n<pre><code>except KeyboardInterrupt:\n digitalio.cleanup() \n print ("Program Exited Cleanly")\n</code></pre>\n<p>should instead be</p>\n<pre><code>except KeyboardInterrupt:\n pass\nfinally:\n digitalio.cleanup() \n print ("Program Exited Cleanly")\n</code></pre>\n<p>In other words, you should clean up regardless of why and how the program exited.</p>\n<p>Don't hard-code the device ID - if you can assume that there's only one such sensor, use glob-matching instead.</p>\n<h2>Suggested (not tested)</h2>\n<pre class=\"lang-py prettyprint-override\"><code>class TempSensor:\n def __init__(self):\n sensor = digitalio.DigitalInOut(D14) # Temp sensor DS18B20 as configured in terminal\n sensor.switch_to_input(pull=digitalio.Pull.UP)\n sensor.pull = digitalio.Pull.UP\n\n parent, = Path('/sys/bus/w1/devices/').glob('28-*')\n self.path = parent / 'w1_slave'\n\n def read(self) -> float:\n with self.path.open() as f:\n for line in f:\n parts = line.split('t=', 1)\n if len(parts) == 2:\n return float(parts[1].rstrip()) / 1000\n raise ValueError('Temperature not found')\n\n\ndef polling_loop(interval: float=1, threshold: float=24) -> None:\n sensor = TempSensor()\n led = digitalio.DigitalInOut(D17) # PIN LED for too hot sensor. \n led.direction = digitalio.Direction.OUTPUT\n\n while True:\n temperature = sensor.read()\n print(temperature)\n led.value = temperature > threshold\n time.sleep(interval)\n\n\ndef main() -> None:\n try:\n polling_loop()\n except KeyboardInterrupt:\n pass\n finally:\n digitalio.cleanup() \n print("Program Exited Cleanly")\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T16:14:58.777",
"Id": "265919",
"ParentId": "265914",
"Score": "10"
}
},
{
"body": "<p>Here are a few comments:</p>\n<ul>\n<li>To ensure resources are closed, use a <code>with</code> statement instead of a simple <code>open</code> and <code>close</code>:</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>with open("/sys/bus/w1/devices/28-3cffe076cfcf/w1_slave") as tempStore:\n data = tempStore.read()\n</code></pre>\n<ul>\n<li>If the device ID is subject to change, extract it to a variable so its easier to modify. Otherwise, you'd have to go through the code to see where its uses whenever you need to change it:</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>DEVICE_ID = "28-3cffe076cfcf"\nTEMP_SENSOR_PATH = f"/sys/bus/w1/devices/{DEVICE_ID}/w1_slave"\n...\nopen(TEMP_SENSOR_PATH)\n</code></pre>\n<ul>\n<li>A simple <code>open</code> statement is fine, but the usual way to go now is using <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"noreferrer\">pathlib</a>:</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>from pathlib import Path\n\nDEVICE_ID = "28-3cffe076cfcf"\nTEMP_SENSOR_PATH = Path("/sys/bus/w1/devices/") / DEVICE_ID / "w1_slave"\n...\nwith TEMP_SENSOR_PATH.open() as tempStore:\n...\n</code></pre>\n<ul>\n<li>Separate concerns: Reading the temperature is unrelated to updating the sensor, so make it clearer by creating two different functions with signatures as such:</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>...\nwhile True:\n temperature = readTemperature()\n updateLED(temperature, tempLed)\n</code></pre>\n<ul>\n<li><p>I am not familiar with <code>digitalio</code>, but it seems a bit weird to create and configure the variable <code>tempSensor</code>, but then read the temperature from a file instead requesting it to the sensor directly. This could possibly also fix what @AJNeufeld commented with regards of the obscure parsing of the file.</p>\n</li>\n<li><p>I am not sure what you mean by "use Temperature as a global variable so I can use it on other things like a screen/LCD". Are you referring to inter-process communications? Otherwise, if you plan on controlling the LCD display in the same process (which seems like a good option), your main loop would end up like:</p>\n</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>while True:\n temperature = readTemperature()\n updateLED(temperature, tempLed)\n updateLCD(temperature, tempLcd)\n</code></pre>\n<p>You could say this already seems like a good fit for the observer pattern, but if you don't plan on adding more subscribers, it might be a bit of an overhead</p>\n<ul>\n<li>To make the code cleaner, you could use OOP, and encapsulate the sensors in your own classes, so you would first initialise them:</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>tempSensor = TempSensor(pin=TEMP_SENSOR_PIN)\ntempLed = TempLed(pin=TEMP_LED_PIN)\ntempLcd = TempLcd(pin=TEMP_LCD_PIN)\n</code></pre>\n<p>And them use them in the main loop:</p>\n<pre class=\"lang-py prettyprint-override\"><code>while True:\n temperature = tempSensor.readTemperature()\n tempLed.update(temperature)\n tempLcd.update(temperature)\n</code></pre>\n<ul>\n<li>Try to avoid using <code>from xxx import *</code>, as it makes it harder to know which package is being used when using global statements, as in <code>D19</code>.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T16:43:34.797",
"Id": "265920",
"ParentId": "265914",
"Score": "5"
}
},
{
"body": "<h1>Introduce hysteresis</h1>\n<p>In addition to the excellent comments reviewing your code, I want to address something in the algorithm being used. The current algorithm that uses a single threshold will cause frequent starts and stops of the unit. In the very worst case, noise in the temperature sensor could cause the unit to cycle on and off many times per minute or even per second, leading to its rapid destruction. Even if that doesn't happen, starts are a major source of wear on the cooling unit, so it is desirable to reduce the frequency with which it is started. This can be done by introducing <a href=\"https://en.m.wikipedia.org/wiki/Deadband#Hysteresis_versus_Deadband\" rel=\"nofollow noreferrer\">hysteresis</a> to the algorithm. So instead of there being a single threshold:</p>\n<pre><code>tempLed.value = temperature > 24\n</code></pre>\n<p>there would be one threshold for turning the cooling unit on, and a separate threshold for turning it off:</p>\n<pre><code>threshold = 24\nhysteresis = 1\n# If the unit is running, then require a lower temperature before\n# turning it off\nif tempLed.value:\n threshold = threshold - hysteresis\ntempLed.value = temperature > threshold\n</code></pre>\n<p>To prevent the destruction of the cooling unit, the hysteresis should be at least large enough that it prevents signal noise from starting or stopping the unit. However, if the application is to keep people comfortable, then the hysteresis should not be so large that people feel too cold before the unit shuts off. The larger the hysteresis, the less frequent the unit will start and the longer it will last.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T12:08:49.677",
"Id": "265950",
"ParentId": "265914",
"Score": "6"
}
},
{
"body": "<h1>imports</h1>\n<p>Already mentioned earlier, but it is not recommended to do that:</p>\n<pre><code>from board import *\n</code></pre>\n<p>because of <strong>namespace pollution</strong> and potential <strong>function clashes</strong> which could be hard to debug. Some background reading: <a href=\"https://bytebaker.com/2008/07/30/python-namespaces/\" rel=\"nofollow noreferrer\">A guide to Python Namespaces</a></p>\n<p>Besides, you import the same module later:</p>\n<pre><code>import board\n</code></pre>\n<p>But you could import just the functions you need eg:</p>\n<pre><code>from board import somefunc, someotherfunc\n</code></pre>\n<p>However it seems that you not even using the module in this code. <code>datetime</code> also appears to be unused. Ditto for <code>busio</code>. I recommend that you get rid of unused imports or variables because they are unnecessary distractions. The program could be more concise. A good IDE can highlight unused resources in your code.</p>\n<h1>Comments</h1>\n<p>The actions you are doing on your pins (?) right after the imports deserve to be commented in plain English. It's not obvious what these lines achieve exactly and why they are critical. Even one line or two would be welcome. Yours comments are a bit cryptic but no doubt you know what they mean now, but if you revisit your code in 6 months you may need a refresher.</p>\n<p>The rest of the code is self-explanatory.</p>\n<h1>Naming conventions</h1>\n<p>Mixing lowercase and uppercase in variables should be avoided but you can use the underscore <kbd>_</kbd> character to separate keywords. Read up on PEP8.</p>\n<h1>Parsing data</h1>\n<p>The way the data is being parsed is a bit clumsy and may be not very robust.\nYou could use a <strong>regular expression</strong> and <strong>capture</strong> the desired pattern. Or simplify your split operation like this:</p>\n<pre><code>data.split(" ")[-1]\n</code></pre>\n<p>If you know that the temperature value is the <strong>rightmost</strong> data field, then you can just split the string like you're doing and take the first element starting from the right, hence the negative index. Then you can for example use a further <code>[2:]</code> to extract the temperature from the string after <code>t=</code>.</p>\n<h1>logging</h1>\n<p>Instead of using print I recommend that you start the habit of using the <strong>logging</strong> module. To quote myself, <a href=\"https://codereview.stackexchange.com/a/238459/219060\">an example</a>. It would be beneficial for the following reasons:</p>\n<ul>\n<li>in addition to console you can also output text to a file, and the text can be formatted differently than on console</li>\n<li>the file can also be more <strong>verbose</strong> than the console - you can decide to send debug messages to file only for example</li>\n<li>your data samplings will be <strong>timestamped</strong> automatically if you so wish</li>\n<li>this is definitely desirable for unattended applications</li>\n</ul>\n<h1>Exception handling</h1>\n<p>There is no real exception handling presently, you are only handling the Ctrl-C event but the program could crash for any reason. Just add a catch-all except clause to handle other exceptions that are not explicitly addressed in your code, and log the full error details along with <strong>stacktrace</strong>. For this you use the logging module.</p>\n<p>As mentioned by @Reinderien you can also add a <strong>finally</strong> clause in your try block and move this code to finally:</p>\n<pre><code>digitalio.cleanup()\n</code></pre>\n<p>Thus, it will be systematically executed when leaving the program, even if the program exits as a result of an unhandled exception.</p>\n<h1>Improvements for the future - data collection</h1>\n<p>As I pointed earlier you are not logging anything, not keeping any <strong>history</strong>.\nI think you may be interested in <strong>collecting data</strong> to analyze trends or answer questions like:</p>\n<ul>\n<li><strong>How long</strong> has the temperature been above threshold within a certain time period ?</li>\n<li><strong>How many times</strong> did the program turn on the air conditioning ?</li>\n<li><strong>How long</strong> did the air conditioning operate within a certain time period ?</li>\n<li>What was the <strong>maximum temperature</strong> recorded ?</li>\n</ul>\n<p>For example if you find out that the airco is running 25% of the time it could mean a number of things: possibly the room is not insulated enough, or the airco is not powerful enough. But it's not something you can easily tell without <strong>measuring</strong> and <strong>recording</strong> data samples.</p>\n<p>If your program turns the airco on and off like it should, it's already good - it's doing its job. But it does not help improve the operating conditions in the long term.</p>\n<p>What follows is outside the scope of the review and is merely a suggestion if you want to take your project to the next level, but you could have a machine running <a href=\"https://prometheus.io/\" rel=\"nofollow noreferrer\">Prometheus</a> that collects data from your sensors at regular intervals with the help of a custom <a href=\"https://prometheus.io/docs/instrumenting/exporters/\" rel=\"nofollow noreferrer\">exporter</a> and all that data could be visualized on nice dashboards using <a href=\"https://grafana.com/\" rel=\"nofollow noreferrer\">Grafana</a>. Free and open source of course.</p>\n<p>Here is a long <a href=\"https://leanpub.com/rpcmonitor/read#leanpub-auto-about-prometheus\" rel=\"nofollow noreferrer\">tutorial</a>, you can skip a good chunk of it and start with the Prometheus section. FYI the default retention period in Prometheus is 15 days... but you can configure that.</p>\n<p>Finally, you could have a graph like this in your dashboard to review observed temperatures with the ability to filter on a time range... (courtesy of the above-mentioned tutorial)</p>\n<p><a href=\"https://i.stack.imgur.com/PeIT8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/PeIT8.png\" alt=\"Grafana screenshot\" /></a></p>\n<p>This may look like a big infrastructure project but if you run other machines or even servers it definitely makes sense. You can monitor all sorts of machines and collects all types of metrics to gain insight into the health and activity of your systems.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T21:52:08.913",
"Id": "525363",
"Score": "0",
"body": "I'd say the actions being done on the pins are pretty standard when working with electronics. They just define the led pin being output, and the sensor being a pull up input"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T21:16:02.563",
"Id": "265971",
"ParentId": "265914",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T14:00:33.267",
"Id": "265914",
"Score": "5",
"Tags": [
"python-3.x"
],
"Title": "Temperature Sensor that loop and turns on cooling"
}
|
265914
|
<p>I'm working on a project that will have both a server and a client, using Boost's ASIO library for networking.
I'm not really comfortable working with Makefiles, but, with some help from Chase Lambert's <a href="https://makefiletutorial.com/#makefile-cookbook" rel="nofollow noreferrer">https://makefiletutorial.com/#makefile-cookbook</a> and other things I found online I got the following Makefile:</p>
<pre><code>BUILD_DIR := ./build
INC_DIRS := ./include
SRC_DIRS := ./src
SERVER_TARGET_EXEC := server
CLIENT_TARGET_EXEC := client
TARGETS := $(BUILD_DIR)/$(SERVER_TARGET_EXEC) $(BUILD_DIR)/$(CLIENT_TARGET_EXEC)
# Find all the C and C++ files we want to compile
# For SRCS we exclude files inside the src/server and src/client directories
SRCS := $(shell find $(SRC_DIRS) \( -name "*.cpp" -or -name "*.c" \) ! \( -path '*/server/*' -or -path '*/client/*' \))
SERVER_SRCS := $(shell find $(SRC_DIRS)/server -name *.cpp -or -name *.c)
CLIENT_SRCS := $(shell find $(SRC_DIRS)/client -name *.cpp -or -name *.c)
# String substitution for every C/C++ file.
# As an example, hello.cpp turns into ./build/hello.cpp.o
OBJS := $(SRCS:%=$(BUILD_DIR)/%.o)
SERVER_OBJS := $(SERVER_SRCS:%=$(BUILD_DIR)/%.o)
CLIENT_OBJS := $(CLIENT_SRCS:%=$(BUILD_DIR)/%.o)
ALL_OBJS := $(SUDOKU_OBJS) $(SERVER_OBJS) $(CLIENT_OBJS)
# String substitution (suffix version without %).
# As an example, ./build/hello.cpp.o turns into ./build/hello.cpp.d
DEPS := $(ALL_OBJS:.o=.d)
# Every folder in ./src will need to be passed to GCC so that it can find header files
INC_DIRS += $(shell find $(SRC_DIRS) -type d ! \( -path '*/server' -or -path '*/client' \))
# Add a prefix to INC_DIRS. So moduleA would become -ImoduleA. GCC understands this -I flag
INC_FLAGS := $(addprefix -I,$(INC_DIRS))
# The -MMD and -MP flags together generate Makefiles for us!
# These files will have .d instead of .o as the ouput
CPPFLAGS := $(INC_FLAGS) -MMD -MP -g
CPPFLAGS += -g
CPPFLAGS += -Wall -Wextra
CPPFLAGS += -Wpedantic -Warray-bounds -Weffc++
CPPFLAGS += -Werror
# For Boost ASIO we need to link against Boost Thread and Boost System
LDFLAGS := -pthread
LDFLAGS += -lboost_thread -lboost_system
all: $(TARGETS)
$(BUILD_DIR)/$(SERVER_TARGET_EXEC): $(OBJS) $(SERVER_OBJS)
$(BUILD_DIR)/$(CLIENT_TARGET_EXEC): $(OBJS) $(CLIENT_OBJS)
# The final build step
$(TARGETS):
$(CXX) $^ -o $@ $(LDFLAGS)
# Build step for C source
$(BUILD_DIR)/%.c.o: %.c
mkdir -p $(dir $@)
$(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@
# Build step for C++ source
$(BUILD_DIR)/%.cpp.o: %.cpp
mkdir -p $(dir $@)
$(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $< -o $@
.PHONY: clean
clean:
rm -r $(BUILD_DIR)
# Include the .d makefiles. The - at the front suppresses the errors of missing
# Makefiles. Initially, all the .d files will be missing, and we don't want those
# errors to show up
-include $(DEPS)
</code></pre>
<p>Any suggestions on what could be improved?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T03:01:32.277",
"Id": "525279",
"Score": "0",
"body": "Is SUDOKU_OBJS a copy paste error?"
}
] |
[
{
"body": "<p>Why are <code>INC_DIRS</code> and <code>SRC_DIRS</code> pluralized if they only contain one value each, and are treated that way throughout the rest of the makefile? These should be singular.</p>\n<p>It looks like <code>$(OBJS)</code> is common to both executables, and is re-linked in each case. It would be (in most cases) better to represent this as a separate, dedicated link step that produces a <code>.so</code> shared object rather than static linking. This shared object file would be shipped beside both the server and client, and the size of the server and client binaries would be reduced.</p>\n<p>Your</p>\n<pre><code> mkdir -p $(dir $@)\n $(CC) $(CPPFLAGS) $(CFLAGS) -c $< -o $@\n</code></pre>\n<p>would ideally be split up into two different make targets - one to make the directory, and the second depending on the directory and compiling the object.</p>\n<p><code>SUDOKU_OBJS</code> seems a likely error.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T13:59:08.737",
"Id": "525308",
"Score": "0",
"body": "Thank you for your suggestions, I like the idea of compiling `$(OBJS)` as a shared object :)\n\nAnd yes, `SUDOKU_OBJS` was indeed a copy paste error, I forgot to change its name when modifying the code for my question :/"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T03:35:10.377",
"Id": "265933",
"ParentId": "265916",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "265933",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T14:24:07.817",
"Id": "265916",
"Score": "2",
"Tags": [
"c++",
"boost",
"makefile",
"make"
],
"Title": "Makefile that compiles to two separate executables"
}
|
265916
|
<p>I'm trying to write a function to replace the standard <code>std::stod(...)</code>. I want to parse the following valid inputs:</p>
<p><code>/[+-]?\d+(?:\.\d+)?(?:e[-+]?\d+)?/g</code></p>
<p>Here's the <a href="https://regexr.com/63fv4" rel="nofollow noreferrer">RegExr link</a>.</p>
<p>And also the words <code>infinity</code>, <code>+infinity</code>, <code>-infinity</code>, <code>undefined</code>, <code>+undefined</code> and <code>-undefined</code>. Note, if I remember well, <code>infinity</code> and <code>+infinity</code> are the same underlying values while <code>undefined</code>, <code>+undefined</code> and <code>-undefined</code> are all different <code>NaN</code> values.</p>
<p>So I came up with this:</p>
<pre><code>#include <iostream>
#include <cmath>
#include <limits>
#include <cstring>
using namespace std;
class invalid_number { };
static bool is_digit(char c) {
// probably faster than `return c >= '0' && c <= '9';`?
switch (c) {
case '0': case '1': case '2':
case '3': case '4': case '5':
case '6': case '7': case '8':
case '9': return true;
default: return false;
}
}
double safe_pow(double a, double b) {
if (b < 0) return 1.0 / pow(a, abs(b));
else return pow(a, b);
}
// parses /[+-]?\d+(?:\.\d+)?(?:e[-+]?\d+)?/g
static double s2d(char * s) {
bool negative = (s[0] == '-');
bool positive = (s[0] == '+');
if (positive || negative) s++;
// + infinity == infinity
if (!strcmp(s, "infinity\0")) {
if (negative) return - numeric_limits<double>::infinity();
return numeric_limits<double>::infinity();
}
// + undefined != undefined != - undefined
if (!strcmp(s, "undefined\0")) {
if (negative) return - numeric_limits<double>::quiet_NaN();
if (positive) return + numeric_limits<double>::quiet_NaN();
return numeric_limits<double>::quiet_NaN();
}
if (!is_digit(* s)) throw invalid_number();
int64_t x = 0, point = 0, d = 0;
while (is_digit(* s)) {
x = (x * 10) + (* s) - '0';
s++; point++; d++;
}
if ((* s) == '.') {
s++;
if (!is_digit(* s)) throw invalid_number();
while (is_digit(* s)) {
x = x * 10 + (* s) - '0';
s++; d++;
}
} else point = 0;
if (negative) x *= -1;
uint64_t e = 0; bool ne = false;
if ((* s) == 'e') {
s++;
if ((* s) == '-') { ne = true; s++; }
else if ((* s) == '+') s++;
if (!is_digit(* s)) throw invalid_number();
while (is_digit(* s)) {
e = (e * 10) + (* s) - '0';
s++;
}
}
if (!point) return x;
point = d - point;
if (ne) point += e; else point -= e;
return x / safe_pow(10, point);
}
int main(int argc, char * argv[]) {
cout << "test number: ";
string number;
getline(cin, number);
/* test cases:
-537e+4
+20
34.3e-10
2e5
-5e3
-2
-22.27e0
*/
try {
cout << s2d((char *)number.c_str()) << endl;
} catch (invalid_number & inv) {
cout << "invalid number" << endl;
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T15:45:21.290",
"Id": "525251",
"Score": "2",
"body": "Why are you putting an extra `\\0` in your strings? Note that in the comparisons that doesn't do anything since the compare stops at the _first_ `\\0`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T16:59:11.950",
"Id": "525255",
"Score": "3",
"body": "I'd expect \".125\" and `\"123.\"` to be acceptable, yet it appears `/[+-]?\\d+(?:\\.\\d+)?(?:e[-+]?\\d+)?/g` does not allow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T17:01:20.920",
"Id": "525256",
"Score": "1",
"body": "`undefined` is not certainly different from both `+undefined` and `-undefined`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T17:43:13.700",
"Id": "525262",
"Score": "0",
"body": "@chux-ReinstateMonica, javascript has a different opinion on the matter + undefined, -undefined, undefined. Also, I put the regex because I want to parse only what the regex parses, it's not an error, it's exactly what I want it to do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T17:45:45.167",
"Id": "525263",
"Score": "0",
"body": "@JDługosz I know, I know, but of course I was just testing it. Also, shouldn't c-strings be always null-terminated for consistency and for the eventual `strlen(...)` function to work?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T19:06:46.830",
"Id": "525265",
"Score": "0",
"body": "@Cristian Hmmm, \"javascript has a different opinion on the matter\" seems unrelated to the `C` tagged review. IAC look forward to reviewing code once fixed. (Curious you did not post your input with the errant result and expected result). Perhaps try stack overflow?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T19:09:33.623",
"Id": "525266",
"Score": "1",
"body": "@chux-ReinstateMonica, last time I checked, the IEEE 754 standard was the same for c, c++ and javascript... Also, there are several undefined type of values that indicate different things like 0 / 0 should be NaN different than inf / inf. Anyways, now the code works."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T19:10:12.093",
"Id": "525267",
"Score": "4",
"body": "@PavloSlavynskyy now the code works. sorry for wasting you time, now it's ready to be reviewed"
}
] |
[
{
"body": "<h3>Identifiers</h3>\n<p>Identifiers should be meaningful. What's <code>s</code>? What's <code>d</code>? What's <code>e</code>? Maybe you should name them <code>str</code>, <code>digits_count</code> (or at least <code>n_digits</code>) and <code>exponent</code> or something like that?</p>\n<p>The only exceptions are <code>i</code> and <code>j</code> as common loop variables.</p>\n<h3>One line - one statement</h3>\n<p>Don't put several statements in a single line.</p>\n<pre><code>if( condition )\n statement1;\nelse\n statement2;\n</code></pre>\n<p>is much more readable.</p>\n<h3><code>using namespace std;</code> is bad</h3>\n<p>It's OKish while you're writing a code like this - 50 lines in a single file; but C++ is intended for bigger projects, and mixing names from different namespaces can be at least misleading, at most dangerous.</p>\n<h3>Use standard exceptions</h3>\n<p>There's a <code>std::invalid_argument</code> exception type in <code><stdexcept></code>. You can use it or derive your own class from it. Just <code>invalid_number</code> is unclear.</p>\n<h3><code>is_digit</code> is replacing default <code>std::isdigit</code></h3>\n<p>Is this intended to be so?\nThe same for <code>safe_pow</code> and <code>std::pow</code> - it works with negative values fine, your problem is somewhere else.</p>\n<p>At this point I've run your code - and it still fails on the first example, -537e+4 should be -5370000, not -537.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T13:34:23.377",
"Id": "525304",
"Score": "0",
"body": "oops, I missed that. Good thing you found it, so I can fix it again :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T14:09:12.213",
"Id": "525311",
"Score": "1",
"body": "@Cristian OK to post your own answer with that functional fix (and other improvements) - or post another review . (Tip: If posting a new review, give it a week for this one to get fully vetted)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T21:32:37.837",
"Id": "265925",
"ParentId": "265917",
"Score": "3"
}
},
{
"body": "<p><strong>Edge cases</strong></p>\n<p>Even though the mathematical quotient may be in the <code>double</code> range, <code>safe_pow(10, point)</code> may be outside the <code>double</code> range.</p>\n<p>An alternative scales by 5, then 2</p>\n<pre><code>// return x / safe_pow(10, point);\nx *= pow(5, -point);\nx *= pow(2, -point); // see also scalbn()\nreturn x;\n</code></pre>\n<p><strong>Avoid <a href=\"https://softwareengineering.stackexchange.com/q/80084/94903\">premature optimization</a></strong></p>\n<p><code>// probably faster than return c >= '0' && c <= '9';</code> is simply not supported. The switch statement could as well by 10x slower. Look to <code>isdigit()</code>.</p>\n<p><strong>Nothing safer about <code>safe_pow()</code></strong></p>\n<p>Instead:</p>\n<pre><code>double safe_pow(double a, double b) {\n // if (b < 0) return 1.0 / pow(a, abs(b));\n // else return pow(a, b);\n return pow(a, b);\n}\n</code></pre>\n<p><strong>No overflow protection</strong></p>\n<p><code>x = (x * 10) + (* s) - '0';</code> may overflow on the 19th/20th digit.</p>\n<p>Consider using <code>double</code> math here instead of <code>int64_t</code>.</p>\n<p><strong>It works now - or does it?</strong></p>\n<p>Also test with the string equivalent of <code>DBL_MAX, DBL_MIN, DBL_TRUE_MIN</code> (or the C++ counterparts). See output of <a href=\"https://codereview.stackexchange.com/q/212490/29485\">this</a></p>\n<pre><code> "1.7976931348623157e+308" "179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368.0"\n "2.2250738585072014e-308" "0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002225073858507201383090232717332404064219215980462331830553327416887204434813918195854283159012511020564067339731035811005152434161553460108856012385377718821130777993532002330479610147442583636071921565046942503734208375250806650616658158948720491179968591639648500635908770118304874799780887753749949451580451605050915399856582470818645113537935804992115981085766051992433352114352390148795699609591288891602992641511063466313393663477586513029371762047325631781485664350872122828637642044846811407613911477062801689853244110024161447421618567166150540154285084716752901903161322778896729707373123334086988983175067838846926092773977972858659654941091369095406136467568702398678315290680984617210924625396728515625"\n"-4.9406564584124654e-324" "-0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004940656458412465441765687928682213723650598026143247644255856825006755072702087518652998363616359923797965646954457177309266567103559397963987747960107818781263007131903114045278458171678489821036887186360569987307230500063874091535649843873124733972731696151400317153853980741262385655911710266585566867681870395603106249319452715914924553293054565444011274801297099995419319894090804165633245247571478690147267801593552386115501348035264934720193790268107107491703332226844753335720832431936092382893458368060106011506169809753078342277318329247904982524730776375927247874656084778203734469699533647017972677717585125660551199131504891101451037862738167250955837389733598993664809941164205702637090279242767544565229087538682506419718265533447265625"\n</code></pre>\n<p><strong>Use <code>const</code></strong></p>\n<p>For greater application.</p>\n<pre><code>// double s2d(char * s) {\ndouble s2d(const char * s) {\n</code></pre>\n<p><strong>IEEE 754</strong></p>\n<p>OP <a href=\"https://codereview.stackexchange.com/questions/265917/string-to-double/265930#comment525266_265917\">commented</a> "IEEE 754 standard was the same for c, c++ and javascript." C++ does <em>not</em> specify adherence to <a href=\"https://en.wikipedia.org/wiki/Double-precision_floating-point_format\" rel=\"nofollow noreferrer\">IEEE 754</a>. Better to avoid assuming that.</p>\n<p><strong><code>"-0.0"</code></strong></p>\n<p>Code can properly return -0.0 - good. Better to do the <code>x *= -1</code> after the power-of-10 scaling though to always preserve the sign.</p>\n<p><strong>Curious code</strong></p>\n<p>Two different negation approaches. I'd expect more similar code.</p>\n<pre><code>if (negative) x *= -1;\n...\nif (ne) point += e; else point -= e;\n</code></pre>\n<p><strong>Minor: Caseless <code>e</code></strong></p>\n<p>I'd expect <code>'E'</code> to work as well as <code>'e'</code>.</p>\n<hr />\n<p><strong>Deeper</strong></p>\n<ol>\n<li><p>String to <code>double</code> is a difficult function to get high quality results without extended bit-width math. Conversion from <code>int64_t</code> to <code>double</code>, prior to the multiplication/division can lose many bits. <code>pow()</code> is prone to losing about 1-1.5 bits. I'd expected overall precision to be within 2 bits of the best answer (aside from overflow issues) - not too bad for basic code.</p>\n</li>\n<li><p>IEEE Std 754-2019 discusses how many significant decimal digits should be read before effectively assuming the rest are 0 (even if not) as <code>H</code>. <code>H >= M + 3</code> where <code>M</code> is 17 for <code>double</code>, the number needed to round-trip <code>double</code> -> <em>text</em> -> <code>double</code>. To encode all 20 significant decimal digit takes <code>uint67_t</code> or wider. Thus a <em>quality</em> conversion obliges better than <code>int64_t</code> math. For now, I recommend to settle for a <code>double x</code> in the significant calculation and its inherent imprecision. Later, when ready for a better conversions, look to extended math.</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T13:33:24.747",
"Id": "525303",
"Score": "0",
"body": "this is very useful, thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T14:03:38.350",
"Id": "525309",
"Score": "1",
"body": "@Cristian Looked it up. The `double` significant parsing should handle at least 20 decimal digits to meet IEEE Std 754-2019 standards."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T01:17:56.500",
"Id": "265930",
"ParentId": "265917",
"Score": "3"
}
},
{
"body": "<p><a href=\"https://stackoverflow.com/questions/1452721\">Don’t</a> write <code>using namespace std;</code>.</p>\n<p>You can, however, in a CPP file (not H file) or inside a function put individual <code>using std::string;</code> etc. (See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#sf7-dont-write-using-namespace-at-global-scope-in-a-header-file\" rel=\"nofollow noreferrer\">SF.7</a>.)</p>\n<hr />\n<p><code>if (!strcmp(s, "undefined\\0")) {</code></p>\n<p>First, a <a href=\"https://en.cppreference.com/w/cpp/language/string_literal\" rel=\"nofollow noreferrer\">lexical string literal</a> already contains a terminating <code>\\0</code>. If you write <code>"x"</code> you get a <code>const char unnamed_variable [2] = {'x','\\0'};</code></p>\n<p>Second, don't use <code>strcmp</code> in C++. It is confusing and difficult to use, and very inefficient compared to comparisons that know the length up front. (To be fair, <em>sometimes</em> I can get the compiler to optimize it when experimenting with Compiler Explorer, sometimes it will not.) Use <code>string_view</code> literals so you can write:</p>\n<pre><code>using namespace std::literals; // at the top of your CPP file\n ⋮\nif (s == "undefined"sv) {\n</code></pre>\n<hr />\n<p><code>static double s2d(char * s) {</code></p>\n<p>It should raise a <strong> big red flag </strong> that you must cast the argument to <code>char*</code> any time you want to use it, including the result of <code>string::c_str()</code> and a lexical string literal. Where else does a "normal" string come from? If your function is incompatible with these, there's something fundimentally wrong with it.</p>\n<p>The type should be <code>const char*</code> to fix this problem.</p>\n<p>But, you are not writing in C here, but C++. You want to pass in a <code>std::string</code> (as seen from your test code), as well as pass in a lexical string literal (like <code>"1.23"</code>). To handle both of these and more efficiently, write your functions to take a <code>std::string_view</code> (by value).</p>\n<p>With a <code>string_view</code> you can still use subscript notation, or get a pointer to the underlying characters, <em>as well as</em> getting most of the API of the <code>string</code> class.</p>\n<hr />\n<p>Why is <code>s2d</code> defined as <code>static</code>? That means it will only be seen by this translation unit, which doesn't matter in a simple program that only has one CPP file, but in real code I expect this would be in a library you actually expect to call from somewhere.</p>\n<p>Meanwhile, the helper function <code>safe_pow</code> is <em>not</em>, so you're not just making everything <code>static</code>.</p>\n<hr />\n<h1>const</h1>\n<p>Besides the missing <code>const</code> on your argument type, you don't use it at all anywhere in your post. You should use it <em>a lot</em>. For example,</p>\n<pre><code> const bool negative = (s[0] == '-');\n const bool positive = (s[0] == '+');\n</code></pre>\n<p>Generally, make a variable <code>const</code> if you can.</p>\n<p>As for declarations in general,</p>\n<p><code>int64_t x = 0, point = 0, d = 0;</code><br />\nIt's good to see that you didn't put this at the top of the function, but where you were ready to start using them. However, it is strongly the idiom in C++ to only make one declaration per statement, and they should be on separate lines.</p>\n<hr />\n<h1>Test Code</h1>\n<p>You can write your test code to not require you to type each example every time you run it! And, you can automate the testing that it got the right answer. Take a look at a testing framework such as <a href=\"https://github.com/catchorg/Catch2\" rel=\"nofollow noreferrer\">Catch2</a>.</p>\n<p>Rather than prompting for input, turn your comment into useful data:</p>\n<pre><code>constexpr string_view testdata[]= {\n "-537e+4",\n "+20",\n "34.3e-10",\n "2e5",\n "-5e3",\n "-2",\n "-22.27e0" };\n\nfor (auto s : testdata) {\n const double result= s2d(s);\n // compare result against library's parser or other data\n cout << result << '\\n'; // until it's automated\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T20:59:25.293",
"Id": "265969",
"ParentId": "265917",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "265930",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T14:48:20.887",
"Id": "265917",
"Score": "2",
"Tags": [
"c++",
"strings",
"floating-point"
],
"Title": "string to double"
}
|
265917
|
<p>The Microsoft.Extensions method for Polly, to use policies via dependency injection,
<code>serviceCollection.AddPolicyRegistry()</code>
only allows to add already created policies, while still defining the <em>ServiceCollection</em> content, so other DI service instances, such as loggers, are not available.</p>
<p>To resolve the problem and also because I need some additional data on the policies, I created an interface, which provides a policy:</p>
<pre><code>public interface IPolicySource
{
/// <summary>
/// Name of <see cref="IPolicySource"/> instance, also key in the <see cref="PolicyRegistry"/>.
/// </summary>
string GetName();
/// <summary>
/// The Polly policy, created by the <see cref="IPolicySource"/> implementation.
/// Shall be a singleton instance.
/// </summary>
IsPolicy PollyPolicy { get; }
}
</code></pre>
<p>Implementations of <em>IPolicySource</em> commonly have constructors with a logger as parameter. Later, different configurations per instance shall be possible, represented by different <em>GetName()</em> return values. The implementations can have additional members, like <code>TimeSpan GetHttpClientRequestTimeout()</code> (to have sufficient time for retrying via policy).</p>
<p>I then register the factories for implementations in the <em>ServiceCollection</em>:</p>
<pre><code>public static IServiceCollection AddPolicySource(this IServiceCollection serviceCollection,
Func<IServiceProvider, IPolicySource> policySourceFactory)
{
return serviceCollection.AddSingleton<IPolicySource>(policySourceFactory);
}
</code></pre>
<p>which allows code like:</p>
<pre><code>serviceCollection.AddPolicySource(sp =>
new MyPolicySource( // logger from dependency injection
sp.GetRequiredService<ILogger<MyPolicySource>>()));
</code></pre>
<p>Multiple <em>IPolicySource</em> implementations, even of the same type and with the same <em>GetName()</em> results, can be registered this way.</p>
<p>Finally, the build of the PolicyRegistry is defined through a factory. The normal <em>AddPolicyRegistry()</em> from the Microsoft extensions registers for the interfaces <code>IPolicyRegistry<string></code> and <code>IReadOnlyPolicyRegistry<string></code>:</p>
<pre><code>public static IServiceCollection AddPolicyRegistryUsingPolicySources(this IServiceCollection serviceCollection)
{
serviceCollection.AddSingleton<IPolicyRegistry<string>>(sp =>
sp.BuildPolicyRegistryWithPolicySources())
.AddSingleton<IReadOnlyPolicyRegistry<string>>(sp =>
sp.GetRequiredService<IPolicyRegistry<string>>());
return serviceCollection;
}
</code></pre>
<p>and the <em>IServiceProvider</em> extension method <em>BuildPolicyRegistryWithPolicySources()</em>:</p>
<pre><code>public static PolicyRegistry BuildPolicyRegistryWithPolicySources(this IServiceProvider serviceProvider)
{
var policySourcesByName = new Dictionary<string, IPolicySource>();
foreach (var policySource in serviceProvider.GetServices<IPolicySource>())
{
var policySourceName = policySource.GetName();
policySourcesByName[policySourceName] = policySource; // use last, ignore previous with same name.
}
var policyRegistry = new PolicyRegistry();
foreach (var policySourceByName in policySourcesByName)
{
policyRegistry.Add(policySourceByName.Key, policySourceByName.Value.PollyPolicy);
}
return policyRegistry;
}
</code></pre>
<p>As of now, it seems to work well. The registration of multiple identical <em>IPolicySource</em> instances follows the rule to always use the last, if multiple with the same name have been registered.</p>
<p>One caveat is, that there is no easy way to register the singleton <em>IPolicySource</em> instances multiple times, e.g. for implementation type or extended interfaces.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T07:57:36.570",
"Id": "525292",
"Score": "0",
"body": "How are you planning to use the registered policies? Do you want to use them to decorate typed HttpClients?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T12:24:45.463",
"Id": "525295",
"Score": "0",
"body": "@PeterCsala I have the HttpClient added to DI via `serviceCollection.AddHttpClient(...)` and add the policy with `httpClientBuilder.AddPolicyHandlerFromRegistry(MyPolicySource.GetInstanceName())`, so in this case a previously registered policy. I also set `httpClient.Timeout` from an additional property on `MyPolicyFactory` (not in the `IPolicySource` interface)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T12:36:22.073",
"Id": "525296",
"Score": "0",
"body": "And are you using the registered policies exclusive for HttpClients? Or are there any policy which applied for something other than a HttpClient?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T13:32:49.520",
"Id": "525302",
"Score": "0",
"body": "As of now, it's HttpClient only, but the interface and PolicyRegistry allow Polly policies for any purpose (future option). But it is planned only for key-value selection, by name."
}
] |
[
{
"body": "<p>We have gone through the same problem (more or less) whenever we started to use Polly. But after a couple of months we have realized that this flexibility is really <strong>error-prone</strong> and it is <strong>not needed</strong>.</p>\n<p>Let me give an example why is it error-prone. Let's suppose you have two policies: a Timeout and a Retry. You can use them <em>separately</em> and can use them in a <em>combined way</em>. The problem arises whenever you want to combine the two policies, since the inner's exception should be handled by the outer to trigger that.</p>\n<h3>Retry outer, Timeout inner:</h3>\n<pre><code>private static IAsyncPolicy<HttpResponseMessage> TimeoutPolicy(ResilienceSettings settings)\n => Policy\n .TimeoutAsync<HttpResponseMessage>( \n timeout: TimeSpan.FromMilliseconds(settings.HttpRequestTimeoutInMilliseconds));\n\nprivate static IAsyncPolicy<HttpResponseMessage> RetryPolicy(ResilienceSettings settings)\n => HttpPolicyExtensions\n .HandleTransientHttpError() //Catches HttpRequestException or checks the status code: 5xx or 408\n .Or<TimeoutRejectedException>() //Catches TimeoutRejectedException, which can be thrown by an inner TimeoutPolicy\n .WaitAndRetryAsync( \n retryCount: settings.HttpRequestRetryCount, \n sleepDurationProvider: _ =>\n TimeSpan.FromMilliseconds(settings.HttpRequestRetrySleepDurationInMilliseconds)); \n</code></pre>\n<p>With this each request (the initial attempt and the retried attempts) has a separate timeout.</p>\n<h3>Timeout outer, Retry inner:</h3>\n<pre><code>private static IAsyncPolicy<HttpResponseMessage> TimeoutPolicy(ResilienceSettings settings)\n => Policy\n .TimeoutAsync<HttpResponseMessage>( \n timeout: TimeSpan.FromMilliseconds(settings.HttpRequestTimeoutInMilliseconds));\n\nprivate static IAsyncPolicy<HttpResponseMessage> RetryPolicy(ResilienceSettings settings)\n => HttpPolicyExtensions\n .HandleTransientHttpError()\n .WaitAndRetryAsync( \n retryCount: settings.HttpRequestRetryCount, \n sleepDurationProvider: _ =>\n TimeSpan.FromMilliseconds(settings.HttpRequestRetrySleepDurationInMilliseconds)); \n</code></pre>\n<p>With this we have a global timeout. We have an overall threshold for requests (the initial attempt and the retried attempts).</p>\n<p>As you can see depending on <a href=\"https://github.com/peter-csala/resilience-service-design/blob/main/resilience.md#esc\" rel=\"nofollow noreferrer\">how you chain them</a> you might need to declare them differently. The things can get even more complicated if you want to add a third policy as well, like a Circuit breaker (Retry >> Circuit Breaker >> Timeout).</p>\n<hr />\n<p>We have ended up with a solution where we can register HttpClients with resilient strategies. Here is a simplified version of that:</p>\n<ul>\n<li>With this class you can parameterise all properties of the combined policy:</li>\n</ul>\n<pre><code>public class ResilienceSettings\n{\n public int HttpRequestTimeoutInMilliseconds { get; set; }\n \n public int HttpRequestRetrySleepDurationInMilliseconds { get; set; }\n\n public int HttpRequestRetryCount { get; set; }\n\n public int HttpRequestCircuitBreakerFailCountInCloseState { get; set; }\n\n public int HttpRequestCircuitBreakerDelayInMillisecondsBetweenOpenAndHalfOpenStates { get; set; }\n}\n</code></pre>\n<ul>\n<li>We did not expose the combined policy (so called strategy) to our consumers:</li>\n</ul>\n<pre><code>internal static IAsyncPolicy<HttpResponseMessage> CombinedPolicy(ResilienceSettings settings)\n => Policy.WrapAsync(RetryPolicy(settings), CircuitBreakerPolicy(settings), TimeoutPolicy(settings))\n</code></pre>\n<ul>\n<li>Rather we have created a higher level API to register any typed HttpClient which should be decorated with this strategy:</li>\n</ul>\n<pre><code>public static class ResilientHttpClientRegister\n{\n public static IServiceCollection AddResilientHttpClientProxy<TInterface, TImplementation>\n (this IServiceCollection services, ResilientHttpClientConfigurationSettings settings, Action<IServiceProvider, HttpClient> configureClient = null)\n where TInterface : class\n where TImplementation : class, TInterface\n {\n services.AddHttpClient<TInterface, TImplementation>(\n (serviceProvider, client) =>\n {\n client.BaseAddress = settings.BaseAddress;\n configureClient?.Invoke(serviceProvider, client);\n })\n .AddPolicyHandler(ResilientHttpPolicies.CombinedPolicy(settings.ResilienceSettings));\n\n return services;\n }\n}\n</code></pre>\n<ul>\n<li>We have created yet another settings class <code>ResilientHttpClientConfigurationSettings</code> to capture the baseAddress as well:</li>\n</ul>\n<pre><code>public class ResilientHttpClientConfigurationSettings\n{\n public Uri BaseAddress { get; set; }\n\n public ResilienceSettings ResilienceSettings { get; set; }\n}\n</code></pre>\n<hr />\n<p>As you can see this solution tries to hide entirely the fact that we are using Polly under the hood. Because we are exposing a higher level API that's why it is less error prone. It is less flexible for sure, but at the end you want to come up reliable resilience strategies.</p>\n<p>We are aware of one known issue: You can register the typed client interface as implementation:</p>\n<pre><code>services.AddResilientHttpClientProxy<IXYZResilientClient, IXYZResilientClient>(xyzSvcSettings);\n</code></pre>\n<p>It causes runtime exception rather than compile time, but I think we can live with this.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T16:57:13.123",
"Id": "525417",
"Score": "0",
"body": "Thank you for the detailed answer! I didn't even have combining of policies, upon adding a policy handler to `HttpClient`, in mind. Our current policies in the registry already combine policies, retry and timeout per-request (defined locally), and are selected from the registry with a single `httpClientBuilder.AddPolicyHandlerFromRegistry(key)`. Others may follow in the future. They were, in fact, called \"strategy\" in the previous, self-made implementation, before Polly was introduced on top level (so Polly usage is exposed, but much simpler than with a top-layer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T19:21:31.953",
"Id": "525425",
"Score": "0",
"body": "@ErikHart According to my understanding there is no guarantee that the consumer of your API calls the `BuildPolicyRegistryWithPolicySources` method. The consumer can also call the `AddPolicyHandlerFromRegistry` as many times as (s)he want and in any order. So, my opinion still stands, this flexibility can cause problems."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T16:20:02.193",
"Id": "525696",
"Score": "1",
"body": "In the task I want to achieve, I basically want to provide an exposed Polly usage with a few utilities, rather than a fool-proof layer on top (we had sth. like this before). So I can expect people to know at least a bit about nesting and ordering. We would have preferred even plain Polly over this IPolicySource, but had the above problems with policy creation and DI. And the IPolicySource offers a chance for more complex policies/strategies, which the user can just select by name. It's also possible to make the implementation configurable (represented in name), much like with your config."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T09:33:49.320",
"Id": "265983",
"ParentId": "265921",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "265983",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T18:52:54.423",
"Id": "265921",
"Score": "1",
"Tags": [
"c#",
"dependency-injection",
"singleton",
"polly"
],
"Title": "Polly AddPolicyRegistry() with factory and registered dependency injection service instances?"
}
|
265921
|
<p>I'm new to Rust. I wanted to create a script to read the contents on a directory, and then generate a js file exporting this assets. I wrote this code, it works but I'm not totally happy with it. I want to know the best way to do this.</p>
<p>you can check full code here: <a href="https://gist.github.com/JoseLuna12/0e576081761fa0594471fdb15ee3d038" rel="nofollow noreferrer">https://gist.github.com/JoseLuna12/0e576081761fa0594471fdb15ee3d038</a></p>
<pre><code> let r_files = ReadFiles::new(public_path);
let file_names = r_files.file_names();
let mut file_content = "".to_owned();
let mut variable_names = "".to_owned();
for f in file_names {
let v_name: Vec<&str> = f.split(".").collect();
let content = vec![
"import".to_owned(),
["'".to_owned(), v_name[0].to_owned(), "'".to_owned()].join(""),
"from".to_owned(),
["'".to_owned(), f.to_owned(), "'".to_owned()].join(""),
"\r\n".to_owned(),
];
file_content.push_str(&content.join(" "));
variable_names.push_str(v_name[0]);
variable_names.push_str(",\r\n")
}
let export_values = vec!["export {\r\n", &variable_names, "}"].join("");
let final_file = [file_content, export_values].join("");
fs::write("utils.js", &final_file);<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T00:56:12.297",
"Id": "525276",
"Score": "1",
"body": "Since your full code is not long, consider including the full code to provide more context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T15:14:57.987",
"Id": "525327",
"Score": "0",
"body": "Welcome to Code Review! Like @l-f said, please include more context for your question - also the link to the full code doesn't work, otherwise I'd have to that for you now."
}
] |
[
{
"body": "<p>To build strings in rust, use <code>format!()</code> or <code>write!()</code></p>\n<pre><code>let content = vec![\n "import".to_owned(),\n ["'".to_owned(), v_name[0].to_owned(), "'".to_owned()].join(""),\n "from".to_owned(),\n ["'".to_owned(), f.to_owned(), "'".to_owned()].join(""),\n "\\r\\n".to_owned(),\n ];\nfile_content.push_str(&content.join(" "));\n</code></pre>\n<p>Can be:</p>\n<pre><code> let content = format!("import '{}' from '{}'\\r\\n", v_name[0], f);\n file_content.push_str(&format!("import '{}' from '{}'\\r\\n", v_name[0], f));\n</code></pre>\n<p>Or even:</p>\n<pre><code> write!(file_content, "import '{}' from '{}'\\r\\n", v_name[0], f)?;\n</code></pre>\n<p>This is much simpler and more efficient then what you are doing because it builds less intermediate strings.</p>\n<pre><code>let r_files = ReadFiles::new(public_path);\n</code></pre>\n<p>I don't know what this ReadFiles is, but it seems like it could readily replaced with the builtin <code>std::fs::readdir</code>.</p>\n<pre><code> let v_name: Vec<&str> = f.split(".").collect();\n</code></pre>\n<p>If you use the standard <code>std::path::PathBuf</code>, instead of strings you can use the <code>file_stem</code> method instead of this.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T13:52:36.900",
"Id": "266076",
"ParentId": "265922",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "266076",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T18:59:25.667",
"Id": "265922",
"Score": "3",
"Tags": [
"rust"
],
"Title": "Rust script to generate JavaScript asset list file based on directory contents"
}
|
265922
|
<p>For the company I work for we spec lengths of tube of varying lengths.<br />
For a given project let's say there is a list like this</p>
<p>100', 115', 105', 205', 195', 240', 240', 130', 180', 140', 225', 85'</p>
<p>Edit 4: Entries in the list can not go over 285', and are always rounded to the nearest 5'.</p>
<p>The goal is to figure out how to cut the different lengths of tube from as few rolls as possible to reduce waste. We use rolls of 1000', 500', and 300'. We also figure 15' of extra tube per grouping. So a 1000' roll only takes 985' from the 1960' total for the project, 485' of a 500' and 285 of 300. So this project would need 2 1000' rolls.</p>
<p>I already have logic for determining how many of each roll type will be needed.</p>
<p>I start the recursive function like so</p>
<pre><code>public static bool RecursiveLoopGroup(Int32 remainingLength, List<System.Collections.DictionaryEntry> loops, int[] bundlesNeeded, ref List<System.Collections.Generic.Dictionary<String, Int32>> dt1000, ref List<System.Collections.Generic.Dictionary<String, Int32>> dt500, ref List<System.Collections.Generic.Dictionary<String, Int32>> dt300)
{
Debug.Print("\nStarting RecursiveLoopGroup Method");
System.Collections.Generic.Dictionary<String, Int32> returnDict = new System.Collections.Generic.Dictionary<String, Int32>();
List<System.Collections.DictionaryEntry> modifiedLoopList = new List<System.Collections.DictionaryEntry>(loops);
List<System.Collections.DictionaryEntry> skipEntries = new List<System.Collections.DictionaryEntry>();
System.Collections.DictionaryEntry lastEntry = new System.Collections.DictionaryEntry();
</code></pre>
<p>The returnDict is a dictionary of the loops that get grouped for return. So if</p>
<p>Group 1 : 100', 115', 105', 205', 195', 240'</p>
<p>Was found to be a good group, these would be returned in <code>returnDict</code>, with their keys being unique numbers specific to each length of tube. More on that later.</p>
<p>The <code>modifiedLoopList</code> is a copy of the loop List given. This is so as the function gets called recursively I can pass the reduced list to the new iteration.</p>
<p><code>skipEntries</code> is to keep track if which loops have been tried to be grouped with the current working group, but were not effective. More on that later.</p>
<p>and <code>lastEntry</code> is to keep track of the last loop that was added to the current working group. It is used to remove the last loop from the group is a solution can't be found with the current configuration.</p>
<p>The algorithm is this</p>
<blockquote>
<p>Determine which size group the current iteration is working on 1000', 500', or 300'<br />
Look at each loop starting from the front of the list, if adding it to the group will not go over the limit of the group, add it.<br />
Once you've formed a group, call the recursive function with the list of remaining loops, and repeat until each loop is in a group.</p>
</blockquote>
<p>So far this looks like this</p>
<pre><code>bool success = false;//exit condition for while loop
while (!success)
{
//since you cant edit the loop list while iterating, must save loops added to loop group to be removed after
List<System.Collections.DictionaryEntry> loopsToRemove = new List<System.Collections.DictionaryEntry>();
//loop through each loop in the modfiedLoopList, which is the list of all the loops to use
foreach (System.Collections.DictionaryEntry entry in modifiedLoopList)
{
//check if adding the loop will put the group over the limit or not
if (groupTotal + (Int32)entry.Value <= groupLimit && skipEntries.Count > 0)
{
bool entryIsInSkipList = false;//exit condition for the foreach loop
//check if the current entry is on the list of entries to skip
foreach (System.Collections.DictionaryEntry skip in skipEntries)
{
if (entry.Equals(skip))
{
entryIsInSkipList = true;
break;//breaks the foreach loop, since the entry was on the skip list
}
}
//if the entry was on the skip list, then move to the next entry
if (!entryIsInSkipList)
{
groupTotal += (Int32)entry.Value;
loopsToRemove.Add(entry);
totalRemaining -= (Int32)entry.Value;
returnDict.Add((String)entry.Key, (Int32)entry.Value);//the dictionary that will be returned by each iteration, which contains the loops as entries that get treated as a group
}
}//end if adding entry will go over limit
else if(groupTotal + (Int32)entry.Value <= groupLimit)//need this else incase there are no entries in the skip list yet
{
groupTotal += (Int32)entry.Value;
loopsToRemove.Add(entry);
totalRemaining -= (Int32)entry.Value;
returnDict.Add((String)entry.Key, (Int32)entry.Value);
}
}//end foreach entry in loopList
//remove used loops from list after iterating
foreach (System.Collections.DictionaryEntry entry in loopsToRemove)
{
modifiedLoopList.Remove(entry);
}
//if the list count is not zero, there are still loops to place
if (modifiedLoopList.Count != 0)
{
Debug.Print("\nThere are " + modifiedLoopList.Count.ToString() + "Loops left");
Debug.Print("\nReturn Dict = " + returnDict.ToArray().ToString());
#region reset number of needed bundles and exit
//If each bundle is 0, then you're in the last group being formed.
//if you're in the last group being formed and there are still some left
//then the current grouping fails, so add the loop group this iteration is on and return up
//to the iteration before
if (bundlesNeeded[0] == 0 && bundlesNeeded[1] == 0 && bundlesNeeded[2] == 0)
{
if (groupLimit == 1000)
bundlesNeeded[0]++;
else if (groupLimit == 500)
bundlesNeeded[1]++;
else if (groupLimit == 300)
bundlesNeeded[2]++;
return false;
}
#endregion number of needed bundles and exit
bool needToUndoLast;
if (groupTotal < (groupLimit - slackAmount)) needToUndoLast = false;
else needToUndoLast = RecursiveLoopGroup(totalRemaining, modifiedLoopList, bundlesNeeded, ref dt1000, ref dt500, ref dt300); //if the iteration called by this fails, then something might be wrong with this groups configuration.
//So remove the last entry, adding it to the skip list so the same grouping isn't tried again, and try another grouping
//configuration with the next loop in the list
if (!needToUndoLast)
{
//if the return dictionary is empty, then all the loops are on the skip list
//so a configuration could not be found SEE ELSE
if (returnDict.Count != 0)
{
System.Collections.Generic.KeyValuePair<String, Int32> lastDictEntry = returnDict.ElementAt(returnDict.Count - 1);
lastEntry = new System.Collections.DictionaryEntry((String)lastDictEntry.Key, (Int32)lastDictEntry.Value);
Debug.Print("\nNeed to undo last. Last Entry is" + lastEntry.Key.ToString() + "," + lastEntry.Value.ToString());
groupTotal -= (Int32)lastEntry.Value;
totalRemaining += (Int32)lastEntry.Value;
returnDict.Remove((String)lastEntry.Key);
skipEntries.Add(lastEntry);
//int returnIndex = loops.IndexOf(lastEntry);
modifiedLoopList.Add(lastEntry);
purgeSkipList(skipEntries);
}
else//so add back the needed loop length, and return to the iteration before so it can try a different configuration
{
if (groupLimit == 1000)
bundlesNeeded[0]++;
else if (groupLimit == 500)
bundlesNeeded[1]++;
else if (groupLimit == 300)
bundlesNeeded[2]++;
return false;
}
}//end need to undo if
else
{
success = true;//if an undo isn't needed, then the iteration that was called succeeded, which means all groupings work
}
}//end if list has remaining loops
else
{
success = true;//no remaining loops, all have been sorted properly
}
}//end while loop
</code></pre>
<p>the <code>PurgeSkipList</code> function is to keep the skip list in order based on the unique number for each loop, which increment more or less.</p>
<p>I think running through an example with the list from above will help. I'll use pictures to help. It's important to know we don't want to make perfect rolls of 1000', 500', and 300' but give 15' of slack on each. So the total taken from the remaining unassigned loops can be 985', 485', and 285'</p>
<p>So first we start with the unsorted list</p>
<p>The algorithm would start from the top and select all it can that will fit into a total of 985'</p>
<p>Then the function would be called recursively and the next group would start being created</p>
<p>At this point the last 85' loop can't be added as it would create create a 1000' group and we can only go to 985'. So this recursive call would return false, meaning it failed to completely sort all the loops.</p>
<p>This would then trigger the group above it to remove the last loop in the group, add it to a skip list so the same configuration is not tried again. Then go back through all the remaining loops again and find the next one to try and create a finished group. I'll now just show the step as it's just a cycle now</p>
<p><a href="https://i.stack.imgur.com/wTmAn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wTmAn.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/JtXLO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JtXLO.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/1dxaK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1dxaK.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/HD6vq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HD6vq.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/ZU1rg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZU1rg.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/tSAEn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tSAEn.png" alt="enter image description here" /></a></p>
<p>As you can see the last instance would work for both loops. The grouping works best when the loop being built is as close to 985' as possible. I've implemented a check right after checking if there are any more loops, to see if the loop being built is close enough, and if it's way off then the rest of the iterations would be a waste since it would all result in a fail. So I'm trying to stop unnecessary recursion when possible.</p>
<p>This method worked pretty quickly for this list, but when I move to a <a href="https://warmboard-my.sharepoint.com/:x:/p/nshupe/EdloP2T4cLxArpC_0cvoAkcBkmnszGMdN-CbnvUoqpjr-A?e=X7TVsi" rel="nofollow noreferrer">normally large group</a> (34 distinct lengths for a total of about 100 pieces and almost 7000 feet), or our <a href="https://warmboard-my.sharepoint.com/:x:/p/nshupe/EWMwNo90vKJPoaBHSf-D-7UBUIPNbD5Kt-qJZfWkai-KQA?e=T6lbcH" rel="nofollow noreferrer">extreme edge case</a> of almost 26000 feet, it never seems to find a solution.<br />
So any help trying to optimize, I realize that is a big ask, but would help a lot, Thank you.</p>
<p>What is an algorithm with low resource use for larger data sets?</p>
<p>Edit 1: It was suggested to me that I post this here when I first posted on Stack Overflow.</p>
<p>Edit 2: This is the code for how I determine what the optimal number of rolls will be needed for the loop grouping</p>
<pre><code>public static int[] findOptimalBundlesNeeded(Int32 totalLength)
{
int[] arrReturn = { 0, 0, 0 };//index 0 represents 1000's rolls, index 1 500's, and index 2 300's
while (totalLength > 0)
{
if (totalLength > 1000)
{
arrReturn[0]++;
totalLength -= 985;//for every 1000' roll, we are only taking 985 from the total tubing, 15 being left for safety
}
else if (totalLength > 500)
{
arrReturn[1]++;
totalLength -= 485;
}
else if (totalLength > 300)
{
arrReturn[2]++;
totalLength -= 285;
}
else
{
arrReturn[2]++;
totalLength = 0;
}
}
</code></pre>
<p>The logic being that if I have a total length of tube that needs to be sorted, say 1960', I take 985' from the total and that will equal 1 1000' roll since we add 15 of slack to each roll. The same logic applies for 500' and 300'.</p>
<p>And if the math comes out where you get two of either 500' or 300', you round up because two 500' could be a 1000' and 2 300' could be a 500'.</p>
<p>Edit 3:
And here is the <code>purgeSkipList</code> function that is used in the main recursive function.</p>
<pre><code> public static void purgeSkipList(List<System.Collections.DictionaryEntry> skipList)
{
System.Collections.DictionaryEntry last = skipList.ElementAt(skipList.Count-1);
List<System.Collections.DictionaryEntry> tempRemoveList = new List<System.Collections.DictionaryEntry>();
foreach (System.Collections.DictionaryEntry entry in skipList)
{
if (!last.Equals(entry))
{
if(Convert.ToDecimal((String)entry.Key) > Convert.ToDecimal((String)last.Key))
{
tempRemoveList.Add(entry);
}
}
}
foreach (System.Collections.DictionaryEntry remove in tempRemoveList)
{
skipList.Remove(remove);
}
}
</code></pre>
<p>The logic here is that there are cases when trying different combinations of loops, that two loops can be added while trying to add up to the limit. So there would be a group of x number of loops, and these two loops are one of the iterations attempting to find a solution. Lets call the two loops y1 and y2.</p>
<p>If it turns out that the group x + y1 + y2 results in a failed configuration, we remove y2 and try x + y1 with all the other available loops in trying to find a working solution.</p>
<p>But if none of those groupings work, we now remove y1 so we are back to just the group x. But we might want to try y2 with another loop as a new pair say x + z1 + y2.</p>
<p>This logic makes it so loops that are further down the list can be tried again. This is tied to their unique identified.</p>
<p>Each loop corresponds to a manifold, and then is numbered 1 - 8. So a list would look like 1.1, 1.2, 1.3...</p>
<p>This numbering system can also be seen in the pictures from the original post.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T05:48:48.483",
"Id": "525286",
"Score": "0",
"body": "Welcome to CodeReview@SE. I've touched up your post, please refer to [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask) and find ideas why."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T05:55:54.117",
"Id": "525287",
"Score": "0",
"body": "(You write of *rolls* and *loops*, I remember sheet metal to come in *coils*. *Loop* rubs me the wrong way, and it collides with the name of one type of program control structure.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T06:01:37.937",
"Id": "525288",
"Score": "0",
"body": "Please reconsider presenting the *logic for determining how many of each roll type will be needed*, or even including it for review and suggestions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T07:54:32.600",
"Id": "525291",
"Score": "1",
"body": "Does your production code have comments like this or have they been added for the question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T10:18:02.710",
"Id": "525294",
"Score": "0",
"body": "Can you include the code for `PurgeSkipList`, please"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T14:06:21.597",
"Id": "525310",
"Score": "0",
"body": "@greybeard thank you for the edits and comments. I call them loops and rolls because the material in question is PEX tubing. And we loop create closed loops for hydronic radiant floor heating. I tried to eliminate details like this since the post was already so long, but I see how that could be confusing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T14:26:00.480",
"Id": "525316",
"Score": "0",
"body": "@greybeard I've edited the post to include the logic you've requested."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T14:27:11.760",
"Id": "525317",
"Score": "1",
"body": "@RobH Those comments are in the production code. I've also included the code for 'PurgeSkipList'"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T12:20:27.747",
"Id": "525448",
"Score": "0",
"body": "Never use fully qualified namespaces unless absolutely necessary. Always use `var` unless you can't. Your code will be much more readable."
}
] |
[
{
"body": "<p>I know I asked about the comments in a comment on the question, so I'll just point out that this type of commenting makes code so hard to read.</p>\n<pre><code>bool success = false;//exit condition for while loop\nwhile (!success)\n</code></pre>\n<p>You don't need a comment for what success is used for, it's on the very next line. Same for comments like <code>// end if ...</code>. If the code is hard enough to follow that these are helpful, you need to split the code into separate methods.</p>\n<p>On to some code:</p>\n<pre><code>public static int[] findOptimalBundlesNeeded(Int32 totalLength)\n{\n int[] arrReturn = { 0, 0, 0 };//index 0 represents 1000's rolls, index 1 500's, and index 2 300's\n\n while (totalLength > 0)\n {\n if (totalLength > 1000)\n {\n arrReturn[0]++;\n totalLength -= 985;//for every 1000' roll, we are only taking 985 from the total tubing, 15 being left for safety\n }\n else if (totalLength > 500)\n {\n arrReturn[1]++;\n totalLength -= 485;\n }\n else if (totalLength > 300)\n {\n arrReturn[2]++;\n totalLength -= 285;\n }\n else\n {\n arrReturn[2]++;\n totalLength = 0;\n }\n\n }\n}\n</code></pre>\n<p>You don't need a while loop for this, you just need division. Something like this (my C# is rusty so it might not be 100% correct).</p>\n<pre><code>public static int[] FindOptimalBundlesNeeded(int totalLength)\n{\n // I may have misunderstood what the padding is for. I assumed it meant each 1000 roll only has 985 useable.\n const int padding = 15;\n int remainder;\n int numberOf1000 = Math.DivRem(totalLength, 1000 - padding, out remainder);\n int numberOf500 = Math.DivRem(remainder, 500 - padding, out remainder);\n int numberOf300 = Math.Ceiling(remainder/(300.0 - padding));\n return new int[] { numberOf1000, numberOf500, numberOf300 };\n} \n</code></pre>\n<p><strong>There's a serious problem with this though</strong>. Assume a cutting list of <code>{ 286, 286, 286, 286 }</code> giving a total length of 1144. Your optimal solution gives 1x1000 roll and 1x300 roll. That's not valid, you can't cut 286 from a 300 roll. I don't know how this is used but it can easily suggest something that can't really be achieved. If this forms an important part of your algorithm, which I suspect it does, the whole thing is flawed. As soon as you have a cut over 285, you risk never finding a solution. Based on this, I won't look at the rest of the code.</p>\n<p><strong>Edit</strong>: And what about 8x250? Total length 2000 gives an 'optimal solution' of 2x1000 rolls and 1x300 roll. However, you can only cut 3x250 from 1000 (because of the 15 padding/buffer) so the optimal solution is not achievable (you can only cut 7 from 2x1000 and 1x300). Your <em>optimal</em> solution is basically trying to find a zero waste solution which is probably not possible.</p>\n<p>You really want to add some usings, namespace qualifying everything makes the code unnecessarily verbose.</p>\n<p>If you are happy with an approximate solution, you could sort the cutting list in descending size order and just do a first (or best) fit bin pack which may be good enough for your purposes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T20:55:39.220",
"Id": "525430",
"Score": "0",
"body": "Thank you for your response. Our standard is actually to not have entries go over 285 for this reason as well as others. Thanks you for pointing this case out though. Sorry I had not mentioned this, that is a mistake on my part and I'll edit the post.\n\nI also hadn't ever thought about comments in the way you described above. I'll be sure to take that into account. \n\nI like your solution very much to FindOptimalBundlesNeeded(), very clean and much easier to understand."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T21:05:41.473",
"Id": "525432",
"Score": "0",
"body": "@Nick Both of your spreadsheets linked in your question have lengths over 285 (e.g. 295). Are you sure about the standard always being held?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T01:22:01.070",
"Id": "525437",
"Score": "0",
"body": "Those are older files, from a time where the rule was more negotiable. It's more strictly informed now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T05:42:48.687",
"Id": "525440",
"Score": "0",
"body": "@Nick - fair enough. I've added another example of why it won't work :("
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T14:13:59.923",
"Id": "525461",
"Score": "0",
"body": "Thank you for your continued help @RobH. I should have put it in a comment replying to you but I put it in the post edit at the top. Entries can't go over 285'. They pretty much have a range between 50' - 285'. It's very rare even to get under 85', but it happens.\nSo the situation above would never occur as we wouldn't have two entries that large. We would have a list like \n\n235', 235', 235', 250, 250' = 1205' (little over but the idea holds)\n\nThen the groupings would be \n\nGroup A: 235, 235, 235, 250 = 955'\nGroup B: 250'"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T14:43:50.260",
"Id": "525462",
"Score": "1",
"body": "@Nick - And what about 8x250? Total length 2000 gives an 'optimal solution' of 2x1000 rolls and 1x300 roll. However, you can only cut 3x250 from 1000 (because of the 15 padding/buffer) so the optimal solution is not achievable (you can only cut 7 from 2x1000 and 1x300). Does that make sense?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T22:32:05.953",
"Id": "525479",
"Score": "0",
"body": "That does make sense. It is very unlikely in my experience to occur but it could happen. The way to fix it would be to add another 300' bundle once it was determined that no solution could be found. which I hadn't written in yet, as I hadn't thought of this scenario exactly @RobH"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T07:13:02.357",
"Id": "525636",
"Score": "1",
"body": "@Nick `Our standard is actually to not have entries go over 285` Please complement your question with this precondition."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T07:17:55.000",
"Id": "525637",
"Score": "0",
"body": "@Nick - I'd suggest you try your code with 8x250 and see whether it exits or loops forever. That would let you know if there's a bug in your code or whether the search space is just too big to enumerate all the options."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T20:01:53.087",
"Id": "266006",
"ParentId": "265926",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T22:37:19.133",
"Id": "265926",
"Score": "4",
"Tags": [
"c#",
"sorting",
"recursion"
],
"Title": "recursive bin packing"
}
|
265926
|
<p>This is a simple implementation of the calendar(1) utility included in some UNIX systems (all BSDs have it, GNU has not). I do not have much experience with <code><sys/time.h></code> and <code><time.h></code></p>
<p>Manual:</p>
<pre class="lang-none prettyprint-override"><code>CALENDAR(1) General Commands Manual CALENDAR(1)
NAME
calendar - print upcoming events
SYNOPSIS
calendar [-l] [-A num] [-B num] [-t [[yyyy]mm]dd] [file...]
DESCRIPTION
calendar reads files for events, one event per line; and writes to
standard output those events beginning with either today's date or
tomorrow's. On Fridays and Saturdays, events through Monday are
printed. If a hyphen (-) is provided as argument or the argument is
absent, calendar reads from the standard input.
The options are as follows:
-A num Print lines from today and next num days (forward, future).
-B num Print lines from today and previous num days (backward, past).
-l Rather than print the date on the same line of each event, print
the date alone in a line and followed by each event indented
with a tab.
-t[[yyyy]mm]dd
Act like the specified value is “today” instead of using the
current date.
Each event should begin with a date pattern in the format
[[YYYY-[MM]]-DDWW[+N|-N]. The hyphen (-) that separates the values can
be replaced by a slash (/) or a period (.). Several date patterns can
be supplied separated by a comma (,).
YYYY should be any year number. MM should be a month number or a month
name (either complete or abbreviate, such as "April" or "Apr"). DD
should be the number of a day in the month. WW should be the name of a
day in the week (either complete or abbreviate). Either DD or WW (or
both) must be supplied.
The date pattern can be followed by +N or -N to specify the week on the
month (for example Sun+2 is the second Sunday in the month, Mon-3 is
the third from last Monday in the month).
EXAMPLES
Consider the following input.
# holidays
01/01 New Year's day
05/01 Labor Day
07/25 Generic holiday
12/25 Christmas
May/Sun+2 Mother's day
13Fri Friday the 13th
# classes
Mon,Wed Java Class
Tue,Thu Algebra Class
Tue,Thu Operating Systems Class
Tue,Thu Computer Network Class
If today were 09 March 2021, then running calendar with the options -l
and -A7 on this input would print the following:
Sunday 09 May 2021
Mother's day
Monday 10 May 2021
Java Class
Tuesday 11 May 2021
Algebra Class
Computer Network Class
Operating Systems Class
Wednesday 12 May 2021
Java Class
Thursday 13 May 2021
Algebra Class
Computer Network Class
Operating Systems Class
Friday 14 May 2021
Saturday 15 May 2021
SEE ALSO
at(1), cal(1), cron(1), todo(1)
STANDARDS
The calendar program previously selected lines which had the correct
date anywhere in the line. This is no longer true: the date is only
recognized when it occurs at the beginning of a line.
The calendar program previously could interpret only one date for each
event. This is no longer true: each event can occur in more than one
date (see the examples for the classes above).
The calendar program previously could not read events from the standard
input. This is no longer true: this version of calendar is an actual
filter, which can read from the standard input or from named files.
The calendar program previously had an option to send a mail to all
users. This is no longer true: to have your calendar mailed every day,
use cron(8).
HISTORY
A calendar command appeared in Version 7 AT&T UNIX.
CALENDAR(1)
</code></pre>
<p>calendar.c:</p>
<pre class="lang-c prettyprint-override"><code>#include <sys/time.h>
#include <ctype.h>
#include <err.h>
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include "calendar.h"
#define SECS_PER_DAY (24 * 60 * 60)
#define DAYS_PER_WEEK 7
#define MIDDAY 12
#define EPOCH 1970
#define isleap(y) ((!((y) % 4) && ((y) % 100)) || !((y) % 400))
static const int days_in_month[2][13] = {
{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
};
/* show usage and exit */
static void
usage(void)
{
(void)fprintf(stderr, "usage: calendar [-d] [-A num] [-B num] -t [yyyymmdd] [file ...]\n");
exit(1);
}
/* call calloc checking for error */
static void *
ecalloc(size_t nmemb, size_t size)
{
void *p;
if ((p = calloc(nmemb, size)) == NULL)
err(1, "malloc");
return p;
}
/* call strdup checking for error */
static char *
estrdup(const char *s)
{
char *t;
if ((t = strdup(s)) == NULL)
err(1, "strdup");
return t;
}
/* convert string value to int */
static int
strtonum(const char *s)
{
long n;
char *ep;
errno = 0;
n = strtol(s, &ep, 10);
if (s[0] == '\0' || *ep != '\0')
goto error;
if ((errno == ERANGE && (n == LONG_MAX || n == LONG_MIN)) || (n > INT_MAX || n < 0))
goto error;
return (int)n;
error:
errno = EINVAL;
err(1, "%s", s);
return -1;
}
/* convert YYYYMMDD to time */
static time_t
strtotime(const char *s)
{
struct tm *tmorig;
struct tm tm;
size_t len;
time_t t;
char *ep;
t = time(NULL);
tmorig = localtime(&t);
tm = *tmorig;
len = strlen(s);
if (len == 2 || len == 1)
ep = strptime(s, "%d", &tm);
else if (len == 4)
ep = strptime(s, "%m%d", &tm);
else
ep = strptime(s, "%Y%m%d", &tm);
if (s[0] == '\0' || ep == NULL || ep[0] != '\0')
goto error;
tm.tm_hour = MIDDAY;
tm.tm_min = 0;
tm.tm_sec = 0;
t = mktime(&tm);
if (t == -1)
goto error;
return t;
error:
errno = EINVAL;
err(1, "%s", s);
return (time_t)-1;
}
/* set today time for 12:00; also set number of days after today */
static void
settoday(time_t *today, int *after)
{
struct tm *tmorig;
struct tm tm;
time_t t;
t = time(NULL);
tmorig = localtime(&t);
tm = *tmorig;
tm.tm_hour = MIDDAY;
tm.tm_min = 0;
tm.tm_sec = 0;
*today = mktime(&tm);
switch (tm.tm_wday) {
case 5:
*after = 3;
break;
case 6:
*after = 2;
break;
default:
*after = 1;
break;
}
}
/* check if c is separator */
static int
isseparator(int c)
{
return c == '-' || c == '.' || c == '/';
}
/* get patterns for event s; also return its name */
static struct Day *
getpatterns(char *s, char **name)
{
struct tm tm;
struct Day *patt, *oldpatt;
struct Day d;
size_t len;
int n;
char *t, *end;
patt = NULL;
for (;;) {
memset(&d, 0, sizeof(d));
while (isspace(*s)) {
s++;
}
n = strtol(s, &end, 10);
if (n > 0 && isseparator(*end)) {
/* got numeric year or month */
d.month = n;
s = end + 1;
n = strtol(s, &end, 10);
if (n > 0 && isseparator(*end)) {
/* got numeric month after year */
d.year = d.month;
d.month = n;
s = end + 1;
} else if ((t = strptime(s, "%b", &tm)) != NULL && isseparator(*t)){
/* got month name after year */
d.year = d.month;
d.month = tm.tm_mon + 1;
s = t + 1;
}
} else if ((t = strptime(s, "%b", &tm)) != NULL && isseparator(*t)) {
/* got month name */
d.month = tm.tm_mon + 1;
s = t + 1;
}
n = strtol(s, &end, 10);
if (n > 0 && *end != '\0') {
/* got month day */
d.monthday = n;
s = end;
}
if ((t = strptime(s, "%a", &tm)) != NULL) {
/* got week day */
d.weekday = tm.tm_wday + 1;
s = t;
}
if (d.monthday == 0 && d.weekday == 0)
break;
n = strtol(s, &end, 10);
if (n >= -5 && n <= 5 && *end != '\0') {
d.monthweek = n;
s = end;
}
oldpatt = patt;
patt = ecalloc(1, sizeof(*patt));
*patt = d;
patt->next = oldpatt;
while (isspace(*s)) {
s++;
}
if (*s == ',') {
s++;
while (isspace(*s)) {
s++;
}
} else {
break;
}
}
*name = s;
len = strlen(*name);
if ((*name)[len - 1] == '\n')
(*name)[len - 1] = '\0';
return patt;
}
/* get events for file fp */
static struct Event *
getevents(FILE *fp, struct Event *evs)
{
struct Event *p;
struct Day *patt;
char buf[BUFSIZ];
char *name;
while (fgets(buf, BUFSIZ, fp) != NULL) {
if ((patt = getpatterns(buf, &name)) != NULL) {
p = ecalloc(1, sizeof(*p));
p->next = evs;
p->days = patt;
p->name = estrdup(name);
evs = p;
}
}
return evs;
}
/* get week of year */
static int
getwofy(int yday, int wday)
{
return (yday + DAYS_PER_WEEK - (wday ? (wday - 1) : (DAYS_PER_WEEK - 1))) / DAYS_PER_WEEK;
}
/* check if event occurs today */
static int
occurstoday(struct Event *ev, struct tm *tm, int thiswofm, int lastwofm)
{
struct Day *d;
for (d = ev->days; d != NULL; d = d->next) {
if ((d->year == 0 || d->year == tm->tm_year + EPOCH) &&
(d->month == 0 || d->month == tm->tm_mon + 1) &&
(d->monthday == 0 || d->monthday == tm->tm_mday) &&
(d->weekday == 0 || d->weekday == tm->tm_wday + 1) &&
(d->monthweek == 0 ||
(d->monthweek < 0 && d->monthweek == -1 * (lastwofm - thiswofm - 1)) ||
(d->monthweek == thiswofm))) {
return 1;
}
}
return 0;
}
/* print events for today and after days */
static void
printevents(struct Event *evs, time_t today, int after, int lflag)
{
struct tm *tmorig;
struct tm tm;
struct Event *ev;
int wofy; /* week of year of first day of month */
int thiswofm; /* this week of current month */
int lastwofm; /* last week of current month */
int n, a, b;
char buf1[BUFSIZ];
char buf2[BUFSIZ];
buf1[0] = buf2[0] = '\0';
while (after-- > 0) {
tmorig = localtime(&today);
tm = *tmorig;
n = days_in_month[isleap(tm.tm_year + EPOCH)][tm.tm_mon + 1];
a = (tm.tm_wday - tm.tm_mday + 1) % DAYS_PER_WEEK;
if (a < 0)
a += DAYS_PER_WEEK;
b = (tm.tm_wday + n - tm.tm_mday + 1) % DAYS_PER_WEEK;
if (b < 0)
b += DAYS_PER_WEEK;
wofy = getwofy(tm.tm_yday - tm.tm_mday + 1, a);
thiswofm = getwofy(tm.tm_yday, tm.tm_wday) - wofy + 1;
lastwofm = getwofy(tm.tm_yday + n - tm.tm_mday + 1, b) - wofy + 1;
if (lflag) {
strftime(buf1, sizeof(buf1), "%A", &tm);
strftime(buf2, sizeof(buf2), "%d %B %Y", &tm);
printf("%-10s %s\n", buf1, buf2);
} else {
strftime(buf1, sizeof(buf1), "%b %d", &tm);
}
for (ev = evs; ev != NULL; ev = ev->next) {
if (occurstoday(ev, &tm, thiswofm, lastwofm)) {
if (lflag) {
printf("\t");
} else {
printf("%-8s ", buf1);
}
printf("%s\n", ev->name);
}
}
today += SECS_PER_DAY;
}
}
/* calendar: print upcoming events */
int
main(int argc, char *argv[])
{
static struct Event *evs;
FILE *fp;
time_t today; /* seconds of 12:00:00 of today since epoch*/
int before; /* number of days before today */
int after; /* number of days after today */
int lflag; /* whether to print in long format */
int exitval;
int ch;
before = lflag = 0;
settoday(&today, &after);
while ((ch = getopt(argc, argv, "A:B:lt:")) != -1) {
switch (ch) {
case 'A':
after = strtonum(optarg);
break;
case 'B':
before = strtonum(optarg);
break;
case 'l':
lflag = 1;
break;
case 't':
today = strtotime(optarg);
break;
default:
usage();
break;
}
}
argc -= optind;
argv += optind;
today -= before * SECS_PER_DAY;
evs = NULL;
exitval = 0;
if (argc == 0) {
evs = getevents(stdin, evs);
} else {
for (; *argv != NULL; argv++) {
if (strcmp(*argv, "-") == 0) {
evs = getevents(stdin, evs);
continue;
}
if ((fp = fopen(*argv, "r")) == NULL) {
warn("%s", *argv);
exitval = 1;
continue;
}
evs = getevents(fp, evs);
fclose(fp);
}
}
printevents(evs, today, after, lflag);
return exitval;
}
</code></pre>
<p>calendar.h:</p>
<pre class="lang-c prettyprint-override"><code>/* day or day pattern */
struct Day {
/*
* This structure express both a day and a day pattern. For
* convenience, let's express a Day entry as YYYY-MM-DD-m-w,
* where:
* - year is YYYY (1 to INT_MAX)
* - month is MM (1 to 12)
* - monthday is DD (1 to 31)
* - monthweek is m (-5 to 5)
* - weekday is w (1-Monday to 7-Sunday)
*
* A day is expressed with all values nonzero. For example,
* 2020-03-11-2-3 represents 11 March 2020, which was a
* Wednesday (3) on the second week of March.
*
* A day pattern can have any value as zero. A zero value
* matches anything. For example:
* - 0000-12-25-0-0 matches 25 December of every year.
* - 0000-05-00-2-7 matches the second Sunday of May.
* - 2020-03-11-2-3 matches 11 March 2020.
*/
struct Day *next;
int year;
int month;
int monthday;
int monthweek;
int weekday;
};
/* event */
struct Event {
struct Event *next;
struct Day *days; /* list of day patterns */
char *name; /* event name */
};
</code></pre>
|
[] |
[
{
"body": "<p><strong>Missing error checks</strong></p>\n<pre><code>t = time(NULL);\nif (t == -1) handle_error_gracefully();\ntmorig = localtime(&t);\nif (tmorig == NULL) handle_error_gracefully();\n</code></pre>\n<p><strong>Simplify</strong></p>\n<p>Value check not needed.</p>\n<pre><code>// if ((errno == ERANGE && (n == LONG_MAX || n == LONG_MIN)) || (n > INT_MAX || n < 0))\nif ((errno == ERANGE) || (n > INT_MAX || n < 0))\n goto error;\n</code></pre>\n<p><strong>Better description</strong></p>\n<p>As <code>strtonum()</code> fails on negative numbers, consider a different comment or function name.</p>\n<p><strong>Overflow detection</strong></p>\n<p>As <code>strtonum()</code> results are used in subsequent calculations that lack overflow protection, perhaps form <code>strtonum(const char *s, int min, int max)</code> and pass in limiting range values.</p>\n<p><strong>Week of the year</strong></p>\n<p>OP’s <code>getwofy(int yday, int wday)</code> does not appear to follow the week-of-the-year per <a href=\"https://en.wikipedia.org/wiki/ISO_8601\" rel=\"nofollow noreferrer\">ISO8601</a> as that depends on the day of the week of Jan 1.</p>\n<p><strong>calendar.h does not discuss <code>next</code> member</strong></p>\n<p><strong>calendar.h does not discuss a negative <code>monthweek</code></strong></p>\n<p>Unclear how negative values relate, given a value of zero is special.</p>\n<p><strong><code>day</code> vs. <code>struct Day</code></strong></p>\n<pre><code>// A day pattern can have any value as zero. \nA struct Day pattern can have any value as zero. \n</code></pre>\n<p><strong>calendar.h naming</strong></p>\n<p>Consider code re-use. <code>calendar.h</code> introduces <code>struct Day</code> and <code>struct Event</code>. These common names can easily conflict with other code and are surprising to find in a file called <code> calendar.h</code>.</p>\n<p><strong>calendar.h missing public functions</strong></p>\n<p>I’d expect the calendar functions in calendar.c meant for general use to be non-<code>static</code> and declared in calendar.h.</p>\n<p>Else as a stand-alone program, might as well put all of <code>calendar.h</code> in <code>calendar.c</code> as nothing is for general use.</p>\n<p><strong>Pedantic: Avoid UB of negative <code>char</code> in <code>is...()</code></strong></p>\n<pre><code> // while (isspace(*s)) {\n while (isspace(* (unsigned char *)s)) {\n s++;\n }\n</code></pre>\n<p><strong>Various <code>strtol()</code> lack error checks</strong></p>\n<p><strong><a href=\"https://en.wikipedia.org/wiki/Resource_acquisition_is_initialization\" rel=\"nofollow noreferrer\">RAII</a></strong></p>\n<pre><code>// struct Day d;\n…\n\nfor (;;) {\n // memset(&d, 0, sizeof(d));\n struct Day d = { 0 };\n</code></pre>\n<p><strong>Avoid hacker exploit</strong></p>\n<p>Consider what happens when <code>len == 0</code>.</p>\n<pre><code>len = strlen(*name);\nif ((*name)[len - 1] == '\\n')\n (*name)[len - 1] = '\\0';\n</code></pre>\n<p>Instead:</p>\n<pre><code>(*name)[strcspn(*name, "\\n")] = 0;\n</code></pre>\n<p><strong>Minor: Alternative to <code>a < 0</code></strong></p>\n<pre><code> // a = (tm.tm_wday - tm.tm_mday + 1) % DAYS_PER_WEEK;\n // if (a < 0)\n // a += DAYS_PER_WEEK;\n a = (tm.tm_wday - tm.tm_mday + 1 + 35 /* some large multiple of 7) % DAYS_PER_WEEK;\n</code></pre>\n<p><strong>Easter</strong></p>\n<p>Reference should you want to include <a href=\"https://codereview.stackexchange.com/q/217528/29485\">Easter</a>.</p>\n<p><strong>Minor: Overflow with 16-bit <code>int</code></strong></p>\n<p>Common in embedded processors, <code>24 * 60 * 60</code> overflows 16-bit <code>int</code>. Posix, I believe, requires at least 32-bit <code>int</code>.</p>\n<pre><code>// #define SECS_PER_DAY (24 * 60 * 60)\n#define SECS_PER_DAY ((time_t) 24 * 60 * 60)\n// or \n#define SECS_PER_DAY 86400\n</code></pre>\n<p><strong>Minor: Failure to account DST</strong></p>\n<p><code>localtime()</code> will populate <code>.tm_isdst</code>, yet noon of that day may have a different <code>.tm_isdst</code> value. Usually best to let <code>mktime()</code> determine best setting.</p>\n<pre><code>tmorig = localtime(&t);\ntm = *tmorig;\ntm.tm_hour = MIDDAY;\ntm.tm_min = 0;\ntm.tm_sec = 0;\ntm.tm_isdst = -1; // Add\n*today = mktime(&tm);\n</code></pre>\n<p>Also in <code>strtotime()</code>.</p>\n<p>Unclear if this affects overall code, yet something to consider.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T02:53:12.037",
"Id": "525375",
"Score": "1",
"body": "Funnily enough I had the exact 16-bit int overflow occur when I was doing an arduino project for a clock."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T03:36:08.400",
"Id": "525376",
"Score": "0",
"body": "@qwr I too had many stubbed toes. See also [Why (not) write 1,000,000,000 as 1000*1000*1000](https://stackoverflow.com/a/40637622/2410359)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T14:59:01.967",
"Id": "525531",
"Score": "0",
"body": "is there any difference between `isspace(*(unsigned char *)s)` and `isspace((unsigned char)*s)`? Here's the preliminary of `calendar.c`: https://0x0.st/-yzU.c I merged the header into the .c file. I'm gonna implement easter later."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T15:04:15.467",
"Id": "525532",
"Score": "0",
"body": "`getwofy` should not follow ISO8601. Instead, it follows [strftime(3)'s `%w` format](https://man.openbsd.org/strftime.3#_w). This is necessary to calculate the number of the week in a month (for a `monthweek` equals to 2 or -4 in a `struct Day` to match the second or fourth-to-last week of the month)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T17:09:09.853",
"Id": "525535",
"Score": "0",
"body": "@phillbush `isspace(*(unsigned char *)s)` and `isspace((unsigned char)*s)` differs when `char` is like `signed char` and encoded using non-2's complement. `isspace(*(unsigned char *)s)` is the more formally correct approach."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T22:50:32.833",
"Id": "265975",
"ParentId": "265928",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "265975",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T01:12:43.493",
"Id": "265928",
"Score": "3",
"Tags": [
"c",
"datetime",
"reinventing-the-wheel",
"posix",
"to-do-list"
],
"Title": "UNIX calendar(1) in C"
}
|
265928
|
<p>It's my first time using stack exchange and getting my code reviewed, so if you find any issues with this post, please tell me. Anyway, I have done a very simple program in JS to find the average length of a decimal number created by a Math.random() function. The program works well, but since I'm new to coding, any improvements on my code would be greatly appreciated.</p>
<pre><code>//make a program to see the average of lenght of random decimal numbers, find the lenght of each
var randomNums = [];
var length = [];
var total = 0
//random
for (var i = 0; i < 100; i++) {
randomNums.push(Math.random());
}
//length
for (var i = 0; i < randomNums.length; i++) {
length.push(randomNums[i].toString().length);
}
//average
function average() {
for (var i = 0; i < length.length; i++) {
total += length[i];
}
var avg = total / randomNums.length;
avg = Math.round(avg);
return avg;
}
console.log(average());
//output: 18
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li>(Styling) First thing that you should consider is to apply formatting:\n<ol>\n<li>Your tabs are not consistent.</li>\n<li>In most code styles, you should have a single space between // and text.</li>\n</ol>\n</li>\n<li>You should declare variables only when they are started to be used. Do not declare variables at the start of code - that's confusing. (Well, when you are using <code>var</code> this makes some sense, but see also recommendation about not using <code>var</code>). See <a href=\"https://agiletribe.wordpress.com/2012/04/14/27-dont-declare-variables-at-the-top/\" rel=\"noreferrer\">https://agiletribe.wordpress.com/2012/04/14/27-dont-declare-variables-at-the-top/</a> for some explanation.</li>\n<li>You should avoid imperative for-s and use map/reduce. This makes your code cleaner & composable at cost of a non-significant performance drop. See <a href=\"https://medium.com/@ExplosionPills/map-vs-for-loop-2b4ce659fb03\" rel=\"noreferrer\">https://medium.com/@ExplosionPills/map-vs-for-loop-2b4ce659fb03</a> for some explanation.</li>\n<li>It's better to make function <code>average</code> as an independent helper. In order to do that, you need to stop reading global variables & start accepting parameters. By this, you ensure that your helper can be reused in other places.</li>\n<li>Function <code>average</code> has too many lines for no reason. Remove empty lines. Merge dividing + rounding into a single line.</li>\n<li>It's better not to introduce global variables <code>randomNums</code> and <code>length</code>. It's better to create functions that generate such things. Then chain calls together. See <a href=\"https://wiki.c2.com/?GlobalVariablesAreBad\" rel=\"noreferrer\">https://wiki.c2.com/?GlobalVariablesAreBad</a> for some explanation.</li>\n<li><code>var</code> is bad. Use <code>let</code> and <code>const</code>. See <a href=\"https://www.freecodecamp.org/news/var-let-and-const-whats-the-difference/\" rel=\"noreferrer\">https://www.freecodecamp.org/news/var-let-and-const-whats-the-difference/</a> for some explanation.</li>\n<li>Delete comments. Comments are worth only when they explain why you are doing things you are doing. In case if you need to explain what you are doing, it's better to create a variable or a function with good name. See <a href=\"https://stackoverflow.blog/2021/07/05/best-practices-for-writing-code-comments/\">https://stackoverflow.blog/2021/07/05/best-practices-for-writing-code-comments/</a> for some explanation.</li>\n<li>Leverage using of external libraries, like <code>lodash</code>.\n<ul>\n<li>In order to do that you need:\n<ul>\n<li>either run your application via npm+node (in case if you have troubles with that, google "building console application via node")</li>\n<li>use bundler like the webpack in the case if you develop a website. See <a href=\"https://webpack.js.org/\" rel=\"noreferrer\">https://webpack.js.org/</a></li>\n<li>use online-IDE with the ability to install custom libaries. Like stackblitz. For example, you can see your reworked code sample: <a href=\"https://stackblitz.com/edit/js-jp1rdv?devtoolsheight=33&file=index.js\" rel=\"noreferrer\">https://stackblitz.com/edit/js-jp1rdv?devtoolsheight=33&file=index.js</a></li>\n</ul>\n</li>\n<li>And apply the next changes to your code:\n<ol>\n<li>Replace your own <code>average</code> with <code>mean</code> from <code>lodash</code>. See <a href=\"https://lodash.com/docs/4.17.15#mean\" rel=\"noreferrer\">https://lodash.com/docs/4.17.15#mean</a></li>\n<li>Leverage your code by using <code>range</code> from <code>lodash</code>. See <a href=\"https://lodash.com/docs/4.17.15#range\" rel=\"noreferrer\">https://lodash.com/docs/4.17.15#range</a></li>\n</ol>\n</li>\n</ul>\n</li>\n</ol>\n<p>Final code is here:</p>\n<pre><code>import { range, mean } from 'lodash';\n\nfunction generateRandomNumbers() {\n return range(0, 100).map(() => Math.random());\n}\n\nfunction getLengths(array) {\n return array.map(num => num.toString().length);\n}\n\nconsole.log(mean(getLengths(generateRandomNumbers())));\n</code></pre>\n<p>Or you can get rid of temporary functions and merge all of that into one call:</p>\n<pre><code>import { range, mean } from 'lodash';\n\nconsole.log(mean(\n range(0, 100)\n .map(() => Math.random())\n .map(num => num.toString().length)));\n</code></pre>\n<p>You can see these changes applied here one-by-one (in reverse order): <a href=\"https://gist.github.com/vlova/c69e3bd254af87c4acf50d6be44adbb5/revisions\" rel=\"noreferrer\">https://gist.github.com/vlova/c69e3bd254af87c4acf50d6be44adbb5/revisions</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T15:13:55.327",
"Id": "525326",
"Score": "2",
"body": "Welcome to Code Review! Your answers looks good, enjoy your stay!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T09:50:29.587",
"Id": "265943",
"ParentId": "265931",
"Score": "5"
}
},
{
"body": "<h2>Use functions</h2>\n<p>Where you have the comments <code>// random</code> <code>//length</code> and <code>//average</code> the bits of code they refer to should be defined as functions, as you have done with <code>average</code>.</p>\n<p>Give the functions the arguments need to produce the data, and have the function return that data so you don't need to store data in the global scope.</p>\n<p>Example converting the 2 tasks <code>// random</code> <code>//length</code> to functions using function declarations, and cleaning up <code>average</code> to use reduce.</p>\n<pre><code>function randNums(count, nums = []) {\n while (count-- > 0) { nums.push(Math.random()) }\n return nums\n}\nfunction numsLen(nums) {\n return nums.map(num => num.toString().length);\n}\nfunction average(lengths) {\n return lengths.reduce((total, num) => total + num, 0) / lengths.length;\n}\n</code></pre>\n<p>You can then call them as follows, with the next function in the step getting the return from the previous.</p>\n<pre><code>console.log(average(numsLen(randNums(1000))));\n</code></pre>\n<p>You can also define functions using expressions, where the unnamed function is assigned to a variable. JavaScript has a shortened function syntax called an <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript Functions/Arrow functions\">Arrow_functions</a> Arrow function are not identical to <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions\" rel=\"nofollow noreferrer\">functions</a> created using the <code>function</code> token</p>\n<pre><code>const randNums = count => new Array(count).fill().map(() => Math.random());\nconst numsLen = nums => nums.map(num => ("" + num).length);\nconst average = lens => lens.reduce((tot, num) => tot+ num, 0) / lens.length;\n</code></pre>\n<p><sub><strong>Note</strong> the the above functions do not contain returns, the <code>return</code> is implied. See <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript Functions/Arrow functions\">Arrow_functions</a> for details. </sub></p>\n<p>Below the arrow functions are identical to above but just add the implied tokens.</p>\n<pre><code>const randNums = (c) => { return new Array(c).fill().map(() => Math.random()) }\nconst numsLen = (n) => { return n.map(num => ("" + num).length) }\nconst average = (l) => { return l.reduce((tot, num) => tot + num, 0) / l.length }\n</code></pre>\n<p><sub><strong>Note</strong> I have shortened the names just so they fit the CodeReview page.</sub></p>\n<h2>Problem / Bug?</h2>\n<h3>Counting the decimal point?</h3>\n<p>One does not normally count the decimal place when counting digits in a number. <code>0.1</code> has two digits not three</p>\n<p>When you get the length you need to subtract 1 to ignore the decimal point.</p>\n<p>However there is a chance that random will give you a whole number 0 which will not have a decimal point. Thus for that one case you are forced to check that the string length is not 1 before subtracting, or check the number is zero before converting it to a string</p>\n<p>This can be done using a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. Conditional operator\">? (Conditional operator)</a></p>\n<pre><code>const numsLen = nums => nums.map(num => num ? ("" + num).length - 1 : 1);\n\n// same as\n\nconst numsLen = nums => {\n nums.map((num) => {\n if (num !== 0) { return num.toString().length - 1; }\n return 1;\n });\n}\n</code></pre>\n<h3>Very small numbers</h3>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Math random\">Math.random</a> will give number from 0 to < 1 and many of the numbers in that range can be very small. When JavaScript converts number to a string it will use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Exponential\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript Lexical grammar#Exponential\">Lexical_grammar#Exponential</a> notation when there are many leading or trailing zeros.</p>\n<p>For example the number <code>0.00000003499165601716925</code> (25 characters) which is a valid random value is converted to the string <code>"3.499165601716925e-8"</code> with 20 characters.</p>\n<p>The <code>"e-8"</code> means move the decimal point 8 places to the left. If the value was positive then it would mean move 8 places to the right. As random values will never be >= 1 then the exponent will always be negative.</p>\n<p>There could be hundreds of leading zeros, eg <code>1.0e-300</code> is a very small possible result for <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Math random\">Math.random</a></p>\n<p>You will need you create a function that parses the number string so that you can count the leading zeros. As the exponential notation will only be for very small values you can ignore the sign of the exponent.</p>\n<pre><code>const parseNumLen = str => {\n if (str.includes("e")) {\n const [digits, exp] = str.split("e-");\n return digits.length - 1 + Number(exp);\n }\n return str.length;\n}\n</code></pre>\n<p>The above uses <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. String includes\">String.includes</a> to first test if the number contains an exponent. If it does it splits the string into an array of strings using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. String split\">String.split</a>. The array is assigned to variables digits and exp using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. Destructuring assignment\">Destructuring_assignments</a> and the length is is calculated using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Number\">Number</a> to convert the string exp to a number. If you don't convert the string to a number the + operator would convert the result to a string.</p>\n<p>For example</p>\n<pre><code>const [digits, exp] = ("0.3e-10").split("e-");\nconsole.log(digits.length - 1 + exp); // >> 210 as 2 is converted to "2" by the + \n // that prefers adding strings when it sees one\nconsole.log(digits.length - 1 + Number(exp)); // >> 12\n</code></pre>\n<h3>Global scope</h3>\n<p>The names you have used <code>randomNums</code>, <code>length</code>, <code>total</code>, <code>average</code> and <code>i</code> all exist in the global scope. This means that any code on the page can get access to the variables and means that the code using these names can no longer trust the values they contain. You MUST always be able to trust your data.</p>\n<p>To build a good JavaScript coding habit always isolate you code from the global scope. There are many ways to do this but the most effective is to put your code inside an unnamed function that calls its self. Generally referred to as a <a href=\"https://developer.mozilla.org/en-US/docs/Glossary/IIFE\" rel=\"nofollow noreferrer\">Immediately Invoked Function Expression (IIFE)</a></p>\n<p>eg</p>\n<pre><code>;(()=>{\n /* your code */\n})();\n</code></pre>\n<p><sub><strong>Note</strong> the leading ";" this is to protect your function wrapper from poorly formatted code that may sit above your code</sub></p>\n<h2>Sloppy V Strict</h2>\n<p>JavaScript has two modes of operation that effect how the code is interpreted / complied and then executed.</p>\n<ol>\n<li><p><a href=\"https://developer.mozilla.org/en-US/docs/Glossary/Sloppy_mode\" rel=\"nofollow noreferrer\" title=\"MDN Glossary Sloppy mode\">Sloppy_mode</a></p>\n<p>Default mode for standard code and script tags. This mode is called Sloppy Mode not because its sloppy, but rather that it lets you be sloppy.</p>\n</li>\n<li><p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript Strict mode\">Strict_mode</a></p>\n<p>For code that is in a module or has the directive <code>"use strict"</code> at the top of the script tag, file, and or function and ensures that you do not make some common coding errors by throwing syntax errors when you write sloppy code.</p>\n<p>Strict code not only forces you to write better code, but that code also runs a little quicker. Making it a JavaScript coding habit to use strict mode is always a win win.</p>\n</li>\n</ol>\n<h2>Rewrite</h2>\n<p>Using all the points above we can write the code as</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>;(()=>{\n \"use strict\";\n const parseNumLen = str => {\n if (str.includes(\"e\")) {\n const [digits, exp] = str.split(\"e-\");\n return digits.length - 1 + Number(exp);\n }\n return str.length - 1;\n }\n const randNums = count => new Array(count).fill().map(() => Math.random());\n const numsLen = nums => nums.map(num => num ? parseNumLen(\"\" + num) : 1);\n const average = lens => lens.reduce((tot, num) => tot + num, 0) / lens.length;\n\n const nums = randNums(10);\n const aveDigits = average(numsLen(nums));\n\n console.log(nums);\n console.log(\"Average number of digits: \" + aveDigits);\n})();</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T16:01:07.690",
"Id": "525405",
"Score": "0",
"body": "Nice gotcha about parseNumLen"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T16:02:40.507",
"Id": "525407",
"Score": "0",
"body": "Just as a note. Sections global scope and strict mode are required if you aren't using any tooling. If you use bundlers, they will do that for you."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T01:17:50.373",
"Id": "265977",
"ParentId": "265931",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "265943",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T02:07:23.700",
"Id": "265931",
"Score": "6",
"Tags": [
"javascript"
],
"Title": "Basic AVG length of a decimal number program"
}
|
265931
|
<p>Cancel the old timeout for the trip.
Find the trip by Id validate it.
Find the new driver not in old driver.
If driver not found Try again</p>
<p>Sent request to the new driver.
Update the trip driver.
Sent the socket request to the driver.</p>
<pre><code> console.log("sendNewDriverRequest", tripId, typeof tripId);
if (tripTimeout[tripId]) {
tripTimeout[tripId] && clearTimeout(tripTimeout[tripId]);
delete tripTimeout[tripId];
}
const driverRequestRepository = getRepository(DriverRequest);
const tripRepository = getRepository(Trip);
const userRepository = getRepository(User);
let trip = await tripRepository.findOne({
where: { id: tripId },
relations: ["driverRequests", "driverRequests.driver"],
});
if (!trip) return console.log("Trip not found");
if (trip.status != TripStatus.SEARCHING) return console.log("Trip is not in searching status");
if (dayjs(trip.created_at).add(driverSearchTime, "m").isBefore(dayjs())) {
trip.status = TripStatus.DRIVER_NOT_FOUND;
console.log(`Changing trip ${tripId} to driver not found status.`);
await tripRepository.save(trip);
return io.to(`trip-${tripId}`).emit(tripStatusUpdated, trip);
}
if (trip.driver) {
let oldDriver = await getUserById(trip.driver.id);
if (oldDriver) {
oldDriver.trip_and_rating_info.trips_declined += 1;
await userRepository.save(oldDriver);
}
}
let oldDriverRequests = await trip.driverRequests;
let oldDriversId = oldDriverRequests.map((driverRequest) => driverRequest.driver?.id);
oldDriversId.push(0);
console.log(oldDriversId, `Old driver ids of trip ${trip.id}.`);
const newDriver = await getNewDriver(oldDriversId);
if (!newDriver?.driver_profile) {
console.error(`Driver not found for tripId ${trip.id}`);
trip.driver = null;
trip.requested_driver_id = null;
trip.requested_at = null;
await tripRepository.save(trip);
} else {
// Create the new driver request.
let driverRequest = new DriverRequest();
driverRequest.trip = trip;
driverRequest.driver = newDriver;
await driverRequestRepository.save(driverRequest);
let newTrip = (await getTripById(trip.id)) as Trip;
newTrip.driver = newDriver;
newTrip.requested_driver_id = newDriver.id;
newTrip.requested_at = dayjs().utc().format() as string;
await tripRepository.save(newTrip);
console.log(
io.sockets.adapter.rooms,
newDriver?.id,
"userId",
io.sockets.adapter.rooms.get(`user-${newDriver?.id}`),
);
if (io.sockets.adapter.rooms.get(`user-${newDriver?.id}`)) {
console.log(`Sending request to the driver ${newDriver?.driver_profile.id} by socket`);
io.to(`user-${newDriver?.id}`).emit(notifyDriverRequest, newTrip);
}
}
tripTimeout[`${tripId}`] = setTimeout(() => {
sentNewDriverRequest(location, tripId);
}, 1000 * 60 * driverRequestTime);
};
Cancel the driver timeout
export const cancelDriverRequest = (tripId: number) => {
if (tripTimeout[`${tripId}`]) {
console.log("timeout = ", !tripTimeout[`${tripId}`], "From cancelDriverRequest");
clearTimeout(tripTimeout[`${tripId}`]);
delete tripTimeout[tripId];
console.log(tripTimeout[`${tripId}`], "From cancelDriverRequest");
}
};
</code></pre>
<p>Does using setInterval in this way and recursion in this way decrease the performance.
How can i improve the code.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T03:09:23.640",
"Id": "265932",
"Score": "0",
"Tags": [
"node.js",
"socket"
],
"Title": "Does using the multiple setTimeout decrease the performance of the nodejs app"
}
|
265932
|
<p>A very simple function that can be used such that it returns a pointer to the first character on which <code>func</code> returned <code>0</code>. However, it also handles escaped lines.
Needless to say this could be very useful in my cases, for example skipping spaces when converting a csv to an array.</p>
<pre><code>/** Skip characters from @src
* @func: isspace, isdigit, isalpha, etc can be used
*/
char *skip (const char *src, int(*func)(int))
{
char* p = NULL;
for(p = src; *p != '\0'; p++)
{
if(!func(*p))
{
if(*p == '\\')
{
p++;
if(*p == '\r') /* Will probably have to deal with annoying MS-style line endings when the source string is loaded from a file */
{
p++;
}
if(*p == '\n')
{
continue;
}
}
break;
}
}
return p;
}
</code></pre>
<p>Example test usage:</p>
<pre><code>int ishspace (char ch) { return(ch == ' ' || ch == '\t'); }
int main (void)
{
char* p = skip(" \t \\\n \t Hello World\n", ishspace);
printf("%s", p);
return 0;
}
</code></pre>
<p>Output:</p>
<blockquote>
<p>> Hello World</p>
</blockquote>
<blockquote>
<p>></p>
</blockquote>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T04:35:11.757",
"Id": "525281",
"Score": "0",
"body": "What should happen if func returns true on '\\\\', like `ispunct`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T04:46:51.540",
"Id": "525282",
"Score": "0",
"body": "@PavloSlavynskyy then the loop continues (the `\\\\` is consumed) as it is supposed to be? If the line is escaped though, I imagine it will break on the NL"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T04:52:24.497",
"Id": "525283",
"Score": "0",
"body": "That should be easily solved by moving the inner condition toplevel and adding \"else\". Do you think I should edit it or wait for a complete review. Hopefully there are better, potentially faster ways to achieve this, as it is often used a lot and in performance-sensitive context."
}
] |
[
{
"body": "<h3>Code Review</h3>\n<p><strong>Problem #1</strong></p>\n<p>In the function header <code>char *skip (const char *src, int(*func)(int))</code>, in particular, making the argument <code>char *src</code> a <code>const</code> does not make much sense, as it is not regarded as so throughout the function.</p>\n<p>For instance, <code>p</code> is assigned <code>src</code> in the for loop, despite the fact that <code>p</code> is not a pointer to a const char. <code>p</code> is also returned from the function, despite the fact that the function does not return a const char (it is just char).</p>\n<p>Hence, you should either</p>\n<ol>\n<li>Drop the <code>const</code> from <code>const char *src</code> or</li>\n<li>Make the function return a <code>const char</code> and make <code>p</code> a <code>const char</code>\nas well (if you are doing this, you must also make <code>char* p</code> a\n<code>const char* p</code> in the main function)</li>\n</ol>\n<p><strong>Problem #2</strong></p>\n<p>Also in the function header <code>char *skip (const char *src, int(*func)(int))</code>, in particular, making the argument <code>int(*func)(int)</code> does not make sense. At least, according to your "test usage".</p>\n<p>For instance, you have defined your <code>ishspace</code> function as <code>int ishspace (char ch)</code>. I do not know if this was intentional or not, but this translates to <code>int (*)(char)</code> (because it accepts char as an argument), not <code>int (*)(int)</code> as your <code>skip</code> function requires. For your information, <code>isspace()</code>, <code>isdigit()</code>, <code>isalpha()</code>, etc. (the ones that are defined in <code><ctype.h></code>, I assume) all accept <code>int</code> as an argument.</p>\n<p>Hence, you should either</p>\n<ol>\n<li><p>Change the argument from <code>int(*func)(int)</code> to <code>int(*func)(char)</code>;\nthough, this is probably not what you want</p>\n</li>\n<li><p>Change the <code>ishspace</code> function in the usage example to accept <code>int</code>\ninstead of <code>char</code> (this will not affect the overall capability of the\nfunction anyways)</p>\n</li>\n</ol>\n<p>This can be improved. Using something like a <code>switch</code> statement for comparing the values of <code>*p</code> would also be more readable/efficient, if you will have to compare against 6 or more escape sequences in the future.</p>\n<p><strong>"Parting thoughts"</strong></p>\n<p>In terms of design choices, I am personally against passing <code>isspace()</code>, <code>isdigit()</code>, <code>isalpha()</code>, etc. as an argument of <code>int(*func)(int)</code>. Instead, it may be better to actually just use some those functions within the <code>skip</code> function, or try to create separate functions that checks separate things. This is due to a couple of reasons:</p>\n<ol>\n<li>It gives the users (programmers) too much power by allowing them to\npass in virtually whatever function they want. This could generate\nall sorts of undefined behavior and even security issues.</li>\n<li>It can conflict with your internal checks for certain escape\nsequences, like <code>'\\\\'</code> in particular. For instance, <code>ispunct()</code>\nfunction (assuming that we are talking about the functions in\n<code><ctype.h></code>) will return non-zero for <code>'\\\\'</code>, which is <strong>definitely not</strong>\nwhat you want.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T23:10:29.577",
"Id": "525370",
"Score": "1",
"body": "Your \"readability\" improvement changes the logic . OP's only advances `p` on an `\\r` following a '\\\\'. Yours advances on all `\\r`s."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T23:13:07.510",
"Id": "525371",
"Score": "0",
"body": "I don't believe you can give programmers \"too much power\". You just need to document what happens with the power you give them. If application end users were able to pass in arbitrary functions, that would be a different story."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T02:09:32.607",
"Id": "525374",
"Score": "0",
"body": "@AShelly Edited accordingly. I did not see that for the if-statement. As for giving programmers \"too much power\", I think my **Problem #2** demonstrates exactly what you are talking about where \"end users were able to pass in arbitrary functions\", despite the said documentation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T15:27:03.013",
"Id": "525399",
"Score": "0",
"body": "I commented that 2. was basically a missed design consideration. Instead of editing the question, I just left it as-is in case someone already started a C/R. I didn't paid attention for the `ishspace` accepting char too, that's definitely not correct. I only have to agree with @AShelly that instead of purposely restricting programmers, I should just carefully document the function."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T19:05:17.733",
"Id": "265966",
"ParentId": "265934",
"Score": "3"
}
},
{
"body": "<p>On the function arguments: <code>src</code> should definitely be a <code>const char*</code>, that is a signal to the caller that this function guarantees not to modify the string. Enforce that guarantee by making <code>p</code> a <code>const char*</code> also.</p>\n<p>And that guarantee implies that you should then return an <code>const char*</code>, so that this function is not a backdoor for the caller to cast away constness.</p>\n<p>I would probably rename <code>func</code> to <code>testfunc</code> or <code>predicate</code>.</p>\n<p>I don't think there is any problem with accepting an arbitrary test function. Tons of code out there uses callbacks. This isn't end-user facing code, and you are not responsible for limiting the "power" of programmers who use your code. You should clearly document the conditions under which this function is called, and what is done with it's output, so that programmers understand what's happening. For example</p>\n<p><code>// calls 'testfunc' on every non-escaped character in 'str' until it returns zero.</code></p>\n<p><code>testfunc</code> should take a <code>char</code> argument. Yes, <code>isalpha</code> and the like take integers, but the spec says</p>\n<blockquote>\n<p>[isalpha's] argument is an int, the value of which the application shall ensure is representable as an unsigned char ...</p>\n</blockquote>\n<p>Since you have chars, and you are responsible for ensuring chars are passed to isalpha, I would change the type and write an adapter</p>\n<pre><code>int alphatest(char c) { return isalpha(c); }\n</code></pre>\n<p>I don't understand the goal of the escape skipping part. Right now you skip calling the test func on any character following a <code>'\\\\'</code>, but only if testfunc doesn't match the <code>\\\\</code>. That seems odd.</p>\n<p>I would probably simplify the spec to: "doesn't test any character after an <code>\\</code>". Or maybe "never matches on escaped newlines", if that's what you intend. Either way, I'd refactor to</p>\n<pre><code>for(p = src; *p != '\\0'; p++)\n{\n p = skip_escapes(p);\n if (p == '\\0' or func(*p) == 0)\n {\n break;\n }\n}\n</code></pre>\n<p>Where <code>skip_escapes</code> returns <code>p</code> or the first character after a valid escape sequence starting at <code>p</code>, whatever you decide the escape sequence to be.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T23:33:17.040",
"Id": "525372",
"Score": "0",
"body": "`int alphatest(char c) { return isalpha(c); }` is UB when `c < 0` and not `EOF`. In that case \"value of which the application shall ensure is representable as an unsigned char\" was not met."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T15:33:18.163",
"Id": "525400",
"Score": "0",
"body": "\"Right now you skip calling the test func on any character following a '\\\\', but only if testfunc doesn't match the \\\\. That seems odd.\"\nPlease, take a look at my comment on the answer above.\nAlso The function only explicitly skips \"\\\", \"\\\\r\" and \"\\\\r\\n\", not every character following a `'\\\\'`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T23:09:40.413",
"Id": "265976",
"ParentId": "265934",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T04:09:59.820",
"Id": "265934",
"Score": "1",
"Tags": [
"c",
"strings",
"parsing"
],
"Title": "Function to skip characters"
}
|
265934
|
<p>A unix convention is to use <code>-</code> as a placeholder for stdin/stdout in command lines, e.g. <code>gcc -x c -</code> to compile stdin as C. I often find myself writing logic to get this behavior in my Python scripts, so I abstracted it out into a context manager:</p>
<pre class="lang-py prettyprint-override"><code>from typing import IO
class argfile:
def __init__(self, default: IO, filename: str, mode: str = 'r'):
self.__file = default if filename == '-' else open(filename, mode)
self.__should_close = filename != '-'
def __enter__(self) -> IO:
return self.__file
def __exit__(self, exc_type, exc_value, exc_traceback):
self.close()
def close(self):
if self.__should_close:
self.__file.close()
</code></pre>
<p>Now instead of writing this mess:</p>
<pre class="lang-py prettyprint-override"><code>args = parser.parse_args()
if args.inputfile == '-':
infile = sys.stdin
else:
infile = open(args.inputfile, 'r')
if args.output == '-':
outfile = sys.stdout
else:
outfile = open(args.output, 'w')
try:
do_work(infile, outfile)
finally:
if args.output != '-':
outfile.close()
if args.inputfile != '-':
infile.close()
</code></pre>
<p>I instead write:</p>
<pre class="lang-py prettyprint-override"><code>args = parser.parse_args()
with argfile(sys.stdin, args.inputfile, 'r') as infile, \
argfile(sys.stdout, args.output, 'w') as outfile:
do_work(infile, outfile)
</code></pre>
<p>I do consider it important to close the files and not close stdin/stdout, as I often call the <code>main()</code> functions of my Python scripts inside other scripts with much longer lifetimes. Also note that I named the class in lowercase because I think of it more as a function call replacing <code>open(...)</code> than as a class constructor.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T16:40:47.557",
"Id": "525343",
"Score": "0",
"body": "Is there a reason you don't use [`type=argparse.FileType(\"r\")`](https://docs.python.org/3.9/library/argparse.html#argparse.FileType) to get automatic handling of '-' as a command line argument?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T20:03:42.133",
"Id": "525356",
"Score": "0",
"body": "@RootTwo Because I didn't know that exists. This is exactly why I asked this question: I wanted someone to tell me I was working too hard. Although I don't quite see how to close the file without closing `stdin`/`stdout` if a `-` was passed..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T20:13:51.897",
"Id": "525357",
"Score": "0",
"body": "@RootTwo I'm not going to use that, though, see https://bugs.python.org/issue13824 . In particular, \"FileType is not what you want for anything but quick scripts that can afford to either leave a file open or to close stdin and/or stdout.\" I don't want to do either of those things. However, that thread does have some other solutions I might prefer"
}
] |
[
{
"body": "<p>The code can be simplified using the <code>contextlib.contextmanager</code> decorator:</p>\n<pre><code>from contextlib import contextmanager\n\n@contextmanager\ndef argfile(default: IO, filename: str, mode: str = 'r'):\n file_like = open(filename, mode) if filename != '-' else default\n yield file_like\n if filename != '-':\n file_like.close()\n</code></pre>\n<p>Use it the same way as your code.</p>\n<p>Is <code>default</code> ever anything other than <code>stdin</code> or <code>stdout</code>? If not, then maybe something like:</p>\n<pre><code>@contextmanager\ndef argfile(filename: str, mode: str = 'r'):\n\n if filename != '-' :\n file_like = open(filename, mode)\n\n else:\n file_like = sys.stdin if mode == 'r' else sys.stdout\n\n yield file_like\n\n if filename != '-':\n file_like.close()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T01:08:27.467",
"Id": "525436",
"Score": "0",
"body": "I ended up using a modification of the second version which is `if filename == '-': yield sys.stdout if mode == 'w' else sys.stdin; else: with open(...) as f: yield f`, which is a bit shorter and nicer IMO"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T05:34:16.303",
"Id": "265978",
"ParentId": "265935",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "265978",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T04:48:31.650",
"Id": "265935",
"Score": "0",
"Tags": [
"python",
"python-3.x"
],
"Title": "argfile: read/write stdio or specified file depending on command line argument"
}
|
265935
|
<p>I am solving the 2D Wave Equation using Fourier Transform. The Discrete Fourier Transform (and the inverse also) is done inside the <code>kx</code>-loop and <code>ky</code>-loop. But this code runs slow, is there anyway to make it much more efficient? I guess the <code>kx</code>-loop, <code>ky</code>-loop inside the <code>i</code>-loop and <code>j</code>-loop makes it slow. I am also open for external package suggestion.</p>
<pre><code>program fourier_transform_solution
implicit none
integer :: i,j,kx, ky, it
real, parameter :: PI = 3.1415926
integer, parameter :: N=100, N_t=100
integer, parameter :: N_k = N/2
real, dimension(N):: x, y
real, dimension(N,N) :: f, ut_init, u_r
real, dimension(N_t) :: t
complex, dimension(N,N) :: u, u_hat, u_hat_prev, ut_hat, ut_hat_prev
complex, dimension(N) :: wx, wy
complex, parameter :: I_complex = complex(0, 1)
real :: dx, xmin=0, xmax=3*PI, dy, ymin = 0, ymax = 3*PI
real :: d, dt = 0.001
do i=1,N_t,1
t(i) = 0 + (i-1)*dt
end do
dx = (xmax-xmin)/(N-1); dy = (ymax-ymin)/(N-1); d = dx/(2*PI);
do i=1,N_k,1
wx(i) = 0 + -(N_k-i)/(d*(N-1)); wx(N_k+i) = 0 + (i)/(d*(N-1))
wy(i) = 0 + -(N_k-i)/(d*(N-1)); wy(N_k+i) = 0 + (i)/(d*(N-1))
end do
do i=1,N,1
x(i) = xmin+ (i-1)*dx
y(i) = ymin+ (i-1)*dy
end do
do i=1,N,1
do j=1,N,1
f(i,j) = 0.6*exp( -((x(i)- 1.5*PI)**2) + -((y(j)- 1.5*PI)**2) )
u(i,j) = f(i,j)
u_r(i,j) = f(i,j)
ut_init(i,j) = 0
end do
end do
!Fourier Transform
do i=1,(N),1
do j=1,N,1
u_hat_prev(i,j) = 0
ut_hat_prev(i,j) = 0
do kx=1,N,1
do ky=1,N,1
u_hat_prev(i,j) = u_hat_prev(i,j) + u_r(kx, ky)*exp(-(wx(i)*x(kx) + wy(j)*y(ky))*(I_complex))
ut_hat_prev(i,j) = ut_hat_prev(i, j) + ut_init(kx, ky)*exp(-(wx(i)*x(kx) + wy(j)*y(ky))*(I_complex))
end do
end do
end do
end do
do it=2,N_t,1
do i=1,(N),1
do j=1, N, 1
ut_hat(i, j) = ut_hat_prev(i, j) + dt*(-(wx(i) + wy(j))**2)*(u_hat_prev(i, j))
end do
end do
do i=1,(N),1
do j=1,N,1
u_hat(i,j) = u_hat_prev(i,j) + dt*ut_hat(i,j)
end do
end do
!Inverse Fourier
do i=1,N,1
do j = 1,N,1
u(i, j)=0
do kx=1,N,1
do ky=1,N,1
u(i,j) = u(i,j) + u_hat(kx, ky)*exp((I_complex)*(wx(kx)*x(i) + wy(ky)*y(j)))
end do
end do
u_r(i,j) = (real(u(i,j)))/(N*N)
ut_hat_prev(i,j) = ut_hat(i,j)
u_hat_prev(i,j) = u_hat(i,j)
end do
end do
print *, it
end do
end program fourier_transform_solution
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T07:11:26.583",
"Id": "525380",
"Score": "0",
"body": "You should never ever compute the discrete Fourier transform from the definition. Instead, use FFT (fast Fourier transform). There are packages like P3DFFT, FFTW3, FFTPACK and some others available."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T04:18:29.217",
"Id": "525486",
"Score": "0",
"body": "@VladimirF which one you recommend? I downloaded the intel one but dont mnow"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T04:56:07.650",
"Id": "265936",
"Score": "0",
"Tags": [
"performance",
"mathematics",
"numerical-methods",
"signal-processing",
"fortran"
],
"Title": "2D Discrete Fourier Transform using Fortran"
}
|
265936
|
<p>My daughter and I are trying to teach ourselves Python and OOP. We wrote a hangman game, and we'd really appreciate some feedback. Are we heading in the right direction? How could we improve it? Anything that makes a Python programmer go "ouch"? Anything that makes an OOP expert cringe? All sorts of questions occur to us. For example, should we be instantiating classes when there is only one instance? Feel free to be brutal! We've posted it as a repl here:
<a href="https://replit.com/@scripta/Hangman#main.py" rel="nofollow noreferrer">https://replit.com/@scripta/Hangman#main.py</a></p>
<p>Changed the invoking functionality into a class "Game" as per ASM's suggestion.</p>
<p>A huge thanks for the time and effort that went into commenting on the code. With apologies for having initially changed the code in this initial post (see above), here is a new post with most of the suggestions acted upon:
<a href="https://codereview.stackexchange.com/questions/266049/oop-hangman-game-amended-code">OOP Hangman Game - amended code</a></p>
<pre><code>import random
class Word:
def __init__(self):
words = ("foxglove", "captain", "oxygen", "microwave", "rhubarb")
self._word = random.choice(words)
self.letters_in_word=set(self._word)
@property
def word(self):
return self._word
def progress(self, guesses):
# create string of underscores and guessed letters to show progress to guessing word
progress_string= ""
for char in self.word:
if guesses.guessed(char):
progress_string= progress_string+" "+char+" "
else:
progress_string= progress_string +" _ "
return(progress_string)
def guessed(self, guesses):
letters_guessed = self.letters_in_word.intersection(guesses.guesses_made)
if letters_guessed == self.letters_in_word:
return True
else:
return False
class Guesses:
def __init__(self):
# guesses holds all guesses made (wrong or right)
self.guesses_made = set()
def guessed(self,char):
if char in self.guesses_made:
return True
else:
return False
def record(self,guess,word):
# All valid guesses (wrong or right) are added to the guesses set
self.guesses_made.add(guess)
if not guess in word.letters_in_word:
Gallows.record_bad_guess()
def made(self):
# to sort the set of guesses made we need to cast it to a list
guesses_list= list(self.guesses_made)
guesses_list.sort()
guesses_string=""
#comma separate the guesses
for char in guesses_list:
guesses_string= guesses_string+char+","
return guesses_string
class Gallows:
_bad_guesses=0
gallows_images = (" \n \n \n \n \n__________",
" \n | \n | \n | \n | \n_|________",
" _____\n | \n | \n | \n | \n_|________",
" _____\n |/ \n | \n | \n | \n_|________",
" _____\n |/ |\n | \n | \n | \n_|________",
" _____\n |/ |\n | O \n | \n | \n_|________",
" _____\n |/ |\n | O \n | | \n | \n_|________",
" _____\n |/ |\n | O \n | /| \n | \n_|________",
" _____\n |/ |\n | O \n | /|\\ \n | \n_|________",
" _____\n |/ |\n | O \n | /|\\ \n | / \n_|________",
" _____\n |/ |\n | O \n | /|\\ \n | / \\\n_|________",)
@classmethod
def record_bad_guess(cls):
cls._bad_guesses +=1
@classmethod
def hanged(cls):
if cls._bad_guesses >= len(cls.gallows_images)-1:
return True
else:
return False
@classmethod
def draw(cls):
return cls.gallows_images[cls._bad_guesses]
class Game:
def get_letter(self, guesses):
while True:
char= input("\nPlease enter your guess: ")
if len(char)<1:
print ("You didn't choose a letter!")
elif len(char)!=1:
print ("One letter at a time!")
elif not char.isalpha():
print ("Alphabetic characters only!")
elif guesses.guessed (char):
print ("You already guessed that letter")
else:
break
return (char)
def display_progress(self, target, gallows, guesses):
print("\n",target.progress(guesses))
print(gallows.draw())
print("\nUsed: \n",guesses.made())
def play(self):
target= Word()
guesses= Guesses()
gallows= Gallows()
while True:
guess= self.get_letter(guesses)
guesses.record(guess,target)
self.display_progress(target, gallows, guesses)
if target.guessed(guesses):
print("\nYou win, well done")
break
if gallows.hanged():
print ("\nI win. The word was:",target.word)
break
if __name__ == "__main__":
game= Game()
game.play()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T07:32:38.387",
"Id": "525289",
"Score": "3",
"body": "It's not an answer neither the code review but I recommend writing unit tests for your code which helps to decompose your code better while giving insights on the dependency management. \n \nQuick over view, OOP implementation is good enough. You have separated different entities with their roles which is the most important part in OOAD. The main invoking functionality can also be changed into a class to complete it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T12:42:21.143",
"Id": "525297",
"Score": "0",
"body": "We've created a class \"Game\" to run the game. Is that what you meant? Will look at adding unit tests."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T13:55:12.603",
"Id": "525307",
"Score": "0",
"body": "@scripta questions should not be modified based on answers. It should be left as is, because it could make certain comments lose meaning. If, after receiving feedback, you'd like to update your code and have it reviewed, you should post another question, and add a link to it here (maybe even a link to this question in the new one)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T18:18:39.333",
"Id": "525348",
"Score": "0",
"body": "I don't know much about the technical aspects of python, but that looks like pretty code to me. I have three suggestions, which have nothing to do with your coding: 1) present a game introduction; 2) get the words from a file containing a list of many more words; and 3) introduce scorekeeping and a display of scores, wins and losses, at the end. That will make it more interesting and competitive. (I first wrote a hangman game like that as a DOS batch file and I have one written in bash on my web server now.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T14:58:28.853",
"Id": "525398",
"Score": "1",
"body": "@AnitShresthaManandhar recomending unit-testing for a private hobby project is like building a sewer system and high-voltage transformator for your garden-shed"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T17:32:42.347",
"Id": "525419",
"Score": "0",
"body": "@clockw0rk: True...but if you're doing it for the purpose of learning the language and practicing best practices, it's not a horrible idea. Lots of things that are overkill in regular use can be beneficial for education. That said, I wouldn't recommend unit tests for this purpose, either. ;)"
}
] |
[
{
"body": "<p>From the first looks, quite nice. I have mostly just a few smaller\nconcerns:</p>\n<ul>\n<li>Consistency matters for readers, so should be either <code>x = y</code>, <code>x= y</code>\nor <code>x =y</code> (or any variant really). Using\n<a href=\"https://black.readthedocs.io/en/stable/\" rel=\"noreferrer\">an autoformatter</a> is of\ncourse easier than doing that manually, but otherwise I'd generally go\nfor the first variant.</li>\n<li>For <code>words</code>: if you have a sequence, use a <code>list</code>, not a <code>tuple</code>.\nIt's clearer and fits the purpose better, e.g. if you were to add new\nelements to the list of words it only works with <code>list</code>, because\n<code>tuple</code>'s are immutable.</li>\n<li>Negating <code>in</code> can be done with <code>not in</code>, which reads more naturally.</li>\n<li>The pattern <code>if x == y: return True else: return False</code> is not making\nuse of the fact that <code>x == y</code> <em>already</em> returns a boolean value - it\ncan simply be replaced by the much shorter <code>return x == y</code>.</li>\n<li>Some members have an underscore, some don't - unless you strife for a\nvery hard border between private and public properties I'd pick one\nand stick with it, if you go with the underscores, then just provide\n<code>@property</code> accessors for them if necessary.</li>\n<li>Each of the images could probably be easier to read by using\nmulti-line strings (<code>"""these ones"""</code>).</li>\n<li>If you want to get into list comprehensions, <code>made</code>'s way of\nformatting can be a little bit simpler via <code>str</code>'s <code>join</code> method,\ne.g. <code>",".join(self.guessed_made)</code>.</li>\n<li><code>sorted</code> can be simpler than <code>list</code> followed by <code>sort</code>,\ne.g. <code>sorted(self.guesses_made)</code> does what you think it does.</li>\n</ul>\n<p>Structurally, the next thing I saw was that <code>Guesses</code> uses the <code>Gallows</code>\nclass, not an object, while in <code>play_hangman.py</code> it's being constructed\nas an object and also used like one. I'd pick one and stick with it.\nSince it's intended to be more OOP, right, I'd go with dropping the\nclass methods and make it an actual object, that seems cleaner and\nat least in theory would allow for better testing anyway.</p>\n<p>Wrt. an overall <code>Game</code> class: if you want to do it for learning\nreasons, sure, but really in Python at least it's fine to have\nstandalone functions too. Of course you can do things like mocking all\nyour dependencies that way, but even just having <code>play_game</code> take\n<code>target</code>, <code>guesses</code> and <code>gallows</code> as parameters would still allow you to\ndo that. Edit: And I'm not gonna follow that edit since I was already typing this out before.</p>\n<p><code>play_hangman.py</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import hangman\n\n\ndef get_letter(guesses):\n while True:\n char = input("\\nPlease enter your guess: ")\n if len(char) < 1:\n print("You didn't choose a letter!")\n elif len(char) != 1:\n print("One letter at a time!")\n elif not char.isalpha():\n print("Alphabetic characters only!")\n elif guesses.guessed(char):\n print("You already guessed that letter")\n else:\n break\n return char\n\n\ndef play_game():\n target = hangman.Word()\n guesses = hangman.Guesses()\n gallows = hangman.Gallows()\n while True:\n guess = get_letter(guesses)\n guesses.record(gallows, guess, target)\n print("\\n", target.progress(guesses))\n print(gallows.draw())\n print("\\nUsed: \\n", guesses.made())\n if target.guessed(guesses):\n print("\\nYou win, well done")\n break\n if gallows.hanged():\n print("\\nI win. The word was:", target.word)\n break\n\n\nif __name__ == "__main__":\n play_game()\n</code></pre>\n<p><code>hangman.py</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import random\n\n\nclass Word:\n def __init__(self):\n words = ["foxglove", "captain", "oxygen", "microwave", "rhubarb"]\n self.word = random.choice(words)\n self.letters_in_word = set(self.word)\n\n def progress(self, guesses):\n # create string of underscores and guessed letters to show progress to guessing word\n return " ".join(char if guesses.guessed(char) else "_" for char in self.word)\n\n def guessed(self, guesses):\n letters_guessed = self.letters_in_word & guesses.guesses_made\n return letters_guessed == self.letters_in_word\n\n\nclass Guesses:\n def __init__(self):\n # guesses holds all guesses made (wrong or right)\n self.guesses_made = set()\n\n def guessed(self, char):\n return char in self.guesses_made\n\n def record(self, gallows, guess, word):\n # All valid guesses (wrong or right) are added to the guesses set\n self.guesses_made.add(guess)\n if guess not in word.letters_in_word:\n gallows.record_bad_guess()\n\n def made(self):\n return ",".join(sorted(self.guesses_made))\n\n\nclass Gallows:\n gallows_images = (\n " \\n \\n \\n \\n \\n__________",\n " \\n | \\n | \\n | \\n | \\n_|________",\n " _____\\n | \\n | \\n | \\n | \\n_|________",\n " _____\\n |/ \\n | \\n | \\n | \\n_|________",\n " _____\\n |/ |\\n | \\n | \\n | \\n_|________",\n " _____\\n |/ |\\n | O \\n | \\n | \\n_|________",\n " _____\\n |/ |\\n | O \\n | | \\n | \\n_|________",\n " _____\\n |/ |\\n | O \\n | /| \\n | \\n_|________",\n " _____\\n |/ |\\n | O \\n | /|\\\\ \\n | \\n_|________",\n " _____\\n |/ |\\n | O \\n | /|\\\\ \\n | / \\n_|________",\n " _____\\n |/ |\\n | O \\n | /|\\\\ \\n | / \\\\\\n_|________",\n )\n\n def __init__(self):\n self._bad_guesses = 0\n\n def record_bad_guess(self):\n self._bad_guesses += 1\n\n def hanged(self):\n return self._bad_guesses >= len(self.gallows_images) - 1\n\n def draw(self):\n return self.gallows_images[self._bad_guesses]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T14:29:51.140",
"Id": "525319",
"Score": "1",
"body": "Note that, about your _unless you [strive] for a very hard border between private and public properties_, there's not really such a thing in Python."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T14:46:04.890",
"Id": "525320",
"Score": "1",
"body": "Regarding your comment about `words` being a `list`, I'd argue a `tuple` fits the purpose better, as it is being used a fixed number of possibilities that will not be updated at runtime"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T13:58:07.143",
"Id": "265956",
"ParentId": "265940",
"Score": "8"
}
},
{
"body": "<p>(Some of these points have already been covered by the answer already posted, but I was already halfway through writing this when it appeared.)</p>\n<hr />\n<p>This looks like a fun programme, and has got a lot of great stuff in it! This isn't a full review by any means, but here's a few small tips for improving your code:</p>\n<p><strong>1. Move the <code>words</code> variable out of the <code>Word.__init__</code> method.</strong></p>\n<p>This variable is an arbitrary constant that isn't altered during execution of the program. You should try to minimise the extent to which such constant values are buried in the middle of your code, so that it is obvious where they are and easy to modify their values should you find yourself editing your code in the future. It's also good practice to give them ALL_CAPS names, which is the convention for constant values that never change. (Your <code>Gallows.gallows_images</code> attribute should be renamed as <code>Gallows.GALLOWS_IMAGES</code> for the same reason.)</p>\n<p>Constant values should either go at the top of a module in the global namespace, or at the top of a class in the class namespace. In this case, I'd put it at the top of the class:</p>\n<pre><code>import random\n\nclass Word:\n WORDS = ("foxglove", "captain", "oxygen", "microwave", "rhubarb")\n\n def __init__(self):\n self._word = random.choice(self.WORDS)\n self.letters_in_word = set(self._word)\n</code></pre>\n<p><strong>2. Keeping to the <a href=\"https://pep8.org/\" rel=\"nofollow noreferrer\">PEP8 style guide</a> will make your code more readable for other people.</strong></p>\n<p>In particular, there are lots of places in your code where you don't have spaces around operators such as <code>+</code> and <code>=</code>, which I personally find quite hard to read.</p>\n<p><strong>3. Using F-strings is a more pythonic way of concatenating strings</strong></p>\n<p>In your <code>Word.progress</code> method, you start with an empty string, and add values to it iteratively using the <code>+</code> operator. You could make this more readable by using the <code>+=</code> operator to add characters to your string, and by using F-strings to reduce your other uses of the <code>+</code> operator:</p>\n<pre><code>class Word:\n # <--- snip --->\n\n def progress(self, guesses):\n # create string of underscores and guessed letters to show progress to guessing word\n progress_string = ""\n for char in self.word:\n if guesses.guessed(char):\n progress_string += f" {char} "\n else:\n progress_string += " _ "\n return(progress_string)\n</code></pre>\n<p>You could even use Python's ternary operator to shorten this even further:</p>\n<pre><code>class Word:\n # <--- snip --->\n\n def progress(self, guesses):\n # create string of underscores and guessed letters to show progress to guessing word\n progress_string = ""\n for char in self.word:\n progress_string += f" {char} " if guesses.guessed(char) else " _ "\n return(progress_string)\n</code></pre>\n<p>Or use the <code>str.join</code> method and a generator expression to make it into a one-liner!</p>\n<pre><code>class Word:\n # <--- snip --->\n\n def progress(self, guesses):\n # create string of underscores and guessed letters to show progress to guessing word\n return "".join((f" {char} " if guesses.guessed(char) else " _ ") for char in self.word)\n</code></pre>\n<p><strong>4. Your methods that return <code>bool</code> values can be simplified</strong></p>\n<p>Your <code>Word.guessed</code> method can be simplified like so:</p>\n<pre><code>class Word:\n # <--- snip --->\n\n def guessed(self, guesses):\n return bool(self.letters_in_word.difference(guesses.guesses_made))\n</code></pre>\n<p>Your <code>Guesses.guessed</code> method can be simplified like so:</p>\n<pre><code>class Guesses:\n # <--- snip --->\n\n def guessed(self, char):\n return char in self.guesses_made\n</code></pre>\n<p>And your <code>Gallows.hanged</code> method can also be shortened to one line:</p>\n<pre><code>class Gallows:\n # <-- snip -->\n\n @classmethod\n def hanged(cls):\n return cls._bad_guesses >= (len(cls.gallows_images) - 1)\n</code></pre>\n<p>It's a little unclear to me why your <code>Gallows._bad_guesses</code> attribute is marked as private, by the way. I think it would be fine to have it as a public <code>Gallows.bad_guesses</code> attribute. It's also a bit of a code smell to have a class where every method is a <code>classmethod</code> — for a more comprehensive refactoring of your <code>Gallows</code> class, I'd take a look at @ferada's answer.</p>\n<p>I also agree with @ferada that there's no real need for your <code>Game</code> class, as none of its functions keep track of internal state at all. If your code is purely procedural, it's more pythonic to have your functions in the global namespace rather than creating objects for the sake of objects (this is very different to other languages such as Java).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T14:24:04.077",
"Id": "265959",
"ParentId": "265940",
"Score": "5"
}
},
{
"body": "<p>Welcome to Code Review!</p>\n<p>If you just started learning, it seems decently good. Here are a few comments in no particular order:</p>\n<p>Edit: After posting the answer, I've seen most it not all the points below have already being covered in other answers written while I was writing mine. Still, I will leave it here as it might be useful</p>\n<ul>\n<li>In general, have a read at <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a>. It is a general style guide widely followed by the community. For example, you are not using consistent spacing:</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code># No slace on the left of the assignment\nprogress_string= progress_string+" "+char+" "\n# Space on the left\nself.guesses_made = set()\n</code></pre>\n<ul>\n<li><p>Regarding OOP design, <code>Gallows</code> is poorly designed. It is used as a king of namespace, having all methods being classmethods, it has class properties, but it is also instatiated. It should simply be a class with its properties and its methods.</p>\n</li>\n<li><p>Useage of bools:</p>\n</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>if condition:\n return True\nelse:\n return False\n</code></pre>\n<p>Can be changed to:</p>\n<pre class=\"lang-py prettyprint-override\"><code>retun condition\n</code></pre>\n<p>For example, the <code>guessed</code> method in <code>Guesses</code></p>\n<ul>\n<li>The <code>Guesses#made</code> method can be simplified:</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>sorted_guesses = list(self.guesses_made).sort()\nreturn ",".joint(sorted_guesses)\n</code></pre>\n<ul>\n<li><p><code>Guesses</code> is just a wrapper around a set, so it probably should not be a class, and just a property in the game object. The <code>Guesses#made</code> method could be a method a <code>Game</code> method. The <code>Guesses#record</code> method should not depend on <code>Gallows</code> (it doesn't really make sense), so it its just a <code>set#add</code>.</p>\n</li>\n<li><p>To me, method names should have meaning all by themselves. For example, <code>made</code> does not tell me anything unless I read it as <code>Guesses#made</code>. So it probably should be renamed to something like <code>made_guesses</code>.</p>\n</li>\n<li><p><code>word</code>, <code>guesses</code> and <code>gallows</code> should be <code>Game</code>'s properties created upon initialization. They could also be created on a method called <code>init</code> or <code>reset</code> that was called upon initialization. This would allow restarting a game in a more explicit way (currently you could just call <code>play</code> twice)</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T14:42:21.033",
"Id": "265960",
"ParentId": "265940",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T07:19:59.427",
"Id": "265940",
"Score": "15",
"Tags": [
"python",
"beginner",
"object-oriented",
"hangman"
],
"Title": "OOP Hangman Game"
}
|
265940
|
<p>The aim of the implementation is divide an array to two sub array which the total of the every sub array should be equal. If Array is dividable then method return <code>true</code> else return <code>false</code>.</p>
<p>For example:</p>
<p>This array can be dividable to two sub parts and each sub array sum is equal to 5.</p>
<pre><code>int[] array = {4, 1, 1, 3, 1}; // true {4, 1} , {1, 3, 1}
</code></pre>
<p>This array can be dividable to two sub parts and each sub array sum is equal to 4.</p>
<pre><code>int[] array1 = {5, 4, -5, 3, 1}; // true {5, 4, -5} , {3, 1}
</code></pre>
<p>This array can be dividable to two sub parts and each sub array sum is equal to 5.</p>
<pre><code>int[] array2 = {3, 2, -5, 10}; // true {3, 2} , {-5, 10}
</code></pre>
<hr />
<p>This array can not be divided.</p>
<pre><code>int[] array3 = {10, 11, 15, 8}; // false
</code></pre>
<hr />
<p>Looking forward to hear other approaches. Thanks.</p>
<p><strong>Code:</strong></p>
<pre><code>public class SplitArray {
public static void main(String[] args) {
int[] array = {4, 1, 1, 3, 1};
int[] array1 = {5, 4, -5, 3, 1};
int[] array2 = {3, 2, -5, 10};
int[] array3 = {10, 11, 15, 8};
System.out.println( isSeparable(array) );
System.out.println( isSeparable(array1) );
System.out.println( isSeparable(array2) );
System.out.println( isSeparable(array3) );
}
private static boolean isSeparable(int[] array) {
if (array.length == 0)
return false;
int sum = 0;
for(int i=0;i<array.length;i++) {
sum += array[i];
}
if(sum % 2 == 1){
return false;
}
int expectedSum = sum / 2;
int tempSum = 0;
for(int i=0;i<array.length;i++) {
tempSum += array[i];
if(tempSum == expectedSum) {
return true;
}
}
return false;
}
}
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n<p>The aim of the implementation is <strong>divide an array to two sub array</strong> which the total of the every sub array should be equal. If Array is dividable then method return true else return false.</p>\n</blockquote>\n<p>The aim is clearly not met by your code; you never actually <em>divide the array</em>. Either the requirements are incorrect, or the code is. At this point in time you should ask for clarification. Trust me: as an architect I know how things can quickly derail; requirements should be very precise. For one, you've now wound up with a class <code>SplitArray</code> that never splits the array.</p>\n<p>Furthermore, the "separable" property is rather specific, which means it should be clearly described in the code using comments. Otherwise you'll look to your code later on, wondering what the heck it was supposed to do.</p>\n<hr />\n<p>The strategy followed is correct and performant. I like that it doesn't use an doubles, and that it returns <code>true</code> or <code>false</code> whenever it can. That's very high level (C-programmers that have to worry about resource allocation would not agree, but for Java it's OK).</p>\n<hr />\n<pre><code>System.out.println( isSeparable(array) );\n</code></pre>\n<p>Don't use manual formatting of code, just use:</p>\n<pre><code> System.out.println(isSeparable(array));\n</code></pre>\n<p>If the code becomes too hard to read, create a local variable and print that.</p>\n<hr />\n<pre><code>private static boolean isSeparable(int[] array) {\n</code></pre>\n<p>Probably not part of this exercise, but normally you'd create a <code>int separableIndex(int[] array)</code> and a constant <code>NOT_SEPARABLE = -1</code>. That way you don't just know that it is separable or not, but you can also decide to perform the actual split later. If you allow negative values then it should be named <code>firstSeparableIndex</code> or return an entire list of indices, whichever is required (e.g. <code>{-1, 1, -1, 1, -1, 1 }</code> can be split in two ways).</p>\n<hr />\n<pre><code> if (array.length == 0)\n return false;\n</code></pre>\n<p>Always use braces in <code>if</code>. What you are saying here is that you cannot split an array in two if it is empty. However, are you sure that you've caught the boundaries right? Can <code>{ 0 }</code> be split into an array of 1 and an empty array? What about <code>{ 1, -1 }</code>? Doesn't this method always return <code>true</code> as long as the array contains elements? The problem here is that you use the division to check for correctness. If you would only allow two or more elements then you'd be alright.</p>\n<p>If this was part of a library you may even have to consider the number of bits and two-complement implementation of <code>int</code>, otherwise you may overshoot <code>Integer.MAX_VALUE</code> or even go round-robin. I guess that's taking it too far for this exercise though.</p>\n<p><strong>Always check your boundary conditions</strong>.</p>\n<hr />\n<pre><code> for(int i=0;i<array.length;i++) {\n</code></pre>\n<p>Please use more whitespace or perform a code cleanup / run a formatter before sharing your code (you are <strong>now</strong> sharing your code!).</p>\n<hr />\n<pre><code>int sum = 0;\n\nif(sum % 2 == 1){\n return false;\n}\n</code></pre>\n<p>The whiteline here is distracting, especially since you've so nicely kept the lines together with the <code>for</code> loop later on.</p>\n<p>Please see the discussion <a href=\"https://stackoverflow.com/a/51998794/589259\">here</a> if you want to consider negative values. And yeah, why not create an <code>isEven</code> or <code>isOdd</code> function?</p>\n<p>Finally, for this simple exercise we can immediately understand why you return <code>false</code>, but generally if we can only grasp <em>what</em> you are doing and not <em>why</em>, then you have to indicate the <em>why</em>.</p>\n<pre><code>// sub-arrays of integers can not add up to a fraction\n</code></pre>\n<p>or something along those lines.</p>\n<hr />\n<pre><code> for(int i=0;i<array.length;i++) {\n</code></pre>\n<p>Again the whitespace. Please keep to Java coding conventions.</p>\n<p>But you're also overshooting: you could and probably should go to <code>array.length - 1</code> here so that you know that the final array will have at least 1 element in it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T15:47:29.000",
"Id": "265961",
"ParentId": "265945",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T10:17:21.980",
"Id": "265945",
"Score": "1",
"Tags": [
"java",
"array"
],
"Title": "Is Array Separable To Two List"
}
|
265945
|
<p>I recently started making a game in JavaScript, but I've only really built the renderer. This is the first 'real' game I started working on and I don't know if I'm doing any major things wrong and if there's things to improve.</p>
<p><strong>renderer.js</strong></p>
<pre><code>function Renderer(atlas){
this.canvas = document.querySelector("canvas");
this.ctx = this.canvas.getContext("2d");
this.width = this.canvas.width = screen.width;
this.height = this.canvas.height = screen.height;
this.loaded = 0;
this.tileSize = 64;
if(atlas){
this.tileAtlas = new Image(this.tileSize, this.tileSize);
this.loaded = 1;
this.tileAtlas.src = atlas;
}
this.showImg = function(arg, x, y){
let offset = arg * 16 - 16;
if(arg){
this.ctx.drawImage(this.tileAtlas, offset, 0, 16, 16, x, y, this.tileSize + 1, this.tileSize + 1);
}
}
this.renderMap = function(map, xd, yd){
this.ctx.imageSmoothingEnabled = false;
for(let y = 0; y < map.length; y++){
for(let x = 0; x < map[y].length; x++){
if(x*this.tileSize+xd<-this.tileSize){continue}
if(x*this.tileSize+xd>this.canvas.width){break}
this.showImg(map[y][x], x*this.tileSize+xd, y*this.tileSize+yd);
}
}
}
this.clear = function(){
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
}
</code></pre>
<p><strong>index.html</strong></p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Gayme test</title>
<style>
body{
overflow: hidden;
background-color: white;
}
canvas{
position: absolute;
background-color: rgb(0, 140, 255);
top: 0px;
left: 0px;
z-index: -1;
}
</style>
</head>
<body>
<canvas></canvas>
<p></p>
<script src="terrain.js"></script>
<script src="renderer.js"></script>
<script src="main.js"></script>
</body>
</html>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T14:24:39.143",
"Id": "525315",
"Score": "0",
"body": "Just an idea: you could scale using the height of the atlas if you have an atlas consisting of subsequent images. Generally, if you still have literals such as 16 in your code, you should either use them to validate the size or you should remove them in favor of the input."
}
] |
[
{
"body": "<pre><code>this.loaded = 0;\n</code></pre>\n<p>I don't see the point of this variable; not much longer it will be set to 1, but it is never exposed anywhere.</p>\n<hr />\n<pre><code>this.width = this.canvas.width = screen.width;\nthis.height = this.canvas.height = screen.height;\n</code></pre>\n<p>I think this should be a parameter to the renderer with a default value. Why do you need <code>this.width</code> if you're only going to use <code>canvas.width</code>? Please make sure that all values are represented only <em>once</em>, or you'll certainly get into an illegal state later on.</p>\n<hr />\n<pre><code>this.showImg = function(arg, x, y){\n</code></pre>\n<p><code>arg</code> = "Arg!" - variables should be named according to their function; this one isn't. Apparently it is a 1 based index, but at least then call it <code>index</code> or <code>indexInAtlas</code>. That makes the whole idea of using an atlas clear in one go. Personally, I <strong>always</strong> use zero based indexing - and with good reason, but if you use <em>one based</em> then use: <code>(indexInAtlas - 1) * 16</code> to increase understanding.</p>\n<hr />\n<pre><code>if(arg){\n</code></pre>\n<p>If you don't want to draw anything, then <em>don't call a method that starts with <code>show</code></em>; skip calling the function in <code>renderMap</code>.</p>\n<hr />\n<pre><code>this.renderMap = function(map, xd, yd){\n</code></pre>\n<p>There is no indication whatsoever what <code>xd</code> and <code>yd</code> is and it is even more confusing with the <code>x</code> and <code>y</code> parameters in the function right above it. It seems some kind of margin, but in that case it should be <code>marginX</code> and <code>marginY</code>. However, I don't expect margins to change at every call: this should be a property of the canvas, it should not be a parameter.</p>\n<hr />\n<pre><code> for(let y = 0; y < map.length; y++){\n if(x*this.tileSize+xd<-this.tileSize){continue}\n</code></pre>\n<p>Here you show the readability of a line with whitespace and the one without. Always use whitespace:</p>\n<pre><code> if(x * this.tileSize + xd < -this.tileSize) {\n continue\n }\n</code></pre>\n<p>See what a difference it makes?</p>\n<hr />\n<p>Where is the testing of <code>y</code> and <code>yd</code>? Do you assume infinite space there? In that case, at least create a note / comment for it.</p>\n<hr />\n<pre><code> this.showImg(map[y][x], x*this.tileSize+xd, y*this.tileSize+yd);\n</code></pre>\n<p>The drawing of the map should not yet perform these calculations. It is much better to have a <code>drawTile</code> function that uses <code>x</code> and <code>y</code> for the map, and then retrieves the margins from the properties.</p>\n<hr />\n<p>It is highly recommended to separate calculations on the map, the calculations to retrieve images from the atlas and the calculations to perform the actual drawing as much as possible. This will save you an awful lot of trouble trying to understand the code later on, when the game starts to become more and more complex. Divide and conquer is not just a strategy when playing the game; it is also the best strategy during development.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T14:29:35.900",
"Id": "525318",
"Score": "0",
"body": "Ok, thanks so much! About the last answer, if I were to add a drawTile() function, would I pass in x and y as inputs to calculate in said function? I don't really get what you mean by 'retrieve margins from the properties', sorry."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T14:58:48.793",
"Id": "525321",
"Score": "0",
"body": "Yes, so you do the checking if you have to draw a tile in `renderMap`, and you calculate the actual place where to put the image in the `drawTile` functions. Maybe I misunderstood the `dx` and `dy` values - if the starting point of the map can change for every call to `renderMap` then they are maybe not margins and should indeed be parameters. Often you can avoid these kind of confusions by creating e.g. a `CanvasPosition(x,y)` class and then create a `CanvasPosition mapPosition` variable or similar. That way `x` and `y` are just `x` and `y` but the function of the coordinates is clear."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T15:02:06.953",
"Id": "525322",
"Score": "0",
"body": "Ok, I get it now. Thank you good sir!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T15:02:41.887",
"Id": "525323",
"Score": "0",
"body": "In that case you'd get e.g. `drawTile(tileIndex, positionOnMap, mapPositionOnCanvas)`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T14:09:52.293",
"Id": "265958",
"ParentId": "265946",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "265958",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T10:38:12.387",
"Id": "265946",
"Score": "2",
"Tags": [
"javascript",
"beginner"
],
"Title": "A renderer; JavaScript game beginnings"
}
|
265946
|
<p>I am working on a test infrastructure that can help developers in a web api project. Below I wrapped up assertion classes. However when we increase the number of verification classes then it will look weird like it does right now :)</p>
<p>Do you have any clear idea to refactor this code piece?</p>
<pre><code>public class TestModuleVerificationWrapper
{
private Lazy<CompanyTestVerificationWrapper> inCompany;
private Lazy<LookUpTestVerificationWrapper> inLookUp;
private Lazy<LookUpTypeTestVerificationWrapper> inLookUpType;
public CompanyTestVerificationWrapper InCompany => CreateVerificationWrapper<CompanyTestVerificationWrapper>(inCompany);
public LookUpTestVerificationWrapper InLookUp => CreateVerificationWrapper<LookUpTestVerificationWrapper>(inLookUp);
public LookUpTypeTestVerificationWrapper InLookUpType => CreateVerificationWrapper<LookUpTypeTestVerificationWrapper>(inLookUpType);
private T CreateVerificationWrapper<T>(Lazy<T> lazy)
{
if (lazy == null)
{
lazy = new Lazy<T>(() => Activator.CreateInstance<T>(), true);
}
if (!lazy.IsValueCreated)
{
return lazy.Value;
}
return lazy.Value;
}
}
public class CompanyTestVerificationWrapper
{
public CompanyTestVerification<T> WithResult<T>(T result) where T : class
{
return new CompanyTestVerification<T>(result);
}
}
public class LookUpTestVerificationWrapper
{
public LookUpTestVerification<T> WithResult<T>(T result) where T : class
{
return new LookUpTestVerification<T>(result);
}
}
public class LookUpTypeTestVerificationWrapper
{
public LookUpTypeTestVerification<T> WithResult<T>(T result) where T : class
{
return new LookUpTypeTestVerification<T>(result);
}
}
</code></pre>
<p>I use this class in another base class to wrap all modules like below</p>
<pre><code>public abstract class IntegrationTest : ApplicationFactory
{
private Lazy<TestModuleWrapper> when;
private Lazy<TestModuleVerificationWrapper> then;
public TestModuleWrapper When => GetWhen();
public TestModuleVerificationWrapper Then => GetThen();
private TestModuleWrapper GetWhen()
{
if (when is null)
{
when = new Lazy<TestModuleWrapper>(() => new TestModuleWrapper(base.Self()), true);
}
return when.Value;
}
private TestModuleVerificationWrapper GetThen()
{
if (then is null)
{
then = new Lazy<TestModuleVerificationWrapper>(() => new TestModuleVerificationWrapper(), true);
}
return then.Value;
}
}
</code></pre>
<p>And the usage sample is like below</p>
<pre><code>[Test]
public async Task CanList_OnePage_Company()
{
var result = await When.InCompany.IListCompanies(With.PageNumber(1).Items(10));
Then.InCompany.WithResult(result).ResultShouldBeLoaded()
.And.TotalCompanyCountShouldBe(20)
.And.CompanyCounOnPageShouldBe(10)
.And.PageNumberShouldBe(1);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T04:55:03.937",
"Id": "525378",
"Score": "1",
"body": "could you explain the purpose of these classes, and how and when it's going to be used. As it seems you're trying to create a unit test, while there are multiple testing tools already implemented and ready to use (XUnit, NUnit, ..etc), which you should consider using instead of re-inventing the wheels."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T06:22:57.640",
"Id": "525379",
"Score": "0",
"body": "@iSR5 thanks for your feedback and I added more explanations. You are right by the, I am trying to create an integration test on BDD approach with using NUnit. All assertions are used in the third code block, so it is not reinventing wheel"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T10:49:24.607",
"Id": "265947",
"Score": "0",
"Tags": [
"c#",
"integration-testing"
],
"Title": "Repeated generic type instances with generic method"
}
|
265947
|
<p>Below is a simple calculator program in which I'm using break statements to control the logic. I was wondering if this is overkill on the break statements or is it OK.</p>
<pre><code>while True:
try:
print("Choose operation(+ | - | * | / | Enter 'e' to exit)")
op=input()
if op!="+" and op!="-" and op!="*" and op!="/" and op!="e":
print("Invalid input, you must choose an option from the menu.")
break
elif op=="e":
break
else:
print(">")
val1=float(input(val1))
print(">")
val2=float(input(val2))
if op=="+":
print("= ", val1+val2)
elif op=="-":
print("= ", val1-val2)
elif op=="*":
print("= ", val1*val2)
else:
print("= ", val1/val2)
except ValueError:
print("Input must be numerical.")
break
except ZeroDivisionError:
print("Dividing by zero is undefined.")
break
exit()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T15:13:25.180",
"Id": "525325",
"Score": "0",
"body": "Welcome to Code Review! Your post looks fine, hope you get some good answers!"
}
] |
[
{
"body": "<h1>Choosing an Operation</h1>\n<p>You can use a dictionary, rather than <code>if/elif/else</code> statements to choose operations more cleanly:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from operator import add, sub, mul, truediv\n\nOPERATIONS = {\n '+': add,\n '-': sub,\n '*': mul,\n '/': truediv\n}\n\n# if an operation is present\nprint(OPERATIONS['+'](1, 2))\n3\n\n# otherwise\nprint(OPERATIONS['%'](1, 2))\nKeyError\n</code></pre>\n<p>Now, you can clean up your <code>if</code> statements, and get rid of most of your <code>if op ==</code> checks:</p>\n<pre class=\"lang-py prettyprint-override\"><code>op = input("Choose operation(+ | - | * | / | Enter 'e' to exit)\\n").strip()\n\nif op == 'e':\n print('Exiting')\n exit()\n\ntry:\n operation = OPERATIONS[op]\nexcept KeyError:\n print(f"{op} was an invalid choice")\n break\n\n~snip~\n\n# This is how you'd use that operation, since it is a function\ntry:\n print(operation(val1, val2))\nexcept ZeroDivisionError:\n print("Can't divide by zero!")\n</code></pre>\n<h1>Choosing <code>val1</code> and <code>val2</code></h1>\n<p>I think you made a typo by mistake and the argument to <code>input</code> was supposed to be <code>input('val1')</code> and <code>input('val2')</code>. Either way, I think it might be a bit cleaner to add a function here. This makes it easier to wrap up the possible <code>ValueErrors</code> that could come from generating your values on bad input:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def get_input_values():\n """\n Parse numerical input into floats for calculator operations\n """\n values = []\n\n for i in range(2):\n print('>')\n # this gives some visual space for the user to break up\n # the prompt from the actual input\n val = float(input(f'val{i}: ')\n values.append(val)\n\n return value\n\n\n# now you can do a try/except wrapping this function\n# and unpack the result\ntry:\n val1, val2 = get_input_values()\nexcept ValueError as e:\n print(e)\n exit()\n</code></pre>\n<p>You could even extend this to <code>N</code> values if you wanted to:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def get_input_values(N=2):\n ~snip~\n for i in range(N):\n # rest of function\n\ntry:\n values = get_input_values(5)\nexcept ValueError as e:\n ~snip~\n</code></pre>\n<h1>Adding a <code>main</code> function and <code>__name__</code> guard</h1>\n<p>This will help wrap your code up into a single function that can be called/looped/etc. It's cleaner and, for larger programs, makes it easier to find what runs the code. Also, an <code>if __name__ == "__main__"</code> guard allows you to import items from this code without it executing:</p>\n<pre class=\"lang-py prettyprint-override\"><code># OPERATIONS still lives in global scope here\nOPERATIONS = {\n '+': add,\n '-': sub,\n '*': mul,\n '/': truediv\n}\n\n\ndef main():\n op = input("Choose operation(+ | - | * | / | Enter 'e' to exit)\\n").strip()\n \n if op == 'e':\n print('Exiting')\n exit()\n\n try:\n operation = OPERATIONS[op]\n except KeyError:\n print(f"{op} was an invalid choice")\n break\n\n\n try:\n val1, val2 = get_input_values()\n except ValueError as e:\n print(e)\n exit()\n\n try:\n result = operation(val1, val2)\n except ZeroDivisionError:\n print("Can't divide by zero!")\n exit()\n else:\n print(result)\n\n\nif __name__ == "__main__":\n # you can move your loop down here now\n while True:\n main()\n \n \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T13:17:54.113",
"Id": "265954",
"ParentId": "265953",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T12:40:37.967",
"Id": "265953",
"Score": "3",
"Tags": [
"python",
"calculator"
],
"Title": "Basic calculator using break statements to control the logic"
}
|
265953
|
<p>I read about, that I only should have up to two parameters and a function should have about 10 lines. Now I am in trouble to achieve this. It is a Javascript/JSON thing in C#.</p>
<p>I have too many parameters and too many lines in a function and I would like to reduce it. I reduced it already, but what can I do better. I need all the parameters, because the DB needs them.</p>
<pre><code>public JsonResult AddFolder(int id, string structureId, string newFolderName, string parent)
{
int folderNumber = 0;
//parent folder id
int parentFolder = Convert.ToInt32(GetFolderId(id).Split('_')[0]);
//get current period
int period = GetLastPeriod();
//actual ISO date
string folderDate = Helper.ConvertToIsoDate(DateTime.Now.ToString().Split(' ')[0]);
if (period == -1)
{
throw new Exception(ErrorMessages.PeriodNotFound);
}
bool publish;
//implement publish true when it is parent - false when it is child
try
{
if (parent == "#")
{
publish = true;
structureId = AddNewParentFolderId(folderNumber);
}
else
{
publish = false;
structureId = AddNewChildFolderId(structureId, parentFolder, parent);
}
}
catch (Exception ex)
{
Logging.LogToFile(ex, 3);
return Json(new
{
success = false,
message = ErrorMessages.CountFolderNotPossible
}, JsonRequestBehavior.AllowGet);
}
if (folderNumber < 0)
{
Logging.LogToFile("MrNumber has to be > 0", 3);
base.Response.StatusCode = 500;
return Json(new
{
errorAddFolderMsg = ErrorMessages.MrNumberNotFound
}, JsonRequestBehavior.AllowGet);
}
id = _folderRepository.AddFolder(structureId, parent, period, folderNumber, newFolderName, publish, folderDate);
if (id == -1)
{
Logging.LogToFile("Folder ID is -1", 3);
base.Response.StatusCode = 500;
return Json(new
{
success = false,
errorAddFolderMsg = ErrorMessages.AddFolderNotPossible
}, JsonRequestBehavior.AllowGet);
}
return Json(new
{
id = id,
folderId = structureId,
newFolderName = newFolderName,
parent = parent,
period = period
});
}
</code></pre>
<p>Furthermore I am not sure about my namings.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T19:47:34.310",
"Id": "525353",
"Score": "1",
"body": "what is the difference between strcture id and folder id ? could you provide a data sample data for both ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T19:49:23.037",
"Id": "525354",
"Score": "1",
"body": "also, please provide `AddNewParentFolderId` and `AddNewChildFolderId` codes as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T09:03:07.193",
"Id": "525444",
"Score": "3",
"body": "Don't think of guidelines as inescapable hard rules, because they are not. There is no hard limit on method arguments or method body line count. That's not to say you don't have to look for improvements, but it's a matter of setting realistic expectations because otherwise you are prone to falling into an overkill trap."
}
] |
[
{
"body": "<p>The whole <code>try block( //implement publish true when it is parent - false when it is child)</code> can be reduced to one line.</p>\n<pre><code>try\n{\n structureId = parent == # ? AddNewParentFolderId(...) : AddNewChildFolderId(...);\n}\ncatch\n{\n}\n</code></pre>\n<p>No need of the <code>publish</code> variable.<br />\nUse <code>"parent == #"</code> expression in place of publish variable.</p>\n<p>To reduce the function parameters create an object and include the related parameters as the objects properties.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T20:11:43.470",
"Id": "266007",
"ParentId": "265957",
"Score": "0"
}
},
{
"body": "<p>To amplify what's already been stated in comments, the concept of having two parameters and approximately ten lines of code per function (it's called a method in C# by the way), is really just a guideline. Its purpose is to make you think about the following points (there are more, but these are some of the primary points):</p>\n<ul>\n<li>Am I following OOP?</li>\n<li>Does my method have a single responsibility?</li>\n<li>Is my method easy to understand?</li>\n</ul>\n<p>Simply put, your method should serve one purpose, it should be concise and easy to maintain, and since you're using a language that supports OOP, you should use it when needed.</p>\n<h4> Parameter Count</h4>\n<p>I wouldn't personally say that you have too many parameters for your method. The golden rule of thumb is actually a cap of seven, but this isn't software driven, it's <a href=\"https://phys.org/news/2009-11-brain-magic.html\" rel=\"nofollow noreferrer\">a limitation for most human beings</a>:</p>\n<blockquote>\n<p>Countless psychological experiments have shown that, on average, the longest sequence a normal person can recall on the fly contains about seven items. This limit, which psychologists dubbed the "magical number seven" when they discovered it in the 1950s, is the typical capacity of what's called the brain's working memory.</p>\n</blockquote>\n<p>There are also several posts on Stack Exchange (<a href=\"https://softwareengineering.stackexchange.com/questions/145055/are-there-guidelines-on-how-many-parameters-a-function-should-accept\">here</a> and <a href=\"https://stackoverflow.com/questions/12431932/how-many-parameters-in-c-sharp-method-are-acceptable\">here</a> are two good ones) asking about the topic of parameter count. The general consensus is that as you approach <em>four</em> parameters, you're either starting to do too much, or you should be creating a model to represent those parameters.</p>\n<p>In your particular case, I think you're fine, count wise.</p>\n<h4> Line Count</h4>\n<p>Similar to your parameter counts, I can't say you have <em>too many</em> lines. However, I will say that your method isn't focused. It currently has the following responsibilities:</p>\n<pre><code>- Get a new structure ID.\n- Attempt to add a new folder to the repo.\n- Generate error response.\n- Generate full response.\n</code></pre>\n<p>Why not separate those into their own methods?</p>\n<h4> Data Models</h4>\n<p>With all of the above in mind, why not create two new data models:</p>\n<pre><code>public sealed class FolderSummary {\n public int FolderId { get; set; }\n public string StructureId { get; set; }\n public string FolderName { get; set; }\n public string Parent { get; set; }\n public int Period { get; set; }\n}\npublic sealed class RepoResponse<T> {\n public bool Success { get; set; }\n public string Message { get; set; }\n public T Data { get; set; }\n}\n</code></pre>\n<p>You'll come to find that you can utilize <code>FolderSummary</code> to call <code>AddFolder</code>, and make your return data strongly typed:</p>\n<pre><code>public JsonResult AddFolder(FolderSummary summary) {\n ...\n return Json(new FolderSummary(...));\n}\n</code></pre>\n<p>Additionally, you can utilize <code>RepoResponse</code> to handle error data <em>and</em> the full response at the same time, adding even further consistency to your output:</p>\n<pre><code>public JsonResult AddFolder(FolderSummary summary) {\n ...\n catch (Exception ex) {\n Logging.LogToFile(ex, 3);\n return Json(new RepoResult<string>\n {\n Success = false,\n Message = ErrorMessages.CountFolderNotPossible,\n Data = structureId\n }, JsonRequestBehavior.AllowGet);\n }\n ...\n return Json(new RepoResult<FolderSummary> { Data = new FolderSummary(...) });\n</code></pre>\n<h4> Results</h4>\n<p>I took the liberty to implement everything I previously mentioned to demonstrate it in action:</p>\n<pre><code>public JsonResult AddFolderToRepo(FolderSummary summary) {\n // Nothing prior to this check impacts the check itself, so do it first and get it out of the way since you're throwing an exception.\n if (!TryGetLastPeriod(out int period))\n throw new Exception(ErrorMessages.PeriodNotFound);\n\n // Create a variable for storing the folder number.\n int folderNumber = 0;\n\n // Create a generic response to handle errors and the full data as part of the JsonResult.\n RepoResponse<object> result = null;\n\n // Get the structure ID.\n result = TryGetStructureId(folderNumber, summary);\n if (result.Success) {\n\n // Save the new structure ID and attempt to add the folder.\n string newStructureId = result.Data;\n result = TryAddFolderToRepo(result.Data, folderNumber, summary);\n if (result.Success) {\n int newId = result.Data;\n\n // Update the result data to the new folder summary\n result.Data = new FolderSummary {\n FolderId = newId,\n StructureId = newStructureId,\n FolderName = summary.FolderName,\n Parent = summary.Parent,\n Period = period\n };\n }\n }\n\n // Return the structured response.\n if (result.Success)\n return Json(result);\n else\n return Json(result, JsonRequestBehavior.AllowGet);\n}\nprivate bool TryGetLastPeriod(out int period) {\n period = GetLastPeriod();\n return period >= 0;\n}\nprivate RepoResponse<string> TryGetStructureId(int folderNumber, FolderSummary summary) {\n string resultMessage = string.Empty;\n string newStructureId = string.Empty;\n try {\n // Attempt to get the folder ID from the summary.\n if (int.TryParse(GetFolderId(summary.Id).Split('_')[0], out int parentFolderId)) {\n // Attempt to get the structure ID.\n if (summary.Parent.Equals("#", StringComparison.InvariantCultureIgnoreCase))\n newStructureId = AddNewParentFolderId(folderNumber);\n else\n newStructureId = AddNewChildFolderId(summary.StructureId, parentFolderId, summary.Parent);\n }\n } catch (Exception e) {\n Logging.LogToFile(e, 3);\n resultMessage = ErrorMessages.CountFolderNotPossible;\n }\n\n return new RepoResponse<string> {\n Success = !string.IsNullOrWhiteSpace(newStructureId),\n Message = resultMessage,\n Data = newStructureId\n };\n}\nprivate RepoResponse<int> TryAddFolderToRepo(string newStructureId, int folderNumber, FolderSummary summary) {\n string resultMessage = string.Empty;\n int newId = -1;\n try {\n if (folderNumber > 0) {\n string isoDate = Helper.ConvertToIsoDate(DateTime.Now.ToString().Split(' ')[0]);\n bool shouldPublish = summary.Parent.Equals("#", StringComparison.InvariantCultureIgnoreCase);\n newId = _folderRepository.AddFolder(newStructureId, summary.Parent, summary.Period,\n folderNumber, summary.FolderName, shouldPublish, isoDate);\n } else {\n Logging.LogToFile("MrNumber has to be > 0", 3);\n Response.StatusCode = 500;\n resultMessage = ErrorMessages.MrNumberNotFound;\n }\n } catch (Exception e) {\n Logging.LogToFile(e, 3);\n resultMessage = ErrorMessages.AddFolderNotPossible;\n }\n\n return new RepoResponse<int> {\n Success = newId >= 0,\n Message = resultMessage,\n\n // Return folder number if we blew up on folder number.\n Data = folderNumber > 0 ? newId : folderNumber\n }\n}\n</code></pre>\n<hr />\n<p><em><strong>Note</strong>: There may be spelling and syntactical errors in the code snippets due to me typing this up quickly. However, I believe the message is clear, so, I'll entrust you to resolve those.</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T14:05:17.317",
"Id": "526691",
"Score": "0",
"body": "Thank you for your answer. So would you furthermore say, that I can make a own Model for _folderRepo.Addfolder(AddFolderModel newFolder)? Or is this bad practice?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T15:29:53.050",
"Id": "526696",
"Score": "0",
"body": "@SpedoDeLaRossa assuming that `_folderRepository` is an instance of a type that *you* created, then yes, you could create a model for it; however, the signature could be as simple as `summary, newStructureId, folderNumber, publish, isoDate`, not really a need for a whole new model there IMO because it currently appears rather niche."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T16:59:57.477",
"Id": "266143",
"ParentId": "265957",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "266143",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T14:06:54.467",
"Id": "265957",
"Score": "1",
"Tags": [
"c#",
"json"
],
"Title": "Add a folder via JSON"
}
|
265957
|
<p>I have for some time been frustrated by the limitations around enumerations in VBA. Googling didn't find anything really simple and comprehensive. So after a bit of head scratching I came up with the following code which provides a neat intellisense based solution for managing enums to allow easy access to</p>
<ul>
<li>member names</li>
<li>counting members</li>
<li>enumerating members correctly</li>
<li>testing if an enum member exists</li>
</ul>
<p>The code is contained in a Class with a PredeclaredId and the Class Name used was Enums. Most of what I've achieved could be done just using a Scripting.Dictionary, but you would not get the intellisense that the code below provides.</p>
<pre><code>Option Explicit
'@PredeclaredId
'@Exposed
Public Enum EnumAction
AsEnum
AsString
AsExists
AsDictionary
AsCount
End Enum
Public Enum TestingEnum
'AsProperty is assigned -1 because it is not included in the backing dictionary
' and we want the enummeration to start at 0 unless defined otherwise
AsProperty = -1
Apples
Oranges
Cars
Lemons
Trees
Giraffes
End Enum
Private Type Enumerations
Testing As Scripting.Dictionary
End Type
Private e As Enumerations
Private Sub Class_Initialize()
If Not Me Is Enums Then
VBA.Err.Raise _
17, _
"Enumerations.ClassInitialize", _
"Class Enums:New'ed Instances of Class Enums are not allowed"
End If
End Sub
Private Sub PopulateTesting()
Set e.Testing = New Scripting.Dictionary
With e.Testing
' Note: AsProperty is not included in the dictionary
.Add Apples, "Apples"
.Add Oranges, "Oranges"
.Add Cars, "Cars"
.Add Lemons, "Lemons"
.Add Trees, "Trees"
.Add Giraffes, "Giraffes"
End With
End Sub
Public Property Get Testing(ByVal ipEnum As TestingEnum, Optional ByVal ipAction As EnumAction = EnumAction.AsEnum) As Variant
If e.Testing Is Nothing Then PopulateTesting
Select Case ipAction
Case EnumAction.AsEnum
Testing = ipEnum
Case EnumAction.AsString
Testing = e.Testing.Item(ipEnum)
Case EnumAction.AsExists
Testing = e.Testing.Exists(ipEnum)
Case EnumAction.AsCount
Testing = e.Testing.Count
Case EnumAction.AsDictionary
Dim myDictionary As Scripting.Dictionary
Set myDictionary = New Scripting.Dictionary
Dim myKey As Variant
For Each myKey In e.Testing
myDictionary.Add myKey, e.Testing.Item(myKey)
Next
Set Testing = myDictionary
End Select
End Property
</code></pre>
<p>Usage</p>
<pre><code>Public Sub Test()
Const Bannannas As Long = 42
Debug.Print "Enum value of lemons is 3", Enums.Testing(Lemons)
Debug.Print "String is Lemons", Enums.Testing(Lemons, AsString)
Debug.Print "Bannannas are False", Enums.Testing(Bannannas, AsExists)
' The AsProperty member is the preferred awkwardness
' as it is a 'Foreign' member just used to make the
' intellisense a bit more sensible.
' in practise any enumeration member could be used as
' the count and dictionary cases ignore the input enum.
Debug.Print "Count is 6", Enums.Testing(AsProperty, AsCount)
Dim myKey As Variant
Dim myDictionary As Scripting.Dictionary
Set myDictionary = Enums.Testing(AsProperty, AsDictionary)
For Each myKey In myDictionary
Debug.Print myKey, myDictionary.Item(myKey)
Next
Dim mykeys As Variant
mykeys = Enums.Testing(AsProperty, AsDictionary).Keys
Dim myvalues As Variant
myvalues = Enums.Testing(AsProperty, AsDictionary).Items
Debug.Print "Apples are apples", myDictionary.Item(Enums.Testing(Apples))
myDictionary.Item(Enums.Testing(Apples)) = "Plums"
Debug.Print "Apples are plums", myDictionary.Item(Enums.Testing(Apples))
Debug.Print "Apples are apples", Enums.Testing(Apples, AsString)
End Sub
</code></pre>
<p>test output</p>
<pre><code>Enum value of lemons is 3 3
String is Lemons Lemons
Test is False False
Count is 6 6
0 Apples
1 Oranges
2 Cars
3 Lemons
4 Trees
5 Giraffes
Apples are apples Apples
Apples are plums Plums
Apples are apples Apples
</code></pre>
<p>There are some awkwardnesses with the code above</p>
<ul>
<li><p>no support for enums as default values for optional parameters</p>
</li>
<li><p>no assignment of enums to constants</p>
</li>
<li><p>a Local variable could be defined with the same name as an enum member but with a non existing, or worse, alternative value to the enumeration member</p>
</li>
<li><p>The use of the 'AsProperty' 'Foreign' member of the enumeration (partially handled by not including that member in the backing scripting.dictionary.</p>
</li>
</ul>
<p>I'd welcome any comments or suggestions for improvements.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T17:42:55.417",
"Id": "525346",
"Score": "0",
"body": "`AsProperty` is not defined anywhere - is it supposed to be a public member of each enum, for example a member of `Enum Testing`? `AsCount` is not defined or implemented in the select case statement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T17:46:56.063",
"Id": "525347",
"Score": "1",
"body": "Apologies. I had two version going, one in Word and one in twinbasic (as word was acting up). Correct version is now uploaded."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T18:50:22.323",
"Id": "525351",
"Score": "0",
"body": "A solution I've used in the past is an oldie, but has always provided what I need from the [daily dose](http://dailydoseofexcel.com/archives/2010/07/08/class-property-fixed-values/). How would your solution compare?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T07:58:39.737",
"Id": "525383",
"Score": "0",
"body": "@Freeflow haha just to be clear, I didn't mean your statement of assumptions was lazy, I meant you were lazy loading the enums - i.e. only registering them as required one by one rather than all at once in an initialise step."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T08:03:51.383",
"Id": "525384",
"Score": "0",
"body": "Also if you want feedback on the updated code then maybe put it in another question? For example couldn't that whole `Select Case` block still become a Private Function which takes a `Dictionary`, `ipEnum` and `ipAction` all as arguments. Since it is internal use only, `ipEnum` could be declared as Long in that function whilst still keeping the public interface strongly typed with intellisense. As you're probably aware, an Enum is just a Long under the hood, and callers can pass any long to your function even if that function purports to accept only a strict range defined by the enum."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T08:08:19.460",
"Id": "525385",
"Score": "0",
"body": "@PeterT I guess the drawback for portability is that would require a different class for each enum. If you also want to add some standard code like `.Count` or `.AsDict` then you'd get a lot of copypasta that's basically identical between instances."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T10:37:58.587",
"Id": "525390",
"Score": "0",
"body": "@Greedo Yes, I understood the reference to lazy initialization. But I still think your comments made me realise I''d been lazy in framing my question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T11:49:15.217",
"Id": "525392",
"Score": "1",
"body": "I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T14:35:39.580",
"Id": "525397",
"Score": "1",
"body": "@Greedo - I certainly agree that a separate class would be required for each enum, and your \"standard\" properties are good suggestions. This whole discussion is based on a very weak implementation of enums in VBA to begin with, and many solutions/fixes/workarounds are proposed to \"fix\" it. I think it's more of a \"pick your poison\" situation in which we'll have to decide what code to drag along from project to project to suit our needs -- unless and until VBA is redesigned for more comprehensive enum support (which will never happen!). So where is the built-in Python automation support???? ;)"
}
] |
[
{
"body": "<p>Some thought in no particular order:</p>\n<hr />\n<p>Could the <code>Enums</code> predeclared Class be a standard module? That would avoid the need to have this check:</p>\n<blockquote>\n<pre><code>Private Sub Class_Initialize()\n \n If Not Me Is Enums Then\n \n VBA.Err.Raise _\n 17, _\n "Enumerations.ClassInitialize", _\n "Class Enums:New'ed Instances of Class Enums are not allowed"\n \n End If\n \nEnd Sub\n</code></pre>\n</blockquote>\n<p>And would make prepending <code>Enums</code> optional. The downside would be <code>PopulateTesting</code> isn't automatically called (I assume you meant to call it in <code>Class_Initialize</code>), but you can call it upon first invocation of <code>Public Property Get Testing</code> which would save a hit at runtime if you have many enums to populate but only a few are actually required. <strong>edit: in your updated code I see you've gone with the lazy populate option</strong></p>\n<p>Incidentally if we're being perfectionists, I would rather see this above code written as a <a href=\"https://github.com/rubberduck-vba/MVVM/blob/02a486f04be79c5fcff468b055f422d95cb6633c/src/GuardClauses.bas#L25-L32\" rel=\"nofollow noreferrer\">named guard clause</a> - and why magic <code>17</code>?</p>\n<hr />\n<blockquote>\n<pre><code>Private Type Enumerations\n \n Testing As Scripting.Dictionary\n \nEnd Type\n\nPrivate e As Enumerations\n</code></pre>\n</blockquote>\n<p>Why is this module level? If I add a second enum, why does it need to know about the <code>e.Testing</code> dictionary? I'd use a Static variable inside the sub.</p>\n<p>Also I'd probably rename <code>e.Testing</code> to <code>this.TestingMap</code> or even <code>this.TestingNamesFromEnumValues</code>.</p>\n<hr />\n<p>There's a lot of boilerplate adding a new Enum to this class, particularly this big select case block:</p>\n<blockquote>\n<pre><code>Select Case ipAction\n \n Case EnumAction.AsEnum\n \n Testing = ipEnum\n \n Case EnumAction.AsString\n \n Testing = e.Testing.Item(ipEnum)\n \n Case EnumAction.AsExists\n \n Testing = e.Testing.Exists(ipEnum)\n \n Case EnumAction.AsCount\n \n Testing = e.Testing.Count\n \n Case EnumAction.AsDictionary\n \n Dim myDictionary As Scripting.Dictionary\n Set myDictionary = New Scripting.Dictionary\n \n Dim myKey As Variant\n For Each myKey In e.Testing\n \n myDictionary.Add myKey, e.Testing.Item(myKey)\n \n Next\n \n Set Testing = myDictionary\n \nEnd Select\n</code></pre>\n</blockquote>\n<p>... wouldn't want to write that out too many times! This could be extracted into a private function which takes the dictionary/ enum name as a parameter - maybe the class stores a collection of <code>enumName:lookupDictionary</code> pairs rather than hard coding them in a UDT.</p>\n<hr />\n<p>The EnumAction stuff is kinda weird, I see why you've done it but honestly these <code>actions</code> are just begging to be methods of a class.</p>\n<p>I think another approach here would be to have 1 class for each enum, maybe even predeclared and shadowing the enum name, although a strongly typed member of a global collection could be a neater API (so a <code>property get Testing() As TestingEnum</code>). You can then just write some helper functions for letting these classes register their members somewhere, quickly look them up or look up properties about them, and then the enum classes can use these to implement the actions you want without repeating too much boilerplate. For standard methods like <code>Count</code> or <code>AsDictionary</code>, your Enum objects could implement a standard interface, perhaps with an easy accessor for the interface:</p>\n<h3>Interface: <code>IEnum</code></h3>\n<pre><code>Public Property Get Count() As Long\n\nPublic Function AsDictionary() As Dictionary\n\n</code></pre>\n<h3>Class: <code>TestingEnum</code></h3>\n<pre><code>Public Property Get Info() As IEnum\n Set Info = Me\nEnd Property\n</code></pre>\n<p>then you can do <code>TestingEnum.Info.Count</code> for example. Or a caller can cast to <code>IEnum</code> and call <code>.Count</code> themselves. You get the idea.</p>\n<hr />\n<p>Scripting.Dictionary doesn't expose an <code>IEnumVariant</code> member like Collections do, but you could expose a <a href=\"https://stackoverflow.com/a/52261687/6609896\">generator function</a> to allow your enums to be used in a for each loop</p>\n<hr />\n<blockquote>\n<pre><code>Public Enum TestingEnum\n \n 'AsProperty is assigned -1 because it is not included in the backing dictionary\n ' and we want the enummeration to start at 0 unless defined otherwise\n AsProperty = -1\n Apples\n Oranges\n Cars\n Lemons\n Trees\n Giraffes\n \nEnd Enum\n</code></pre>\n</blockquote>\n<p>I would expose a constant from your class so users know <code>-1</code> isn't a hard requirement:</p>\n<pre><code>Public Const AsPropertyEnumValue As Long = -1 'or anything really\n'...\nPublic Enum TestingEnum\n AsProperty = AsPropertyEnumValue \n</code></pre>\n<p>Having a default 0 starting position is a weird requirement I think you should scrap, if the user wants Apples to be 0, they should set it to zero. Abstracting away the implementation of this <code>AsProperty</code> member will encourage the user not to assume any particular starting value.</p>\n<p>If you switch to methods defined in an interface rather than by this Action parameter then the <code>AsProperty</code> member can be removed or made <code>[_hidden]</code> as an implementation detail.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T18:24:13.987",
"Id": "265964",
"ParentId": "265962",
"Score": "1"
}
},
{
"body": "<p>I think everybody is frustrated with how enumerations are working in VBA. Not the richest language syntax. As @PeterT mentioned in the comments we all just need to "pick our poison".</p>\n<p>There is always some functionality around a single Enum and that could be a simple function or a group of related modules/classes. I would not group all the enums inside a single predeclared class or even a standard module. What if you need to reuse the functionality related to an enum inside another project? You would then need to copy the Enums class/module to that separate project and then trim the extra enums isn't it? Or even worse leave all the enums in there because you don't have the time to do the trimming.</p>\n<p>On the other hand, there is one good reason I would not wrap each enum in it's own class just for Intellisense. What if I have 50 enums? Should I add 50 classes to a project which is suffering anyway from having a single class per code module and no inheritance? I would not do it but that's just my subjective point of view. It's difficult to navigate a project even with help from Rubberduck (and even worse without) so I try to minimize the number of code modules.</p>\n<p>I've used another "poison" over the years and it seemed to serve me well and of course that does not mean it's better than yours, it's just different and works for me.</p>\n<p>Before I start, I must say that the <code>AsEnum</code> feature of your code can be removed because something like <code>Enums.Testing(77)</code> will simply return 77. It's like "give me back the value I gave you" kind of thing really.</p>\n<p><strong>A different approach</strong></p>\n<p>I am using a general wrapper class but it could be a standard module having the same UDT inside. The reason I prefer a class is because I do not want to pass around a UDT <code>ByRef</code> whenever I write the "wrapper functions" (more on that below). Also, I am not using a Dictionary as I usually do not want to be bound to using just Windows and don't want an extra library reference so instead I use 2 collections for mapping.\nI have a general class called <code>EnumWrapper</code> with the following code:</p>\n<pre><code>Option Explicit\n\nPrivate Type EnumLists\n arrEnum() As Variant\n arrText() As Variant\n enumToText As Collection\n textToEnum As Collection\nEnd Type\n\nPrivate m_eLists As EnumLists\n\nPublic Sub Init(ByRef arrEnum As Variant, ByRef arrText As Variant)\n With m_eLists\n .arrEnum = arrEnum\n .arrText = arrText\n '\n Set .enumToText = New Collection\n Set .textToEnum = New Collection\n '\n Dim i As Long\n Dim textValue As String\n Dim enumValue As Long\n '\n For i = LBound(.arrEnum) To UBound(.arrEnum)\n enumValue = .arrEnum(i)\n textValue = .arrText(i)\n '\n .enumToText.Add textValue, CStr(enumValue)\n .textToEnum.Add enumValue, textValue\n Next i\n End With\nEnd Sub\n\nPublic Function Count() As Long\n Count = m_eLists.enumToText.Count\nEnd Function\n\nPublic Function Exists(ByVal enumValue As Long) As Boolean\n On Error Resume Next\n m_eLists.enumToText.Item CStr(enumValue)\n Exists = (Err.Number = 0)\n On Error GoTo 0\nEnd Function\n\nPublic Function FromString(ByVal textValue As String _\n , Optional ByVal valueIfNotFound As Long) As Long\n On Error Resume Next\n FromString = m_eLists.textToEnum(textValue)\n If Err.Number <> 0 Then FromString = valueIfNotFound\n On Error GoTo 0\nEnd Function\n\nPublic Function Items() As Variant()\n Items = m_eLists.arrEnum\nEnd Function\n\nPublic Function Self() As EnumWrapper\n Set Self = Me\nEnd Function\n\nPublic Function Texts() As Variant()\n Texts = m_eLists.arrText\nEnd Function\n\nPublic Function ToString(ByVal enumValue As Long _\n , Optional ByVal valueIfNotFound As String) As String\n On Error Resume Next\n ToString = m_eLists.enumToText(CStr(enumValue))\n If Err.Number <> 0 Then ToString = valueIfNotFound\n On Error GoTo 0\nEnd Function\n</code></pre>\n<p>We could write more code for validation and raising errors in the <code>Init</code> method but I kept it simple for the purpose of this answer.</p>\n<p>I then proceed to wrap an instance of this class for each enum that I need so I get the proper Intellisense. For example for your <code>TestingEnum</code> I would do the following wherever the enum is actually placed (class/document/standard module - doesn't really matter):</p>\n<pre><code>Option Explicit\n\nPublic Enum TestingEnum\n InvalidValue = -1\n Apples\n Oranges\n Cars\n Lemons\n Trees\n Giraffes\nEnd Enum\n\nPrivate Function GetTestingWrapper() As EnumWrapper\n Static eWrapper As EnumWrapper\n '\n If eWrapper Is Nothing Then\n Set eWrapper = New EnumWrapper\n eWrapper.Init Array(Apples, Oranges, Cars, Lemons, Trees, Giraffes) _\n , Array("Apples", "Oranges", "Cars", "Lemons", "Trees", "Giraffes")\n End If\n Set GetTestingWrapper = eWrapper\nEnd Function\nPublic Function TestingEnumToString(ByVal enumValue As TestingEnum) As String\n TestingEnumToString = GetTestingWrapper.ToString(enumValue) 'Could use optional parameter to return specific string on failure\nEnd Function\nPublic Function TestingEnumFromString(ByVal textValue As String) As TestingEnum\n TestingEnumFromString = GetTestingWrapper.FromString(textValue, InvalidValue)\nEnd Function\nPublic Function TestingEnumExists(ByVal enumValue As TestingEnum) As Boolean\n TestingEnumExists = GetTestingWrapper.Exists(enumValue)\nEnd Function\nPublic Function TestingEnumCount() As Long\n TestingEnumCount = GetTestingWrapper.Count\nEnd Function\nPublic Function TestingEnumItems() As Variant()\n TestingEnumItems = GetTestingWrapper.Items\nEnd Function\nPublic Function TestingEnumTexts() As Variant()\n TestingEnumTexts = GetTestingWrapper.Texts\nEnd Function\n</code></pre>\n<p>Typing <code>TestingEnum</code> would make the Intellisense look like this:<br />\n<a href=\"https://i.stack.imgur.com/9Hnk3.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9Hnk3.png\" alt=\"enter image description here\" /></a></p>\n<p>All methods are easy to find and can't really forget their names as they all start with the enum name.</p>\n<p>An example of method call:<br />\n<a href=\"https://i.stack.imgur.com/ypM1Q.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ypM1Q.png\" alt=\"enter image description here\" /></a></p>\n<p>Of course, sometimes you don't need all of these "wrapper" methods so you would just write the ones you need which helps minimize the bloating.</p>\n<p>Your tests would then become:</p>\n<pre><code>Option Explicit\n\nPublic Sub Test()\n Const Bannannas As Long = 42\n Debug.Print "Enum value of lemons is 3", TestingEnumFromString("Lemons")\n Debug.Print "String is Lemons", TestingEnumToString(Lemons)\n Debug.Print "Bannannas are False", TestingEnumExists(Bannannas)\n Debug.Print "Count is 6", TestingEnumCount()\n \n Dim myEnumValue As Variant\n For Each myEnumValue In TestingEnumItems()\n Debug.Print myEnumValue, TestingEnumToString(myEnumValue)\n Next\n \n Dim myEnums As Variant\n myEnums = TestingEnumItems()\n \n Dim myTexts As Variant\n myTexts = TestingEnumTexts()\n \n Debug.Print "Apples are apples", TestingEnumToString(Apples)\nEnd Sub\n</code></pre>\n<p>I removed the "replace apples with plums" part as I don't see the point of that. The purpose of an Enum is to be "constant". If there is a need to change the texts that should happen in the <code>GetTestingWrapper</code> method and of course those values could come from a different source (like a table).</p>\n<p>Of course this approach is bloating the global namespace but I can live with that as long as I gain the advantage of placing the code for each enum in the module/class where it actually belongs along other related functionality and this helps with portability with the downside that I also need to carry the <code>EnumWrapper</code> class module.</p>\n<p>The bloating would happen anyway even if you were to add all enums to a single class or a separate class per enum because you still need the Intellisense at least for the <code>ToString</code>, <code>FromString</code> and <code>Exists</code> methods. Less true for the <code>Count</code>, <code>Items</code> and <code>Texts</code> methods but this is just part of this approach.</p>\n<p>Having 3 lines of code for each "wrapper" method (out of which one is the function definition and one is <code>End Function</code>) is not really a big deal and overall seems cleaner to my subjective view.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T18:13:49.923",
"Id": "525603",
"Score": "0",
"body": "\"Before I start, I must say that the AsEnum feature of your code can be removed because something like Enums.Testing(77) will simply return 77. It's like \"give me back the value I gave you\" kind of thing really.\" You really are missing the point with this comment. The whole point of this function, is that the intellisense for the enumeration is presented as an option at the dot rather than as a separate entity somewhere in VBA unnamespaceland."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T06:26:44.890",
"Id": "525633",
"Score": "0",
"body": "@Freeflow So, let me get this straight. If the action is ```AsEnum``` then your method returns ```Testing = ipEnum``` the same value being passed. This is what I was reffering to. Since ```AsEnum``` is 0 then ```Testing(77)``` is the same as ```Testing(77,AsEnum)``` which returns 77. This simply returns the value you pass. I see there is Intellinsense. But for what? Why do you need a function that returns the value you pass in? I expressed exactly what I wanted to say. Again, I am only referring when the action is set to ```AsEnum```. I can see how ```AsString``` and the others are useful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T06:39:39.780",
"Id": "525634",
"Score": "0",
"body": "@Freeflow It only clicked with me now what you meant by Intellisense. Why would you use ```Testing(...,AsEnum)``` to get the Intellisense instead of simply typing the name of the Enum and then the dot like in ```TestingEnum.```. Second one is much cleaner and it's like calling a constant instead of unnecesarilly running a method that returns the value you pass in."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T11:56:27.713",
"Id": "525662",
"Score": "0",
"body": "Things have probably got slightly confused by now compared to the original implementation. For Enumerations, they are not visible in the VBA Ide project explorer so you need to look at source code to discover them. Once you know the name then as you say you can just use enumerationname.membername. However, the AsEnum public method means that for an object, you get AsEnum listed as a method and then a list of the enum members. Additionally if you are offering other options, such as toString, IsMember etc then asenum quite clearly states what you are getting."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T12:16:38.620",
"Id": "525667",
"Score": "0",
"body": "@Freeflow Makes more sense now. Yes, you cannot see an Enum in the Project Explorer but if you have too many enums then it would be overkill to make one Predeclared Class for each. The project would get really cluttered. On the other hand, combining all enums into a single class will hurt your project when it comes to portability and not to mention that unrelated enums will become tightly coupled (along with their related functionality). I think you must decide the best approach by having the long-term maintainability and support of the project in mind and that might as well be your approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T12:17:47.790",
"Id": "525668",
"Score": "0",
"body": "@Freeflow I do hope that the approach I suggested makes sense at least from the perspective of keeping enums and related functionality independent from each other."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T13:21:38.157",
"Id": "266033",
"ParentId": "265962",
"Score": "1"
}
},
{
"body": "<p>Since VBA/VB6 treats <code>Enums</code> as <code>Longs</code> under the hood, so I suggest a generic wrapper to which you can supply your <code>Enums</code> and their string representations. This way you avoid having to have a separate class for each one.</p>\n<p>Let's start with a generic class that serves a two-way or "bi-directional" map, which I have aptly named <code>BiDirectionalMap</code>.</p>\n<p><code>BiDirectionalMap.cls</code></p>\n<pre><code>VERSION 1.0 CLASS\nBEGIN\n MultiUse = -1 'True\nEND\nAttribute VB_Name = "BiDirectionalMap"\nAttribute VB_GlobalNameSpace = False\nAttribute VB_Creatable = False\nAttribute VB_PredeclaredId = True\nAttribute VB_Exposed = True\n'@Exposed\n'@PredeclaredId\nOption Explicit\n\nPrivate Enum BiDirectionalMapErrors\n MismatchedLength = vbObjectError + 1024\n SetsNotIterable\n KeyDoesNotExist\n ValueDoesNotExist\n KeyOrValueDoesNotExist = KeyDoesNotExist Or ValueDoesNotExist\nEnd Enum\n\nPrivate Const MismatchedLengthErrorDesc As String = "Keys and Values must have have the same number of values (i.e. one-to-one correspondence)."\nPrivate Const SetsNotIterableErrorDesc As String = "Key(s), Value(s), or both are is not iterable. For single values, wrap in 'Array()' function."\nPrivate Const DoesNotExistErrorDesc As String = "does not exist. Ensure that the data type is consistent with the original "\n\nPrivate Type TBiDirectionalMap\n KeyCompareMethod As VBA.VbCompareMethod\n ValueCompareMethod As VBA.VbCompareMethod\n\n KeysDict As Scripting.Dictionary\n ValuesDict As Scripting.Dictionary\nEnd Type\n\nPrivate this As TBiDirectionalMap\n\nPublic Function Create(ByVal keys As Variant, ByVal values As Variant, _ \nOptional ByVal keyCompareMethod As VBA.VbCompareMethod = vbBinaryCompare, _ \nOptional ByVal valueCompareMethod As VBA.VbCompareMethod = vbBinaryCompare) As BiDirectionalMap\n Errors.GuardNonDefaultInstance Me, BiDirectionalMap, VBA.TypeName(Me)\n\n Dim result As BiDirectionalMap\n Set result = New BiDirectionalMap\n result.KeyCompareMethod = keyCompareMethod\n result.ValueCompareMethod = valueCompareMethod\n\n result.AddRange keys, values\n\n Set Create = result\nEnd Function\n\nPublic Property Get KeyCompareMethod() As VBA.VbCompareMethod\n KeyCompareMethod = this.KeyCompareMethod\nEnd Property\nFriend Property Let KeyCompareMethod(ByVal value As VBA.VbCompareMethod)\n Errors.GuardNullReference this.KeysDict, VBA.TypeName(Me) & "." & "KeyCompareMethod"\n\n this.KeyCompareMethod = value\n\n If this.KeysDict.Count = 0 Then \n this.KeysDict.CompareMode = this.KeyCompareMethod\n \n End If \nEnd Property\n\nPublic Property Get ValueCompareMethod() As VBA.VbCompareMethod\n ValueCompareMethod = this.ValueCompareMethod\nEnd Property\nFriend Property Let ValueCompareMethod(ByVal value As VBA.VbCompareMethod)\n Errors.GuardNullReference this.ValuesDict, VBA.TypeName(Me) & "." & "ValueCompareMethod"\n\n this.ValueCompareMethod = value\n\n If this.ValuesDict.Count = 0 Then \n this.ValuesDict.CompareMode = this.ValueCompareMethod\n \n End If \nEnd Property\n\nPublic Property Get Count() As Long\n If this.KeysDict.Count = this.ValuesDict.Count Then\n Count = this.KeysDict.Count\n\n Else\n Errors.ThrowError BiDirectionalMapErrors.MismatchedLength, _ \n VBA.TypeName(Me) & "." & "Count()", _ \n GetErrorMessage(BiDirectionalMapErrors.MismatchedLength) \n\n End If\nEnd Property\n\nPublic Property Get Keys() As Scripting.Dictionary\n Set Keys = this.KeysDict\nEnd Property\n\nPublic Property Get Values() As Scripting.Dictionary\n Set Values = this.ValuesDict\nEnd Property\n\nPublic Property Get Key(ByVal valueKey As Variant) As Variant\n If this.ValuesDict.Exists(valueKey) Then\n AssignProperty(Key) = this.ValuesDict(valueKey)\n\n Else\n Errors.ThrowError BiDirectionalMapErrors.KeyDoesNotExist, _ \n VBA.TypeName(Me) & "." & "Get Key()", _ \n GetErrorMessage(BiDirectionalMapErrors.KeyDoesNotExist) \n\n End If\nEnd Property\n\nPublic Property Let Key(ByVal valueKey As Variant, ByVal value As Variant)\n this.KeysDict(valueKey) = value\n this.ValuesDict(value) = valueKey\nEnd Property\n\nPublic Property Set Key(ByVal valueKey As Variant, ByVal value As Variant)\n Set this.KeysDict(valueKey) = value\n Set this.ValuesDict(value) = valueKey\nEnd Property\n\nPublic Property Get Value(ByVal keyValue As Variant) As Variant\n If this.KeysDict.Exists(keyValue) Then\n AssignProperty(Value) = keyValue\n\n Else\n Errors.ThrowError BiDirectionalMapErrors.ValueDoesNotExist, _ \n VBA.TypeName(Me) & "." & "Get Value()", _ \n GetErrorMessage(BiDirectionalMapErrors.ValueDoesNotExist) \n\n End If\nEnd Property\n\nPublic Property Let Value(ByVal keyValue As Variant, ByVal key As Variant)\n this.ValuesDict(keyValue) = key\n this.KeysDict(key) = keyValue\nEnd Property\n\nPublic Property Set Value(ByVal keyValue As Variant, ByVal key As Variant)\n Set this.ValuesDict(keyValue) = key\n Set this.KeysDict(key) = keyValue\nEnd Property\n\n\nPublic Function ContainsKey(ByVal key As Variant) As Boolean\n ContainsKey = this.KeysDict.Exists(key)\nEnd Function\n\nPublic Function ContainsValue(ByVal value As Variant) As Boolean\n ContainsValue = this.ValuesDict.Exists(value)\nEnd Function\n\nPublic Function ContainsPair(ByVal key As Variant, ByVal value As Variant) As Boolean\n ContainsPair = (ContainsKey(key) And ContainsValue(value))\nEnd Function\n\nPublic Sub AddRange(ByVal keys As Variant, ByVal values As Variant)\n Errors.GuardNullReference this.KeysDict, VBA.TypeName(Me) & "." & "AddRange()"\n Errors.GuardNullReference this.ValuesDict, VBA.TypeName(Me) & "." & "AddRange()"\n\n Dim keysColl As Collection\n Set keysColl = IterableToCollection(keys)\n\n Dim valuesColl As Collection\n Set valuesColl = IterableToCollection(values)\n\n If keysColl.Count <> valuesColl.Count Then \n Errors.ThrowError BiDirectionalMapErrors.MismatchedLength, _ \n VBA.TypeName(Me) & "." & "AddRange()", _ \n GetErrorMessage(BiDirectionalMapErrors.MismatchedLength) \n\n End If \n\n Dim i As Long\n For i = 1 To keysColl.Count\n Add keysColl(i), valuesColl(i)\n\n Next i\nEnd Sub\n\nPublic Sub Add(ByVal key As Variant, ByVal value As Variant)\n On Error GoTo CleanFail\n this.KeysDict.Add key, value\n this.ValuesDict.Add value, key\n\nCleanExit:\n Exit Sub\n\nCleanFail:\n Errors.ThrowError Err.Number, VBA.TypeName(Me) & "." & "Add()", Err.Description\n\nResume CleanExit\nEnd Sub\n\nPublic Sub RemoveRange(ByVal keysOrValues As Variant)\n Dim keysOrValueColl As Collection\n Set keysOrValueColl = IterableToCollection(keysOrValues)\n \n Dim i As Long\n For i = 1 To keysOrValueColl.Count\n Remove keysOrValueColl(i)\n\n Next i\n \nEnd Sub\n\nPublic Sub Remove(ByVal keyOrValue As Variant)\n If ContainsKey(keyOrValue) Then \n Dim val As Variant \n val = Value(keyOrValue)\n \n this.KeysDict.Remove keyOrValue\n this.ValuesDict.Remove val\n \n ElseIf ContainsValue(keyOrValue) Then \n Dim key As Variant \n key = Key(keyOrValue)\n \n this.ValuesDict.Remove key\n this.KeysDict.Remove keyOrValue\n \n Else \n Errors.ThrowError BiDirectionalMapErrors.KeyOrValueDoesNotExist, _ \n VBA.TypeName(Me) & "." & "Remove()", _ \n GetErrorMessage(BiDirectionalMapErrors.KeyOrValueDoesNotExist) \n \n End If\n \nEnd Sub\n\nPublic Sub Clear()\n If this.KeysDict.Count > 0 Then \n this.KeysDict.RemoveAll\n \n End If \n \n If this.ValuesDict.Count > 0 Then \n this.ValuesDict.RemoveAll\n \n End If \nEnd Sub\n\n'*****************************************************************************************\n'Private Methods / Properties\n'*****************************************************************************************\nPrivate Sub Class_Initialize()\n Errors.GuardDoubleInitialization this.KeysDict, VBA.TypeName(Me) & "." & "Class_Initialize()"\n Set this.KeysDict = New Scripting.Dictionary\n\n Errors.GuardDoubleInitialization this.ValuesDict, VBA.TypeName(Me) & "." & "Class_Initialize()"\n Set this.ValuesDict = New Scripting.Dictionary\nEnd Sub\n\nPrivate Function IterableToCollection(ByVal iterable As Variant) As Collection\n Select Case VBA.VarType(iterable)\n Case (vbArray + vbVariant) '8204; https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/vartype-function\n Set IterableToCollection = ArrayToCollection(iterable)\n\n Case vbObject\n Set IterableToCollection = ObjectToCollection(iterable)\n\n End Select\nEnd Function\n\nPrivate Function ArrayToCollection(ByVal variantArray As Variant) As Collection\n ValidateArrayDimensions variantArray, "ArrayToCollection()"\n\n Dim result As Collection\n Set result = New Collection\n\n Dim dimensions As Long\n dimensions = GetArrayDimensions(variantArray)\n\n Dim i As Long\n On Error GoTo CleanFail\n Select Case dimensions\n Case 1\n For i = LBound(variantArray) To UBound(variantArray)\n result.Add variantArray(i)\n\n Next i\n\n Case 2\n Dim secondDimLBound As Long\n secondDimLBound = LBound(variantArray, 1)\n\n For i = LBound(variantArray, 1) To UBound(variantArray, 1)\n result.Add variantArray(i, secondDimLBound)\n\n Next i\n\n End Select\n\n Set ArrayToCollection = result\n\nCleanExit:\n Exit Function\n\nCleanFail:\n ManageIterableError Err.Number, "ArrayToCollection()"\n\n Resume CleanExit\nEnd Function\n\nPrivate Function ObjectToCollection(ByVal obj As Variant) As Collection\n Dim result As Collection\n Set result = New Collection\n\n On Error GoTo CleanFail\n Dim value As Variant\n For Each value In obj\n result.Add value\n\n Next\n\n Set ObjectToCollection = result\n\nCleanExit:\n Exit Function\n\nCleanFail:\n ManageIterableError Err.Number, "ObjectToCollection()"\n\nResume CleanExit\nEnd Function\n\n\nPrivate Property Let AssignProperty(ByRef returnValue As Variant, ByVal value As Variant)\n If IsObject(value) Then\n Set returnValue = value\n\n Else\n returnValue = value\n\n End If\nEnd Property\n\n\n'*****************************************************************************************\n'Error Handling\n'*****************************************************************************************\nPrivate Sub ValidateArrayDimensions(ByVal variantArray As Variant, ByVal methodName As String)\n Dim dimensions As Long\n dimensions = GetArrayDimensions(variantArray)\n\n Select Case dimensions\n Case Is > 2\n Errors.ThrowError BiDirectionalMapErrors.SetsNotIterable, VBA.TypeName(Me) & "." & methodName\n\n Case Is = 2\n Errors.GuardExpression IsMultiColumnArray(variantArray), BiDirectionalMapErrors.SetsNotIterable, VBA.TypeName(Me) & "." & methodName\n\n End Select\nEnd Sub\n \nPrivate Sub ManageIterableError(ByVal errorNumber As Long, ByVal methodName As String)\n Select Case errorNumber\n Case Errors.ObjectDoesNotSupportMethodRuntimeError, Errors.TypeMismatchRuntimeError\n Errors.ThrowError BiDirectionalMapErrors.SetsNotIterable, _ \n VBA.TypeName(Me) & "." & methodName, _ \n GetErrorMessage(BiDirectionalMapErrors.SetsNotIterable)\n\n Case Else\n Errors.ThrowError errorNumber, _ \n VBA.TypeName(Me) & "." & methodName, _ \n Err.Description \n\n End Select \nEnd Sub\n\nPrivate Function GetErrorMessage(ByVal errorNumber As BiDirectionalMapErrors) As String\n Dim result As String \n\n Select Case errorNumber\n Case BiDirectionalMapErrors.MismatchedLength\n result = MismatchedLengthErrorDesc\n\n Case BiDirectionalMapErrors.SetsNotIterable\n result = SetsNotIterableErrorDesc\n\n Case BiDirectionalMapErrors.KeyDoesNotExist\n result = "Key " & DoesNotExistErrorDesc & " keys."\n\n Case BiDirectionalMapErrors.ValueDoesNotExist\n result = "Value " & DoesNotExistErrorDesc & " values."\n \n Case BiDirectionalMapErrors.KeyOrValueDoesNotExist\n result = "Key or Value " & DoesNotExistErrorDesc & " keys or values."\n\n End Select\n\n GetErrorMessage = result\nEnd Function\n\nPrivate Function GetArrayDimensions(ByVal variantArray As Variant) As Long\n Dim index As Long\n On Error Resume Next\n Err.Clear\n\n Dim upperBound As Long\n Do\n index = index + 1\n upperBound = UBound(variantArray, index)\n\n Loop Until Err.Number <> 0\n On Error GoTo 0\n\n GetArrayDimensions = (index - 1)\nEnd Function\n\nPrivate Function IsMultiColumnArray(ByVal variantArray As Variant) As Boolean\n On Error Resume Next\n Err.Clear\n\n Dim value As Variant\n value = variantArray(LBound(variantArray), 2)\n\n IsMultiColumnArray = (Err.Number = 0)\n On Error GoTo 0\nEnd Function\n</code></pre>\n<p>Essentially, all we are doing is tracking keys and values in 2 separate dictionaries. The underlying <code>KeysDict</code> has key == key and value == value, while the <code>ValuesDict</code> has key == value and value == key. We want to ensure that they are in sync at all times so as to maintain the bijection of the keys/values.</p>\n<p>Now we can follow up with a wrapper to work specifically with <code>Enums</code>.</p>\n<p><code>EnumMap.cls</code></p>\n<pre><code>VERSION 1.0 CLASS\nBEGIN\n MultiUse = -1 'True\nEND\nAttribute VB_Name = "EnumMap"\nAttribute VB_GlobalNameSpace = False\nAttribute VB_Creatable = False\nAttribute VB_PredeclaredId = True\nAttribute VB_Exposed = True\n'@Exposed\n'@PredeclaredId\nOption Explicit\n\nPrivate Mappings As BiDirectionalMap\n\nPublic Function Create(ByVal enumns As Variant, ByVal names As Variant, _ \nOptional ByVal nameCompareMethod As VBA.VbCompareMethod = vbBinaryCompare) As EnumMap\n Errors.GuardNonDefaultInstance Me, EnumMap, VBA.TypeName(Me) & "." & "Create()"\n\n Dim result As EnumMap\n Set result = New EnumMap\n\n result.SetMappings enumns, names, nameCompareMethod\n\n Set Create = result\nEnd Function\n\nPublic Property Get Count() As Long\n Errors.GuardNullReference Mappings, VBA.TypeName(Me) & "." & "Count()"\n \n Count = Mappings.Count\nEnd Property\n\nPublic Property Get Enumns() As Scripting.Dictionary\n Errors.GuardNullReference Mappings, VBA.TypeName(Me) & "." & "Enumns()"\n \n Set Enumns = Mappings.Keys\nEnd Property\n\nPublic Property Get Names() As Scripting.Dictionary\n Errors.GuardNullReference Mappings, VBA.TypeName(Me) & "." & "Names()"\n \n Set Names = Mappings.Values\nEnd Property\n\nPublic Function ToEnum(ByVal name As String) As Long\n Errors.GuardNullReference Mappings, VBA.TypeName(Me) & "." & "ToEnum()"\n \n ToEnum = Mappings.Key(name)\nEnd Function\n\nPublic Function ToName(ByVal enumValue As Long) As String\n Errors.GuardNullReference Mappings, VBA.TypeName(Me) & "." & "ToName()"\n \n ToName = Mappings.Value(enumValue)\nEnd Function\n\n\nFriend Sub SetMappings(ByVal enumns As Variant, ByVal names As Variant, _ \nByVal nameCompareMethod As VBA.VbCompareMethod)\n If Mappings Is Nothing Then\n Set Mappings = BiDirectionalMap.Create(enumns, names, vbBinaryCompare, nameCompareMethod)\n\n Exit Sub\n\n End If\n\n If Mappings.Count = 0 Then\n Set Mappings = BiDirectionalMap.Create(enumns, names, vbBinaryCompare, nameCompareMethod)\n\n End If\nEnd Sub\n</code></pre>\n<p>The we can test like so:</p>\n<pre><code>Public Enum TestingEnum\n Apples\n Oranges\n Cars\n Lemons\n Trees\n Giraffes\nEnd Enum\n\nPrivate Sub Tester()\n Dim enumValues() As Variant\n enumValues() = Array(Apples, Oranges, Cars, Lemons, Trees, Giraffes)\n \n Dim enumNames() As Variant\n enumNames() = Array("Apples", "Oranges", "Cars", "Lemons", "Trees", "Giraffes")\n\n Dim map As EnumMap\n Set map = EnumMap.Create(enumValues, enumNames)\n \n Debug.Print map.ToEnum("Cars")\n Debug.Print map.ToName(Cars)\n\n Debug.Print map.Count()\n \n Debug.Assert map.names.Exists("Trucks")\n \n Debug.Assert map.enumns.Exists(10)\nEnd Sub\n</code></pre>\n<p>The only caveat with a generic wrapper is that does not support intellisense, but the reusability/portability that it affords outways this in my mind.</p>\n<p>For reference, below is the Errors module referenced in the 2 classes above.</p>\n<p><code>Errors.bas</code></p>\n<pre><code>Attribute VB_Name = "Errors"\nOption Explicit\n\nPublic Const InvalidProcedureCallOrArgumentError As Long = 5\nPublic Const TypeMismatchRuntimeError As Long = 13 \nPublic Const ObjectDoesNotSupportMethodRuntimeError As Long = 438 \nPublic Const ObjectAlreadyInitializedError As Long = 1004 'Technically this is an Application-defined or object-defined error\n\n\nPublic Const InvalidProcedureCallOrArgumentErrorDesc As String = "Invalid procedure call or argument."\nPublic Const ObjectAlreadyInitializedErrorDesc As String = "Object is already initialized."\nPublic Const NonDefaultInstanceErrorDesc As String = "Method should be invoked from the default/predeclared instance of this class."\nPublic Const NullObjectErrorDesc As String = "Object reference cannot be Nothing."\n\nPublic Sub GuardNonDefaultInstance(ByVal instance As Object, ByVal defaultInstance As Object, _\nOptional ByVal source As String = "Errors", _\nOptional ByVal message As String = NonDefaultInstanceErrorDesc)\n GuardExpression Not instance Is defaultInstance, errorNumber:=InvalidProcedureCallOrArgumentError, source:=source, message:=message\nEnd Sub\n\nPublic Sub GuardDoubleInitialization(ByVal instance As Object, _\nOptional ByVal source As String = "Errors", _\nOptional ByVal message As String = ObjectAlreadyInitializedErrorDesc)\n GuardExpression Not instance Is Nothing, errorNumber:=ObjectAlreadyInitializedError, source:=source, message:=message\nEnd Sub\n\nPublic Sub GuardNullReference(ByVal instance As Object, _\nOptional ByVal source As String = "Errors", _\nOptional ByVal message As String = NullObjectErrorDesc)\n GuardExpression instance Is Nothing, errorNumber:=InvalidProcedureCallOrArgumentError, source:=source, message:=message\nEnd Sub\n\nPublic Sub GuardExpression(ByVal throw As Boolean, _\nOptional ByVal errorNumber As Long = InvalidProcedureCallOrArgumentError, _\nOptional ByVal source As String = "Errors", _\nOptional ByVal message As String = InvalidProcedureCallOrArgumentErrorDesc)\n If throw Then\n ThrowError IIf(errorNumber = 0, InvalidProcedureCallOrArgumentError, errorNumber), source, message\n\n End If\nEnd Sub\n\nPublic Sub ThrowError(ByVal errorNumber As Long, Optional ByVal source As String = "Errors", _\nOptional ByVal message As String = "Invalid procedure call or argument.")\n VBA.Information.Err.Err.Raise errorNumber, source:=source, message:=message\nEnd Sub\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T14:23:45.293",
"Id": "266167",
"ParentId": "265962",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T16:13:38.320",
"Id": "265962",
"Score": "4",
"Tags": [
"vba",
"enum",
"properties"
],
"Title": "A method for managing enumerations in VBA"
}
|
265962
|
<p>I'm working through these Koans: <a href="https://github.com/paytonrules/typescript.koans#readme" rel="nofollow noreferrer">https://github.com/paytonrules/typescript.koans#readme</a></p>
<p>I'm on file 3, collections, the very first function <code>foreach</code>:</p>
<pre><code>export interface Dictionary<T> {
[index: string]: T;
}
interface ArrayForEachIteratee<T> {
(value?: T, index?: number, collection?: Array<T>): any;
}
interface DictionaryForEachIteratee<T> {
(value?: T, key?: string, collection?: Dictionary<T>): any;
}
/**
* ### forEach
* should iterate over all items of array or all properties of an object
*
* ## Examples
*
* let collection = ["first", "second", "third"];
* let result = [];
* let iteratee = (value, index, collection) => result[index] = [index, value];
*
* _.forEach(collection, iteratee); => result === [[0, 'first'], [1, 'second'], [2, 'thidrd']];
*
* collection = {
* "0": "first",
* "1": "second",
* "2": "third"
* };
* result = [];
* iteratee = (value, index, collection) => result[index] = [index, value];
*
* _.forEach(collection, iteratee); => result === [['0', 'first'], ['1', 'second'], ['2', 'thidrd']];
*
*/
export function forEach() {
}
</code></pre>
<p>When I look at the test code, I can see that the first test sends it an array and a function, and the second test sends it a dictionary and a function:</p>
<pre><code>describe("forEach", function () {
context("when collection is an array", function () {
it("should iterate over all items of array", function () {
const collection = ["first", "second", "third"];
const iteratee = sinon.spy();
_.forEach(collection, iteratee);
sinon.assert.calledWithExactly(iteratee, "first", 0, collection);
sinon.assert.calledWithExactly(iteratee, "second", 1, collection);
sinon.assert.calledWithExactly(iteratee, "third", 2, collection);
});
});
context("when collection is an object", function () {
it("should iterate over all items of object", function () {
const collection: _.Dictionary<string> = {
"0": "first",
"1": "second",
"2": "third"
};
const iteratee = sinon.spy();
_.forEach(collection, iteratee);
sinon.assert.calledWithExactly(iteratee, "first", "0", collection);
sinon.assert.calledWithExactly(iteratee, "second", "1", collection);
sinon.assert.calledWithExactly(iteratee, "third", "2", collection);
});
});
});
</code></pre>
<p>So I set up my code to accept an array or a dictionary, and the corresponding array / dictionary callback for the second argument:</p>
<pre><code>export function forEach<T>(collection: Array<T> | Dictionary<T>, iteratee: ArrayForEachIteratee<T> | DictionaryForEachIteratee<T>): void {
if (Array.isArray(collection)) {
collection.forEach(iteratee);
} else {
Object.keys(collection)
.forEach(key => {
const value = collection[key];
iteratee(value, key, collection);
});
}
}
</code></pre>
<p>My code passes the tests - I'm passing the right arguments to the right functions in the right ways - but I'm absolutely certain that I'm not doing it in the proper Typescript-y type-safe way. My editor is showing me lots of red.</p>
<p>Can I get some pointers on how an expert typescripter would gracefully handle this situation?</p>
|
[] |
[
{
"body": "<h2>Compilation errors</h2>\n<p>Here is the reason is why you got compilation errors. Compiler doesn't understands that if <code>collection</code> is <code>Array<T></code>, then <code>iteratee</code> is <code>ArrayForEachIteratee<T></code>.</p>\n<p>We should help compiler to realize that. Unfortunately, it seems it's impossible to build such instruction to typescript without significant rework of code.</p>\n<p>So instead we can leverage type-casting:</p>\n<pre><code>if (Array.isArray(collection)) {\n collection.forEach(iteratee as ArrayForEachIteratee<T>);\n return;\n} \n\nObject.keys(collection)\n .forEach(key => {\n const value = collection[key];\n (iteratee as DictionaryForEachIteratee<T>)(value, key, collection);\n });\n</code></pre>\n<p>But this doesn't looks pretty.\nIn typescript there are <a href=\"https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#assertion-functions\" rel=\"nofollow noreferrer\">assertion functions</a>. Let's build one, but without actual checks on type (because we don't need them & we can't perform then):</p>\n<pre><code>function forceTypeNarrow<TWanted>(value: any): asserts value is TWanted {}\n</code></pre>\n<p>Now if we will put <code>forceTypeNarrow</code> somewhere in code, then all next lines in scope will think that <code>value</code> has type <code>TWanted</code>.</p>\n<p>Now we can rewrite contents of our <code>forEach</code> function:</p>\n<pre><code>if (Array.isArray(collection)) {\n forceTypeNarrow<ArrayForEachIteratee<T>>(iteratee);\n collection.forEach(iteratee);\n return;\n} \n\nObject.keys(collection)\n .forEach(key => {\n const value = collection[key];\n forceTypeNarrow<DictionaryForEachIteratee<T>>(iteratee);\n iteratee(value, key, collection);\n });\n</code></pre>\n<h1>Proper function declaration</h1>\n<p>Let's take a look on your function declaration</p>\n<pre><code>export function forEach<T>(collection: Array<T> | Dictionary<T>, iteratee: ArrayForEachIteratee<T> | DictionaryForEachIteratee<T>): void {\n</code></pre>\n<p>This declaration allows user-code to pass <code>(collection: Array<T>, iteratee: DictionaryForEachIteratee<T>)</code>. But we don't want to allow that!</p>\n<p>Let's leverage <a href=\"https://www.typescriptlang.org/docs/handbook/functions.html#overloads\" rel=\"nofollow noreferrer\">overloads</a>. We will put one overload for <code>Array<T></code>, second overload for <code>Dictionary<T></code>. And typescript forces us to put third non-end-user-code overload for internal purposes.</p>\n<pre><code>export function forEach<T>(\n collection: Array<T>, \n iteratee: ArrayForEachIteratee<T>\n): void;\nexport function forEach<T>(\n collection: Dictionary<T>, \n iteratee: DictionaryForEachIteratee<T>\n): void;\nexport function forEach<T>(\n collection: Array<T> | Dictionary<T>, \n iteratee: ArrayForEachIteratee<T> | DictionaryForEachIteratee<T>\n): void {\n …\n}\n</code></pre>\n<h2>Proper formatting of header</h2>\n<p>Long lines are not good, because they force everyone to use scroll (in IDE, in PR or here on codereview).</p>\n<p>In case if your function header is too long, you should put each parameter on new-line. That will make your code readable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T12:09:25.940",
"Id": "525393",
"Score": "0",
"body": "Thank you for this. I have a questino about your Overload area - is there a reason for the last specification? `collection: Array<T> | Dictionary<T>, \n iteratee: ArrayForEachIteratee<T> | DictionaryForEachIteratee<T>` -- aren't all the possibilities covered by the previous two specifications?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T13:21:26.197",
"Id": "525394",
"Score": "0",
"body": "my system isn't liking the forceTypeNarrow definition..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T15:54:21.807",
"Id": "525402",
"Score": "0",
"body": "> aren't all the possibilities covered by the previous two specifications?.\nWell, yeah, they covered. But typescript is a bit \"stupid\" and can't merge them automatically. Typescript forces you to specify merged version as last specification. \nThe first and second declaration is called the overload signature. The last declaration is called the implementation signature (and this signature can't be called directly).\n\nI don't know why typescript compiler forces us to write an implementation signature. Maybe for clarity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T15:58:05.397",
"Id": "525403",
"Score": "0",
"body": "If your system doesn't like forceTypeNarrow, then probably the issue is that your typescript is before v3.7.5. Try to update it. \nIt works perfectly in typescript playground, see https://shorturl.at/dCQ03"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T16:57:12.253",
"Id": "525416",
"Score": "1",
"body": "thanks, this all was extremely helpful! thank you! I couldn't find any of this `forceTypeNarrow` function online -- do you know if a similar pattern is commonly used by a different name?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T17:46:11.960",
"Id": "525420",
"Score": "1",
"body": "No, sorry. I just invented it for sake of clarity and never seen it before"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-19T10:21:41.390",
"Id": "525844",
"Score": "1",
"body": "Hey, one more question: `forceTypeNarrow<ArrayForEachIteratee<T>>(iteratee);` vs `iteratee = iteratee as <ArrayForEachIteratee<T>` -- is there any reason to prefer one over the other in your opinion?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-19T11:05:11.690",
"Id": "525845",
"Score": "0",
"body": "@TKoL your code (i = i as T) will not change type of variable i. In order to change type you need to introduce new variable (i2 = i as T). I think, there are no strict preference except beauty/ugly (and it's up to you)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-19T11:14:37.263",
"Id": "525848",
"Score": "1",
"body": "\"your code (i = i as T) will not change type of variable i\" -- my editor seems to think it works, and it compiles okay."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-19T14:48:37.543",
"Id": "525867",
"Score": "1",
"body": "@TKoL wow, I was wrong."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-19T14:59:00.237",
"Id": "525868",
"Score": "1",
"body": "@TKoL okay, in such case it seems that forceTypeNarrow is redundant, because u can achieve that by \"normal\" way"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-19T15:03:13.753",
"Id": "525869",
"Score": "0",
"body": "ty for considering it, and for your advice"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T11:17:05.643",
"Id": "527752",
"Score": "1",
"body": "@TKoL recently I found that trick `i = i as T` doesn't works for `const` variables. I also found that this trick doesn't work when `i` is `any` or `unknown`. So it seems, that there are cases for `forceTypeNarrow`"
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T11:53:41.753",
"Id": "265987",
"ParentId": "265963",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "265987",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T16:55:29.893",
"Id": "265963",
"Score": "0",
"Tags": [
"typescript"
],
"Title": "Having trouble with this Koan - solved it, but I don't think what I wrote is correct in regards to Typing"
}
|
265963
|
<p>Im trying to implement a plugin system.
A plugin is a compressed gzip tarball with files and folders.
The tar file gets extractet and stored in memory. (The files are never written to the filesystem)</p>
<p>Now with all the content of the files in memory, i load/compile the content of the entry file. For that i found this solution (<a href="https://stackoverflow.com/a/17585470/5781499">https://stackoverflow.com/a/17585470/5781499</a>):</p>
<pre class="lang-js prettyprint-override"><code>const Module = require("module");
//var Module = module.constructor;
const m = new Module();
m.paths = Module._nodeModulePaths("/tmp/virtal-file/folder/")
m._compile("console.log('Hello from Plugin entry file', __filename);", "/tmp/virtal-file/folder/index.js");
</code></pre>
<p>Now i need a solution that <a href="https://nodejs.org/dist/latest-v14.x/docs/api/modules.html#modules_require_id" rel="nofollow noreferrer"><code>require()</code></a> can also load other files from memory. (To be able to require other js files that the plugin provides.</p>
<p>I came up with a solution like this:</p>
<pre class="lang-js prettyprint-override"><code>const path = require("path");
function isLocal(moduleId) {
return /^[\/\.]/.test(moduleId);
}
function isNative(moduleId) {
return process.binding("natives").hasOwnProperty(moduleId);
}
function isThirdParty(moduleId) {
return !isLocal(moduleId) && !isNative(moduleId);
}
const Module = require("module");
const _require = Module.prototype.require;
// root/index.js module
const m = new Module();
// intercept require
// to resolve virtual files
// https://stackoverflow.com/a/56203843/5781499
Module.prototype.require = (id) => {
try {
// if (filelist.has(path.resolve(dirname, id))) {
if (filelist.has(path.resolve(dirname, id)) && isLocal(id)) {
console.log("Load virtual file '%s'", id);
// request module is plugin/localy
let mod = new Module();
// resolve absolute paths
id = path.resolve(dirname, id);
mod.paths = Module._nodeModulePaths(id);
mod._compile(filelist.get(id), id);
return mod.exports;
} else if (isNative(id)) {
console.log("Load native module '%s'", id);
return _require(id);
} else if (isThirdParty(id)) {
console.log("load third party '%s'", id);
return _require(require.resolve(id));
} else {
console.log("Load file '%s'", id);
return _require(path.resolve(dirname, id));
}
} catch (err) {
console.log("Could not load module '%s'", id, err);
}
};
</code></pre>
<p>But this seems like a huge messup with paths/resolving mechanism.</p>
<p>Is there a better solution to load files from in-memory?</p>
<p>Any help is appreciated.
Thanks in advance.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-17T20:05:42.083",
"Id": "265965",
"Score": "0",
"Tags": [
"node.js"
],
"Title": "manipulate \"require\" to load files from a \"virtual file system\"/in-memory"
}
|
265965
|
<p>I'm writing a breadth first search algorithm in Haskell that supports pruning. It is guaranteed that the search will never encounter nodes that have been visited before, so I implemented the search as a <code>filter</code> along a stream of candidates.</p>
<p>I'm concerned about the efficiency of the code. Is there some slow, bad-practice code that I can try to avoid? What are some possible ways to optimize the code? Other feedback is also welcome!</p>
<pre class="lang-hs prettyprint-override"><code>bfs :: (a -> Bool) -- ^ Goal if evaluates to True
-> (a -> Bool) -- ^ Prune if evaluates to False
-> a -- ^ Starting point of search
-> (a -> [a]) -- ^ Branches at a point
-> [a] -- ^ Goals
bfs predicate prune a0 branch = filter predicate searchspace
where
-- An elegant solution
-- searchspace = a0 : (branch =<< searchspace)
-- However, this solution <<loop>>'s when the search is finite
searchspace = concat $ takeWhile (not.null) epochs
epochs = [a0] : map (\as -> [ a' | a <- as, prune a, a' <- branch a]) epochs
</code></pre>
|
[] |
[
{
"body": "<p>Your</p>\n<pre><code>bfs feasible interesting branches tree = \n filter feasible . \n concat . takeWhile(>[]) .\n iterate(concatMap branches . filter interesting)[tree] \n</code></pre>\n<p>is about as efficient as you can get if you also prune some of your finds. Otherwise you can save some memory by pruning branches immediately after their generation as in <code>filter interesting . concatMap branches</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T07:47:19.490",
"Id": "266023",
"ParentId": "265967",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T19:51:19.777",
"Id": "265967",
"Score": "4",
"Tags": [
"performance",
"haskell",
"breadth-first-search"
],
"Title": "Breadth first search on trees in Haskell"
}
|
265967
|
<p>Could someone please help me out, I'm trying to remove the need to iterate through the dataframe and know it is likely very easy for someone with the knowledge.</p>
<p>Dataframe:</p>
<pre><code> id racecourse going distance runners draw draw_bias
0 253375 178 Standard 7.0 13 2 0.50
1 253375 178 Standard 7.0 13 11 0.25
2 253375 178 Standard 7.0 13 12 1.00
3 253376 178 Standard 6.0 12 2 1.00
4 253376 178 Standard 6.0 12 8 0.50
... ... ... ... ... ... ... ...
378867 4802789 192 Standard 7.0 16 11 0.50
378868 4802789 192 Standard 7.0 16 16 0.10
378869 4802790 192 Standard 7.0 16 1 0.25
378870 4802790 192 Standard 7.0 16 3 0.50
378871 4802790 192 Standard 7.0 16 8 1.00
378872 rows × 7 columns
</code></pre>
<p>What I need is to add a new column with the count of unique races (id) by the conditions defined below. This code works as expected but it is sooo slow....</p>
<pre><code>df['race_count'] = None
for i, row in df.iterrows():
df.at[i, 'race_count'] = df.loc[(df.racecourse==row.racecourse)&(df.going==row.going)&(df.distance==row.distance)&(df.runners==row.runners), 'id'].nunique()
</code></pre>
|
[] |
[
{
"body": "<p>Sorry, this is not a complete solution, just an idea.</p>\n<p>In Pandas you can split a data frame in subgroups based on one or multiple grouping variables using the <code>groupby</code> method. You can then apply an operation (in this case <code>nunique</code>) to each of the subgroups:</p>\n<pre class=\"lang-py prettyprint-override\"><code>df.groupby(['racecourse', 'going', 'distance', 'runners'])['id'].nunique()\n</code></pre>\n<p>This should give you the number of races with the same characteristics (racecourse, going, ...) but unique values for <code>id</code>.</p>\n<p>Most importantly, this should be much faster than looping over the rows, especially for larger data frames.</p>\n<hr />\n<p><strong>EDIT:</strong></p>\n<p>Here's a complete solution also including the combination with the original data frame (thanks to <em>ojdo</em> for suggesting <code>join</code>/<code>merge</code>)</p>\n<pre class=\"lang-py prettyprint-override\"><code>race_count = df.groupby(['racecourse', 'going', 'distance', 'runners'])['id'].nunique()\nrace_count.name = 'race_count'\ndf.merge(race_count, on=['racecourse', 'going', 'distance', 'runners'])\n</code></pre>\n<p>Conveniently, <code>merge</code> broadcasts the values in <code>race_count</code> to all rows of <code>df</code> based on the values in the columns specified by the <code>on</code> parameter.</p>\n<p>This outputs:</p>\n<pre><code> id racecourse going distance runners draw draw_bias race_count \n0 253375 178 Standard 7.0 13 2 0.50 1 \n1 253375 178 Standard 7.0 13 11 0.25 1 \n2 253375 178 Standard 7.0 13 12 1.00 1 \n3 253376 178 Standard 6.0 12 2 1.00 1 \n4 253376 178 Standard 6.0 12 8 0.50 1 \n5 4802789 192 Standard 7.0 16 11 0.50 2 \n6 4802789 192 Standard 7.0 16 16 0.10 2 \n7 4802790 192 Standard 7.0 16 1 0.25 2 \n8 4802790 192 Standard 7.0 16 3 0.50 2 \n9 4802790 192 Standard 7.0 16 8 1.00 2 \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T12:49:19.880",
"Id": "525449",
"Score": "1",
"body": "And to complete this thought, the remaining step \"combine\", simply set the index of this result to the desired column, and `join` it with the original. (The general pattern is called [split-apply-combine](https://pandas.pydata.org/pandas-docs/stable/user_guide/groupby.html?highlight=split%20apply%20combine#), and is often a good way to express operations.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T13:05:57.290",
"Id": "525450",
"Score": "0",
"body": "Yes, good call. To be honest, I had problems coming up with a good implementation for combining the results (number of unique elements) with the original data frame `df`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T14:11:18.747",
"Id": "525495",
"Score": "0",
"body": "This is fantastic, exactly what I needed. Thank you very much and may the force continue to be with you "
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T03:41:52.880",
"Id": "528825",
"Score": "1",
"body": "You can do this directly with [`groupby transform`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.transform.html) instead of needing `merge` at all -> `df['race_count'] = df.groupby(['racecourse', 'going', 'distance', 'runners'])['id'].transform('nunique')`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-22T14:44:56.287",
"Id": "528946",
"Score": "0",
"body": "@Henry Ecker: Nice solution, very elegant and concise. I did not know about the `groupby transform` method. Cool!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T11:34:48.490",
"Id": "266030",
"ParentId": "265968",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "266030",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T20:23:57.220",
"Id": "265968",
"Score": "0",
"Tags": [
"python",
"pandas"
],
"Title": "add column with count by constraint"
}
|
265968
|
<p>I am just beginning to learn Python, and thought I would give myself a challenge using the lessons I have learned so far. I am following the Udemy course, Automate the Boring Stuff with Python. The point that I've reached so far has covered the basics of functions, handling errors, lists and dictionaries.</p>
<p>I wanted to see if I had a grasp of what I'd learned by making a tic-tac-toe game with certain features/challenges/objectives in mind:</p>
<ul>
<li>make use of loops, functions, methods, lists/dictionaries.</li>
<li>the player would need to see the board and what spots were taken/left</li>
<li>I wanted players to be able to type in the choice in upper/lower/mixed case</li>
<li>the game had to recognize all win conditions, lose conditions, and stalemate conditions.</li>
<li>the opponent (in this case, the CPU) would need to only have access to the choices remaining. For now, it would be random, but maybe I would come back to the code to have some form of AI.</li>
<li>When the game ends, give the player the choice of starting a new game, and keep track of the score.</li>
</ul>
<p>This is my code, and as far as I can see, it works and I managed to complete all the goals I set out to do:</p>
<pre><code>
import copy
import time
import random
import sys
##Board design to make it look pretty
def printBoard(board):
print('')
print(board['top-l'] + '|' + board['top-m'] + '|' + board['top-r'])
print('-----')
print(board['mid-l'] + '|' + board['mid-m'] + '|' + board['mid-r'])
print('-----')
print(board['low-l'] + '|' + board['low-m'] + '|' + board['low-r'])
print('')
##Function for initiating the board back to blank
def blankBoard(zeroBoard):
for value in zeroBoard:
zeroBoard[value] = ' '
##Function for initiating a New Game after a game over situation
def newGame(YorN):
print('\n ~ Would you like to play again? if yes, type ''Y'': ~ ')
newGame = input()
if newGame.upper() == 'Y':
print(' ~ okay, please wait while we set up a new game! ~ ')
blankBoard(theBoard)
time.sleep(random.randint(1,2))
printBoard(theBoard)
else:
print('\n ~ Bye and thank you for playing!! ~ ')
sys.exit()
##Function containing all the win conditions
def winCondition(winner):
if ((winner['top-l'] == winner['top-m'] == winner['top-r'] == 'X') or
(winner['mid-l'] == winner['mid-m'] == winner['mid-r'] == 'X') or
(winner['low-l'] == winner['low-m'] == winner['low-r'] == 'X') or
(winner['top-l'] == winner['mid-l'] == winner['low-l'] == 'X') or
(winner['top-m'] == winner['mid-m'] == winner['low-m'] == 'X') or
(winner['top-r'] == winner['mid-r'] == winner['low-r'] == 'X') or
(winner['top-l'] == winner['mid-m'] == winner['low-r'] == 'X') or
(winner['top-r'] == winner['mid-m'] == winner['low-l'] == 'X')):
print('\n ~ Congratulations! You are a winner! ')
return 'win'
##Function containing all the loss conditions
def loseCondition(loser):
if ((loser['top-l'] == loser['top-m'] == loser['top-r'] == 'O') or
(loser['mid-l'] == loser['mid-m'] == loser['mid-r'] == 'O') or
(loser['low-l'] == loser['low-m'] == loser['low-r'] == 'O') or
(loser['top-l'] == loser['mid-l'] == loser['low-l'] == 'O') or
(loser['top-m'] == loser['mid-m'] == loser['low-m'] == 'O') or
(loser['top-r'] == loser['mid-r'] == loser['low-r'] == 'O') or
(loser['top-l'] == loser['mid-m'] == loser['low-r'] == 'O') or
(loser['top-r'] == loser['mid-m'] == loser['low-l'] == 'O')):
print('\n ~ Aww man, you''re are a loser! ~ ')
return 'lose'
##Function for Computer Players Choice
def computerChoice(cpuChoice):
theBoardCPU = copy.deepcopy(theBoardChoices)
print(','.join(theBoardCPU.keys()))
cpuChoice = random.choice(list(theBoardCPU.keys()))
print(' ~ ' + cpuChoice + ' ~ ')
del theBoardChoices[cpuChoice]
theBoard[cpuChoice] = 'O'
printBoard(theBoard)
##Blank board to begin with and making a copy of the board for choices remaining, and finally printing a pretty board
theBoard = {'top-l': ' ', 'top-m': ' ', 'top-r': ' ',
'mid-l': ' ', 'mid-m': ' ', 'mid-r': ' ',
'low-l': ' ', 'low-m': ' ', 'low-r': ' '}
theBoardChoices = copy.deepcopy(theBoard)
printBoard(theBoard)
##The actual game
print(' ~ Hello player. What is your name? ~ ')
player1Name = input()
print(' ~ Hello ' + player1Name + ', welcome to tic-tac-toe ~ ')
playerScore = 0
CPUScore = 0
while theBoardChoices != None:
print(' ~ ' +player1Name + ', please type in one of the options for blank spaces: ~ ')
print('')
print(' , '.join(theBoardChoices.keys()))
playerInput = input()
playerChoice = playerInput.lower()
choiceCheck = theBoard.get(playerChoice,'bad choice')
if choiceCheck != 'bad choice':
if theBoard[playerChoice] == ' ':
theBoard[playerChoice] = 'X'
printBoard(theBoard)
del theBoardChoices[playerChoice]
if winCondition(theBoard) == 'win':
theBoardChoices = copy.deepcopy(theBoard)
playerScore = playerScore + 1
print(' ~ the current score is ' + str(playerScore) +'-' + str(CPUScore) + ' ~ ')
newGame(theBoardChoices)
continue
if theBoardChoices == {}:
theBoardChoices = copy.deepcopy(theBoard)
newGame(theBoardChoices)
continue
print(' ~ Please wait. Computer making a choice... ~ ')
time.sleep(random.randint(1,2))
computerChoice(theBoard)
if loseCondition(theBoard) == 'lose':
theBoardChoices = copy.deepcopy(theBoard)
CPUScore = CPUScore + 1
print(' ~ the current score is ' + str(playerScore) +'-' + str(CPUScore) + ' ~ ')
newGame(theBoardChoices)
continue
else:
print(' ~ that space is already taken ~ ')
</code></pre>
<p>My questions regarding this code are as follows:</p>
<ol>
<li><p>My win and lose condition functions seem very bulky, but I couldn't think of another way of reducing that down or preferably making them into one function. I thought maybe I could make something that would be 'if these three keys values = x', and then if 'x = O then lose', or 'x = X then lose'. But I think my understanding of functions is still a bit cloudy.
Is there a way to make a function that would generate that list of win/loss conditions using my set up? Or would I have had to made the board a list instead of a dictionary in order to use a more mathematical approach to reduce that?</p>
</li>
<li><p>I have a bunch of nested <code>if</code>'s in my while statement. I feel like I could have made more use of functions to reduce that, but even so, I'm wondering if there are issues down the line of having that.</p>
</li>
<li><p>I was planning on having a try/except in there, but by the time I reached the code that I have, I couldn't find a way to break it to make it active. Should I have put that in there any ways? I feel like always having that back up system there is a good habit, even if the code seems unbreakable. Or would that just make the code more messy and a waste of space?</p>
</li>
<li><p>In general, I know that old habits die hard, and that can be true of bad habits too. I would very much like to know if there are signs of bad things in my code that I can be wary of so I can nip it in the bud before I keep going. My plan is to revisit this code in the future and add to it (option of 2 human players or vs CPU or 2 CPU's face eachother, some AI of sorts, option of letting players set the size of the board, etc).</p>
</li>
</ol>
<p>Anyways, I am looking forward to any feed back!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T14:17:13.690",
"Id": "525396",
"Score": "1",
"body": "Just a quick comment addressing question (4): your use of `del` and `copy.deepcopy` is probably one of the bad habits that you don't want to develop. Usually you don't want or need this type of memory manipulation in Python. Instead of copying from a template, and then deleting from that copy, you would rather use a list that manages the remaining valid keys. For this you may want to learn the appropriate methods to remove elements from containers (e.g. `pop()` for dictionaries or `remove()` and `pop()` for lists)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T23:03:29.123",
"Id": "525434",
"Score": "0",
"body": "@schmuddi - thanks for the advice! I'm a bit confused as to the different of what I did and what you are suggesting. In my case, I've created a dictionary/list of the remaining choices and removing data from it, and then essentially just resetting it upon a new game. In your suggestion, I would, say, be taking from a list using pop(), and placing that in a new list regardless? I'm not doubting that your approach is better, but I just am not seeing how one is more efficient (unless of course there is a situation I'm not thinking about!)"
}
] |
[
{
"body": "<p>As an...InTeRmEdIaTe...I think I <em>can</em> give some recomendations/advice about this.</p>\n<ol>\n<li>When building something don't think about what data structures or syntax features are you going to use. You can search for example "python dictionary/loops exercises" for practicing those basics, but when building an app, <strong>split the main goal into steps and consequently code them up.</strong> Focus on HOW you will do a certain task.</li>\n</ol>\n<p>You will definetly have those basics set-in-stone later on, becuase you will implement them in almost every project you make.</p>\n<p>About the code, try to seperate functions that are related to the same thing in different .py files like <em>modules</em> (if you have heart about them) and then use <em>importing</em>.Use this for not only not making a mess, but also for easily finding a bug or an error. That will make your code cleaner.</p>\n<ol start=\"2\">\n<li><p>In your code you use camelCase for your variable names and functions, but in python it will be better to use snake_case, because most of python's methods and builtin functions are in snake_case.</p>\n</li>\n<li><p><strong>Separate functions with 2 and loops/conditions with 1 blank line.</strong> That will make your code easier to read. In the end there's a big block of code, which is pain to figure out for me.</p>\n</li>\n</ol>\n<p>You will definitely see the difference:</p>\n<pre><code>while theBoardChoices != None: \n\n print(' ~ ' +player1Name + ', please type in one of the options for blank spaces: ~ ')\n print('')\n print(' , '.join(theBoardChoices.keys()))\n\n playerInput = input()\n playerChoice = playerInput.lower()\n choiceCheck = theBoard.get(playerChoice,'bad choice')\n \n if choiceCheck != 'bad choice':\n \n if theBoard[playerChoice] == ' ':\n theBoard[playerChoice] = 'X'\n printBoard(theBoard)\n\n del theBoardChoices[playerChoice]\n\n if winCondition(theBoard) == 'win':\n theBoardChoices = copy.deepcopy(theBoard)\n playerScore = playerScore + 1\n \n print(' ~ the current score is ' + str(playerScore) +'-' + str(CPUScore) + ' ~ ')\n \n newGame(theBoardChoices)\n continue\n\n if theBoardChoices == {}:\n theBoardChoices = copy.deepcopy(theBoard)\n\n newGame(theBoardChoices)\n continue \n\n print(' ~ Please wait. Computer making a choice... ~ ')\n time.sleep(random.randint(1,2))\n computerChoice(theBoard)\n\n if loseCondition(theBoard) == 'lose':\n theBoardChoices = copy.deepcopy(theBoard)\n CPUScore = CPUScore + 1\n\n print(' ~ the current score is ' + str(playerScore) +'-' + str(CPUScore) + ' ~ ')\n \n newGame(theBoardChoices)\n continue \n \n else:\n print(' ~ that space is already taken ~ ')\n</code></pre>\n<ol start=\"4\">\n<li>I didn't get why your comments start with <code>##</code> and not just <code>#</code>.\nComment the <em>bodies</em> of functions too.</li>\n</ol>\n<pre><code>def func():\n print("something") # <-- the body of a function (stuff, that goes inside of a function)\n</code></pre>\n<p>It's very good, that you want to practice the things you've learned, but learn a little more and try this again...You'll feel the improvement...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T21:25:50.567",
"Id": "266010",
"ParentId": "265972",
"Score": "1"
}
},
{
"body": "<p>Great start but there's a long list of typical things that bite beginners.</p>\n<ul>\n<li>Use an IDE (PyCharm or otherwise) that has an integrated linter able to point out when you're violating PEP8. Listen to its suggestions and learn why they're being made. For instance, <code>printBoard</code> should be <code>print_board</code>.</li>\n<li>Add some PEP484 type hints, so that you can marginally shift Python's typing from "anything goes, no static analysis possible" to "slightly constrained though still not in runtime"</li>\n<li>A dict is a bad representation for your board. Better data structures include a lists of lists, or a two-dimensional Numpy <code>ndarray</code>.</li>\n<li>What even is <code>YorN</code>? It's never used; delete it</li>\n<li>Avoid the double-<code>''</code> escape by using a string literal defined by <code>"</code> instead of <code>'</code></li>\n<li><code>you''re are a loser!</code> -> <code>you are a loser!</code></li>\n<li>Rather than expressions like <code>' ~ the current score is ' + str(playerScore) +'-' + str(CPUScore) + ' ~ '</code>, use an f-string like <code>f' ~ the current score is {player_score}-{cpu_score} ~ '</code></li>\n<li>Rather than <code>playerScore = playerScore + 1</code>, use in-place addition: <code>player_score += 1</code>.</li>\n<li>Do not print on the inside of <code>lose_condition</code>, and do not return a string from <code>lose_condition</code>. Return a boolean, and let the caller decide what to print.</li>\n</ul>\n<p>Here's a pet peeve of mine - lying to your user. You say</p>\n<blockquote>\n<p>please wait while we set up a new game!</p>\n<p>Please wait. Computer making a choice...</p>\n</blockquote>\n<p>which implies that you're working hard to actually <em>do</em> something while the program hangs; but that's not true. Don't <code>sleep</code> and lie about it.</p>\n<p>There are other things but this should be a good start.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T00:17:48.800",
"Id": "525481",
"Score": "1",
"body": "Thanks so much for all the helpful feedback!\n\nI had no idea there was a generally accepted style guide for programming, but thinking about it that does make a lot of sense. I've only seen NumPy mentioned in a few posts, but I didn't want to overwhelm myself in the beginning and start learning things when I don't fully grasp the basics yet. I've added that to my growing list of tings to look into. \n\nSeems like I have a habit of over complicating things and it's really showing in my code. I will be taking a look at the changes you've suggested and refresh myself on the lessons. Thanks again!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T18:24:27.663",
"Id": "266042",
"ParentId": "265972",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T21:31:01.307",
"Id": "265972",
"Score": "3",
"Tags": [
"python",
"beginner",
"tic-tac-toe"
],
"Title": "Beginner learner: Python 3.9.6 tic-tac-toe code and questions about optimization"
}
|
265972
|
<p>I'm trying to capture all input fields in a form (i.e. sign_up.html) & validating them - if one of them is null or empty then it should show a validation message. I've done it but I'm looking for an elegant way to do it.</p>
<h2>sign_up.html</h2>
<pre><code>{% extends "layout.html" %}
{% block main %}
<form action="/sign_up.html" method="POST" autocomplete="off" name="sign_up">
<h2>Sign Up</h2>
<label for="username">User name:
<input type="text" placeholder="Username" name="username" required="required" maxlength="20">
</label>
<br>
<sup>* Password must be 8-12 Digit ,Numbers & letters & punctuations @, !, $, ETC..</sup>
<label for="password">Password:
<input type="password" placeholder="password" name="password" required="required" minlength="8" maxlength="12">
</label>
<label for="check">Check Password:
<input type="password" placeholder="Check Password" name="check" required="required" minlength="8" maxlength="12">
</label>
<br>
<label for="security_question">Security question :
<select name="security_question">
<option value="where were you born?" name="q1" >where were you born?</option>
<option value="what is your favorite nickname?" name="q2" >what is your favorite nickname?</option>
<option value="what is the name of your first pet?" name="q3" >what is the name of your first pet?</option>
<option value="what is the name of your first best friend?" name="q4" >what is the name of your first best friend?</option>
</select>
</label>
<label for="answer">Security answer:
<input type="text" placeholder="Answer" name="answer" required="required">
</label>
<br>
<input type="submit" value="Sign Up">
</form>
{% endblock %}
</code></pre>
<p>this is my spaghetti validation python code:</p>
<pre><code>from flask import Flask, flash, redirect, render_template, Request, request, session
from werkzeug.datastructures import ImmutableOrderedMultiDict
from werkzeug.utils import HTMLBuilder
#Something in between
class OrderedRequest(Request):
parameter_storage_class = ImmutableOrderedMultiDict
app = Flask(__name__)
app.request_class = OrderedRequest
#Something in between
@app.route("/sign_up.html", methods=["GET", "POST"])
def sign_up():
if request.method == "POST":
#assigning returning page
page = "sign_up.html"
#Null fields checking
if not request.form.get("username"):
return render_template("errors/general_error.html", error = "Username field is Empty", page = page)
elif not request.form.get("password"):
return render_template("errors/general_error.html", error = "Password field is Empty", page = page)
elif not request.form.get("check"):
return render_template("errors/general_error.html", error = "Check Password field is Empty", page = page)
elif not request.form.get("answer"):
return render_template("errors/general_error.html", error = "answer field is Empty", page = page)
#something at the end
</code></pre>
<p>this will return a page with the validation error massage.</p>
<p>I need to loop through an element gives me names of all the inputs inside the form & I'll return the error massage due to it..</p>
<p>& code will be like:</p>
<pre><code>for i in needed_element:
if not i:
return render_template("errors/general_error.html", error = f"{i} field is Empty", page = page)
</code></pre>
<p>or something similar or any more elegant way because I'm repeating this step many times in the project :'D</p>
|
[] |
[
{
"body": "<h2>Readability</h2>\n<p>Before addressing the main concern, readability should be addressed.</p>\n<p>Many python developers adhere to <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> for consistent code style.</p>\n<p>This code does not adhere to a few aspects:</p>\n<blockquote>\n<p>Limit all lines to a maximum of 79 characters. <br><br>For flowing long blocks of text with fewer structural restrictions (docstrings or comments), the line length should be limited to 72 characters.</p>\n</blockquote>\n<blockquote>\n<p>Don't use spaces around the = sign when used to indicate a keyword argument, or when used to indicate a default value for an unannotated function parameter:</p>\n</blockquote>\n<h2>Repeated code</h2>\n<p>As you already identified, the code to check for missing fields in order to display validation prior errors is quite redundant. This goes against the <a href=\"http://deviq.com/don-t-repeat-yourself/\" rel=\"nofollow noreferrer\"><em><strong>D</strong>on't <strong>R</strong>epeat <strong>Y</strong>ourself</em> principle </a>.</p>\n<p>One option is to abstract out the fields to check into a dictionary:</p>\n<pre><code>field_mapping = {'username': 'Username', 'password': 'Password',\n 'check': 'Check Password', 'answer': 'Answer'}\n</code></pre>\n<p>Then the <code>items()</code> method can be used to <a href=\"https://docs.python.org/3/tutorial/datastructures.html#looping-techniques\" rel=\"nofollow noreferrer\">iterate through the keys and values</a>, unpacked to a tuple:</p>\n<pre><code>for field, label in field_mapping.items():\n if not request.form.get(field):\n return render_template("errors/general_error.html",\n error=f"{label} field is Empty", page=page)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T15:52:50.360",
"Id": "525401",
"Score": "0",
"body": "many thanks for Readability instruction's.\nI found that too I can easily do\n```\nfor i in request.form:\n if not request.form.get(i):\n return render_template(\"errors/general_error.html\", error = i + \" field is Empty\", page=page)\n```"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T16:02:28.443",
"Id": "525406",
"Score": "0",
"body": "Ah I had considered mentioning that but figured it wouldn't allow customizing the label - e.g. `check` -> `Check Password`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T16:11:48.413",
"Id": "525408",
"Score": "1",
"body": "that's a nice concentration, I find that too so I changed the input names to be `check -> check_password` then applying `\"check_password\".replace(\"_\",\" \").capitalize()` when returning values to jinja."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T05:56:19.407",
"Id": "265979",
"ParentId": "265974",
"Score": "2"
}
},
{
"body": "<p>I found that I can iterate through form inputs by doing this..</p>\n<pre><code>for i in request.form:\n if not request.form.get(i):\n return render_template("errors/general_error.html", error = i + " field is Empty", page=page)\n</code></pre>\n<p>as request.form will give you a list contains all names of inputs in form.</p>\n<p>Note: it excludes <code><input type="submit" value="Sign Up"></code> by default, because this input have no name.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T15:59:10.883",
"Id": "265996",
"ParentId": "265974",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-11T21:49:15.250",
"Id": "265974",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"validation",
"flask"
],
"Title": "Displaying validation messages for an input form"
}
|
265974
|
<p>From <a href="https://github.com/App-vNext/Polly" rel="nofollow noreferrer">GitHub</a>:</p>
<blockquote>
<p><a href="http://www.thepollyproject.org" rel="nofollow noreferrer">Polly</a> is a .NET resilience and transient-fault-handling library that allows developers to express policies such as <a href="https://github.com/App-vNext/Polly/wiki/Retry" rel="nofollow noreferrer">Retry</a>, <a href="https://github.com/App-vNext/Polly/wiki/Circuit-Breaker" rel="nofollow noreferrer">Circuit Breaker</a>, <a href="https://github.com/App-vNext/Polly/wiki/Timeout" rel="nofollow noreferrer">Timeout</a>, <a href="https://github.com/App-vNext/Polly/wiki/Bulkhead" rel="nofollow noreferrer">Bulkhead Isolation</a>, and <a href="https://github.com/App-vNext/Polly/wiki/Fallback" rel="nofollow noreferrer">Fallback</a> in a fluent and thread-safe manner. Polly targets .NET Standard 1.1 and 2.0+.</p>
</blockquote>
<p>For further information read <a href="https://github.com/App-vNext/Polly/wiki/" rel="nofollow noreferrer">Polly's wiki</a>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T09:40:12.123",
"Id": "265984",
"Score": "0",
"Tags": null,
"Title": null
}
|
265984
|
"Polly is a [...] resilience and transient-fault-handling library" for ".NET Standard 1.1 and .NET Standard 2.0."
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T09:40:12.123",
"Id": "265985",
"Score": "0",
"Tags": null,
"Title": null
}
|
265985
|
<h1>Overview</h1>
<p>I am working on an android To-Do app. I have a piece of code that I use to work with tasks.I am new to android development and want to grow, so I would really like someone to rate my code and tell me how i can make it better.</p>
<h1>Code</h1>
<p>TaskManager.kt</p>
<pre><code>class TaskManager {
fun isNeedShowNotification(task: Task): Boolean {
return when (task.repeatInterval) {
RepeatInterval.Once -> true
RepeatInterval.EveryDay -> true
RepeatInterval.Weekends -> return LocalDate.now().dayOfWeek == DayOfWeek.SATURDAY || LocalDate.now().dayOfWeek == DayOfWeek.SUNDAY
RepeatInterval.WorkingDays -> return LocalDate.now().dayOfWeek != DayOfWeek.SATURDAY && LocalDate.now().dayOfWeek != DayOfWeek.SUNDAY
}
}
fun getInProgressTaskTasksByList(tasks: List<Task>, listId: Long): List<TasksForTimeStatus> {
return getTasksForTimeStatuses(getInProgressTasksWithListId(tasks, listId))
}
fun getFinishedTasksForTimeStatuses(tasks: List<Task>): List<TasksForTimeStatus> {
return getTasksForTimeStatuses(getFinishedTasks(tasks))
}
fun getInProgressTasksForTimeStatuses(tasks: List<Task>): List<TasksForTimeStatus> {
return getTasksForTimeStatuses(getInProgressTasks(tasks))
}
private fun getTasksForTimeStatuses(tasks: List<Task>): List<TasksForTimeStatus> {
val timeStatuses: MutableList<TasksForTimeStatus> = ArrayList()
tasks.sortedBy { task -> task.notificationDate.epochMillis }
.forEach {
if (timeStatuses.size == 0) {
addNewTasksTimeStatus(timeStatuses, it)
} else {
if (timeStatuses.last().taskTimeStatus == getTaskTimeStatus(it))
addTask(timeStatuses, it)
else {
addNewTasksTimeStatus(timeStatuses, it)
}
}
}
return timeStatuses
}
private fun getInProgressTasksWithListId(tasks: List<Task>, listId: Long): List<Task> {
return getInProgressTasks(tasks).filter { it.taskList == listId }
}
private fun getInProgressTasks(tasks: List<Task>): List<Task> {
return getTasks(tasks).filter { task -> task.status == TaskStatus.InProgress }
}
private fun getFinishedTasks(tasks: List<Task>): List<Task> {
return getTasks(tasks).filter { task -> task.status == TaskStatus.Finished }
}
private fun getTasks(tasks: List<Task>): List<Task> {
return tasks.filter { task -> !task.isDeleted }
}
private fun getTaskTimeStatus(task: Task): TaskTimeStatus {
val timeNow = Date(LocalDateTime.now())
val timeTomorrow = timeNow + TimeUnit.DAYS.toMillis(1)
return when {
task.notificationDate.epochMillis - timeNow.epochMillis < 0 -> TaskTimeStatus.Overdue
timeNow.toLongString() == task.notificationDate.toLongString() -> TaskTimeStatus.Today
timeTomorrow.toLongString() == task.notificationDate.toLongString() -> TaskTimeStatus.Tomorrow
task.notificationDate.epochMillis - TimeUnit.DAYS.toMillis(30) <= timeNow.epochMillis -> TaskTimeStatus.ThisMonth
else -> TaskTimeStatus.Later
}
}
private fun addNewTasksTimeStatus(timeStatuses: MutableList<TasksForTimeStatus>, task: Task) {
timeStatuses.add(TasksForTimeStatus(getTaskTimeStatus(task)))
addTask(timeStatuses, task)
}
private fun addTask(timeStatuses: MutableList<TasksForTimeStatus>, task: Task) {
timeStatuses.last().addTask(task)
}
fun finishTaskByNotification(task: Task): Boolean {
if (task.repeatInterval == RepeatInterval.Once)
finishTask(task)
else
task.notificationDate = getNewNotificationDate(task)
task.isFIncisedOnce = true
return task.status == TaskStatus.Finished
}
private fun finishTask(task: Task) {
if (task.status != TaskStatus.Finished)
task.status = TaskStatus.Finished
else
task.status = TaskStatus.InProgress
}
private fun getNewNotificationDate(task: Task): Date {
val skipDays: Long
when (task.repeatInterval) {
RepeatInterval.EveryDay -> skipDays = 1
RepeatInterval.WorkingDays -> {
skipDays = when (task.notificationDate.getAsLocalDate().dayOfWeek) {
DayOfWeek.SATURDAY -> 2
DayOfWeek.FRIDAY -> 3
else -> 1
}
}
RepeatInterval.Weekends -> {
skipDays = when (task.notificationDate.getAsLocalDate().dayOfWeek) {
DayOfWeek.THURSDAY -> 2
DayOfWeek.WEDNESDAY -> 3
DayOfWeek.TUESDAY -> 4
DayOfWeek.MONDAY -> 5
else -> 1
}
}
else -> throw Exception("TaskManager do not know how get time for new notification for task with repeat interval - " + task.repeatInterval.name)
}
return task.notificationDate + TimeUnit.DAYS.toMillis(skipDays)
}
}
</code></pre>
<p>Task.kt</p>
<pre><code> @Entity
@Parcelize
class Task(
@PrimaryKey(autoGenerate = true) var id: Int = 0,
var taskList: Long = 0,
var taskText: String = "",
var repeatInterval: RepeatInterval = RepeatInterval.Once,
var notificationDate: Date = Date(0),
var isNotificationNeed: Boolean = false,
var status: TaskStatus = TaskStatus.InProgress,
var taskColor: Int = -1972243,
var isFIncisedOnce: Boolean = false,
var isDeleted: Boolean = false
) : Parcelable {
fun copy() = Task(id, taskList, taskText, repeatInterval, notificationDate, isNotificationNeed, status,taskColor,isFIncisedOnce,isDeleted)
override fun equals(other: Any?): Boolean {
if (other == null || other !is Task) return false
return id == other.id && taskList == other.taskList && taskText == other.taskText && repeatInterval.id == other.repeatInterval.id &&
notificationDate.epochMillis == other.notificationDate.epochMillis && isNotificationNeed == other.isNotificationNeed &&
status.name == other.status.name && taskColor == other.taskColor && isDeleted == other.isDeleted
}
}
</code></pre>
<p>TasksForTimeStatus.kt</p>
<pre><code> class TasksForTimeStatus(var taskTimeStatus:TaskTimeStatus){
val tasks: MutableList<Task> = ArrayList()
fun addTask(task:Task){
tasks.add(task)
}
}
</code></pre>
<p>TaskTimeStatus.kt</p>
<pre><code>enum class TaskTimeStatus (private val stringId:Int){
Overdue(R.string.overdue),
Today(R.string.today),
Tomorrow(R.string.tomorrow),
ThisMonth(R.string.thismonth),
Later(R.string.later);
fun getString(context: Context): String {
return context.getString(stringId)
}
}
</code></pre>
<p>RepeatInterval.kt</p>
<pre><code>enum class RepeatInterval(val id: Int,private val stringId:Int) {
Once(0, R.string.repeat_interval_once),
EveryDay(1,R.string.repeat_interval_every_day),
WorkingDays(2,R.string.working_days_interval),
Weekends(3,R.string.weekends_interval);
fun toString(context: Context): String {
return context.getString(stringId)
}
companion object {
fun getById(id: Int): RepeatInterval {
values().forEach {
if (it.id == id)
return it
}
throw Exception("Cant find RepeatInterval with id - $id")
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T13:19:02.660",
"Id": "525455",
"Score": "1",
"body": "Since Code Review doesn't get a ton of daily traffic, you might not want to be so quick to accept an answer, because it discourages further answers that might provide additional helpful advice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T14:00:16.060",
"Id": "525460",
"Score": "0",
"body": "thanks for the advice"
}
] |
[
{
"body": "<p>The word "manager" is a class name trap. It's vague and if you don't have a clear idea of exactly what the class is responsible for, you're in danger of violating the single responsibility principle. You might be tempted to add too much functionality into this one class.</p>\n<p>But in your case, you're not using it the way I've typically seen, which would be storing the list of tasks and doing various operations on it. These are all utility functions for working with arbitrary <code>List<Task></code>s. They are better suited to be extension functions. There's also no reason to have a class if it has no properties. Then you have to instantiate something for no reason just to use its functions.</p>\n<p>I would name the file something like <code>TaskLists.kt</code> and make these top level extension functions with receiver <code>List<Task></code>. For the functions that work with a single Task, pretty much all of them look to me like they should simply be member functions of the Task class.</p>\n<p><code>isNeedShowNotification</code> will be shorter and easier/faster to comprehend if you have a utility function for determining if it's the weekend. And it makes it easier to modify later, like if you decide to add a localization that changes which days are considered weekend.</p>\n<pre><code>private fun isNowWeekend(): Boolean = \n LocalDate.now().dayOfWeek.let { it == DayOfWeek.SATURDAY || it == DayOfWeek.SUNDAY }\n\nfun Task.isNeedShowNotification: Boolean {\n return when (task.repeatInterval) {\n RepeatInterval.Once, RepeatInterval.EveryDay -> true\n RepeatInterval.Weekends -> isNowWeekend()\n RepeatInterval.WorkingDays -> !isNowWeekend()\n }\n}\n</code></pre>\n<p>The name TaskTimeStatus could drop the word Task to make code easier to read. After all, the enum itself has no notion of a Task. With the word Task in its name, you end up littering your code all over the place with the word <code>task</code> both for the Task class and the TaskTimeStatus enum, making it harder to follow.</p>\n<p>I think the TasksForTimeStatus class contributes to your code being more complicated. It takes an extra step each time you want to unpack the list of Tasks that go with each TaskTimeStatus. The name is also wordy. Since you pass around lists of TasksForTimeStatus, anyway, I think it would be simpler to eliminate this class and replace your uses of <code>List<TasksForTimeStatus></code> with <code>Map<TimeStatus, List<Task>></code>.</p>\n<p>Then, <code>getTasksForTimeStatuses</code> could become much simpler:</p>\n<pre><code>private fun List<Task>.byCurrentTimeStatus(): Map<TaskTimeStatus, List<Task>> {\n return tasks.sortedBy { task -> task.notificationDate.epochMillis }\n .groupBy(Task::getCurrentTimeStatus)\n}\n\nprivate fun Task.getCurrentTimeStatus(): TimeStatus {\n // your existing getTaskTimeStatus as an extension function with clearer name\n}\n</code></pre>\n<p>In <code>getNewNotificationDate</code>, you should use the <code>when</code> block as an expression instead of a statement since all branches either throw or assign a value to <code>skipDays</code>. Basically <code>val skipDays = when //...</code>.</p>\n<p>For the Task class, it is incorrect to override <code>toString()</code> without overriding <code>hashCode()</code> to match it. But in this case, you can have it done for you automatically by marking it as a <code>data</code> class. Then the <code>copy</code> function will be written for you, too.</p>\n<p>And a minor tip, the function in RepeatInterval's companion could be simplified to:</p>\n<pre><code> fun getById(id: Int): RepeatInterval {\n return values().firstOrNull { it.id == id } \n ?: error("Cant find RepeatInterval with id - $id")\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T19:37:56.503",
"Id": "266005",
"ParentId": "265988",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "266005",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T11:56:41.460",
"Id": "265988",
"Score": "1",
"Tags": [
"android",
"kotlin",
"to-do-list"
],
"Title": "Code for working with a tasks in To-Do Android application"
}
|
265988
|
<p>I want to learn Java, so I ported a C# Enigma implementation of mine. It got UnitTests and is running.</p>
<p>I'm looking for a review, telling me, where I don't know best practices, where I break naming conventions, where I look like a C# programmer writing Java:-)</p>
<p>Thanks & have fun Harry</p>
<p><a href="https://github.com/HaraldLeitner/Enigma" rel="nofollow noreferrer">https://github.com/HaraldLeitner/Enigma</a></p>
<p>BusniessLogic.java</p>
<pre><code>package main;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class BusinessLogic {
private List<Roll> Rolls;
private List<Roll> RollsReverse;
public BusinessLogic(List<Roll> rolls) {
Rolls = rolls;
RollsReverse = new ArrayList<Roll>(rolls);
Collections.reverse(RollsReverse);
}
public void TransformFile(String inputFfilename, String outputFilename, Enums.Mode mode) throws IOException {
final int buffersize = 65536;
FileInputStream fileInStream = new FileInputStream(inputFfilename);
FileOutputStream fileOutStream = new FileOutputStream(outputFilename);
byte[] buffer = new byte[buffersize];
int readCount = 0;
while ((readCount = fileInStream.read(buffer, 0, buffersize)) > 0) {
TransformByteArray(buffer, mode);
fileOutStream.write(buffer, 0, readCount);
}
fileInStream.close();
fileOutStream.close();
}
public void TransformByteArray(byte[] input, Enums.Mode mode) {
if (mode == Enums.Mode.Encode) {
for (int i = 0; i < input.length; i++) {
for (Roll roll : Rolls)
input[i] = roll.Encrypt(input[i]);
RollOn();
}
}
if (mode == Enums.Mode.Decode) {
for (int i = 0; i < input.length; i++) {
for (Roll roll : RollsReverse)
input[i] = roll.Decrypt(input[i]);
RollOn();
}
}
}
private void RollOn() {
for (Roll roll : Rolls) {
if (!roll.RollOn())
break;
}
}
}
</code></pre>
<p>Enigma.Properties</p>
<pre><code>TransitionCount = 53
</code></pre>
<p>Enums.java</p>
<pre><code>package main;
public class Enums
{
public enum Mode
{
Encode,
Decode
};
}
</code></pre>
<p>Program.java</p>
<pre><code>package main;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Random;
public class Program {
private static List<Roll> Rolls;
private static Enums.Mode Mode;
private static String KeyFilename;
private static String InputFileName;
private static int TransitionCount;
public static void main(String[] args) throws Exception {
if (args.length != 3) {
System.out.println("Generate key with 'keygen x key.file' where x > 3 is the number of rolls.");
System.out.println("Encrypt a file with 'enc a.txt key.file'");
System.out.println("Decrypt a file with 'dec a.txt key.file'");
return;
}
ReadProperties();
KeyFilename = args[2];
if (args[0].compareToIgnoreCase("keygen") == 0) {
Keygen(Integer.parseInt(args[1]));
return;
}
InputFileName = args[1];
CreateRolls();
if (args[0].compareToIgnoreCase("enc") == 0)
Mode = Enums.Mode.Encode;
else if (args[0].compareToIgnoreCase("dec") == 0)
Mode = Enums.Mode.Decode;
else
throw new Exception("Undefined Encryption Mode.");
BusinessLogic businessLogic = new BusinessLogic(Rolls);
businessLogic.TransformFile(InputFileName, InputFileName + "." + Mode, Mode);
}
private static void ReadProperties() throws FileNotFoundException, IOException {
Properties prop = new Properties();
prop.load(new FileInputStream("Enigma.properties"));
TransitionCount = Integer.parseInt(prop.getProperty("TransitionCount"));
}
private static void CreateRolls() throws Exception {
Rolls = new ArrayList<Roll>();
int rollKeylength = 256 + TransitionCount;
byte[] definition = new byte[(int) new File(KeyFilename).length()];
FileInputStream fileInputStream = new FileInputStream(KeyFilename);
fileInputStream.read(definition);
fileInputStream.close();
if (definition.length % rollKeylength > 0)
throw new Exception("Invalid Keysize");
int rollCount = definition.length / rollKeylength;
for (int rollNumber = 0; rollNumber < rollCount; rollNumber++) {
List<Integer> transitions = new ArrayList<Integer>();
for (int index = 0; index < TransitionCount; index++)
transitions.add((int) definition[rollNumber * rollKeylength + 256 + index]);
byte[] singleRoll = new byte[256];
for(int index = 0; index < 256; index ++)
singleRoll[index] = definition[rollNumber * rollKeylength + index];
Rolls.add(new Roll(singleRoll, transitions));
}
for (Roll roll : Rolls)
roll.CheckInput(TransitionCount);
}
private static void Keygen(int rollCount) throws Exception {
if (rollCount < 4)
throw new Exception("Not enough rolls.");
Random random = new Random();
if((new File(KeyFilename)).exists())
Files.delete(Paths.get(KeyFilename));
byte[] key = new byte[(256 + TransitionCount) * rollCount] ;
for (int i = 0; i < rollCount; i++) {
byte[] transform = new byte[256];
for (int j = 0; j <= 255; j++)
transform[j] = (byte) j;
while (!IsTwisted(transform)) {
for (int j = 0; j < 256 * 2; j++) {
int rand1 = random.nextInt(256);
int rand2 = random.nextInt(256);
byte temp = transform[rand1];
transform[rand1] = transform[rand2];
transform[rand2] = temp;
}
}
for (int index = 0; index < 256; index++)
key[(256 + TransitionCount) * i + index] = transform[index];
List<Integer> transitions = new ArrayList<Integer>();
while (transitions.size() < TransitionCount)
{
int rand = random.nextInt(256);
if (!transitions.contains(rand))
transitions.add(rand);
}
for (int index = 0; index < TransitionCount; index++)
key[(256 + TransitionCount) * i + 256 + index] = (byte)(int) transitions.get(index);
}
FileOutputStream fileOutputStream = new FileOutputStream(KeyFilename);
fileOutputStream.write(key);
fileOutputStream.close();
System.out.println("Keys generated.");
Thread.sleep(1000);
}
private static boolean IsTwisted(byte[] trans) {
for (int i = 0; i <= 255; i++)
if (trans[i] == i)
return false;
return true;
}
}
</code></pre>
<p>Roll.java</p>
<pre><code>package main;
import java.util.Collections;
import java.util.List;
public class Roll
{
private int Position; //This is the actual position of this roll starting at 0
private byte[] Transitions; //This is the wiring of the roll: if Transitions[0] = 0x04 the value 0x00 will be mapped to 0x04
private List<Integer> TurnOverIndices; //While rolling after each char encryption the next roll will also rotate, if these indices contain Position
private byte[] ReTransitions; //Reverted transitionlist for decryption
public Roll(byte[] transitions, List<Integer> turnOverIndices) {
Transitions = transitions;
TurnOverIndices = turnOverIndices;
Position = 0;
ReTransitions = new byte[256];
for (int i = -128; i < 128; i++)
ReTransitions[Transitions[i + 128] + 128] = (byte) i;
}
public void CheckInput(int transitionCount) throws Exception {
if (Transitions.length != 256)
throw new Exception("Wrong Transition length ");
for (int i = -128; i < 128; i++) {
boolean found = false;
for (int j = 0; j < 256; j++)
{
if (Transitions[j] == i)
{
found = true;
break;
}
}
if (!found)
throw new Exception("Transitions not 1-1 complete. Problem at " + i);
}
if (TurnOverIndices.size() != transitionCount)
throw new Exception("Wrong TurnOverIndices length ");
Collections.sort(TurnOverIndices);
for (int i = 0; i < TurnOverIndices.size() - 1; i++)
if (TurnOverIndices.get(i) == TurnOverIndices.get(i + 1))
throw new Exception("Turnoverindizes has doubles");
}
public byte Encrypt(byte input) {
return Transitions[((input + Position + 128)%256)];
}
public byte Decrypt(byte input) {
return (byte) (ReTransitions[input + 128] - Position);
}
public boolean RollOn() {
Position = (Position + 1) % 256;
return TurnOverIndices.contains(Position);
}
}
</code></pre>
<p>UnitTest.java</p>
<pre><code>package test;
import static org.junit.jupiter.api.Assertions.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.imageio.stream.FileImageInputStream;
import javax.xml.stream.events.EntityDeclaration;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import main.*;
class UnitTest {
byte[] transLinear = new byte[256]; // here every char is mapped to itself
byte[] transLinearInvert = new byte[256]; // match the first to the last etc
byte[] transShift1 = new byte[256]; // 'a' is mapped to 'b' etc
byte[] transShift2 = new byte[256]; // 'a' is mapped to 'c' etc
private BusinessLogic BusinessLogicEncode;
private BusinessLogic BusinessLogicDecode;
byte[] encryptedMsg;
byte[] decryptedMsg;
void Crypt(byte[] msg) {
encryptedMsg = msg.clone();
BusinessLogicEncode.TransformByteArray(encryptedMsg, Enums.Mode.Enc);
decryptedMsg = encryptedMsg.clone();
BusinessLogicDecode.TransformByteArray(decryptedMsg, Enums.Mode.Dec);
}
@BeforeEach
public void Init() {
for (int i = -0; i < 256; i++)
transLinear[i] = (byte) (i - 128);
for (int i = 0; i < 256; i++)
transLinearInvert[i] = (byte) (255 - i - 128);
for (int i = 0; i < 256; i++)
transShift1[i] = (byte) ((i + 1 - 128) % 256);
for (int i = 0; i < 256; i++)
transShift2[i] = (byte) ((i + 2 - 128) % 256);
}
void InitBusinessLogic(ArrayList<byte[]> transitions, ArrayList<ArrayList<Integer>> turnovers) {
if (transitions.size() != turnovers.size())
assertFalse(true, "There must be as much transitions as roll defs!");
List<Roll> rollsEncrypt = new ArrayList<Roll>();
List<Roll> rollsDecrypt = new ArrayList<Roll>();
for (int i = 0; i < transitions.size(); i++) {
rollsEncrypt.add(new Roll(transitions.get(i), turnovers.get(i)));
rollsDecrypt.add(new Roll(transitions.get(i), turnovers.get(i)));
}
BusinessLogicEncode = new BusinessLogic(rollsEncrypt);
BusinessLogicDecode = new BusinessLogic(rollsDecrypt); // need a second, because the enc BusinessLogic has
// turned over rolls
}
@Test
public void OneByte1RollLinear() {
for (int i = -128; i < 128; i++) {
ArrayList<Integer> turnover = new ArrayList<>(Arrays.asList(0));
ArrayList<ArrayList<Integer>> turnovers = new ArrayList<ArrayList<Integer>>();
turnovers.add(turnover);
ArrayList<byte[]> transformation = new ArrayList<byte[]>();
transformation.add(transLinear);
InitBusinessLogic(transformation, turnovers);
Crypt(new byte[] { (byte) i });
assertEquals(i, encryptedMsg[0]);
assertEquals(i, decryptedMsg[0]);
}
}
@Test
public void OneByte1RollShift1() {
for (int i = -128; i < 128; i++) {
ArrayList<Integer> turnover = new ArrayList<>(Arrays.asList(0));
ArrayList<ArrayList<Integer>> turnovers = new ArrayList<ArrayList<Integer>>();
turnovers.add(turnover);
ArrayList<byte[]> transformation = new ArrayList<byte[]>();
transformation.add(transShift1);
InitBusinessLogic(transformation, turnovers);
Crypt(new byte[] { (byte) i });
assertEquals((byte) (i + 1), encryptedMsg[0]);
assertEquals(i, decryptedMsg[0]);
}
}
@Test
public void OneByte1RollShift2() {
for (int i = -128; i < 128; i++) {
ArrayList<Integer> turnover = new ArrayList<>(Arrays.asList(0));
ArrayList<ArrayList<Integer>> turnovers = new ArrayList<ArrayList<Integer>>();
turnovers.add(turnover);
ArrayList<byte[]> transformation = new ArrayList<byte[]>();
transformation.add(transShift2);
InitBusinessLogic(transformation, turnovers);
Crypt(new byte[] { (byte) i });
assertEquals((byte) (i + 2), encryptedMsg[0]);
assertEquals(i, decryptedMsg[0]);
}
}
@Test
public void TwoByte1RollLinear() {
for (int i = -128; i < 128; i++) {
ArrayList<Integer> turnover = new ArrayList<>(Arrays.asList(0));
ArrayList<ArrayList<Integer>> turnovers = new ArrayList<ArrayList<Integer>>();
turnovers.add(turnover);
ArrayList<byte[]> transformation = new ArrayList<byte[]>();
transformation.add(transLinear);
InitBusinessLogic(transformation, turnovers);
Crypt(new byte[] { (byte) i, (byte) ((i + 1)) });
assertEquals(i, encryptedMsg[0]);
assertEquals((byte) (i + 2), encryptedMsg[1]);
assertEquals(i, decryptedMsg[0]);
assertEquals((byte) (i + 1), decryptedMsg[1]);
}
}
@Test
public void TwoByte1RollShift() {
for (int i = -128; i < 128; i++) {
ArrayList<Integer> turnover = new ArrayList<>(Arrays.asList(0));
ArrayList<ArrayList<Integer>> turnovers = new ArrayList<ArrayList<Integer>>();
turnovers.add(turnover);
ArrayList<byte[]> transformation = new ArrayList<byte[]>();
transformation.add(transShift1);
InitBusinessLogic(transformation, turnovers);
Crypt(new byte[] { (byte) i, (byte) ((i + 1)) });
assertEquals((byte) (i + 1), encryptedMsg[0]);
assertEquals((byte) (i + 3), encryptedMsg[1]);
assertEquals(i, decryptedMsg[0]);
assertEquals((byte) (i + 1), decryptedMsg[1]);
}
}
@Test
public void TwoByte1RollInvert() {
for (int i = -128; i < 128; i++) {
ArrayList<Integer> turnover = new ArrayList<>(Arrays.asList(0));
ArrayList<ArrayList<Integer>> turnovers = new ArrayList<ArrayList<Integer>>();
turnovers.add(turnover);
ArrayList<byte[]> transformation = new ArrayList<byte[]>();
transformation.add(transLinearInvert);
InitBusinessLogic(transformation, turnovers);
Crypt(new byte[] { (byte) i, (byte) ((i)) });
assertEquals((byte) (-i - 1), encryptedMsg[0]);
assertEquals((byte) (-i - 2), encryptedMsg[1]);
assertEquals(i, decryptedMsg[0]);
assertEquals(i, decryptedMsg[1]);
}
}
@Test
public void TwoByte2RollLinearInvert() {
for (int i = -128; i < 128; i++) {
ArrayList<Integer> turnover = new ArrayList<>(Arrays.asList(0));
ArrayList<ArrayList<Integer>> turnovers = new ArrayList<ArrayList<Integer>>();
turnovers.add(turnover);
turnovers.add(turnover);
ArrayList<byte[]> transformation = new ArrayList<byte[]>();
transformation.add(transLinearInvert);
transformation.add(transLinearInvert);
InitBusinessLogic(transformation, turnovers);
Crypt(new byte[] { (byte) i, (byte) ((i + 1)) });
assertEquals(i, encryptedMsg[0]);
assertEquals((byte) (i + 2), encryptedMsg[1]);
assertEquals(i, decryptedMsg[0]);
assertEquals((byte) (i + 1), decryptedMsg[1]);
}
}
@Test
public void TwoByte2RollShift() {
for (int i = -128; i < 128; i++) {
ArrayList<Integer> turnover = new ArrayList<>(Arrays.asList(0));
ArrayList<ArrayList<Integer>> turnovers = new ArrayList<ArrayList<Integer>>();
turnovers.add(turnover);
turnovers.add(turnover);
ArrayList<byte[]> transformation = new ArrayList<byte[]>();
transformation.add(transShift1);
transformation.add(transShift1);
InitBusinessLogic(transformation, turnovers);
Crypt(new byte[] { (byte) i, (byte) ((i + 1)) });
assertEquals((byte) (i + 2), encryptedMsg[0]);
assertEquals((byte) (i + 4), encryptedMsg[1]);
assertEquals(i, decryptedMsg[0]);
assertEquals((byte) (i + 1), decryptedMsg[1]);
}
}
@Test
public void TwoByte2RollShift2() {
ArrayList<Integer> turnover = new ArrayList<>(Arrays.asList(0));
ArrayList<ArrayList<Integer>> turnovers = new ArrayList<ArrayList<Integer>>(0);
turnovers.add(turnover);
turnovers.add(turnover);
ArrayList<byte[]> transformation = new ArrayList<byte[]>();
transformation.add(transShift2);
transformation.add(transShift2);
InitBusinessLogic(transformation, turnovers);
Crypt(new byte[] { 7, 107 });
assertEquals(11, encryptedMsg[0]);
assertEquals(112, encryptedMsg[1]);
assertEquals(7, decryptedMsg[0]);
assertEquals(107, decryptedMsg[1]);
}
@Test
public void TwoByte2RollInvert() {
for (int i = -128; i < 128; i++) {
ArrayList<Integer> turnover = new ArrayList<>(Arrays.asList(0));
ArrayList<ArrayList<Integer>> turnovers = new ArrayList<ArrayList<Integer>>();
turnovers.add(turnover);
turnovers.add(turnover);
ArrayList<byte[]> transformation = new ArrayList<byte[]>();
transformation.add(transLinearInvert);
transformation.add(transLinearInvert);
InitBusinessLogic(transformation, turnovers);
Crypt(new byte[] { (byte) i, (byte) ((i + 1)) });
assertEquals((byte) (i), encryptedMsg[0]);
assertEquals((byte) (i + 2), encryptedMsg[1]);
assertEquals(i, decryptedMsg[0]);
assertEquals((byte) (i + 1), decryptedMsg[1]);
}
}
@Test
public void ThreeByte2RollTransit() {
ArrayList<Integer> always = new ArrayList<>();
for (int j = 0; j < 256; j++)
always.add(j);
for (int i = -128; i < 128; i++) {
ArrayList<ArrayList<Integer>> turnovers = new ArrayList<ArrayList<Integer>>();
turnovers.add(always);
turnovers.add(always);
ArrayList<byte[]> transformation = new ArrayList<byte[]>();
transformation.add(transLinear);
transformation.add(transLinear);
InitBusinessLogic(transformation, turnovers);
Crypt(new byte[] { (byte) i, (byte) (i + 1), (byte) (i + 2) });
assertEquals((byte) (i), encryptedMsg[0]);
assertEquals((byte) (i + 3), encryptedMsg[1]);
assertEquals((byte) (i + 6), encryptedMsg[2]);
assertEquals(i, decryptedMsg[0]);
assertEquals((byte) (i + 1), decryptedMsg[1]);
assertEquals((byte) (i + 2), decryptedMsg[2]);
}
}
@Test
public void TwoByte2DifferentRollsTransit() {
ArrayList<Integer> turnover = new ArrayList<>(Arrays.asList(0, 1, 2, 3, 4));
ArrayList<ArrayList<Integer>> turnovers = new ArrayList<ArrayList<Integer>>();
turnovers.add(turnover);
turnovers.add(turnover);
ArrayList<byte[]> transformation = new ArrayList<byte[]>();
transformation.add(transLinear);
transformation.add(transShift1);
InitBusinessLogic(transformation, turnovers);
Crypt(new byte[] { 7, 107 });
assertEquals(8, encryptedMsg[0]);
assertEquals(110, encryptedMsg[1]);
assertEquals(7, decryptedMsg[0]);
assertEquals(107, decryptedMsg[1]);
}
@Test
public void TwoByte2DifferentRollsTransit3() {
ArrayList<Integer> turnover = new ArrayList<>(Arrays.asList(0, 1, 2, 3, 4));
ArrayList<ArrayList<Integer>> turnovers = new ArrayList<ArrayList<Integer>>();
turnovers.add(turnover);
turnovers.add(turnover);
ArrayList<byte[]> transformation = new ArrayList<byte[]>();
transformation.add(transLinear);
transformation.add(transLinearInvert);
InitBusinessLogic(transformation, turnovers);
Crypt(new byte[] { 7, 107 });
assertEquals(-8, encryptedMsg[0]);
assertEquals(-110, encryptedMsg[1]);
assertEquals(7, decryptedMsg[0]);
assertEquals(107, decryptedMsg[1]);
}
@Test
public void RealLive()
{
int msgSize = 5 * 65536;
byte[] msg = new byte[msgSize];
for (int i = 0; i < msgSize; i++)
msg[i] = (byte)(i);
ArrayList<Integer> turnover1 = new ArrayList<>(Arrays.asList(0, 22, 44, 100));
ArrayList<Integer> turnover2 = new ArrayList<>(Arrays.asList(11, 44, 122, 200));
ArrayList<Integer> turnover3 = new ArrayList<>(Arrays.asList(33, 77, 99, 222));
ArrayList<Integer> turnover4 = new ArrayList<>(Arrays.asList(55, 67, 79, 240));
ArrayList<ArrayList<Integer>> turnovers = new ArrayList<ArrayList<Integer>>();
turnovers.add(turnover1);
turnovers.add(turnover2);
turnovers.add(turnover3);
turnovers.add(turnover4);
ArrayList<byte[]> transformation = new ArrayList<byte[]>();
transformation.add(transLinear);
transformation.add(transLinearInvert);
transformation.add(transShift1);
transformation.add(transShift2);
InitBusinessLogic(transformation, turnovers);
Crypt(msg);
assertEquals(msg.length, decryptedMsg.length);
Crypt(msg);
for (int i = 0; i < msgSize; i++)
assertEquals(msg[i], decryptedMsg[i]);
}
@Test
public void Integrationtest() throws Exception
{
int msgSize = 5 * 65536; //bigger than buffersize:-)
String keyname = "any.key";
String msgFileName = "msg.file";
byte[] msg = new byte[msgSize];
for (int i = 0; i < msgSize; i++)
msg[i] = (byte)(i % 256);
FileOutputStream fileOutputStream = new FileOutputStream(msgFileName);
fileOutputStream.write(msg);
fileOutputStream.close();
Program.main(new String[] { "keygen", "4", keyname});
Program.main(new String[] { "enc", msgFileName, keyname });
Program.main(new String[] { "dec", msgFileName + ".Enc", keyname });
byte[] encdec = new byte[msgSize];
FileInputStream fileInputStream = new FileInputStream(msgFileName + ".Enc.Dec");
fileInputStream.read(encdec);
fileInputStream.close();
for(int i = 0; i < msg.length; i++)
assertEquals(msg[i], encdec[i]);
assertEquals(msg.length, encdec.length);
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>Basically, I don't see too many C# - Java issues other than the method naming and the enum, where you seemed to have gone from <code>namespace</code> to <code>class</code> while the class is unnecessary in Java.</p>\n<p>Unfortunately I see a lot of problems that would be equally bad in C# as well as in Java, or any other programming language for that matter.</p>\n<h2>C# -> Java</h2>\n<p><strong>BusinessLogic class</strong></p>\n<pre><code>public void TransformFile(String inputFfilename, String outputFilename, Enums.Mode mode) throws IOException {\n</code></pre>\n<p>Method names should not start with a capitalized letter in Java, this is different from C#.</p>\n<h2>Other issues</h2>\n<p><strong>BusinessLogic class</strong></p>\n<pre><code>private List<Roll> Rolls;\n</code></pre>\n<p>I don't think that fields are even capitalized in C#, but it is still wrong.</p>\n<hr />\n<pre><code>Rolls = rolls;\n</code></pre>\n<p>should be (after renaming the fields):</p>\n<pre><code>this.rolls = Objects.requireNonNull(rolls, "Parameter rolls should not be null");\n</code></pre>\n<p>Generally we want to avoid copying data, but in this case you do need to do this. However, in that case it is better to use <code>List.copyOf(rolls);</code> if the list itself won't be changed (as this allows trickery to make it more efficient).</p>\n<p>Note that because a <code>Roll</code> is mutable it can be changed outside of the class, so you would normally also copy the referenced <code>Roll</code> instances themselves.</p>\n<hr />\n<pre><code>final int buffersize = 65536;\n</code></pre>\n<p>The <code>buffersize</code> should be a constant (<code>private static final int BUFFER_SIZE = 0x10000;</code>).</p>\n<hr />\n<pre><code>FileInputStream fileInStream = new FileInputStream(inputFfilename);\n</code></pre>\n<p>Resource creation should always take place using "try-with-resources":</p>\n<pre><code>try (FileInputStream fileInStream = new FileInputStream(inputFfilename;\n FileOutputStream fileOutStream = new FileOutputStream(outputFilename)) {\n // your stream handling here\n}\n</code></pre>\n<p>This would also remove the <code>close()</code> lines, and remove the probem if the first <code>close()</code> throws an exception.</p>\n<hr />\n<p><strong>Program class</strong></p>\n<pre><code>private static List<Roll> Rolls;\n</code></pre>\n<p>Never ever use mutable class fields, just create a <code>Program</code> instance and use multiple fields. In principle, it is completely possible to call <code>Program.main(String[] args)</code> multiple times. Using local variables would however be even more logical.</p>\n<hr />\n<pre><code>if (args[0].compareToIgnoreCase("enc") == 0)\n Mode = Enums.Mode.Encode;\n</code></pre>\n<p>Always use blocks, even if you just execute one statement in an <code>if</code>.</p>\n<hr />\n<pre><code>businessLogic.TransformFile(InputFileName, InputFileName + "." + Mode, Mode);\n</code></pre>\n<p>One nice thing of Java is that you can have enums with fields, e.g.:</p>\n<pre><code>public enum Mode {\n ENCODE("enc"),\n DECODE("dec");\n\n private String extension;\n private Mode(String extension) {\n this.extension = extension;\n }\n public String getExtension() {\n return this.extension;\n }\n}\n</code></pre>\n<hr />\n<p>Ignored exception when the <code>"TransitionCount"</code> property is not present.</p>\n<pre><code>TransitionCount = Integer.parseInt(prop.getProperty("TransitionCount"));\n</code></pre>\n<hr />\n<pre><code>Random random = new Random();\n</code></pre>\n<p>Try <code>Random random = new SecureRandom()</code>, we're doing cryptography here (also note the difference in C# where .NET made the horrible mistake of having a secure random class that doesn't extend the <code>Random</code> class.)</p>\n<hr />\n<pre><code>if((new File(KeyFilename)).exists())\n Files.delete(Paths.get(KeyFilename));\n</code></pre>\n<p>Not needed, file will be overwritten automatically, appending is optional.</p>\n<hr />\n<p>Use a logger, a debugger and always indicate debugging code with a <code>// TODO remove</code> or <code>// DEBUG testing only</code> comment. Don't ever call <code>sleep(1000)</code>, that's why breakpoints exist.</p>\n<pre><code>System.out.println("Keys generated.");\nThread.sleep(1000);\n</code></pre>\n<hr />\n<pre><code>throw new Exception("Turnoverindizes has doubles");\n</code></pre>\n<p>Perfect time to create an Enigma specific exception.</p>\n<p><strong>Rolls class</strong></p>\n<pre><code>private byte[] Transitions; //This is the wiring of the roll: if Transitions[0] = 0x04 the value 0x00 will be mapped to 0x04\n</code></pre>\n<p>You are now mixing integers and bytes, and arrays and lists. I would use <code>List<Integer></code> here as well, or use a <code>Map</code>.</p>\n<pre><code>public Roll(byte[] transitions, List<Integer> turnOverIndices) {\n</code></pre>\n<p>Again, the lists are not copied and remain mutable from outside.</p>\n<hr />\n<pre><code>ReTransitions = new byte[256];\nfor (int i = -128; i < 128; i++)\n ReTransitions[Transitions[i + 128] + 128] = (byte) i;\n</code></pre>\n<p>Copious use of magic values here, and an assumption about the size of the list in an input parameter.</p>\n<hr />\n<pre><code>public void CheckInput(int transitionCount) throws Exception {\n</code></pre>\n<p>Check input for <strong>what</strong>? Checks should return a result preferably, not throw an exception, as a calling class should not have to interpret the message.</p>\n<h2>Design issues</h2>\n<p>It's great to put the "business logic" into a separate class, but that doesn't mean that these class should be named <code>BusinessLogic</code>. What about <code>Enigma</code>?</p>\n<hr />\n<p>Enigma doesn't have rolls, it has <strong>rotors</strong>.</p>\n<hr />\n<p>The public enum <code>Mode</code> is specific to your <code>BusinessLogic</code> class. If you want to have it on the package level then you can just directly put it in a <code>Mode.java</code> class, but in this case I would advice against that.</p>\n<hr />\n<p>To me the rotors are immutable; which position (or location) they are in is specific to an Enigma machine. It's the machine that performs the encryption, not the rotor.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T16:04:42.290",
"Id": "525498",
"Score": "0",
"body": "I've skipped reviewing the math required to run Enigma."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-24T13:39:14.570",
"Id": "526164",
"Score": "0",
"body": "Changed the field capitalisation and the try - constructs. Interesting SecureRandom.\nGood advice, thx!\nChanged it on github."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-24T13:39:43.867",
"Id": "526165",
"Score": "0",
"body": "C# -> Java: \n The given Example IS starting with a capitalized character.\nBusinessLogic : \n Since it is working, copying is not necessary. Additional copying is just slowing down.\n Why should I follow an advice for extra memcopies?\n Buffersize IS a const, because it is marked final.\n Blocking a single statement line is disussed in different Java groups with different results."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-24T13:39:58.710",
"Id": "526166",
"Score": "0",
"body": "Magic Numbers / BIT-Arithmethic: In the businesslogic it is time critical, the operation time is linear to the input size.\n That's why a array of ptimitiv types is used, so you can calculate with the indices.\n Crucial is the absence of unsigned byte. At least I can avoid the magic numbers.\n Is there a beautiful way of bitcalculations?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-24T13:40:14.707",
"Id": "526167",
"Score": "0",
"body": "If this kind of discussion is not appropriate on stackexchange, pls tell me and I will delete it!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T16:02:25.540",
"Id": "266055",
"ParentId": "265989",
"Score": "1"
}
},
{
"body": "<p>When using something that needs clean-up and implements <code>java.lang.AutoCloseable</code>, make it a habit to use <a href=\"https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow noreferrer\">try-with-resources</a>:</p>\n<pre><code>public void TransformFile(String inputFilename, String outputFilename, Enums.Mode mode) throws IOException {\n final int buffersize = i << 16;\n\n try (\n InputStream input = new FileInputStream(inputFilename);\n FileOutputStream output = new FileOutputStream(outputFilename);\n ) {\n input.transferTo(output);\n } // closed implicitly, even in case of an exception\n}\n</code></pre>\n<p>(To copy a file, it may be wiser to use <a href=\"https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/nio/file/Path.html\" rel=\"nofollow noreferrer\"><code>nio.file.Files.copy(Path source, Path target, CopyOption... options)</code></a>.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-21T10:26:24.633",
"Id": "266260",
"ParentId": "265989",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T11:58:10.893",
"Id": "265989",
"Score": "4",
"Tags": [
"java",
"beginner",
"cryptography"
],
"Title": "Enigma Implementation by JAVA newbie"
}
|
265989
|
<p>I want to learn Python, so I ported a C# Enigma implementation of mine. It got UnitTests and is running.</p>
<p>I'm looking for a review, telling me, where I don't know best practices, where I break naming conventions, where I look like a C# programmer writing Python:-)</p>
<p>Thanks & have fun Harry</p>
<p><a href="https://github.com/HaraldLeitner/Enigma" rel="nofollow noreferrer">https://github.com/HaraldLeitner/Enigma</a>
BusinessLogic.py</p>
<pre><code>from Enums import Mode
class BusinessLogic:
def __init__(self, rolls):
self._rolls = rolls
self._rolls_reverse = rolls.copy()
self._rolls_reverse.reverse()
def transform_file(self, infile, outfile, mode):
buffer_size = 65536
in_file = open(infile, 'rb', buffer_size)
out_file = open(outfile, 'wb', buffer_size)
buffer = bytearray(in_file.read(buffer_size))
while len(buffer):
self.transform_buffer(buffer, mode)
out_file.write(buffer)
buffer = bytearray(in_file.read(buffer_size))
in_file.close()
out_file.close()
def transform_buffer(self, buffer, mode):
if mode == Mode.ENC:
for i in range(len(buffer)):
for roll in self._rolls:
roll.encrypt(buffer, i)
self.roll_on()
if mode == Mode.DEC:
for i in range(len(buffer)):
for roll in self._rolls_reverse:
roll.decrypt(buffer, i)
self.roll_on()
def roll_on(self):
for roll in self._rolls:
if not roll.roll_on():
break
</code></pre>
<p>Enums.py</p>
<pre><code>from enum import Enum
class Mode(Enum):
ENC = 0
DEC = 1
</code></pre>
<p>Roll.py</p>
<pre><code>class Roll:
def __init__(self, transitions, turn_over_indices):
self._transitions = transitions
self._turn_over_indices = turn_over_indices
self._re_transitions = bytearray(256)
for x in self._transitions:
self._re_transitions[self._transitions[x]] = x
self._position = 0
def check_input(self, turnover_indices_count):
if len(self._transitions) != 256:
raise ValueError("Wrong Transition length ")
for i in range(256):
found = 0
for j in self._transitions:
if self._transitions[j] == i:
found = 1
continue
if not found:
raise ValueError("Transitions not 1-1 complete")
if len(self._turn_over_indices) != turnover_indices_count:
raise ValueError("Wrong TurnOverIndices length ")
for i in range(len(self._turn_over_indices) - 1):
if self._turn_over_indices[i] == self._turn_over_indices[i + 1]:
raise ValueError("turn_over_indices has doubles")
def encrypt(self, buffer, index):
buffer[index] = self._transitions[(buffer[index] + self._position) & 0xff]
def decrypt(self, buffer, index):
buffer[index] = (self._re_transitions[int(buffer[index])] - self._position) & 0xff
def roll_on(self):
self._position = (self._position + 1) & 0xff
return self._turn_over_indices.count(self._position)
</code></pre>
<p>Enigma.ini</p>
<pre><code>[DEFAULT]
TransitionCount = 53
</code></pre>
<p>Main.py</p>
<pre><code>from configparser import ConfigParser
import os
import sys
from random import random, randbytes, randint
from time import sleep
from BusinessLogic import BusinessLogic
from Enums import Mode
from Roll import Roll
class Program:
def __init__(self, transition_count=0):
self._mode = None
self._rolls = []
self._inputFilename = None
self._keyFilename = None
self._transitionCount = None
config = ConfigParser()
config.read("enigma.ini")
if transition_count < 1:
self._transitionCount = config.getint("DEFAULT", "TransitionCount")
else:
self._transitionCount = transition_count
def main(self):
if len(sys.argv) != 4:
print("Generate key with 'keygen x key.file' where x > 3 is the number of rolls.")
print("Encrypt a file with 'enc a.txt key.file'")
print("Decrypt a file with 'dec a.txt key.file'")
exit(1)
self.run_main(sys.argv[1], sys.argv[2], sys.argv[3])
def run_main(self, arg1, arg2, arg3):
self._keyFilename = arg3
if arg1 == "keygen":
self.keygen(int(arg2))
return
self._inputFilename = arg2
if arg1.lower() == 'enc':
self._mode = Mode.ENC
elif arg1 == 'dec':
self._mode = Mode.DEC
else:
raise Exception("Undefined Encryption Mode.")
self.create_rolls()
BusinessLogic(self._rolls).transform_file(self._inputFilename, self._inputFilename + '.' + self._mode.name,
self._mode)
def keygen(self, roll_count):
if roll_count < 4:
raise Exception("Not enough rolls.")
if os.path.exists(self._keyFilename):
os.remove(self._keyFilename)
key = bytearray()
for i in range(roll_count):
transform = bytearray(256)
for j in range(256):
transform[j] = j
while not self.is_twisted(transform):
for j in range(256):
rand1 = randint(0, 255)
rand2 = randint(0, 255)
temp = transform[rand1]
transform[rand1] = transform[rand2]
transform[rand2] = temp
key += transform
transitions = bytearray()
while len(transitions) < self._transitionCount:
rand = randint(0, 255)
if not transitions.count(rand):
transitions.append(rand)
key += transitions
file = open(self._keyFilename, 'wb')
file.write(key)
file.close()
print("Keys generated.")
sleep(1)
def is_twisted(self, trans):
for i in range(256):
if trans[i] == i:
return 0
return 1
def create_rolls(self):
roll_key_length = 256 + self._transitionCount
file = open(self._keyFilename, 'rb')
key = file.read()
file.close()
if len(key) % roll_key_length:
raise Exception('Invalid key_size')
roll_count = int(len(key) / roll_key_length)
for rollNumber in range(roll_count):
self._rolls.append(Roll(key[rollNumber * roll_key_length: rollNumber * roll_key_length + 256],
key[
rollNumber * roll_key_length + 256: rollNumber * roll_key_length + 256 + self._transitionCount]))
for roll in self._rolls:
roll.check_input(self._transitionCount)
if __name__ == '__main__':
Program().main()
</code></pre>
<p>UnitTest.py</p>
<pre><code>import os
import unittest
from BusinessLogic import BusinessLogic
from Enums import Mode
from Roll import Roll
from main import Program
class MyTestCase(unittest.TestCase):
def setUp(self):
self.trans_linear = bytearray(256) # here every char is mapped to itself
self.trans_linear_invert = bytearray(256) # match the first to the last etc
self.trans_shift_1 = bytearray(256) # 'a' is mapped to 'b' etc
self.trans_shift_2 = bytearray(256) # 'a' is mapped to 'c' etc
self.businesslogic_encode = None
self.businesslogic_decode = None
self.encrypted_message = bytearray()
self.decrypted_message = bytearray()
self.init_test_rolls()
def init_test_rolls(self):
for i in range(256):
self.trans_linear[i] = i
self.trans_linear_invert[i] = 255 - i
self.trans_shift_1[i] = (i + 1) % 256
self.trans_shift_2[i] = (i + 2) % 256
def init_business_logic(self, transitions, turnovers):
rolls_encrypt = []
rolls_decrypt = []
for index in range(len(transitions)):
rolls_encrypt.append(Roll(transitions[index], turnovers[index]))
rolls_decrypt.append(Roll(transitions[index], turnovers[index]))
self.businesslogic_encode = BusinessLogic(rolls_encrypt)
self.businesslogic_decode = BusinessLogic(rolls_decrypt)
def crypt(self, msg):
self.encrypted_message = bytearray(msg)
self.businesslogic_encode.transform_buffer(self.encrypted_message, Mode.ENC)
self.decrypted_message = bytearray(self.encrypted_message)
self.businesslogic_decode.transform_buffer(self.decrypted_message, Mode.DEC)
def test_one_byte_one_roll_linear(self):
for i in range(256):
self.init_business_logic([self.trans_linear], [[0]])
self.crypt([i])
self.assertEqual(i, self.encrypted_message[0])
self.assertEqual(i, self.decrypted_message[0])
def test_one_byte_one_roll_shift_one(self):
for i in range(256):
self.init_business_logic([self.trans_shift_1], [[0]])
self.crypt([i])
self.assertEqual((i + 1) % 256, self.encrypted_message[0])
self.assertEqual(i, self.decrypted_message[0])
def test_one_byte_one_roll_shift_two(self):
for i in range(256):
self.init_business_logic([self.trans_shift_2], [[0]])
self.crypt([i])
self.assertEqual((i + 2) % 256, self.encrypted_message[0])
self.assertEqual(i, self.decrypted_message[0])
def test_two_byte_one_roll_linear(self):
for i in range(256):
self.init_business_logic([self.trans_linear], [[0]])
self.crypt([i, (i + 1) % 256])
self.assertEqual(i, self.encrypted_message[0])
self.assertEqual((i + 2) % 256, self.encrypted_message[1])
self.assertEqual(i, self.decrypted_message[0])
self.assertEqual((i + 1) % 256, self.decrypted_message[1])
def test_two_byte_one_roll_shift1(self):
for i in range(256):
self.init_business_logic([self.trans_shift_1], [[0]])
self.crypt([i, (i + 1) % 256])
self.assertEqual((i + 1) % 256, self.encrypted_message[0])
self.assertEqual((i + 3) % 256, self.encrypted_message[1])
self.assertEqual(i, self.decrypted_message[0])
self.assertEqual((i + 1) % 256, self.decrypted_message[1])
def test_two_byte_one_roll_invert(self):
for i in range(256):
self.init_business_logic([self.trans_linear_invert], [[0]])
self.crypt([i, i])
self.assertEqual(255 - i, self.encrypted_message[0])
self.assertEqual((256 + 255 - i - 1) & 0xff, self.encrypted_message[1])
self.assertEqual(i, self.decrypted_message[0])
self.assertEqual(i, self.decrypted_message[1])
def test_two_byte_two_roll_linear(self):
for i in range(256):
self.init_business_logic([self.trans_linear, self.trans_linear], [[0], [0]])
self.crypt([i, (i + 1) & 0xff])
self.assertEqual(i, self.encrypted_message[0])
self.assertEqual((i + 2) & 0xff, self.encrypted_message[1])
self.assertEqual(i, self.decrypted_message[0])
self.assertEqual((i + 1) & 0xff, self.decrypted_message[1])
def test_two_byte_two_roll_shift1(self):
for i in range(256):
self.init_business_logic([self.trans_shift_1, self.trans_shift_1], [[0], [0]])
self.crypt([i, (i + 1) & 0xff])
self.assertEqual((i + 2) & 0xff, self.encrypted_message[0])
self.assertEqual((i + 4) & 0xff, self.encrypted_message[1])
self.assertEqual(i, self.decrypted_message[0])
self.assertEqual((i + 1) & 0xff, self.decrypted_message[1])
def test_two_byte_two_roll_shift2(self):
self.init_business_logic([self.trans_shift_2, self.trans_shift_2], [[0], [0]])
self.crypt([7, 107])
self.assertEqual(11, self.encrypted_message[0])
self.assertEqual(112, self.encrypted_message[1])
self.assertEqual(7, self.decrypted_message[0])
self.assertEqual(107, self.decrypted_message[1])
def test_two_byte_two_roll_invert(self):
for i in range(256):
self.init_business_logic([self.trans_linear_invert, self.trans_linear_invert], [[0], [0]])
self.crypt([i, (i + 1) & 0xff])
self.assertEqual(i, self.encrypted_message[0])
self.assertEqual((i + 2) & 0xff, self.encrypted_message[1])
self.assertEqual(i, self.decrypted_message[0])
self.assertEqual((i + 1) & 0xff, self.decrypted_message[1])
def test_three_byte_two_roll_turnover(self):
for i in range(256):
self.init_business_logic([self.trans_linear, self.trans_linear], [range(256), range(256)])
self.crypt([i, (i + 1) & 0xff, (i + 2) & 0xff])
self.assertEqual(i, self.encrypted_message[0])
self.assertEqual((i + 3) & 0xff, self.encrypted_message[1])
self.assertEqual((i + 6) & 0xff, self.encrypted_message[2])
self.assertEqual(i, self.decrypted_message[0])
self.assertEqual((i + 1) & 0xff, self.decrypted_message[1])
self.assertEqual((i + 2) & 0xff, self.decrypted_message[2])
def test_three_byte_two_different_roll_turnover(self):
self.init_business_logic([self.trans_linear, self.trans_shift_1], [range(4), range(4)])
self.crypt([7, 107])
self.assertEqual(8, self.encrypted_message[0])
self.assertEqual(110, self.encrypted_message[1])
self.assertEqual(7, self.decrypted_message[0])
self.assertEqual(107, self.decrypted_message[1])
def test_three_byte_two_different_roll_turnover3(self):
self.init_business_logic([self.trans_linear, self.trans_linear_invert], [range(4), range(4)])
self.crypt([7, 107])
self.assertEqual(248, self.encrypted_message[0])
self.assertEqual(146, self.encrypted_message[1])
self.assertEqual(7, self.decrypted_message[0])
self.assertEqual(107, self.decrypted_message[1])
def test_real_live(self):
msg_size = 65536
msg = bytearray(msg_size)
for i in range(msg_size):
msg[i] = i & 0xff
self.init_business_logic([self.trans_linear, self.trans_linear_invert, self.trans_shift_1, self.trans_shift_2],
[[0, 22, 44, 100], [11, 44, 122, 200], [33, 77, 99, 222], [55, 67, 79, 240]])
self.crypt(msg)
for i in range(msg_size):
self.assertEqual(msg[i], self.decrypted_message[i])
def test_integration(self):
key_file_name = "any.key"
msg_file_name = "msg.file"
msg_size = 65536 * 5
msg = bytearray(msg_size)
for i in range(msg_size):
msg[i] = i & 0xff
if os.path.exists(msg_file_name):
os.remove(msg_file_name)
file = open(msg_file_name, 'wb')
file.write(msg)
file.close()
program = Program(55)
program.run_main("keygen", 5, key_file_name)
program.run_main("enc", msg_file_name, key_file_name)
program2 = Program(55)
program2.run_main("dec", msg_file_name + ".enc", key_file_name)
file = open(msg_file_name + ".enc.dec", 'rb')
decypted = file.read()
file.close()
for i in range(msg_size):
self.assertEqual(msg[i], decypted[i])
self.assertEqual(msg_size, len(decypted))
if __name__ == '__main__':
unittest.main()
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>First, a warm welcome to the python language! None of this is in any particular order.</p>\n<h1><code>argparse</code></h1>\n<p>There is a really nice argument parsing library available out of the box which makes parsing command line args much less clunky. I'd set up your parser like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code># Maybe put this into cli.py\nfrom argparse import ArgumentParser\n\n\ndef setup_parser():\n parser = ArgumentParser(desc="Enigma written in python")\n parser.add_argument("mode", type=str, choices=['enc', 'dec', 'keygen'], help="Encode, Decode, or generate key")\n parser.add_argument("-i", "--input-file", dest="input_file", type=str, help="File to be encrypted/decrypted")\n parser.add_argument("key_file", type=str, help="Key file to be generated or to be used to encode/decode")\n return parser\n\n\nparser = setup_parser()\n</code></pre>\n<p>Then your arguments can be used like:</p>\n<pre class=\"lang-py prettyprint-override\"><code>args = parser.parse_args()\n\nargs.mode\n'enc'\n\nargs.key_file\n'mykey.rsa'\n\nargs.input_file\n'to_be_encrypted.txt'\n</code></pre>\n<h1>Variable Names</h1>\n<p>To go along with the argparse suggestion, variables should be given descriptive names. In <code>run_main</code>, you have names like <code>arg<i></code>, which make reading and debugging the code a little tricky. Name them how you intend to use them:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def main(mode, key_file, input_file=None, num_rolls=0):\n ... \n</code></pre>\n<p>Variable names and function names are recommended to be <code>snake_case</code>, where classes are recommended to be <code>PascalCase</code>. The Style Guide (also known as PEP-8) can be found <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">here</a>. Note however, that it's a guide. You don't <em>have</em> to follow it at every step, but it will make your code look nicer most of the time.</p>\n<h1>Enums and type-checking</h1>\n<p>Enums do a nice job of handling type-checking for you. You can re-define your enum like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Mode(Enum):\n ENC = 'enc'\n DEC = 'dec'\n</code></pre>\n<p>Then, not only will the argument parser catch an invalid enum entry, so will the class:</p>\n<pre class=\"lang-py prettyprint-override\"><code>mode = Mode('enc')\nmode is Mode.ENC\nTrue\n\nmode = Mode('dec')\nmode is Mode.DEC\nTrue\n\nmode = Mode('bad')\nTypeError:\n 'bad' is not a valid Mode\n</code></pre>\n<h1>Creating <code>rolls</code></h1>\n<p>There are a few ways to clean this code up. First, I think defining your slice points outside of the slice notation itself on the key is a bit easier to read:</p>\n<pre class=\"lang-py prettyprint-override\"><code> ~snip~\n for roll_number in range(roll_count):\n # For readability, I would just compute these values here. It\n # makes the slices look better\n start = roll_number * roll_key_length\n middle = roll_number * roll_key_length + 256\n end = roll_number * roll_key_length + 256 + transition_count\n\n # now it's easier to see what the key slices are\n roll = Roll(key[start:middle], key[middle:end]))\n</code></pre>\n<p>Second, you iterate over all of your rolls twice, when you don't need to. Just do the check during the iteration:</p>\n<pre class=\"lang-py prettyprint-override\"><code> for roll_number in range(roll_count):\n ~snip~\n\n roll.check_input(transition_count)\n\n rolls.append(roll)\n</code></pre>\n<h2>File Handling</h2>\n<p>It's better practice to open files using the context manager <code>with</code>, as it will automatically close the file handle for you when you are done using it, no matter what happens:</p>\n<pre class=\"lang-py prettyprint-override\"><code># go from this\nfh = open(myfile, 'rb')\ncontent = fh.read()\nfh.close()\n\n# to this\nwith open(myfile, 'rb') as fh:\n content = fh.read()\n\n\n# and to open multiple files:\nwith open('file1.txt') as fh1, open('file2.txt') as fh2, ..., open('fileN.txt') as fhN:\n # do things\n</code></pre>\n<p>There is also a spot in your code where you remove a file, do some calculations, and then create it again by writing to it. The <code>w</code> and <code>wb</code> modes will truncate an existing file for you. So go from:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if os.path.exists(self._keyFilename):\n os.remove(file)\n\n# skipping code\n\nfile = open(self._keyFilename, 'wb')\nfile.write(key)\nfile.close()\n</code></pre>\n<p>Do this instead:</p>\n<pre class=\"lang-py prettyprint-override\"><code># get rid of the `if file exists` check\n\n# skipping code\nwith open(self.key_file_name, 'wb') as fh:\n fh.write(key)\n</code></pre>\n<h1>Filling a <code>bytearray</code></h1>\n<p>You have a loop where you fill a <code>bytearray</code> with numbers:</p>\n<pre class=\"lang-py prettyprint-override\"><code>for i in range(roll_count):\n transform = bytearray(256)\n for j in range(256):\n transform[j] = j\n</code></pre>\n<p>You can skip the other loop and simply have <code>bytearray</code> consume the <code>range</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>for i in range(roll_count):\n transform = bytearray(range(256))\n</code></pre>\n<h1>Swapping variables</h1>\n<p>You can use tuple-style assignment to quickly and easily swap variable values:</p>\n<pre class=\"lang-py prettyprint-override\"><code># go from this\ntemp = transform[rand1]\ntransform[rand1] = transform[rand2]\ntransform[rand2] = temp\n\n# to this\ntransform[rand1], transform[rand2] = transform[rand2], transform[rand1]\n</code></pre>\n<h1>Generating a list of pseudo-random numbers (no dupes)</h1>\n<p>You have the following code to do this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>transitions = bytearray()\nwhile len(transitions) < self._transitionCount:\n rand = randint(0, 255)\n if not transitions.count(rand):\n transitions.append(rand)\n</code></pre>\n<p>This can be simplified down to</p>\n<pre class=\"lang-py prettyprint-override\"><code>transitions = bytearray(\n random.sample(range(256), transition_count)\n)\n</code></pre>\n<p>This is much, much faster. <code>transitions.count(x)</code> will be O(N), where N is growing for each iteration. Not ideal.</p>\n<h1><code>is_twisted</code></h1>\n<p>While <code>0</code> and <code>1</code> can be interpreted as <code>False</code> and <code>True</code>, respectively through their truthiness, I think it would be better to actually return a boolean here. Also, this could be more succinctly expressed as an <code>any</code> statement:</p>\n<pre class=\"lang-py prettyprint-override\"><code># go from this\ndef is_twisted(self, trans):\n for i in range(256):\n if trans[i] == i:\n return 0\n\n return 1\n\n# to this\ndef is_twisted(self, trans):\n return any(item == i for i, item in enumerate(trans))\n</code></pre>\n<p>Where <code>enumerate</code> will produce <code>index</code>, <code>item</code> pairs for each item in an iterable/sequence/generator. Last, you don't actually use <code>self</code> here, so <code>is_twisted</code> could be a <code>staticmethod</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>@staticmethod\ndef is_twisted(trans):\n return any(item == i for i, item in enumerate(trans))\n</code></pre>\n<h1><code>for</code>...<code>else</code>?</h1>\n<p>In <code>Rolls.py</code>, you have the following snippet:</p>\n<pre class=\"lang-py prettyprint-override\"><code>for i in range(256):\n found = 0\n for j in self._transitions:\n if self._transitions[j] == i:\n found = 1\n continue\n\n if not found:\n raise ValueError("Transitions not 1-1 complete")\n</code></pre>\n<p>This can be reduced down by using an <code>else</code> statement on a <code>for</code> loop. Yes, there is an <code>else</code> for <code>for</code>. You can think of it checking to see if a <code>StopIteration</code> has occurred:</p>\n<pre class=\"lang-py prettyprint-override\"><code>for i in range(10):\n if i == 5:\n break\nelse:\n print("Didn't exit early!")\n\n\nfor i in range(10:\n if i == 11:\n break # this won't happen\nelse:\n print("Didn't exit early!")\n\nDidn't exit early!\n</code></pre>\n<p>So your code snippet can reduce down to:</p>\n<pre class=\"lang-py prettyprint-override\"><code>for i in range(256):\n for j in self._transitions:\n if self._transitions[j] == i:\n break\n else:\n # is not found\n raise ValueError("Transitions not 1-1 complete")\n</code></pre>\n<h1>Checking Corresponding Elements</h1>\n<p>Any time you have code comparing corresponding elements of a collection, you can probably use <code>zip</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>for i in range(len(self._turn_over_indices) - 1):\n if self._turn_over_indices[i] == self._turn_over_indices[i + 1]:\n raise ValueError("turn_over_indices has doubles")\n</code></pre>\n<p>Can be turned into:</p>\n<pre class=\"lang-py prettyprint-override\"><code>for left, right in zip(\n self._turn_over_indices[:-1], \n self._turn_over_indices[1:]\n):\n if left == right:\n raise ValueError("doubles!")\n</code></pre>\n<p>This could even be cleaned up in your unit tests:</p>\n<pre class=\"lang-py prettyprint-override\"><code> def init_business_logic(self, transitions, turnovers):\n rolls_encrypt = []\n rolls_decrypt = []\n\n for index in range(len(transitions)):\n rolls_encrypt.append(Roll(transitions[index], turnovers[index]))\n rolls_decrypt.append(Roll(transitions[index], turnovers[index]))\n\n# can now be\n def init_business_logic(self, transitions, turnovers):\n rolls_encrypt, rolls_decrypt = [], []\n\n for transition, turnover in zip(transitions, turnovers):\n rolls_encrypt.append(Roll(transition, turnover))\n rolls_decrypt.append(Roll(transition, turnover))\n</code></pre>\n<h1><code>transform_buffer</code></h1>\n<p>This could be refactored to be more DRY:</p>\n<pre class=\"lang-py prettyprint-override\"><code> def transform_buffer(self, buffer, mode):\n if mode == Mode.ENC:\n # almost all of this code is repeated except roll.encrypt/decrypt\n for i in range(len(buffer)):\n for roll in self._rolls:\n roll.encrypt(buffer, i)\n self.roll_on()\n\n if mode == Mode.DEC:\n for i in range(len(buffer)):\n for roll in self._rolls_reverse:\n roll.decrypt(buffer, i)\n self.roll_on()\n</code></pre>\n<p>The only difference is <code>roll.encrypt</code>, <code>roll.decrypt</code>, and the direction in which we iterate over <code>self._rolls</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code> def transform_buffer(self, buffer, mode):\n if mode is Mode.ENC:\n rolls = self._rolls\n func_name = 'encrypt'\n else:\n rolls = self._rolls[::-1]\n func_name = 'decrypt'\n\n for i in range(len(buffer)):\n for roll in rolls:\n f = getattr(roll, func_name)\n f(buffer, i)\n self.roll_on()\n</code></pre>\n<p>Speaking of which...</p>\n<h1>Reversing iterators</h1>\n<p>Instead of copying an object and reversing its order, you can just do:</p>\n<pre class=\"lang-py prettyprint-override\"><code>for item in reversed(collection):\n print(item)\n</code></pre>\n<p>However, for <code>transform_buffer</code>, I used <code>self._rolls[::-1]</code> because after the first loop, the <code>reversed</code> iterator will be consumed whereas the slice can be reused.</p>\n<p>So instead of doing:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Rolls:\n def __init__(self, rolls):\n self._rolls = rolls\n self._rolls_reverse = rolls.copy()\n self._rolls_reverse.reverse()\n\n</code></pre>\n<p>Just keep one copy of <code>self._rolls</code> around.</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Rolls:\n def __init__(self, rolls):\n self._rolls = rolls\n # no reverse copy\n</code></pre>\n<h1><code>Rolls.roll_on</code></h1>\n<p>I think this method could be named better, since you have two implementations of the <code>roll_on</code> function for two different classes. However, <code>Rolls.roll_on</code> has a different problem. It's using <code>bytearray.count</code> to effectively do a membership test:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def roll_on(self):\n self._position = (self._position + 1) & 0xff\n return self._turn_over_indices.count(self._position)\n</code></pre>\n<p>Now, normally with a membership test, I'd recommend a <code>dict</code> or <code>set</code>, but for this example, I'd just use <code>in</code>, since you are either creating a whole new object in memory that you need to keep in sync with the <code>bytearray</code> or sacrificing time to check for membership in a 256 element array. I'd choose the latter. However, <code>bytearray.count</code> (or any <code>collection.count</code>, for that matter) will always iterate through the whole thing. <code>in</code> will short-circuit:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def roll_on(self):\n self._position = (self._position + 1) & 0xff\n return self._position in self._turn_over_indices \n</code></pre>\n<p>I'll add more items as I find them, but I think this is more than enough to start with.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T05:04:43.383",
"Id": "525439",
"Score": "0",
"body": "Wow, what a lot of advice! I'm really looking forward to implementing this after my holidays... Thx very much!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-30T07:16:18.400",
"Id": "526578",
"Score": "0",
"body": "Helped me to see what's possible in Python, all points really informative, thx again!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T03:41:17.450",
"Id": "266020",
"ParentId": "265990",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T12:45:28.667",
"Id": "265990",
"Score": "4",
"Tags": [
"python",
"beginner",
"cryptography"
],
"Title": "Enigma Implementation by Python newbie"
}
|
265990
|
<p>The following bash code is meant to check every second the amount of NEW (relative to the last second) network socket files.
at the end of the run it summarizes every 60 entries (should be 60 seconds) and output a file called verdict.csv that tells me how many new network sockets were opened in that minute (I run under the assumption that those sockets live for more than 1 second and hence I don't miss new ones).</p>
<p>The problem starts when I run it on a busy server where I have a lot of new network sockets being opened, then I start seeing that the lsof_func iterations takes much more then 1 second (even more than a minute some times) and than I cannot trust the output of this script.</p>
<pre><code>#!/bin/bash
TIMETORUN=84600 # Time for the script to run in seconds
NEWCONNECTIONSPERMINUTE=600
# collect number of new socket files in the last second
lsof_func () {
echo "" > /tmp/lsof_test
while [[ $TIME -lt $TIMETORUN ]]; do
lsof -i -t > /tmp/lsof_test2
echo "$(date +"%Y-%m-%d %H:%M:%S"),$(comm -23 <(cat /tmp/lsof_test2|sort) <(cat /tmp/lsof_test|sort) | wc -l)" >> /tmp/results.csv # comm command is used as a set subtractor operator (lsof_test minus lsof_test2)
mv /tmp/lsof_test2 /tmp/lsof_test
TIME=$((TIME+1))
sleep 0.9
done
}
# Calculate the number of new connections per minute
verdict () {
cat /tmp/results.csv | uniq > /tmp/results_for_verdict.csv
echo "Timestamp,New Procs" > /tmp/verdict.csv
while [[ $(cat /tmp/results_for_verdict.csv | wc -l) -gt 60 ]]; do
echo -n $(cat /tmp/results_for_verdict.csv | head -n 1 | awk -F, '{print $1}'), >> /tmp/verdict.csv
cat /tmp/results_for_verdict.csv | head -n 60 | awk -F, '{s+=$2} END {print s}' >> /tmp/verdict.csv
sed -n '61,$p' < /tmp/results_for_verdict.csv > /tmp/tmp_results_for_verdict.csv
mv /tmp/tmp_results_for_verdict.csv /tmp/results_for_verdict.csv
done
echo -n $(cat /tmp/results_for_verdict.csv | head -n 1 | awk -F, '{print $1}'), >> /tmp/verdict.csv
cat /tmp/results_for_verdict.csv | head -n 60 | awk -F, '{s+=$2} END {print s}' >> /tmp/verdict.csv
}
lsof_func
verdict
#cleanup
rm /tmp/lsof_test
#rm /tmp/lsof_test2
rm /tmp/results.csv
rm /tmp/results_for_verdict.csv
</code></pre>
<p>How can I make the iterations of lsof_func function be more consistent / run faster and collect this data every second?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T21:05:25.547",
"Id": "525431",
"Score": "1",
"body": "It's possible that another tool could yield better performance than lsof but make sure you are aware of all the available command line arguments to fine tune your request. I would have a look at the [ss](https://www.tecmint.com/ss-command-examples-in-linux/) command which is the successor of netstat. Try for example `ss -s` for a start. This could be enough for your purpose, you only need counters and not the full details even if the information is aggregated after collection."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T13:16:47.400",
"Id": "525453",
"Score": "0",
"body": "For anyone in the Close Vote Queue. This is not broken code, this is a performance issue which is on-topic for the Code Review Community."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T13:17:37.990",
"Id": "525454",
"Score": "1",
"body": "@Anonymous I think that might be most of a good answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T13:37:34.413",
"Id": "526689",
"Score": "0",
"body": "Is `84600` a typo for `86400`? If not, what's significant about 23½ hours that makes it a good sampling period?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T14:21:40.540",
"Id": "527766",
"Score": "0",
"body": "@TobySpeight Yes this is a Typo..."
}
] |
[
{
"body": "<h1>Temporary files</h1>\n<p>Don't assume that <code>/tmp/</code> is the right location for temporary files - if <code>$TMPDIR</code> is set, we should prefer that directory instead (e.g. which <code>pam_tmpdir</code> is used for per-user temp directories).</p>\n<p>It's a good idea to create a single directory for all the script's temporary files, then we can arrange for it to be cleaned up however the script exits:</p>\n<pre><code>export TMPDIR=$(mktemp -d)\ntrap 'rm -rf "$TMPDIR"' EXIT\n</code></pre>\n<p>By using the well-known <code>TMPDIR</code> environment variable for this, we also clean up any of our subprocesses' temporary files if they get left lying around.</p>\n<p>We can also simplify code by changing into the temporary directory (but always fail if <code>cd</code> is unsuccessful, either explicitly or by using <code>set -e</code>).</p>\n<h1>Variables</h1>\n<p>Prefer lower-case for non-exported shell variables, as they share a namespace with environment variables, and upper-case is conventionally used for communicating between programs.</p>\n<p>Extending the comment would expose a bug:</p>\n<pre><code>timetorun=84600 # Time for the script to run (1 day)\n</code></pre>\n<p>We could then see that actually 86,400 seconds was intended.</p>\n<p><code>NEWCONNECTIONSPERMINUTE</code> certainly needs a comment, as it appears to be completely unused.</p>\n<h1>Unnecessary <code>cat</code></h1>\n<p>There's no need to concatenate a single file like this:</p>\n<blockquote>\n<pre><code>cat results.csv | uniq > results_for_verdict.csv\n</code></pre>\n</blockquote>\n<p>Simply redirect standard input using <code><</code>:</p>\n<pre><code><results.csv uniq >results_for_verdict.csv\n</code></pre>\n<p>or pass the filenames as argument to <code>uniq</code>:</p>\n<pre><code>uniq results.csv results_for_verdict.csv\n</code></pre>\n<p>An even more egregious case is the use of <code>cat</code> in process substitution here:</p>\n<blockquote>\n<pre><code>comm -23 <(cat lsof_test2|sort) <(cat lsof_test|sort)\n</code></pre>\n</blockquote>\n<p>The obvious transformation is to:</p>\n<blockquote>\n<pre><code>comm -23 <(sort lsof_test2) <(sort lsof_test)\n</code></pre>\n</blockquote>\n<p>But if we arrange for the files to be sorted (<code>lsof -i -t | sort >lsof_test2</code>), then we can just pass the file names directly, and we only sort each file once rather than twice:</p>\n<blockquote>\n<pre><code>comm -23 lsof_test2 lsof_test\n</code></pre>\n</blockquote>\n<h1>Timing</h1>\n<p>Counting loop iterations is a very approximate method of timing. A better way is to calculate the time we should finish, and loop until that time is reached. We can use the Bash magic variable <code>SECONDS</code> to determine how long the script has been running, so our test becomes:</p>\n<pre><code>local -i endtime=$SECONDS+$timetorun\nwhile [ $SECONDS -lt $endtime ]\n</code></pre>\n<h1>Multiple opens of output files</h1>\n<p>Instead of opening for append each time around the loop, we can redirect the entire loop's output:</p>\n<pre><code>while …\n⋮\ndone >results.csv\n</code></pre>\n<p>Or let <code>lsof_func</code> just write to its standard output, and pipe that into <code>verdict</code> (which can also write to its standard output):</p>\n<pre><code>lsof_func | verdict >verdict.csv\n</code></pre>\n<h1>Splitting by minute</h1>\n<p>Instead of a shell loop to count lines, we could use the standard <code>split</code> utility to break our input into 60-line files. That simplifies our code a great deal:</p>\n<pre><code>verdict() {\n echo "Timestamp,New Procs"\n # Create 1 file per 60 seconds\n uniq | split -l 60 - results_\n for file in results_*\n do\n printf '%s' "$(head -n 1 "$file" | awk -F, '{print $1}'),"\n awk -F, '{s+=$2} END {print s}' "$file"\n done\n}\n</code></pre>\n<p>I don't think we need two separate <code>awk</code> programs here, as a single one can capture the initial timestamp and accumulate the values:</p>\n<pre><code>for file in results_*\ndo\n awk -F, 'FNR==1{ts=$1} {s+=$2} END{OFS="," ; print ts,s}' "$file"\ndone\n</code></pre>\n<p>The full program would then be</p>\n<pre><code>#!/bin/bash\n\nset -eu\n\ntimetorun=86400 # Gather statistics for 1 day\n\nexport TMPDIR=$(mktemp -d)\ntrap 'rm -rf "$TMPDIR"' EXIT\n\ncd "$TMPDIR" || exit $?\n\n# collect number of new socket files in the last second\nlsof_func() {\n true > lsof_test\n local -i endtime=$SECONDS+$timetorun\n while [ $SECONDS -lt $endtime ]\n do\n lsof -i -t | sort >lsof_test2\n date +"%F %T,$(comm -23 lsof_test2 lsof_test | wc -l)"\n mv lsof_test2 lsof_test\n sleep 0.9\n done\n}\n\n# Calculate the number of new connections per minute\nverdict() {\n echo "Timestamp,New Procs"\n # Create 1 file per 60 seconds\n uniq | split -l 60 - results_\n for file in results_*\n do\n awk -F, 'FNR==1{ts=$1} {s+=$2} END{OFS="," ; print ts,s}' "$file"\n done\n}\n\nlsof_func | verdict\n</code></pre>\n<h1>Alternative approach</h1>\n<p>Instead of writing to files and post-processing them with <code>awk</code>, we could simply hold all our data in memory, in a Bash array. We can add as we go, so that we're only storing one value per minute.</p>\n<p>Easiest of all is if we care only about calendar minutes, and don't mind that we have a partial minute at start and end:</p>\n<pre><code># collect number of new socket files in each second, and add to per-minute counter\ndeclare -i endtime=$SECONDS+$timetorun\ndeclare -A -i minute\nwhile [ "$SECONDS" -lt "$endtime" ]\ndo\n lsof -i -t | sort >lsof_test2\n minute["$(date +'%F %R')"]+=$(comm -23 lsof_test2 lsof_test | wc -l)\n mv lsof_test2 lsof_test\n sleep 0.9\ndone\n\n# Output the number of new connections per minute\necho "Timestamp,New Procs"\nfor t in "${!minute[@]}"\ndo\n printf '%s,%u\\n' "$t" "${minute[$t]}"\ndone\n</code></pre>\n<p>If we want to keep the current behaviour, we'll need to store into arbitrary 60-second chunks, and store the times separately:</p>\n<pre><code>declare -i endtime=$SECONDS+$timetorun\ndeclare -A -i minute\ndeclare -A date\nwhile [ $SECONDS -lt $endtime ]\ndo\n lsof -i -t | sort >lsof_test2\n declare -i m=$SECONDS/60\n minute[$m]+=$(comm -23 lsof_test2 lsof_test | wc -l)\n date[$m]=$(date -d -1min '+%F %T')\n mv lsof_test2 lsof_test\n sleep 0.9\ndone\n\n# Output the number of new connections per minute\necho "Timestamp,New Procs"\nfor m in "${!minute[@]}"\ndo\n printf '%s,%u\\n' "${date[$m]}" "${minute[$m]}"\ndone | sort\n</code></pre>\n<hr />\n<h1>Modified code</h1>\n<p>The full, rewritten version (with no Shellcheck warnings):</p>\n<pre><code>#!/bin/bash\nset -eu -o pipefail\n\ndeclare -i endtime=86400 # Stop after 1 day\n\nTMPDIR=$(mktemp -d); export TMPDIR\ntrap 'rm -rf "$TMPDIR"' EXIT\ncd "$TMPDIR"\n\nlist_sockets() {\n lsof -i -t | sort\n}\n\n# Initial open sockets\nlist_sockets >sockets\n\n# Update per-minute counters with new sockets\ndeclare -A -i minute\ndeclare -A date\nwhile [ $SECONDS -lt $endtime ]\ndo\n mv sockets sockets.old\n list_sockets >sockets\n declare -i m=$SECONDS/60\n minute[$m]+=$(comm -23 sockets sockets.old | wc -l)\n date[$m]=$(date -d -1min '+%F %T')\n sleep 0.5\ndone\n\n# Output the number of new connections per minute\necho "Timestamp,New Procs"\nfor m in "${!minute[@]}"\ndo printf '%s,%u\\n' "${date[$m]}" "${minute[$m]}"\ndone | sort\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-05T11:36:28.417",
"Id": "527881",
"Score": "0",
"body": "This is great, thank you very much for all the output.\nI didn't try everything but I did use variables instead if files and that alone made performance much better, I will try and implement other suggestions you had thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-04T09:46:24.560",
"Id": "267677",
"ParentId": "265991",
"Score": "1"
}
},
{
"body": "<p>We have a simple bug - using <code>lsof -t</code> causes it to print one line <em>per process</em> rather than one line per socket. If we want to observe changes to the open sockets as claimed in the question, then we'll want something like <code>lsof -i -b -n -F 'n' | grep '^n'</code>.</p>\n<p>Instead of using <code>lsof</code>, it may be more efficient to use <code>netstat</code>; on my lightly-loaded system it's about 10-20 times as fast, but you should benchmark the two on your target system.</p>\n<p>So instead of comparing subsequent runs of <code>lsof -i -t | sort</code>, we could compare runs of</p>\n<pre><code>netstat -tn | awk '{print $4,$5}' | sort\n</code></pre>\n<p>Some things to note here:</p>\n<ul>\n<li><code>netstat -t</code> examines TCP connections over IPv4 and IPv6. I believe that's what's wanted.</li>\n<li><code>netstat -n</code>, like <code>lsof -n</code>, saves a vast amount of time by not doing DNS reverse lookup.</li>\n<li><code>awk</code> is more suitable than <code>cut</code> for selecting columns, since <code>netstat</code> uses a variable number of spaces to separate fields.</li>\n<li>Netstat includes a couple of header lines, but because these are the same in every invocation, they will disappear in the comparison. We could remove them if we really want: <code>awk 'FNR>2 {print $4,$5}'</code>.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-04T12:18:22.367",
"Id": "267681",
"ParentId": "265991",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T13:04:29.030",
"Id": "265991",
"Score": "2",
"Tags": [
"performance",
"bash"
],
"Title": "bash script to collect new network sockets in a given period of time"
}
|
265991
|
<p>In my web app, I am trying to secure a payment transaction, that is:</p>
<ol>
<li>prevent users spending more than they have, especially in the case of concurrent execution</li>
<li>and prevent partial execution.</li>
</ol>
<p>Additional details:</p>
<ul>
<li>Orders can be partially paid, we store the amount already paid in the <em>paid</em> column</li>
<li>I use a MySQL database and InnoDB as storage engine</li>
<li>I prefer not to use an ORM</li>
</ul>
<p>I'd be glad if some of you SQL masters would shed some light about it!<br />
Are my implementations correct?<br />
How would you tackle this?</p>
<h3>LOCK TABLES</h3>
<p>Here is a first attempt using LOCK TABLES.<br />
It works as expected but I think it does not prevent partial execution and it is not optimal in terms of contention (locks two complete tables).</p>
<pre><code>import mysql from "mysql2/promise";
const config = {
host: "localhost",
port: 3306,
database: "testdb",
user: "louis",
password: "almost_posted_it_online!",
};
const pool = mysql.createPool(config);
pay_v2().then(() => console.log("done"));
async function pay_v2() {
const orderId = 1;
const userId = 1;
const aConnection = await pool.getConnection();
try {
await aConnection.query("LOCK TABLES users2 WRITE, orders2 WRITE");
const [rows1] = await aConnection.execute(
"SELECT total FROM orders2 WHERE id = ?", [orderId]);
const orderTotal = (rows1 as any[])[0]["total"] as number;
const [rows2] = await aConnection.execute(
"SELECT coins FROM users2 WHERE id = ?", [userId]);
const coinsAvailable = (rows2 as any[])[0]["coins"] as number;
const coinsUsed = Math.min(coinsAvailable, orderTotal);
console.log(`Using ${coinsUsed} coins`);
await aConnection.execute(
"UPDATE orders2 SET paid = ? WHERE id = ?", [coinsUsed, orderId]);
await aConnection.execute(
"UPDATE users2 SET coins = coins - ? WHERE id = ?", [coinsUsed, userId]);
await aConnection.query("UNLOCK TABLES");
} finally {
aConnection.release();
}
}
</code></pre>
<h3>Transaction and locking reads</h3>
<p>Here is a second attempt using a transaction and <a href="https://dev.mysql.com/doc/refman/5.6/en/innodb-locking-reads.html" rel="nofollow noreferrer">locking reads</a>. It prevents partial updates, it reduces contention to a minimum (only the two concerned rows are locked), but I am not completely sure that it prevents two concurrent execution to spend the same coins twice.</p>
<pre><code>async function pay_v3() {
const orderId = 1;
const userId = 1;
let aConnection = await pool.getConnection();
try {
await aConnection.beginTransaction()
const [rows1] = await aConnection.execute(
"SELECT total FROM orders2 WHERE id = ? FOR UPDATE", [orderId]);
const orderTotal = (rows1 as any[])[0]["total"] as number;
const [rows2] = await aConnection.execute(
"SELECT coins FROM users2 WHERE id = ? FOR UPDATE", [userId]);
const coinsAvailable = (rows2 as any[])[0]["coins"] as number;
const coinsUsed = Math.min(coinsAvailable, orderTotal);
console.log(`Using ${coinsUsed} coins`);
await aConnection.execute(
"UPDATE orders2 SET paid = ? WHERE id = ?", [coinsUsed, orderId]);
await aConnection.execute(
"UPDATE users2 SET coins = coins - ? WHERE id = ?", [coinsUsed, userId]);
await aConnection.commit();
} catch (error) {
await aConnection.rollback();
throw error;
} finally {
aConnection.release();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T16:18:33.560",
"Id": "525410",
"Score": "0",
"body": "Just curious why you don't use `transaction` :/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T16:22:09.977",
"Id": "525412",
"Score": "0",
"body": "I have just added this alternative after learning about locking reads, but I am not sure if the the locking is sufficient. Have you tried it yourself?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T16:27:23.543",
"Id": "525413",
"Score": "0",
"body": "I've never tried it before, I think your question is more related to the database topic than code review. Maybe you should ask on StackOverflow or https://dba.stackexchange.com."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T16:53:58.860",
"Id": "525415",
"Score": "0",
"body": "I am looking for feedback on \"Potential security issues\" or \"Correctness in unanticipated cases\" which fits this particular site according to the [help page](https://codereview.stackexchange.com/help/on-topic)."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T14:22:03.413",
"Id": "265993",
"Score": "0",
"Tags": [
"javascript",
"mysql",
"typescript",
"locking",
"transactions"
],
"Title": "Trying to secure a payment transaction with mysqljs2"
}
|
265993
|
<p>Hello I have this function that looks for nested value 3 levels deep currently</p>
<pre><code> // This handle nested data to be applied to filter option which comes from filterProps.prop values
// This is currently chained 3 level deep I.E clock.props.children to add more just keep chaineding
const handleNestFilterProp = (prop: any, item: any, trim?: boolean) => {
return trim
? prop.length === 1
? item[prop[0]] && item[prop[0]].trim().length > 0
: prop.length === 2
? item[prop[0]][prop[1]].trim().length > 0
: prop.length === 3 && item[prop[0]][prop[1]][prop[2]].trim().length > 0
: prop.length === 1
? item[prop[0]] && item[prop[0]]
: prop.length === 2
? item[prop[0]][prop[1]]
: prop.length === 3 && item[prop[0]][prop[1]][prop[2]];
};
</code></pre>
<p>I'm trying to figure out a way to reduce the logic and make it simpler.
I thinking if it would be a good idea to use get from Lodash
<a href="https://lodash.com/docs/4.17.15#get" rel="nofollow noreferrer">https://lodash.com/docs/4.17.15#get</a></p>
<h6>UPDATE added lodash get to simplify</h6>
<pre><code> const handleNestFilterProp = (prop: any, item: any, trim?: boolean) => {
const L1 = _.get(item, prop[0]);
const L2 = _.get(item, [prop[0], prop[1]]);
const L3 = _.get(item, [prop[0], prop[1], prop[2]]);
return trim
? prop.length === 1
? L1 && L1.trim().length > 0
: prop.length === 2
? L2 && L2.trim().length > 0
: prop.length === 3 && L3.trim().length > 0
: prop.length === 1
? L1
: prop.length === 2
? L2
: prop.length === 3 && L3;
};
</code></pre>
<h6>UPDATE 2</h6>
<pre><code> const handleNestFilterProp = (prop: any, item: any, trim?: boolean) => {
const L1 = _.get(item, prop[0]);
const L2 = _.get(item, [prop[0], prop[1]]);
const L3 = _.get(item, [prop[0], prop[1], prop[2]]);
return prop.length === 1
? trim
? L1.trim().length > 0
: L1
: prop.length === 2
? trim
? L2.trim().length > 0
: L2
: prop.length === 3 && trim
? L3.trim().length > 0
: L3;
};
</code></pre>
<h6>UPDATE 3</h6>
<pre><code> const handleNestFilterProp = (prop: any, item: any, trim?: boolean) => {
const nest = [prop[0], prop[1], prop[2]];
const L1 = _.get(item, nest.slice(0, 1));
const L2 = _.get(item, nest.slice(0, 2));
const L3 = _.get(item, nest);
return prop.length === 1
? trim
? L1.trim().length > 0
: L1
: prop.length === 2
? trim
? L2.trim().length > 0
: L2
: prop.length === 3 && trim
? L3.trim().length > 0
: L3;
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T16:12:17.810",
"Id": "525409",
"Score": "1",
"body": "(Tagging with a programming language is quite enough, [including the language name in the title without special reason is frowned upon](https://codereview.meta.stackexchange.com/a/768.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T19:26:36.607",
"Id": "525426",
"Score": "0",
"body": "Using a boolean as an argument probably means you could have two different methods with more meaningful names, and call then depending on the variable. See [this](https://softwareengineering.stackexchange.com/questions/147977/is-it-wrong-to-use-a-boolean-parameter-to-determine-behavior) question"
}
] |
[
{
"body": "<p>For me, using nested conditional expression makes the code very hard to understand, I think you should use <code>if</code> and <code>switch</code> statements for readability. It's difficult to understand what your code returns in each case so I only write the structure of the code.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>const handleNestFilterProp = (prop: any, item: any, trim?: boolean) => {\n if (trim) {\n switch (prop.length) {\n case 1:\n break;\n case 2:\n break;\n case 3:\n break;\n \n }\n } else {\n switch (prop.length) {\n switch (prop.length) {\n case 1:\n break;\n case 2:\n break;\n case 3:\n break;\n \n }\n }\n }\n};\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T16:19:23.383",
"Id": "525411",
"Score": "2",
"body": "(The nested `switch (prop.length) {` looks off, not just for its indentation. And it would see CR@SE still wants a newline after a closing *code fence*.)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T16:13:13.313",
"Id": "265997",
"ParentId": "265994",
"Score": "-2"
}
},
{
"body": "<pre><code>const handleNestFilterProp = (prop: string, item: any, trim?: boolean) => {\n return trim ? _.get(item, prop).trim().length > 0 : _.get(item, prop);\n }; \n</code></pre>\n<p>_.get just takes 'props.clock.children' and goes deep no matter how deep</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T16:16:47.317",
"Id": "265998",
"ParentId": "265994",
"Score": "0"
}
},
{
"body": "<h2>Undefined</h2>\n<p>Information is missing in regard to the function's possible inputs. I will make a guess as to what the possibilities are in the rewrites</p>\n<h2>TypeScript</h2>\n<p>To use TypeScript and gain any benefit you need to define the types of all variables. Using <code>any</code> is just lazy and degrades the code quality as type syntax just becomes noise.</p>\n<p>I will treat the code as if its JavaScript</p>\n<h2>Names</h2>\n<p>You are using some poor names. This means one must decipher their content by reading the code. Names should provide the information needed to understand their content and how they are used.</p>\n<p>Looking at the line...</p>\n<pre><code>const handleNestFilterProp = (prop: any, item: any, trim?: boolean) => {\n</code></pre>\n<p>... here are some suggest improvements</p>\n<ul>\n<li><p><code>handleNestFilterProp</code> can be <code>trimAtPath</code>,</p>\n<p>or if <code>trim</code> is always <code>false</code> <code>traversePath</code></p>\n<p>or if <code>trim</code> is always <code>true</code> <code>pathStrHasLength</code></p>\n<p>See second rewrite for how the last two names can be used.</p>\n</li>\n<li><p><code>prop</code> Is an array so the name should be a plural <code>props</code>.</p>\n<p>Yes they are property names but they are used as directions to the property we are after. It is common to call this type of array usage a <code>path</code></p>\n</li>\n<li><p><code>item</code> Is OK but rather generic. It is the starting point (root) of the object you are traversing so the name <code>rootObj</code> or just <code>root</code> would be more informative.</p>\n</li>\n<li><p><code>trim</code> is a good name. But really should not be part of the function (see second rewrite)</p>\n</li>\n</ul>\n<p>So the line becomes</p>\n<pre><code>const traversePath = (path, root, trim) => {\n</code></pre>\n<h2>Your question</h2>\n<p>Taking from</p>\n<blockquote>\n<p><em>"...for nested value 3 levels deep currently"</em></p>\n</blockquote>\n<p>with <em>"currently"</em> meaning you want to handle any depth.</p>\n<p>Rather than statically check the depth to find the linked object, the function can step along the path using a loop. You assign the root the next object on the path to the variable that holds the current root.</p>\n<p>You don't need to slow down your page with a bulky library (like lodash) as the this is very easy to do in JavaScript or TypeScript</p>\n<h2>Rewrite</h2>\n<p>We can greatly simplify the function using the above points, however there are some caveats regarding the inputs.</p>\n<ul>\n<li>Assumes path has 1 or more items</li>\n<li>Assumes root can be indexed or has properties</li>\n<li>Assumes the path is valid</li>\n</ul>\n<p>Thus we get the function below.</p>\n<pre><code>function trimAtPath(path, root, trim) {\n var i = 0;\n while (i < path.length) { root = root[path[i++]] }\n return trim ? root.trim().length > 0 : root;\n}\n</code></pre>\n<p>The above is still not right as the return is not evident in the call. We can break it into two functions.</p>\n<p><sub><strong>Note</strong> I have swapped the argument order of <code>root</code> and <code>path</code></sub></p>\n<p><sub><strong>Note</strong> traversing the path can be done using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Array reduce\">Array.reduce</a></sub></p>\n<pre><code>const traversePath = (root, path) => path.reduce((root, key) => root[key], root);\nconst pathStrHasLen = (root, path) => traversePath(root, path).trim().length > 0;\n</code></pre>\n<p>To test the trimmed string length is made when calling the function using a ternary to select the correct function.</p>\n<pre><code>const result = (trim ? pathStrHasLen : traversePath)(root, path);\n</code></pre>\n<h2>Alternative</h2>\n<p>You can also write the <code>traversePath</code> function to have the same signature as <code>lodash.get</code> using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript Functions rest parameters\">... (rest parameters)</a></p>\n<pre><code>const traversePath = (root, ...path) => path.reduce((root, key) => root[key], root);\n\n// called using\ntraversePath(root, ...path);\n\n// or\ntraversePath(root, path[0], path[1], path[2]);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T08:21:12.827",
"Id": "266093",
"ParentId": "265994",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "265998",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T15:03:51.357",
"Id": "265994",
"Score": "0",
"Tags": [
"javascript",
"performance",
"algorithm",
"array",
"lodash.js"
],
"Title": "Javascript: Reducing redundancy of notation nested value"
}
|
265994
|
<p>First post. I posted this on stack as well but somebody suggested I post it here too/instead.</p>
<p>I wrote a shortest-path script for a Unity game project, and while it works, it gets so slow when applied at scale that it crashes Unity when executed. This is to say, it works slowly for a single test character, but scale is required for the project.</p>
<p>I didn't really follow any of the known shortest path techniques to create it, rather I did it myself. The way it works is that it spawns a series of recursive methods each containing a for loop to explore each possible node in the network, bringing with each method a pathway and a list of pathways. If the target is found, or if the current path gets longer than a known path, or if a new node has already been inspected, the method terminates.</p>
<p>Here is some code. I have excluded the method that initially calls this recursive method:</p>
<pre><code>void ExploreBranch(List<Point> stem, List<List<Point>> masterList, Point target)
{
if (masterList.Count > 0)
{
for (int m = 0; m < masterList.Count; m++)
{
List<Point> thisList = masterList[m];
if (stem.Count + 1 >= thisList.Count)
{
return;
}
}
}
Point lastPoint = stem[stem.Count - 1];
for (int c = 0; c < lastPoint.Connections.Count; c++)
{
List<Point> updatedRoute = new List<Point>(stem);
Point newConnection = new Point();
newConnection = lastPoint.Connections[c];
if (newConnection == target)
{
updatedRoute.Add(newConnection);
masterList.Add(updatedRoute);
return;
}
if (updatedRoute.Contains(newConnection))
{
continue;
}
updatedRoute.Add(newConnection);
ExploreBranch(updatedRoute, inspected, masterList, target);
}
}
</code></pre>
<p>So, basically this is nowhere near efficient enough and I can't figure out a way within this basic framework to improve it. I am now leaning in the direction of starting over or trying to get really experimental, but thought I would check here first.</p>
<p>One of the main things here is that I need to preserve the actual pathway, which the character needs to use and follow within the game. So it's not just that I need to know how short the path can be, I also need the actual path.</p>
<p>Any ideas would be most appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T09:09:51.203",
"Id": "525445",
"Score": "3",
"body": "Pathfinding is a _notoriously_ difficult problem, especially when balancing performance and scalability. It may be considerably more fruitful to look at existing pathfinding algorithms because this is not something anyone can draw up easily from scratch."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T09:23:07.097",
"Id": "525491",
"Score": "0",
"body": "I actually ended up switching to a breadth first algo, which is working much better. It turns out the one I had made was basically a depth first search, ideally bad for what I was trying to do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T09:35:45.057",
"Id": "525492",
"Score": "1",
"body": "Not enough code for review. Btw, this code can be optimized. But I can't figure out what is `Point` and how the method is used, show it. _I have excluded the method that initially calls this recursive method_ - please show it, it can give a sense what's really happening. Then It isn't clear how the result returned, the methond returns `void`. Can you explain how the result is used? Show the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T14:02:31.190",
"Id": "525494",
"Score": "2",
"body": "`ExploreBranch(updatedRoute, inspected, masterList, target);` isn't a recursive call but call of the other mehtod overload. Where's it?"
}
] |
[
{
"body": "<p><code>void ExploreBranch(List<Point> stem, List<List<Point>> masterList, Point target)</code></p>\n<p>Based on this signature, I can't understand what this function takes in (what is a "masterList"? what is a "stem"?). Since it returns <code>void</code>, I can't understand what it returns or updates, if anything. Include ALL your code in a short working example, and clearly document what each function takes in and returns. I recommend reading some standard library function documentation--look for descriptions that are 1-2 sentences or less. You can still understand what the function will do--try to follow this style.</p>\n<p>"My path finding is too slow and I don't know why" is a good trigger that you should try asymptotic analysis of algorithm runtime, if you know how. If you expect to solve problems like this regularly, you should learn how if not (it's not acutally hard, it's just that it's a common college intro class and people make it way too formal). And/or, read existing path-finding algorithms.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T07:53:31.967",
"Id": "266576",
"ParentId": "265995",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T15:45:18.067",
"Id": "265995",
"Score": "2",
"Tags": [
"c#",
"time-limit-exceeded",
"pathfinding",
"unity3d"
],
"Title": "Shortest route algo terribly slow"
}
|
265995
|
<p>I was told that the following code of mine was poorly written. How bad is it? Do you have any recommendations?</p>
<pre><code>
#include <iostream>
#include <fstream>
void ioMenu(std::ifstream&, std::ofstream&, std::string&, std::string&);
int ioMenuChoice();
void fileOpener(std::ifstream&, std::ofstream&, std::string&, int&);
void fileReader(std::ifstream&, std::string&);
void fileWriter(std::ofstream&);
void fileOpenAndRead(std::ifstream&, std::ofstream&, std::string&, std::string&);
void fileCreateAndWrite(std::ifstream&, std::ofstream&, std::string&);
void readAndWrite(std::ifstream&, std::ofstream&, std::string&, std::string&);
int main() {
std::string fileName {};
std::string reader {};
std::ifstream inputFile {};
std::ofstream outputFile {};
ioMenu(inputFile, outputFile,fileName,reader);
}
void ioMenu(std::ifstream& inputFile, std::ofstream& outputFile, std::string& fileName, std::string& reader) {
switch (ioMenuChoice()) {
case 1:
fileOpenAndRead(inputFile, outputFile, fileName, reader);
break;
case 2:
fileCreateAndWrite(inputFile, outputFile, fileName);
break;
case 3:
readAndWrite(inputFile, outputFile, fileName, reader);
}
}
int ioMenuChoice(){
int choice {};
std::cout << "1. Read from file\n2. Output to File\n3. Both\n4. Exit\n";
std::cin >> choice;
while (choice < 1 || choice > 4){
std::cout << "\nInvalid input. Please re-enter a number from 1 to 3 : ";
std::cin >> choice;
}
return choice;
}
void fileOpener(std::ifstream& inputFile, std::ofstream& outputFile, std::string& fileName, int choice) { // Grab / Open file
// Grab file name
std::cout << "Please enter the directory and file name : Example : C:\\Users\\Alex\\Desktop\\numbers.txt : ";
std::cin >> fileName;
if (choice == 1) {
inputFile.open(fileName);
while (inputFile.fail()) {
std::cout << "Invalid input. Please re-enter the directory and file name : Example : C:\\Users\\Alex\\Desktop\\numbers.txt : ";
std::cin >> fileName;
inputFile.open(fileName);
}
}
else {
outputFile.open(fileName);
}
}
void fileReader(std::ifstream& inputFile, std::string& reader) { // Read from file
while (inputFile >> reader) {
std::cout << reader;
}
inputFile.close();
}
void fileWriter(std::ofstream& outputFile) {
std::string outputString("");
std::cout << "What would you like to write to the file? ";
std::cin >> outputString;
outputFile << outputString;
outputFile.close();
}
void fileOpenAndRead(std::ifstream& inputFile, std::ofstream& outputFile, std::string& fileName, std::string& reader) {
fileOpener(inputFile, outputFile, fileName, 1);
fileReader(inputFile, fileName);
}
void fileCreateAndWrite(std::ifstream& inputFile, std::ofstream& outputFile, std::string& fileName) {
fileOpener(inputFile, outputFile, fileName, 2);
fileWriter(outputFile);
}
void readAndWrite(std::ifstream& inputFile, std::ofstream& outputFile, std::string& fileName, std::string& reader) {
fileOpenAndRead(inputFile, outputFile, fileName, reader);
fileCreateAndWrite(inputFile, outputFile, fileName);
}
</code></pre>
<p>edit : Heres the finished code, sorry. The main thing I am looking for is if I am using functions correctly ( Does each have a specific role? etc</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T17:22:37.187",
"Id": "525418",
"Score": "0",
"body": "Welcome to Code Review! I [changed the title](https://codereview.stackexchange.com/posts/265999/revisions#rev-body-09f198ac-3467-4bb0-a637-981b1e57e594) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T20:14:44.633",
"Id": "525427",
"Score": "1",
"body": "There are indeed several things amiss here. Which ones do you already know about? You mentioned one criterium, what does that mean and does your code fulfill it?"
}
] |
[
{
"body": "<p>Well, the first thing that jumps out is that there is no <code>const</code> in any of the parameters.</p>\n<p><code>void fileOpener(std::ifstream&, std::ofstream&, std::string&, int&);</code></p>\n<p>for example, the 3rd and 4th parameters are "out" parameters? This indicates that the function will modify the <code>string</code> and the <code>int</code> in the caller's copy. Yet, it is <code>void</code> so why not provide a result in the normal way?</p>\n<p>The lack of parameter names also makes it less clear what these functions are doing and how to use them.</p>\n<pre><code> std::string fileName {};\n std::string reader {};\n std::ifstream inputFile {};\n std::ofstream outputFile {};\n</code></pre>\n<p>You don't need <code>{}</code> after all of these, as they have default constructors.</p>\n<p>The <code>main</code> function continues with<br />\n<code> ioMenu(inputFile, outputFile,fileName,reader);</code><br />\nand <strong>nothing else</strong>. So if these are all "out" parameters, what are you doing with the results?</p>\n<hr />\n<p>Looking at the functions, the shared parameters are passed through and (possibly) updated by each individual function that could be called.</p>\n<p>The set of functions should be written as a class, with those 4 values as instance data, instead.</p>\n<p>E.g.</p>\n<pre><code>class Putter {\n std::string fileName;\n std::string reader;\n std::ifstream inputFile;\n std::ofstream outputFile;\n void fileOpener();\n void fileReader();\n void fileWriter();\n void fileOpenAndRead();\n void fileCreateAndWrite();\n void readAndWrite();\npublic:\n void run(); // something like that. What you have in `main` goes here.\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T21:57:10.313",
"Id": "525433",
"Score": "0",
"body": "Thank you. I am a pretty novice programmer, I now get that I should be using const in all my parameters passed by reference if I do not plan on modifying their values. To my understanding, all arrays are passed as a reference since its a pointer to the first element, so whenever I make a function parameter with an array, should I be putting a const infront of them? thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T13:46:25.883",
"Id": "525458",
"Score": "0",
"body": "@d8Alexander It can be overwhelming to be a novice these days, I'm sure! There's something to be said about starting with primitive systems first. Keep it up. Re arrays: passing an \"array\" (really a pointer to the first element) is a C thing and not something you should normally be doing. Write your functions to take _iterators_ and work with any collection class, not limited to arrays. ..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T13:46:34.120",
"Id": "525459",
"Score": "0",
"body": "... OTOH, the most efficient internal code might indeed work directly with a contiguous sequence in memory; use [gsl::span](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#i13-do-not-pass-an-array-as-a-single-pointer) for that. And since I brought it up, be sure to study the \"Standard Guidelines\" document that this is a link into."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T21:40:11.377",
"Id": "266012",
"ParentId": "265999",
"Score": "1"
}
},
{
"body": "<p><strong>Code structure review</strong></p>\n<p>This code intends to support two operations based on command line input</p>\n<ol>\n<li>Read file</li>\n<li>Write file</li>\n</ol>\n<p>File open is not a separate operation, because it is implicitly required for read and write. So there are three function required. One main and and two handler functions for switches. Based on code in question, I don't see any further refactoring required.</p>\n<p>So simple design can be to create following command line options</p>\n<p>-read file_path</p>\n<p>-write file_path</p>\n<pre><code>// Assumes you don't want to return read contents, you just want to push them stdout\nvoid readFile(const std::string& file_path){ \n}\n\n// Assumes you don't write content from stdin to file.\nvoid writeFile(const std::string& file_path){\n}\n\nint main(int argc, char**argv) {\n // Parse commandline to get mode and file_path. On error print usage help\n // Based on switch invoke readFile or writeFile \n \n return 0;\n}\n\n</code></pre>\n<p><strong>Code review</strong></p>\n<pre><code>// Make clear distinction between in, out and in-out parameter.\n// In parameters by const refs and other two can be passes as refs.\nvoid ioMenu(std::ifstream&, std::ofstream&, std::string&, std::string&);\nint ioMenuChoice();\nvoid fileOpener(std::ifstream&, std::ofstream&, std::string&, int&);\nvoid fileReader(std::ifstream&, std::string&);\nvoid fileWriter(std::ofstream&);\nvoid fileOpenAndRead(std::ifstream&, std::ofstream&, std::string&, std::string&);\nvoid fileCreateAndWrite(std::ifstream&, std::ofstream&, std::string&);\nvoid readAndWrite(std::ifstream&, std::ofstream&, std::string&, std::string&);\n</code></pre>\n<pre><code>// As per signature, this function should return int value.\n// But there is no return statement in function body.\nint main() { \n</code></pre>\n<pre><code>// Can file be read without opening?\nvoid fileOpenAndRead(std::ifstream& inputFile, ...) { \n</code></pre>\n<pre><code>// And in function name is red flag.\n// It indicates functions is doing more than one thing which is not good design.\n// Refactor to ensure function does only one thing.\nvoid readAndWrite(std::ifstream& inputFile, ...) {\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-22T14:22:10.567",
"Id": "526042",
"Score": "0",
"body": "Thanks. Should I put code from void ioMenu in main or is it okay if I leave it in this function? Is it considered bad practice? I prefer to have a void function that would normally have my code from main and just call it as it looks cleaner"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-22T10:02:12.833",
"Id": "266289",
"ParentId": "265999",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T16:27:57.063",
"Id": "265999",
"Score": "1",
"Tags": [
"c++",
"io"
],
"Title": "File reader and writer"
}
|
265999
|
<p>This is the first project I have ever undertaken and now that I've gotten it to a point I feel comfortable with, I would love to get some review and tips for any improvement on it! I am especially interested in getting tips on the design, readability and unit testing part of my code and any and all tips for improvement are welcome!</p>
<p>I have purposefully written all the data to files in the Storage-class, but my next step is going to be to implement an SQL database along with a GUI of some sort if I happen to get my project reviewed!</p>
<p><strong>I have not yet written any unit tests for the Storage-class and I am wondering whether it is usually even done? I suppose it is since they must return correct information, but I wanted to ask anyway...</strong></p>
<p>If there is anything that is unclear in the code, please do ask and I will clarify!</p>
<p>Here is a short summary of each of the classes function.</p>
<p><strong>Login-class:</strong> Is responsible for the logging in of a user and returning the correct user along with a correct ToDoList.</p>
<p><strong>RegisterNewUsernameAndPassword-class:</strong> Quite obvious, but it is responsible for creating a new user.</p>
<p><strong>Storage-class:</strong> Responsible for writing the Users and ToDoLists to a file so they can be saved and loaded. Also forwards the information to the Login-class and some other classes.</p>
<p><strong>ToDoList-class:</strong> Responsible for the creation of a ToDoList for the user and the associated methods.</p>
<p><strong>ToDoListTest-class:</strong> Unit tests for the ToDoList class.</p>
<p><strong>User-class:</strong> Defines the parameters for a new User and contains setters and getters.</p>
<p><strong>toDo-class:</strong> Every item added to a ToDoList is a toDo-item and this class is responsible for the creation of those.</p>
<p><strong>UI-class:</strong> The user interface which transmits the information to the user via a console presently.</p>
<pre class="lang-java prettyprint-override"><code>public class UI {
private final Scanner reader;
private Storage storage;
private Login login;
private RegisterNewUsernameAndPassword registerNew;
private User user;
public UI() {
this.reader = new Scanner(System.in);
this.storage = new Storage();
this.login = new Login();
this.registerNew = new RegisterNewUsernameAndPassword();
}
public void start() {
System.out.println("Login or register");
String fromUser = reader.nextLine().trim();
if (fromUser.equalsIgnoreCase("register")) {
System.out.print("Your username:");
String userName = reader.nextLine();
System.out.print("Your first name:");
String firstName = reader.nextLine();
System.out.print("Your last name:");
String lastName = reader.nextLine();
System.out.print("Your password:");
String password = reader.nextLine();
registerNew.createUser(userName, firstName, lastName, password);
}
login.logIn();
this.user = login.returnUser();
this.user.getUsersToDoList().printToDoList();
while (true) {
System.out.println("");
System.out.println("1: Add a to-do item.");
System.out.println("2. Remove a to-do item.");
System.out.println("3. Print a list of my to-do items.");
System.out.println("4. Quit and save");
System.out.print("Type the number of desired action: ");
String input = reader.nextLine();
if (input.equals("4")) {
storage.getToDoLists().put(login.returnUsername(), this.user.getUsersToDoList());
storage.saveUsersToDoLists(storage.getToDoLists());
System.out.println("Quitting!");
break;
} else if (input.equals("1")) {
System.out.println("What would you like to add?");
String add = reader.nextLine();
toDo item = new toDo(add);
this.user.getUsersToDoList().addToDo(item);
} else if (input.equals("2")) {
if (this.user.getUsersToDoList().getList().isEmpty()) {
System.out.println("List is empty.");
continue;
}
System.out.println("");
this.user.getUsersToDoList().printToDoList();
System.out.print("Type the index of the item you wish to remove: ");
int remove = Integer.parseInt(reader.nextLine());
this.user.getUsersToDoList().removeToDo(remove);
} else if (input.equals("3")) {
System.out.println("");
this.user.getUsersToDoList().printToDoList();
}
}
}
}
public class Login {
private User user;
private Storage storage;
private Scanner reader;
private String username;
public Login() {
this.storage = new Storage();
this.reader = new Scanner(System.in);
}
public void logIn() {
storage.loadUserNamesAndPasswords(storage.getUsernamesAndPasswordsFile());
storage.loadUsersToDoLists(storage.getUsersToDoListsFile());
System.out.println("Username:");
this.username = reader.nextLine();
System.out.println("Password:");
String password = reader.nextLine();
try {
if (storage.getUserNamesAndPasswords().get(username).passwordEquals(password) != null) {
this.user = storage.getUserNamesAndPasswords().get(username);
this.user.setList(storage.getToDoLists().get(username));
System.out.println("Welcome " + user.getFirstName() + "!");
}
} catch (NullPointerException npe) {
System.out.println("Incorrect username or password. Please try again!");
this.logIn();
}
}
public User returnUser() {
return this.user;
}
public String returnUsername() {
return this.username;
}
}
public class User implements Serializable {
private String firstName;
private String lastName;
private String password;
private ToDoList toDoList;
public User(String firstName, String lastName, String password) {
this.firstName = firstName;
this.lastName = lastName;
this.password = password;
this.toDoList = new ToDoList();
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public ToDoList getUsersToDoList() {
return this.toDoList;
}
public void setList(ToDoList list) {
this.toDoList = list;
}
public Boolean passwordEquals(String password) {
return this.password.equals(password);
}
}
public class Storage {
private HashMap<String, ToDoList> toDoLists;
private HashMap<String, User> map;
private File UsernamesAndPasswords;
private File UsersToDoLists;
Storage() {
this.UsernamesAndPasswords = new File("UsernamesAndPasswords.ser");
this.UsersToDoLists = new File("ToDoLists.ser");
loadUserNamesAndPasswords(UsernamesAndPasswords);
loadUsersToDoLists(UsersToDoLists);
}
public void saveUsersToDoLists(HashMap<String, ToDoList> usersToDoLists) {
try {
FileOutputStream fosTwo = new FileOutputStream(UsersToDoLists);
ObjectOutputStream oosTwo = new ObjectOutputStream(fosTwo);
oosTwo.writeObject(this.toDoLists);
oosTwo.flush();
oosTwo.close();
fosTwo.close();
} catch (IOException e) {
System.out.println("Exception happened. saveUsersList");
}
}
public void loadUsersToDoLists(File file) {
if (file.length() == 0) {
toDoLists = new HashMap<>();
this.saveUsersToDoLists(toDoLists);
}
try {
FileInputStream fisTwo = new FileInputStream(UsersToDoLists);
ObjectInputStream oisTwo = new ObjectInputStream(fisTwo);
toDoLists = (HashMap<String, ToDoList>) oisTwo.readObject();
oisTwo.close();
fisTwo.close();
} catch (Exception e) {
System.out.println("Exception happened. loadUsersList");
}
}
public void saveUserNamesAndPasswords(HashMap<String, User> loginInfo) {
try {
FileOutputStream fos = new FileOutputStream(UsernamesAndPasswords);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(this.map);
oos.flush();
oos.close();
fos.close();
} catch (IOException e) {
System.out.println("Exception happened. saveUsernames");
}
}
public void loadUserNamesAndPasswords(File file) {
//If the file is empty then this method creates a new empty hashmap and saves it
//in the file
if (file.length() == 0) {
map = new HashMap<>();
this.saveUserNamesAndPasswords(map);
}
try {
FileInputStream fis = new FileInputStream(UsernamesAndPasswords);
ObjectInputStream ois = new ObjectInputStream(fis);
map = (HashMap<String, User>) ois.readObject();
ois.close();
fis.close();
} catch (Exception e) {
System.out.println("Exception happened. loadUserNames");
}
}
public HashMap<String, User> getUserNamesAndPasswords () {
return this.map;
}
public File getUsernamesAndPasswordsFile() {
return this.UsernamesAndPasswords;
}
public HashMap<String, ToDoList> getToDoLists() {
return this.toDoLists;
}
public File getUsersToDoListsFile() {
return this.UsersToDoLists;
}
}
public class RegisterNewUsernameAndPassword {
private Storage storage;
private User user;
public RegisterNewUsernameAndPassword() {
this.storage = new Storage();
}
public void createUser(String userName, String firstName, String lastName, String password) {
this.user = new User(firstName, lastName, password);
this.storage.getUserNamesAndPasswords().putIfAbsent(userName, user);
this.storage.saveUserNamesAndPasswords(storage.getUserNamesAndPasswords());
this.storage.getToDoLists().putIfAbsent(userName, this.user.getUsersToDoList());
this.storage.saveUsersToDoLists(storage.getToDoLists());
}
public class ToDoListTest {
@Test
public void addToDo(){
ToDoList todolist = new ToDoList();
toDo todo = new toDo("Test");
todolist.addToDo(todo);
assertTrue(todolist.getList().contains(todo));
}
@Test
public void removeToDo() {
ToDoList todolist = new ToDoList();
toDo todo = new toDo("Test");
todolist.addToDo(todo);
todolist.removeToDo(1);
assertFalse(todolist.getList().contains(todo));
}
@Test
public void listIsEmptyWhenCreated() {
ToDoList todolist = new ToDoList();
assertTrue(todolist.getList().isEmpty());
}
@Test
public void getList() {
ToDoList todolist = new ToDoList();
ArrayList<toDo> list = new ArrayList<>();
assertEquals(list, todolist.getList());
}
@Test
public void printToDoList() {
ToDoList todolist = new ToDoList();
toDo todo = new toDo("Test");
todolist.addToDo(todo);
PrintStream oldOut = System.out;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
System.setOut(new PrintStream(baos));
todolist.printToDoList();
System.setOut(oldOut);
String output = baos.toString();
assertTrue(output.contains("1: Test"));
}
@Test
public void printEmptyToDoList() {
ToDoList todolist = new ToDoList();
PrintStream oldOut = System.out;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
System.setOut(new PrintStream(baos));
todolist.printToDoList();
System.setOut(oldOut);
String output = baos.toString();
assertTrue(output.contains("List is empty."));
}
}
public class toDo implements Serializable {
private String name;
public toDo(String name) {
this.name = name;
}
public void setName(String setName) {
this.name = setName;
}
public String getName() {
return this.name;
}
public String toString() {
return this.name;
}
}
public class ToDoList implements Serializable {
private ArrayList<toDo> toDoList;
public ToDoList() {
this.toDoList = new ArrayList<>();
}
public void addToDo(toDo toDo) {
this.toDoList.add(toDo);
}
public void removeToDo(int toDo) {
try {
this.toDoList.remove(toDo - 1);
} catch (IndexOutOfBoundsException e) {
System.out.println("The index you have entered is invalid.");
System.out.println("Please enter a number between or equal to 1 or " + toDoList.size() + ".");
}
}
public void printToDoList() {
if (toDoList.isEmpty()) {
System.out.println("List is empty.");
} else {
int i = 1;
for (toDo todo : toDoList) {
System.out.println(i + ": " + todo);
i++;
}
}
}
public ArrayList<toDo> getList() {
return this.toDoList;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T18:47:10.573",
"Id": "525704",
"Score": "1",
"body": "Welcome to Code Review! I have rolled back Rev 4 → 3. Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers)."
}
] |
[
{
"body": "<p>Welcome to code review! There is a lot of code and a lot to say, but I will concentrate on <code>Storage</code> as it is a fairly central component that affects the quality of all other classes.</p>\n<p>You should study the <a href=\"https://en.wikipedia.org/wiki/SOLID\" rel=\"nofollow noreferrer\">SOLID</a> principles, especially the <a href=\"https://en.wikipedia.org/wiki/Dependency_inversion_principle\" rel=\"nofollow noreferrer\">D</a> (dependency inversion). You should treat <code>Storage</code> as a service that is provided to each other class. Not something that the classes have to create themselves. So create a class that bootstraps one <code>Storage</code> instance and passes that instance to the <code>UI</code>, <code>Login</code> and whoever needs it.</p>\n<p>When you think about <code>Storage</code> as a service, you need to identify the operations that are <em>needed</em> by its clients. Knowing the location of the usernames and passwords file hardly is something that is relevant to the user interface or login, right? Thus you shouldn't expose the <code>getUsernamesAndPasswordsFile()</code>. Just let <code>Storage</code> handle all the file related stuff privately. When you have identified the required storage operations, <a href=\"https://en.wikipedia.org/wiki/Interface_segregation_principle\" rel=\"nofollow noreferrer\">define them in an interface</a> and make the classes use the interface, not the concrete class that implements it.</p>\n<p><code>RegisterNewUsernameAndPassword</code> should not be a class. Its name describes an action, therefore it should be a method in <code>Storage</code>. You should also consider whether it makes sense to complicate your application with user accounts when it is not really usable in shared environment. It's a beginner project so you maybe should concentrate first on being able to create a good single user application before submitting yourself to the multitude of complications that arise when many users access a single application.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T17:07:14.847",
"Id": "525500",
"Score": "0",
"body": "So I should make a “StorageBootstrapper”-class, and then create an instance of Storage in that class and thus create an instance of “StorageBootstrapper” in each class that needs the services of the storage? I’m not sure what you mean by passing other than creating an instance of that class inside another? \n\n\nDo you mean that I would create an interface with the methods that I need and then use an instance of the StorageBootstrapper-class inside those methods and via that use methods that are defined in the storage-class itself thus hiding the details of, the file-related stuff for example?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T04:22:04.260",
"Id": "525545",
"Score": "0",
"body": "I mean that UI (and other classes that need Storage) should have a constructor that takes a Storage instance as a parameter."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T08:00:29.080",
"Id": "266024",
"ParentId": "266001",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "266024",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T17:41:14.057",
"Id": "266001",
"Score": "2",
"Tags": [
"java",
"beginner",
"object-oriented",
"to-do-list"
],
"Title": "A to-do list application written with Java"
}
|
266001
|
<p>I have a function called <code>USB()</code>, that will observe a <a href="https://en.wikipedia.org/wiki/USB_flash_drive" rel="nofollow noreferrer">USB stick's</a> insertion and delete files inside of it, if there are some:</p>
<pre><code>import os
import shutil
# 1. Check and clean USB
def USB():
usb_inserted = os.path.isdir("F:") # <-- returns boolean...checks whether a directory exists
if usb_inserted == False:
print("\n\nUSB stick is not plugged in. Waiting for connection...")
while usb_inserted == False: # wait
""" updating variable, because it takes only the return value of function 'isdir()'
and stays the same regardless of the fact, that 'isdir()' changed """
usb_inserted = os.path.isdir("F:")
continue
SECURITY_FILE = "System Volume Information"
if os.listdir("F:") == [SECURITY_FILE] or os.listdir("F:") == []: # if list of files contains only the security file (is empty)
print("\nUSB flash is already empty.") # send a message and continue
else:
files = os.listdir("F:") # list of names of files in the usb flash, that will be deleted
if SECURITY_FILE in files:
""" taking out the security file from the list, because attempting to delete it causes
'PermissionError [WinError 5]' exception """
files.remove(SECURITY_FILE)
for file in files: # Loop through the file list
if os.path.isfile(f"F:\\{file}"): # if it's a file
os.remove(f"F:\\{file}") # Delete the file
elif os.path.isdir(f"F:\\{file}"): # if it's a directory/folder
shutil.rmtree(f"F:\\{file}") # remove the folder
print("\nAll files/folders are deleted from USB.")
USB()
</code></pre>
<p>Is there anything, that can be improved in terms of cleaner code or things that I could have missed while testing?</p>
|
[] |
[
{
"body": "<h1>Boolean Checks</h1>\n<p>Instead of doing:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if usb_inserted == False:\n # do something\n</code></pre>\n<p>use</p>\n<pre class=\"lang-py prettyprint-override\"><code>if not usb_inserted:\n # do something\n</code></pre>\n<h1><code>while not usb_inserted</code></h1>\n<p>This while loop will hammer away at a file system call to check if a drive exists. I'd check once every few seconds instead:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from time import sleep\n\ndef wait_for_usb():\n while True:\n if os.path.isdir('F:'):\n break\n else:\n # give user notification it's still waiting\n print('Detecting...')\n sleep(2)\n</code></pre>\n<h1>Checking List Contents</h1>\n<p>To check for an empty list, you can rely on it's truthiness instead of an explicit equality check:</p>\n<pre class=\"lang-py prettyprint-override\"><code># instead of this:\nif os.listdir("F:") == []:\n # do something\n\n# do this\nif not os.listdir('F:'):\n # do something\n</code></pre>\n<p>Furthermore, it would be better to do that operation only once:</p>\n<pre class=\"lang-py prettyprint-override\"><code># This might be a better check for the security file\ndef only_contains_security_file(contents):\n return len(contents) == 1 and contents[0] == "System Volume Information"\n\n\n# only grab contents once\ncontents = os.listdir('F:')\n\nif not contents or only_contains_security_file(contents):\n print("\\nUSB flash is already empty.")\n</code></pre>\n<h1>Iterating over files</h1>\n<p>Since you just want to do a top-level walk of your drive, you can use <code>os.scandir</code> instead of iterating over <code>os.listdir</code>. This has a few advantages. One being that it doesn't aggregate everything into a <code>list</code> (a disadvantage that <code>os.walk</code> has for this use as well) and that it automatically allows you to check types:</p>\n<pre class=\"lang-py prettyprint-override\"><code>for item in os.scandir('F:'):\n if item.name.endswith("System Volume Information"):\n continue\n elif item.is_file():\n os.remove(item.path)\n else:\n shutil.rmtree(item.path)\n \n</code></pre>\n<p>This is also useful if your usb is full of a ton of files with long names.</p>\n<p>You also don't need to check if it's empty, your loop will just skip everything if it is.</p>\n<h1>Adding <code>if __name__ == "__main__"</code> guard</h1>\n<p>This is useful for scripts that you may want to run, but also want to import things from. With this guard in place, if you import things from the usb module from another python script, it won't execute your script. This is nice considering you have an infinite loop:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def usb():\n # your code\n\nif __name__ == "__main__":\n usb()\n</code></pre>\n<p>So altogether:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import os\nimport shutil\nfrom time import sleep\n\n\ndef wait_for_usb():\n print("Waiting for usb at F:")\n\n while True:\n if os.path.isdir('F:'):\n break\n else:\n print("Detecting...")\n sleep(2)\n\n\ndef usb():\n wait_for_usb()\n\n for item in os.scandir('F:'):\n if item.name.endswith("System Volume Information"):\n print('Skipping system info file')\n continue\n elif item.is_file():\n print(f"Removing file {item.path}")\n os.remove(item.path)\n else:\n print(f"Removing directory {item.path}")\n shutil.rmtree(item.path)\n\n\n print('USB is now empty')\n\n\nif __name__ == "__main__":\n usb()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T13:12:15.297",
"Id": "525452",
"Score": "2",
"body": "@user394299 I mean, it's 2 seconds, but if that's too long to wait, you could either drop the sleep altogether, or make it sleep for less time"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T13:26:20.073",
"Id": "525456",
"Score": "0",
"body": "C.Nivs, ```while not os.path.isdir(\"F:\"): continue```"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T15:40:33.860",
"Id": "525465",
"Score": "15",
"body": "Busy waits like that, occupying a full CPU core merely to monitor for a change, are generally considered pretty terrible. I suppose it'd be adequate for a simple code demonstration in school, but if I saw it in a production application, I'd think very poorly of its author. The computer has other things to do; users hate for a program to use an entire core just to wait for something beyond its control to happen. Ideally, you want to register with the OS for an event, but if you can't, at least pause for half a second or more between checks. Minimize that CPU time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T16:35:54.027",
"Id": "525469",
"Score": "0",
"body": "@Corrodias, is that realted to me or Niv's ```wait_for_usb()``` function? lol"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T17:06:07.123",
"Id": "525471",
"Score": "0",
"body": "@C.Nivs we don't need ```if __name__ == \"__main__\"```, because this function will be with other 2 functions (I'll post about them later) and they will be used in another .py file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T17:09:01.467",
"Id": "525472",
"Score": "5",
"body": "@user394299 Really either implementation of waiting for the usb is bad, so they probably mean both. Mine is an improvement to keep the loop from hammering away at the CPU in a way that degrades performance. Reinderien is right, there are better production quality ways to do this"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T20:01:44.800",
"Id": "525477",
"Score": "9",
"body": "@user394299 Both are suboptimal, yes, but waiting some time between checks is considerably lighter on resource use than a tight loop is. I expect the best performance would come from registering a drive insertion event handler with the Win32 API, but that's awfully complex to do within Python. This question seems to go into some detail on that. https://stackoverflow.com/questions/38689090/"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T23:44:41.550",
"Id": "266016",
"ParentId": "266009",
"Score": "15"
}
},
{
"body": "<p>It is recommended to follow <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> for readability and maintainability. The code violates many guidelines. Consider running the code through <a href=\"https://www.pylint.org/\" rel=\"nofollow noreferrer\"><code>pylint</code></a> and <a href=\"https://pypi.org/project/pycodestyle/\" rel=\"nofollow noreferrer\"><code>pycodestyle</code></a>.</p>\n<h2>Blank Lines</h2>\n<p><code>USB</code> only has one blank line above it.</p>\n<blockquote>\n<h2><a href=\"https://www.python.org/dev/peps/pep-0008/#blank-lines\" rel=\"nofollow noreferrer\">Blank Lines</a></h2>\n<p>Surround top-level function and class definitions with two blank lines.</p>\n</blockquote>\n<h2>Line length</h2>\n<blockquote>\n<h2><a href=\"https://www.python.org/dev/peps/pep-0008/#maximum-line-length\" rel=\"nofollow noreferrer\">Maximum Line Length</a></h2>\n<p>Limit all lines to a maximum of 79 characters.</p>\n<p>For flowing long blocks of text with fewer structural restrictions (docstrings or comments), the line length should be limited to 72 characters.</p>\n</blockquote>\n<p>There are many lines that contain more than 79 characters.</p>\n<h2>Constants</h2>\n<p>It appears there is only one constant used by the function: <code>SECURITY_FILE</code></p>\n<blockquote>\n<h2><a href=\"https://www.python.org/dev/peps/pep-0008/#constants\" rel=\"nofollow noreferrer\">Constants</a></h2>\n<p>Constants are usually defined on a module level and written in all capital letters with underscores separating words. Examples include <code>MAX_OVERFLOW</code> and <code>TOTAL</code>.</p>\n</blockquote>\n<p>Move <code>SECURITY_FILE</code> to the top of the module. While it may never need to be updated, if a change was required then it would be easier to find instead of hunting through the file.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T11:00:32.660",
"Id": "525519",
"Score": "0",
"body": "Perhaps add some suggestions for some tools to check for PEP8 violations? Like [Pycodestyle](https://github.com/PyCQA/pycodestyle) and [Pylint](https://en.wikipedia.org/wiki/Pylint) (presuming the latter can actually do it)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T21:18:37.857",
"Id": "525540",
"Score": "0",
"body": "Strictly conforming to PEP8 for line length is, honestly, overly proscriptive. Even `psf/black`, the \"uncompromising\" formatter, uses a max length of 88, and allows user configuration. I would move the focus away from the actual number of characters there, and more toward the idea of breaking up some lines (e.g. moving comments above/below the described line)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T00:00:23.873",
"Id": "266017",
"ParentId": "266009",
"Score": "10"
}
},
{
"body": "<p>A production-grade solution would not have a polling loop at all, and would rely on a filesystem change notification hook. There are <a href=\"https://stackoverflow.com/questions/182197/how-do-i-watch-a-file-for-changes\">many, many ways</a> to do this with varying degrees of portability and ease of use; if I were you I'd use something portable and off-the-shelf like <a href=\"https://pythonhosted.org/watchdog/\" rel=\"noreferrer\">watchdog</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T15:55:12.520",
"Id": "266038",
"ParentId": "266009",
"Score": "9"
}
},
{
"body": "<p>I am a bit late to the party but I would like to reinforce the already stated comments: polling is a bad approach. You should be listening to system <strong>events</strong> so the program should be idle most of the time. Using watchdog would be an improvement but you can do better.</p>\n<p>There are libraries for USB in Python, for example <a href=\"https://github.com/pyusb/pyusb\" rel=\"nofollow noreferrer\">pyusb</a>, pyudev, <a href=\"https://pypi.org/project/libusb/\" rel=\"nofollow noreferrer\">libusb</a> and there is also the <a href=\"https://pypi.org/project/dbus-python/\" rel=\"nofollow noreferrer\">DBUS</a> library.</p>\n<p>See for example: <a href=\"https://stackoverflow.com/q/469243/6843158\">How can I listen for 'usb device inserted' events in Linux, in Python?</a></p>\n<p>The catch here is that you using <strong>Windows</strong>.</p>\n<p>There is an assumption that the USB stick shall be mounted as F: but it may not always be true, in particular if another USB storage device is already plugged in and has claimed that letter.</p>\n<p>The approach seems to quite dangerous as well, basically your script will wipe the contents of any USB key that satisfies your lax criteria. A more prudent approach would be to look at the <strong>serial number</strong> of the USB stick, and use a <strong>whitelist</strong> of serial numbers to decide if the stick being inserted should be wiped or not by your script.</p>\n<p>Deleting files one by one is not efficient if you have a lot (by the way, is there a trashbin for those files ?). If the goal is to remove sensitive files then maybe doing a quick format or clearing the partition would do the job as fine.</p>\n<p>If you're paranoid and don't want files to be restorable using forensic methods this will likely not suffice, then you're looking at the Windows equivalent of the shred command in Linux.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T05:37:29.703",
"Id": "526419",
"Score": "0",
"body": "I read you review and made a better version...thank you....But where do I upload it to review?...Do I need to make a new question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-30T06:42:56.937",
"Id": "526572",
"Score": "0",
"body": "@Tronzen I see you added an answer so maybe you already saw this but I’m case not see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T15:43:45.570",
"Id": "266081",
"ParentId": "266009",
"Score": "4"
}
},
{
"body": "<p>I read the reviews (thanks to everybody, who was supporting) and did some testing, which helped me to make an improved clean version...ᴵ ᵍᵘᵉˢˢ</p>\n<pre><code># 1.5 find the usb drive letter (path)\n\ndef find_drive_id():\n local_machine_connection = wmi.WMI()\n\n DRIVE_SERIAL_NUMBER = "88809AB5" # serial number is like an identifier for a storage device determined by system\n\n '''.Win32.LogicalDisk returns list of wmi_object objects, which include information\n about all storage devices and discs (C:, D:)'''\n\n for storage_device in local_machine_connection.Win32_LogicalDisk():\n if storage_device.VolumeSerialNumber == DRIVE_SERIAL_NUMBER: # if a device with matching serial number was found\n return storage_device.DeviceID\n\n return False\n\n\n# 1. Observe and clean usb flash\n\ndef USB():\n while not find_drive_id():\n input("\\nUSB stick is not found. Enter it and press [ENTER] to try again...")\n\n drive_id = find_drive_id()\n\n if os.listdir(drive_id) == ["System Volume Information"] or not os.listdir(drive_id):\n print(f"\\nUSB drive {drive_id} is already empty.")\n\n else:\n entry_iterator = os.scandir(drive_id) # iterator/generator of DirEntry objects\n\n for item in entry_iterator: \n if item.is_file(): # if it's a file\n os.remove(item.path) # Delete the file\n\n elif item.is_dir(): # if it's a directory/folder\n shutil.rmtree(item.path) # remove the folder\n\n print(f"\\nAll files/folders are deleted from USB drive {drive_id}.")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T18:18:54.170",
"Id": "266504",
"ParentId": "266009",
"Score": "0"
}
},
{
"body": "<p>Making a program to delete everything on a USB stick is dangerous. Consider listing current contents and asking for confirmation, to make sure you don't accidentally wipe the wrong stick or drive.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-30T07:31:14.440",
"Id": "526579",
"Score": "0",
"body": "In the main program I have to delete the previous temporary PDF files, so I made some changes in ```os.remove()``` part: ```if item.is_file() and item.name.startswith(\"tmp\") and item.name.endswith(\".pdf\"):``` ```os.remove(item.path)```"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T21:04:04.687",
"Id": "266508",
"ParentId": "266009",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "266081",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T20:37:55.113",
"Id": "266009",
"Score": "6",
"Tags": [
"python",
"python-3.x"
],
"Title": "USB stick condition check and file deleting function"
}
|
266009
|
<p>I've started my journey of learning assembly on my Mac. As a start, I've decided to write a program to print the numbers one through ten to the console, then a final string signifying the end of the program. I want to kick bad habits to the curb quick, and know if there's any optimizations I can make to this code. Any and all feedback is appreciated!</p>
<p><strong><code>loop_10.s</code></strong></p>
<pre><code># Author: Ben Antonellis
# Start of stack: offset=-20(%rbp)
# Short: Prints the numbers 1-10, then "End of program."
.section __TEXT,__text
.globl _main
_main:
# Stack construction
pushq %rbp
movq %rsp, %rbp
subq $32, %rsp
movl $0, -20(%rbp) # int i = 0;
Loop_Condition_Compare:
cmpl $10, -20(%rbp) # Check if i equals 10
jne Loop_Inside # True: Continue loop
jmp Loop_Exit # False: Exit loop
Loop_Inside:
# Add one to i
movl -20(%rbp), %eax
addl $1, %eax
movl %eax, -20(%rbp)
# Print i
movl -20(%rbp), %esi
leaq integer(%rip), %rdi
movb $0, %al
callq _printf
# Move to compare i
jmp Loop_Condition_Compare
Loop_Exit:
# Print "End of program."
leaq end_string(%rip), %rdi
movb $0, %al
callq _printf
# Stack deconstruction
xorl %eax, %eax
addq $32, %rsp
popq %rbp
retq
.data
integer: .asciz "%d\n"
end_string: .asciz "End of program.\n"
</code></pre>
<p>And here's how I run my code:</p>
<p><strong><code>run.sh</code></strong></p>
<pre><code>FILE=loop_10
gcc -o $FILE -fno-pie $FILE.s
./$FILE
rm $FILE
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T20:23:51.853",
"Id": "526280",
"Score": "1",
"body": "You can add to *i* with a single instruction `addl $1, -20(%rbp)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T20:26:30.407",
"Id": "526281",
"Score": "1",
"body": "Instead of the 2 jumps `jne Loop_Inside` `jmp Loop_Exit` `Loop_Inside:`, you should inverse the condition and allow falling through in the code beneath: `je Loop_Exit` `Loop_Inside:`"
}
] |
[
{
"body": "<blockquote>\n<p>I want to kick bad habits to the curb quick, and know if there's any optimizations I can make to this code</p>\n</blockquote>\n<p>Sure thing. I'll look past the option to print all text at once without a loop though, that would be an optimization but it wouldn't be as instructive or interesting. The details that are left are all minor compared to the cost of printing anything, but so be it.</p>\n<h2><code>movb $0, %al</code></h2>\n<p>In general when possible, I recommend <code>xorl %eax, %eax</code> (which you used later). Writing to 8-bit registers has <a href=\"https://stackoverflow.com/q/45660139/555045\">complicated issues</a>. Taking out the high bits of <code>eax</code> as "collateral damage" isn't a problem here, so I'd go with the good old <code>xorl %eax, %eax</code>, which doesn't have complicated issues and is in general the <a href=\"https://stackoverflow.com/q/33666617/555045\">recommended way to zero a register</a>.</p>\n<h2>loop patterns</h2>\n<p>The loop pattern has a lot of jumps and branches, all of them in the loop. Looping a known non-zero number of times can be done with just one branch. Even in general, you can do it with one branch and a jump <em>outside</em> of the loop (so it is executed less often).</p>\n<p>For example, for the general case:</p>\n<pre><code> jmp Loop_Condition_Compare\nLoop_Inside:\n ; stuff\nLoop_Condition_Compare:\n ; some comparison\n jcc Loop_Inside\nLoop_Exit:\n</code></pre>\n<p>And if you know that the loop condition will be true the first time it would be evaluated in that general pattern, you can leave out the jump that goes to the loop condition, leaving only the <code>jcc</code>. By the way <code>jcc</code> is a short-hand for a conditional jump with whichever condition code that you need.</p>\n<p>Iterating to zero can help save an instruction, but involves either counting down, or counting up through negative numbers, so this technique is not always easy or good to apply. I probably wouldn't use it in a case like this, but it's possible.</p>\n<p>You can also align the loop, but when that helps and by how much is not easy to predict.</p>\n<h2>Prefer registers over stack</h2>\n<p>Putting <code>i</code> on the stack is not necessary, it could be in a callee-save (aka non-volatile) register instead. For the x64 SysV ABI (used by x64 Mac and x64 Linux and generally almost anything that isn't Windows) that's <code>rbx</code>, <code>rbp</code>, <code>r12</code>, <code>r13</code>, <code>r14</code> and <code>r15</code>. Saving one of those (in the function prologue) and using it for <code>i</code> will also mean that <code>i</code> survives the function calls, and saves on stores and loads.</p>\n<p>Alternatively, you could keep <code>i</code> in a convenient register most of the time and only store it to the stack right before the call, and then load it back right after the call.</p>\n<p>I don't know if maybe you're following a mental model of "local variables go on the stack" (which I absolutely wouldn't blame you for, that's a common oversimplification found in most textbooks and tutorial websites and so on), but that's a thing for compilers in <code>-O0</code> mode. My general advice is: prefer to put values in registers. I intentionally write "values", because a <em>variable</em> doesn't need to be in the same place all the time, it could be in one place at one time and another place another time if that works out better in the code, so picking a location for a variable is not really the proper/complete way to look at it (it might lead you to miss optimization opportunities). Compilers also try to be a bit clever with this sort of thing, when not in <code>-O0</code> mode.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T22:45:44.023",
"Id": "266014",
"ParentId": "266011",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "266014",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T21:38:09.330",
"Id": "266011",
"Score": "1",
"Tags": [
"beginner",
"assembly",
"x86"
],
"Title": "Printing one to ten in (GAS/AT&T x86/x64) assembly"
}
|
266011
|
<p>Currently I am working on a project for which I want to have the different links (div elements) placed randomly on my webpage. To accomplish this, I first generate a set of coordinates and later check whether they overlap (<a href="https://stackoverflow.com/questions/68734459/how-to-make-sure-randomly-generated-divs-dont-overlap">SO thread, user @Robson helped me figure things out)</a>.</p>
<p>However, since this is my first JavaScript project that is longer than 15 lines of code, I am am sure to have missed some best-practices or simply took a too complicated approach. I am happy to learn about my mistakes and how to come up with more efficient or clean code!</p>
<p>Maybe I can describe my thought process a little:</p>
<ul>
<li><code>getMaxDimension</code>: in Order to have the divs not overflow the site, I need to only spawn them in coordinates far enough away from the right and bottom border of the screen, since coordinates are calculated from the top left corner.</li>
<li><code>getOffset</code>: To check whether two divs overlay, I check if any point of the polygon of div a is inside div b. To do that I calculate all the coordinates and store them in an object.</li>
<li><code>getOverlap</code>: basically just checks if div a's points and div b's points are inside of each other. The code seems rather complicated, but is just an implementation of the mathematical notation</li>
<li><code>getChar</code>: (<em>I really think there are better ways to do this</em>); In order to control every div uniquely, they all need different ID's. However, <code>id=1</code>, <code>id=2</code> and so on didn't work (maybe they are not allowed?). Now in order to "convert" iteration variables <code>i</code> and <code>j</code> to the corresponding div I just chose letters.</li>
</ul>
<p>MWE:</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> // Returns largest div's width and height
function getMaxDimension(arr) {
var maxWidth = 0;
for (var i = 0; i < div_selection.length; i++) {
if (div_selection[i].offsetWidth > maxWidth) {
maxWidth = div_selection[i].offsetWidth;
}
}
var maxHeight = 0;
for (var i = 0; i < div_selection.length; i++) {
if (div_selection[i].offsetHeight > maxHeight) {
maxHeight = div_selection[i].offsetHeight;
}
}
var values = {
maxWidth: maxWidth,
maxHeight: maxHeight
};
return values;
}
// Retruns a random number x; min < x < max
function getRandomNumber(min, max) {
return Math.random() * (max - min) + min;
}
// returns the position in xy-space of every corner of a rectangular div
function getOffset(element) {
var position_x = element.offsetLeft;
var position_y = element.offsetTop;
var height_x = element.offsetWidth;
var height_y = element.offsetHeight;
var tolerance = 0; // will get doubled
return {
A: {
y: position_y - tolerance,
x: position_x - tolerance
},
B: {
y: position_y + height_x + tolerance,
x: position_x - tolerance
},
C: {
y: position_y + height_x + tolerance,
x: position_x + height_y + tolerance
},
D: {
y: position_y - tolerance,
x: position_x + height_y + tolerance
}
};
}
// Returns true if any corner is inside the coordinates of the other div
function getOverlap(div1, div2) {
coor_1 = getOffset(document.getElementById(div1));
coor_2 = getOffset(document.getElementById(div2));
return (
(coor_1.A.x <= coor_2.A.x && coor_2.A.x <= coor_1.D.x) && (coor_1.A.y <= coor_2.A.y && coor_2.A.y <= coor_1.B.y) ||
(coor_1.A.x <= coor_2.B.x && coor_2.B.x <= coor_1.D.x) && (coor_1.A.y <= coor_2.B.y && coor_2.B.y <= coor_1.B.y) ||
(coor_1.A.x <= coor_2.C.x && coor_2.C.x <= coor_1.D.x) && (coor_1.A.y <= coor_2.C.y && coor_2.C.y <= coor_1.B.y) ||
(coor_1.A.x <= coor_2.D.x && coor_2.D.x <= coor_1.D.x) && (coor_1.A.y <= coor_2.D.y && coor_2.D.y <= coor_1.B.y)
);
}
// Number to Letter
function getChar(n) {
var ordA = 'a'.charCodeAt(0);
var ordZ = 'z'.charCodeAt(0);
var len = ordZ - ordA + 1;
var s = "";
while (n >= 0) {
s = String.fromCharCode(n % len + ordA) + s;
n = Math.floor(n / len) - 1;
}
return s;
}
var div_selection = document.getElementsByClassName("random");
maxDimensions = getMaxDimension(div_selection);
var widthBoundary = maxDimensions.maxWidth;
var heightBoundary = maxDimensions.maxHeight;
for (var i = 0; i < div_selection.length; i++) {
var isOverlapping = false;
var attemptCount = 0;
do {
randomLeft = getRandomNumber(0, window.innerWidth - widthBoundary);
randomTop = getRandomNumber(0, window.innerHeight - heightBoundary);
div_selection[i].style.left = randomLeft + "px";
div_selection[i].style.top = randomTop + "px";
isOverlapping = false;
for (var j = 0; j < i; j++) {
if (getOverlap(getChar(i), getChar(j))) {
isOverlapping = true;
break;
}
}
} while (++attemptCount < 50 && isOverlapping);
}
// check every element
for (var i = 0; i < div_selection.length; i++) {
for (var j = i + 1; j < div_selection.length; j++) {
console.log(i, j)
console.log(getChar(i), getChar(j))
console.log(getOverlap(getChar(i), getChar(j)))
}
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>div {
width: 60px;
height: 60px;
position: absolute;
}
#a {
background-color: pink;
}
#b {
background-color: lightblue;
}
#c {
background-color: lightgreen;
}
#d {
background-color: silver;
}
#e {
background-color: yellow;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<body>
<div class="random" id="a">Div1</div>
<div class="random" id="b">Div2</div>
<div class="random" id="c">Div3</div>
<div class="random" id="d">Div4</div>
<div class="random" id="e">Div5</div>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<h2>Style</h2>\n<p>Some styling points</p>\n<ul>\n<li><p>Names. You have some poor naming</p>\n<ul>\n<li>The JavaScript naming convention is <code>camelCase</code> avoid using <code>snake_case</code></li>\n<li>Use the context of the function to imply additional meaning. Eg you have <code>maxWidth</code> and <code>maxHeight</code> in a function called <code>getMaxDimension</code>. As they are the only variables (appart from <code>i</code>) declared and as such can just be <code>width</code> and <code>height</code></li>\n<li><code>getRandomNumber</code> could be <code>randomNumber</code> or <code>randomNum</code> or <code>randNum</code></li>\n<li><code>arr</code> Avoid naming variables after their type. <code>arr</code> could be <code>elements</code>. Also always try to name arrays or array like objects using plurals.</li>\n</ul>\n</li>\n<li><p>Don't repeat code. The two loops in <code>getMaxDimension</code> can be just one loop.</p>\n</li>\n<li><p>Don't add unused code. The variable <code>arr</code> in <code>getMaxDimension(arr)</code> is never used. You access the array of elements from its global name. <code>div_selection</code></p>\n</li>\n<li><p>Avoid single use variable unless they help reduce long cluttered lines.</p>\n</li>\n<li><p>When finding only a max value use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Math max\">Math.max</a> rather than an if statement. Same with minimums <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Math min\">Math.min</a></p>\n</li>\n<li><p>Comments should not state the obvious. If you must add comments make sure they are grammatically correct.</p>\n<p>DO NOT add comments that directly conflict with the code they are commenting on. You have <code>// Retruns a random number x; min < x < max</code> but the function returns <code>min <= x < max</code> Anyone reading this code will be unsure of your intent.</p>\n</li>\n<li><p>Use short form where possible.</p>\n<ul>\n<li>Use <code>for of</code> loops over <code>for</code> loops unless you need the index or if performance is super critical.</li>\n<li>Use property shorthand to define object literals <code>values = {maxWidth: maxWidth, maxHeight: maxHeight};</code> can be <code>values = {maxWidth, maxHeight};</code></li>\n<li>Use arrow functions for simple one line functions.</li>\n<li>You seldom need to reference <code>window</code> as it is the default object. Eg <code>window.innerWidth</code> is the same as <code>innerWidth</code>. You dont add window when accessing other <code>window</code> properties like <code>window.document</code> so why selectivly do it with others?</li>\n<li>Use destructure assignment when pulling properties from object or arrays. EG <code>const {maxWidth, maxHeight} = getMaxDimension(div_selection)</code></li>\n</ul>\n</li>\n</ul>\n<h2>Rewrite</h2>\n<p>This rewrites only parts of your code as your code is far too complex for what it does, the example at the bottom of answer does not use any of your code,</p>\n<p>The function <code>getRandomNumber</code>, <code>getChar</code>, <code>getMaxDimension</code> have been rewritten and renamed.</p>\n<pre><code>const randNum = (min, max) => Math.random() * (max - min) + min;\nfunction getMaxSize(elements) {\n var width = 0, height = 0;\n for (const el of elements) {\n width = Math.max(width, el.offsetWidth);\n height = Math.max(height, el.offsetWidth);\n }\n return {widtyh, height};\n}\nfunction intToBase(n, digits = "abcdefghijklmnopqrstuvwxyz") {\n const base = digits.length, result = [];\n do {\n result.push(digits[(n |= 0) % base]);\n n = n / base;\n } while (n > 0);\n return result.reverse().join("");\n}\n</code></pre>\n<h2>Fitting boxes</h2>\n<p>This is a common problem in computer science and is a hard problem to solve depending on the constraints.</p>\n<p>I will assume that the given elements can fit the area.</p>\n<p>That is the area of the elements to fit is less than the area to fit and that the longest edge of the elements to fit is less than the longest corresponding axis of the area to fit.</p>\n<p>This at least guaranties that one element can be placed. The algorithm will have average of 50 tries per box if it can not find a position.</p>\n<h3>Some Notes</h3>\n<ul>\n<li><p>You can use <code>getBoundingClientRect</code> to get the bounds of a element.</p>\n</li>\n<li><p>The object <code>Bounds</code> defines the bounding boxes and provides function to check for overlap, position, and finally place the element if needed.</p>\n</li>\n<li><p>Elements are first added to the array <code>placing</code>. Each element is then checked for overlap against elements in the array <code>fitted</code>. If no overlaps found the element is moved to <code>fitted</code> and removed from <code>placing</code></p>\n</li>\n<li><p>Once you have the elements there is no need to query the DOM every time you need to know where it is. The elements you store in the array <code>div_selection</code> are references to the elements so any changes you make will be accessible as the stored reference.</p>\n</li>\n<li><p>The example allocates 50 tries per box. If a box does not use all its tries they become available for others to use.</p>\n</li>\n<li><p>Only if the box can be placed its color is changed to red. Boxes that could not be moved remain in the top left and are colored black.</p>\n</li>\n</ul>\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>;(() => {\n\"use strict\";\nconst TRIES_PER_BOX = 50;\nconst randUint = range => Math.random() * range | 0;\nconst placing = [...document.querySelectorAll(\".random\")].map(el => Bounds(el, 5));\nconst fitted = [];\nconst areaToFit = Bounds();\nvar maxTries = TRIES_PER_BOX * placing.length;\nwhile (placing.length && maxTries > 0) {\n let i = 0;\n while (i < placing.length) {\n const box = placing[i];\n box.moveTo(randUint(areaToFit.w - box.w), randUint(areaToFit.h - box.h));\n if (fitted.every(placed => !placed.overlaps(box))) {\n fitted.push(placing.splice(i--, 1)[0].placeElement());\n } else { maxTries-- }\n i++;\n }\n} \nfunction Bounds(el, pad = 0) { \n const box = el?.getBoundingClientRect() ?? {\n left: 0, top: 0, \n right: innerWidth, bottom: innerHeight, \n width: innerWidth, height: innerHeight\n };\n return {\n l: box.left - pad, \n t: box.top - pad, \n r: box.right + pad, \n b: box.bottom + pad,\n w: box.width + pad * 2,\n h: box.height + pad * 2,\n overlaps(bounds) { \n return !(\n this.l > bounds.r || \n this.r < bounds.l || \n this.t > bounds.b || \n this.b < bounds.t\n ); \n },\n moveTo(x, y) {\n this.r = (this.l = x) + this.w;\n this.b = (this.t = y) + this.h;\n return this;\n },\n placeElement() {\n if (el) {\n el.style.top = (this.t + pad) + \"px\";\n el.style.left = (this.l + pad) + \"px\";\n el.classList.add(\"placed\");\n }\n return this;\n }\n };\n}\n})();</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.random {\n position: absolute;\n margin: 2;\n border: 1px solid black;\n font-size: xx-large;\n top: 0px;\n left: 0pc;\n \n}\n.placed {\n color: red;\n border: 1px solid red;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"random\">Div 1</div>\n<div class=\"random\">Div 2</div>\n<div class=\"random\">Div 3</div>\n<div class=\"random\">Div 4</div>\n<div class=\"random\">Div 5</div>\n<div class=\"random\">Div 6</div>\n<div class=\"random\">Div 7</div>\n<div class=\"random\">Div 8</div>\n<div class=\"random\">Div 9</div>\n<div class=\"random\">Div 10</div>\n<div class=\"random\">Div 11</div>\n<div class=\"random\">Div 12</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T12:22:22.083",
"Id": "525522",
"Score": "0",
"body": "Thank you for your very thorough answer! I have learned a lot of new things from your post :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T18:53:31.357",
"Id": "266061",
"ParentId": "266019",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "266061",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T01:23:34.723",
"Id": "266019",
"Score": "2",
"Tags": [
"javascript",
"html",
"css",
"random",
"layout"
],
"Title": "Randomly place Divs on webpage and make sure they don't overlap"
}
|
266019
|
<p>I have two <code>ArrayList</code>s of objects and the after comparison I am taking out the value which has a difference based on the attribute.</p>
<p>So in my condition when the <code>deptCode</code> is the same in both lists but <code>deptName</code> is different then the output will be the updated <code>deptName</code>.</p>
<p>Here is my code.</p>
<pre><code>public class educationMain {
public static void main(String[] args) {
List<person> list=new ArrayList<person>();
person l1 = new person(1,"Samual",100,"Sales","Business");
person l2 = new person(2,"Alex",100,"Sales","Business");
person l3 = new person(3,"Bob",101,"Engineering","Technology");
person l4 = new person(4,"Michel",101,"Engineering","Technology");
person l5 = new person(5,"Ryan",102,"PR","Services");
person l6 = new person(6,"Horward",103,"Leadership","Managmnet");
person l7 = new person(7,"Cyna",104,"HR","Human Resource");
list.add(l1);
list.add(l2);
list.add(l3);
list.add(l4);
list.add(l5);
list.add(l6);
list.add(l7);
List<department> depList = new ArrayList<department>();
department d1 = new department(100, "Sales","Business");
department d2 = new department(101, "Engineering","Technology");
department d3 = new department(102, "PR","Support");
depList.add(d1);
depList.add(d2);
depList.add(d3);
List<person> listC = new ArrayList<person>();
// My comparision Logic
for(person p : list) {
boolean flag = false;
for (department d:depList) {
if(p.deptCode == d.deptCode) {
if(p.deptName != d.deptName) {
p.deptName = d.deptName;
listC.add(p);
}
}
}
}
for(person b:listC){
System.out.println(b.personId+" "+b.name+" "+b.deptCode+" "+b.parentDept+" "+b.deptName);
}
}
}
</code></pre>
<p>This is code is working fine and I am getting my output.</p>
<pre><code>5 Ryan 102 PR Support
</code></pre>
<p>But instead of using two for loop do we have any efficient way to achieve that?</p>
|
[] |
[
{
"body": "<p>Welcome to the site!<br />\nI doubt that there are much better ways to do what you want to do here. You'll always have to compare each element of <code>list</code> to each of <code>depList</code>. Databases have to do similar things like this; you could try resarching in that direction (index, ...), but for small projects this is fine.<br />\n<strong>Ideally, you'd want to setup your data in a way where problems like this can't occur</strong>, this would mean removing the department info from the persons and only keeping the department ID.</p>\n<p>On a sidenote, classes (<code>educationMain</code>, <code>person</code>, <code>department</code>) always start with a capital letter by convention. You're also missing some whitespace, but that's easily fixed with an autoformatter. The <code>flag</code> inside the outer loop also serves no purpose.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T11:32:06.967",
"Id": "266029",
"ParentId": "266021",
"Score": "0"
}
},
{
"body": "<h2>Code review:</h2>\n<ul>\n<li>Capitalize class names</li>\n<li>Be consistent in formatting: <code>List<person> list=new ArrayList<person>()</code> doesn't have spaces around <code>=</code>, but in all other places it has. Also indentations are inconsistent.</li>\n<li>Variable naming: names should say what particular object is. <code>l1</code> doesn't say anything at all. Furthermore, if they are not used anywhere, you can omit variable declaration and add them to the list right away, like: <code>someList.add(new Person(...))</code>. <code>list</code> better be named as <code>personas</code> and <code>listC</code> as <code>personasWithMismatchedDepartmentName</code> to reflect their actual content.</li>\n<li><code>flag</code> inside loop is not used anywhere, should be deleted</li>\n<li>Comments like <code>// My comparision Logic</code> doesn't bring any value to the reader, better if this logic will be in a separate method.</li>\n<li>Try to reduce amount of nested conditions. Instead of</li>\n</ul>\n<pre><code>if(p.deptCode == d.deptCode) {\n if(p.deptName != d.deptName) { ... } \n</code></pre>\n<p>better write</p>\n<pre><code>if(p.deptCode == d.deptCode && p.deptName != d.deptName) {...}\n</code></pre>\n<h2>Algo impovement:</h2>\n<p>Your algo has <code>O(number of personas) * O(number of departments)</code> time complexity. You can reduce that to <code>O(number of personas)</code> if you replace inner loop with hash table lookup.</p>\n<p>We can create hash map from department code to department and instead of iterating over all departments in inner loop, we can lookup required department by its code. Pseudocode:</p>\n<pre><code>for (dept in departments):\n add mapping (deptCode, dept) to hashmap\n\nfor (p in personas):\n dept = hashmap.get(p.deptCode)\n if p.deptName != dept.name:\n p.deptName = dept.name\n add p to list\n\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T11:54:40.217",
"Id": "266031",
"ParentId": "266021",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T05:07:00.883",
"Id": "266021",
"Score": "1",
"Tags": [
"java",
"performance",
"array"
],
"Title": "How to take out attribute from two ArrayList of object which have different match in optimize way"
}
|
266021
|
<p>I'm very new with Go (started to learn it two weeks ago) and I would like to get your comments on the code below. The code is implementation of identifier used by DHT (Kademlia)
The code works as expected in tests.</p>
<pre><code>package identifier
import (
"fmt"
"math/bits"
)
type idBuilderType struct {
length int
}
type identifierType struct {
unsafe bool
bytes []byte
}
const (
illegalLength = "illegal length: %d"
nilInput = "invalid input: nil"
invalidLength = "invalid input length, expected: %d, got: %d"
differenLength = "ids have different lengths: %d and %d"
ERROR = -200
EQUAL = 0
GREATER = 1
LESSER = -1
)
// creates a builder for building of identifiers with given length
// returns nil and error if given length is lesser or equal to 0
func GetBuilder(len int) (*idBuilderType, error) {
if len <= 0 {
return nil, fmt.Errorf(illegalLength, len)
}
builder := new(idBuilderType)
builder.length = len
return builder, nil
}
//builds identifier. if unsafe is set to true then "unsafe identifier"
//is created. returns nil and error if given array has length different
//from length defined by builder
func (builder *idBuilderType) BuildFromBytes(bytes []byte, unsafe bool) (*identifierType, error) {
if bytes == nil {
return nil, fmt.Errorf(nilInput)
}
length := len(bytes)
if length != builder.length {
return nil, fmt.Errorf(invalidLength, builder.length, length)
}
id := new(identifierType)
id.unsafe = unsafe
if unsafe {
id.bytes = bytes
} else {
id.bytes = make([]byte, length)
copy(id.bytes, bytes)
}
return id, nil
}
//returns byte array representation of the identifier
//if identifier is unsafe then internal buffer of
//identifier returned, otherwise method returns copy
//of the buffer
func (this *identifierType) GetBytes() []byte {
if this.unsafe {
return this.bytes
} else {
bytes := make([]byte, this.GetLength())
copy(bytes, this.bytes)
return bytes
}
}
func (this *identifierType) IsUnsafe() bool {
return this.unsafe
}
//returns length of the identifier
func (this *identifierType) GetLength() int {
return len(this.bytes)
}
//compares two identifiers.
//returns ERROR (-200) and error if identifiers have different length
//returns GREATER (1) if this identifier is greater then another
//returns EQUAL (0) if identifiers are equal
//returns LESSER (-1) if this identifier is lesser then another
func (this *identifierType) Compare(another *identifierType) (int, error) {
err := this.checkLength(another)
if err != nil {
return ERROR, err
}
for i, b := range this.bytes {
if b > another.bytes[i] {
return GREATER, nil
}
if b < another.bytes[i] {
return LESSER, nil
}
}
return EQUAL, nil
}
//returns length of shared prefix of two identifiers
//returns ERROR (-200) and error if identifiers have different length
func (this *identifierType) GetSharedPrefixLen(another *identifierType) (int, error) {
err := this.checkLength(another)
if err != nil {
return ERROR, err
}
count := 0
for i, b := range this.bytes {
if b == another.bytes[i] {
count += 8
} else {
xor := byte(b ^ another.bytes[i])
count = count + bits.LeadingZeros8(xor)
return count, nil
}
}
return count, nil
}
//calculates and returns arithmetical mean of two identifiers
//returns ERROR (-200) and error if identifiers have different length
func (this *identifierType) Mid(another *identifierType) (*identifierType, error) {
err := this.checkLength(another)
if err != nil {
return nil, err
}
bytes := sum(this.bytes, another.bytes, this.GetLength())
return divideByTwo(bytes, this.GetLength()+1), nil
}
func sum(bytes []byte, bytes1 []byte, length int) []byte {
index := length
buffer := make([]byte, index+1)
sum := uint16(0)
for i := index - 1; i >= 0; i-- {
sum = uint16(bytes[i]&0xff) + uint16(bytes1[i]&0xff) + sum>>8
buffer[i+1] = byte(sum)
}
if (sum >> 8) != 0 {
buffer[0] = byte(sum >> 8)
}
return buffer
}
func divideByTwo(bytes []byte, len int) *identifierType {
length := len - 1
ba := make([]byte, length)
carry := (bytes[0] & 1) != 0
for i := 0; i < length; i++ {
ba[i] = byte((bytes[i+1] & 0xff) >> 1)
if carry {
ba[i] = byte(ba[i] | 0b10000000)
}
carry = (bytes[i+1] & 1) != 0
}
result := new(identifierType)
result.bytes = ba
return result
}
func (this *identifierType) checkLength(id *identifierType) error {
len1 := this.GetLength()
len2 := id.GetLength()
if len1 != len2 {
return fmt.Errorf(differenLength, len1, len2)
}
return nil
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T21:25:41.020",
"Id": "526414",
"Score": "0",
"body": "do you mind to get ride of the unsafe thing ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T09:22:12.970",
"Id": "526440",
"Score": "2",
"body": "It's spelled \"Kademlia\""
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T12:00:38.847",
"Id": "266032",
"Score": "1",
"Tags": [
"go"
],
"Title": "Kademlia identifier package written in go"
}
|
266032
|
<p>In a larger project, I need a (rather simple) expression parser able to accept numerical values, operators and string identifiers. Fine, a lexical parser fed with some input which gives <em>tokens</em> one at the time to the syntactic parser. As a token can contain one single value type at a time, I decide to use an union. Problems came soon when I realized that an identifier was an arbitrary string of unknown length, and that <code>std::string</code> inside unions was not the simplest thing...</p>
<p>The general design is to initialize a lexical parser with some input, and the expression parser repeatedly calls its <em>next</em> member to get one token at a time. My 2 first attemps in designing a Token class ended in awfully complex code for the first, and code invoking UB for the second.</p>
<p>Before going further I would like to be sure whether my current <code>Token</code> class can be used to build the full machinery above it. In my tests I can successfully create tokens of all the types, copy them or store them in stacks or vectors and access their types and values, but I also know that <em>it works</em> neither means <em>it is correct according to the standard and portable</em>, nor <em>it does not contain anti-patterns</em>... For the C++ versions, I expect to follow the C++14 and above standards.</p>
<pre><code>/**
* Token represents a token extracted by a lexical parser.
*
* It has a type among integer, double, operator (single char) or string and
* contains an appropriate value, except for the special type Eof which has
* no value and represents the end of the input data
*
* It is a copyable and default constructible type (default constructor gives
* an Eof token) or can be constructed from a value of an acceptable type to
* produce a token of that type.
*/
class Token {
public:
enum class Type { Int, Double, Operator, Identifier, Eof } type;
protected:
// only 1! member at at time => union
union Foo {
// group trivial member to be able to process them as a whole
// because Bar is a trival union
union Bar {
int val;
double fval;
char op;
} y;
// one non trivial member: shall define all special methods
Foo() { y.val = 0; }
Foo(int i) { y.val = i; }
Foo(double d) { y.fval = d; }
Foo(char c) { y.op = c; }
Foo(const std::string& str) : str(str) {};
~Foo() {}
std::string str;
} x;
public:
// Simple ctors from nothing (Eof) or an acceptable type
Token() : type(Type::Eof) {}
Token(int i) : type(Type::Int), x(i) {};
Token(double d) : type(Type::Double), x(d) {};
Token(char c) : type(Type::Operator), x(c) {};
Token(const std::string& str) : type(Type::Identifier), x(str) {};
//Copy ctor handles specifically the string member
Token(const Token& other): type(other.type) {
if (type == Type::Identifier) {
// in place construction for the string
new (&x.str) std::string(other.x.str);
}
else {
x.y = other.x.y; // magic of the trivial member y
}
}
// Explicit dtor destroys a possible string member
~Token() {
if (type == Type::Identifier) {
x.str.~basic_string();
}
}
// assignment operator again handles the string member
Token& operator = (const Token& other) {
if (type == Type::Identifier) {
if (other.type == Type::Identifier) {
x.str = other.x.str;
}
else {
// different types: we can safely destroy the destination
x.str.~basic_string();
x.y = other.x.y;
}
}
else {
if (other.type == Type::Identifier) {
// we shall construct a new string member
new (&x.str) std::string(other.x.str);
}
else {
x.y = other.x.y;
}
}
type = other.type;
return *this;
}
// const accessors...
int getVal() const { return x.y.val; }
double getFval() const { return x.y.fval; }
char getOp() const { return x.y.op; }
std::string getStr() const { return x.str; }
Type getType() const { return type; }
};
// and a stream injector to ease debugging traces
std::ostream& operator << (std::ostream& out, const Token& tok) {
switch (tok.getType()) {
case Token::Type::Int:
out << tok.getVal();
break;
case Token::Type::Double:
out << tok.getFval();
break;
case Token::Type::Operator:
out << tok.getOp();
break;
case Token::Type::Identifier:
out << tok.getStr();
break;
case Token::Type::Eof:
out << "__EOF__";
}
return out;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T15:57:42.830",
"Id": "525467",
"Score": "1",
"body": "You’ve basically just reimplemented [`std::variant`](https://en.cppreference.com/w/cpp/utility/variant)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T16:35:29.670",
"Id": "525468",
"Score": "0",
"body": "@indi: My problem is that `variant` requires c++17 or boost. And c++14 is one of my requirements..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T17:58:55.843",
"Id": "525473",
"Score": "3",
"body": "`std::variant` requires C++17, `boost::variant` or `boost::variant2::variant` require Boost… but a C++17-compatible variant type requires only C++11. There are dozens of implementations out there you could use or copy. If you can’t use `std::variant`, you should at least use a compatible type, so that when you *can* use `std::variant`, the transition is painless."
}
] |
[
{
"body": "<p>In order to do what you want, you can either have (non-union'ed) members of different types and only one is populated, which is your approach;<br />\nor, you can use a byte array buffer large enough to hold any of the different types, and in-place construct and destruct the actual object there. That's how Boost's <code>variant</code> was implemented before you could put such types in a primitive <code>union</code>.</p>\n<p>I suggest finding an off-the-shelf, mature version of <code>variant</code> to include in your project, even if you are not using Boost's or including all of Boost's libraries. Doing this well is difficult and something that's already been done by others.</p>\n<p>Also, have you considered using a <code>string_view</code> instead of a <code>string</code>? You don't need to <em>copy</em> the token, if you can refer to it in the original input. That would avoid the issues you are running into.</p>\n<p>(Again, if you don't have <code>std::string_view</code>, obtain a stand-alone implementation to include in your project. Remember, all these fancy new library types were proofed out and well-worn before being included in the ISO standard!)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T23:54:28.363",
"Id": "266045",
"ParentId": "266035",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T14:54:32.173",
"Id": "266035",
"Score": "1",
"Tags": [
"c++",
"lexical-analysis"
],
"Title": "A Token class for a lexical parser"
}
|
266035
|
<p>I have recently gotten back into writing python and i decided to take up a project of writing a backtracking algorithm in python to solve Sudoku puzzles</p>
<p><strong>How it Works</strong></p>
<p>A matrix is declared to represent the Sudoku grid the blank spaces on the Sudoku grid are represented by zero A function is declared that checks for all the zeros in the grid, another function is the declared to check the answers are valid by checking against a variable declared as <code>Row_Values</code> it also checks against a variable declared as <code>column_values</code> then another function is declared which calls the first function to locate where it can make guesses it returns none if all the spaces are filled, it inputs a number between 1 and 9 in a valid place and then checks it doesn't conflict it then uses recursion to call the function it repeatedly checks if anything is invalid if it becomes invalid it uses backtracking to try new number(s) it returns false if the puzzle is invalid</p>
<p><strong>Code</strong></p>
<pre><code>import numpy as np
import time
start_time = time.time()
grid = [[4,3,0,0,0,0,0,0,0],
[0,2,0,4,0,0,0,0,0],
[9,0,0,0,8,1,0,2,6],
[0,0,4,9,0,3,0,5,2],
[0,9,0,5,6,8,0,3,4],
[8,0,3,2,4,0,6,0,0],
[3,0,9,8,5,0,0,0,0],
[2,0,6,7,3,9,1,8,5],
[5,0,0,0,2,0,0,4,0]]
print (np.matrix(grid))
def find_empty_box(sudoku):
for x in range(9):
for y in range(9):
if sudoku[x][y] == 0:
return x, y
return None, None
def Answer_Valid(sudoku, guess, row, col):
row_values = sudoku[row]
if guess in row_values:
return False
column_values = [sudoku[i][col]for i in range(9)]
if guess in column_values:
return False
row_start = (row // 3) * 3
col_start = (col // 3) * 3
for x in range(row_start, row_start + 3):
for y in range(col_start, col_start + 3):
if sudoku[x][y] == guess:
return False
return True
def Solver(sudoku):
row, col = find_empty_box(sudoku)
if row is None:
return True
for guess in range(1,10):
if Answer_Valid(sudoku, guess, row, col):
sudoku[row][col] = guess
if Solver(sudoku):
return True
sudoku[row][col] = 0
return False
print(Solver(grid))
print(np.matrix(grid))
print("%s seconds " % (time.time() - start_time))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T18:29:28.540",
"Id": "525475",
"Score": "1",
"body": "Does this work as expected? I suspect that your `Answer_Valid` has a `return True` at the wrong level of indentation, which would in turn manifest as a bug where only the first column is checked."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T22:39:59.457",
"Id": "525480",
"Score": "0",
"body": "Yep it works as expected the indentation error must be something with the post because it works fine when i run it on my computer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T02:31:05.993",
"Id": "525483",
"Score": "0",
"body": "`works fine when I run it on my computer` is an argument only in debugging, and, where other environments/users have problems, an indication there may be a problem with undefined interpretation, if not *undefined behaviour*. If there is *something with the post*, the poster or some other /post( editor should fix it. Taking a look…"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T02:51:31.433",
"Id": "525484",
"Score": "0",
"body": "(No. Indented using tabs consistently, with interspersed *empty* lines in functions. Which *should* be ignored by contemporary environments, but are not in, for one, in my 3.5.2 interpreter. Resulting in `IndentationError: unexpected indent` over and again.)"
}
] |
[
{
"body": "<p>Here are a few comments in no particular order:</p>\n<ul>\n<li><p>To find the time taken to solve the sudoku, you are now taking into account the time taken to declare the functions used and the time taken to print to std. Probably that is not intended.</p>\n</li>\n<li><p>As per PEP-8, function names youd be spelled as <code>answer_valid</code> and <code>solver</code>.</p>\n</li>\n<li><p>There is no validation on your input data. For an example, it should be fine, but if you are going to assume your sudoku is always 9x9, you should at least check that and raise a <code>ValueError</code>.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T09:41:07.713",
"Id": "266050",
"ParentId": "266036",
"Score": "0"
}
},
{
"body": "<h2>The bug in <code>Answer_Valid</code></h2>\n<blockquote>\n<pre><code>for x in range(row_start, row_start + 3):\n for y in range(col_start, col_start + 3):\n if sudoku[x][y] == guess:\n return False\n\n return True\n</code></pre>\n</blockquote>\n<blockquote>\n<p>it works fine when i run it on my computer</p>\n</blockquote>\n<p>Does it actually? There's no question that it will run. The consequences of this bug aren't of the form "not running", but giving bad results. The main consequence is that <code>True</code> will be returned too early, without checking the entire 3x3 block. That may result in invalid solutions. The program would still run, but do the wrong thing. And of course the program may also give a correct solution, by getting lucky, so getting some correct solutions does not mean that there is no problem.</p>\n<h2>Unconventional use of <code>x</code> and <code>y</code></h2>\n<p>Using <code>x</code> to index rows and <code>y</code> to index columns is transposed from how the usual order. It means that <code>x</code> increases <em>down</em>, and <code>y</code> increases <em>across</em>. That's strange and confusing, I initially thought there were many bugs due to that, but it seems like there aren't. That's still an issue worth addressing: code that <em>looks wrong</em> even if it isn't wrong is still not a good thing.</p>\n<p>The conventional meanings of <code>x</code> and <code>y</code> would cause the indexing expressions to look like <code>sudoku[y][x]</code> which looks odd, using a 2D numpy array would allow proper 2D indexing. By the way, <code>matrix</code> should be avoided according to <a href=\"https://numpy.org/doc/stable/reference/generated/numpy.matrix.html\" rel=\"nofollow noreferrer\">its documentation</a>, prefer to use a 2D array.</p>\n<h2>Algorithmic techniques could be improved</h2>\n<p>The grid you used as an example is solved in a reasonable time, but there are grids that cause trouble. For example:</p>\n<pre><code>grid = [[0,0,0,0,0,0,0,0,0],\n [0,0,0,0,0,3,0,8,5],\n [0,0,1,0,2,0,0,0,0],\n [0,0,0,5,0,7,0,0,0],\n [0,0,4,0,0,0,1,0,0],\n [0,9,0,0,0,0,0,0,0],\n [5,0,0,0,0,0,0,7,3],\n [0,0,2,0,1,0,0,0,0],\n [0,0,0,0,4,0,0,0,9]]\n</code></pre>\n<p>After solving the bug, I believe that such hard instances would be solved <em>eventually</em>, but it took too long for me to let it finish. There are some commonly used algorithmic techniques that would enable solving more sudokus in a reasonable amount of time:</p>\n<ol>\n<li>Process trivial cells without waiting for them to be "picked" to be guessed. If a cell only has one possible value left (aka a Naked Single), just fill it in (but be careful to empty them again when backtracking).</li>\n<li>Look at the puzzle from the point of view of "where in this row could I put the 5". If there is only one place where it can go (aka a Hidden Single), it will have to go there, so you can fill a cell. Techniques 1 and 2 can be iterated together until they stop finding cells to fill. I tried adding this to your solver, and that made it powerful enough to solve the example grid that I showed.</li>\n<li>(more advanced) Pick an empty cell to guess based on how many possibilities it has left, rather than the simply the first one. Cells with a small domain should be done first. That causes conflicts to occur earlier, which in backtracking is exponentially better. This sort of subsumes the first technique (cells with only one possibility left would be picked one by one and filled with the only possible "guess"), but it still makes sense to break that out into its own thing.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T17:32:05.110",
"Id": "525502",
"Score": "0",
"body": "Thank you for your analysis of the code do you know how i could go about doing the things you suggest for improving the algorithm iv'e had a think of how to do it but i'm stuck on how to implement it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T17:39:44.370",
"Id": "525503",
"Score": "0",
"body": "@HiddenSquid123 For technique 1, a basic implementation could be taking the set of 1 through 9, then removing anything that already occurs in the same row/column/house as the cell that's being analyzed. Technique 2 is really similar but from a different perspective."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T12:59:01.067",
"Id": "266054",
"ParentId": "266036",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "266054",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T14:58:13.907",
"Id": "266036",
"Score": "6",
"Tags": [
"python",
"algorithm",
"recursion",
"sudoku",
"backtracking"
],
"Title": "Python backtracking algorithm to solve sudoku"
}
|
266036
|
<p>I have a list of dictionaries <code>x</code> and a list of random numbers <code>x_randoms</code>. I want to update each of the dictionaries with the values from the list of random numbers. I've done the following and it works, but it feels a bit strange:</p>
<pre><code>import random
x = [{'key1': '123', 'key2': {'key2.1': 500, 'key2.2': True}},
{'key1': '123', 'key2': {'key2.1': 500, 'key2.2': True}},
{'key1': '123', 'key2': {'key2.1': 500, 'key2.2': True}}]
x_randoms = [random.random() for i in range(len(x))]
print("\nBefore loop...", x)
[j.update({'key3': x_randoms[i]}) for i, j in enumerate(x)]
print("\nAfter loop...", x)
</code></pre>
<p>The list comp at the bottom is mostly what is bothering me. Is that ok, or can it be improved?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T18:27:22.783",
"Id": "525474",
"Score": "2",
"body": "This is too hypothetical to be on-topic, unfortunately."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T18:00:05.593",
"Id": "525505",
"Score": "0",
"body": "If you're not using the result of a list comprehension, it's a huge clue that there's a far clearer way to write your program. In this case, you should be using an imperative-style `for` loop instead."
}
] |
[
{
"body": "<p>Instead of iterating over <code>range(len(x))</code> and ignoring the value, you can simply iterate over <code>x</code> and ignore the value:</p>\n<pre><code>x_randoms = [random.random() for _ in x]\n</code></pre>\n<p>Instead of enumerating <code>x</code> only to access <code>x_randoms</code>, you can use <code>zip</code> to iterate over both in parallel:</p>\n<pre><code>for xdic, xr in zip(x, x_randoms):\n xdic['key3'] = xr\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T17:21:09.483",
"Id": "266040",
"ParentId": "266039",
"Score": "3"
}
},
{
"body": "<p>Your suspicions are correct, this is called using comprehension syntax for side-effects, and is normally bad practice.</p>\n<p>A better way to do this is with a <code>for</code> loop</p>\n<pre class=\"lang-py prettyprint-override\"><code>for item in x:\n # this also gets rid of your random number list\n item['key3'] = random.random()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T17:21:21.390",
"Id": "266041",
"ParentId": "266039",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "266041",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T16:58:51.493",
"Id": "266039",
"Score": "1",
"Tags": [
"python"
],
"Title": "Updating python dictionary in a loop"
}
|
266039
|
<p>I am trying write a method that will calculate kendalls tau in O(n log n) time. I have a managed to it in O(n^2) quite easily however I cannot find any GOOD explanation online that will describe with ease how to code it in faster time complexity?</p>
<p>Here are some links as to mentioning how a modified merge sort or a bubble sort can help with calculate the ranks for every x,y point for kendalls tau but all they mention is that you can get the number of swaps made as a return and go from there? then what? <a href="https://en.wikipedia.org/wiki/Kendall_rank_correlation_coefficient" rel="nofollow noreferrer">wikipedia</a> <a href="https://stackoverflow.com/questions/42514262/fast-algorithm-for-computing-kendall-tau-distance-between-two-integer-sequences">stackoverflow</a></p>
<p>Here is my code in O(n^2). Pretty please someone explain to me how to do this using the modifed merge/bubble sort in O(n log n)?</p>
<pre><code>using System.Linq;
using System;
class Kendall
{
public static double Compute(double[] Xs, double[] Ys)
{
XYPoint[] ByX = new double[Xs.Length];
ByX = sortByX(Xs, Ys);
double concordant = 0;
double discordant = 0;
for (int i = 0; i< ByX.Count; i++)
{
for(int j = i+1; j < ByX.Count; j++)
{
if(ByX[j].Y < ByX[i].Y)
{
discordant += 1;
}
if(ByX[j].Y > ByX[i].Y)
{
concordant += 1;
}
}
}
double kendall = (concordant - discordant) / (concordant + discordant);
return kendall;
}
public static XYPoint[] sortByX(double[] Xs, double[] Ys)
{
XYPoint[] XYPoints = new XYPoint[Xs.Length]();
for(int i = 0; i<Xs.Length; i++)
{
Xs[i] = new XYPoint(){X = Xs[i], Y = Ys[i]};
}
XYPoint[] ByX = new XYPoint[Xs.Length];
ByX = XYPoints.OrderBy(z => z.X).ToArray();
return ByX;
}
}
public class XYPoint
{
public double X;
public double Y;
}
</code></pre>
<p>EDIT: Heres a github code i found that implements this modified sort algorithm that returns inversions. How would one go from here? <a href="https://github.com/antoniomtz/kendalltau/blob/master/kendallTauDistance.cs" rel="nofollow noreferrer">github</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T21:00:00.310",
"Id": "266043",
"Score": "0",
"Tags": [
"c#",
"algorithm",
"statistics"
],
"Title": "How to do kendalls tau in O(n log n)? O(n^2) is shown"
}
|
266043
|
<p>I am using Next.js and want to properly implement session management into this serverless architecture. I checked out nextauth but I am not really a fan and it doesn't implement some things I think I might need, so just trying to keep things simple and do it myself. I also read through express-session where most of this code comes from.</p>
<p>Here is the bulk of the session management utilities:</p>
<pre><code>import stringifyJSON from './stringify-json'
import moment from 'moment'
import knex from 'initializers/knex'
const crypto = require('crypto')
const cookie = require('cookie')
const signature = require('cookie-signature')
const random = (size) => {
return new Promise((res, rej) => {
crypto.randomBytes(size, function(err, rnd) {
if (err) return rej(err)
res(rnd)
})
})
}
export const generateSessionId = async () => {
const sessionIdBuffer = await random(32)
const sessionId = sessionIdBuffer.toString('hex')
return sessionId
}
export function getcookie(cookieHeader, name, secret) {
var raw;
var val;
var cookies = cookie.parse(cookieHeader);
raw = cookies[name];
if (raw) {
if (raw.substr(0, 2) === 's:') {
val = signature.unsign(raw.slice(2), secret)
if (val === false) {
val = undefined;
}
} else {
}
}
return val
}
export function setcookie(res, name, val, secret, options) {
var signed = 's:' + signature.sign(val, secret);
var data = cookie.serialize(name, signed, options);
var prev = res.getHeader('Set-Cookie') || []
var header = Array.isArray(prev) ? prev.concat(data) : [prev, data];
res.setHeader('Set-Cookie', header)
}
export async function resolvePublicSession(req, res) {
const privateSession = await resolvePrivateSession(req, res)
const user = await knex.from('user').select('*').where('id', privateSession.user_id).first()
if (!user.is_guest) {
const avatar = await knex.from('image')
.where('id', user.avatar_id)
.select('*')
.first()
if (avatar) {
avatar.sources = await knex.from('image_source')
.where('image_id', avatar.id)
.returning('*')
.all()
user.avatar = avatar
}
}
const session = {
user,
ip: req.headers['x-real-ip'] || req.connection.remoteAddress,
// csrfToken
}
return JSON.parse(stringifyJSON(session))
}
export async function resolvePrivateSession(req, res) {
let session
if (req.headers.cookie) {
// TODO: move these secrets/names into config somewhere
const token = getcookie(req.headers.cookie, 'head', 'a secret')
if (token) {
session = await knex('session')
.select('*')
.where('token', token)
.first()
if (session) {
if (session.expires_at <= new Date) {
session.token = await generateSessionId()
session.expires_at = moment().add('days', 30).toDate()
await knex('session').where('token', token)
.update({
token: session.token,
expires_at: session.expires_at
})
}
}
}
}
if (!session) {
const [guestUser] = await knex('user').insert({ is_guest: true })
const newToken = await generateSessionId()
const expires_at = moment().add('days', 30).toDate()
const sessions = await knex('session')
.returning('*')
.insert({
user_id: guestUser.id,
token: newToken,
expires_at
})
session = sessions[0]
}
setcookie(res, 'head', session.token, 'a secret', {
// maxAge:
// domain:
path: '/',
expires: session.expires_at,
httpOnly: process.env.NODE_ENV === 'production',
secure: process.env.NODE_ENV === 'production',
sameSite: process.env.NODE_ENV === 'production',
})
return session
}
</code></pre>
<p>And here is how it might be used in a server API call:</p>
<pre><code>export default async function(req, res) {
const { code } = req.query
try {
const session = await sessionController.resolve(req, res)
const creds = await linkedinController.getAccessToken(code)
await linkedinController.upsertAccount(session, creds)
const user = await userController.getFromSession(session)
if (user.is_guest) {
await userController.promote(user)
}
res.redirect(`/name`)
} catch (e) {
}
}
</code></pre>
<p>And here is how it might be used on the frontend:</p>
<pre><code>export default function MyPage({ session }) {
// handle session object, and render view
}
export async function getServerSideProps({ req, res }) {
const sessionController = require('../utils/session')
const session = await sessionController.resolvePublicSession(req, res)
return {
props: { session },
}
}
</code></pre>
<p>What is wrong with and/or missing from making this a <em>robust</em> session management system? I think I still need to add csrf tokens somewhere in the mix (not sure where yet, maybe you can advise on that). But other than that I think this is all you really need. What else do I need and/or what am I doing wrong?</p>
<p>The bulk of the cookie reading/writing code comes straight out of <a href="https://github.com/expressjs/session" rel="nofollow noreferrer">express-session</a> (slightly modified to allow for only one secret, not sure why they used an array of secrets).</p>
<p>Basically how it works is, inside of a Next.js API request handler, you call <code>sessionController.resolvePrivateSession</code>, which just results in a session object straight from the sessions table in the database, which has <code>token</code> (the unique random bytes in hex), and the expires_at time, which currently I am not sure how to use this, how do I use/implement the expires_at feature?</p>
<p>The process of "returning a session object from the db" really is quite involved. First it tries parsing the cookie, which might look like this:</p>
<pre><code>s:fd51d213b6935caf5d987dac8dbadf3674dba89dac5d976ab56b5ba88cdf731b.O9jinFhrd7F/R+oazU3+5pxzAaBwbybt+meJTjcQKLg
</code></pre>
<p>Noticing the <code>s:</code>, it knows to try and verify the token. That uses a standard node.js library to unsign the cookie, which gives back <code>false</code> or the original token. I'm not entirely sure how this works internally, but I assume it's correct. Have more reading to do there.</p>
<p>Then it tries to find the session from the DB using that <code>token</code> it got from the cookie. If it finds it, it checks if the session is expired, in which case I'm not sure if I should just generate a new token or what. Oh I also have a "guest" sort of system in here, so there is <em>always</em> a user (so things can be tracked more systematically). This I think could be spammed and create a bunch of users, so periodically the sessions with guest users should just be cleared from the db, but that's a tangent. But given it finds the session, we can now find the <code>user_id</code> stored on the session db object, and go from there and do what we need. That is the whole purpose of this function.</p>
<p>But then just before returning the session + user_id, it writes the signed cookie to the header in the response. I don't think anything else needs to be passed in as a string to the encoder, but express-session passed in a hash of the entire JSON.stringify(sessionObject), which seems like a lot and unnecessary so I cut it out. But then we have the cookie written which has the signed token obscurified, so we can retrieve it in the next request. <strong>Is that all that needs to happen for session management?</strong> What am I missing?</p>
<p>Key questions:</p>
<ul>
<li>What do you do with the expires_at field on the session db object?</li>
<li>Does anything else need to be added to make this more secure?</li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T01:30:22.657",
"Id": "266046",
"Score": "1",
"Tags": [
"javascript",
"node.js",
"session",
"https"
],
"Title": "How to implement robust and secure session management (in general, and in Next.js)"
}
|
266046
|
<p>I wrote a binary search to find the closest element to x in an array. How can show the correctness of the algorithm for any cases? Because it handles with floating points and variable length arrays, there are many cases.</p>
<pre class="lang-java prettyprint-override"><code>import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.Random;
public class BinarySearchWithAFuzzinessTest {
/**
* Returns the first occurrence, that fulfills the constraints.
*/
public static int binaryContains(double[] list, double x, double delta) {
if (list == null || list.length == 0) {
throw new NoSuchElementException("provide at least one element");
}
int i = 0;
int j = list.length / 2;
int k = list.length - 1;
int r = -1;
if (x + delta < list[i]) {
return r;
}
if (Math.abs(x - list[i]) <= delta) {
r = i;
delta = Math.nextAfter(Math.abs(x - list[i]), -1);
}
if (Math.abs(x - list[j]) <= delta) {
r = j;
delta = Math.nextAfter(Math.abs(x - list[j]), -1);
}
if (Math.abs(x - list[k]) <= delta) {
r = k;
delta = Math.nextAfter(Math.abs(x - list[k]), -1);
}
while (true) {
System.out.println(i + " " + j + " " + k);
if (x < list[j]) {
k = j;
j = (i + j) / 2;
if (j == k) {
return r;
}
if (Math.abs(x - list[j]) <= delta) {
r = j;
delta = Math.nextAfter(Math.abs(x - list[j]), -1);
} else if (Math.abs(x - list[k]) <= delta) {
r = k;
delta = Math.nextAfter(Math.abs(x - list[k]), -1);
}
} else if (x < list[k]) {
i = j;
j = (j + k) / 2;
if (i == j) {
return r;
}
if (Math.abs(x - list[i]) <= delta) {
r = i;
delta = Math.nextAfter(Math.abs(x - list[i]), -1);
} else if (Math.abs(x - list[j]) <= delta) {
r = j;
delta = Math.nextAfter(Math.abs(x - list[j]), -1);
}
} else {
return r;
}
}
}
/**
* Returns the first occurrence, that fulfills the constraints. This is for testing.
*/
public static int linearContains(double[] list, double x, double delta) {
for (int i = 0; i < list.length; i++) {
if (Math.abs(x - list[i]) <= delta) {
delta = Math.abs(x - list[i]);
while (i + 1 < list.length && Math.abs(x - list[i + 1]) < delta) {
i++;
delta = Math.abs(x - list[i]);
}
return i;
}
}
return -1;
}
public static void main(String[] args) {
Random r = new Random(1234);
for (int i = 0; i < 100000; i++) {
double[] a = new double[1 + r.nextInt(20)];
double x = r.nextInt(20) - 10;
double delta = r.nextDouble();
for (int j = 0; j < a.length; j++) {
if (r.nextBoolean()) {
a[j] = x + r.nextDouble() * 5 * delta;
} else {
a[j] = x - r.nextDouble() * 5 * delta;
}
}
Arrays.sort(a);
int c1 = binaryContains(a, x, delta);
int c2 = linearContains(a, x, delta);
if (c1 != c2) {
System.out.println("OOPS " + x + " " + delta);
System.out.println(Arrays.toString(a) + " " + c1 + " " + c2);
break;
}
}
double[] a = {4, 4, 4};
System.out.println(binaryContains(a, 4, 0));
System.out.println(linearContains(a, 4, 0));
}
}
</code></pre>
|
[] |
[
{
"body": "<h3>Variable names</h3>\n<p>It's hard to read the code with one-letter variables. Sometimes it could be justified (like <code>i</code> and <code>j</code> as loop variables or names that were mentioned in a task); but usually you should name them <code>array</code> instead of <code>a</code>, <code>binary</code> instead of <code>c1</code>, <code>result</code> instead of <code>r</code> etc.</p>\n<h3>"Magic" numbers</h3>\n<p>Use named constants instead of hardcoded values.</p>\n<pre><code>static final int SEED = 1234;\nstatic final int TEST_COUNT = 100000;\n</code></pre>\n<p>etc.</p>\n<h3>Different behavior</h3>\n<p><code>binaryContains</code> throws <code>NoSuchElementException</code> when <code>linearContains</code> returns -1. If you're testing different algorithms - make sure you're testing the same behavior.</p>\n<h3>Changing arguments is bad</h3>\n<p>What if you'll need an initial value of delta after you've changed it? Yes, sometimes it's OK and even needed, but not here. Leave delta as it was and add a new variable - maybe "<code>closest</code>" or something like to store current closest value.</p>\n<h3><code>Math.nextAfter</code> is a delicate tool for floating point manipulation</h3>\n<p>You don't need it in common math, just compare using <code><</code>, not <code><=</code>.</p>\n<h3>Unnecessary loop in <code>linearContains</code></h3>\n<p>The inner loop goes over the array one by one, as well as the outer loop. You can refactor it into a single loop.</p>\n<h3>Better algorithm</h3>\n<p>First, do a binary search until <span class=\"math-container\">\\$a[i]≤x≤a[i+1]\\$</span>. Next, check if distance from the closest is less than <code>delta</code>, checking it during the search is useless.</p>\n<h3>Your question</h3>\n<p><a href=\"https://en.wikipedia.org/wiki/Formal_verification\" rel=\"nofollow noreferrer\">Formal verification</a> is hard, but usually <a href=\"https://en.wikipedia.org/wiki/Unit_testing\" rel=\"nofollow noreferrer\">unit tests</a> covering all possible paths of execution and known former bugs are good enough for practical use.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T06:41:32.387",
"Id": "266048",
"ParentId": "266047",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T05:38:46.640",
"Id": "266047",
"Score": "0",
"Tags": [
"java",
"algorithm",
"binary-search"
],
"Title": "Binary search to find the closest element"
}
|
266047
|
<p>This code was originally posted <a href="https://codereview.stackexchange.com/questions/265940/oop-hangman-game?noredirect=1#comment525419_265940">here</a>. An exercise into learning OOP and Python. A huge thanks for the time and effort that @ferada @Alex Waygood @m-alorda and others put into commenting on it.</p>
<p>You can run it as a repl here:
<a href="https://replit.com/@scripta/Hangman#main.py" rel="nofollow noreferrer">https://replit.com/@scripta/Hangman#main.py</a></p>
<p>Most of the issues raised have been acted on. A couple of things are still to be addressed.</p>
<p><strong>Quality of partitioning into objects:</strong></p>
<p>Should there be a “Game” object or should the driving logic be left as standalone procedures? There seems a need to group the driving logic (and supporting functions), either as a separate module or an object. Does it really matter which?</p>
<p>What about the Gallows class? In a way the gallows is a record of bad guesses. However it has the merit of being familiar in terms of the game. Should guesses be a property of a Game object?</p>
<p>How to judge what makes a good object? Simplicity? Familiarity in terms of subject? ...? Any thoughts?</p>
<p><strong>Method naming:</strong></p>
<p>Object.method() seemed to leave room for a succinct and natural English like approach when invoking methods such as
if target.guessed()...
That can make the method names confusing when read in isolation (in a class definition). Anyone else want to chip in on that?</p>
<p>Hope nothing was missed. Now that the code’s been cleaned up, any other comments?</p>
<p>play_hangman.py (uses objects Word, Guesses and Gallows in hangman.py)</p>
<pre><code>import hangman
def get_letter(guesses):
while True:
char= input("\nPlease enter your guess: ")
if len(char) < 1:
print ("You didn't choose a letter!")
elif len(char)!= 1:
print ("One letter at a time!")
elif not char.isalpha():
print ("Alphabetic characters only!")
elif guesses.guessed (char):
print ("You already guessed that letter")
else:
break
return (char)
def display_progress(target, gallows, guesses):
print("\n",target.progress(guesses))
print(gallows.draw())
print("\nUsed: \n",guesses.made())
def play_game():
target = hangman.Word()
guesses = hangman.Guesses()
gallows = hangman.Gallows()
while True:
guess = get_letter(guesses)
guesses.record(guess,target,gallows)
display_progress(target, gallows, guesses)
if target.guessed(guesses):
print("\nYou win, well done")
break
if gallows.hanged():
print ("\nI win. The word was:",target.word)
break
if __name__ == "__main__":
play_game()
</code></pre>
<p>hangman.py</p>
<pre><code>import random
class Word:
WORDS = ("foxglove", "captain", "oxygen", "microwave", "rhubarb")
def __init__(self):
self._word = random.choice(self.WORDS)
self.letters_in_word = set(self._word)
@property
def word(self):
return self._word
def progress(self, guesses):
# create string of underscores and guessed letters to show progress to guessing word
progress_string = ""
for char in self.word:
if guesses.guessed(char):
progress_string += f" {char} "
else:
progress_string += " _ "
return(progress_string)
def guessed(self, guesses):
letters_guessed= self.letters_in_word.intersection(guesses.guesses_made)
return letters_guessed == self.letters_in_word
class Guesses:
def __init__(self):
# guesses holds all guesses made (wrong or right)
self.guesses_made = set()
def guessed(self,char):
return char in self.guesses_made
def record(self,guess,word,gallows):
# All valid guesses (wrong or right) are added to the guesses set
self.guesses_made.add(guess)
if guess not in word.letters_in_word:
gallows.record_bad_guess()
def made(self):
guesses_list = sorted(self.guesses_made)
#comma separate the guesses
guesses_string = ",".join(guesses_list)
return guesses_string
class Gallows:
bad_guesses = 0
GALLOWS_IMAGES= (" \n \n \n \n \n__________",
" \n | \n | \n | \n | \n_|________",
" _____\n | \n | \n | \n | \n_|________",
" _____\n |/ \n | \n | \n | \n_|________",
" _____\n |/ |\n | \n | \n | \n_|________",
" _____\n |/ |\n | O \n | \n | \n_|________",
" _____\n |/ |\n | O \n | | \n | \n_|________",
" _____\n |/ |\n | O \n | /| \n | \n_|________",
" _____\n |/ |\n | O \n | /|\\ \n | \n_|________",
" _____\n |/ |\n | O \n | /|\\ \n | / \n_|________",
" _____\n |/ |\n | O \n | /|\\ \n | / \\\n_|________",)
def record_bad_guess(self):
self.bad_guesses += 1
def hanged(self):
return self.bad_guesses >= len(self.GALLOWS_IMAGES) -1
def draw(self):
return self.GALLOWS_IMAGES[self.bad_guesses]
</code></pre>
|
[] |
[
{
"body": "<p>This is a great improvement on the original code -- well done! A few points:</p>\n<p><strong>1. Still not <a href=\"https://pep8.org/\" rel=\"nofollow noreferrer\">PEP8</a>-compliant :(</strong></p>\n<p>There's still lots of places in your code where you don't have spaces around operators (sorry, it's a bit of a bugbear of mine!), and a few other PEP8 breaches. <code>elif len(char)!= 1</code> should be <code>elif len(char) != 1</code>; <code>guesses.guessed (char)</code> should be <code>guesses.guessed(char)</code>; <code>print("\\n",target.progress(guesses))</code> should be <code>print("\\n", target.progress(guesses))</code>, etc. If you use an IDE like PyCharm, this will help you a lot with this, as it will automatically flag parts of your code that don't conform to PEP8.</p>\n<p>Another thing that you could consider adding to your code that would make your code more readable for other people is docstrings, which are hugely valuable.</p>\n<p><strong>2. Is a <code>Game</code> class necessary?</strong></p>\n<p>Your code looks much more logical to me as it is now, without the <code>Game</code> class. I probably wouldn't call the main file <code>play_hangman.py</code>, however -- you should probably call the directory that both files are in <code>hangman</code>, and call the file that's currently called <code>play_hangman.py</code> <code>main.py</code>. Files called <code>main.py</code> are commonly understood by python users to be the main entrypoint to a python project.</p>\n<p>With regard to your broader question about how you should conceptualise objects in object-oriented programming... it depends. One of the wonderful things about Python is how easy it makes it to combine elements from multiple programming paradigms. In some scripts I find myself writing extremely procedural code, in others extremely object-oriented code, and in others extremely functional code. In this case, a certain amount of object-oriented style makes sense for the project, but there's no need to go overboard. To program pythonically is to prioritise elegance and simplicity above any "rules" associated with one or another programming paradigm. You don't <em>need</em> a <code>Game</code> class here, and it doesn't really make your code more efficient, elegant, or easier to understand... so why have one?</p>\n<p><strong>3. Is a <code>Gallows</code> class necessary?</strong></p>\n<p>I think you're correct that your <code>Gallows</code> class, as it is, isn't currently doing much work. However, as you say, it's easy to understand what a <code>Gallows</code> class might do. If anything, the idea of a <code>Guesses</code> class feels slightly harder to wrap my head around. I think I might combine your <code>Guesses</code> and <code>Gallows</code> classes like so:</p>\n<pre><code>class Gallows:\n """The `Gallows` class records the guesses you've made,\n and delivers upon you a slow and painful death\n should you make too many incorrect guesses.\n """\n\n GALLOWS_IMAGES = (\n " \\n \\n \\n \\n \\n__________",\n " \\n | \\n | \\n | \\n | \\n_|________",\n " _____\\n | \\n | \\n | \\n | \\n_|________",\n " _____\\n |/ \\n | \\n | \\n | \\n_|________",\n " _____\\n |/ |\\n | \\n | \\n | \\n_|________",\n " _____\\n |/ |\\n | O \\n | \\n | \\n_|________",\n " _____\\n |/ |\\n | O \\n | | \\n | \\n_|________",\n " _____\\n |/ |\\n | O \\n | /| \\n | \\n_|________",\n " _____\\n |/ |\\n | O \\n | /|\\\\ \\n | \\n_|________",\n " _____\\n |/ |\\n | O \\n | /|\\\\ \\n | / \\n_|________",\n " _____\\n |/ |\\n | O \\n | /|\\\\ \\n | / \\\\\\n_|________"\n )\n\n GALLOWS_IMAGES_LEN = len(GALLOWS_IMAGES)\n\n def __init__(self):\n # `guesses_made` holds all guesses made (wrong or right)\n self.guesses_made = set()\n self.incorrect_guesses = 0\n\n def character_already_guessed(self, char):\n return char in self.guesses_made\n\n def record_guess(self, guess, word):\n # All valid guesses (wrong or right) are added to the `guesses_made` set\n self.guesses_made.add(guess)\n if guess not in word.letters_in_word:\n self.incorrect_guesses += 1\n\n def all_guesses_made(self):\n guesses_list = sorted(self.guesses_made)\n # comma-separate the guesses\n guesses_string = ",".join(guesses_list)\n return guesses_string\n\n def hanged(self):\n return self.bad_guesses >= self.GALLOWS_IMAGES_LEN - 1\n\n def draw(self):\n return self.GALLOWS_IMAGES[self.bad_guesses]\n</code></pre>\n<p>If you go down this route, you'll need to make sure you update the file that's currently called <code>play_hangman.py</code> so that it doesn't hold any references to a <code>Guesses</code> class that no longer exists.</p>\n<p><strong>4. Places you could consider taking the project next</strong></p>\n<p>I'd say the main outstanding issue with your project is that there are only a few words that the word you're trying to guess could be. One solution to this might be to have a text file with several hundred -- or even several thousand -- words in it, that Python could quite easily and quickly load into your <code>Word</code> class on initialisation of your programme. If the words are saved in a <code>words.txt</code> file, and are separated with newlines, you could do it like this:</p>\n<pre><code>class Word:\n WORDS_FILE = 'words.txt'\n\n with open(WORDS_FILE, 'r') as f:\n WORDS = tuple(f.read().splitlines())\n\n # <--- snip --->\n</code></pre>\n<p><a href=\"http://www.mieliestronk.com/corncob_lowercase.txt\" rel=\"nofollow noreferrer\">Here's a list</a> of 58,000 words just waiting for you to copy and paste.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-19T13:52:52.347",
"Id": "525859",
"Score": "1",
"body": "Now using *PyCharm* rather than *Idle* - good tip (though it does gobble up screen space on a little XPS13 - we're travelling at the mo). Your DocString for *Gallows* caused much amusement here :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-19T14:24:19.760",
"Id": "525862",
"Score": "0",
"body": "Ha, glad you enjoyed it! Always good to remember to keep coding fun, I think"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T16:28:57.193",
"Id": "266056",
"ParentId": "266049",
"Score": "2"
}
},
{
"body": "<p>Not sure if posting as an answer is the right way to do this? Here's the code reworked to take into account suggestions from @Alex Waygood (thanks for good and useful points Alex).</p>\n<ul>\n<li>Running <em>pycodestyle</em> did throw up a lot of conflicts with PEP8!</li>\n<li>Swapped ‘ for “ as the string delimiter (seems we’re more likely to\nneed to embed a ‘ than a “ within a string).</li>\n<li>Moved everything relating to the command line out of the <em>hangman</em>\nmodule into <em>main.py</em>. The <em>hangman</em> module can then be, for example,\nused to support a GUI version (next project?). Means saying goodbye\nto the <em>Gallows</em> class (and excellent docstring suggestion for it)</li>\n<li>Acted on the suggestion to get the words from a text file but amended\nslightly - multiple topic files for topic focused word lists.</li>\n<li>Reading text files allowed experimenting with exception handling.\nI don’t really get exception handling. If you can predict an exception\ncouldn’t you just write normal code to deal with it?</li>\n<li>Program now allows for spaces and hyphens in words/names.</li>\n<li>Adding docstrings comments - a work in progress at the momement. Harder to write than expected, but focuses the mind.</li>\n<li>Repl here: <a href=\"https://replit.com/@scripta/Hangman?v=1\" rel=\"nofollow noreferrer\">https://replit.com/@scripta/Hangman?v=1</a></li>\n</ul>\n<p>Hangman.py</p>\n<pre><code>"""\nSupport for a game of hangman\n\nClasses:\n Word\n Guesses\n"""\n\nimport random\nimport sys\n\n\nclass Word:\n """Represents the target word for the game. """\n\n TOPICS = ("bird", "city", "scientist", "animal")\n\n def __init__(self):\n """Gets random topic and then a random word from that topic's file."""\n self._topic = random.choice(Word.TOPICS)\n filename = (self._topic+".txt")\n try:\n f = open(filename, "r")\n except OSError:\n print("Cannot open word list " + filename + " unable to continue")\n sys.exit()\n with f:\n WORDS = tuple(f.read().splitlines())\n self._word = random.choice(WORDS)\n self.extract_letters()\n\n @property\n def word(self):\n return self._word\n\n @property\n def topic(self):\n return self._topic\n\n @property\n def letters(self):\n return self._letters\n\n def extract_letters(self):\n """Extracts unique letters from the word,\n discarding spaces and hyphens."""\n uppercase_word = self._word.upper()\n self._letters = set(uppercase_word)\n self._letters.discard(" ")\n self._letters.discard("-")\n\n def progress(self, guesses):\n """Creates a string of guessed letters, spaces & hyphens.\n Unguessed letters replaced with underscores."""\n progress_string = ""\n for char in self.word:\n if guesses.guessed(char.upper()):\n progress_string += f" {char} "\n elif char == " ":\n progress_string += " "\n elif char == "-":\n progress_string += " - "\n else:\n progress_string += " _ "\n return progress_string\n\n def guessed(self, guesses):\n """Determines if the player has successfully guessed the word."""\n letters_guessed = self._letters.intersection(guesses.guesses_made)\n return letters_guessed == self._letters\n\n\nclass Guesses:\n """Guesses holds all guesses made (right or wrong)."""\n\n def __init__(self):\n self.guesses_made = set()\n\n def guessed(self, char):\n """Determines whether a character already been guessed."""\n return char in self.guesses_made\n\n def record(self, guess):\n """Adds all valid guesses (wrong or right) to the guesses set."""\n self.guesses_made.add(guess)\n\n def made(self):\n """Creates a comma separated string of letters guessed so far."""\n guesses_list = sorted(self.guesses_made)\n guesses_string = ",".join(guesses_list)\n return guesses_string\n</code></pre>\n<p>main.py</p>\n<pre><code>import hangman\n\nGALLOWS_IMAGES = (" ",\n " \\n \\n \\n \\n \\n__________",\n " \\n | \\n | \\n | \\n | \\n_|________",\n " _____\\n | \\n | \\n | \\n | \\n_|________",\n " _____\\n |/ \\n | \\n | \\n | \\n_|________",\n " _____\\n |/ |\\n | \\n | \\n | \\n_|________",\n " _____\\n |/ |\\n | O \\n | \\n | \\n_|________",\n " _____\\n |/ |\\n | O \\n | | \\n | \\n_|________",\n " _____\\n |/ |\\n | O \\n | /| \\n | \\n_|________",\n " _____\\n |/ |\\n | O \\n | /|\\\\ \\n | \\n_|________",\n " _____\\n |/ |\\n | O \\n | /|\\\\ \\n | / \\n_|________",\n " _____\\n |/ |\\n | O \\n | /|\\\\ \\n | / \\\\\\n_|________",)\n\n\ndef hanged(number_of_bad_guesses):\n return number_of_bad_guesses >= len(GALLOWS_IMAGES) - 1\n\n\ndef draw_gallows(number_of_bad_guesses):\n print(GALLOWS_IMAGES[number_of_bad_guesses])\n\n\ndef display_progress_to_target_word(target_word, guesses):\n print("\\n", target_word.progress(guesses))\n\n\ndef display_letters_guessed(guesses):\n print("\\nUsed: \\n", guesses.made())\n\n\ndef display_topic(target_word):\n print("\\nHangman - guess the name of the", target_word.topic)\n\n\ndef get_letter(guesses):\n while True:\n char = input("\\nEnter a letter: ")\n char = char.upper()\n if len(char) < 1:\n print("You didn't choose a letter!")\n elif len(char) != 1:\n print("One letter at a time!")\n elif not char.isalpha():\n print("Alphabetic characters only!")\n elif guesses.guessed(char):\n print("You already guessed that letter")\n else:\n break\n return char\n\n\ndef display_status_of_game(target_word, guesses, number_of_bad_guesses):\n display_topic(target_word)\n display_progress_to_target_word(target_word, guesses)\n draw_gallows(number_of_bad_guesses)\n display_letters_guessed(guesses)\n\n\ndef play_game():\n number_of_bad_guesses = 0\n target_word = hangman.Word()\n guesses = hangman.Guesses()\n display_topic(target_word)\n display_progress_to_target_word(target_word, guesses)\n while True:\n guess = get_letter(guesses)\n guesses.record(guess)\n if guess not in target_word.letters:\n number_of_bad_guesses += 1\n display_status_of_game(target_word, guesses, number_of_bad_guesses)\n if target_word.guessed(guesses):\n print("\\nYou win, well done")\n break\n if hanged(number_of_bad_guesses):\n print("\\nI win. The", target_word.topic, "was:", target_word.word)\n break\n\n\nif __name__ == "__main__":\n play_game()\n</code></pre>\n<p>scientist.txt</p>\n<pre><code>Albert Einstein\nIssac Newton\nGalileo\nCharles Darwin\nCopernicus\nAristotle\nNiels Bohr\nMax Planck\nMichael Faraday\n</code></pre>\n<p>city.txt</p>\n<pre><code>Sydney\nLos Angeles\nFrankfurt\nKuala Lumpur\n</code></pre>\n<p>bird.txt</p>\n<pre><code>blackbird\nbuzzard\ncrow\ncurlew\ndunnock\neagle\nfirecrest\ngannet\ngoldfinch\nheron\nhobby\nhouse martin\njackdaw\nmoorhen\nnightingale\nquail\nrobin\nskylark\nsong thrush\nsparrow\nswallow\nswift\ntern\nwaxwing\nwoodpecker\nyellowhammer\nblack-headed gull\n</code></pre>\n<p>animal.txt</p>\n<pre><code>Aardvark\nChimpanzee\nCrocodile\nIguana\nSquirrel\nWalrus\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T08:18:34.040",
"Id": "525733",
"Score": "0",
"body": "Is there any reason why you do not just run [black](https://github.com/psf/black) over your code to make the code PEP-8 compliant? I run Black on save to always keep my code formated =)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T09:34:42.750",
"Id": "525739",
"Score": "1",
"body": "Thanks for the suggestion. Looks like *Black* zaps your code into shape, rather than helping embed good habits. Maybe later."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T09:44:48.937",
"Id": "525742",
"Score": "0",
"body": "Good habits is more than just formating. E.g difference between a linter and a formater. I leave the formating to black and focus on getting rid of my linting errors (in contrast to formating errors). Something like flake8 is often used, but I find it to be a little over bearing. Instead turn to a proper editor like VsCode and use pylance =) Something like this in the settings.json https://stackoverflow.com/questions/65800536/black-formatter-does-not-work-in-vscode-after-installing-anaconda3."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T15:08:56.130",
"Id": "525765",
"Score": "0",
"body": "I've played around with *Black* some more. It picked up one transgression that pycodestyle missed.\n- filename = (self._topic+\".txt\")\n+ filename = self._topic + \".txt\""
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T13:52:20.097",
"Id": "266128",
"ParentId": "266049",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T09:33:57.527",
"Id": "266049",
"Score": "3",
"Tags": [
"python",
"object-oriented"
],
"Title": "OOP Hangman Game - amended code"
}
|
266049
|
<h3>Introduction</h3>
<p>I have implemented a generalization to the <a href="https://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle" rel="nofollow noreferrer">inclusion-exclusion principle</a>, which extends the principle from sets to more general objects. In short the principle calculates the left by doing the calculation on the right</p>
<p><a href="https://i.stack.imgur.com/KrEaC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KrEaC.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/PxGTS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PxGTS.png" alt="enter image description here" /></a></p>
<p>In order to extend this to general objects, these objects need to have some <code>structure</code> (some defining property). They need to have a concept of <code>intersection</code> (what it two objects have in common) and lastly a notion of <code>cardinality</code> (size or in pythons terms the length). The symbol for intersection is ∩ and for cardinality | | is used.</p>
<p>So this code does precisely that. It creates objects which have a notion of intersection, cardinality and then uses the inclusion-exclusion principle to calculate the size (cardinality) of their union (|A U B U .. |).</p>
<h3>Wanted feedback</h3>
<p>My code works, but I do get some typing hint errors as I am unsure
on how to annotate the <code>IEP</code> class. So feedback on how to implement proper typing hints is more than welcome.</p>
<p>Speaking of IEP, I feel my whole construction of objects is contrived. What I want is some generic metaclass, which again produces <code>IEP</code> objects which has a set <code>intersection</code> and <code>cardinality</code>. This is what the <code>make_IEP</code> do, but again, pushing a class inside a function seems counter-intuitive.</p>
<h3>Code</h3>
<p><strong>utilities.py</strong></p>
<pre><code>from collections.abc import Iterable, Callable
from typing import Any, TypeVar, Tuple, Union
import functools
import itertools
_T = TypeVar("_T")
_S = TypeVar("_S")
@functools.cache
def reduce_w_cache(function: Callable[[_T, _S], _T], sequence: Iterable[_S]) -> _S:
"""Reduces the sequence to a single number by left folding function over it
Example:
The easiest way to understand how reduce works is applying a tuple to it
>>> sequence = tuple([1, 3, 5, 6, 2])
>>> make_tuple = lambda x, y: tuple([x, y])
>>> reduce_w_cache(make_tuple, sequence)
((((1, 3), 5), 6), 2)
Similarly a right fold would look like ``(1, (3, (5, (6, 2))))``
>>> add = lambda x, y: x + y
>>> sum_reduce = lambda x: reduce_w_cache(add, x)
>>> reduce_w_cache(add, sequence)
17
Understanding how this works is as easy as replacing , with + in the
example above
reduce_w_cache(add, sequence) = ((((1 + 3) + 5) + 6) + 2) = 17
Let us test if the caching works. We first save how many misses we
have, where a miss corresponds to a value being added to the cache. We
will then perform some lookups and study how many values were cached.
>>> repeat_reduce = lambda fun, seqs: [reduce_w_cache(fun, tuple(s)) for s in seqs]
>>> def values_cached(function, sequences):
... initial = reduce_w_cache.cache_info().misses
... repeat_reduce(function, sequences)
... total = reduce_w_cache.cache_info().misses
... return total - initial
>>> test_function = lambda x, y: [x, y]
>>> sequences = [
[103], [103, 105], [103, 105, 107], [103, 105, 107, 109], [103, 105, 107, 109, 111]
]
We are going to run ``reduce_w_cache`` with ``test_function`` over each
element in ``sequences``. With no caching we would expect ``len - 1``
function calls with a minimal of ``1`` for each sequence in sequences.
Totaling to ``1 + 1 + 2 + 3 + 4 = 11`` function calls.
However with cached values this is greatly lowered. For instance ``(103,
105, 107)`` folds to ``(103, (105, 107))`` and the value of
``(105, 107)`` is already stored in the cache.
>>> values_cached(test_function, sequences)
5
No new values should be added if we lookup the same values again
>>> values_cached(test_function, sequences)
0
As a sanity check let us test how many values are cached when
we can not use previously stored values
>>> sequences = [
[112], [113, 114], [115, 116, 117], [118, 119, 120, 121], [118, 119, 120, 121, 122]
]
>>> values_cached(test_function, sequences)
11
Let us double check that the number of calls really is 11. For each
function call we wrap two elements in ``[]`` so simply counting the number
of either ``[`` or ``]`` returns the number of function calls.
>>> str(repeat_reduce(test_function, sequences)).count('[')
11
"""
*remaining, last = sequence
if not remaining:
return last
return function(reduce_w_cache(function, tuple(remaining)), last)
def powerset(iterable:Iterable[Any], emptyset:bool=False, flatten:bool=True) -> Iterable[Union[Tuple[Any, ...],Iterable[Tuple[Any, ...]]]]:
"""Returns the powerset of some list without the emptyset as default
Examples:
>>> list(powerset([1,2,3]))
[(1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
>>> list(powerset([1,2,3], emptyset=True))
[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
>>> list(list(i) for i in powerset([1,2,3], flatten=False))
[[(1,), (2,), (3,)], [(1, 2), (1, 3), (2, 3)], [(1, 2, 3)]]
>>> list(list(i) for i in powerset([1,2,3], emptyset=True, flatten=False))
[[()], [(1,), (2,), (3,)], [(1, 2), (1, 3), (2, 3)], [(1, 2, 3)]]
"""
try:
iter(iterable)
s = list(iterable)
except TypeError:
if not isinstance(iterable, list):
raise TypeError("Input must be list or iterable")
s = iterable
start = 0 if emptyset else 1
powerset_ = (itertools.combinations(s, r) for r in range(start, len(s) + 1))
return itertools.chain.from_iterable(powerset_) if flatten else powerset_
if __name__ == "__main__":
import doctest
doctest.testmod()
</code></pre>
<p><strong>iep.py</strong></p>
<pre><code>"""
Provides a module for the inclusion exclusion protocol
"""
from collections.abc import Callable
import functools
from typing import Annotated, Any, Union, Type
from utilities import powerset, reduce_w_cache
Structure = Annotated[
Any,
"An intrinsic property that defines the shape and form of our object",
]
Intersection = Annotated[
Callable[[Structure, Structure], Structure],
"Is a callable function that takes in two structures and returns the"
"intersection, which is a new (smaller or equal) structure.",
]
# Defines an empty class here for typing hints
class IEP:
def __init__(self, structure: Structure):
self.structure = structure
pass
Cardinality = Annotated[
Callable[[Type[IEP]], Union[int, float]],
"Is a callable function that returns the general concept of size for an object",
]
class ConstructorIEP:
"""Implements intersection and cardinality (len) for the IEP class"""
def cardinality(self, x):
return x
def intersect(self, x, _):
return x
@property
def structure(self):
return self._structure
@structure.setter
def structure(self, stuff: Structure):
self._structure = stuff
self.len = self.cardinality(self._structure)
def intersection(self, *others: Type[IEP]):
if len(others) == 0:
new_structure = self.structure
new_structure = self.structure
for other in others:
new_structure = self.intersect(new_structure, other.structure)
NewIEP = make_IEP(self.intersect, self.cardinality)
return NewIEP(new_structure)
def __len__(self):
return self.len
def __repr__(self):
return f"IEP({self.structure})"
def __str__(self):
return f"{self.structure}, len={self.len}"
def make_IEP(intersect: Intersection, cardinality: Cardinality) -> Type[IEP]:
"""Creates an IEP class with a fixed intersect and cardinality"""
class IEP(ConstructorIEP):
def __init__(self, structure: Structure):
self.intersect = intersect
self.cardinality = cardinality
self.structure = structure
return IEP
def inclusion_exclusion_principle(
structure_of_objects: list[Structure],
intersection_: Intersection,
cardinality_: Cardinality,
cache: bool = False,
) -> int:
"""If structure_of_objects = [A, B, C, ...] this function returns |A U B U C U ...|
The return value is calculated using the exclusion inclusion principle;
here | | denotes the cardinality (or in Pythons words the length) of the set,
and ∩ represents the intersection of two objects, and U representens the union.
See the link for more information
https://en.wikipedia.org/wiki/Inclusion%E2%80%93exclusion_principle
Args:
structure_of_objects: A list of structures that with intersection and
cardinality defines an object
intersection: A function(x, y) that returns what two object structures has
in common (defines x.intersection(y))
cardinality: A function(x) that returns the size of an object (defines len(object))
Returns:
int: Returns the size (``len``) of the intersection of every element in ``list_of_objects``
Examples:
Setup for discrete sets
>>> intersection = lambda a, b: a.intersection(b)
>>> cardinality = len
>>> sets = [set([])]
>>> inclusion_exclusion_principle([{}], intersection, cardinality)
0
>>> inclusion_exclusion_principle([{1, 2, 3}, {1, 2, 3}], intersection, cardinality)
3
>>> inclusion_exclusion_principle([{1, 2, 3}, {4, 5, 6}], intersection, cardinality)
6
Setup for continous ranges is a bit harder as it is cumbersome to define the
intersections between two intervals properly
>>> def intersection(*intervals):
... max_first, min_last = [f(i) for f, i in zip([max, min], zip(*intervals))]
... if (min_last - max_first) >= 0:
... return [max_first, min_last]
... return [float("inf"), float("inf")]
...
>>> cardinality = lambda a: len(range(*a))
>>> inclusion_exclusion_principle([[0, 0]], intersection, cardinality)
0
>>> inclusion_exclusion_principle([[1, 2], [1, 2]], intersection, cardinality)
1
>>> inclusion_exclusion_principle([[0, 3], [1, 2]], intersection, cardinality)
3
>>> inclusion_exclusion_principle([[2, 4], [3, 5], [4, 6]], intersection, cardinality)
4
As a more advanced example we can use inclusion-exclusion-principle to
find the union of all numbers divisible by 1 or more of our objects.
Essentially solving the first project euler problem
>>> gcd = lambda m,n: m if not n else gcd(n, m % n)
>>> lcm = lambda a, b: abs(a * b) // gcd(a, b)
>>> start, stop = 1, 1000
>>> intersection = lcm
>>> cardinality = lambda x: sum(i for i in range(start, stop) if i % x == 0)
>>> inclusion_exclusion_principle([3, 5], intersection, cardinality)
233168
Of course this could have been improved by implementing a cardinality
that runs in linear time
>>> sum_linear = lambda start, stop: (stop + start + 1) * (stop - start) // 2
>>> cardinality = lambda x: x * sum_linear(start//x, (stop-1)//x)
>>> inclusion_exclusion_principle([3, 5], intersection, cardinality)
233168
"""
class IEP(ConstructorIEP):
def __init__(self, structure: Structure):
self.intersect = intersection_
self.cardinality = cardinality_
self.structure = structure
list_of_objects = list(map(IEP, structure_of_objects))
reduce = reduce_w_cache if cache else functools.reduce
def intersect(list_of_objects: list[Type[IEP]]):
"""Finds the intersection of a list of objects according to the rules set by intersection"""
# If the list of sets only contains one element, we are left with
# finding the intersection of a set with itself. However, this is just
# the set itself, because intersection retrieves the common elements.
# Here, all elements of a set is common with itself. Hence, the
# resulting intersection of a set with itself, is itself
if len(list_of_objects) == 1:
return list_of_objects[0]
return reduce(lambda x, y: x.intersection(y), list_of_objects)
def cardinality(obj):
return len(obj)
cardinality_of_union, sign = 0, 1
# It will be easier to follow this code through an example
# list_of_objects = [A, B, C]
# powerset(list_of_objects, flatten=False) = [
# [[A], [B], [C]],
# [[A, B], [A, C], [B, C]],
# [A, B, C]]
# ]
for subsets_w_same_len in powerset(list_of_objects, flatten=False):
# intersections:
# First pass: = [A, B, C] # All subsets of len 1 (intersection of itself is itself)
# Second pass: = [A ∩ B, A ∩ C, B ∩ C] # All subsets of len 2
# Final pass: = [A ∩ B ∩ C] # All subsets of len 3
intersections = map(intersect, subsets_w_same_len)
# cardinalities:
# First pass: = [ |A|, |B|, |C| ]
# Second pass: = [ |A ∩ B|, |A ∩ C|, |B ∩ C| ]
# Final pass: = [ |A ∩ B ∩ C| ]
cardinalities = map(cardinality, intersections)
# cardinality_of_union:
# First pass: = |A| + |B| + |C|
# Second pass: = |A| + |B| + |C|
# - ( |A ∩ B| + |A ∩ C| + |B ∩ C| )
# Final pass: = |A| + |B| + |C|
# - ( |A ∩ B| + |A ∩ C| + |B ∩ C| )
# + ( |A ∩ B ∩ C| )
cardinality_of_union += sign * sum(cardinalities)
sign *= -1
# Where
# cardinality_of_union = |A| + |B| + |C|
# - ( |A ∩ B| + |A ∩ C| + |B ∩ C| )
# + ( |A ∩ B ∩ C| )
# = |A U B U C |
# By the inclusion excluion principle, which is what we wanted
return cardinality_of_union
if __name__ == "__main__":
import doctest
doctest.testmod()
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p><code>reduce_w_cache</code></p>\n<ul>\n<li><p>Prone to hitting recursion limits.\nYou should use an iterative approach not a functional one.</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> reduce_w_cache(int.__add__, (1,) * 1000)\nTraceback (most recent call last):\n File "<stdin>", line 1, in <module>\n File "<stdin>", line 6, in reduce_w_cache\n File "<stdin>", line 6, in reduce_w_cache\n File "<stdin>", line 6, in reduce_w_cache\n [Previous line repeated 496 more times]\nRecursionError: maximum recursion depth exceeded\n</code></pre>\n</li>\n<li><p>Doesn't work with a sequence of 0. Convention is to provide a default kwarg, eg; <code>max</code>, <code>min</code>, <code>dict.get</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> max([], default=0)\n0\n</code></pre>\n</li>\n<li><p>Your function is slow <span class=\"math-container\">\\$O(n^2)\\$</span> you can get an (amortized) <span class=\"math-container\">\\$O(n)\\$</span> performance by building the cache yourself.\nA very basic and naive (aka broken) approach could be:</p>\n<ol>\n<li><p>Store the size of the cache.\nThis prevents us from needing to slice the input (getting <span class=\"math-container\">\\$O(n^2)\\$</span> time).</p>\n</li>\n<li><p>Iteratively build the cache.\nSuppose we use <code>reduce_w_cache</code> to hash the sequence, you should notice we can just build off the previous hash.</p>\n</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>_hash = 0\nfor size, value in enumerate(sequence, 1):\n _hash ^= hash(value)\n cache[size, _hash] = ...\n</code></pre>\n<p>To make the algorithm work you would need to properly handle collisions (the hard part of building a hash map).\nYou should store the original in the key, but not use it to compare values.\nIf the size and hash match then you need to use it to compare collisions using an <span class=\"math-container\">\\$O(nk)\\$</span> algorithm.\nWhere <span class=\"math-container\">\\$n\\$</span> is the size of the value and <span class=\"math-container\">\\$k\\$</span> is the amount of collisions.</p>\n<p>To reduce collisions you'd have to take into account the birthday problem, and so can get a little memory hungry.</p>\n</li>\n</ul>\n<p>Overall I think <code>functools.reduce</code> would be better here.</p>\n</li>\n<li><p><code>powerset</code><br />\nAbout what I expect from a powerset function.</p>\n<ul>\n<li><p>I think <code>flatten</code> is a bad design, and makes your function succeptable to becoming a god function.</p>\n<pre class=\"lang-py prettyprint-override\"><code>powerset(..., flatten=True)\n</code></pre>\n<p>vs</p>\n<pre class=\"lang-py prettyprint-override\"><code>flatten = itertools.chain.from_iterable\nflatten(powerset(...))\n</code></pre>\n</li>\n<li><p>"Input must be list or iterable" and <code>isinstance(iterable, list)</code> are odd as <code>list</code> <em>is</em> an iterable.\nYou can probably just remove the code.</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> import collections.abc\n>>> issubclass(list, collections.abc.Iterable)\nTrue\n</code></pre>\n</li>\n</ul>\n</li>\n<li><p><code>IEP</code></p>\n<ul>\n<li><p>Should be a Protocol.</p>\n</li>\n<li><p><code>IEP</code> should be called <code>IIEP</code>, well anything other than <code>IEP</code>.\nThe additional <code>I</code> is <a href=\"https://stackoverflow.com/a/681815\">nomenculture taken from C#</a> standing for "Interface".</p>\n<p>The biggest benefit, and why I've copied the style from C#, is not having duplicate names for the interface and the implementation.</p>\n</li>\n</ul>\n</li>\n<li><p><code>ConstructorIEP</code>\nLooks rather good. But have some nitpicks.</p>\n<ul>\n<li><p>I don't like the dunder methods being at the bottom of your class.\nRegardless kudos are due for having a clear style.</p>\n<p>Here is my style:</p>\n<ol>\n<li><p>Type hints.</p>\n</li>\n<li><p>Constructors.</p>\n<ul>\n<li><code>__new__</code></li>\n<li><code>__init__</code></li>\n<li>Class or static builders.</li>\n</ul>\n</li>\n<li><p>Dunder methods</p>\n</li>\n<li><p>Everything else</p>\n</li>\n</ol>\n<p>I class 'helper functions' to be grouped with the source function.\nSay you have a dunder method which is getting a bit big, splitting the function in two methos (one dunder one normal) shouldn't move the normal method to the bottom of the class.</p>\n</li>\n<li><p><code>intersection</code> looks a little off.</p>\n<pre class=\"lang-py prettyprint-override\"><code>if len(others) == 0:\n new_structure = self.structure\nnew_structure = self.structure\n</code></pre>\n</li>\n<li><p>Your str dunder should call <code>__len__</code> not lookup <code>len</code>.\nMakes your code more Pythonic and allows subclasses to follow Python's idioms and still have the code work fine.</p>\n</li>\n</ul>\n</li>\n<li><p><code>make_IEP</code></p>\n<ul>\n<li><p>I think the function should be a class builder on <code>ConstructorIEP</code>.</p>\n</li>\n<li><p>I'm not a fan of <code>self.intersect = intersect</code>.\nBind the method to the class not the instance.</p>\n<pre class=\"lang-py prettyprint-override\"><code>@classmethod\ndef build_type(cls, intersect: Intersection, cardinality: Cardinality) -> Type[IEP]:\n """Creates an IEP class with a fixed intersect and cardinality"""\n\n class IEP(ConstructorIEP):\n intersect = staticmethod(intersect)\n cardinality = staticmethod(cardinality)\n\n def __init__(self, structure: Structure):\n self.structure = structure\n\n return IEP\n</code></pre>\n</li>\n</ul>\n</li>\n<li><p><code>inclusion_exclusion_principle</code> (not a full review)</p>\n<ul>\n<li><p><code>intersection_</code> should be <code>intersection</code> and <code>intersection</code> should be <code>intersection_</code>.\nA user of your function couldn't care less what the internal names of your function are, but <em>do</em> care about having sensible argument names.</p>\n</li>\n<li><p>Why have you defined <code>IEP</code> again and not used <code>make_IEP</code>?</p>\n</li>\n</ul>\n<p>I'm no mathematician so I'm going to stop here.</p>\n</li>\n</ul>\n<p>Overall my answer is mostly nitpicks or somewhat trivial tidbits. Good code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T08:09:33.407",
"Id": "525515",
"Score": "0",
"body": "I never knew I could push the class builder into `ConstructorIEP`! =) Similarly `staticmethod` was the missing piece, I tried to bind the methods to the class and not the instance, but could not make it work. Why IEP was defined again was leftover code from a refactor attempt (wanted to remove `make_IEP`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T08:11:04.267",
"Id": "525516",
"Score": "0",
"body": "As an after thought do I need the `ConstructorIEP` class? Or could I simply shove everything into the `build_type` function? It seems a little off that the `IEP`'s inherit the `build_type` classmethod."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T15:04:44.950",
"Id": "525533",
"Score": "0",
"body": "@N3buchadnezzar I don't really see anything wrong with having `ConstructorIEP` which builds a new type. At the end of the day the builder is just a helper method. If your code becomes more complex then relying on a helper method for core functionality could be bad, but we'd need to know the situation to actually comment on whether the approach is sub-optimal. You could try other methods to do what you want, but if all the approaches work optimally, what's the problem? Regardless, I find meta programming to be quite abnormal and doesn't follow 'normal' processes."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T22:44:24.200",
"Id": "266065",
"ParentId": "266051",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "266065",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T09:55:20.027",
"Id": "266051",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"classes"
],
"Title": "Extending the inclusion-exclusion principle to general objects"
}
|
266051
|
<p>I'm currently trying to improve my ChaCha algorithm implementation. Here's the my code (written in C):</p>
<pre><code>#include <string.h> // memcpy
#include <stddef.h> // size_t
#include <stdint.h> // uint32_t
typedef uint32_t ChaChaSigma [4];
typedef uint32_t ChaChaKey [8];
typedef uint32_t ChaChaNonce [4];
typedef enum ChaChaStandard {
kOriginal,
kIetf
} ChaChaStandard;
typedef short ChaChaRounds;
typedef uint32_t ChaChaBlock [16];
typedef struct ChaChaMatrix {
union {
struct {
ChaChaSigma sigma; // The costant used. Usually "expand 32-byte k".
ChaChaKey key; // The key used. Has to be hashed or padded by the user manually.
ChaChaNonce nonce; // The nonce used. It's formed by a block counter and an iv.
};
uint32_t words [16]; // The words of the matrix. Used for raw access.
};
ChaChaStandard standard;
ChaChaRounds rounds;
} ChaChaMatrix;
// trick to have default values
#define INIT_CHACHAMATRIX(...) ((ChaChaMatrix){ \
.sigma = {0x61707865UL, 0x3320646eUL, 0x79622d32UL, 0x6b206574UL}, \
.key = {0, 0, 0, 0, 0, 0, 0, 0}, \
.nonce = {0, 0, 0, 0}, \
.standard = kOriginal, \
.rounds = 20, \
__VA_ARGS__ \
})
uint32_t rotl32 (uint32_t n, short r) {
return (n << r) | (n >> (32 - r));
}
void ChaChaStep (uint32_t x[16], size_t a, size_t b, size_t c, short r) {
x[a] += x[b];
x[c] = rotl32(x[c] ^ x[a], r);
}
void ChaChaQuarterRound (uint32_t x[16], size_t a, size_t b, size_t c, size_t d) {
ChaChaStep(x, a, b, d, 16);
ChaChaStep(x, c, d, b, 12);
ChaChaStep(x, a, b, d, 8);
ChaChaStep(x, c, d, b, 7);
}
void ChaChaVerticalRound (uint32_t x[16]) {
ChaChaQuarterRound(x, 0, 4, 8, 12);
ChaChaQuarterRound(x, 1, 5, 9, 13);
ChaChaQuarterRound(x, 2, 6, 10, 14);
ChaChaQuarterRound(x, 3, 7, 11, 15);
}
void ChaChaDiagonalRound (uint32_t x[16]) {
ChaChaQuarterRound(x, 0, 5, 10, 15);
ChaChaQuarterRound(x, 1, 6, 11, 12);
ChaChaQuarterRound(x, 2, 7, 8, 13);
ChaChaQuarterRound(x, 3, 4, 9, 14);
}
void ChaChaComputeBlock (ChaChaMatrix * matrix, ChaChaBlock * block) {
memcpy(block, matrix, sizeof(uint32_t)*16);
short i;
for (i = 0; i < matrix->rounds; i+=2) {
ChaChaVerticalRound(*block);
ChaChaDiagonalRound(*block);
}
for (i = 0; i < 16; i++) {
(*block)[i] += matrix->words[i];
}
}
</code></pre>
<p>I'm still planning an implementation to increase the counter without having to deal with type cast and IETF/Original standards.</p>
<p>The second action performed on the matrix uses the variable part (the block counter, inside the nonce). Because this (usually) increases only by 1 unit every time I was wondering if there's a way to improve its XOR efficency.</p>
<p>I opened excel and plotted a grpah of <code>BITXOR(314, i)</code>, <code>i</code> being the variable going from 0 to 999. The graph shows a nice pattern. Every <code>0x100*n</code> (in other words: every 4 "big downward steps" by <code>0x40</code> units) it jumps. The pattern is similar to the <code>XOR(0, ..., n)</code> one (?)</p>
<p><a href="https://i.stack.imgur.com/DUeFL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DUeFL.png" alt="graph" /></a></p>
<p>My question are:</p>
<ul>
<li>Are there some efficient ways to calculate <code>a XOR (b+1)</code> known <code>a XOR b</code>? The pattern, to me, suggests that it might be possible, but I'm not smart enough to find a solution...</li>
<li>Does it make sense to implement this tiny improvement?</li>
</ul>
<p>PS: if the software engegneering stackexchange better fits the question format I can move it there :)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T17:30:07.350",
"Id": "525501",
"Score": "0",
"body": "I don't think that 1. it is possible, as you cannot magic the possible carry out of nothing and 2. that it would make any difference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T22:08:13.640",
"Id": "525507",
"Score": "1",
"body": "Inlining the functions rotl32 and ChaChaStep would allow some compiler optimizations for a small speed improvement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T14:42:37.170",
"Id": "525530",
"Score": "2",
"body": "There's `(a ^ (b + 1)) == (a ^ b) ^ (b ^ (b + 1))` to compute that thing from the \"previous\" thing, but that's worse. It's hard to compete with 2 operations."
}
] |
[
{
"body": "<p>A small review</p>\n<blockquote>\n<p>trying to improve my ChaCha algorithm implementation</p>\n</blockquote>\n<p><strong><code>static</code> function</strong></p>\n<p><code>rotl32()</code> is not a well defined function for rotating when the count is 0 (or 32). That does not matter here as <code>rotl32(n, 0)</code> is not used. Since the function is only correct for local usage, make it <code>static</code> to avoid other modules using this reduced purpose function.</p>\n<pre><code>// uint32_t rotl32 (uint32_t n, short r) {\nstatic uint32_t rotl32 (uint32_t n, short r) {\n</code></pre>\n<p><strong>Avoid magic numbers</strong></p>\n<p>Why 16 below? Why <code>uint32_t</code>?. One could look around code and eventuality see what <code>memcpy()</code> is doing, but how about some direct alternatives?:</p>\n<pre><code>void ChaChaComputeBlock (ChaChaMatrix * matrix, ChaChaBlock * block) {\n // memcpy(block, matrix, sizeof(uint32_t)*16);\n memcpy(block, matrix, sizeof *block);\n // or \n *block = (ChaChaBlock){0};\n</code></pre>\n<blockquote>\n<p>Are there some efficient ways to calculate a XOR (b+1) known a XOR b? The pattern, to me, suggests that it might be possible, but I'm not smart enough to find a solution...</p>\n</blockquote>\n<p>Perhaps, I do not see one now.<br />\nSome other small ideas:</p>\n<p><strong><code>int</code> vs. <code>short</code></strong></p>\n<p>A small inefficiency is using sub-<code>int</code> parameters/objects. <code>int</code> is usually the best size for crisp code.</p>\n<pre><code>// uint32_t rotl32 (uint32_t n, short r) {\nuint32_t rotl32 (uint32_t n, int r) {\n\n // short i;\n int i;\n</code></pre>\n<p><strong><code>const, restrict</code></strong></p>\n<p>Let the compiler know that <code>matrix</code> and <code>block</code> do not overlap.</p>\n<p>Use <code>const</code> to allow for greater functional usage and potentially some select optimizations.</p>\n<pre><code>// void ChaChaComputeBlock (ChaChaMatrix * matrix, ChaChaBlock * block) {\nvoid ChaChaComputeBlock (const ChaChaMatrix * restrict matrix, \n ChaChaBlock * restrict block) {\n</code></pre>\n<blockquote>\n<p>Does it make sense to implement this tiny improvement?</p>\n</blockquote>\n<p>Perhaps yes. Keep in mind <a href=\"https://softwareengineering.stackexchange.com/questions/80084/is-premature-optimization-really-the-root-of-all-evil\">Is premature optimization really the root of all evil?\n</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T08:03:21.657",
"Id": "525514",
"Score": "0",
"body": "Thank you very much for the detailed answer! Do I have to use the `static` keyword even if I'm using `chahca.c` for the rotl32 declaration and definition and the definition of all other functions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T17:05:31.417",
"Id": "525534",
"Score": "0",
"body": "@DadiBit If a function is only ued in `chahca.c`, consider making it `static`. Other functions should also be declared in `chahca.h`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T23:43:47.953",
"Id": "266066",
"ParentId": "266052",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "266066",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T12:26:18.623",
"Id": "266052",
"Score": "3",
"Tags": [
"performance",
"algorithm",
"c"
],
"Title": "Efficient (a XOR (b+1)) known (a XOR b) in C for the ChaCha algorithm"
}
|
266052
|
<p>I recently got this question in an exam, this is how I implemented, it is working fine. However, I would like to know if the code can be improved, as I think it for sure needs to be improved. The question was:</p>
<blockquote>
<p>In the past, Twitter had a 140 characters limitation per tweet. If you wanted to enter longer tweets, you had to split it into several. We want to create a function that receives a String, which is the content of the tweet, that returns all the tweets with numbered prefixes (a List). It does not matter if the words are splitted. Something like this: (Tweet 1/5)tweetcontent.... (Tweet 2/5)tweetcontent...</p>
</blockquote>
<pre><code>public class Exercise {
static int MAX_CHARACTERS_OF_MESSAGE_IN_TWEET = 129;
public List<String> tweets(String message) {
List<String> tweetsToReturn = new ArrayList<>();
//calculate numberOfTweets needed to tweet
int numberOfTweets = message.length() / MAX_CHARACTERS_OF_MESSAGE_IN_TWEET;
//check if we need to add another tweet for the latest characters of the message
int restOfTWeet = message.length() % MAX_CHARACTERS_OF_MESSAGE_IN_TWEET;
if (restOfTWeet != 0) {
numberOfTweets++;
}
//if there is only one tweet
if (numberOfTweets == 1) {
tweetsToReturn.add(message);
} else { //if there is more than one tweet
for (int i = 0; i < numberOfTweets - 1; i++) {
tweetsToReturn.add("(Tweet " + (i + 1) + "/" + numberOfTweets + ")" + message.substring(i * MAX_CHARACTERS_OF_MESSAGE_IN_TWEET, (i+1) * MAX_CHARACTERS_OF_MESSAGE_IN_TWEET));
}
//create the latest tweet
if (restOfTWeet != 0) {
tweetsToReturn.add("(Tweet " + numberOfTweets + "/" + numberOfTweets + ")" + message.substring((numberOfTweets - 1) * MAX_CHARACTERS_OF_MESSAGE_IN_TWEET));
}
}
return tweetsToReturn;
}}
</code></pre>
<p>Bonus point: Do it now but without the words being splitted. (This one I did not manage to do it).</p>
<p>Thank you!!!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T14:45:33.713",
"Id": "525497",
"Score": "1",
"body": "Do you have a constraint that the number of tweets will be fewer than 10? If not, the problem becomes a bit more challenging to use up every available character."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T16:20:01.257",
"Id": "525499",
"Score": "0",
"body": "From what I remember, the number of tweets were not going to be very big. However, I would like to know the different solutions depending on the number of tweets. Thanks!"
}
] |
[
{
"body": "<p>Overall, your code does the job correctly, and does it in a way that is not unnecessarily complicated. Good job. The rest of my comments are just how you can make the code a little easier to read, because the simpler it is to read, the easier it will be to tackle the bonus problem.</p>\n<p>To start, when you share code with others you should run the auto-format in your IDE, and you should include the necessary imports.</p>\n<p><code>MAX_CHARACTERS_OF_MESSAGE_IN_TWEET</code> is too long, I would prefer <code>MAX_TWEET_LENGTH</code> and it should be marked <code>final</code>. The value should reflect the knowledge of the domain, i.e. the 140 character length. Then you can show how you got to 129:</p>\n<pre><code> static final int MAX_TWEET_LENGTH = 140;\n static final int PREFIX_LENGTH = 11;\n static final int CHARS_PER_TWEET = MAX_TWEET_LENGTH - PREFIX_LENGTH;\n</code></pre>\n<pre><code>public List<String> tweets(String message) {\n</code></pre>\n<p>This should marked static, because it doesn't use any instance variables. This makes it available to its consumers without having to make a <code>new Exercise()</code>. And it makes the code slightly easier to read for people reading the code, because they know they don't need to consider any variables defined elsewhere, except for other <code>static</code> variables (which are usually <code>final</code> constants that are self-descriptive).</p>\n<p>Variables should be declared close to where they are first used, so <code>List<String> tweetsToReturn</code> should come later. Variables that you are intending to return are often take the name of the method itself, and therefore the <code>toReturn</code> part is implied and can be left out.</p>\n<pre><code> // if there is only one tweet\n</code></pre>\n<p>This comment is unnecessary - it just says what the code already says. Most of the comments fall into this category. Once you are "fluent" in "reading" code, this just becomes obvious. It's as though you've written something to a bilingual person, but said the same thing twice, once in each language.</p>\n<pre><code> // if there is more than one tweet\n</code></pre>\n<p>Same with this comment, but I will add that it is sometimes nicer to avoid <code>else</code> blocks altogether in cases where the <code>if</code> block can simply <code>return</code> out of the function. You can use <code>Arrays.asList</code> to simply return an array if all the values are already known. In this case, there will only be one value, and we already know it (<code>message</code>).</p>\n<p>If you calculate a value, check it once, and don't use it again, you don't need to create a variable name for it (<code>restofTWeet</code>), just put it "inline". Here you are using the value again later, but I get the feeling we can make changes so that won't actually be necessary, so I would still inline it for now.</p>\n<p>To build the list of tweets, you are using a <code>for</code> loop, which works in cases where we know how many times we are going to loop, and we indeed do know. But it takes more mental effort to verify that we have calculated the number of loops properly, compared to if we just set up a simple "loop until done" using <code>while</code>, so I would use <code>while</code> and that turned out to make the bonus problem a little easier too.</p>\n<p>As for building the tweets the way you have with <code>+</code> on Strings, that's fine performance-wise, and it's not so bad in terms of readability, but you should be aware of the other ways of writing the same thing, which you may sometimes prefer if it makes it even easier to read. Specifically, also be aware of how to use <code>String.format</code> and <code>StringBuilder</code>, which have their own pros and cons. I used both in the examples below.</p>\n<p>Here's the version after the after the above changes, and still solving the original problem:</p>\n<pre class=\"lang-java prettyprint-override\"><code>import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class Exercise {\n\n static final int MAX_TWEET_LENGTH = 140;\n static final int PREFIX_LENGTH = 11;\n static final int CHARS_PER_TWEET = MAX_TWEET_LENGTH - PREFIX_LENGTH;\n\n public static List<String> tweets(String message) {\n if (message.length() <= MAX_TWEET_LENGTH) {\n return Arrays.asList(message);\n }\n \n int tweetCount = message.length() / CHARS_PER_TWEET;\n if (message.length() % CHARS_PER_TWEET != 0) {\n tweetCount++;\n }\n\n List<String> tweets = new ArrayList<>();\n int cursor = 0;\n int currentCount = 1;\n while (cursor < message.length()) {\n final int contentLength = Math.min(message.length() - cursor,\n CHARS_PER_TWEET);\n final String content = message.substring(cursor, cursor + contentLength);\n tweets.add(String.format("(Tweet %d/%d)%s", currentCount, tweetCount, content));\n cursor += contentLength;\n currentCount++;\n }\n return tweets;\n }\n\n}\n</code></pre>\n<p>Then for the bonus points, we can get an array of the words using <code>String.split</code>, and instead of working out how many characters we are going to add per loop, we do an inner loop, adding words from the list until the next word won't fit or there are no more words:</p>\n<pre class=\"lang-java prettyprint-override\"><code>import java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\npublic class Exercise {\n\n static final int MAX_TWEET_LENGTH = 140;\n static final int PREFIX_LENGTH = 11;\n static final int CHARS_PER_TWEET = MAX_TWEET_LENGTH - PREFIX_LENGTH;\n\n public static List<String> tweets(String message) {\n if (message.length() <= MAX_TWEET_LENGTH) {\n return Arrays.asList(message);\n }\n\n int tweetCount = message.length() / CHARS_PER_TWEET;\n if (message.length() % CHARS_PER_TWEET != 0) {\n tweetCount++;\n }\n\n String[] words = message.split("\\\\s");\n \n List<String> tweets = new ArrayList<>();\n int cursor = 0;\n int currentCount = 1;\n\n while (cursor < words.length) {\n StringBuilder content = new StringBuilder(CHARS_PER_TWEET);\n while (cursor < words.length\n && content.length() + words[cursor].length() + 1 < CHARS_PER_TWEET) {\n content.append(" ");\n content.append(words[cursor]);\n cursor++;\n }\n tweets.add(\n String.format("(Tweet %d/%d)%s", currentCount, tweetCount, content));\n currentCount++;\n }\n return tweets;\n }\n\n}\n</code></pre>\n<p>And a simple test method:</p>\n<pre class=\"lang-java prettyprint-override\"><code> public static void main(String[] args) {\n List<String> tweets = tweets(\n "It was the best of times, it was the worst of times, it was the age of " + \n "wisdom, it was the age of foolishness, it was the epoch of belief, it was " + \n "the epoch of incredulity, it was the season of Light, it was the season of " + \n "Darkness, it was the spring of hope, it was the winter of despair, we had " + \n "everything before us, we had nothing before us, we were all going direct " + \n "to Heaven, we were all going direct the other way—in short, the period " + \n "was so far like the present period, that some of its noisiest authorities " + \n "insisted on its being received, for good or for evil, in the superlative " + \n "degree of comparison only.");\n for (String tweet : tweets) {\n System.out.println(tweet);\n }\n }\n</code></pre>\n<p>Output:</p>\n<pre><code>(Tweet 1/5) It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch\n(Tweet 2/5) of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of\n(Tweet 3/5) hope, it was the winter of despair, we had everything before us, we had nothing before us, we were all going direct to Heaven,\n(Tweet 4/5) we were all going direct the other way—in short, the period was so far like the present period, that some of its noisiest\n(Tweet 5/5) authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only.\n</code></pre>\n<p><em>(We have been assuming the number of tweets will be less than 10, and less than 100, etc. The problem becomes quite a bit trickier if that's not the case, because the number of characters you can use per tweet depends on the number of characters in the prefix, which depends on the number of total tweets, which depends on the number of characters used per tweet. A circular dependency. So the solution might involve attempting to build with one prefix length and when the prefix length changes, start all over again with the new prefix length, and repeat until you have gone through all the input.</em></p>\n<p><em>Actually, my code for the bonus problem has a bug related to the same issue, because I'm still using the <code>CHARS_PER_TWEET</code> to calculate the number of tweets, but the tweets are sometimes shorter than that based on the word splitting. To fix that, you would need to calculate the content of all the tweets without the prefix, then go back and prepend the prefix containing the correct count. Then similarly, if the prefix length changes based on the tweet count, do it all over again.)</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T18:08:20.900",
"Id": "525537",
"Score": "0",
"body": "Wow! Thanks a lot for this answer Jeremy! It is super complete! I will try it now and will see if I am able to fix this bug that you comment on the bonus problem. You rock!!!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T04:02:11.137",
"Id": "266072",
"ParentId": "266053",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "266072",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T12:50:23.930",
"Id": "266053",
"Score": "7",
"Tags": [
"java",
"algorithm",
"strings",
"array"
],
"Title": "Create tweet threads from String in Java"
}
|
266053
|
<p>I've Never really made a game or such in python but was bored, so I tried to make a hangman game. I don't like how many if else statements I used but I can’t think of a better way to do it. Any feedback is appreciated!</p>
<pre class="lang-py prettyprint-override"><code># global varibles
SECRET_WORD = "Python".lower()
#main function
def main():
#setups Variable
CHAR_WORD = set(SECRET_WORD)
NUMBER_OF_GUESSES = 6
CORRECT_GUESSES = set()
WRONG_GUESSES = set()
# while we still have guess
while NUMBER_OF_GUESSES > 0:
# gets our next guess
current_guess = input("Guess: ").lower()
# checks if our guess is only 1 char long
if len(current_guess) != 1:
print("Please Input a Character")
# checks if we have already guessed the character
elif current_guess in CORRECT_GUESSES or current_guess in WRONG_GUESSES:
print("Already Guess that Character")
else:
#if our guess is in the word we add the the char to the correct guesses set
if current_guess in CHAR_WORD:
CORRECT_GUESSES.add(current_guess)
print(f"Correct, {NUMBER_OF_GUESSES} guesses remaining. Current Word: {blank_letters(CORRECT_GUESSES, SECRET_WORD)}\n")
else:
WRONG_GUESSES.add(current_guess)
NUMBER_OF_GUESSES -= 1
print(f"Wrong, {NUMBER_OF_GUESSES} guesses remaining. Current Word: {blank_letters(CORRECT_GUESSES, SECRET_WORD)}\n")
if CORRECT_GUESSES == CHAR_WORD:
break
# if we break out of the loop and have more than 1 guess we win
if NUMBER_OF_GUESSES != 0:
print("Congratulations, You Won")
#if we break out the loop and have 0 guess we have lost
else:
print(f"You Lost, The Word Was: {SECRET_WORD}")
#used to return a string only showing the letters we have already guessed
def blank_letters(current_Guesses, secret_Word):
return_sting = ""
#loops through all the letters
for i in range(len(secret_Word)):
# if we havent guess the current letter we replace that letter with an underscore
if secret_Word[i] not in current_Guesses:
return_sting += '_'
# if we have guessed the current word we replace it with that letter
else:
return_sting += secret_Word[i]
return return_sting
if __name__ == '__main__':
print("\n")
main()
</code></pre>
|
[] |
[
{
"body": "<p>I have split up my suggestions into various sections. Overall the code was pretty well formatted, there were some small syntax changes I would recommend as well as a bit of potential restructuring of your code.</p>\n<h2>Function Docstrings & declarations</h2>\n<p>For your <code>blank_letters()</code> function you put the docstring as a single line comment above the function. While this is mostly fine when someone is looking directly at your source code in a small program, it is better to use a properly formatted docstring to explain your functions like <a href=\"https://numpydoc.readthedocs.io/en/latest/format.html#docstring-standard\" rel=\"nofollow noreferrer\">numpystyle</a> or <a href=\"https://google.github.io/styleguide/pyguide.html#38-comments-and-docstrings\" rel=\"nofollow noreferrer\">google style</a>.</p>\n<p>Personally I prefer numpystyle docstrings that have the parameter and returns section, along with a short description. For something small like this where you <strong>know</strong> what types you are going to use I also recommend using <a href=\"https://www.python.org/dev/peps/pep-0484/\" rel=\"nofollow noreferrer\">type hints</a>, but this is more personal preference.</p>\n<p>So instead of:</p>\n<pre class=\"lang-py prettyprint-override\"><code>#used to return a string only showing the letters we have already guessed\ndef blank_letters(current_Guesses, secret_Word):\n return_sting = ""\n\n #loops through all the letters \n for i in range(len(secret_Word)):\n # if we havent guess the current letter we replace that letter with an underscore\n if secret_Word[i] not in current_Guesses:\n return_sting += '_'\n \n # if we have guessed the current word we replace it with that letter\n else:\n return_sting += secret_Word[i]\n \n return return_sting\n</code></pre>\n<p>You could do</p>\n<pre class=\"lang-py prettyprint-override\"><code>def blank_letters(current_Guesses:set, secret_Word:str) -> str:\n """Used to return a string only showing the letters we have already guessed\n\n Parameters\n ----------\n current_Guesses : set\n The set of characters the player has guessed\n\n secret_Word : str\n The word they are trying to guess\n\n Returns\n -------\n str\n A printable string that displays where guessed characters appear in word\n """\n return_sting = ""\n\n #loops through all the letters \n for i in range(len(secret_Word)):\n # if we havent guess the current letter we replace that letter with an underscore\n if secret_Word[i] not in current_Guesses:\n return_sting += '_'\n \n # if we have guessed the current word we replace it with that letter\n else:\n return_sting += secret_Word[i]\n \n return return_sting\n</code></pre>\n<p>In VSCode and other tools these style of docstrings also give you helpful hints when trying to run functions and remember parameters. If you also use VSCode there is <a href=\"https://marketplace.visualstudio.com/items?itemName=njpwerner.autodocstring\" rel=\"nofollow noreferrer\">an extension to autogenerate these</a> and similar functionality exists in pycharm etc.:\n<a href=\"https://i.stack.imgur.com/fOYD9.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fOYD9.png\" alt=\"example vs code\" /></a></p>\n<h2>Naming conventions and readability</h2>\n<p>Overall the readability was pretty good. The only thing that was a little awkward was the <code>CHAR_WORD</code> variable. There are two ways to adress this, the first is to put a little note next to where you are defining the variables:</p>\n<pre class=\"lang-py prettyprint-override\"><code>#main function\ndef main():\n # Setup Variables\n\n CHAR_WORD = set(SECRET_WORD) # Set of characters in SECRET_WORD\n NUMBER_OF_GUESSES = 6 # How many guesses the player gets\n CORRECT_GUESSES = set() # Set of characters player guessed that are in the SECRET_WORD\n WRONG_GUESSES = set() # Set of characters player guessed that are not in the SECRET_WORD\n\n ... # Rest of code\n</code></pre>\n<p>The second would be to maybe rename this to something more obvious like <code>ANSWER_CHARACTERS</code>. This just helps convey to people what the variable is for, since at first it took me a little bit of tracing to figure it out.</p>\n<p>Oh, also change <code>current_Guesses</code> in <code>blank_letters()</code> to <code>current_guesses</code>, so it matches the correct syntax along with everything else.</p>\n<h2>Restructuring/Refactoring</h2>\n<p>Since this is a single game you can take this next part with a grain of salt, since it's more preference than hard/fast rule. I personally try to make any projects I have work in two ways:</p>\n<ol>\n<li>When people just run the file</li>\n<li>When people import my project into their own project</li>\n</ol>\n<p>Since this is a game it may seem pointless to let people import it, but I personally built a mini command-line launcher for a bunch of my games I wrote a few years ago and being able to easily import that code saved me a bunch of time and it gets you practice for when you have projects that benefit from it more.</p>\n<p>In your case the easiest and fastest way to just get this up and running would be to add an optional keyword parameter to your <code>main()</code> function that allows people to specify the word (which gets rid of the global variable), and add a docstring to it. So something like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def main(SECRET_WORD:str = "python"):\n """Primary function that runs whole hangman game\n\n Parameters\n ----------\n SECRET_WORD : str, optional\n The word players need to guess, by default "python"\n """\n ... # Function code\n</code></pre>\n<p>This means if you ever want to use your game in another project you can just do:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from hangman import main # assuming your file is called `hangman.py`\n\nSECRET_WORD = "" # Put word here\n\nmain(SECRET_WORD)\n</code></pre>\n<p>You could take this further by refactoring the game into a custom <code>Game</code> class instead, or splitting up the main loop into multiple functions instead of just 1 main function but I think that would be a bit overkill for a sub-80 line project.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T06:33:46.233",
"Id": "266116",
"ParentId": "266059",
"Score": "3"
}
},
{
"body": "<h1>PEP 8</h1>\n<p>The <a href=\"https://pep8.org/\" rel=\"nofollow noreferrer\">Style Guide for Python Code (PEP8)</a> enumerates many conventions which should be followed to increase readability of the code. Please read it.</p>\n<p>PEP 8 states that variable names and function names should be in <code>snake_case</code>. <code>CAP_WORDS</code> are only for constants. <code>CHAR_WORD</code>, <code>CORRECT_GUESSES</code>, <code>WRONG_GUESSES</code>, and <code>NUMBER_OF_GUESSES</code> are variables, so should be in <code>snake_case</code>. Additionally, <code>secret_Word</code> and <code>current_Guesses</code> should not have uppercase letters.</p>\n<h1>Naming</h1>\n<p><code>return_sting</code> should probably be <code>return_string</code>.</p>\n<p><code>main()</code> is an obvious name for the main function, but it doesn't really convey any information. It would be better to name the function something like <code>hangman_game()</code>.</p>\n<h1>Global variables</h1>\n<p>Global variables are, in general, a bad idea. Avoid them when possible.</p>\n<p>You have one, which is used exactly once: passing <code>SECRET_WORD</code> into <code>main()</code>. You understand parameters, as you could have used the global variable in <code>blank_letters()</code>, but instead choose to pass <code>SECRET_WORD</code> into <code>blank_letters()</code> as a parameter. Simply reuse this pattern:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def hangman_game(secret_word: str) -> None:\n ... omitted ...\n\ndef main() -> None:\n secret_word = "Python".lower()\n print("\\n")\n hangman_game(secret_word)\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p>Here, I've used <code>main()</code> to hide the main script's variables inside the <code>main()</code> function scope, preventing them from accidentally becoming global variables.</p>\n<h1>lowercase</h1>\n<p>The game loop calls <code>input("Guess: ").lower()</code> to turn anything the user types in into lowercase. Clearly, the secret word has to be given in lower case. That is performed by the global script, and now in the <code>main()</code> code. However, if the game is given a secret word with uppercase characters, it should change that to lowercase, instead of relying on the caller properly providing a lowercase secret word:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def hangman_game(secret_word: str) -> None:\n secret_word = secret_word.lower()\n ... omitted ...\n\ndef main() -> None:\n print("\\n")\n hangman_game("Python")\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<h1>Loop like a native</h1>\n<p>(Section title from <a href=\"https://nedbatchelder.com/text/iter.html\" rel=\"nofollow noreferrer\">talk by Ned Batchelder</a>)</p>\n<p>The loop:</p>\n<pre class=\"lang-py prettyprint-override\"><code>for i in range(len(secret_Word)):\n ... never use "i" except in "secret_Word[i]" ...\n</code></pre>\n<p>is an anti-pattern. Python is a scripting language, which (indirectly) means it can be very inefficient. In your case, you are actually making it worse! Here, you are determining the length of a container, and then looping over the range of indices into that container. For each index, you then retrieve the value of in the container at that index. If a test fails (<code>secret_Word[i] not in current_Guesses</code>), you then are repeating the retrieval of the value of the container at that index (<code>return_sting += secret_Word[i]</code>).</p>\n<p>The Python designers know that iterating over containers can be inefficient, so they have given us tools to do it efficiently.</p>\n<pre class=\"lang-py prettyprint-override\"><code>for letter in secret_Word:\n ... use letter ...\n</code></pre>\n<p>The indexing is now done internally by Python. It is done exactly once per element, with the value stored in <code>letter</code>, which can be reused many times inside the loop without having to reindex into the container.</p>\n<p>Improved code (version 1):</p>\n<pre class=\"lang-py prettyprint-override\"><code>def blank_letters(current_guesses: set[str], secret_word: str) -> str:\n """return a string only showing the letters we have already guessed"""\n\n return_string = ""\n\n #loops through all the letters \n for letter in secret_word:\n # if we haven't guessed the current letter, replace that letter with an underscore\n if letter not in current_guesses:\n return_string += '_'\n \n # if we have guessed the current letter, append it unchanged\n else:\n return_string += letter\n \n return return_string\n</code></pre>\n<p>Note. If you are on Python 3.8 or earlier, you'll need to replace the type hint <code>set[str]</code> with <code>Set[str]</code>, and add <code>from typing import Set</code> at the top of the script.</p>\n<p>The above code is better, but we can still improve it. It has a common pattern. Initialize an accumulator, loop through a container, for each item, add something to the accumulator. Python has built-in syntax to support things like this. One is the <code>... if ... else ...</code> <strong><em>expression</em></strong> (not the <code>if ... elif ... else ...</code> statement):</p>\n<p>Improved code (version 2):</p>\n<pre class=\"lang-py prettyprint-override\"><code>def blank_letters(current_guesses: set[str], secret_word: str) -> str:\n """return a string only showing the letters we have already guessed"""\n\n return_string = ""\n\n #loops through all the letters \n for letter in secret_word:\n # if we haven't guessed the current letter, replace that letter with an underscore\n return_string += letter if letter in current_guesses else '_'\n \n return return_string\n</code></pre>\n<p>Now we are accumulating <code>letter</code> or <code>'_'</code> into <code>return_string</code>. So we have the structure:</p>\n<pre class=\"lang-py prettyprint-override\"><code> accumulator = ""\n for thing in container:\n accumulator += expression\n</code></pre>\n<p>This structure is easily replaced with a string join on a generator expression: <code>"".join(expression for thing in container)</code>.</p>\n<p>Improved code (version 3):</p>\n<pre class=\"lang-py prettyprint-override\"><code>def blank_letters(current_guesses: set[str], secret_word: str) -> str:\n """return a string only showing the letters we have already guessed"""\n\n # Replace unguessed letters with an underscore.\n return "".join(letter if letter in current_guesses else '_' for letter in secret_word)\n</code></pre>\n<p>I've replaced your function 7 statement function with a 1 statement function. This might cause you some worry ... so let's make sure it works.</p>\n<p>Improved code (version 4):</p>\n<pre class=\"lang-py prettyprint-override\"><code>def blank_letters(current_guesses: set[str], secret_word: str) -> str:\n """\n Return a string only showing the letters we have already guessed\n\n >>> blank_letters(set(), "hello")\n '_____'\n\n >>> blank_letters({'l', 'e'}, "hello")\n '_ell_'\n\n >>> blank_letters({'h', 'o', 'x', 'y', 'z'}, "hello")\n 'h___o'\n """\n\n # Replace unguessed letters with an underscore.\n return "".join(letter if letter in current_guesses else '_' for letter in secret_word)\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n</code></pre>\n<p>Now I've added "doctest" code into the docstring for the function. <code>doctest.testmod()</code> will read the docstrings for the functions inside the file, look for the lines which start with <code>>>></code>, and execute the code on that line. If the returned values matches the following text, the test passes.</p>\n<p>For example, if you change the last test to use <code>"Hello"</code> instead of "<code>hello"</code>, and run the code, you'd see something like:</p>\n<pre class=\"lang-none prettyprint-override\"><code>**********************************************************************\nFile "C:/Users/aneufeld/Documents/Stack Exchange/Code Review/hangman.py", line 11, in __main__.blank_letters\nFailed example:\n blank_letters({'h', 'o', 'x', 'y', 'z'}, "Hello")\nExpected:\n 'h___o'\nGot:\n '____o'\n**********************************************************************\n1 items had failures:\n 1 of 3 in __main__.blank_letters\n***Test Failed*** 1 failures.\n>>> \n</code></pre>\n<h1>State variables</h1>\n<p>You maintain two sets: <code>CORRECT_GUESSES</code> and <code>WRONG_GUESSES</code>. <code>WRONG_GUESSES</code> is only used to validate the letter hasn't been guessed before:</p>\n<pre class=\"lang-py prettyprint-override\"><code> elif current_guess in CORRECT_GUESSES or current_guess in WRONG_GUESSES:\n print("Already Guess that Character")\n</code></pre>\n<p>Consider instead simply maintaining a <code>GUESSES</code> variable. If each new guess (right or wrong) is added to <code>GUESSES</code>, then the above test simplifies to:</p>\n<pre class=\"lang-py prettyprint-override\"><code> elif current_guess in GUESSES:\n print("Already Guess that Character")\n</code></pre>\n<p>Note that, as shown in the doctest for <code>blank_letters</code>, including both incorrect guesses along with correct guesses still results in the correctly blanked secret word, you could even pass <code>GUESSES</code> instead of <code>CORRECT_GUESSES</code> to the function:</p>\n<pre class=\"lang-py prettyprint-override\"><code> print(f"... Current Word: {blank_letters(GUESSES, SECRET_WORD)}\\n")\n</code></pre>\n<p>With that change, the only place <code>CORRECT_GUESSES</code> is used is testing if all of the letters in <code>CHAR_WORD</code> have been guessed. Python has a rich set of set comparison operations, so this:</p>\n<pre class=\"lang-py prettyprint-override\"><code> if CORRECT_GUESSES == CHAR_WORD:\n break\n</code></pre>\n<p>could be replaced with:</p>\n<pre class=\"lang-py prettyprint-override\"><code> if GUESSES >= CHAR_WORD:\n break\n</code></pre>\n<p>and we've eliminated the <code>CORRECT_GUESSES</code> variable as well.</p>\n<h1>Improved Code</h1>\n<pre class=\"lang-py prettyprint-override\"><code>def hangman_game(secret_word: str, max_guesses: int = 6) -> None:\n """A console-based hangman game"""\n\n secret_word = secret_word.lower()\n \n correct_letters = set(secret_word)\n guesses_left = max_guesses\n guesses = set()\n\n while guesses_left:\n\n current_guess = input("Guess: ").lower()\n\n if len(current_guess) != 1:\n print("Please Input a Character")\n \n elif current_guess in guesses:\n print("Already Guessed that Character")\n\n else:\n guesses.add(current_guess)\n if current_guess in correct_letters:\n print(f"Correct, ", end='')\n\n else:\n guesses_left -= 1\n print(f"Wrong, ", end='')\n \n print(f"{guesses_left} guesses remaining. Current Word: {blank_letters(guesses, secret_word)}\\n")\n \n if guesses >= correct_letters:\n break\n \n if guesses_left:\n print("Congratulations, You Won")\n else:\n print(f"You Lost, The Word Was: {secret_word}")\n\ndef blank_letters(current_guesses: set[str], secret_word: str) -> str:\n """\n Return a string only showing the letters we have already guessed\n\n >>> blank_letters(set(), "hello")\n '_____'\n\n >>> blank_letters({'l', 'e'}, "hello")\n '_ell_'\n\n >>> blank_letters({'h', 'o', 'x', 'y', 'z'}, "hello")\n 'h___o'\n """\n\n # Replace unguessed letters with an underscore.\n return "".join(letter if letter in current_guesses else '_' for letter in secret_word)\n\ndef main():\n print("\\n")\n hangman_game("Python")\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n main()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T15:56:26.770",
"Id": "266139",
"ParentId": "266059",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T18:33:46.917",
"Id": "266059",
"Score": "5",
"Tags": [
"python",
"hangman"
],
"Title": "First Time Making A hangman game"
}
|
266059
|
<p>taking into account the <strong>scale2x</strong> algorithm for scaling an image to 2x.
Im using <strong>winapi</strong> in an Emulator.
When tha scale2x algorithm is used <strong>i don't see too much difference in the image scaled2x</strong> as it states in <a href="https://www.scale2x.it/algorithm" rel="nofollow noreferrer">Scale2x algorithm</a></p>
<p>My C++ class is as follows:</p>
<pre><code>typedef unsigned long pixel_32;
class Scale2x
{
pixel_32 * surface = 0, * ptr_surface = 0;
pixel_32* surface_scale2x = 0, * surface_scale2x_ptr;
int width, height;
pixel_32 B = 0, D = 0, F = 0, H = 0;
pixel_32 E0 = 0, E1 = 0, E2 = 0, E3 = 0;
pixel_32 E = 0;
void Scale()
{
if (B != H && D != F) {
E0 = D == B ? D : E;
E1 = B == F ? F : E;
E2 = D == H ? D : E;
E3 = H == F ? F : E;
}
else {
E0 = E;
E1 = E;
E2 = E;
E3 = E;
}
}
public:
Scale2x(int p_width, int p_height) : width(p_width), height(p_height)
{
surface = new pixel_32[width * height];
surface_scale2x = new pixel_32[width * height * 2*4];
surface_scale2x_ptr = surface_scale2x;
}
void SetSourceSurface(pixel_32* source_sourface)
{
memcpy(surface, source_sourface, width * height * 2);
}
void PutPixel(pixel_32 pixel)
{
*ptr_surface = pixel;
ptr_surface++;
}
void Lock()
{
ptr_surface = surface;
}
void ScaleImage()
{
ptr_surface = surface;
surface_scale2x_ptr = surface_scale2x;
int double_width = width * 2;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
E = *ptr_surface;
B = ptr_surface[-width];
H = ptr_surface[+width];
D = ptr_surface[-1];
F = ptr_surface[+1];
ptr_surface++;
Scale();
surface_scale2x_ptr[0] = E0;
surface_scale2x_ptr[1] = E1;
surface_scale2x_ptr[double_width] = E2;
surface_scale2x_ptr[double_width + 1] = E3;
surface_scale2x_ptr += 2;
}
surface_scale2x_ptr += double_width;
}
}
pixel_32 * GetScaledPtr()
{
surface_scale2x_ptr = surface_scale2x;
return surface_scale2x;
}
};
</code></pre>
<p><strong>Scale2x image:</strong>
<a href="https://i.stack.imgur.com/OHgJP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OHgJP.png" alt="enter image description here" /></a></p>
<p><strong>Raw image:</strong>
<a href="https://i.stack.imgur.com/r0idM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/r0idM.png" alt="enter image description here" /></a></p>
<p>There can be seen that the image effectivly changes, but they are my eyes that i don't see too much difference.</p>
<p>In a nutshell: is the algorithm implemented well?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T22:02:29.267",
"Id": "525506",
"Score": "0",
"body": "What are you expecting more? The top image is smoother."
}
] |
[
{
"body": "<p>There are a couple of challenges to reviewing this:</p>\n<ol>\n<li>You don’t mention what version(s) of C++ you are targeting. I will assume C++20, because that’s the current standard.</li>\n<li>You don’t provide any example of how this code is going to be used. I have no way of knowing if this interface is required, or if I can suggest a completely different interface. I will assume the interface can be completely rewritten.</li>\n<li>You don’t provide any description of requirements. For example, can I assume that <code>p_width</code> and <code>p_height</code> will never be negative? Or zero? Can I assume <code>source_sourface</code> in <code>SetSourceSurface()</code> will never be <code>nullptr</code>? I will just have to make guesses here.</li>\n<li>You don’t provide any example code or test code, so I have literally no idea how you expect this code to be used. Again, I’ll just have to make guesses.</li>\n</ol>\n<p>I will also not be checking that the algorithm is correctly implemented; this is CodeReview, so I assume it is. What you <em>should</em> do is write test cases to confirm this.</p>\n<h1>Design review</h1>\n<p>Before reviewing the actual code, I usually do a review of the overall design.</p>\n<p>The big problem with the design of this code is that it seems bizarrely over-engineered. You are implementing the “winapi scale2x algorithm”. The key word there is “algorithm”. (I don’t actually see what the Windows API has to do with anything, but whatever.) Algorithms are not classes; algorithms are functions. Just take a look at <a href=\"https://en.cppreference.com/w/cpp/algorithm\" rel=\"nofollow noreferrer\">the C++ <code><algorithm></code> library</a>; other than the execution policies (which are not algorithms) there’s literally not a single class in it. (Well, I mean, not counting neibloids.)</p>\n<p>You don’t provide any sample code to show how this class is supposed to be used, so I have to guess that common usage would be something like this:</p>\n<pre><code>// source = an array of 61440 (256x240) unsigned longs\n// draw() = function that draws an image\n\nauto scale2x = Scale2x{256, 240}; // create your scalar\nscale2x.SetSourceSurface(source); // copy the source image\nscale2x.ScaleImage(); // do the scaling\ndraw(scale2x.GetScaledPtr()); // do something with the result\n</code></pre>\n<p>This is… ugly, to say the least. Not to mention wildly inefficient. I would like to be able to write code like this:</p>\n<pre><code>auto const scaled = scale2x(source, 256, 240);\ndraw(scaled);\n</code></pre>\n<p>Or even just:</p>\n<pre><code>draw(scale2x(source, 256, 240));\n</code></pre>\n<p>It doesn’t make a lot of sense to have a class that copies the entire source image, just so it can hold on to it to scale later. Why not just scale it right away?</p>\n<p>That being said, because you haven’t given nearly enough information about your requirements, I have no idea what functions like <code>Lock()</code> and <code>PutPixel()</code> are for. They seem pointless, but for all I know, there’s some API requirement you haven’t mentioned. </p>\n<p>The first step to writing good C++ code is to stop and think… the worst programmers I’ve ever seen are the ones who hear a problem and then immediately start banging on the keyboard. No, the right way to program is to stop and think about what it is you are trying to do. What is the model of your problem? Where are the “things” (objects) and “actions” (functions) in your problem?</p>\n<p>You’re scaling images, so right away it should be obvious that you need an image class:</p>\n<pre><code>class image {};\n</code></pre>\n<p>What properties does an image have? Well, it’s got a width and a height, and a bunch of pixels:</p>\n<pre><code>using pixel = unsigned long; // okay for now, but you should really make a\n // proper pixel type\n\nclass image\n{\n using size_type = int;\n\n size_type width;\n size_type height;\n std::unique_ptr<pixel[]> pixels;\n};\n</code></pre>\n<p>Just that much already prevents a whole slew of bugs that your code is vulnerable to. For example:</p>\n<pre><code>auto img_1 = std::array<pixel_32, 32*32>{}; // a 32x32 image\nauto img_2 = std::array<pixel_32, 16*16>{}; // a 16x16 image\n\n\nauto scale2x_1 = Scale2x{32, 32}; // scaler meant for img_1, which is 32x32\nscale2x_1.SetSourceSurface(img_2); // uh-oh, accidentally used img_2, which is 16x16!\n\n// crash!\n</code></pre>\n<p>If the image itself knows its size, then you can’t possibly make this error. That’s what good C++ looks like.</p>\n<p>Once you have a proper image type, then your scale algorithm is obviously just:</p>\n<pre><code>auto scale2x(image const& src)\n{\n // create a new image of the correct size\n\n // do the scaling from src into the new image\n\n // return the new image\n}\n</code></pre>\n<p>As you can see, there’s no need for a class.</p>\n<p>So I would advise you to step back and rethink your problem, and then try to model it properly. That will not only make your code less likely to have silly or dangerous bugs, it will also make it more efficient.</p>\n<h1>Code review</h1>\n<pre><code>typedef unsigned long pixel_32;\n</code></pre>\n<p>This is the old-fashioned, C way of doing type aliases. The much better, much clearer modern version is:</p>\n<pre><code>using pixel_32 = unsigned long;\n</code></pre>\n<p>Now, I don’t know if you <em>have</em> to use <code>unsigned long</code> as the pixel type, because you didn’t give the requirements. Assuming you have a choice, then you should make a proper pixel class. At the very least you might consider using <code>std::uint_fast32_t</code> or—if you don’t care about portability—<code>std::uint32_t</code> rather than <code>unsigned long</code>, because it more clearly indicates that you really want a 32-bit type. <code>unsigned long</code> is guaranteed to be <em>at least</em> 32 bits, but it can be much, much more.</p>\n<pre><code> pixel_32 * surface = 0, * ptr_surface = 0;\n</code></pre>\n<p>There is a <em>lot</em> wrong here.</p>\n<p>First, never, ever declare multiple variables on the same line. That is terrible practice.</p>\n<p>Second, since at least C++11, we don’t use <code>0</code> as a null pointer constant; we have <code>nullptr</code>.</p>\n<p>So, so far, that means:</p>\n<pre><code> pixel_32* surface = nullptr;\n pixel_32* ptr_surface = nullptr;\n</code></pre>\n<p>But the biggest issue is the use of naked pointers at all. Naked pointers are a code smell. And the worst part is, you are using these naked pointers in absolutely the worst possible way: as owning pointers to array memory. That’s one of the worst things you can possibly do in modern C++ code.</p>\n<p>Let’s start with <code>surface</code>. This is supposed to be a dynamically-sized array of pixels, where the size of the array is determined by <code>width</code> and <code>height</code>. For dynamically-sized arrays, you <em>normally</em> use <code>std::vector</code>; that should be your first choice here. <em>However</em>… your use case is special, because the size is not a single number: it’s calculated from the width and the height. If you use <code>std::vector</code>, that means duplicated information. Also, you don’t need the array to be resizable; you size it once when constructing it, and then that’s its size forever. Given all that, you could do better than <code>std::vector<pixel_32></code> by using <code>std::unique_ptr<pixel_32[]></code> instead. It’s <em>almost</em> a drop-in replacement for <code>std::vector</code> in this case, but you do have to do a bit more manual work.</p>\n<p>Now, as for <code>ptr_surface</code>… I don’t really see any point to it. The only place it seems to have any purpose is <code>PutPixel()</code>… which is a terrible function for reasons I’ll get to later. I say just dump it.</p>\n<p>So that gives:</p>\n<pre><code> std::unique_ptr<pixel_32[]> surface = nullptr;\n</code></pre>\n<p>The same logic applies for <code>surface_scale2x</code> and <code>surface_scale2x_ptr</code>, except that <code>surface_scale2x_ptr</code> seems to be <em>completely</em> useless. <code>surface_ptr</code> is a terrible idea, but at least it has a point (a bad point, but a point). <code>surface_scale2x_ptr</code> does absolutely nothing except waste space.</p>\n<pre><code> int width, height;\n</code></pre>\n<p>Again, each of these should be on its own line. And while you’re at it, you might as well add initializers.</p>\n<pre><code> pixel_32 B = 0, D = 0, F = 0, H = 0;\n pixel_32 E0 = 0, E1 = 0, E2 = 0, E3 = 0;\n pixel_32 E = 0;\n</code></pre>\n<p>All of these are wrong. These should all be local variables to the scaling functions, not class data members. (But then, none of this should be a class at all.)</p>\n<pre><code> void Scale()\n {\n if (B != H && D != F) {\n E0 = D == B ? D : E;\n E1 = B == F ? F : E;\n E2 = D == H ? D : E;\n E3 = H == F ? F : E;\n }\n else {\n E0 = E;\n E1 = E;\n E2 = E;\n E3 = E;\n }\n }\n</code></pre>\n<p>This is a terrible function, because it uses class data members rather than parameters, which leads to spooky action at a distance, and bugs that are going to be impossible to diagnose.</p>\n<p>To fix this, the first step is to use C++ conventions, and not use uppercase variable names. Uppercase variable names are reserved for macros, and—for single-letter names only, or single-letter-and-number names—template parameter names.</p>\n<p>The second step is to make all those outside variables into local variables and return values:</p>\n<pre><code> auto Scale(pixel_32 e, pixel_32 b, pixel_32 h, pixel_32 d, pixel_32 f)\n {\n if (b != h && d != f) {\n return std::tuple{\n d == b ? d : e,\n b == f ? f : e,\n d == h ? d : e,\n h == f ? f : e\n };\n }\n else {\n return std::tuple{e, e, e, e};\n }\n }\n</code></pre>\n<p>This is still terrible, but it’s getting slightly better. Doing this allows us to mark the function as <code>constexpr</code> and <code>noexcept</code>, both of which offer potential performance gains:</p>\n<pre><code> constexpr auto Scale(pixel_32 e, pixel_32 b, pixel_32 h, pixel_32 d, pixel_32 f) noexcept\n {\n if (b != h && d != f) {\n return std::tuple{\n d == b ? d : e,\n b == f ? f : e,\n d == h ? d : e,\n h == f ? f : e\n };\n }\n else {\n return std::tuple{e, e, e, e};\n }\n }\n</code></pre>\n<p>You could also eliminate the repetition with a local lambda:</p>\n<pre><code> constexpr auto Scale(pixel_32 e, pixel_32 b, pixel_32 h, pixel_32 d, pixel_32 f) noexcept\n {\n // give these proper names, of course, or at least comments explaining\n // the pattern\n auto const x1 = [e](auto v1, auto v2) { return v1 == v2 ? v1 : e; };\n auto const x2 = [e](auto v1, auto v2) { return v1 == v2 ? v2 : e; };\n\n if (b != h && d != f)\n return std::tuple{x1(d, b), x2(b, f), x1(d, h), x2(h, f)};\n else\n return std::tuple{e, e, e, e};\n }\n</code></pre>\n<p>Let’s put this function aside for the moment, but we’ll come back to it.</p>\n<pre><code> Scale2x(int p_width, int p_height) : width(p_width), height(p_height)\n {\n surface = new pixel_32[width * height];\n surface_scale2x = new pixel_32[width * height * 2*4];\n surface_scale2x_ptr = surface_scale2x;\n }\n</code></pre>\n<p>You are using naked pointers as owning pointers, you are using <code>new</code>, but you never once use <code>delete</code> anywhere in your code. Your code leaks memory like a sieve. If you were to attempt to use this in an actual game emulator, which will likely need to run this function on the entire screen every frame, you’d probably crash the system in a matter of minutes (or, more likely, trigger the OOM manager, which will start killing processes until the emulator itself finally dies).</p>\n<p>On the other hand, if you use smart pointers or containers, you won’t have this problem.</p>\n<pre><code> void SetSourceSurface(pixel_32* source_sourface)\n {\n memcpy(surface, source_sourface, width * height * 2);\n }\n</code></pre>\n<p>Avoid low-level C library functions like <code>std::memcpy()</code> in C++. For this, you should use:</p>\n<pre><code> void SetSourceSurface(pixel_32* source_surface)\n {\n std::copy_n(source_surface, width * height * 2, surface);\n }\n</code></pre>\n<p>But overall, this is a terrible function, because there is no way to be sure that <code>source_sourface</code> (watch the spelling: “source sour face”!) points to an array of the right size. In fact, I’m pretty sure you have it wrong! Look closely. Should it not be <code>width * height</code>, and not <code>width * height * 2</code>?</p>\n<p>That’s just one sample of the many, many bugs you will have in your code because you’re not using proper types.</p>\n<pre><code> void PutPixel(pixel_32 pixel)\n {\n *ptr_surface = pixel;\n ptr_surface++;\n }\n</code></pre>\n<p>I don’t see what the point of this function is at all. There is a concept in programming called the “single responsibility principle”. Basically one “thing”—class, object, function, whatever—should have one and only one job. If the job of <code>Scale2x</code> is to scale images… then that’s its job. It is not its job to <em>also</em> be a drawing surface you can colour on. It should take an image source, scale it, and then return it, and then be done. If someone wants to doodle on either the source image or the scaled image, fine… but that’s no longer <code>Scale2x</code>’s job. (That should be the job of a dedicated image class.)</p>\n<p>In any case, this function is terrible and dangerous for other reasons, too, not least being there is no checking or control to make sure you don’t blow past the end of <code>surface</code> and start overwriting other memory.</p>\n<pre><code> void Lock()\n {\n ptr_surface = surface;\n }\n</code></pre>\n<p>All this seems to be doing is resetting the “write-to” pointer back to the start of the image. I don’t see how this is “locking” anything, in any sense.</p>\n<p>I’m going to skip <code>ScaleImage()</code> for the moment, and go to <code>GetScaledPtr()</code>:</p>\n<pre><code> pixel_32 * GetScaledPtr()\n {\n surface_scale2x_ptr = surface_scale2x;\n return surface_scale2x;\n }\n</code></pre>\n<p>The convention in C++ is to put the type modifier—the <code>*</code> for pointers, and the <code>&</code> or <code>&&</code> for references—with the type. In other words:</p>\n<ul>\n<li><code>pixel_32 *GetScaledPtr()</code> is C style.</li>\n<li><code>pixel_32* GetScaledPtr()</code> is C++ style.</li>\n<li><code>pixel_32 * GetScaledPtr()</code> is just confused.</li>\n</ul>\n<p>The first line of the function seems completely pointless.</p>\n<p>Now let’s get to the actual meat of the class, the <code>ScaleImage()</code> function:</p>\n<pre><code> void ScaleImage()\n {\n ptr_surface = surface;\n surface_scale2x_ptr = surface_scale2x;\n int double_width = width * 2;\n for (int y = 0; y < height; y++)\n {\n for (int x = 0; x < width; x++)\n {\n E = *ptr_surface;\n B = ptr_surface[-width];\n H = ptr_surface[+width];\n D = ptr_surface[-1];\n F = ptr_surface[+1];\n ptr_surface++;\n Scale();\n surface_scale2x_ptr[0] = E0;\n surface_scale2x_ptr[1] = E1;\n surface_scale2x_ptr[double_width] = E2;\n surface_scale2x_ptr[double_width + 1] = E3;\n surface_scale2x_ptr += 2;\n }\n surface_scale2x_ptr += double_width;\n }\n }\n</code></pre>\n<p>One of the main reasons this class is so bad is that it uses class data members when it <em>should</em> be using local variables. Putting all those variables—<code>B</code>, <code>D</code>, and so on—in the class is not just bad design, it’s also less efficient. If all those variables were local, they could probably be optimized to register-only variables, rather than having to read from and write to memory (slow!!!).</p>\n<p>So as a first pass, let’s make everything local that can be (and give them proper names, too), and spread things out a bit:</p>\n<pre><code> auto ScaleImage()\n {\n auto ptr_surface = surface;\n auto surface_scale2x_ptr = surface_scale2x;\n\n auto double_width = width * 2;\n\n for (auto y = 0; y < height; y++)\n {\n for (auto x = 0; x < width; x++)\n {\n auto const e = ptr_surface[0];\n auto const b = ptr_surface[-width];\n auto const h = ptr_surface[+width];\n auto const d = ptr_surface[-1];\n auto const f = ptr_surface[+1];\n\n ptr_surface++;\n\n Scale(); // we'll fix this next, ignore it for now\n\n surface_scale2x_ptr[0] = E0;\n surface_scale2x_ptr[1] = E1;\n surface_scale2x_ptr[double_width] = E2;\n surface_scale2x_ptr[double_width + 1] = E3;\n\n surface_scale2x_ptr += 2;\n }\n\n surface_scale2x_ptr += double_width;\n }\n }\n</code></pre>\n<p>Now, remember how I refactored <code>Scale()</code> above to use parameters and return values, rather than spooky action at a distance variables? That means we can write this:</p>\n<pre><code> auto ScaleImage()\n {\n auto ptr_surface = surface;\n auto surface_scale2x_ptr = surface_scale2x;\n\n auto double_width = width * 2;\n\n for (auto y = 0; y < height; y++)\n {\n for (auto x = 0; x < width; x++)\n {\n std::tie(\n surface_scale2x_ptr[0],\n surface_scale2x_ptr[1],\n surface_scale2x_ptr[double_width],\n surface_scale2x_ptr[double_width + 1]\n ) =\n Scale(\n ptr_surface[0],\n ptr_surface[-width],\n ptr_surface[+width],\n ptr_surface[-1],\n ptr_surface[+1]\n );\n\n ptr_surface++;\n\n surface_scale2x_ptr += 2;\n }\n\n surface_scale2x_ptr += double_width;\n }\n }\n</code></pre>\n<p>Hmm, I really think that big chunk of code in the middle needs to be refactored out better:</p>\n<pre><code>constexpr auto scale2x_internal_pixel_(pixel_32 const* src, pixel_32* dest_top_left, int src_width) noexcept\n{\n auto const dest_width = src_width * 2;\n\n auto const e = src[0];\n auto const b = src[-width];\n auto const h = src[+width];\n auto const d = src[-1];\n auto const f = src[+1];\n\n if (b != h && d != f) {\n dest_top_left[0] = (d == b) ? d : e;\n dest_top_left[1] = (b == f) ? f : e;\n dest_top_left[dest_width] = (d == h) ? d : e;\n dest_top_left[dest_width + 1] = (h == f) ? f : e;\n }\n else {\n dest_top_left[0] = e;\n dest_top_left[1] = e;\n dest_top_left[dest_width] = e;\n dest_top_left[dest_width + 1] = e;\n }\n}\n\nauto ScaleImage()\n{\n auto ptr_surface = surface;\n auto surface_scale2x_ptr = surface_scale2x;\n\n for (auto y = 0; y < height; y++)\n {\n for (auto x = 0; x < width; x++)\n {\n scale2x_internal_pixel_(ptr_surface, surface_scale2x_ptr, width);\n\n ptr_surface++;\n\n surface_scale2x_ptr += 2;\n }\n\n surface_scale2x_ptr += width * 2;\n }\n}\n</code></pre>\n<p>Now we can really clean up the function:</p>\n<pre><code>auto ScaleImage(pixel_32 const* p_src, int width, int height)\n{\n // create the output image\n auto dest = std::unique_ptr<pixel_32[]>{new pixel_32[(width * 2) * (height * 2)]};\n\n auto p_dest = dest.get(); // to make it easier to iterate\n\n // using auto and decltype makes the code future-proof\n for (auto y = decltype(height){0}; y < height; ++y)\n {\n for (auto x = decltype(width){0}; x < width; ++x)\n {\n scale2x_internal_pixel_(p_src, p_dest, width);\n\n ++p_src;\n\n p_dest += 2;\n }\n\n p_dest += width * 2;\n }\n\n return dest;\n}\n</code></pre>\n<p>Now that the function has been simplified, there are some obvious problems visible. I know I said I wasn’t going to review the algorithm, but some of these issues are far too basic to ignore.</p>\n<p>The scale2x algorithm takes the pixel <code>E</code> in this:</p>\n<pre class=\"lang-none prettyprint-override\"><code>A B C\nD E F\nG H I\n</code></pre>\n<p>And, using the values of <code>B</code>, <code>D</code>, <code>F</code>, and <code>H</code>, calculates four output pixels.</p>\n<p>Okay… but… what if there is no <code>B</code>, <code>D</code>, <code>F</code>, and <code>H</code>?</p>\n<p>Let’s look at your code again. Let’s just look at the loop, and assume the source width is 8 pixels and height is 6 pixels, and it’s the first iteration, so <code>x</code> and <code>y</code> are both zero:</p>\n<pre><code> ptr_surface = surface;\n\n // ... [snip] ...\n\n for (int y = 0; y < height; y++)\n {\n for (int x = 0; x < width; x++)\n {\n E = *ptr_surface;\n B = ptr_surface[-width];\n H = ptr_surface[+width];\n D = ptr_surface[-1];\n F = ptr_surface[+1];\n\n // ... [snip] ...\n }\n\n // ... [snip] ...\n }\n\n // ... [snip] ...\n</code></pre>\n<p>Now, on the very first iteration, <code>ptr_surface</code> is the same as <code>surface</code>, right? And <code>surface</code> is an array of pixels from <code>surface[0]</code> to <code>surface[width * height]</code>, which is <code>surface[8 * 6]</code> or <code>surface[48]</code>, right? So reading any pixel from <code>surface[0]</code> to <code>surface[47]</code> is okay… anything else is reading from other memory… which is bad.</p>\n<p>So on the first iteration:</p>\n<pre><code>E = surface[0];\nB = surface[-8]; // !!!\nH = surface[+8];\nD = surface[-1]; // !!!\nF = surface[+1];\n</code></pre>\n<p>See what you’ve just done?</p>\n<p>What went wrong?</p>\n<p>Well, the source image looks like this, where each square is a pixel:</p>\n<pre class=\"lang-none prettyprint-override\"><code>□□□□□□□□\n□□□□□□□□\n□□□□□□□□\n□□□□□□□□\n□□□□□□□□\n□□□□□□□□\n</code></pre>\n<p>When you are running the scale2x algorithm on the fifth pixel of the third row (for example), there are no problems:</p>\n<pre class=\"lang-none prettyprint-override\"><code>□□□□□□□□\n□□□■■■□□\n□□□■■■□□\n□□□■■■□□\n□□□□□□□□\n□□□□□□□□\n</code></pre>\n<p>But when you are running the algorithm on the fifth pixel of the <em>first</em> row…:</p>\n<pre class=\"lang-none prettyprint-override\"><code>⬚⬚⬚◇◇◇⬚⬚\n□□□■■■□□\n□□□■■■□□\n□□□□□□□□\n□□□□□□□□\n□□□□□□□□\n□□□□□□□□\n</code></pre>\n<p>The dotted squares are memory <em>outside</em> the image memory… and the diamonds are places where you are illegally reading memory.</p>\n<p>So this is what’s happening—in theory—on that first iteration:</p>\n<pre class=\"lang-none prettyprint-override\"><code>⬚⬚⬚⬚⬚⬚⬚⬚⬚⬚⬚⬚\n⬚◇◇◇⬚⬚⬚⬚⬚⬚⬚⬚\n⬚◇■■□□□□□□⬚⬚\n⬚◇■■□□□□□□⬚⬚\n⬚⬚□□□□□□□□⬚⬚\n⬚⬚□□□□□□□□⬚⬚\n⬚⬚□□□□□□□□⬚⬚\n⬚⬚□□□□□□□□⬚⬚\n⬚⬚⬚⬚⬚⬚⬚⬚⬚⬚⬚⬚\n⬚⬚⬚⬚⬚⬚⬚⬚⬚⬚⬚⬚\n</code></pre>\n<p>As you can see, the reads for <code>B</code> and <code>D</code> are reading illegal memory outside of <code>surface</code>.</p>\n<p>(This is what’s happening in reality, because memory is not actually two-dimensional.):</p>\n<pre class=\"lang-none prettyprint-override\"><code>⬚⬚⬚⬚⬚⬚⬚◇\n◇◇⬚⬚⬚⬚⬚◇\n■■□□□□□■\n■■□□□□□□\n□□□□□□□□\n□□□□□□□□\n□□□□□□□□\n□□□□□□□□\n⬚⬚⬚⬚⬚⬚⬚⬚\n⬚⬚⬚⬚⬚⬚⬚⬚\n</code></pre>\n<p>Here’s the problem: if your image is 8×6 pixels, then the only pixels you can do the full scale2x algorithm on are the ones shaded black:</p>\n<pre class=\"lang-none prettyprint-override\"><code>□□□□□□□□\n□■■■■■■□\n□■■■■■■□\n□■■■■■■□\n□■■■■■■□\n□□□□□□□□\n</code></pre>\n<p>In other words, you can’t do the naïve algorithm on the edges. For an 8×6 image, you can only do the naïve algorithm on the 6×4 bit in the middle.</p>\n<p>The algorithm description even says so, but you have to read carefully or you miss it:</p>\n<blockquote>\n<p>The image border is computed reusing the value of the nearest pixel on the border when the value of a pixel over the border is required.</p>\n</blockquote>\n<p>So what you have to do is handle the border specially. You actually need <em><strong>NINE</strong></em> different algorithms to handle all the cases:</p>\n<pre class=\"lang-none prettyprint-override\"><code>╔ ╤ ╤ ╤ ╤ ╤ ╤ ╗\n\n╟ ┼ ┼ ┼ ┼ ┼ ┼ ╢\n\n╟ ┼ ┼ ┼ ┼ ┼ ┼ ╢\n\n╟ ┼ ┼ ┼ ┼ ┼ ┼ ╢\n\n╟ ┼ ┼ ┼ ┼ ┼ ┼ ╢\n\n╚ ╧ ╧ ╧ ╧ ╧ ╧ ╝\n</code></pre>\n<p>That’s 4 special cases for the corners (“╔”, “╗”, “╚”, and “╝”), 1 for the top border (“╤”), 1 for the left border (“╟”), 1 for the right border (“╢”), 1 for the bottom border (“╧”), and 1 for the big chunk in the middle (“┼”).</p>\n<p>You also need to consider degenerate cases, like a single-pixel source image, or a source image that is 1×N or N×1 pixels (or zero pixels in any dimension, perhaps). Perhaps the most efficient solution would be to handle the top and bottom rows and the left and right columns separately, because they require special attention (probably just clamping the indices would work)… and then, if and only if the size is greater than 2 in <em>both</em> dimensions, run the algorithm on the middle pixels in one fell swoop.</p>\n<h1>Summary</h1>\n<p>Your overall design is clunky, and makes no sense. Scale2x is an algorithm, so it should be a function, not a class.</p>\n<p>You are also abusing the idea of a class, by using class data members when you should be using local variables and/or function parameters or return values. This makes your code spaghetti code, with functions accessing variables willy-nilly, which is guaranteed to lead to bugs when things get changed in one place far away from where they’re used.</p>\n<p>Your code is in dire need of some proper types. A good image class will solve 90% of the interface, efficiency, and spaghetti code problems. With a proper image class, the scale2x algorithm would naturally exist as a function:</p>\n<pre><code>// scale2x takes an image, and returns a new image that's been scaled\nauto scale2x(image const&) -> image;\n</code></pre>\n<p>A properly written image class could also have bounds-checking—even if only in debug mode—which would have caught most, if not all of the bugs that currently exist in your code.</p>\n<p>And finally, and most importantly, <em><strong>TEST YOUR CODE</strong></em>. I don’t mean just try it and see if it sorta-kinda looks like it maybe produces the right output possibly. I mean <strong>write proper tests</strong>. Use a test framework: my favourite is Boost.Test, but that’s <em>really</em> heavyweight. You could use GoogleTest or Catch2 or whatever you like. But whatever you use, <em><strong>TEST YOUR CODE</strong></em>. Test <em>everything</em> you can think of. Test what happens when you try to scale a 0×0 image (if that’s a possibility). Test what happens when you try to scale a 1×1 image. Test every possible edge case! Anyway you can imagine the algorithm failing… test it! And, of course, test the ways you expect it succeed as well. For example:</p>\n<pre><code>TEST_CASE("1x1 image should produce a 2x2 image with the single pixel repeated")\n{\n // 1x1 image whose single pixel is red\n auto const src = image{red};\n\n // 2x2 image whose pixels are all red\n auto const expected = image{\n {red, red},\n {red, red},\n };\n\n TEST(scale2x(src) == expected);\n}\n\nTEST_CASE("1x2 image")\n{\n auto const src = image{\n {red},\n {blue},\n };\n\n auto const expected = image{\n {red, red},\n {red, red},\n {blue, blue},\n {blue, blue},\n };\n\n TEST(scale2x(src) == expected);\n}\n\nTEST_CASE("example on algorithm description page")\n{\n // the example page gives you a before and after, so copy both those\n // images' data, and test!\n}\n\n// and so on...\n</code></pre>\n<p>A proper image class + testing will give you the confidence that your code is implemented well.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T01:22:43.577",
"Id": "266067",
"ParentId": "266060",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T18:38:16.757",
"Id": "266060",
"Score": "1",
"Tags": [
"c++",
"winapi"
],
"Title": "C++ winapi scale2x algorithm. Is it well implemented?"
}
|
266060
|
<p>I am new to web development and would like to get feedback on a JavaScript library that automatically finds and replaces text on a webpage using the <a href="https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver" rel="nofollow noreferrer">MutationObserver</a> interface.</p>
<p>EDIT: Seeing that this has gone a week unanswered I've cut out non-essential code to reduce the line count from 300 to more manageable 150.</p>
<p>The <a href="https://github.com/DanielZTing/TextObserver/blob/master/README.md" rel="nofollow noreferrer">README</a> may also be helpful in understanding how it is meant to be used. My main questions are:</p>
<ul>
<li>As you might have inferred from the heavy use of private variables, I have a Java background. Is such usage of OOP/encapsulation idiomatic in JS?</li>
<li>To prevent replacements made by one observer's callback from alerting other observers and creating an infinite "ping-pong" effect, I store every created <code>TextObserver</code> in a static class variable and deactivate them before running the callback. Is this good practice? It feels like a <a href="https://en.wikipedia.org/wiki/God_object" rel="nofollow noreferrer">God object</a>.</li>
<li>Is there anything else I should do to make this more fit for use as a library? (<a href="https://github.com/umdjs/umd" rel="nofollow noreferrer">UMD?</a>) And is the README understandable? (If it is appropriate to ask for reviews on documentation here.)</li>
</ul>
<pre class="lang-javascript prettyprint-override"><code>class TextObserver {
#target;
#callback;
#observer;
// Sometimes, MutationRecords of type 'childList' have added nodes with overlapping subtrees
// Nodes can also be removed and reattached from one parent to another
// This can cause resource usage to explode with "recursive" replacements, e.g. expands -> physically expands
// The processed set ensures that each added node is only processed once so the above doesn't happen
#processed = new Set();
// Keep track of all created observers to prevent infinite callbacks
static #observers = new Set();
// Use static read-only properties as class constants
static get #IGNORED_NODES() {
// Node types that implement the CharacterData interface but are not relevant or visible to the user
return [Node.CDATA_SECTION_NODE, Node.PROCESSING_INSTRUCTION_NODE, Node.COMMENT_NODE];
}
static get #IGNORED_TAGS() {
// Text nodes that are not front-facing content
return ['SCRIPT', 'STYLE', 'NOSCRIPT'];
}
static get #CONFIG() {
return {
subtree: true,
childList: true,
characterData: true,
characterDataOldValue: true,
};
}
constructor(callback, target = document, processExisting = true) {
this.#callback = callback;
// If target is entire document, manually process <title> and skip the rest of the <head>
// Processing the <head> can increase runtime by a factor of two
if (target === document) {
document.title = callback(document.title);
// Sometimes <body> may be missing, like when viewing an .SVG file in the browser
if (document.body !== null) {
target = document.body;
} else {
console.warn('Document body does not exist, exiting...');
return;
}
}
this.#target = target;
if (processExisting) {
TextObserver.#flushAndSleepDuring(() => this.#processNodes(target));
}
const observer = new MutationObserver(mutations => {
const records = [];
for (const textObserver of TextObserver.#observers) {
// This ternary is why this section does not use flushAndSleepDuring
// It allows the nice-to-have property of callbacks being processed in the order they were declared
records.push(textObserver === this ? mutations : textObserver.#observer.takeRecords());
textObserver.#observer.disconnect();
}
let i = 0;
for (const textObserver of TextObserver.#observers) {
textObserver.#observerCallback(records[i]);
i++;
}
TextObserver.#observers.forEach(textObserver => textObserver.#observer.observe(textObserver.#target, TextObserver.#CONFIG));
});
observer.observe(target, TextObserver.#CONFIG);
this.#observer = observer;
TextObserver.#observers.add(this);
}
#observerCallback(mutations) {
for (const mutation of mutations) {
const target = mutation.target;
switch (mutation.type) {
case 'childList':
for (const node of mutation.addedNodes) {
if (node.nodeType === Node.TEXT_NODE) {
if (this.#valid(node) && !this.#processed.has(node)) {
node.nodeValue = this.#callback(node.nodeValue);
this.#processed.add(node);
}
} else if (!TextObserver.#IGNORED_NODES.includes(node.nodeType)) {
// If added node is not text, process subtree
this.#processNodes(node);
}
}
break;
case 'characterData':
if (this.#valid(target) && target.nodeValue !== mutation.oldValue) {
target.nodeValue = this.#callback(target.nodeValue);
this.#processed.add(target);
}
break;
}
}
}
static #flushAndSleepDuring(callback) {
// Disconnect all other observers to prevent infinite callbacks
const records = [];
for (const textObserver of TextObserver.#observers) {
// Collect pending mutation notifications
records.push(textObserver.#observer.takeRecords());
textObserver.#observer.disconnect();
}
// This is in its own separate loop from the above because we want to disconnect everything before proceeding
// Otherwise, the mutations in the callback may trigger the other observers
let i = 0;
for (const textObserver of TextObserver.#observers) {
textObserver.#observerCallback(records[i]);
i++;
}
callback();
TextObserver.#observers.forEach(textObserver => textObserver.#observer.observe(textObserver.#target, TextObserver.#CONFIG));
}
#valid(node) {
return (
// Sometimes the node is removed from the document before we can process it, so check for valid parent
node.parentNode !== null
&& !TextObserver.#IGNORED_NODES.includes(node.nodeType)
&& !TextObserver.#IGNORED_TAGS.includes(node.parentNode.tagName)
// Ignore contentEditable elements as touching them messes up the cursor position
&& !node.parentNode.isContentEditable
// HACK: workaround to avoid breaking icon fonts
&& !window.getComputedStyle(node.parentNode).getPropertyValue('font-family').toUpperCase().includes('ICON')
);
}
#processNodes(root) {
// Process valid Text nodes
const nodes = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, { acceptNode: node => (
this.#valid(node) && !this.#processed.has(node)) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT
});
while (nodes.nextNode()) {
nodes.currentNode.nodeValue = this.#callback(nodes.currentNode.nodeValue);
this.#processed.add(nodes.currentNode);
}
}
}
// A good page to try this out on would be https://en.wikipedia.org/wiki/Heck
const badWordFilter = new TextObserver(text => text.replaceAll(/heck/gi, 'h*ck'));
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T19:11:01.767",
"Id": "266062",
"Score": "4",
"Tags": [
"javascript",
"beginner",
"html",
"dom"
],
"Title": "Find and replace text in a webpage with JavaScript"
}
|
266062
|
<p>The problem is that we have an unsolved sudoku board, and we want to validate it, we need to check each column, row and sub-square.</p>
<p>Here we represent a empty cell with -1.</p>
<p>My idea was to create a multi-threaded solution to this problem, where we deal with each case.</p>
<p>I didn't know how to pool threads before this problem, so it's probably not 100% ...</p>
<p>In "check task", we have type 0: columns, type 1: rows and type 2: squares.</p>
<p>The rest of the solution is basically just messing around with the pthread library, and it seems to work.</p>
<p>Could it be better in any way?</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#define threadNum 4
#define squareUnit 2
#define square 4
int** input;
int isValid = 1;
//
// threadpool for col calculations
//
typedef struct Task {
int** input;
int type;
int index;
int subX;
int subY;
} Task;
Task taskQueue[3*square];
int taskCount = 0;
pthread_mutex_t mutexQueue;
pthread_cond_t condQueue;
void checkTask(Task* task){
int** input = task -> input;
int available[] = {0,0,0,0,0,0,0,0,0,0};
int type = task -> type;
if(type == 0){
int index = task -> index;
for(int i = 0; i < square; i++){
if(input[i][index] == -1){
continue;
}
else{
available[input[i][index]]++;
if(available[input[i][index]] > 1){
isValid = 0;
printf("col index: %d fails\n", index);
return;
}
}
}
printf("col index: %d passes\n", index);
}
if(type == 1){
int index = task -> index;
for(int i = 0; i < square; i++){
if(input[index][i] == -1){
continue;
}
else{
available[input[index][i]]++;
if(available[input[index][i]] > 1){
isValid = 0;
printf("row index: %d fails\n", index);
return;
}
}
}
printf("row index: %d passes\n", index);
}
if(type == 2){
int subX = task -> subX;
int subY = task -> subY;
for(int i = subX; i < subX + squareUnit; i++){
for(int j = subY; j < subY + squareUnit; j++){
if(input[i][j] == -1){
continue;
}
else{
available[input[i][j]]++;
if(available[input[i][j]] > 1){
isValid = 0;
printf("square: %d %d fails\n", subX, subY);
return;
}
}
}
}
printf("square: %d %d passes\n", subX, subY);
}
return;
}
void* startThread(void* args){
while(1){
Task task;
pthread_mutex_lock(&mutexQueue);
task = taskQueue[0];
int i;
for(i = 0; i < taskCount; i++){
taskQueue[i] = taskQueue[i + 1];
}
taskCount--;
pthread_mutex_unlock(&mutexQueue);
checkTask(&task);
if(taskCount == 0){
break;
}
}
}
void submitTask(Task task){
pthread_mutex_lock(&mutexQueue);
taskQueue[taskCount] = task;
taskCount++;
pthread_mutex_unlock(&mutexQueue);
pthread_cond_signal(&condQueue);
}
int main(void){
//
// input example
//
int arrayIn[][square] = {
{1,-1,-1,2},
{2,-1,1,-1},
{0,3,-1,-1},
{1,-1,-1,0}
};
input = malloc(square * sizeof(int*));
for(int i = 0; i < square; i++){
input[i] = malloc(square * sizeof(int));
for(int j = 0; j < square; j++){
input[i][j] = arrayIn[i][j];
}
}
//
// execute threadpool
//
pthread_t th_col[threadNum];
pthread_mutex_init(&mutexQueue, NULL);
pthread_cond_init(&condQueue, NULL);
for(int i = 0; i < threadNum; i++){
if(pthread_create(&th_col[i], NULL, &startThread, NULL) != 0){
printf("failed to create thread\n");
}
}
for(int i = 0; i < square; i++){
Task t = {
.input = input,
.type = 0,
.index = i,
.subX = -1,
.subY = -1
};
submitTask(t);
}
for(int i = 0; i < square; i++){
Task t = {
.input = input,
.type = 1,
.index = i,
.subX = -1,
.subY = -1
};
submitTask(t);
}
int subX = 0;
int subY = 0;
for(int i = 0; i < squareUnit; i++){
subY = 0;
for(int j = 0; j < squareUnit; j++){
Task t = {
.input = input,
.type = 2,
.index = -1,
.subX = subX,
.subY = subY
};
submitTask(t);
subY = subY + squareUnit;
}
subX = subX + squareUnit;
}
for(int i = 0; i < threadNum; i++){
if(pthread_join(th_col[i], NULL) != 0){
printf("failed to join thread\n");
}
}
pthread_mutex_destroy(&mutexQueue);
pthread_cond_destroy(&condQueue);
//
// output result
//
switch(isValid){
case 0:
printf("does not pass\n");
break;
case 1:
printf("passes\n");
break;
}
free(input);
return 1;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T01:59:04.597",
"Id": "525510",
"Score": "0",
"body": "I'm not really clear what validating an empty sudoku would entail. I can understand validating a proposed solution, but not an empty board. `arrayIn` is a 4x4 matrix with negative numbers that appears to have no relation to sudoku. Maybe I'm missing something obvious."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T09:19:47.353",
"Id": "525517",
"Score": "0",
"body": "It is explained much better [here](https://leetcode.com/problems/valid-sudoku/). '-1' is code here for \"empty\" position."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T14:22:25.287",
"Id": "525528",
"Score": "0",
"body": "Thanks for the link. That looks like a normal 9x9 board only, although I understand what you mean by validating a partial board. This is a subprocedure of solving Sudoku with backtracking where you ensure a move made is legal before continuing to child positions. Does the code here solve this LC problem? Did you benchmark it against single-threaded to ensure you're actually getting a speedup?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T17:42:38.597",
"Id": "525536",
"Score": "1",
"body": "Yep it is correct, haven't tried benchmarking it yet though ..."
}
] |
[
{
"body": "<p>I usually like to rewrite symbols like</p>\n<pre><code>#define threadNum 4\n#define squareUnit 2\n#define square 4\n</code></pre>\n<p>as <code>static const int</code>s, since that makes the type easier to see.</p>\n<p>Since this is a single-translation-unit program, all of your functions other than <code>main</code> can also be <code>static</code>.</p>\n<p>You should be using C99 or later, in which case</p>\n<pre><code>int i;\nfor(i = 0; i < taskCount; i++){\n</code></pre>\n<p>would be</p>\n<pre><code>for (int i = 0; i < taskCount; i++) {\n</code></pre>\n<p>This declaration:</p>\n<pre><code>int arrayIn[][square] = {\n</code></pre>\n<p>seems a little risky. If you need for your array to be square, then I would expect no implicit dimensions and instead</p>\n<pre><code>int arrayIn[square][square] = {\n</code></pre>\n<p>which would catch any accidents around the size of the outer dimension.</p>\n<p>Rather than a <code>switch</code> here:</p>\n<pre><code> switch(isValid){\n case 0:\n printf("does not pass\\n");\n break;\n case 1:\n printf("passes\\n");\n break;\n }\n</code></pre>\n<p>I would expect a simple</p>\n<pre><code>puts(isValid ? "passes" : "does not pass");\n</code></pre>\n<p>You have a large block of nearly-duplicated code between types 0 and 1. The common element on the inside can be factored out into a function that accepts <code>i</code>, <code>j</code>, <code>available</code>, and the row/column title string.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T19:50:37.790",
"Id": "266107",
"ParentId": "266063",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "266107",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-14T21:27:53.293",
"Id": "266063",
"Score": "1",
"Tags": [
"c",
"multithreading",
"sudoku"
],
"Title": "Validate Empty Sudoku: Multi-Threaded Solution"
}
|
266063
|
<h2>Function:</h2>
<p>Outputs daily and weekly dose totals with means for time between doses and dose amount.</p>
<h3>Code:</h3>
<pre class="lang-py prettyprint-override"><code>
from decimal import Decimal
from dataclasses import dataclass
from typing import List, Dict, Iterable, Collection
UNIT = 'u'
SUBSTANCE = 'sub'
@dataclass
class DayDoseMean:
day: str
time_dose: Dict[float, float]
@property
def doses(self) -> List[Decimal]:
return [
round(
Decimal(i), 1
) for i in self.time_dose.values()
]
@property
def times(self) -> List[Decimal]:
return [
round(
Decimal(i), 2
) for i in self.time_dose.keys()
]
@property
def daily_dose(self) -> Decimal:
return sum(i for i in self.doses)
@property
def mean(self) -> Decimal:
return self.daily_dose / len(self.doses)
@property
def diff(self) -> Iterable[Decimal]:
return (
abs(
self.times[i] - self.times[i+1]
) for i in range(len(self.times) - 1)
)
@property
def time_mean(self) -> Decimal:
return sum(self.diff) / len(self.times)
@property
def prnt(self):
return (
f'{self.day}{":":4}'
f'{self.daily_dose}{UNIT:4}'
f'{self.mean}{self.time_mean:7}'
)
@dataclass
class WeekDoseMean:
week_dose_mean: Collection[DayDoseMean]
@property
def weekly_dose(self) -> Decimal:
return sum(
i.daily_dose
for i in self.week_dose_mean
)
@property
def weekly_mean(self) -> Decimal:
return round(
sum(
i.mean
for i in self.week_dose_mean
) / 7, 1
)
@property
def weekly_time_mean(self) -> Decimal:
return round(
sum(
i.time_mean
for i in self.week_dose_mean
) / 7, 2
)
@property
def echo(self):
print(
f'\n--------------------------\n'
f'{"Day":7}{SUBSTANCE:7}'
f'{"dM":6}tM\n'
f'--------------------------'
)
print(
'\n'
.join(
i.prnt
for i in self.week_dose_mean
)
)
print(
f'--------------------------\n'
f'Weekly {"dM":4} -> mean: '
f'{self.weekly_mean}\n'
f'Weekly {"tM":4} -> mean: '
f'{self.weekly_time_mean}\n'
f'--------------------------\n'
f'Weekly dose -> {SUBSTANCE}:'
f'{self.weekly_dose}{UNIT}\n'
f'--------------------------'
)
def main():
week_date = WeekDoseMean(
week_dose_mean=(
DayDoseMean(
day='Mon',
time_dose={
12: 1,
13: 1
}
),
DayDoseMean(
day='Tue',
time_dose={
12: 1,
13: 1
}
),
DayDoseMean(
day='Wed',
time_dose={
12: 1,
13: 1
}
),
DayDoseMean(
day='Thu',
time_dose={
12: 1,
13: 1
}
),
DayDoseMean(
day='Fri',
time_dose={
12: 1,
13: 1
}
),
DayDoseMean(
day='Sat',
time_dose={
12: 1,
13: 1
}
),
DayDoseMean(
day='Sun',
time_dose={
12: 2,
14: 2
}
)
)
)
week_date.echo
if __name__ == '__main__':
main()
</code></pre>
<h3>Output:</h3>
<pre><code>
--------------------------
Day phen dM tM
--------------------------
Mon: 2.0u 1.0 0.50
Tue: 2.0u 1.0 0.50
Wed: 2.0u 1.0 0.50
Thu: 2.0u 1.0 0.50
Fri: 2.0u 1.0 0.50
Sat: 2.0u 1.0 0.50
Sun: 4.0u 2.0 1.00
--------------------------
Weekly dM -> mean: 1.1
Weekly tM -> mean: 0.57
--------------------------
Weekly dose -> sub:16.0u
--------------------------
</code></pre>
<h3>Help:</h3>
<p>I don’t know if I understand classes and OOP yet.</p>
<ul>
<li>Am I correctly using classes?</li>
<li>Is this OOP?</li>
<li>Please suggest improvements</li>
</ul>
<h4>Background:</h4>
<p>I wrote this script a long time ago after learning many things about classes and data structures from a very kind member on here.</p>
<p>I was trying to learn OOP and classes.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T14:04:20.627",
"Id": "525526",
"Score": "0",
"body": "What is the \"real\" way that data are going to be entered? Surely they won't be hard-coded. Will you have datetimes, rather than strictly days-of-the-week?"
}
] |
[
{
"body": "<blockquote>\n<p>Am I correctly using classes?</p>\n</blockquote>\n<p>Very vaguely yes, though there's always room for improvement.</p>\n<blockquote>\n<p>Is this OOP?</p>\n</blockquote>\n<p>Yes!</p>\n<blockquote>\n<p>Please suggest improvements</p>\n</blockquote>\n<p><code>time_dose</code> has as its key type <code>float</code>, which is not a good representation of a time in Python (generally speaking). <code>datetime.time</code> should be used instead. Since you're running these values through a mean, maybe a float would be justified, but</p>\n<ol>\n<li>making it clear that this is used as a time with a <code>NewType</code> type alias, and</li>\n<li>using the standard seconds-since-1970-epoch "Unix" timestamp format rather than what seems to be fractional-hours-after-midnight.</li>\n</ol>\n<p><code>DayDoseMean</code> is not a great name, since the class itself doesn't represent a mean, only one of its members; so perhaps call it <code>DayDoses</code>. Likewise with <code>WeekDoses</code>.</p>\n<p>Don't abbreviate <code>print</code> to <code>prnt</code>.</p>\n<p>This is a little advanced, but in CPython a function like this:</p>\n<pre><code>@property\ndef diff(self) -> Iterable[Decimal]:\n return (\n abs(\n self.times[i] - self.times[i+1]\n ) for i in range(len(self.times) - 1)\n )\n</code></pre>\n<p>will, in bytecode, produce a second hidden generator function, whereas a <code>for/yield</code> will not. I only learned this recently, and I encourage you to use the disassembly tool to see for yourself the difference.</p>\n<p><code>{":":4}</code> and <code>{UNIT:4}</code> are odd. You're putting a delimiter in a fixed-width field. That's probably not what you want. Instead, put your <code>self.day</code>, <code>daily_dose</code> etc. in fixed-width fields, since they're the strings whose length is subject to variance.</p>\n<p><code>sum(i for i in self.doses)</code> can just be <code>sum(self.doses)</code>.</p>\n<p>You're scattering <code>round</code> calls throughout your analysis code. This does not seem like a good idea. If it's for the purposes of formatting, don't do it where it is now, and just add a fixed-precision specifier in your interpolated strings, like</p>\n<pre><code>f'{self.weekly_mean:.1f}\\n'\n</code></pre>\n<p><code>DayDoseMean.prnt</code> and <code>WeekDoseMean.echo</code> are both properties; the first correctly returns a value and the second doesn't. To fix the second, either:</p>\n<ul>\n<li>Keep it as a property but return a string; or</li>\n<li>Remove the property decorator and represent it as a normal method.</li>\n</ul>\n<p>Instead of passing days-of-week as strings, use integers. When it comes time to print use <a href=\"https://docs.python.org/3/library/calendar.html#calendar.day_name\" rel=\"nofollow noreferrer\">https://docs.python.org/3/library/calendar.html#calendar.day_name</a> .</p>\n<h2>Pandas</h2>\n<p>For something very different: Pandas is a better fit for this kind of data-munging and analysis. Advantages are that it's a little more concise, probably runs faster for large datasets, and more expressive in terms of grouping semantics.</p>\n<ul>\n<li>Treat datetimes as first-class and weekday names as second-class</li>\n<li>Are you sure that <code>/ len(self.times)</code> is what you want to be doing? Given <code>n</code> times in a day, there are <code>n-1</code> differential values.</li>\n<li>What do you want to happen for a series of datetimes that spans over one week? Do you still want to group by weekday, or do you simply want to group by day? I've shown the latter, but your example data do not make this clear. In your sample data, using a dictionary of weekday names to doses is not particularly representative of reality. What if your data span eight days? Probably this should just be a sequence of datetimes.</li>\n<li>Don't round anywhere except at the output formatting</li>\n</ul>\n<h2>Suggested</h2>\n<pre><code>import numpy as np\nfrom datetime import datetime\n\nimport pandas as pd\n\nSUBSTANCE = 'phen'\n\n\ndef group_by_day(doses: pd.DataFrame) -> pd.DataFrame:\n # Fractional hours after midnight\n doses['hour'] = (\n doses.index - doses.index.date.astype('datetime64[ns]')\n ) / np.timedelta64(1, 'h')\n\n # Get dose sum, dose mean, and time-differential grouped by day (not weekday)\n by_day = (\n doses.groupby(by=doses.index.date)\n .agg({\n SUBSTANCE: ('sum', 'mean'),\n 'hour': lambda hour: hour.diff().mean(),\n })\n )\n by_day.columns = (SUBSTANCE, 'dM', 'tM')\n by_day.insert(\n loc=0, column='weekday',\n value=by_day.index.astype('datetime64[ns]').strftime('%a'),\n )\n return by_day\n\n\ndef summarize(by_day: pd.DataFrame) -> None:\n print(\n f'\\nWeekly dM mean: {by_day.dM.mean():.1f}'\n f'\\nWeekly tM mean: {by_day.tM.mean():.2f}'\n f'\\nWeekly dose: {SUBSTANCE}: {by_day[SUBSTANCE].sum():.1f}'\n )\n\n\ndef main():\n # All data, entered flat (not grouped by weekday), plain datetimes\n times = (\n datetime(2021, 8, 9, 12, 0), datetime(2021, 8, 9, 13, 0),\n datetime(2021, 8, 10, 12, 0), datetime(2021, 8, 10, 13, 0),\n datetime(2021, 8, 11, 12, 0), datetime(2021, 8, 11, 13, 0),\n datetime(2021, 8, 12, 12, 0), datetime(2021, 8, 12, 13, 0),\n datetime(2021, 8, 13, 12, 0), datetime(2021, 8, 13, 13, 0),\n datetime(2021, 8, 14, 12, 0), datetime(2021, 8, 14, 13, 0),\n datetime(2021, 8, 15, 12, 0), datetime(2021, 8, 15, 14, 0),\n )\n doses = pd.DataFrame(\n (\n 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,\n 1.0, 1.0, 1.0, 1.0, 2.0, 2.0,\n ),\n columns=(SUBSTANCE,), index=times,\n )\n\n by_day = group_by_day(doses)\n print(by_day)\n summarize(by_day)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<h2>Output</h2>\n<pre class=\"lang-none prettyprint-override\"><code> weekday phen dM tM\n2021-08-09 Mon 2.0 1.0 1.0\n2021-08-10 Tue 2.0 1.0 1.0\n2021-08-11 Wed 2.0 1.0 1.0\n2021-08-12 Thu 2.0 1.0 1.0\n2021-08-13 Fri 2.0 1.0 1.0\n2021-08-14 Sat 2.0 1.0 1.0\n2021-08-15 Sun 4.0 2.0 2.0\n\nWeekly dM mean: 1.1\nWeekly tM mean: 1.14\nWeekly dose: phen: 16.0\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-15T11:31:06.037",
"Id": "528530",
"Score": "1",
"body": "Sorry for the late response, I’ve been away for a while, thanks for the knowledge will use this"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T03:40:46.950",
"Id": "266071",
"ParentId": "266069",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "266071",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T01:41:51.063",
"Id": "266069",
"Score": "3",
"Tags": [
"python-3.x",
"object-oriented",
"classes"
],
"Title": "Weekly Dose tracker with time and dose mean"
}
|
266069
|
<p>I am brand new to programming in C. I am following along with the book "The C Programming Language, Second Edition." I am making my own modifications to the example code presented in the book as I go along. Anyway I am posting my code here for review because I want to make sure I am off to a good start. There a few things in particular that I want to make sure that I am doing right as to not develop any future bad habits:</p>
<ol>
<li><p>I would like to make sure I am adhering to the C standards. Based on my research I found that the current and most recent standard for C is C17 or ISO/IEC 9899:2018, please correct me if I am wrong. As a result I have been compiling the code with the following parameters: <code>gcc -Wall -pedantic-errors -std=c17 source.c</code> Is this a good practice?</p>
</li>
<li><p>I know I am a beginner but I would like to make sure that I am doing even the simplest things in a clean and efficient way.</p>
</li>
</ol>
<p>So if I can get a review on this code sample, that would be great.</p>
<pre><code>/* This program uses the formula C = (5/9)(F-32) to print a table of Farenheit
* temperatures and their Centigrade or Celsius equivalents. Adapted from:
* Kernighan, B. W., & Ritchie, D. M. (1988). The C programming language. */
#include <stdio.h>
/* Print Fahrenheit-Celsius table for Fahrenheit = 0, 20, ..., 300. */
int main(void)
{
float fahr, celsius;
int lower, upper, step;
lower = 0; /* Lower limit of temperature table. */
upper = 300; /* Upper limit. */
step = 20; /* Step size. */
printf("Fahrenheit to Celsius\n"); /* Table header */
printf("%3s %6s\n", "F", "C"); /* Temperature label */
fahr = lower;
while (fahr <= upper) {
celsius = (5.0/9.0) * (fahr-32.0);
printf("%3.0f %6.1f\n", fahr, celsius);
fahr = fahr + step;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T07:55:58.700",
"Id": "525513",
"Score": "1",
"body": "I don't have a copy of K&R ready, but how much of the code provided is theirs and how much of it is yours?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T11:59:40.447",
"Id": "525570",
"Score": "0",
"body": "In a real application you'd generate all these values at compile time and store them in a read-only array. But if you are an absolute beginner, you'll need to study arrays and loops first :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T17:58:29.283",
"Id": "525597",
"Score": "2",
"body": "I have rolled back Rev 4 → 3. Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T18:03:51.067",
"Id": "525601",
"Score": "1",
"body": "@Lundin Really? I don't think it's possible to claim that a compile-time table is desirable over a simple loop in all cases. It depends on what you're optimizing for and what architecture you're on. The runtime-generated loop is much simpler and easier to maintain."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T06:21:17.910",
"Id": "525632",
"Score": "0",
"body": "@Reinderien There's always exceptions, but generally, on almost all systems from low end microcontrollers to high end 64 bit CPUs, execution time is much more valuable than read-only memory."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T04:09:42.837",
"Id": "525722",
"Score": "0",
"body": "@Lundin I've ran out of memory often enough on a microcontroller to know that wasn't always true, but on modern systems (even embedded) there's usually a bit more (EEP)ROM available. It's all a matter of how it's used in the field. Considering this is more of an exercise, it's good for OP to be aware of both possibilities and get experience with both."
}
] |
[
{
"body": "<blockquote>\n<p>I want to make sure I am off to a good start.</p>\n</blockquote>\n<p><strong><code>float</code> vs <code>double</code></strong></p>\n<p>Save <code>float</code> for cases when serious reduced memory needed or when performance has compelled the use of narrow floating point, else use <code>double</code> as the go-to floating point type.</p>\n<p><strong>Units</strong></p>\n<p>300 what?<br />\nPhysical units deserve clarity, perhaps a comment, in code. Be clear or <a href=\"https://en.wikipedia.org/wiki/Mars_Climate_Orbiter#Cause_of_failure\" rel=\"nofollow noreferrer\">oops!</a>.</p>\n<pre><code>// upper = 300; /* Upper limit. */\nupper = 300 /* F */; /* Upper limit. */\n</code></pre>\n<hr />\n<blockquote>\n<p>make sure I am adhering to the C standards.</p>\n</blockquote>\n<p><strong>Warnings</strong></p>\n<p>Using a modern compiler with many, if not all, warnings enabled is a <em>good</em> thing. Maybe add <code>-Wetra</code>.</p>\n<hr />\n<blockquote>\n<p>make sure that I am doing even the simplest things in a clean and efficient way.</p>\n</blockquote>\n<p><strong>Overall</strong></p>\n<p>Code looks very clean and mostly efficient.</p>\n<p><strong>Unnecessary FP mixed operations</strong></p>\n<p>Notice by using <code>float</code> objects, yet <code>double</code> constants, code is like below incurring up and down FP conversions.</p>\n<pre><code>celsius = (float)((5.0/9.0) * ((double)fahr-32.0));\nprintf("%3.0f %6.1f\\n", (double)fahr, (double)celsius);\n</code></pre>\n<p>If wanting to stay with <code>float</code>, use <code>float</code> constants</p>\n<pre><code>celsius = (5.0f/9.0f) * (fahr-32.0f);\n</code></pre>\n<hr />\n<p><strong>Idea: abstract formatting</strong></p>\n<pre><code>#define F_WIDTH1 3\n#define C_WIDTH2 6\n\nprintf("%*s %*s\\n", F_WIDTH, "F", C_WIDTH, "C");\n...\n printf("%*.0f %*.1f\\n", F_WIDTH, fahr, C_WIDTH, celsius);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T20:18:46.967",
"Id": "525539",
"Score": "0",
"body": "This is great thank you. I am definitely going to implement and look further into your suggestions. I understand the float vs double suggestion but need to do further research into abstract formatting as I am not yet familiar with that one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T06:58:47.833",
"Id": "525728",
"Score": "1",
"body": "The float vs double constant problem is inherited from K&R. Your review makes several valid points but what you are actually reviewing is the verbatim of K&R. K&R apparently didn't know the difference between float and double either... it's such a harmful book."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T12:43:45.303",
"Id": "525751",
"Score": "0",
"body": "@Lundin In K&R defense, at the time, all FP was typically very expensive vs. integer math. Somewhat true today, but often a a greatly lesser degree. ( I still use `float` primarily on embedded task lacking HW FP.) Benefits of `float` .v `double` _were_ more significant. Agree K&R as a C primer today is at best: questionable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T13:21:18.093",
"Id": "525757",
"Score": "0",
"body": "Is there a more modern and relevant book you guys recommend?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T13:36:11.547",
"Id": "525758",
"Score": "1",
"body": "@drebrb Although not a good primer, access to the C spec (or a draft of it) is very useful as it is definitive."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T14:06:24.343",
"Id": "525761",
"Score": "0",
"body": "@chux-ReinstateMonica are you referring to iso9899:2017?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T14:34:49.090",
"Id": "525763",
"Score": "1",
"body": "@drebrb Yes, Also see [latest ANSI C](https://stackoverflow.com/a/11504332/2410359) and other via various web searches."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T17:27:26.073",
"Id": "266082",
"ParentId": "266070",
"Score": "3"
}
},
{
"body": "<ul>\n<li>It's great that you're using C17.</li>\n<li>Your <code>gcc</code> mostly looks sane, though I would add <code>-ggdb</code> and start learning about <code>gdb</code>.</li>\n<li>Since you are using above-C99, I would rewrite</li>\n</ul>\n<pre><code> float fahr, celsius;\n int lower, upper, step;\n\n lower = 0; /* Lower limit of temperature table. */\n upper = 300; /* Upper limit. */\n step = 20; /* Step size. */\n</code></pre>\n<p>as</p>\n<pre><code> const int lower = 0, // Lower limit of temperature table.\n upper = 300, // Upper limit.\n step = 20; // Step size.\n</code></pre>\n<p>and move <code>fahr</code> to a <code>for</code> index:</p>\n<pre><code>for (double fahr = lower; fahr <= upper; fahr += step)\n</code></pre>\n<p>Also, due to the semantics of float promotion,</p>\n<pre><code>(5.0/9.0) * (fahr-32.0)\n</code></pre>\n<p>can just be</p>\n<pre><code>(fahr - 32)*5/9\n</code></pre>\n<p>This:</p>\n<pre><code>printf("Fahrenheit to Celsius\\n"); /* Table header */\nprintf("%3s %6s\\n", "F", "C"); /* Temperature label */\n</code></pre>\n<p>can use implicit string concatenation and character fields:</p>\n<pre><code>printf(\n "Fahrenheit to Celsius\\n" // Table header\n "%3c %6c\\n", // Temperature label \n 'F', 'C'\n);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T17:59:35.240",
"Id": "525599",
"Score": "0",
"body": "This was really great. Thank you. I am going to look into gdb, I ran the -ggdb flag but didn't notice anything different."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T18:00:17.090",
"Id": "525600",
"Score": "1",
"body": "It's been rolled back - rather than doing that, if you want another round of review you should post a new question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T06:55:02.647",
"Id": "525727",
"Score": "1",
"body": "Several declarations on a single line is generally considered bad practice/bad style since it increases the chance of bugs when using const, pointers etc. Mixing fixed point integer constants with floating point is considered very bad style since it's very easy to get integer promotion bugs. Your string concatenation example makes the code harder too read and there's no need for such pre-mature optimizations in a simple program like this. Overall, lots of bad and/or subjective advise, I have to down vote."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T17:18:11.563",
"Id": "266102",
"ParentId": "266070",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "266102",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T03:39:46.467",
"Id": "266070",
"Score": "2",
"Tags": [
"c"
],
"Title": "Fahrenheit to Celsius table temperature converter in C"
}
|
266070
|
<p><code>element.parentNode.parentNode.children[3].innerHTML</code> is fine but not
<code>element.parentNode.parentNode.querySelectorAll(":nth-child(3)").innerHTML</code> (outputs <code>undefined</code>)</p>
<p>I also tried different numbers in <code>:nth-child()</code> but without any progress.</p>
<p>Any ideas why?</p>
<p>I get this with Mozilla Firefox 91.0.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T04:35:12.303",
"Id": "525546",
"Score": "0",
"body": "How `element.parentNode.parentNode.children[3].innerHTML` isn't a working code for me? What?"
}
] |
[
{
"body": "<blockquote>\n<p>The Document method querySelectorAll() returns a static (not live)\nNodeList representing a list of the document's elements that match the\nspecified group of selectors.</p>\n</blockquote>\n<p>For this reason it returns you a list of nodes from the DOM, basically you can think of an array of elements which matches all of the CSS selector, so you will have to choose one of them and then call the <code>innerHTML</code> on it.</p>\n<p>Something like this:</p>\n<pre><code>el.parentNode.parentNode.querySelectorAll(":nth-child(3)")[0].innerHTML\n</code></pre>\n<p>The example below demonstrates it for you</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var el = document.getElementById(\"span1\")\n//document.getElementById(\"result\").innerHTML = (el.parentNode.parentNode.children[3].innerHTML);\ndocument.getElementById(\"result\").innerHTML = (el.parentNode.parentNode.querySelectorAll(\":nth-child(3)\")[0].innerHTML);</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div>\n <div>\n <span id=\"span1\"> 1</span>\n </div>\n <div>\n <span id=\"span2\"> 2</span>\n </div>\n <div>\n <span id=\"span3\"> 3</span>\n </div>\n <div>\n <span id=\"span4\"> 4</span>\n </div>\n\n</div>\n\n<hr/>\n<div id=\"result\">\n\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T14:41:23.633",
"Id": "525529",
"Score": "3",
"body": "While this is a good answer, the question is off-topic for the Code Review Community so I doubt you will get many up votes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-24T14:53:37.887",
"Id": "526172",
"Score": "0",
"body": "Thanks @pacmaninbw I understand but I was also trying to be helpful which I think is the primary spirit of the whole community :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T14:23:24.970",
"Id": "266079",
"ParentId": "266077",
"Score": "-2"
}
}
] |
{
"AcceptedAnswerId": "266079",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T13:58:02.153",
"Id": "266077",
"Score": "-2",
"Tags": [
"javascript",
"css",
"dom"
],
"Title": "undefined instead of innerHTML"
}
|
266077
|
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/263729/231235">Tests for the operators of image template class in C++</a>. As <a href="https://codereview.stackexchange.com/a/264348/231235">G. Sliepen's answer</a> mentioned, I am attempting to use <a href="https://www.boost.org/doc/libs/1_77_0/libs/test/doc/html/index.html" rel="nofollow noreferrer">Boost.Test</a> and several test cases are created with <code>BOOST_AUTO_TEST_CASE_TEMPLATE</code> structure.</p>
<p><strong>The experimental implementation</strong></p>
<ul>
<li><p><code>Image</code> template class implementation (<code>image.h</code>):</p>
<pre><code>/* Developed by Jimmy Hu */
#ifndef Image_H
#define Image_H
#include <algorithm>
#include <array>
#include <cassert>
#include <chrono>
#include <complex>
#include <concepts>
#include <fstream>
#include <functional>
#include <iostream>
#include <iterator>
#include <list>
#include <numeric>
#include <string>
#include <type_traits>
#include <variant>
#include <vector>
#include "image_operations.h"
#ifdef USE_BOOST_SERIALIZATION
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/array.hpp>
#include <boost/serialization/base_object.hpp>
#include <boost/serialization/export.hpp>
#include <boost/serialization/list.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/split_free.hpp>
#include <boost/serialization/unique_ptr.hpp>
#include <boost/serialization/vector.hpp>
#endif
namespace TinyDIP
{
template <typename ElementT>
class Image
{
public:
Image() = default;
Image(const std::size_t width, const std::size_t height):
width(width),
height(height),
image_data(width * height) { }
Image(const std::size_t width, const std::size_t height, const ElementT initVal):
width(width),
height(height),
image_data(width * height, initVal) {}
Image(const std::vector<ElementT>& input, std::size_t newWidth, std::size_t newHeight):
width(newWidth),
height(newHeight)
{
assert(input.size() == newWidth * newHeight);
this->image_data = input; // Deep copy
}
Image(const std::vector<std::vector<ElementT>>& input)
{
this->height = input.size();
this->width = input[0].size();
for (auto& rows : input)
{
this->image_data.insert(this->image_data.end(), std::begin(input), std::end(input)); // flatten
}
return;
}
constexpr ElementT& at(const unsigned int x, const unsigned int y)
{
checkBoundary(x, y);
return this->image_data[y * width + x];
}
constexpr ElementT const& at(const unsigned int x, const unsigned int y) const
{
checkBoundary(x, y);
return this->image_data[y * width + x];
}
constexpr std::size_t getWidth() const
{
return this->width;
}
constexpr std::size_t getHeight() const
{
return this->height;
}
constexpr auto getSize()
{
return std::make_tuple(this->width, this->height);
}
std::vector<ElementT> const& getImageData() const { return this->image_data; } // expose the internal data
void print(std::string separator = "\t", std::ostream& os = std::cout)
{
for (std::size_t y = 0; y < this->height; ++y)
{
for (std::size_t x = 0; x < this->width; ++x)
{
// Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number
os << +this->at(x, y) << separator;
}
os << "\n";
}
os << "\n";
return;
}
// Enable this function if ElementT = RGB
void print(std::string separator = "\t", std::ostream& os = std::cout) requires(std::same_as<ElementT, RGB>)
{
for (std::size_t y = 0; y < this->height; ++y)
{
for (std::size_t x = 0; x < this->width; ++x)
{
os << "( ";
for (std::size_t channel_index = 0; channel_index < 3; ++channel_index)
{
// Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number
os << +this->at(x, y).channels[channel_index] << separator;
}
os << ")" << separator;
}
os << "\n";
}
os << "\n";
return;
}
friend std::ostream& operator<<(std::ostream& os, const Image<ElementT>& rhs)
{
const std::string separator = "\t";
for (std::size_t y = 0; y < rhs.height; ++y)
{
for (std::size_t x = 0; x < rhs.width; ++x)
{
// Ref: https://isocpp.org/wiki/faq/input-output#print-char-or-ptr-as-number
os << +rhs.at(x, y) << separator;
}
os << "\n";
}
os << "\n";
return os;
}
Image<ElementT>& operator+=(const Image<ElementT>& rhs)
{
assert(rhs.width == this->width);
assert(rhs.height == this->height);
std::transform(image_data.cbegin(), image_data.cend(), rhs.image_data.cbegin(),
image_data.begin(), std::plus<>{});
return *this;
}
Image<ElementT>& operator-=(const Image<ElementT>& rhs)
{
assert(rhs.width == this->width);
assert(rhs.height == this->height);
std::transform(image_data.cbegin(), image_data.cend(), rhs.image_data.cbegin(),
image_data.begin(), std::minus<>{});
return *this;
}
Image<ElementT>& operator*=(const Image<ElementT>& rhs)
{
assert(rhs.width == this->width);
assert(rhs.height == this->height);
std::transform(image_data.cbegin(), image_data.cend(), rhs.image_data.cbegin(),
image_data.begin(), std::multiplies<>{});
return *this;
}
Image<ElementT>& operator/=(const Image<ElementT>& rhs)
{
assert(rhs.width == this->width);
assert(rhs.height == this->height);
std::transform(image_data.cbegin(), image_data.cend(), rhs.image_data.cbegin(),
image_data.begin(), std::divides<>{});
return *this;
}
bool operator==(const Image<ElementT>& rhs) const
{
/* do actual comparison */
if (rhs.width != this->width ||
rhs.height != this->height)
{
return false;
}
return rhs.image_data == this->image_data;
}
bool operator!=(const Image<ElementT>& rhs) const
{
return !(this == rhs);
}
Image<ElementT>& operator=(Image<ElementT> const& input) = default; // Copy Assign
Image<ElementT>& operator=(Image<ElementT>&& other) = default; // Move Assign
Image(const Image<ElementT> &input) = default; // Copy Constructor
Image(Image<ElementT> &&input) = default; // Move Constructor
#ifdef USE_BOOST_SERIALIZATION
void Save(std::string filename)
{
const std::string filename_with_extension = filename + ".dat";
// Reference: https://stackoverflow.com/questions/523872/how-do-you-serialize-an-object-in-c
std::ofstream ofs(filename_with_extension, std::ios::binary);
boost::archive::binary_oarchive ArchiveOut(ofs);
// write class instance to archive
ArchiveOut << *this;
// archive and stream closed when destructors are called
ofs.close();
}
#endif
private:
std::size_t width;
std::size_t height;
std::vector<ElementT> image_data;
void checkBoundary(const size_t x, const size_t y) const
{
assert(x < width);
assert(y < height);
}
#ifdef USE_BOOST_SERIALIZATION
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive& ar, const unsigned int version)
{
ar& width;
ar& height;
ar& image_data;
}
#endif
};
}
#endif
</code></pre>
</li>
<li><p><code>image_operations.h</code>:</p>
<pre><code>/* Developed by Jimmy Hu */
#ifndef ImageOperations_H
#define ImageOperations_H
#include <numbers>
#include <string>
#include "base_types.h"
#include "image.h"
#define is_size_same(x, y) {assert(x.getWidth() == y.getWidth()); assert(x.getHeight() == y.getHeight());}
namespace TinyDIP
{
// Forward Declaration class Image
template <typename ElementT>
class Image;
template<class T = GrayScale>
requires (std::same_as<T, GrayScale>)
constexpr static auto constructRGB(Image<T> r, Image<T> g, Image<T> b)
{
is_size_same(r, g);
is_size_same(g, b);
is_size_same(r, b);
return;
}
template<typename T>
T normalDistribution1D(const T x, const T standard_deviation)
{
return std::exp(-x * x / (2 * standard_deviation * standard_deviation));
}
template<typename T>
T normalDistribution2D(const T xlocation, const T ylocation, const T standard_deviation)
{
return std::exp(-(xlocation * xlocation + ylocation * ylocation) / (2 * standard_deviation * standard_deviation)) / (2 * std::numbers::pi * standard_deviation * standard_deviation);
}
template<class InputT1, class InputT2>
constexpr static auto cubicPolate(const InputT1 v0, const InputT1 v1, const InputT1 v2, const InputT1 v3, const InputT2 frac)
{
auto A = (v3-v2)-(v0-v1);
auto B = (v0-v1)-A;
auto C = v2-v0;
auto D = v1;
return D + frac * (C + frac * (B + frac * A));
}
template<class InputT = float, class ElementT>
constexpr static auto bicubicPolate(const ElementT* const ndata, const InputT fracx, const InputT fracy)
{
auto x1 = cubicPolate( ndata[0], ndata[1], ndata[2], ndata[3], fracx );
auto x2 = cubicPolate( ndata[4], ndata[5], ndata[6], ndata[7], fracx );
auto x3 = cubicPolate( ndata[8], ndata[9], ndata[10], ndata[11], fracx );
auto x4 = cubicPolate( ndata[12], ndata[13], ndata[14], ndata[15], fracx );
return std::clamp(
cubicPolate( x1, x2, x3, x4, fracy ),
static_cast<InputT>(std::numeric_limits<ElementT>::min()),
static_cast<InputT>(std::numeric_limits<ElementT>::max()));
}
template<class FloatingType = float, class ElementT>
Image<ElementT> copyResizeBicubic(Image<ElementT>& image, size_t width, size_t height)
{
auto output = Image<ElementT>(width, height);
// get used to the C++ way of casting
auto ratiox = static_cast<FloatingType>(image.getWidth()) / static_cast<FloatingType>(width);
auto ratioy = static_cast<FloatingType>(image.getHeight()) / static_cast<FloatingType>(height);
for (size_t y = 0; y < height; ++y)
{
for (size_t x = 0; x < width; ++x)
{
FloatingType xMappingToOrigin = static_cast<FloatingType>(x) * ratiox;
FloatingType yMappingToOrigin = static_cast<FloatingType>(y) * ratioy;
FloatingType xMappingToOriginFloor = std::floor(xMappingToOrigin);
FloatingType yMappingToOriginFloor = std::floor(yMappingToOrigin);
FloatingType xMappingToOriginFrac = xMappingToOrigin - xMappingToOriginFloor;
FloatingType yMappingToOriginFrac = yMappingToOrigin - yMappingToOriginFloor;
ElementT ndata[4 * 4];
for (int ndatay = -1; ndatay <= 2; ++ndatay)
{
for (int ndatax = -1; ndatax <= 2; ++ndatax)
{
ndata[(ndatay + 1) * 4 + (ndatax + 1)] = image.at(
std::clamp(xMappingToOriginFloor + ndatax, static_cast<FloatingType>(0), image.getWidth() - static_cast<FloatingType>(1)),
std::clamp(yMappingToOriginFloor + ndatay, static_cast<FloatingType>(0), image.getHeight() - static_cast<FloatingType>(1)));
}
}
output.at(x, y) = bicubicPolate(ndata, xMappingToOriginFrac, yMappingToOriginFrac);
}
}
return output;
}
// multiple standard deviations
template<class InputT>
constexpr static Image<InputT> gaussianFigure2D(
const size_t xsize, const size_t ysize,
const size_t centerx, const size_t centery,
const InputT standard_deviation_x, const InputT standard_deviation_y)
{
auto output = TinyDIP::Image<InputT>(xsize, ysize);
auto row_vector_x = TinyDIP::Image<InputT>(xsize, 1);
for (size_t x = 0; x < xsize; ++x)
{
row_vector_x.at(x, 0) = normalDistribution1D(static_cast<InputT>(x) - static_cast<InputT>(centerx), standard_deviation_x);
}
auto row_vector_y = TinyDIP::Image<InputT>(ysize, 1);
for (size_t y = 0; y < ysize; ++y)
{
row_vector_y.at(y, 0) = normalDistribution1D(static_cast<InputT>(y) - static_cast<InputT>(centery), standard_deviation_y);
}
for (size_t y = 0; y < ysize; ++y)
{
for (size_t x = 0; x < xsize; ++x)
{
output.at(x, y) = row_vector_x.at(x, 0) * row_vector_y.at(y, 0);
}
}
return output;
}
// single standard deviation
template<class InputT>
constexpr static Image<InputT> gaussianFigure2D(
const size_t xsize, const size_t ysize,
const size_t centerx, const size_t centery,
const InputT standard_deviation)
{
return gaussianFigure2D(xsize, ysize, centerx, centery, standard_deviation, standard_deviation);
}
template<typename Op, class InputT, class... Args>
constexpr static Image<InputT> pixelwiseOperation(Op op, const Image<InputT>& input1, const Args&... inputs)
{
Image<InputT> output(
recursive_transform<1>(
[&](auto&& element1, auto&&... elements)
{
auto result = op(element1, elements...);
return static_cast<InputT>(std::clamp(
result,
static_cast<decltype(result)>(std::numeric_limits<InputT>::min()),
static_cast<decltype(result)>(std::numeric_limits<InputT>::max())));
},
(input1.getImageData()),
(inputs.getImageData())...),
input1.getWidth(),
input1.getHeight());
return output;
}
template<class InputT>
constexpr static Image<InputT> plus(const Image<InputT>& input1)
{
return input1;
}
template<class InputT, class... Args>
constexpr static Image<InputT> plus(const Image<InputT>& input1, const Args&... inputs)
{
return TinyDIP::pixelwiseOperation(std::plus<>{}, input1, plus(inputs...));
}
template<class InputT>
constexpr static Image<InputT> subtract(const Image<InputT>& input1, const Image<InputT>& input2)
{
is_size_same(input1, input2);
return TinyDIP::pixelwiseOperation(std::minus<>{}, input1, input2);
}
template<class InputT = RGB>
requires (std::same_as<InputT, RGB>)
constexpr static Image<InputT> subtract(Image<InputT>& input1, Image<InputT>& input2)
{
is_size_same(input1, input2);
Image<InputT> output(input1.getWidth(), input1.getHeight());
for (std::size_t y = 0; y < input1.getHeight(); ++y)
{
for (std::size_t x = 0; x < input1.getWidth(); ++x)
{
for(std::size_t channel_index = 0; channel_index < 3; ++channel_index)
{
output.at(x, y).channels[channel_index] =
std::clamp(
input1.at(x, y).channels[channel_index] -
input2.at(x, y).channels[channel_index],
0,
255);
}
}
}
return output;
}
template<class InputT>
constexpr static Image<InputT> multiplies(const Image<InputT>& input1, const Image<InputT>& input2)
{
return TinyDIP::pixelwiseOperation(std::multiplies<>{}, input1, input2);
}
template<class InputT, class... Args>
constexpr static Image<InputT> multiplies(const Image<InputT>& input1, const Args&... inputs)
{
return TinyDIP::pixelwiseOperation(std::multiplies<>{}, input1, multiplies(inputs...));
}
template<class InputT>
constexpr static Image<InputT> divides(const Image<InputT>& input1, const Image<InputT>& input2)
{
return TinyDIP::pixelwiseOperation(std::divides<>{}, input1, input2);
}
template<class InputT>
constexpr static Image<InputT> modulus(const Image<InputT>& input1, const Image<InputT>& input2)
{
return TinyDIP::pixelwiseOperation(std::modulus<>{}, input1, input2);
}
template<class InputT>
constexpr static Image<InputT> negate(const Image<InputT>& input1, const Image<InputT>& input2)
{
return TinyDIP::pixelwiseOperation(std::negate<>{}, input1);
}
}
#endif
</code></pre>
</li>
<li><p><code>base_types.h</code>: The base types</p>
<pre><code>/* Developed by Jimmy Hu */
#ifndef BASE_H
#define BASE_H
#include <filesystem>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <utility>
using BYTE = unsigned char;
struct RGB
{
BYTE channels[3];
};
using GrayScale = BYTE;
struct HSV
{
double channels[3]; // Range: 0 <= H < 360, 0 <= S <= 1, 0 <= V <= 255
};
struct BMPIMAGE
{
std::filesystem::path FILENAME;
unsigned int XSIZE;
unsigned int YSIZE;
BYTE FILLINGBYTE;
BYTE *IMAGE_DATA;
};
#endif
</code></pre>
</li>
</ul>
<p><strong>Unit Tests with <a href="https://www.boost.org/doc/libs/1_77_0/libs/test/doc/html/index.html" rel="nofollow noreferrer">Boost.Test</a></strong></p>
<pre><code>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE image_elementwise_tests
#ifdef BOOST_TEST_MODULE
#include <boost/test/included/unit_test.hpp>
#ifdef BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#else
#include <boost/test/included/unit_test.hpp>
#endif // BOOST_TEST_DYN_LINK
#include <boost/mpl/list.hpp>
#include <boost/mpl/vector.hpp>
#include <tao/tuple/tuple.hpp>
typedef boost::mpl::list<
byte, char, int, short, long, long long int,
unsigned int, unsigned short int, unsigned long int, unsigned long long int,
float, double, long double> test_types;
BOOST_AUTO_TEST_CASE_TEMPLATE(image_elementwise_add_test, T, test_types)
{
std::size_t size_x = 10;
std::size_t size_y = 10;
T initVal = 10;
T increment = 1;
auto test = TinyDIP::Image<T>(size_x, size_y, initVal);
test += TinyDIP::Image<T>(size_x, size_y, increment);
BOOST_TEST(test == TinyDIP::Image<T>(size_x, size_y, initVal + increment));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(image_elementwise_add_test_zero_dimensions, T, test_types)
{
std::size_t size_x = 0; // Test images with both of the dimensions having size zero.
std::size_t size_y = 0; // Test images with both of the dimensions having size zero.
T initVal = 10;
T increment = 1;
auto test = TinyDIP::Image<T>(size_x, size_y, initVal);
test += TinyDIP::Image<T>(size_x, size_y, increment);
BOOST_TEST(test == TinyDIP::Image<T>(size_x, size_y, initVal + increment));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(image_elementwise_add_test_large_dimensions, T, test_types)
{
std::size_t size_x = 18446744073709551615; // Test images with very large dimensions (std::numeric_limits<std::size_t>::max()).
std::size_t size_y = 18446744073709551615; // Test images with very large dimensions (std::numeric_limits<std::size_t>::max()).
T initVal = 10;
T increment = 1;
auto test = TinyDIP::Image<T>(size_x, size_y, initVal);
test += TinyDIP::Image<T>(size_x, size_y, increment);
BOOST_TEST(test == TinyDIP::Image<T>(size_x, size_y, initVal + increment));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(image_elementwise_minus_test, T, test_types)
{
std::size_t size_x = 10;
std::size_t size_y = 10;
T initVal = 10;
T difference = 1;
auto test = TinyDIP::Image<T>(size_x, size_y, initVal);
test -= TinyDIP::Image<T>(size_x, size_y, difference);
BOOST_TEST(test == TinyDIP::Image<T>(size_x, size_y, initVal - difference));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(image_elementwise_minus_test_zero_dimensions, T, test_types)
{
std::size_t size_x = 0; // Test images with both of the dimensions having size zero.
std::size_t size_y = 0; // Test images with both of the dimensions having size zero.
T initVal = 10;
T difference = 1;
auto test = TinyDIP::Image<T>(size_x, size_y, initVal);
test -= TinyDIP::Image<T>(size_x, size_y, difference);
BOOST_TEST(test == TinyDIP::Image<T>(size_x, size_y, initVal - difference));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(image_elementwise_minus_test_large_dimensions, T, test_types)
{
std::size_t size_x = 18446744073709551615; // Test images with very large dimensions (std::numeric_limits<std::size_t>::max()).
std::size_t size_y = 18446744073709551615; // Test images with very large dimensions (std::numeric_limits<std::size_t>::max()).
T initVal = 10;
T difference = 1;
auto test = TinyDIP::Image<T>(size_x, size_y, initVal);
test -= TinyDIP::Image<T>(size_x, size_y, difference);
BOOST_TEST(test == TinyDIP::Image<T>(size_x, size_y, initVal - difference));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(image_elementwise_multiplies_test, T, test_types)
{
std::size_t size_x = 10;
std::size_t size_y = 10;
T initVal = 10;
T multiplier = 2;
auto test = TinyDIP::Image<T>(size_x, size_y, initVal);
test *= TinyDIP::Image<T>(size_x, size_y, multiplier);
BOOST_TEST(test == TinyDIP::Image<T>(size_x, size_y, initVal * multiplier));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(image_elementwise_multiplies_test_zero_dimensions, T, test_types)
{
std::size_t size_x = 0; // Test images with both of the dimensions having size zero.
std::size_t size_y = 0; // Test images with both of the dimensions having size zero.
T initVal = 10;
T multiplier = 2;
auto test = TinyDIP::Image<T>(size_x, size_y, initVal);
test *= TinyDIP::Image<T>(size_x, size_y, multiplier);
BOOST_TEST(test == TinyDIP::Image<T>(size_x, size_y, initVal * multiplier));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(image_elementwise_multiplies_test_large_dimensions, T, test_types)
{
std::size_t size_x = 18446744073709551615; // Test images with very large dimensions (std::numeric_limits<std::size_t>::max()).
std::size_t size_y = 18446744073709551615; // Test images with very large dimensions (std::numeric_limits<std::size_t>::max()).
T initVal = 10;
T multiplier = 2;
auto test = TinyDIP::Image<T>(size_x, size_y, initVal);
test *= TinyDIP::Image<T>(size_x, size_y, multiplier);
BOOST_TEST(test == TinyDIP::Image<T>(size_x, size_y, initVal * multiplier));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(image_elementwise_divides_test, T, test_types)
{
std::size_t size_x = 10;
std::size_t size_y = 10;
T initVal = 10;
T divider = 2;
auto test = TinyDIP::Image<T>(size_x, size_y, initVal);
test /= TinyDIP::Image<T>(size_x, size_y, divider);
BOOST_TEST(test == TinyDIP::Image<T>(size_x, size_y, initVal / divider));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(image_elementwise_divides_test_zero_dimensions, T, test_types)
{
std::size_t size_x = 0; // Test images with both of the dimensions having size zero.
std::size_t size_y = 0; // Test images with both of the dimensions having size zero.
T initVal = 10;
T divider = 2;
auto test = TinyDIP::Image<T>(size_x, size_y, initVal);
test /= TinyDIP::Image<T>(size_x, size_y, divider);
BOOST_TEST(test == TinyDIP::Image<T>(size_x, size_y, initVal / divider));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(image_elementwise_divides_test_large_dimensions, T, test_types)
{
std::size_t size_x = 18446744073709551615; // Test images with very large dimensions (std::numeric_limits<std::size_t>::max()).
std::size_t size_y = 18446744073709551615; // Test images with very large dimensions (std::numeric_limits<std::size_t>::max()).
T initVal = 10;
T divider = 2;
auto test = TinyDIP::Image<T>(size_x, size_y, initVal);
test /= TinyDIP::Image<T>(size_x, size_y, divider);
BOOST_TEST(test == TinyDIP::Image<T>(size_x, size_y, initVal / divider));
}
BOOST_AUTO_TEST_CASE_TEMPLATE(image_elementwise_divides_zero_test, T, test_types)
{
std::size_t size_x = 10;
std::size_t size_y = 10;
T initVal = 10;
T divider = 0;
auto test = TinyDIP::Image<T>(size_x, size_y, initVal);
test /= TinyDIP::Image<T>(size_x, size_y, divider);
BOOST_TEST(test == TinyDIP::Image<T>(size_x, size_y, initVal / divider)); // dividing by zero test
}
#endif
</code></pre>
<p>All suggestions are welcome.</p>
<p>The summary information:</p>
<ul>
<li><p>Which question it is a follow-up to?</p>
<p><a href="https://codereview.stackexchange.com/q/263729/231235">Tests for the operators of image template class in C++</a></p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<p>I am attempting to create some test cases with Boost.Test framework in this post.</p>
</li>
<li><p>Why a new review is being asked for?</p>
<p>If there is any possible improvement, please let me know.</p>
</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T23:54:05.010",
"Id": "525542",
"Score": "0",
"body": "What will this cost be used for? Is it just practice for using boost.test?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T23:49:40.570",
"Id": "525621",
"Score": "0",
"body": "@EmilyL. Thank you for your comments. Both practice and validation of the functions. Do you have any suggestions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T16:17:31.227",
"Id": "525775",
"Score": "3",
"body": "Just an observation that if you're doing this for practice then fair enough but if you're building this for production, I'd recommend using an existing library instead to save the time and get more features and likely more performance as your code seems very bare bones at the moment."
}
] |
[
{
"body": "<h1>Ensure you cover the basics</h1>\n<p>You have a lot of tests that check the operations on already created <code>TinyDIP::Image</code>s, but you lack tests to check that the creation and initialization of images works as expected. I would add something like this at least:</p>\n<pre><code>BOOST_AUTO_TEST_CASE_TEMPLATE(image_creation, T, test_types)\n{\n std::size_t size_x = 10;\n std::size_t size_y = 10;\n T initVal = 10;\n auto test = TinyDIP::Image<T>(size_x, size_y, initVal);\n for (std::size_t y = 0; y < size_y; ++y) {\n for (std::size_t x = 0; x < size_x; ++x) {\n BOOST_TEST(test.at(x, y) == initval);\n }\n }\n}\n</code></pre>\n<p>You also might want to check that images remember different values for different pixels, and that operations on them also give the right result, and not accidentily swap x and y coordinates for example.</p>\n<h1>Aim for 100% code coverage by your test suite</h1>\n<p>I see a lot of public functions not being tested in your test suite. Ideally, your test suite covers all your code. <a href=\"https://en.wikipedia.org/wiki/Code_coverage\" rel=\"nofollow noreferrer\">Code coverage</a> tools can help you track how much of the code is tested by your test suite. They might have a hard time with templates though, but have a look at these StackOverflow questions for some pointers:</p>\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/7710404/whats-the-best-c-code-coverage-tool-that-works-with-templates\">What's the best C++ code coverage tool that works with templates?</a></li>\n<li><a href=\"https://stackoverflow.com/questions/9666800/getting-useful-gcov-results-for-header-only-libraries\">Getting useful GCov results for header-only libraries</a></li>\n</ul>\n<h1>Avoid code duplication</h1>\n<p>I see quite a lot of code duplication. The test cases all look the same, except for <code>size_x</code> and <code>size_y</code> being different, and the operation on <code>test</code> being different. Boost.Test has macros for running the same test with different values, perhaps that can be combined some way with the macros for using different template types. Otherwise, consider writing a generic function like so:</p>\n<pre><code>template<typename T, typename Op>\nstatic void test_image_operation(std::size_t size, T operand, Op op) {\n std::size_t size_x = size;\n std::size_t size_y = size;\n T initVal = 10;\n auto test = TinyDIP::Image<T>(size_x, size_y, initVal);\n op(test, operand);\n T finalVal = initVal;\n op(finalVal, operand);\n BOOST_TEST(test == TinyDIP::Image<T>(size_x, size_y, finalVal));\n}\n</code></pre>\n<p>And call it like so:</p>\n<pre><code>BOOST_AUTO_TEST_CASE_TEMPLATE(image_elementwise_add_test, T, test_types)\n{\n test_image_operation<T>(10, 1, [](auto &lhs, auto &rhs){ lhs += rhs; });\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-05T15:36:16.813",
"Id": "267709",
"ParentId": "266080",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "267709",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T14:53:22.640",
"Id": "266080",
"Score": "0",
"Tags": [
"c++",
"unit-testing",
"template",
"boost",
"overloading"
],
"Title": "Unit Tests for the operators of image template class with Boost.Test framework in C++"
}
|
266080
|
<p>I created a quick "demonstration of proposal behavior" tool for my post on MSO: <a href="https://meta.stackoverflow.com/q/410790/2943403">A proposal to put ALL answerers on a path to curating better content</a>.</p>
<p>Because I have never asked for a review before and I am not a JavaScript or CSS SME, I'd like to see if I've used any antipatterns and how my code can be made more direct/maintainable/readable/professional.</p>
<p>The technique that I used to create repeatable table rows doesn't <em>feel</em> very slick.</p>
<p>I don't necessarily need the actual presentation to be improved (since it was just something I scratched up), but if anyone want to go down that rabbit hole, I won't stop you.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).on('click', '.add', function() {
let mostRecentAnswer = $('#summary').prev(),
id = !mostRecentAnswer.length ? 1 : 1 + mostRecentAnswer.data('id');
$('#summary').before(
'<tr data-id=' + id + '>'
+ '<td><input type="button" class="del" value="-"></td>'
+ '<td>'
+ '<label for="open' + id + '"><input type="radio" id="open' + id + '" name="status' + id + '" checked> Open</label>'
+ '<label for="closed' + id + '"><input type="radio" id="closed' + id + '" name="status' + id + '"> Closed</label>'
+ '</td>'
+ '<td class="newest5 hide"></td>'
+ '<td class="newest10 hide"></td>'
+ '<td class="newest20 hide"></td>'
+ '</tr>'
);
handleNewest();
});
$(document).on('click', '.del', function() {
$(this).closest('tr').remove();
handleNewest();
});
$(document).on('change', '[type="radio"]', function() {
handleNewest();
});
function handleNewest() {
let totalAnswers = $('#demo tr[data-id]').length;
if (totalAnswers < 5) {
$('#outcome').html('<b class="red">Please post carefully constructed and educational answers to questions which are at least 4 hours old -- it is presumed that this community has had ample to time to vet these new questions as clear, complete, unique and on-topic.</b>');
return;
}
$('#outcome').html('More than 40% of your recent answers have been on open questions which the community has deemed to be a good fit for our repository of knowledge.');
[5, 10, 20].forEach(function(group) {
$('td[class^="newest' + group + '"]').addClass('hide').removeClass('groupStart groupEnd');
if (totalAnswers >= group) {
let lastCount = group - 1,
sumOpen = 0,
row = $('#summary').prev(),
groupCell;
for (let i = 0; i < group; ++i) {
sumOpen += $('td label input[id^="open"]:checked', row).length;
groupCell = $('td[class^="newest' + group + '"]', row);
groupCell.removeClass('hide');
if (!i) {
groupCell.addClass('groupEnd');
} else if (i === lastCount) {
groupCell.addClass('groupStart');
}
row = row.prev();
}
let percent = Math.round(sumOpen / group * 100);
$('#newest' + group + 'Total').html(percent).toggleClass('red', percent <= 40);
$('td[class^="newest' + group + '"]:not(.hide)').toggleClass('redBG', percent <= 40);
if (percent <= 40) {
$('#outcome').html('<b class="red">' + (100 - percent) + '% of your last ' + group + ' answers have been on closed pages. Please take more care to only post answers to clear, complete, unique, on-topic questions.</b>');
}
}
});
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#demo {
border-spacing: 0;
}
.newest5:not(.hide),
.newest10:not(.hide),
.newest20:not(.hide) {
border-right: 1px solid black; min-width: 30px;
}
.groupStart {
border-top-right-radius: 30px;
}
.groupEnd {
border-bottom-right-radius: 30px;
}
#summaryLabel {
text-align: right;
}
#[id$="Total"]:after {
content: '%';
}
.red {
color: red;
}
.newest5.redBG:not(.hide),
.newest10.redBG:not(.hide),
.newest20.redBG:not(.hide) {
background-color: red;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="demo">
<tr id="summary">
<td><input type="button" class="add" value="+"></td>
<td id="summaryLabel">Open Percent:</td>
<td id="newest5Total"></td>
<td id="newest10Total"></td>
<td id="newest20Total"></td>
</tr>
</table>
<h2 id="outcome"></h2></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<h2>Declarations</h2>\n<p>Always declare variables that do not change as <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. const\">const</a> rather than <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. let\">let</a> or <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. var\">var</a></p>\n<p>For example the line</p>\n<pre><code>let mostRecentAnswer = $('#summary').prev(),\n id = !mostRecentAnswer.length ? 1 : 1 + mostRecentAnswer.data('id');\n</code></pre>\n<p>Should start with <code>const</code> and if written using native API</p>\n<pre><code>const id = Number(summary.previousSibling?.dataset.id ?? 0) + 1;\n</code></pre>\n<p>References <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. Nullish coalescing operator\">?? (Nullish coalescing operator)</a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. Optional chaining\">?. (Optional chaining)</a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Node/previousSibling\" rel=\"nofollow noreferrer\" title=\"MDN Web API's Node previousSibling\">Node.previousSibling</a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset\" rel=\"nofollow noreferrer\" title=\"MDN Web API's HTMLElement dataset\">HTMLElement.dataset</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Number\">Number</a></p>\n<p><strong>Note</strong> that <code>summary</code> must reference a unique <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element\" rel=\"nofollow noreferrer\" title=\"MDN Web API's Element\">Element</a> via its unique <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/id\" rel=\"nofollow noreferrer\" title=\"MDN Web API's Element id\">Element.id</a>. Unique means unique on page (including <a href=\"https://developer.mozilla.org/en-US/docs/Glossary/Global_scope\" rel=\"nofollow noreferrer\">Global Scope</a>)</p>\n<h2>Markup</h2>\n<p>Avoid adding markup directly to the page. jQuery users have a tendency to manipulate page content via markup strings.</p>\n<p>Most IDE will not provide markup syntax styling when the markup is bound by quotes inside a script, significantly decreasing the readability and maintainability of a major part of your content.</p>\n<p>Most importantly is that adding and parsing markup is up to 2 orders of magnitude slower than using native APIs.</p>\n<h3>Table via Native API</h3>\n<p>In your code you are building a <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement\" rel=\"nofollow noreferrer\" title=\"MDN Web API's HTMLTableElement\">HTMLTableElement</a>. The table element provides a good set of properties and functions to quickly and easily manipulate rows, columns, and cells. <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement/rows\" rel=\"nofollow noreferrer\" title=\"MDN Web API's HTMLTableElement rows\">HTMLTableElement.rows</a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableRowElement\" rel=\"nofollow noreferrer\" title=\"MDN Web API's HTMLTableRowElement\">HTMLTableRowElement</a>, and <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableRowElement\" rel=\"nofollow noreferrer\" title=\"MDN Web API's HTMLTableRowElement\">HTMLTableRowElement</a> to link but a few.</p>\n<p>To create elements you can us <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement\" rel=\"nofollow noreferrer\" title=\"MDN Web API's Document createElement\">Document.createElement</a> using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Object assign\">Object.assign</a> to assign properties.</p>\n<p>Example util functions to help build page content</p>\n<pre><code>const tag = (type, props = {}) => Object.assign(document.createElement(type), props);\nconst append = (par, ...sibs) => sibs.reduce((p, sib) => (p.appendChild(sib), p), par));\nconst row = (table, props, ...cells) => \n const row = Object.assign(table.insertRow(-1), props);\n cells.map(cell => append(Object.assign(row.insertCell(-1), cell.shift()), ...cell));\n return row;\n}\n</code></pre>\n<p>Example using native API to add and remove rows from a table</p>\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>;(()=>{\n\"use strict\";\n\n// Global DOM utils. Note each call returns an element as defined by first arg\nconst tag = (type, props = {}) => Object.assign(document.createElement(type), props);\nconst append = (par, ...sibs) => sibs.reduce((p, sib) => (p.appendChild(sib), p), par);\nconst event = (element, type, call, opts = {}) => (element.addEventListener(type, call, opts), element);\n\n// return new row\nconst row = (table, props, ...cells) => {\n const row = Object.assign(table.insertRow(-1), props);\n cells.map(cell => append(Object.assign(row.insertCell(-1), cell.shift()), ...cell));\n return row;\n};\n\n// App code\nconst newCellProp = num => ({className: \"newest\" + num + \" hide\"});\nconst table = tag(\"table\");\nappend(document.body,\n table, event(tag(\"button\", {textContent: \"AddRow\"}), \"click\", addRow)\n);\nvar id = 1;\nfunction addRow() {\n const name = \"Status\" + id;\n const removeBtn = event(\n tag(\"input\", {type: \"button\", className: \"del\", value: \"-\"}),\n \"click\",\n () => table.deleteRow([...table.rows].indexOf(newRow)));\n \n const newRow = row(\n table, {}, [{}, removeBtn], [{}, tag(\"span\", {textContent: name})], [{},\n append(\n tag(\"label\", {for: \"open\" + id, textContent: \"Open\"}),\n tag(\"input\", {type: \"radio\", id: \"open\" + id, checked: true, textContent: \" Open\", name})\n ),\n append(\n tag(\"label\", {for: \"close\" + id, textContent: \"Close\"}),\n tag(\"input\", {type: \"radio\", id: \"close\" + id, textContent: \" Closed\", name})\n ),\n ], [newCellProp(5)], [newCellProp(10)], [newCellProp(15)]);\n newRow.dataset.id = id++;\n}\n})();</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h3>Use a template</h3>\n<p>Alternatively you can use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLTemplateElement\" rel=\"nofollow noreferrer\" title=\"MDN Web API's HTMLTemplateElement\">HTMLTemplateElement</a> to define the table and contained elements in the page. The template element is not visible, You copy parts from it to create new page content.</p>\n<h2>jQuery</h2>\n<p>Your code is too reliant on jQuery. It is my opinion that jQuery is dead and one should avoid its use.</p>\n<p>Reasoning...</p>\n<h3>Browser support</h3>\n<p>The most common reason people give for still using jQuery is legacy browser support.</p>\n<p>I agree that jQuery is a great tool if you wish to support the very few that still use Internet Explorer (IE).</p>\n<p>However this argument fails when your JavaScript is not written with legacy browsers in mind.</p>\n<p>In your case you use <code>let</code> which has no support on IE6-10 and partial support on IE11. <a href=\"https://caniuse.com/?search=let\" rel=\"nofollow noreferrer\">Can I use let</a></p>\n<p>To use jQuery and still use modern JS (ECMAScript2015+) one must also include a transcompiler (for example <a href=\"https://babeljs.io/\" rel=\"nofollow noreferrer\">BabelJS</a>) to ensure full support</p>\n<h3>Performance</h3>\n<p>HTML5 provides very good coverage and using native API's reduce page load times (no need to load and parse bloated jQuery script) and significantly increase execution speed. If you need to also bundle a transcompiler (eg BabelJS) the page load will further be slowed.</p>\n<h3>Skills</h3>\n<p>You as a front end developer using jQuery do not gain experience using the native API's an important current and future skill set to master.</p>\n<h3>Verbose native API</h3>\n<p>Some will argue that jQuery is less verbose than the native APIs, and this is true, however in less than a dozen lines one can create functions to help call the most common DOM related tasks and greatly reduce the verbosity overhead associated with native API call.</p>\n<p>For example. You can replace the long <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelector\" rel=\"nofollow noreferrer\" title=\"MDN Web API's Element querySelector\">Element.querySelector</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelectorAll\" rel=\"nofollow noreferrer\" title=\"MDN Web API's Element querySelectorAll\">Element.querySelectorAll</a> with 2 functions</p>\n<pre><code>const query = (qStr, element = document) => element.querySelector(qStr);\nconst queryAll = (qStr, element = document) => [...element.querySelectorAll(qStr)];\n</code></pre>\n<p>Also see example code in previous section.</p>\n<hr />\n<h2>Answer Note</h2>\n<p>Sorry I have run out of time so could not complete this review. Rather than drop it all, I applied <em>"Something is better than nothing"</em> as there is currently no answer to your post. Hope this helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T03:54:44.933",
"Id": "525720",
"Score": "0",
"body": "The `summary` id is unique on the document. Why do you mention this? Good review, thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T08:21:57.537",
"Id": "525734",
"Score": "0",
"body": "@mickmackusa All `Element.id` must be unique or the page is not valid. When using the `Element.id` as a name to reference an element eg `<div id=\"byIdName\"></div><script>console.log(byIdName === document.getElementById(\"byIdName\")) // >> true</script>` That id must be unique on both the HTML and the global JS scope. Declaring the name in JS eg `var byIdName` will remove the reference, within that scope, to the element. Using the id twice in the HTML makes the JS reference undefined (well sort of as there are many edge cases, and browser type and version caveats)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T10:13:43.320",
"Id": "525745",
"Score": "0",
"body": "I am not confused about the rule. I am confused about why you are telling me in the review that my id must be unique. Is this just additional fact sharing? Because I don't see in my code where I have violated the rule."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T18:23:27.387",
"Id": "525793",
"Score": "0",
"body": "@mickmackusa Though you do not have the same ID on the page at any one time, you do re-assign the same id when you add a new row after deleting rows. Thought the browser will re-assign the id name with the reference to the new element when the element is added to the page, the reference becomes undefined when the element is created and before it has been added. This is not an issue when adding content via markup, it can be problematic when building content via the DOM API's"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T03:52:33.030",
"Id": "266150",
"ParentId": "266084",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-15T23:46:43.507",
"Id": "266084",
"Score": "0",
"Tags": [
"javascript",
"jquery",
"html",
"css",
"user-interface"
],
"Title": "HTML table with repeatable rows and live-calculated column totals with row grouping indication"
}
|
266084
|
<p>Firstly, the code relies on importing images, so I'll link to the repository as well as including the code here. If it's an issue that images need to be downloaded OR there is another solution please let me know and this post can be deleted and a more appropriate one can be made or I can annoy people on reddit with my questions instead. I suspect a lot of mistakes could probably be spotted without even having to run it it, though.</p>
<p>I'd like broad feedback on the structure of the project and classes that could just be functions but I'm sure there are many many places where I've made faux pas, and so picking up and learning from any one of these would be extremely helpful. It's also big and chunky and could probably be a lot shorter, so help with that without sacrificing readability would be great.</p>
<p>Currently it runs, but it definitely doesn't work like proper chess, lacking a lot of rules and checks/game termination. I'm hoping this isn't an issue, as I <strong>DO</strong> know how I could try to finish this and am not looking for specific solutions, and feel like if there are issues with the structure or efficiency now is when I need to get help, not after I've worked on it for another month. If it is an issue I'll suck it up and post when it fully works, I suppose.</p>
<p>I'm aware that this could be an absolutely pityful attempt, and that it could be better if I just gave up, but I want to persist, and so even if the criticisms are more of a general "what the hell are you doing", I won't mind and can start again structuring the code in a more intelligent and informed way, and I suppose this is the best way to at least try and improve before I get <em>too</em> used to all of my bad habits. I know a few bad practices have been committed here, like using global variables, but I couldn't think of or find a way around them with my small brain, but I'm willing to learn. At the very least, I feel like it's decently commented in most places, although some are probably lacking.</p>
<pre><code>"""A simple chess engine using Python."""
import tkinter as tk
import os
import pathlib
# Global variables
FEN = "rnbqkbnr/pPpppppp/8/8/8/8/P1PPPPPP/RNBQKBNR w KQkq - 0 1"
move_from = None
BLACK = -1
WHITE = 1
en_passant_flag = None
class Piece:
"""
Object for pieces.
Attributes:
colour (int): The colour of the piece, WHITE = 1, BLACK = -1
piece_type (str): The piece type character. Uppercase represents white, lowercase black.
"""
def __init__(self, colour: int = None, piece_type: str = None):
self.colour = colour
self.piece_type = piece_type
class Square:
"""
An object that represents a square.
Attributes:
col (int): Integer value for the column.
row (int): Integer value for the row.
canvas (tk.Canvas): Canvas object for this square, used for changing its appearance (default: None).
piece (Piece): The piece that occupies this square (default: None).
colour (str):
String for the square's color, using tkinter internal colour names (default: None).
http://www.science.smith.edu/dftwiki/index.php/Color_Charts_for_TKinter
"""
def __init__(self, col: int, row: int, canvas: tk.Canvas = None, piece: Piece = None, colour=None):
self.col = col
self.row = row
self.canvas = canvas
self.piece = piece
self.colour = colour
class Move:
"""
A class that represents a move between two Square objects.
Attributes:
square_from (Square): A Square which the Move originates from.
square_to (Square): A Square which is the destination of the Move.
"""
def __init__(self, square_from, square_to):
"""Initialises Move class."""
self.square_from = board.get_square(square_from)
self.square_to = board.get_square(square_to)
def is_legal(self):
"""Method to check if a Move object is legal, using the check_legality function and checking
what player's turn it is."""
if self.square_from.piece is None:
return check_legality(self)
elif self.square_from.piece.colour == board.turn:
return check_legality(self)
else:
return False
def make_move(self):
"""Method for executing a move with a given Move object on the board, given a legal Move."""
if self.is_legal():
if self.square_to.row == 0 or self.square_from.row == 7:
if self.square_from.piece.piece_type.lower() == "p":
promotion_window(self, self.square_to.piece)
self.square_to.piece = self.square_from.piece
self.square_from.piece = None
board.draw()
board.turn = board.turn * -1
# This flags the en passant square
global en_passant_flag
if self.square_from.row == 1 or self.square_from.row == 6:
if self.square_from == square_offset(self.square_to, 0, + self.square_to.piece.colour * 2):
if self.square_to.piece.piece_type.lower() == "p":
en_passant_flag = square_offset(self.square_to, 0, + self.square_to.piece.colour)
else:
en_passant_flag = None
class Board:
"""
Board class.
Attributes:
squares (list): The list of all 64 squares on the board. Created in Board.initialise_squares().
turn (int): Which colour's turn it is; WHITE = 1, BLACK = -1 (default: 1).
"""
def __init__(self):
""" Initialises the Board class. """
self.squares = []
self.turn = WHITE
self.initialise_squares()
self.read_fen(FEN)
self.draw()
def initialise_squares(self):
""" A method for creating the squares of the board. """
for row in range(8):
for col in range(8):
self.squares.append(Square(col, row))
def draw(self):
"""
A method that draws the board.
It uses the Board.squares list and draws each of them, iterating through rows and columns and
fetching each square. It then assigns the colour of the square, creates and assigns a canvas,
binds the functions on clicking to the canvases, and then draws the piece.
Todo:
* Creating a new canvas and re-assigning the colours every time the board updates seems
* inefficient, perhaps separate some functionality into Board.initialise_squares()?
"""
for row in range(8):
for col in range(8):
# Fetches the correct square object to assign its canvas and to read its piece information for drawing
square = self.get_square(Square(col, row))
# Determines the colour of each square
square.colour = "linen" if (col + row) % 2 == 0 else "PaleVioletRed3"
# Creates canvas to represent each square of the correct colour
square.canvas = tk.Canvas(window.board_frame, width=50, height=50, bg=square.colour, bd=0,
highlightthickness=0, relief='ridge')
# Binds commands to the canvas
square.canvas.bind("<Button-1>", lambda e, s=square: square_clicked(e, s))
square.canvas.bind("<Button-3>", lambda e: clear_move())
# If a piece exists it places it
if square.piece is not None:
colour = "w" if square.piece.colour == WHITE else "b"
piece = colour + square.piece.piece_type + ".png"
square.canvas.create_image(24, 25, image=images[piece])
square.canvas.grid(row=row, column=col)
def get_square(self, square: Square):
"""
Returns a specific Square object belonging to Board.squares
when given a square of the same coordinates.
Args:
square (Square): A square whose row and col attributes are read to find the square of the same coordinates.
Returns:
element (Square): The board's Square object, if it exists.
None: if a square with the same coordinates as the argument square doesn't exist.
"""
for element in self.squares:
if element.col == square.col and element.row == square.row:
return element
return None
def read_fen(self, fen_string: str):
"""
Reads a string in FEN format, and assigns relevant variables based off of what it reads.
https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation
Args:
fen_string (str): A string that should be in FEN format with information on the board's status.
Todo:
* Some function that reads the board's status and creates a FEN string.
* Castling rights.
* Remaining values at the bottom of this function.
"""
col = 0
row = 0
fen = fen_string.split()
for char in fen[0]:
if (char == "/") or (col >= 9):
# Skips to the next row if the character is a slash
col = 0
row += 1
continue
if char.isdigit():
# If the FEN string has a number, skip that many columns over
col += int(char)
else:
# This part creates the piece object and assigns it to the correct square
piece_type = char
square = self.get_square(Square(col, row))
col += 1
if char.isupper():
colour = WHITE
else:
colour = BLACK
square.piece = Piece(colour, piece_type)
if fen[1] == "w":
self.turn = WHITE
elif fen[1] == "b":
self.turn = BLACK
for char in fen[2]:
pass
def square_offset(square: Square, col: int, row: int):
"""A function that returns a square offset by a specified row and column values."""
return board.get_square(Square(square.col + col, square.row + row))
def check_legality(move: Move):
"""
A function that takes in a Move object and returns if it is legal.
Args:
move (Move): A Move object between two squares which is checked to see if it is a valid move.
Attributes:
move.square_from (Square):
move.square_to (Square):
A Square for a Move.
Returns:
(Bool): True if the move is legal, False otherwise.
"""
if move.square_from.piece is None:
# If you're trying to move an empty square, it fails
return False
if move.square_to.piece is not None:
if move.square_from.piece.colour == move.square_to.piece.colour:
# If you're trying to capture a piece of the same colour, it fails
return False
# If it gets here we know a piece is moving and isn't trying to capture its own piece - do more checks here
if move.square_from.piece.piece_type.lower() == "p":
# Pawns
# Moving forward if the square is empty
if move.square_to == square_offset(move.square_from, 0, - move.square_from.piece.colour):
if move.square_to.piece is None:
return True
# Moving two squares if on the 2nd or 7th rank
if move.square_to == square_offset(move.square_from, 0, - move.square_from.piece.colour * 2):
if move.square_to.piece is None:
if move.square_from.row == 6 or move.square_from.row == 1:
return True
# Capturing
if move.square_to.piece is not None and move.square_to.piece.colour != move.square_from.colour:
if move.square_to == square_offset(move.square_from, 1, - move.square_from.piece.colour):
return True
if move.square_to == square_offset(move.square_from, -1, - move.square_from.piece.colour):
return True
# Capturing en passant
if move.square_to == en_passant_flag:
if move.square_to == square_offset(move.square_from,-1,- move.square_from.piece.colour):
return True
if move.square_to == square_offset(move.square_from, 1, - move.square_from.piece.colour):
return True
# Movement for sliding pieces
# the list here stores the offsets for all 8 directions which sliding pieces can move.
sliding_directions = [(1, 1), (-1, 1), (1, -1), (-1, -1), (0, 1), (0, -1), (1, 0), (-1, 0)]
if move.square_from.piece.piece_type.lower() == "r":
# Rooks
for i in range(4, 8):
if move.square_to in sliding_move(move.square_from, sliding_directions[i][0], sliding_directions[i][1]):
return True
if move.square_from.piece.piece_type.lower() == "b":
# Bishops
for i in range(4):
if move.square_to in sliding_move(move.square_from, sliding_directions[i][0], sliding_directions[i][1]):
return True
if move.square_from.piece.piece_type.lower() == "q":
# Queens
for i in range(8):
if move.square_to in sliding_move(move.square_from, sliding_directions[i][0], sliding_directions[i][1]):
return True
if move.square_from.piece.piece_type.lower() == "k":
# Kings
for i in range(8):
if move.square_to == square_offset(move.square_from, sliding_directions[i][0], sliding_directions[i][1]):
return True
if move.square_from.piece.piece_type.lower() == "n":
# Knights
knight_moves = ((2, 1), (2, -1), (-2, 1), (-2, -1), (1, 2), (1, -2), (-1, 2), (-1, -2))
for m in knight_moves:
if move.square_to == square_offset(move.square_from, m[0], m[1]):
return True
return False
def sliding_move(square: Square, col_offset: int, row_offset: int, original_square: Square = None):
"""
A function to calculate a list of squares a sliding piece can move to in a line with a given offset direction,
for both straight and diagonal moving pieces.
Args:
square (Square): The original square to check from.
col_offset (int): Integer value for the column offset.
row_offset (int): Integer value for the row offset.
original_square (Square):
A temporary variable that is used to store the original square, to
see see if a piece on a square we check can be captured (default: None).
Todo:
* This doesn't need to be recursive and may be more readable and faster if refactored.
"""
# This is meant to be for capturing
if original_square is None:
original_square = square
temp_square = square_offset(square, col_offset, row_offset)
if temp_square is None:
return [square]
if temp_square.piece is not None:
if temp_square.piece.colour == original_square.colour:
return [square]
else:
return [square] + [temp_square]
else:
return [temp_square] + sliding_move(temp_square, col_offset, row_offset, original_square)
def square_clicked(event: tk.Event, square: Square):
"""
A function which allows a player to make moves by clicking pieces on the board.
It checks to see if a piece has already been clicked; if not, it will store the Square
in the global move_from variable, highlight the square to visually differentiate it,
and highlights possble moves from that square. If a Square has already been stored
before this function is triggered again, it will make the move and redraw the board.
Args:
event (tk.Event): The Tkinter event. Not currently used.
square (Square): The Square object that has been clicked.
Todo:
* Generate all legal moves elsewhere and fetch them instead of iterating through every square
when highlighting legal moves.
"""
square = board.get_square(square)
global move_from
if move_from is None:
square.canvas.config(bg="red")
move_from = square
for squ in board.squares:
if move_from is not squ:
if Move(move_from, squ).is_legal():
squ.canvas.create_oval(20, 20, 30, 30, fill="orange")
else:
if move_from == square:
move_from = None
board.draw()
return
Move(move_from, square).make_move()
move_from = None
board.draw()
def clear_move():
"""Function to clear the global make_move variable, used in square_clicked().
Todo:
* move_from could be one of board's variables instead of global?
"""
global move_from
move_from = None
board.draw()
class Window:
"""A static class used for drawing the UI."""
def __init__(self):
main_frame = tk.Frame(root, width=1200, height=600, bg="white")
main_frame.grid(row=0, column=0)
self.board_frame = tk.Frame(main_frame, height=400, width=400, bd=10, bg="pink")
self.board_frame.grid(row=0, column=0)
right_frame = tk.Frame(root, width=600)
right_frame.grid(row=0, column=1, rowspan=2)
bottom_left_frame = tk.Frame(root, width=420, height=200)
bottom_left_frame.grid(row=1, column=0)
fen_string_entry = tk.Entry(bottom_left_frame, width=40, relief="flat", bd=4)
fen_string_entry.grid(row=0, column=0)
reset_button = tk.Button(bottom_left_frame, width=10, relief="groove", pady=10, text="Reset",
command=lambda: self.reset())
reset_button.grid(row=1, column=0)
def reset(self):
"""Resets the board to its original state."""
board.squares.clear()
board.initialise_squares()
board.read_fen(FEN)
board.draw()
def promotion_window(move: Move, other_piece: Piece):
"""
Function that displays pawn promotion options.
Todo:
* Expand for both colours (currently, black pawns can't promote).
"""
w = tk.Toplevel(root)
w.title("Promote pawn")
w.geometry("264x90")
b1 = tk.Button(w, image=images["wN.png"], command=lambda: promote_piece(move, w, "N")).grid(row=0, column=0)
b2 = tk.Button(w, image=images["wB.png"], command=lambda: promote_piece(move, w, "B")).grid(row=0, column=1)
b3 = tk.Button(w, image=images["wQ.png"], command=lambda: promote_piece(move, w, "Q")).grid(row=0, column=2)
b4 = tk.Button(w, image=images["wR.png"], command=lambda: promote_piece(move, w, "R")).grid(row=0, column=3)
bC = tk.Button(w, text="cancel", command=lambda: cancel_promotion(move, w, other_piece)).grid(row=1, column=0,
columnspan=4)
def cancel_promotion(move, w, other_piece):
"""Undoes piece promotion and closes the promotion window."""
w.destroy()
move.square_from.piece = move.square_to.piece # Swaps pieces
move.square_to.piece = other_piece
board.turn = board.turn * -1
board.draw()
a = 1
b = 2
a, b = b, a
def promote_piece(move: Move, w: tk.Toplevel, piece: str):
"""Promotes a pawn to a piece given by the piece string."""
move.square_to.piece.piece_type = piece
board.draw()
w.destroy()
if __name__ == "__main__":
root = tk.Tk()
# This just fetches images from the folder images, creates tkinter PhotoImage classes
# and stores them in a dictionary with the file name as the key for easy access
# TODO - there's got to be a cleaner way of both retrieving the files, and maybe don't rely on file names?
images = {}
local_dir = pathlib.Path(__file__).parent.absolute()
image_dir = os.path.join(local_dir, "images")
for filename in os.listdir(image_dir):
images[filename] = tk.PhotoImage(file=image_dir + "/" + filename)
# Makes the window that the board is drawn in
window = Window()
# Creates the main board whose __init__ method has calls to other functions to initialise the game
board = Board()
root.mainloop()
</code></pre>
<p>Here's the github so you can run the code by downloading it, because it relies on image files. <a href="https://github.com/Dewi-Payne/python-chessengine" rel="noreferrer">https://github.com/Dewi-Payne/python-chessengine</a></p>
<p>Thank you very much for your time. This is my first code review so I expect there are a few things in this post people might be angry at me for, if stackoverflow is anything to go on.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T09:27:09.427",
"Id": "525557",
"Score": "4",
"body": "Don't be so hard on yourself, this is significantly better than most the crud you see on SO, nice docstrings and clear variable names are a good start:) Hope you get some useful feedback!"
}
] |
[
{
"body": "<p>In no particular order:</p>\n<ul>\n<li>I found FEN notation very interesting! Thanks for sharing that.</li>\n<li><code>FEN</code> being a global that's read during <code>__init__</code> does not make sense. Instead, pass a <code>fen</code> parameter (as optional) that, if <code>None</code>, sets out a standard starting board.</li>\n<li>Consider adding PEP484 type hints to your method signatures</li>\n<li>This:</li>\n</ul>\n<pre><code> square = self.get_square(Square(col, row))\n</code></pre>\n<p>is suspicious. To <em>fetch</em> a <code>Square</code>, you shouldn't have to <em>construct</em> a <code>Square</code>. <code>get_square</code> should accept row and column integer arguments.</p>\n<ul>\n<li>I don't think that <code>tk.Canvas</code> should be reconstructed on every <code>draw</code> call. Instead, make one of these during your own <code>__init__</code> constructor and hold onto a reference.</li>\n<li><code>Square</code> is a clear use case for a <code>@dataclass</code> with no explicit <code>__init__</code>.</li>\n<li><code>check_legality</code> should just be a method on <code>Move</code>.</li>\n<li>This <code>if</code> block:</li>\n</ul>\n<pre><code> if self.square_from.piece is None:\n return check_legality(self)\n elif self.square_from.piece.colour == board.turn:\n return check_legality(self)\n else:\n return False\n</code></pre>\n<p>can just be</p>\n<pre><code>return (\n self.square_from.piece and self.square_from.piece.colour\n) == board.turn and self.check_legality()\n</code></pre>\n<ul>\n<li>You're conflating presentation and logic. <code>make_move</code> should not need to call <code>draw</code>.</li>\n<li><code>board.turn * -1</code> can just be <code>-board.turn</code>.</li>\n<li>Your globals <code>move_from</code> and <code>en_passant_flag</code> break re-entrance and need to be moved to class state.</li>\n<li><code>self.square_from.row == 1 or self.square_from.row == 6</code> can be <code>self.square_from.row in {1, 6}</code></li>\n<li>Your <code>BLACK</code> and <code>WHITE</code> would be better represented using an <code>Enum</code>.</li>\n<li>Reduce your dependence on lambdas where they can be plain function references instead. This:</li>\n</ul>\n<pre><code>square.canvas.bind("<Button-3>", lambda e: clear_move())\n</code></pre>\n<p>can just be</p>\n<pre><code>square.canvas.bind("<Button-3>", clear_move)\n</code></pre>\n<p>so long as <code>clear_move</code> is made to accept and ignore the event parameter.</p>\n<ul>\n<li>Your <code>check_legality</code>, if you were to drink the OOP coolaid, would be torn apart, and each <code>move.square_from.piece.piece_type.lower() ==</code> check would be replaced by a polymorphic method override in a child class written for that piece type.</li>\n<li>This block should be deleted:</li>\n</ul>\n<pre><code> a = 1\n b = 2\n a, b = b, a\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T15:47:10.047",
"Id": "266101",
"ParentId": "266085",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "266101",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T02:18:36.383",
"Id": "266085",
"Score": "5",
"Tags": [
"python",
"object-oriented",
"chess"
],
"Title": "I'm writing a python chess UI+backend and I would like feedback on where there are issues before I continue to expand it"
}
|
266085
|
<p>I'm currently writing a game of chess, and, more specifically, I'm creating the code for the game board. The board is simply a static class that contains a multi-dimensional array representing the board, and methods to interact with it. The method in question for the purposes of <em>this</em> question, is called <code>TryGetEntity</code>:</p>
<pre><code>private static GameEntity[,] _board = new GameEntity[8,8];
...
public static bool TryGetEntity(BoardCoordinate requestedPosition, out GameEntity occupyingEntity) {
occupyingEntity = null;
if (_board.GetLength(0) < requestedPosition.X || _board.GetLength(1) < requestedPosition.Y)
return false;
if (_board[requestedPosition.X, requestedPosition.Y] != null)
occupyingEntity = _board[requestedPosition.X, requestedPosition.Y];
else return false;
return true;
}
</code></pre>
<p>My concern with this implementation is the default return value of <code>true</code>. I've been taught over many years to assume failure which loosely translates to returning <code>false</code> by default. Currently, I'm at war with myself on refactoring this to:</p>
<pre><code>occupyingEntity = null;
if (_board.GetLength(0) >= requestedPosition.X || _board.GetLength(1) >= requestedPosition.Y) {
if (_board[requestedPosition.X, requestedPosition.Y] != null) {
occupyingEntity = _board[requestedPosition.X, requestedPosition.Y];
return true;
}
}
return false;
</code></pre>
<p>I personally think that the second version reads better, but I'm wanting a second (or more) opinion on it.</p>
<hr />
<p><em><strong>Edit</strong>: Per request from the comments, here is the entire <code>GameBoard</code> class, along with an example use-case (this project is still in very early phases, so no actual calls exist yet):</em></p>
<pre><code>public static class GameBoard {
private static GameEntity[,] _board = new GameEntity[8,8];
public static bool TryGetEntity(BoardCoordinate requestedPosition, out GameEntity occupyingEntity) {
occupyingEntity = null;
if (_board.GetLength(0) >= requestedPosition.X || _board.GetLength(1) >= requestedPosition.Y) {
if (_board[requestedPosition.X, requestedPosition.Y] != null) {
occupyingEntity = _board[requestedPosition.X, requestedPosition.Y];
return true;
}
}
return false;
}
}
// Example use-case:
var requestedCoordinate = new BoardCoordinate(3, 3);
if (GameBoard.TryGetEntity(requestedCoordinate, out GameEntity occupyingPiece))
CapturePiece(occupyingPiece);
else
MoveToPosition(requestedCoordinate);
</code></pre>
<hr />
<p>Does this implementation of the try pattern, in its originally presented state, seem easy to follow? How about the second version?</p>
<p><em><strong>Edit</strong>: I <strong>think</strong>, that by posting this question, I sort-of answered it. Given that it made me stop and seek a second opinion in its original state, I suspect the same would be true for others. Additionally, now that I've gotten some sleep, the first version is much harder to read than the second. It's not more complex, just, cluttered and doing too much. I'll keep this question up for others to answer in greater detail, but I'm not going to be surprised if the consensus is "the first method is harder to read".</em></p>
<p><sub><em><strong>Note</strong>: Let's ignore formatting for this post.</em></sub></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T09:41:33.043",
"Id": "525563",
"Score": "3",
"body": "Any an all critiques of the code should be posted in answers. Posting critiques of the code in comments are subject to removal for being a violation of the [commenting privilege](https://codereview.stackexchange.com/help/privileges/comment) - \"Comments are not recommended for any of the following: Answering a question or providing an alternate solution to an existing answer; instead, post an actual answer (or edit to expand an existing one);\"."
}
] |
[
{
"body": "<p>Yes the code is readable.</p>\n<p>I'm curious why you feel you need multiple return statements. The return statement can return a boolean expression.</p>\n<pre><code>public static class GameBoard\n{\n private static GameEntity[,] _board = new GameEntity[8, 8];\n public static bool TryGetEntity(BoardCoordinate requestedPosition, out GameEntity occupyingEntity)\n {\n occupyingEntity = null;\n if (_board.GetLength(0) >= requestedPosition.X || _board.GetLength(1) >= requestedPosition.Y)\n {\n if (_board[requestedPosition.X, requestedPosition.Y] != null)\n {\n occupyingEntity = _board[requestedPosition.X, requestedPosition.Y];\n }\n }\n\n return occupyingEntity != null;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T14:24:37.410",
"Id": "525582",
"Score": "1",
"body": "I *think* I wrote it that way due to lack of sleep and all the while trying to be explicit with the intent of the code. By far, I like this approach **much** more than my initial version. Thanks for taking the time to answer!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T16:50:27.517",
"Id": "525596",
"Score": "3",
"body": "IMHO this is a bad solution. `_board[requestedPosition.X, requestedPosition.Y]` gets used twice, plus there is a second level of `if` and that second level isn't even necessary since if `_board[requestedPosition.X, requestedPosition.Y]` is null, there is no danger in assigning that value to `occupyingEntity` anyway."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T13:53:51.223",
"Id": "525676",
"Score": "0",
"body": "@BCdotWEB IMHO, this answer is true to the message it's trying to convey, regardless of the redundant array access. The takeaway here is to return an expression instead of utilizing multiple return statements. As such, I wouldn't say this is a bad solution, in-fact, it's a great solution; it just has an oversight on the redundancy."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T14:23:01.577",
"Id": "266099",
"ParentId": "266086",
"Score": "9"
}
},
{
"body": "<p>First version:</p>\n<ul>\n<li>You shouldn't omit braces, <code>{}</code>, although they might be optional, because that can lead to hidden and therefore hard-to-track bugs. Having braces helps structuring the code as well.</li>\n<li>Instead of the <code>else</code> you just could return early inside the <code>if</code> block and have a <code>return false;</code> afterwards.</li>\n</ul>\n<p>This would result in</p>\n<pre><code>public static bool TryGetEntity(BoardCoordinate requestedPosition, out GameEntity occupyingEntity)\n{\n occupyingEntity = null;\n if (_board.GetLength(0) < requestedPosition.X || _board.GetLength(1) < requestedPosition.Y)\n {\n return false;\n }\n\n if (_board[requestedPosition.X, requestedPosition.Y] != null)\n {\n occupyingEntity = _board[requestedPosition.X, requestedPosition.Y];\n return true;\n }\n return false;\n}\n</code></pre>\n<p>which is IMO easy to read.</p>\n<p>The second version:</p>\n<p>Well, I think the nested <code>if</code>s are hurting readability. I would at least keep the first <code>if</code> separately and would change the ..... no, forget it. I would just take the first version and change it like so</p>\n<pre><code>public static bool TryGetEntity(BoardCoordinate requestedPosition, out GameEntity occupyingEntity)\n{\n occupyingEntity = null;\n if (_board.GetLength(0) < requestedPosition.X || _board.GetLength(1) < requestedPosition.Y)\n {\n return false;\n }\n\n occupyingEntity = _board[requestedPosition.X, requestedPosition.Y];\n return occupyingEntity != null;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T09:59:51.483",
"Id": "525653",
"Score": "4",
"body": "Just because you _can_ add braces everywhere doesn't mean you _have to_. When you have lots of `if... else if ... else if ... else` and they're all one-liners, you double the length by adding the redundant braces. I agree, though, that if at least one of the `if`'s needs the braces, the whole block should get them."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T14:33:14.447",
"Id": "266100",
"ParentId": "266086",
"Score": "10"
}
},
{
"body": "<p>I don't know C#, but this is what Nullable types are for. From what I can tell, they obsolete the <code>TryX</code>+<code>out</code> parameter combination.</p>\n<p>So your method signature should be more like:</p>\n<pre><code>public static GameEntity? GetEntity(BoardCoordinate requestedPosition)\n</code></pre>\n<p>Where you either return a valid GameEntity directly, or just <code>return null</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T19:56:41.653",
"Id": "525610",
"Score": "2",
"body": "Not sure if this was the answer you were speaking on earlier, but it's a great point. Since you pointed out that you're not well versed in C#, I'd like to point out that `GameEntity` is a reference type, and as such it is null by default. However, it would be good practice if I added explicit declaration that `null` is permitted within my method by using the nullable annotation `GameEntity?` as you suggest. +1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T20:01:27.547",
"Id": "525611",
"Score": "0",
"body": "@Tacoタコス Yep, and then you get a nicer syntax at the callsite :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T22:45:57.010",
"Id": "525619",
"Score": "2",
"body": "A significant amount of the time, enough to feel like always, when I program (in Python) I use `if None is not (value := foo.get(bar)):`. I did like C# having `tryGet` because it'd make all those if statements quite a bit nicer IMO - `if foo.tryGet(bar, value):`. Ultimately I think providing _both_ a `tryGet` and `get` gives the user the ability to pick the nicest option for the situation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T09:51:43.707",
"Id": "525652",
"Score": "0",
"body": "Try to beat `if (board.TryGetPiece( position, out var piece ))` in terms of nice syntax with `Nullable` and lots of `?`... perhaps in the future, but right now you can't even write `piece?.Color = red;`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T15:19:15.243",
"Id": "525686",
"Score": "0",
"body": "\"but right now you can't even write `piece?.Color = red;`\" Has that syntax not shipped yet?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T16:00:44.160",
"Id": "525692",
"Score": "0",
"body": "@Haukinger `?.` is pretty good in C#. Additionally if you need `?.{foo} = {bar}` then you're just abusing `null`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T06:16:45.960",
"Id": "525724",
"Score": "0",
"body": "@Peilonrayz don't get me wrong, `?.` is great, no discussion whatsoever. Why do you think `if (foo != null) foo.Something = bar;` is abusing `null`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T09:35:14.250",
"Id": "525740",
"Score": "0",
"body": "@Haukinger If you're needing `?.{foo} = {bar}` to the point nulls are not nice then the objects in your code are partially initialized. I had similar ideas back when I was a noob and had partially initialized state all over my code. One place where it could be compelling is a REST microservice which mutates the output of another REST service, but using dictionaries and lists with a FP/MP approach is better than building objects."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T10:34:06.390",
"Id": "525747",
"Score": "0",
"body": "@Peilonrayz exactly. I'd never use properties for building objects (except for the new init-only-properties). _Changing_ an object's property is completely fine, though, from one valid state to another. In this case, `nullable?.Property = newValue;` is a nice shorthand to hide an `if` when [issue 2883](https://github.com/dotnet/csharplang/issues/2883) is implemented."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T19:18:28.120",
"Id": "266105",
"ParentId": "266086",
"Score": "5"
}
},
{
"body": "<p>Your first version of <code>TryGetEntity</code> essentially follows this structure:</p>\n<pre><code>public static bool TryGetEntity(BoardCoordinate x, out GameEntity ret) {\n ret = null;\n if (condition1)\n return false;\n \n if (! condition2)\n ret = value;\n else return false;\n return true;\n}\n</code></pre>\n<p>It’s otherwise clean, but this structure is just … weirdly inconsistent. Why not write the conditions as consistent guard clauses with early exits, and put the successful code path at the end (saving one <code>else</code> in the process)?</p>\n<pre><code>public static bool TryGetEntity(BoardCoordinate x, out GameEntity ret) {\n ret = null;\n\n if (condition1)\n return false;\n if (condition2)\n return false;\n \n ret = value;\n return true;\n}\n</code></pre>\n<p>This makes the logic much more obvious.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T22:09:40.197",
"Id": "266111",
"ParentId": "266086",
"Score": "4"
}
},
{
"body": "<p>I don't know C# but this is how I would write the code</p>\n<pre><code>public static class GameBoard {\n private static GameEntity[,] _board = new GameEntity[8,8];\n public static GameEntity TryGetEntity(x, y) {\n if (_board.GetLength(0) < x && _board.GetLength(1) > y)\n return null;\n \n return _board[x, y];\n }\n}\n\n// Example use-case:\nGameEntity occupyingPiece = GameBoard.TryGetEntity(3,3);\nif (occupyingPiece != null)\n CapturePiece(occupyingPiece);\nelse\n MoveToPosition(3,3);\n</code></pre>\n<p>Syntax might not be 100% correct, as I said I don't know much C#, but the theme should be the same:</p>\n<ol>\n<li>Do your checks and return null rather than true/false</li>\n<li>Check for null on return, better on a variable than on a function</li>\n<li>Coordinates class seemed redundant</li>\n</ol>\n<p>Without seeing your entire code something tells me that your choice of statics is a bit exaggerated.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T08:16:08.253",
"Id": "525645",
"Score": "1",
"body": "Thanks for taking the time to answer, and welcome to CodeReview! The try pattern is designed to return a boolean value indicating if the attempt was successful or not. It’s great to explicitly check for null after getting the value back out, though if the method returns false, we already know the output is invalid and as such, within the scope of the use-case, we don’t use the it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T09:30:31.663",
"Id": "525650",
"Score": "0",
"body": "@Tacoタコスreturning a boolean result and a value makes redundant code/logic and makes the program prone to errors. If the function returns false then the returned value must be null, and if the function returns true then the returned value must not be null. Any other scenario (which can happen with the original code) is wrong and would require development time tracing the problem.\nI will admit that I am not familiar with a 'try pattern', is it a design pattern? Even if it is, design patterns are guidelines or skeleton structures and can/should be adapted where it makes sense."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T09:50:00.633",
"Id": "525651",
"Score": "2",
"body": "@slepax It’s an established pattern in C#. Yes, there are better modern solutions but the API pattern is from a time before C# supported those. To stay consistent with those APIs, the pattern persists, and it’s best practice to follow it. At any rate the pattern really isn’t error-prone at all, just unnecessarily verbose."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T06:38:57.380",
"Id": "266117",
"ParentId": "266086",
"Score": "-1"
}
},
{
"body": "<p>To me the code presented by @pacmaninbw is close to what I would write, but I would simplify it to avoid the second if-statement giving:</p>\n<pre><code>public static bool TryGetEntity(BoardCoordinate requestedPosition, out GameEntity occupyingEntity) {\n occupyingEntity = null;\n\n if (_board.GetLength(0) >= requestedPosition.X || _board.GetLength(1) >= requestedPosition.Y) {\n occupyingEntity = _board[requestedPosition.X, requestedPosition.Y];\n }\n\n return occupyingEntity != null;\n}\n</code></pre>\n<p>I also find that this style of <code>{...}</code> is less impactful making it easier to consistently add it everywhere.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T07:54:16.640",
"Id": "266119",
"ParentId": "266086",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "266100",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T02:40:24.120",
"Id": "266086",
"Score": "6",
"Tags": [
"c#"
],
"Title": "Is this try pattern to fetch entities from a chess board, easy to follow?"
}
|
266086
|
<p>Well, it's not actually a <em>schema validator</em> but anyway...</p>
<h1>Motivation</h1>
<p>I'm writing a library which is a UI to work with some electronics - modules. Each real module is represented by a corresponding class in the library. I've decided to add the ability to program a module at once using the <em>config</em> entity. Also it should be possible to <em>read</em> the current configuration from a module. Also I want a user could save (load) config to (from) file on disk, and that data should be human readable and editable. So I've chosen <strike>death</strike> JSON as a config entity.</p>
<p>So my classes have the following member functions:</p>
<pre><code>void ReadConfig( json& config );
void WriteConfig( const json& config );
</code></pre>
<p>As an <strong>advantage</strong> I have a polymorphic object here : I don't need many different configs for each class.</p>
<p>As a <strong>disadvantage</strong> well ... the same. Having such a polymorphic object makes it impossible to check actions with wrong configs at compile time, for example, passing the discriminator config to program an ADC.</p>
<h1>Solution</h1>
<p>I've decided that any configurable module must have a default config (some kind of schema) which values, if any, are <code>null</code>s. For example:</p>
<pre><code>{
"name": "V2718",
"settings": {
"inputs": [
{
"led_polarity": null,
"polarity": null
},
{
"led_polarity": null,
"polarity": null
}
],
...
}
</code></pre>
<p>So the config is correct <em>if and only if it can be obtained from the default one using only replacements of <code>null</code>s</em>. How do I check this? The answer is <a href="https://datatracker.ietf.org/doc/html/rfc6902" rel="nofollow noreferrer">JSON Patch</a>.</p>
<h1>Code</h1>
<p>Here is the code (see the <code>Validate</code> member function). Each module-class inherits from the <code>UConfigurable</code> abstract class. Of course, I could provide code for the <code>Validate</code> function only, but I think the whole header is more consistent.</p>
<h2>UConfigurable.h</h2>
<pre><code>#ifndef V_PLUS_CONFIGURABLE_H
#define V_PLUS_CONFIGURABLE_H
#include <nlohmann/json.hpp>
#include <iostream>
namespace vmeplus
{
using json = nlohmann::json;
// Curiously recurring template pattern
template <typename T>
class UConfigurable
{
protected :
static json fDefaultConfig;
public :
UConfigurable() {};
virtual ~UConfigurable() {};
virtual void ReadConfig( nlohmann::json &config ) = 0;
virtual void WriteConfig( const nlohmann::json &config ) = 0;
static json GetDefaultConfig() { return fDefaultConfig; }
static bool Validate( const json& source );
};
template<typename T>
bool UConfigurable<T>::Validate( const json& source )
{
bool verdict = true;
json patch = json::diff( source, fDefaultConfig );
for( auto it = patch.begin(); it != patch.end(); ++it )
{
// key "op" MUST be in any patch according to
// https://datatracker.ietf.org/doc/html/rfc6902
// and its value MUST be one of the following
// "add", "remove", "replace", "move", "copy", or "test"
if( it->at("op") == "replace" )
{
// if "op" is "replace" then there MUST be the "value" key
if( not (it->at("value").is_null()) )
{
verdict = false;
break;
}
}
else
{
verdict = false;
break;
}
}
return verdict;
}
void WriteConfigToFile( const json& j, const std::string& path );
json ReadConfigFromFile( const std::string& path );
}
#endif
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T20:34:41.050",
"Id": "525616",
"Score": "1",
"body": "Seems like you're sort of trying to re-invent [`JSON Schema`](https://json-schema.org/). If you're interested primarily in the end result, maybe it would be easier to use this instead?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T14:49:40.593",
"Id": "525681",
"Score": "0",
"body": "@JerryCoffin, No, I'm not trying to re-invent JSON Schema. I knew about it when I was writing this post. Of course, JSON Schema would be more appropriate here, but then I would have to write a schema instead of a default config =)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T17:10:07.620",
"Id": "525699",
"Score": "1",
"body": "I use [ThorsSerializer](https://github.com/Loki-Astari/ThorsSerializer/blob/master/doc/example1.md) to convert to/from JSON for storage. But while in the application it is a standard C++ object (thus you don't have to check for the correct type it is or it does not compile). Note: It supports polymorphic objects and strict validation if you need it out of the box."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T07:43:24.313",
"Id": "525731",
"Score": "0",
"body": "@MartinYork, looks cool ! Thank you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-16T10:57:48.213",
"Id": "528584",
"Score": "0",
"body": "I want to also mention the [cereal](https://uscilab.github.io/cereal/index.html) library."
}
] |
[
{
"body": "<pre><code> if ( ⋯ ) {\n if ( ⋯ ) {\n verdict = false;\n break;\n }\n }\n else\n {\n verdict = false;\n break;\n }\n }\n return verdict;\n</code></pre>\n<p>Just <code>return false;</code> when you detect a failure case!<br />\nThen <code>return true;</code> if you reach the end.</p>\n<p>You get:</p>\n<pre><code> if ( ⋯ ) {\n if ( ⋯ ) return false;\n }\n else return false;\n }\n return true;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T14:52:36.643",
"Id": "525682",
"Score": "0",
"body": "I prefer only one `return` in a function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T17:13:17.487",
"Id": "525700",
"Score": "2",
"body": "@LRDPRDX Thats very C like and not very C++ like."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T04:08:04.687",
"Id": "525721",
"Score": "3",
"body": "This is a great point. Using one `return` means you have more complex control flow and state (extra boolean variable). It's mostly a historical antipattern nowadays. See [Where did the notion of “one return only” come from?](https://softwareengineering.stackexchange.com/questions/118703/where-did-the-notion-of-one-return-only-come-from/118717#118717). If the function is too complex, break it out into a subroutine such that it has fewer/one return, then the parent function can operate at a higher level with a single return as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T15:12:00.720",
"Id": "525766",
"Score": "2",
"body": "@LRDPRDX \"one `return` in a function\" is an anti-pattern that is contrary to good C++. Instead you should \"keep to the left\", and avoid extra state variables and \"dead flow\" to drain out of the function when you're actually done. Look how much smaller it gets in this example: eliminate the `break` and you have a clean single-statement in a if/else branch so you get rid of the braces too, and you delete 8 lines."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-19T09:17:36.327",
"Id": "525842",
"Score": "0",
"body": "@JDługosz, I must agree :). Honestly, I try to avoid local variables in my code, but I used to follow the \"one return\" rule (don't remember why)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-19T14:41:22.133",
"Id": "525866",
"Score": "1",
"body": "@LRDPRDX _I don't remember why_ My guess would be an obsolete coding standard you had to use when you were learning. That's why it's good to keep re-evaluating our patterns; the best practices change over a period of years, based on updates to the language and library as well as discussions within the C++ community."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T14:44:13.870",
"Id": "266133",
"ParentId": "266090",
"Score": "2"
}
},
{
"body": "<p>Following on from @JDlugosz</p>\n<p>I would simplify the code to:</p>\n<pre><code>// Why is this a template class!!!!\n// I don't see any use of the type "T"?\n// Could we move it to a base class that is not templated?\n// or is this an artifact of simplifying the code for review?\ntemplate<typename T>\nbool UConfigurable<T>::Validate( const json& source )\n{\n json patch = json::diff( source, fDefaultConfig );\n\n // Use the (new*) range based for loop\n for(auto const& it: patch)\n {\n // key "op" MUST be in any patch according to\n // https://datatracker.ietf.org/doc/html/rfc6902\n // Therefore "op" must be "replace"\n if( it.at("op") != "replace" ) {\n return false;\n }\n\n // if "op" is "replace" then there MUST be the "value" key\n if( not (it.at("value").is_null()) ) {\n return false;\n }\n }\n // If it did not fail.\n // We are good and can return true.\n return true;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-19T09:09:03.723",
"Id": "525839",
"Score": "0",
"body": "1) Why CRTP ? At least for `static json fDefaultConfig`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-19T09:13:53.947",
"Id": "525840",
"Score": "0",
"body": "2) I see your control flow is indeed simpler but less readable I think. Because the key \"value\" is guaranteed to exist only when the \"op\" is \"replace\". So I would prefer @JDlugosz's variant."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-19T17:37:04.440",
"Id": "525881",
"Score": "0",
"body": "1) It has a type `json` not `T`. If you have a default value based on `T` then make getting the default based on a virtual function in the base class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-19T17:39:36.320",
"Id": "525882",
"Score": "0",
"body": "2) Its a subjective call I suppose. I prefer mine as more readable, that's why I wrote it. But no major objection to the original. If I was the senior engineer on a team I would put a note in the code review but not require a change."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-19T17:39:52.770",
"Id": "525883",
"Score": "0",
"body": "3) Yea. I messed up the comment. Fixed it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-19T19:41:52.480",
"Id": "525887",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/128741/discussion-between-lrdprdx-and-martin-york)."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T17:59:02.673",
"Id": "266176",
"ParentId": "266090",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T06:35:37.037",
"Id": "266090",
"Score": "3",
"Tags": [
"c++",
"json"
],
"Title": "Simple \"schema validator\" of JSON using JSON Patch (nlohmann:json)"
}
|
266090
|
<p>I have a headless application that does either of two things.</p>
<ol>
<li>If table does not exist within database create it and copy all the data over</li>
</ol>
<p>OR</p>
<ol start="2">
<li>If table exists update it</li>
</ol>
<p>Now I usually use access layers but this application is a bit older so I can't. This is what I've written.</p>
<pre><code>using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
using System;
using System.Text.RegularExpressions;
using System.Reflection;
namespace FPS_ClientTable_Mirroring
{
class DoWorkController
{
private ApplicationSettings applicationSettings;
internal int Start(ApplicationSettings applicationSettings)
{
string sourceCS = applicationSettings.MSWConnectionString;
string destinationCS = applicationSettings.ClientTableConnectionString;
int doesDbExist = 0;
try
{
this.applicationSettings = applicationSettings;
DateTime yesterday = applicationSettings.ProcessingDate.AddDays(-1);
applicationSettings.Logger.Info("Checking for EODTable within ClientTable");
SqlConnection connectionClientTable = new SqlConnection(destinationCS);
SqlCommand cmd = new SqlCommand("SELECT CASE WHEN OBJECT_ID('dbo.EODTable', 'U') IS NOT NULL THEN 1 ELSE 0 END", connectionClientTable);
connectionClientTable.Open();
doesDbExist = Convert.ToInt32(cmd.ExecuteScalar());
if (doesDbExist == 1)
{
applicationSettings.Logger.Info("Found EODTable within ClientTable");
applicationSettings.Logger.Info("Updating EODTable within ClientTable");
connectionClientTable.Close();
using (SqlConnection mswConnection = new SqlConnection(sourceCS))
{
SqlCommand cmdCopyData = new SqlCommand("Select * from EODTable where TxnDT = @yesterday", mswConnection);
cmdCopyData.Parameters.Add(new SqlParameter("@yesterday", yesterday));
mswConnection.Open();
using (SqlDataReader rdr = cmdCopyData.ExecuteReader())
{
using (SqlConnection ClientTableConnection = new SqlConnection(destinationCS))
{
using (SqlBulkCopy bc = new SqlBulkCopy(ClientTableConnection))
{
bc.DestinationTableName = "EODTable";
ClientTableConnection.Open();
bc.WriteToServer(rdr);
}
}
}
}
applicationSettings.Logger.Info("Finished updating EODTable within ClientTable");
}
else
{
applicationSettings.Logger.Info("EODTable was not found within ClientTable");
applicationSettings.Logger.Info("Creating EODTable within ClientTable");
SqlCommand buildTableCommand = new SqlCommand("CREATE TABLE EODTable(ID bigint, RecID char(64), rectype char(1), mercid varchar(15), termid char(8), edcbatch char(3), batchprdt char(8), batchsrc char(13)");
buildTableCommand.Connection = connectionClientTable;
buildTableCommand.ExecuteNonQuery();
connectionClientTable.Close();
using (SqlConnection mswConnection = new SqlConnection(sourceCS))
{
SqlCommand cmdCopyData = new SqlCommand("Select * from EODTable", mswConnection);
mswConnection.Open();
using (SqlDataReader rdr = cmdCopyData.ExecuteReader())
{
using (SqlConnection ClientTableConnection = new SqlConnection(destinationCS))
{
using (SqlBulkCopy bc = new SqlBulkCopy(ClientTableConnection))
{
bc.DestinationTableName = "EODTable";
ClientTableConnection.Open();
bc.WriteToServer(rdr);
}
}
}
}
applicationSettings.Logger.Info("Finished creating EODTable within ClientTable");
}
applicationSettings.Logger.Info("Checking for EODPayments within ClientTable");
SqlCommand cmdCheckMrPayment = new SqlCommand("SELECT CASE WHEN OBJECT_ID('dbo.EODPayments', 'U') IS NOT NULL THEN 1 ELSE 0 END", connectionClientTable);
connectionClientTable.Open();
doesDbExist = Convert.ToInt32(cmdCheckMrPayment.ExecuteScalar());
if (doesDbExist == 1)
{
applicationSettings.Logger.Info("Found EODPayments within ClientTable");
applicationSettings.Logger.Info("Updating EODPayments within ClientTable");
connectionClientTable.Close();
using (SqlConnection mswConnection = new SqlConnection(sourceCS))
{
SqlCommand cmdCopyData = new SqlCommand("Select * from EODPayments where TransactionDate = @yesterday", mswConnection);
cmdCopyData.Parameters.Add(new SqlParameter("@yesterday", yesterday));
mswConnection.Open();
using (SqlDataReader rdr = cmdCopyData.ExecuteReader())
{
using (SqlConnection ClientTableConnection = new SqlConnection(destinationCS))
{
using (SqlBulkCopy bc = new SqlBulkCopy(ClientTableConnection))
{
bc.DestinationTableName = "EODPayments";
ClientTableConnection.Open();
bc.WriteToServer(rdr);
}
}
}
}
applicationSettings.Logger.Info("Finished updating EODPayments within ClientTable");
}
else
{
applicationSettings.Logger.Info("EODPayments was not found within ClientTable");
applicationSettings.Logger.Info("Creating EODPayments within ClientTable");
SqlCommand buildTableCommand = new SqlCommand("CREATE TABLE EODPayments(ID bigint, ProdID bigint, MercID nchar(15), Currency nchar(3), DbCr nchar(1), Amount float, " +
"Institution nchar(10), Transit nchar(10), AccountNumber nchar(16), EsiAppID nchar(10), TxnType int, ProdType nchar(1), TxnCode nchar(10), TxnDesc nchar(56), " +
"TransactionDate datetime, CoreBankingID bigint, Processed bit, ProcessedDate datetime, DataWarehouse bit, DataWarehouseDate datetime, GLInstitution nchar(10), " +
"GLTransit nchar(10), Converted bit, OriginalAmount float, OriginalCurrency nchar(3), Rate float, EntryID nvarchar(32), GLID nvarchar(32), NewCurrency char(3), SendRate bit) ");
buildTableCommand.Connection = connectionClientTable;
buildTableCommand.ExecuteNonQuery();
connectionClientTable.Close();
using (SqlConnection mswConnection = new SqlConnection(sourceCS))
{
SqlCommand cmdCopyData = new SqlCommand("Select * from EODPayments", mswConnection);
mswConnection.Open();
using (SqlDataReader rdr = cmdCopyData.ExecuteReader())
{
using (SqlConnection ClientTableConnection = new SqlConnection(destinationCS))
{
using (SqlBulkCopy bc = new SqlBulkCopy(ClientTableConnection))
{
bc.DestinationTableName = "EODPayments";
ClientTableConnection.Open();
bc.WriteToServer(rdr);
}
}
}
}
applicationSettings.Logger.Info("Finished creating EODPayments within ClientTable");
}
applicationSettings.Logger.Info("Checking for EODRentals within ClientTable");
SqlCommand cmdCheckRentalFees = new SqlCommand("SELECT CASE WHEN OBJECT_ID('dbo.EODRentals', 'U') IS NOT NULL THEN 1 ELSE 0 END", connectionClientTable);
connectionClientTable.Open();
doesDbExist = Convert.ToInt32(cmdCheckRentalFees.ExecuteScalar());
if (doesDbExist == 1)
{
applicationSettings.Logger.Info("Found EODRentals within ClientTable");
applicationSettings.Logger.Info("Updating EODRentals within ClientTable");
connectionClientTable.Close();
using (SqlConnection mswConnection = new SqlConnection(sourceCS))
{
SqlCommand cmdCopyData = new SqlCommand("Select * from EODRentals where DateProcessed = @yesterday", mswConnection);
cmdCopyData.Parameters.Add(new SqlParameter("@yesterday", yesterday));
mswConnection.Open();
using (SqlDataReader rdr = cmdCopyData.ExecuteReader())
{
using (SqlConnection ClientTableConnection = new SqlConnection(destinationCS))
{
using (SqlBulkCopy bc = new SqlBulkCopy(ClientTableConnection))
{
bc.DestinationTableName = "EODRentals";
ClientTableConnection.Open();
bc.WriteToServer(rdr);
}
}
}
}
applicationSettings.Logger.Info("Finished updating EODRentals within ClientTable");
}
else
{
applicationSettings.Logger.Info("EODRentals was not found within ClientTable");
applicationSettings.Logger.Info("Creating EODRentals within ClientTable");
SqlCommand buildTableCommand = new SqlCommand("CREATE TABLE EODRentals(ID bigint, Year nchar(4), Month nchar(12), DateProcessed datetime, CoreBankingID bigint, " +
"MerchantRecordID bigint, TerminalRecordID bigint, DeployedDate datetime, RecoveredDate datetime, MonthlyFee float, IsProRated bit, DaysActive int, TotalFee float, " +
"IsPinPad bit, Currency nchar(3)) ");
buildTableCommand.Connection = connectionClientTable;
buildTableCommand.ExecuteNonQuery();
connectionClientTable.Close();
using (SqlConnection mswConnection = new SqlConnection(sourceCS))
{
SqlCommand cmdCopyData = new SqlCommand("Select * from EODRentals", mswConnection);
mswConnection.Open();
using (SqlDataReader rdr = cmdCopyData.ExecuteReader())
{
using (SqlConnection ClientTableConnection = new SqlConnection(destinationCS))
{
using (SqlBulkCopy bc = new SqlBulkCopy(ClientTableConnection))
{
bc.DestinationTableName = "EODRentals";
ClientTableConnection.Open();
bc.WriteToServer(rdr);
}
}
}
}
applicationSettings.Logger.Info("Finished creating EODRentals within ClientTable");
}
return 0;
}
catch (System.Exception ex)
{
applicationSettings.Logger.Fatal(ex.ToString());
return applicationSettings.DefaultFailedExitCode;
}
}
}
}
</code></pre>
<p>I was hoping if I can get an idea of how to make this a bit more efficient in what it does. I also am not sure what is the best way to deal with error handling such as in between creating the table the connection is lost.</p>
<p>Any help would be greatly appreciated!</p>
|
[] |
[
{
"body": "<p>You have a lot of redundant code. Also, the <code>Start</code> method is very long and difficult to read. Basically, it executes three times the same procedure applied to different tables. The idea is to create a parametrized method that can be called three times for the three tables. This increases the maintainability of the code. Its signature is</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private int CreateOrUpdateTable(\n string tableName, string dateColumn, string createTableSql)\n</code></pre>\n<p>We can make the code more readable by creating some helper methods. The time to call methods (a few nanoseconds) is negligible compared to the time it takes to perform operations on the DB (milliseconds to seconds or even minutes). Even for milliseconds we have a factor of 1 million to the nanoseconds.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private void LogInfo(string message)\n{\n applicationSettings.Logger.Info(message);\n}\n\nprivate static bool TableExists(SqlConnection connection, string tableName)\n{\n using var cmd = new SqlCommand(\n $"SELECT CASE WHEN OBJECT_ID('dbo.{tableName}', 'U') IS NOT NULL THEN 1 ELSE 0 END",\n connection);\n return (int)cmd.ExecuteScalar() == 1;\n}\n</code></pre>\n<p>Both cases (table exists or not) use the same code to execute a bulk copy. We extract it to a method as well:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private static void ExecuteBulkCopy(\n string tableName, SqlConnection connectionClientTable, SqlCommand cmdCopyData)\n{\n using SqlDataReader rdr = cmdCopyData.ExecuteReader();\n using var bc = new SqlBulkCopy(connectionClientTable);\n bc.DestinationTableName = tableName;\n bc.WriteToServer(rdr);\n}\n</code></pre>\n<p>We can use the new handy using declarations (since C# 8.0 I think). They do not require nested code blocks as the using statements do.</p>\n<p>You create, open, and close the same connections at different places. By creating and opening both connections before the if statement, we can simplify further. Also closing the connections explicitly is not necessary, as the using declarations (or statements) do it automatically.</p>\n<p>We end up with this implementation:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private int CreateOrUpdateTable(string tableName, string dateColumn, string createTableSql)\n{\n string sourceCS = applicationSettings.MSWConnectionString;\n string destinationCS = applicationSettings.ClientTableConnectionString;\n\n try {\n LogInfo($"Checking for {tableName} within ClientTable");\n\n using SqlConnection connectionClientTable = new SqlConnection(destinationCS);\n connectionClientTable.Open();\n\n using SqlConnection mswConnection = new SqlConnection(sourceCS);\n mswConnection.Open();\n\n if (TableExists(connectionClientTable, tableName)) {\n LogInfo($"Found {tableName} within ClientTable");\n LogInfo($"Updating {tableName} within ClientTable");\n\n using var cmdCopyData = new SqlCommand($"Select * from {tableName} where {dateColumn} = @yesterday", mswConnection);\n DateTime yesterday = applicationSettings.ProcessingDate.AddDays(-1);\n cmdCopyData.Parameters.Add(new SqlParameter("@yesterday", yesterday));\n ExecuteBulkCopy(tableName, connectionClientTable, cmdCopyData);\n\n LogInfo($"Finished updating {tableName} within ClientTable");\n } else {\n LogInfo($"{tableName} was not found within ClientTable");\n LogInfo($"Creating {tableName} within ClientTable");\n\n var buildTableCommand = new SqlCommand(createTableSql, connectionClientTable);\n buildTableCommand.ExecuteNonQuery();\n\n var cmdCopyData = new SqlCommand($"Select * from {tableName}", mswConnection);\n ExecuteBulkCopy(tableName, connectionClientTable, cmdCopyData);\n\n LogInfo($"Finished creating {tableName} within ClientTable");\n }\n return 0;\n } catch (System.Exception ex) {\n applicationSettings.Logger.Fatal(ex.ToString());\n return applicationSettings.DefaultFailedExitCode;\n }\n}\n</code></pre>\n<p>The <code>Start</code> method becomes</p>\n<pre class=\"lang-cs prettyprint-override\"><code>internal int Start(ApplicationSettings applicationSettings)\n{\n this.applicationSettings = applicationSettings;\n\n int result = CreateOrUpdateTable("EODTable", "TxnDT", "CREATE TABLE EODTable ...");\n if (result != 0) return result;\n\n result = CreateOrUpdateTable("EODPayments", "TransactionDate", "CREATE TABLE EODPayments ...");\n if (result != 0) return result;\n\n return CreateOrUpdateTable("EODRentals", "DateProcessed", "CREATE TABLE EODRentals ...");\n}\n</code></pre>\n<p>The lengthy create table statements could be created as string resources of the project. This allows you to write them with line breaks and indentations and does not clutter the C# code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T05:07:02.600",
"Id": "525631",
"Score": "0",
"body": "Loved this worked like a charm!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T19:38:36.297",
"Id": "266106",
"ParentId": "266103",
"Score": "1"
}
},
{
"body": "<p>I would suggest creating an abstract class for constructing minimal <code>Sql</code> protected methods such as <code>ExecuteNonQuery</code>, <code>ExecuteScalar</code>, and <code>ExecuteReader</code> ..etc. these methods would be used in inherited classes (Repositories). So, each repository would work with only one table, which would give you a scoped work. This would give you more flexibility and maintainability to your project.</p>\n<p>So, you can start with an abstract class :</p>\n<pre><code>public abstract class SqlRepoistoryBase\n{\n private readonly string _connectionString; \n \n protected SqlRepoistoryBase(string connectionString)\n {\n _connectionString = connectionString;\n }\n\n protected void ExecuteCommand(string query)\n { \n try\n {\n if(string.IsNullOrWhiteSpace(query))\n {\n throw new ArgumentNullException(nameof(query));\n }\n \n using(var connection = new SqlConnection(_connectionString))\n using(var command = new SqlCommand(query, connection))\n {\n connection.Open(); \n command.ExecuteCommand();\n }\n }\n catch (Exception ex)\n {\n applicationSettings.Logger.Fatal(ex.ToString());\n }\n }\n\n \n protected object ExecuteScalar(string query)\n { \n try\n {\n if(string.IsNullOrWhiteSpace(query))\n {\n throw new ArgumentNullException(nameof(query));\n }\n \n using(var connection = new SqlConnection(_connectionString))\n using(var command = new SqlCommand(query, connection))\n {\n connection.Open(); \n return command.ExecuteScalar();\n }\n }\n catch (Exception ex)\n {\n applicationSettings.Logger.Fatal(ex.ToString());\n return null;\n }\n }\n\n //...etc\n}\n</code></pre>\n<p>then, you will do a class for <code>EODTable</code> only, which would contain its logic, something like :</p>\n<pre><code>public class SqlEoDRepoistory : SqlRepoistoryBase \n{\n public SqlEoDRepoistory(string connectionString) \n : base(connectionString) { }\n \n private bool IsTableExist()\n {\n const string query = $"SELECT CASE WHEN OBJECT_ID('dbo.EODTable', 'U') IS NOT NULL THEN 1 ELSE 0 END";\n \n var queryResult = ExecuteScalar(query);\n \n return int.TryParse(queryResult?.ToString(), out int queryResultInt) && queryResultInt == 1;\n }\n \n private void CreateIfNotExists()\n {\n if(!IIsTableExist())\n {\n const string query = "CREATE TABLE EODTable(ID bigint, RecID char(64), rectype char(1), mercid varchar(15), termid char(8), edcbatch char(3), batchprdt char(8), batchsrc char(13)";\n ExecuteCommand(query);\n }\n }\n \n \n public void CopyData()\n {\n if(!IIsTableExist())\n {\n const string query = "CREATE TABLE EODTable(ID bigint, RecID char(64), rectype char(1), mercid varchar(15), termid char(8), edcbatch char(3), batchprdt char(8), batchsrc char(13)";\n ExecuteCommand(query);\n }\n \n const string query = "Select * from EODTable where TxnDT = @yesterday";\n \n var parameters = new SqlParameter[]\n {\n new SqlParameter("@yesterday", yesterday)\n };\n \n // implement CopyFrom in the base, and reuse it in this class\n CopyFrom(query, parameters, destinationTableName: "EODTable");\n \n }\n \n //.... etc \n}\n</code></pre>\n<p>now in the main class <code>DoWorkController</code> would reduce the code to something like :</p>\n<pre><code>public class DoWorkController \n{\n private ApplicationSettings applicationSettings;\n private readonly SqlEoDRepoistory _eodTableRepoistory;\n \n internal int Start(ApplicationSettings settings)\n {\n \n try\n {\n _eodTableRepoistory = new SqlEoDRepoistory(settings.MSWConnectionString);\n _eodTableRepoistory.CopyData();\n \n // you do the same for the EODPayments\n \n return 0;\n }\n catch (System.Exception ex)\n {\n applicationSettings.Logger.Fatal(ex.ToString());\n return applicationSettings.DefaultFailedExitCode;\n }\n }\n \n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T20:37:16.650",
"Id": "266109",
"ParentId": "266103",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "266106",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T17:27:19.443",
"Id": "266103",
"Score": "0",
"Tags": [
"c#",
"sql"
],
"Title": "Efficient way to build table within database or update it using C#"
}
|
266103
|
<p>I write a function which takes as input 2 arrays of zeros and ones ~8000 elements per array. Input array size is variable, can have much higher number of elements. The density of ones is expected to be higher than zeros for most cases, but outliers may exist. My function <code>eps</code> calculates a statistic on these array pairs and returns the output. This statistic is just a way to find if 2 timeseries data correlate with each other.
Relatively trivial operations of checking for 0 and noting the index where 0 is found in array and then some calculations. I tried my best to optimize for speed but the best I could get is 4.5 ~5 seconds (for 18k array pairs) using <code>timeit</code> (1000 runs) library. Fast execution is important as I need to run this function on billions of array pairs.</p>
<p>UPDATE: The solution I tried from the answers below improved runtime for larger inputs than my original approach. However, I still face the problem of running this statistical function a 1000 times per array pair. The background for this is to perform a permutation test on the statistic with 'x' (1000) number of permutations to arrive at a significance level at p= .01
Some asked below why I need to run this function billions of times. So my data is a timeseries data for events: 'E1,E2,E3.....En' I need to find combinations of all possible event pairs from this data i.e. nCr. (E1,E2), (E2,E3)....nCr times. This leads to a large number of event pairs about billions of event pairs for my data. Add to that the time complexity of a permutation test (1000x times/pair). Any suggestions if any other parts like permutation tests can be improved. Thanks<br />
UPDATE2: Is size always ~8000? No it depends on input data, array size can be between 2000 ~ 10,000.
What's your tau value? tau is a random positive integer or float and we jus test for different tau values, so I cannot given a certain Tau.</p>
<pre><code>#e.g. inputs
#ts_1 = [0,1,1,0,0,1,1,0,......] #timeseries1
#ts_2 = [1,1,1,1,1,1,1,0,......] #timeseries2
# tau = positive integer/float #time lag
import numpy as np
from itertools import product
def eps(ts_1, ts_2, tau):
Q_tau = 0
q_tau = 0
event_index1, = np.where(np.array(ts_1) == 0)
n1 = event_index1.shape[0]
event_index2, = np.where(np.array(ts_2) == 0)
n2 = event_index2.shape[0]
if (n1 != 0 and n2 != 0):
matching_idx = set(event_index1).intersection(event_index2)
c_ij = c_ji = 0.5 *len(matching_idx)
for x,y in product(event_index1,event_index2):
if x-y > 0 and (x-y)<= tau:
c_ij += 1
elif y-x > 0 and (y-x) <= tau:
c_ji += 1
Q_tau = (c_ij+c_ji)/math.sqrt( n1 * n2 )
q_tau = (c_ij - c_ji)/math.sqrt( n1 * n2 )
return Q_tau, q_tau
#permutation test
def eps_permutationtest(ts_1,ts_2,permutations=1000,Q_tau): #Q_tau= original statistic to evaluate significance for
lst_Q_tau = [] # list to hold Q_tau values from each shuffle
for i in range(0,permutations):
np.random.shuffle(ts_1) #shuffle ts_1 everytime
Q_tau = eps(ts_1 = ts_1, ts_2 = ts_2 , tau= 5)
lst_Q_tau.append(Q_tau)
lst_Q_tau= np.array(lst_Q_tau)
p_val = len(np.where(lst_Q_tau>= [Q_tau])[0])/permutations
return p_val # significant if p < .01 alpha
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T07:05:52.447",
"Id": "525635",
"Score": "1",
"body": "Welcome to CodeReview@SE. See [How do I ask a Good Question?](https://codereview.stackexchange.com/help/how-to-ask) on how to title your question. Please include clarifications in your post instead of commenting comments. (And keep everything [DRY](https://en.m.wikipedia.org/wiki/Don%27t_repeat_yourself).)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T13:50:25.277",
"Id": "525674",
"Score": "2",
"body": "What are your actual densities? Is size always ~8000? What's your tau value? Do you actually need the billions of results from the billions of array pairs, or are you actually after something else, which might be doable without doing all those pairs?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T14:12:27.343",
"Id": "525679",
"Score": "4",
"body": "Since the statistic calculation is the slow part, I think it would make sense for you to explain what it actually computes. It saves us having to figure out your intentions from the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-20T12:39:34.630",
"Id": "525951",
"Score": "0",
"body": "Why are you running it 1000x per pair? What changes between each of these runs? When you say \"nCr\", do you really mean \"nC2\", that is, you have n arrays, and you want to calculate this statistic for all possible pairs of arrays? Are all n arrays the same size, even if that size varies? Your edit provided some information, but it's still too terse for us to tell what you're actually doing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-20T15:15:15.943",
"Id": "525962",
"Score": "0",
"body": "Hi. I mentioned this loop per pair of 1000 times is called permutation test. The ts_1 is shuffled each time and the statistic is calculated again. This is so as to understand if results are significant, and did not merely occur by chance. This could be called as bootstrapping/resampling. nCr where n is total events and r = 2. This statistic needs to be calculated for all array pairs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-21T15:28:22.267",
"Id": "526007",
"Score": "0",
"body": "When you permute the 1000 times, are you permuting both arrays? Or are you permuting just one of them? Over those 1000 permutations, are you looking for the minimum or the unnamed statistic? Or the average? Or the entire distribution?"
}
] |
[
{
"body": "<p><code>for x,y in product(event_index1,event_index2)</code> looks like an efficiency killer. If the lengths of <code>event_index1, event_index2</code> are <code>L1, L2</code> respectively, this loop has <code>O(L1 * L2)</code> time complexity. You may get away with <code>O(L1 * log L2)</code> (or <code>O(L2 * log L1)</code>, depending on which one is larger.</p>\n<p>Notice that for any given <code>x</code> the <code>c_ij</code> is incremented by the number of <code>y</code>s in the <code>[x - tau, x)</code>range. Two binary searches over <code>event_index2</code> would give you this range, along the lines of</p>\n<pre><code> for x in event_index1:\n c_ij += bisect_left(event_index2, x) - bisect_left(event_index2, x - tau)\n</code></pre>\n<p>and ditto for <code>c_ji</code>. Of course, <code>from bisect import bisect_left</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T02:41:53.117",
"Id": "525627",
"Score": "1",
"body": "In my testing, your binary search suggestion is by far the fastest (though I used Numpy's `search_sorted` implementation rather than native Python)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T02:52:56.950",
"Id": "525629",
"Score": "2",
"body": "@Reinderien `search_sorted` shall indeed be better than native `bisect`. I am not too versed in `numpy` to suggest it. Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T09:01:52.863",
"Id": "525646",
"Score": "0",
"body": "@vnp I really like this solution. I never even thought it could be done using sorting instead of loop iteration."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T23:10:35.670",
"Id": "266112",
"ParentId": "266108",
"Score": "10"
}
},
{
"body": "<p>First, some basics of your implementation:</p>\n<ul>\n<li>Type-hint your arguments; I had to read and investigate a bunch to deduce that <code>tau</code> is a positive integer</li>\n<li><code>(y-x) <= tau</code> does not need parens</li>\n<li>save <code>math.sqrt( n1 * n2 )</code> to a variable instead of repeating it</li>\n</ul>\n<h2>Full matrix implementation</h2>\n<p>This is an n**2 operation, which is on the order of 64,000,000 elements if your arrays are 8,000 elements long. That's beyond the point where I would have given up and used C and something like BLAS. If you <em>actually</em> care about performance, now is the time.</p>\n<p>Your solution scales according to event density, being slower as event density increases. There is a solution that is constant-time in density:</p>\n<ul>\n<li>Don't call <code>np.where</code></li>\n<li>Don't use set intersection; use vectorized comparison</li>\n<li>Recognize that you can represent your <code>c_ij</code> summation as the sum over a partial triangular matrix (<code>ij</code> upper, <code>ji</code> lower) stopping at the diagonal set by <code>tau</code></li>\n<li>The matrix itself is formed by the broadcast of the two event vectors, and receives a mask for the upper and lower halves</li>\n<li>The initial values for <code>c_**</code> are the halved trace (diagonal sum) of this broadcast matrix</li>\n<li>For a given <code>tau</code> and vector lengths, you could save time by pre-calculating the masks (not shown in the reference code). This is very important and can reduce execution time of this method by about two thirds. Many kinds of datasets in the wild have constant dimensions and can benefit from this.</li>\n</ul>\n<p>Somewhere in around 85% ones-density, this method has equivalent performance to the original (for the test vector length of 2000) if you don't pre-calculate the mask.</p>\n<h2>Sparse approach</h2>\n<p>A library that supports sparse matrices should do better than the above. Scipy has them. Things to note about this approach:</p>\n<ul>\n<li>The input data need to be inverted - 1 for events, 0 everywhere else</li>\n<li>Be careful not to call <code>np.*</code> methods; exclusively use sparse methods</li>\n<li>Rather than forming the triangular bands and then summing at the end, it's faster to perform a difference-of-sums using <code>tau</code></li>\n<li>This scales with density, unlike the full-matrix approach, and uses less memory</li>\n</ul>\n<h2>Sorted logarithmic traversal</h2>\n<p>Riffing on @vpn's idea a little:</p>\n<ul>\n<li>This doesn't need to be n**2 if you tell Numpy to correctly apply a binary search</li>\n<li>This binary search can be vectorized via <code>searchsorted</code></li>\n<li>Rather than your Python-native set intersection, you can use <code>intersect1d</code></li>\n</ul>\n<p>For very high ones-densities, this method remains the fastest; but has poorer scaling characteristics than the full-matrix trace-only method for lower ones-densities (higher event densities).</p>\n<h2>Full or sparse matrix, traces only</h2>\n<p>(Yet another) approach is:</p>\n<ul>\n<li>For either sparse or full matrix</li>\n<li>non-masked</li>\n<li>based on diagonal trace sum only, with no calls to the triangular methods</li>\n<li>constant time in density</li>\n</ul>\n<p>Particularly for the full matrix, this method is very fast: always faster than sparse, masked broadcast and original; and faster than logarithmic traversal for densities below ~70%.</p>\n<h2>Cumulative sum</h2>\n<p>For completeness the reference source below includes @KellyBundy's cumulative sum approach, which is competitive for all but very high densities.</p>\n<h2>Output</h2>\n<pre class=\"lang-none prettyprint-override\"><code>All method durations (ms)\n d% trace sorted cumsum old bcast sparse sparsetr\n50.0 0.70 4.12 0.21 491.82 41.73 80.62 21.62 \n55.0 0.64 3.27 0.18 411.49 40.09 65.46 18.25 \n60.0 0.58 2.69 0.18 311.74 40.69 50.05 14.60 \n65.0 0.58 2.27 0.23 250.12 41.50 35.52 13.45 \n70.0 1.03 1.84 0.18 182.37 41.84 24.03 10.20 \n75.0 1.34 1.40 0.18 113.49 42.36 16.37 7.31 \n80.0 0.61 1.06 0.18 77.04 40.99 11.78 6.11 \n85.0 0.81 0.69 0.17 44.68 52.77 10.30 5.95 \n90.0 1.56 0.56 0.22 24.50 46.26 6.32 3.94 \n95.0 1.50 0.26 0.18 6.27 40.60 4.80 3.48 \n96.0 1.77 0.21 0.18 3.71 41.01 4.25 3.31 \n96.5 1.79 0.17 0.18 1.89 40.69 4.16 3.24 \n97.0 1.79 0.16 0.18 1.75 43.89 4.69 3.30 \n97.5 1.87 0.14 0.18 1.16 43.34 4.31 3.22 \n98.0 2.10 0.15 0.19 1.22 41.16 4.10 3.33 \n98.5 1.75 0.10 0.18 0.42 40.75 3.94 3.15 \n99.0 1.73 0.09 0.22 0.16 40.71 3.97 3.11 \n99.5 1.78 0.08 0.18 0.09 41.29 4.09 3.42 \n\nFast method durations (us)\n d% trace sorted cumsum\n50.0 604 3993 124 \n55.0 556 3504 124 \n60.0 577 2895 125 \n65.0 569 2440 130 \n70.0 556 2041 126 \n75.0 574 1372 125 \n80.0 556 1078 123 \n85.0 562 686 126 \n90.0 563 477 128 \n95.0 561 238 126 \n96.0 558 176 126 \n96.5 569 139 124 \n97.0 557 137 131 \n97.5 568 104 124 \n98.0 601 116 128 \n98.5 565 61 128 \n99.0 567 51 129 \n99.5 566 43 127 \n</code></pre>\n<h2>Reference source</h2>\n<pre><code>import math\nfrom numbers import Real\nfrom timeit import timeit\nfrom typing import Tuple\n\nimport numpy as np\nfrom itertools import product\n\nimport scipy.sparse\nfrom scipy.sparse import spmatrix\n\n\ndef old_eps(ts_1, ts_2, tau):\n Q_tau = 0\n q_tau = 0\n\n event_index1, = np.where(np.array(ts_1) == 0)\n n1 = event_index1.shape[0]\n\n event_index2, = np.where(np.array(ts_2) == 0)\n n2 = event_index2.shape[0]\n\n if (n1 != 0 and n2 != 0):\n matching_idx = set(event_index1).intersection(event_index2)\n c_ij = c_ji = 0.5 *len(matching_idx)\n\n for x,y in product(event_index1,event_index2):\n if x-y > 0 and (x-y)<= tau:\n c_ij += 1\n elif y-x > 0 and (y-x) <= tau:\n c_ji += 1\n\n Q_tau = (c_ij+c_ji)/math.sqrt( n1 * n2 )\n q_tau = (c_ij - c_ji)/math.sqrt( n1 * n2 )\n\n return Q_tau, q_tau\n\n\ndef bcast_eps(ts_1: np.ndarray, ts_2: np.ndarray, tau: int) -> Tuple[Real, Real]:\n if ts_1.shape != ts_2.shape or len(ts_1.shape) != 1:\n raise ValueError('Vectors must be flat and of the same length')\n N, = ts_1.shape\n\n events_1 = ts_1 == 0\n events_2 = ts_2 == 0\n n1 = np.sum(events_1)\n n2 = np.sum(events_2)\n if n1 == 0 or n2 == 0:\n return 0, 0\n\n all_true = np.ones((N, N), dtype=bool)\n upper_mask = np.logical_or(np.tril(all_true), np.triu(all_true, k=+1+tau))\n lower_mask = np.logical_or(np.triu(all_true), np.tril(all_true, k=-1-tau))\n\n matches = np.logical_and(events_1[np.newaxis, :], events_2[:, np.newaxis])\n matches_u = np.ma.array(matches, mask=upper_mask)\n matches_l = np.ma.array(matches, mask=lower_mask)\n\n n_matches = np.trace(matches)\n c_ij = c_ji = n_matches / 2\n c_ij += np.sum(matches_u)\n c_ji += np.sum(matches_l)\n\n den = math.sqrt(n1 * n2)\n Q_tau = (c_ij + c_ji) / den\n q_tau = (c_ij - c_ji) / den\n return Q_tau, q_tau\n\n\ndef trace_eps(ts_1: np.ndarray, ts_2: np.ndarray, tau: int) -> Tuple[Real, Real]:\n if ts_1.shape != ts_2.shape or len(ts_1.shape) != 1:\n raise ValueError('Vectors must be flat and of the same length')\n\n events_1 = ts_1 == 0\n events_2 = ts_2 == 0\n n1 = np.sum(events_1)\n n2 = np.sum(events_2)\n if n1 == 0 or n2 == 0:\n return 0, 0\n\n matches = np.logical_and(events_1[np.newaxis, :], events_2[:, np.newaxis])\n n_matches = np.trace(matches)\n c_ij = c_ji = n_matches / 2\n\n for k in range(1, tau+1):\n c_ij += np.trace(matches, k)\n c_ji += np.trace(matches, -k)\n\n den = math.sqrt(n1 * n2)\n Q_tau = (c_ij + c_ji) / den\n q_tau = (c_ij - c_ji) / den\n return Q_tau, q_tau\n\n\ndef sorted_eps(ts_1: np.ndarray, ts_2: np.ndarray, tau: int) -> Tuple[Real, Real]:\n if ts_1.shape != ts_2.shape or len(ts_1.shape) != 1:\n raise ValueError('Vectors must be flat and of the same length')\n\n event_index1, = np.where(np.array(ts_1) == 0)\n event_index2, = np.where(np.array(ts_2) == 0)\n n1, = event_index1.shape\n n2, = event_index2.shape\n\n if n1 == 0 or n2 == 0:\n return 0, 0\n\n n_matches, = np.intersect1d(\n event_index1, event_index2, assume_unique=True,\n ).shape\n c_ij = c_ji = n_matches/2\n\n insertions = np.searchsorted(\n a=event_index1, # array to pretend insertion into\n v=event_index2, # values to insert\n )\n\n for insertion, y in zip(insertions, event_index2):\n i1 = insertion\n if i1 < n1:\n if y == event_index1[i1]:\n i1 += 1\n for x in event_index1[i1:]:\n if x - y > tau:\n break\n c_ij += 1\n\n i2 = insertion - 1\n if i2 >= 0:\n for x in event_index1[i2::-1]:\n if y - x > tau:\n break\n c_ji += 1\n\n den = math.sqrt(n1 * n2)\n Q_tau = (c_ij + c_ji) / den\n q_tau = (c_ij - c_ji) / den\n\n return Q_tau, q_tau\n\n\ndef sparse_eps(ts_1: spmatrix, ts_2: spmatrix, tau: int) -> Tuple[Real, Real]:\n if ts_1.shape != ts_2.shape or len(ts_1.shape) != 2 or ts_1.shape[0] != 1:\n raise ValueError('Vectors must be flat and of the same length')\n\n n1 = ts_1.sum()\n n2 = ts_2.sum()\n if n1 == 0 or n2 == 0:\n return 0, 0\n\n matches = ts_2.T * ts_1\n matches_u = scipy.sparse.triu(matches, +1).sum() - scipy.sparse.triu(matches, k=+1+tau).sum()\n matches_l = scipy.sparse.tril(matches, -1).sum() - scipy.sparse.tril(matches, k=-1-tau).sum()\n\n n_matches = matches.diagonal().sum()\n c_ij = c_ji = n_matches / 2\n c_ij += matches_u\n c_ji += matches_l\n\n den = math.sqrt(n1 * n2)\n Q_tau = (c_ij + c_ji) / den\n q_tau = (c_ij - c_ji) / den\n return Q_tau, q_tau\n\n\ndef sparsetr_eps(ts_1: spmatrix, ts_2: spmatrix, tau: int) -> Tuple[Real, Real]:\n if ts_1.shape != ts_2.shape or len(ts_1.shape) != 2 or ts_1.shape[0] != 1:\n raise ValueError('Vectors must be flat and of the same length')\n\n n1 = ts_1.sum()\n n2 = ts_2.sum()\n if n1 == 0 or n2 == 0:\n return 0, 0\n\n matches = ts_2.T * ts_1\n n_matches = matches.diagonal().sum()\n c_ij = c_ji = n_matches / 2\n\n for k in range(1, tau+1):\n c_ij += matches.diagonal(+k).sum()\n c_ji += matches.diagonal(-k).sum()\n\n den = math.sqrt(n1 * n2)\n Q_tau = (c_ij + c_ji) / den\n q_tau = (c_ij - c_ji) / den\n return Q_tau, q_tau\n\n\ndef cumsum_eps(ts_1: spmatrix, ts_2: spmatrix, tau: int) -> Tuple[Real, Real]:\n ts_1 = 1 - ts_1\n ts_2 = 1 - ts_2\n n1 = ts_1.sum()\n n2 = ts_2.sum()\n if n1 == 0 or n2 == 0:\n return 0, 0\n\n cs1 = np.pad(ts_1.cumsum(), (0, tau), 'edge')\n cs2 = np.pad(ts_2.cumsum(), (0, tau), 'edge')\n c_ij = c_ji = 0.5 * (ts_1 * ts_2).sum()\n c_ij += ((cs1[tau:] - cs1[:-tau]) * ts_2).sum()\n c_ji += ((cs2[tau:] - cs2[:-tau]) * ts_1).sum()\n\n sqrt = math.sqrt(n1 * n2)\n Q_tau = (c_ij + c_ji) / sqrt\n q_tau = (c_ij - c_ji) / sqrt\n return Q_tau, q_tau\n\n\ndef test() -> None:\n shape = 2, 2000\n full_ts = np.ones(shape, dtype=np.uint8)\n sparse_ts = scipy.sparse.lil_matrix(shape, dtype=np.uint8)\n\n density = 0.9\n rand = np.random.default_rng(seed=0).random\n events = rand(shape) > density\n full_ts[events] = 0\n sparse_ts[events] = 1\n\n # Add some interesting values to test boundary conditions: on the diagonal\n full_ts[:, 5] = 0\n sparse_ts[:, 5] = 1\n\n Q_exp = 1.9446638724075895\n q_exp = 0.026566446344365977\n\n methods = (\n (old_eps, full_ts),\n (bcast_eps, full_ts),\n (trace_eps, full_ts),\n (sorted_eps, full_ts),\n (sparse_eps, sparse_ts),\n (sparsetr_eps, sparse_ts),\n (cumsum_eps, full_ts),\n )\n\n for eps, ts in methods:\n Q_tau, q_tau = eps(*ts, tau=10)\n assert math.isclose(Q_tau, Q_exp, abs_tol=1e-12, rel_tol=0)\n assert math.isclose(q_tau, q_exp, abs_tol=1e-12, rel_tol=0)\n\n\ndef compare(fast: bool) -> None:\n shape = 2, 2000\n rand = np.random.default_rng(seed=0).random\n\n n = 400 if fast else 1\n\n methods = (\n trace_eps,\n sorted_eps,\n cumsum_eps,\n )\n\n if fast:\n print('Fast method durations (us)')\n factor = 1e6\n fmt = '{:8.0f}'\n else:\n print('All method durations (ms)')\n factor = 1e3\n fmt = '{:8.2f}'\n methods += (\n old_eps,\n bcast_eps,\n sparse_eps,\n sparsetr_eps,\n )\n\n print(' d%', ' '.join(\n f'{method.__name__.removesuffix("_eps"):>8}'\n for method in methods\n ))\n\n densities = np.hstack((\n np.linspace(0.50, 0.95, 10),\n np.linspace(0.960, 0.995, 8),\n ))\n for density in densities:\n print(f'{100*density:4.1f}', end=' ')\n\n full_ts = np.ones(shape, dtype=np.uint8)\n sparse_ts = scipy.sparse.lil_matrix(shape, dtype=np.uint8)\n\n events = rand(shape) > density\n full_ts[events] = 0\n sparse_ts[events] = 1\n\n inputs = (\n full_ts,\n full_ts,\n full_ts,\n )\n if not fast:\n inputs += (\n full_ts,\n full_ts,\n sparse_ts,\n sparse_ts,\n )\n\n for eps, ts in zip(methods, inputs):\n t = timeit(lambda: eps(*ts, tau=10), number=n)\n\n print(fmt.format(t/n*factor), end=' ')\n print()\n print()\n\n\nif __name__ == '__main__':\n test()\n compare(False)\n compare(True)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T07:50:15.470",
"Id": "525643",
"Score": "3",
"body": "Thank you for the detailed explanation and the performance tests. I liked the sorted solution more for the straightforwardness, but will be deploying all on the real data for a more hands-on performance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T16:07:50.860",
"Id": "525694",
"Score": "2",
"body": "Thanks. Much cleaner display, too :-). Now I wonder what the OP's tau is really like. I think your trace solution gets faster with smaller tau, while mine gets faster with larger tau. At very high densities, the sorted solution approaches linear time, like mine always is, so they should differ by a constant factor there. Maybe either could be improved further to tweak this constant factor, but meh. I suspect bigger further improvement at a higher level, not by handling each vector pair faster but by reducing the number of pairs to do at all (or maybe it shouldn't even be done pairwise)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T00:07:47.100",
"Id": "266113",
"ParentId": "266108",
"Score": "18"
}
},
{
"body": "<p>You have quadratic runtime, we can reduce it to linear. You want to count the numbers of zeros in certain ranges. Let's flip zeros and ones and count the numbers of ones in ranges by subtracting prefix sums:</p>\n<pre><code>def Kelly_eps(ts_1, ts_2, tau):\n ts_1 = 1 - ts_1\n ts_2 = 1 - ts_2\n n1 = ts_1.sum()\n n2 = ts_2.sum()\n if n1 == 0 or n2 == 0:\n return 0, 0\n\n cs1 = np.pad(ts_1.cumsum(), (0, tau), 'edge')\n cs2 = np.pad(ts_2.cumsum(), (0, tau), 'edge')\n c_ij = c_ji = 0.5 * (ts_1 * ts_2).sum()\n c_ij += ((cs1[tau:] - cs1[:-tau]) * ts_2).sum()\n c_ji += ((cs2[tau:] - cs2[:-tau]) * ts_1).sum()\n\n sqrt = math.sqrt(n1 * n2)\n Q_tau = (c_ij + c_ji) / sqrt\n q_tau = (c_ij - c_ji) / sqrt\n return Q_tau, q_tau\n</code></pre>\n<p>Using Reinderien's script to benchmark against its two fastest solutions:</p>\n<pre><code>d=50% trace_eps: 1.37 ms sorted_eps: 8.33 ms Kelly_eps: 0.19 ms \nd=55% trace_eps: 0.80 ms sorted_eps: 7.10 ms Kelly_eps: 0.17 ms \nd=61% trace_eps: 1.20 ms sorted_eps: 5.79 ms Kelly_eps: 0.19 ms \nd=66% trace_eps: 1.25 ms sorted_eps: 4.20 ms Kelly_eps: 0.22 ms \nd=72% trace_eps: 0.98 ms sorted_eps: 2.50 ms Kelly_eps: 0.19 ms \nd=77% trace_eps: 0.73 ms sorted_eps: 1.62 ms Kelly_eps: 0.13 ms \nd=83% trace_eps: 0.73 ms sorted_eps: 1.23 ms Kelly_eps: 0.12 ms \nd=88% trace_eps: 0.72 ms sorted_eps: 0.65 ms Kelly_eps: 0.12 ms \nd=94% trace_eps: 0.71 ms sorted_eps: 0.37 ms Kelly_eps: 0.12 ms \nd=99% trace_eps: 0.69 ms sorted_eps: 0.07 ms Kelly_eps: 0.12 ms\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-20T09:52:24.177",
"Id": "525935",
"Score": "0",
"body": "Thank you for this solution. On multiple tests, your solution gave higher runtimes than original and Reinderien solution. For a particular set runtimes were:\nOriginal : 434 secs\nReinderien : 424 secs\nKelly : 598 secs"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-20T10:30:34.720",
"Id": "525939",
"Score": "0",
"body": "@skynaive Well it very much depends on the parameters/context. I asked about them under your question, but so far you ignored that."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T15:24:09.870",
"Id": "266137",
"ParentId": "266108",
"Score": "6"
}
},
{
"body": "<p>(This might not be 100% relevant since it's not about Python, and it's about just the intersection part, not the harder within-threshold-distance matching part. But maybe at least food for thought.)</p>\n<hr />\n<p><code>matching_idx</code> is the list of all places where both inputs have a 0, I think? You don't actually need that list, just the count of how many positions where <code>ts_1[i]</code> and <code>ts_2[i]</code> are both zero. It would be very fast to compute that from the original inputs, like <code>count_zeros( ts_1 | ts_2 )</code>, instead of using intersection on two lists of indices.</p>\n<p><strong>That wouldn't share any work with finding <em>nearby</em> indices</strong>, though, so you'd probably still need to generate the lists of indices where the inputs are zero. Still, it might be cheaper than the intersection part.</p>\n<p>(IDK how to get numpy to do this (I don't know numpy), but it's straightforward in C with SIMD intrinsics, or any other way of getting a programming language to compile or JIT to machine code with SIMD instructions that gives you a similar level of control.)</p>\n<p>To make it efficient, do the OR on the fly (one SIMD vector at a time, not storing the result in a new array), and the <code>count_zeros</code> probably do as <code>len - count_ones(ts1|ts2)</code>.</p>\n<p>If you store your input elements as packed bitmaps, then you can OR 128 or 256 bits per 16 or 32-byte SIMD vector, and efficiently popcount (<a href=\"https://github.com/WojciechMula/sse-popcount/\" rel=\"nofollow noreferrer\">https://github.com/WojciechMula/sse-popcount/</a>). Some SIMD popcount algorithms would work equally efficiently to count zeros directly, in which case you can do that, but out of the box you'll generally find optimized code to count ones, hence my suggestion.</p>\n<p>Or if you store your input arrays as unpacked 8-bit or 32-bit integer elements, you can just <code>sum += ts_1[i] | ts_2[i]</code> (ideally SIMD vectorized). To efficiently vectorize a sum of 8-bit 0 / 1 elements, see <a href=\"https://stackoverflow.com/questions/54541129/how-to-count-character-occurrences-using-simd\">https://stackoverflow.com/questions/54541129/how-to-count-character-occurrences-using-simd</a> - very similar problem to accumulating <code>_mm256_cmpeq_epi8</code> results (0 / -1).</p>\n<p>For 32-bit elements, you don't need to widen to avoid overflow when summing the OR results, but your data density would be very low (4x or 32x lower than possible), so hopefully you aren't doing that.</p>\n<p>8000 bits is only 31.25 SIMD vectors of 256 bits each, or 1000 bytes, so this should be blazing fast, like maybe 100 clock cycles or so with the data already hot in L1d cache. (<a href=\"https://github.com/WojciechMula/sse-popcount/blob/master/results/skylake/skylake-i7-6700-gcc5.3.0-avx2.rst#input-size-1024b\" rel=\"nofollow noreferrer\">https://github.com/WojciechMula/sse-popcount/blob/master/results/skylake/skylake-i7-6700-gcc5.3.0-avx2.rst#input-size-1024b</a>)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T21:55:18.090",
"Id": "525716",
"Score": "0",
"body": "Thank you for posting your answer. Your answer comments about things I've never heard of, and you're talking about things I can't think of a way to implement in Python. Your answer is the first compelling argument I've seen against Python (wrt being a high-level language). However I don't think your answer is inappropriate as using C is an accepted practice when you need speed Python can't get you. I'd say it's idiomatic Python, but given I, like many other Python programmers, can't program in C, it may be a stretch to say idiomatic..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T21:59:57.400",
"Id": "525717",
"Score": "0",
"body": "@Peilonrayz: Just to be clear, `count_zeros( ts_1 | ts_2 )` is pseudo-code, not something you can literally write in C. You can't OR whole arrays, you need to loop over them. (You *could* do basically that with [C++ `std::bitset<8000>`](https://en.cppreference.com/w/cpp/utility/bitset) - it does overload the `|` operator and has a `.count()` method to count ones which hopefully uses an optimized popcnt under the hood.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T22:07:14.850",
"Id": "525718",
"Score": "1",
"body": "FWIW I found that to be clear. The reason I mentioned C specifically, is because C is a common way to speed up Python. Such as in much of std-lib like [bisect](https://github.com/python/cpython/blob/599f5c8481ca258ca3a5d13eaee7d07a9103b5f2/Lib/bisect.py#L102)/[_bisect](https://github.com/python/cpython/blob/3.9/Modules/_bisectmodule.c) or numpy which are coincidentally mentioned in the above answers."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T21:35:53.487",
"Id": "266147",
"ParentId": "266108",
"Score": "2"
}
},
{
"body": "<p>The closest you come to documentation is telling us that you are calculating a statistic. What is this statistic? I tried searching for "Q statistic", "tau statistic" and "eps statistic", but didn't find anything that seemed to match what you've done. You may think you know what it's doing and would not forget, but you will completely forget in six months time, and when you come back to this you'll have as much knowledge as us. Your explanation of the input variables might as well go into a docstring.</p>\n<p>Intersecting the event indices and subtracting <code>x</code> and <code>y</code> suggests that the input arrays have the same length. That should be documented if true.</p>\n<p>You should know what a variable is just by its name, without looking back at how you defined it. <code>eps</code>, <code>Q_tau</code>, <code>q_tau</code>, and <code>tau</code> might pass that test (depending on what "this statistic" actually is). <code>ts_1</code>, <code>ts_2</code>, <code>event_index1</code>, <code>event_index2</code>, <code>n1</code>, <code>n2</code>, <code>matching_idx</code>, <code>c_ij</code>, <code>c_ji</code>, <code>x</code> and <code>y</code> don't. I would suggest naming them <code>input_array_1</code>, <code>input_array_2</code>, <code>zeros_indices_of_1</code>, <code>zero_indices_of_2</code>, <code>num_zeros_1</code>, <code>num_zeros_2</code>, <code>zero_indices_of_both</code>, <code>above_diagonal</code>, <code>below_diagonal</code>, <code>index_1</code>, and <code>index_2</code>. (Did you notice that you knew what all of those should be except for the diagonals?)</p>\n<p>It appears you aren't using pandas, so let's not import it.</p>\n<p>I like to return early if possible. You could have\n<code>if ( n1 == 0 or n2 == 0 ): return 0,0</code>\nThis would free you from declaring <code>Q_tau</code> and <code>q_tau</code> at the beginning and allow you to remove a level of indentation at the end.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T02:08:20.913",
"Id": "266149",
"ParentId": "266108",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "266113",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T20:05:08.367",
"Id": "266108",
"Score": "13",
"Tags": [
"python",
"algorithm",
"numpy"
],
"Title": "Iterate through two arrays calculating a statistic from indexes of zeros"
}
|
266108
|
<p>I have a workbook that loads in the results of an SQL query into two worksheets called Old and New. The New worksheet is then edited by an end user. Rows can be inserted, deleted and values changed. There is a unique key in column M. With the following code, I am able to detect changes between Old and New, additions and deletions but it is slow and can take 10+ minutes to execute when looking at 5000+ rows. Would appreciate any advice in making this a faster process.</p>
<pre><code>Sub Compare()
Dim OldArray as Variant
Dim NewArray as Variant
'Load List objects into arrays.
OldArray = Old.DataBodyRange
NewArray = New.DataBodyRange
For i = LBound(OldArray) to UBound(OldArray)
OldValueToFind = OldArray(i,IDColumn) 'Find the ID value in the i row.
With Sheets("New").Range("M:M") 'ID Column
Set NewRng = .Find(What:=OldValueToFind, _
After:=.Cells(.Cells.Count), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=True)
If Not NewRng Is Nothing Then 'Found OldValue in New Worksheet
NewRowIndex = NewRng.Row - 1 'Remove header column
For j = LBound(OldArray, 2) to UBound(OldArray, 2) 'For each column in Old
If j <> 2 and j <> 9 and j <> 10 and j <> 11 and j < 14 Then 'We don't care about comparing these value. There has to be a better way to discard these.
If OldArray(i,j) <> NewArray(NewRowIndex, j) Then
'Add new row to 3rd worksheet with differences
End If
End If
Next
Else
'Add new row to 3rd worksheet as this record has been deleted
End If
End With
Next
'End of checking for deletions and changes
'Now to repeat for NewArray to find any additional rows added.
For i = LBound(NewArray) to UBound(NewArray)
NewRowValue = NewArray(i, IDColumn) 'Get ID Value from New Worksheet
With Sheets("Old").Range("M:M")
Set viewRng = .Find(What:=NewRowValue, _
After:=.Cells(.Cells.Count), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=True)
If viewRng Is Nothing Then 'Must be additional row as not found
'Add new row to 3rd worksheet with all required columns.
End If
End With
Next
End Sub
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T23:25:35.433",
"Id": "525620",
"Score": "0",
"body": "Have you already tried using the [comapare feature built-in to Excel](https://support.microsoft.com/en-us/office/basic-tasks-in-spreadsheet-compare-f2b20af8-a6d3-4780-8011-f15b3229f5d8)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T04:05:42.347",
"Id": "525630",
"Score": "0",
"body": "This was resolved on another forum.\nhttps://www.mrexcel.com/board/threads/fastest-way-to-compare-2-excel-worksheets-and-output-differences-to-3rd-worksheet.1179336/#post-5738245"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T10:04:59.630",
"Id": "525744",
"Score": "0",
"body": "If you've solved it yourself then you could still put the new code up for review in a separate question? Alternatively, if you could add the commented out `'Add new row to 3rd worksheet` code/ post your full code you might get better answers, as that will probably have a big impact on your code's performance"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-16T22:00:55.050",
"Id": "266110",
"Score": "0",
"Tags": [
"vba",
"excel"
],
"Title": "Fastest Way To Compare 2 Excel Worksheets And Output Differences To 3rd Worksheet"
}
|
266110
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.