body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I've created an on-demand class that can be initiated to collected any new data written to file from <code>start_recording</code> call until <code>stop_recording</code> which close the connection and retrieve the collected data so far.</p>
<p>It uses in test cases for obtaining relevant logs during the time where a certain operation was performed in order to verify its success.</p>
<p>I'm currently using this class for tests in remote machine, but would be happy to hear for any idea for improvements, correctness, etc.</p>
<pre><code>import time
import paramiko
import select
from virtual_machine import utils
from multiprocessing import Queue
import multiprocess
class background():
def __init__(self, config_file):
self.q = Queue(1000)
#this methods implemented elsewhere and read a config file into dictionary
self.config = utils.get_params(config_file)
@staticmethod
def linesplit(socket):
buffer_string = socket.recv(4048).decode('utf-8')
done = False
while not done:
if '\n' in buffer_string:
(line, buffer_string) = buffer_string.split('\n', 1)
yield line + "\n"
else:
more = socket.recv(4048)
if not more:
done = True
else:
buffer_string = buffer_string + more.decode('utf-8')
if buffer_string:
yield buffer_string
def do_tail(self, log_file):
data = ""
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
from os.path import expanduser
home = expanduser("~")
client.connect(self.config["ip"],self.config["username"],self.config["password"])
grep_pattern = "grep_filter"
remote_command = 'tail -0 -f {} '.format(log_file)
print(remote_command)
transport = client.get_transport()
channel = transport.open_session()
channel.exec_command(remote_command)
while 1:
try:
rl, _, _ = select.select([channel], [], [], 0.0)
if len(rl) > 0:
print("ready to read")
for line in background.linesplit(channel):
self.q.put_nowait(line)
except (KeyboardInterrupt, SystemExit):
print('got ctrl+c')
break
client.close()
return data
def start_recording(self, log_file):
q = Queue(100)
self.p = multiprocess.Process(target=self.do_tail, args=(log_file,), daemon=True)
self.p.start()
def stop_recording(self):
self.p.terminate()
data = ""
while not self.q.empty():
data += self.q.get()
return data
#example
if __name__ == '__main__':
x = background("config.conf")
x.start_recording("/tmp/logfile.log")
# doing some operation
data = x.stop_recording()
print(data)
</code></pre>
|
[] |
[
{
"body": "<p>Your <code>linesplit</code> repeats a little bit of code; you could phrase it as</p>\n<pre><code>while True:\n buffer_bytes = socket.recv(4096)\n if len(buffer_bytes) == 0:\n break\n buffer_string = buffer_bytes.decode('utf-8')\n *lines, buffer_string = buffer_string.split('\\n')\n yield from lines\n</code></pre>\n<p><code>'tail -0 -f {} '.format(log_file)</code> could be simply <code>'tail -0 -f ' + log_file</code>.</p>\n<p><code>background</code> should be <code>Background</code>.</p>\n<p>Consider adding some PEP484 type hints.</p>\n<p><code>rl, _, _ = select ...</code></p>\n<p>can be</p>\n<p><code>rl, *_ = select ...</code></p>\n<p>The code between <code>paramiko.SSHClient()</code> and <code>client.close()</code> has no close-guarantee protection. There are various options, including a <code>try</code>/<code>finally</code>, or making your current class (or a factored-out tail-specific class) a context manager.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T15:44:27.057",
"Id": "524567",
"Score": "0",
"body": "Thanks for your comments. Btw, I've encountered where the log recording was lagging behind, and where it did, the interesting part already finished. I wonder if there's any kind of system wide lock that can block the `start_recording` from returning, until the subprocess reach the `ready to read` line. Can you recommend anything ? thanks !"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T15:03:45.273",
"Id": "265553",
"ParentId": "265545",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "265553",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T10:59:18.943",
"Id": "265545",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"linux",
"integration-testing"
],
"Title": "remote file follow using python"
}
|
265545
|
<p>As part of a larger project I'm writing to learn C++, I'm trying to read through some almost-XML files generated by another program. Unfortunately this program uses its own custom escaping logic, so some of these files aren't actually valid XML. As far as I can tell, its escape logic works like this:</p>
<ul>
<li>Attribute values are always surrounded with double quotes. The only escape sequence is <code>\"</code>, evaluating to a double quote. Backslashes elsewhere are just interpreted literally; it's impossible for a value to end with a backslash.</li>
<li>Nested elements always have the opening outer tag on one line, each inner tag on its own line, and the closing outer tag on another.</li>
<li>Tags with text content are always entirely on a single line, and interpret all characters between the opening tag and closing tag literally. It is impossible for a copy of the closing tag to be in the text content, but other tags may be.</li>
</ul>
<p>In practice the files have a bit more structure than this, but I've been trying to work off of just these assumptions to keep the code flexible.</p>
<p>As an example, this is a possible, invalid XML, input:</p>
<pre class="lang-xml prettyprint-override"><code><outer attr="&amp;value\"">
<empty />
<inner><notnested></outer></inner>
</outer>
</code></pre>
<p>Which is equivalent to this valid XML:</p>
<pre class="lang-xml prettyprint-override"><code><outer attr="&amp;amp;value&quot;">
<empty />
<inner>&lt;notnested&gt;&lt;/outer&gt;</inner>
</outer>
</code></pre>
<p>My approach to dealing with this is to do some simplified parsing over these files to convert them into valid XML, before feeding them into a more traditional XML parser (leaning towards <a href="https://pugixml.org/" rel="nofollow noreferrer">pugixml</a>, but open to change if it makes things easier). Here are the relevant functions in a small demo program:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <cctype>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
static void put_xml_escaped(char c, std::stringstream& stream) {
switch (c) {
case '"': stream << "&quot;"; break;
case '\'': stream << "&apos;"; break;
case '<': stream << "&lt;"; break;
case '>': stream << "&gt;"; break;
case '&': stream << "&amp;"; break;
default: stream << c; break;
}
}
static std::stringstream preprocess_file(std::string filename) {
enum tag_parse_state {
// " <tag attr="val">content</tag> "
before_tag, // ^^^^
tag_name, // ^^^^
tag_body, // ^^^^^^^ ^
attr, // ^^^^
content, // ^^^^^^^
closing_tag, // ^^^^^^
closed // ^^^^
};
std::ifstream file{filename};
std::stringstream processed{};
for (std::string line; std::getline(file, line); ) {
tag_parse_state state = before_tag;
size_t tag_name_start;
size_t closing_tag_start, closing_tag_end;
for (size_t i = 0; i < line.size(); i++) {
auto c = line[i];
if (state == before_tag) {
if (c == '<') {
processed << c;
state = tag_name;
tag_name_start = i + 1;
} else if (!isspace(c)) {
throw std::runtime_error(
"Failed to parse line (text before inital tag): " + line
);
}
} else if (state == tag_name) {
processed << c;
if (c == ' ' || c == '>') {
// Nice little coincidence: if we're parsing over a closing tag, this will
// double up on the '/' and thus not find itself
auto closing_tag_str = (
"</" + line.substr(tag_name_start, i - tag_name_start) + ">"
);
closing_tag_start = line.rfind(closing_tag_str);
closing_tag_end = (
closing_tag_start == std::string::npos
? std::string::npos
: closing_tag_start + closing_tag_str.size() - 1
);
if (c == ' ') {
state = tag_body;
} else {
state = closing_tag_start == std::string::npos ? closed : content;
}
}
} else if (state == tag_body) {
processed << c;
if (c == '"') {
state = attr;
} else if (c == '>') {
state = closing_tag_start == std::string::npos ? closed : content;
}
} else if (state == attr) {
if (c == '"') {
processed << c;
state = tag_body;
} else if (c == '\\' && i + 1 < line.size() && line[i + 1] == '"') {
put_xml_escaped('"', processed);
i++;
} else {
put_xml_escaped(c, processed);
}
} else if (state == content) {
put_xml_escaped(c, processed);
if (i + 1 >= closing_tag_start) {
state = closing_tag;
}
} else if (state == closing_tag) {
processed << c;
if (i >= closing_tag_end) {
state = closed;
}
} else if (state == closed) {
if (!isspace(c)) {
throw std::runtime_error(
"Failed to parse line (text after closing tag): " + line
);
}
}
}
if (state != closed) {
throw std::runtime_error("Failed to parse line (missed closing tag): " + line);
}
}
return processed;
}
int main() {
std::cout << preprocess_file("example.xml").str() << "\n";
return 0;
}
</code></pre>
<p>I'm interested in feedback on:</p>
<ul>
<li>General best practices (minus code style)</li>
<li>Edge cases I may have missed</li>
<li>Algorithmic improvements - I don't think you can do much better than O(n) when using a state machine like this, but maybe there's a completely different approach.</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T16:31:22.743",
"Id": "524506",
"Score": "0",
"body": "This isn't really an XML question. It's about a proprietary data syntax that has some resemblances to XML, but you can't use any XML tooling, so this doesn't help you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T22:20:06.537",
"Id": "524534",
"Score": "0",
"body": "Fair enough, removed that tag."
}
] |
[
{
"body": "<h1>Use <code>enum class</code></h1>\n<p>Consider using <a href=\"https://en.cppreference.com/w/cpp/language/enum#Scoped_enumerations\" rel=\"nofollow noreferrer\"><code>enum class</code></a> instead of a plain <code>enum</code> for a little more type safety.</p>\n<p>I would also recommend you use all-caps for the names of the <code>enum</code> options, as this is commonly done and is a strong hint that those are constants and not variables.</p>\n<h1>Prefer using <code>switch</code>-statements when <code>enum</code>s are involved</h1>\n<p>Use a <code>switch</code>-statement instead of a chain of <code>if</code>-<code>else</code>-statements when checking the value of an <code>enum</code> variable. Most compilers will then be able to emit warnings if you forget a <code>case</code> statement. It also makes the code a little bit more readable.</p>\n<h1>Make <code>preprocess_file()</code> take <code>istream</code> and <code>ostream</code>s as parameters</h1>\n<p>Your <code>preprocess_file()</code> has a filename as an argument, and returns a <code>std::stringstream</code>. However, that means that now it is responsible for opening the file, and returning the result as a <code>std::stringstream</code> is inefficient if you are just going to write it to <code>std::out</code> afterwards. Consider having this function take two parameters: one for the input stream, and one for the output stream, like so:</p>\n<pre><code>void preprocess(std::istream &file, std::ostream &processed) {\n ...\n}\n</code></pre>\n<p>Then in <code>main()</code> you can write:</p>\n<pre><code>preprocess(std::ifstream("example.xml"), std::cout);\nstd::cout << "\\n";\n</code></pre>\n<p>If you want to be able to write <code>std::cout << preprocess(...)</code>, that is possible too, but then you have to make it a <code>class</code> and add a <a href=\"https://www.learncpp.com/cpp-tutorial/overloading-the-io-operators/\" rel=\"nofollow noreferrer\"><code>friend operator<<(std::ostream &, preprocess &)</code> function</a>, which might be a bit overkill for your application.</p>\n<h1>Missing error checking</h1>\n<p>I/O errors can happen at any time, both when reading from and writing to a file. You could add checks after every I/O operation, but that would quickly lead to a lot of messy code. Luckily, any error state persists, so what you can do is just add <a href=\"https://en.cppreference.com/w/cpp/io/basic_ios/fail\" rel=\"nofollow noreferrer\">checks</a> at the end of <code>preprocess_file()</code>, like so:</p>\n<pre><code>if (file.fail()) {\n throw std::runtime_error("Error while reading input");\n}\n\nif (processed.fail()) {\n throw std::runtime_error("Error while writing output");\n}\n</code></pre>\n<h1>Performance</h1>\n<p>You are going over each character individually, most of the time just copying it to the output. For each state you only have a few characters you want to match. Consider using <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/find_first_of\" rel=\"nofollow noreferrer\"><code>std::string::find_first_of()</code></a> to get the position of the first interesting character; the standard library might do that in a more optimal way.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T22:29:22.313",
"Id": "524535",
"Score": "1",
"body": "Lot of good tips, thanks. I realized I didn't mention it in the post, but for what it's worth I was looking at feeding [pugixml from a stream](https://pugixml.org/docs/manual.html#loading.stream), hence why I left it outputting the stringstream. I can definitely see how having the parent function manage ownership would be better though."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T16:12:22.507",
"Id": "265557",
"ParentId": "265550",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T13:13:41.297",
"Id": "265550",
"Score": "4",
"Tags": [
"c++",
"beginner",
"parsing"
],
"Title": "Preprocessing invalid xml before feeding it to a parser"
}
|
265550
|
<p>I want to create a function that takes a numpy array, an axis and an index of that axis and returns the array with the index on the specified axis fixed. What I thought is to create a string that change dynamically and then is evaluated as an index slicing in the array (as showed in <a href="https://stackoverflow.com/a/47354114/11764049">this answer</a>). I came up with the following function:</p>
<pre><code>import numpy as np
def select_slc_ax(arr, slc, axs):
dim = len(arr.shape)-1
slc = str(slc)
slice_str = ":,"*axs+slc+",:"*(dim-axs)
print(slice_str)
slice_obj = eval(f'np.s_[{slice_str}]')
return arr[slice_obj]
</code></pre>
<h3>Example</h3>
<pre><code>>>> arr = np.array([[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
[[0, 1, 0],
[1, 1, 1],
[0, 1, 0]],
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]], dtype='uint8')
>>> select_slc_ax(arr, 2, 1)
:,2,:
array([[0, 0, 0],
[0, 1, 0],
[0, 0, 0]], dtype=uint8)
</code></pre>
<p>I was wondering if there is a better method to do this.</p>
|
[] |
[
{
"body": "<ul>\n<li>Avoid <code>eval</code> at all costs</li>\n<li>Use the <code>slice</code> built-in for your <code>:</code> components, or the numeric index at the selected axis</li>\n<li>Do not abbreviate your variable names</li>\n<li>Type-hint your function signature</li>\n<li>Turn your example into something resembling a unit test with an <code>assert</code></li>\n<li>Modify the data in your example to add more non-zero entries making it clearer what's happening</li>\n<li>Prefer immutable tuples over mutable lists when passing initialization constants to Numpy</li>\n<li>Prefer the symbolic constants for Numpy types rather than strings</li>\n</ul>\n<h2>Suggested</h2>\n<pre><code>import numpy as np\n\n\ndef select_slice_axis(array: np.ndarray, index: int, axis: int) -> np.ndarray:\n slices = tuple(\n index if a == axis else slice(None)\n for a in range(len(array.shape))\n )\n return array[slices]\n\n\narr = np.array(\n (\n ((0, 0, 0),\n (0, 0, 0),\n (0, 0, 9)),\n ((0, 1, 0),\n (2, 3, 4),\n (0, 5, 0)),\n ((0, 0, 0),\n (0, 0, 0),\n (8, 0, 0)),\n ),\n dtype=np.uint8,\n)\n\nactual = select_slice_axis(arr, 2, 1)\nexpected = np.array(\n (\n (0, 0, 9),\n (0, 5, 0),\n (8, 0, 0),\n ), dtype=np.uint8\n)\nassert np.all(expected == actual)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T07:51:31.133",
"Id": "525143",
"Score": "0",
"body": "Thank you very much, this is really helpful! Just one more clarification: why `eval` is so bad? Thank you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T12:51:27.720",
"Id": "525156",
"Score": "1",
"body": "It greatly increases the surface area for bugs and security flaws."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T16:23:38.230",
"Id": "265604",
"ParentId": "265551",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "265604",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T14:35:05.840",
"Id": "265551",
"Score": "3",
"Tags": [
"python",
"numpy"
],
"Title": "Dynamically indexing numpy array"
}
|
265551
|
<p>This is an effect to augment juggling videos:</p>
<p><a href="https://i.stack.imgur.com/KTcV4.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KTcV4.gif" alt="output" /></a></p>
<p>The goal of this effect is to add a rainbow trail to a video using a tracked set of points.</p>
<p><a href="https://drive.google.com/drive/folders/1-0L_TAQp71TE31lQxFQi-z0zcW8GxthU" rel="nofollow noreferrer">Link to source video</a></p>
<p><a href="https://drive.google.com/drive/folders/12UaOtej1Is1r60abc1DoilXFva80qa0f" rel="nofollow noreferrer">Link to source data</a></p>
<p><a href="https://gist.github.com/smeschke/f19ebfd48581cf1f6b7f441cc93ea129" rel="nofollow noreferrer">Link to complete Python script</a></p>
<p><a href="https://www.youtube.com/watch?v=_xnA727D8Vc" rel="nofollow noreferrer">Link to complete video</a></p>
<p><strong>This is how the script works step-by-step</strong>:</p>
<p>Look at the relevant tracking points:</p>
<pre><code>import numpy as np
import cv2
import pandas as pd
import numpy.polynomial.polynomial as poly
import math
# Read Source Data
cap = cv2.VideoCapture('/home/stephen/Desktop/ss5_id_412.MP4')
df = pd.read_csv('/home/stephen/Desktop/ss5_id_412.csv')
#Write Video Out
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('/home/stephen/Desktop/parabola.avi', fourcc, 120.0, (480,848))
# Define x and y as the first two columns of the spreadsheet
x = df['0']
y = df['1']
# Filter the data to smooth it out
from scipy.signal import savgol_filter
x = savgol_filter(x, 7, 3)
y = savgol_filter(y, 7, 3)
# Start at frame number 0
frameNum = 0
# Define trail length
trail = 30
# Colors of the rainbow
rainbow = [(0,0,255), (0,127,255), (0,255,0), (255,0,0), (95,43,46), (255,0,139)]
def distance(a,b): return(math.sqrt((a[0]-b[0])**2+(a[1]-b[1])**2))
# Read a few frames of the video
# Define distance to calculate parabola from (in frames)
interval = 6
for i in range(interval):
_,_ = cap.read()
frameNum+= 1
# https://stackoverflow.com/questions/57065080/draw-perpendicular-line-of-fixed-length-at-a-point-of-another-line
def perpendicular(slope, target, dist):
dy = math.sqrt(3**2/(slope**2+1))*dist
dx = -slope*dy
left = target[0] - dx, target[1] - dy
right = target[0] + dx, target[1] + dy
return left, right
# Create a list to store past points
history = []
completeHistory = []
### This is the first loop through the video
### In this loop the rainbow-trail data is collected
while True:
# Read Image
_, img = cap.read()
try: _ = img.shape
except: break
# Define a small distance
smallDistance = 0.2
# Find relevant data
x_values = x[frameNum-interval:frameNum+interval]
y_values = y[frameNum-interval:frameNum+interval]
# Graph x and y values
for point in zip(x_values, y_values):
point = tuple(np.array(point,int))
#cv2.circle(img, point, 1, (255,0,255), 2)
</code></pre>
<p><a href="https://i.stack.imgur.com/Dm6T6.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Dm6T6.gif" alt="tracking points" /></a></p>
<p>Find a parabola that fits those points:</p>
<pre><code># Fit the parabola
coefs = poly.polyfit(x_values,y_values,2)
# Draw the parabola
target = int(x[frameNum]), int(poly.polyval(x[frameNum], coefs))
xRange = np.arange(target[0]-9,target[0]+9,1)
yRange = poly.polyval(xRange, coefs)
rangePoints = zip(xRange, yRange)
for ppp in rangePoints:
center = tuple(np.array(ppp,int))
#cv2.circle(img, center, 1, 123, 2)
#print(yRange)
</code></pre>
<p><a href="https://i.stack.imgur.com/mXQP8.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mXQP8.gif" alt="parabola gif" /></a></p>
<p>Find the tangent of the parabola at the ball's position:</p>
<pre><code># https://stackoverflow.com/questions/57065080/draw-perpendicular-line-of-fixed-length-at-a-point-of-another-line
def perpendicular(slope, target, dist):
dy = math.sqrt(3**2/(slope**2+1))*dist
dx = -slope*dy
left = target[0] - dx, target[1] - dy
right = target[0] + dx, target[1] + dy
return left, right
# Calculate the points on either end of the tangent line
leftX, rightX = x[frameNum] - smallDistance, x[frameNum] + smallDistance
left = leftX, poly.polyval(leftX, coefs)
right = rightX, poly.polyval(rightX, coefs)
# Calculate the slope of the tangent line
slope = (left[1]-right[1])/(left[0]-right[0])
intercept = target[1] - slope*target[0]
# Draw line
leftPoint = target[0]-10, (target[0]-10)*slope + intercept
rightPoint = target[0]+10, (target[0]+10)*slope + intercept
leftPoint = tuple(np.array(leftPoint, int))
rightPoint= tuple(np.array(rightPoint, int))
cv2.line(img, leftPoint, rightPoint, (123,234,123), 3)
</code></pre>
<p><a href="https://i.stack.imgur.com/KJcxm.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KJcxm.gif" alt="tangent line" /></a></p>
<p>Draw the trails:</p>
<pre><code># List to save data for this frame
frameHistory = []
# Find Perpendicular points
for i in range(len(rainbow)):
color = rainbow[i]
left, right = perpendicular(slope, target, i-3)
left, right = tuple(np.array(left, int)), tuple(np.array(right, int))
point = left
#cv2.circle(img, left, 1, color, 1)
frameHistory.append(point)
history.append(frameHistory)
completeHistory.append(frameHistory)
# Show the history too
a,b,c,d,e,f = zip(*history)
for pointList, color in zip([a,b,c,d,e,f], rainbow):
for i in range(len(pointList)-1):
pass
cv2.line(img, pointList[i], pointList[i+1], color, 2)
# Pop the oldest frame off the history if the history is longer than 0.25 seconds
if len(history)>15:
history.pop(0)
</code></pre>
<p><a href="https://i.stack.imgur.com/TuMOh.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TuMOh.gif" alt="not smoothed" /></a></p>
<p>Smooth the trails (this is the final output):</p>
<pre><code>#Smooth the data
smoothed = []
a,b,c,d,e,f = zip(*completeHistory)
for i in a,b,c,d,e,f:
x, y = zip(*i)
x = savgol_filter(x, 27, 3)
y = savgol_filter(y, 21, 2)
smoothed.append(list(zip(x,y)))
# Read Source Data
cap = cv2.VideoCapture('/home/stephen/Desktop/ss5_id_412.MP4')
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('/home/stephen/Desktop/parabola.avi', fourcc, 120.0, (480,848))
frameNum = 0
### This is the second loop through the video
### In this loop the smoothed rinbow-trail points are diplayed
while True:
# Read Image
_, img = cap.read()
if frameNum>21:
for color, line in zip(rainbow, smoothed):
pointList = line[frameNum-20:frameNum-5]
for i in range(len(pointList)-1):
a,b = tuple(np.array(pointList[i], int)), tuple(np.array(pointList[i+1], int))
cv2.line(img, a,b, color, 2)
</code></pre>
<p><a href="https://i.stack.imgur.com/SmtMm.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SmtMm.gif" alt="smoothed gif slow" /></a></p>
|
[] |
[
{
"body": "<p>This is SO COOL. Some minor improvements:</p>\n<p><code>from scipy.signal import savgol_filter</code> should be moved to the top of the file</p>\n<p>You should be moving your global code into subroutines.</p>\n<p><code>distance</code> can be replaced with the built-in <code>np.linalg.norm</code>.</p>\n<p><code>_,_ = cap.read()</code> does not need any return assignments; just call <code>cap.read()</code>.</p>\n<pre><code> left = target[0] - dx, target[1] - dy\n right = target[0] + dx, target[1] + dy\n</code></pre>\n<p>would benefit from unpacking:</p>\n<pre><code>x, y = target\nleft = x - dx, y - dy\nright = x + dx, y + dy\n</code></pre>\n<p>By PEP8, <code>frameHistory</code> would be <code>frame_history</code>, and <code>pointList</code> to <code>point_list</code>.</p>\n<p>You have a bunch of hard-coded paths - these should be parametrized, either to global constants, or a configuration file etc.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T15:17:56.580",
"Id": "265554",
"ParentId": "265552",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "265554",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T14:52:01.647",
"Id": "265552",
"Score": "5",
"Tags": [
"python",
"opencv",
"scipy",
"video"
],
"Title": "Rainbow Trails Video Effect"
}
|
265552
|
<p>I created this sample and wanted any advice on how to make this code; cleaner, more effective, just overall better! I am collecting the days data from the NegativeScheduleSentence model and ScheduleSentencePart model and removing the model from the concepts object. only to have to re-add them back in using the days object from both models. Any help would be great.</p>
<p>sample working
<a href="https://dotnetfiddle.net/5jA7xh" rel="nofollow noreferrer">https://dotnetfiddle.net/5jA7xh</a></p>
<pre class="lang-cs prettyprint-override"><code>if (concepts.NegativeScheduleSentencePartModel.Count() > 0 &&
concepts.ScheduleSentencePartModel.Count() > 0)
{
var conceptsNegativeScheduleCalendarDays =
concepts.NegativeScheduleSentencePartModel.Select(x => x.Days).ToList();
var PositiveandNegativeDays = new List<int>();
for (int i = 0; i < conceptsNegativeScheduleCalendarDays.Count; i++)
{
foreach (int day in conceptsNegativeScheduleCalendarDays[i])
{
Console.WriteLine(day);
PositiveandNegativeDays.Add(day);
}
}
var conceptscheduleCalendarDays = concepts.ScheduleSentencePartModel
.Select(x => x.Days).ToList();
for (int i = 0; i < conceptscheduleCalendarDays.Count; i++)
{
foreach (int day in conceptscheduleCalendarDays[i])
{
Console.WriteLine(day);
PositiveandNegativeDays.Add(day);
}
}
concepts.ScheduleSentencePartModel
.RemoveRange(0, ScheduleSentencePartModel.Count);
concepts.NegativeScheduleSentencePartModel
.RemoveRange(0, conceptsNegativeScheduleCalendarDays.Count);
var PositiveandNegativeScheduleSentencePartModel =
new List<ScheduleSentencePartModel>();
ScheduleSentencePartModel.Add(
new ScheduleSentencePartModel() {
Days = PositiveandNegativeDays, Isvalid = true });
concepts.ScheduleSentencePartModel = ScheduleSentencePartModel;
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li>Type names should be written in PascalCase (<code>class Concepts</code>). Variables should be written in camelCase (<code>negativeScheduleSentence</code>).</li>\n<li>All the public fields should be properties (PascalCase).</li>\n<li><code>concepts.NegativeScheduleSentencePartModel</code> and <code>concepts.ScheduleSentencePartModel</code> are lists (<code>List<T></code>). Lists have a <code>Count</code> property. No need to call the LINQ <code>Count()</code> extension method. Write <code>concepts.NegativeScheduleSentencePartModel.Count > 0</code>.</li>\n<li><code>NegativeScheduleSentencePartModel</code> and <code>ScheduleSentencePartModel</code> are identical. From a conceptual point of view, it can sometimes make sense to have two types, because they could evolve differently in future, but then they should have a common (abstract) base class (e.g., <code>ScheduleSentencePartModelBase</code>) or implement the same interface. This allows you to treat them the same way. E.g., you could have a method <code>void PrintScheduleSentence(ScheduleSentencePartModelBase scheduleSentence)</code> that can print both models. However, in your example code I see no reason to have two types.</li>\n<li>You declare and initialize an unused list <code>PositiveandNegativeScheduleSentencePartModel</code>. Remove it unless it is used in your real code.</li>\n<li>Instead of <code>someList.RemoveRange(0, someList.Count);</code> you can write <code>someList.Clear();</code>.</li>\n<li>Classes are reference types. This means that <code>concepts.ScheduleSentencePartModel</code> and the variable <code>scheduleSentencePartModel</code> (changed to camelCase) point to the same list object. It makes no sense to re-assign the variable (last line in the code above).</li>\n</ul>\n<p>It is hard to understand what you are trying to achieve with this code, but if its purpose is simply to concatenate all the days from all the lists, this can be achieved much easier. The LINQ extension method <code>SelectMany</code> flattens nested collections.</p>\n<p>It still makes sense to clear the lists, because you are potentially replacing many ScheduleSentencePartModels by one containing all the days of all the models (if this was your intention, after all it is what your loops do).</p>\n<pre class=\"lang-cs prettyprint-override\"><code>if (concepts.NegativeScheduleSentencePartModel.Count > 0 &&\n concepts.ScheduleSentencePartModel.Count > 0) {\n\n var positiveandNegativeDays = concepts.NegativeScheduleSentencePartModel\n .SelectMany(x => x.Days)\n .Concat(\n concepts.ScheduleSentencePartModel\n .SelectMany(x => x.Days)\n )\n .OrderBy(d => d) // Optionally sort the days.\n .ToList();\n\n concepts.NegativeScheduleSentencePartModel.Clear();\n concepts.ScheduleSentencePartModel.Clear();\n\n concepts.ScheduleSentencePartModel.Add(\n new ScheduleSentencePartModel {\n Days = positiveandNegativeDays, IsValid = true \n });\n}\n</code></pre>\n<p>Is the surrounding if-statement necessary? If the lists are empty the code would still work as expected. The only effect it has is to collect the data only when both lists have entries. If only one of the two lists has entries, nothing happens. Was this intended?</p>\n<ul>\n<li>A possible problem is that you select all the entries, even those with <code>IsValid = false</code> and replace them by an entry with with <code>IsValid = true</code>. Maybe you should exclude the invalid ones.</li>\n</ul>\n<pre class=\"lang-cs prettyprint-override\"><code>var positiveandNegativeDays = concepts.NegativeScheduleSentencePartModel\n .Where(x => x.IsValid)\n .SelectMany(x => x.Days)\n .Concat(\n concepts.ScheduleSentencePartModel\n .Where(x => x.IsValid)\n .SelectMany(x => x.Days)\n )\n .OrderBy(d => d)\n .ToList();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T18:18:58.813",
"Id": "524519",
"Score": "0",
"body": "Thanks I was thinking that I only needed to do this logic if both models have data. If only one of the model has data I dont need to clear and then re-add"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T18:23:29.190",
"Id": "524521",
"Score": "0",
"body": "Note that if `concepts.ScheduleSentencePartModel` has more than one `ScheduleSentencePartModel` then it will be replaced by a single one having the days of all of them plus the ones from all the `NegativeScheduleSentencePartModel`s in `concepts.NegativeScheduleSentencePartModel`. So you are not just clearing one and re-adding one but potentially removing many and re-adding one."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T18:07:36.703",
"Id": "265564",
"ParentId": "265559",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "265564",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T16:44:07.047",
"Id": "265559",
"Score": "0",
"Tags": [
"c#"
],
"Title": "Collecting data from list and then removing"
}
|
265559
|
<h1>Aim of the Code:</h1>
<p>The aim of the function I'm working on is to take a particular column from a DataFrame that contains multiple <code><tag><content></code> pairs in the form of a string and expand them into individual columns in an efficient way.</p>
<p>An example file can be found <a href="https://ftp.ncbi.nlm.nih.gov/refseq/H_sapiens/annotation/GRCh38_latest/refseq_identifiers/GRCh38_latest_genomic.gff.gz" rel="nofollow noreferrer">here</a> (aprox. 3M entries), which can be loaded as a DataFrame with:</p>
<pre><code>def load_refseq_coordinates(ifile):
# https://m.ensembl.org/info/website/upload/gff3.html
return pd.read_csv(ifile, sep='\t', comment='#',
names=['seqid', 'source', 'type', 'start', 'end', 'score',
'strand', 'phase', 'attributes'])
return df
</code></pre>
<p>The loaded DataFrame will have a column named <code>attributes</code> that has content such as:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>attributes</th>
</tr>
</thead>
<tbody>
<tr>
<td>ID=NC_000001.11:1..248956422;Dbxref=taxon:9606;Name=1;chromosome=1;gbkey=Src;genome=chromosome;mol_type=genomic DNA</td>
</tr>
</tbody>
</table>
</div>
<p>with different pairs separated by <code>;</code> and <code><tag><content></code> pairs defined with <code>=</code>.</p>
<p>The aim would, then to keep the rest of the columns of the DataFrame and get this one converted to:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>attributes.ID</th>
<th>attributes.Dbxref</th>
<th>attributes.Name</th>
<th>attributes.chromosome</th>
<th>attributes.gbkey</th>
<th>attributes.genome</th>
<th>attributes.mol_type</th>
</tr>
</thead>
<tbody>
<tr>
<td>NC_000001.11:1..248956422</td>
<td>taxon:9606</td>
<td>1</td>
<td>1</td>
<td>Src</td>
<td>chromosome</td>
<td>genomic DNA</td>
</tr>
</tbody>
</table>
</div>
<p>And the same for all rows of the DataFrame.</p>
<h1>The Issue:</h1>
<p>All the solutions I've found so far do <strong>not</strong> scale proficiently and applying them to the 3M entry file takes just too long.</p>
<p><strong>In the last 3 cases I'll show, performance seems better, as I can test up to 100K in around 4s (with that time is around 10K rows in the first solutions), but it is still poor performance for the 3M rows.</strong></p>
<h1>Current Solutions:</h1>
<p>Note that:</p>
<ul>
<li>I'm running this in a Jupyter Notebook, thus the <code>%timeit</code> call.</li>
<li>I'm only checking up to 10k rows to see how it scales (gets too long with more), except the last 3 solutions, as they perform better (thus I time them for 100K rows)</li>
</ul>
<h2>1. Series.apply a function that does the double string split</h2>
<pre><code>def expand_info_string1(df, column='info', entity_sep=';', id_sep='='):
def do_expand(cell, entity_seq, id_sep):
data = [x.split(id_sep) for x in str(cell).split(entity_seq)]
return pd.Series(list(zip(*data))[-1], index=list(zip(*data))[0])
info = df[column].apply(do_expand, entity_seq=entity_sep, id_sep=id_sep)
return pd.concat([df.drop(columns=[column]), info.add_prefix(f'{column}.')], axis=1).fillna('')
%timeit dd = expand_info_string1(df.sample(10), 'attributes')
%timeit dd = expand_info_string1(df.sample(100), 'attributes')
%timeit dd = expand_info_string1(df.sample(1000), 'attributes')
%timeit dd = expand_info_string1(df.sample(10000), 'attributes')
</code></pre>
<pre><code>330 ms ± 267 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
299 ms ± 18.9 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
708 ms ± 375 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
4.4 s ± 263 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
</code></pre>
<h2>2. Series.str.split + Series.apply a function to do 1 split</h2>
<pre><code>def expand_info_string3(df, column='info', entity_sep=';', id_sep='='):
def do_expand(cell, id_sep):
data = [str(x).split(id_sep) for x in cell]
return pd.Series(list(zip(*data))[-1], index=list(zip(*data))[0])
info = df[column].str.split(entity_sep).apply(do_expand, id_sep=id_sep)
return pd.concat([df.drop(columns=[column]), info.add_prefix(f'{column}.')], axis=1).fillna('')
%timeit dd = expand_info_string3(df.sample(10), 'attributes')
%timeit dd = expand_info_string3(df.sample(100), 'attributes')
%timeit dd = expand_info_string3(df.sample(1000), 'attributes')
%timeit dd = expand_info_string3(df.sample(10000), 'attributes')
</code></pre>
<pre><code>90 ms ± 28.5 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
338 ms ± 66.5 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
553 ms ± 13.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
4.55 s ± 379 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
</code></pre>
<h2>3. Series.str.split(expand=True) + Series.apply a function to do 1 split</h2>
<pre><code>def expand_info_string2(df, column='info', entity_sep=';', id_sep='='):
def do_expand(cell):
data = cell.dropna().values
return pd.Series(list(zip(*data))[-1], index=list(zip(*data))[0])
info = df[column].str.split(entity_sep, expand=True).apply(lambda cell: cell.str.split(id_sep), axis=1).apply(do_expand, axis=1)
return pd.concat([df.drop(columns=[column]), info.add_prefix(f'{column}.')], axis=1).fillna('')
%timeit dd = expand_info_string2(df.sample(10), 'attributes')
%timeit dd = expand_info_string2(df.sample(100), 'attributes')
%timeit dd = expand_info_string2(df.sample(1000), 'attributes')
%timeit dd = expand_info_string2(df.sample(10000), 'attributes')
</code></pre>
<pre><code>236 ms ± 44.2 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
262 ms ± 19.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
1.35 s ± 281 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
11.2 s ± 313 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
</code></pre>
<h2>4. Series.str.extractall + regex</h2>
<pre><code>def expand_info_regex(df, column='info', entity_sep=';', id_sep='='):
info_re = re.compile("([^;]+?)=(?:([^;]+))?")
info= (df[column].str.extractall(info_re).reset_index(level=1, drop=True)
.set_index(0, append=True)[1]
.unstack(level=1))
return pd.concat([df.drop(columns=[column]), info.add_prefix(f'{column}.')], axis=1).fillna('')
%timeit dd = expand_info_regex(df.sample(10), 'attributes')
%timeit dd = expand_info_regex(df.sample(100), 'attributes')
%timeit dd = expand_info_regex(df.sample(1000), 'attributes')
%timeit dd = expand_info_regex(df.sample(10000), 'attributes')
%timeit dd = expand_info_regex(df.sample(100000), 'attributes')
</code></pre>
<pre><code>122 ms ± 3.41 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
129 ms ± 3.38 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
157 ms ± 3.03 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
474 ms ± 9.87 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
4.28 s ± 33.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
</code></pre>
<h2>5. Series.str.split(expand).stack + DataFrame.groupby</h2>
<pre><code>def expand_info_stackgroup(df, column='info', entity_sep=';', id_sep='='):
info = (df[column].str.split(entity_sep, expand=True).stack()
.str.split(id_sep, expand=True).reset_index()
.drop(columns='level_1').groupby(['level_0', 0]).first()
.unstack(fill_value='').reset_index(drop=True))
info.columns = [x[1] for x in info.columns]
info.index = df.index
return pd.concat([df.drop(columns=[column]), info.add_prefix(f'{column}.')], axis=1)
%timeit dd = expand_info_stackgroup(df.sample(10), 'attributes')
%timeit dd = expand_info_stackgroup(df.sample(100), 'attributes')
%timeit dd = expand_info_stackgroup(df.sample(1000), 'attributes')
%timeit dd = expand_info_stackgroup(df.sample(10000), 'attributes')
%timeit dd = expand_info_stackgroup(df.sample(100000), 'attributes')
</code></pre>
<pre><code>178 ms ± 24.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
269 ms ± 114 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
231 ms ± 87.2 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
494 ms ± 21.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
4.51 s ± 99.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
</code></pre>
<h2>6. Series.str.split(expand).stack + DataFrame.set_index</h2>
<pre><code>def expand_info_stackindex(df, column='info', entity_sep=';', id_sep='='):
info = (df[column].str.split(entity_sep, expand=True).stack()
.str.split(id_sep, expand=True).reset_index()
.drop(columns='level_1').set_index(['level_0', 0])
.unstack(fill_value='').reset_index(drop=True))
info.columns = [x[1] for x in info.columns]
info.index = df.index
return pd.concat([df.drop(columns=[column]), info.add_prefix(f'{column}.')], axis=1)
%timeit dd = expand_info_stackindex(df.sample(10), 'attributes')
%timeit dd = expand_info_stackindex(df.sample(100), 'attributes')
%timeit dd = expand_info_stackindex(df.sample(1000), 'attributes')
%timeit dd = expand_info_stackindex(df.sample(10000), 'attributes')
%timeit dd = expand_info_stackindex(df.sample(100000), 'attributes')
</code></pre>
<pre><code>200 ms ± 91.7 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
133 ms ± 4.39 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
158 ms ± 4.02 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
467 ms ± 16.2 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
4.16 s ± 252 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
</code></pre>
<p>Any help in trying to optimise this so that is doable for file with high number of entries would be really appreciated. Thanks!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T14:55:19.433",
"Id": "524972",
"Score": "1",
"body": "Incorporating advice from an answer into the question violates the question-and-answer nature of this site. You could post improved code as a new question, as an answer, or as a link to an external site - as described in [I improved my code based on the reviews. What next?](/help/someone-answers#help-post-body). I have rolled back the edit, so the answers make sense again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T15:20:32.623",
"Id": "524975",
"Score": "0",
"body": "Apologies. Fair enough. I'll add the modified function as a new answer, then. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T15:22:07.277",
"Id": "524976",
"Score": "0",
"body": "Or, if you want it to be reviewed and possibly further improved, post it as a new question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T15:29:09.640",
"Id": "524981",
"Score": "2",
"body": "I think I would just rather not repeat the question again, it would just look like a duplication. Posting it as a non-accepted self-answer seems to me more appropriate in this context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T17:07:56.350",
"Id": "528641",
"Score": "0",
"body": "Is it possible to obtain the source data in some other format which is faster to parse? Alternatively, have you considered something like fromfile from numpy?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T18:30:17.993",
"Id": "528648",
"Score": "0",
"body": "Admittedly, the way the file is set up is not optimal. But this is a widely used format for genomic data sharing, so not much can be done on that regard. For the `numpy.fromfile` option, although I am not familiar with the function, for what I read it seems to be for applying during file load time, similar to @sergei-malanin's reply. Ideally I would want to have the two logics (df creation and \"expansion\") separated"
}
] |
[
{
"body": "<p>I've prepared a code snippet to solve your problem:</p>\n<pre><code>import pandas as pd\nfrom tqdm import tqdm\nimport datetime as dt\n\ndef convert_data(input_file_path):\n print(f"converting file: {input_file_path}")\n output = []\n with open(input_file_path) as f:\n for i in tqdm(f):\n if i.startswith("#"):\n continue\n data = i.split("\\t")[-1]\n item = dict()\n for j in data.split(";"):\n k, v = j.split("=")\n item[k] = v.strip()\n output.append(item)\n return output\n\ndef process_data(input_file_path):\n data = convert_data(input_file_path)\n print("converting to dataframe")\n return pd.DataFrame.from_dict(data)\n\n\nstart = dt.datetime.utcnow()\ndf = process_data("stackOverflow/pandas_split_columns_optimisation/test_data/data")\nprint(dt.datetime.utcnow() - start)\n# converting file: stackOverflow/pandas_split_columns_optimisation/test_data/data\n# 3854329it [00:28, 134941.12it/s]\n# converting to dataframe\n# 0:01:53.006208\n</code></pre>\n<p>Please check it, maybe it works for you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T13:40:54.030",
"Id": "524967",
"Score": "0",
"body": "Hi @sergei-malanin, thanks for your solution. It does not cover several points I was planning to solve (1) it does not keep the other columns, (2) it cannot be guided by column name, (3) it can only be applied on read, (4) it does not append the original column name to the new columns.\nThat said, the solution is really fast in comparison to mine (0:02:57.497253 for the full 3.8M rows), I suspect because of the DataFrame.from_dict construction. Thus, I implemented that part into its own function following the others I have. Will update my question taking this adaptation into consideration."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T15:44:18.967",
"Id": "265704",
"ParentId": "265561",
"Score": "1"
}
},
{
"body": "<p>@sergei-malanin's answer is really fast in comparison with the options I provided but does not completely meet the needs of the question, namely:</p>\n<ol>\n<li>it does not keep the other columns,</li>\n<li>it cannot be guided by column name,</li>\n<li>it can only be applied on read,</li>\n<li>it does not append the original column name to the new columns</li>\n</ol>\n<p>As such, I took the idea of the <code>DataFrame.from_dict</code> construction of his solution and I adapted it to work within my requirements to showcase how it would look like:</p>\n<pre><code>def expand_info_fromdict(df, column='info', entity_sep=';', id_sep='='):\n def split_to_dict(data, entity_sep, id_sep):\n return dict([j.split(id_sep) for j in data.split(entity_sep)])\n\n info = pd.DataFrame.from_dict(list(df[column].apply(split_to_dict, entity_sep=entity_sep, id_sep=id_sep).values))\n info.index = df.index\n return pd.concat([df.drop(columns=[column]), info.add_prefix(f'{column}.').fillna('')], axis=1)\n\n%timeit dd = expand_info_fromdict(df.sample(10), 'attributes')\n%timeit dd = expand_info_fromdict(df.sample(100), 'attributes')\n%timeit dd = expand_info_fromdict(df.sample(1000), 'attributes')\n%timeit dd = expand_info_fromdict(df.sample(10000), 'attributes')\n%timeit dd = expand_info_fromdict(df.sample(100000), 'attributes')\n</code></pre>\n<p>The times I got where somewhat better.</p>\n<pre><code>129 ms ± 30.9 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n175 ms ± 124 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n205 ms ± 23 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)\n374 ms ± 6.11 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n2.42 s ± 45.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n</code></pre>\n<p>For the 100k sample, this is almost a 40% improvement.</p>\n<p>The full 3.8M rows run in just over 3 minutes.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T15:37:05.803",
"Id": "265785",
"ParentId": "265561",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T16:49:41.877",
"Id": "265561",
"Score": "3",
"Tags": [
"python",
"performance",
"pandas"
],
"Title": "Pandas split column into multiple: performance improvement"
}
|
265561
|
<p>I have a Item Service that is Called from an Asp.Net Core API Controller. The query gets all items in a particular category for display on an eCommerce web site (reactjs). The controller only returns json:</p>
<pre><code> public async Task<IEnumerable<EcommerceItemDto>> GetAllItemsAsync(string customerNumber, string category = "All", int page = 0, int pageSize = 9999)
{
IQueryable<Category> categories;
if (category == "All")
{
categories = _context.Categories
.Include(c => c.Children)
.Include(p => p.Parent)
.AsNoTrackingWithIdentityResolution();
}
else
{
categories = _context.Categories
.Where(n => n.Name == category)
.Include(c => c.Children)
.Include(p => p.Parent)
.AsNoTrackingWithIdentityResolution();
}
var items = await _context.EcommerceItems
.FromSqlInterpolated($"SELECT * FROM [cp].[GetEcommerceItemsView] WHERE [CustomerNumber] = {customerNumber}")
.Include(x => x.Category)
.Include(i => i.Images.OrderByDescending(d => d.Default))
.OrderBy(i => i.ItemNumber)
.Where(c => categories.Any(x => x.Children.Contains(c.Category)) || categories.Contains(c.Category))
.Skip(page * pageSize)
.Take(pageSize)
.AsNoTracking()
.ToListAsync();
var dto = _mapper.Map<IEnumerable<EcommerceItemDto>>(items);
return dto;
}
</code></pre>
<p>I can show my Controller <code>Action</code>, <code>[cp].[GetEcommerceItemsView]</code> View, <code>EcommerceItem</code> Class, <code>EcommerceItemDto</code> Class, <code>Category</code> Class and <code>Images</code> Class if anyone thinks that will help. I have run <code>Tuning</code> on my Sql Database and applied the recommendations. I have bench-marked this using <code>_mapper.Map</code> as well as <code>.ProjectTo</code> and mapper.Map is faster by a hair. In my test Database, I only have about 65 Items with Images. But this request is taking about 1000 to 1500 ms.</p>
<p><strong>UPDATE</strong></p>
<p>As Per requested by @iSR5...</p>
<pre><code>public class EcommerceItem : INotifyPropertyChanged
{
[Key]
public string ItemNumber { get; set; }
public string ItemDescription { get; set; }
[Column(TypeName = "text")]
public string ExtendedDesc { get; set; }
public bool Featured { get; set; }
public string CategoryName { get; set; }
public Category Category { get; set; }
[Column(TypeName = "numeric(19, 5)")]
public decimal Price { get; set; }
[Column(TypeName = "numeric(19, 5)")]
public decimal QtyOnHand { get; set; }
public bool? Metadata1Active { get; set; }
[StringLength(50)]
public string Metadata1Name { get; set; }
[StringLength(50)]
public string Metadata1 { get; set; }
... // I have Twenty Matadata Groups
public bool? Metadata20Active { get; set; }
[StringLength(50)]
public string Metadata20Name { get; set; }
[StringLength(50)]
public string Metadata20 { get; set; }
public ICollection<EcommerceItemImages> Images { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
</code></pre>
<p>My EcommerceItemDto:</p>
<pre><code>public class EcommerceItemDto
{
[Key]
public string ItemNumber { get; set; }
public string ItemDescription { get; set; }
[Column(TypeName = "text")]
public string ExtendedDesc { get; set; }
public bool Featured { get; set; }
public string CategoryName { get; set; }
[Column(TypeName = "numeric(19, 5)")]
public decimal Price { get; set; }
[Column(TypeName = "numeric(19, 5)")]
public decimal QtyOnHand { get; set; }
public bool? Metadata1Active { get; set; }
[StringLength(50)]
public string Metadata1Name { get; set; }
[StringLength(50)]
public string Metadata1 { get; set; }
... // Same as EcommerceItem I have twenty Metadata groups
public bool? Metadata20Active { get; set; }
[StringLength(50)]
public string Metadata20Name { get; set; }
[StringLength(50)]
public string Metadata20 { get; set; }
public ICollection<EcommerceItemImagesDto> Images { get; set; }
}
</code></pre>
<p>My Category Model:</p>
<pre><code>[Table("bma_ec_categories")]
public class Category : INotifyPropertyChanged
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column("category_id")]
public int CategoryId { get; set; }
[Column("parent_category_id")]
public int? ParentId { get; set; }
[Required]
[Column("category_name")]
[StringLength(50)]
public string Name { get; set; }
public Category Parent { get; set; }
public ICollection<Category> Children { get; set; }
[Column("title")]
[StringLength(150)]
public string Title { get; set; }
[Column("description")]
[StringLength(250)]
public string Description { get; set; }
[Column("keywords")]
[StringLength(250)]
public string Keywords { get; set; }
[Column("page_content", TypeName = "text")]
public string PageContent { get; set; }
[Column("banner_group_id")]
public int? BannerGroupId { get; set; }
[Column("inactive")]
public byte? Inactive { get; set; }
[Column("issitecategory")]
public byte Issitecategory { get; set; }
[Column("metadata1_active")]
public byte Metadata1Active { get; set; }
[Column("metadata1_name")]
[StringLength(50)]
public string Metadata1Name { get; set; }
...
[Column("metadata20_active")]
public byte? Metadata20Active { get; set; }
[Column("metadata20_name")]
[StringLength(50)]
public string Metadata20Name { get; set; }
[Column("sort_order")]
public int? SortOrder { get; set; }
public ICollection<EcommerceItem> Items { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
</code></pre>
<p>Just to be complete, my <code>View</code>, it gets the calculated Price for the logged in user and flattens the category and item Metadata:</p>
<pre class="lang-sql prettyprint-override"><code>SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER VIEW [cp].[GetEcommerceItemsView]
AS
SELECT
RTRIM(LTRIM(IV.ITEMNMBR)) AS ItemNumber
,RTRIM(LTRIM(IM.ITEMDESC)) AS ItemDescription
,ecItems.[extended_desc] AS ExtendedDesc
,CAST(ecItems.Featured AS BIT) AS Featured
,cat.category_name AS CategoryName
,CASE IM.PRICMTHD
WHEN 1 THEN IV.UOMPRICE
WHEN 2 THEN IV.UOMPRICE * IC.LISTPRCE / 100
WHEN 3 THEN (IM.CURRCOST) * (1 + (IV.UOMPRICE / 100))
WHEN 4 THEN (IM.STNDCOST) * (1 + (IV.UOMPRICE / 100))
WHEN 5 THEN (IM.CURRCOST) / (1 - (IV.UOMPRICE / 100))
WHEN 6 THEN (IM.STNDCOST) / (1 - (IV.UOMPRICE / 100))
ELSE 0
END AS Price
,IQ.QTYONHND AS QtyOnHand
,CAST(cat.[metadata1_active] AS BIT) AS [Metadata1Active]
,cat.[metadata1_name] AS [Metadata1Name]
,ecItems.[metadata1] AS [Metadata1]
...
,CAST(cat.[metadata20_active] AS BIT) AS [Metadata20Active]
,cat.[metadata20_name] AS [Metadata20Name]
,ecItems.[Metadata20] AS [Metadata20]
,C.CUSTNMBR AS CustomerNumber
FROM dbo.RM00101 AS C
LEFT OUTER JOIN dbo.IV00108 AS IV
ON C.PRCLEVEL = IV.PRCLEVEL
LEFT OUTER JOIN dbo.IV00101 AS IM
ON IM.ITEMNMBR = IV.ITEMNMBR
LEFT OUTER JOIN dbo.IV00102 AS IQ
ON IQ.ITEMNMBR = IV.ITEMNMBR
AND IQ.RCRDTYPE = 1
LEFT OUTER JOIN dbo.IV00105 AS IC
ON IC.ITEMNMBR = IV.ITEMNMBR
AND IV.CURNCYID = IC.CURNCYID
LEFT OUTER JOIN dbo.bma_ec_items AS ecItems
ON ecItems.ITEMNMBR = IV.ITEMNMBR
LEFT OUTER JOIN dbo.bma_ec_item_category AS icat
ON icat.ITEMNMBR = IV.ITEMNMBR
LEFT OUTER JOIN dbo.bma_ec_categories AS cat
ON cat.category_id = icat.category_id
WHERE (IM.ITEMNMBR IN (SELECT
ITEMNMBR
FROM dbo.bma_ec_items
WHERE (display_on_ecommerce = 1))
)
GO
</code></pre>
<p><em>Special Note:</em> I am using Newtonsoft Json Serializer in my controller. I know There are faster Serializers out there.</p>
<p><strong>UPDATE 2</strong></p>
<p>As requested, Test Results follows:</p>
<p>BenchmarkDotNet=v0.13.0, OS=Windows 10.0.19043.1110 (21H1/May2021Update)
Intel Core i7-7700 CPU 3.60GHz (Kaby Lake), 1 CPU, 8 logical and 4 physical cores
.NET SDK=5.0.302
[Host] : .NET 5.0.8 (5.0.821.31504), X64 RyuJIT [AttachedDebugger]
DefaultJob : .NET 5.0.8 (5.0.821.31504), X64 RyuJIT</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Method</th>
<th>IterationCount</th>
<th style="text-align: right;">Mean</th>
<th style="text-align: right;">Error</th>
<th style="text-align: right;">StdDev</th>
<th style="text-align: right;">Min</th>
<th style="text-align: right;">Max</th>
<th style="text-align: right;">Ratio</th>
<th style="text-align: right;">RatioSD</th>
</tr>
</thead>
<tbody>
<tr>
<td>GetItems</td>
<td>50</td>
<td style="text-align: right;">228.2 ms</td>
<td style="text-align: right;">8.15 ms</td>
<td style="text-align: right;">23.65 ms</td>
<td style="text-align: right;">119.7 ms</td>
<td style="text-align: right;">265.6 ms</td>
<td style="text-align: right;">1.00</td>
<td style="text-align: right;">0.00</td>
</tr>
<tr>
<td>GetItemsWithChanges</td>
<td>50</td>
<td style="text-align: right;">231.0 ms</td>
<td style="text-align: right;">4.60 ms</td>
<td style="text-align: right;">10.66 ms</td>
<td style="text-align: right;">211.3 ms</td>
<td style="text-align: right;">253.1 ms</td>
<td style="text-align: right;">1.04</td>
<td style="text-align: right;">0.22</td>
</tr>
<tr>
<td></td>
<td></td>
<td style="text-align: right;"></td>
<td style="text-align: right;"></td>
<td style="text-align: right;"></td>
<td style="text-align: right;"></td>
<td style="text-align: right;"></td>
<td style="text-align: right;"></td>
<td style="text-align: right;"></td>
</tr>
<tr>
<td>GetItems</td>
<td>100</td>
<td style="text-align: right;">455.8 ms</td>
<td style="text-align: right;">9.04 ms</td>
<td style="text-align: right;">24.29 ms</td>
<td style="text-align: right;">414.9 ms</td>
<td style="text-align: right;">522.0 ms</td>
<td style="text-align: right;">1.00</td>
<td style="text-align: right;">0.00</td>
</tr>
<tr>
<td>GetItemsWithChanges</td>
<td>100</td>
<td style="text-align: right;">453.8 ms</td>
<td style="text-align: right;">9.00 ms</td>
<td style="text-align: right;">20.32 ms</td>
<td style="text-align: right;">421.0 ms</td>
<td style="text-align: right;">502.2 ms</td>
<td style="text-align: right;">1.00</td>
<td style="text-align: right;">0.08</td>
</tr>
</tbody>
</table>
</div>
<p><strong>UPDATE 3</strong></p>
<p>Test without categories:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Method</th>
<th>IterationCount</th>
<th style="text-align: right;">Mean</th>
<th style="text-align: right;">Error</th>
<th style="text-align: right;">StdDev</th>
<th style="text-align: right;">Min</th>
<th style="text-align: right;">Max</th>
<th style="text-align: right;">Ratio</th>
<th style="text-align: right;">RatioSD</th>
</tr>
</thead>
<tbody>
<tr>
<td>GetItems</td>
<td>50</td>
<td style="text-align: right;">231.1 ms</td>
<td style="text-align: right;">6.06 ms</td>
<td style="text-align: right;">17.88 ms</td>
<td style="text-align: right;">140.4 ms</td>
<td style="text-align: right;">259.7 ms</td>
<td style="text-align: right;">1.00</td>
<td style="text-align: right;">0.00</td>
</tr>
<tr>
<td>GetItemsWithChangesWithoutCategories</td>
<td>50</td>
<td style="text-align: right;">230.9 ms</td>
<td style="text-align: right;">4.61 ms</td>
<td style="text-align: right;">10.69 ms</td>
<td style="text-align: right;">214.0 ms</td>
<td style="text-align: right;">255.4 ms</td>
<td style="text-align: right;">1.01</td>
<td style="text-align: right;">0.15</td>
</tr>
<tr>
<td></td>
<td></td>
<td style="text-align: right;"></td>
<td style="text-align: right;"></td>
<td style="text-align: right;"></td>
<td style="text-align: right;"></td>
<td style="text-align: right;"></td>
<td style="text-align: right;"></td>
<td style="text-align: right;"></td>
</tr>
<tr>
<td>GetItems</td>
<td>100</td>
<td style="text-align: right;">450.2 ms</td>
<td style="text-align: right;">8.99 ms</td>
<td style="text-align: right;">22.40 ms</td>
<td style="text-align: right;">416.6 ms</td>
<td style="text-align: right;">510.1 ms</td>
<td style="text-align: right;">1.00</td>
<td style="text-align: right;">0.00</td>
</tr>
<tr>
<td>GetItemsWithChangesWithoutCategories</td>
<td>100</td>
<td style="text-align: right;">452.5 ms</td>
<td style="text-align: right;">9.01 ms</td>
<td style="text-align: right;">23.10 ms</td>
<td style="text-align: right;">417.3 ms</td>
<td style="text-align: right;">515.9 ms</td>
<td style="text-align: right;">1.01</td>
<td style="text-align: right;">0.08</td>
</tr>
</tbody>
</table>
</div>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T19:30:16.863",
"Id": "524527",
"Score": "0",
"body": "Please follow our title guidance: https://codereview.stackexchange.com/help/how-to-ask"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T02:33:23.143",
"Id": "524540",
"Score": "0",
"body": "please provide the `Category` and `EcommerceItem` models along with `EcommerceItemDto`. We need to know how the relationships works. Also, did you try to query the table and not the `View` and see how it performs ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T13:02:35.490",
"Id": "524559",
"Score": "0",
"body": "@iSR5 Done+. My `View` get the custom Price for the logged-in user."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T15:43:10.777",
"Id": "524566",
"Score": "0",
"body": "@Randy on `items`, comment out `.Include(x => x.Category)` and `.OrderBy(i => i.ItemNumber)` and in the raw sql add `TOP {pageSize} * FROM` and also `ORDER BY ItemNumber ASC;` test it, and let me know the performance difference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T16:46:11.220",
"Id": "524573",
"Score": "0",
"body": "@iSR5 Test results posted"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T17:04:43.807",
"Id": "524575",
"Score": "0",
"body": "@Randy thanks for the update, I need to confirm if the issue is from the DB side or the code part. Would you be kind and do another test excluding the `Category` part. So you only doing a direct query without a category. and check the SQL execution plan for it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T17:59:07.543",
"Id": "524577",
"Score": "0",
"body": "@iSR5 New test results posted"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T18:17:48.343",
"Id": "524578",
"Score": "0",
"body": "@Randy it seems that the bottleneck is the view itself. You'll need to re-evaluate it and review its execution plan, do the proper indexes (also include full-text indexes if needed) to improve its performance."
}
] |
[
{
"body": "<p>I followed all the recommendations from RedGate's Sql Prompt (Modified my view to the one recommended change):</p>\n<pre class=\"lang-sql prettyprint-override\"><code>SET ANSI_NULLS ON\nGO\n\nSET QUOTED_IDENTIFIER ON\nGO\n\nALTER VIEW [cp].[GetEcommerceItemsView]\nAS\nSELECT\n RTRIM(LTRIM(IV.ITEMNMBR)) AS ItemNumber\n ,RTRIM(LTRIM(IM.ITEMDESC)) AS ItemDescription\n ,ecItems.[extended_desc] AS ExtendedDesc\n ,CAST(ecItems.Featured AS BIT) AS Featured\n ,cat.category_name AS CategoryName\n ,CASE IM.PRICMTHD\n WHEN 1 THEN IV.UOMPRICE\n WHEN 2 THEN IV.UOMPRICE * IC.LISTPRCE / 100\n WHEN 3 THEN (IM.CURRCOST) * (1 + (IV.UOMPRICE / 100))\n WHEN 4 THEN (IM.STNDCOST) * (1 + (IV.UOMPRICE / 100))\n WHEN 5 THEN (IM.CURRCOST) / (1 - (IV.UOMPRICE / 100))\n WHEN 6 THEN (IM.STNDCOST) / (1 - (IV.UOMPRICE / 100))\n ELSE 0\n END AS Price\n ,IQ.QTYONHND AS QtyOnHand\n ,CAST(cat.[metadata1_active] AS BIT) AS [Metadata1Active]\n ,cat.[metadata1_name] AS [Metadata1Name]\n ,ecItems.[metadata1] AS [Metadata1]\n\n ... \n\n ,CAST(cat.[metadata20_active] AS BIT) AS [Metadata20Active]\n ,cat.[metadata20_name] AS [Metadata20Name]\n ,ecItems.[Metadata20] AS [Metadata20]\n ,C.CUSTNMBR AS CustomerNumber\nFROM dbo.RM00101 AS C\nLEFT OUTER JOIN dbo.IV00108 AS IV\n ON C.PRCLEVEL = IV.PRCLEVEL\nLEFT OUTER JOIN dbo.IV00101 AS IM\n ON IM.ITEMNMBR = IV.ITEMNMBR\nLEFT OUTER JOIN dbo.IV00102 AS IQ\n ON IQ.ITEMNMBR = IV.ITEMNMBR\n AND IQ.RCRDTYPE = 1\nLEFT OUTER JOIN dbo.IV00105 AS IC\n ON IC.ITEMNMBR = IV.ITEMNMBR\n AND IV.CURNCYID = IC.CURNCYID\nLEFT OUTER JOIN dbo.bma_ec_items AS ecItems\n ON ecItems.ITEMNMBR = IV.ITEMNMBR \n AND ecItems.display_on_ecommerce = 1\nLEFT OUTER JOIN dbo.bma_ec_item_category AS icat\n ON icat.ITEMNMBR = IV.ITEMNMBR\nLEFT OUTER JOIN dbo.bma_ec_categories AS cat\n ON cat.category_id = icat.category_id\nGO\n\n</code></pre>\n<p>Re-Ran the the tuning advisor and applied those Index creations. Then I switched to System.Text.Json from Newtonsoft.Json as my serializer in the Asp.net Core project. Re-Ran my Bench-Mark test:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Method</th>\n<th>IterationCount</th>\n<th style=\"text-align: right;\">Mean</th>\n<th style=\"text-align: right;\">Error</th>\n<th style=\"text-align: right;\">StdDev</th>\n<th style=\"text-align: right;\">Min</th>\n<th style=\"text-align: right;\">Max</th>\n<th style=\"text-align: right;\">Ratio</th>\n<th style=\"text-align: right;\">RatioSD</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>GetItems</td>\n<td>50</td>\n<td style=\"text-align: right;\">225.5 ms</td>\n<td style=\"text-align: right;\">4.89 ms</td>\n<td style=\"text-align: right;\">14.26 ms</td>\n<td style=\"text-align: right;\">134.77 ms</td>\n<td style=\"text-align: right;\">250.5 ms</td>\n<td style=\"text-align: right;\">1.00</td>\n<td style=\"text-align: right;\">0.00</td>\n</tr>\n<tr>\n<td>GetItemsWithChangesWithoutCategories</td>\n<td>50</td>\n<td style=\"text-align: right;\">225.4 ms</td>\n<td style=\"text-align: right;\">6.86 ms</td>\n<td style=\"text-align: right;\">20.23 ms</td>\n<td style=\"text-align: right;\">98.31 ms</td>\n<td style=\"text-align: right;\">254.2 ms</td>\n<td style=\"text-align: right;\">1.01</td>\n<td style=\"text-align: right;\">0.13</td>\n</tr>\n<tr>\n<td></td>\n<td></td>\n<td style=\"text-align: right;\"></td>\n<td style=\"text-align: right;\"></td>\n<td style=\"text-align: right;\"></td>\n<td style=\"text-align: right;\"></td>\n<td style=\"text-align: right;\"></td>\n<td style=\"text-align: right;\"></td>\n<td style=\"text-align: right;\"></td>\n</tr>\n<tr>\n<td>GetItems</td>\n<td>100</td>\n<td style=\"text-align: right;\">434.6 ms</td>\n<td style=\"text-align: right;\">7.65 ms</td>\n<td style=\"text-align: right;\">11.21 ms</td>\n<td style=\"text-align: right;\">415.40 ms</td>\n<td style=\"text-align: right;\">460.2 ms</td>\n<td style=\"text-align: right;\">1.00</td>\n<td style=\"text-align: right;\">0.00</td>\n</tr>\n<tr>\n<td>GetItemsWithChangesWithoutCategories</td>\n<td>100</td>\n<td style=\"text-align: right;\">442.1 ms</td>\n<td style=\"text-align: right;\">8.78 ms</td>\n<td style=\"text-align: right;\">16.50 ms</td>\n<td style=\"text-align: right;\">418.91 ms</td>\n<td style=\"text-align: right;\">478.6 ms</td>\n<td style=\"text-align: right;\">1.02</td>\n<td style=\"text-align: right;\">0.05</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>I guess this is optimized as it gets, unless I switch to Dapper.</p>\n<p><strong>UPDATE</strong></p>\n<p>To be fair to @iSR5, I discovered I had a typo in my username I was using to get the Authorization Token. I corrected it and re-ran the test:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Method</th>\n<th>IterationCount</th>\n<th style=\"text-align: right;\">Mean</th>\n<th style=\"text-align: right;\">Error</th>\n<th style=\"text-align: right;\">StdDev</th>\n<th style=\"text-align: right;\">Min</th>\n<th style=\"text-align: right;\">Max</th>\n<th style=\"text-align: right;\">Ratio</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>GetItems</td>\n<td>50</td>\n<td style=\"text-align: right;\">6.260 s</td>\n<td style=\"text-align: right;\">0.1213 s</td>\n<td style=\"text-align: right;\">0.1490 s</td>\n<td style=\"text-align: right;\">6.012 s</td>\n<td style=\"text-align: right;\">6.598 s</td>\n<td style=\"text-align: right;\">1.00</td>\n</tr>\n<tr>\n<td>GetItemsWithChangesWithoutCategories</td>\n<td>50</td>\n<td style=\"text-align: right;\">2.036 s</td>\n<td style=\"text-align: right;\">0.0407 s</td>\n<td style=\"text-align: right;\">0.0543 s</td>\n<td style=\"text-align: right;\">1.948 s</td>\n<td style=\"text-align: right;\">2.162 s</td>\n<td style=\"text-align: right;\">0.32</td>\n</tr>\n<tr>\n<td></td>\n<td></td>\n<td style=\"text-align: right;\"></td>\n<td style=\"text-align: right;\"></td>\n<td style=\"text-align: right;\"></td>\n<td style=\"text-align: right;\"></td>\n<td style=\"text-align: right;\"></td>\n<td style=\"text-align: right;\"></td>\n</tr>\n<tr>\n<td>GetItems</td>\n<td>100</td>\n<td style=\"text-align: right;\">12.521 s</td>\n<td style=\"text-align: right;\">0.2439 s</td>\n<td style=\"text-align: right;\">0.2281 s</td>\n<td style=\"text-align: right;\">12.048 s</td>\n<td style=\"text-align: right;\">12.932 s</td>\n<td style=\"text-align: right;\">1.00</td>\n</tr>\n<tr>\n<td>GetItemsWithChangesWithoutCategories</td>\n<td>100</td>\n<td style=\"text-align: right;\">4.135 s</td>\n<td style=\"text-align: right;\">0.0790 s</td>\n<td style=\"text-align: right;\">0.0739 s</td>\n<td style=\"text-align: right;\">4.031 s</td>\n<td style=\"text-align: right;\">4.242 s</td>\n<td style=\"text-align: right;\">0.33</td>\n</tr>\n</tbody>\n</table>\n</div>",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T01:41:29.657",
"Id": "524657",
"Score": "0",
"body": "I don't think that dapper will solve the issue. You need to re-evaluate the view outside your code (using SSMS or any DBMS IDE), then apply the same query on it while `Execution Plan` is on. then review the execution plan, see what you can improve. And about the updated benchmark (with corrected username), it shows that it's even getting slower than before. (probably because of getting more data since you've corrected the username)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T20:55:22.853",
"Id": "265587",
"ParentId": "265562",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "265587",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T16:56:39.597",
"Id": "265562",
"Score": "0",
"Tags": [
"c#",
"performance",
"asp.net-core",
"entity-framework-core"
],
"Title": "Finding items involving a particular category"
}
|
265562
|
<p>the introduction is this:</p>
<blockquote>
<p>You are a member of a biotechnology programming team that is responsible for creating a system for lab technicians, which will assist them with drug analysis.</p>
<p>Your goal is to create the application that will let them input their findings into the system, provide a meaningful analysis and verify the correctness of the data that they have sent.</p>
<h2>tasks:</h2>
<p>Your goal in this part is to implement the <code>app.drug_analyzer.DrugAnalyzer</code> class. It will be responsible for analyzing data like the data presented below:</p>
<pre class="lang-none prettyprint-override"><code>+-----------+-------------+------------------+-------------+
| pill_id | pill_weight | active_substance | impurities |
+-----------+-------------|------------------|-------------|
| L01-10 | 1007.67 | 102.88 | 1.00100 |
| L01-06 | 996.42 | 99.68 | 2.00087 |
| G02-03 | 1111.95 | 125.04 | 3.00004 |
| G03-06 | 989.01 | 119.00 | 4.00062 |
+-----------+-------------+-------------+-------------+-----
</code></pre>
<p>The initialization of the class can be done from Python's list of lists (or nothing) and stored in the instance
variable called data as per example below:</p>
<pre><code>>>> my_drug_data = [
... ['L01-10', 1007.67, 102.88, 1.00100],
... ['L01-06', 996.42, 99.68, 2.00087],
... ['G02-03', 1111.95, 125.04, 3.00100],
... ['G03-06', 989.01, 119.00, 4.00004]
... ]
>>> my_analyzer = DrugAnalyzer(my_drug_data)
>>> my_analyzer.data
[['L01-10', 1007.67, 102.88, 0.001], ['L01-06', 996.42, 99.68, 0.00087], > ['G02-03', 1111.95, 125.04, 0.00100], ['G03-06', 989.01, 119.00, 0.00004]]
>>> DrugAnalyzer().data
[]
</code></pre>
<p>The class should also have an option to add single lists into the object. Adding a list to the <code>DrugAnalyzer</code> object
should return a new instance of this object with an additional element. Adding improper type or a list with improper
length should raise a <code>ValueError</code>. An example of a correct and wrong addition output is shown below:</p>
<pre><code>>>> my_new_analyzer = my_analyzer + ['G03-01', 789.01, 129.00, 0.00008]
>>> my_new_analyzer.data
[['L01-10', 1007.67, 102.88, 0.001], ['L01-06', 996.42, 99.68, 0.00087], > ['G02-03', 1111.95, 125.04, 0.00100], ['G03-06', 989.01, 119.00, 0.00004], ['G03-01', 789.01, 129.00, 0.00008]]
>>> my_new_analyzer = my_analyzer + ['G03-01', 129.00, 0.00008]
Traceback (the most recent call is displayed as the last one):
File "<stdin>", line 1, in <module>
ValueError: Improper length of the added list.
</code></pre>
<h1>Part 2</h1>
<p>Implement the <code>verify_series</code> method inside the <code>app.drug_analyzer.DrugAnalyzer</code> class.</p>
<p>The goal of this method is to receive a list of parameters and use them to verify if the pills described inside the instance
variable data matches the given criteria. It should return a Boolean value as a result.</p>
<p>The function would be called as follows:</p>
<pre><code>verify_series(series_id = 'L01', act_subst_wgt = 100, act_subst_rate = 0.05, allowed_imp = 0.001)
</code></pre>
<p>Where:</p>
<ul>
<li>the <code>series_id</code> is a 3 characters long string that is present at the beginning of every <code>pill_id</code>, before the - sign; for example, <code>L01</code> is the <code>series_id</code> in <code>pill_id = L01-12</code>.</li>
<li>the <code>act_subst_wgt</code> is the expected weight (mg) of the active substance content in the given series in one pill.</li>
<li>the <code>act_subst_rate</code> is the allowed rate of difference in the active substance weight from the expected one. For example,
for 100 mg, the accepted values would be between 95 and 105.</li>
<li>the <code>allowed_imp</code> is the allowed rate of impure substances in the <code>pill_weight</code>. For example, for 1000 mg <code>pill_weight</code>
and 0.001 rate, the allowed amount of impurities is 1 mg.</li>
</ul>
<p>The function should take all pills that are part of the <code>L01</code> series, sum their weight and calculate if the
amount of <code>active_substance</code>, as well as impurities, match the given rates. It should return <code>True</code> if both conditions
are met and <code>False</code> if any of them is not met.</p>
<p>The <code>False</code> result should mean that all the passed parameters are proper, but either the active substance amount or the impurities amount is improper.
In case of a series_id that is not present in the data at all or in case of any improper parameter, the function should throw a <code>ValueError</code>.
Please think what could be the possible edge case in such a scenario.</p>
<h2>Example:</h2>
<pre><code>>>> my_drug_data = [
... ['L01-10', 1000.02, 102.88, 1.00100],
... ['L01-06', 999.90, 96.00, 2.00087],
... ['G02-03', 1000, 96.50, 3.00100],
... ['G03-06', 989.01, 119.00, 4.00004]
... ]
>>> my_analyzer = DrugAnalyzer(my_drug_data)
>>> my_analyzer.verify_series(series_id = 'L01', act_subst_wgt = 100, act_subst_rate = 0.05, allowed_imp = 0.001)
False
>>> // The overall active_substances weight would be 198.88, which is within the given rate of 0.05 for 200 mg (2 * act_subst_wgt).
>>> // However, the sum of impurities would be 3.00187, which is more than 0.001*1999.92 (allowed_imp_rate * (1000.02 + 999.90).
>>> my_analyzer.verify_series(series_id = 'L01', act_subst_wgt = 100, act_subst_rate = 0.05, allowed_imp = 0.0001)
True
>>> my_analyzer.verify_series(series_id = 'B03', act_subst_wgt = 100, act_subst_rate = 0.05, allowed_imp = 0.001)
Traceback (the most recent call is displayed as the last one):
File "<stdin>", line 1, in <module>
ValueError: B03 series is not present within the dataset.
</code></pre>
</blockquote>
<p><strong>my code passed through all of tests</strong></p>
<p>After my first failure I tried to make the code as compact and light as possible, using list comprehension and eliminating unnecessary variables, even though it added just 5% more to my score. Can someone can tell me what is wrong with my code and how I can write better code?</p>
<h3>my latest code</h3>
<p>(score: 58%)</p>
<pre><code> class DrugAnalyzer:
def __init__(self, data):
self.data = data
def __add__(self, data):
if len(data) == 4:
if all(isinstance(i, float) for i in data[1:]) and isinstance(data[0], str):
self.data = self.data + [data]
return self
else:
raise ValueError('Improper type on list added')
else:
raise ValueError('improper length on list added')
def verify_series(
self,
series_id: str,
act_subst_wgt: float,
act_subst_rate: float,
allowed_imp: float,
) -> bool:
pills = [pill for pill in self.data if series_id in pill[0]]
if pills:
return act_subst_wgt*len(pills)-(act_subst_wgt * len(pills) * act_subst_rate) < sum([i[2] for i in pills]) < act_subst_wgt*len(pills)+(act_subst_wgt * len(pills) * act_subst_rate) and sum([i[3] for i in pills]) < allowed_imp*sum([i[1] for i in pills])
else:
raise ValueError(f'There is no {series_id} series in database')
</code></pre>
<h3>previous version</h3>
<p>(score: 55%)</p>
<pre><code>class DrugAnalyzer():
def __init__(self,data):
self.data = data
def __add__(self,data1):
if len(data1) < 4:
raise ValueError('improper lenght of list added')
if type(data1[0]) == str:
if type(data1[1]) and type(data1[2]) and type(data1[3]) == float:
self.data = self.data + [data1]
return self
else:
raise ValueError('Improper type on list added')
else: raise ValueError('Improper type on list added')
def verify_series(
self,
series_id: str,
act_subst_wgt: float,
act_subst_rate: float,
allowed_imp: float,
) -> bool:
serie = []
for pill in self.data:
if series_id in pill[0]:
serie.append(pill)
active = []
imp = []
weight = []
print(serie)
for pill in serie:
weight.append(pill[1])
active.append(pill[2])
imp.append(pill[3])
if serie == 0:
raise ValueError('the serie isnt in list')
dif = (act_subst_wgt*len(serie))*act_subst_rate
if act_subst_wgt*len(serie)-dif < sum(active) < act_subst_wgt*len(serie)+dif and sum(imp) < allowed_imp*sum(weight):
return True
else:
return False
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T19:14:05.133",
"Id": "524526",
"Score": "4",
"body": "Welcome to Code Review (again)! The current question title, which states your concerns about the code, is too general to be useful here. Simply deleting your [old question](https://codereview.stackexchange.com/questions/265558/i-made-a-python-code-test-from-devskiller-several-times-but-i-keep-getting-a-lo) and reposting it as a new question, without fixing issues like the title is not fixing the problem. Edit the title to something like \"Drug Analyzer\". Put your concerns in the question's body. If this is an online challenge, post a link to it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T00:02:43.643",
"Id": "524537",
"Score": "1",
"body": "It's worth stating that this is the entry test for Brainly recruitment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T07:03:11.263",
"Id": "524541",
"Score": "0",
"body": "What does the \"score\" mean? If it's a fraction of unit tests that pass, then clearly the code isn't finished and ready for review. If it's a performance measure (and functionally incorrect code doesn't get any score), then please say so, and add the [tag:performance] tag to indicate what kind of review is required."
}
] |
[
{
"body": "<p>I don't know about how these scores are being figured, so I can't say what would improve your score. Your code looks like an OK "face value" implementation of the spec, with <s>two</s> three details "wrong".</p>\n<ol>\n<li>The spec doesn't say that the addition operation should modify <code>self</code>, it actually implies that the operation should <em>not</em> modify <code>self</code>. <em>"Adding a list to the DrugAnalyzer object should return a new instance of this object with an additional element."</em> This is consistent with how we usually think of <code>+</code>; <code>5+1</code> returns <code>6</code>, but it doesn't <em>change</em> 5.</li>\n<li><code>if series_id in pill[0]</code> will be True for <code>'L01'</code> and <code>'G02-L01'</code>; you want <a href=\"https://docs.python.org/3/library/stdtypes.html#str.startswith\" rel=\"nofollow noreferrer\"><code>startswith</code></a>. (Note that it's a <em>method of</em> the larger string.)</li>\n<li>You didn't account for the empty constructor call.</li>\n</ol>\n<p>Other stuff:</p>\n<ul>\n<li>You're using type hints; that's great! Make sure you're validating them with <a href=\"http://mypy-lang.org/\" rel=\"nofollow noreferrer\">MyPy</a>, and go ahead and use them for everything.</li>\n<li><a href=\"https://pycodestyle.pycqa.org/en/latest/\" rel=\"nofollow noreferrer\">pycodestyle</a> will help keep your formatting standardized. It's pretty strict; I don't always use it. But your line-23 is really bad!</li>\n<li>There's no reason I can imagine for the validation to <em>only</em> happen when adding to an existing object; it should be centralized. Maybe it could be centralized in its own class? That way you could have a consistent "list of row objects" instead of a less trustworthy "list of lists". Some extra conversion machinery will be needed though... Anyway, I'd use <a href=\"https://docs.python.org/3/library/dataclasses.html\" rel=\"nofollow noreferrer\">dataclasses</a> for this.</li>\n<li>The validation code itself could be tightened up a little, in my opinion.</li>\n<li>The spec says <em>"... the function should throw a ValueError. Please think what could be the possible edge case in such a scenario."</em>\nMaybe they mean negative numbers or something; IDK? Whoever's designing this API isn't doing a good job, but that's out of your hands!</li>\n<li>Many functions (like <code>sum</code>) can take bare generators instead of a list.</li>\n<li>I think for the verification inequalities, you should technically use the "or-equal-to" versions, but I would really hope it doesn't matter!</li>\n</ul>\n<p>IDK how helpful this version will be to you. If you run it you'll find that the assertions at the end don't pass; they're based on the shell output examples in your question, which seem to have incorrect values in the last column of the output? This could be a really important detail you've overlooked, but I'm out of time. Sorry!</p>\n<pre class=\"lang-py prettyprint-override\"><code>import collections.abc as c # these are _classes_, not _types_.\nfrom dataclasses import dataclass\nfrom numbers import Real # again, a class, for typing we'll use float.\nfrom typing import Any, Iterable, Sequence, List # these are _types_.\n# You can just use List for everything; I like to split hairs.\n\n\n@dataclass(frozen=True) # I think they should be frozen by default.\nclass PillRow:\n pill_id: str\n series: str\n weight: float\n active: float\n impure: float\n\n @staticmethod\n def from_data(data: Any) -> "PillRow":\n if isinstance(data, PillRow):\n return data\n try:\n assert isinstance(data, c.Sized) and isinstance(data, c.Iterable), ("Could not parse data.", data)\n assert 4 == len(data), f"Four columns needed; found {len(data)}."\n pill_id, pill_weight, active_substance, impurities = data\n assert isinstance(pill_id, str), ("Column One must be the pill id.", pill_id)\n series_id = pill_id.split('-')[0]\n assert 3 == len(series_id), ("Could not parse series id from the pill id.", pill_id)\n assert isinstance(pill_weight, Real), ("Invalid pill weight.", pill_weight)\n assert isinstance(active_substance, Real), ("Invalid active-substance weight.", active_substance)\n assert isinstance(impurities, Real), ("Invalid impurities weight.", impurities)\n return PillRow(pill_id=pill_id,\n series=series_id,\n weight=float(pill_weight),\n active=float(active_substance),\n impure=float(impurities))\n except AssertionError as ae:\n raise ValueError(ae)\n\n def to_list(self) -> list:\n return [self.pill_id, self.weight, self.active, self.impure]\n\n\nclass DrugAnalyzer:\n def __init__(self, *datas: Iterable[Sequence]): # taking *args will make __add__ easier to write.\n self._data = [PillRow.from_data(pill)\n for data in datas\n for pill in data]\n self.data = [pill.to_list() for pill in self._data]\n\n def __add__(self, data):\n return DataAnalyzer(self._data, [data]) # that's what all the above work was for!\n\n def verify_series(self,\n series_id: str,\n act_subst_wgt: float,\n act_subst_rate: float,\n allowed_imp: float) -> bool:\n pills = [p for p in self._data if p.series == series_id]\n if not pills:\n raise ValueError(f'There is no {series_id} series in database')\n else:\n num_pills = len(pills)\n target_active = act_subst_wgt * num_pills\n margin_active = target_active * act_subst_rate\n actual_active = sum(p.active for p in pills)\n max_impure = allowed_imp * sum(p.weight for p in pills)\n actual_impure = sum(p.impure for p in pills)\n return (abs(target_active - actual_active) <= margin_active) and (actual_impure <= max_impure)\n\n\nif __name__ == "__main__":\n # tests constructors\n my_drug_data = [\n ['L01-10', 1007.67, 102.88, 1.00100],\n ['L01-06', 996.42, 99.68, 2.00087],\n ['G02-03', 1111.95, 125.04, 3.00100],\n ['G03-06', 989.01, 119.00, 4.00004]\n ]\n my_analyzer = DrugAnalyzer(my_drug_data)\n assert tuple(map(tuple, my_analyzer.data)) == (\n ('L01-10', 1007.67, 102.88, 0.001),\n ('L01-06', 996.42, 99.68, 0.00087),\n ('G02-03', 1111.95, 125.04, 0.00100),\n ('G03-06', 989.01, 119.00, 0.00004)\n ), tuple(map(tuple, my_analyzer.data))\n assert tuple(DrugAnalyzer().data) == (), DrugAnalyzer().data\n\n # tests plus\n my_new_analyzer = my_analyzer + ['G03-01', 789.01, 129.00, 0.00008]\n assert tuple(map(tuple, my_new_analyzer.data)) == (\n ('L01-10', 1007.67, 102.88, 0.001),\n ('L01-06', 996.42, 99.68, 0.00087),\n ('G02-03', 1111.95, 125.04, 0.00100),\n ('G03-06', 989.01, 119.00, 0.00004),\n ('G03-01', 789.01, 129.00, 0.00008)\n ), my_new_analyzer.data\n thrown = False\n try:\n my_new_analyzer = my_analyzer + ['G03-01', 129.00, 0.00008]\n except ValueError:\n thrown = True\n assert thrown, my_new_analyzer\n\n # tests verify\n my_drug_data = [['L01-10', 1000.02, 102.88, 1.00100],\n ['L01-06', 999.90, 96.00, 2.00087],\n ['G02-03', 1000, 96.50, 3.00100],\n ['G03-06', 989.01, 119.00, 4.00004]]\n my_analyzer = DrugAnalyzer(my_drug_data)\n assert not my_analyzer.verify_series(series_id='L01',\n act_subst_wgt=100,\n act_subst_rate=0.05,\n allowed_imp=0.001)\n assert my_analyzer.verify_series(series_id='L01',\n act_subst_wgt=100,\n act_subst_rate=0.05,\n allowed_imp=0.0001)\n thrown = False\n try:\n my_analyzer.verify_series(series_id='B03',\n act_subst_wgt=100,\n act_subst_rate=0.05,\n allowed_imp=0.001)\n except ValueError:\n thrown = True\n assert thrown\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T00:00:01.043",
"Id": "524536",
"Score": "0",
"body": "Asserting, catching the assertion, and re-raising as a `ValueError` trashing the original stack is... not great? You'd be better-off replacing the assertions with individual raises of your own error type. Even if you kept your current assert-reraise pattern, you would want to perhaps `raise ValueError(str(ae)) from ae` to preserve the original stack."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T19:00:00.300",
"Id": "524581",
"Score": "0",
"body": "It's _not_ great. The spec asks for a specific error type, and I really think having a separate `if...raise...` for each cause is too verbose. Asserting/catching/re-raising smells bad, but gets the point across. Using `raise...from` preserves some extra information, which is good, but in this case it actually makes the error messages harder to read, so I feel conflicted. Ideally/intuitively the \"error\" clause of an `assert...` statement could be the actual exception you want raised, but python doesn't do that :("
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T19:04:44.067",
"Id": "524583",
"Score": "0",
"body": "I suppose there's always the danger of someone running this with the `-O` flag set..."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T22:00:29.047",
"Id": "265569",
"ParentId": "265563",
"Score": "1"
}
},
{
"body": "<p>I don't know how the code is scored, but <em>flat is better than nested</em>. If you want to raise an exception, do it early. Consider</p>\n<pre><code>def __add__(self, data):\n if len(data) != 4:\n raise ValueError('improper length on list added')\n if not all(isinstance(i, float) for i in data[1:]) or not isinstance(data[0], str):\n raise ValueError('Improper type on list added')\n self.data = self.data + [data]\n return self\n</code></pre>\n<p>I am also not clear why do you insist on <code>data[1:]</code> being <code>float</code>. <code>Fraction</code> would work perfectly fine, as would many other types do, as long as <code>+</code> and <code><</code> are defined.</p>\n<hr />\n<blockquote>\n<p><code>series_id</code> is a 3 characters long string that is present at the beginning of every <code>pill_id</code>, before the <code>-</code> sign</p>\n</blockquote>\n<p>I don't see how this requirement is implemented.</p>\n<hr />\n<pre><code> act_subst_wgt*len(pills)-(act_subst_wgt * len(pills) * act_subst_rate) < sum([i[2] for i in pills]) < act_subst_wgt*len(pills)+(act_subst_wgt * len(pills) * act_subst_rate) and sum([i[3] for i in pills]) < allowed_imp*sum([i[1] for i in pills])\n</code></pre>\n<p>is utterly unreadable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T11:51:18.327",
"Id": "524551",
"Score": "0",
"body": "Your second point about `float` could be improved by saying to use [`numbers.Real`](https://docs.python.org/3/library/numbers.html#numbers.Real) instead in the `isinstance` check."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T05:16:55.693",
"Id": "265571",
"ParentId": "265563",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T17:55:51.483",
"Id": "265563",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"interview-questions"
],
"Title": "Interview: Drug Analyzer class"
}
|
265563
|
<p>So I built a house recently and didn't want to rely on "privacy-questionnable" systems like Google Home or Amazon whatever so I decided to build a doorbell system myself.</p>
<h3>Hardware</h3>
<p>I use a RPI4B+ as doorbell hardware and MQTT as communication platform between my home server, the doorbell hardware and my Android app, which makes three components.</p>
<ol>
<li>RPI4B+ - my outdoor doorbell including RPI webcam, a simple mic and a simple speaker</li>
<li>Ubuntu server - my MQTT server</li>
<li>Android client - my doorbell app (which is the one to be reviewed here)</li>
</ol>
<h3>Software - Android Client</h3>
<p>For development, I use Qt 5.15 with <a href="https://doc.qt.io/QtMQTT/index.html" rel="nofollow noreferrer">QtMQTT</a>.
For webcam video transfer, I use a simple RTSP server.</p>
<p>I am having heavy architectural issues in my code, which you're about to see.</p>
<h3>The Problem</h3>
<p>My MQTT client is built upon the <code>QMqttClient</code> class which I use both in QML and C++. When triggering the <strong>open door</strong> MQTT message, I want to use the same client I'm using declared in my QML file but I just don't feel like what I am doing there is right because I just can't seem to use the QML-declared MQTT client in my C++ code reasonably.</p>
<p>Please give me some feedback on my code architecture and tell me a better way to have a clean architecture here, thanks a lot in advance.</p>
<h3>Code</h3>
<h4>DoorOpener.h</h4>
<pre class="lang-cpp prettyprint-override"><code>#ifndef DOOROPENER_H
#define DOOROPENER_H
#include <QObject>
#include <QByteArray>
#include <QMqttClient>
class DoorOpener : public QObject
{
Q_OBJECT
public:
DoorOpener(QObject *parent = nullptr);
~DoorOpener() = default;
public slots:
bool open();
private:
QMqttClient* _client;
std::string _access_token {};
void initializeWithMqtt();
};
#endif // DOOROPENER_H
</code></pre>
<h4>DoorOpener.cpp</h4>
<pre class="lang-cpp prettyprint-override"><code>#include "DoorOpener.h"
#include "log.h"
#include "variables.h"
#include <QFile>
#include <QDebug>
DoorOpener::DoorOpener(QObject* parent)
{
Q_UNUSED(parent);
initializeWithMqtt();
}
void DoorOpener::initializeWithMqtt()
{
_client = new QMqttClient();
_client->setHostname(hdvars::MQTT_HOSTNAME.c_str());
_client->setPort(hdvars::MQTT_PORT);
LOG_DBG("Initializing DoorOpener:");
LOG_DBG("\t - Host: " + _client->hostname().toStdString());
LOG_DBG("\t - Port: " + std::to_string(_client->port()));
// TODO this is bad architecture. it should be safe to know when the connection is established. (see main.qml)
if (_client->state() != QMqttClient::Connected) {
_client->connectToHost();
}
connect(_client, &QMqttClient::stateChanged, [](QMqttClient::ClientState state) {
LOG_INF("MQTT client state is now " + [&]() -> std::string {
switch (state) {
case QMqttClient::Disconnected:
return "\"Disconnected\"";
case QMqttClient::Connecting:
return "\"Connecting\"";
case QMqttClient::Connected:
return "\"Connected\"";
default:
return "";
}
}());
});
if (QFile atFile { "access_token" }; atFile.open(QIODevice::ReadOnly)) {
LOG_DBG("Reading access token.");
QString token { atFile.readAll() };
// we only care about the first line of the "access_token" file
_access_token = token.split("\n").first().toStdString();
if (_access_token.empty()) {
LOG_ERR("Unable to read access token.");
}
else {
LOG_INF("Access token read.");
}
}
}
bool DoorOpener::open()
{
if (_client->state() != QMqttClient::Connected) {
LOG_ERR("Connect to MQTT client before calling open() function.");
return false;
}
LOG_DBG("Trying to send MQTT message to server with topic " + hdvars::MQTT_TOPIC + ".");
if (_access_token.empty()) {
LOG_WRN("No access token provided.");
}
qint32 retval { _client->publish(QMqttTopicName(hdvars::MQTT_TOPIC.c_str()), QByteArray(_access_token.c_str())) };
LOG_DBG("publish() returned " + std::to_string(retval) + ".");
return 0 == retval;
}
</code></pre>
<h4>QmlMqttClient.h</h4>
<pre class="lang-cpp prettyprint-override"><code>#ifndef QMLMQTTCLIENT_H
#define QMLMQTTCLIENT_H
#include <QtCore/QMap>
#include <QtMqtt/QMqttClient>
#include <QtMqtt/QMqttSubscription>
class QmlMqttClient;
class QmlMqttSubscription : public QObject
{
Q_OBJECT
Q_PROPERTY(QMqttTopicFilter topic MEMBER m_topic NOTIFY topicChanged)
public:
QmlMqttSubscription(QMqttSubscription *s, QmlMqttClient *c);
~QmlMqttSubscription();
Q_SIGNALS:
void topicChanged(QString);
void messageReceived(const QString &msg);
public slots:
void handleMessage(const QMqttMessage &qmsg);
private:
Q_DISABLE_COPY(QmlMqttSubscription)
QMqttSubscription *sub;
QmlMqttClient *client;
QMqttTopicFilter m_topic;
};
class QmlMqttClient : public QMqttClient
{
Q_OBJECT
public:
QmlMqttClient(QObject *parent = nullptr);
Q_INVOKABLE QmlMqttSubscription* subscribe();
private:
Q_DISABLE_COPY(QmlMqttClient)
};
#endif // QMLMQTTCLIENT_H
</code></pre>
<h4>QmlMqttClient.cpp</h4>
<pre class="lang-cpp prettyprint-override"><code>#include "QmlMqttClient.h"
#include "log.h"
#include "variables.h"
QmlMqttClient::QmlMqttClient(QObject *parent)
: QMqttClient(parent)
{
setHostname(hdvars::MQTT_HOSTNAME.c_str());
setPort(hdvars::MQTT_PORT);
}
QmlMqttSubscription* QmlMqttClient::subscribe()
{
LOG_INF("Initializing subscription with topic " + hdvars::MQTT_TOPIC + ".");
QMqttSubscription* sub { QMqttClient::subscribe(QMqttTopicFilter(hdvars::MQTT_TOPIC.c_str()), 0) };
QmlMqttSubscription* result { new QmlMqttSubscription(sub, this) };
return result;
}
QmlMqttSubscription::QmlMqttSubscription(QMqttSubscription *s, QmlMqttClient *c)
: sub(s)
, client(c)
{
connect(sub, &QMqttSubscription::messageReceived, this, &QmlMqttSubscription::handleMessage);
m_topic = sub->topic();
}
QmlMqttSubscription::~QmlMqttSubscription()
{
}
void QmlMqttSubscription::handleMessage(const QMqttMessage &qmsg)
{
emit messageReceived(qmsg.payload());
}
</code></pre>
<h4>variables.h</h4>
<pre class="lang-cpp prettyprint-override"><code>#ifndef VARIABLES_H
#define VARIABLES_H
#include <string>
namespace hdvars
{
static const std::string MQTT_HOSTNAME { "localhost" };
static const std::string MQTT_TOPIC { "my_topic/heimdall" };
static const std::uint32_t MQTT_PORT { 1883 };
}
#endif // VARIABLES_H
</code></pre>
<h4>main.cpp</h4>
<pre class="lang-cpp prettyprint-override"><code>#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "log.h"
#include "QmlMqttClient.h"
#include "DoorOpener.h"
int main(int argc, char *argv[])
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
// TODO put all these log lines in a static function in log.h: initialize(std::string filename)
// Logging configuration
std::string const& logfile { "heimdall-client.log" };
if (!freopen(logfile.c_str(), "a", stderr)) {
// we can still write to stderr.
LOG_ERR("Unable to create log file! Continuing without log.");
}
LOG_INF("------------------\n");
LOG_INF("Hello from heimdall client.");
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl) {
LOG_FTL("Unable to load " + url.toString().toStdString() + ". Exiting.");
QCoreApplication::exit(-1);
}
}, Qt::QueuedConnection);
qmlRegisterType<QmlMqttClient>("MqttClient", 1, 0, "MqttClient");
qmlRegisterUncreatableType<QmlMqttSubscription>("MqttClient", 1, 0, "MqttSubscription", QLatin1String("Subscriptions are read-only"));
qmlRegisterType<DoorOpener>("DoorOpener", 1, 0, "DoorOpener");
engine.load(url);
return app.exec();
}
</code></pre>
<h4>main.qml</h4>
<pre><code>import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.1
import QtQuick.Layouts 1.1
import QtMultimedia 5.12
import MqttClient 1.0
import DoorOpener 1.0
Window {
width: 360
height: 640
visible: true
title: qsTr("heimdall")
// background image
Image {
source: "qrc:/bg.jpg"
anchors.fill: parent
fillMode: Image.Pad
opacity: .25
}
// mqtt client
MqttClient {
id: client
Component.onCompleted: {
// TODO this is bad architecture. it should be safe to know when the connection is established. (see DoorOpener.cpp)
connectToHost()
}
onConnected: {
subscribe()
}
onDisconnected: {
video.stop()
}
onStateChanged: {
stateIndicator.color = getState()
stateIndicatorText.text = color == "green" ? "✔" : ""
}
onMessageReceived: {
video.play()
}
Component.onDestruction: {
disconnectFromHost()
}
function getState() {
switch (state) {
case MqttClient.Disconnected:
return "red"
case MqttClient.Connecting:
return "yellow"
case MqttClient.Connected:
return "green"
default:
return "gray"
}
}
}
DoorOpener {
id: doorOpener
}
// caption
Label {
id: caption
// text: "Heimdall - Welcome Home"
text: "Here's Heimdall"
font {
family: "Open Sans MS"
bold: true
capitalization: Font.SmallCaps
pointSize: 14
}
anchors {
top: parent.top
topMargin: 10
horizontalCenter: parent.horizontalCenter
}
}
// webcam stream
Video {
id: video
objectName: "vplayer"
width: parent.width - 20
height: 200
autoPlay: client.connected
source: "rtsp://localhost:8554/mystream" // TODO
onPlaying: vplaceholder.visible = false
Image {
id: vplaceholder
width: parent.width
height: parent.height
source: "qrc:/test_picture.png"
}
anchors {
top: caption.bottom
topMargin: 10
horizontalCenter: parent.horizontalCenter
}
onErrorChanged: {
console.log("error: " + video.errorString)
}
MouseArea {
anchors.fill: parent
onClicked: {
video.muted = !video.muted
}
}
focus: true
Image {
id: muteIndicator
source: "mute_white.png"
width: 64
height: width
visible: video.muted
anchors.centerIn: parent
}
} // Video
// Buttons
Item {
width: parent.width
height: 50
anchors {
top: video.bottom
topMargin: 10
centerIn: parent
}
Button {
id: btnTalk
objectName: "btnTalk"
text: "Sprechen"
anchors.left: parent.left
anchors.leftMargin: 10
onClicked: {
bgrTalk.start()
}
Rectangle {
id: bgrect_talk
width: parent.width
height: parent.height
color: "white"
}
SequentialAnimation {
id: bgrTalk
PropertyAnimation {
target: bgrect_talk
property: "color"
to: "darkseagreen"
duration: 500
}
PropertyAnimation {
target: bgrect_talk
property: "color"
to: "white"
duration: 500
easing.type: Easing.InCirc
}
}
}
Button {
id: btnOpen
objectName: "btnOpen"
text: "Öffnen"
property var bgColor: "darkred"
anchors.right: parent.right
anchors.rightMargin: 10
onClicked: {
var opened = doorOpener.open()
if (opened) {
bgColor = "forestgreen"
}
bgrOpened.start()
}
Rectangle {
id: bgrect_open
width: parent.width
height: parent.height
color: "white"
}
SequentialAnimation {
id: bgrOpened
PropertyAnimation {
target: bgrect_open
property: "color"
to: btnOpen.bgColor
duration: 500
}
PropertyAnimation {
target: bgrect_open
property: "color"
to: "white"
duration: 500
easing.type: Easing.InCirc
}
}
}
}
Item {
anchors {
left: parent.left
leftMargin: 10
bottom: parent.bottom
bottomMargin: 10
}
width: parent.width - 20
height: 25
Rectangle {
id: stateIndicator
width: 75
height: 20
color: "gray"
Text {
id: stateIndicatorText
text: "?"
color: "white"
anchors.centerIn: parent
}
}
Button {
anchors.right: parent.right
text: "Reconnect"
onPressed: {
client.disconnectFromHost()
vplaceholder.visible = true
client.connectToHost()
}
width: 75
height: 20
}
}
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T19:06:02.870",
"Id": "265566",
"Score": "7",
"Tags": [
"c++",
"c++17",
"qt",
"qml"
],
"Title": "A simple Qt + MQTT doorbell application"
}
|
265566
|
<p>I am writing a web application (Servlets, JDBC, no Spring - for learning purposes) that accepts orders from customers, while registered couriers can choose which one of these orders they want to deliver. Several couriers may want to deliver the same order, in which case the system creates a contest and sets the deadline for every willing courier to apply. When the time is up, the system selects the winner and deletes the contest.</p>
<p>I made one class that takes care of all contest logic and chose to make a <code>static final ConcurrentHashMap<Long, Queue<Courier>></code> for holding all contests. I am also using a <code>final static ScheduledExecutorService</code> to set timers for every contest.</p>
<p>The two most important methods are <code>addOrCreate()</code> and <code>withdraw()</code> (while the timer is on and selection process hasn't started yet, any candidate can change his mind and withdraw his application). Since there will be a harsh multithreaded environment with many concurrent requests from different couriers, I need to make sure that these methods work in a predictable, thread-safe manner. I am particularly concerned with <code>withdraw()</code> method, as I use synchronization on a map bucket, and I am not sure if that is the best solution.</p>
<p>Please advice whether the following implementation is acceptable.</p>
<pre><code>public class ContestManager
{
private static final ConcurrentMap<Long, Queue<Courier>> ALL_CONTESTS = new ConcurrentHashMap<>();
private static final ScheduledExecutorService THREAD_POOL = Executors.newScheduledThreadPool(16);
/**
* Add courier to an existing contest or create new contest with courier
*/
public static void addOrCreate(final Long orderId, final Courier courier) {
if (ALL_CONTESTS.get(orderId) == null) {
ALL_CONTESTS.computeIfAbsent(orderId, o -> {
// Create new contest
final Queue<Courier> contest = new ConcurrentLinkedQueue<>();
// Set selection process delay
THREAD_POOL.schedule(() -> {
updateDataBase(orderId, applySelectionLogic(contest));
// Remove entry from the map
ALL_CONTESTS.remove(orderId);
}, 5, TimeUnit.MINUTES);
// Store contest in map
return contest;
});
}
// Add courier to contest
ALL_CONTESTS.get(orderId).offer(courier);
}
/**
* Withdraw courier from an existing contest
*/
public static void withdraw(Long orderId, Courier courier) {
if (ALL_CONTESTS.get(orderId) != null) {
synchronized (ALL_CONTESTS.get(orderId)) {
if (ALL_CONTESTS.get(orderId) != null) {
ALL_CONTESTS.get(orderId).remove(courier);
}
}
}
}
private static Courier applySelectionLogic(Queue<Courier> queue) {
// Selection logic
}
private static void updateDataBase(Long orderId, Courier courier) {
// Update database
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T06:36:44.713",
"Id": "524611",
"Score": "0",
"body": "Welcome to Stack Review, in the withdraw method the synchronized is really necessary ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T13:35:39.690",
"Id": "524627",
"Score": "0",
"body": "@jimmayhem if you see something in the question code that can be improved, please write an answer instead of editing."
}
] |
[
{
"body": "<ul>\n<li>Naming: Uppercase names are usually reserved for constants.</li>\n<li>addOrCreate :\nWhy are you checking orderId twice? computeIfAbsent will check if the orderid is there, there is no performance or any other gain in doing it beforehand. Then you are getting it for the third time, however your function is not atomic. So it is possible that it is not going to be there at this point and your method will throw a null pointer exception. It is also possible that the callback is called just after your final get call. In that case you will just silently lose the courier. Your schedule code just schedules a task and forgets about it. It means that among other things, you can not restart your server without losing the queue.</li>\n<li>withdraw :\nYou are checking orderid three times here for no reason. When your second call happens, the value might already gone and your synchronize will fail. Also, not sure what this synchronize synchronizes with. Since it is the only statement here, it can only synchronize with itself, however, there is little need to synchronize a single call to a concurrent collection. The third get is equally unnneded since remove succeeds if the item does not exist.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T07:47:29.233",
"Id": "265594",
"ParentId": "265567",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T21:01:42.800",
"Id": "265567",
"Score": "2",
"Tags": [
"java",
"concurrency",
"servlets"
],
"Title": "Correct synchronization of reads and writes to ConcurrentHashMap and ConcurrentLinkedQueue"
}
|
265567
|
<p>I was working on <a href="https://leetcode.com/problems/kth-largest-element-in-an-array/" rel="nofollow noreferrer">kth largest element problem on leetcode</a></p>
<h2>Question</h2>
<p>Given an integer array nums and an integer k, return the kth largest element in the array.</p>
<p>Note that it is the kth largest element in the sorted order, not the kth distinct element.</p>
<p>Example 1:</p>
<pre><code>Input: nums = [3,2,1,5,6,4], k = 2
Output: 5
</code></pre>
<p>Example 2:</p>
<pre><code>Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
Output: 4
</code></pre>
<h2>My Solution</h2>
<p>I'm basically setting every max element in array to Minimum possible integer and doing this k times.</p>
<p>Then i just calculate the maximum value in the array.</p>
<pre><code>class Solution {
public int findKthLargest(int[] nums, int k) {
for(int i = 0; i < k-1; i++){
replaceLargestWithMin(nums);
}
return findLargest(nums);
}
//TC: O(N)
public void replaceLargestWithMin(int[] nums){
// O(N)
int currMax = findLargest(nums);
// O(N)
for(int i = nums.length - 1; i >= 0; i--){
if(nums[i] == currMax){
nums[i] = Integer.MIN_VALUE;
break;
}
}
}
//TC: O(N)
public int findLargest(int[] nums){
int max = nums[0];
for(int num : nums){
max = Math.max(max, num);
}
return max;
}
}
</code></pre>
<p>As per my understanding the time complexity of solution will be <code>kO(n) ~ O(n)</code> which is same for heap solution.</p>
<p>However, the above solution is performing in the lower 5 percentile solutions in java.</p>
<p>Is this solution not in O(n)? Am I calculating the time complexity incorrectly?</p>
<p><strong>EDIT:</strong></p>
<p>Updated solution after doing changes suggested by <code>vvotan</code> in comments:</p>
<pre><code>class Solution {
public int findKthLargest(int[] nums, int k) {
for(int i = 0; i < k-1; i++){
replaceLargestWithMin(nums);
}
return nums[findLargest(nums)];
}
public void replaceLargestWithMin(int[] nums){
nums[findLargest(nums)] = Integer.MIN_VALUE;
}
public int findLargest(int[] nums){
int maxIndex = 0;
for(int i = 0; i < nums.length; i++){
if(nums[maxIndex] < nums[i]){
maxIndex = i;
}
}
return maxIndex;
}
}
</code></pre>
<p>This increases the overall performance (only tested on leetcode) ~ 15%</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T01:26:08.507",
"Id": "524539",
"Score": "2",
"body": "Am I calculating the time complexity incorrectly? - Yes. You presume that `k` is fixed (or small compared to `n`). Only then the conclusion `kO(n) ~ O(n)` holds. In the worst case `k ~ n` the time complexity degrades to \\$O(n^2)\\$."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T10:19:53.063",
"Id": "524544",
"Score": "0",
"body": "you've jus found the largest value, why are you searching for it again? Make findLargest return the position of the larges element"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T10:22:14.113",
"Id": "524546",
"Score": "0",
"body": "@vnp\nThat makes sense. But the solution using heap has time complexity of O(Nlogk). How is that better than a simple sorting solution i.e. O(NlogN). Why are heaps the go to solution for these problems?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T10:28:38.177",
"Id": "524547",
"Score": "0",
"body": "@vvotan\nSorry but i don't understand can you explain what you are proposing? I'm calling findLargest k times to search for the kth largest element"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T10:43:41.670",
"Id": "524549",
"Score": "1",
"body": "@D_S_X, in replaceLargestWithMin you are finding the maximum value by looking through the whole array. Then you are looking through the whole array again until you find that same value again to replace it. But you already knew where it was, just chose to ignore that information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T10:58:18.330",
"Id": "524550",
"Score": "0",
"body": "Got it thanks ... that improves the performance slightly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T15:54:39.363",
"Id": "524569",
"Score": "1",
"body": "There is a bot that runs that finds edits after a question is answered. Rather than editing in the future after an answer has been provided, it might be better if you either posted your own answer or provided a followup question with a link to the previous question. It might also have been better if @vvotan had posted an answer rather than a comment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T02:39:53.257",
"Id": "524703",
"Score": "0",
"body": "@pacmaninbw\nI get the point, however vvotan's comment didn't answer the question that why this function is not in O(n). But it did help optimise the code, so i made an edit with optimised code for future readers."
}
] |
[
{
"body": "<p>You need to be observant of the bounds in the problem description, in particular they allow k=n which means your worst case time complexity is <em>not</em> constant k times O(n), it's actually O(kn), and when k is approximately n, then it turns into O(n^2).</p>\n<p>I solved a similar problem a while ago and did some interesting <a href=\"https://codereview.stackexchange.com/questions/116469/print-the-n-longest-lines-in-a-file\">benchmarking</a>. I'm not sure why you don't want to use a heap which is the obvious solution but I showed that insertion sort works well for moderately big k.</p>\n<p><strong>Edit: Why is using a heap preferred over sort and pick k'th element?</strong></p>\n<p>Excellent question, for a heap you only need to keep a heap of size K as you can always drop the smallest element and add a new, larger element from the input and get correct result. This yields time complexity of O(nlog(k)) as opposed to O(nlog(n)) for sort and pick. However note that for the heap you only need O(k) memory instead of O(n). Indeed when n=k sort and pick using quicksort is expected to be superior to a heap because quicksort is generally faster even though they have the same big-O behaviour. However in the case of this particular problem, it's reasonable to expect that k is notably smaller than n <em>most of the time</em> so we expect the heap to be better. But these are just qualified guesses, you really should try both and benchmark.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T10:30:36.150",
"Id": "524548",
"Score": "0",
"body": "Thanks, yeah i understand why my solution is performing so. \n\nBut in case k = n, won't heap solution O(Nlogk) take O(NlogN) which is same as a simple sort and fetch kth element solution? Why is heap preferred over sorting solution?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T11:53:29.877",
"Id": "524552",
"Score": "0",
"body": "@D_S_X I updated my answer, ptal"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T14:16:57.340",
"Id": "524562",
"Score": "1",
"body": "*\"not kO(n), it's actually O(kn)\"* - [Aren't they the same?](https://en.wikipedia.org/wiki/Big_O_notation#Product)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T15:23:59.937",
"Id": "524565",
"Score": "0",
"body": "@KellyBundy\nIt says `f.O(g) = O(fg)` so i guess they're the same right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T15:55:47.697",
"Id": "524570",
"Score": "0",
"body": "Nice to see you are still providing good answers!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T19:52:50.967",
"Id": "524589",
"Score": "0",
"body": "@KellyBundy well technically yes I was trying to make the point that it needs to be considered part of the big-O behaviour as OP simplified kO(n) to O(n) implying to me that they though k was constant. I'll update soon"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T10:23:34.947",
"Id": "265573",
"ParentId": "265568",
"Score": "4"
}
},
{
"body": "<p>It is possible to achieve a much better performance in a brutal way result with the use of auxiliary sorted k size array obtained copying and ordering the first k elements from your <code>nums</code> array:</p>\n<pre><code>int length = nums.length;\nint lastIndex = k - 1; \nint[] arr = Arrays.copyOf(nums, k);\nArrays.sort(arr);\n</code></pre>\n<p>Once you initialized the <code>arr</code> array for every remaining element in the <code>nums</code> array you can check if it is lesser than <code>arr[0]</code> and if the answer is positive you can insert the new element in the 0 position and swapping the adiacent elements to reorder the array :</p>\n<pre><code>for (int i = k; i < length; ++i) {\n if (nums[i] > arr[0]) { //<.-- elements minor than arr[0] will be excluded\n arr[0] = nums[i];\n for (int j = 1; j < k && arr[j - 1] > arr[j]; ++j) {\n int tmp = arr[j - 1];\n arr[j - 1] = arr[j];\n arr[j] = tmp;\n }\n }\n}\n</code></pre>\n<p>The final code of the method :</p>\n<pre><code>public static int findKthLargest(int[] nums, int k) {\n int length = nums.length;\n int lastIndex = k - 1; \n int[] arr = Arrays.copyOf(nums, k);\n Arrays.sort(arr);\n \n for (int i = k; i < length; ++i) {\n if (nums[i] > arr[0]) { \n arr[0] = nums[i];\n for (int j = 1; j < k && arr[j - 1] > arr[j]; ++j) {\n int tmp = arr[j - 1];\n arr[j - 1] = arr[j];\n arr[j] = tmp;\n }\n }\n }\n \n return arr[0];\n}\n</code></pre>\n<p>Note that this solution is not an optimal solution, like stated in Emily L.'s <a href=\"https://codereview.stackexchange.com/a/265573/203649\">answer</a> use of heaps can help you to improve performance.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T03:58:14.033",
"Id": "524705",
"Score": "0",
"body": "Nice approach!! I wish they had better set of test cases on leetcode to showcase which solutions is better. Oddly enough your solution runs slightly faster than heap solution. Also, simply sorting the nums and fetching kth element runs faster than both :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T05:49:32.937",
"Id": "524708",
"Score": "0",
"body": "@D_S_X Thank you :), as you said I think it depends from showcases used in the leetcode site. About my solution, to erase elements exchange once you know the position i of your new element, you could overwrite the 0..i-1 elements with the 1..i elements and write the new element in the i position."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T15:23:21.480",
"Id": "265579",
"ParentId": "265568",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "265573",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-30T21:50:49.880",
"Id": "265568",
"Score": "1",
"Tags": [
"java",
"performance",
"algorithm",
"programming-challenge"
],
"Title": "Leetcode kth largest element without using heaps"
}
|
265568
|
<p>Although there exists the most efficient "Knuth-Morris-Pratt" algorithm of string pattern matching. I tried to achieve the same result with a different approach. But I am not sure about it's efficiency. I am a novice in programming. Can anyone show me how to analyze this algorithm and find it's efficiency?</p>
<blockquote>
<p>Algorithm:<p>
Step 1: Calculate the integer value of the pattern by adding the integer values of each of the characters in it. Let it be "m"<p>
Step2: Calculate the integer values of parts of the string, with the same length as that of the pattern in the similar way as described in step 1.<p>
Step3 : Store these values in an array.<p>
Step 4 : Compare the values in array with the "m" value from step1.<P>
Step 5: If the values match then check if the part of the string matches with the pattern.
If it does then return true. If the pattern does not match at all then return false.</p>
</blockquote>
<p>I have coded the algorithm in Java. Here is the code.</p>
<pre class="lang-java prettyprint-override"><code>public class StringPatternMatchingAlgorithm {
public static boolean patternMatching(String str,String pattern){
int patternLength = pattern.length();
int patternSum = 0;
int[] patternSumArray = new int[(str.length() - patternLength)+1];
int patternSumArrayIndex = 0;
int patternSumToCheck = 0;
String toCompare = "";
for(int i=0; i<pattern.length();i++){
patternSumToCheck = patternSumToCheck + pattern.charAt(i);
}
for(int i=0; i<((str.length())-(pattern.length()-1));i++){
patternSum = 0;
for(int j=i; j<patternLength;j++){
patternSum = patternSum + str.charAt(j);
}
patternLength++;
patternSumArray[patternSumArrayIndex] = patternSum;
if(patternSumArrayIndex < patternSumArray.length-1 ){
patternSumArrayIndex++;
}
}
for(int i=0; i<patternSumArray.length;i++){
if(patternSumArray[i] == patternSumToCheck){
toCompare = "";
for(int j=i; j<(i+pattern.length());j++){
toCompare = toCompare + str.charAt(j);
}
if(toCompare.equals(pattern)){
return true;
}
}
}
return false;
}
public static void main(String[] args) {
String str = "cdxabie";
String pattern = "bie";
System.out.println(patternMatching(str, pattern));
}
}
</code></pre>
<p>The code can be run <a href="https://onlinegdb.com/uRL0smgDt" rel="nofollow noreferrer">here</a></p>
<p><strong>Edit:</strong>
As suggested in the comments to the first version of algorithm, I have committed a modification.
I used two variables <strong>"forthIndex"</strong> which is initialized to pattern's length and <strong>"backIndex"</strong> initialized to 0. Also, I calculated the integer sum of number of characters, equal to the length of pattern from index 0 and stored it in a variable named <strong>"patternSum"</strong> only once. Then onwards the algorithm adds the integer value of character at <strong>"forthIndex"</strong> to <strong><strong>"patternSum"</strong></strong> and substracts the integer value of character at <strong>"backIndex"</strong> from <strong>"patternSum"</strong> simultaneously, as the string is traversed. This eliminates the recalculation of integer sum of characters in string as it was in the former version of algorithm.</p>
<p>Here is the improved code:</p>
<pre><code>public class StringPatternMatchingAlgoVariant1 {
public static boolean matchPattern(String str,String pattern){
int patternLength = pattern.length();
int patternSum = 0;
int[] patternSumArray = new int[(str.length() - patternLength)+1];
int patternSumArrayIndex = 0;
int patternSumToCheck = 0;
String toCompare = "";
int backIndex = 0;
int forthIndex = pattern.length();
for(int i=0; i<pattern.length();i++){
patternSumToCheck = patternSumToCheck + pattern.charAt(i);
patternSum = patternSum + str.charAt(i);
}
patternSumArray[patternSumArrayIndex] = patternSum;
patternSumArrayIndex++;
for(int i=0; forthIndex<str.length();i++){
patternSum = patternSum + str.charAt(forthIndex) - str.charAt(backIndex);
forthIndex++;
backIndex++;
patternSumArray[patternSumArrayIndex] = patternSum;
patternSumArrayIndex++;
}
for(int i=0; i<patternSumArray.length;i++){
if(patternSumArray[i] == patternSumToCheck){
toCompare = "";
for(int j=i; j<(i+pattern.length());j++){
toCompare = toCompare + str.charAt(j);
}
if(toCompare.equals(pattern)){
return true;
}
}
}
return false;
}
public static void main(String[] args) {
String str = "cdxabie";
String pattern = "bie";
System.out.println(matchPattern(str, pattern));
}
</code></pre>
<p>}</p>
<p>The new version of the code can be run <a href="https://onlinegdb.com/fAJLXp1NV" rel="nofollow noreferrer">here</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T12:51:46.810",
"Id": "524619",
"Score": "1",
"body": "In the future it would be better to add a follow up question with a link back to the original question rather than editing the question. Changing the question may cause answer invalidation. Everyone needs to be able to see what the reviewer was referring to. [What to do after the question has been answered](https://codereview.stackexchange.com/help/someone-answers)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T12:54:19.733",
"Id": "524621",
"Score": "0",
"body": "@pacmaninbw You are correct bro. Will keep in mind hereafter."
}
] |
[
{
"body": "<p>A couple of comments on your answer:</p>\n<h1>Code style</h1>\n<ul>\n<li><p>If you've already stored the <code>pattern.length()</code>, why keep calling the method? Just be consistent and use that variable. Same goes for <code>str.length()</code>. I'd just store it and use it.</p>\n</li>\n<li><p>I would store <code>str.length()-(pattern.length()-1</code> in a variable an name it something like <code>numOfCasesToTest</code>, to make it clearer.</p>\n</li>\n<li><p>Check parenthesis usage:</p>\n</li>\n</ul>\n<pre class=\"lang-java prettyprint-override\"><code>for(int i=0; i<((str.length())-(pattern.length()-1));i++){\n</code></pre>\n<p>Could be written as:</p>\n<pre class=\"lang-java prettyprint-override\"><code>for(int i = 0; i < str.length() - pattern.length() - 1; i++){\n</code></pre>\n<p>Unnecessary parenthesis makes code harder to read. For further details see <a href=\"https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html\" rel=\"nofollow noreferrer\">Operator precedence</a>.</p>\n<ul>\n<li>Keep your spacing consistent. While some people prefer not having spaces between some or most operators, I'd rather have them, as I think it makes the code more readable. Whichever way you prefer, just keep consistent usage in the code. For example:</li>\n</ul>\n<pre class=\"lang-java prettyprint-override\"><code>i<patternSumArray.length // no space around comparison operator\npatternSumArray[i] == patternSumToCheck // space around comparison operator\n</code></pre>\n<h1>Algorithm</h1>\n<p>That was all code style related. Now, a comment on your algorithm:\nWhy calculate all posible cases sum, and only after that look for a match? This way, you are iterating over the whole str whereas it might not be necessary.</p>\n<p>I see how you may have reached that solution: you thought process was as described in the algorithm. But you could just ommit the part in which you store the sums, and compare with the match straight away.</p>\n<p>For example, say you had a string such as</p>\n<pre><code>Abcsomelongstringwithlotsofconentinit\n</code></pre>\n<p>And you are looking for the pattern <code>Abc</code>. Then, why bother doing of all those calculations? Simply, after you calculate one of those sums, compare it with the pattern sum.</p>\n<p>Still (maybe I'm being naive), but I do not see how calculating the sum, comparing it, and then actually comparing the charaters is better than just comparing the characters in the first place</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T16:51:04.597",
"Id": "524574",
"Score": "3",
"body": "\"I do not see ...\" - Because you don't compare the characters at all if the sum already doesn't match. [Rabin-Karp](https://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_algorithm) is better than sum, though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T21:10:32.817",
"Id": "524599",
"Score": "0",
"body": "@m-alorda Thanks for the review, will definitely follow the instructions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T22:10:55.227",
"Id": "524601",
"Score": "3",
"body": "Using the sum as a simple kind of rolling hash *could* in principle be an improvement on the naive algorithm, except you are calculating the sum of each substring independently, in the naive way. For there to be a potential performance benefit, the sum should be calculated using a moving window approach where you add the new character on the right of the window and subtract the character on the left of the window in order to move the window along by one without needing a loop over the whole window to recompute the sum."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T02:26:19.507",
"Id": "524606",
"Score": "0",
"body": "@kaya3, Great suggestion! Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T07:15:56.600",
"Id": "524612",
"Score": "0",
"body": "@kelly-bundy Oh, I see now. So the idea is prefering to do some calculations instead of doing more comparisons. Also, thanks for the link!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T11:41:51.867",
"Id": "524617",
"Score": "0",
"body": "@kaya3 Hi, I have modified the algorithm as you have suggested. Please have a look and let me know your opinion."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T16:34:23.590",
"Id": "265580",
"ParentId": "265575",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "265580",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T13:59:33.837",
"Id": "265575",
"Score": "4",
"Tags": [
"java",
"algorithm",
"strings",
"pattern-matching"
],
"Title": "A different approach to string pattern matching algorithm"
}
|
265575
|
<p>Have been constructing an array that can be used to populate options to find. <code>${incl[@]}</code> made from function parameter arguments that takes filename suffixes.</p>
<pre><code># get parameter arguments
("--incl")
incl+=("$2") ; shift 2 ;; # file type suffix
</code></pre>
<p>Example using <code>--incl .texi --incl .org</code> gives <code>incl=( .texi .org )</code>.</p>
<p>But I also have the option for the user to pass a delimiter called <code>fs</code>, so one can use <code>--incl .texi,.org</code> by using <code>--fs ","</code>. This means that if <code>fs</code> is specified, I would need to split each element of array incl.</p>
<p>But I believe there is repetition in the code and possible fails in some circumstances. It could need some cleaning up, and need suggestions and analysis.</p>
<pre><code> if [[ -z "$fs" ]]; then # undefined field separator
isufx=( '(' )
for ext in "${incl[@]}"; do
isufx+=( -name "*$ext" -o ) # for find cmd
done
isufx[${#isufx[@]}-1]=')' # modify last -o with )
else
isufx=( '(' )
for ext in "${incl[@]}"; do
if [[ "$ext" == *"$fs"* ]]; then
s=${ext//"$fs"/" "}
for fltyp in $s; do
isufx+=( -name "*$fltyp" -o ) # for find cmd
done
else
isufx+=( -name "*$ext" -o ) # for find cmd
fi
done
isufx[${#isufx[@]}-1]=')' # modify last -o with )
fi
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T14:19:24.737",
"Id": "524563",
"Score": "0",
"body": "Is this a good way for an if condition `[[ -z \"$fs\" && \"$ext\" == *\"$fs\"* ]]`. If I remember, one can also introduce parentheses. So it becomes `[[ (-z \"$fs\") && (\"$ext\" == *\"$fs\"*) ]]`."
}
] |
[
{
"body": "<p>The code the variable <code>s</code> that splits according to the value of <code>fs</code>.\nA more compact implementation is to use the variable <code>s</code>, then decide whether to split tho value of <code>s</code>, or not.</p>\n<p>Thus, the following code</p>\n<pre><code> isufx=( '(' )\n\n for ext in "${incl[@]}"; do\n\n s="$ext"\n [[ ! -z "$fs" && "$ext" == *"$fs"* ]] && s=${ext//"$fs"/" "}\n for fltyp in $s; do\n isufx+=( -name "*$fltyp" -o ) # options for find cmd\n done\n\n done\n\n isufx[${#isufx[@]}-1]=')' # modify last -o with )\n\n if (( vb >= 2 )); then\n echo "isufx[*]: ${isufx[*]}" \n fi\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T14:26:24.163",
"Id": "265577",
"ParentId": "265576",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T14:15:58.853",
"Id": "265576",
"Score": "0",
"Tags": [
"bash"
],
"Title": "Handling field separator option"
}
|
265576
|
<h2>What my program does</h2>
<p>My program does simulation for fantasy football. Its inputs are teams and teams results in a particular match and its outputs are how many points each team earned in each match according to given scoring rules.</p>
<p><em>Here is an example of a team:</em></p>
<pre><code>team1 = [
calculate_points.Player(p_id=204597, full_name='Jordan Pickford', club='ENG',
position='goalkeeper', is_captain=True,
is_vice_captain=False, points=0.0),
calculate_points.Player(p_id=213442, full_name='Luke Shaw', club='ENG',
position='defender', is_captain=False,
is_vice_captain=True, points=0.0),
calculate_points.Player(p_id=204614, full_name='Harry Maguire', club='ENG',
position='defender', is_captain=False,
is_vice_captain=False, points=0.0),
calculate_points.Player(p_id=204615, full_name='Mason Mount', club='ENG',
position='midfielder', is_captain=False,
is_vice_captain=False, points=0.0),
calculate_points.Player(p_id=204617, full_name='Harry Kane', club='ENG',
position='forward', is_captain=False,
is_vice_captain=False, points=0.0),
]
</code></pre>
<p><em>And an example of a team result:</em></p>
<pre><code>team_result1 = calculate_points.TeamResult(
team='ENG',
goals_for=1,
goals_against=0,
scored_goals=['Harry Kane'],
made_assist=['Kalvin Phillips'],
played60=['Jordan Pickford', 'Luke Shaw', 'John Stones', 'Harry Maguire',
'Kieran Trippier', 'Kyle Walker', 'Kalvin Phillips',
'Raheem Sterling', 'Declan Rice', 'Harry Kane'],
finished_game=['Jordan Pickford', 'Luke Shaw', 'John Stones', 'Harry Maguire',
'Kieran Trippier', 'Kyle Walker', 'Kalvin Phillips',
'Mason Mount', 'Harry Kane'],
got_booked=['Kyle Walker'],
made_shots_on_tg=['Harry Kane', 'Harry Kane', 'Raheem Sterling',
'Mason Mount', 'Harry Kane'],
saves=3)
</code></pre>
<h2>What kind of feedback I would like to get</h2>
<p>The heart of the program is <code>get_team_points()</code> function which calculates how many points a team earned in a given match by adding points earned by each player in the team.</p>
<p>To be able to perform high-throughput simulations it has to work as fast as possible. With that in mind I'm looking for a way to achieve that.</p>
<p>Since I don't have any limitations of what can be used to do that, I'm open to any suggestions including refactoring existing code, using third-party libraries, writing C/C++ extensions or even rewriting the program in another language.</p>
<p>Any other feedback beyond performance is also appreciated.</p>
<h2>What I have already tried</h2>
<ul>
<li>reducing the size of <code>TeamResult</code> object, I tried to use list of players ids instead of their fullnames.</li>
<li>eliminating some function calls, I tried removing functions for calculating player points per position, such as <code>calculate_goalkeeper_points()</code>, <code>calculate_defender_points()</code>, <code>calculate_midfielder_points()</code> and <code>calculate_forward_points()</code> in order to do that in a single function for all the players.</li>
<li>using <code>Cython</code> for making <code>calculate_team_points()</code> function precompiled and importing it as C extension.</li>
</ul>
<p>Though these steps didn't gain any significant speed up.</p>
<h2>My code, including a few unit tests</h2>
<p><em>calculate_points.py</em></p>
<pre><code>from dataclasses import dataclass
from typing import List
CAPTAIN_BONUS = 2.0
VICE_CAPTAIN_BONUS = 1.5
@dataclass
class Scoring:
"""
Represents football scoring.
"""
defender_goal: int=6
midfielder_goal: int=5
forward_goal: int=4
assist: int=3
defender_shot_on_tg: float=0.6
midfielder_or_forward_shot_on_tg: float=0.4
goalkeeper_save: float=0.5
pos_impact: float=0.3
neg_impact: float=-pos_impact
yellow_card: int=-1
defender_or_goalkeeper_clean_sheet: int=4
midfielder_clean_sheet: int=1
played60: int=2
midfielder_or_forward_finished_game: int=1
scoring = Scoring()
PlayerId = int
PlayerName = str
PlayerClub = str
PlayerPosition = str
Points = float
@dataclass
class Player:
"""
Represents a player in Fantasy Football.
"""
p_id: PlayerId
full_name: PlayerName
club: PlayerClub
position: PlayerPosition
is_captain: bool=False
is_vice_captain: bool=False
points: Points=0.0
Team = List[Player]
Teams = List[Team]
@dataclass
class TeamResult:
"""
Represents the result of a particular team with its name, goals scored,
goals conceded, players who scored goals and made assists and the number of
saves made by the goalkeeper.
"""
team: PlayerClub
goals_for: int
goals_against: int
scored_goals: List[PlayerName]
made_assist: List[PlayerName]
played60: List[PlayerName]
finished_game: List[PlayerName]
got_booked: List[PlayerName]
made_shots_on_tg: List[PlayerName]
saves: int
TeamResults = List[TeamResult]
def get_team_points(team: Team, team_result: TeamResult) -> Points:
"""
Returns how many points the given team earned with the given team result.
"""
team = calculate_team_points(team, team_result)
team = apply_captaincy(team)
return sum(p.points for p in team)
def calculate_team_points(team: Team, team_result: TeamResult) -> Team:
"""
Assigns earned points for each player in the team.
"""
points_factory = {
'goalkeeper': calculate_goalkeeper_points,
'defender': calculate_defender_points,
'midfielder': calculate_midfielder_points,
'forward': calculate_forward_points,
}
for player in team:
player.points = points_factory[player.position](player, team_result)
return team
def calculate_goalkeeper_points(goalkeeper: Player, team_result: TeamResult) -> Points:
"""
Returns points earned by a goalkeeper.
"""
got_booked = scoring.yellow_card if goalkeeper.full_name in team_result.got_booked else 0
goals_conceded = scoring.defender_or_goalkeeper_clean_sheet if team_result.goals_against == 0 else team_result.goals_against // 2 * -1
impact = calculate_impact(team_result)
saves = team_result.saves * scoring.goalkeeper_save
playing_time = scoring.played60
return sum((goals_conceded, impact, saves, playing_time, got_booked))
def calculate_defender_points(defender: Player, team_result: TeamResult) -> Points:
"""
Returns points earned by a defender.
"""
got_booked = scoring.yellow_card if defender.full_name in team_result.got_booked else 0
goals_conceded = scoring.defender_or_goalkeeper_clean_sheet if team_result.goals_against == 0 else team_result.goals_against // 2 * -1
impact = calculate_impact(team_result)
playing_time = scoring.played60
goals = team_result.scored_goals.count(defender.full_name) * scoring.defender_goal
assists = team_result.made_assist.count(defender.full_name) * scoring.assist
shots_on_tg = ((team_result.made_shots_on_tg.count(defender.full_name) -
team_result.scored_goals.count(defender.full_name)) * scoring.defender_shot_on_tg)
return sum((goals_conceded, impact, playing_time, goals, assists,
got_booked, shots_on_tg))
def calculate_midfielder_points(midfielder: Player, team_result: TeamResult) -> Points:
"""
Returns points earned by a midfielder.
"""
got_booked = scoring.yellow_card if midfielder.full_name in team_result.got_booked else 0
clean_sheet = scoring.midfielder_clean_sheet if team_result.goals_against == 0 else 0
impact = calculate_impact(team_result)
playing_time = scoring.midfielder_or_forward_finished_game + scoring.played60 if midfielder.full_name in team_result.finished_game else scoring.played60
goals = team_result.scored_goals.count(midfielder.full_name) * scoring.midfielder_goal
assists = team_result.made_assist.count(midfielder.full_name) * scoring.assist
shots_on_tg = ((team_result.made_shots_on_tg.count(midfielder.full_name) -
team_result.scored_goals.count(midfielder.full_name)) * scoring.midfielder_or_forward_shot_on_tg)
return sum((clean_sheet, impact, playing_time, goals, assists, got_booked,
shots_on_tg))
def calculate_forward_points(forward: Player, team_result: TeamResult) -> Points:
"""
Returns points earned by a forward.
"""
got_booked = scoring.yellow_card if forward.full_name in team_result.got_booked else 0
impact = calculate_impact(team_result)
playing_time = scoring.midfielder_or_forward_finished_game + scoring.played60 if forward.full_name in team_result.finished_game else scoring.played60
goals = team_result.scored_goals.count(forward.full_name) * scoring.forward_goal
assists = team_result.made_assist.count(forward.full_name) * scoring.assist
shots_on_tg = ((team_result.made_shots_on_tg.count(forward.full_name) -
team_result.scored_goals.count(forward.full_name)) * scoring.midfielder_or_forward_shot_on_tg)
return sum((impact, playing_time, goals, assists, got_booked, shots_on_tg))
def calculate_impact(team_result: TeamResult) -> Points:
"""
Calculates impact for a team based on whether it won, lost or drew.
"""
if team_result.goals_for > team_result.goals_against:
return scoring.pos_impact
elif team_result.goals_for < team_result.goals_against:
return scoring.neg_impact
return 0
def apply_captaincy(team: Team) -> Team:
"""
Multiplies points of captain and vice_captain.
"""
for player in team:
if player.is_captain:
player.points *= CAPTAIN_BONUS
elif player.is_vice_captain:
player.points *= VICE_CAPTAIN_BONUS
return team
</code></pre>
<p><em>test_points.py</em></p>
<pre><code>import unittest
import calculate_points
team1 = [
calculate_points.Player(p_id=204597, full_name='Jordan Pickford', club='ENG',
position='goalkeeper', is_captain=True,
is_vice_captain=False, points=0.0),
calculate_points.Player(p_id=213442, full_name='Luke Shaw', club='ENG',
position='defender', is_captain=False,
is_vice_captain=True, points=0.0),
calculate_points.Player(p_id=204614, full_name='Harry Maguire', club='ENG',
position='defender', is_captain=False,
is_vice_captain=False, points=0.0),
calculate_points.Player(p_id=204615, full_name='Mason Mount', club='ENG',
position='midfielder', is_captain=False,
is_vice_captain=False, points=0.0),
calculate_points.Player(p_id=204617, full_name='Harry Kane', club='ENG',
position='forward', is_captain=False,
is_vice_captain=False, points=0.0),
]
team_result1 = calculate_points.TeamResult(
team='ENG',
goals_for=1,
goals_against=0,
scored_goals=['Harry Kane'],
made_assist=['Kalvin Phillips'],
played60=['Jordan Pickford', 'Luke Shaw', 'John Stones', 'Harry Maguire',
'Kieran Trippier', 'Kyle Walker', 'Kalvin Phillips',
'Raheem Sterling', 'Declan Rice', 'Harry Kane'],
finished_game=['Jordan Pickford', 'Luke Shaw', 'John Stones', 'Harry Maguire',
'Kieran Trippier', 'Kyle Walker', 'Kalvin Phillips',
'Mason Mount', 'Harry Kane'],
got_booked=['Kyle Walker'],
made_shots_on_tg=['Harry Kane', 'Harry Kane', 'Raheem Sterling',
'Mason Mount', 'Harry Kane'],
saves=3)
team_result2 = calculate_points.TeamResult(
team='ENG',
goals_for=2,
goals_against=1,
scored_goals=['Raheem Sterling', 'Mason Mount'],
made_assist=['Substitutes', 'Luke Shaw'],
played60=['Jordan Pickford', 'Luke Shaw', 'John Stones', 'Harry Maguire',
'Kieran Trippier', 'Kyle Walker', 'Kalvin Phillips',
'Raheem Sterling', 'Mason Mount', 'Harry Kane'],
finished_game=['Jordan Pickford', 'Luke Shaw', 'John Stones',
'Harry Maguire', 'Kieran Trippier', 'Kyle Walker',
'Raheem Sterling'],
got_booked=['Jordan Pickford'],
made_shots_on_tg=['Harry Kane', 'Mason Mount', 'Mason Mount',
'Substitutes', 'Harry Kane'], saves=2)
team_result3 = calculate_points.TeamResult(
team='ENG',
goals_for=0,
goals_against=2,
scored_goals=[],
made_assist=[],
played60=['Jordan Pickford', 'Luke Shaw', 'John Stones', 'Harry Maguire',
'Kieran Trippier', 'Kyle Walker', 'Kalvin Phillips',
'Declan Rice', 'Harry Kane'],
finished_game=['Jordan Pickford', 'Luke Shaw', 'John Stones',
'Harry Maguire', 'Kieran Trippier', 'Kyle Walker',
'Kalvin Phillips', 'Declan Rice', 'Harry Kane'],
got_booked=['Luke Shaw', 'John Stones', 'Raheem Sterling', 'Mason Mount'],
made_shots_on_tg=['Harry Kane'], saves=2)
class TestGetTeamPoints(unittest.TestCase):
def test_won_game_with_cleansheet(self):
self.assertAlmostEqual(calculate_points.get_team_points(team1, team_result1), 44.15)
def test_won_game_with_conceded_goal(self):
self.assertAlmostEqual(calculate_points.get_team_points(team1, team_result2), 25.65)
def test_lost_game_with_no_goals_scored(self):
self.assertAlmostEqual(calculate_points.get_team_points(team1, team_result3), 7.45)
if __name__ == '__main__':
unittest.main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T17:05:27.307",
"Id": "524837",
"Score": "0",
"body": "Have you run a profiler on the code to find where to optimize? It seems like there is more code that is not shown. Presumably there is code to get the player and game stats from a web site, database, or file. Could that code be slow? How many players, teams, and games are there?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T17:15:38.963",
"Id": "524839",
"Score": "0",
"body": "I have run a profiler, it spends almost all the time in `calculate_team_points()` function and its calls to calculate player points for each position, since it is called so many times. Game stats are generated by another program, they aren't retrieved from anywhere. Usually I run ~10,000 teams over ~50,000 game stats, that's why it takes some reasonable amount of time, which I would like to reduce. The program has no I/O at all."
}
] |
[
{
"body": "<p>I don't think that your <code>Scoring</code> class is a great place to store constants. (Even if it was, a regular class with statics would be a better fit than a singleton dataclass.) If you wanted to do something like this, make a module instead of a class to get a cheap namespace. Given how these figures are used I'm going to propose that they just be moved inline.</p>\n<p>It's nice to see that you're aliasing types for <code>PlayerId</code> etc. If you want to go one step further in type safety, instead of a simple alias you can use <code>NewType</code>.</p>\n<p><s>I don't understand why <code>club</code> is a property on the player. Isn't that a property of the team?</s> Since <code>club</code> is supposed to be a property on the player, why is it also associated with the result object?</p>\n<p>Having <code>is_captain</code> and <code>is_vice_captain</code> as booleans on the player is problematic because you could make multiple team captains, which is probably not supposed to be possible. The more reliable thing to do is just have captain and vice members on the team object.</p>\n<p>I find "TeamResult" to be more understandable as "TeamGame", and for it to refer to a team object rather than keep a club string. Also, some of those lists should actually be sets given how they're used.</p>\n<p>The way that you're running in-place mutation for <code>apply_captaincy</code> introduces problems - more difficult-to-debug code, and objects whose validity is more difficult to guarantee. Instead, return point numbers from methods and don't store them on any of the class objects.</p>\n<p>Your <code>points_factory</code> is a somewhat-awkward stab at polymorphism where a more traditional polymorphic class inheritance model will make things easier, and also cut down on a lot of the repeated code in the <code>calculate_*</code> methods. Even if you were to keep this pattern, passing around positions as strings is not a good idea and these should be enums instead.</p>\n<p><code>team1</code> etc. in your test module can be kept out of the global namespace and moved to e.g. statics on your test class. The result variables should be moved to the individual test methods as they're only used once.</p>\n<p>Your player references, rather than being full-name strings, would be better-represented as IDs - that's what IDs are for.</p>\n<p>There's an element of your logic that I don't understand: you <em>always</em> add <code>scoring.played60</code> regardless of whether the given player actually appeared in your <code>played60</code> collection. I've shown a (commented-out) implementation that does not add this score element unless the player appeared in that collection. While this is commented out the results I've shown are equal to yours.</p>\n<p>Your test data are a little strange - you have big gaps in your team definition and are missing many of the players referenced in your results. Maybe this is OK; until you validate that the references in your results objects appear in the team instance and then it's not OK.</p>\n<h2>Suggested</h2>\n<pre><code>from dataclasses import dataclass\nfrom numbers import Real\nfrom typing import NewType, Iterable, Tuple, ClassVar, Set, Sequence\nimport unittest\nfrom unittest import TestCase\n\n\nPlayerId = NewType('PlayerId', int)\nPlayerName = NewType('PlayerName', str)\nClub = NewType('Club', str)\nPoints = NewType('Points', Real)\n\n\n@dataclass\nclass Player:\n """\n Represents a player in Fantasy Football.\n """\n p_id: PlayerId\n full_name: PlayerName\n shot_bonus: ClassVar[Points] = 0.4\n clean_sheet_bonus: ClassVar[Points] = 4\n assist_bonus: ClassVar[Points] = 3\n goal_bonus: ClassVar[Points]\n\n @staticmethod\n def booked_points(was_booked: bool) -> Points:\n if was_booked:\n return -1 # yellow_card\n return 0\n\n @classmethod\n def clean_sheet_points(cls, goals_against: int) -> Points:\n if goals_against == 0:\n return cls.clean_sheet_bonus\n return -(goals_against//2)\n\n @staticmethod\n def playtime_points(played_60: bool, finished_game: bool) -> Points:\n # if played_60:\n return 2\n # return 0\n\n @classmethod\n def goal_points(cls, goals: int) -> Points:\n return cls.goal_bonus * goals\n\n @classmethod\n def assist_points(cls, assists: int) -> Points:\n return assists * cls.assist_bonus\n\n @classmethod\n def shot_points(cls, shots_on: int, scored_goals: int) -> Points:\n return cls.shot_bonus*(shots_on - scored_goals)\n\n def captaincy_bonus(self, team: 'Team') -> Points:\n if team.captain is self:\n return 2\n if team.vice_captain is self:\n return 1.5\n return 1\n\n def get_points_before_captaincy(self, game: 'TeamGame') -> Points:\n return (\n self.booked_points(self.p_id in game.got_booked)\n + self.clean_sheet_points(game.goals_against)\n + game.impact\n + self.playtime_points(\n self.p_id in game.played60,\n self.p_id in game.finished_game,\n )\n + self.goal_points(\n game.scored_goals.count(self.p_id)\n )\n + self.assist_points(\n game.made_assist.count(self.p_id)\n )\n + self.shot_points(\n game.made_shots_on_tg.count(self.p_id),\n game.scored_goals.count(self.p_id),\n )\n )\n\n def get_points(self, game: 'TeamGame') -> Points:\n return self.get_points_before_captaincy(game) * self.captaincy_bonus(game.team)\n\n\nclass GoalKeeper(Player):\n shot_bonus = 0\n goal_bonus = 0\n assist_bonus = 0\n\n def get_points_before_captaincy(self, game: 'TeamGame') -> Points:\n return (\n super().get_points_before_captaincy(game)\n + game.saves * 0.5\n )\n\n\nclass Defender(Player):\n shot_bonus = 0.6\n goal_bonus = 6\n\n\nclass FrontLine(Player):\n @staticmethod\n def playtime_points(played_60: bool, finished_game: bool) -> Points:\n p = Player.playtime_points(played_60, finished_game)\n if finished_game:\n p += 1\n return p\n\n\nclass Midfielder(FrontLine):\n clean_sheet_bonus = 1\n goal_bonus = 5\n\n @classmethod\n def clean_sheet_points(cls, goals_against: int) -> Points:\n if goals_against == 0:\n return cls.clean_sheet_bonus\n return 0\n\n\nclass Forward(FrontLine):\n goal_bonus = 4\n\n @classmethod\n def clean_sheet_points(cls, goals_against: int) -> Points:\n return 0\n\n\nclass Team:\n def __init__(\n self,\n club: Club,\n players: Iterable[Player],\n vice_captain: Player,\n captain: Player,\n ) -> None:\n self.club, self.vice_captain, self.captain = club, vice_captain, captain\n self.players = {p.p_id: p for p in players}\n\n\n@dataclass\nclass TeamGame:\n """\n Represents the result of a particular team with its name, goals scored,\n goals conceded, players who scored goals and made assists and the number of\n saves made by the goalkeeper.\n """\n team: Team\n goals_for: int\n goals_against: int\n saves: int\n scored_goals: Sequence[PlayerId]\n made_assist: Sequence[PlayerId]\n made_shots_on_tg: Sequence[PlayerId]\n played60: Set[PlayerId]\n finished_game: Set[PlayerId]\n got_booked: Set[PlayerId]\n\n @property\n def points_by_player(self) -> Iterable[Tuple[Player, Points]]:\n for player in self.team.players.values():\n yield player, player.get_points(self)\n\n @property\n def won(self) -> bool: return self.goals_for > self.goals_against\n @property\n def lost(self) -> bool: return self.goals_for < self.goals_against\n @property\n def draw(self) -> bool: return self.goals_for == self.goals_against\n\n @property\n def impact(self) -> Points:\n """\n Calculates impact for a team based on whether it won, lost or drew.\n """\n if self.won: return 0.3\n if self.lost: return -0.3\n return 0\n\n @property\n def points(self) -> Points:\n """\n Returns how many points the given team earned with the given team result.\n """\n return sum(points for player, points in self.points_by_player)\n\n\nclass TestGetTeamPoints(TestCase):\n pickford_id, shaw_id, maguire_id, mount_id, kane_id = (\n PlayerId(i) for i in (\n 204597, 213442, 204614, 204615, 204617,\n )\n )\n phillips_id = PlayerId(99999) # ???\n\n pickford = GoalKeeper(\n p_id=pickford_id, full_name=PlayerName('Jordan Pickford'),\n )\n shaw = Defender(\n p_id=shaw_id, full_name=PlayerName('Luke Shaw'),\n )\n\n team1 = Team(\n club=Club('ENG'),\n captain=pickford,\n vice_captain=shaw,\n players=(\n pickford, shaw,\n Defender(p_id=maguire_id, full_name=PlayerName('Harry Maguire')),\n Midfielder(p_id=mount_id, full_name=PlayerName('Mason Mount')),\n Forward(p_id=kane_id, full_name=PlayerName('Harry Kane')),\n ),\n )\n\n def test_won_game_with_cleansheet(self) -> None:\n team_result1 = TeamGame(\n team=self.team1,\n goals_for=1,\n goals_against=0,\n saves=3,\n scored_goals=[self.kane_id],\n made_assist=[self.phillips_id],\n played60={\n self.pickford_id, self.shaw_id, self.maguire_id, self.kane_id, self.phillips_id,\n },\n finished_game={\n self.pickford_id, self.shaw_id, self.maguire_id, self.kane_id, self.phillips_id, self.mount_id,\n },\n got_booked=set(),\n made_shots_on_tg=[\n self.kane_id, self.kane_id, self.mount_id, self.kane_id,\n ],\n )\n\n self.assertAlmostEqual(team_result1.points, Points(44.15))\n\n def test_won_game_with_conceded_goal(self) -> None:\n team_result2 = TeamGame(\n team=self.team1,\n goals_for=2,\n goals_against=1,\n scored_goals=[self.mount_id],\n made_assist=[self.shaw_id],\n played60={self.pickford_id, self.shaw_id, self.maguire_id, self.phillips_id, self.mount_id, self.kane_id},\n finished_game={self.pickford_id, self.shaw_id, self.maguire_id},\n got_booked={self.pickford_id},\n made_shots_on_tg=[self.kane_id, self.mount_id, self.mount_id, self.kane_id],\n saves=2,\n )\n\n self.assertAlmostEqual(team_result2.points, Points(25.65))\n\n def test_lost_game_with_no_goals_scored(self) -> None:\n team_result3 = TeamGame(\n team=self.team1,\n goals_for=0,\n goals_against=2,\n scored_goals=[],\n made_assist=[],\n played60={self.pickford_id, self.shaw_id, self.maguire_id, self.phillips_id, self.kane_id},\n finished_game={self.pickford_id, self.shaw_id, self.maguire_id, self.phillips_id, self.kane_id},\n got_booked={self.shaw_id, self.mount_id},\n made_shots_on_tg=[self.kane_id],\n saves=2,\n )\n\n self.assertAlmostEqual(team_result3.points, Points(7.45))\n\n\nif __name__ == '__main__':\n unittest.main()\n</code></pre>\n<p>Though it's really outside of the scope of your question, given your priorities you shouldn't be using generators or classes at all. This is an example that should get you started down the path to vectorization; it's not exactly the same as what you do because you have piecewise operations and floor division in some places. The less of that you do the better.</p>\n<pre><code> positions = np.array(\n (\n # Goalkeep defender midfield forward\n (-1.0, -1.0, -1.0, -1.0), # yellow-card booked\n (-0.5, -0.5, 0.0, 0.0), # goals-against\n ( 0.0, 0.0, 1.0, 1.0), # finished game\n ( 0.0, 6-0.6, 5-0.4, 4-0.4), # goals, subtracting shot coefficient\n ( 0.5, 0.0, 0.0, 0.0), # saves\n ( 0.0, 3.0, 3.0, 3.0), # assists\n ( 0.0, 0.6, 0.4, 0.4), # shots\n )\n )\n\n players = np.array(\n (\n # pickford shaw maguire mount kane\n (1.0, 0.0, 0.0, 0.0, 0.0), # goalkeep\n (0.0, 1.0, 1.0, 0.0, 0.0), # defender\n (0.0, 0.0, 0.0, 1.0, 0.0), # midfield\n (0.0, 0.0, 0.0, 0.0, 1.0), # forward\n )\n )\n\n result2 = np.array(\n (\n # pickford shaw maguire mount kane\n (1, 0, 0, 0, 0), # yellow-card booked\n (1, 1, 1, 1, 1), # goals against (whole team, broadcast)\n (1, 1, 1, 0, 0), # finished game\n (0, 0, 0, 1, 0), # goals\n (2, 2, 2, 2, 2), # saves (whole team, broadcast)\n (0, 1, 0, 0, 0), # assists\n (0, 0, 0, 2, 2), # shots\n )\n )\n\n impact = 0.3\n played60 = 2\n captain = np.array((2, 1.5, 1, 1, 1))\n points = (positions @ players) * result2\n player_points = captain*(np.sum(points, axis=0) + impact + played60)\n game_points = np.sum(player_points)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T20:42:18.030",
"Id": "524592",
"Score": "0",
"body": "Thanks for the review!\n1. `club` is a property of a player because a fantasy team may consist of players from different clubs; \n2. I had captaincy as `Enum` in another version of this program, though it is not a major concern; \n3. I used in-place mutation in `apply_captaincy` to save some function calls and had it as a class method in another version as well; \n4. The same with 'points_factory', just tried to save some function call overhead; \n5. `test_points.py` is for demonstration purposes only;"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T20:42:29.800",
"Id": "524593",
"Score": "0",
"body": "6. `scoring.played60` is for future use, it can be left for now; \n7. Many players are missing because I created only one team for demonstration purposes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T20:45:19.450",
"Id": "524594",
"Score": "0",
"body": "If you care so much about micro-optimization that function call overhead is a problem, you're using entirely the wrong stack, and would want to move to numpy."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T20:45:30.627",
"Id": "524595",
"Score": "0",
"body": "I'm going to propose that that's premature optimization."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T20:47:51.317",
"Id": "524596",
"Score": "0",
"body": "In fact it is not, I have been successfully using this for a few months, nevertheless I would like to make it faster in order to run larger simulations within a few minutes instead of within an hour or two."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T20:49:36.093",
"Id": "524597",
"Score": "0",
"body": "As you might have noticed from my original post, I'm considering using different technologies, but need assistance with the best options for that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T21:08:37.960",
"Id": "524598",
"Score": "0",
"body": "https://chat.stackexchange.com/rooms/128086/fantasy-football-soccer-simulation"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T20:19:33.603",
"Id": "265585",
"ParentId": "265581",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "265585",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-31T17:02:57.390",
"Id": "265581",
"Score": "3",
"Tags": [
"python",
"performance",
"cython"
],
"Title": "Fantasy Football (Soccer) Simulation"
}
|
265581
|
<p>I recently learned about Finite State Machines (FSM) and thought I'd use that to implement a Reverse Polish Notation (RPN) calculator.</p>
<p>I wanted it to also work nicely with the unix pipe. For example, if we have an input file with a set of RPN expressions, I can do something like:</p>
<p><code>$ cat file.txt | rpn </code></p>
<p>Where <code>rpn</code> is the name of my executable.</p>
<p>For those who don't know, RPN is a type of postfix notation that helps with disambiguating order of operations in a mathematical expression, for example:</p>
<p><code>5 4 +</code> == <code>5 + 4</code> == <code>9</code></p>
<p><code>4 1 - 3 2 + *</code> == <code>(4 - 1) * (3 + 2)</code> == <code>15</code></p>
<p>Here's the implementation:</p>
<pre><code>#include <stdio.h>
#include <ctype.h>
#define MAXLEN 1000
typedef int(*opfunc)(int, int);
typedef enum
{
START,
NUMBER,
SPACE,
MINUS,
NEWLINE, // used to flush a calculation
OPERATOR,
ERROR
} State;
int add(int a, int b) { return a + b; }
int mul(int a, int b) { return a * b; }
int div(int a, int b) { return a / b; }
opfunc getop(char c)
{
switch (c) {
case '+':
return add;
case '*':
return mul;
case '/':
return div;
default:
return NULL;
}
}
int main()
{
State state = START;
int c, number, stack[MAXLEN], sign = 1, stackpos = 0;
char message[MAXLEN];
opfunc op = NULL;
while (state != ERROR && ((c = getchar()) != EOF)) {
if (state == START) {
if (isdigit(c)) {
number = c - '0';
state = NUMBER;
} else if (c == '\n') {
continue;
} else if (isspace(c)) {
state = SPACE;
} else if (c == '-') {
state = MINUS;
} else {
state = ERROR;
strcpy(message, "Invalid character at start of line");
}
} else if (state == NUMBER) {
if (isdigit(c)) {
number = (number * 10) + (c - '0');
} else if (c == '\n') {
stack[stackpos++] = sign * number;
sign = 1;
state = NEWLINE;
} else if (isspace(c)) {
stack[stackpos++] = sign * number;
sign = 1;
state = SPACE;
} else {
state = ERROR;
strcpy(message, "Invalid character at the end of number");
}
} else if (state == MINUS) {
if (isdigit(c)) {
number = c - '0';
sign = -1;
state = NUMBER;
continue;
}
if (stackpos < 2) {
state = ERROR;
strcpy(message, "More operands required");
} else if (isspace(c)) {
int right = stack[--stackpos];
int left = stack[--stackpos];
stack[stackpos++] = left - right;
state = c == '\n' ? NEWLINE : SPACE;
} else {
state = ERROR;
strcpy(message, "Invalid character after '-'");
}
} else if (state == SPACE) {
if (isdigit(c)) {
number = c - '0';
state = NUMBER;
} else if (c == '\n') {
state = NEWLINE;
} else if (c == '-') {
state = MINUS;
} else if (!isspace(c)) {
op = getop(c);
if (op == NULL) {
state = ERROR;
strcpy(message, "Expected one of +/*");
} else {
if (stackpos < 2) {
state = ERROR;
strcpy(message, "More operands required");
continue;
}
int right = stack[--stackpos];
int left = stack[--stackpos];
if (right == 0 && c == '/') {
state = ERROR;
strcpy(message, "Division by zero");
} else {
stack[stackpos++] = op(left, right);
state = OPERATOR;
}
}
}
} else if (state == OPERATOR) {
if (c == '\n') {
state = NEWLINE;
} else if (isspace(c)) {
state = SPACE;
} else {
strcpy(message, "Expected space or newline after operator");
state = ERROR;
}
}
if (state == NEWLINE) {
if (stackpos > 1) {
state = ERROR;
strcpy(message, "Too many operands");
} else {
if (stackpos == 1) {
printf("result: %d\n", stack[0]);
stackpos = 0;
}
state = START;
}
}
}
if (state == ERROR) {
printf("%s\n", message);
} else if (stackpos > 1) {
printf("Too many operands\n");
} else if (stackpos == 1) {
printf("result: %d\n", stack[0]);
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T08:37:00.370",
"Id": "524614",
"Score": "1",
"body": "Obviously you'd use `<` to take input from a file, rather than pulling out `cat` for that!"
}
] |
[
{
"body": "<p>Here are some things that may help you improve your program.</p>\n<h2>Make sure you have all required <code>#include</code>s</h2>\n<p>The code uses <code>strcpy</code> but doesn't <code>#include <string.h></code>.</p>\n<h2>Use a <code>switch</code> instead of long <code>if ...else</code> chain</h2>\n<p>The parser logic is much easier to see if a <code>switch</code> statement is used instead of the long <code>if...else</code> chain.</p>\n<h2>Consider overflow errors</h2>\n<p>If I enter 12345678901234567890, on my machine the program reports:</p>\n<blockquote>\n<p>result: -350287150</p>\n</blockquote>\n<p>Some detection and warning of this overflow would be helpful to the user. One way to do this is to make sure that, when multiplying by the next digit, that the new number calculated is not less than the old one.</p>\n<h2>Consider handling unary <code>+</code></h2>\n<p>The code handles unary <code>-</code> but, in an odd asymmetry, does not handle unary <code>+</code>. I realize that unsigned numbers are treated as positive (which is certainly the expected and correct behavior) but it sometimes helps when adding a long list of numbers, say, "debits and credits" to be able to indicate which is which with an explicit sign.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T21:24:17.953",
"Id": "524648",
"Score": "0",
"body": "Thanks! Could you elaborate on the switch case usage? Aside from checking the state variable, how can it help avoid the chain? Some of the conditions are not checks against constant expressions, for example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T22:15:31.907",
"Id": "524651",
"Score": "0",
"body": "Only the outermost `if` would be replaced with `case` statements. The others would remain within each `case` for the reasons you mention."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T20:02:24.493",
"Id": "265611",
"ParentId": "265591",
"Score": "1"
}
},
{
"body": "<p><strong>Enable all warnings</strong></p>\n<p>Good compilers will aid in quicker, good code development</p>\n<ul>\n<li>warning: implicit declaration of function 'strcpy' [-Wimplicit-function-declaration]</li>\n<li>warning: incompatible implicit declaration of built-in function 'strcpy'</li>\n<li>warning: conversion from 'int' to 'char' may change value [-Wconversion]</li>\n<li>error: conflicting types for 'div'</li>\n</ul>\n<p><strong>Detecting overflow</strong></p>\n<p><code>add(), mul(), div()</code> could all test arguments and report overflow rather than the <em>undefined behavior</em> of current code. <a href=\"https://codereview.stackexchange.com/a/93699/29485\">Sample code</a></p>\n<p><strong>Extract from <code>main()</code></strong></p>\n<p>Make this nifty parser a stand-alone set of routines and <em>call</em> from <code>main()</code> with a <em>string</em>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T00:01:34.120",
"Id": "265617",
"ParentId": "265591",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T02:21:36.440",
"Id": "265591",
"Score": "5",
"Tags": [
"c",
"calculator"
],
"Title": "Reverse Polish Notation in C (using a Finite State Machine)"
}
|
265591
|
<p>I am making a program about numbers. The user will enter a number and will get its properties.</p>
<h3>Program objectives</h3>
<ol>
<li>Welcome users;</li>
<li>Display the instructions;</li>
<li>Ask for a request;</li>
<li>If a user enters zero, terminate the program;</li>
<li>If numbers are not natural, print the error message;</li>
<li>If an incorrect property is specified, print the error message and
the list of available properties;</li>
<li>For one number, calculate and print the properties of the number;</li>
<li>For two numbers print the list of numbers with their properties;</li>
<li>For two numbers and one property print the numbers with this
property only;</li>
<li>For two numbers and two properties print the numbers that have both properties.</li>
<li>If a user specifies mutually exclusive properties, abort the request and warn a user.</li>
<li>Once a request has been processed, continue execution from step 3</li>
</ol>
<p>The property names include even, odd, buzz, duck, palindromic, gapful, spy, square, and sunny.</p>
<h2>The code</h2>
<pre><code>package numbers;
import java.util.Scanner;
public class Main {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// write your code here
Numbers.welcome();
Numbers.request();
while (true) {
System.out.print("Enter a request: ");
String number = input.nextLine();
String[] numberArray = number.split(" ");
if (numberArray.length == 1) {
if (numberArray[0].equals("0")) {
break;
} else {
System.out.println("The first parameter should be a natural number or zero.");
}
Numbers.getPropertiesOfNumber(number);
}
if (numberArray.length == 2) {
if (Numbers.isNatural(Long.parseLong(numberArray[0]))) {
System.out.println("The first parameter should be a natural number or zero.");
continue;
}
if (Numbers.isNatural(Long.parseLong(numberArray[1]))) {
System.out.println("The second parameter should be a natural number.");
continue;
}
long num1 = Long.parseLong(numberArray[0]);
long num2 = Long.parseLong(numberArray[1]);
for (long i = num1; i < num1 + num2; i++) {
Numbers.getPropertiesOfNumberSequence(i);
System.out.println();
}
}
if (numberArray.length == 3) {
if (Numbers.isNatural(Long.parseLong(numberArray[0]))) {
System.out.println("The first parameter should be a natural number or zero.");
continue;
}
if (Numbers.isNatural(Long.parseLong(numberArray[1]))) {
System.out.println("The second parameter should be a natural number.");
continue;
}
String parameter = numberArray[2];
if (!Numbers.requestList.contains(parameter.toUpperCase())) {
StringBuilder errorOutput = new StringBuilder();
errorOutput.append("The property [").append(parameter.toUpperCase()).append("] is wrong.");
errorOutput.append("\nAvailable properties: [").append(Numbers.requestList + "]");
System.out.println(errorOutput);
} else {
long num1 = Long.parseLong(numberArray[0]);
long num2 = Long.parseLong(numberArray[1]);
Numbers.getPropertiesOfNumberWithParameter(num1, num2, parameter);
}
}
if (numberArray.length == 4) {
if (Numbers.isNatural(Long.parseLong(numberArray[0]))) {
System.out.println("The first parameter should be a natural number or zero.");
continue;
}
if (Numbers.isNatural(Long.parseLong(numberArray[1]))) {
System.out.println("The second parameter should be a natural number.");
} else {
long num1 = Long.parseLong(numberArray[0]);
long num2 = Long.parseLong(numberArray[1]);
String parameter1 = numberArray[2].toLowerCase();
String parameter2 = numberArray[3].toLowerCase();
Numbers.checkParameters(num1, num2, parameter1, parameter2);
}
}
}
System.out.println("Goodbye!");
}
}
class Numbers {
public final static String requestList = "BUZZ, DUCK, PALINDROMIC, GAPFUL, SPY, SQUARE, SUNNY, EVEN, ODD";
public static void request() {
StringBuilder output = new StringBuilder();
output.append("\nSupported requests: ");
output.append("\n- enter a natural number to know its properties;");
output.append("\n- enter two natural numbers to obtain the properties of the list:");
output.append("\n * the first parameter represents a starting number;");
output.append("\n * the second parameters show how many consecutive numbers are to be processed;");
output.append("\n- two natural numbers and a properties to search for;");
output.append("\n- separate the parameters with one space;");
output.append("\n- enter 0 to exit.\n");
System.out.println(output);
}
public static void welcome() {
System.out.println("Welcome to Amazing Numbers!");
}
public static boolean isNatural(long num) {
return num <= 0;
}
public static boolean isEven(long num) {
return num % 2 == 0;
}
public static boolean isOdd(long num) {
return num % 2 != 0;
}
public static boolean isBuzzNumber(long num) {
return num % 7 == 0 || num % 10 == 7;
}
public static boolean isDuckNumber(long num) {
String number = num + "";
return number.contains("0");
}
public static boolean isPalindromicNumber(long num) {
String number = num + "";
for (int i = 0; i < number.length() / 2; i++) {
if (number.charAt(i) != number.charAt(number.length() - i - 1)) {
return false;
}
}
return true;
}
public static boolean isGapfulNumber(long num) {
String number = num + "";
if (number.length() > 2) {
String str = "";
str += number.charAt(0) + "" + number.charAt(number.length() - 1);
return Long.parseLong(number) % Long.parseLong(str) == 0;
}
return false;
}
public static boolean isSpyNumber(long num) {
String number = num + "";
int sum = 0;
int product = 1;
for (int i = 0; i < number.length(); i++) {
int temp = Integer.parseInt(number.charAt(i) + "");
sum += temp;
product *= temp;
}
return sum == product;
}
public static boolean isSquareNumber(long num) {
long sqrt = (long) Math.sqrt(num);
return sqrt * sqrt == num;
}
public static boolean isSunnyNumber(long num) {
return isSquareNumber(num + 1);
}
public static void getPropertiesOfNumber(String number) {
long num = Long.parseLong(number);
StringBuilder output = new StringBuilder();
if (isNatural(num)) {
System.out.println("The first parameter should be a natural number or zero.");
} else {
output.append("Properties of ").append(number);
output.append("\n\t buzz: ").append(isBuzzNumber(num));
output.append("\n\t duck: ").append(isDuckNumber(num));
output.append("\npalindromic: ").append(isPalindromicNumber(num));
output.append("\n\t gapful: ").append(isGapfulNumber(num));
output.append("\n\t\tspy: ").append(isSpyNumber(num));
output.append("\n\t square: ").append(isSquareNumber(num));
output.append("\n\t sunny: ").append(isSunnyNumber(num));
output.append("\n\t even: ").append(isEven(num));
output.append("\n\t\todd: ").append(isOdd(num));
System.out.println(output);
}
}
public static void getPropertiesOfNumberSequence(long i) {
StringBuilder output = new StringBuilder();
output.append(i).append(" is");
if (isBuzzNumber(i)) {
output.append(" buzz");
}
if (isDuckNumber(i)) {
output.append(" duck");
}
if (isPalindromicNumber(i)) {
output.append(" palindromic");
}
if (isGapfulNumber(i)) {
output.append(" gapful");
}
if (isSpyNumber(i)) {
output.append(" spy");
}
if (isSquareNumber(i)) {
output.append(" square");
}
if (isSunnyNumber(i)) {
output.append(" sunny");
}
if (isEven(i)) {
output.append(" even");
}
if (isOdd(i)) {
output.append(" odd");
}
System.out.println(output);
}
public static void getPropertiesOfNumberWithParameter(long num1, long num2, String parameter) {
long i = 1;
parameter = parameter.toLowerCase();
while (i <= num2) {
switch (parameter) {
case "buzz":
if (isBuzzNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "duck":
if (isDuckNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "palindromic":
if (isPalindromicNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "gapful":
if (isGapfulNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "spy":
if (isSpyNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "square":
if (isSquareNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "sunny":
if (isSunnyNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "even":
if (isEven(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "odd":
if (isOdd(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
}
num1++;
}
}
public static void getSeveralProperties(long num1, long num2, String parameter1, String parameter2) {
long i = 1;
parameter1 = parameter1.toLowerCase();
parameter2 = parameter2.toLowerCase();
while (i <= num2) {
switch (parameter1) {
case "buzz":
switch (parameter2) {
case "buzz":
if (isBuzzNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "duck":
if (isBuzzNumber(num1) && isDuckNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "palindromic":
if (isBuzzNumber(num1) && isPalindromicNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "gapful":
if (isBuzzNumber(num1) && isGapfulNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "spy":
if (isBuzzNumber(num1) && isSpyNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "square":
if (isBuzzNumber(num1) && isSquareNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "sunny":
if (isBuzzNumber(num1) && isSunnyNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "even":
if (isBuzzNumber(num1) && isEven(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "odd":
if (isBuzzNumber(num1) && isOdd(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
}
break;
case "duck":
switch (parameter2) {
case "buzz":
if (isBuzzNumber(num1) && isDuckNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "duck":
if (isDuckNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "palindromic":
if (isDuckNumber(num1) && isPalindromicNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "gapful":
if (isDuckNumber(num1) && isGapfulNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "square":
if (isDuckNumber(num1) && isSquareNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "sunny":
if (isDuckNumber(num1) && isSunnyNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "even":
if (isDuckNumber(num1) && isEven(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "odd":
if (isDuckNumber(num1) && isOdd(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
}
break;
case "palindromic":
switch (parameter2) {
case "buzz":
if (isPalindromicNumber(num1) && isBuzzNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "duck":
if (isPalindromicNumber(num1) && isDuckNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "palindromic":
if (isPalindromicNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "gapful":
if (isPalindromicNumber(num1) && isGapfulNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "spy":
if (isPalindromicNumber(num1) && isSpyNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "square":
if (isPalindromicNumber(num1) && isSquareNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "sunny":
if (isPalindromicNumber(num1) && isSunnyNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "even":
if (isPalindromicNumber(num1) && isEven(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "odd":
if (isPalindromicNumber(num1) && isOdd(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
}
break;
case "gapful":
switch (parameter2) {
case "buzz":
if (isGapfulNumber(num1) && isBuzzNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "duck":
if (isGapfulNumber(num1) && isDuckNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "palindromic":
if (isGapfulNumber(num1) && isPalindromicNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "gapful":
if (isGapfulNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "spy":
if (isGapfulNumber(num1) && isSpyNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "square":
if (isGapfulNumber(num1) && isSquareNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "sunny":
if (isGapfulNumber(num1) && isSunnyNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "even":
if (isGapfulNumber(num1) && isEven(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "odd":
if (isGapfulNumber(num1) && isOdd(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
}
break;
case "spy":
switch (parameter2) {
case "buzz":
if (isSpyNumber(num1) && isBuzzNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "palindromic":
if (isSpyNumber(num1) && isPalindromicNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "gapful":
if (isSpyNumber(num1) && isGapfulNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "spy":
if (isSpyNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "square":
if (isSpyNumber(num1) && isSquareNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "sunny":
if (isSpyNumber(num1) && isSunnyNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "even":
if (isSpyNumber(num1) && isEven(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "odd":
if (isSpyNumber(num1) && isOdd(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
}
break;
case "square":
switch (parameter2) {
case "buzz":
if (isSquareNumber(num1) && isBuzzNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "duck":
if (isSquareNumber(num1) && isDuckNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "palindromic":
if (isSquareNumber(num1) && isPalindromicNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "gapful":
if (isSquareNumber(num1) && isGapfulNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "spy":
if (isSquareNumber(num1) && isSpyNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "square":
if (isSquareNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "even":
if (isSquareNumber(num1) && isEven(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "odd":
if (isSquareNumber(num1) && isOdd(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
}
break;
case "sunny":
switch (parameter2) {
case "buzz":
if (isSunnyNumber(num1) && isBuzzNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "duck":
if (isSunnyNumber(num1) && isDuckNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "palindromic":
if (isSunnyNumber(num1) && isPalindromicNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "gapful":
if (isSunnyNumber(num1) && isGapfulNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "spy":
if (isSunnyNumber(num1) && isSpyNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "sunny":
if (isSunnyNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "even":
if (isSunnyNumber(num1) && isEven(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "odd":
if (isSunnyNumber(num1) && isOdd(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
}
break;
case "even":
switch (parameter2) {
case "buzz":
if (isEven(num1) && isBuzzNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "duck":
if (isEven(num1) && isDuckNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "palindromic":
if (isEven(num1) && isPalindromicNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "gapful":
if (isEven(num1) && isGapfulNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "spy":
if (isEven(num1) && isSpyNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "square":
if (isEven(num1) && isSquareNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "sunny":
if (isEven(num1) && isSunnyNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "even":
if (isEven(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
}
break;
case "odd":
switch (parameter2) {
case "buzz":
if (isOdd(num1) && isBuzzNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "duck":
if (isOdd(num1) && isDuckNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "palindromic":
if (isOdd(num1) && isPalindromicNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "gapful":
if (isOdd(num1) && isGapfulNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "spy":
if (isOdd(num1) && isSpyNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "square":
if (isOdd(num1) && isSquareNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "sunny":
if (isOdd(num1) && isSunnyNumber(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
case "odd":
if (isOdd(num1)) {
getPropertiesOfNumberSequence(num1);
i++;
}
break;
}
break;
}
num1++;
}
}
public static void mutuallyExclusiveError(String parameter1, String parameter2) {
System.out.println("The request contains mutually exclusive properties: [" +
parameter1.toUpperCase() + ", " + parameter2.toUpperCase() + "]\n" +
"There are no numbers with these properties.");
}
public static boolean isMutuallyExclusive(String parameter1, String parameter2) {
String[] mutualParameters1 = new String[]{"even odd", "spy duck", "sunny square"};
String[] mutualParameters2 = new String[]{"odd even", "duck spy", "square sunny"};
String parameter = parameter1 + " " + parameter2;
for (int i = 0; i < mutualParameters1.length; i++) {
if (parameter.equals(mutualParameters1[i]) || parameter.equals(mutualParameters2[i])) {
return true;
}
}
return false;
}
public static boolean checkParameter(String parameter) {
String[] parameters = requestList.split(", ");
for (String s : parameters) {
if (parameter.equalsIgnoreCase(s)) {
return false;
}
}
return true;
}
public static void checkParameters(long num1, long num2, String parameter1, String parameter2) {
if (isMutuallyExclusive(parameter1, parameter2)) {
mutuallyExclusiveError(parameter1, parameter2);
} else if (checkParameter(parameter1) && checkParameter(parameter2)) {
System.out.println("The properties [" + parameter1.toUpperCase() + ","
+ parameter2.toUpperCase() + "] are wrong.\n" +
"Available properties: " + "[" + requestList + "]");
} else if (checkParameter(parameter1)) {
System.out.println("The property [" + parameter1.toUpperCase() + "] is wrong.\n" +
"Available properties: [" + requestList + "]");
} else if (checkParameter(parameter2)) {
System.out.println("The property [" + parameter2.toUpperCase() + "] is wrong.\n" +
"Available properties: [" + requestList + "]");
} else {
getSeveralProperties(num1, num2, parameter1, parameter2);
}
}
}
</code></pre>
<p>This code works fine.</p>
<p>But I feel I have messed up with this code. E.g. in the <code>getSeveralProperties()</code> method, I have used <code>switch</code> inside <code>switch</code>, and my code became duplicated, not DRY. And there are many more examples. Especially with the get...() methods.</p>
|
[] |
[
{
"body": "<p>As far as I can understand, you're a beginner lacking some knowledge. But the job is done well. Some considerations:</p>\n<h3>Comments</h3>\n<p>A perfect code should use identifier names to avoid comments; your code have good names and one unneeded comment at the beginning. But, on the other hand, you have good task description for comments. You can break it into comments, so anyone could find every part of the task in the code.</p>\n<h3>Use different classes for different tasks</h3>\n<p>Your <code>Numbers</code> class does 2 things: output and calculations. In a bigger project, you should break this functionality into several classes.</p>\n<h3>Use <code>else</code> if <code>if</code>'s are mutually exclusive, and <code>switch</code> if you check one value</h3>\n<pre><code>if(numberArray.length == 1)\n...\nelse if(numberArray.length == 2)\n...\n</code></pre>\n<p>or even</p>\n<pre><code>switch(numberArray.length)\n case 1:\n ....\n</code></pre>\n<h3><code>requestList</code> should be an array</h3>\n<p>So you shouldn't split it every time. Also, constants are usually named in FULL_UPPER_CASE.</p>\n<h3>Turn <code>while</code>s with known boundaries into <code>for</code>s</h3>\n<pre><code>long i = 1;\n...\nwhile (i <= num2) \n{\n ....\n i++;// in every branch\n}\n</code></pre>\n<p>is just</p>\n<pre><code>for(long i=1; i<=num2; i++)\n</code></pre>\n<h3>Now to your problem</h3>\n<p>First, AFAIS, <code>i++</code> happens in all branches - so you can move it out if switch and do once, before or after.\nSecond, I presume you don't know flag technique, Maps and method references. Still, you can DRY the code. Imagine you've had a method in <code>Numbers</code>:</p>\n<pre><code>public static boolean hasNumberProperty(long number, String property)\n</code></pre>\n<p>so <code>hasNumberProperty(10, 'buzz')</code> would call and return <code>isBuzzNumber(10)</code>. You see the point, right? All the <code>switch</code>es are moved into one small <code>switch</code>, inside this <code>hasNumberProperty</code>. All the big switch-in-switch statement turns into</p>\n<pre><code>if(hasNumberProperty(number1, parameter1) and hasNumberProperty(number2, parameter2))\n{\n getPropertiesOfNumberSequence(num1);\n}\ni++;\n</code></pre>\n<h3>Some more code cleaning</h3>\n<p>In <code>checkParameters</code>, <code>checkParameter</code> is called several times with same arguments. This work is redundant, so I'll show you the very secret flag technique:</p>\n<pre><code>int parameter1Ok = 0;\nif(checkParameter(parameter1))\n parameter1Ok = 1;\n/*the same for parameter 2*/\n...\nif(parameter1Ok==1 and parameter2Ok==1)\n...\nelse if(parameter1Ok)\n</code></pre>\n<p>Flags (variables parameter1Ok and parameter2Ok) allow you to save the sign of some property and check it afterwards, without recalculating. Boolean flags are much more common - try to change this code into boolean flags, you will see, why.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T13:32:51.353",
"Id": "265598",
"ParentId": "265592",
"Score": "1"
}
},
{
"body": "<blockquote>\n<p>E.g. in the <code>getSeveralProperties()</code> method, I have used switch inside switch, and my code became duplicated, not DRY.</p>\n</blockquote>\n<p>You can fix this by creating a <code>Property</code> interface with implementations for even, sunny, etc. Then, rather than using nested switches, you could simply say</p>\n<pre><code>for (long i = 1; i < top; i++) {\n if (Numbers.holdsAll(number, properties)) {\n getPropertiesOfNumberSequence(number);\n }\n}\n</code></pre>\n<p>I also renamed <code>num1</code> to <code>number</code> and <code>num2</code> to <code>top</code> as being more descriptive. I changed from two properties to an arbitrary sized collection. This will also allow you to combine the single case with the pair case as well as allow for future expansion.</p>\n<pre><code>public static boolean holdsAll(long number, Iterable<Property> properties) {\n foreach (Property property : properties) {\n if (!property.isHeldBy(number)) {\n return false;\n }\n }\n\n return true;\n}\n</code></pre>\n<p>Note that while I call this an <code>Iterable</code> here, I would probably implement it as an <code>ArrayList</code> when initialized. But the only thing that is required is that it be some form of <code>Iterable</code> so that the <code>foreach</code> works.</p>\n<p>An implementation would look like</p>\n<pre><code>class Even implements Property {\n\n public function isHeldBy(long number) {\n return number % 2 == 0;\n }\n\n}\n</code></pre>\n<p>Some time before calling <code>getSeveralProperties</code>, you would have to convert the strings to the properties, but that would be much simpler and would only need done once. Something like</p>\n<pre><code>public convertParameterToProperty(String parameter) {\n switch (parameter) {\n case "even":\n return new Even();\n</code></pre>\n<p>Obviously with cases for each type. Or</p>\n<pre><code>private static final Map<String, Property> PROPERTY_DICTIONARY = new HashMap<>();\n\nstatic {\n PROPERTY_DICTIONARY.put("even", new Even());\n</code></pre>\n<p>(again entries for each type) with</p>\n<pre><code>public static Property convertParameterToProperty(String parameter) {\n return PROPERTY_DICTIONARY.get(parameter);\n}\n</code></pre>\n<p>Another alternative would be to do the same thing with an <code>enum</code> where each value defines its own <code>isHeldBy</code> method.</p>\n<p>These approaches would be much DRYer than what you have now. I.e. my code observation is that you can replace nested switches with either interface implementations or an <code>enum</code> to DRY the code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T19:41:12.943",
"Id": "265642",
"ParentId": "265592",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "265598",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T05:33:02.353",
"Id": "265592",
"Score": "3",
"Tags": [
"java"
],
"Title": "Determine number properties"
}
|
265592
|
<p>I am trying to time <a href="https://en.wikipedia.org/wiki/Radix_sort" rel="nofollow noreferrer">radix sort</a> on 128 bit unsigned integers for different base sizes (that I call bitwidth). My code has at least the following problems:</p>
<ul>
<li>The radix sort itself may run slower than it would otherwise as the bit
width, number of passes etc are not constants that the compiler can
understand and also maybe the use of variable length arrays.</li>
<li>I use variable length arrays. It might be better without those</li>
<li>It doesn't work (crashes due to stack overflow) for bitwidth > 18.</li>
</ul>
<p>Here is the code:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
#include <time.h>
#include <string.h>
#include <time.h>
#include <sys/sysinfo.h>
#define LENGTH 1000000
void print128(__uint128_t u) {
if (u>9) print128(u/10);
putchar(48+(int)(u%10));
}
// 2^(bitwidth) == count_size for counting sort. 16 is 128/bitwidth == num_passes (number of radix sort passes)
typedef __uint128_t u128;
typedef uint32_t u32;
u128* radix_sort128(u128* array, u32 size, u32 count_size, u32 num_passes, u32 bitwidth) {
u32 counts[num_passes][count_size];
memset(&counts, 0, count_size * num_passes * sizeof(u32));
u128* cpy = (u128*) malloc(size * sizeof(u128));
u32 o[num_passes];
memset(o, 0, sizeof o);
// u32 o[num_passes] = {0};
u32 t, x, pos;
u128* array_from, * array_to;
for (x = 0; x < size; x++) {
for (pos = 0; pos < num_passes; pos++) {
t = (array[x] >> bitwidth * pos) % count_size;
counts[pos][t]++;
}
}
for (x = 0; x < count_size; x++) {
for (pos = 0; pos < num_passes; pos++) {
t = o[pos] + counts[pos][x];
counts[pos][x] = o[pos];
o[pos] = t;
}
}
for (pos = 0; pos < num_passes; pos++) {
array_from = pos % 2 == 0 ? array : cpy;
array_to = pos % 2 == 0 ? cpy : array;
for (x = 0; x < size; x++) {
t = (array_from[x] >> bitwidth * pos) & 0xff;
array_to[counts[pos][t]] = array_from[x];
counts[pos][t]++;
}
}
free(cpy);
return array;
}
uint64_t wyhash64_x;
uint64_t wyhash64() {
wyhash64_x += 0x60bee2bee120fc15;
__uint128_t tmp;
tmp = (__uint128_t) wyhash64_x * 0xa3b195354a39b70d;
uint64_t m1 = (tmp >> 64) ^ tmp;
tmp = (__uint128_t)m1 * 0x1b03738712fad5c9;
uint64_t m2 = (tmp >> 64) ^ tmp;
return m2;
}
int main() {
u128* vals128 = malloc(LENGTH * sizeof(*vals128));
u128 lower;
u128 higher;
struct timespec start, end;
// make an array of random u128s
for (int i = 0; i < LENGTH; i++) {
lower = (u128) wyhash64();
higher = (u128) wyhash64();
higher = higher << 64;
vals128[i] = lower + higher;
}
for (u32 bitwidth = 8; bitwidth < 20; bitwidth+=2){
u32 num_passes = 128/bitwidth;
u32 count_size = 1 << bitwidth;
printf("bitwidth %d num_passes %d count_size %d\n", bitwidth, num_passes, count_size);
clock_gettime(CLOCK_MONOTONIC, &start);
radix_sort128(vals128, LENGTH, count_size, num_passes, bitwidth);
clock_gettime(CLOCK_MONOTONIC, &end);
printf("%f seconds\n", (end.tv_sec - start.tv_sec) + (end.tv_nsec - start.tv_nsec) / 1000000000.0);
}
free(vals128);
}
</code></pre>
<p>Any improvements gratefully received.</p>
<p><strong>Edit</strong></p>
<p>Corrected bug. <code>& 0xff</code> is now <code>% count_size</code>.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T09:24:03.260",
"Id": "524615",
"Score": "1",
"body": "The problem is the 0xff. That needs fixing"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T13:52:30.573",
"Id": "524628",
"Score": "0",
"body": "Hi, you can refer to this https://codereview.stackexchange.com/q/216460/190450. The code is in c++. But you can go through it as a reference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T08:21:16.047",
"Id": "524669",
"Score": "1",
"body": "num_passes is wrong unless 128 is divisible by bitwidth. You need to round up."
}
] |
[
{
"body": "<p>There's an opaque magic number here, that reduces portability:</p>\n<blockquote>\n<pre><code> putchar(48+(int)(u%10));\n</code></pre>\n</blockquote>\n<p>I think that was intended to be <code>'0'</code>, and we unnecessarily created an ASCII-only program.</p>\n<p>This function might be better if it works in larger chunks, and recursed less:</p>\n<pre><code>void print128(__uint128_t u) {\n static const uint64_t ten18 = 10000000000000000000u;\n if (u < ten18) {\n printf("%" PRIu64, (uint64_t)u);\n } else {\n print128(u/ten18);\n printf("%018" PRIu64, (uint64_t)(u % ten18));\n }\n}\n</code></pre>\n<hr />\n<blockquote>\n<pre><code> u128* cpy = (u128*) malloc(size * sizeof(u128));\n</code></pre>\n</blockquote>\n<p>Don't cast the return from <code>malloc()</code> - it's a <code>void*</code>, which is convertible to any pointer type in C. And it's good practice to refer the size directly to the variable being initialised, rather than to its type - that makes it easier for the reader to see correctness without having to find the declaration, which may be further away. Another good habit is to multiply beginning with the <code>size_t</code> quantity, which can avoid overflow when there are more terms in the product.</p>\n<pre><code> u128* cpy = malloc(sizeof *cpy * size);\n</code></pre>\n<p>Whatever we do, we <strong>must not</strong> dereference that pointer until we know it's not a null pointer.</p>\n<pre><code> if (!cpy) {\n return NULL;\n }\n</code></pre>\n<hr />\n<blockquote>\n<pre><code>uint64_t wyhash64()\n</code></pre>\n</blockquote>\n<p>This function declaration should be a prototype (as should <code>main()</code>):</p>\n<pre><code>uint64_t wyhash64(void)\n</code></pre>\n<p>There's no need for <code>wyhash64_x</code> to have global scope - it would be better as a <code>static</code> local within the function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T14:33:32.933",
"Id": "524632",
"Score": "0",
"body": "On linux at least, I am not sure malloc ever returns NULL . See https://stackoverflow.com/questions/16674370/why-does-malloc-or-new-never-return-null"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T14:36:18.947",
"Id": "524633",
"Score": "1",
"body": "It certainly does when you hit your `ulimit -v` value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T14:38:57.477",
"Id": "524634",
"Score": "0",
"body": "That is true. It looks like the code as written is actually incorrect because of the 0xFF. Would you be able to add a correction to your great answer? That is it doesn't work for bitwidth other than 8. I think the mask just has to be change to count-size - 1 ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T14:44:53.907",
"Id": "524635",
"Score": "1",
"body": "It's probably better for you to add an answer of your own to explain that (and will help you build reputation here). (We like having multiple different answers here on Code Review.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T11:02:58.437",
"Id": "524675",
"Score": "0",
"body": "As I mention in a comment above, there seems to be a fatal bug in any case"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T13:28:21.450",
"Id": "524685",
"Score": "0",
"body": "@TobySpeight OK, LSNED. I suspect my C++ side of the brain had confused my C side."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T14:29:46.620",
"Id": "524688",
"Score": "0",
"body": "Yes, one of the ways in which C++ isn't \"just like C\"."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T08:35:55.433",
"Id": "265595",
"ParentId": "265593",
"Score": "6"
}
},
{
"body": "<p>Not much left after @Toby Speight review.</p>\n<p><strong>Bug?</strong></p>\n<p>Code has a mysterious <code>& 0xff</code>. Perhaps <code>% count_size</code>?</p>\n<pre><code>u32 counts[num_passes][count_size];\n...\n// t = (array[x] >> bitwidth * pos) & 0xff;\nt = (array[x] >> bitwidth * pos) % count_size;\ncounts[pos][t]++;\n</code></pre>\n<p><strong>Minor bug</strong></p>\n<p>Assuming <code>int</code> is 32-bit`.</p>\n<p>When <code>int</code> is 16-bit, <code>1 << bitwidth</code> shifts outside <code>int</code> range.</p>\n<pre><code>// u32 count_size = 1 << bitwidth;\nu32 count_size = ((u32)1) << bitwidth; // or the like.\n</code></pre>\n<p><code>for</code> loop like-wise fails. As <code>i</code> is used to index arrays, recommend <code>size_t</code>.</p>\n<pre><code>#define LENGTH 1000000\n// for (int i = 0; i < LENGTH; i++) { \nfor (size_t i = 0; i < LENGTH; i++) { \n</code></pre>\n<p><strong>Multiplication order for size</strong></p>\n<p>Rather than assume 32-bit for <code>size_t</code>, (e.g. it may be 64-bit), perform the size multiplication starting with <code>size_t</code> to take advantage where a wide <code>size_t</code> may prevent overflow of <code>u32 * u32</code>. (I now see Toby mentioned part of this.)</p>\n<pre><code>... u32 count_size, u32 num_passes ...\n// u32 counts[num_passes][count_size];\n// memset(&counts, 0, count_size * num_passes * sizeof(u32));\n// ^---------------------^ may overflow 32 bit math \nmemset(&counts, 0, sizeof(u32) * count_size * num_passes);\n ^----------------------^ Math done using wider of size_t, u32\n</code></pre>\n<p>Even simpler, just use the size of the array.</p>\n<pre><code>// memset(&counts, 0, count_size * num_passes * sizeof(u32));\nmemset(&counts, 0, sizeof counts);\n</code></pre>\n<p><strong><code>u32</code> vs <code>uint32_t</code></strong></p>\n<p>Rather than a user/implementation defined fixed width type, consider using the standard one.</p>\n<p>To know if <code>u32</code> code is correct obliges a look-up of <code>u32</code> definition.</p>\n<p><strong>Superfluous casts</strong></p>\n<p>Not needed with up conversions.</p>\n<pre><code>//lower = (u128) wyhash64();\n// higher = (u128) wyhash64();\nlower = wyhash64();\nhigher = wyhash64();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T22:33:28.217",
"Id": "524652",
"Score": "1",
"body": "And If you do both `malloc()` and `memset()`, use `calloc()` instead, and you don't have to worry about those sizes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T23:39:49.753",
"Id": "524654",
"Score": "2",
"body": "@G.Sliepen Sounds like a good idea, perhaps post that, even if it is only a small review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T06:33:14.123",
"Id": "524658",
"Score": "0",
"body": "Will % count_size be as fast as & (count_size - 1)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T07:29:33.267",
"Id": "524661",
"Score": "0",
"body": "Can you also see how to fix “ It doesn't work (crashes due to stack overflow) for bitwidth > 18.”?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T08:22:01.290",
"Id": "524670",
"Score": "0",
"body": "There is another bug it seems. I don't think num_passes is correct if 128 is not divisible by bitwidth,"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T12:58:07.180",
"Id": "524676",
"Score": "0",
"body": "@Anush \"Will % count_size be as fast as & (count_size - 1)?\" --> maybe the same, maybe slower, maybe different on your machine vs mine. [Is premature optimization really the root of all evil?](https://softwareengineering.stackexchange.com/questions/80084/is-premature-optimization-really-the-root-of-all-evil)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T13:01:49.010",
"Id": "524677",
"Score": "0",
"body": "@Anush \"I don't think num_passes is correct if 128 is not divisible by bitwidth\" --> Likely true. Rather than worry about [small performance issues](https://codereview.stackexchange.com/questions/265593/radix-sort-with-benchmarks/265612?noredirect=1#comment524658_265612), make functionally correct for lots of different inputs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T13:08:28.840",
"Id": "524680",
"Score": "0",
"body": "@Anush \"It doesn't work (crashes due to stack overflow) for bitwidth > 18\" --> `for (u32 bitwidth = 8; bitwidth < 20; bitwidth+=2){` is a first place to look as code has an artifical limit here. `bitwidth` , once reaching more than 18, exits the loops and calls `free()`. I think your \"It\" in \"It doesn't work\" is referring to some other unposted variation on this code."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T21:10:22.730",
"Id": "265612",
"ParentId": "265593",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T07:26:18.400",
"Id": "265593",
"Score": "4",
"Tags": [
"c",
"benchmarking",
"radix-sort"
],
"Title": "Radix sort with benchmarks"
}
|
265593
|
<h3>Background</h3>
<p>I'm interested in implementing a small script to display multiple independent instances of a Canvas-based control on one page. The ultimate intention is to add many similar controls to the same page, so efficiency is helpful.</p>
<h3>Inspiration Code</h3>
<p>Here is the <a href="https://github.com/andrepxx/pure-knob" rel="nofollow noreferrer">original source code</a> that I'm working from that creates a Canvas-based UI control (additional <a href="https://github.com/andrepxx/pure-knob/blob/master/pureknob.js" rel="nofollow noreferrer">pureknob.js code</a> omitted here for brevity). This code block creates a single UI control. (The inspiration code isn't mine and I'm not seeking advice on how to improve it.)</p>
<blockquote>
<pre><code>// Create knob element, 300 x 300 px in size.
const knob = pureknob.createKnob(300, 300);
// Set properties.
knob.setProperty('angleStart', -0.75 * Math.PI);
knob.setProperty('angleEnd', 0.75 * Math.PI);
knob.setProperty('colorFG', '#88ff88');
knob.setProperty('trackWidth', 0.4);
knob.setProperty('valMin', 0);
knob.setProperty('valMax', 100);
// Set initial value.
knob.setValue(50);
/*
* Event listener.
*
* Parameter 'knob' is the knob object which was
* actuated. Allows you to associate data with
* it to discern which of your knobs was actuated.
*
* Parameter 'value' is the value which was set
* by the user.
*/
const listener = function(knob, value) {
console.log(value);
};
knob.addListener(listener);
// Create element node.
const node = knob.node();
// Add it to the DOM.
const elem = document.getElementById('some_element');
elem.appendChild(node);
</code></pre>
</blockquote>
<h4>HTML:</h4>
<p>The following snippet is used to display the controls (through a Django server, if that's relevant).</p>
<pre class="lang-html prettyprint-override"><code>...
<td style="width:150px; text-align: center;">
<span id="some_element_1"></span>
</td>
<td style="width:150px; text-align: center;">
<span id="some_element_2"></span>
</td>
...
</code></pre>
<h3>Generating Multiple Controls</h3>
<p>I'm able to produce multiple UI objects by simply duplicating every element of the script, i.e.,</p>
<pre class="lang-javascript prettyprint-override"><code>const knob1 = pureknob.createKnob(300, 300);
const knob2 = pureknob.createKnob(300, 300);
...
knob1.setProperty('angleStart', -0.75 * Math.PI);
knob2.setProperty('angleStart', -0.75 * Math.PI);
</code></pre>
<p>which works, but obviously isn't DRY.</p>
<h4>Output: Example of Multiple Control Objects</h4>
<p><a href="https://i.stack.imgur.com/qbHbu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qbHbu.png" alt="Example of Multiple Control Objects" /></a></p>
<h3>Code to Produce Multiple Independent Canvas Objects</h3>
<p>Therefore, I've chosen to create a list of objects and iterate over them. Is there a more efficient or safer way to create multiple control object instances?</p>
<pre class="lang-javascript prettyprint-override"><code><script type="text/javascript">
// <![CDATA[
let i = 0;
// Create knob elements, 100 x 100 px in size.
const knob1 = pureknob.createKnob(100, 100);
const knob2 = pureknob.createKnob(100, 100);
const knobs = [knob1, knob2];
knobs.forEach(demoKnob)
/*
* Demo code for knob element.
*/
function demoKnob(k) {
++i
// Set properties.
k.setProperty('angleStart', -0.75 * Math.PI);
k.setProperty('angleEnd', 0.75 * Math.PI);
k.setProperty('colorFG', '#245166');
k.setProperty('trackWidth', 0.4);
k.setProperty('valMin', 0);
k.setProperty('valMax', 100);
// Set initial value.
k.setValue(40);
/*
* Event listener.
*
* Parameter 'knob' is the knob object which was
* actuated. Allows you to associate data with
* it to discern which of your knobs was actuated.
*
* Parameter 'value' is the value which was set
* by the user.
*/
let listener = function(k, value) {
console.log(value);
};
k.addListener(listener);
// Create element node.
let node = k.node();
// Add it to the DOM.
document.getElementById('some_element_' + String(i)).appendChild(node);
}
/*
* This is executed after the document finished loading.
*/
function ready() {
demoKnob();
}
document.addEventListener('DOMContentLoaded', ready, false);
// ]]>
</script>
</code></pre>
|
[] |
[
{
"body": "<h2>Review</h2>\n<p>There are bugs and the code is accessibly noisy.</p>\n<h2>Style</h2>\n<p>Some source code style points</p>\n<ul>\n<li><p>Avoid unneeded code as it is just noise. Code noise makes code harder to read amd maintain.</p>\n<ul>\n<li><p>The script tag default type is <code>"text/javascript"</code> and thus is not required.</p>\n</li>\n<li><p>JavaScript does type conversion automatically. Thus <code>'some_element_' + String(i)</code> is the same as <code>'some_element_' + i</code></p>\n</li>\n<li><p>The function <code>listener</code> does nothing but log to the console. This is debug/development code and should not be in release code (You may not be aware but Code Review question are considered to be release code)</p>\n</li>\n<li><p>Avoid redirection functions (Functions that only call another function). Eg you have the event listener <code>ready</code> that just calls <code>demoKnob</code></p>\n</li>\n<li><p>Avoid single use variables when they do not improve readability. EG shorten very long lines, reduces complex statement clauses.</p>\n</li>\n<li><p>Comments are just noise, good code does not need comments.</p>\n</li>\n</ul>\n</li>\n<li><p>There are some poor and inappropriate variable names</p>\n<ul>\n<li><p>Avoid naming a variable in global scope <code>i</code>,<code>j</code>,or <code>k</code>. In this case <code>i</code> can be <code>idCount</code>, or not needed at all as you can get the id from the iterating callback's second argument.</p>\n</li>\n<li><p>Take care to correctly capitalize <code>camelCase</code> names. <code>pureknob</code> should be <code>pureKnob</code></p>\n</li>\n<li><p><code>listener</code> is a very poor function name. Yes it is a listener but that gives no clue as to what it does.</p>\n</li>\n</ul>\n</li>\n</ul>\n<h2>BUG!</h2>\n<p>The <code>DOMContentLoaded</code> will cause a error to be thrown as when it indirectly calls <code>demoKnob</code> there are no arguments passed. I do not understand why you have the listener there? As I see it it is not required, all the setup has already beeen executed before you add the listener.</p>\n<h2>Question</h2>\n<p>You ask...</p>\n<blockquote>\n<p><em>"Is there a more efficient or safer way to create multiple control object instances?"</em></p>\n</blockquote>\n<p>From your point of view and apart from the points above and considering that there is some information missing the answer is No and No.</p>\n<p>That said (and I have not looked at any of the 3rd party code as we only review the OP's code) the use of the property <code>Knob.colorFG</code> indicates that the object is very old school in its design and as such may not be optimal for what it does.</p>\n<p>The best way to know if it is efficient is to test it.</p>\n<ul>\n<li>Degradation limit: How many can you add to a page before it degrades the page's performance metrics?</li>\n<li>Are you planing on using significantly less than the degradation limit?</li>\n</ul>\n<p>If you answer yes to the second then its safe to use. However do keep an eye out for more efficient components.</p>\n<h2>Rewrite</h2>\n<p>Removes noise and buggy code.\nMoves default properties to a constant for easier maintenance and readability.</p>\n<pre><code><script>\n const KNOB_DEFAULTS = {\n angleStart: -0.75 * Math.PI,\n angleEnd: 0.75 * Math.PI,\n colorFG: '#245166',\n trackWidth: 0.4,\n valMin: 0,\n valMax: 100,\n value: 40,\n };\n [pureknob.createKnob(100, 100), pureknob.createKnob(100, 100)].forEach(demoKnob);\n\n function demoKnob(knob, i) {\n for (const [name, val] of Object.entries(KNOB_DEFAULTS)) { knob.setProperty(name, val) }\n document.getElementById('some_element_' + (i + 1)).appendChild(knob.node());\n }\n</script>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T01:17:23.623",
"Id": "524656",
"Score": "0",
"body": "Thank you for a thorough and thoughtful review. I will definitely apply your elegant revisions. As an amateur, I clearly have much to learn. My initial concerns revolved around efficient iteration. While, I can't answer a number of your questions regarding design decision-making--as those choices were made by the original author of the inspiration code I'm using--my decisions were inspired by other languages I'm more familiar with. I'm aware that code for review should be considered final and that was my intention. Cheers!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T00:49:22.293",
"Id": "265618",
"ParentId": "265599",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "265618",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T14:11:49.677",
"Id": "265599",
"Score": "2",
"Tags": [
"javascript",
"beginner",
"canvas"
],
"Title": "Generate Multiple Instances of Canvas-based UI Object"
}
|
265599
|
<p>As a C++ newbie, I am practicing my C++ skill by implement games in <a href="https://www.atariarchives.org/basicgames/" rel="nofollow noreferrer">BASIC Computer Games</a> and here is my C++ version for <a href="https://www.atariarchives.org/basicgames/showpage.php?page=15" rel="nofollow noreferrer">Battle</a>.</p>
<h3>Suggestions I want</h3>
<p>Any suggestion are welcome!</p>
<p>Current Project code from my work place full of C styles in C++ (which is not a good thing), I want my code to be C++ style, and to be more C++11 or modern C++ style. And I was a Python coder, I am still not know well about things in C++ like <code>static</code>, <code>pointer</code> and so on.</p>
<h3>About My Code</h3>
<p>In my Battle implementation, I hard code the game map part, I don't have a good idea about this still XD. So let's skip it first, that is my <code>TODO</code></p>
<pre><code>void InitMap()
{
// TODO: random map algorithm
m_gameMap = {
{0,0,0,2,2,6},
{0,4,4,4,6,0},
{5,0,0,6,0,0},
{5,0,6,0,0,3},
{5,1,0,0,0,3},
{5,0,1,0,0,3},
};
}
</code></pre>
<p>Game is simple, user input a coordinate to hit, and then tell the user result.</p>
<p>When a ship is down(all coordinates about this one are hit), tell the user whole situation about game right now.</p>
<pre><code>if (iAttack > 0) {
std::cout << "A Direction Hit On Ship Number " << iAttack << std::endl;
if (!game.IsShipStillSurvive(iAttack)) {
std::cout << "And you sunk it. Hurrah for the good guys." << std::endl;
std::cout << "So far the bad gut have lost" << std::endl;
game.ShipLost(iDestroyerLost, iCruisersLost, iAircraftLost);
std::cout << iDestroyerLost << " Destroyer(s), " << iCruisersLost;
std::cout << " Cruiser(s), And " << iAircraftLost << " Aircraft Carrier(s)." << std::endl;
}
} else {
std::cout << "Splash!" << std::endl;
}
</code></pre>
<h3>Code</h3>
<pre><code>#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <sstream>
typedef enum {
SHIP_TYPE_DESTROYER,
SHIP_TYPE_CRUISERS,
SHIP_TYPE_AIRCRAFT,
} ShipType;
typedef unsigned int ShipNumber ;
struct Coordinate {
unsigned int x;
unsigned int y;
};
class Game
{
public:
Game()
{
m_shipLiveInfo.clear();
for (auto iter = m_shipNumberInfo.begin(); iter != m_shipNumberInfo.end(); ++iter) {
unsigned int iLive = 0;
auto fleetIter = m_shipFleetInfo.find(iter->second);
if (fleetIter != m_shipFleetInfo.end()) {
iLive = fleetIter->second;
}
m_shipLiveInfo.insert(std::pair<ShipNumber, unsigned int>(iter->first, iLive));
}
InitMap();
}
virtual ~Game() {}
void Attack(const Coordinate& coordinate, ShipNumber& iAttackShip)
{
iAttackShip = 0;
if (coordinate.x <= m_iMapWidth && coordinate.y <= m_iMapHeight && coordinate.x > 0 && coordinate.y > 0) {
iAttackShip = m_gameMap[coordinate.x - 1][coordinate.y - 1];
std::cout << "Attack " << iAttackShip << std::endl;
m_gameMap[coordinate.x - 1][coordinate.y - 1] = 0;
auto iter = m_shipLiveInfo.find(iAttackShip);
if (iter != m_shipLiveInfo.end()) {
--(iter->second);
}
}
}
bool IsShipStillSurvive(ShipNumber& iShip)
{
std::map<ShipNumber, unsigned int>::iterator iter = m_shipLiveInfo.find(iShip);
if (iter == m_shipLiveInfo.end()) {
return true;
}
return (iter->second > 0);
}
bool IsGameOver()
{
for (auto iter = m_shipLiveInfo.begin(); iter != m_shipLiveInfo.end(); ++iter) {
if (iter->second > 0) {
return false;
}
}
return true;
}
void ShipLost(unsigned int& iDestroyer, unsigned int& iCruisers, unsigned int& iAircraft)
{
for (auto iter = m_shipLiveInfo.begin(); iter != m_shipLiveInfo.end(); ++iter) {
auto shipIter = m_shipNumberInfo.find(iter->first);
if (shipIter == m_shipNumberInfo.end()) {
continue;
}
ShipType shipType = shipIter->second;
if (iter->second == 0) {
switch (shipType) {
case SHIP_TYPE_DESTROYER:
++iDestroyer;
break;
case SHIP_TYPE_CRUISERS:
++iCruisers;
break;
case SHIP_TYPE_AIRCRAFT:
++iAircraft;
break;
}
}
}
}
static const unsigned int m_iMapWidth = 6;
static const unsigned int m_iMapHeight = 6;
private:
std::vector<std::vector<ShipNumber>> m_gameMap;
std::map<ShipNumber, unsigned int> m_shipLiveInfo;
static const std::map<ShipType, unsigned int> m_shipFleetInfo;
static const std::map<unsigned int, ShipType> m_shipNumberInfo;
void InitMap()
{
// TODO: random map algorithm
m_gameMap = {
{0,0,0,2,2,6},
{0,4,4,4,6,0},
{5,0,0,6,0,0},
{5,0,6,0,0,3},
{5,1,0,0,0,3},
{5,0,1,0,0,3},
};
}
};
const std::map<ShipNumber, ShipType> Game::m_shipNumberInfo = {
{1, SHIP_TYPE_DESTROYER},
{2, SHIP_TYPE_DESTROYER},
{3, SHIP_TYPE_CRUISERS},
{4, SHIP_TYPE_CRUISERS},
{5, SHIP_TYPE_AIRCRAFT},
{6, SHIP_TYPE_AIRCRAFT},
};
const std::map<ShipType, unsigned int> Game::m_shipFleetInfo = {
{SHIP_TYPE_DESTROYER, 2},
{SHIP_TYPE_CRUISERS, 3},
{SHIP_TYPE_AIRCRAFT, 4}
};
int main(int argc, char** argv)
{
Game game = Game();
Coordinate cor;
std::string strPosition;
std::vector<unsigned int> positionNums;
ShipNumber iAttack;
bool isFirstStart = true;
unsigned int iDestroyerLost = 0;
unsigned int iCruisersLost = 0;
unsigned int iAircraftLost = 0;
while (!game.IsGameOver()) {
iDestroyerLost = 0;
iCruisersLost = 0;
iAircraftLost = 0;
if (isFirstStart) {
std::cout << "Start Game" << std::endl;
isFirstStart = false;
} else {
std::cout << "Try Again" << std::endl;
}
positionNums.clear();
std::cin >> strPosition;
std::stringstream ss(strPosition);
for (unsigned int i; ss>>i;) {
positionNums.push_back(i);
if (ss.peek() == ',') {
ss.ignore();
}
}
if (positionNums.size() < 2) {
std::cout << "InValid Input" << std::endl;
continue;
}
cor.x = positionNums[0];
cor.y = positionNums[1];
if (cor.x > Game::m_iMapWidth || cor.x == 0 || cor.y > Game::m_iMapHeight || cor.y == 0) {
std::cout << "InValid Input" << std::endl;
continue;
}
game.Attack(cor, iAttack);
if (iAttack > 0) {
std::cout << "A Direction Hit On Ship Number " << iAttack << std::endl;
if (!game.IsShipStillSurvive(iAttack)) {
std::cout << "And you sunk it. Hurrah for the good guys." << std::endl;
std::cout << "So far the bad gut have lost" << std::endl;
game.ShipLost(iDestroyerLost, iCruisersLost, iAircraftLost);
std::cout << iDestroyerLost << " Destroyer(s), " << iCruisersLost;
std::cout << " Cruiser(s), And " << iAircraftLost << " Aircraft Carrier(s)." << std::endl;
}
} else {
std::cout << "Splash!" << std::endl;
}
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T14:25:34.903",
"Id": "524629",
"Score": "0",
"body": "Are you really stuck with C++11? That's pretty archaic these days."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T14:30:04.883",
"Id": "524631",
"Score": "0",
"body": "@TobySpeight xD, Good point, now is 2021. I should go for C++20!"
}
] |
[
{
"body": "<p>The code is not bad, but I see some things that may help you improve it.</p>\n<h2>Check your spelling</h2>\n<p>There are some typos and peculiar capitalization in the strings displayed for the user. For instance "gut" should probably be "guys," "InValid" should be "Invalid" and "Direction Hit" should be "direct hit." A little extra effort on that helps the user.</p>\n<h2>Omit autoconstructed functions</h2>\n<p>The code currently has this line:</p>\n<pre><code>virtual ~Game() {}\n</code></pre>\n<p>It's reasonable to make the destructor virtual if you expect to derive from it, but that's not the case here, so I would recommend simply omitting it and letting the compiler generate the default destructor.</p>\n<h2>Use <code>const</code> where practical</h2>\n<p>In many cases, such as <code>IsGameOver()</code>, the code doesn't and shouldn't alter the underlying <code>Game</code> object, and so it should be declared <code>const</code>:</p>\n<pre><code>bool IsGameOver() const;\n</code></pre>\n<h2>Prefer <code>std::array</code> to <code>std::vector</code> if sizes are fixed at compile time</h2>\n<p>Because we know the sizes at compile time, everywhere you've used a <code>std::vector</code>, I'd suggest using a <code>std::array</code> instead. For this code it probably won't make much of a difference, but it's useful to get into the habit of using the most economical data type that is practical.</p>\n<h2>Don't use <code>std::endl</code> if you don't really need it</h2>\n<p>The difference betweeen <code>std::endl</code> and <code>'\\n'</code> is that <code>'\\n'</code> just emits a newline character, while <code>std::endl</code> actually flushes the stream. This can be time-consuming in a program with a lot of I/O and is rarely actually needed. It's best to <em>only</em> use <code>std::endl</code> when you have some good reason to flush the stream and it's not very often needed for simple programs such as this one. Avoiding the habit of using <code>std::endl</code> when <code>'\\n'</code> will do will pay dividends in the future as you write more complex programs with more I/O and where performance needs to be maximized.</p>\n<h2>Rethink your use of objects</h2>\n<p>The <code>Game</code> class is a good idea, but information about ships is scattered in multiple places. For example, the <code>m_shipNumberInfo</code> has a map of ship number to ship type, and then <code>m_shipFleetInfo</code> has a map of ship type to ship length. Both make references to the <code>enum ShipType</code>. For this, I'd suggest instead using objects. One could start with this:</p>\n<pre><code>class Ship {\npublic:\n enum ShipType { DESTROYER=2, CRUISER=3, AIRCRAFT=4 };\n Ship(ShipType t) : myType{t}, remaining{t} {}\n unsigned hit() { return remaining ? --remaining : 0; }\n // return true if ship is still alive\n bool operator()() const { return remaining; }\n // data members\n ShipType myType;\n unsigned remaining;\n};\n</code></pre>\n<p>Now all of the information about a ship is contained in a single place. We can then make this class <code>private</code> within <code>Game</code> and keep track of them with a default initialization like this:</p>\n<pre><code>std::array<Ship, 6> ships = { \n Ship::ShipType::DESTROYER, \n Ship::ShipType::DESTROYER, \n Ship::ShipType::CRUISER, \n Ship::ShipType::CRUISER, \n Ship::ShipType::CARRIER, \n Ship::ShipType::CARRIER,\n};\n</code></pre>\n<p>Many things become much simpler now. For example:</p>\n<pre><code>bool IsShipStillSurvive(ShipNumber& iShip) const\n{\n return ships.at(iShip - 1)();\n}\n\nbool IsGameOver() const\n{\n return std::none_of(ships.begin(), ships.end(), [](const Ship& s){return s();});\n}\n</code></pre>\n<h2>Think of the user</h2>\n<p>The game gives very little instruction or feedback, making it a bit difficult to play. I'd suggest adding some instructions and also providing a map for the user at each turn to show places where attacks had already been made and which ones resulted in hits.</p>\n<h2>Consider additional objects</h2>\n<p>In addition to the <code>Ship</code> object mentioned above, it might also be nice to separate a <code>Board</code> object from the <code>Game</code> and to use a <a href=\"https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"noreferrer\"><em>Model-View-Container</em></a> approach. Also, the <code>Coordinate</code> could be a public object within <code>Game</code> and the input and validation could be a member function of that class rather than in <code>main</code>.</p>\n<h2>Use C++20 features</h2>\n<p>One handy feature of C++20 is the ability to return a <code>std::tuple</code>. So instead of this:</p>\n<pre><code>game.ShipLost(iDestroyerLost, iCruisersLost, iAircraftLost);\n</code></pre>\n<p>We can instead write this:</p>\n<pre><code>auto [iDestroyerLost, iCruisersLost, iAircraftLost] = game.ShipLost();\n</code></pre>\n<p>The corresponding function can be simplified using <code>std::count_if</code>:</p>\n<pre><code>std::tuple<unsigned, unsigned, unsigned > ShipLost()\n{\n unsigned iDestroyer = std::count_if(ships.begin(), ships.end(), [](const Ship& s){ \n return s.myType == Ship::ShipType::DESTROYER && !s(); });\n unsigned iCruisers = std::count_if(ships.begin(), ships.end(), [](const Ship& s){ \n return s.myType == Ship::ShipType::CRUISER && !s(); });\n unsigned iAircraft = std::count_if(ships.begin(), ships.end(), [](const Ship& s){ \n return s.myType == Ship::ShipType::CARRIER && !s(); });\n return std::make_tuple(iDestroyer, iCruisers, iAircraft);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T18:45:24.713",
"Id": "265609",
"ParentId": "265600",
"Score": "7"
}
},
{
"body": "<p>First, your "TODO" to populate the map is good. This is an example of top-down decomposition, and it is good to block out your code and start with a stub.</p>\n<hr />\n<pre><code>typedef enum {\n SHIP_TYPE_DESTROYER,\n SHIP_TYPE_CRUISERS,\n SHIP_TYPE_AIRCRAFT,\n} ShipType;\n\ntypedef unsigned int ShipNumber ;\n</code></pre>\n<p><code>typedef enum</code>? This isn't C. Write <code>enum ShipType { ⋯ };</code> or even an <code>enum class</code> depending on your needs. You don't need to <code>typedef</code> what are "tags" in C to get type names; they already are type names in C++.</p>\n<p>It's good to give your types symbolic names even if they are not "strong types", but don't use the <code>typedef</code> keyword anymore, at all. Write this as:</p>\n<pre><code>using ShipNumber = unsigned int;\n</code></pre>\n<p>or better yet, use the <code><stdint></code> types like <code>uint32_t</code>.</p>\n<hr />\n<p>Why are you making your destructor <code>virtual</code>? You have <em>no</em> (other) virtual functions in the class, and you don't use polymorphism in any way. You are using the class itself, not derived classes.</p>\n<hr />\n<pre><code>Game game = Game();\n</code></pre>\n<p>Just:</p>\n<pre><code>Game game;\n</code></pre>\n<p>is what you need. Do you understand that <code>Game</code> is created on the stack, not the heap? I wonder if you're thinking Java-like because other variables are not being initialized this way.</p>\n<hr />\n<p>Use signed integer types, not <code>unsigned</code>, unless you are doing bit manipulation, rely on overflow rolling over, or <em>really need</em> one more bit of range.</p>\n<hr />\n<pre><code>Coordinate cor;\nstd::string strPosition;\nstd::vector<unsigned int> positionNums;\n</code></pre>\n<p>These are defined as part of a bunch at the beginning of <code>main</code>. But, you don't need them to preserve their value across loop iterations; in fact, you call <code>positionNums.clear()</code> near the top of the loop. Declare variables <em>where you first need them</em>.</p>\n<hr />\n<h2>Abstract out the users input/interaction</h2>\n<p>Instead of mixing <code>cin >></code> stuff throughout the huge loop that does everything,<br />\n⭐ write functions to do <em>one thing</em> as a single level of abstraction farther down.⭐<br />\nYour game loop should read like an outline, with named functions expressing high-level steps, not blobs of code <em>doing</em> those steps.</p>\n<p>As for the input in particular, using <code>cin>></code> is nasty in that it goes against best practices of defining variables where you need them, initializing them, and hopefully making them <code>const</code>. And then you have to parse the input and deal with errors, all "deeper" levels of detail than you need. The main loop should state simply:</p>\n<pre><code>const Coordinate cor = get_play();\n</code></pre>\n<p>This whole blob of code:</p>\n<pre><code> positionNums.clear();\n std::cin >> strPosition;\n std::stringstream ss(strPosition);\n for (unsigned int i; ss>>i;) {\n positionNums.push_back(i);\n if (ss.peek() == ',') {\n ss.ignore();\n }\n }\n if (positionNums.size() < 2) {\n std::cout << "InValid Input" << std::endl;\n continue;\n }\n cor.x = positionNums[0];\n cor.y = positionNums[1];\n</code></pre>\n<p>is detail that <strong>does not belong</strong> expanded out here in the main loop.</p>\n<p>It's also good to abstract out the input/interaction as a separate concern, anyway. In the BASIC port you can use terminal input as you have here, but you might replace that with some kind of GUI or game controls later, simply by changing the implementation of these well-specified functions and not affecting the core game play logic at all.</p>\n<hr />\n<pre><code>void Attack(const Coordinate& coordinate, ShipNumber& iAttackShip)\n</code></pre>\n<p>I'm supposing the second must be "out" parameters, and this function is providing this information to the caller.</p>\n<p>Strenuously avoid "out" parameters.<br />\nReturn things using function return values.</p>\n<pre><code>if (coordinate.x <= m_iMapWidth && coordinate.y <= m_iMapHeight && coordinate.x > 0 && coordinate.y > 0) {\n // the entire meat of the function\n }\n</code></pre>\n<p>Write "to the left margin". Don't keep opening up deeper and deeper levels of nesting. What you have here is a <em>precondition</em>. Since this is a global constraint (the entire map) it should have been checked already, as part of the input function, and this function can assume it's passed a valid value of <code>coordinate</code>.</p>\n<p>But just to illustrate, preconditions should return or throw, as a prelude to the real body of the function. Rather than opening another nesting level:</p>\n<pre><code>if (!mapbounds.contains(coordinate)) return 0;\n</code></pre>\n<p>And notice that checking to see if a point is within a rectangle is a general reusable operation. You make it more complex and less "high level meaning" by keeping your map size in two separate variables rather than another coordinate pair.</p>\n<hr />\n<pre><code>[coordinate.x - 1][coordinate.y - 1]\n</code></pre>\n<p>You are repeatedly adjusting the indexes when you access your game data.\nUse internal coordinate values that <em>match</em> the board's representation. That is, zero-based.\nThe adjustment should be done as part of the <strong>user I/O</strong>. In fact, on a real Battleship board, you use letters for one of the axis, so it would actually be <code>A</code> through <code>K</code> or however big the board is. So, the User I/O mapping is more general than just subtracting 1; it can be a completely different representation. One axis can subtract 1 from a input number, the other mapps the letter to a number. Likewise, displaying the coordinate is a User I/O issue and the output functions should take the same <code>coordinate</code> that's used by the data structure.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T00:06:55.927",
"Id": "265683",
"ParentId": "265600",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "265609",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T14:22:22.540",
"Id": "265600",
"Score": "3",
"Tags": [
"c++",
"battleship"
],
"Title": "BASIC Computer Games: Battle in C++"
}
|
265600
|
<p>In one of my personal python libraries I have a custom class used for computing the running average and variance of a stream of numbers:</p>
<pre><code>import numpy as np
class RunningStatsVariable:
def __init__(self, ddof=0, parallel=None):
self.mean = 0
self.var = 0
self.std = 0
self._n = 0
self._s = 0
self._ddof = ddof
if parallel == 'multiprocessing':
from multiprocessing import Lock
self._lock = Lock()
elif parallel == 'threading':
from threading import Lock
self._lock = Lock()
else:
self._lock = None
def update(self, values):
if self._lock:
self._lock.acquire()
values = np.array(values, ndmin=1)
n = len(values)
self._n += n
delta = values - self.mean
self.mean += (delta / self._n).sum()
self._s += (delta * (values - self.mean)).sum()
self.var = self._s / (self._n - self._ddof) if self._n > self._ddof else 0
self.std = np.sqrt(self.var)
if self._lock:
self._lock.release()
def update_single(self, value):
if self._lock:
self._lock.acquire()
self._n += 1
old_mean = self.mean
self.mean += (value - old_mean) / self._n
self._s += (value - old_mean) * (value - self.mean)
self.var = self._s / (self._n - self._ddof) if self._n > self._ddof else 0
self.std = np.sqrt(self.var)
if self._lock:
self._lock.release()
def __str__(self):
if self.std:
return f"(μ ± σ): {self.mean} ± {self.std}"
else:
return f"{self.name}: {self.mean}"
def __len__(self):
return self._n
</code></pre>
<p>The idea is to make the class safe for parallel updates, regardless of the type of parallelism used (threading or multiprocessing), and regardless of which method of updating (single-value or list) is used. The code is also available on <a href="https://replit.com/@matedevita/ParallelSafeVariable" rel="nofollow noreferrer">Replit</a>. The below test seems to show this code works as expected:</p>
<pre><code>data = [(np.random.random(), np.random.rand(20)) for _ in range(1000)]
def _update(var, value, arr):
var.update_single(value)
var.update(arr)
v1 = RunningStatsVariable()
for v, a in data:
_update(v1, v, a)
from joblib import Parallel, delayed
v2 = RunningStatsVariable(parallel='multiprocessing')
Parallel(n_jobs=-1)(
delayed(_update)(v2, v, a)
for v, a in data
)
v3 = RunningStasVariable(parallel='threading')
Parallel(n_jobs=-1, prefer='threads')(
delayed(_update)(v3, v, a)
for v, a in data
)
# Can't use x == y == z for float comparison, so we use np.allclose instead
print(np.allclose(v1.mean, [v2.mean, v3.mean])) # True
print(np.allclose(v1.var, [v2.var, v3.var])) # True
print(np.allclose(v1.std, [v2.std, v3.std]))])) # True
</code></pre>
<p>However, in parallelism testing is usually not enough to guarantee correctness. So are the updates really parallel-safe? I don't necessarily care about the parallel-safety of the <code>__len__</code> and <code>__str__</code> methods.</p>
<p>Also, is locking at the start of the update method and unlocking at the end good practice or should I use more specific locks?</p>
<p>Additionally, I would like this code to work for other people, who may not be using <code>joblib</code> for their parallelism needs. Are there other lock types I should consider?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T17:34:04.030",
"Id": "265605",
"Score": "1",
"Tags": [
"python",
"multithreading",
"thread-safety",
"multiprocessing"
],
"Title": "Thread-safe running mean and variance"
}
|
265605
|
<p>This code needs to extract data from in XML file.
Specifically it needs to iterate over it, looking for a node called <code>CHARGE_CODES</code> that repeats over and over and has several elements.
it needs to extract the values of one of them, called <code>CODE</code>.
the XML contents are composed of repeating blocks like these:</p>
<pre><code><CHARGE_CODE>
<CODE>some value</CODE>
<OtherElement>some value</Otherelement>
..
..
</CHARGE_CODE>
..
..
</code></pre>
<p>The code then needs to put these values of "CODE" into an array.
I create several arrays like these each containing the values of one of these tags.</p>
<p>Then all these arrays are used to send SOAP POSTS and enter together (all elements from one CHARGE_CODES block) into a database as the details of a service.</p>
<p>This code contains one such array collecting the values of one node.</p>
<pre><code>public class Main {
public static void main(String argv[]){
String test = "URL";
File inputFile = new File(test);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(inputFile);
doc.getDocumentElement().normalize();
NodeList blocks = doc.getElementsByTagName("CHARGE_CODE");
ArrayList<String> codes = new ArrayList<>();
for(int i = 0; i<blocks.getLength(); i++){
Element children = (Element) blocks.item(i);
if(children.getElementsByTagName("CODE") != null){
codes.add(children.getElementsByTagName("CODE").item(0).getTextContent());
}else{
codes.add("");
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T18:56:19.740",
"Id": "524642",
"Score": "1",
"body": "That looks a lot like something that XPath is well suited to. You might find that the subset of XPath support in [`xml.etree.ElementTree`](https://docs.python.org/3/library/xml.etree.elementtree.html#xpath-support) is good enough for this task."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T19:14:36.650",
"Id": "524643",
"Score": "0",
"body": "You mean I should use python?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T20:12:23.003",
"Id": "524646",
"Score": "0",
"body": "Welcome to Stack Review, you can use xpath with java too. If you want to send a message to an user use @name in your message, see [how-do-comment-replies-work](https://meta.stackexchange.com/questions/43019/how-do-comment-replies-work) for further informations"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T20:37:12.623",
"Id": "524647",
"Score": "0",
"body": "Oops, sorry - I had just reviewed a Python question, so had those docs to hand. I don't know what XPath libraries exist for Java, but it may be worth researching, as you may find that much of the work is done for you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T09:20:36.487",
"Id": "524671",
"Score": "0",
"body": "Are you sure your code works ? Your main method throws no exceptions and there and you used `\"CHARGE_CODE\"` instead of `\"CHARGE_CODES\"`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T09:47:54.943",
"Id": "524673",
"Score": "0",
"body": "@dariosicily yes, the CHARGE_CODES is a mistake, ill correct it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T10:53:35.723",
"Id": "524674",
"Score": "1",
"body": "XPath for java is in the package javax.xml.xpath. All contained in the standard library."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T18:22:52.450",
"Id": "265607",
"Score": "1",
"Tags": [
"java",
"xml",
"dom"
],
"Title": "Extract series of XML elements' values into an array"
}
|
265607
|
<p>Ratiorg got statues of different sizes as a present from CodeMaster for his birthday, each statue having an non-negative integer size. Since he likes to make things perfect, he wants to arrange them from smallest to largest so that each statue will be bigger than the previous one exactly by 1. He may need some additional statues to be able to accomplish that. Help him figure out the minimum number of additional statues needed.</p>
<p>Example</p>
<p>For statues = [6, 2, 3, 8], the output should be
makeArrayConsecutive2(statues) = 3.</p>
<p>Ratiorg needs statues of sizes 4, 5 and 7.</p>
<p>Input/Output</p>
<p>[execution time limit] 3 seconds (java)</p>
<p>[input] array.integer statues</p>
<p>An array of distinct non-negative integers.</p>
<p>Guaranteed constraints:
1 ≤ statues.length ≤ 10,
0 ≤ statues[i] ≤ 20.</p>
<p>[output] integer</p>
<p>The minimal number of statues that need to be added to existing statues such that it contains every integer size from an interval [L, R] (for some L, R) and no other sizes.</p>
<p>Code:</p>
<pre><code>int makeArrayConsecutive2(int[] statues) {
int count =0;
Arrays.sort(statues);
for(int i=1;i<statues.length;i++){
count+=statues[i]-statues[i-1]-1;
}
return count;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T20:01:35.793",
"Id": "524644",
"Score": "0",
"body": "Welcome back to Code Review, please add the link to the programming challenge in your question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T20:06:31.740",
"Id": "524645",
"Score": "0",
"body": "It will not visible for an anonymous user"
}
] |
[
{
"body": "<h1>Indentation</h1>\n<p>You indentation is inconsistent. <code>int count =0;</code> is not indented the same amount as the following line, despite being logically at the same level.</p>\n<p>Your indentation amount is not consistent. You should use the same increment for each additional level. Assuming your first indentation was 2 spaces (instead of both 1 & 2), your next indentation should be an additional 2 spaces (total of 4 spaces).</p>\n<h1>White space</h1>\n<p>Use spaces to increase the readability of your code.</p>\n<p><code>int count =0;</code> should have a space after the equals sign.</p>\n<p><code>for(int i=1;i<statues.length;i++){</code> should at least have spaces after each semicolon.</p>\n<p><code>count+=statues[i]-statues[i-1]-1;</code> should have spaces around <code>+=</code>, as well as the outermost subtraction operators.</p>\n<p>This is more readable:</p>\n<pre class=\"lang-java prettyprint-override\"><code>int makeArrayConsecutive2(int[] statues) {\n int count = 0;\n Arrays.sort(statues);\n for(int i=1; i<statues.length; i++) {\n count += statues[i] - statues[i-1] - 1;\n }\n return count;\n}\n</code></pre>\n<h1>Names</h1>\n<p><code>count</code> is a very generic variable name. Count of what? Looking at the code, it isn’t clear.</p>\n<p>(<code>statues</code> is pretty vague, too. I’d prefer <code>statue_heights</code>. <code>makeArrayConsecutive2</code> is just awful. However, both those names get a pass, because they were given to you.)</p>\n<p>Instead of <code>count</code>, using <code>statues_to_add</code> really helps improve the readers comprehension. alternately, <code>count_of_missing_heights</code> would really increase understandability.</p>\n<h1>Algorithm</h1>\n<p>The <code>sort(statues)</code> makes the algorithm <span class=\"math-container\">\\$O(n \\log n)\\$</span>. With at most 10 statues, the sorting won’t take a lot of time, but it is doing more work than is needed.</p>\n<p>There is an <span class=\"math-container\">\\$O(n)\\$</span> algorithm, which only requires finding the largest and smallest statue heights. <s>Left to student.</s></p>\n<p>Since dariosicily has provided the solution, instead of allowing you to discover it, I’ll provide a shorter <a href=\"https://docs.oracle.com/javase/9/docs/api/java/util/Arrays.html\" rel=\"nofollow noreferrer\">stream</a>-based solution.</p>\n<pre class=\"lang-java prettyprint-override\"><code>int makeArrayConsecutive2(int[] statues) {\n return Arrays.stream(statues).max().getAsInt()\n - Arrays.stream(statues).min().getAsInt()\n + 1 - statues.length;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T07:14:06.767",
"Id": "524660",
"Score": "0",
"body": "thanks, just a question here we are creating stream objects twice, so maybe it will increase space complexity and I am not aware of Stream max time complexity"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T15:03:56.093",
"Id": "524693",
"Score": "2",
"body": "A stream is a glorified for-loop. It has a time complexity of \\$O(n)\\$ and a space complexity of \\$O(1)\\$ ... unless intermediate operations (`.sorted()`, `.distinct()`, ...) themselves have non-trivial requirements. You can avoid creating a second stream and gather the min/max values with just one stream using [`.summaryStatistics()`](https://docs.oracle.com/javase/9/docs/api/java/util/stream/IntStream.html#summaryStatistics--), but you'd be hard pressed to solve the problem in only one statement ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T20:57:34.580",
"Id": "524848",
"Score": "0",
"body": "Challenge revoked; it actually wasn't that hard to solve the problem with only one stream in only one statement. `return Arrays.stream(statues).boxed().collect(Collectors.collectingAndThen(Collectors.summarizingInt(i -> i), s -> s.getMax() - s.getMin() + 1 - s.getCount()));` Definitely not more efficient due to the need for `.boxed()` integers."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T21:15:44.160",
"Id": "265613",
"ParentId": "265610",
"Score": "5"
}
},
{
"body": "<p>Your algorithm is correct, but the performance can be improved to <em>O(n)</em> avoiding the sorting of the <em>n</em> elements array with <em>O(n log n)</em> cost. The final result is equal to <em>max + 1 - min - n</em> where min and max are respectively the minimum and the maximum element in the array, so your method can be rewritten like below :</p>\n<pre><code>private static int makeArrayConsecutive2(int[] statues) {\n int length = statues.length;\n if (length < 2) { return 0; }\n int min = Math.min(statues[0], statues[1]);\n int max = Math.max(statues[0], statues[1]);\n \n for (int i = 2; i < length; ++i) {\n min = Math.min(min, statues[i]);\n max = Math.max(max, statues[i]);\n }\n \n return max + 1 - min - length;\n}\n</code></pre>\n<p>For arrays containing one or zero elements the answer is zero because there are no elements in an interval of one or zero numbers; the fact that the array always contains distinct numbers guarantees that <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#max-int-int-\" rel=\"nofollow noreferrer\"><code>Math#max</code></a> and <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#min-int-int-\" rel=\"nofollow noreferrer\"><code>Math#min</code></a> always return distinct results.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T21:18:31.573",
"Id": "265614",
"ParentId": "265610",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T19:37:25.850",
"Id": "265610",
"Score": "3",
"Tags": [
"java",
"programming-challenge"
],
"Title": "Make Array Consecutive"
}
|
265610
|
<p>I'm starting to learn about networking and as a project I am building a really simple DNS client in Rust.</p>
<p>Functionality to start was just to take a command line domain argument and sending a DNS A record request to the google DNS server (8.8.8.8:53).</p>
<p>The application works right now (when compared to output from dig) with just googles DNS and with me testing several different domains.</p>
<p>I'm new to many topics involved here including:</p>
<ul>
<li>Rust</li>
<li>Networking in general</li>
<li>DNS in particular</li>
<li>Working with Binary / Bytes</li>
</ul>
<p>As such, those are the areas im most looking for feedback on - with a particular focus on idiomatic Rust (ive already used rustfmt and clippy) and working with Bit / Bytes.</p>
<p>Thanks in advance!</p>
<pre><code>use std::convert::TryInto;
use std::net::UdpSocket;
#[derive(Debug)]
struct DnsHeader {
tx_id: u16,
msg_type: DnsHeaderType,
opt_code: DnsOptCode,
aa: bool,
tc: bool,
rd: bool,
ra: bool,
rcode: DnsResponseCode,
}
impl DnsHeader {
fn from_bytes(bytes: [u8; 16]) -> DnsHeader {
let mut bits = u128::from_be_bytes(bytes);
let tx_mask = 0b1111_1111_1111_1111;
let tx_id = (bits & tx_mask) as u16;
bits >>= 16;
let dns_type = match bits & 1 {
0 => Ok(DnsHeaderType::Query),
1 => Ok(DnsHeaderType::Response),
_ => Err("Unexpected DNS type"),
};
let four_bit_mask = 0b1111_u128;
let opt_code = match (bits >> 1) & four_bit_mask {
0 => Ok(DnsOptCode::Query),
1 => Ok(DnsOptCode::Iquery),
2 => Ok(DnsOptCode::Status),
3 => Ok(DnsOptCode::Future),
_ => Err("Unexpected Opt Code"),
};
let aa = ((bits >> 5) & 1) != 0;
let tc = ((bits >> 6) & 1) != 0;
let rd = ((bits >> 7) & 1) != 0;
let ra = ((bits >> 15) & 1) != 0; // Do I really need to add 8 since
// its the next byte and little endian? I'm looking for the next bit
// and expected to be able to use >> 8
let response_code = match (bits >> 19) & four_bit_mask {
0 => Ok(DnsResponseCode::NoError),
1 => Ok(DnsResponseCode::FormatError),
2 => Ok(DnsResponseCode::ServerFailure),
3 => Ok(DnsResponseCode::NameError),
4 => Ok(DnsResponseCode::NotImplemented),
5 => Ok(DnsResponseCode::Refused),
6 => Ok(DnsResponseCode::Future),
_ => Err("Unexpected Response Code"),
};
DnsHeader {
tx_id,
msg_type: dns_type.expect("DNS Type Error"),
opt_code: opt_code.expect("DNS Opt Code Error"),
aa,
tc,
rd,
ra,
rcode: response_code.expect("DNS Response Code Error"),
}
}
}
#[derive(Debug)]
enum DnsHeaderType {
Query = 0,
Response = 1,
}
#[derive(Debug)]
enum DnsOptCode {
Query = 0,
Iquery = 1,
Status = 2,
Future = 3,
}
#[derive(Debug)]
enum DnsResponseCode {
NoError = 0,
FormatError = 1,
ServerFailure = 2,
NameError = 3,
NotImplemented = 4,
Refused = 5,
Future = 6,
}
fn construct_dns_headerr(
tx_id: u16,
dns_type: DnsHeaderType,
op_code: DnsOptCode,
aa: u128,
tc: u128,
rd: u128,
ra: u128,
qdcount: u128,
) -> u128 {
let mut header: u128 = tx_id as u128;
header |= (dns_type as u128) << 9;
header |= (op_code as u128) << 10;
header |= aa << 14;
header |= tc << 15;
header |= rd << 16;
header |= ra << 17;
header |= qdcount << 40;
header
}
fn convert_domain_to_questions(domain: String) -> Vec<u8> {
let labels: Vec<&str> = domain.split('.').collect();
let mut questions = Vec::new();
for label in labels.iter() {
let length = label.len();
questions.push(length as u8);
questions.extend_from_slice(label.as_bytes());
}
questions
}
fn main() -> std::io::Result<()> {
{
let local = "0.0.0.0:0";
let google_dns = "8.8.8.8:53";
let socket = UdpSocket::bind(local)?;
let dns_type = DnsHeaderType::Query;
let opt_code = DnsOptCode::Query;
let domain = std::env::args().nth(1).expect("Misisng domain");
let records = std::env::args().nth(2).unwrap_or_else(|| String::from("All"));
println!("Domain: {}, Record: {}", domain, records);
let header = construct_dns_headerr(7, dns_type, opt_code, 0, 0, 1, 0, 1);
let mut full_buf = header.to_be_bytes();
full_buf.reverse();
let mut buf = Vec::new();
buf.extend_from_slice(&full_buf[..12]);
let questions = convert_domain_to_questions(domain);
buf.extend_from_slice(&questions);
buf.extend_from_slice(&[0, 0, 1, 0, 1]);
println!("Buf bits: \n{:034b}", u128::from_be_bytes(full_buf));
println!("Buf byte array: {:?}", buf);
socket
.send_to(&buf, google_dns)
.expect("Couldnt send datat");
let mut read_buf = [0; 64];
let (number_of_bytes, src_addr) = socket
.recv_from(&mut read_buf)
.expect("Didn't receive data");
println!("Read socket source address: {}", src_addr);
println!("Read socket bytes read: {}", number_of_bytes);
read_buf.reverse();
println!("Filled buf:\n{:?}", read_buf);
let header_bytes = &read_buf[48..]
.try_into()
.expect("Failed to get header bytes");
let bits = u128::from_be_bytes(*header_bytes);
println!("Reponse bits:\n{:b}", bits);
let dns_response = DnsHeader::from_bytes(*header_bytes);
println!("Response: {:?}", dns_response);
let mut ip = vec![0; 4];
let buf_size = read_buf.len();
let ip_start = buf_size - number_of_bytes;
let ip_bytes = &read_buf[ip_start..ip_start + 4];
ip.clone_from_slice(&ip_bytes);
ip.reverse();
println!("Answer IP: {:?}", ip);
}
Ok(())
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T21:37:34.063",
"Id": "265615",
"Score": "4",
"Tags": [
"rust",
"networking",
"bitwise"
],
"Title": "Barebones DNS Client in Rust"
}
|
265615
|
<p>So I am once again beating a dead horse, by solving the <a href="https://projecteuler.net/problem=1" rel="nofollow noreferrer">first Project Euler problem</a>:</p>
<blockquote>
<p>If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.</p>
<p>Find the sum of all the multiples of 3 or 5 below 1000.</p>
</blockquote>
<p>However, this time I am by trying to dip my toes into <em>functional programming</em> in javascript. I followed the following advice</p>
<blockquote>
<p>no self-respecting functional programmer would be caught dead without a <a href="https://en.wikipedia.org/wiki/Fold_(higher-order_function)" rel="nofollow noreferrer">fold function</a> (AKA reduce), whether she needed it or not, so let's be sure to write one now and worry about finding a way to use it later:</p>
</blockquote>
<p>and added a few fold functions to my code. Any suggestions on the javascript in regards to functional programming is more than welcome. The code works as expected and returns the sum of every number bellow 1000 divisible by either 3 or 5.</p>
<p><sup>I am aware that this approach is very wasteful memory wise, and it would be better simply using a for each loop.</sup></p>
<pre><code>const pipe = (...functions) => value =>
functions.reduce((currValue, currFunc) => currFunc(currValue), value)
const range = (start, stop) => {
return new Array(stop - start).fill().map((d, i) => i + start);
}
const divisibleByDivisors = divisors => numbers =>
numbers.filter(num => divisors.some((divisor) => num % divisor === 0));
const addValues = (numA, numB) => numA + numB
const sumNumbers = numbers => numbers.reduce(addValues, 0)
let divisors = [3, 5]
let numbers = range(1, 1000);
const PE_001 = pipe(
divisibleByDivisors(divisors),
sumNumbers
)
console.log(PE_001(numbers));
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T19:21:48.723",
"Id": "524739",
"Score": "1",
"body": "No need for the helpers. This can be done as a single reduce: `[...Array(1000).keys()].reduce((m,x)=> m + ((x % 3 == 0 || x % 5 == 0) ? x : 0))`."
}
] |
[
{
"body": "<p>You can definitely reduce the length of some of your variable names without losing any readability:</p>\n<pre><code>const pipe = (...functions) => value =>\n functions.reduce((currValue, currFunc) => currFunc(currValue), value)\n</code></pre>\n<p>Could be:</p>\n<pre><code>const pipe = (...functions) => seed =>\n functions.reduce((value, fn) => fn(value), seed)\n</code></pre>\n<p>There's no need to add braces to your <code>range</code> function. As we know, all functions have one argument in FP* so I think we should do that too:</p>\n<pre><code>const range = start => stop => new Array(stop - start).fill().map((_, i) => i + start);\n</code></pre>\n<p>I've also used <code>_</code> (sometimes called discard) to show that <code>d</code> isn't useful.</p>\n<p>*I think ensuring all functions have one argument in js is painful so you probably don't really want to do this.</p>\n<p>Some more names that might benefit from being shorter:</p>\n<ul>\n<li><code>divisibleByDivisors</code> -> <code>isDivisibleBy</code></li>\n<li><code>addValues</code> -> <code>add</code></li>\n<li><code>sumNumbers</code> -> <code>sum</code></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T10:04:31.680",
"Id": "265628",
"ParentId": "265616",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-01T22:55:33.170",
"Id": "265616",
"Score": "2",
"Tags": [
"javascript",
"programming-challenge",
"functional-programming"
],
"Title": "Project Euler 1 using functional programming in JS"
}
|
265616
|
<p>File: InfoFactory.h contains four classes.</p>
<ol>
<li><code>CaffienatedBeverage</code> is an Abstract class with one pure virtual function <code>Name</code>. It also contains some data members that are used to make a coffee based drink and name of the drink.</li>
<li><code>Latte</code> is a class that inherits <code>CaffienatedBeverage</code> class. Latte contains milk and coffee.</li>
<li><code>Expresso</code> is another class that inherits <code>CaffienatedBeverage</code> class and is made of water and coffee.</li>
<li><code>BeverageFactory</code> class that contains a static method <code>createBeverage</code> which takes input and creates a Caffienated Beverage.</li>
</ol>
<pre><code>#include <iostream>
class CaffeinatedBeverage
{
private:
bool _water;
bool _milk;
bool _coffee;
std::string _name;
public:
CaffeinatedBeverage() : _water{ false }, _milk{ false }, _coffee{ false }, _name{nullptr}{};
CaffeinatedBeverage(bool water, bool milk, bool coffee, std::string str)
{
_water = water;
_milk = milk;
_coffee = coffee;
_name = str;
}
~CaffeinatedBeverage(){}
virtual std::string Name() = 0;
};
class Latte : public CaffeinatedBeverage
{
public:
Latte(): CaffeinatedBeverage(false, true, true, std::string("Latte"))
{
std::cout << "Latte is a Coffee based drink that contains milk\n";
}
~Latte() {};
std::string Name() override;
};
class Espresso : public CaffeinatedBeverage
{
public:
Espresso(): CaffeinatedBeverage(true, false, true, std::string("Espresso"))
{
std::cout << "Creates \n";
}
~Espresso() {};
std::string Name() override;
};
class BeverageFactory
{
public:
static CaffeinatedBeverage* createBeverage();
};
</code></pre>
<p>File InfoFactory.cxx</p>
<pre><code>#include <iostream>
#include "InfoFactory.h"
std::string Latte::Name()
{
return "\n\n\n\nLatte\n\n\n\n";
}
std::string Espresso::Name()
{
return "\n\n\nEspresso\n\n\n";
}
CaffeinatedBeverage* BeverageFactory::createBeverage()
{
int option = -1;
std::cout << "Please enter 1 for Latte and 2 for Espresso. To exit please enter 0. ";
std::cin >> option;
while (option)
{
switch (option)
{
case 1:
return new Latte();
break;
case 2:
return new Espresso();
break;
case 0:
break;
default:
std::cout << "Please try again: ";
std::cin >> option;
}
}
}
</code></pre>
<p>File main.cxx</p>
<pre><code>#include <iostream>
#include "InfoFactory.h"
int main()
{
auto beverage = BeverageFactory::createBeverage();
std::cout << beverage->Name() << std::endl;
return 0;
}
</code></pre>
<p><strong>Does this code implements Factory Method desing pattern correctly?</strong></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T07:47:45.750",
"Id": "524664",
"Score": "0",
"body": "I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Please check that I haven't misrepresented your code, and correct it if I have."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T04:59:13.187",
"Id": "524757",
"Score": "0",
"body": "Welcome to Code Review. I have rolled back your latest edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] |
[
{
"body": "<h2>Memory management and cleanup with inheritance</h2>\n<p>Objects allocated with <code>new</code> must be cleaned up by calling <code>delete</code>. In this case the <code>beverage</code> object is never cleaned up. In modern (and not so modern) C++ we should use a <code>std::unique_ptr</code> instead of doing manual memory management.</p>\n<p>When we call member functions on a pointer to the base-class (<code>CaffeinatedBeverage</code>), it will call the base-class member function if that function is not marked <code>virtual</code>. The destructor behaves in a similar way. So when destroying an object from a base class pointer, we <em>must</em> make the destructor <code>virtual</code> to ensure the derived destructor is called.</p>\n<p>(Note that <code>virtual</code> destructors are not quite the same as <code>virtual</code> functions - the base class destructor will be called automatically after the virtual derived class destructor, so we don't need to that manually.)</p>\n<hr />\n<h2>Undefined behavior</h2>\n<blockquote>\n<pre><code>CaffeinatedBeverage() : _water{ false }, _milk{ false }, _coffee{ false }, _name{nullptr}{};\n</code></pre>\n</blockquote>\n<p>Passing a <code>nullptr</code> to a <code>std::string</code> constructor is actually undefined behavior (and will be explicitly prevented in C++23). The relevant constructor requires a null-terminated character string.</p>\n<p>We can create an empty <code>std::string</code> by using the default constructor (<code>_name{}</code>) or simply omitting it from the initializer list.</p>\n<hr />\n<h2>Constructor initializer list and <code>std::move</code></h2>\n<blockquote>\n<pre><code>CaffeinatedBeverage(bool water, bool milk, bool coffee, std::string str)\n{\n _water = water;\n _milk = milk;\n _coffee = coffee;\n _name = str;\n}\n</code></pre>\n</blockquote>\n<p>We should also use the constructor initializer list here. Since we make a copy of the name when taking it as an argument, we can move that copy into place instead of copying it again: <code>_name{ std::move(str) }</code>.</p>\n<hr />\n<h2>Prefer free functions when we have no class state</h2>\n<blockquote>\n<pre><code>class BeverageFactory\n{\npublic:\n static CaffeinatedBeverage* createBeverage();\n};\n</code></pre>\n</blockquote>\n<p>This class has no state (member variables), and only a single static function. This implies that it should not be a class. It can be a simple function instead.</p>\n<hr />\n<h2>Simplify</h2>\n<p>Note that currently there is no need to use inheritance here. The name is stored in the base class, and there is no significant difference in behavior between the classes. We can use a simple struct to store the data, such as:</p>\n<pre><code>struct CoffeeDrink\n{\n std::string name;\n bool water;\n bool milk;\n bool coffee;\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T13:22:37.953",
"Id": "524684",
"Score": "0",
"body": "Thanks for pointing these problems out. I have attempted to implement Factory Method design patterns with the code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T09:03:43.903",
"Id": "265624",
"ParentId": "265621",
"Score": "3"
}
},
{
"body": "<pre><code>class CaffeinatedBeverage\n{\nprivate:\n bool _water;\n bool _milk;\n bool _coffee;\n std::string _name;\npublic:\n CaffeinatedBeverage() : _water{ false }, _milk{ false }, _coffee{ false }, _name{nullptr}{};\n ⋮\n</code></pre>\n<p>You should use inline initializers and then you don't need the default constructor to be spelled out. Note that <code>string</code> has a constructor and defaults to being empty, so you don't need to specify an initializer for that.</p>\n<p>Write:</p>\n<pre><code> bool _water = false;\n bool _milk = false;\n bool _coffee = false;\n std::string _name;\npublic:\n CaffeinatedBeverage() = default;\n\n</code></pre>\n<p>Continuing...</p>\n<pre><code> ⋮\n CaffeinatedBeverage(bool water, bool milk, bool coffee, std::string str)\n {\n _water = water;\n _milk = milk;\n _coffee = coffee;\n _name = str;\n }\n ~CaffeinatedBeverage(){}\n virtual std::string Name() = 0;\n};\n</code></pre>\n<p>This constructor should use the member init list, not assignments in the constructor function body. It is strange that <code>str</code> is being passed <strong>by value</strong>. In this case you could use the "sink" idiom to avoid copying, but I don't think you were aware of that. More generally, pass <code>string</code> values using <code>const &</code> parameters, or use <code>string_view</code> where you can.</p>\n<p>The destructor should also be declared <code>virtual</code>. And don't define trivial destructors (or other special members) like that, as it makes the compiler not understand that it really is the trivial or same-as-automatic stuff. Use:</p>\n<p><code>virtual ~CaffeinatedBeverage() =default;</code></p>\n<hr />\n<p><code> Latte(): CaffeinatedBeverage(false, true, true, std::string("Latte"))</code></p>\n<p>Why are you explicitly constructing <code>string</code> here? Just passing <code>"Latte"</code> by itself to the <code>std::string</code> parameter would work, and is idiomatic.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T17:41:53.817",
"Id": "265744",
"ParentId": "265621",
"Score": "2"
}
},
{
"body": "<p>I see the other answers have focused on the use of C++, so I'll briefly comment about the actual use of the design pattern.</p>\n<p>You are indeed using the factory method pattern.</p>\n<p>After all, this pattern just needs for a method to create an instance of a certain class. The actual instace created (one of its children) will be chosen depending on a certain condition.</p>\n<p>In your case, this was a simple stdin prompt. In a real-world application, the decision could have been made by the user iteracting with the UI.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T18:40:33.763",
"Id": "265746",
"ParentId": "265621",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "265624",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T06:51:47.740",
"Id": "265621",
"Score": "2",
"Tags": [
"c++",
"object-oriented",
"c++11",
"design-patterns",
"factory-method"
],
"Title": "Factory Method Design Pattern Implementation as a Coffee maker program"
}
|
265621
|
<p>The original purpose of this script was saving data to a local file, which is still the primary purpose.</p>
<p>Since I may only obtain one copy of a data stream (not this particular Coinbase one; it's just a free example), I'd like to add a secondary purpose using websockets to mirror the data for a Python web-server, but absolutely without interfering with the primary purpose above. Here is what I have so far:</p>
<pre class="lang-py prettyprint-override"><code>import asyncio
import websockets
import json
import aiofiles
from websockets.exceptions import ConnectionClosedOK
subscribers = set()
sub_limit = 3
async def mirror_ticks():
async with websockets.connect("wss://ws-feed.pro.coinbase.com") as ws:
await ws.send(json.dumps({
"type": "subscribe",
"product_ids": ["BTC-USD", "ETH-USD"],
"channels": ["ticker"]
}))
while True:
data = await ws.recv()
# Critical primary purpose: Save data to local file
async with aiofiles.open('filename', mode='a') as file:
await file.write(data + '\n')
# Secondary purpose: Mirror data to Python web-server
for sub in subscribers:
try:
await sub.send(data)
except:
pass
async def subscribe_ws(ws, path):
if len(subscribers) >= sub_limit:
ws.send("All client slots are currently in use")
print(f"Slots full, turned away: {ws.request_headers.get('User-Agent', '')}")
subscribers.add(ws)
while True:
try:
await ws.recv()
except ConnectionClosedOK:
print(f"Client disconnected: {ws.request_headers.get('User-Agent', '')}")
subscribers.discard(ws)
break
start_server = websockets.serve(subscribe_ws, "localhost", 8765)
asyncio.get_event_loop().run_until_complete(asyncio.gather(start_server, mirror_ticks()))
# asyncio.get_event_loop().run_forever()
</code></pre>
<p>I've added some precautions by limiting the number of subscribers to prevent overloading the secondary task from gobbling up resources, and I've tried to make sure any disconnects are handled so that it doesn't interfere with the primary purpose.</p>
<ol>
<li>Any edge-cases or unexpected consequences to beware of here? Eg. could a misbehaving subscriber somehow still interfere with the primary purpose?</li>
<li>The last line is commented-out because it doesn't seem necessary, can I remove it? Where would it be necessary?</li>
</ol>
|
[] |
[
{
"body": "<p>I'm not familiar with how <code>websocket</code> works, but from your code I think I can infer it. So here a few comments:</p>\n<p>It seems your subscribers list depends on currently opened connections. That is bad practise. The first reason being, HTTP sessions have a timeout. Hence, after a while (I think its a couple of minutes), you will lose connection to your subscribers. Keeping the connection open, you are also wasting resources, as you don't really need a connection until you are about to send something.</p>\n<p>Also, it seems you are only removing a subscriber from the list if the connection closes correctly. However, what happens it the connection is closed unexpectedly? Instead, you should have caught <code>ConnectionClosed</code> exception.</p>\n<p>To solve both these issues, you could have your subscribers be web servers. To subscribe, they would send the server a message with a url to which send the data (and the close the connection), and the server would send them the data when available. Then, the subscribers could send another message to be unsubscribed.</p>\n<p>Now, regarthing the second question, both lines of code would have the same behaviour as <code>mirror_ticks</code> has an infinite loop. Hence, no matter if you wait for it to finish, it never will</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T09:20:50.580",
"Id": "265625",
"ParentId": "265623",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T08:04:19.560",
"Id": "265623",
"Score": "1",
"Tags": [
"python",
"async-await",
"websocket"
],
"Title": "Adding websocket functionality to send live data from a Python script. Any edge-cases or unexpected consequences to beware of?"
}
|
265623
|
<p>I am trying to use Scrapy for one of the sites I've scraped before using Selenium over <a href="https://codereview.stackexchange.com/questions/263373/requests-vs-selenium-vs-scrapy">here</a>.</p>
<p>Because the search field for this site is dynamically generated and requires the user to hover the cursor over a button before it appears, I can't seem to find a way to POST the query using <code>Requests</code> or Scrapy's spider alone.</p>
<p>In <code>scrapy shell</code>, though I can:</p>
<pre class="lang-py prettyprint-override"><code>fetch(FormRequest.from_response(response,
formdata={'.search-left input':"尹至"},
callback=self.search_result))
</code></pre>
<p>I have no way to tell whether the search query is successful or not.</p>
<p>Here is a simple <em>working code</em> which I will be using for my spider below.</p>
<pre class="lang-py prettyprint-override"><code>from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver import Firefox, FirefoxProfile
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time
def parse(url):
with Firefox() as driver:
driver.get(url)
wait = WebDriverWait(driver, 100)
xpath = "//form/button/input"
element_to_hover_over = driver.find_element_by_xpath(xpath)
hover = ActionChains(driver).move_to_element(element_to_hover_over)
hover.perform()
search = wait.until(
EC.presence_of_element_located((By.ID, 'showkeycode1015273'))
)
search.send_keys("尹至")
search.submit()
time.sleep(5)
rows = driver.find_elements_by_css_selector(".search_list > li")
for row in rows:
caption_elems = row.find_element_by_tag_name('a')
yield {
"caption" : caption_elems.text,
"date": row.find_element_by_class_name('time').text,
"url": caption_elems.get_attribute('href')
}
x = parse('https://www.ctwx.tsinghua.edu.cn')
for rslt in x:
print(rslt)
</code></pre>
<p>The scrapy spider below stops short at entering the search query when I run <code>scrapy crawl qinghua</code>.</p>
<pre class="lang-py prettyprint-override"><code>import scrapy
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver import Firefox, FirefoxProfile
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time
class QinghuaSpider(scrapy.Spider):
name = 'qinghua'
allowed_domains = ['https://www.ctwx.tsinghua.edu.cn']
start_urls = ['https://www.ctwx.tsinghua.edu.cn']
def __init__(self):
self.driver = webdriver.Firefox()
def parse(self, response):
with Firefox() as driver:
driver.get(response.url)
wait = WebDriverWait(self.driver, 100)
xpath = "//form/button/input"
element_to_hover_over = driver.find_element_by_xpath(xpath)
hover = ActionChains(driver).move_to_element(element_to_hover_over)
hover.perform()
search = wait.until(
EC.presence_of_element_located((By.ID, 'showkeycode1015273'))
)
search.send_keys("尹至")
search.submit()
time.sleep(5)
rows = self.driver.find_elements_by_css_selector(".search_list > li")
for row in rows:
caption_elems = row.find_element_by_tag_name('a')
yield {
"caption" : caption_elems.text,
"date": row.find_element_by_class_name('time').text,
"url": caption_elems.get_attribute('href')
}
# return FormRequest.from_response(
# response,
# formdata={'.search-left input':"尹至"},
# callback=self.search_result)
def search_result(self, response):
pass
</code></pre>
<p>I would like to ask:</p>
<ol>
<li>Why the spider code doesn't work, and</li>
<li>How to do this properly in Scrapy, with or (preferably) without the help of Selenium.</li>
</ol>
<p>I suspect this website has a robust anti-bot infrastructure that can prevent spiders from operating properly.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T16:08:45.943",
"Id": "524728",
"Score": "0",
"body": "I think for this to be on topic, you're going to need to excise the part that doesn't work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T06:16:16.553",
"Id": "524765",
"Score": "0",
"body": "@Heslacher: No. I did not update any code in my question. I merely provided extra information to point out where the present answer is lacking."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T06:20:22.907",
"Id": "524766",
"Score": "0",
"body": "I would agree to a rollback of the title if that is absolutely necessary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T06:21:56.917",
"Id": "524768",
"Score": "0",
"body": "Oh, wow, sorry I just saw \"The suggested code given by Reinderien below, though it produced an output, did not actually capture the keyword.\" and didn't check what you actually added. Sorry for that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T11:17:42.607",
"Id": "524888",
"Score": "0",
"body": "Agreed........."
}
] |
[
{
"body": "<blockquote>\n<p>the search field for this site is dynamically generated</p>\n</blockquote>\n<p>That doesn't matter, since - if you bypass the UI - the form field name itself is not dynamic. Even if you were to keep using Selenium, it should be possible to write an element selector that does not need to rely on the dynamic attributes of the search field.</p>\n<blockquote>\n<p>Why the spider code doesn't work</p>\n</blockquote>\n<p>Non-working code is off-topic, so I'm ignoring that part.</p>\n<blockquote>\n<p>I suspect this website has a robust anti-bot infrastructure that can prevent spiders from operating properly.</p>\n</blockquote>\n<p>It actually doesn't (thankfully); and my prior difficulties were due to a silly error on my part omitting some form entries. This doesn't need to manipulate headers or cookies, or even fill in a fake user agent.</p>\n<p>So in terms of review, the usual: use Requests if you can; improve your type safety; avoid dictionaries for internal data.</p>\n<h2>Suggested</h2>\n<pre><code>from base64 import b64encode\nfrom datetime import date\nfrom typing import Iterable, ClassVar\n\nfrom attr import dataclass\nfrom bs4 import BeautifulSoup, SoupStrainer, Tag\nfrom requests import Session\n\n\n@dataclass\nclass Result:\n caption: str\n when: date\n path: str\n\n @classmethod\n def from_list_item(cls, item: Tag) -> 'Result':\n return cls(\n caption=item.a.text,\n path=item.a['href'],\n when=date.fromisoformat(item.find('span', recursive=False).text),\n )\n\n\nclass TsinghuaSite:\n subdoc: ClassVar[SoupStrainer] = SoupStrainer(name='ul', class_='search_list')\n\n def __init__(self):\n self.session = Session()\n\n def __enter__(self) -> 'TsinghuaSite':\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.session.close()\n\n def search(self, query: str) -> Iterable[Result]:\n with self.session.post(\n 'https://www.ctwx.tsinghua.edu.cn/search.jsp',\n params={'wbtreeid': 1001},\n data={\n 'lucenenewssearchkey': b64encode(query.encode()),\n '_lucenesearchtype': '1',\n 'searchScope': '0',\n 'x': '0',\n 'y': '0',\n },\n ) as resp:\n resp.raise_for_status()\n doc = BeautifulSoup(markup=resp.text, features='html.parser', parse_only=self.subdoc)\n\n for item in doc.find('ul', recursive=False).find_all('li', recursive=False):\n yield Result.from_list_item(item)\n\n\ndef main():\n with TsinghuaSite() as site:\n query = '尹至'\n results = tuple(site.search(query))\n\n assert any(query in r.caption for r in results)\n for result in results:\n print(result)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<h2>Output</h2>\n<pre><code>Result(caption='出土文献研究与保护中心2020年报', when=datetime.date(2021, 4, 9), path='info/1041/2615.htm')\nResult(caption='《战国秦汉文字与文献论稿》出版', when=datetime.date(2020, 7, 17), path='info/1012/1289.htm')\nResult(caption='【光明日报】清华简十年:古书重现与古史新探', when=datetime.date(2018, 12, 25), path='info/1072/1551.htm')\nResult(caption='《清華簡與古史探賾》出版', when=datetime.date(2018, 8, 30), path='info/1012/1436.htm')\nResult(caption='【出土文獻第九輯】鄔可晶:《尹至》“惟(肉哉)虐德暴(身童)亡典”句試解', when=datetime.date(2018, 5, 24), path='info/1073/1952.htm')\nResult(caption='【出土文獻第五輯】袁金平:從《尹至》篇“播”字的討論談文義對文字考釋的重要性', when=datetime.date(2018, 4, 26), path='info/1081/2378.htm')\nResult(caption='【出土文獻第五輯】袁金平:從《尹至》篇“播”字的討論談文義對文字考釋的重要性', when=datetime.date(2018, 4, 26), path='info/1081/2378.htm')\nResult(caption='【出土文獻第二輯】羅 琨:讀《尹至》“自夏徂亳”', when=datetime.date(2018, 4, 12), path='info/1081/2283.htm')\nResult(caption='【出土文獻第二輯】羅 琨:讀《尹至》“自夏徂亳”', when=datetime.date(2018, 4, 12), path='info/1081/2283.htm')\nResult(caption='《出土文獻》(第九輯)出版', when=datetime.date(2016, 10, 26), path='info/1012/1411.htm')\nResult(caption='《出土文獻研究》第十三輯出版', when=datetime.date(2015, 4, 8), path='info/1012/1396.htm')\nResult(caption='清華大學藏戰國竹簡第五冊相關研究論文', when=datetime.date(2015, 4, 8), path='info/1081/2215.htm')\nResult(caption='清華大學藏戰國竹簡第五冊相關研究論文', when=datetime.date(2015, 4, 8), path='info/1081/2215.htm')\nResult(caption='《出土文獻》(第五輯)出版', when=datetime.date(2014, 10, 13), path='info/1012/1393.htm')\nResult(caption='清华简入选《国家珍贵古籍名录》', when=datetime.date(2013, 12, 11), path='info/1072/1496.htm')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T20:18:45.680",
"Id": "524743",
"Score": "0",
"body": "Could you elaborate on what's wrong with using Selenium? Are you talking about it in general or about OP's case in particular?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T20:20:57.930",
"Id": "524744",
"Score": "1",
"body": "@KonstantinKostanzhoglo Thanks; I added some nuance. The answer is \"don't use Selenium certainly in this case, but also usually in general it should be avoided for scraping unless there are no alternatives\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T20:29:33.157",
"Id": "524745",
"Score": "0",
"body": "Can you do without it, particularly without web driver, when a task requires scrolling down the page, hovering over some elements or clicking buttons?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T20:41:26.590",
"Id": "524746",
"Score": "2",
"body": "@KonstantinKostanzhoglo That's kind of not the right question to ask. Instead, you should ask: \"Do I really need to worry about scrolling and clicking, or can I bypass the UI entirely?\" Bypassing the UI entirely is strongly preferred."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T05:02:27.010",
"Id": "524758",
"Score": "0",
"body": "@Reinderien I believe a lot of Rookie Coders like me lack the background knowledge to `bypass the UI`. And the docs don't seem to be of much help in this case. Any books you would recommend for us to read up further on this topic?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T05:11:38.030",
"Id": "524759",
"Score": "0",
"body": "\"Luckily for you, you suspect incorrectly.\" My suspicion stemmed from Scrapy invoking robots.txt from the site server. I do believe the site has code to disallow spiders. Maybe this is a side-effect of the \"overkill\" you mentioned."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T05:50:02.253",
"Id": "524761",
"Score": "0",
"body": "@Reinderien, Your suggested code did not work as expected. Please see the update to my question above."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T13:01:37.347",
"Id": "524806",
"Score": "0",
"body": "Interesting! I'll have to dig into this. Apologies for being hasty. I probably would have noticed the incorrect results if I were able to speak mandarin."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T19:22:57.327",
"Id": "524845",
"Score": "0",
"body": "\"Someone who actually cared about preventing scraping would add a captcha.\" I think adding captcha to each and every search query POSTed just to prevent scraping would only irritate normal users by making it super inconvenient to search. So I am more inclined to interpret the \"bug\" as a feature in this case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T21:00:48.940",
"Id": "524849",
"Score": "4",
"body": "@Sati I rewrote this answer. It turns out it actually is trivially easy to use requests after all; I had just forgotten to include some form fields. Regarding your question on reading - basically google site reverse engineering; there are many many guides on this e.g. on [medium](https://devavratvk.medium.com/how-to-reverse-engineer-websites-8dcfe35727d4)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T12:30:56.883",
"Id": "524891",
"Score": "0",
"body": "What are the form variables and how are they generated? How do you decide what values to use for each? (other than the query search key)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T13:24:53.050",
"Id": "524895",
"Score": "0",
"body": "https://chat.stackexchange.com/rooms/128255/scraping-a-dynamic-website-with-scrapy-or-requests-and-selenium"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-06T16:52:50.767",
"Id": "532487",
"Score": "0",
"body": "@Reinderien May i ask why session is on __init__ and not in __enter__ ? what is the difference? Thanks!!!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-06T16:57:30.117",
"Id": "532488",
"Score": "1",
"body": "@AlexDotis Best practice for Python class member variables is to set them on the instance in the `__init__`, rather than them first appearing in another function. So either the session would need to be constructed as an `Optional[]` equal to `None` and then written in `__enter__`, which is awkward; or just initialized in the constructor. One other difference is that if a caller instantiates `TsinghuaSite` but then does not use context management, the class will still work (whereas it would not if the session were constructed in `__enter__`)."
}
],
"meta_data": {
"CommentCount": "14",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T16:45:18.323",
"Id": "265668",
"ParentId": "265627",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "265668",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T09:33:20.043",
"Id": "265627",
"Score": "3",
"Tags": [
"python",
"web-scraping",
"beautifulsoup",
"selenium",
"scrapy"
],
"Title": "Scraping a dynamic website with Scrapy (or Requests) and Selenium"
}
|
265627
|
<p>File - DatabaseOperations.h</p>
<p>This file contain classes representing database operations for three different types of databases (relational, document based and graph based) like establishing connections, executing statements, and committing and closing the connections.</p>
<p>There are four abstract classes with one pure virtual functions each.</p>
<ol>
<li><p>The class <code>DatabaseConnection</code> contains pure virtual function <code>connect()</code> - this class is inherited by three concrete classes representing three different types of databases each one of those implement the <code>connect()</code> function.</p>
</li>
<li><p>The class <code>ExecuteStatements</code> contains one pure virtual function <code>Execute()</code> - this class is again inherited by three concrete classes representing three different types of databases and each one of those implement the <code>Execute()</code> function.</p>
</li>
<li><p>The class <code>CommitDisconnect</code> contains one pure virtual function <code>commit()</code> - this class is yet again inherited by three concrete classes representing three different types of databases and each one of those implement the <code>commit()</code> function.</p>
</li>
<li><p>The class <code>DatabaseOperation</code> which aggregates all the operations and contains three pure virtual functions, <code>connect</code>, <code>execute</code> and <code>commit</code>. All these three virtual functions are implemented in three respective classes.</p>
</li>
</ol>
<pre><code>#include <iostream>
#include <string>
/****************************************************************
* Connection
*****************************************************************/
class DatabaseConnection
{
public:
virtual void connect() = 0;
};
class RelationalDatabaseConnection : public DatabaseConnection
{
public:
void connect() override
{
std::cout << "Connection to RDBMS\n";
}
};
class DocumentDatabaseConnection : public DatabaseConnection
{
public:
void connect() override
{
std::cout << "Connection to Document DBMS\n";
}
};
class GraphDatabaseConnection : public DatabaseConnection
{
public:
void connect() override
{
std::cout << "Connection to Graph DBMS\n";
}
};
/****************************************************************
* Execute Statements
*****************************************************************/
class ExecuteStatements
{
public:
virtual void Execute() = 0;
};
class RelationalDatabaseExecute : public ExecuteStatements
{
public:
void Execute() override
{
std::cout << "Executing ANSI SQL\n";
}
};
class DocumentDatabaseExecute : public ExecuteStatements
{
public:
void Execute() override
{
std::cout << "Executing JSON/Parquet etc.\n";
}
};
class GraphDatabaseExecute : public ExecuteStatements
{
public:
void Execute() override
{
std::cout << "Creating Nodes and Edges\n";
}
};
/****************************************************************
* Commit & Disconnection
*****************************************************************/
class CommitDisconnect
{
public:
virtual void commit() = 0;
};
class RelationalCommitDisconnect : public CommitDisconnect
{
public:
void commit() override
{
std::cout << "Committing and closing RDBMS connection\n";
}
};
class DocumentCommitDisconnect : public CommitDisconnect
{
public:
void commit() override
{
std::cout << "Committing and closing Document DBMS connection\n";
}
};
class GraphCommitDisconnect : public CommitDisconnect
{
public:
void commit() override
{
std::cout << "Committing and closing Graph DBMS connection\n";
}
};
class DatabaseOperation
{
public:
virtual DatabaseConnection* connect() = 0;
virtual ExecuteStatements* execute() = 0;
virtual CommitDisconnect* commit() = 0;
};
class Relational : public DatabaseOperation
{
public:
DatabaseConnection* connect() override
{
return new RelationalDatabaseConnection();
}
ExecuteStatements* execute() override
{
return new RelationalDatabaseExecute();
}
CommitDisconnect* commit() override
{
return new RelationalCommitDisconnect();
}
};
class Document : public DatabaseOperation
{
public:
DatabaseConnection* connect() override
{
return new DocumentDatabaseConnection();
}
ExecuteStatements* execute() override
{
return new DocumentDatabaseExecute();
}
CommitDisconnect* commit() override
{
return new DocumentCommitDisconnect();
}
};
class Graph : public DatabaseOperation
{
public:
DatabaseConnection* connect() override
{
return new GraphDatabaseConnection();
}
ExecuteStatements* execute() override
{
return new GraphDatabaseExecute();
}
CommitDisconnect* commit() override
{
return new GraphCommitDisconnect();
}
};
</code></pre>
<p>file - main.cxx</p>
<pre><code>#include <iostream>
#include "DatabaseOperations.h"
int main()
{
int value = -1;
DatabaseOperation* operation = nullptr;
std::cout << "Relational: 1, Document: 2 and Graph: 3\n" << "Enter: ";
std::cin >> value;
switch (value)
{
case 1:
operation = new Relational();
break;
case 2:
operation = new Document();
break;
case 3:
operation = new Graph();
default:
break;
}
if (operation != nullptr)
{
operation->connect()->connect();
operation->execute()->Execute();
operation->commit()->commit();
}
return 0;
}
</code></pre>
<p><strong>Does the above code implements the Abstract Factory design pattern correctly?</strong></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T06:45:52.907",
"Id": "524772",
"Score": "0",
"body": "I have rolled back your last edit. Please don't change or add to the code in your question after you have received answers. See [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) Thank you."
}
] |
[
{
"body": "<blockquote>\n<p>Does the above code implements the Abstract Factory design pattern correctly?</p>\n</blockquote>\n<p>No.</p>\n<p>First, it is wildly overcomplicated. It seems ridiculous to need <em>four</em> different class hierarchies just to do a database transaction.</p>\n<p>Second, it is just plain bad C++, because it leaks memory all over the place. You use <code>new</code> like it’s going out of style (which it is), but you never once use <code>delete</code>.</p>\n<p>And third, and perhaps most importantly, you don’t actually make a factory. A factory is kinda important if you want to implement the abstract factory pattern.</p>\n<p>The abstract factory pattern only requires a single abstract base, and a single factory (which is a function). For your case, it might look something like this:</p>\n<pre><code>// database.hpp ================================================\n\n// abstract base\nclass database\n{\npublic:\n virtual ~database() = default;\n\n virtual auto connect() -> void = 0;\n virtual auto execute() -> void = 0;\n virtual auto commit() -> void = 0;\n};\n\n// factory\n[[nodiscard]] auto create_database(int id) -> std::unique_ptr<database>;\n\n// database.cpp ================================================\n\n#include "database.hpp"\n\n// concrete class\n//\n// actual implementation could be in another file, but declaration must be\n// visible to the factory function\nclass relational_database : public database\n{\npublic:\n auto connect() -> void override { std::cout << "Connection to RDBMS\\n"; }\n auto execute() -> void override { std::cout << "Executing ANSI SQL\\n"; }\n auto commit() -> void override { std::cout << "Committing and closing RDBMS connection\\n"; }\n};\n\n// and the same thing for the other database types\n\n// factory implementation\n[[nodiscard]] auto create_database(int id) -> std::unique_ptr<database>\n{\n switch (id)\n {\n case 1:\n return std::unique_ptr{new relational_database{}};\n case 2:\n return std::unique_ptr{new document_database{}};\n case 3:\n return std::unique_ptr{new graph_database{}};\n default:\n // should really throw an exception here, but whatevs\n return nullptr;\n }\n}\n\n// main.cpp ====================================================\n\n#include "database.hpp"\n\n// usage in main()\nauto main() -> int\n{\n std::cout << "Relational: 1, Document: 2 and Graph: 3\\n" << "Enter: ";\n\n auto input = -1;\n std::cin >> input;\n\n if (auto operation = create_database(input); operation != nullptr)\n {\n operation->connect();\n operation->execute();\n operation->commit();\n }\n}\n</code></pre>\n<p>To use the factory, you only need to be able to see the abstract base (<code>database</code>), and the factory (<code>create_database()</code>). All of the concrete classes could be hidden (though, of course, they need to be visible to the factory.</p>\n<p>Now as for some specific problems in the code…</p>\n<p>I don’t see any sense in breaking the connect, execute, and commit/close functions into <em>three</em> different class hierarchies. All of these functions are tightly connected: the mechanism for connecting to a database is intimately connected to the mechanism for closing that connection. It makes no sense at all for those two things to be in two entirely different classes. And to actually <em>do</em> anything with the database, you need the connection handle… so how are you supposed to get the connection handle opened in one class… over to the execute class… then finally over to the commit/close class. That whole mess is just bonkers.</p>\n<pre><code>class Relational : public DatabaseOperation\n{\npublic:\n DatabaseConnection* connect() override\n {\n return new RelationalDatabaseConnection();\n }\n</code></pre>\n<p>No. Just no. We don’t use raw pointers for ownership in C++ anymore. That was bad practice even back in C++98 (hence, <code>std::auto_ptr</code>). This is just plain unacceptable in modern C++.</p>\n<p>But the real problem here is that your entire interface is just terrible. Your base class looks like this:</p>\n<pre><code>class DatabaseOperation\n{\npublic:\n virtual DatabaseConnection* connect() = 0;\n virtual ExecuteStatements* execute() = 0;\n virtual CommitDisconnect* commit() = 0;\n};\n</code></pre>\n<p>In order to implement this interface <em>correctly</em> you would have to do something like this:</p>\n<pre><code>class CorrectDatabase : public DatabaseOperation\n{\n std::unique_ptr<DatabaseConnection> _connection;\n std::unique_ptr<ExecuteStatements> _statements;\n std::unique_ptr<CommitDisconnect> _commit;\n\npublic:\n // note we have to do all the allocations in the constructor, and hold\n // the pointers as data members\n CorrectDatabase()\n : _connection{new RelationalDatabaseConnection}\n , _statements{new RelationalDatabaseExecute}\n , _commit{new RelationalCommitDisconnect}\n {}\n\n DatabaseConnection* connect() override { return _connection.get(); }\n ExecuteStatements* execute() override { return _statements.get(); }\n CommitDisconnect* commit() override { return _commit.get(); }\n};\n</code></pre>\n<p>The way you tried to do it—allocating each class in the actual function—is not only clunky, it is wrong, because there is no possible way to do that without leaking memory.</p>\n<p>But while the code above is now <em>correct</em>, it’s still terrible. Because to use it, I have to do this:</p>\n<pre><code>auto db = CorrectDatabase{};\n\ndb.connect()->connect();\ndb.execute()->execute();\ndb.commit()->commit();\n</code></pre>\n<p>That’s just silly. Why not:</p>\n<pre><code>auto db = CorrectDatabase{};\n\ndb.connect();\ndb.execute();\ndb.commit();\n</code></pre>\n<p>That looks a lot more reasonable. And all you’d have to do is this:</p>\n<pre><code>class DatabaseOperation\n{\npublic:\n virtual void connect() = 0;\n virtual void execute() = 0;\n virtual void commit() = 0;\n};\n\nclass CorrectDatabase : public FixedDatabaseOperation\n{\n std::unique_ptr<DatabaseConnection> _connection;\n std::unique_ptr<ExecuteStatements> _statements;\n std::unique_ptr<CommitDisconnect> _commit;\n\npublic:\n // note we have to do all the allocations in the constructor, and hold\n // the pointers as data members\n CorrectDatabase()\n : _connection{new RelationalDatabaseConnection}\n , _statements{new RelationalDatabaseExecute}\n , _commit{new RelationalCommitDisconnect}\n {}\n\n void connect() override { return _connection->connect(); }\n void execute() override { return _statements->execute(); }\n void commit() override { return _commit->commit(); }\n};\n</code></pre>\n<p>But of course, this is still terrible design. What happens if someone forgets to call <code>connect()</code> before they call <code>execute()</code>? What happens if they forget to call <code>commit()</code> after?</p>\n<p>A good C++ interface is easy to use, and hard to use incorrectly. For example:</p>\n<pre><code>auto db = create_database(database_type); // the factory function\n\n// the database is *already* connected to when it was constructed, so you can\n// just go ahead and use it\n\ndb->execute(statement_1);\ndb->execute(statement_2);\ndb->execute(statement_3);\n\n// you can manually commit, if you want\n\ndb->commit(); // commits the transaction consisting of the previous 3 statements\n\n// more statements\n\ndb->execute(statement_4);\ndb->execute(statement_5);\n\n// you don't need to manually commit, the destructor will commit automatically\n\n// the destructor will also close the connection\n</code></pre>\n<p>There is no way to use that kind of interface wrong. That’s what good C++ looks like. (You could go even further and have RAII transaction objects, that will auto-commit in smaller chunks.)</p>\n<p>The bottom line:</p>\n<ol>\n<li>No, you have not implemented the factory pattern… mostly because you didn’t actually implement a factory.</li>\n<li>Your code is just plain wrong because it leaks memory all over the place.</li>\n<li>You have wildly over-engineered the whole thing, to the point of absurdity. I don’t even see how it could possibly work in practice. Try it with a <em>real</em> database, and see if you can actually get it to work.</li>\n</ol>\n<p>I would suggest throwing the whole thing out, and starting from scratch with a much simpler design. I would suggest starting with the absolute basic abstract factory pattern, if that’s what you’re interested in (an example of the absolute basic abstract factory is below). I would also suggest trying it out with a <em>real</em> database (just use SQLite as a test database, for example), to see what’s practical, because what seems to make sense in the abstract just won’t work in reality. (For example, how the hell are you going to handle the connection handle across <em>three</em> distinct class hierarchies?)</p>\n<p>Example of absolute basic abstract factory:</p>\n<pre><code>// thing.hpp ===================================================\n\n// the only header you need to include to use the factory\n\n#include <memory>\n#include <string_view>\n\n// abstract base\nclass thing_base\n{\npublic:\n virtual ~thing_base() = default;\n\n virtual void func() = 0;\n};\n\n// factory declaration\n[[nodiscard]] auto create_thing(std::string_view id) -> std::unique_ptr<thing_base>;\n\n// thing.cpp ===================================================\n\n#include "thing.hpp"\n\n#include "thing_concrete.hpp"\n\n// factory implementation\n[[nodiscard]] auto create_thing(std::string_view id) -> std::unique_ptr<thing_base>\n{\n if (id = "thing_concrete")\n return std::unique_ptr{new thing_concrete};\n // handle error for unknown ID\n}\n\n// thing_concrete.hpp ==========================================\n\n// example concrete type, can be a private header\n\n#include "thing.hpp"\n\nclass thing_concrete : public thing\n{\npublic:\n void func() override;\n};\n\n// thing_concrete.cpp ==========================================\n\n#include "thing_concrete.hpp"\n\nvoid thing_concrete::func() override\n{\n // ...\n}\n\n// main.cpp ====================================================\n\n// usage\n\n#include "thing.hpp"\n\nauto main() -> int\n{\n auto t = create_thing("thing_concrete");\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T07:30:02.663",
"Id": "524710",
"Score": "0",
"body": "\"_like it’s going out of style (which it is),_\" - I like what you did there!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T02:37:37.007",
"Id": "524755",
"Score": "0",
"body": "Thanks for pointing these problems out. However, I was just trying to implement the design pattern so did not care about the memory leaks, but now when I come to think of it a good design must take care of those as well. Much Thanks."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T18:58:20.737",
"Id": "265640",
"ParentId": "265629",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "265640",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T10:11:07.503",
"Id": "265629",
"Score": "0",
"Tags": [
"c++",
"c++11",
"design-patterns",
"abstract-factory"
],
"Title": "The Abstract Factory design pattern as a Database Operations program"
}
|
265629
|
<p>I have a model of Author which has books, awards and pricing as shown below (Not showing getters and setter just to avoid verbosity)</p>
<p>Author: Has books and prices for the books</p>
<pre><code>public class Author {
private long id;
private String name;
private Set<Book> books;
private Set<Price> prices;
}
</code></pre>
<p>Book: Can have optional awards</p>
<pre><code>public class Book {
private long id;
private String name;
private Set<Award> awards;
private long pages;
private String coverType;
}
</code></pre>
<p>Award</p>
<pre><code>public class Award {
private long id;
private String name;
}
</code></pre>
<p>Price - Price of book (Can have multiple prices for same book.. Not showing all fields just to avoid verbosity)</p>
<pre><code>public class Price {
private long id;
private long bookId;
private double price;
}
</code></pre>
<p>Now if I have an Author with Book and his prices I am trying to get/convert it to price stats which has following model</p>
<p>BookPriceStats - Has statkey consisting of pages, coverType, price and award(which may or may not be part of the key based on if a book has got award) and set of prices itself(I have shortened price here just for avoiding verbosity )</p>
<pre><code>public class BookPriceStats {
private Statkey bookStatKey;
Set<Price> prices;
}
public class Statkey {
private long pages;
private String coverType;
private double price;
private Award award;
}
</code></pre>
<p>I already have written logic to get booking price stats for books of author which are less than equal to certain price. This is working fine</p>
<pre><code> private static List<BookPriceStats> getBookPriceStats(Author author, double price) {
var prices =
author.getPrices().stream()
.filter(pr -> pr.getPrice() <= price)
.collect(Collectors.toSet());
var books = author.getBooks();
Map<Statkey, Set<Price>> statKeyPricingMap = new HashMap<>();
for (Price pr : prices) {
var pricingBooking =
books.stream()
.filter(book -> pr.getBookId() == book.getId())
.findFirst();
if (pricingBooking.isPresent()) {
var awards = pricingBooking.get().getAwards();
var statkey = new Statkey();
statkey.setPrice(pr.getPrice());
statkey.setPages(pricingBooking.get().getPages());
statkey.setCoverType(pricingBooking.get().getCoverType());
if (awards==null || awards.size()==0) {
statKeyPricingMap.computeIfAbsent(statkey, k -> new HashSet<>()).add(pr);
} else {
awards.stream()
.forEach(
a -> {
var statkeyWithAward = new Statkey();
statkeyWithAward.setPrice(pr.getPrice());
statkeyWithAward.setPages(pricingBooking.get().getPages());
statkeyWithAward.setCoverType(pricingBooking.get().getCoverType());
statkeyWithAward.setAward(a);
statKeyPricingMap.computeIfAbsent(statkeyWithAward, k -> new HashSet<>()).add(pr);
});
}
}
}
List<BookPriceStats> bookPriceStats = new ArrayList<>();
statKeyPricingMap.keySet().stream().forEach(s -> {
BookPriceStats bookingPriceStat = new BookPriceStats();
bookingPriceStat.setBookStatKey(s);
bookingPriceStat.setPrices(statKeyPricingMap.get(s));
bookPriceStats.add(bookingPriceStat);
});
return bookPriceStats;
}
</code></pre>
<p>As mentioned, the above logic works fine and I have tested it</p>
<pre><code> public static void main(String args[]){
Award booker = createAward(1, "Booker");
Award nobel = createAward(2, "Nobel");
Book book1 = createBook(1, "Book 1", Set.of(booker,nobel), 100, "Hard Cover");
Book book2 = createBook(2, "Book 2", new HashSet<>(), 150, "Paperback");
Book book3 = createBook(3, "Book 3", Set.of(booker), 100, "Hard Cover");
Price price1Book1 = createPrice(1, book1.getId(), 5D);
Price price2Book1 = createPrice(2, book1.getId(), 8D);
Price price3Book1 = createPrice(3, book1.getId(), 12D);
Price price1Book2 = createPrice(4, book2.getId(), 6D);
Price price2Book2 = createPrice(5, book2.getId(), 7D);
Price price3Book2 = createPrice(6, book2.getId(), 15D);
Price price1Book3 = createPrice(7, book3.getId(), 5D);
Author author = createAuthor(
1,"Author 1",
Set.of(book1, book2, book3),
Set.of(price1Book1, price2Book1, price3Book1, price1Book2, price2Book2, price3Book2, price1Book3));
System.out.println(getBookPriceStats(author, 7D));
}
</code></pre>
<p>Gives me the following correct output in the above example</p>
<pre><code>[BookPriceStats
{bookStatKey=Statkey{pages=100, coverType='Hard Cover', price=5.0, award=Award{name='Nobel'}},
prices=[Price{id=1, bookId=1, price=5.0}]},
BookPriceStats{
bookStatKey=Statkey{pages=100, coverType='Hard Cover', price=5.0, award=Award{name='Booker'}},
prices=[Price{id=1, bookId=1, price=5.0}, Price{id=7, bookId=3, price=5.0}]},
BookPriceStats{
bookStatKey=Statkey{pages=150, coverType='Paperback', price=6.0, award=null},
prices=[Price{id=4, bookId=2, price=6.0}]},
BookPriceStats{
bookStatKey=Statkey{pages=150, coverType='Paperback', price=7.0, award=null},
prices=[Price{id=5, bookId=2, price=7.0}]}]
</code></pre>
<p>My question here is if there is a better way to convert the object with just Java and no libraries using java streams and optionals in a better way.</p>
<p>Note I posted it here because someone in stackoverflow suggested this is the correct place.. There is also one question on stackoverflow.</p>
|
[] |
[
{
"body": "<p>Here are a few comments on your code:</p>\n<h1>Business objects</h1>\n<p>If the business objects' model is given, there is nothing to do here. Otherwise, just the way you have described it:</p>\n<blockquote>\n<p>Price - Price of book (Can have multiple prices for same book...</p>\n</blockquote>\n<p>Why is prices a field of Author? It makes way more sense to let each book have a list of its prices. That way, you do not need to iterate all books for every price to find their matching book.</p>\n<h1>Code style</h1>\n<p>All in all, I'd say your code style is consistent and mostly makes use of good variable names. However, there is one thing seems a bit off to me, and that is the use of <code>var</code>:</p>\n<p>At first, I thought you were using it on every variable, but you are actually not. Moreover, I think var is helpful whenever you are explicitly creating a new object:</p>\n<pre class=\"lang-java prettyprint-override\"><code>List<Integer> myList = new ArrayList<>();\n\nvar myList = new ArrayList<Integer>(); // Here its useful\n</code></pre>\n<p>However, it makes code harder to read if you use it on an expression, as then you have to mentally evaluate the expression if you want to know the data type you are dealing with:</p>\n<pre class=\"lang-java prettyprint-override\"><code>// Here, even if you just want to know the data type of prices, you first need to know author.getPrices()\n// returns a collection of Prices, and then see the stream isn't doing any mapping, and collecting to a Set\nvar prices =\n author.getPrices().stream()\n .filter(pr -> pr.getPrice() <= price)\n .collect(Collectors.toSet());\n\n// Here, at a glance, you can see prices is a Set of Prices\nSet<Price> prices =\n author.getPrices().stream()\n .filter(pr -> pr.getPrice() <= price)\n .collect(Collectors.toSet());\n</code></pre>\n<p>Also, I'd say using one letter variable names in lambdas makes them harder to read:</p>\n<pre class=\"lang-java prettyprint-override\"><code>// s is not a meaningful name\nstatKeyPricingMap.keySet().stream().forEach(s -> {\n BookPriceStats bookingPriceStat = new BookPriceStats();\n bookingPriceStat.setBookStatKey(s);\n bookingPriceStat.setPrices(statKeyPricingMap.get(s));\n bookPriceStats.add(bookingPriceStat);\n });\n\n// Better semantics on the variable name\nstatKeyPricingMap.keySet().stream()\n .forEach(statKey -> {\n BookPriceStats bookingPriceStat = new BookPriceStats();\n bookingPriceStat.setBookStatKey(statKey);\n bookingPriceStat.setPrices(statKeyPricingMap.get(statKey));\n bookPriceStats.add(bookingPriceStat);\n });\n</code></pre>\n<p>Extra note: if you have a map and want to iterate both keys and values, use entry sets, so that you do not need to query the map for values:</p>\n<pre class=\"lang-java prettyprint-override\"><code>statKeyPricingMap.entrtSet().stream()\n .forEach(statKeyPricingEntry -> {\n BookPriceStats bookingPriceStat = new BookPriceStats();\n bookingPriceStat.setBookStatKey(statKeyPricingEntry.getKey());\n bookingPriceStat.setPrices(statKeyPricingEntry.getValue());\n bookPriceStats.add(bookingPriceStat);\n });\n</code></pre>\n<p>I'd also say <code>getBookPriceStats</code> is not a good method name, as that implies the method is some sort of getter (or at least, it implies it does not have much logic to it). I'd say something along the lines of <code>createBookPriceStats</code> is more accurate to the actual behaviour of the method.</p>\n<h1>Stream usage</h1>\n<p>You are using <code>foreach</code> to do both mapping and collection. Instead of:</p>\n<pre class=\"lang-java prettyprint-override\"><code>statKeyPricingMap.keySet().stream()\n .forEach(statKey -> {\n BookPriceStats bookingPriceStat = new BookPriceStats();\n bookingPriceStat.setBookStatKey(statKey);\n bookingPriceStat.setPrices(statKeyPricingMap.get(statKey));\n bookPriceStats.add(bookingPriceStat);\n });\n</code></pre>\n<p>I'd use:</p>\n<pre class=\"lang-java prettyprint-override\"><code>statKeyPricingMap.keySet().stream()\n .map(statKey -> {\n BookPriceStats bookingPriceStat = new BookPriceStats();\n bookingPriceStat.setBookStatKey(statKey);\n bookingPriceStat.setPrices(statKeyPricingMap.get(statKey));\n })\n .collect(Collector.toList());\n</code></pre>\n<h1>Algorithm</h1>\n<p>Regarding the algorithm, and if we do not change the business objects' model, the way I'd go about it is:</p>\n<p>First, have either extract the logic to create a <code>StatKey</code> to another method, or to the <code>StatKey</code> itself, to remove logic from <code>getBookPriceStats</code>.</p>\n<p>As a rule of thumb, if you are using a lambda with multiple expressions inside it, you are doing something wrong. It would probably be more readable to extract logic to another method.</p>\n<p>Also, I'd use a map as such:</p>\n<pre class=\"lang-java prettyprint-override\"><code>Map<Long, Set<Price>> bookIdToPricesMap\n</code></pre>\n<p>So that you just iterate over the whole prices set once.</p>\n<p>Then, just by iterating over the books set, you already have all the information you need to create the list of <code>BookPriceStats</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T06:32:57.690",
"Id": "524769",
"Score": "0",
"body": "Upvote + Marked as answer. Thank you so much for taking time to review and giving feedback."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T18:47:45.240",
"Id": "265638",
"ParentId": "265631",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "265638",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T11:39:54.763",
"Id": "265631",
"Score": "2",
"Tags": [
"java"
],
"Title": "Efficient usage of Java Stream API to convert one object to another"
}
|
265631
|
<p>Could someone say if this kind of contextual binding for plugins has a point?</p>
<pre class="lang-csharp prettyprint-override"><code>
//it is a AbstractModule code
public abstract class AbstractModule : Module
{
private ContainerBuilder _containerBuilder;
protected AbstractBinderBehavior BinderBehavior { get; init; }
public abstract void Binder();
protected sealed override void Load(ContainerBuilder builder)
{
_containerBuilder = builder;
Binder();
}
public void Bind<T, K>(Scope scope = Scope.Transient) where K : class, T
=> BinderBehavior.Bind<T, K>(scope, _containerBuilder);
public void Bind<T>(Scope scope) where T : class
=> BinderBehavior.Bind<T>(scope, _containerBuilder);
public void BindGenerics(Type from, Type to)
=> BinderBehavior.BindGenerics(from, to, _containerBuilder);
}
</code></pre>
<p>the whole source with the test is here:
<strong><a href="https://github.com/musselek/AutofacCallerAssemblyContextualBinding" rel="nofollow noreferrer">https://github.com/musselek/AutofacCallerAssemblyContextualBinding</a></strong></p>
<p>Thank you in advance</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T13:07:11.457",
"Id": "524679",
"Score": "1",
"body": "Welcome to the Code Review Community. Are you the author of the code? We can only review code by the author of the code. The more code you post in the question the better the answers will be. We can only review the code in the question itself. Please read [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T13:21:24.630",
"Id": "524682",
"Score": "0",
"body": "Hi\nYes - I'm the author\nand because of the fact it is not a simple method I've added the link to the github"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T12:33:01.510",
"Id": "265632",
"Score": "0",
"Tags": [
"c#",
"dependency-injection",
"plugin",
"autofac"
],
"Title": "Contextual binding based on Autafac and caller assembly"
}
|
265632
|
<p>I'm working on a card game using Amethyst's Specs crate and am fairly new to Rust (therefore I'm learning through the fight with the compiler). My first <code>System</code> is to deal the cards to each player. I have:</p>
<ul>
<li>a <code>Card</code> type that has <code>Copy</code> semantics</li>
<li>a <code>Cards</code> component that represents a set of <code>Card</code> the players or deck are holding</li>
</ul>
<pre><code>struct Deal {
deck: Entity,
players: Vec<Entity>,
}
impl<'a> System<'a> for Deal {
type SystemData = WriteStorage<'a, Cards>;
fn run(&mut self, mut cards: Self::SystemData) {
// code smell - can't use `get_mut`
let mut deck = cards.get(self.deck).unwrap().clone();
deck.shuffle();
for player in self.players.iter().cycle() {
let player_cards = cards.get_mut(*player).unwrap();
if let Some(card) = deck.take_top() {
player_cards.add(card);
} else {
break;
}
}
// code smell
let mut deck = cards.get_mut(self.deck).unwrap();
deck.clear();
}
}
</code></pre>
<p>The compiler complains that I can't take a mutable reference to the <code>deck</code>'s cards because the <code>player_cards</code> is a mutable one (or vice versa).</p>
<p>As noted in the code above, I clone the <code>Cards</code> for the <code>deck</code>, shuffle that, deal to the mutable players' and then empty the deck.</p>
<p>I would have expected that I could get a mutable reference to the deck up front, shuffle that and remove it.</p>
<p>Is there something simple I am missing?</p>
<p>Aside, I do not know if it is convention to pass entities on the system struct it self or not. Is that wrong?</p>
|
[] |
[
{
"body": "<p>I'm not familiar with ECS or some of the types you used in your code, and to be honest I don't think I quite understand your code as it seems incomplete, but this seems like something that could be fixed by using the <a href=\"https://doc.rust-lang.org/std/rc/struct.Rc.html\" rel=\"nofollow noreferrer\"><code>Rc</code></a> and <a href=\"https://doc.rust-lang.org/std/cell/struct.RefCell.html\" rel=\"nofollow noreferrer\"><code>RefCell</code></a> types. Instead of having <code>cards</code> as having type <code>Self::SystemData</code>, I think you'd want it to be <code>Rc<RefCell<Self::SystemData>></code> instead, which should allow you to create multiple mutable references to it by using the <code>Rc::clone</code> function.</p>\n<p>Whilst using <code>Rc</code> and <code>RefCell</code>, you'd still need to make sure that you stick to Rust's borrowing semantics though, as this will then be runtime-checked instead of compile-time checked. <a href=\"https://doc.rust-lang.org/book/ch15-05-interior-mutability.html#having-multiple-owners-of-mutable-data-by-combining-rct-and-refcellt\" rel=\"nofollow noreferrer\">This section of the book</a> has more information about these types and how they might be used.</p>\n<p>I don't have your full code, so I can't check if this is correct, but I think you should end up with something similar to:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>use std::{cell::RefCell, rc::Rc};\n\nstruct Deal {\n deck: Entity,\n players: Vec<Entity>,\n}\n\nimpl<'a> System<'a> for Deal {\n type SystemData = WriteStorage<'a, Cards>;\n\n fn run(&mut self, mut cards: Rc<RefCell<Self::SystemData>>) {\n let mut deck = Rc::clone(&cards).get(self.deck).unwrap().clone();\n deck.shuffle();\n\n for player in self.players.iter().cycle() {\n let player_cards = Rc::clone(&cards).get_mut(*player).unwrap();\n if let Some(card) = deck.take_top() {\n player_cards.add(card);\n } else {\n break;\n }\n }\n\n let mut deck = Rc::clone(&cards).get(self.deck).unwrap().clone();\n deck.clear(); \n }\n}\n</code></pre>\n<p>After switching to using <code>Rc</code> and <code>RefCell</code> in some cases, you might even find that you're able to do without using explicit lifetime annotations, but YMMV.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-09T10:21:16.063",
"Id": "268806",
"ParentId": "265633",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T12:58:22.183",
"Id": "265633",
"Score": "0",
"Tags": [
"game",
"rust"
],
"Title": "Avoiding cloning references in a Specs system"
}
|
265633
|
<p>I want to make the code below prettier but I don't know what to change and how to change. I know that the controller should be easy, delegating actions related to models or to services or something else.</p>
<p>The task the code below solves is to authenticate a client with 2 factory authentication. If a client has 2fa enabled, then additional field <code>2faCode</code> is required, otherwise only email and password are required. I really don't like so many <code>if</code>s for such a simple task. The code should be easy and readable.</p>
<pre><code>/**
* Get a JWT via given credentials.
*
* @param LoginUserRequest $request
* @return JsonResponse
*/
public function login(LoginUserRequest $request): JsonResponse
{
$data = $request->validated();
if (!$token = auth()->attempt(['email' => $data['email'], 'password' => $data['password']])) {
return response()->json(['error' => 'Unauthorized. Credentials are wrong'], 401);
}
$user = auth()->user();
if (!$user->has2fa) {
return $this->respondWithToken($token);
}
if (!isset($data['2faCode'])) {
return response()->json(['error' => 'Unauthorized. 2faCode is not specified but it is required'], 401);
}
$checkResult = $this->googleAuthenticator->verifyCode(env('GOOGLE_AUTHENTICATOR_SECRET'), $data['2faCode'], 10);
if ($checkResult) {
return $this->respondWithToken($token);
} else {
return response()->json(['error' => 'Unauthorized. Wrong 2faCode.'], 401);
}}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T14:57:36.407",
"Id": "524692",
"Score": "2",
"body": "Welcome to Code Review! I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Please check that I haven't misrepresented your code, and correct it if I have."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T23:40:05.340",
"Id": "524701",
"Score": "0",
"body": "@sko `$checkResult` is a single-use variable, right? I'd not declare it at all if you aren't going to use it more than once. (same with `$user`)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T05:37:31.677",
"Id": "525133",
"Score": "0",
"body": "Although it is not related to the main question, you should not use `env('GOOGLE_AUTHENTICATOR_SECRET')` in your code. You should use `config('GOOGLE_AUTHENTICATOR_SECRET')` as it will be cached and is more optimized."
}
] |
[
{
"body": "<p>I actually think you are doing it ok. You made the choice to test a number of conditions in a logical order and <strong>return early</strong> in case of failure. Thus each test takes only a few lines of code and is clearly delimited. The control flow is easy to grasp.</p>\n<p>You could have done it differently using <strong>nested ifs</strong> and testing for <strong>positive conditions</strong> like this:</p>\n<pre><code>{\n $data = $request->validated();\n if ($token = auth()->attempt(['email' => $data['email'], 'password' => $data['password']])) {\n $user = auth()->user();\n if (!$user->has2fa) {\n return $this->respondWithToken($token);\n }\n if (isset($data['2faCode'])) {\n $checkResult = $this->googleAuthenticator->verifyCode(env('GOOGLE_AUTHENTICATOR_SECRET'), $data['2faCode'], 10);\n if ($checkResult) {\n return $this->respondWithToken($token);\n } else {\n return response()->json(['error' => 'Unauthorized. Wrong 2faCode.'], 401);\n }\n } else {\n return response()->json(['error' => 'Unauthorized. 2faCode is not specified but it is required'], 401);\n }\n } else {\n return response()->json(['error' => 'Unauthorized. Credentials are wrong'], 401);\n }\n\n}\n</code></pre>\n<p>Pardon the poor transposition.\nYou get the point: this approach is much less comprehensible because the whole context has to be analyzed.</p>\n<p>Now:</p>\n<pre><code>if (!$user->has2fa) {\n return $this->respondWithToken($token);\n}\n</code></pre>\n<p>It's possible I misunderstood but did you mean:</p>\n<pre><code>if ($user->has2fa) {\n return $this->respondWithToken($token);\n}\n</code></pre>\n<p>If that is the case, and barring any possible misunderstanding on my end then it may be justified to combine the two ifs in a nested block. Possibly like this:</p>\n<pre><code>if (!$user->has2fa) {\n if (!isset($data['2faCode'])) {\n return response()->json(['error' => 'Unauthorized. 2faCode is not specified but it is required'], 401);\n }\n return $this->respondWithToken($token);\n}\n</code></pre>\n<hr />\n<p>One simple thing you could also have done is simply add <strong>line spacing</strong> between your blocks.</p>\n<p>There is lots of ifs you say, in fact there are just four and if you are going to test disparate conditions there are not many better ways. A switch/case block is a possibility with some adjustments but I don't see the added value here. You would end up with a bigger control block like the counter-example above.</p>\n<p>To sum up I think your code is ok as-is, it's about 15 lines of effective code and not really screaming for a massive refactor.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T08:58:28.673",
"Id": "524715",
"Score": "0",
"body": "The main problem is where that code is written and what problem that code solves. That code is written inside of controller method and that code is related to business logic. Controllers should not be fat. I think about creating an object which will do authentication and 2 factory authentication. This object will provide high-level interface."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T19:25:47.697",
"Id": "265641",
"ParentId": "265635",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T14:44:42.563",
"Id": "265635",
"Score": "1",
"Tags": [
"php",
"authentication",
"laravel"
],
"Title": "Login using two-factor authentication"
}
|
265635
|
<p>I'm kinda new to C# and Unity, coming from PHP/Python background.<br />
So I'm curious, if this CubeController script <strong>can be considered a bad code</strong>.<br />
I mean the coding style, performance, & overall Unity C# best practices.</p>
<p>The code itself is a simple CubeController script.<br />
It adds jumping mechanic, and constantly moves the cube forward.
As simple as that.</p>
<p>Also, instead of checking if a cube is grounded with a tags, I'm using a check by layer id.<br />
As I know, it's more performant.</p>
<p>DG.Tweening is a <a href="http://dotween.demigiant.com/" rel="nofollow noreferrer">DOTween</a> plugin for Unity.</p>
<pre><code>using UnityEditor;
using UnityEngine;
using DG.Tweening;
/// <summary>
/// Attribute to select a single layer.
/// </summary>
public class LayerAttribute : PropertyAttribute
{}
[CustomPropertyDrawer(typeof(LayerAttribute))]
class LayerAttributeEditor : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
property.intValue = EditorGUI.LayerField(position, label, property.intValue);
}
}
[RequireComponent(typeof(Rigidbody))]
public class CubeController : MonoBehaviour
{
[SerializeField] private float moveSpeed = 15f; // cube movement speed, applied to Rigidbody.MovePosition
[SerializeField] private float jumpForce = 30f; // cube jump force, applied to Rigidbody.AddForce
[SerializeField] private float fallMultiplier = 10f; // determinates fall gravity multiplier (how fast a cube will fall after jump)
[SerializeField, Layer] int groundLayer = 0; // ground layer selector (instead of tags? :3)
[SerializeField]
[Range(1, 360)]
private int spinAnimationAngle = 180; // (DG.Tweening) DORotate target angle
[SerializeField]
[Range(0.1f, 1.0f)]
private float spinAnimationTime = 0.75f; // (DG.Tweening) DORotate target animation time
private Rigidbody _rb;
private bool _doJump = false; // used to transfer input from Update into FixedUpdate
private bool _isJumping = false; // determinates if a cube is currently jumping or not
void Awake()
{
_rb = transform.GetComponent <Rigidbody>();
}
void Update() {
// Unity built-in Input Manager
if(Input.GetButtonDown("Jump") && !_isJumping) {
Jump();
}
}
// FixedUpdate is called once per Fixed Timestep (50 times/second default)
void FixedUpdate()
{
// move the cube forward
Vector3 moveVector = Vector3.forward * moveSpeed * Time.deltaTime;
_rb.MovePosition(transform.position + moveVector);
// check for a jump input
if(_doJump) {
_rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
_doJump = false;
}
// Gravity fall multiplier
_rb.velocity += Vector3.up * Physics.gravity.y * (fallMultiplier - 1) * Time.deltaTime;
}
void OnCollisionEnter(Collision collision) {
// CompareTag is alot performant, that equality-operator or TryGetComponent
// but still, it is much faster to use layers :3
// (if you interested in such micro optimization)
if(collision.gameObject.layer == groundLayer) {
if(Input.GetButton("Jump") && _isJumping) {
// Bunny Hop
Jump();
} else if(_isJumping) {
_isJumping = false;
}
}
}
void Jump() {
_doJump = true; // set flag for FixedUpdate
_isJumping = true; // set jump status
// some cool DG stuff :]
transform.DOComplete();
transform.DOShakeScale(.5f, .5f, 3, 30);
transform.DORotate(new Vector3(spinAnimationAngle, 0, 0), spinAnimationTime, RotateMode.LocalAxisAdd).SetRelative(true);
}
}
</code></pre>
<p>Any suggestions on improving it?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T14:50:56.963",
"Id": "265636",
"Score": "0",
"Tags": [
"c#",
"performance",
"game",
"unity3d"
],
"Title": "Unity C# CubeController script (jumping & moving the cube)"
}
|
265636
|
<p>Im currently working with discord with Python 3.9.6 where I am trying to create a embed based on how much text I have.</p>
<p>According to discord:</p>
<pre><code>+-------------+------------------------+
| Field | Limit |
+-------------+------------------------+
| title | 256 characters |
| description | 4096 characters* |
| fields | Up to 25 field objects |
| field.name | 256 characters |
| field.value | 1024 characters |
| footer.text | 2048 characters |
| author.name | 256 characters |
+-------------+------------------------+
</code></pre>
<p>and what I am trying to achieve is that I want to split into new embed if we reach 1000 characters, as we already know we cannot reach more than 1020 characters for one field.</p>
<p>What I have done so far is:</p>
<pre><code>from discord_webhook import DiscordEmbed, DiscordWebhook
# payload = {
# "hello": 1,
# "world": 2,
# "test": None,
# "yes": 4
# }
payload = {
'Hello, everyone! This is the LONGEST TEXT EVER! I was inspired by the various other "longest texts ever" on the internet, and I wanted to make my own.': None,
'The first time, I didnt save it. The second time, the Neocities editor crashed. Now Im writing this in Notepad,': 50,
'Waffles is a funny word. Theres a Teen Titans Go episode called "Waffles" where the word "Waffles" is said a hundred-something': 10,
' surprised me when I saw the episode for the first time. I speak Pig Latin with my sister sometimes. Its pretty fun. I like speaking i': None,
'f it ever does, twill be pretty funny. By the way is a word I invented recently, and its a contraction of it will. I really hope it gains popularity in the near future, because Itll is too boring. Nobody likes boring. This is nowhere near being the longest text ever, but eventually it will be! I mig': 10,
'No, Im not. I should probably get some sleep. Goodnight! Hello, Im back again. I basically have only two interests nowaday': 20,
' I would like to have a fursuit, go to furry conventions, all that stuff. But for now I can only dream of that. Sorry you had to deal with me talking about furries, but Im honestly very desperate for this to be the longest text ever. Last night I': 13
}
embed = DiscordEmbed(color=8149447)
stock = sum(v for v in payload.values() if v)
texts = [f"{k} - ({v})" if v else k for k, v in payload.items()]
character_count, i = 0, 0
for j, item in enumerate(texts):
if len(item) + character_count > 900:
embed.add_embed_field(
name="Text",
value="\n".join(texts[i:j])
)
character_count, i = len(item), j
else:
character_count += len(item)
if character_count:
embed.add_embed_field(
name="Text",
value="\n".join(texts[i:])
)
if stock:
embed.add_embed_field(
name="Total Stock",
value=stock
)
# Insert ur own discord URL (The URL here is not real)
webhook = DiscordWebhook(
url="https://discord.com/api/webhooks/788360382141825054/m_Et9RT5f9AReTQuVuJJ4Qk60ETEe1KcezBRuGc2HlWyXdTgKpOjUI5u39NGvoFhfsy8"
)
webhook.add_embed(embed)
response = webhook.execute()
</code></pre>
<p>There is different scenario I am trying to achieve:</p>
<ol>
<li>If we have a value in the key, then I want to sum it up to a "stock" variable and also add <code>"- (n)</code>" in the text <code>texts = [f"{k} - ({v})" if v else k for k, v in payload.items()]</code></li>
<li>I would like to print out the whole stock if we have a stock value (e.g. if I set all the values as <code>None</code>that could be a scenario</li>
<li>If we reach more than 1000 characters of a embed field, we should create a new field embed and continue to print out the key-values that have not been embeded yet.</li>
</ol>
<p>Looking forward learn new stuff!</p>
<p>How I would like to have it: See where it does a break on every end of the text
<a href="https://i.stack.imgur.com/RkXhB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RkXhB.png" alt="How I would like to have it" /></a></p>
|
[] |
[
{
"body": "<p>Overall your algorithm is pretty reasonable, but it needs to be pulled out into a function, and type hints will help. Your input type is a sequence since it needs to be indexed, and your output is an iterable.</p>\n<p>Rather than having an <code>if</code> statement that increments or assigns to your count, conditionally assign 0 to your count and unconditionally increment.</p>\n<p>If your maximum field length is 1024, why are you splitting at 900?</p>\n<p>Your colour constant should be represented in hex, i.e. <code>0x7C59C7</code>, and not decimal.</p>\n<p>Move your calculation for total stock closer to where it's used.</p>\n<h2>Suggested</h2>\n<pre class=\"lang-py prettyprint-override\"><code>from typing import Optional, Dict, Iterable, Sequence\n\nfrom discord_webhook import DiscordEmbed, DiscordWebhook\n\n\ndef group_by_len(items: Sequence[str], max_len: int = 1024) -> Iterable[str]:\n start, count = 0, 0\n\n for end, item in enumerate(items):\n n = len(item)\n if n + count >= max_len:\n yield '\\n'.join(items[start: end])\n count = 0\n start = end\n count += n\n\n if count > 0:\n yield '\\n'.join(items[start:])\n\npayload: Dict[str, Optional[int]] = { ... }\n\nembed = DiscordEmbed(color=0x7C59C7)\ntexts = [f"{k} - ({v})" if v else k for k, v in payload.items()]\n\nfor paragraph in group_by_len(texts):\n embed.add_embed_field(name="Text", value=paragraph)\n\nstock = sum(v for v in payload.values() if v)\nif stock > 0:\n embed.add_embed_field(name="Total Stock", value=stock)\n\n# Insert your own discord URL (The URL here is not real)\nwebhook = DiscordWebhook(\n url="https://discord.com/api/webhooks/788360382141825054"\n "/m_Et9RT5f9AReTQuVuJJ4Qk60ETEe1KcezBRuGc2HlWyXdTgKpOjUI5u39NGvoFhfsy8"\n)\nwebhook.add_embed(embed)\nresponse = webhook.execute()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T16:36:36.560",
"Id": "524729",
"Score": "0",
"body": "Hi! I was almost pretty sure that I did a really great job but as usual you chock me again. I have tried to run your suggested script and I got an error saying `yield '\\n'.join(items[start: end]), TypeError: 'generator' object is not subscriptable`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T16:37:54.313",
"Id": "524730",
"Score": "1",
"body": "My mistake; please try with the edit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T17:10:55.667",
"Id": "524732",
"Score": "0",
"body": "Works now! Its actually really nice! I have again no words to say than thank you. I would not have came up with this solution but its really nice and less complicated than mine. I will try to understand more the group_by_len as I dont fully get it 100% but with some debugging that should help me out. Thanks once again!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T15:59:30.473",
"Id": "265666",
"ParentId": "265637",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "265666",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T17:17:29.340",
"Id": "265637",
"Score": "2",
"Tags": [
"python-3.x",
"discord"
],
"Title": "Split message when too many character"
}
|
265637
|
<p>A quick and dirty line-based approach for detecting duplicated text blocks.</p>
<p>Did not find any references as to what (deterministic) algorithms are there for detecting duplicated text blocks, so went with the most straightforward way: take the biggest possible text block starting from fist line + 1 to the bottom, keep reducing the block size, and when it's size is less than half of the entire document try to compare the block with the other parts of the document, and then keep reducing the block size by one line and repeat the scanning recursively.</p>
<p>Questions: is there a better/faster and more efficient way? does this approach make sense? how and when would it fail? what I might have missed?</p>
<pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python3
# Remove multiline duplicated blocks from text files
import argparse
import os
import sys
from pathlib import Path
def remove_duplicate_blocks(lines):
num_lines = len(lines)
for idx_start in range(num_lines):
idx_end = num_lines
for idx in range(idx_end, -1, -1):
if idx_start < idx:
dup_candidate_block = lines[idx_start + 1: idx]
len_dup_block = len(dup_candidate_block)
if len_dup_block and len_dup_block < int(num_lines / 2):
for scan_idx in range(idx):
if ((idx_start + 1) > scan_idx
and dup_candidate_block == lines[scan_idx: scan_idx + len_dup_block]):
if config.verbose:
print(f'FOUND DUPLICATE: {dup_candidate_block}')
lines[idx_start + 1: idx] = []
return remove_duplicate_blocks(lines)
return lines
def traverse_tree(conf):
for f in Path(conf.dir).glob(conf.glob):
print(f)
lines = f.open('r', encoding='utf-8').readlines()
clean_lines = remove_duplicate_blocks(lines)
print(clean_lines)
if not conf.dry_run:
with f.open('w', encoding='utf-8') as fo:
fo.write(''.join(clean_lines))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='''DESCRIPTION:
Find and remove multiline duplicated text blocks ''',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog='''USAGE:
{0} -d [root_dir] -g [glob_pattern]
'''.format(os.path.basename(sys.argv[0])))
parser.add_argument('--dir', '-d',
help='folder to search in; by default current folder',
default='.')
parser.add_argument('--glob', '-g',
help='glob pattern, i.e. *.html',
default="*.*")
parser.add_argument('--verbose', '-v',
action='store_true',
help="Print duplicated blocks",
default=False)
parser.add_argument('--dry-run', '-dr',
action='store_true',
help="don't change anything; only print result to stdout",
default=False)
config = parser.parse_args(sys.argv[1:])
traverse_tree(config)
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T20:33:58.233",
"Id": "524698",
"Score": "8",
"body": "It would be helpful to add some test cases. So far it looks like an instance of a [longest repeated substring](https://en.wikipedia.org/wiki/Longest_repeated_substring_problem) problem; perhaps a [non-overlapping](https://www.geeksforgeeks.org/longest-repeating-and-non-overlapping-substring/) variation."
}
] |
[
{
"body": "<p>This approach will work, but be slow. You will be comparing something like N**2.5 lines in the worst case, which is quite bad. You should be running in something more like linear time.</p>\n<p>The biggest problem I see here is that your problem is not well-defined, so first clarify your problem to yourself. What do you want to count as "duplicate text"? Do you want to find the biggest duplicate block? All blocks above a certain size? Do you care if you split a large block into two, or is it important to have the longest possible as one unit? Do you care about matching duplicated text generally or only matching lines? Depending on your problem, the fastest way to do it varies radically.</p>\n<p>Then, reduce the number of line comparisons for whatever your problem is. I suggest learning about longest repeated substring (as suggested), and maybe suffix trees.</p>\n<p>If you want to squeeze the last ounce of performance out of something line-based, you can try pre-processing by hashing the lines into integers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T13:55:29.157",
"Id": "526452",
"Score": "0",
"body": "The use case is to detect and remove repeating blocks of text, starting with biggest multiline blocks and then down to single lines. To be more specific, I had a bunch of vCard files which had certain fields duplicated and repeated multiple times, sometimes multilines, so I had to make sure that I first remove the bigger blocks before starting removing single line dupes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T00:06:53.043",
"Id": "526483",
"Score": "0",
"body": "Yes, I understand the intuition already. The problem isn't that you're communicating poorly, if that's you're using fuzzy thinking (which is fine most of the time, but not for algorithms). Try turning it into a formally defined problem, and you'll have better lucking designing or finding an algorithm to fit it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T09:35:08.477",
"Id": "526497",
"Score": "0",
"body": "That's exactly why there was the need to ask the question — I was aware I didn't have a clear understanding of how to approach the task and went with a sloppy fuzzy solution instead; the intent was to find reference points, and the hint regarding the `longest repeated substring ` was exactly what I was looking for."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T09:37:41.630",
"Id": "266472",
"ParentId": "265639",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "266472",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-02T18:53:37.190",
"Id": "265639",
"Score": "1",
"Tags": [
"python",
"algorithm"
],
"Title": "Remove duplicated multiline blocks in text"
}
|
265639
|
<p>I am learning data structures and below is my implementation of a stack in JavaScript. I didn't want to use built in functions for an array because in JavaScript that would be too easy, so I made my own.</p>
<pre><code>class Stack {
constructor(data=null) {
this.items = [data]
this.length = 0
}
push(data) {
this.items[this.length] = data
this.length++
}
pop() {
delete this.items[this.length-1]
this.length--
}
printStack() {
for(let i = 0; i<this.length; i++)
console.log(this.items[i])
}
isEmpty() {
return (this.length) > 0 ? false : true
}
}
let myStack = new Stack();
myStack.push(123)
myStack.push(456)
myStack.pop()
myStack.printStack()
console.log(myStack.isEmpty())
</code></pre>
|
[] |
[
{
"body": "<p>You have a bug in your constructor:</p>\n<pre><code>constructor(data=null) {\n this.items = [data]\n this.length = 0\n }\n</code></pre>\n<p>If you pass an item and then push to the stack, you lose the first item:</p>\n<pre><code>let myStack = new Stack("123");\nmyStack.push("456")\n// myStack.items = ["456"]\n</code></pre>\n<p>You need to make sure that you initialize length to 1 if an item is passed in. The simplest way to do that is something like this:</p>\n<pre><code>constructor(datum = null) {\n if (datum !== null) {\n this.items = [datum];\n this.length = 1;\n } else {\n this.items = [];\n this.length = 0;\n }\n}\n</code></pre>\n<p>Some people like to prefix private fields with <code>_</code> to show that they aren't supposed to be used externally. You could consider using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields\" rel=\"noreferrer\">private names</a> but they aren't supported everywhere.</p>\n<p>Your <code>pop</code> function should return the element that was popped from the stack to be useful.</p>\n<p>You can also simplify <code>isEmpty</code>:</p>\n<pre><code>isEmpty() {\n return this.length === 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T06:41:09.480",
"Id": "265649",
"ParentId": "265646",
"Score": "6"
}
},
{
"body": "<h2>Encapsulate</h2>\n<p>The object <code>Stack</code> should protect its state as it is easy to add and remove items via the exposed referenced <code>Stack.items</code>, or if <code>Stack.length</code> were to be set some erroneous value eg <code>myStack.length = 1.001</code></p>\n<p>You can never guarantee your object will act like a stack if you can not trust its state.</p>\n<h2>Review</h2>\n<p>Most points are already covered by accepted answer, however there are some additional points.</p>\n<ul>\n<li><p>Avoid using <code>null</code></p>\n</li>\n<li><p><code>Stack.pop</code> does not return anything? What is the point of a stack that does not provide access to the top item.</p>\n</li>\n<li><p>Use getters and setters rather than give direct access to state critical properties.</p>\n</li>\n<li><p>Rather than <code>Stack.printStack</code>, use a getter to get a copy of the stack that you can then use to log to the console or anything else.</p>\n</li>\n<li><p>Spaces between operators. eg <code>[this.length - 1]</code> not <code>[this.length-1]</code></p>\n</li>\n<li><p>Always delimit code blocks. <code>for( ; ; ) /* code */</code> should be <code>for( ; ; ) { /* code */ }</code></p>\n</li>\n<li><p>Avoid redundant or long form code.</p>\n<p>You had <code>delete this.items[this.length-1]; this.length--</code> could have been a single line <code>delete this.items[--this.length]</code></p>\n</li>\n</ul>\n<h2>Rewrite</h2>\n<p>The rewrite creates a stack using a factory function. The Stack is frozen to ensure it's state can be trusted.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function Stack(...items) {\n const stack = items;\n return Object.freeze({\n push(...items) { stack.push(...items) },\n pop() { return stack.pop() },\n clear() { stack.length = 0 },\n get size() { return stack.length },\n get isEmpty() { return !stack.length },\n get items() { return [...stack] },\n }); \n}\n\n\n// usage\nconst myStack = Stack(1, 2, 3);\nmyStack.push(123, 436, 512);\nconsole.log(myStack.items.join(\",\"));\nwhile (!myStack.isEmpty) { \n console.log(\"Pop item[\" + (myStack.size - 1) + \"]: \" + myStack.pop());\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T09:56:08.600",
"Id": "524716",
"Score": "0",
"body": "THank you! And just to check my knowledge, the returned object has access to the `stack` variable because it forms a closure since `Object.freeze` is a function?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T15:00:12.217",
"Id": "524725",
"Score": "1",
"body": "@JordanBaron It doesn't matter that `Object.freeze` is a function, but that the frozen object contains functions. Each of `push`, `pop`, `clear`, `size`, `isEmpty`, and `items` is a separate closure that has has access to this specific copy of `stack` after being returned."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T05:44:55.240",
"Id": "524760",
"Score": "1",
"body": "@JordanBaron Exactly what @TheRubberDuck commented. However to clarify terminology. As used in the rewrite `Object.freeze` is a *\"function call\"*, while the object it freezes contains *\"function declarations\"* `push`, `pop`, ... . Only function declarations / expressions can close over (closure) variables within scope"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T11:07:32.390",
"Id": "524800",
"Score": "0",
"body": "\"Avoid redundant or long form code.\". Using -- or ++ as part of a larger expression is such an incredibly common cause of errors and confusion that languages worrying about clarity explicitly forbid this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T21:49:59.293",
"Id": "524852",
"Score": "0",
"body": "@Voo At CodeReview I endeavor to review code at professional level. Wide spread miss understanding of the pre/post decrement/increment operator is not a reason to avoid its use, rather it is a reason to improve education and training. The mind set of \"too hard don't use\" helps no one and does nothing but hold the industry back."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T22:06:54.330",
"Id": "524854",
"Score": "0",
"body": "@Blindman Well if \"least amounts of characters being used\" is a good metric for quality of code in your mind, I assume awk and co are your favorite languages ;-) Suffice to say there's been enough bugs in professional code due to this with very little benefit but to each their own."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T22:14:52.120",
"Id": "524855",
"Score": "0",
"body": "@Voo I have never said least characters. The most common metric used to assay code quality is bugs per line. Reducing the number of lines by 20% reduces the number of \"bugs\" by the same amount. The most effective way to reduce \"bugs\" in code is to reduce the number of lines of code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T22:22:00.173",
"Id": "524856",
"Score": "0",
"body": "@Blindman Ah I see the problem. When talking about \"lines of code\" in that context what those papers (yes I know them) mean are *logical lines of code* and not actual physical lines of code. There's a simple thought experiment that should make this clearer: If you simply remove extra newlines (easy to do in languages with statement terminators such as JavaScript) but keep the code identical otherwise this shouldn't change the expected bug count - but yes rather unfortunate naming. Going by \"logical lines of code\" (i.e. statements) both `i++; foo(i);` and `foo(i++)` are considered identical."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T22:46:28.110",
"Id": "524859",
"Score": "0",
"body": "@voo You are using logical lines of code LLOC rather than physical lines of code LOC. Using logic lines of code is high problematic for compiled and interpreted languages (what is `i++`, is it `load a, i`, `load b, 1`, `add a, b`, `store i, a` or just `inc i`, that will depend on the target) LOC holds true in the realm of high level languages as it is the more robust metric by avoiding the vagary of interpretation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T23:08:31.197",
"Id": "524860",
"Score": "0",
"body": "@Blindman So you really think that putting each part of a for loop on its own line magically triples the likelihood of bugs? (What some code compiles to is irrelevant for logical locs, although obviously how you define a statement/function point/whatever you want to use is open to discussion - but I've never seen a single paper that used assembly instructions for that)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T00:03:44.813",
"Id": "524863",
"Score": "0",
"body": "@Voo Yes 3 lines of code has 3 times the likely hood of bugs than 1 line, but no project is 3 lines long. A typical medium to large project can come in at half a million lines +. Writing tight short form code (as a habit) with rigorous testing (apart reducing time to read and navigate) can reduce line count by 20%, 10000 less lines is substantial. At standard coding rates the savings are 7 figure $"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T05:46:45.117",
"Id": "524867",
"Score": "0",
"body": "@Blindman So you really think that the exact same code formatted in different ways will have different bug counts? Well I assume everyone will have to decide for themselves whether that sounds like a reasonable argument to them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T23:31:36.337",
"Id": "524933",
"Score": "0",
"body": "@Voo Again you are attempting to put words in my mouth. I never said *\"formatted\"* I will say *\"The same code written in different styles will have different bug counts? That the number of bugs correlates strongly with the number of line of code.\"*"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T02:13:03.233",
"Id": "524936",
"Score": "0",
"body": "@Blimdman Huh? You yourself said \"Yes 3 lines of code has 3 times the likely hood of bugs than 1 line\". Which means that if I take that 1 line of code and reformat it to be 3 lines that means the likelihood of bugs increased by a factor of 3 despite it being the same code. That is simply a consequence of using physical lines of code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T02:17:03.483",
"Id": "524937",
"Score": "0",
"body": "What I imagine your actual argument is, is that physical lines of code are a reasonable proxy for some actually relevant code metric assuming the analyzed code base is large enough. So instead of trying to compute the more complex metric one can approximate its value by using physical loc. This is all fine. The problem arises when you then try to apply that proxy metric on small code snippets and reason based on that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T03:47:22.023",
"Id": "524940",
"Score": "0",
"body": "@Voo My answer stated *\"Avoid redundant or long form code.\"* My reasoning is in the comments. What you imagine I think is irrelevant . Thanks for the discussion and have a nice day :)"
}
],
"meta_data": {
"CommentCount": "16",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T08:37:36.893",
"Id": "265654",
"ParentId": "265646",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "265649",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T02:08:49.593",
"Id": "265646",
"Score": "4",
"Tags": [
"javascript",
"reinventing-the-wheel",
"stack"
],
"Title": "Stack Implementation in JavaScript"
}
|
265646
|
<p>I am a new F# programmer, and a student in a security class. As part of my notes, I wrote a small implementation of a monoalphabetic cipher as follows:</p>
<pre class="lang-fs prettyprint-override"><code>open System
let random = Random()
let defaultCharMap() =
['a' .. 'z'] @ ['A' .. 'Z'] @ ['0' .. '9']
let randomCharMap() =
let map = defaultCharMap()
map
|> List.sortBy (fun t -> random.Next(map.Length))
|> List.zip map
|> Map.ofList
let encode msg =
let map = randomCharMap()
msg
|> String.map (fun t -> map.TryFind t |> defaultArg <| t)
encode "Hello, world!!!"
</code></pre>
<p>The code is designed to take any alphanumeric input, which is then encoded to a random map (done in <code>randomCharMap</code>). This map is simply the plaintext values as keys to a random ciphertext value.</p>
<p>As this is a functional language, I have done my best to use piping and HOF to achieve this. I am looking to validate my work and see if this can be optimised in any way.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T11:10:54.530",
"Id": "524887",
"Score": "0",
"body": "Undoubtedly not for production use, but `Random` is not a cryptographically secure RNG."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T11:41:01.833",
"Id": "524890",
"Score": "0",
"body": "Yeah, no issues there. Just random code I threw together to play with F# and my university material :) Later this semester we implement our own security systems and I am well prepared for proper implementation ;) @MaartenBodewes"
}
] |
[
{
"body": "<p>Your code looks good in terms of being idiomatic functional-ish F#. </p>\n<p>I do still have some suggestions:</p>\n<ul>\n<li><p><code>defaultCharMap</code> is a function that always returns the same value. Therefore it might as well be a plain module-level value instead. This will mean it's evaluated when the module is loaded (essentially just before the program starts). However, if you only want it to evaluate it once just before it is first needed you can make it a lazy value, and then request the value using the <code>.Value</code> property. Also, it is not a map so I would call it <code>chars</code>.</p>\n</li>\n<li><p>When building up <code>chars</code> you're using <code>@</code> to append lists. This can be slow when the list on the left is quite long. This is probably not an issue at all given the lists are small but it might be better to prefer a list comprehension.</p>\n</li>\n<li><p>4 space formatting is much more common than 2 spaces in F# code.</p>\n</li>\n<li><p>The <code>t</code> in the <code>List.sortBy</code> function is not used so the convention is to discard the value by naming it <code>_</code>.</p>\n</li>\n<li><p>People generally avoid using <code>defaultArg</code>, preferring <code>Option.defaultValue</code> instead. The latter has a better parameter order that allows easy piping without the need for the backwards pipe <code><|</code>. It's usually recommended to avoid using <code><|</code> as the operator precedence can be confusing.</p>\n</li>\n</ul>\n<p>With all of those suggestions applied, the code would look like this:</p>\n<pre><code>open System\n\nlet random = Random()\n\nlet chars = lazy [\n for c in 'a' .. 'z' do c\n for c in 'A' .. 'Z' do c\n for c in '0' .. '9' do c\n]\n\nlet randomCharMap() = \n chars.Value\n |> List.sortBy (fun _ -> random.Next(chars.Value.Length))\n |> List.zip chars.Value\n |> Map.ofList\n\nlet encode msg = \n let map = randomCharMap()\n msg\n |> String.map (fun t -> map.TryFind t |> Option.defaultValue t)\n\nencode "Hello, world!!!"\n</code></pre>\n<p>You could arguably make the code more functional by passing in the <code>Random</code> as an argument to any function that needs it, instead of accessing a static <code>Random</code>. This would mean that the functions could be considered to be more pure and you could pass in a seeded <code>Random</code> which always produces the same result, allowing predictable testing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T23:10:37.227",
"Id": "524749",
"Score": "0",
"body": "Awesome!! I never considered list comprehension in that way, that is a great tip! I am a C# dev, and use 2 spaces since it fits more on screen, but I will keep that in mind for when sharing code! I didn't consider passing `random` as an arg, but that makes a lot of sense. Thank you very much for the criticism! I very much appreciate it in order to become better at FP :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T23:21:45.753",
"Id": "524750",
"Score": "0",
"body": "One question I forgot to ask: rather than a list for `chars`, would a `Seq` be better? iirc isn't it lazy? Or is it the elements that are lazy?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T12:13:05.537",
"Id": "524803",
"Score": "1",
"body": "@TimeTravelPenguin `Seq` is just another name for `IEnumerable`. So yes it is lazy but it will be evaluated again every time it is used. The F# `lazy` is guaranteed to only evaluate once. But the trade off in this case is that the list will be held in memory for the duration of the program even if it is no longer used."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T12:56:45.757",
"Id": "265660",
"ParentId": "265650",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "265660",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T06:48:14.180",
"Id": "265650",
"Score": "2",
"Tags": [
"functional-programming",
"f#",
"caesar-cipher"
],
"Title": "F# simple monoalphabetic cipher code implementation"
}
|
265650
|
<p>I've been experimenting with the <a href="https://tryfsharp.fsbolero.io/" rel="nofollow noreferrer">F# Bolero</a> environment to learn F# a bit and I was trying to get the hang of pattern matching by generating ordinal numbers (1st, 2nd, 3rd, ...) from cardinal numbers (1, 2, 3, ...).</p>
<p>Here's the code I came up with:</p>
<pre><code>let ordinal n =
if n > 20 then
match n % 10 with
| 1 -> string n + "st"
| 2 -> string n + "nd"
| 3 -> string n + "rd"
| _ -> string n + "th"
else
match n % 20 with
| 1 -> string n + "st"
| 2 -> string n + "nd"
| 3 -> string n + "rd"
| _ -> string n + "th"
let hundred = [1..100]
let hundredOrdinals = List.map ordinal hundred
printfn "First %d ordinals:\n%A" hundred.Length hundredOrdinals
</code></pre>
<p>Which I believe produces the right ordinal numbers both for numbers less than and numbers greater than or equal to 20.</p>
<p>However, the patterns that are matched are identical for both branches of the <code>if</code> statement: both match an input of <code>1</code> to an output with <code>"st"</code>, and input of <code>2</code> to an output with <code>"nd"</code> and so on, so I was wondering if I couldn't somehow recycle the matching criteria while keeping the matching expressions (<code>n % 20</code> and <code>n % 10</code>). Any alternative approaches are also welcome.</p>
<p>Here's the output of the snippet above just in case it might contain errors, I've aligned some of the values to make it more readable.</p>
<pre><code>First 100 ordinals:
[ "1st"; "2nd"; "3rd"; "4th"; "5th"; "6th"; "7th"; "8th"; "9th"; "10th";
"11th"; "12th"; "13th"; "14th"; "15th"; "16th"; "17th"; "18th"; "19th"; "20th";
"21st"; "22nd"; "23rd"; "24th"; "25th"; "26th"; "27th"; "28th"; "29th"; "30th";
"31st"; "32nd"; "33rd"; "34th"; "35th"; "36th"; "37th"; "38th"; "39th"; "40th";
"41st"; "42nd"; "43rd"; "44th"; "45th"; "46th"; "47th"; "48th"; "49th"; "50th";
"51st"; "52nd"; "53rd"; "54th"; "55th"; "56th"; "57th"; "58th"; "59th"; "60th";
"61st"; "62nd"; "63rd"; "64th"; "65th"; "66th"; "67th"; "68th"; "69th"; "70th";
"71st"; "72nd"; "73rd"; "74th"; "75th"; "76th"; "77th"; "78th"; "79th"; "80th";
"81st"; "82nd"; "83rd"; "84th"; "85th"; "86th"; "87th"; "88th"; "89th"; "90th";
"91st"; "92nd"; "93rd"; "94th"; "95th"; "96th"; "97th"; "98th"; "99th"; "100th" ]
</code></pre>
|
[] |
[
{
"body": "<p>You can combine both cases with an if .. then .. else ..</p>\n<pre><code>let ordinal n =\n match if n > 20 then n % 10 else n % 20 with\n | 1 -> string n + "st"\n | 2 -> string n + "nd"\n | 3 -> string n + "rd"\n | _ -> string n + "th"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T16:02:08.497",
"Id": "524727",
"Score": "0",
"body": "Oh, so this is like the [ternary operator](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator) in C# then? Very succinct and handy!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T06:53:41.173",
"Id": "524774",
"Score": "1",
"body": "It is, see https://stackoverflow.com/questions/28551938/does-f-have-the-ternary-operator/28551962#28551962"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T14:59:07.447",
"Id": "265664",
"ParentId": "265656",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "265664",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T10:23:41.553",
"Id": "265656",
"Score": "0",
"Tags": [
"beginner",
"functional-programming",
"f#",
"pattern-matching"
],
"Title": "Cardinal to ordinal numbers in F# code reuse"
}
|
265656
|
<p>As this is a very basic word wrap program, it has at least the following 3 limitations :-</p>
<ol>
<li>The file should have a terminating newline.</li>
<li>The column number at which the lines are to be wrapped must be greater than or equal to the length of the longest word.</li>
<li>Tabs (<code>\t</code>) should not have been used in the lines to be wrapped.</li>
</ol>
<p>Also, the usage of <code>argv[0]</code> makes this code non-portable.</p>
<hr />
<p>Here is the code :-</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static char * modified_fgets(char *, const int, FILE *);
static void wrap_line(char *, const int);
int main(int argc, char ** argv)
{
if (argc != 2)
printf("Enter this: %s filename\n", argv[0]), exit(EXIT_FAILURE);
FILE * in;
if ((in = fopen(argv[1], "r")) == NULL)
fprintf(stderr, "Can't open %s\n", argv[1]), exit(EXIT_FAILURE);
FILE * out;
if ((out = fopen("OUT.txt", "w")) == NULL)
fprintf(stderr, "Can't create output file\n"), exit(EXIT_FAILURE);
char s[1024];
while (modified_fgets(s, 1024, in) != NULL)
wrap_line(s, 80), fprintf(out, "%s\n", s);
if ((fclose(in) != 0) || (fclose(out) != 0))
fprintf(stderr, "Error in closing files\n");
return EXIT_SUCCESS;
}
// This function reads a line that is terminated by '\n'.
static char * modified_fgets(char * s, const int n, FILE * fp)
{
char * returnValue;
returnValue = fgets(s, n, fp);
int i = 0;
if (returnValue != NULL)
{
while ((s[i] != '\n') && (s[i] != '\0'))
i++;
if (s[i] == '\n')
s[i] = '\0';
else // s[i] == '\0' (i.e. there are extra characters in the line).
while (getc(fp) != '\n')
continue;
}
return returnValue;
}
// This function wraps a single line, terminated by '\0' instead of '\n'.
// wrapColumn should be >= the length of the longest word.
// '\t' should not have been used in the line to be wrapped.
static void wrap_line(char * s, const int wrapColumn)
{
int lastWrap = 0;
for (int i = 0; i < (int) strlen(s); i++)
if (i - lastWrap == wrapColumn)
for (int k = i; k > 0; k--)
if (s[k] == ' ')
{
s[k] = '\n';
lastWrap = k+1;
break;
}
}
</code></pre>
<hr />
<p>Here is a sample input file :-</p>
<pre><code>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).
</code></pre>
<hr />
<p>Here is the desired output file :-</p>
<pre><code>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem
Ipsum has been the industry's standard dummy text ever since the 1500s, when an
unknown printer took a galley of type and scrambled it to make a type specimen
book. It has survived not only five centuries, but also the leap into electronic
typesetting, remaining essentially unchanged. It was popularised in the 1960s
with the release of Letraset sheets containing Lorem Ipsum passages, and more
recently with desktop publishing software like Aldus PageMaker including
versions of Lorem Ipsum.
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots
in a piece of classical Latin literature from 45 BC, making it over 2000 years
old. Richard McClintock, a Latin professor at Hampden-Sydney College in
Virginia, looked up one of the more obscure Latin words, consectetur, from a
Lorem Ipsum passage, and going through the cites of the word in classical
literature, discovered the undoubtable source. Lorem Ipsum comes from sections
1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and
Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of
ethics, very popular during the Renaissance. The first line of Lorem Ipsum,
"Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.
It is a long established fact that a reader will be distracted by the readable
content of a page when looking at its layout. The point of using Lorem Ipsum is
that it has a more-or-less normal distribution of letters, as opposed to using
'Content here, content here', making it look like readable English. Many desktop
publishing packages and web page editors now use Lorem Ipsum as their default
model text, and a search for 'lorem ipsum' will uncover many web sites still in
their infancy. Various versions have evolved over the years, sometimes by
accident, sometimes on purpose (injected humour and the like).
</code></pre>
<hr />
<p>Edit :-</p>
<p>I guess the first limitation is easy to fix.
Using <code>while (((c = getc(fp)) != '\n') && (c != EOF))</code> instead of <code>while (getc(fp) != '\n')</code> in the <code>modified_fgets()</code> function does the trick, where c is declared as an integer beforehand.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T16:34:40.233",
"Id": "524834",
"Score": "1",
"body": "Yes that is a good fix as `while (getc(fp) != '\\n')` is a potential infinite loop should `get()` return a `EOF` due to a rare input error (even if file has a final `'\\n'`)."
}
] |
[
{
"body": "<p><strong>Readability</strong></p>\n<p>Your (ab)use of the comma operator is detrimental to program readability. It is <em>extremely</em> easy for a reader of your code to miss the fact that you have two expressions on one line. Reformat your code to have one statement (expression) on a line, and make full use of curly braces to make the code easy for someone to casually follow.</p>\n<p>For example:</p>\n<pre><code> if (argc != 2) {\n printf("Enter this: %s filename\\n", argv[0]);\n exit(EXIT_FAILURE);\n }\n</code></pre>\n<p>The lack of curly braces in <code>wrap_line</code> makes the code a bit harder to follow because of all that indentation. A reader has to consider if that is one statement on multiple lines or multiple statements. The additional curly braces would make it obvious to a reader that these are distinct statements.</p>\n<p>A minor possible issue is the excessive use of blank lines. Having a blank line after the opening <code>{</code> of a function (before any code) can have the effect of disconnecting that code form the function declaration. (The same applies to the closing <code>}</code> of the function.)</p>\n<p><strong>Performance</strong></p>\n<p>The <code>modified_fgets</code> could handle long lines better (reading in a block of characters rather than looking at them one at a time). Adding this would then show a possible way to handle (and wrap) those long lines, as well as files that don't end in a newline.</p>\n<p><code>wrap_line</code> is a big bottleneck. This can all be handled in a single pass thru the string, but your method is O(N<sup>2</sup>) because you call <code>strlen</code> every time. You can walk thru the string, one character at a time. Keep track of where you start, the number of characters you've looked at, and when the last space was. Then, when you gone as far as you can before you have to wrap, you can update that last space, move the start indicator, update the length, and keep processing. (This would also allow for adding handling of "words" longer than the wrap length.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T15:34:24.127",
"Id": "265665",
"ParentId": "265661",
"Score": "3"
}
},
{
"body": "<p>Here are some things that may help you improve your code.</p>\n<h2>Use a named <code>const</code> for fixed values</h2>\n<p>The buffer size is fixed a 1024 bytes, and the number 1024 appears in two places. I'd recommend making that a named constant instead, using <s>the C11 <code>const</code> keyword</s> C99 variable length arrays (thanks to chux for the correction!) or via a <code>#define</code>.</p>\n<pre><code>/* using variable length array */\nconst unsigned buffsize = 1024;\n/* alternative using #define */\n#define BUFFSIZE 1024\n</code></pre>\n<h2>Use curly braces for clarity</h2>\n<p>The only place the curly braces (<code>{}</code>) are <em>needed</em> for control flow in this program is the innermost <code>if</code> within <code>wrap_line()</code>, but using them for each control structure may help with clarity and readability for human programmers. For that reason, I'd recommend their use.</p>\n<h2>Don't abuse the comma operator</h2>\n<p>This line doesn't really need a comma operator:</p>\n<pre><code>if (argc != 2)\n printf("Enter this: %s filename\\n", argv[0]), exit(EXIT_FAILURE);\n</code></pre>\n<p>If you follow the previous advice, and write for clarity, that would look like this instead:</p>\n<pre><code>if (argc != 2) {\n printf("Enter this: %s filename\\n", argv[0]); \n exit(EXIT_FAILURE);\n}\n</code></pre>\n<p>It's too easy to overlook the <code>exit()</code> at the end.</p>\n<h2>Apply error checking consistently</h2>\n<p>If the final <code>fclose()</code> for either file fails, the program still exits with <code>EXIT_SUCCESS</code> which does not seem consistent with the other error handling in <code>main()</code>. Additionally, because of logical operator short-circuit evaluation, if the first <code>fclose(in)</code> results in a non-zero return, the second <code>fclose()</code> will not be called. In this <em>particular</em> case, the program would exit and the operating system would flush and close the file, but again, that's handling the errors inconsistently.</p>\n<h2>Think of the user</h2>\n<p>There are a few things about this implementation that could be improved for the user's experience. The first is to either allow specifying the output file name. One way this might be done is to simply read from <code>stdin</code> and write to <code>stdout</code> as many programs do in Linux. This allows one to pipe from the output of one program to the input of another, for example. The second thing is to adjust how the word wrapping is done. If the user feeds this program a line that is longer than 1024 characters, this program will silently discard the excess length to the next newline character. At the very least, signalling that this has happened might be better. I'd prefer instead if the program didn't have such an arbitrary limit.</p>\n<h2>Fix the bug</h2>\n<p>Try changing your output line length to 5 and check the output. I'd characterize it as a bug.</p>\n<h2>Consider an alternative approach</h2>\n<p>An alternative approach would be to read in characters until either a newline or 80 characters were read. If a newline is read, simply print the buffer to that point. If 80 characters were read, back up from there and insert a break at the first whitespace, keeping the remainder of the buffer to append to for the next line. If no whitespace was found, consider whether to insert a break anyway or printing the line as is and implement your choice.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T17:31:34.507",
"Id": "265670",
"ParentId": "265661",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T13:55:11.367",
"Id": "265661",
"Score": "7",
"Tags": [
"c",
"formatting",
"io"
],
"Title": "Word wrap with file input & ouput"
}
|
265661
|
<p>I'm developing a screen recording as an application log. The recording should capture a full HD screen at 25fps and on request it should save last 60 seconds of record. It is for embedded app, but the app is built for 32 bit and during development the recording app threw OutOfMemory exception during video generating when I used <code>ImageFormat.Png</code>.</p>
<p>I solved this problem - I forgot to dispose bitmap created during looping list of images. But it should work with rest of application (not well written). Is there a way to optimize memory usage of the recording?</p>
<p>I found a template using array but I changed array to list since it is easier to work with a list than with an array for me. Is it a problem in this case? Is it consuming more memory or CPU to add/remove item to the list instead of array?</p>
<p>Recorder:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace ScreenRecord
{
public class ScreenRecorder
{
private Rectangle bounds = new Rectangle(0, 0, 1920, 1080);
private Timer fpsTimer = new Timer();
private List<Tuple<byte[], DateTime>> Buffer = new List<Tuple<byte[], DateTime>>();
private int BufferLengthSeconds = 60;
public List<Tuple<byte[], DateTime>> SaveVideoLog() {
List<Tuple<byte[], DateTime>> tempBuffer = new List<Tuple<byte[], DateTime>>(Buffer);
Buffer.Clear();
return tempBuffer;
}
private void AddBitmap(Bitmap bitmap) {
try {
DateTime currentTime = DateTime.Now;
DateTime minTime = currentTime.AddSeconds(- BufferLengthSeconds);
//Buffer.RemoveAll(frame => frame.Item2 < minTime);
for (int i = 0; i < Buffer.Count; i++) {
if (Buffer.First().Item2 < minTime)
Buffer.RemoveAt(0);
else
break;
}
using (MemoryStream ms = new MemoryStream()) {
bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
Buffer.Add(Tuple.Create(ms.ToArray(), currentTime));
}
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
}
}
public void RecordVideo()
{
using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
//Add screen to bitmap:
g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);
}
//Save screenshot:
AddBitmap(bitmap);
}
}
public ScreenRecorder()
{
fpsTimer.Interval = 40;
fpsTimer.Start();
fpsTimer.Tick += new EventHandler(timer1_Tick);
}
private void timer1_Tick(object sender, EventArgs e)
{
RecordVideo();
}
}
}
</code></pre>
<p>Video coder:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using Accord.Video.FFMPEG;
namespace ScreenRecord
{
public static class VideoConverter
{
public static void ConvertToVideoAndSave(List<Tuple<byte[], DateTime>> source, string destinationPath) {
if (!source.Any())
return;
using (MemoryStream ms = new MemoryStream(source.First().Item1)) {
Image frame = Image.FromStream(ms);
ConvertToVideoAndSave(source, destinationPath, frame.Width, frame.Height);
}
}
public static void ConvertToVideoAndSave(List<Tuple<byte[], DateTime>> source, string destinationPath, int width, int height) {
ConvertToVideoAndSave(source, destinationPath, width, height, 25);
}
public static void ConvertToVideoAndSave(List<Tuple<byte[], DateTime>> source, string destinationPath, int width, int height, int framerate) {
ConvertToVideoAndSave(source, destinationPath, width, height, framerate, VideoCodec.H264);
}
public static void ConvertToVideoAndSave(List<Tuple<byte[], DateTime>> source, string destinationPath, int width, int height, int framerate, VideoCodec codecs) {
if (!source.Any()) {
return;
}
using (VideoFileWriter writer = new VideoFileWriter()) {
writer.Open(destinationPath, width, height, framerate, codecs);
DateTime startTime = source.First().Item2;
foreach (Tuple<byte[], DateTime> frame in source) {
using (MemoryStream ms = new MemoryStream(frame.Item1))
using (Bitmap videoFrame = new Bitmap(ms))
writer.WriteVideoFrame(videoFrame, frame.Item2 - startTime);
}
writer.Close();
}
}
}
}
</code></pre>
<p>Main form with two buttons:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace ScreenRecord
{
public partial class MainForm : Form
{
ScreenRecorder rec;
public MainForm()
{
InitializeComponent();
}
void Button1Click(object sender, EventArgs e)
{
rec = new ScreenRecorder();
}
void Button2Click(object sender, EventArgs e)
{
VideoConverter.ConvertToVideoAndSave( rec.SaveVideoLog(), "D:\\Test.mp4");
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I don't think this is the best way of capturing the screen, but I'll leave it to someone with more experience in the area to comment on that.\nWhat I will comment on are rather obvious performance issues assuming the overall code stays as it is:</p>\n<ul>\n<li><p>List<Tuple<byte[], DateTime>> tempBuffer = new List<Tuple<byte[], DateTime>>(Buffer)</p>\n<p>This copies the list for no obvious reason. The only reason I can think of is to decouple it from an async reader, but by the looks of it everything is sync here. And even so, you can just switch the references without copying everything.</p>\n</li>\n<li><p>Use UtcNow instead of Now, it is both more performant and makes more sense</p>\n</li>\n<li><p>Buffer.RemoveAt(0); shifts the list to the left, so your for cycle is O(n^2)</p>\n</li>\n<li><p>ms.ToArray() copies the entire memory stream.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T07:50:35.707",
"Id": "524784",
"Score": "0",
"body": "Thank you, I think I improved all the mentioned points. I'm not just sure with the ```Buffer.RemoveAt(0)``` part. I changed it to ```Buffer.RemoveAll``` (just commented the for loop and uncomented the line before). My thought was that it would remove max two items from beginning so why to check whole list but load seems equal and it's safer when app gets stuck for a while.\n\nIf you know better way to capture the screen please share source where I could learn it. If I won't use it here then for future use. I am new in the area of images and video so everyone is better than me"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T21:18:53.453",
"Id": "265678",
"ParentId": "265662",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "265678",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T14:30:17.097",
"Id": "265662",
"Score": "2",
"Tags": [
"c#",
"performance",
"image",
"memory-optimization",
"video"
],
"Title": "C# screen recording"
}
|
265662
|
<p>I'm using C#, .NET Core and the entity framework and am currently working on optimizing various functions for better performance.</p>
<p>One of the main functions is getting a calculation based on two indexes; a product and machine. The records in this database table is currently at 500 rows but can go upwards to 10.000.</p>
<p>My code for finding a record in this table is as follows:</p>
<pre><code>public Calculation GetCalculationByProduct(Machine currentMachine, Product currentProduct)
{
IList<Calculation> calculations = _calculationRepository.Index().ToList();
for (int i = 0; i < calculations.Count(); i++)
{
if (calculations[i].MachineForeignKey == currentMachine.ID && calculations[i].ProductRef.ID == currentProduct.ID)
{
return calculations[i];
}
}
return null;
}
</code></pre>
<p>The function searches for the relative calculation based on both the product and the machine; since a machine and a product can both have multiple calculations.</p>
<p>The actual model looks like this:</p>
<pre><code>public class Calculation
{
public int ID { get; set; }
public int MachineForeignKey { get; set; }
public Machine MachineRef { get; set; }
public Product ProductRef {get; set; }
public double Value { get; set; }
}
</code></pre>
<p>A product model and Machine model both use this like so:</p>
<pre><code>public class Product
{
[Key]
public int ID { get; set; }
[Required]
public string ProductName { get; set; }
public string Name { get; set; }
public IEnumerable<Calculation> Calculations { get; set; }
}
public class Machine
{
[Key]
public int ID { get; set; }
public string OrderNo { get; set; }
public IEnumerable<Calculation> Calculations { get; set; }
}
</code></pre>
<p>The repository used is a basic linq implementation using generics like so:</p>
<pre><code> public IEnumerable<TEntity> Index()
{
return _context.Set<TEntity>();
}
</code></pre>
<p>And the relations for the calculation / model have been set with a modelbuilder like this:</p>
<pre><code> protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Machine>()
.HasMany(m => m.Calculations)
.WithOne(s => s.MachineRef)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<Product>()
.HasMany(m => m.CalculatedValues)
.WithOne(s => s.ProductRef)
.OnDelete(DeleteBehavior.Cascade);
}
</code></pre>
<p>I first used LINQ like so:</p>
<pre><code> _calculationRepository.Index().Where(c => c.MachineForeignKey == Current_Machine.ID && c.ProductRef.ID == Current_Product.ID).FirstOrDefault();
</code></pre>
<p>But that caused quite bad performance; where it was around 2000ms</p>
<p>Currently, it goes through 500 records in about 900ms. Using visual studio's diagnostic tools I could see that this function was slowing everything down quite a lot; especially since the function is used for nearly every calculation done.</p>
<p>I'm looking to optimize the code, but any other advice is welcome.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T10:03:58.313",
"Id": "524792",
"Score": "1",
"body": "Specify the exact version of the Entity Framework. Remove the asp.net tag."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T10:06:44.450",
"Id": "524793",
"Score": "1",
"body": "Change `IEnumerable<TEntity> Index()` to `IQueryable<TEntity> Index()`. As a result, the linq query with `FirstOrDefault` should work with lightning speed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T10:08:07.533",
"Id": "524794",
"Score": "0",
"body": "Tag has been removed; but changing IEnumerable to IQueryable doesn't really impact the performance as far as I can see."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T10:09:58.777",
"Id": "524795",
"Score": "1",
"body": "Did you try it? With IEnumerable, all data will be pumped to the client. With IQueryable, the query will be executed completely in the database,"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T10:13:02.867",
"Id": "524796",
"Score": "0",
"body": "Is if EF6? EF Core? What exact version?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T12:17:27.573",
"Id": "524804",
"Score": "0",
"body": "I believed that IQueryable was merely an extension of IEnumerable, interesting to see that the query is completely executed in the databse. Still the performance isn't impacted that greatly. As for the version it's EF Core 5.0.4"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T09:56:32.607",
"Id": "524879",
"Score": "0",
"body": "This also requires the source code of `_calculationRepository.Index()`."
}
] |
[
{
"body": "<p>When using EF, it would be better if you query the database then create a list of the results. in <code>GetCalculationByProduct</code> method, see this line :</p>\n<pre><code>IList<Calculation> calculations = _calculationRepository.Index().ToList();\n</code></pre>\n<p>at this line, it will populate all table records and stores it in memory, which is something you don't need to be a habit in most cases.</p>\n<p>While this line of code :</p>\n<pre><code> _calculationRepository.Index().Where(c => c.MachineForeignKey == Current_Machine.ID && c.ProductRef.ID == Current_Product.ID).FirstOrDefault();\n</code></pre>\n<p>it'll build the SQL query, then execute it, and then gets the first record.</p>\n<p>So, what you are actually missing here is <code>AsNoTracking</code>. You can do it like this :</p>\n<pre><code>_calculationRepository.Index().AsNoTracking().FirstOrDefault(c => c.MachineForeignKey == Current_Machine.ID && c.ProductRef.ID == Current_Product.ID);\n</code></pre>\n<p>by default, <code>EF</code> catches any returned entity, so any changes to that entity can be saved by running <code>SaveChanges</code> method. If you want to return results that you don't want to do any changes to them (just read-only results) use <code>AsNoTracking</code> this would make the execution a bit faster as the entity results won't be cached.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T06:46:31.690",
"Id": "524773",
"Score": "0",
"body": "Using asNoTracking does have a significant impact; but are there any side effects of using that comment? I do need to update the obtained value further down the line"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T07:09:48.707",
"Id": "524776",
"Score": "1",
"body": "@RDAxRoadkill the only side effects is that the retrieved won't be tracked, so any changes to the retrieved entries will need to `Attach` it and change its state manually, and also you might to use `Load` method to re-load entity values from the database with the new values."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T09:33:43.317",
"Id": "525738",
"Score": "0",
"body": "The issue here seems to be related more to the `IEnumerable` return type of `Index()` (as opposed to `IQueryable`. Tracking should be negligible performance-wise for fetching one entity."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T17:57:22.917",
"Id": "265671",
"ParentId": "265663",
"Score": "3"
}
},
{
"body": "<p>Disclaimer: my practical knowledge of EF is limited. But when you are using a database the first step is to run an <strong>execution plan</strong> against your queries. Make sure that they run fast enough and within predictable times regardless of how many records you are storing.</p>\n<p>You may have to add <strong>indexes</strong>, for instances on fields being searched or JOIned. So I would start by reviewing the table structure and the overall data model. It may be lacking optimization. If the DB structure is the problem EF will not improve things, although there are things it can do like caching data or the execution plan itself for reuse.</p>\n<p>Also ask yourself if EF+LINQ is really the best way to do it, or if using a stored procedure would make sense perhaps. The whole logic does not necessarily needs to be handled by the client. Stored procedures can be used with EF too.</p>\n<p>As a rule you don't want to pull out more data to the client than strictly necessary.</p>\n<p>Suggested reading:</p>\n<ul>\n<li><a href=\"https://www.thinktecture.com/en/entity-framework-core/execution-plans-in-3-1/\" rel=\"nofollow noreferrer\">Better Entity Framework Core Performance by Reading Execution Plans</a></li>\n<li><a href=\"https://docs.microsoft.com/en-us/ef/ef6/fundamentals/performance/perf-whitepaper?redirectedfrom=MSDN\" rel=\"nofollow noreferrer\">Performance considerations for EF 4, 5, and 6</a> (long read but I learned a lot)</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T06:45:51.000",
"Id": "524771",
"Score": "0",
"body": "Thanks for the interesting links; I'll definitely have a look at those. As for the database optimization itself I'll have to do some additional research; I do believe the ID's both have an index."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-18T09:36:35.633",
"Id": "525741",
"Score": "0",
"body": "As to the stored procedure suggestion, while there are fringe cases where it makes sense to delegate work to a sproc, fetching a row based on two columns values is not such a case. Barring those fringe cases, sprocs should generally be avoided when using EF simply because it start negating the code-driven aspect of having EF as your ORM."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T20:01:58.740",
"Id": "265675",
"ParentId": "265663",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T14:50:50.043",
"Id": "265663",
"Score": "0",
"Tags": [
"c#",
"linq",
"entity-framework"
],
"Title": "Efficiency of finding one database record using two ID's"
}
|
265663
|
<p>I'm trying to perform a 4-dimensional numerical integration in <code>R</code> using a function I wrote in <code>C++</code> code which is then sourced in <code>R</code> using the <code>Rcpp</code> package.</p>
<p>Below there is my code:</p>
<pre><code>// [[Rcpp::depends(RcppEigen)]]
// [[Rcpp::depends(RcppNumerical)]]
#define EIGEN_PERMANENTLY_DISABLE_STUPID_WARNINGS
#include <Eigen/Eigen>
#include <Rcpp.h>
#include <math.h>
#include <iostream>
#include <cstdlib>
#include <boost/math/special_functions/bessel.hpp>
#include <boost/math/special_functions/gamma.hpp>
using namespace std;
using namespace Rcpp;
using namespace Numer;
// [[Rcpp::depends(BH)]]
// [[Rcpp::export]]
double gaussian_free_diffusion(double x,double x0, double sigma, double t) {
double pi = 2 * acos(0.0);
double a1 = (1/sqrt(2.0 * pi * sigma * t));
double b1 = exp(-pow((x - x0), 2.0)/(2.0 * sigma * t));
double res = a1 * b1;
return res;
}
// [[Rcpp::export]]
double integral_CppFunctionCUBATURE(NumericVector Zt_pos, const double& xA0, const double& xB0, const double& yA0,
const double& yB0, const double& t1, const double& sigma){
double xAt_pos = Zt_pos[0];
double xBt_pos = Zt_pos[1];
double yAt_pos = Zt_pos[2];
double yBt_pos = Zt_pos[3];
double temp_pbxA = gaussian_free_diffusion(xAt_pos, xA0, sigma,t1);
double temp_pbxB = gaussian_free_diffusion(xBt_pos, xB0, sigma, t1);
double temp_pbyA = gaussian_free_diffusion(yAt_pos, yA0, sigma,t1);
double temp_pbyB = gaussian_free_diffusion(yBt_pos, yB0, sigma, t1);
return (temp_pbxB * temp_pbyB) * (temp_pbxA * temp_pbyA);
};
</code></pre>
<p><code>integral_CppFunctionCUBATURE</code> is the function I use with <code>cubintegrate</code>. In R, I would then do:</p>
<p>sourceCpp('./myCppcode.cpp')</p>
<pre><code>xA0<-3
xB0<-2
yA0<-5
yB0<-10
t<-500
sigma<-1
cubature::cubintegrate(integral_CppFunctionCUBATURE,lower=rep(-1000,4), upper=rep(1000,4),
xA0=xA0, xB0=xB0, yA0=yA0,yB0=yB0, t1=t, sigma=sigma,method='cuhre')$integral
</code></pre>
<p>Result: 0.9999978</p>
<p>The multidimensional integration takes about 4 sec, but I would like to speed it up as much as possible, since when I run the multidimensional integration on several xA0 values this can take quite some time. Do you have any suggestion on how I could improve the speed of the code?</p>
<p>And also, would you suggest an alternative way to perform fast 4-dimensional integration in <code>C++</code>/<code>Rcpp</code>?</p>
|
[] |
[
{
"body": "<h1>Sources of slowness</h1>\n<p>The actual calculations you are doing are fine, I don't see anything you can optimize that the compiler won't already do for you itself. The main overhead will be caused by R repeatedly having to call <code>integral_CppFunctionCUBATURE()</code>. The first issue I see is that you are passing <code>NumericVector Zt_pos</code> by value, but all the <code>double</code>s by reference. That's exactly the wrong way around. While <code>Rccp::NumericVector</code> itself already has reference semantics, it still needs to do reference counting, and that can be avoided by passing it as a reference. You are not trying to modify the <code>double</code> parameters, so passing it by reference just means you are going to pay to overhead of pointer indirection. Pass them by value instead.</p>\n<p>The next issue is that R's <code>cubature::cubintegrate()</code> function is going to repeatedly have to call your function. You can avoid this by implementing the same algorithm as R uses in C++, so it can inline your <code>integral_CppFunctionCubature()</code>. It probably won't give a dramatic speedup though; the Cuhre method in R is implemented in C, and function call overhead is probably not that big compared to the actual cost of the calculations you are doing.</p>\n<h1>Choose the right integration algorithm</h1>\n<p>I am assuming that you don't just want to integrate the Guassian distribution function from effectively <span class=\"math-container\">\\$-\\infty\\$</span> to <span class=\"math-container\">\\$+\\infty\\$</span>, as the result will by definition be 1. Assuming you want to integrate other functions, first check if you can integrate that function analytically. If not, then which algorithm works best to integrate it will depend on the shape of the function inside the range you want to integrate over. The Cuhre algorithm might not be the best, so try out others and benchmark their speed and accuracy if possible.</p>\n<h1>Don't <code>#include</code> headers you are not using</h1>\n<p>I see you are including a lot of headers, but almost none are actually used. This will just unnecessarily slow down compilation. The only headers you need are those for Rccp (for <code>Rccp::NumericVector</code>) and those for the math functions you use. For the latter, make sure you include the C++ version:</p>\n<pre><code>#include <cmath>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T19:08:26.187",
"Id": "524737",
"Score": "1",
"body": "For the avoidance of uncertainty: including `<cmath>` rather than `<math.h>` means you need to call `std::sqrt()`, `std::pow()` and `std::exp()` rather than the global-namespace versions (even if the latter are defined, on your platform). This is a Good Thing, as it separates standard identifiers from your own ones. (Addressed at asker, not at you, G.S.!)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T19:17:52.927",
"Id": "524738",
"Score": "0",
"body": "OK, clear! I was wondering whether it would be possible in c++ to split multidimensional integration in chuncks for parallelization and if you think that this would speed up the algorithm."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T19:28:30.920",
"Id": "524740",
"Score": "0",
"body": "Parallelization of adaptive numerical integration is not trivial. You could try the solution mentioned in [this StackOverflow question](https://stackoverflow.com/questions/50103632/parallelize-integrate-in-r), but note the comment below the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T10:54:57.390",
"Id": "524798",
"Score": "0",
"body": "Ok, indeed splitting up the integral intervals could be a good idea, but I see that the real limiting factor is the complexity of the integrand."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T19:02:45.320",
"Id": "265674",
"ParentId": "265667",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "265674",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T16:43:34.860",
"Id": "265667",
"Score": "3",
"Tags": [
"c++",
"performance",
"numerical-methods",
"rcpp"
],
"Title": "Implementation of Multidimensional numerical integration in C++ and R"
}
|
265667
|
<p>So I made an inverted index following a tutorial online and was wondering if I can improve it by implementing one or more algorithms or reduce code or maybe make the processing files faster. I am using .txt files as data which there is not a lot of files but if the there is then this inverted index might not be that fast and this is for a search engine that I am working on that I plan on releasing it for fun but I want to make it efficient so I can learn more to become a better programmer since that's the reason I started on my search engine project.</p>
<pre><code>import re
import math
from nltk.stem import *
from nltk.tokenize import sent_tokenize, word_tokenize
class BuildIndex:
def __init__(self, files):
self.tf = {}
self.df = {}
self.idf = {}
self.filenames = files
self.file_to_terms = self.process_files(self.filenames)
self.regdex = self.regIndex(self.filenames)
self.totalIndex = self.execute()
self.vectors = self.vectorize()
self.mags = self.magnitudes(self.filenames)
self.populateScores()
def process_files(self,filenames):
file_to_terms = {}
for file in filenames:
pattern = re.compile('[\W_]+')
file_to_terms[file] = open(file, 'r').read().lower();
file_to_terms[file] = pattern.sub(' ',file_to_terms[file])
re.sub(r'[\W_]+','', file_to_terms[file])
file_to_terms[file] = file_to_terms[file].split()
with open(file) as f:
file_to_terms[file] = f.readlines()
# to remove whitespace characters like `\n` at the end of each line
file_to_terms[file] = [x.strip() for x in file_to_terms[file]]
return file_to_terms
def index_one_file(self, termlist):
fileIndex = {}
ps = PorterStemmer()
for index, words in enumerate(termlist):
line=words.split()
for word in line:
word=word.lower()
word=word.strip('.')
word=word.strip(',')
word = ps.stem(word)
if word in fileIndex.keys():
fileIndex[word].append(index)
else:
fileIndex[word] = [index]
return fileIndex
def make_indices(self, termlists):
total = {}
for filename in termlists.keys():
total[filename] = self.index_one_file(termlists[filename])
return total
def fullIndex(self):
total_index = {}
indie_indices = self.regdex
for filename in indie_indices.keys():
self.tf[filename] = {}
for word in indie_indices[filename].keys():
self.tf[filename][word] = len(indie_indices[filename][word])
if word in self.df.keys():
self.df[word] += 1
else:
self.df[word] = 1
if word in total_index.keys():
if filename in total_index[word].keys():
total_index[word][filename].append(indie_indices[filename][word][:])
else:
total_index[word][filename] = indie_indices[filename][word]
else:
total_index[word] = {filename: indie_indices[filename][word]}
return total_index
def vectorize(self):
vectors = {}
for filename in self.filenames:
vectors[filename] = [len(self.regdex[filename][word]) for word in self.regdex[filename].keys()]
return vectors
def document_frequency(self, term):
if term in self.totalIndex.keys():
return len(self.totalIndex[term].keys())
else:
return 0
def collection_size(self):
return len(self.filenames)
def magnitudes(self, documents):
mags = {}
for document in documents:
mags[document] = pow(sum(map(lambda x: x**2, self.vectors[document])),.5)
return mags
def term_frequency(self, term, document):
return self.tf[document][term]/self.mags[document] if term in self.tf[document].keys() else 0
def populateScores(self):
for filename in self.filenames:
for term in self.getUniques():
self.tf[filename][term] = self.term_frequency(term, filename)
if term in self.df.keys():
self.idf[term] = self.idf_func(self.collection_size(), self.df[term])
else:
self.idf[term] = 0
return self.df, self.tf, self.idf
def idf_func(self, N, N_t):
if N_t != 0:
return math.log(1 + N/N_t)
else:
return 1
def generateScore(self, term, document):
return self.tf[document][term] * self.idf[term]
def execute(self):
return self.fullIndex()
def regIndex(self,filenames):
file_to_terms={}
for file in filenames:
file_to_terms[file]=self.file_to_terms[file]
return self.make_indices(file_to_terms)
def getUniques(self):
return self.totalIndex.keys()
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T20:27:00.443",
"Id": "265676",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"algorithm",
"search"
],
"Title": "Simple Inverted Index made in python"
}
|
265676
|
<p>So I've started writing an OS to know how they work, and I came up with the following makefile to compile it.</p>
<p>The reason I used a makefile is because I wanted to <em>see</em> everything it was doing and have full control over it, to be as explicit as possible. Hence, please don't tell me about CMake (I don't care enough to switch to it, and I find the syntax quite... not ugly, but definitely too compacted at times), or autotools (except if you think it does <em>exactly</em> what I want. I want it to be as explicit as possible as well), or other Makefile-like generators.</p>
<p>Furthermore, please don't tell me about implicit rules or their brother <code>.c.o</code>. I know. I don't want them. They're <em>implicit</em> (and also they generate the object next to the source, which I find annoying and unwanted).</p>
<hr />
<p>With that out of the way, here's what I want it to be able to do:</p>
<p>I only use GNU Make and a Linux distribution (though it's supposed to be a standalone build, not much should be impacted by the source OS...). I'm currently on an x86_64 computer, and I don't think I'll ever change, but if there are easy fixes I could make, please do tell. Because I like to be up-to-date, I don't care about features only present in recent <code>make</code>s, I can use it if it's useful.</p>
<p>My current tree (after a <code>make distclean</code> or a <code>git clone</code>) is:</p>
<pre><code>.
├── Makefile
└── src
├── common
│ └── include
│ └── string.h
├── i686
│ └── linker.ld
└── kernel
├── include
│ ├── arch
│ │ └── i686
│ │ └── [some headers]
│ └── [some headers]
└── source
├── arch
│ └── i686
│ └── [some sources]
└── [some sources]
</code></pre>
<p>(If you need the exact tree, I can put it.)</p>
<p>As you can see, I want to be able to support multiple destination architectures, as well as a potential <code>libc</code> (and maybe <code>libk</code> when I understand what it's used for; I only have C and memory management setup hopefully correctly right now in it, so it's far from being complete).</p>
<p>The Makefile generates a parallel tree of <code>src</code> in <code>makedeps</code> for any <code>.mk</code> source dependencies and another in <code>obj/[debug or release]</code> for objects.</p>
<p>Once all objects are compiled, a new directory <code>$(SYSROOT)</code> is created and populated with the root directory of the image file (as I understand how <code>grub-mkrescue</code> works), including all required headers and/or object/binary/... files (of which I have none for now). It also generates a GRUB configure file and then packages everything in a single <code>iso</code>.</p>
<p>One feature my Makefile takes advantage of that I have not seen on this site is that I use <code>eval</code>s and <code>call</code>s. I have made some "functions" to add a source file for the kernel (no wildcard, <em>as explicit as possible</em>), which could easily be adapted to add source files to a <code>libc</code>.</p>
<p>This makefile is thus structured as such:</p>
<ol>
<li><code>all</code> default target</li>
<li>Variables definitions</li>
<li>"Functions"/macros definitions</li>
<li>Files declarations</li>
</ol>
<hr />
<p>What I'd like to know is:</p>
<ol>
<li>What would you do differently (apart from "use $(YOUR_PREFERRED_MAKE_GENERATOR) instead")?</li>
<li>Is there anything that seems wrong/hardly maintainable?</li>
<li>Is this Makefile easily modifiable to fit for generic C/C++ compiling?</li>
<li>Is this Makefile organized in a logical and readable way?</li>
<li>Are there GNU Make features (or compiler options) that I am missing? (For instance, would <code>VPATH</code> be useful in this situation? As I understand it, it's useful for compilation out of the source tree, which seems... redundant.)</li>
<li>What other things could I improve?</li>
<li>More specific question: I use ANSI escape codes for colors. Should I assume such a computer also has <code>mkdir -p</code> support (which would remove some dependencies)?</li>
</ol>
<p>Also, if I need to add some comments, please tell me.</p>
<hr />
<pre><code>all:
.PHONY: all
NAME?=kernel
SYSROOT?=sysroot
TARGET_MACHINE?=i686
OPTIM?=2
DEBUG?=1
# FORCE_COLOR: set to non-empty, non 0 to force colorized output
# ECHO: set to non-empty, non 0 to echo commands out
usage:
@echo 'Targets:'
@echo ' - usage (current target)'
@echo ' - all (default target)'
@echo ' - kernel.iso'
@echo ' - obj/{target}/*.o'
@echo ' - clean'
@echo ' - distclean'
@echo ''
@echo 'Options:'
@echo ' - NAME: rename the kernel in the GRUB menu'
@echo ' - SYSROOT: system root directory'
@echo ' - TARGET_MACHINE: target architecture'
@echo ' - OPTIM: GCC optimization level (-O is prepended)'
@echo ' - DEBUG: set to 0 for release build, set to non-0 for debug build (default)'
@echo ' - FORCE_COLOR: set to non-0 to force colorized output'
@echo ' - ECHO: set to non-0 to echo out commands executed'
.PHONY: usage
ifeq ($(ECHO:0=),)
SILENCER:=@
else
SILENCER:=
endif
ifeq ($(SYSROOT),)
$(error SYSROOT cannot be empty!)
endif
ifeq ($(strip $(TARGET_MACHINE)),i686)
AS:=i686-elf-as
CC:=i686-elf-gcc
CXX:=i686-elf-g++
else
$(error Unknown target machine $(strip $(TARGET_MACHINE)))
endif
ifneq ($(strip $(DEBUG)),0)
CFLAGS+= -g -DDEBUG
CXXFLAGS+= -g -DDEBUG
OBJDIR?=debug
else
CFLAGS+= -DRELEASE
CXXFLAGS+= -DRELEASE
OBJDIR?=release
endif
COMMON_WARNINGS:=-Wall -Wextra -Wfloat-equal -Wundef -Werror=shadow -Werror=implicit-function-declaration
COMMON_WARNINGS+= -Werror=return-type -Werror=pointer-arith -Werror=strict-overflow
COMMON_WARNINGS+= -Wwrite-strings -Waggregate-return -Wcast-qual -Werror=switch-enum -Wconversion -Wunreachable-code
COMMON_WARNINGS+= -Werror=format=2 -Werror=format-overflow=2 -Werror=format-signedness -Wformat-truncation=2
COMMON_WARNINGS+= -Wnull-dereference -Wimplicit-fallthrough=3 -Wfatal-errors
COMMON_WARNINGS+= -fanalyzer -Wmissing-include-dirs -Wshift-overflow=2 -Wunknown-pragmas -Wstringop-overflow=4
COMMON_WARNINGS+= -Wsuggest-attribute=pure -Wsuggest-attribute=const -Wsuggest-attribute=noreturn
COMMON_WARNINGS+= -Wsuggest-attribute=malloc -Wsuggest-attribute=format -Wsuggest-attribute=cold -Wmissing-noreturn
COMMON_WARNINGS+= -Wmissing-format-attribute -Walloc-zero -Werror=attribute-alias=2 -Wduplicated-branches
COMMON_WARNINGS+= -Werror=duplicated-cond -Wsystem-headers -Wtrampolines -Wstack-usage=1024 -Wunsafe-loop-optimizations
COMMON_WARNINGS+= -Wunused-macros -Wcast-align=strict -Wdate-time -Wlogical-op -Wredundant-decls -Winline
COMMON_WARNINGS+= -Wdisabled-optimization
CFLAGS_WARNINGS:= -Werror=jump-misses-init -Werror=strict-prototypes
CXXFLAGS_WARNINGS:= -Werror=overloaded-virtual
override ASFLAGS+=
override CFLAGS+= -Isrc/common/include -std=gnu17 -ffreestanding -O$(OPTIM) $(COMMON_WARNINGS) $(CFLAGS_WARNINGS)
override CXXFLAGS+= -Isrc/common/include -std=gnu++20 -ffreestanding -fdiagnostics-show-template-tree -O$(OPTIM) $(COMMON_WARNINGS)
override CXXFLAGS+= $(CXXFLAGS_WARNINGS)
# Machine specific
ifeq ($(strip $(TARGET_MACHINE)),i686)
# SSE3 is required, AVX/AVX512 is enabled if available
override CFLAGS+= -mmmx -msse -msse2 -msse3
override CXXFLAGS+= -mmmx -msse -msse2 -msse3
override CFLAGS+= -DIS_I686
override CXXFLAGS+= -DIS_I686
#CFLAGS/CXXFLAGS+= -mcmodel=kernel -mno-red-zone in x86-64
endif
# For the entry kernel file, if compiled in C++
# CXXFLAGS_ENTRYKER=-fno-exception -fno-rtti
override LDFLAGS+= -ffreestanding -O$(OPTIM) -nostdlib
override LDLIBS+= -lgcc
ASKERFLAGS+=
CKERFLAGS+= -D__kernel__ -Isrc/kernel/include
CXXKERFLAGS+= -D__kernel__ -Isrc/kernel/include
CRTBEGIN_OBJ:=$(shell $(CC) $(CFLAGS) -print-file-name=crtbegin.o)
CRTEND_OBJ:=$(shell $(CC) $(CFLAGS) -print-file-name=crtend.o)
OBJLIST=$(OBJLIST_KERNEL)
OBJLIST_KERNEL:=
SPECIAL_OBJS:=%/crti.o $(CRTBEGIN_OBJ) $(CRTEND_OBJ) %/crtn.o
INSTALL_HEADERS:=
# Until bug #101648 is fixed
obj/$(OBJDIR)/kernel/arch/i686/mm.o: private CFLAGS+= -Wno-analyzer-malloc-leak
.SUFFIXES:
.SECONDEXPANSION:
ifneq ($(MAKECMDGOALS),clean)
.: ;
# $(eval $(call reproduce_tree,<base>))
define reproduce_tree =
$(1): ; $(SILENCER)mkdir <span class="math-container">$$@
$(1)/kernel: | $(1) ; $(SILENCER)mkdir $$</span>@
$(1)/kernel/arch: | $(1)/kernel ; $(SILENCER)mkdir <span class="math-container">$$@
$(1)/kernel/arch/$(TARGET_MACHINE): | $(1)/kernel/arch ; $(SILENCER)mkdir $$</span>@
endef
obj: ; $(SILENCER)mkdir $@
obj/$(OBJDIR): | obj
$(eval $(call reproduce_tree,obj/$(OBJDIR)))
$(eval $(call reproduce_tree,makedir))
$(SYSROOT): ; $(SILENCER)mkdir $@
$(SYSROOT)/boot: | $(SYSROOT) ; $(SILENCER)mkdir $@
$(SYSROOT)/boot/grub: | $(SYSROOT)/boot ; $(SILENCER)mkdir $@
$(SYSROOT)/usr: | $(SYSROOT) ; $(SILENCER)mkdir $@
$(SYSROOT)/usr/include: | $(SYSROOT)/usr ; $(SILENCER)mkdir $@
endif
# Colors:
# -------
# +----------+-----------+
# | 3 | 9 |
# +-+----------+-----------+
# |0| | | Black
# |1| | RM | Red
# |2| | [MSG] | Green
# |3| Creating | ISO | Yellow
# |4|Installing| CP | Blue
# |5| --- |LD/Checking| Purple
# |6| AS/C/C++ | | Cyan
# |7| | | White/gray
# +-+----------+-----------+
# $(call colorize,<br_color>,<br_text>,<text_color>,<text>)
ifdef $(if $(FORCE_COLOR:0=),FORCE_COLOR,MAKE_TERMOUT)
colorize=@echo "\033[$(1)m[$(2)]\033[m \033[$(3)m$(4)\033[m"
else
colorize=@echo "[$(2)] $(4)"
endif
define newline :=
endef
# $(call remove,<list of file_names to remove>)
define remove =
$(call colorize,1;91,RM ,91,Removing $(1))
$(SILENCER)$(RM) -r $(1)
endef
# $(eval $(call install_header,<install_dir>,<source_dir>,<file_name>))
define install_header =
INSTALL_HEADERS+=$(SYSROOT)/usr/include/$(1)$(3)
$(SYSROOT)/usr/include/$(1)$(3): src/$(2)$(3) | <span class="math-container">$$$$</span>(@D)
$(call colorize,94,CP ,34,Installing $(3))
$(SILENCER)cp <span class="math-container">$$^ $$</span>@
endef
# $(eval $(call add_deptree,<output_filename_noext>,<input_filename_withoutsrc>))
ifeq ($(MAKECMDGOALS),clean)
add_deptree=
else
define add_deptree =
makedir/$(1).mk: | <span class="math-container">$$$$</span>(@D)
$(call colorize,95,DEP,33,Creating $(2) dependancies)
$(SILENCER)set -e; <span class="math-container">$$(CC) $$</span>(CFLAGS) <span class="math-container">$$(CKERFLAGS) -MM src/$(2) \
| sed 's,\($$</span>(notdir <span class="math-container">$$(basename $(2)))\)\.o[ :]*,src/$$</span>(dir $(2))\1.o <span class="math-container">$$@: ,g' >$$</span>@
include makedir/$(1).mk
endef
endif
# $(call kernel_o,<base_dir>,<source_filename>,<output_filename>)
kernel_o=obj/$(OBJDIR)/kernel/$(1)$(3).o
# $(eval $(call compile_kernel_s,<base_dir>,<source_filename>,<output_filename>))
define compile_kernel_s =
OBJLIST_KERNEL+=$(call kernel_o,$(1),$(2),$(3))
$(call kernel_o,$(1),$(2),$(3)): src/kernel/source/$(1)$(2).s | <span class="math-container">$$$$</span>(@D)
$(call colorize,36,AS ,92,Compiling <span class="math-container">$$@)
$(SILENCER)$$</span>(AS) <span class="math-container">$$(ASFLAGS) $$</span>(ASKERFLAGS) -c src/kernel/source/$(1)$(2).s -o <span class="math-container">$$@
endef
# $(eval $(call compile_kernel_c,<base_dir>,<source_filename>,<output_filename>))
define compile_kernel_c =
$$</span>(eval <span class="math-container">$$(call add_deptree,kernel/$(1)$(3),kernel/source/$(1)$(2).c))
OBJLIST_KERNEL+=$(call kernel_o,$(1),$(2),$(3))
$(call kernel_o,$(1),$(2),$(3)): src/kernel/source/$(1)$(2).c | $$</span><span class="math-container">$$(@D)
$(call colorize,36,C ,92,Compiling $$</span>@)
$(SILENCER)<span class="math-container">$$(CC) $$</span>(CFLAGS) <span class="math-container">$$(CKERFLAGS) -c src/kernel/source/$(1)$(2).c -o $$</span>@
endef
# $(eval $(call compile_kernel_cxx,<base_dir>,<source_filename>,<output_filename>))
define compile_kernel_cxx =
<span class="math-container">$$(eval $$</span>(call add_deptree,kernel/$(1)$(3),kernel/source/$(1)$(2).cpp))
OBJLIST_KERNEL+=$(call kernel_o,$(1),$(2),$(3))
$(call kernel_o,$(1),$(2),$(3)): src/kernel/source/$(1)$(2).cpp | <span class="math-container">$$$$</span>(@D)
$(call colorize,36,C++,92,Compiling <span class="math-container">$$@)
$(SILENCER)$$</span>(CXX) <span class="math-container">$$(CXXFLAGS) $$</span>(CXXKERFLAGS) -c src/kernel/source/$(1)$(2).cpp -o $$@
endef
# $(eval $(call compile_arch_dependant,<arch list>,<group>,<lang>,<args...>)); arch will be added automatically
compile_arch_dependant = $(foreach arch,$(1),$\
$(if $(TARGET_MACHINE:$(arch)),$\
OBJLIST+=$(call $(2)_o,$(4),$(5),$(6))$(newline),$\
$(call compile_$(2)_$(3),arch/$(arch)/$(4),$(5),$(6))$(newline)))
kernel.iso: $(SYSROOT)/boot/kernel.kern | $(SYSROOT)/boot/grub
$(call colorize,93,ISO,33,Creating iso)
$(SILENCER)echo "menuentry \"$(NAME)\" {\n\tmultiboot /boot/kernel.kern\n}" >$(SYSROOT)/boot/grub/grub.cfg
$(SILENCER)grub-mkrescue -o kernel.iso $(SYSROOT) -quiet
$(SYSROOT)/boot/kernel.kern: <span class="math-container">$$(OBJLIST_KERNEL) obj/$(OBJDIR)/kernel/arch/$(TARGET_MACHINE)/crti.o \
obj/$(OBJDIR)/kernel/arch/$(TARGET_MACHINE)/crtn.o src/$(TARGET_MACHINE)/linker.ld | $$</span>(@D)
$(call colorize,95,LD ,92,Linking $@)
$(SILENCER)$(CC) -T src/$(TARGET_MACHINE)/linker.ld -o $@ \
obj/$(OBJDIR)/kernel/arch/$(TARGET_MACHINE)/crti.o $(CRTBEGIN_OBJ) $(OBJLIST_KERNEL) $(LDFLAGS) $(LDLIBS) \
$(CRTEND_OBJ) obj/$(OBJDIR)/kernel/arch/$(TARGET_MACHINE)/crtn.o
$(call colorize,35,---,95,Checking output kernel)
$(SILENCER)grub-file --is-x86-multiboot $@
$(eval $(call compile_arch_dependant,i686,kernel,s,,crti,crti))
$(eval $(call compile_arch_dependant,i686,kernel,s,,boot,boot))
$(eval $(call compile_arch_dependant,i686,kernel,s,,tables,tables))
$(eval $(call compile_arch_dependant,i686,kernel,s,,interrupts,interrupts))
$(eval $(call compile_arch_dependant,i686,kernel,s,,apic,apic))
$(eval $(call compile_arch_dependant,i686,kernel,s,,atomic,atomic))
$(eval $(call compile_kernel_c,,entry,entry))
$(eval $(call compile_arch_dependant,i686,kernel,c,,kernel,kernel))
$(eval $(call compile_arch_dependant,i686,kernel,s,,tty,tty.s))
$(eval $(call compile_arch_dependant,i686,kernel,c,,tty,tty.c))
$(eval $(call compile_arch_dependant,i686,kernel,c,,mm,mm))
$(eval $(call compile_kernel_c,,multiboot,multiboot))
$(eval $(call compile_arch_dependant,i686,kernel,s,,crtn,crtn))
OBJLIST_KERNEL:=$(filter-out $(SPECIAL_OBJS),$(OBJLIST_KERNEL))
all: kernel.iso
clean:
$(call remove,kernel.iso)
$(call remove,isodir)
$(call remove,$(OBJLIST))
$(call remove,obj/$(OBJDIR)/kernel/arch/$(TARGET_MACHINE)/crti.o obj/$(OBJDIR)/kernel/arch/$(TARGET_MACHINE)/crtn.o)
$(call remove,$(INSTALL_HEADERS))
.PHONY: clean
distclean: clean
$(call remove,makedir)
.PHONY: distclean
.DELETE_ON_ERROR:
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T21:56:22.160",
"Id": "524748",
"Score": "0",
"body": "By the way, this was detected as spam... Any idea why? (I saw [here](https://meta.stackexchange.com/questions/311147/this-looks-like-spam-error-message-when-attempting-to-ask-a-non-spam-question) that the length is the problem, but I don't really know why. Also, removing the makefile fixed the issue... Maybe someone should report this to meta? (Me maybe?))"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T07:54:31.007",
"Id": "524785",
"Score": "1",
"body": "Implicit rules \"generate the object next to the source\" only if you're building in the source directory. You probably want an _out-of-tree_ build, so you can have multiple builds with different configurations, and keep the sources read-only. Implicit rules work well for this, in conjunction with `VPATH`."
}
] |
[
{
"body": "<p>Here are some things that may help you improve your code.</p>\n<h2>Understand your tools</h2>\n<p>There are a huge number of redundant compiler warnings that serve little purpose except to clutter up the Makefile. I would recommend trimming that to the smallest possible non-redundant equivalent. The reason is that it will be very painful if you decide that you need to, for example, ignore a particular cast warning, but can't easily turn it off because <code>-Wall</code> enables it anyway.</p>\n<p>Also, alphabetizing the remaining flags will help in maintenance. The documentation for gcc, for example, shows the <code>-Wall</code> and <code>-Wextra</code> flags in alphabetical order, which makes it easier to scan the list.</p>\n<h2>Don't override all user settings</h2>\n<p>If I have set <code>ASFLAGS</code>, <code>CFLAGS</code>, and <code>CXXFLAGS</code> on my system, it seems rather presumptuous to override every single one of those in the Makefile. Better would be to either allow for using either user environment strings or at the very least letting the user know you're ignoring all of them.</p>\n<h2>Put user-adjustable variables at the top</h2>\n<p>I have the equivalent of <code>i686-elf-gcc</code> on my machine, but that is not the name of the executable on my machine. User variables such as these should be at the top of the Makefile, if they're used at all (see previous note).</p>\n<h2>Support out-of-tree build</h2>\n<p>Right now, everything is rigidly nailed in place with no flexibility about where or how the project is built. The problem with that is that it means that, for example, trying two different versions to see how they perform, is made more difficult because there is not any obvious way to specify the destination directory tree. That is something that <code>autotools</code> supports that is extremely useful.</p>\n<h2>Rethink your use of macros</h2>\n<p>The Makefile current contains this:</p>\n<pre><code>define compile_kernel_c =\n<span class=\"math-container\">$$(eval $$</span>(call add_deptree,kernel/$(1)$(3),kernel/source/$(1)$(2).c))\nOBJLIST_KERNEL+=$(call kernel_o,$(1),$(2),$(3))\n$(call kernel_o,$(1),$(2),$(3)): src/kernel/source/$(1)$(2).c | <span class=\"math-container\">$$$$</span>(@D)\n $(call colorize,36,C ,92,Compiling <span class=\"math-container\">$$@)\n $(SILENCER)$$</span>(CC) <span class=\"math-container\">$$(CFLAGS) $$</span>(CKERFLAGS) -c src/kernel/source/$(1)$(2).c -o $$@\nendef\n</code></pre>\n<p>This is obtuse in the extreme. If the purpose is to provide separate flags for certain subsets of source code, the way to do that is to create variables such as your existing <code>OBJLIST_KERNEL</code> for each of the different types and then create either an explicit or implicit rule for each. You can have 100% control with implicit rules if you think carefully about what you're doing.</p>\n<p>If you run gnu <code>make</code> with <code>--trace --always-build</code> you will see that the build is not reliable with this Makefile. If, for example, the <code>obj</code> directory already exists, it will fail.</p>\n<h2>Consider supporting a "help" target</h2>\n<p>Most <code>Makefiles</code> that I use or maintain support <code>make help</code> rather than <code>make usage</code>. At the least, I'd suggest supporting <code>help</code> as an alias for <code>usage</code>.</p>\n<h2>Fix the bug(s)</h2>\n<p>Your <code>colorize</code> macro does not seem to work on my 64-bit Linux machine. Instead of color, I get things like this:</p>\n<pre><code>make: i686-elf-gcc: No such file or directory\nmake: i686-elf-gcc: No such file or directory\n\\033[95m[DEP]\\033[m \\033[33mCreating kernel/source/multiboot.c dependancies\\033[m\n/bin/sh: i686-elf-gcc: command not found\n</code></pre>\n<p>The reason for this is that you are using <code>\\033</code> to represent <code>ESC</code>, but that requires the use of <code>echo -e</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T09:27:40.803",
"Id": "524787",
"Score": "0",
"body": "So, in order: **Tools:** Well, actually I don't think any of these flags are redundant. I've read the entire GCC documentation about common warnings to make sure only disabled flags are enabled. Yup, `-Wall -Wextra` doesn't do all... (There are still some left disabled.) One thing to consider too is that I specfically enabled all of those since I work with only my files which are warning-free. Obviously, I wouldn't want all of these in someone else's build :p Though, thanks for the feedback about disabling some warnings. I'll change the `CFLAGS+=` into a `CFLAGS:=[warnings] $(CFLAGS) ...`[1/x]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T09:34:18.260",
"Id": "524789",
"Score": "0",
"body": "**USER-adjustable variables:** Yeah, I could just check where the variable come from before overriding it. (The problem is that their default value doesn't work for me, or rather shouldn't work for anyone...) **Out-of-tree build:** Now, it's not like I *hate* it. It's just, is it really useful here? And doesn't `make -f` somewhere else already do that? **Macros:** Well, I don't think that's really the way to go here, because of multiple destination targets support. I *can* see another way to do it though (`foreach` after adding all of the files), but the rule would still be *huge*. [2/3]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T09:40:03.500",
"Id": "524790",
"Score": "0",
"body": "**help:** Yep, I'll fix that (the rest of the makefile I was reading the documentation in parallel, for this one I just said \"Oh yeah I need something like that\"). **Bug:** Huh, weird. For me, it works even when setting `MAKE_SHELL` to `/bin/sh`... After a quick search I found out I should rather use `printf`. Well, thanks for the review anyways! I'll mark it as the answer. [3/3]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T12:34:17.217",
"Id": "524805",
"Score": "0",
"body": "If you read the gcc docs closely, you'll see that `-Wimplicit-fallthrough=3` is enabled by `-Wextra` and is also separately listed in your makefile. That meets my definition of \"redundant.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T13:40:48.113",
"Id": "524809",
"Score": "0",
"body": "Whoops. Well, 1 doesn't meet my definition of \"huge number\"... :p (Still, I'll remove it. It'd be nicer if GCC could have a `-Wyes-I-want-all` though...) I've found another redundant warning, but 2 isn't \"a lot\"... (I agree though, it's still a huge block.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T15:51:01.560",
"Id": "524824",
"Score": "0",
"body": "I've updated my answer with some additional detail."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T17:15:04.473",
"Id": "524838",
"Score": "0",
"body": "So for the edit: **tools:** I didn't think of sorting the flags by alphabetic order... Thanks for pointing that out. **\"Macros\"** *(not really in the right category, but anyway)* to be fair, usually it isn't supposed to execute a target when it already exists. But still, I got to also fix some issues elsewhere with it (notably on the use of `$(CPPFLAGS)`...), so thanks. **Bug:** yeah, I don't know why it works on my computer. Still, `printf` is the portable way to go. **PS:** for your macro complaint, you're right about its goal: I plan to have `compile_libc_c` et al. for libc et al."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T23:51:55.210",
"Id": "265682",
"ParentId": "265679",
"Score": "2"
}
},
{
"body": "<blockquote>\n<pre><code>colorize=@echo "\\033[$(1)m[$(2)]\\033[m \\033[$(3)m$(4)\\033[m"\n</code></pre>\n</blockquote>\n<p>How do you know what kind of terminal is being used? Or even that output is going to a terminal? This is the kind of crap that makes build logs hard to read.</p>\n<p>If you really must do this, use <code>tput</code> to determine the codes you want (when supported by the output device, or a nice empty string when not).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T09:25:57.523",
"Id": "524786",
"Score": "0",
"body": "Well, that's what `MAKE_TERMOUT` is for. I tested, and when redirecting to `less` colors are removed. If you don't like it, I could add support for a `FORCE_NO_COLOR`, but... is that really useful?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T07:57:03.323",
"Id": "265694",
"ParentId": "265679",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "265682",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T21:54:12.770",
"Id": "265679",
"Score": "2",
"Tags": [
"makefile",
"kernel"
],
"Title": "Makefile to compile an OS which also uses functions/macros"
}
|
265679
|
<p>This is poorly written Java code, intended to implement a thread-safe collection to store Member objects and failing at doing so.</p>
<pre><code>import javax.annotation.concurrent.ThreadSafe;
import java.io.Closeable;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
/**
* A thread-safe container that stores a group ID and members.
*
* This class can store Member and/or AdminMember.
* Also, it can start and stop a background task that writes a member list to specified 2 files.
*
* This class is called many times, so it should have a good performance.
*
* Example usage:
*
* MemberGroup group = new MemberGroup("group-001");
*
* group.addMember(new MemberGroup.Member("member-100", 42));
* group.addMember(new MemberGroup.AdminMember("admin-999", 30));
* group.addMember(new MemberGroup.Member("member-321", 15));
*
* group.startLoggingMemberList10Times("/tmp/output.primary", "/tmp/output.secondary");
*/
@ThreadSafe
public class MemberGroup
implements Closeable
{
String groupId;
HashSet<Member> members;
boolean isRunning;
boolean shouldStop;
class Member
{
String memberId;
int age;
Member(String memberId, int age)
{
this.memberId = memberId;
this.age = age;
}
public String getMemberId()
{
return memberId;
}
public int getAge()
{
return age;
}
// TODO: check class type too
public boolean equals(Object o)
{
// If `memberId` matches the other's one, they should be treated as the same `Member` objects.
Member member = (Member) o;
return this.memberId == member.memberId;
}
}
class AdminMember extends Member
{
AdminMember(String memberId, int age)
{
super(memberId, age);
}
}
public MemberGroup(String groupId)
{
this.groupId = groupId;
this.members = new HashSet<>();
}
public void addMember(Member member)
{
members.add(member);
}
// TODO: Need to create a Decorator class for print memberId?
private String getDecoratedMemberId(Member member)
{
if (member instanceof Member) {
return member.getMemberId() + "(normal)";
}
else if (member instanceof AdminMember) {
return member.getMemberId() + "(admin)";
}
return null;
}
// TODO: Need to create a Decorator class for calculation too?
private String getMembersAsStringFlooringAge()
{
String buf = "";
for (Member member : members)
{
// Floor the age: e.g. 37 -> 30
Integer flooredAge = (member.getAge() / 10) * 10;
String decoratedMemberId = getDecoratedMemberId(member);
buf += String.format("memberId=%s, age=%d¥n", decoratedMemberId, flooredAge);
}
return buf;
}
@Override
public void close()
throws IOException
{
}
/**
* Run a background task that writes a member list to specified files 10 times in background thread
* so that it doesn't block the caller's thread.
*
* Only one thread is allowed to run at once
* - When this method is called and another thread is running, the method call should just return w/o starting any thread
* - When this method is called and another thread is already finished, the method call should start a new thread
*/
/*
TODO:
- Should return a CompletableFuture
- shouldStop should be volatile
- Using ExecutorService to support thread pool and to submit multi parallel tasks
- Create a runnable task name LoggingMembersTask to submit new thread using Threadpool. Each Task writes data to one file and it also check shouldStop to continue or not.
- Create a Job class as parameter for this startLoggingMemberList10Times method which contains
- the list of output file name
- the number of times each task should write members to file
- Each file in this job class is submitted 1 LoggingMembersTask to write output to file
- Using CompletableFuture to combine all Future from all submitted task by ExecutorService and return this CompletableFuture.
- The method should be rename to startLoggingMemberList to make it more generic and configurable.
- Should throw exception in case if job is summitted and not submit to stop.
*/
public void startLoggingMemberList10Times(final String outputFilePrimary, final String outputFileSecondary)
{
// Only one thread is allowed to run at once
if (isRunning) {
return;
}
isRunning = true;
new Thread(new Runnable() {
@Override
public void run()
{
int i = 0;
while (!shouldStop)
{
if (i++ >= 10)
break;
FileWriter writer0 = null;
FileWriter writer1 = null;
try {
String membersStr = DisappointingGroup.this.getMembersAsStringFlooringAge();
writer0 = new FileWriter(new File(outputFilePrimary));
writer0.append(membersStr);
writer1 = new FileWriter(new File(outputFileSecondary));
writer1.append(membersStr);
}
catch (Exception e) {
throw new RuntimeException(
"Unexpected error occurred. Please check these file names. outputFilePrimary="
+ outputFilePrimary + ", outputFileSecondary=" + outputFileSecondary);
}
finally {
try {
if (writer0 != null)
writer0.close();
if (writer1 != null)
writer1.close();
}
catch (Exception ignored) {
// Do nothing since there isn't anything we can do here, right?
}
}
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
/**
* Stop the background task started by startLoggingMemberList10Times
*/
public void stopPrintingMemberList()
{
shouldStop = true;
}
}
</code></pre>
<p>I also put some TODO comments which I am going to do to improve this code block. I don't know if I still miss anything else? How to safely stop all threads; is using a boolean flag like this good?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T01:42:52.883",
"Id": "524753",
"Score": "0",
"body": "I'm not sure where you think thread-safety is an issue."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T01:49:40.310",
"Id": "524754",
"Score": "0",
"body": "the code need to be refactor to avoid boiler plate code, defect code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T03:25:00.630",
"Id": "524756",
"Score": "0",
"body": "Did you already get a code review from one of your colleagues? It seems like you have posted one in the TODO section, and it seems like they know what they want from you.Therefore, code review here would be more relevant to you when you post the updated version. If you need help with how to implement those suggestions, you should ask the reviewer, your manager, google, stackoverflow etc, rather than here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T05:55:29.033",
"Id": "524762",
"Score": "0",
"body": "No, I am the code reviewer, and I don't know if it's still miss anything"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T06:13:12.227",
"Id": "524763",
"Score": "0",
"body": "I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Please check that I haven't misrepresented your code, and correct it if I have."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T10:22:08.147",
"Id": "524881",
"Score": "3",
"body": "Can you confirm that you're responsible for the maintenance of this code? We have rules about reviewing code that you've not written yourself (and for good reasons), so we want to be sure that it's okay to review this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T02:44:50.957",
"Id": "524938",
"Score": "0",
"body": "it's ok to review, I write and I want to review its by my self first. Self assessment"
}
] |
[
{
"body": "<h2>Thread Unsafe</h2>\n<p>It's not thread-safe. <code>addMember(Member member)</code> directly calls <code>members.add(member);</code> with <code>members</code> being a <code>HashSet</code>. And its documentation says</p>\n<blockquote>\n<p>Note that this implementation is not synchronized. If multiple threads\naccess a hash set concurrently, and at least one of the threads\nmodifies the set, it must be synchronized externally.</p>\n</blockquote>\n<p>So, wrap the HashSet into a <code>Collections.synchronizedSet(...)</code> expression, or use the <code>synchronized</code> keyword on relevant methods, or use other means of making the set access thread-safe.</p>\n<p>Making classes thread-safe can be tricky, and testing for thread-safety is close to impossible, so you have to do it right from the start by applying the correct patterns on a theoretical foundation.</p>\n<p>Another example of not being thread-safe is your <code>isRunning</code> field. Probably, this is meant to guarantee that there aren't multiple calls of <code>startLoggingMemberList10Times()</code> running in parallel. First of all, you should set it to <code>false</code> somewhere after you finished. But this pattern has so many loopholes where things will go wrong if it's really used in a multi-threading environment that I can't name them all.</p>\n<p>I can only recommend to get a good text book on multi-threading and really read through it. You'll learn where things can go wrong and what you can do against it.</p>\n<h2>Non-OO design</h2>\n<p><code>private String getDecoratedMemberId(Member member)</code> makes decisions depending on the class of <code>member</code>, using <code>instanceof</code>. Using <code>instanceof</code> always is an indicator of an OO design flaw. Instead, make that a method of the <code>Member</code> class which can be overridden in <code>AdminMember</code>. Or add a <code>public String getRole()</code> method to the <code>Member</code> class, and use that for the text generation.</p>\n<p>Why do you want to have two classes, <code>Member</code> and <code>AdminMember</code> at all? The only difference seems to be in generating some reporting text. This can be done more easily with a new field <code>private String role</code> in the <code>Member</code> class.</p>\n<p>If you really want to maintain different classes for the different member roles, then you'd better create an interface <code>Member</code> that defines the methods needed from a <code>Member</code>, and create classes like <code>NormalMember</code>, <code>AdminMember</code>, and maybe <code>GuestMember</code>, all implementing <code>Member</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T11:22:22.867",
"Id": "265701",
"ParentId": "265681",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-03T23:43:49.727",
"Id": "265681",
"Score": "-2",
"Tags": [
"java",
"multithreading",
"thread-safety"
],
"Title": "Thread-safe collection to store Member objects"
}
|
265681
|
<p>This is the second time I am writing any practical JavaScript so it is pretty likely that I have messed something up.</p>
<p>I am beginner, so just need a piece of advice before sharing the code: Do I need to be more focused on writing maintainable and flexible code or do I need to be more focused on writing as concise code as possible? Personally I am working for writing maintainable and flexible code, but I feel like the web is about transfer of data between the server and the client, so more code means slower transfer speed, which means rough user experience. But anyways, because minification can be done with the help of git, that is why I am practicing for maintainable and flexible code. Is it right thing to do?</p>
<p>This code only removes strings that have <code>"garbage"</code> (case-insensitive) in them. No matter how deep they lie.</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 dirtyArray = [{
id: 1,
listOfItems: ["item1", 34, null, 56, "totalgarbage", null],
garbage: "trash"
},
[2, "kPOP", undefined, null, 23],
45, ["NoLeSsThAnGaRbAgE"],
"thisIsGarBageArray"
]
function containsGarbage(something) {
if (typeof something === "string") return something.toLowerCase().includes("garbage")
if (Array.isArray(something)) return arrayCleaner(something) // don't know if this will cause any unforeseen problems ... it looks like the function is returning somthing, while it really isn't.
if (something instanceof Object) return objectCleaner(something)
}
function arrayCleaner(arr) {
arr.forEach((item, index, array) => {
if (containsGarbage(item)) delete array[index]
})
}
function objectCleaner(obj) {
for (let [key, value] of Object.entries(obj)) {
if (containsGarbage(value) || containsGarbage(key)) delete obj[key]
}
}
containsGarbage(dirtyArray)
console.log(dirtyArray)</code></pre>
</div>
</div>
</p>
<p>The main functionality is performed by the three functions, other code is just an example to show what it does.</p>
<p>One pitfall is that while deleting an element, the array substitutes the deletion with <code>undefined</code>. That might not be a problem practically because I don't think someone keeps their arrays this dirty, but given that there were pre-existing <code>undefined</code>s, that might be a problem. Another pitfall is mention in the code.</p>
|
[] |
[
{
"body": "<blockquote>\n<p>I am practicing for maintainable and flexible code. Is it right thing to do?</p>\n</blockquote>\n<p>Yes!</p>\n<p>Delivering loads of javascript to the client can be slow, but the way to solve is this is not by writing worse code. You solve it by minifying/uglyfying, chunking, tree shaking, and by not including lots of third party code that you haven't determined is worth the size. Writing bad code (dense, hard to read) makes it harder to understand and harder to refactor, and might ironically make it longer in the end.</p>\n<p>I have just a couple of comments, and it seems you are aware of them already:</p>\n<ul>\n<li><code>containsGarbage</code> reads like something that just reads the input and returns a boolean, but in fact it mutates the input and possibly returns undefined (the pitfall you mentioned). A better name would be removeGarbage. I would also make it return true or false explicitly, rather than relying on undefined.</li>\n<li>You can use array.filter() to avoid the <code><empty value></code>'s laying around.</li>\n</ul>\n<p>Also, If you want to write maintainable code I cannot recommend pure functions enough (no input mutations or side effects allowed). The performance is sometimes worse, but often acceptable.</p>\n<p>For instance:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const isGarbageString = (something) =>\n typeof something === 'string' && something.toLowerCase().includes("garbage")\n\nconst removeGarbage = (something) => {\n if (Array.isArray(something)) return removeGarbageFromArray(something)\n if (something instanceof Object) return removeGarbageFromObject(something)\n return something\n}\nconst removeGarbageFromArray = arr => arr\n .filter(item => !isGarbageString(item))\n .map(removeGarbage)\n\nconst removeGarbageFromObject = obj =>\n Object.entries(obj).reduce((newObj, [key, value]) => {\n if (isGarbageString(key)) return newObj\n if (isGarbageString(value)) return newObj\n return { ...newObj, [key]: removeGarbage(value) }\n }, {})\n</code></pre>\n<p>Here <code>removeGarbage</code> is pure, and that is a win for maintainability and readability since you can always call pure functions without worrying about unintended consequences. The performance of this example is not the best though, so maybe don't use this for millions of large objects ;)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T18:34:59.470",
"Id": "265709",
"ParentId": "265684",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "265709",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T01:27:20.870",
"Id": "265684",
"Score": "3",
"Tags": [
"javascript",
"strings",
"functional-programming"
],
"Title": "garbage string remover with array or object input"
}
|
265684
|
<p>I implemented a simple Java virtual machine in C.<br />
Here it is: <a href="https://github.com/phillbush/jvm" rel="nofollow noreferrer">https://github.com/phillbush/jvm</a><br />
It includes two programs: javap(1), a Java disassembler; and java(1), the JVM itself.<br />
It does not have a garbage collector nor exception handler yet, but I want to implement them (but how should I do it? I accept comments on the best way to implement them).</p>
<p>The files are:</p>
<ul>
<li>util.[ch]: miscellaneous routines</li>
<li>class.[ch]: routines and definitions related to class structure</li>
<li>native.[ch]: routines and definitions related to native code</li>
<li>memory.[ch]: routines and definitions related to JRE memory</li>
<li>file.[ch]: routines to read and free .class files</li>
<li>javap.c: .class file disassembler</li>
<li>java.c: .class file interpreter</li>
<li>tests/*: collection of simple .java files for testing the jvm</li>
</ul>
<p>I am not including all files because of the 65536 char limit.<br />
To see all the code, clone the git repo.<br />
I'm including the file <code>file.c</code>, which reads the <code>.class</code> file into a
<code>ClassFile</code> structure.</p>
<pre><code>#include <errno.h>
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "util.h"
#include "class.h"
#include "file.h"
#define MAGIC 0xCAFEBABE
#define TRY(expr) \
do { \
if ((expr) == -1) { \
goto error; \
} \
} while(0)
/* error tags */
enum {
ERR_NONE = 0,
ERR_READ,
ERR_ALLOC,
ERR_CODE,
ERR_CONSTANT,
ERR_DESCRIPTOR,
ERR_EOF,
ERR_INDEX,
ERR_KIND,
ERR_MAGIC,
ERR_TAG,
ERR_METHOD,
};
/* error variables */
static int errtag = ERR_NONE;
static char *errstr[] = {
[ERR_NONE] = NULL,
[ERR_READ] = "could not read file",
[ERR_ALLOC] = "could not allocate memory",
[ERR_CODE] = "code does not follow jvm code constraints",
[ERR_CONSTANT] = "reference to entry of wrong type on constant pool",
[ERR_DESCRIPTOR] = "invalid descriptor string",
[ERR_EOF] = "unexpected end of file",
[ERR_INDEX] = "index to constant pool out of bounds",
[ERR_KIND] = "invalid method handle reference kind",
[ERR_MAGIC] = "invalid magic number",
[ERR_METHOD] = "invalid method name",
[ERR_TAG] = "unknown constant pool tag",
};
/* call malloc; add returned pointer to stack of pointers to be freed when error occurs */
static int
fmalloc(void **p, size_t size)
{
if ((*p = malloc(size)) == NULL) {
errtag = ERR_ALLOC;
return -1;
}
return 0;
}
/* call calloc; add returned pointer to stack of pointers to be freed when error occurs */
static int
fcalloc(void **p, size_t nmemb, size_t size)
{
if ((*p = calloc(nmemb, size)) == NULL) {
errtag = ERR_ALLOC;
return -1;
}
return 0;
}
/* get attribute tag from string */
static AttributeTag
getattributetag(char *tagstr)
{
static struct {
AttributeTag t;
char *s;
} tags[] = {
{ConstantValue, "ConstantValue"},
{Code, "Code"},
{Deprecated, "Deprecated"},
{Exceptions, "Exceptions"},
{InnerClasses, "InnerClasses"},
{SourceFile, "SourceFile"},
{Synthetic, "Synthetic"},
{LineNumberTable, "LineNumberTable"},
{LocalVariableTable, "LocalVariableTable"},
{UnknownAttribute, NULL},
};
int i;
for (i = 0; tags[i].s; i++)
if (strcmp(tagstr, tags[i].s) == 0)
break;
return tags[i].t;
}
/* check if string is valid field type, return pointer to next character: */
static int
isdescriptor(char *s)
{
if (*s == '(') {
s++;
while (*s && *s != ')') {
if (*s == 'L') {
while (*s != '\0' && *s != ';')
s++;
if (*s == '\0')
return 0;
} else if (!strchr("BCDFIJSZ[", *s)) {
return 0;
}
s++;
}
if (*s != ')')
return 0;
s++;
}
do {
if (*s == 'L') {
while (*s != '\0' && *s != ';')
s++;
if (*s == '\0')
return 0;
} else if (!strchr("BCDFIJSVZ[", *s)) {
return 0;
}
} while (*s++ == '[');
return 1;
}
/* check if kind of method handle is valid */
static int
checkkind(U1 kind)
{
if (kind <= REF_none || kind >= REF_last) {
errtag = ERR_KIND;
return -1;
}
return 0;
}
/* check if index is valid and points to a given tag in the constant pool */
static int
checkindex(CP **cp, U2 count, ConstantTag tag, U2 index)
{
if (index < 1 || index >= count) {
errtag = ERR_INDEX;
return -1;
}
switch (tag) {
case CONSTANT_Untagged:
break;
case CONSTANT_Constant:
if (cp[index]->tag != CONSTANT_Integer &&
cp[index]->tag != CONSTANT_Float &&
cp[index]->tag != CONSTANT_Long &&
cp[index]->tag != CONSTANT_Double &&
cp[index]->tag != CONSTANT_String)
goto error;
break;
case CONSTANT_U1:
if (cp[index]->tag != CONSTANT_Integer &&
cp[index]->tag != CONSTANT_Float &&
cp[index]->tag != CONSTANT_String)
goto error;
break;
case CONSTANT_U2:
if (cp[index]->tag != CONSTANT_Long &&
cp[index]->tag != CONSTANT_Double)
goto error;
break;
default:
if (cp[index]->tag != tag)
goto error;
break;
}
return 0;
error:
errtag = ERR_CONSTANT;
return -1;
}
/* check if index is points to a valid descriptor in the constant pool */
static int
checkdescriptor(CP **cp, U2 count, U2 index)
{
if (index < 1 || index >= count) {
errtag = ERR_INDEX;
return -1;
}
if (cp[index]->tag != CONSTANT_Utf8) {
errtag = ERR_CONSTANT;
return -1;
}
if (!isdescriptor(cp[index]->info.utf8_info.bytes)) {
errtag = ERR_DESCRIPTOR;
return -1;
}
return 0;
}
/* check if method is not special (<init> or <clinit>) */
static int
checkmethod(ClassFile *class, U2 index)
{
CONSTANT_Methodref_info *methodref;
char *name, *type;
methodref = &class->constant_pool[index]->info.methodref_info;
class_getnameandtype(class, methodref->name_and_type_index, &name, &type);
if (strcmp(name, "<init>") == 0 || strcmp(name, "<clinit>") == 0) {
errtag = ERR_METHOD;
return -1;
}
return 0;
}
/* read count bytes into buf; longjmp to class_read on error */
static int
readb(FILE *fp, void *buf, U4 count)
{
if (fread(buf, 1, count, fp) != count)
return -1;
return 0;
}
/* read unsigned integer U4 and return it */
static int
readu(FILE *fp, void *u, U2 count)
{
U1 b[4];
TRY(readb(fp, b, count));
switch (count) {
case 4:
*(U4 *)u = (b[0] << 24) | (b[1] << 16) | (b[2] << 8) | b[3];
break;
case 2:
*(U2 *)u = (b[0] << 8) | b[1];
break;
default:
*(U1 *)u = b[0];
break;
}
return 0;
error:
return -1;
}
/* read string of length count into buf; insert a nul at the end of it */
static int
reads(FILE *fp, char **s, U2 count)
{
TRY(fmalloc((void **)s, count + 1));
TRY(readb(fp, (*s), count));
(*s)[count] = '\0';
return 0;
error:
return -1;
}
/* read index to constant pool and check whether it is a valid index to a given tag */
static int
readindex(FILE *fp, U2 *u, int canbezero, ClassFile *class, ConstantTag tag)
{
U1 b[2];
TRY(readb(fp, b, 2));
*u = (b[0] << 8) | b[1];
if (!canbezero || *u)
TRY(checkindex(class->constant_pool, class->constant_pool_count, tag, *u));
return 0;
error:
return -1;
}
/* read descriptor index to constant pool and check whether it is a valid */
static int
readdescriptor(FILE *fp, U2 *u, ClassFile *class)
{
U1 b[2];
TRY(readb(fp, b, 2));
*u = (b[0] << 8) | b[1];
TRY(checkdescriptor(class->constant_pool, class->constant_pool_count, *u));
return 0;
error:
return -1;
}
/* read constant pool, return pointer to constant pool array */
static int
readcp(FILE *fp, CP ***cp, U2 count)
{
U2 i;
if (count == 0) {
*cp = NULL;
return 0;
}
TRY(fcalloc((void **)cp, count, sizeof(**cp)));
for (i = 1; i < count; i++) {
TRY(fcalloc((void **)&(*cp)[i], 1, sizeof(*(*cp)[i])));
TRY(readu(fp, &(*cp)[i]->tag, 1));
switch ((*cp)[i]->tag) {
case CONSTANT_Utf8:
TRY(readu(fp, &(*cp)[i]->info.utf8_info.length, 2));
TRY(reads(fp, &(*cp)[i]->info.utf8_info.bytes, (*cp)[i]->info.utf8_info.length));
break;
case CONSTANT_Integer:
TRY(readu(fp, &(*cp)[i]->info.integer_info.bytes, 4));
break;
case CONSTANT_Float:
TRY(readu(fp, &(*cp)[i]->info.float_info.bytes, 4));
break;
case CONSTANT_Long:
TRY(readu(fp, &(*cp)[i]->info.long_info.high_bytes, 4));
TRY(readu(fp, &(*cp)[i]->info.long_info.low_bytes, 4));
i++;
break;
case CONSTANT_Double:
TRY(readu(fp, &(*cp)[i]->info.double_info.high_bytes, 4));
TRY(readu(fp, &(*cp)[i]->info.double_info.low_bytes, 4));
i++;
break;
case CONSTANT_Class:
TRY(readu(fp, &(*cp)[i]->info.class_info.name_index, 2));
break;
case CONSTANT_String:
TRY(readu(fp, &(*cp)[i]->info.string_info.string_index, 2));
break;
case CONSTANT_Fieldref:
TRY(readu(fp, &(*cp)[i]->info.fieldref_info.class_index, 2));
TRY(readu(fp, &(*cp)[i]->info.fieldref_info.name_and_type_index, 2));
break;
case CONSTANT_Methodref:
TRY(readu(fp, &(*cp)[i]->info.methodref_info.class_index, 2));
TRY(readu(fp, &(*cp)[i]->info.methodref_info.name_and_type_index, 2));
break;
case CONSTANT_InterfaceMethodref:
TRY(readu(fp, &(*cp)[i]->info.interfacemethodref_info.class_index, 2));
TRY(readu(fp, &(*cp)[i]->info.interfacemethodref_info.name_and_type_index, 2));
break;
case CONSTANT_NameAndType:
TRY(readu(fp, &(*cp)[i]->info.nameandtype_info.name_index, 2));
TRY(readu(fp, &(*cp)[i]->info.nameandtype_info.descriptor_index, 2));
break;
case CONSTANT_MethodHandle:
TRY(readu(fp, &(*cp)[i]->info.methodhandle_info.reference_kind, 1));
TRY(readu(fp, &(*cp)[i]->info.methodhandle_info.reference_index, 2));
break;
case CONSTANT_MethodType:
TRY(readu(fp, &(*cp)[i]->info.methodtype_info.descriptor_index, 2));
break;
case CONSTANT_InvokeDynamic:
TRY(readu(fp, &(*cp)[i]->info.invokedynamic_info.bootstrap_method_attr_index, 2));
TRY(readu(fp, &(*cp)[i]->info.invokedynamic_info.name_and_type_index, 2));
break;
default:
errtag = ERR_TAG;
goto error;
}
}
for (i = 1; i < count; i++) {
switch ((*cp)[i]->tag) {
case CONSTANT_Utf8:
case CONSTANT_Integer:
case CONSTANT_Float:
break;
case CONSTANT_Long:
case CONSTANT_Double:
i++;
break;
case CONSTANT_Class:
break;
case CONSTANT_String:
TRY(checkindex((*cp), count, CONSTANT_Utf8, (*cp)[i]->info.string_info.string_index));
break;
case CONSTANT_Fieldref:
TRY(checkindex((*cp), count, CONSTANT_Class, (*cp)[i]->info.fieldref_info.class_index));
TRY(checkindex((*cp), count, CONSTANT_NameAndType, (*cp)[i]->info.fieldref_info.name_and_type_index));
break;
case CONSTANT_Methodref:
TRY(checkindex((*cp), count, CONSTANT_Class, (*cp)[i]->info.methodref_info.class_index));
TRY(checkindex((*cp), count, CONSTANT_NameAndType, (*cp)[i]->info.methodref_info.name_and_type_index));
break;
case CONSTANT_InterfaceMethodref:
TRY(checkindex((*cp), count, CONSTANT_Class, (*cp)[i]->info.interfacemethodref_info.class_index));
TRY(checkindex((*cp), count, CONSTANT_NameAndType, (*cp)[i]->info.interfacemethodref_info.name_and_type_index));
break;
case CONSTANT_NameAndType:
TRY(checkindex((*cp), count, CONSTANT_Utf8, (*cp)[i]->info.nameandtype_info.name_index));
TRY(checkdescriptor((*cp), count, (*cp)[i]->info.nameandtype_info.descriptor_index));
break;
case CONSTANT_MethodHandle:
TRY(checkkind((*cp)[i]->info.methodhandle_info.reference_kind));
switch ((*cp)[i]->info.methodhandle_info.reference_kind) {
case REF_getField:
case REF_getStatic:
case REF_putField:
case REF_putStatic:
TRY(checkindex((*cp), count, CONSTANT_Fieldref, (*cp)[i]->info.methodhandle_info.reference_index));
break;
case REF_invokeVirtual:
case REF_newInvokeSpecial:
TRY(checkindex((*cp), count, CONSTANT_Methodref, (*cp)[i]->info.methodhandle_info.reference_index));
break;
case REF_invokeStatic:
case REF_invokeSpecial:
/* TODO check based on ClassFile version */
break;
case REF_invokeInterface:
TRY(checkindex((*cp), count, CONSTANT_InterfaceMethodref, (*cp)[i]->info.methodhandle_info.reference_index));
break;
}
break;
case CONSTANT_MethodType:
TRY(checkdescriptor((*cp), count, (*cp)[i]->info.methodtype_info.descriptor_index));
break;
case CONSTANT_InvokeDynamic:
TRY(checkindex((*cp), count, CONSTANT_NameAndType, (*cp)[i]->info.invokedynamic_info.name_and_type_index));
break;
default:
break;
}
}
return 0;
error:
return -1;
}
/* read interface indices, return pointer to interfaces array */
static int
readinterfaces(FILE *fp, U2 **p, U2 count)
{
U2 i;
if (count == 0) {
*p = NULL;
return 0;
}
TRY(fcalloc((void **)p, count, sizeof(**p)));
for (i = 0; i < count; i++)
TRY(readu(fp, &(*p)[i], 2));
return 0;
error:
return -1;
}
/* read code instructions, return point to instruction array */
static int
readcode(FILE *fp, U1 **code, ClassFile *class, U4 count)
{
int32_t j, npairs, off, high, low;
U4 base, i;
U2 u;
if (count == 0) {
*code = NULL;
return 0;
}
TRY(fmalloc((void **)code, count));
for (i = 0; i < count; i++) {
TRY(readu(fp, &(*code)[i], 1));
if ((*code)[i] >= CodeLast)
goto error;
switch ((*code)[i]) {
case WIDE:
TRY(readu(fp, &(*code)[++i], 1));
switch ((*code)[i]) {
case IINC:
TRY(readu(fp, &(*code)[++i], 1));
TRY(readu(fp, &(*code)[++i], 1));
/* FALLTHROUGH */
case ILOAD:
case FLOAD:
case ALOAD:
case LLOAD:
case DLOAD:
case ISTORE:
case FSTORE:
case ASTORE:
case LSTORE:
case DSTORE:
case RET:
TRY(readu(fp, &(*code)[++i], 1));
TRY(readu(fp, &(*code)[++i], 1));
break;
default:
goto error;
break;
}
break;
case LOOKUPSWITCH:
while ((3 - (i % 4)) > 0)
TRY(readu(fp, &(*code)[++i], 1));
for (j = 0; j < 8; j++)
TRY(readu(fp, &(*code)[++i], 1));
npairs = ((*code)[i-3] << 24) | ((*code)[i-2] << 16) | ((*code)[i-1] << 8) | (*code)[i];
if (npairs < 0)
goto error;
for (j = 8 * npairs; j > 0; j--)
TRY(readu(fp, &(*code)[++i], 1));
break;
case TABLESWITCH:
base = i;
while ((3 - (i % 4)) > 0)
TRY(readu(fp, &(*code)[++i], 1));
for (j = 0; j < 12; j++)
TRY(readu(fp, &(*code)[++i], 1));
off = ((*code)[i-11] << 24) | ((*code)[i-10] << 16) | ((*code)[i-9] << 8) | (*code)[i-8];
low = ((*code)[i-7] << 24) | ((*code)[i-6] << 16) | ((*code)[i-5] << 8) | (*code)[i-4];
high = ((*code)[i-3] << 24) | ((*code)[i-2] << 16) | ((*code)[i-1] << 8) | (*code)[i];
if (base + off < 0 || base + off >= count)
goto error;
if (low > high)
goto error;
for (j = low; j <= high; j++) {
TRY(readu(fp, &(*code)[++i], 1));
TRY(readu(fp, &(*code)[++i], 1));
TRY(readu(fp, &(*code)[++i], 1));
TRY(readu(fp, &(*code)[++i], 1));
off = ((*code)[i-3] << 24) | ((*code)[i-2] << 16) | ((*code)[i-1] << 8) | (*code)[i];
if (base + off < 0 || base + off >= count) {
goto error;
}
}
break;
case LDC:
TRY(readu(fp, &(*code)[++i], 1));
TRY(checkindex(class->constant_pool, class->constant_pool_count, CONSTANT_U1, (*code)[i]));
break;
case LDC_W:
TRY(readu(fp, &(*code)[++i], 1));
TRY(readu(fp, &(*code)[++i], 1));
TRY(checkindex(class->constant_pool, class->constant_pool_count, CONSTANT_U1, (*code)[i - 1] << 8 | (*code)[i]));
break;
case LDC2_W:
TRY(readu(fp, &(*code)[++i], 1));
TRY(readu(fp, &(*code)[++i], 1));
TRY(checkindex(class->constant_pool, class->constant_pool_count, CONSTANT_U2, (*code)[i - 1] << 8 | (*code)[i]));
break;
case GETSTATIC: case PUTSTATIC: case GETFIELD: case PUTFIELD:
TRY(readu(fp, &(*code)[++i], 1));
TRY(readu(fp, &(*code)[++i], 1));
TRY(checkindex(class->constant_pool, class->constant_pool_count, CONSTANT_Fieldref, (*code)[i - 1] << 8 | (*code)[i]));
break;
case INVOKESTATIC:
TRY(readu(fp, &(*code)[++i], 1));
TRY(readu(fp, &(*code)[++i], 1));
u = (*code)[i - 1] << 8 | (*code)[i];
TRY(checkindex(class->constant_pool, class->constant_pool_count, CONSTANT_Methodref, u));
TRY(checkmethod(class, u));
break;
case MULTIANEWARRAY:
TRY(readu(fp, &(*code)[++i], 1));
TRY(readu(fp, &(*code)[++i], 1));
u = (*code)[i - 1] << 8 | (*code)[i];
TRY(checkindex(class->constant_pool, class->constant_pool_count, CONSTANT_Class, u));
TRY(readu(fp, &(*code)[++i], 1));
if ((*code)[i] < 1)
goto error;
break;
default:
for (j = class_getnoperands((*code)[i]); j > 0; j--)
TRY(readu(fp, &(*code)[++i], 1));
break;
}
}
if (i != count)
goto error;
return 0;
error:
return -1;
}
/* read indices to constant pool, return point to index array */
static int
readindices(FILE *fp, U2 **indices, U2 count)
{
U2 i;
if (count == 0) {
*indices = NULL;
return 0;
}
TRY(fcalloc((void **)indices, count, sizeof(**indices)));
for (i = 0; i < count; i++)
TRY(readu(fp, &(*indices)[i], 2));
return 0;
error:
return -1;
}
/* read exception table, return point to exception array */
static int
readexceptions(FILE *fp, Exception ***p, U2 count)
{
U2 i;
if (count == 0) {
*p = NULL;
return 0;
}
TRY(fcalloc((void **)p, count, sizeof(*(*p))));
for (i = 0; i < count; i++) {
TRY(fcalloc((void **)&(*p)[i], 1, sizeof(*(*p)[i])));
TRY(readu(fp, &(*p)[i]->start_pc, 2));
TRY(readu(fp, &(*p)[i]->end_pc, 2));
TRY(readu(fp, &(*p)[i]->handler_pc, 2));
TRY(readu(fp, &(*p)[i]->catch_type, 2));
}
return 0;
error:
return -1;
}
/* read inner class table, return point to class array */
static int
readclasses(FILE *fp, InnerClass ***p, ClassFile *class, U2 count)
{
U2 i;
if (count == 0) {
*p = NULL;
return 0;
}
TRY(fcalloc((void **)p, count, sizeof(*(*p))));
for (i = 0; i < count; i++) {
TRY(fcalloc((void **)&(*p)[i], 1, sizeof(*(*p)[i])));
TRY(readindex(fp, &(*p)[i]->inner_class_info_index, 0, class, CONSTANT_Class));
TRY(readindex(fp, &(*p)[i]->outer_class_info_index, 1, class, CONSTANT_Class));
TRY(readindex(fp, &(*p)[i]->inner_name_index, 1, class, CONSTANT_Utf8));
TRY(readu(fp, &(*p)[i]->inner_class_access_flags, 2));
}
return 0;
error:
return -1;
}
/* read line number table, return point to LineNumber array */
static int
readlinenumber(FILE *fp, LineNumber ***p, U2 count)
{
U2 i;
if (count == 0) {
*p = NULL;
return 0;
}
TRY(fcalloc((void **)p, count, sizeof(*(*p))));
for (i = 0; i < count; i++) {
TRY(fcalloc((void **)&(*p)[i], 1, sizeof(*(*p)[i])));
TRY(readu(fp, &(*p)[i]->start_pc, 2));
TRY(readu(fp, &(*p)[i]->line_number, 2));
}
return 0;
error:
return -1;
}
/* read local variable table, return point to LocalVariable array */
static int
readlocalvariable(FILE *fp, LocalVariable ***p, ClassFile *class, U2 count)
{
U2 i;
if (count == 0) {
*p = NULL;
return 0;
}
TRY(fcalloc((void **)p, count, sizeof *(*p)));
for (i = 0; i < count; i++) {
TRY(fcalloc((void **)&(*p)[i], 1, sizeof *(*p)[i]));
TRY(readu(fp, &(*p)[i]->start_pc, 2));
TRY(readu(fp, &(*p)[i]->length, 2));
TRY(readindex(fp, &(*p)[i]->name_index, 0, class, CONSTANT_Utf8));
TRY(readdescriptor(fp, &(*p)[i]->descriptor_index, class));
TRY(readu(fp, &(*p)[i]->index, 2));
}
return 0;
error:
return -1;
}
/* read attribute list, longjmp to class_read on error */
static int
readattributes(FILE *fp, Attribute ***p, ClassFile *class, U2 count)
{
U4 length;
U2 index;
U2 i;
U1 b;
if (count == 0) {
*p = NULL;
return 0;
}
TRY(fcalloc((void **)p, count, sizeof(**p)));
for (i = 0; i < count; i++) {
TRY(fcalloc((void **)&(*p)[i], 1, sizeof(*(*p)[i])));
TRY(readindex(fp, &index, 0, class, CONSTANT_Utf8));
TRY(readu(fp, &length, 4));
(*p)[i]->tag = getattributetag(class->constant_pool[index]->info.utf8_info.bytes);
switch ((*p)[i]->tag) {
case ConstantValue:
TRY(readindex(fp, &(*p)[i]->info.constantvalue.constantvalue_index, 0, class, CONSTANT_Constant));
break;
case Code:
TRY(readu(fp, &(*p)[i]->info.code.max_stack, 2));
TRY(readu(fp, &(*p)[i]->info.code.max_locals, 2));
TRY(readu(fp, &(*p)[i]->info.code.code_length, 4));
TRY(readcode(fp, &(*p)[i]->info.code.code, class, (*p)[i]->info.code.code_length));
TRY(readu(fp, &(*p)[i]->info.code.exception_table_length, 2));
TRY(readexceptions(fp, &(*p)[i]->info.code.exception_table, (*p)[i]->info.code.exception_table_length));
TRY(readu(fp, &(*p)[i]->info.code.attributes_count, 2));
TRY(readattributes(fp, &(*p)[i]->info.code.attributes, class, (*p)[i]->info.code.attributes_count));
break;
case Deprecated:
break;
case Exceptions:
TRY(readu(fp, &(*p)[i]->info.exceptions.number_of_exceptions, 2));
TRY(readindices(fp, &(*p)[i]->info.exceptions.exception_index_table, (*p)[i]->info.exceptions.number_of_exceptions));
break;
case InnerClasses:
TRY(readu(fp, &(*p)[i]->info.innerclasses.number_of_classes, 2));
TRY(readclasses(fp, &(*p)[i]->info.innerclasses.classes, class, (*p)[i]->info.innerclasses.number_of_classes));
break;
case SourceFile:
TRY(readindex(fp, &(*p)[i]->info.sourcefile.sourcefile_index, 0, class, CONSTANT_Utf8));
break;
case Synthetic:
break;
case LineNumberTable:
TRY(readu(fp, &(*p)[i]->info.linenumbertable.line_number_table_length, 2));
TRY(readlinenumber(fp, &(*p)[i]->info.linenumbertable.line_number_table, (*p)[i]->info.linenumbertable.line_number_table_length));
break;
case LocalVariableTable:
TRY(readu(fp, &(*p)[i]->info.localvariabletable.local_variable_table_length, 2));
TRY(readlocalvariable(fp, &(*p)[i]->info.localvariabletable.local_variable_table, class, (*p)[i]->info.localvariabletable.local_variable_table_length));
break;
case UnknownAttribute:
while (length-- > 0)
TRY(readb(fp, &b, 1));
break;
}
}
return 0;
error:
return -1;
}
/* read fields, reaturn pointer to fields array */
static int
readfields(FILE *fp, Field ***p, ClassFile *class, U2 count)
{
U2 i;
if (count == 0) {
*p = NULL;
return 0;
}
TRY(fcalloc((void **)p, count, sizeof(**p)));
for (i = 0; i < count; i++) {
TRY(fcalloc((void **)&(*p)[i], 1, sizeof(*(*p)[i])));
TRY(readu(fp, &(*p)[i]->access_flags, 2));
TRY(readindex(fp, &(*p)[i]->name_index, 0, class, CONSTANT_Utf8));
TRY(readdescriptor(fp, &(*p)[i]->descriptor_index, class));
TRY(readu(fp, &(*p)[i]->attributes_count, 2));
TRY(readattributes(fp, &(*p)[i]->attributes, class, (*p)[i]->attributes_count));
}
return 0;
error:
return -1;
}
/* read methods, reaturn pointer to methods array */
static int
readmethods(FILE *fp, Method ***p, ClassFile *class, U2 count)
{
U2 i;
if (count == 0) {
*p = NULL;
return 0;
}
TRY(fcalloc((void **)p, count, sizeof(**p)));
for (i = 0; i < count; i++) {
TRY(fcalloc((void **)&(*p)[i], 1, sizeof(*(*p)[i])));
TRY(readu(fp, &(*p)[i]->access_flags, 2));
TRY(readindex(fp, &(*p)[i]->name_index, 0, class, CONSTANT_Utf8));
TRY(readdescriptor(fp, &(*p)[i]->descriptor_index, class));
TRY(readu(fp, &(*p)[i]->attributes_count, 2));
TRY(readattributes(fp, &(*p)[i]->attributes, class, (*p)[i]->attributes_count));
}
return 0;
error:
return -1;
}
/* free attribute */
static void
attributefree(Attribute **attr, U2 count)
{
U2 i, j;
if (attr == NULL)
return;
for (i = 0; i < count; i++) {
switch (attr[i]->tag) {
case UnknownAttribute:
case ConstantValue:
case Deprecated:
case SourceFile:
case Synthetic:
break;
case Code:
free(attr[i]->info.code.code);
free(attr[i]->info.code.exception_table);
attributefree(attr[i]->info.code.attributes, attr[i]->info.code.attributes_count);
break;
case Exceptions:
free(attr[i]->info.exceptions.exception_index_table);
break;
case InnerClasses:
if (attr[i]->info.innerclasses.classes != NULL)
for (j = 0; j < attr[i]->info.innerclasses.number_of_classes; j++)
free(attr[i]->info.innerclasses.classes[j]);
free(attr[i]->info.innerclasses.classes);
break;
case LineNumberTable:
if (attr[i]->info.linenumbertable.line_number_table != 0)
for (j = 0; j < attr[i]->info.linenumbertable.line_number_table_length; j++)
free(attr[i]->info.linenumbertable.line_number_table[j]);
free(attr[i]->info.linenumbertable.line_number_table);
break;
case LocalVariableTable:
if (attr[i]->info.localvariabletable.local_variable_table != 0)
for (j = 0; j < attr[i]->info.localvariabletable.local_variable_table_length; j++)
free(attr[i]->info.localvariabletable.local_variable_table[j]);
free(attr[i]->info.localvariabletable.local_variable_table);
break;
}
}
free(attr);
}
/* free class structure */
void
file_free(ClassFile *class)
{
U2 i;
if (class == NULL)
return;
if (class->constant_pool) {
for (i = 1; i < class->constant_pool_count; i++) {
switch (class->constant_pool[i]->tag) {
case CONSTANT_Utf8:
free(class->constant_pool[i]->info.utf8_info.bytes);
break;
case CONSTANT_Double:
case CONSTANT_Long:
i++;
break;
default:
break;
}
}
}
free(class->constant_pool);
free(class->interfaces);
if (class->fields)
for (i = 0; i < class->fields_count; i++)
attributefree(class->fields[i]->attributes, class->fields[i]->attributes_count);
free(class->fields);
if (class->methods)
for (i = 0; i < class->methods_count; i++)
attributefree(class->methods[i]->attributes, class->methods[i]->attributes_count);
free(class->methods);
attributefree(class->attributes, class->attributes_count);
}
/* read class file */
int
file_read(FILE *fp, ClassFile *class)
{
U4 magic;
TRY(readu(fp, &magic, 4));
if (magic != MAGIC) {
errtag = ERR_MAGIC;
goto error;
}
class->init = 0;
class->next = NULL;
class->super = NULL;
TRY(readu(fp, &class->minor_version, 2));
TRY(readu(fp, &class->major_version, 2));
TRY(readu(fp, &class->constant_pool_count, 2));
TRY(readcp(fp, &class->constant_pool, class->constant_pool_count));
TRY(readu(fp, &class->access_flags, 2));
TRY(readu(fp, &class->this_class, 2));
TRY(readu(fp, &class->super_class, 2));
TRY(readu(fp, &class->interfaces_count, 2));
TRY(readinterfaces(fp, &class->interfaces, class->interfaces_count));
TRY(readu(fp, &class->fields_count, 2));
TRY(readfields(fp, &class->fields, class, class->fields_count));
TRY(readu(fp, &class->methods_count, 2));
TRY(readmethods(fp, &class->methods, class, class->methods_count));
TRY(readu(fp, &class->attributes_count, 2));
TRY(readattributes(fp, &class->attributes, class, class->attributes_count));
return ERR_NONE;
error:
file_free(class);
return errtag;
}
/* return string describing error tag */
char *
file_errstr(int i)
{
return errstr[i];
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T14:55:15.520",
"Id": "524818",
"Score": "2",
"body": "Despite the char limit the rule is also that we only review code that is included directly into the question. If it is too much, consider splitting up your code into multiple reviews."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T21:26:50.027",
"Id": "524851",
"Score": "0",
"body": "Great effort! I did the same, but in java, allowing to borrow from the existing JVM until done - a bit of cheating. There should be a better forum to find other enthusiasts, interested people: programming languages, interpreters, JVM."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T12:57:46.410",
"Id": "524894",
"Score": "0",
"body": "As @G.Sliepen mentioned it is possible to break the code up over multiple questions, [here is an example](https://codereview.stackexchange.com/questions/248559/hand-coded-state-driven-lexical-analyzer-in-c-with-unit-test-part-a)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T01:45:02.150",
"Id": "265685",
"Score": "0",
"Tags": [
"c"
],
"Title": "Class file reader for simple java virtual machine"
}
|
265685
|
<p>I was trying to implement a generic PriorityQueue in C#. Below is my implementation which works fine as per few test cases.
Operations supported-</p>
<ul>
<li>Add: Adds an element</li>
<li>Poll: Removes the smallest element and returns it</li>
<li>Remove: Removes a specific element (only first occurence) and returns it</li>
<li>Clear: Clears all elements</li>
<li>Contains: Return true if the element is found else false</li>
</ul>
<p>Code:</p>
<pre><code>// Complete binary tree, smallest/largest at the top
// Canonical representation using array
// LeftIndex = 2 * ParentIndex + 1
// RightIndex = 2 * ParentIndex + 2
// Insert always in bottom-left order, filling up the level (row). Last position in array/linked list
// After insert at root (end) sift-up/swim to maintain heap-invariant by sawapping
// Poll happens at root (first) position by swapping with the last element
// SiftDown after removing element: Swap parent and smaller child. If same, choose left. SiftDown till lastIndex or heap variant stisfied
// Remove(element): Linear search the element. Swap the node with the last node then remove last node. SiftUp (if bubble up) or SiftDown (bubble down)
public class PriorityQueue<T> where T : IComparable<T>
{
public int Length { get; private set; }
private List<T> _elements;
public PriorityQueue()
{
_elements = new List<T>();
}
public PriorityQueue(int capacity)
{
_elements = new List<T>(capacity);
}
// Adds an item to the end of the list
public void Add(T item)
{
if (_elements == null)
throw new NullReferenceException("Queue is not initialized");
_elements.Add(item);
Length++;
SiftUp(Length - 1);
}
// Removes and returns the root (first) item from the list
public T Poll()
{
T output;
if (Length <= 0)
{
throw new IndexOutOfRangeException("No elements to remove");
}
if (Length == 1)
{
--Length;
output = _elements[0];
_elements.Clear();
return output;
}
output = _elements[0];
_elements[0] = _elements[--Length];
_elements.RemoveAt(Length);
SiftDown(0);
return output;
}
//Removes the first occurrence of the specified item
public void Remove(T item)
{
int removeIndex = _elements.IndexOf(item);
if (removeIndex == -1)
throw new IndexOutOfRangeException("No such element found");
Swap(removeIndex, --Length);
_elements.RemoveAt(Length);
SiftDown(removeIndex);
SiftUp(removeIndex);
}
// Returns the root (first) item from the list
public T Peek()
{
if (Length >= 1)
return _elements[0];
throw new IndexOutOfRangeException("Queue is empty");
}
// Returns true if the item is found else false
public bool Contains(T item)
{
return _elements.Contains(item);
}
// Removes all items from the list
public void Clear()
{
_elements.Clear();
}
// Swaps the position of 2 items in the list
private void Swap(int index1, int index2)
{
T temp = _elements[index1];
_elements[index1] = _elements[index2];
_elements[index2] = temp;
}
// Bubble up operation to maintain heap invariant
private void SiftUp(int index)
{
int parentIndex = index % 2 == 0 ? (index - 2) / 2 : (index - 1) / 2;
while (index >= 0 && parentIndex >= 0 && _elements[parentIndex].CompareTo(_elements[index]) >= 1)
{
Swap(index, parentIndex);
index = parentIndex;
parentIndex = index % 2 == 0 ? (index - 2) / 2 : (index - 1) / 2;
}
}
// Bubble down operation to maintain heap invariant
private void SiftDown(int index)
{
if (Length == 1)
return;
if (Length == 2)
{
if (_elements[0].CompareTo(_elements[1]) > 0)
Swap(0, 1);
return;
}
int leftChildIndex = 2 * index + 1;
int rightChildIndex = leftChildIndex + 1;
if (leftChildIndex >= Length || rightChildIndex >= Length)
return;
int childSwapIndex = _elements[leftChildIndex].CompareTo(_elements[rightChildIndex]) < 1 ? leftChildIndex : rightChildIndex;
while (leftChildIndex < Length && rightChildIndex < Length && _elements[index].CompareTo(_elements[childSwapIndex]) >= 1)
{
Swap(index, childSwapIndex);
index = childSwapIndex;
leftChildIndex = 2 * index + 1;
rightChildIndex = 2 * index + 2;
if (leftChildIndex < Length && rightChildIndex < Length)
childSwapIndex = _elements[leftChildIndex].CompareTo(_elements[rightChildIndex]) < 1 ? leftChildIndex : rightChildIndex;
else
break;
}
}
}
</code></pre>
<p>Online heap visualization for reference: <a href="https://www.cs.usfca.edu/%7Egalles/visualization/Heap.html" rel="nofollow noreferrer">https://www.cs.usfca.edu/~galles/visualization/Heap.html</a></p>
<p>Can someone review and provide your feedback on how this can be improved, optimized or structured better?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T06:36:47.933",
"Id": "524770",
"Score": "1",
"body": "Just a small remark: I think `Size` shouldn't have a public setter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T07:14:32.327",
"Id": "524777",
"Score": "0",
"body": "Why do you repeat the methods' name in the comments?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T07:35:45.507",
"Id": "524779",
"Score": "0",
"body": "@SomeBody Actually I should rename it to Length or Count. It can be used to get the current size of the queue. I should remove the 'Capacity' as it is initialized by constructor to keep the dynamic resizing of the List restricted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T07:36:15.290",
"Id": "524780",
"Score": "0",
"body": "@PeterCsala I used it initially as placeholders for the implementations. I can remove them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T07:44:51.383",
"Id": "524781",
"Score": "1",
"body": "@SouvikGhosh The problem with `Size`'s publicity is that it can be overwritten by the consumer because of the public setter."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T07:46:28.367",
"Id": "524783",
"Score": "0",
"body": "@PeterCsala good catch. I totally missed it. Will change"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T13:13:28.423",
"Id": "524808",
"Score": "2",
"body": "Please do not edit the question, especially the code, after an answer has been posted. Changing the question may cause answer invalidation. Everyone needs to be able to see what the reviewer was referring to. [What to do after the question has been answered](https://codereview.stackexchange.com/help/someone-answers)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T15:20:20.137",
"Id": "524823",
"Score": "0",
"body": "@pacmaninbw Got it"
}
] |
[
{
"body": "<blockquote>\n<pre><code>public int Length { get; private set; }\n</code></pre>\n</blockquote>\n<p><code>_elements</code> carries the length already, and duplicate state that you keep in sync manually is a good way to create bugs. Consider implementing the getter as returning <code>_elements.Count</code>, and not having a setter. That way it is <em>impossible</em> for the length to ever be wrong, instead of it being possible but hopefully avoided through careful coding. It will also save some small snippets of code where you update the <code>Length</code>.</p>\n<blockquote>\n<pre><code>if (_elements == null)\n throw new NullReferenceException("Queue is not initialized");\n</code></pre>\n</blockquote>\n<p>There is no legitimate way to create an uninitialized instance (or initialized, but nulled out afterwards) of this queue, so this is testing for a case that is highly unusual (created intentionally via <code>unsafe</code> code, reflection, etc). The method will fail safely if <code>_elements</code> is null anyway (ie it doesn't do any damage before automatically throwing an NRE due to accessing the list). So I deem this unnecessary.</p>\n<blockquote>\n<pre><code>int parentIndex = index % 2 == 0 ? (index - 2) / 2 : (index - 1) / 2;\n</code></pre>\n</blockquote>\n<p>You don't need to test whether <code>index</code> is even, the parent index is always <code>(index − 1) ∕ 2</code>. When <code>index</code> is even, <code>index - 1</code> is odd, and the division rounds down.</p>\n<blockquote>\n<pre><code> if (Length == 1)\n return;\n if (Length == 2)\n {\n if (_elements[0].CompareTo(_elements[1]) > 0)\n Swap(0, 1);\n return;\n }\n</code></pre>\n</blockquote>\n<p>This looks unnecessary. They're "fast paths" that skip a bunch of extra work in some cases, but those cases should be rare and unimportant: a priority queue that is almost empty is fast anyway regardless of such tricks, and the case of calling <code>SiftDown</code> on a big queue should be more common (because big queues will probably have more items removed from them). These fast path are actually slowing down the common case. But by how much, well probably not a lot.. try it.</p>\n<blockquote>\n<pre><code> if (leftChildIndex >= Length || rightChildIndex >= Length)\n return;\n</code></pre>\n</blockquote>\n<p>This is a bug. If the right child does not exist, the left child could still exist, and may need to swapped with the current node to restore the heap property. The <code>while</code> loop has the same bug. As a trick, you may set the indexes of the left and right child equal when only the left child exists, that way the code for the case of two children can handle that case as well, without needing a whole special case for it.</p>\n<p>For an example of it breaking:</p>\n<pre><code>PriorityQueue<int> P = new PriorityQueue<int>();\nP.Add(0);\nP.Add(1);\nP.Add(2);\nP.Add(3);\nP.Add(4);\nP.Poll();\n</code></pre>\n<p>Now inspect the elements, they are <code>{ 1, 4, 2, 3 }</code> which is wrong, because it has 3 as a child of 4, which violates the heap property. I could not quickly find a sequence of actions where elements are polled in the wrong order, but it seems dangerous to rely on it never happening, given that the internal structure of the heap has been corrupted.</p>\n<p>By the way there is also a fundamentally different alternative way to implement both sift down and sift up that does approximately half the data movement. What both of them really do is take some non-contiguous subset of elements and "shift" them all by one place . That can be done by remembering one element, leaving a "hole" in the list, then instead of swapping you always <em>write</em> an element into the "hole" (which costs only 1 read and 1 write, instead of 2 of each that a swap would cost). Then at the end, you drop the remembered element into the final position of the hole. That would be especially relevant if <code>T</code> is a sizable struct.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T10:28:53.963",
"Id": "524797",
"Score": "0",
"body": "Good points, +1. Updated the code with the fixes."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T08:45:25.393",
"Id": "265696",
"ParentId": "265686",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T02:16:14.177",
"Id": "265686",
"Score": "2",
"Tags": [
"c#",
"priority-queue"
],
"Title": "Generic PriorityQueue (Min-Heap) implementation"
}
|
265686
|
<p>I am trying to code up a basic combinatorial math library for C++. Started with the implementation of the factorial function. Here I include the code and the test code. Please review.</p>
<ol>
<li>Is the way of throwing argument exceptions the best way to do it?</li>
<li>Am I using the Test code the correct way for testing exceptions?</li>
<li>Any other advice will be welcome.</li>
</ol>
<p>N.B: I have seen that the boost library uses a tabularized approach with gamma functions. I shall do these optimizations later.</p>
<pre><code>namespace Combinatorics
{
unsigned long long factorial(int n)
{
if (n < 0)
throw std::invalid_argument("The argument cannot be negative");
unsigned long long fact = 1;
for (int i = 1; i <= n; i++)
{
if ((ULLONG_MAX / i) >= fact)
{
fact = fact * i;
}
else
{
throw std::invalid_argument("The argument is too large");
}
}
return fact;
}
}
TEST(CombinatorialTestCase, Factorial)
{
EXPECT_EQ(120, Combinatorics::factorial(5));
EXPECT_EQ(1, Combinatorics::factorial(0));
EXPECT_EQ(1, Combinatorics::factorial(1));
try
{
EXPECT_EQ(3, Combinatorics::factorial(-1));
}
catch (std::invalid_argument &exception)
{
EXPECT_EQ(exception.what(), std::string("The argument cannot be negative"));
}
catch (...)
{
FAIL();
}
try
{
EXPECT_EQ(500, Combinatorics::factorial(500));
}
catch (std::invalid_argument& exception)
{
EXPECT_EQ(exception.what(), std::string("The argument is too large"));
}
catch (...)
{
FAIL();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T13:48:12.520",
"Id": "524810",
"Score": "1",
"body": "Aside: \"a tabularized approach with gamma functions\" is not an optimization; it's a completely different approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T14:11:35.210",
"Id": "524811",
"Score": "1",
"body": "@Teepeemm, yeah what I wanted to say that I am not talking about different algorithmic optimizations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T14:41:50.507",
"Id": "524813",
"Score": "2",
"body": "You're not supposed to edit the code after posting."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T19:44:23.370",
"Id": "524847",
"Score": "0",
"body": "I think that editing the code after posting is fine. If it makes a comment or answer seem out-of-date, a comment should be placed in the correct spot."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T10:44:34.400",
"Id": "524886",
"Score": "0",
"body": "Initializing an `std::vector<unsigned long long> ` has some CPU overhead at program startup time, even if the `factorial` function is never called. To get rid of this, use an array instead (`const unsigned long long representableFactors[] = { ... }`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T14:42:38.630",
"Id": "524906",
"Score": "3",
"body": "Your new code deserves its own review. It certainly belongs elsewhere than this question, where responders ignored that solution as requested."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T15:53:41.017",
"Id": "524913",
"Score": "0",
"body": "@JosephDoggie, if you want to propose a change to how we operate here, you should probably ask on [meta]. But don't expect a lot of support for that idea, as there's a pretty firm consensus against invalidating answers or having to edit them to remove much of the educational content."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T15:55:38.017",
"Id": "524915",
"Score": "0",
"body": "To me, getting things correct by editing is very important. Perhaps the code review exchange has more rigid rules. I was told in grad school, even if you have to make a pen and ink correction to your thesis/dissertation, it's better (though more messy) than leaving a known error. It's much easier to edit on the web than with pen and ink of course."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T17:42:48.773",
"Id": "524922",
"Score": "1",
"body": "The largest number whose factorial can be represented in a `long long` is 29. This means you may as well just precompute a const array of all 30 possible values and return the result in constant-time rather than compute it on the fly. Check if the value is <0 or >29 and throw an exception, otherwise just return the value indexed from the array."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T20:27:51.390",
"Id": "524928",
"Score": "0",
"body": "Many textbooks use recursion as a way to solve the factorial problem. Or alternatively, use the factorial as an example to teach recursion. However it is done, please do NOT use recursion. Also, reading through all the answers, as often happens, exception handling for overflow, input problems (e.g. negative) etc dominates much of the problem."
}
] |
[
{
"body": "<p>We're missing some required headers:</p>\n<pre><code>#include <climits>\n#include <stdexcept>\n#include <string>\n</code></pre>\n\n<pre><code>#include <gtest/gtest.h>\n</code></pre>\n<hr />\n<p>We can reduce the number of division operations here:</p>\n<blockquote>\n<pre><code> if ((ULLONG_MAX / i) >= fact)\n</code></pre>\n</blockquote>\n<p>If we use <code>ULLONG_MAX / n</code> instead, we get the exception in the same cases, but this doesn't change during the loop and the compiler can hoist the calculation to perform the division just once.</p>\n<p>If we swap the <code>if</code>/<code>else</code> around, we find we don't need <code>else</code> because throwing an exception breaks the flow of control:</p>\n<blockquote>\n<pre><code> if (fact > ULLONG_MAX / n) {\n throw std::invalid_argument("The argument is too large");\n }\n fact *= i;\n</code></pre>\n</blockquote>\n<hr />\n<p>Since negative numbers don't have factorials, it may be better to accept an unsigned type as argument, so we don't need the <code>n < 0</code> test.</p>\n<hr />\n<p>There's no need to check whether other exceptions are thrown:</p>\n<blockquote>\n<pre><code>catch(...)\n{\n FAIL();\n}\n</code></pre>\n</blockquote>\n<p>This is actually harmful, because it gives a information-free failure, whereas GTest's own handling of exceptions will report the exception that was thrown.</p>\n<p>If the concern is that any exception will abort the test case and not run subsequent tests, then the fix is simple - create individual tests for each value.</p>\n<p>In any case, instead of using our own <code>try</code>/<code>catch</code>, we could do better by using the framework's provided <code>EXPECT_THROW</code> macro:</p>\n<pre><code>TEST(Combinatorial_Factorial, small_ints)\n{\n EXPECT_EQ(120, Combinatorics::factorial(5));\n EXPECT_EQ(1, Combinatorics::factorial(0));\n EXPECT_EQ(1, Combinatorics::factorial(1));\n}\n\nTEST(Combinatorial_Factorial, negative)\n{\n EXPECT_THROW(Combinatorics::factorial(-1), std::invalid_argument);\n}\n\nTEST(Combinatorial_Factorial, too_big)\n{\n EXPECT_THROW(Combinatorics::factorial(500), std::invalid_argument);\n}\n</code></pre>\n<p>You'll see that these tests don't verify the message within the exception. That's really a Good Thing, as the content of the message isn't (shouldn't) be part of the spec, and that level of verification is <strong>over-testing</strong>.</p>\n<p>As an aside, we (theoretically at least) can't guarantee that <code>ULLONG_MAX</code> is less than 500!, since there is no upper limit imposed by the standard, only a lower limit.</p>\n<hr />\n<p>The correct exception type to throw is really <code>std::range_error</code> (<em>result of the computation cannot be represented by the destination type</em>).</p>\n<hr />\n<p>Minor style issue: established convention is that we use lower-case names for namespace identifiers.</p>\n<p>Minor issue: <code>fact *= i</code> is equivalent to <code>fact = fact * i</code> and somewhat easier to take in.</p>\n<hr />\n<h1>Modified code</h1>\n<pre><code>#include <climits>\n#include <stdexcept>\n#include <string>\n\nnamespace combinatorics\n{\n unsigned long long factorial(unsigned n)\n {\n unsigned long long fact = 1;\n for (unsigned i = 2; i <= n; ++i) {\n if (fact > ULLONG_MAX / n) {\n throw std::domain_error("The result is too large");\n }\n fact *= i;\n }\n return fact;\n }\n}\n\n\n#include <gtest/gtest.h>\n\nTEST(Combinatorial_Factorial, small_ints)\n{\n EXPECT_EQ(combinatorics::factorial(0), 1);\n EXPECT_EQ(combinatorics::factorial(1), 1);\n EXPECT_EQ(combinatorics::factorial(5), 120);\n}\n\nTEST(Combinatorial_Factorial, too_big)\n{\n EXPECT_THROW(combinatorics::factorial(500), std::invalid_argument);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T06:57:13.017",
"Id": "524775",
"Score": "0",
"body": "Great insights there thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T14:24:07.777",
"Id": "524812",
"Score": "3",
"body": "**Don't** use `unsigned` just because the domain is non-negative. See [ES.106](https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es106-dont-try-to-avoid-negative-values-by-using-unsigned)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T14:49:15.320",
"Id": "524815",
"Score": "3",
"body": "@JDługosz Disagree, yet also agree. (I feel strongly both ways)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T14:53:47.970",
"Id": "524817",
"Score": "0",
"body": "@chux-ReinstateMonica What's to disagree? It doesn't \"fix\" the domain problem but actually makes it worse, as the function can no longer check for invalid values. Plus, `unsigned` is slower."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T14:56:12.957",
"Id": "524819",
"Score": "0",
"body": "@chux-ReinstateMonica counting up will be faster for extended types and on CPUs that don't have fully pipelined multiplication. The test should be done outside the loop, so \"sooner\" is moot; it only makes it clearer how the repeated division and test is redundant."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T14:59:12.430",
"Id": "524820",
"Score": "0",
"body": "@JDługosz \"The test should be done outside the loop,\" is unclear. `i > 0` is the loop test. Do you mean some other test?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T16:07:39.303",
"Id": "524825",
"Score": "0",
"body": "@chux, downside to downcounting is that we need a division every iteration to check for overflow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T16:08:23.027",
"Id": "524826",
"Score": "6",
"body": "@JDługosz, with unsigned type, there is no need to check for invalid values, as _all_ values are then valid. That's the whole point. (And that ES.106 link seems to assume that compiler warnings aren't enabled - just enable them)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T16:15:20.983",
"Id": "524830",
"Score": "0",
"body": "@TobySpeight Agree about downcounting. Suggestion deleted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T16:16:20.583",
"Id": "524831",
"Score": "0",
"body": "@chux: because when we're downcounting, the last multiplication is by 1, not by `n`. So we get a false positive when the result is greater than `ULLONG_MAX / n` but less than `ULLONG_MAX`. (As JDługosz says in answer, we can precompute the largest computable input given the limit of the output type, and that would allow a nice simple downcount without introducing `i`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T17:37:35.653",
"Id": "524843",
"Score": "2",
"body": "If you fi the exceptions, `std::domain_error` looks more appropriate imho."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T08:12:09.113",
"Id": "524876",
"Score": "0",
"body": "You say \"We can reduce the number of division operations here:\" but you don't extract `ULLONG_MAX / n` to a variable, so you actually don't reduce the number of division operations... Correct?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T08:17:38.943",
"Id": "524877",
"Score": "0",
"body": "Also, why not declare `unsigned i = 2` rather than `unsigned i = 1` to avoid useless multiplications?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T09:15:51.230",
"Id": "524878",
"Score": "2",
"body": "@OlivierGrégoire, any decent compiler will hoist `ULLONG_MAX / n` out of the loop; you can store it in a variable if you prefer. Yes, it would make sense to start the loop at `i = 2`; I'll edit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T10:43:13.347",
"Id": "524884",
"Score": "0",
"body": "I'm wondering how costly it would be to essentially reverse the factorial computation in order to find the largest `n` possible, then just use that instead of checking `fact` at every loop iteration. May be overkill, though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T11:35:12.203",
"Id": "524889",
"Score": "1",
"body": "@MatthieuM. I think JDługosz's suggestion to find it as a compile-time constant using `constexpr` calculation is better. Or use `std::tgamma()` to get a `double` approximation to the factorial, and test that against `ULLONG_MAX`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T13:50:26.640",
"Id": "524897",
"Score": "0",
"body": "@TobySpeight: Yes, I hadn't seen JDługosz's answer, and we're essentially saying the same thing."
}
],
"meta_data": {
"CommentCount": "17",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T06:47:12.797",
"Id": "265690",
"ParentId": "265688",
"Score": "12"
}
},
{
"body": "<p>You should write it as a template rather than hard-coding it to produce <code>unsigned long long</code>. You might want to call it with 128-bit integers (a gnu extension), or a Bignum class of some kind such as Boost.Multiprecision.</p>\n<p>Rather than using C's limits macros (<code>ULLONG_MAX</code>), use the C++ <a href=\"https://en.cppreference.com/w/cpp/types/numeric_limits\" rel=\"nofollow noreferrer\"><code>numeric_limits</code></a> library feature. This is template-friendly, and that helps even if you are not writing template code: you don't have to remember <em>different</em> names for the limit based on the type, and finding and fixing these when you change the type of something.</p>\n<hr />\n<p>For the exception, you can include the function name in the error message without complicating the code. You'll be glad of this if the error is ever hit in real code rather than in trivial test code where you're only calling one function!</p>\n<p>As Toby pointed out, you can move the test outside of the loop. (Division is <em>very expensive</em> and will take far longer than the actual factorial computation, as written!). But I'll add to that: Find the maximum legal input value as a <code>constexpr</code> local variable. This will be computed at compile time. But if it's a template, the specified type (some big-int library) might not support <code>constexpr</code> arithmetic if it's not fairly recent, so use <code>static const</code> instead, so it will be computed once and reused on subsequent calls to the function.</p>\n<hr />\n<p>Another tip: concerning <code>std::string("The argument cannot be negative")</code>, assuming you really need to explicitly make it a <code>std::string</code> rather than just passing the lexical string literal, you can use the <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/operator%22%22s\" rel=\"nofollow noreferrer\">string literal operator</a> with identical meaning: <code>"The argument cannot be negative"s</code>.\n<strong>Update:</strong> because the reason is to have <code>==</code> work, it's far more efficient to use a <code>std::string_view</code>. That not only prevents copying the characters, but the comparison is much faster than <code>strcmp</code>.<br />\nWrite: <code>"The argument cannot be negative"sv</code>.<br />\n(read the link above to learn how to opt-in to enable these literals)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T16:14:33.037",
"Id": "524829",
"Score": "0",
"body": "Good idea to compile-time compute the max value. I was trying to think how we could compute inverse-factorial of `ULLONG_MAX`, but of course we don't need to do that - we can loop until we're about to overflow and record that value, all in `constexpr` with favourable types."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T16:23:42.323",
"Id": "524832",
"Score": "0",
"body": "The reason to construct a `std::string` is because `ASSERT_EQ` will use `==` to test the assertion. We don't want to be comparing two `const char*` (as that's pointer equality), so converting one to string object gives us the value equality we want. @suryasis, you'll need `using namespace std::literals;` for that - it's a namespace designed to be used that way, unlike `namespace std`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T17:36:06.727",
"Id": "524841",
"Score": "0",
"body": "maximum value for an unsigned type is easier to just calculate as needed: `T(-1)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T13:48:27.500",
"Id": "524896",
"Score": "1",
"body": "@TobySpeight to get `==` to work naturally, it's more efficient to use a `string_view`. This also has a literal form using the `\"\"sv` suffix. (I have a Code Project article in draft promoting this, in fact.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T13:51:28.333",
"Id": "524898",
"Score": "0",
"body": "@Deduplicator If `T` is not a primitive type but something like Boost.Multiprecision, or a \"safe integer\" wrapper (see the 2021 _CPPNow!_ conference videos) that trick will not work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T13:56:27.870",
"Id": "524899",
"Score": "0",
"body": "Imho, that's moving the goal-posts, as `std::numeric_limits` doesn't really work with either."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T14:41:11.230",
"Id": "265702",
"ParentId": "265688",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "265690",
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T04:35:37.143",
"Id": "265688",
"Score": "9",
"Tags": [
"c++",
"beginner"
],
"Title": "Factorial function for a math library in C++"
}
|
265688
|
<p>I have a project where I publish and subscribe some data packages. Mostly those data packages are just one package, but sometimes (1 in 100) there could be more packages at one time (a lot more, like 100.000 at the same time) I have a class <code>PacketTransport</code> which only has a <code>IDataPacket</code> property in it. I do this so I can serialize and deserialize it with JSON.net and the <code>JsonSerializerSettings</code> with <code>TypeNameHandling = TypeNameHandling.Auto</code> so the deserializer will know which kind of type it is.</p>
<p>I think about making <code>IDataPacket</code> to an <code>IEnumerable<IDataPacket></code> so I will always enumerate eventhough there is just one data packet inside because when sometimes 100.000 Data Packages at a time are coming, my MQTT is overloaded with 100.000 <code>PacketTransport</code> packages and for the next minutes nothing else can pass. But as those 100.000 packets are mostly very small, I would like to pack it in one <code>PacketTransport</code> message.</p>
<p>So my question is: Is it bad to use an IEnumerable where most of the time only one item is inside it? Is the overhead that much or can I ignore it?</p>
<pre><code>public class PacketTransport
{
//Serialize with:
//JsonConvert.SerializeObject(packetTransport, new() { TypeNameHandling = TypeNameHandling.Auto });
public IEnumerable<IDataPacket> DataPackets { get; }
public PacketTransport(IDataPacket dataPacket)
{
if (dataPacket is null) throw new ArgumentNullException(nameof(dataPacket));
DataPackets = new[] { dataPacket }; //Is this the most efficient way?
}
public PacketTransport(IEnumerable<IDataPacket> dataPackets)
{
if (dataPackets is null) throw new ArgumentNullException(nameof(dataPackets));
DataPackets = dataPackets.ToArray(); //Copy the original dataPackets
}
}
public interface IDataPacket
{
int Id { get; }
}
</code></pre>
<p>p.s.: I know, that my main bottleneck is probably the JSON serialization, I will go with protobuf in the future</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T09:29:35.257",
"Id": "524788",
"Score": "3",
"body": "It seems like you are worrying about micro optimization. Have you done any performance analyzis to spot the sweets spots / bottleneck of your system? Like via [CodeTrack](https://www.getcodetrack.com/)"
}
] |
[
{
"body": "<p>The only area I would consider for maintainability of your code is to avoid repeating code i.e. "DRY".</p>\n<pre><code>public class PacketTransport\n{\n public IEnumerable<IDataPacket> DataPackets { get; }\n\n // constructor chaining\n public PacketTransport(IDataPacket dataPacket) \n : this(new[] { dataPacket ?? throw new ArgumentNullException(nameof(dataPacket)) })\n { }\n\n public PacketTransport(IEnumerable<IDataPacket> dataPackets)\n {\n if (dataPackets is null) throw new ArgumentNullException(nameof(dataPackets));\n \n // now we have all the logic for construction in one place.\n DataPackets = dataPackets;\n }\n}\n</code></pre>\n<p>Also note, that I don't see the value of enumerating your collection <code>IDataPacket> dataPackets</code> in your constructor, as it doesn't show any apparent value or "need".</p>\n<pre><code>DataPackets = dataPackets.ToArray(); // <-- no obvious reason why you are doing this...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T20:50:20.343",
"Id": "525002",
"Score": "0",
"body": "In addition to DRY, you can add an extension method on object and do, something like `dataPackets.ValueOrThrow()`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T23:29:47.297",
"Id": "525202",
"Score": "1",
"body": "There is a good reason for `DataPackets = dataPackets.ToArray()`: copy the items from the passed `IEnumerable<IDataPacket>` and ignore future changes in it. Imagine you pass a `List<IDataPacket>` to the constructor and you are saving only a reference to this list by using `DataPackets = dataPackets`. If you remove or add items from this list later, your class will reflect this through `DataPackets`. Using some Linq for `dataPackets` values would be also an example. So it depends on the requirements."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T13:20:01.087",
"Id": "265731",
"ParentId": "265691",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T07:29:20.827",
"Id": "265691",
"Score": "0",
"Tags": [
"c#",
".net",
".net-core"
],
"Title": "Using a IEnumerable where we have mostly only one item"
}
|
265691
|
<p>Component:</p>
<pre class="lang-js prettyprint-override"><code>import React from 'react';
interface QuestionsProps {}
export default function Questions({ children }: React.PropsWithChildren<QuestionsProps>) {
return <div>{children && React.Children.count(children) > 1 ? children.join('\n') : children}</div>;
}
</code></pre>
<p>TSC throws error:</p>
<pre class="lang-bsh prettyprint-override"><code>Property 'join' does not exist on type 'true | ReactChild | ReactFragment | ReactPortal'.
Property 'join' does not exist on type 'string'.ts(2339)
</code></pre>
<p>So I decided to use <a href="https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates" rel="nofollow noreferrer">type predicates</a> of TypeScript.</p>
<pre><code>import React, { ReactNode } from 'react';
interface QuestionsProps {}
const isArrayChildren = (children: any): children is ReactNode[] => {
return React.Children.count(children) > 1;
};
export default function Questions({ children }: React.PropsWithChildren<QuestionsProps>) {
return <div>{isArrayChildren(children) ? children.join('\n') : children}</div>;
}
</code></pre>
<p>Is there any better solution?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T07:48:47.160",
"Id": "265693",
"Score": "0",
"Tags": [
"react.js",
"typescript"
],
"Title": "React children props array type predicate"
}
|
265693
|
<p>I have this method that I feel has code repetition that can be improved but since I am new to Go, I am not quite sure how to improve it. I would appreciate if anyone can give me their opinion.</p>
<pre><code>func (c *Configuration) loadFromEnvVars(key string, target interface{}, optional bool, defaultValue interface{}) error {
err := c.configReader.BindEnv(key)
if err != nil {
if optional {
switch target := target.(type) {
case *string:
*target = defaultValue.(string)
case *bool:
*target = defaultValue.(bool)
default:
return fmt.Errorf("default value type provided is not supported")
}
return nil
}
return fmt.Errorf("%s could not be loaded: %v", key, err)
}
switch target := target.(type) {
case *string:
*target = c.configReader.GetString(key)
case *bool:
*target = c.configReader.GetBool(key)
default:
return fmt.Errorf("configuration value type provided is not supported")
}
return nil
}
</code></pre>
<p>The two switch statements seems like code repetition but I couldn't figure out how to refactor it.</p>
|
[] |
[
{
"body": "<p>You won't get rid of entirely, you could trade the <code>switch</code> cases for <code>if</code> statements of course:</p>\n<pre class=\"lang-golang prettyprint-override\"><code>func (c *Configuration) loadFromEnvVars(key string, target interface{}, optional bool, defaultValue interface{}) error {\n err := c.configReader.BindEnv(key)\n if err != nil && !optional {\n return fmt.Errorf("%s could not be loaded: %v", key, err)\n }\n switch target := target.(type) {\n case *string:\n if err == nil {\n *target = defaultValue.(string)\n } else {\n *target = c.configReader.GetString(key)\n }\n case *bool:\n if err == nil {\n *target = defaultValue.(bool)\n } else {\n *target = c.configReader.GetBool(key)\n }\n default:\n return fmt.Errorf("configuration value type provided is not supported")\n }\n return nil\n}\n</code></pre>\n<p>The upside would be that "similar" code is now closer together.</p>\n<p>Or, if you really wanted to, you could <a href=\"https://pkg.go.dev/reflect\" rel=\"nofollow noreferrer\">use reflection</a> to get rid of the whole thing. That has an additional runtime cost, though for configuration it likely wouldn't matter.</p>\n<p>Something like this:</p>\n<pre class=\"lang-golang prettyprint-override\"><code>func (c *Configuration) loadFromEnvVars(key string, target interface{}, optional bool, defaultValue interface{}) error {\n refTarget := reflect.ValueOf(target).Elem()\n targetType := refTarget.Type()\n\n var value reflect.Value\n\n err := c.configReader.BindEnv(key)\n if err == nil {\n value = reflect.ValueOf(c.configReader.Get(key))\n } else {\n if !optional {\n return fmt.Errorf("%s could not be loaded: %v", key, err)\n }\n value = reflect.ValueOf(defaultValue)\n }\n\n valueType := value.Type()\n\n if !valueType.AssignableTo(targetType) {\n return fmt.Errorf("incompatible types %v and %v", targetType, valueType)\n }\n \n refTarget.Set(value)\n\n return nil\n}\n</code></pre>\n<p>Note that you have to check the types here too to make sure that the assignment call (<code>Set</code>) doesn't panic.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T16:50:41.867",
"Id": "524835",
"Score": "0",
"body": "I ended up using the if/else approach....I'm not a bog fan of reflection because besides the performance hit, it feels like magic"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T10:41:35.417",
"Id": "265700",
"ParentId": "265695",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "265700",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T08:13:02.043",
"Id": "265695",
"Score": "2",
"Tags": [
"go"
],
"Title": "Loading configuration options from environment or default values"
}
|
265695
|
<p>Taking forward the combinatorial library <a href="https://codereview.stackexchange.com/questions/265688/factorial-function-for-a-math-library-in-c">link</a>, I have tried to implement the nCr function. Please mention if this is prone to failing somewhere</p>
<ol>
<li>Any other test code that needs to be added.</li>
<li>Any more efficient way to code this.</li>
</ol>
<p>N.B: I am aware that overflow handling has to be taken into consideration, that is a work in progress.</p>
<p><strong>Code</strong></p>
<pre><code>// MathLibrary.cpp: Defines the functions for the static library.
//
#include "pch.h"
#include "framework.h"
#include <vector>
#include <iostream>
// TODO: This is an example of a library function
namespace Combinatorics
{
const std::vector<unsigned long long> representableFactors = {1,1,2,6,24,120,720,5040,40320,362880,3628800,39916800,
479001600,6227020800,87178291200,1307674368000,20922789888000,355687428096000,6402373705728000,121645100408832000,2432902008176640000};
unsigned long long factorial(unsigned int n)
{
if (n >= representableFactors.size())
{
throw std::invalid_argument("Combinatorics:factorial - The argument is too large");
}
return representableFactors[n];
}
//CODE to be reviewed.
inline unsigned long long gcd(unsigned long long a, unsigned long long b)
{
if (a % b == 0)
return b;
return gcd(b, (a % b));
}
unsigned long long combinations(int n, int r)
{
if (n - r < r)
r = n - r;
unsigned long long int denominatorProduct = 1, numeratorProduct = 1;
for (int denomCount = r, numCount = n ; denomCount >= 1; denomCount--, numCount--)
{
denominatorProduct = denominatorProduct * denomCount;
numeratorProduct = numeratorProduct * numCount;
unsigned gcdCommonFactor = gcd(denominatorProduct, numeratorProduct);
denominatorProduct /= gcdCommonFactor;
numeratorProduct /= gcdCommonFactor;
}
return (numeratorProduct / denominatorProduct);
}
}
</code></pre>
<p><strong>Test code</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#include "pch.h"
#include <iostream>
#include "../MathLibrary/MathLibrary.cpp"
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);
}
</code></pre>
|
[] |
[
{
"body": "<p>I’ll ignore the factorial code, since that was already reviewed in your previous question.</p>\n<p>In <code>combinations()</code>, what would happen if <code>r>n</code>? What if either input is negative? Neither case appears in your test set, and is not tested for in the function either. Unsigned arithmetic with a negative signed integer leads to overflow and headaches…</p>\n<p>In</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>if (n - r < r)\n r = n - r;\n</code></pre>\n<p>you should prefer to use braces. I think they increase readability. There is also an famous story about a bug introduced because of the missing braces: it is easy to add a line of code and think it is inside the conditional, when it’s not. I don’t know how true this is, but GCC added a warning when the indentation is misleading, presumably to address that situation in the legend.</p>\n<p>Here:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>unsigned long long int denominatorProduct = 1, numeratorProduct = 1;\n</code></pre>\n<p>I would prefer two lines, one declaration per line. Again to improve readability.</p>\n<p>You could think of declaring some integer types to use across your library, avoiding the repeated use of <code>unsigned long long int</code> and the like. Not just to make the type name shorter, but also to add some flexibility and consistency.</p>\n<p>Instead of</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>denominatorProduct = denominatorProduct * denomCount;\n</code></pre>\n<p>write:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>denominatorProduct *= denomCount;\n</code></pre>\n<p>This is easier to read. You do use this notation for the division later on. Try to be consistent with your syntax!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T01:35:32.980",
"Id": "265715",
"ParentId": "265703",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T15:25:45.430",
"Id": "265703",
"Score": "1",
"Tags": [
"c++",
"beginner"
],
"Title": "Combination function for a math library in C++"
}
|
265703
|
<p>I build the Shortest Path to Get All Keys algorithm in JavaScript. It's working properly, but with a really bad performance.</p>
<p>The problem:</p>
<p>You are given an m x n grid grid where:</p>
<p>'.' is an empty cell.
'#' is a wall.
'@' is the starting point.
Lowercase letters represent keys.
Uppercase letters represent locks.
You start at the starting point and one move consists of walking one space in one of the four cardinal directions. You cannot walk outside the grid, or walk into a wall.</p>
<p>If you walk over a key, you can pick it up and you cannot walk over a lock unless you have its corresponding key.</p>
<p>For some 1 <= k <= 6, there is exactly one lowercase and one uppercase letter of the first k letters of the English alphabet in the grid. This means that there is exactly one key for each lock, and one lock for each key; and also that the letters used to represent the keys and locks were chosen in the same order as the English alphabet.</p>
<p>Return the lowest number of moves to acquire all keys. If it is impossible, return -1.</p>
<p>Examples:</p>
<pre><code>Input: grid = ["@.a.#","###.#","b.A.B"]
Output: 8
Explanation: Note that the goal is to obtain all the keys not to open all the locks.
</code></pre>
<pre><code>Input: grid = ["@..aA","..B#.","....b"]
Output: 6
</code></pre>
<pre><code>Input: grid = ["@Aa"]
Output: -1
</code></pre>
<p>I implemented a BFS where I keep the current state (path) in which position, so it allows me to go back to a position where I had been before, but now with a different state.</p>
<pre><code>var shortestPathAllKeys = function(grid) {
const directions = [ [0,1], [0,-1], [1,0], [-1,0] ];
const keys = new Set(['a', 'b', 'c', 'd', 'e', 'f']);
const locks = new Set(['A', 'B', 'C', 'D', 'E', 'F']);
const lockToKey = {
'A': 'a', 'B': 'b', 'C': 'c', 'D': 'd', 'E': 'e', "F": 'f'
};
let totalKeys = 0;
let queue = [];
for(let i=0; i<grid.length; i++) {
for(let j=0; j<grid[i].length; j++) {
if(keys.has(grid[i][j]))
totalKeys++;
else if(grid[i][j] === '@') {
const path = `@`;
queue.push([[i,j], path, new Set(), 0]);
}
}
}
const copyKeysSet = (set) => {
let newSet = new Set();
for(const value of set)
newSet.add(value);
return newSet;
}
let visited = new Set();
while(queue.length > 0) {
const [pos, curPath, curKeys, curSteps] = queue.shift();
if(curKeys.size === totalKeys) {
return curSteps;
}
const buildPath = `${pos[0]},${pos[1]},${curPath}`;
if(!visited.has(buildPath)) {
visited.add(buildPath);
for(const d of directions) {
const row = pos[0]+d[0];
const col = pos[1]+d[1];
if(row >= 0 && row < grid.length && col >=0 && col < grid[row].length) {
const c = grid[row][col];
if(c === '#') continue;
if(locks.has(c) && !curKeys.has(lockToKey[c])) continue;
if(keys.has(c)) {
curKeys.add(c);
const newPath = `${curPath},${c}`;
queue.push([[row, col], newPath, copyKeysSet(curKeys), curSteps+1]);
} else {
const newPath = `${curPath}`;
queue.push([[row, col], newPath, copyKeysSet(curKeys), curSteps+1]);
}
}
}
}
}
return -1;
};
</code></pre>
<p>It works fine for the test cases examples. However, if I try the input <code>["@abcdeABCDEFf"]</code> it takes forever to run. Any idea how I could improve the performance?</p>
<p>Thank you.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T03:41:56.687",
"Id": "524866",
"Score": "1",
"body": "Your code does not work, The code either, ends up in an endless loop (Im guessing as I just killed the page rather than waited) or returns a incorrect distance,. example `[\"@cbaABC\"]` should return 13 but your code returns 3 and `[\"@abABcC\"] ` returns 5, should be 7."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T14:34:59.523",
"Id": "524904",
"Score": "0",
"body": "@Blindman67 why should return 13? Move 3 times to the right and grab all 3 keys"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T14:37:02.867",
"Id": "524905",
"Score": "0",
"body": "```[\"@abABcC\"]``` Same. Move 5 times to the right and get all keys."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T22:37:39.120",
"Id": "524931",
"Score": "0",
"body": "My apologies I miss understood the requirement of the task that the doors do not need to be moved over, only the keys, sorry, However does the example where the key is blocked by a looked door `[\"@abcdeABCDEFf\"]` return a value `-1`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T14:58:59.083",
"Id": "524973",
"Score": "0",
"body": "@Blindman67 no worries. Yes, it's a confusing problem. Yes in the example ```[\"@abcdeABCDEFf\"]``` it returns -1."
}
] |
[
{
"body": "<h2>Style</h2>\n<ul>\n<li><p>Always delimit code blocks. eg <code>if (foo) bar()</code> should be <code>if (foo) { bar() }</code></p>\n</li>\n<li><p>Avoid using <code>continue</code></p>\n</li>\n<li><p>Spaces between operators and after commas. Eg <code>pos[0]+d[0]</code> should be <code>pos[0] + d[0]</code> and <code>[0,1]</code> is <code>[0, 1]</code></p>\n</li>\n<li><p>Use constants for variables that do not change.</p>\n</li>\n<li><p>Try to use arrays only to store items that represent the same thing, and use object to store sets of unique items.</p>\n<p>For example you create the queue array item as an array of 4 items <code>queue.push([[i,j], path, new Set(), 0]);</code></p>\n<p>This should be an object <code>queue.push({pos: {x: j, y: i}, path, keys: new Set(), steps: 0})</code></p>\n</li>\n<li><p>Keep code compact, using short form style when possible.</p>\n<p>For example when copying a set you have the function (rewritten as...)</p>\n<pre><code> const copyKeysSet = set => {\n const newSet = new Set();\n for (const value of set) {\n newSet.add(value);\n }\n return newSet;\n }\n</code></pre>\n<p>however this can be written as</p>\n<pre><code> const copyKeysSet = set => new Set([...set])\n</code></pre>\n</li>\n<li><p>Avoid duplication. When you add to the queue you have the same line twice...</p>\n<pre><code> queue.push([[row, col], newPath, copyKeysSet(curKeys), curSteps+1]);\n</code></pre>\n<p>With some rearranging that line need only be written once, one could thus also negate the need to call <code>copyKeySet</code> amd using an object</p>\n<pre><code> queue.push({pos: {x: col, y: row}, path: newPath, keys: new Set([...curKeys]), steps: curSteps + 1});\n</code></pre>\n</li>\n</ul>\n<h2>Bug</h2>\n<p>Testing your code I still find inconsistencies</p>\n<p>The problem, collect all keys using the shortest path. Return the number of steps needed to find all keys.</p>\n<p>Paths steps can only be one of 4 directions, up down left right.</p>\n<p>Lowercase characters are keys, uppercase are doors. Doors can not be stepped over unless you have the corresponding key.</p>\n<h2>Bug 1</h2>\n<p>When given the String (Example <strong>A</strong>)</p>\n<pre><code>const map = [\n "@...b",\n "....B",\n "..a.A"\n];\n</code></pre>\n<p>Your function returns 6, yet the shortest path I can manually find is 8 steps</p>\n<pre><code>"@.678" "@1234" "@1278"\n"1.5.B" "..765" "..36B"\n"234.A" "..8.A" "..45A"\n</code></pre>\n<p>Yet for...</p>\n<pre><code>const map = [\n "@....",\n ".....",\n "..a.A"\n];\n</code></pre>\n<p>...you return 4</p>\n<p>I will assume your code is missing something simple as it works more often than not.</p>\n<h3>Bug 2</h3>\n<p>There are a few cases where the function does not return (even after very long waits). As I don't think your solution is worth further refinement (too computational complex) I have not tracked down why this happens.</p>\n<h2>Performance</h2>\n<p>In terms of speed and memory use your function is very poor.</p>\n<h3>Estimating complexity.</h3>\n<p>Using <span class=\"math-container\">\\$n\\$</span> as cells times keys. For example input <strong>A</strong> we get <span class=\"math-container\">\\$n = 5 * 3 * 2 = 30\\$</span> 5 columns, 3 rows, and 2 keys</p>\n<p>I will play it safe and say the its <span class=\"math-container\">\\$O(n^{log(n)})\\$</span> in both time and space complexity. This is very bad and makes the solution only usable for very small grids.</p>\n<h2>Improving performance</h2>\n<p>Time and space complexity is not a measure of performance as some simple changes to your code that does not change the complexity can improve performance by a order of magnitude.</p>\n<p>The most basic performance improvements can be found...</p>\n<ul>\n<li><p>JavaScript string are slow. Rather than manipulate strings, convert the input grid to character codes as JavaScript handles number much quicker than strings.</p>\n<pre><code>grid.map(line => [...line].map((c, i) => line.charCodeAt(i)));\n</code></pre>\n</li>\n<li><p>Use flat arrays to reduce indexing overhead.</p>\n</li>\n<li><p>JavaScript's <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> is just a simple hash map. However the hashing function is a general function and are rather slow. The values you are hashing eg <code>${y},${x},${key}</code> can easily be converted to unique sequential values <code>x + (y * gridWidth) + (key * gridWidth * gridHeight)</code> and used to quickly index into a pre allocated array. This can be many times quicker than using Set</p>\n<p>You also use sets to check for keys eg the letters <code>"a"</code>,<code>"b"</code>,<code>"c"</code>,<code>"d"</code>... However if you use character codes you can test for a key as <code>cell[idx] >= 97</code> (is lowercase key) you can convert to a key index by subtracting 97. To get the Door for a key just flip the 6th bit <code>doorCC = cell[idx] & 0b1011111</code> for <code>"a"</code> charCode <code>97</code> doorCC is <code>65</code> <code>"A"</code></p>\n<p>As <code>@</code>, <code>.</code>, <code>#</code> are all under character code 65 you can test for a door or key with just <code>if (grid[idx] >= 65)</code>to check if its a key check the 6th bit <code>if (grid[idx] & 0b100000) { /* is key */ } else { /* is door */ }</code></p>\n</li>\n</ul>\n<h2>Alternative algorithm</h2>\n<p>You can use <a href=\"https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm\" rel=\"nofollow noreferrer\">Dijktra's algorithm</a> to find the shortest path between pairs of keys and then recursive select the shortest path.</p>\n<p>This <a href=\"https://codereview.stackexchange.com/a/257681/120556\">answer</a> contains an implementation of Dijktra's algorithm</p>\n<p>Thus if we have 3 keys find the distance from <code>"@"</code> to <code>"a"</code>, <code>"b"</code>, <code>"c"</code>. If doors block the path some keys will not be found. Assuming the first key can be found repeat the search but open the door for <code>"A"</code> finding the path from <code>"a"</code> to <code>"b"</code>, <code>"c"</code> repeat until you have found the distance between all pairs of keys.</p>\n<p>As you do this you will be in a state where all keys are found. You will have a distance traveled, you can then just check that against the lowest distance, and if lower that is the current shortest distance.</p>\n<h2>Example</h2>\n<p>A full solution is too long, so I have given a sub set solution...</p>\n<ul>\n<li><p>It does not handle maps that do not have a solution.</p>\n</li>\n<li><p>It expected that maps are correctly formed. Keys are in order, IE if there is a key <code>c</code> then there must be keys <code>a</code>, <code>b</code>. For each key there must be a door</p>\n</li>\n<li><p>The maps are rectangular, thus the length of grid <code>H</code> and the length of the first element <code>W</code> matches the number of cells <code>cells === W * H</code></p>\n</li>\n</ul>\n<p>The example algorithm is much more complex however the 2 orders improvement in performance is worth the effort, and has lots of room for optimization.</p>\n<p><strong>Hint</strong> the shortest paths from each key to all other keys is often duplicated. Key a to b is the same as b to a, if there is no door between the two. This is ignored in the example</p>\n<h3>The complexity</h3>\n<ul>\n<li>Space is <span class=\"math-container\">\\$O(n)\\$</span> and</li>\n<li>Time is <span class=\"math-container\">\\$O(mn^2)\\$</span> where <span class=\"math-container\">\\$m\\$</span> is number of cells and <span class=\"math-container\">\\$n\\$</span> is number of keys. (This is an estimate that resembles a guess)</li>\n</ul>\n<h3>Performance</h3>\n<p>Excluding visuals The example solves a 13 by 13 grid with 3 keys in <strong>47µs</strong> compared to the <strong>64,610µs</strong> your function requires to solve the same map.</p>\n<p><sub><strong>µs</strong> is 1/1,000,000th second</sub></p>\n<h3>Snippet</h3>\n<p>I have added visual representation to the algorithm that extracts the best paths as arrays of cell indexes. However this is not required to get the length of the shortest path.</p>\n<p>To simplify the need to check for the map edge I add a wall around the grid. This means that at no time do I need to use coordinate pairs when searching for a path.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code> const data = [\n \"@....A.......\",\n \".....#######.\",\n \".....#.....#.\",\n \".....#...c.#.\",\n \".....B.....#.\",\n \".....#######.\",\n \".....#.......\",\n \".....#.......\",\n \".....#.......\",\n \".....#.......\",\n \".....#.......\",\n \".....#.......\",\n \"a....#b...C..\",\n];\n\nsetTimeout(() => console.log(\"Shortest path: \" + shortestPathAllKeys(data)));\n\n\n\n\nfunction shortestPathAllKeys(grid) {\n const CHAR_CODE = c => c.charCodeAt(0);\n const Door = (cc, idx) => cc & 32 ? {key: idx, loc: undefined} : {key: undefined, loc: idx, distTo: undefined};\n const Path = (loc, doorIdx, dist) => ({loc, dist, doorIdx, paths: []});\n const MAX_DOORS = 26;\n const KEY_MASK = 0b11111;\n const CC_START = 64; // or use CHAR_CODE(\"@\");\n const CC_WALL = 35; // CHAR_CODE(\"#\");\n const CC_OPEN = 46; // CHAR_CODE(\".\");\n const CC_LOCKED = 65; // CHAR_CODE(\"A\");\n const CC_KEY = 65 | 32; // CHAR_CODE(\"a\");\n const W = grid[0].length + 2, H = grid.length + 2;\n const boundWall = (\"\").padStart(W + 1 , \"#\");\n var startIdx, minDist = Infinity, keysFound, maxDoors = 0, doors = new Array(MAX_DOORS).fill();\n\n const map = flattenMap(grid);\n const DOOR_COUNT = doors.length;\n if (DOOR_COUNT === 0) { return 0 }\n const mapSize = map.length;\n const workMap = new Array(mapSize).fill(0);\n const foundPaths = [], displayPaths = []; // only for visuals\n \n showMap();\n findPaths(Path(startIdx, -1, 0));\n {\n let i = 0;\n for (const p of displayPaths) { drawPath(p, W, DOOR_COUNT - 1 - i++) }\n }\n return minDist < Infinity ? minDist : -1;\n\n function showMap() {\n var i = 0;\n const showMap = [...map];\n for (const d of doors) {\n showMap[d.loc] = i + 65;\n showMap[d.key] = i + 97;\n i++;\n }\n drawMap(showMap, W, H);\n }\n\n\n\n function flattenMap(grid) {\n var i = 0;\n grid = boundWall + grid.join(\"##\") + boundWall;\n const map = [];\n while (i < grid.length) {\n const cc = grid.charCodeAt(i);\n if (cc === CC_START) {\n startIdx = i;\n map.push(CC_OPEN);\n } else if (cc >= CC_LOCKED) {\n const doorArrayIdx = (cc & KEY_MASK) - 1;\n maxDoors = Math.max(maxDoors, doorArrayIdx + 1);\n const door = doors[doorArrayIdx];\n map.push(cc & 32 ? cc : CC_WALL);\n door ? (cc & 32 ? door.key = i : door.loc = i) : doors[doorArrayIdx] = Door(cc, i);\n } else { map.push(cc) }\n i++;\n }\n doors.length = maxDoors;\n return map;\n }\n\n function pathsDistFrom(fromIdx) { // modified Dijktra's algorithm\n const USED = 0x0F000000;\n const DIST_MASK = 0xFFFFFF;\n const wM = workMap, m = map;\n var stackIdx = 0;\n const stack = [fromIdx]; // stack is actualy a queue (too late now its done to fix name in CR snippet)\n const paths = [];\n wM.fill(0);\n wM[fromIdx] = USED;\n\n const distToStart = idx => {\n const checkHomeStep = (next) => {\n const nVal = wM[next];\n if (nVal >= DIST_MASK) {\n const dist = nVal & DIST_MASK;\n if (dist < mDist) {\n mDist = dist;\n bestIdx = next;\n return next;\n }\n }\n }\n var mDist, dist = 0, bestIdx;\n const pathSteps = [idx]; // for visuals \n while (idx !== fromIdx) {\n const distFromHome = Math.abs(idx - fromIdx);\n if (distFromHome === W || distFromHome === 1) { break }\n const up = idx - W, down = idx + W, left = idx - 1, right = idx + 1;\n mDist = wM[idx] & DIST_MASK;\n bestIdx = idx;\n checkHomeStep(up);\n checkHomeStep(down);\n checkHomeStep(left);\n checkHomeStep(right);\n idx = bestIdx\n pathSteps.push(idx); // for visuals \n dist += 1;\n }\n pathSteps.push(fromIdx);\n foundPaths.push(pathSteps); // for visuals \n return dist;\n }\n\n const nextCell = (idx, dist) => {\n const locVal = m[idx];\n if (wM[idx] === 0 && locVal !== CC_WALL) {\n if (locVal >= CC_KEY) { paths.push(Path(idx, (locVal - 97))) }\n if (locVal !== CC_WALL) {\n wM[idx] = USED + dist + 1;\n stack.push(idx);\n }\n }\n }\n\n while (stackIdx < stack.length) {\n const idx = stack[stackIdx++];\n const dist = wM[idx] & DIST_MASK;\n nextCell(idx - W, dist); // up\n nextCell(idx + W, dist); // down\n nextCell(idx - 1, dist); // left\n nextCell(idx + 1, dist); // right\n }\n foundPaths.length = 0; // for visuals \n for (const p of paths) { p.dist = distToStart(p.loc) + 1 }\n return paths;\n }\n\n function findPaths(path, dist = 0, keysFound = 0) {\n var i = 0, foundShort = false, toFirstKey; // for visuals \n const opensDoor = path.doorIdx > -1 ? doors[path.doorIdx] : undefined;\n opensDoor && (map[opensDoor.key] = map[opensDoor.loc] = CC_OPEN);\n keysFound += 1;\n path.paths.push(...pathsDistFrom(path.loc));\n if (!opensDoor) { toFirstKey = foundPaths[0] } // for visuals \n const dPaths = [...foundPaths]; // for visuals \n if (path.paths.length) {\n if (keysFound === DOOR_COUNT ) {\n for (const p of path.paths) { \n if (minDist > dist + p.dist) { // for visuals \n displayPaths.length = 0; // for visuals \n displayPaths[0] = foundPaths[i]; // for visuals \n foundShort = true; // for visuals \n }\n minDist = Math.min(minDist, dist + p.dist);\n i++; // for visuals \n }\n } else { \n for (const p of path.paths) { \n if (findPaths(p, dist + p.dist, keysFound)) { // for visuals \n displayPaths.push(dPaths[i]); // for visuals \n }\n i++; // for visuals \n }\n }\n }\n opensDoor && (map[opensDoor.key] = path.doorIdx + 97, map[opensDoor.loc] = CC_WALL);\n toFirstKey && displayPaths.push(toFirstKey); // for visuals \n return foundShort;\n }\n \n}\n\n\n\n\n\nconst ctx = canvas.getContext(\"2d\");\nconst S = 30; // cell pixel size\nconst cols = [\"red\",\"green\",\"blue\",\"yellow\",\"cyan\",\"pink\",\"brown\",\"purple\"];\nfunction drawArrow(w, idx1, idx2) {\n ctx.lineWidth = 2;\n const x1 = idx1 % w;\n const y1 = idx1 / w | 0;\n const x2 = idx2 % w;\n const y2 = idx2 / w | 0;\n ctx.setTransform(x2 - x1, y2 - y1, -(y2 - y1), x2 - x1, (x2 + 0.5) * S, (y2 + 0.5) * S);\n ctx.beginPath();\n ctx.lineTo(-S * 0.2, S / 4);\n ctx.lineTo(S * 0.5, S / 4);\n ctx.moveTo(-S * 0, S / 4 - S * 0.2);\n ctx.lineTo(-S * 0.2, S / 4);\n ctx.lineTo(-S * 0, S / 4 + S * 0.2);\n ctx.stroke();\n}\nfunction drawPath(path, w, cidx) {\n ctx.strokeStyle = cols[cidx % cols.length];\n var i = 0;\n var pIdx = path[i++];\n while (i < path.length) {\n const idx = path[i++];\n drawArrow(w, pIdx, idx);\n pIdx = idx;\n }\n}\nfunction drawMap(map, w, h) {\n canvas.width = w * S;\n canvas.height = h * S;\n ctx.font = S + \"px Arial black\";\n ctx.textAlign = \"center\";\n ctx.textBaseline = \"middle\";\n\n var x, y = 0;\n ctx.strokeRect(0,0, w * S, h * S)\n while (y < h) {\n x = 0;\n while (x < w) {\n const idx = y * w + x;\n if (map[idx] === 35) {\n ctx.fillStyle = \"black\";\n ctx.fillRect(x * S, y * S, S, S);\n } else if (map[idx] >= 65) {\n ctx.fillStyle = cols[((map[idx] & 0b11111) - 1) % 4];\n if ((map[idx] & 32) === 0) {\n ctx.fillRect(x * S, y * S, S, S);\n } else {\n ctx.fillText(\"K\", (x + 0.5) * S, (y + 0.6) * S);\n }\n } else {\n ctx.strokeRect(x * S, y * S, S, S)\n }\n x++;\n }\n y++;\n }\n ctx.setTransform(1,0,0,1,0,0);\n \n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><canvas id=\"canvas\"></canvas></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T03:04:36.117",
"Id": "265809",
"ParentId": "265705",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T16:20:47.840",
"Id": "265705",
"Score": "0",
"Tags": [
"javascript",
"algorithm"
],
"Title": "Shortest Path to Get All Keys in JavaScript"
}
|
265705
|
<p>I made a simple BlackJack game and I want to make it as good as possible before I move on to creating a few other games in my "casino" - let me know how I can improve it I added a few things here and there if you are interested my GitHub for this project is linked:</p>
<p><a href="https://github.com/sharoika/CasinoGames" rel="nofollow noreferrer">https://github.com/sharoika/CasinoGames</a></p>
<p><strong>main.cpp :</strong></p>
<pre><code>//
// main.cpp
// CasinoGames
//
// Created by Maksim Sharoika on 2021-07-10.
//
#include <stdlib.h>
#include <iostream>
#include "blackjack.hpp"
// contant for spacer
const int spacer_length = 80;
// function pre-call
int get_input(int, int);
void spacer();
using namespace std;
int main() {
// variable declarations
bool game_on = true;
int money = 100;
// random seed generation
srand(unsigned((time(NULL))));
// introduction message
cout << "--------------------------------------------------------------------------------" << endl;
cout << "--------------------------- Welcome to Maximo-Casino ---------------------------" << endl;
cout << "------------------------ You Have $"<< money << " to Gamble With --------------------------" << endl;
cout << "--------------------------------------------------------------------------------" << endl;
// game logic
while (game_on == true && money > 0)
{
int game_choice = 0;
// choice menu of games
cout << "Please enter the # associated with the game you would like to play, enter 1 to leave." << endl;
cout << "1. BlackJack" << endl;
cout << "0. Leave" << endl;
cout << "Your choice... ";
game_choice = get_input(0, 1);
// leave the casino option
if (game_choice == 0)
{
game_on = false;
}
// leave blackjack option
if (game_choice == 1)
{
money = blackjack(money);
cout << "You have returned from backjack with $" << money << "." << endl;
spacer();
}
}
// game end
if (money <= 0)
{
cout << "You lost all your money - come back when you have more." << endl;
}
spacer();
cout << "You are leaving with $" << money << "." << endl;
cout << "Thank you for playing! - Maxino-Casino." << endl;
spacer();
return 0;
}
// space function
void spacer()
{
for(int i = 0; i < spacer_length; i++)
{
cout << "-";
}
cout << endl;
}
// input function
int get_input(int low_range, int high_range)
{
int input;
while(true)
{
cin >> input;
if (!cin)
{
cout << "Invalid response - please try again... ";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
continue;
}
else if(input < low_range || input > high_range)
{
cout << "Invalid response - please try again... ";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
continue;
}
break;
}
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin.clear();
return input;
}
</code></pre>
<p><strong>blackjack.hpp :</strong></p>
<pre><code>//
// blackjack.hpp
// CasinoGames
//
// Created by Maksim Sharoika on 2021-07-11.
//
#ifndef blackjack_hpp
#define blackjack_hpp
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
// casino functions
int get_input(int, int);
void spacer();
// black-jack function
int blackjack(int money);
// blackjack sub-functions
void restart_cards(int[], int[]);
int get_bet(int);
void generate_cards(int[], int[]);
int ask_player_move();
int calculate_dealer_hand(int, int[]);
int calculate_player_hand(int, int[]);
void inform_player_cards(int, int[]);
void inform_dealer_cards(int, int[]);
void inform_player_total(int);
void inform_dealer_total(int);
int standoff(int, int, int, int);
int bust(int, int, int, int);
int end_game(int, int, int, int);
bool play_again(bool);
#endif /* blackjack_hpp */
</code></pre>
<p><strong>blackjack.cpp :</strong></p>
<pre><code>//
// blackjack.cpp
// CasinoGames
//
// Created by Maksim Sharoika on 2021-07-11.
//
// including the header file
#include "blackjack.hpp"
// creating constant varibles
const int max_card_number = 21;
// main BlackJack function
int blackjack(int money)
{
bool blackjack_game = true;
int player_card[max_card_number];
int dealer_card[max_card_number];
spacer();
cout << "----------------------------- Welcome to BlackJack -----------------------------" << endl;
cout << "------------------------ You Have $"<< money << " to Gamble With --------------------------" << endl;
spacer();
// BlackJack game logic
while(blackjack_game == true)
{
// setting up BlackJack round
restart_cards(player_card, dealer_card);
int bet = 0;
int dealer_hand = 0;
int player_hand = 0;
int player_move = 1;
// Request Bet from Player
bet = get_bet(money);
money = money - bet;
generate_cards(player_card, dealer_card);
// Dealer's Section
spacer();
cout << "Dealer's Hand: "<< endl;
cout << "Card #1: " << "###" << endl;
cout << "Card #2: " << dealer_card[1] << endl;
spacer();
// player move logic
for(int i = 2; player_hand < 22 && player_move == 1; i++)
{
player_hand = calculate_player_hand(i, player_card);
inform_player_cards(i, player_card);
inform_player_total(player_hand);
money = bust(player_hand, dealer_hand, money, bet);
if(player_hand < 22)
{
player_move = ask_player_move();
}
}
// dealer move logic
if(player_hand < 22)
{
int dealer_card_number = 2;
dealer_hand = calculate_dealer_hand(dealer_card_number, dealer_card);
for(int i = 2; dealer_hand < 17; i++)
{
dealer_hand = calculate_dealer_hand(i+1, dealer_card);
dealer_card_number++;
}
dealer_hand = calculate_dealer_hand(dealer_card_number, dealer_card);
inform_dealer_cards(dealer_card_number, dealer_card);
inform_dealer_total(dealer_hand);
money = bust(player_hand, dealer_hand, money, bet);
}
// end game logic
if(dealer_hand < 22 && player_hand < 22)
{
money = end_game(money, bet, player_hand, dealer_hand);
}
// play again logic
if(money > 0)
{
blackjack_game = play_again(blackjack_game);
}
else
{
blackjack_game = false;
}
}
return money;
}
void restart_cards(int player_card[], int dealer_card[])
{
for(int i = 0; i < max_card_number; i++)
{
dealer_card[i] = 0;
player_card[i] = 0;
}
}
int get_bet(int money)
{
int local_bet;
cout << "You currently have: $" << money << endl;
cout << "How much would you like to bet... $";
local_bet = get_input(0, money);
return local_bet;
}
void generate_cards(int player_card[], int dealer_card[])
{
for(int i = 0; i < max_card_number; i++)
{
player_card[i] = ((rand() % 13) + 1);
dealer_card[i] = ((rand() % 13) + 1);
if(player_card[i] > 10)
{
player_card[i] = 10;
}
if(dealer_card[i] > 10)
{
dealer_card[i] = 10;
}
}
}
int ask_player_move()
{
int input;
cout << "What would you like your move to be?" << endl;
cout << "1. Hit " << endl;
cout << "2. Stand" << endl;
cout << "Please enter the numerical value associated... ";
input = get_input(1, 2);
spacer();
return input;
}
int calculate_dealer_hand(int number_of_hits, int dealer_card[])
{
int dealer_hand = 0;
for(int i = 0; i < number_of_hits; i++)
{
dealer_hand = dealer_hand + dealer_card[i];
}
return dealer_hand;
}
int calculate_player_hand(int number_of_hits, int player_card[])
{
int player_hand = 0;
for(int i = 0; i < number_of_hits; i++)
{
player_hand = player_hand + player_card[i];
}
return player_hand;
}
void inform_player_cards(int current_cards, int player_card[])
{
cout << "Your have hit " << current_cards - 2 << " time(s)." << endl;
cout << "Player's Hand: " << endl;
for(int i = 0; i < current_cards; i++)
{
cout << "Card #" << i+1 << ": " << player_card[i] << endl;
}
}
void inform_dealer_cards(int current_cards, int dealer_card[])
{
cout << "Dealer has hit " << current_cards - 2 << " time(s)." << endl;
cout << "Dealer's Hand: " << endl;
for(int i = 0; i < current_cards; i++)
{
cout << "Card #" << i+1 << ": " << dealer_card[i] << endl;
}
}
void inform_dealer_total(int dealer_hand)
{
cout << "The dealer's total card value is: " << dealer_hand << endl;
spacer();
}
void inform_player_total(int player_hand)
{
cout << "Your player's card value is: " << player_hand << endl;
spacer();
}
int standoff(int money, int bet, int player_hand, int dealer_hand)
{
if (player_hand == 21)
{
cout << "Both are BlackJacks money returned.";
money = money + bet;
}
else
{
cout << "Dealer wins because no one has blackjacks.";
money = money;
}
return money;
}
int bust(int player_hand, int dealer_hand, int money, int bet)
{
if(player_hand > 21)
{
cout << "PLAYER BUSTED." << endl;
money = money;
cout << "You now have $" << money << "." << endl;
spacer();
}
if(dealer_hand > 21)
{
cout << "DEALER BUSTED." << endl;
money = money + 2*bet;
cout << "You now have $" << money << "." << endl;
spacer();
}
return money;
}
int end_game(int money, int bet, int player_hand, int dealer_hand)
{
if(player_hand == dealer_hand)
{
cout << "Your and the dealer have a 'Stand Off'" << endl;
money = standoff(money, bet, player_hand, dealer_hand);
}
else if(player_hand < dealer_hand)
{
cout << "DEALER WINS." << endl;
}
else if(player_hand > dealer_hand)
{
cout << "PLAYER WINS." << endl;
money = money + 2*bet;
}
cout << "You now have $" << money << "." << endl;
spacer();
return money;
}
bool play_again(bool blackjack_game)
{
cout << "Would you like to play again?" << endl;
cout << "1. Yes" << endl;
cout << "0. No" << endl;
cout << "Please enter numerical value...";
blackjack_game = get_input(0, 1);
spacer();
return blackjack_game;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T19:36:27.770",
"Id": "524846",
"Score": "0",
"body": "[don't import the standard library (std) in your header file](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice)"
}
] |
[
{
"body": "<pre><code>#include <stdlib.h>\n</code></pre>\n<p>Why are you including the <a href=\"https://en.cppreference.com/w/cpp/header\" rel=\"nofollow noreferrer\">deprecated C header</a>? Why do you need the C header <code><stdio.h></code> as well as <code><iostream></code>? You would use <code><cstdlib></code> if you really needed those C library features, but I think this is just for the old <code>rand</code> stuff, and you should look into <code><random></code> header instead.</p>\n<pre><code>// contant for spacer\nconst int spacer_length = 80;\n</code></pre>\n<p>Spelling? Did you mean "constant"?<br />\nThat would be a singularly useless comment.</p>\n<p>For the constant itself, prefer <code>constexpr</code></p>\n<hr />\n<pre><code>// function pre-call\nint get_input(int, int);\nvoid spacer();\n</code></pre>\n<p>What is a "pre-call"? I think you mean you are declaring the functions that will be defined later in the file? That is inferior to just defining them in the proper order. Due to overloading, having this declaration not match the subsequent definition will not be noticed as an error.</p>\n<p>In any case, you also declare them in the HPP file, which is where they belong. Declaring them again here, when you already included the header file, doesn't add anything.</p>\n<hr />\n<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<p>Especially, <strong>never</strong> do that in a header file! You should not pollute the scope of whatever file includes this header, and this is an especially egregious example of polluting the scope. A header file should not cause any modifications to the includer beyond the API it is defining.</p>\n<hr />\n<pre><code> // variable declarations\n bool game_on = true;\n int money = 100;\n</code></pre>\n<p>Your comment makes it seem like you're clustering all the local variables in a specific section. You don't do that — declare variables where needed. You don't need a comment to say you're declaring a variable, as the statement is itself a variable declaration. These are mixed in with other statements so it would be silly to use such a comment each time!</p>\n<hr />\n<pre><code>void restart_cards(int[], int[]);\nint get_bet(int);\nvoid generate_cards(int[], int[]);\n</code></pre>\n<p>Just looking at the functions in the header, I wonder what are those parameters? Note that this syntax is not actually passing an array, but is automatically converted to a pointer. There's no lengths given, nor any names. Many of the functions have the same or similar parameters, so I wonder if that really ought to be a class with member data?</p>\n<hr />\n<p><code>while(blackjack_game == true)</code><br />\nDon't write explicit comparisons against <code>true</code> or <code>false</code>. You already have a <code>bool</code> value. The <code>operator==</code> between bools produces another bool, so would you have to test <em>that</em> too? I mean, you don't write <code>(x==true)==true</code> right? It's the same thing: you <strong>already have a bool</strong> that represents what you want to do.</p>\n<hr />\n<pre><code> int bet = 0;\n ⋮\n ⋮\n // Request Bet from Player\n bet = get_bet(money);\n</code></pre>\n<p>This is an example of what I mentioned earlier: declare variables when you are ready to use them. This should be:</p>\n<pre><code>const auto bet = get_bet(money);\n</code></pre>\n<p>That is, defined where it is ready to get its proper value, and hopefully made <code>const</code> as well.</p>\n<hr />\n<pre><code>money = money - bet;\n</code></pre>\n<p>Note that you can write: <code>money -= bet;</code></p>\n<hr />\n<p>Don't use <code>endl</code>. There are numerous long explanation posts on this board already. Just use the <code>\\n</code> character where you want a line break.</p>\n<hr />\n<pre><code>void restart_cards(int player_card[], int dealer_card[])\n{\n for(int i = 0; i < max_card_number; i++)\n {\n dealer_card[i] = 0;\n player_card[i] = 0;\n }\n}\n</code></pre>\n<p>Learn what's already there in the standard library! This is just <a href=\"https://en.cppreference.com/w/cpp/algorithm/fill_n\" rel=\"nofollow noreferrer\"><code>fill_n</code></a>.</p>\n<p>This is an example too of there being no proper encapsulation: you're passing pointers to the start of arrays to these functions, but those arrays are fixed variables and have specific purposes, and you are not associating the length with the pointer. They should be <strong>member data</strong> and the various functions that use them can refer to the names directly and not have to be passed.</p>\n<p>Why do you need <code>restart_cards</code> anyway? That zeros everything, but you never leave it in such a state, but call <code>generate_cards</code> to populate with the real values.</p>\n<hr />\n<pre><code> player_card[i] = ((rand() % 13) + 1);\n dealer_card[i] = ((rand() % 13) + 1);\n if(player_card[i] > 10)\n {\n player_card[i] = 10;\n }\n if(dealer_card[i] > 10)\n {\n dealer_card[i] = 10;\n }\n }\n</code></pre>\n<p>Don't repeat the same code with only the variable changed. Abstract it out into a function. You would have something like: <code>player_card[i] = deal_card();</code>.</p>\n<p>This is more like dice, not cards: rather than a shuffled deck, it picks a random value every time.</p>\n<p>This function, <code>generate_cards</code>, is doing the same thing for two different arguments. Why not make the function have one copy of the code, and then call it twice with two different arguments? That is:</p>\n<pre><code>generate_cards (dealer_card);\ngenerate_cards (player_card);\n</code></pre>\n<hr />\n<pre><code>int calculate_dealer_hand(int number_of_hits, int dealer_card[])\n{\n int dealer_hand = 0;\n for(int i = 0; i < number_of_hits; i++)\n {\n dealer_hand = dealer_hand + dealer_card[i];\n }\n return dealer_hand;\n}\n\nint calculate_player_hand(int number_of_hits, int player_card[])\n{\n int player_hand = 0;\n for(int i = 0; i < number_of_hits; i++)\n {\n player_hand = player_hand + player_card[i];\n }\n return player_hand;\n}\n</code></pre>\n<p>I think you are not understanding what parameters are for!</p>\n<p>You have two <em>identical</em> functions, that are each called with a different (fixed) variable when you use it. Each call should be passing the data it wants to operate on to the <strong>same</strong> piece of code.</p>\n<p>There are other examples of this throughout.</p>\n<p>As for this function in particular, it took me a while to figure out how it's supposed to work. You're adding up the entire hand each time you add a card, rather than keeping the total and just dealing another card to it. The "number of hits" is the total number of cards dealt, which you have to keep track of specifically, and separate from the cards array.</p>\n<hr />\n<h1>Good things to continue</h1>\n<p>I see you separated the input into its own functions, which is a good thing.</p>\n<p>You have made functions for many different steps, which looks like you did some kind of "top-down design". That's good. However, your <code>main</code> function is not decomposed enough; it calls a lot of small functions with meaningful names, but each "clump" is a cohesive set of logic that should be its own function. Basically, each header-like comment introduces a section that should be a function, and that comment would be the function name.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T21:31:43.123",
"Id": "525068",
"Score": "1",
"body": "Great points - I will be back with all the suggestions sometimes... :) Thanks so much!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T17:17:26.667",
"Id": "265743",
"ParentId": "265706",
"Score": "1"
}
},
{
"body": "<p>You already have a good code review from JDługosz; I am going to give you a higher level design review instead.</p>\n<p>When I look at your code, the first thing that strikes me is that I see no classes anywhere. That’s a code smell; it tells me that what I’m looking at is not actually C++ code, but rather C code. (Or, at best, “C++--”). The reason the lack of classes is such a problem is that the whole point of writing code in a high (or mid) level language like C++ is to <em><strong>model</strong></em> your problem. That’s literally the reason Stroustrup invented the language: he wanted to model his problem and C just couldn’t do it (and the languages that could were too slow).</p>\n<p>So let’s look at how you’ve implemented Blackjack:</p>\n<pre><code>int blackjack(int money)\n{\n // ... [snip] ...\n int player_card[max_card_number];\n int dealer_card[max_card_number];\n\n // ... [snip] ...\n\n // ... actual game happens in this loop block ...\n {\n // ... clear the hands (because you're reusing them each game (not good!)) ...\n\n // ... [snip] ...\n\n // ... get the player's bet ...\n\n // ... generate the two hands ...\n\n // ... report the dealer's first card ...\n\n // ... get the player move (hit or stand) ...\n\n // ... calcuate the dealer move ...\n\n // ... figure out who won ...\n\n // ... ask whether to play again (and restart the loop) ...\n }\n\n return money;\n}\n</code></pre>\n<p>Now the fishy thing about this structure is the <code>... generate the two hands ...</code> part. The way you’ve implemented the game is that you’ve given both players hands with 21 cards, and then you randomly generate the scores for those cards all in one shot at the start of the game, and slowly reveal them to the player as the game goes on.</p>\n<p>That’s not how Blackjack works.</p>\n<p>Blackjack is not played by giving both the player and the dealer 21 cards face down, and then turning up one card at a time. Because you’ve coded it that way, you’ve introduced all kinds of problems and absurdities. For example, it is possible—unlikely, but possible—that <code>generate_cards()</code> gives both the player and the dealer 21 “2” cards. Can you imagine how that game would play out?</p>\n<pre><code>Dealer: 2 ?\nPlayer: (total = 4) 2 2\n\nPlayer hits\n\n================================\n\nDealer: 2 ?\nPlayer: (total = 6) 2 2 2\n\nPlayer hits\n\n================================\n\nDealer: 2 ?\nPlayer: (total = 8) 2 2 2 2\n\nPlayer thinks: WTF? *Five* twos?\nPlayer hits\n\n================================\n\nDealer: 2 ?\nPlayer: (total = 10) 2 2 2 2 2\n\nPlayer thinks: Are you freaking kidding me? *Six* twos?\nPlayer hits\n\n================================\n\nDealer: 2 ?\nPlayer: (total = 12) 2 2 2 2 2 2\n\nPlayer thinks: Okay, this is ridiculous.\nPlayer hits\n\n================================\n\nDealer: 2 ?\nPlayer: (total = 14) 2 2 2 2 2 2 2\n\nPlayer thinks: ...\nPlayer hits several more times\n\n================================\n\nDealer: 2 ?\nPlayer: (total = 20) 2 2 2 2 2 2 2 2 2 2\n\nPlayer thinks: ... wow ...\nPlayer stands\nDealer now hits a bunch of times\n\n================================\n\nDealer: (total = 18) 2 2 2 2 2 2 2 2 2\nPlayer: (total = 20) 2 2 2 2 2 2 2 2 2 2\n\nPlayer wins.\nYay?\n</code></pre>\n<p>Basically the key point of Blackjack—the whole point of the strategy of the game—is that the player is able to look at the cards that have been dealt and calculate odds on what might come up next. But that won’t work here, because you’re just generating random numbers with no respect for what’s left in the deck.</p>\n<p>In other words, this is not really Blackjack. It’s a random number guessing game.</p>\n<p>Let’s take a step back.</p>\n<p>What is Blackjack? It’s a card game; it’s a game played with cards. So you probably need a card type:</p>\n<pre><code>struct card_t {};\n</code></pre>\n<p>What is a card? Well, a card has a suit and a rank:</p>\n<pre><code>struct card_t\n{\n suit_t suit;\n rank_t rank;\n};\n</code></pre>\n<p>I won’t go further into the design of cards, suits, ranks, decks and hands, because <a href=\"https://codereview.stackexchange.com/a/254782/170106\">I’ve already written about that elsewhere</a>. But once you have types for all these things, you just need to add BlackJack-specific logic. In BlackJack, scoring a hand isn’t as simple as just adding up the card values, because aces have <em>two</em> scores: 1 or 11. So when scoring a hand, you need to return <em>multiple</em> possible scores.</p>\n<p>For example, if your hand is , the score is <em>either</em> 5 <em>or</em> 15. This is where a large part of the excitement and strategy comes in. Do I stand with 15? Do I try to hit and hope I get a 6 or less? Do I want to risk getting a 7–9 and my score going <em>down</em>? I can look at the cards that are visible and calculate percentages. <em>THAT</em> is what the game is all about.</p>\n<p>So when you’re scoring a hand, you need to calculate potential <em>multiple</em> scores, and return the list of scores. If all the possible scores of a hand are greater than 21, that’s a bust. If any possible score is 21, you should stop there. If all possible scores are less than 21, then you could either hit or stand depending on a number of factors that the player and your game AI could take into account. For that, you need a scoring function that returns a list of scores. Obviously the minimum number of scores a hand may have is 1… but what is the maximum? Well, if your hand has all 4 aces in the deck, then there are 5 possible scores:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Score</th>\n<th>Ace 1</th>\n<th>Ace 2</th>\n<th>Ace 3</th>\n<th>Ace 4</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>4</td>\n<td>1</td>\n<td>1</td>\n<td>1</td>\n<td>1</td>\n</tr>\n<tr>\n<td>14</td>\n<td>1</td>\n<td>1</td>\n<td>1</td>\n<td>11</td>\n</tr>\n<tr>\n<td>24</td>\n<td>1</td>\n<td>1</td>\n<td>11</td>\n<td>11</td>\n</tr>\n<tr>\n<td>34</td>\n<td>1</td>\n<td>11</td>\n<td>11</td>\n<td>11</td>\n</tr>\n<tr>\n<td>44</td>\n<td>11</td>\n<td>11</td>\n<td>11</td>\n<td>11</td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>More generally, the number of possible scores for a hand is the number of aces in the hand plus one. And each possible score is just plus ten.</p>\n<p>So you could calculate scores like this:</p>\n<pre><code>constexpr auto number_of_aces_in_deck = std::size_t{4};\n\n// rough function, just slapped together, no error checking\nauto score_blackjack_hand(hand_t const& hand)\n{\n auto score_without_aces = 0;\n auto number_of_aces_in_hand = 0;\n for (auto&& card : hand)\n {\n switch (card.rank)\n {\n case rank_t::ace:\n ++number_of_aces;\n break\n case rank_t::jack:\n [[fallthrough]];\n case rank_t::queen:\n [[fallthrough]];\n case rank_t::king:\n score += 10;\n break;\n default;\n score += static_cast<int>(card.rank);\n break;\n }\n }\n\n auto scores = std::array<int, number_of_aces_in_deck + 1>{};\n scores.fill(score_without_aces + number_of_aces_in_hand);\n\n auto p = scores.begin();\n for (auto i = 0; i < number_of_aces_in_hand; ++i)\n std::for_each(++p, scores.end(), [](auto&& score) { score += 10; });\n\n return scores;\n}\n</code></pre>\n<p>This returns an array of possible scores, from lowest to highest (the highest score is repeated because this function just returns an array… you should really use a proper type for this).</p>\n<p>Now the game is basically this:</p>\n<pre><code>auto deck = deck_t::full_deck(); // sets up your full deck of 52 cards\ndeck.shuffle();\n\nauto player_hand = deck.deal(2); // takes 2 cards from the deck to create a new deck (used as the player hand)\nauto dealer_hand = deck.deal(2);\n\n\nwhile (player_is_not_done)\n{\n // ... do the betting ...\n\n std::cout << "you hand is: " << player_hand << '\\n';\n std::cout << "the dealer is showing: " << dealer_hand[0] << '\\n';\n\n std::cout << "hit or stand?\\n";\n\n if (player_wants_hit)\n {\n player_hand.draw_from(deck, 1);\n\n // check minimum score of player's hand\n if (score_blackjack_hand(player_hand)[0] > 21)\n {\n // player busts\n player_is_not_done = false;\n }\n }\n else\n {\n player_is_not_done = false;\n }\n}\n\n// did the player bust?\nif (score_blackjack_hand(player_hand)[0] > 21)\n{\n std::cout << "you're busted, dealer wins\\n";\n}\nelse\n{\n std::cout << "dealer's hand: " << dealer_hand << '\\n';\n\n // get_highest_score() gets the highest score in a set of possible scores\n // that is less than or equal to 21, or if all possible scores are greater\n // than 21, just returns the lowest score\n\n while (get_highest_score(dealer_hand) < get_highest_score(player_hand) and dealer_hand[0] <= 17)\n {\n std::cout << "dealer draws\\n";\n dealer_hand.draw_from(deck, 1);\n std::cout << "dealer's hand: " << dealer_hand << '\\n';\n }\n\n if (dealer_hand[0] > 21)\n {\n std::cout << "dealer busts; you win\\n";\n }\n else if (get_highest_score(dealer_hand) < get_highest_score(player_hand))\n {\n std::cout << "you win\\n";\n }\n else\n {\n std::cout << "dealer wins\\n";\n }\n}\n</code></pre>\n<p>The really powerful thing about doing things this way is that:</p>\n<ol>\n<li>It’s automatically correct (assuming you got the model right). There will be no absurdities like being able to draw 19 twos.</li>\n<li>If you want to modify/extend the game, you can do so naturally. For example, if you want to add another player to the game above, it’s pretty trivial (the only “complication” is that you now need to check multiple scores, but the code above is just slapped together; if I had <em>properly</em> designed it, I would have considered the possibility of multiple players already… I might have created an abstract player class that would allow human players locally and remotely, and multiple types of AI players so people could play against some computer players that are risk-takers, others that are conservative, etc.).</li>\n</ol>\n<p>That’s why we design by modelling the system we’re simulating, rather than just hacking together something that sorta-kinda “looks” right.</p>\n<p>So I would suggest you start by looking at the system—the game of Blackjack. What are the elements of the game? (Well, there are cards, hands, the deck, players, scores, and, if you want betting, money.) How do those elements interact? (Well, players have hands of cards, they draw cards from the deck, and so on.) What is the logic of the system? (Well, scores are calculated by the card’s face value, except face cards are scored at 10, and aces can be 1 or 11. If a hand’s minimum score is 21, the hand busts, and so on.)</p>\n<p>Once you’ve done all that, <em><strong>model</strong></em> the system in C++. Create types for cards, decks, hands, the players, and so on. Make those types work and interact just like the actual things they are modelling.</p>\n<p>If you do all that, and if you get it right, the actual game code will flow very naturally, it will be <em>very</em> hard to introduce bugs or logic errors, and it will be easy to extend or modify the game.</p>\n<p>(You could even take all the above to a higher level, and instead of just thinking about Blackjack, instead think about <em>the whole casino</em>, where Blackjack is only one game of many. At that level, you would be modelling entire <em>games</em> as entities. For example, you might have an abstract <code>game</code> base class, and concrete games like Blackjack derive from that. Then you might be able to do things like keep a history of the games the player has played, so they can see where they’re losing the most money.)</p>\n<p><em>That</em> is what programming in C++ is really like. It’s not just writing C, except using <code>std::cout</code> instead of <code>printf()</code>. It’s about thinking in terms of <em><strong>modelling</strong></em> real-world systems and their interactions in code.</p>\n<p>I am not going to do a code review, because JDługosz already did that. But I will say that your code is <em>archaic</em>; you are not writing C++, you are writing C (with maybe one or two C++ bells and whistles, like <code>std::cout</code>, but for just that there’s really no point). It’s not just that there’s not a single type in your code (which is really bad, because C++ is not just a strongly-typed language, it is <em>the</em> strongly-typed language… C++ is <em>all</em> about the types). It’s a bunch of things, like:</p>\n<ul>\n<li>Using C arrays instead of <a href=\"https://en.cppreference.com/w/cpp/container/array\" rel=\"nofollow noreferrer\">C++ arrays</a>.</li>\n<li>Using bare <code>int</code>s for <em>everything</em> instead of dedicated types for scores, money, etc.. (This is why you have function signatures like this: <code>int end_game(int, int, int, int)</code>. That’s just horrifying. What do all those <code>int</code>s mean? It’s way too easy to forget the order and mix things up.)</li>\n<li>Using naked loops instead of <a href=\"https://en.cppreference.com/w/cpp/algorithm\" rel=\"nofollow noreferrer\">algorithms</a>. Algorithms are already tested, optimized, and safe, and since they’re named, it’s a lot clearer what they’re doing.</li>\n</ul>\n<p>Also, there’s no testing at all. That’s <em>very</em> bad. Untested code is garbage code; you may object by saying “but it works!” to which I’d say… “does it? prove it”. I wouldn’t trust untested in any project I’m working on. You need to get in the habit of properly testing your code; a good practice is to write the tests <em>first</em>, and then write your code… that way you won’t be tempted to skip the tests, and writing the tests first can really help you design your code better because they tests will show you what you actually need.</p>\n<p>So test your code!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T21:31:12.140",
"Id": "525067",
"Score": "0",
"body": "Wonderful - Thank you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T16:17:57.487",
"Id": "265787",
"ParentId": "265706",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T16:26:50.123",
"Id": "265706",
"Score": "3",
"Tags": [
"c++",
"game"
],
"Title": "Simple Blackjack Game in c++"
}
|
265706
|
<p>Currently I am creating an app in Tkinter that creates, displays, and saves sticky notes. I am new to python so I keep trying to rewrite my classes so I have my code more organized but every time I try to create a separate class that inherits from my root class, it quits working properly and won't let me get variables from the inherited class. This is the working code, let me know if this looks terrible or if I just need to better understand how to structure this. It seems far too complicated. I've watched videos on OOP and classes and have been reading Programming Python for some help but I can't seem to impliment classes correctly in Tkinter although I have done general examples that work. The code if functioning fine right now but I am having a hard time adding functionality (allowing user to change font and default colors) with the way it is written.</p>
<pre><code>import tkinter as tk
from tkinter import *
from tkinter.filedialog import asksaveasfile
tiny_font = ('Lucida Console', 8)
small_font = ('CalibriLight', 10)
medium_font = ('CalibriLight', 12)
large_font = ('Lucida Bright', 20)
class MyApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.title(string="Stickies")
self.attributes('-alpha', 0.95)
self.configure(bg="#ffffff")
def makecolor(self):
orange = self.orange.get()
blue = self.blue.get()
purple = self.purple.get()
green = self.green.get()
yellow = self.yellow.get()
pink = self.pink.get()
if orange == '1':
return '#f7d9c4'
if blue == "1":
return '#c6def1'
if purple == "1":
return '#dbcdf0'
if green == "1":
return '#d0f4de'
if yellow == "1":
return '#fcf6bd'
if pink == "1":
return '#f2c6de'
else:
return '#FFFFFF'
def openSettings(self, *args):
settingsWindow = tk.Toplevel(self)
settingsWindow.wm_title('Settings')
Settingsframe = LabelFrame(
settingsWindow,
bg= '#ffffff',
text='Settings',
font=medium_font,
)
Filetypelabel = Label(
Settingsframe,
bg = '#ffffff',
text= 'Set default file save type:'
)
defaulttype = StringVar
Filetypeentry = Entry(
Settingsframe,
bg = '#ffffff',
textvariable = defaulttype,
)
Filetypelabel.pack(padx=10, pady=10)
Filetypeentry.pack(padx=10, pady=10)
saveSettings = Button(Settingsframe,text='Save Settings')
saveSettings.pack(padx=10, pady=10)
Settingsframe.pack(fill=BOTH, padx=10, pady=10)
def getscreensize(self):
screen_width = self.winfo_screenwidth()
screen_height = self.winfo_screenheight()
screen_size = [screen_width, screen_height]
return screen_size
# function invoked when you click the create button ont the main frame
def create_sticky(self, *args):
newWindow = tk.Toplevel(self)
nameentry = self.nameentry.get()
if nameentry == "":
nameentry = 'Untitled'
newWindow.wm_title(nameentry)
Topnoteframe = LabelFrame(
newWindow,
bg= '#ffffff',
font=small_font,
)
saveButton = Button(Topnoteframe, text='Save', command=lambda: save_file())
saveButton.pack(pady=5, expand=True, side=LEFT)
hideButton = Button(Topnoteframe, text='Hide', command=lambda: hide_sticky())
hideButton.pack(pady=5, expand=True, side=LEFT)
showButton = Button(Topnoteframe, text='Show', command=lambda: show_sticky())
showButton.pack(pady=5, expand=True, side=LEFT)
Topnoteframe.pack(fill=BOTH, side=BOTTOM)
newwindowscreenwidth = (getscreensize(newWindow))[1] * 0.3
newwindowscreenheight = (getscreensize(newWindow))[1] * 0.3
stickydims = str(int(newwindowscreenwidth)) + "x" + str(int(newwindowscreenheight))
newWindow.geometry(stickydims)
T = Text(newWindow, height=20, width=40, bg=makecolor(self))
T.pack()
T.configure(font='Calibri')
def save_file():
txtcontent = T.get("1.0", 'end-1c')
f = asksaveasfile(initialfile=(nameentry), defaultextension=".txt",
filetypes=[("All Files", "*.*"), ("Text Documents", "*.txt")])
f.write(txtcontent)
newWindow.destroy()
def show_sticky():
myscreenwidth = (getscreensize(newWindow))[1] * 0.3
myscreenheight = (getscreensize(newWindow))[1] * 0.3
stickydims = str(int(myscreenwidth)) + "x" + str(int(myscreenheight))
newWindow.geometry(stickydims)
def hide_sticky():
stickydims = str(int(0)) + "x" + str(int(50))
newWindow.geometry(stickydims)
myscreenwidth = (getscreensize(self))[1]
myscreenheight = (getscreensize(self))[1]
myscreendims = str(int(myscreenwidth * 0.3)) + "x" + str(int(myscreenheight* 0.5))
myscreenposition = str("+" + str((myscreenwidth+70)) + "+" + str(10))
self.geometry(myscreendims + myscreenposition)
MyMainFrame = frame = LabelFrame(
self,
text='Stickies',
bg='#ffffff',
font=medium_font
)
MyNameFrame = frame_name = LabelFrame(
frame,
text='Name your note',
bg='#ffffff',
font=medium_font
)
MyColorFrame = frame_colors = LabelFrame(
frame,
text='Colors',
bg='#ffffff',
font=medium_font
)
self.nameentry = StringVar()
MyNameEntry = Entry(
frame_name,
textvariable = self.nameentry,
font=small_font,
bg='#f1f1f1'
)
self.purple = StringVar()
self.blue = StringVar()
self.orange = StringVar()
self.green = StringVar()
self.yellow = StringVar()
self.pink = StringVar()
color1 = Checkbutton(
frame_colors,
text = 'Purple',
bg = "#dbcdf0",
variable = self.purple,
font=small_font,
)
color1.deselect()
color2 = Checkbutton(
frame_colors,
text = 'Green',
bg = "#d0f4de",
variable = self.green,
font=small_font,
)
color2.deselect()
color3 = Checkbutton(
frame_colors,
text = 'Blue',
bg = "#c6def1",
variable = self.blue,
font=small_font,
)
color3.deselect()
color4 = Checkbutton(
frame_colors,
text = 'Pink',
bg = "#f2c6de",
variable = self.pink,
font = small_font,
)
color4.deselect()
color5 = Checkbutton(
frame_colors,
text = 'Orange',
bg = "#f7d9c4",
variable = self.orange,
font=small_font,
)
color5.deselect()
color6 = Checkbutton(
frame_colors,
text = 'Yellow',
bg= "#fcf6bd",
variable = self.yellow,
font=small_font,
)
color6.deselect()
# --PACK ELEMENTs----------------------------------------------------------------
color1.pack(padx=5, pady=5)
color2.pack(padx=5, pady=5)
color3.pack(padx=5, pady=5)
color4.pack(padx=5, pady=5)
color5.pack(padx=5, pady=5)
color6.pack(padx=5, pady=5)
MyNameFrame.pack(padx=10, pady=10, fill=BOTH)
MyNameEntry.pack(padx=5, pady=5)
MyMainFrame.pack(expand=False, fill=BOTH, padx=10, pady=10)
MyColorFrame.pack(expand=False, fill=BOTH, padx=10, pady=10)
# Tells the program to return to the create sticky function on click
myCreateButton = Button(
frame,
text='Create',
command=lambda: create_sticky(self),
font = small_font,
)
myCreateButton.pack(padx=5, pady=5)
settingsbutton = Button(
frame,
text= 'Settings',
font = small_font,
command= lambda: openSettings(self),
)
settingsbutton.pack(padx=5, pady=10, side=BOTTOM)
help(MyApp)
if __name__ == '__main__':
w = MyApp()
w.mainloop()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T22:26:00.653",
"Id": "524857",
"Score": "1",
"body": "Your indentation doesn't make much sense starting at `makecolor` and onward. However, by some miracle this all runs as-is, so uh. It's reviewable, but there are going to be some changes needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T23:44:04.977",
"Id": "524861",
"Score": "0",
"body": "I've been writing in Pycharm so I've just been fixing indents as it tells me"
}
] |
[
{
"body": "<p>Overall this is a great start, basically functional, and looks cool.</p>\n<p>Your doing this:</p>\n<p><code>import tkinter as tk</code></p>\n<p>is a good idea - so you should then avoid the next line:</p>\n<p><code>from tkinter import *</code></p>\n<p>as it pollutes your namespace. Using <code>tk.LabelFrame</code> etc. uniformly will help.</p>\n<pre><code> tk.Tk.__init__(self, *args, **kwargs)\n</code></pre>\n<p>should use <code>super()</code> rather than <code>tk.Tk</code>.</p>\n<p>The indentation issue is a case of Python being characterized as friendly to beginners, but actually shooting beginners right in both feet. <code>makecolor</code>, <code>openSettings</code>, and so on should actually be de-indented by one level so that rather than being locally-defined functions, they become actual class methods. Note that the lines starting with:</p>\n<pre><code> myscreenwidth = (getscreensize(self))[1]\n</code></pre>\n<p>are actually just part of <code>__init__</code> - which is fine-ish, but the function definitions above that should all be moved down and de-tabbed.</p>\n<p>You using PyCharm will help - it makes a bunch of suggestions that you would benefit from observing, including PEP8-standard spacing around <code>=</code> operators, etc.</p>\n<p>This:</p>\n<pre><code> myscreenwidth = (getscreensize(self))[1]\n myscreenheight = (getscreensize(self))[1]\n myscreendims = str(int(myscreenwidth * 0.3)) + "x" + str(int(myscreenheight* 0.5))\n myscreenposition = str("+" + str((myscreenwidth+70)) + "+" + str(10))\n</code></pre>\n<p>has a few issues and opportunities for simplification:</p>\n<ul>\n<li>By PEP8, <code>myscreenwidth</code> would be <code>my_screen_width</code></li>\n<li>Seeing <code>[1]</code> twice is likely a bug and you probably want the first one to be <code>[0]</code></li>\n<li>Rather than calling <code>getscreensize(self)</code>, once you properly de-tab your methods, it will look like <code>self.getscreensize()</code></li>\n<li>Tuple unpacking will simplify your return assignment, i.e.</li>\n</ul>\n<pre><code>myscreenwidth, myscreenheight = self.getscreensize()\n</code></pre>\n<p>Your repeated <code>str</code> and <code>+</code> invocations can be simplified using f-strings.</p>\n<p>When you alias a variable like this:</p>\n<pre><code>MyMainFrame = frame =\n</code></pre>\n<p>I'm not sure why. The second variable name seems reasonable and the first does not.</p>\n<p>Your lambda references like</p>\n<pre><code>lambda: openSettings(self)\n</code></pre>\n<p>should be rewritten as</p>\n<pre><code>self.open_settings\n</code></pre>\n<p>Your call to <code>help</code> should probably be dropped.</p>\n<p><code>str(int(0)) + "x" + str(int(50))</code> should just be <code>'0x50'</code>.</p>\n<p><code>initialfile=(nameentry)</code> is a bug and should be <code>initialfile=nameentry.get()</code>.</p>\n<p>Your file type entries should probably be re-expressed as a tuple <code>()</code> instead of a list <code>[]</code>, and put the <code>*.*</code> entry last:</p>\n<pre><code> filetypes=(\n ('Text Documents', '*.txt'),\n ('All Files', '*.*'),\n ),\n</code></pre>\n<p>There's another bug: if you cancel your save dialogue, then currently the application will crash. Adding an <code>if not None</code> will fix this.</p>\n<p>You should also replace your check-boxes with a radio button group so that your colour selection can be mutually exclusive.</p>\n<p>Consider separating out your sticky and settings windows into separate classes.</p>\n<p>You should migrate <code>MyApp</code> from "is-a Tk window" to "has-a Tk window", to enforce better encapsulation.</p>\n<h2 id=\"suggested\">Suggested</h2>\n<p>Addressing some of the above,</p>\n<pre><code>import tkinter as tk\nfrom tkinter.filedialog import asksaveasfile\nfrom typing import Tuple, Callable\n\nTINY_FONT = ('Lucida Console', 8)\nSMALL_FONT = ('CalibriLight', 10)\nMEDIUM_FONT = ('CalibriLight', 12)\nLARGE_FONT = ('Lucida Bright', 20)\n\n\nclass StickyWindow:\n def __init__(\n self,\n name: str,\n colour: str,\n parent: tk.Tk,\n get_size: Callable[[], Tuple[int, int]],\n ) -> None:\n # function invoked when you click the create button ont the main frame\n self.new_window = tk.Toplevel(parent)\n if name == '':\n name = 'Untitled'\n self.name = name\n\n self.new_window.wm_title(name)\n top_note_frame = tk.LabelFrame(\n self.new_window, bg='#ffffff', font=SMALL_FONT,\n )\n\n save_button = tk.Button(top_note_frame, text='Save', command=self.save_file)\n save_button.pack(pady=5, expand=True, side=tk.LEFT)\n\n hide_button = tk.Button(top_note_frame, text='Hide', command=self.hide_sticky)\n hide_button.pack(pady=5, expand=True, side=tk.LEFT)\n\n show_button = tk.Button(top_note_frame, text='Show', command=self.show_sticky)\n show_button.pack(pady=5, expand=True, side=tk.LEFT)\n\n top_note_frame.pack(fill=tk.BOTH, side=tk.BOTTOM)\n\n self.get_size = get_size\n width, height = get_size()\n self.new_window.geometry(f'{width}x{height}')\n\n self.T = T = tk.Text(self.new_window, height=20, width=40, bg=colour)\n T.pack()\n T.configure(font='Calibri')\n\n def save_file(self) -> None:\n txt_content = self.T.get('1.0', 'end-1c')\n f = asksaveasfile(\n initialfile=self.name,\n defaultextension='.txt',\n filetypes=(\n ('Text Documents', '*.txt'),\n ('All Files', '*.*'),\n ),\n )\n if f is not None:\n f.write(txt_content)\n self.new_window.destroy()\n\n def show_sticky(self) -> None:\n width, height = self.get_size()\n self.new_window.geometry(f'{width}x{height}')\n\n def hide_sticky(self) -> None:\n self.new_window.geometry('0x50')\n\n\nclass SettingsWindow:\n def __init__(self, parent: tk.Tk):\n self.window = tk.Toplevel(parent)\n self.window.wm_title('Settings')\n settings_frame = tk.LabelFrame(\n self.window, bg='#ffffff', text='Settings', font=MEDIUM_FONT,\n )\n\n file_type_label = tk.Label(\n settings_frame, bg='#ffffff', text='Set default file save type:'\n )\n\n default_type = tk.StringVar\n file_type_entry = tk.Entry(\n settings_frame, bg='#ffffff', textvariable=default_type,\n )\n file_type_label.pack(padx=10, pady=10)\n file_type_entry.pack(padx=10, pady=10)\n save_settings = tk.Button(settings_frame, text='Save Settings')\n save_settings.pack(padx=10, pady=10)\n settings_frame.pack(fill=tk.BOTH, padx=10, pady=10)\n\n\nclass MyApp:\n def __init__(self) -> None:\n self.window = tk.Tk()\n self.window.title(string='Stickies')\n self.window.attributes('-alpha', 0.95)\n self.window.configure(bg='#ffffff')\n self.mainloop = self.window.mainloop\n\n width, height = self.getscreensize_fraction(0.3, 0.5)\n self.window.geometry(f'{width}x{height}+{width+70}+10')\n\n frame = tk.LabelFrame(\n self.window, text='Stickies', bg='#ffffff', font=MEDIUM_FONT,\n )\n frame_name = tk.LabelFrame(\n frame, text='Name your note', bg='#ffffff', font=MEDIUM_FONT,\n )\n frame_colors = tk.LabelFrame(\n frame, text='Colors', bg='#ffffff', font=MEDIUM_FONT,\n )\n\n self.name_entry = tk.StringVar()\n name_entry = tk.Entry(\n frame_name, textvariable=self.name_entry, font=SMALL_FONT, bg='#f1f1f1',\n )\n\n self.purple = tk.StringVar()\n self.blue = tk.StringVar()\n self.orange = tk.StringVar()\n self.green = tk.StringVar()\n self.yellow = tk.StringVar()\n self.pink = tk.StringVar()\n\n color1 = tk.Checkbutton(\n frame_colors, text='Purple', bg='#dbcdf0', variable=self.purple, font=SMALL_FONT,\n )\n color1.deselect()\n color2 = tk.Checkbutton(\n frame_colors, text='Green', bg='#d0f4de', variable=self.green, font=SMALL_FONT,\n )\n color2.deselect()\n color3 = tk.Checkbutton(\n frame_colors, text='Blue', bg='#c6def1', variable=self.blue, font=SMALL_FONT,\n )\n color3.deselect()\n color4 = tk.Checkbutton(\n frame_colors, text='Pink', bg='#f2c6de', variable=self.pink, font=SMALL_FONT,\n )\n color4.deselect()\n color5 = tk.Checkbutton(\n frame_colors, text='Orange', bg='#f7d9c4', variable=self.orange, font=SMALL_FONT,\n )\n color5.deselect()\n color6 = tk.Checkbutton(\n frame_colors, text='Yellow', bg='#fcf6bd', variable=self.yellow, font=SMALL_FONT,\n )\n color6.deselect()\n\n # --PACK ELEMENTs----------------------------------------------------------------\n color1.pack(padx=5, pady=5)\n color2.pack(padx=5, pady=5)\n color3.pack(padx=5, pady=5)\n color4.pack(padx=5, pady=5)\n color5.pack(padx=5, pady=5)\n color6.pack(padx=5, pady=5)\n frame_name.pack(padx=10, pady=10, fill=tk.BOTH)\n name_entry.pack(padx=5, pady=5)\n frame.pack(expand=False, fill=tk.BOTH, padx=10, pady=10)\n frame_colors.pack(expand=False, fill=tk.BOTH, padx=10, pady=10)\n\n # Tells the program to return to the create sticky function on click\n my_create_button = tk.Button(\n frame, text='Create', command=self.create_sticky, font=SMALL_FONT,\n )\n my_create_button.pack(padx=5, pady=5)\n\n settings_button = tk.Button(\n frame, text='Settings', font=SMALL_FONT, command=self.open_settings,\n )\n settings_button.pack(padx=5, pady=10, side=tk.BOTTOM)\n\n @property\n def colour(self) -> str:\n if self.orange.get() == '1':\n return '#f7d9c4'\n if self.blue.get() == '1':\n return '#c6def1'\n if self.purple.get() == '1':\n return '#dbcdf0'\n if self.green.get() == '1':\n return '#d0f4de'\n if self.yellow.get() == '1':\n return '#fcf6bd'\n if self.pink.get() == '1':\n return '#f2c6de'\n return '#FFFFFF'\n\n def open_settings(self) -> None:\n SettingsWindow(parent=self.window)\n\n def getscreensize_fraction(self, fx: float = 0.3, fy: float = 0.3) -> Tuple[int, int]:\n return (\n int(fx*self.window.winfo_screenwidth()),\n int(fy*self.window.winfo_screenheight()),\n )\n\n def create_sticky(self) -> None:\n StickyWindow(\n name=self.name_entry.get(), colour=self.colour, parent=self.window,\n get_size=self.getscreensize_fraction,\n )\n\n\nif __name__ == '__main__':\n MyApp().mainloop()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T14:34:37.257",
"Id": "524903",
"Score": "2",
"body": "I could cry this is so helpful. Thank you so much. I have been struggling with the Python syntax since all my experience programming is in scripting languages that don't evaluate spaces or indentation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T14:57:26.193",
"Id": "524908",
"Score": "1",
"body": "np - you're in the right place; keep the questions coming :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T01:32:32.703",
"Id": "265714",
"ParentId": "265707",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "265714",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T16:39:54.800",
"Id": "265707",
"Score": "4",
"Tags": [
"python",
"beginner",
"python-3.x",
"tkinter",
"gui"
],
"Title": "Tkinter Sticky Notes"
}
|
265707
|
<p><strong>Hi Everyone, this is my first bash script ever.</strong>
I would really appreciate it if you could provide me with some comments and insights regarding correct function use, logic implementation, and a lead to how to implement the recursive functionality described in the script's body.
Thanks a lot!</p>
<pre><code> #!/bin/bash
#
# The following is a script designed to unpack 4 different compression types.
#
# Known compression type files are unpacked, otherwise, the script ignores them.
#
# The script accepts a file or a list of files, 2 flags which are -v (for verbose) and -r ( for recursive but currently not functional).
#
# The execution syntax is: unpack [-v] [-r] file [file...]
#
# !!!!! Didn't come up with a way to isolate the functionality of -r without code duplication.!!!!!!!!!!!!!!!!
decomp_files=0 # Counts decompressed files.
failed_decomp=0 # Counts filed decompression attempts.
is_verbose=false # States if -v was used (true if used).
is_unpackable=false # States if the can be decompressed.
# The function is responsible for detecting if the parameter provided to the script is a file or not.
# If it's a file, it isolates the type of compression and checks if the -v option is set.
function detect_file_type() {
for file in $@
do
if [ -f "$file" ]
then
# print & isolate compression type
comp_type=`file $file | awk '{print $2}'`
decompress $file $comp_type
if ( $is_verbose && ! $is_unpackable)
then
printf "Ignoring ${file}\n"
elif ( $is_verbose && $is_unpackable )
then
printf "Unpacking ${file}\n"
fi
fi
done
#TOOO: Add logical functionality to: "if file is directory -> cd inside -> repeat".
printf "Decompressed $decomp_files archive(s)\n"
}
# The function decompresses the file with the right binary after its identification.
# Invoked by the detect_file_type function.
function decompress () {
case $comp_type in
"gzip")
gzip --decompress $file
((decomp_files++))
is_unpackable=true
;;
"bzip2")
bunzip2 --decompress $file
((decomp_files++))
is_unpackable=true
;;
"Zip")
unzip $file
((decomp_files++))
is_unpackable=true
;;
"compress'd")
uncompress $file
((decomp_files++))
is_unpackable=true
;;
*)
((failed_decomp++))
is_unpackable=false
;;
esac
}
# This is the first function to be executed.
# The function checks for the optional flags and assigns the corresponding variables accordingly.
function main () {
# Check if the script was executed with parameters.
if [[ -z "${@}" ]]
then
printf "Command structure: unpack [-r] [-v] file [file...]\n"
exit 1
fi
if [ "$1" = "-v" ] || [ "$2" = "-v" ]
then
is_verbose=true
fi
if [ "$1" = "-r" ] || [ "$2" = "-r" ]
then
is_recursive=true
fi
detect_file_type $@
}
main $@
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T10:23:38.760",
"Id": "524882",
"Score": "0",
"body": "Is that first line really indented like that, or is that due to how you copied the code into the question? I'm asking because the shebang (`#!`) only works if it's the first two characters in the file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T10:33:02.830",
"Id": "524959",
"Score": "0",
"body": "Due to the way I copied it, thanks!"
}
] |
[
{
"body": "<p>Please wrap the comments to a reasonable length. Most terminals aren't that wide.</p>\n<p>In a few places, we have <code>$@</code> where we really needed <code>"$@"</code>, causing the script to fail badly when whitespace is present in the values. We should be using Shellcheck to catch silly errors like that.</p>\n<p><code>in "$@"</code> is redundant in a <code>for</code> construct (although some programmers prefer to write it explicitly - that does no harm, I guess).</p>\n<p><code>[[ -z "${@}" ]]</code> is wrong when <code>[$@]</code> expands to multiple arguments. I think it's better expressed as <code>[ "$#" -gt 0 ]</code>. Note the use of plain portable (POSIX) <code>[</code> rather than Bash <code>[[</code>. The script doesn't need any Bash features, so let's stick to standard shell.</p>\n<p>When we print an error message, we should send it to the error stream (<code>>&2</code>).</p>\n<p><code>detect_file_type</code> is badly named - it doesn't just detect the type, but it also acts.</p>\n<p>Why do we update <code>decomp_files</code> and <code>failed_decomp</code> but never use them? We should at least be using the latter to determine our exit status.</p>\n<p>The checking of arguments 1 and 2 for option flags will get unwieldy as we add more options. And the options are getting passed through to <code>detect_file_type</code>, which we don't want. A more conventional structure for handling flags and positional arguments is</p>\n<pre><code>while [ $# -gt 0 ]\ndo\n case "$1" in\n -r) is_recursive=true ;;\n -v) is_verbose=true ;;\n -*) echo "unknown option '$1'" >&2; exit 1;;\n *) process_file "$1"\n esac\n shift\ndone\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T10:35:32.057",
"Id": "524960",
"Score": "0",
"body": "Thanks for the helpful answer. I really appreciate it!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T12:27:07.540",
"Id": "265727",
"ParentId": "265708",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T16:53:53.717",
"Id": "265708",
"Score": "0",
"Tags": [
"bash",
"linux"
],
"Title": "Uncompress files, with autodetection of algorithm"
}
|
265708
|
<p>I have just finished making a maze maker. I took inspiration from <a href="https://www.youtube.com/watch?v=Y37-gB83HKE" rel="nofollow noreferrer">this</a> video, but its my own implementation. I just wanted to know what you guys thought of it and if there are any improvements that can be made like</p>
<ol>
<li>Improving the way the algorithm is implemented</li>
<li>If the code should be less verbose or more lines of code for clarity.</li>
<li>This is not really an issue at all but if the algorithm could have been implemented in a more efficient (faster) way.</li>
</ol>
<p>If you wish to run the code, its <a href="https://github.com/HippozHipos/maze_maker/tree/master/maze%20maker" rel="nofollow noreferrer">here</a>.</p>
<p>Code:</p>
<pre><code>#define OLC_PGE_APPLICATION
#include "pixelGameEngine.h"
#include <stack>
typedef std::pair<olc::vi2d, bool> mazevi2d;
class MazeMaker
{
public:
MazeMaker(olc::vi2d mapSize) :
map{ new int[(size_t)mapSize.x * mapSize.y] }, mapSize{ mapSize }
{
memset(map, 0, (size_t)mapSize.x * mapSize.y * sizeof(int));
map[0] |= CELL_VISITED;
cells.push({ 0, 0 });
maze.push_back({ { 0, 0 }, false });
}
~MazeMaker()
{
delete[] map;
}
public:
std::vector<mazevi2d> Make()
{
bool popped = false;
while (maze.size() < (size_t)mapSize.x * mapSize.y)
{
olc::vi2d lastCell = cells.top();
olc::vi2d direction = GetRandomDirection(lastCell);
if (direction != olc::vi2d{ -1, -1 })
{
olc::vi2d newCell = lastCell + direction;
map[newCell.y * mapSize.x + newCell.x] = CELL_VISITED;
cells.push(newCell);
maze.push_back({ newCell, popped });
popped = false;
}
else
{
popped = true;
cells.pop();
}
}
return maze;
}
private:
olc::vi2d GetRandomDirection(const olc::vi2d& currentCell)
{
int nChoices = 0;
olc::vi2d choices[4];
if (currentCell.y > 0)
{
int topVisited = (map[(currentCell.y - 1) * mapSize.x + currentCell.x] & CELL_VISITED) != CELL_VISITED;
if (topVisited)
choices[nChoices++] = { 0, -1 };
}
if (currentCell.y < mapSize.y - 1)
{
int bottomVisited = (map[(currentCell.y + 1) * mapSize.x + currentCell.x] & CELL_VISITED) != CELL_VISITED;
if (bottomVisited)
choices[nChoices++] = { 0, 1 };
}
if (currentCell.x < mapSize.x - 1)
{
int rightVisited = (map[currentCell.y * mapSize.x + (currentCell.x + 1)] & CELL_VISITED) != CELL_VISITED;
if (rightVisited)
choices[nChoices++] = { 1, 0 };
}
if (currentCell.x > 0)
{
int leftVisited = (map[currentCell.y * mapSize.x + (currentCell.x - 1)] & CELL_VISITED) != CELL_VISITED;
if (leftVisited)
choices[nChoices++] = { -1, 0 };
}
if (nChoices)
{
return choices[rand() % nChoices];
}
return { -1, -1 };
}
private:
std::stack<olc::vi2d> cells;
const olc::vi2d mapSize;
int* map;
std::vector<mazevi2d> maze;
enum CELL
{
CELL_VISITED = 1 << 1,
};
};
class Application : public olc::PixelGameEngine
{
public:
Application()
{
sAppName = "Maze Maker";
}
private:
static constexpr int mapSize = 50;
MazeMaker mazeMaker{ { mapSize, mapSize } };
olc::vi2d offset{ 1, 1 };
std::vector<mazevi2d> maze;
float scale;
public:
bool OnUserCreate() override
{
srand((unsigned int)time(NULL));
scale = ScreenWidth() / mapSize;
maze = mazeMaker.Make();
return true;
}
bool OnUserUpdate(float fElapsedTime) override
{
Clear(olc::BLACK);
for (int i = 1; i < maze.size(); i++)
{
if (!maze[i].second)
DrawLine((maze[i].first * scale) + offset, (maze[(size_t)i - 1].first * scale) + offset);
}
return true;
}
};
int main()
{
Application mazemaker;
if (mazemaker.Construct(300, 300, 2, 2))
mazemaker.Start();
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T06:25:27.183",
"Id": "524871",
"Score": "0",
"body": "The map could be represented more memory efficiently using a smaller datatype such as short or even just a few flags packed into a part of a short/int. In the packed case you would need some shifting logic that would be best to hide in a separate class, although there might not be a performance improvement."
}
] |
[
{
"body": "<h1>Consider making <code>mazevi2d</code> a <code>struct</code>, and rename it</h1>\n<p><code>std::pair</code> is sometimes useful, but the problem is that you access the two elements using <code>.first</code> and <code>.second</code>, and those names are not really describing what you want to do. So I would just create a <code>struct</code> for it, and give proper names to the two elements. Also, the name <code>mazevi2d</code> is not great either, choose a name that better describes what it represents: a segment of the wall. So:</p>\n<pre><code>struct WallSegment {\n olc::vi2d point;\n bool is_start;\n};\n</code></pre>\n<h1>Use a <code>std::vector<bool></code> for <code>map</code></h1>\n<p>It is strange that you are using <code>std::vector</code> and other STL containers in your code, but you manually allocate memory for <code>map</code>. Just use a <code>std::vector</code> for it as well, and you don't have to worry about memory allocation and deallocation. There there is another opportunity to rename it: <code>map</code> is actually tracking whether you have visited a spot on the map, so perhaps naming it <code>visited</code> is better as well. Finally, it only every is set or unset, so a <code>bool</code> is a more appropriate type for it, and then you can also benefit from the specialization of <a href=\"https://en.cppreference.com/w/cpp/container/vector_bool\" rel=\"nofollow noreferrer\"><code>std::vector<bool></code></a> and save memory.</p>\n<pre><code>class MazeMaker {\npublic:\n MazeMaker(olc::vi2d mapSize) :\n mapSize{ mapSize },\n visited( mapSize.x * mapSize. y)\n {\n visited[0] = true;\n ...\n }\n ...\n const olc::vi2d mapSize;\n std::vector<bool> visited;\n ...\n};\n</code></pre>\n<p>It also simplifies the code in <code>GetRandomDirection()</code>. It also brings to light that variables like <code>topVisited</code> actually mean <code>topNotYetVisited</code>. I would remove the temporary variables, and just write code like so:</p>\n<pre><code>if (!visited[(currentCell.y - 1) * mapSize.x + currentCell.x])\n choices[nChoices++] = { 0, -1 };\n</code></pre>\n<h1>Consider turning <code>MazeMaker</code> into a function</h1>\n<p>The only purpose of <code>class MazeMaker</code> is to generate a vector with the walls of the maze, nothing else. All the other member variables are just temporary storage used while running <code>Make()</code>, they are useless afterwards. It also can only generate one maze, afterwards <code>Make()</code> doesn't do anything anymore. So it is better to turn the whole class into a single function that returns the data you actually want:</p>\n<pre><code>std::vector<WallSegment> MakeMaze(olc::vi2d mapSize) {\n const size_t nCells = mapSize.x * mapSize.y;\n std::vector<bool> visited(nCells);\n std::stack<olc::vi2d> cells;\n std::vector<WallSegment> walls;\n\n visited[0] = true;\n cells.push({0, 0});\n walls.push_back({{0, 0}, false});\n bool popped = false;\n\n while (maze.size() < nCells) {\n ...\n }\n\n return walls;\n}\n</code></pre>\n<p>You have to do something with <code>GetRandomDirection()</code>; the simple thing to do is to pass it <code>map</code> and <code>mapSize</code> as const reference parameters.</p>\n<p>Then in <code>class Application</code>, you don't need to have a member variable <code>mazeMaker</code> anymore, just initialize <code>maze</code> like so:</p>\n<pre><code>class Application: public olc::PixelGameEngine {\n ...\nprivate:\n static constexpr size_t mapSize = 50;\n std::vector<WallSegment> walls = MakeMaze({mapSize, mapSize});\n ...\n};\n</code></pre>\n<h1>Better random number generation</h1>\n<p><code>rand()</code> and <code>srand()</code> are the old C way of generating random numbers, and they are quite bad. Since C++11 there are much better ways of generating <a href=\"https://en.cppreference.com/w/cpp/numeric/random\" rel=\"nofollow noreferrer\">random numbers in C++</a>. In particular, consider using a properly seeded <a href=\"https://en.cppreference.com/w/cpp/numeric/random/mersenne_twister_engine\" rel=\"nofollow noreferrer\"><code>std::mt19937</code></a> as the pseudo-random number generator, and use <a href=\"https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution\" rel=\"nofollow noreferrer\"><code>std::uniform_int_distribution</code></a> to choose a number between 0 and <code>nChoices</code> inside <code>GetRandomDirection()</code>.</p>\n<h1>Optimizing memory usage</h1>\n<p>As @worldsmithelper already mentioned, there are better ways to represent the map. In particular, you only need 2 bits per cell, one to indicate whether the cell as a wall on its left, one to indicate it has one at the bottom. You don't need to know whether a cell has a wall on the right, because the cell to the right will already know if it has a wall on the left, which would be the same wall.</p>\n<p>This way, for a 50 by 50 maze, you only need 50 * 50 * 2 / 8 = 625 bytes, whereas your solution uses 50 * 50 * 12 = 30000 bytes.</p>\n<p>For larger mazes, this might be a performance win, but for a 50 by 50 maze it probably won't make a difference.</p>\n<h1>Reduce how often you redraw the maze</h1>\n<p>Your program uses a lot of CPU, and that's because unfortunately by default, olcPixelGameEngine doesn't use vsync, and effectively calls <code>OnUserUpdate()</code> in a loop as fast as possible. The first thing to do is to call <code>Construct()</code> with a few extra parameters to enable vsync:</p>\n<pre><code>if (mazemaker.Construct(300, 300, 2, 2, false, true))\n mazemake.Start();\n</code></pre>\n<p>Secondly, olcPixelGameEngine retains the contents of the screen if you don't do anything in <code>OnUserUpdate()</code>. So you could make it draw the maze the first time <code>OnUserUpdate()</code> is called, and then set a flag. Next time <code>OnUserUpdate()</code> is called, if the flag is set, <code>return true</code> immediately.</p>\n<h1>Optimizing maze generation</h1>\n<p>The algorithm you are using to generate the maze is quite efficient, on average it evaluates the body of the <code>while</code>-loop twice the number of cells in the maze. It is one of the faster algorithms. However, the main reason to use a different algorithm would not be the speed, but what kind of maze it generates. The algorithm you chose results in long, twisty paths with few long straight runs. If that's what you wanted, perfect! Otherwise, look at this StackOverflow question for ideas:</p>\n<p><a href=\"https://stackoverflow.com/questions/38502/whats-a-good-algorithm-to-generate-a-maze?\">What's a good algorithm to generate a maze?</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T11:05:18.740",
"Id": "265723",
"ParentId": "265710",
"Score": "4"
}
},
{
"body": "<ul>\n<li>You should prefer using to typedef</li>\n<li>some of your names like olc::vi2d look more like cypher than an actual name. It might be fine if this is a well-known project-wide terminology, but for a single class it is confusing.</li>\n<li>There is no reason to use new[] to allocate the array. std::vector is a better alternative</li>\n<li>You should not use memset unless you have specific performance considerations. std::fill is a more safe alternative, however if you use vector, you won't need it at all</li>\n<li>You already know what your map contains after initialization, then why |= ?</li>\n<li>you repeat (size_t)mapSize.x * mapSize.y several times, it is better to have a function for that</li>\n<li>Your Maker can actually make only one maze, which is not something I'd expect from this class. You could just call it a Maze in this case or change it to create different mazes</li>\n<li>direction != olc::vi2d{ -1, -1 } this is a non-trivial action which is better extacted in a function just to give it a name</li>\n<li>it is better to have values that are not changed const and the functions that do not change the class stated marked as const</li>\n<li>MakeMaze should return a maze rather than a vector</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T16:28:03.810",
"Id": "524919",
"Score": "0",
"body": "Please use `code` markup. In particular, words like `using` in a sentence, when not marked, make it difficult to read, and expressions of code look strange in general when typeset as text."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T11:10:12.890",
"Id": "265726",
"ParentId": "265710",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "265723",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T20:23:45.740",
"Id": "265710",
"Score": "1",
"Tags": [
"c++"
],
"Title": "General coding style and efficiency of a maze maker"
}
|
265710
|
<p>This is a still incomplete file manager for X11. It can only navigate
through directories, select files (and do nothing with them), call a
script to open files, and call a script to produce and cache thumbnails (it uses the imlib2 library to render images).</p>
<p>Here is the git repository: <a href="https://github.com/phillbush/xfiles" rel="nofollow noreferrer">https://github.com/phillbush/xfiles</a></p>
<p>To test it, do the following:</p>
<ul>
<li><p>First copy the scripts ./thumbnail to your $PATH (or write their
complete path in the following step).</p>
</li>
<li><p>Edit ./config.h, especially the four first items. Set the <code>opener</code>
field of the <code>config</code> structure to the name of the opener program (or
to its complete path, on most linux, it's called xdg-open(1)). Set
<code>thumbnailer</code> to the thumbnailer script (there is one in the github repo). Set <code>dirthumb_path</code> to the
path to
<a href="https://raw.githubusercontent.com/phillbush/xfiles/master/folder.png" rel="nofollow noreferrer"><code>folder.png</code></a>
(the icon of a folder, included in the github repository). And
finally, set <code>filethumb_path</code> to the path to
<a href="https://raw.githubusercontent.com/phillbush/xfiles/master/file.png" rel="nofollow noreferrer"><code>file.png</code></a>
(the icon of a file, included in the github repository).</p>
</li>
<li><p>compile (there is a makefile on the github repository)</p>
</li>
</ul>
<p>Thumbnailing is kinda hacky.
It processes one file thumbnail at a time. First it pipes, forks and execs the thumbnailer script with the given file as argument and add the file descriptor for standard output of this child process to the poll(2). When poll(2) gets the event of this file descriptor, it fgets(3) a line containing the path to the cached thumbnail, closes the file descriptor and wait(2)s for the child process to exit. And then repeats the process for the next file.
This approach is probably hacky and limited to my knowledge (which is not that great). Is there a better way to get thumbnails?
I will probably implement thumbnailing in a separate thread (after I learn pthreads, I have no knowledge in concurrent programming at all).</p>
<p>I'm also reading from stdin because I want to process commands (such as
"cd", "mkdir", etc) from stdin in a future version.</p>
<p><code>config.h</code>:</p>
<pre><code>static struct Config config = {
.opener = "xdg-open",
.thumbnailer = "thumbnail",
.dirthumb_path = "",
.filethumb_path = "",
.font = "monospace:size=9,DejaVuSansMono:size=9",
.background_color = "#000000",
.foreground_color = "#FFFFFF",
.selbackground_color = "#3465a4",
.selforeground_color = "#FFFFFF",
.scrollbackground_color = "#121212",
.scrollforeground_color = "#707880",
.thumbsize_pixels = 64, /* size of thumbnails and icons */
.scroll_pixels = 12, /* scroll bar width */
.width_pixels = 600, /* initial window width */
.height_pixels = 460, /* initial window height */
.hide = 1, /* whether to hide .* entries */
};
</code></pre>
<p><code>xfiles.c</code>:</p>
<pre><code>#include <sys/stat.h>
#include <sys/wait.h>
#include <ctype.h>
#include <dirent.h>
#include <err.h>
#include <fcntl.h>
#include <limits.h>
#include <locale.h>
#include <poll.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/Xresource.h>
#include <X11/Xutil.h>
#include <X11/Xft/Xft.h>
#include <Imlib2.h>
#include "xfiles.h"
/* X11 constant values */
static struct DC dc;
static struct Ellipsis ellipsis;
static Display *dpy;
static Visual *visual;
static Window root;
static Colormap colormap;
static Atom atoms[ATOM_LAST];
static XrmDatabase xdb;
static int screen;
static int depth;
/* flags */
static int running = 1; /* whether xfiles is running */
#include "config.h"
/* show usage and exit */
static void
usage(void)
{
(void)fprintf(stderr, "usage: xfiles [-a] [-g geometry] [path]\n");
exit(1);
}
/* check whether x is between a and b */
static int
between(int x, int a, int b)
{
return a <= x && x <= b;
}
/* get maximum */
static int
max(int x, int y)
{
return x > y ? x : y;
}
/* get minimum */
static int
min(int x, int y)
{
return x < y ? x : y;
}
/* call strdup checking for error; exit on error */
static char *
estrdup(const char *s)
{
char *t;
if ((t = strdup(s)) == NULL)
err(1, "strdup");
return t;
}
/* call malloc checking for error; exit on error */
static void *
emalloc(size_t size)
{
void *p;
if ((p = malloc(size)) == NULL)
err(1, "malloc");
return p;
}
/* call reallocarray checking for error; exit on error */
static void *
ereallocarray(void *ptr, size_t nmemb, size_t size)
{
void *p;
if ((p = reallocarray(ptr, nmemb, size)) == NULL)
err(1, "reallocarray");
return p;
}
/* call getcwd checking for error; exit on error */
static void
egetcwd(char *path, size_t size)
{
if (getcwd(path, size) == NULL) {
err(1, "getcwd");
}
}
/* call pipe checking for error; exit on error */
static void
epipe(int fd[])
{
if (pipe(fd) == -1) {
err(1, "pipe");
}
}
/* call fork checking for error; exit on error */
static pid_t
efork(void)
{
pid_t pid;
if ((pid = fork()) == -1)
err(1, "fork");
return pid;
}
/* call dup2 checking for error; exit on error */
static void
edup2(int fd1, int fd2)
{
if (dup2(fd1, fd2) == -1)
err(1, "dup2");
close(fd1);
}
/* call execlp checking for error; exit on error */
static void
eexec(const char *cmd, const char *arg)
{
if (execlp(cmd, cmd, arg, NULL) == -1) {
err(1, "%s", cmd);
}
}
/* set FD_CLOEXEC on file descriptor; exit on error */
static void
esetcloexec(int fd)
{
if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) {
err(1, "fcntl");
}
}
/* get color from color string */
static void
ealloccolor(const char *s, XftColor *color)
{
if(!XftColorAllocName(dpy, visual, colormap, s, color))
errx(1, "could not allocate color: %s", s);
}
/* call chdir checking for error; print warning on error */
static int
wchdir(const char *path)
{
if (chdir(path) == -1) {
warn("%s", path);
return -1;
}
return 0;
}
/* wrapper around XGrabPointer; e.g., used to grab pointer when scrolling */
static int
grabpointer(struct FM *fm, unsigned int evmask)
{
return XGrabPointer(dpy, fm->win, True, evmask | ButtonReleaseMask,
GrabModeAsync, GrabModeAsync, None,
None, CurrentTime) == GrabSuccess ? 0 : -1;
}
/* ungrab pointer */
static void
ungrab(void)
{
XUngrabPointer(dpy, CurrentTime);
}
/* parse color string */
static void
parsefonts(const char *s)
{
const char *p;
char buf[1024];
size_t nfont = 0;
dc.nfonts = 1;
for (p = s; *p; p++)
if (*p == ',')
dc.nfonts++;
if ((dc.fonts = calloc(dc.nfonts, sizeof *dc.fonts)) == NULL)
err(1, "calloc");
p = s;
while (*p != '\0') {
size_t i;
i = 0;
while (isspace(*p))
p++;
while (i < sizeof buf && *p != '\0' && *p != ',')
buf[i++] = *p++;
if (i >= sizeof buf)
errx(1, "font name too long");
if (*p == ',')
p++;
buf[i] = '\0';
if (nfont == 0)
if ((dc.pattern = FcNameParse((FcChar8 *)buf)) == NULL)
errx(1, "the first font in the cache must be loaded from a font string");
if ((dc.fonts[nfont++] = XftFontOpenName(dpy, screen, buf)) == NULL)
errx(1, "could not load font");
}
dc.fonth = dc.fonts[0]->height;
}
/* parse geometry string, return *width and *height */
static void
parsegeometry(const char *str, int *width, int *height)
{
int w, h;
char *end;
const char *s;
s = str;
w = strtol(s, &end, 10);
if (w < 1 || w > INT_MAX || *s == '\0' || *end != 'x')
goto error;
s = end + 1;
h = strtol(s, &end, 10);
if (h < 1 || h > INT_MAX || *s == '\0' || *end != '\0')
goto error;
*width = w;
*height = h;
error:
return;
}
/* parse icon size string, return *size */
static void
parseiconsize(const char *str, int *size)
{
int m, n;
char *end;
const char *s;
s = str;
m = strtol(s, &end, 10);
if (m < 1 || m > INT_MAX || *s == '\0' || *end != 'x')
goto error;
s = end + 1;
n = strtol(s, &end, 10);
if (n < 1 || n > INT_MAX || *s == '\0' || *end != '\0')
goto error;
if (m != n)
goto error;
*size = m;
error:
return;
}
/* parse path for directory and file icons */
static void
parseiconpath(const char *s, int size, const char **dir, const char **file)
{
static char dirpath[PATH_MAX];
static char filepath[PATH_MAX];
if (s != NULL) {
snprintf(dirpath, sizeof(dirpath), "%s/%dx%d/places/folder.png", s, size, size);
snprintf(filepath, sizeof(filepath), "%s/%dx%d/mimetypes/unknown.png", s, size, size);
}
*dir = dirpath;
*file = filepath;
}
/* get configuration from environment variables */
static void
parseenviron(void)
{
char *s;
if ((s = getenv("ICONSIZE")) != NULL)
parseiconsize(s, &config.thumbsize_pixels);
if ((s = getenv("ICONPATH")) != NULL)
parseiconpath(s, config.thumbsize_pixels, &config.dirthumb_path, &config.filethumb_path);
if ((s = getenv("OPENER")) != NULL)
config.opener = s;
if ((s = getenv("THUMBNAILER")) != NULL)
config.thumbnailer = s;
}
/* get configuration from X resources */
static void
parseresources(void)
{
XrmValue xval;
long n;
char *type;
if (XrmGetResource(xdb, "xfiles.faceName", "*", &type, &xval) == True)
config.font = xval.addr;
if (XrmGetResource(xdb, "xfiles.background", "*", &type, &xval) == True)
config.background_color = xval.addr;
if (XrmGetResource(xdb, "xfiles.foreground", "*", &type, &xval) == True)
config.foreground_color = xval.addr;
if (XrmGetResource(xdb, "xfiles.geometry", "*", &type, &xval) == True)
parsegeometry(xval.addr, &config.width_pixels, &config.height_pixels);
if (XrmGetResource(xdb, "xfiles.scrollbar.background", "XFiles.Scrollbar.background", &type, &xval) == True)
config.scrollbackground_color = xval.addr;
if (XrmGetResource(xdb, "xfiles.scrollbar.foreground", "XFiles.Scrollbar.foreground", &type, &xval) == True)
config.scrollforeground_color = xval.addr;
if (XrmGetResource(xdb, "xfiles.scrollbar.thickness", "XFiles.Scrollbar.thickness", &type, &xval) == True)
if ((n = strtol(xval.addr, NULL, 10)) > 0)
config.scroll_pixels = n;
if (XrmGetResource(xdb, "xfiles.selbackground", "*", &type, &xval) == True)
config.selbackground_color = xval.addr;
if (XrmGetResource(xdb, "xfiles.selforeground", "*", &type, &xval) == True)
config.selforeground_color = xval.addr;
}
/* parse options; return argument (if given) or NULL */
static char *
parseoptions(int argc, char *argv[])
{
int ch;
while ((ch = getopt(argc, argv, "ag:")) != -1) {
switch (ch) {
case 'a':
config.hide = !config.hide;
break;
case 'g':
parsegeometry(optarg, &config.width_pixels, &config.height_pixels);
break;
default:
usage();
break;
}
}
argc -= optind;
argv += optind;
if (argc > 1)
usage();
else if (argc == 1)
return *argv;
return NULL;
}
/* compute number of rows and columns for visible entries */
static void
calcsize(struct FM *fm, int w, int h)
{
if (w >= 0 && h >= 0) {
fm->winw = max(w - config.scroll_pixels, 1);
fm->winh = h;
}
fm->ncol = max(fm->winw / fm->entryw, 1);
fm->nrow = fm->winh / fm->entryh + (fm->winh % fm->entryh ? 2 : 1);
fm->x0 = max((fm->winw - fm->ncol * fm->entryw) / 2, 0);
if (fm->main != None)
XFreePixmap(dpy, fm->main);
fm->main = XCreatePixmap(dpy, fm->win, fm->winw, fm->nrow * fm->entryh, depth);
if (fm->scroll != None)
XFreePixmap(dpy, fm->scroll);
fm->scroll = XCreatePixmap(dpy, fm->win, config.scroll_pixels, fm->winh, depth);
fm->maxrow = fm->nentries / fm->ncol - fm->winh / fm->entryh + 1 + (fm->nentries % fm->ncol != 0);
fm->maxrow = max(fm->maxrow, 1);
fm->scrollh = max(fm->winh / fm->maxrow, 1);
}
/* get next utf8 char from s return its codepoint and set next_ret to pointer to end of character */
static FcChar32
getnextutf8char(const char *s, const char **next_ret)
{
static const unsigned char utfbyte[] = {0x80, 0x00, 0xC0, 0xE0, 0xF0};
static const unsigned char utfmask[] = {0xC0, 0x80, 0xE0, 0xF0, 0xF8};
static const FcChar32 utfmin[] = {0, 0x00, 0x80, 0x800, 0x10000};
static const FcChar32 utfmax[] = {0, 0x7F, 0x7FF, 0xFFFF, 0x10FFFF};
/* 0xFFFD is the replacement character, used to represent unknown characters */
static const FcChar32 unknown = 0xFFFD;
FcChar32 ucode; /* FcChar32 type holds 32 bits */
size_t usize = 0; /* n' of bytes of the utf8 character */
size_t i;
*next_ret = s+1;
/* get code of first byte of utf8 character */
for (i = 0; i < sizeof utfmask; i++) {
if (((unsigned char)*s & utfmask[i]) == utfbyte[i]) {
usize = i;
ucode = (unsigned char)*s & ~utfmask[i];
break;
}
}
/* if first byte is a continuation byte or is not allowed, return unknown */
if (i == sizeof utfmask || usize == 0)
return unknown;
/* check the other usize-1 bytes */
s++;
for (i = 1; i < usize; i++) {
*next_ret = s+1;
/* if byte is nul or is not a continuation byte, return unknown */
if (*s == '\0' || ((unsigned char)*s & utfmask[0]) != utfbyte[0])
return unknown;
/* 6 is the number of relevant bits in the continuation byte */
ucode = (ucode << 6) | ((unsigned char)*s & ~utfmask[0]);
s++;
}
/* check if ucode is invalid or in utf-16 surrogate halves */
if (!between(ucode, utfmin[usize], utfmax[usize]) || between(ucode, 0xD800, 0xDFFF))
return unknown;
return ucode;
}
/* get which font contains a given code point */
static XftFont *
getfontucode(FcChar32 ucode)
{
FcCharSet *fccharset = NULL;
FcPattern *fcpattern = NULL;
FcPattern *match = NULL;
XftFont *retfont = NULL;
XftResult result;
size_t i;
for (i = 0; i < dc.nfonts; i++)
if (XftCharExists(dpy, dc.fonts[i], ucode) == FcTrue)
return dc.fonts[i];
/* create a charset containing our code point */
fccharset = FcCharSetCreate();
FcCharSetAddChar(fccharset, ucode);
/* create a pattern akin to the dc.pattern but containing our charset */
if (fccharset) {
fcpattern = FcPatternDuplicate(dc.pattern);
FcPatternAddCharSet(fcpattern, FC_CHARSET, fccharset);
}
/* find pattern matching fcpattern */
if (fcpattern) {
FcConfigSubstitute(NULL, fcpattern, FcMatchPattern);
FcDefaultSubstitute(fcpattern);
match = XftFontMatch(dpy, screen, fcpattern, &result);
}
/* if found a pattern, open its font */
if (match) {
retfont = XftFontOpenPattern(dpy, match);
if (retfont && XftCharExists(dpy, retfont, ucode) == FcTrue) {
if ((dc.fonts = realloc(dc.fonts, dc.nfonts+1)) == NULL)
err(1, "realloc");
dc.fonts[dc.nfonts] = retfont;
return dc.fonts[dc.nfonts++];
} else {
XftFontClose(dpy, retfont);
}
}
/* in case no fount was found, return the first one */
return dc.fonts[0];
}
/* return width of *s in pixels; draw *s into draw if draw != NULL */
static int
drawtext(XftDraw *draw, XftColor *color, int x, int y, int w, const char *text, size_t maxlen)
{
XftFont *currfont;
XGlyphInfo ext;
FcChar32 ucode;
const char *next, *origtext, *t;
size_t len;
int textwidth = 0;
int texty;
origtext = text;
while (text < origtext + maxlen) {
/* get the next unicode character and the first font that supports it */
ucode = getnextutf8char(text, &next);
currfont = getfontucode(ucode);
/* compute the width of the glyph for that character on that font */
len = next - text;
XftTextExtentsUtf8(dpy, currfont, (XftChar8 *)text, len, &ext);
t = text;
if (w && textwidth + ext.xOff > w) {
t = ellipsis.s;
len = ellipsis.len;
currfont = ellipsis.font;
while (*next)
next++;
textwidth += ellipsis.width;
}
textwidth += ext.xOff;
if (draw) {
texty = y + (dc.fonth - (currfont->ascent + currfont->descent))/2 + currfont->ascent;
XftDrawStringUtf8(draw, color, currfont, x, texty, (XftChar8 *)t, len);
x += ext.xOff;
}
text = next;
}
return textwidth;
}
/* load image from file and scale it to size; return the image and its size */
static Imlib_Image
loadimg(const char *file, int size, int *width_ret, int *height_ret)
{
Imlib_Image img;
Imlib_Load_Error errcode;
const char *errstr;
int width;
int height;
img = imlib_load_image_with_error_return(file, &errcode);
if (*file == '\0') {
return NULL;
} else if (img == NULL) {
switch (errcode) {
case IMLIB_LOAD_ERROR_FILE_DOES_NOT_EXIST:
errstr = "file does not exist";
break;
case IMLIB_LOAD_ERROR_FILE_IS_DIRECTORY:
errstr = "file is directory";
break;
case IMLIB_LOAD_ERROR_PERMISSION_DENIED_TO_READ:
case IMLIB_LOAD_ERROR_PERMISSION_DENIED_TO_WRITE:
errstr = "permission denied";
break;
case IMLIB_LOAD_ERROR_NO_LOADER_FOR_FILE_FORMAT:
errstr = "unknown file format";
break;
case IMLIB_LOAD_ERROR_PATH_TOO_LONG:
errstr = "path too long";
break;
case IMLIB_LOAD_ERROR_PATH_COMPONENT_NON_EXISTANT:
case IMLIB_LOAD_ERROR_PATH_COMPONENT_NOT_DIRECTORY:
case IMLIB_LOAD_ERROR_PATH_POINTS_OUTSIDE_ADDRESS_SPACE:
errstr = "improper path";
break;
case IMLIB_LOAD_ERROR_TOO_MANY_SYMBOLIC_LINKS:
errstr = "too many symbolic links";
break;
case IMLIB_LOAD_ERROR_OUT_OF_MEMORY:
errstr = "out of memory";
break;
case IMLIB_LOAD_ERROR_OUT_OF_FILE_DESCRIPTORS:
errstr = "out of file descriptors";
break;
default:
errstr = "unknown error";
break;
}
warnx("could not load image (%s): %s", errstr, file);
return NULL;
}
imlib_context_set_image(img);
width = imlib_image_get_width();
height = imlib_image_get_height();
if (width > height) {
*width_ret = size;
*height_ret = (height * size) / width;
} else {
*width_ret = (width * size) / height;
*height_ret = size;
}
img = imlib_create_cropped_scaled_image(0, 0, width, height,
*width_ret, *height_ret);
return img;
}
/* draw thumbnail image on pixmaps; then free image */
static void
drawthumb(struct FM *fm, Imlib_Image img, struct Rect *thumb, Pixmap *pix)
{
thumb->x = 0;
thumb->y = 0;
if (img == NULL)
return;
/* compute position of thumbnails */
thumb->x = fm->thumbx + max((config.thumbsize_pixels - thumb->w) / 2, 0);
thumb->y = fm->thumby + max((config.thumbsize_pixels - thumb->h) / 2, 0);
/* clean pixmaps */
XSetForeground(dpy, dc.gc, dc.normal[COLOR_BG].pixel);
XFillRectangle(dpy, pix[UNSEL], dc.gc, fm->thumbx, fm->thumby, config.thumbsize_pixels, config.thumbsize_pixels);
XFillRectangle(dpy, pix[SEL], dc.gc, fm->thumbx - THUMBBORDER, fm->thumby - THUMBBORDER, config.thumbsize_pixels + 2 * THUMBBORDER, config.thumbsize_pixels + 2 * THUMBBORDER);
/* draw border on sel pixmap around thumbnail */
XSetForeground(dpy, dc.gc, dc.select[COLOR_BG].pixel);
XFillRectangle(dpy, pix[SEL], dc.gc, thumb->x - THUMBBORDER, thumb->y - THUMBBORDER, thumb->w + 2 * THUMBBORDER, thumb->h + 2 * THUMBBORDER);
XSetForeground(dpy, dc.gc, dc.normal[COLOR_BG].pixel);
XFillRectangle(dpy, pix[SEL], dc.gc, thumb->x, thumb->y, thumb->w, thumb->h);
/* draw thumbnail on both pixmaps */
imlib_context_set_image(img);
imlib_image_set_changes_on_disk();
imlib_context_set_drawable(pix[UNSEL]);
imlib_render_image_on_drawable(thumb->x, thumb->y);
imlib_context_set_drawable(pix[SEL]);
imlib_render_image_on_drawable(thumb->x, thumb->y);
/* free image */
imlib_free_image();
}
/* call sigaction on sig */
static void
initsignal(int sig, void (*handler)(int sig))
{
struct sigaction sa;
sa.sa_handler = handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
if (sigaction(sig, &sa, 0) == -1) {
err(1, "signal %d", sig);
}
}
/* intern atoms */
static void
initatoms(void)
{
char *atomnames[ATOM_LAST] = {
[UTF8_STRING] = "UTF8_STRING",
[WM_DELETE_WINDOW] = "WM_DELETE_WINDOW",
[_NET_WM_NAME] = "_NET_WM_NAME",
[_NET_WM_PID] = "_NET_WM_PID",
[_NET_WM_WINDOW_TYPE] = "_NET_WM_WINDOW_TYPE",
[_NET_WM_WINDOW_TYPE_NORMAL] = "_NET_WM_WINDOW_TYPE_NORMAL",
};
XInternAtoms(dpy, atomnames, ATOM_LAST, False, atoms);
}
/* initialize drawing context (colors and graphics context) */
static void
initdc(void)
{
dc.gc = XCreateGC(dpy, root, 0, NULL);
ealloccolor(config.background_color, &dc.normal[COLOR_BG]);
ealloccolor(config.foreground_color, &dc.normal[COLOR_FG]);
ealloccolor(config.selbackground_color, &dc.select[COLOR_BG]);
ealloccolor(config.selforeground_color, &dc.select[COLOR_FG]);
ealloccolor(config.scrollbackground_color, &dc.scroll[COLOR_BG]);
ealloccolor(config.scrollforeground_color, &dc.scroll[COLOR_FG]);
parsefonts(config.font);
}
/* create window and set its properties */
static void
initfm(struct FM *fm, int argc, char *argv[])
{
XSetWindowAttributes swa;
XClassHint classh;
Imlib_Image fileimg;
Imlib_Image dirimg;
pid_t pid;
fm->main = None;
fm->scroll = None;
fm->hist = fm->curr = NULL;
fm->entries = NULL;
fm->selected = NULL;
fm->capacity = 0;
fm->nentries = 0;
fm->row = 0;
fm->ydiff = 0;
fm->entryw = config.thumbsize_pixels * 2;
fm->entryh = config.thumbsize_pixels + 3 * dc.fonth + 2 * THUMBBORDER;
fm->thumbx = config.thumbsize_pixels / 2;
fm->thumby = dc.fonth / 2;
fm->textw = fm->entryw - dc.fonth;
fm->textx = dc.fonth / 2;
fm->texty0 = dc.fonth / 2 + config.thumbsize_pixels + 2 * THUMBBORDER;
fm->texty1 = fm->texty0 + dc.fonth;
memset(&fm->dirrect, 0, sizeof(fm->dirrect));
memset(&fm->filerect, 0, sizeof(fm->filerect));
swa.background_pixel = dc.normal[COLOR_BG].pixel;
swa.event_mask = StructureNotifyMask | ExposureMask | KeyPressMask | ButtonPressMask;
fm->win = XCreateWindow(dpy, root, 0, 0, config.width_pixels, config.height_pixels, 0,
CopyFromParent, CopyFromParent, CopyFromParent,
CWBackPixel | CWEventMask, &swa);
classh.res_class = CLASS;
classh.res_name = NULL;
pid = getpid();
XmbSetWMProperties(dpy, fm->win, TITLE, TITLE, argv, argc, NULL, NULL, &classh);
XSetWMProtocols(dpy, fm->win, &atoms[WM_DELETE_WINDOW], 1);
XChangeProperty(dpy, fm->win, atoms[_NET_WM_WINDOW_TYPE], XA_ATOM, 32,
PropModeReplace, (unsigned char *)&atoms[_NET_WM_WINDOW_TYPE_NORMAL], 1);
XChangeProperty(dpy, fm->win, atoms[_NET_WM_PID], XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&pid, 1);
calcsize(fm, config.width_pixels, config.height_pixels);
/* create and clean default thumbnails */
fm->file[UNSEL] = XCreatePixmap(dpy, fm->win, fm->entryw, fm->entryh, depth);
fm->file[SEL] = XCreatePixmap(dpy, fm->win, fm->entryw, fm->entryh, depth);
fm->dir[UNSEL] = XCreatePixmap(dpy, fm->win, fm->entryw, fm->entryh, depth);
fm->dir[SEL] = XCreatePixmap(dpy, fm->win, fm->entryw, fm->entryh, depth);
XSetForeground(dpy, dc.gc, dc.normal[COLOR_BG].pixel);
XFillRectangle(dpy, fm->file[UNSEL], dc.gc, 0, 0, fm->entryw, fm->entryh);
XFillRectangle(dpy, fm->file[SEL], dc.gc, 0, 0, fm->entryw, fm->entryh);
XFillRectangle(dpy, fm->dir[UNSEL], dc.gc, 0, 0, fm->entryw, fm->entryh);
XFillRectangle(dpy, fm->dir[SEL], dc.gc, 0, 0, fm->entryw, fm->entryh);
/* draw default thumbnails */
if (config.filethumb_path != NULL && config.filethumb_path[0] != '\0') {
fileimg = loadimg(config.filethumb_path, config.thumbsize_pixels, &fm->filerect.w, &fm->filerect.h);
drawthumb(fm, fileimg, &fm->filerect, fm->file);
} else {
warnx("could not find icon for files");
}
if (config.dirthumb_path != NULL && config.dirthumb_path[0] != '\0') {
dirimg = loadimg(config.dirthumb_path, config.thumbsize_pixels, &fm->dirrect.w, &fm->dirrect.h);
drawthumb(fm, dirimg, &fm->dirrect, fm->dir);
} else {
warnx("could not find icon for directories");
}
}
/* compute width of ellipsis string */
static void
initellipsis(void)
{
XGlyphInfo ext;
FcChar32 ucode;
const char *s;
ellipsis.s = ELLIPSIS;
ellipsis.len = strlen(ellipsis.s);
ucode = getnextutf8char(ellipsis.s, &s);
ellipsis.font = getfontucode(ucode);
XftTextExtentsUtf8(dpy, ellipsis.font, (XftChar8 *)ellipsis.s, ellipsis.len, &ext);
ellipsis.width = ext.xOff;
}
/* delete current cwd and previous from working directory history */
static void
delcwd(struct FM *fm)
{
struct Histent *h, *tmp;
if (fm->curr == NULL)
return;
h = fm->curr->next;
while (h != NULL) {
tmp = h;
h = h->next;
free(tmp->cwd);
free(tmp);
}
fm->curr->next = NULL;
fm->hist = fm->curr;
}
/* insert cwd into working directory history */
static void
addcwd(struct FM *fm, char *path) {
struct Histent *h;
delcwd(fm);
h = emalloc(sizeof(*h));
h->cwd = estrdup(path);
h->next = NULL;
h->prev = fm->hist;
if (fm->hist)
fm->hist->next = h;
fm->curr = fm->hist = h;
}
/* select entries according to config.hide */
static int
direntselect(const struct dirent *dp)
{
if (strcmp(dp->d_name, ".") == 0)
return 0;
if (strcmp(dp->d_name, "..") == 0)
return 1;
if (config.hide && dp->d_name[0] == '.')
return 0;
return 1;
}
/* compare entries with strcoll, directories first */
static int
entrycompar(const void *ap, const void *bp)
{
struct Entry *a, *b;
a = *(struct Entry **)ap;
b = *(struct Entry **)bp;
/* dotdot (parent directory) first */
if (strcmp(a->name, "..") == 0)
return -1;
if (strcmp(b->name, "..") == 0)
return 1;
/* directories first */
if (a->isdir && !b->isdir)
return -1;
if (b->isdir && !a->isdir)
return 1;
/* dotentries (hidden entries) first */
if (a->name[0] == '.' && b->name[0] != '.')
return -1;
if (b->name[0] == '.' && a->name[0] != '.')
return 1;
return strcoll(a->name, b->name);
}
/* allocate entry */
static struct Entry *
allocentry(struct FM *fm, const char *name, int isdir)
{
struct Entry *ent;
ent = emalloc(sizeof *ent);
ent->sprev = ent->snext = NULL;
ent->pix[UNSEL] = XCreatePixmap(dpy, fm->win, fm->entryw, fm->entryh, depth);
ent->pix[SEL] = XCreatePixmap(dpy, fm->win, fm->entryw, fm->entryh, depth);
ent->issel = 0;
ent->isdir = isdir;
ent->drawn = 0;
ent->name = estrdup(name);
memset(ent->line, 0, sizeof(ent->line));
if (ent->isdir) {
ent->thumb = fm->dirrect;
XCopyArea(dpy, fm->dir[UNSEL], ent->pix[UNSEL], dc.gc, 0, 0, fm->entryw, fm->entryh, 0, 0);
XCopyArea(dpy, fm->dir[SEL], ent->pix[SEL], dc.gc, 0, 0, fm->entryw, fm->entryh, 0, 0);
} else {
ent->thumb = fm->filerect;
XCopyArea(dpy, fm->file[UNSEL], ent->pix[UNSEL], dc.gc, 0, 0, fm->entryw, fm->entryh, 0, 0);
XCopyArea(dpy, fm->file[SEL], ent->pix[SEL], dc.gc, 0, 0, fm->entryw, fm->entryh, 0, 0);
}
return ent;
}
/* destroy entry */
static void
freeentries(struct FM *fm)
{
int i;
for (i = 0; i < fm->nentries; i++) {
XFreePixmap(dpy, fm->entries[i]->pix[UNSEL]);
XFreePixmap(dpy, fm->entries[i]->pix[SEL]);
free(fm->entries[i]->name);
free(fm->entries[i]);
}
}
/* populate list of entries on fm; return -1 on error */
static void
listentries(struct FM *fm, int savecwd)
{
struct dirent **array;
struct stat sb;
int i, n, isdir;
char path[PATH_MAX];
egetcwd(path, sizeof(path));
if (savecwd)
addcwd(fm, path);
if ((n = scandir(path, &array, direntselect, NULL)) == -1)
err(1, "scandir");
freeentries(fm);
if (n > fm->capacity) {
fm->entries = ereallocarray(fm->entries, n, sizeof(*fm->entries));
fm->capacity = n;
}
fm->nentries = n;
for (i = 0; i < fm->nentries; i++) {
if (stat(array[i]->d_name, &sb) == -1) {
warn("%s", path);
isdir = 0;
} else {
isdir = S_ISDIR(sb.st_mode);
}
fm->entries[i] = allocentry(fm, array[i]->d_name, isdir);
free(array[i]);
}
free(array);
qsort(fm->entries, fm->nentries, sizeof(*fm->entries), entrycompar);
}
/* get index of entry from pointer position; return -1 if not found */
static int
getentry(struct FM *fm, int x, int y)
{
struct Entry *ent;
int i, n, w, h;
if (x < fm->x0 || x >= fm->x0 + fm->ncol * fm->entryw)
return -1;
if (y < 0 || y >= fm->winh)
return -1;
x -= fm->x0;
y += fm->ydiff;
w = x / fm->entryw;
h = y / fm->entryh;
i = fm->row * fm->ncol + h * fm->ncol + w;
n = min(fm->nentries, fm->row * fm->ncol + fm->nrow * fm->ncol);
if (i < fm->row * fm->ncol || i >= n)
return -1;
x -= w * fm->entryw;
y -= h * fm->entryh;
ent = fm->entries[i];
if ((x >= ent->thumb.x && x < ent->thumb.x + ent->thumb.w && y >= ent->thumb.y && y < ent->thumb.y + ent->thumb.h) ||
(x >= ent->line[0].x && x < ent->line[0].x + ent->line[0].w && y >= fm->texty0 && y < fm->texty0 + dc.fonth) ||
(x >= ent->line[1].x && x < ent->line[1].x + ent->line[1].w && y >= fm->texty1 && y < fm->texty1 + dc.fonth))
return i;
return -1;
}
/* copy entry pixmap into fm pixmap */
static void
copyentry(struct FM *fm, int i)
{
Pixmap pix;
int x, y;
if (i < fm->row * fm->ncol || i >= fm->row * fm->ncol + fm->nrow * fm->ncol)
return;
pix = (fm->entries[i]->issel ? fm->entries[i]->pix[SEL] : fm->entries[i]->pix[UNSEL]);
i -= fm->row * fm->ncol;
x = i % fm->ncol;
y = (i / fm->ncol) % fm->nrow;
x *= fm->entryw;
y *= fm->entryh;
XCopyArea(dpy, pix, fm->main, dc.gc, 0, 0, fm->entryw, fm->entryh, fm->x0 + x, y);
}
/* commit pixmap into window */
static void
commitdraw(struct FM *fm)
{
fm->scrolly = fm->row * fm->winh / fm->maxrow + fm->ydiff * fm->scrollh / fm->entryh;
XSetForeground(dpy, dc.gc, dc.scroll[COLOR_BG].pixel);
XFillRectangle(dpy, fm->scroll, dc.gc, 0, 0, config.scroll_pixels, fm->winh);
XSetForeground(dpy, dc.gc, dc.scroll[COLOR_FG].pixel);
XFillRectangle(dpy, fm->scroll, dc.gc, 0, fm->scrolly, config.scroll_pixels, fm->scrollh);
XCopyArea(dpy, fm->main, fm->win, dc.gc, 0, fm->ydiff, fm->winw, fm->winh, 0, 0);
XCopyArea(dpy, fm->scroll, fm->win, dc.gc, 0, 0, config.scroll_pixels, fm->winh, fm->winw, 0);
}
/* check if we can break line at the given character (is space, hyphen, etc) */
static int
isbreakable(char c)
{
return c == '.' || c == '-' || c == '_';
}
/* draw names below thumbnail on its pixmaps */
static void
drawentry(struct FM *fm, struct Entry *ent)
{
XftDraw *draw;
int x0, x1, prevw, textw0, textw1, prevlen, len0, len1, i;
textw1 = textw0 = len0 = len1 = 0;
do {
prevw = textw0;
prevlen = len0;
for (; ent->name[len0] != '\0' && !isspace(ent->name[len0]) && !isbreakable(ent->name[len0]); len0++)
;
textw0 = drawtext(NULL, NULL, 0, 0, 0, ent->name, len0);
while (isspace(ent->name[len0]) || isbreakable(ent->name[len0]))
len0++;
} while (textw0 < fm->textw && ent->name[len0] != '\0' && prevw != textw0);
if (textw0 >= fm->textw) {
len0 = prevlen;
textw0 = prevw;
}
while (len0 > 0 && isbreakable(ent->name[len0 - 1]))
len0--;
i = len0;
while (len0 > 0 && isspace(ent->name[len0 - 1]))
len0--;
if (i > 0 && ent->name[i] != '\0') {
len1 = strlen(ent->name+i);
textw1 = drawtext(NULL, NULL, 0, 0, 0, ent->name + i, len1);
} else {
len0 = strlen(ent->name);
textw0 = drawtext(NULL, NULL, 0, 0, 0, ent->name, len0);
}
x0 = fm->textx + max(0, (fm->textw - textw0) / 2);
x1 = fm->textx + max(0, (fm->textw - textw1) / 2);
draw = XftDrawCreate(dpy, ent->pix[UNSEL], visual, colormap);
drawtext(draw, &dc.normal[COLOR_FG], x0, fm->texty0, fm->textw, ent->name, len0);
if (i > 0 && ent->name[i] != '\0')
drawtext(draw, &dc.normal[COLOR_FG], x1, fm->texty1, fm->textw, ent->name + i, len1);
XftDrawDestroy(draw);
ent->line[0].x = x0;
ent->line[0].w = textw0;
XSetForeground(dpy, dc.gc, dc.select[COLOR_BG].pixel);
XFillRectangle(dpy, ent->pix[SEL], dc.gc, x0, fm->texty0, textw0, dc.fonth);
draw = XftDrawCreate(dpy, ent->pix[SEL], visual, colormap);
drawtext(draw, &dc.select[COLOR_FG], x0, fm->texty0, fm->textw, ent->name, len0);
if (i > 0 && ent->name[i] != '\0') {
XFillRectangle(dpy, ent->pix[SEL], dc.gc, x1, fm->texty1, textw1, dc.fonth);
drawtext(draw, &dc.select[COLOR_FG], x1, fm->texty1, fm->textw, ent->name + i, len1);
}
ent->line[1].x = x1;
ent->line[1].w = textw1;
XftDrawDestroy(draw);
ent->drawn = 1;
}
/* draw entries on main window */
static void
drawentries(struct FM *fm)
{
int i, n;
XSetForeground(dpy, dc.gc, dc.normal[COLOR_BG].pixel);
XFillRectangle(dpy, fm->main, dc.gc, 0, 0, fm->winw, fm->nrow * fm->entryh);
n = min(fm->nentries, fm->row * fm->ncol + fm->nrow * fm->ncol);
for (i = fm->row * fm->ncol; i < n; i++) {
if (!fm->entries[i]->drawn)
drawentry(fm, fm->entries[i]);
copyentry(fm, i);
}
commitdraw(fm);
}
/* fork process that get thumbnail */
static int
forkthumb(const char *name)
{
pid_t pid;
int fd[2];
char path[PATH_MAX];
snprintf(path, sizeof(path), "./%s", name);
epipe(fd);
if ((pid = efork()) > 0) { /* parent */
close(fd[1]);
return fd[0];
} else { /* children */
close(fd[0]);
if (fd[1] != STDOUT_FILENO)
edup2(fd[1], STDOUT_FILENO);
eexec(config.thumbnailer, path);
}
return -1;
}
/* read image path from file descriptor and open image; return its size on *w and *h */
static Imlib_Image
openimg(int fd, int *w, int *h)
{
FILE *fp;
int len;
char path[PATH_MAX];
if ((fp = fdopen(fd, "r")) == NULL) {
warn("fdopen");
return NULL;
}
if (fgets(path, sizeof(path), fp) == NULL) {
fclose(fp);
return NULL;
}
fclose(fp);
len = strlen(path);
if (path[len - 1] == '\n')
path[len - 1] = '\0';
return loadimg(path, config.thumbsize_pixels, w, h);
}
/* scroll list by manipulating scroll bar with pointer; return 1 if fm->row changes */
static int
scroll(struct FM *fm, int y)
{
int prevrow;
int half;
prevrow = fm->row;
half = fm->scrollh / 2;
y = max(half, min(y, fm->winh - half));
y -= half;
fm->row = y * fm->maxrow / fm->winh;
fm->ydiff = (y - fm->row * fm->winh / fm->maxrow) * fm->entryh / fm->scrollh;
if (fm->row >= fm->maxrow - 1) {
fm->row = fm->maxrow - 1;
fm->ydiff = 0;
}
return prevrow != fm->row;
}
/* grab pointer and handle scrollbar dragging with the left mouse button */
static void
grabscroll(struct FM *fm, int y)
{
XEvent ev;
int dy;
if (grabpointer(fm, Button1MotionMask) == -1)
return;
dy = between(y, fm->scrolly, fm->scrolly + fm->scrollh) ? fm->scrolly + fm->scrollh / 2 - y : 0;
if (scroll(fm, y + dy))
drawentries(fm);
commitdraw(fm);
while (!XMaskEvent(dpy, ButtonReleaseMask | Button1MotionMask | ExposureMask, &ev)) {
switch (ev.type) {
case Expose:
if (ev.xexpose.count == 0)
commitdraw(fm);
break;
case MotionNotify:
if (scroll(fm, ev.xbutton.y + dy))
drawentries(fm);
commitdraw(fm);
break;
case ButtonRelease:
ungrab();
return;
}
}
}
/* mark or unmark entry as selected */
static void
selectentry(struct FM *fm, struct Entry *ent, int select)
{
if ((ent->issel != 0) == (select != 0))
return;
if (select) {
ent->snext = fm->selected;
ent->sprev = NULL;
if (fm->selected)
fm->selected->sprev = ent;
fm->selected = ent;
} else {
if (ent->snext)
ent->snext->sprev = ent->sprev;
if (ent->sprev)
ent->sprev->snext = ent->snext;
else if (fm->selected == ent)
fm->selected = ent->snext;
ent->sprev = ent->snext = NULL;
}
ent->issel = select;
}
/* mark or unmark entry as selected */
static void
selectentries(struct FM *fm, int a, int b, int select)
{
int min;
int max;
int i;
if (a == -1 || b == -1)
return;
if (a < b) {
min = a;
max = b;
} else {
min = b;
max = a;
}
for (i = min; i >= 0 && i <= max; i++) {
selectentry(fm, fm->entries[i], select);
}
}
/* change directory, reset fd of thumbnailer and index of entry whose thumbnail is being read */
static void
diropen(struct FM *fm, const char *path, int *fd, int *thumbi, int savecwd)
{
while (fm->selected)
selectentry(fm, fm->selected, 0);
if (path == NULL || wchdir(path) != -1) {
if (*thumbi != -1 && *fd != -1) { /* close current thumbnailer fd and wait for it */
close(*fd);
wait(NULL);
*thumbi = -1;
}
listentries(fm, savecwd);
calcsize(fm, -1, -1);
fm->row = 0;
fm->ydiff = 0;
*thumbi = 0;
*fd = forkthumb(fm->entries[*thumbi]->name);
}
}
/* open file using config.opener */
static void
fileopen(struct Entry *ent)
{
pid_t pid1, pid2;
int fd;
char path[PATH_MAX];
snprintf(path, sizeof(path), "./%s", ent->name);
if ((pid1 = efork()) == 0) {
if ((pid2 = efork()) == 0) {
close(STDOUT_FILENO);
fd = open(DEV_NULL, O_RDWR);
edup2(STDOUT_FILENO, fd);
eexec(config.opener, path);
}
exit(0);
}
waitpid(pid1, NULL, 0);
}
/* go back (< 0) in cwd history; return nonzero when changing directory */
static int
navhistory(struct FM *fm, int *fd, int *thumbi, int dir)
{
struct Histent *h;
h = (dir == BACK) ? fm->curr->prev : fm->curr->next;
if (h == NULL)
return 0;
diropen(fm, h->cwd, fd, thumbi, 0);
fm->curr = h;
return 1;
}
/* process X11 and poll events */
static void
runevent(struct FM *fm, struct pollfd pfd[], int *thumbi)
{
static int lastent = -1; /* index of last clicked entry; -1 if none */
static Time lasttime = 0;
struct Entry *ent;
XEvent ev;
Imlib_Image img;
int setlastent;
int i;
char path[PATH_MAX];
if (pfd[POLL_STDIN].revents & POLLHUP)
return;
if (pfd[POLL_STDIN].revents & POLLIN) {
// TODO;
}
if (pfd[POLL_THUMB].revents & POLLIN) {
ent = fm->entries[*thumbi];
img = openimg(pfd[POLL_THUMB].fd, &ent->thumb.w, &ent->thumb.h);
close(pfd[POLL_THUMB].fd);
wait(NULL);
if (img != NULL) {
drawthumb(fm, img, &ent->thumb, ent->pix);
copyentry(fm, *thumbi);
if (*thumbi >= fm->row * fm->ncol && *thumbi < fm->row * fm->ncol + fm->nrow * fm->ncol) {
commitdraw(fm);
}
}
if (*thumbi != -1 && ++(*thumbi) < fm->nentries) {
pfd[POLL_THUMB].fd = forkthumb(fm->entries[*thumbi]->name);
} else {
pfd[POLL_THUMB].fd = -1;
*thumbi = -1;
}
}
while (XPending(dpy) && !XNextEvent(dpy, &ev)) {
setlastent = 1;
if (ev.type == ClientMessage && (Atom)ev.xclient.data.l[0] == atoms[WM_DELETE_WINDOW]) {
/* file manager window was closed */
running = 0;
break;
} else if (ev.type == Expose && ev.xexpose.count == 0) {
/* window was exposed; redraw its content */
commitdraw(fm);
} else if (ev.type == ConfigureNotify) {
/* file manager window was (possibly) resized */
calcsize(fm, ev.xconfigure.width, ev.xconfigure.height);
if (fm->row >= fm->maxrow)
fm->row = fm->maxrow - 1;
drawentries(fm);
commitdraw(fm);
} else if (ev.type == ButtonPress && (ev.xbutton.button == Button4 || ev.xbutton.button == Button5)) {
/* mouse wheel was scrolled */
if (scroll(fm, fm->scrolly + fm->scrollh / 2 + (ev.xbutton.button == Button4 ? -5 : +5)))
drawentries(fm);
commitdraw(fm);
} else if (ev.type == ButtonPress && (ev.xbutton.button == BUTTON8 || ev.xbutton.button == BUTTON9)) {
/* navigate through history with mouse back/forth buttons */
if (navhistory(fm, &pfd[POLL_THUMB].fd, thumbi, (ev.xbutton.button == BUTTON8) ? BACK : FORTH)) {
drawentries(fm);
commitdraw(fm);
}
} else if (ev.type == ButtonPress && ev.xbutton.button == Button1 && ev.xbutton.x > fm->winw) {
/* scrollbar was manipulated */
grabscroll(fm, ev.xbutton.y);
} else if (ev.type == ButtonPress && ev.xbutton.button == Button1) {
/* mouse left button was pressed */
if (!(ev.xbutton.state & (ControlMask | ShiftMask)))
while (fm->selected)
selectentry(fm, fm->selected, 0);
i = getentry(fm, ev.xbutton.x, ev.xbutton.y);
if (ev.xbutton.state & ShiftMask)
selectentries(fm, i, lastent, 1);
else if (i != -1)
selectentry(fm, fm->entries[i], (ev.xbutton.state & ControlMask) ? !fm->entries[i]->issel : 1);
if (!(ev.xbutton.state & (ControlMask | ShiftMask)) && i != -1 &&
i == lastent && ev.xbutton.time - lasttime <= DOUBLECLICK) {
ent = fm->entries[i];
if (ent->isdir) {
snprintf(path, sizeof(path), "./%s", ent->name);
diropen(fm, path, &pfd[POLL_THUMB].fd, thumbi, 1);
setlastent = 0;
} else {
fileopen(ent);
}
}
drawentries(fm);
commitdraw(fm);
lastent = (setlastent) ? i : -1;
lasttime = ev.xbutton.time;
}
}
}
/* clean up drawing context */
static void
cleandc(void)
{
size_t i;
XftColorFree(dpy, visual, colormap, &dc.normal[COLOR_BG]);
XftColorFree(dpy, visual, colormap, &dc.normal[COLOR_FG]);
XftColorFree(dpy, visual, colormap, &dc.select[COLOR_BG]);
XftColorFree(dpy, visual, colormap, &dc.select[COLOR_FG]);
XftColorFree(dpy, visual, colormap, &dc.scroll[COLOR_BG]);
XftColorFree(dpy, visual, colormap, &dc.scroll[COLOR_FG]);
XFreeGC(dpy, dc.gc);
for (i = 0; i < dc.nfonts; i++)
XftFontClose(dpy, dc.fonts[i]);
free(dc.fonts);
}
/* xfiles: X11 file manager */
int
main(int argc, char *argv[])
{
struct pollfd pfd[POLL_LAST];
struct FM fm;
int thumbi = -1; /* index of current thumbnail, -1 if no thumbnail is being read */
char *path;
char *xrm;
if (!setlocale(LC_CTYPE, "") || !XSupportsLocale())
warnx("warning: no locale support");
if ((dpy = XOpenDisplay(NULL)) == NULL)
errx(1, "could not open display");
screen = DefaultScreen(dpy);
visual = DefaultVisual(dpy, screen);
depth = DefaultDepth(dpy, screen);
root = RootWindow(dpy, screen);
colormap = DefaultColormap(dpy, screen);
XrmInitialize();
if ((xrm = XResourceManagerString(dpy)) != NULL && (xdb = XrmGetStringDatabase(xrm)) != NULL)
parseresources();
parseenviron();
path = parseoptions(argc, argv);
imlib_set_cache_size(2048 * 1024);
imlib_context_set_dither(1);
imlib_context_set_display(dpy);
imlib_context_set_visual(visual);
imlib_context_set_colormap(colormap);
initsignal(SIGCHLD, SIG_IGN);
initatoms();
initdc();
initfm(&fm, argc, argv);
initellipsis();
memset(pfd, 0, sizeof pfd);
pfd[POLL_STDIN].fd = STDIN_FILENO;
pfd[POLL_X11].fd = XConnectionNumber(dpy);
pfd[POLL_THUMB].fd = -1;
pfd[POLL_STDIN].events = pfd[POLL_X11].events = pfd[POLL_THUMB].events = POLLIN;
esetcloexec(pfd[POLL_X11].fd);
diropen(&fm, path, &pfd[POLL_THUMB].fd, &thumbi, 1);
drawentries(&fm);
XMapWindow(dpy, fm.win);
while (running && (XPending(dpy) || poll(pfd, POLL_LAST, -1) != -1))
runevent(&fm, pfd, &thumbi);
cleandc();
XCloseDisplay(dpy);
return 0;
}
</code></pre>
<p><code>xfiles.h</code>:</p>
<pre><code>#define ELLIPSIS "…"
#define CLASS "XFiles"
#define TITLE "XFiles"
#define THUMBBORDER 3 /* thumbnail border (for highlighting) */
#define DOUBLECLICK 250
#define DEV_NULL "/dev/null"
#define DOTDOT ".."
/* poll entries */
enum {
POLL_STDIN,
POLL_X11,
POLL_THUMB,
POLL_LAST,
};
/* fg and bg colors */
enum {
COLOR_FG,
COLOR_BG,
COLOR_LAST
};
/* atoms */
enum {
UTF8_STRING,
WM_DELETE_WINDOW,
_NET_WM_NAME,
_NET_WM_PID,
_NET_WM_WINDOW_TYPE,
_NET_WM_WINDOW_TYPE_NORMAL,
ATOM_LAST,
};
/* unselected and selected pixmaps */
enum {
UNSEL = 0,
SEL = 1,
PIX_LAST = 2,
};
/* history navigation direction */
enum {
BACK,
FORTH,
};
/* extra mouse buttons, not covered by XLIB */
enum {
BUTTON8 = 8,
BUTTON9 = 9,
};
/* working directory history entry */
struct Histent {
struct Histent *prev, *next;
char *cwd;
};
/* position and size of a rectangle */
struct Rect {
int x, y, w, h;
};
/* horizontal position and size of a line segment */
struct Line {
int x, w;
};
/* file manager */
struct FM {
struct Entry **entries; /* array of pointer to entries */
struct Entry *selected; /* list of selected entries */
struct Rect dirrect; /* size and position of default thumbnail for directories */
struct Rect filerect; /* size and position of default thumbnail for files */
struct Histent *hist; /* cwd history; pointer to last cwd history entry */
struct Histent *curr; /* current point in history */
Window win; /* main window */
Pixmap main, scroll; /* pixmap for main window and scroll bar */
Pixmap dir[PIX_LAST]; /* default pixmap for directories thumbnails */
Pixmap file[PIX_LAST]; /* default pixmap for file thumbnails */
int capacity; /* capacity of entries */
int nentries; /* number of entries */
int row; /* index of first visible column */
int ydiff; /* how much the icons are scrolled up */
int winw, winh; /* size of main window */
int thumbx, thumby; /* position of thumbnail from entry top left corner */
int x0; /* position of first entry */
int entryw, entryh; /* size of each entry */
int scrollh, scrolly; /* size and position of scroll bar handle */
int textw; /* width of each file name */
int textx; /* position of each name from entry top left corner */
int texty0, texty1; /* position of each line from entry top left corner */
int ncol, nrow; /* number of columns and rows visible at a time */
int maxrow; /* maximum value fm->row can scroll */
};
/* directory entry */
struct Entry {
struct Entry *sprev; /* for the linked list of selected entries */
struct Entry *snext; /* for the linked list of selected entries */
struct Rect thumb; /* position and size of the thumbnail */
struct Line line[2]; /* position and size of both text lines */
Pixmap pix[PIX_LAST]; /* unselected and selected content of the widget */
int issel; /* whether entry is selected */
int isdir; /* whether entry is a directory */
int drawn; /* whether unsel and sel pixmaps were drawn */
char *name; /* file name */
};
/* draw context */
struct DC {
GC gc;
XftColor normal[COLOR_LAST];
XftColor select[COLOR_LAST];
XftColor scroll[COLOR_LAST];
FcPattern *pattern;
XftFont **fonts;
size_t nfonts;
int fonth;
};
/* configuration */
struct Config {
const char *thumbnailer;
const char *opener;
const char *dirthumb_path;
const char *filethumb_path;
const char *font;
const char *background_color;
const char *foreground_color;
const char *selbackground_color;
const char *selforeground_color;
const char *scrollbackground_color;
const char *scrollforeground_color;
int thumbsize_pixels; /* size of icons and thumbnails */
int scroll_pixels; /* scroll bar width */
int width_pixels; /* initial window width */
int height_pixels; /* initial window height */
int hide; /* whether to hide .* entries */
};
/* ellipsis size and font structure */
struct Ellipsis {
char *s;
size_t len; /* length of s */
int width; /* size of ellipsis string */
XftFont *font; /* font containing ellipsis */
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T14:54:27.817",
"Id": "524907",
"Score": "0",
"body": "Why did you choose to write a program using Xlib, when X11 (while still perfectly usable IMO), is planned to be phased out in favor of Wayland? Why not use a widget toolkit that avoids depending on any underlying display protocol?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T15:03:33.437",
"Id": "524909",
"Score": "0",
"body": "@G.Sliepen I use OpenBSD, which has no Wayland support, so X11 is the only way to go. On not using a toolkit, I am used to xlib; I have even written other utilities in xlib, such as a window manager, so I have more familiarity with xlib than with any toolkit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T15:05:57.703",
"Id": "524910",
"Score": "0",
"body": "Fair enough, but just know that it will limit (future) portability."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T23:24:54.327",
"Id": "265712",
"Score": "3",
"Tags": [
"c",
"x11"
],
"Title": "X11 file manager in C, using Xlib and imlib2"
}
|
265712
|
<p>This is a simple implementation of the calendar(1) utility included in some UNIX systems (all BSDs have it, GNU has not).</p>
<p>Here's the 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 the named files for events, one event per line; and
write 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, calendar reads
from the standard input. If no file is provided as argument, calendar
reads the file named calendar on the current directory or on the
directory specified by the CALENDAR_DIR environment variable.
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 -d
and -A7 on this input would print the following:
Sunday 09 May 09
Mother's day
Monday 10 May 10
Java Class
Tuesday 11 May 11
Algebra Class
Computer Network Class
Operating Systems Class
Wednesday 12 May 12
Java Class
Thursday 13 May 13
Algebra Class
Computer Network Class
Operating Systems Class
SEE ALSO
at(1), cal(1), cron(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: if the argument is a hyphen (-), events
are read from the standard input.
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>Here's the code. It is actually a shell script that only calls awk.</p>
<pre><code>#!/bin/sh
exec awk '
# show usage and exit
function usage() {
print "usage: calendar [-d] [-A num] [-B num] -t [yyyymmdd] [file ...]" >"/dev/stderr"
error = 1
exit 1
}
# show error and exit
function err(s) {
printf "calendar: %s\n", s >"/dev/stderr"
error = 1
exit 1
}
# thanks https://github.com/e36freak
function getopts(optstring, longarr, opt, trimmed, hasarg, repeat) {
hasarg = repeat = 0
optarg = ""
optind++
# return -1 if the current arg is not an option or there are no args left
if (ARGV[optind] !~ /^-/ || optind >= ARGC) {
return -1
}
# if option is "--" (end of options), delete arg and return -1
if (ARGV[optind] == "--") {
for (i=1; i<=optind; i++) {
delete ARGV[i]
}
return -1
}
# remove the hyphen, and get just the option letter
opt = substr(ARGV[optind], 2, 1)
# set trimmed to whatevers left
trimmed = substr(ARGV[optind], 3)
# invalid option
if (!index(optstring, opt)) {
printf("invalid option -- '%s'\n", opt) > "/dev/stderr"
return "?"
}
# if there is more to the argument than just -o
if (length(trimmed)) {
# if option requires an argument, set the rest to optarg and hasarg to 1
if (index(optstring, opt ":")) {
optarg = trimmed
hasarg = 1
# otherwise, prepend a hyphen to the rest and set repeat to 1, so the
# same arg is processed again without the first option
} else {
ARGV[optind] = "-" trimmed
repeat = 1
}
}
# set optname by prepending a hypen to opt
optname = "-" opt
# if the option requires an arg and hasarg is 0
if (index(optstring, opt ":") && !hasarg) {
# increment optind, check if no arguments are left
if (++optind >= ARGC) {
printf("option requires an argument -- '%s'\n", optname) > "/dev/stderr"
return "?"
}
# set optarg
optarg = ARGV[optind]
# if repeat is set, decrement optind so we process the same arg again
# mutually exclusive to needing an argument, otherwise hasarg would be set
} else if (repeat) {
optind--
}
# delete all arguments up to this point, just to make sure
for (i=1; i<=optind; i++) {
delete ARGV[i]
}
# return the option letter
return opt
}
# increment date 1 day
function incdate() {
if (++day > daysinmonth[isleap(year), month]) {
day = 1
if (++month > 12) {
month = 1
year++
}
}
wday = (wday + 1) % NDAYS
if (wday == 0) {
wday = NDAYS
}
}
# check if year is leap year
function isleap(y) {
return (!(y % 4) && (y % 100) || !(y % 400))
}
# get date pattern
function getpattern( i, s, t, y, m, d, p, n, u) {
# y = year
# m = month
# d = month day
# p = (positive) week number from beginning of month
# n = (negative) week number from end of month
# u = week day (1 = monday to 7 = sunday)
s = $0
if (npatt++ > 0) { # remove leading comma
if (match(s, /^,[ \t]*/)) {
s = substr(s, RLENGTH + 1)
} else {
return ""
}
}
y = m = d = p = n = u = 0
if (match(s, /^[0-9]+[\/.-]/)) { # check numeric month and year
m = substr(s, 1, RLENGTH - 1)
if (m == 0)
return ""
s = substr(s, RLENGTH + 1)
if (match(s, /^[0-9]+[\/.-]/)) {
y = m
m = substr(s, 1, RLENGTH - 1)
if (m == 0)
return ""
s = substr(s, RLENGTH + 1)
}
}
if (m == 0) { # check month name
match(s, /^[A-Za-z]+/)
t = tolower(substr(s, 1, 3))
for (i = 1; i <= NMONTHS; i++) {
if (t == months[i]) {
if (substr(s, RLENGTH + 1) !~ /[\/.-]/)
return ""
m = i
s = substr(s, RLENGTH + 2)
break
}
}
}
if (match(s, /^[0-9]+/)) { # check numeric month day
d = substr(s, 1, RLENGTH)
s = substr(s, RLENGTH + 1)
}
if (match(s, /^[A-Za-z]+/)) { # check week day name
t = tolower(substr(s, 1, 3))
for (i = 1; i <= NDAYS; i++) {
if (t == days[i]) {
u = i
s = substr(s, RLENGTH + 1)
break
}
}
}
if (d == 0 && u == 0)
return ""
if (match(s, /^[+][1-5]/)) { # check N week from beginning of month
p = substr(s, 2, 1)
s = substr(s, 3)
} else if (match(s, /^-[1-5]/)) { # check N week from end of month
n = substr(s, 2, 1)
s = substr(s, 3)
}
sub(/^[\t ]+/, "", s)
$0 = s
y = (y == 0) ? y = ".*" : sprintf("%d", y)
m = (m == 0) ? m = ".." : sprintf("%02d", m)
d = (d == 0) ? d = ".." : sprintf("%02d", d)
p = (p == 0) ? p = "." : p
n = (n == 0) ? n = "." : n
u = (u == 0) ? u = "." : u
return sprintf("%s-%s-%s-%s-%s-%s", y, m, d, p, n, u)
}
# get week of the month for given date
function getwofm(y, m, d) {
return strftime("%W", mktime(y " " m " " d " 12 00 00")) - strftime("%W", mktime(y " " m " 1 12 00 00")) + 1
}
# get date string (in format y-m-d-p-n-u) for current date
function getdate( last, p, n) {
last = getwofm(year, month, daysinmonth[isleap(year), month])
p = getwofm(year, month, day)
n = -1 * (p - last - 1)
return sprintf("%d-%02d-%02d-%1d-%1d-%1d", year, month, day, p, n, wday)
}
BEGIN {
CALENDARFILE="calendar"
SECSPERDAY = 24 * 60 * 60
daysinmonth[0, 1] = daysinmonth[1, 1] = 31
daysinmonth[0, 2] = 28
daysinmonth[1, 2] = 29
daysinmonth[0, 3] = daysinmonth[1, 3] = 31
daysinmonth[0, 4] = daysinmonth[1, 4] = 30
daysinmonth[0, 5] = daysinmonth[1, 5] = 31
daysinmonth[0, 6] = daysinmonth[1, 6] = 30
daysinmonth[0, 7] = daysinmonth[1, 7] = 31
daysinmonth[0, 8] = daysinmonth[1, 8] = 31
daysinmonth[0, 9] = daysinmonth[1, 9] = 30
daysinmonth[0, 10] = daysinmonth[1, 10] = 31
daysinmonth[0, 11] = daysinmonth[1, 11] = 30
daysinmonth[0, 12] = daysinmonth[1, 12] = 31
NMONTHS = 12
months[1] = "jan"
months[2] = "feb"
months[3] = "mar"
months[4] = "apr"
months[5] = "may"
months[6] = "jun"
months[7] = "jul"
months[8] = "aug"
months[9] = "sep"
months[10] = "oct"
months[11] = "nov"
months[12] = "dec"
outmonths[1] = "January"
outmonths[2] = "February"
outmonths[3] = "March"
outmonths[4] = "April"
outmonths[5] = "May"
outmonths[6] = "June"
outmonths[7] = "July"
outmonths[8] = "August"
outmonths[9] = "September"
outmonths[10] = "October"
outmonths[11] = "November"
outmonths[12] = "December"
NDAYS = 7
days[1] = "mon"
days[2] = "tue"
days[3] = "wed"
days[4] = "thu"
days[5] = "fri"
days[6] = "sat"
days[7] = "sun"
outdays[1] = "Monday"
outdays[2] = "Tuesday"
outdays[3] = "Wednesday"
outdays[4] = "Thursday"
outdays[5] = "Friday"
outdays[6] = "Saturday"
outdays[7] = "Sunday"
time = systime();
year = strftime("%Y", time) + 0
month = strftime("%m", time) + 0
day = strftime("%d", time) + 0
time = mktime(year " " month " " day " 12 00 00")
while ((c = getopts("A:B:lt:")) != -1) {
if (c == "A") {
after = optarg + 0
} else if (c == "B") {
before = optarg + 0
} else if (c == "l") {
printdate = 1
} else if (c == "t") {
today = optarg + 0
} else {
usage()
}
}
len = length(today)
if (today ~ /^..$/) {
time = mktime(year " " month " " today " 12 00 00")
} else if (today ~ /^....$/) {
s = substr(today, 1, 2) " " substr(today, 3, 2)
time = mktime(year " " s " 12 00 00")
} else if (today ~ /^.*....$/) {
s = substr(today, 1, len - 4) " " substr(today, len - 3, 2) " " substr(today, len - 1, 2)
time = mktime(s " 12 00 00")
}
if (time < 0) {
err("invalid time")
}
time -= before * SECSPERDAY
year = strftime("%Y", time) + 0
month = strftime("%m", time) + 0
day = strftime("%d", time) + 0
wday = strftime("%u", time) + 0
if (!after) {
if (wday == 5) {
after = 3
} else if (wday == 6) {
after = 2
} else {
after = 1
}
}
if (optind == ARGC) { # no argument provided, read default calendar file
CALENDARDIR = ENVIRON["CALENDAR_DIR"]
if (system("test -r " CALENDARFILE) != 0 && CALENDARDIR) {
CALENDARFILE = CALENDARDIR "/" CALENDARFILE
}
ARGV[ARGC++] = CALENDARFILE
}
}
{
patt = ""
npatt = 0
while ((s = getpattern()))
patt = patt (patt ? "|" : "") s
if (patt) {
nevents++
events[nevents, "patt"] = patt
events[nevents, "name"] = $0
}
}
END {
if (error)
exit error
for (i = 0; i <= after; i++) {
date = getdate()
if (printdate)
outdate = sprintf("%-9s %02d %s %02d", outdays[wday], day, outmonths[month], day)
else
outdate = sprintf("%s %02d ", substr(outmonths[month], 1, 3), day)
if (printdate)
print outdate
for (j = 1; j <= nevents; j++) {
if (date ~ events[j, "patt"]) {
print (printdate ? "\t" : outdate) events[j, "name"]
}
}
incdate()
}
}
' "$@"
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T02:42:18.870",
"Id": "524865",
"Score": "0",
"body": "might be an issue on some platforms. Here's the error on OSX `awk: calling undefined function systime\n source line number 261`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T10:44:03.197",
"Id": "524885",
"Score": "0",
"body": "@MrR you need GNU awk."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T23:53:27.940",
"Id": "524934",
"Score": "0",
"body": "Perhaps use [this tip](https://unix.stackexchange.com/a/236666) for detecting whether you have suitable awk?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T00:02:49.210",
"Id": "524935",
"Score": "0",
"body": "Thanks for the tip. Btw, I tested my code in GNU awk and OpenBSD awk. Works in both."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-04T23:28:27.870",
"Id": "265713",
"Score": "0",
"Tags": [
"awk"
],
"Title": "UNIX calendar(1) in awk"
}
|
265713
|
<p>Continuing the code for combinatorics library, adding the definition of ⁿPᵣ. This is an extract from a <a href="https://github.com/suryasis-hub/MathLibrary" rel="nofollow noreferrer">larger codebase</a>.</p>
<ol>
<li>Is there any way to limit the code of <code>gcd()</code> to this file? Should I convert the namespace <code>Combinatorics</code> to a class?</li>
<li>Any other advice you would want to give me?</li>
</ol>
<p><strong>Code</strong></p>
<pre><code>// MathLibrary.cpp : Defines the functions for the static library.
//
#include "pch.h"
#include "framework.h"
#include <vector>
#include <iostream>
#include <limits>
#include <cstddef>
namespace Combinatorics
{
const std::vector<unsigned long long> representableFactors = {1,1,2,6,24,120,720,5040,40320,362880,3628800,39916800,
479001600,6227020800,87178291200,1307674368000,20922789888000,355687428096000,6402373705728000,121645100408832000,2432902008176640000};
unsigned long long factorial(unsigned int n)
{
if (n >= representableFactors.size())
{
throw std::invalid_argument("Combinatorics:factorial - The argument is too large");
}
return representableFactors[n];
}
inline long long gcd(long long a, long long b)
{
if (a % b == 0)
{
return b;
}
return gcd(b, (a % b));
}
long long combinations(int n, int r)
{
if (n < 0 || r < 0)
{
throw std::invalid_argument("Combinatorics::combinations - N and R cannot be less than 0");
}
if (n < r)
{
throw std::invalid_argument("Combinatorics::combinations - The value of r cannot be greater than n");
}
if (n - r < r)
{
r = n - r;
}
long long int denominatorProduct = 1;
long long int numeratorProduct = 1;
for (long long int denomCount = r, numCount = n ; denomCount >= 1; denomCount--, numCount--)
{
//TODO : Convert to limits
if((LLONG_MAX / n) < numeratorProduct || (LLONG_MAX / n) < denominatorProduct)
{
throw std::invalid_argument("Combinatorics::combinations - Overflow detected aborting");
}
denominatorProduct *= denomCount;
numeratorProduct *= numCount;
long long gcdCommonFactor = gcd(denominatorProduct, numeratorProduct);
denominatorProduct /= gcdCommonFactor;
numeratorProduct /= gcdCommonFactor;
}
return (numeratorProduct / denominatorProduct);
}
//Code to be reviewed.
long long permutations(int n, int r)
{
if (n < 0 || r < 0)
{
throw std::invalid_argument("Combinatorics::permutations - N and R cannot be less than 0");
}
if (n < r)
{
throw std::invalid_argument("Combinatorics::permutations - The value of r cannot be greater than n");
}
long long permutations = 1;
for (long long int numeratorCount = n; numeratorCount >= (n - r + 1); numeratorCount--)
{
//TODO: Convert to limits
if ((LLONG_MAX / n) < permutations)
{
throw std::invalid_argument("Combinatorics::permutations - Overflow detected aborting");
}
permutations *= numeratorCount;
}
return permutations;
}
}
</code></pre>
<p><strong>Test code</strong></p>
<pre><code>#include "pch.h"
#include <iostream>
#include "../MathLibrary/MathLibrary.cpp"
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);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T06:08:33.040",
"Id": "524870",
"Score": "1",
"body": "As a general note unless you are sure that all your users understand what an overflow is you might want to replace that with an more actionable error message."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T14:09:39.977",
"Id": "524900",
"Score": "0",
"body": "To make your helper function visible inside that source file only, use an anonymous namespace. An older technique (which only works for functions and variables) is to use the `static` storage class."
}
] |
[
{
"body": "<p>Unnecessary includes:</p>\n<blockquote>\n<pre><code>#include "pch.h" // in both files\n#include "framework.h"\n#include <iostream> // in both files\n#include <limits>\n</code></pre>\n</blockquote>\n<p>Missing includes:</p>\n<pre><code>// in implementation\n#include <climits>\n#include <stdexcept>\n\n// in tests\n#include <gtest/gtest.h>\n</code></pre>\n<hr />\n<p>There is no need to call <code>gcd()</code> in the implementation of <code>combinations()</code>, or to keep separate track of denominator. Consider the expansion of ⁿCᵣ:</p>\n<p><span class=\"math-container\">\\$ ^nC_r = \\frac{(r+1) ✕ (r+2) ✕ (r+3) ✕ ... ✕ n}{1✕2✕3✕...✕(n-r)} \\$</span></p>\n<p>At any time, consider the partial result formed by taking <em>i</em> terms from each of the numerator and denominator. The denominator part is obviously just <em>i</em>!; we can show that the numerator part must be an exact multiple of <em>i</em>! because it must contain at least one multiple of each of 0,...,<em>i</em>.</p>\n<p>So if we change our loop to count upwards in the denominator, we can show that we always end up with a denominator of 1 (see the <code>assert()</code>):</p>\n<pre><code>for (long long int denomCount = 1, numCount = n ; denomCount <= r; ++denomCount, --numCount)\n{\n //TODO : Convert to limits\n if((LLONG_MAX / n) < numeratorProduct || (LLONG_MAX / n) < denominatorProduct)\n {\n throw std::invalid_argument("Combinatorics::combinations - Overflow detected aborting");\n }\n denominatorProduct *= denomCount;\n numeratorProduct *= numCount;\n long long gcdCommonFactor = gcd(denominatorProduct, numeratorProduct);\n denominatorProduct /= gcdCommonFactor;\n numeratorProduct /= gcdCommonFactor;\n assert(denominatorProduct == 1);\n}\n</code></pre>\n<p>That observation allows us to remove <code>denominatorProduct</code> altogether:</p>\n<pre><code>long long int product = 1;\nfor (long long int denomCount = 1, numCount = n; denomCount <= r; ++denomCount, --numCount)\n{\n if (LLONG_MAX / n < product)\n {\n throw std::range_error("Combinatorics::permutations - overflow detected");\n }\n product *= numCount;\n product /= denomCount;\n}\nreturn product;\n</code></pre>\n<hr />\n<p>Counting down in <code>permutations()</code> means that this test might catch some false-positives:</p>\n<blockquote>\n<pre><code> for (long long int numeratorCount = n; numeratorCount >= (n - r + 1); numeratorCount--)\n {\n //TODO: Convert to limits\n if ((LLONG_MAX / n) < permutations)\n</code></pre>\n</blockquote>\n<p>If we count upwards, then the final multiplication is by <code>n</code>, and the test is exact.</p>\n<p>The same problem is present in <code>combinations()</code>.</p>\n<hr />\n<p>Since the combinatoric functions are undefined for negative values, we should be throwing <code>std::domain_error</code> to represent that, or simply accept unsigned types (enable your compiler's "signed conversion" warnings to avoid problems with implicit conversions).</p>\n<p>And we should return an unsigned type too, giving us a little extra range to represent the larger values.</p>\n<hr />\n<p>To answer your specific question, the way to make <code>gcd()</code> internal to the translation unit is to declare it in the anonymous namespace (in the implementation file, not in a header!) or to use the old C-style <code>static</code> keyword.</p>\n<p>But we should be using <code>std::gcd()</code> instead of reinventing that wheel. (If we had to reimplement it, I'd prefer to see it written iteratively rather than recursively, since many C++ compilers don't eliminate tail-calls).</p>\n<hr />\n<p>It's probably simpler to use a <code>std::array</code> for the table of factorials, and that should be a local <code>static</code> constant within the <code>factorial()</code> function - it doesn't need to be visible anywhere else. I'm not convinced that a table is a good idea - it inhibits changing this to a template function (which might support larger result types).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T14:17:39.120",
"Id": "524901",
"Score": "0",
"body": "ES.106 is just a brief summary. There have been entire conference talks on this, and discussions hashing out best practice long before StackOverflow or the WWW even existed. I'm **very leery** of giving advice here that directly contradicts the best practice. The fact that signed and unsigned types have different semantics has been greatly amplified in more recent years, with the optimizer taking advantage of it. Again, there are entire conference talks exhibiting how signed types generate faster code!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T07:37:28.473",
"Id": "265719",
"ParentId": "265717",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T03:54:32.360",
"Id": "265717",
"Score": "3",
"Tags": [
"c++",
"beginner",
"mathematics",
"library"
],
"Title": "Permutation function for a math library in C++"
}
|
265717
|
<p>I have applied a DFS solution for to check finding path if exist from beginning point to the end point.</p>
<blockquote>
<p>OA: Given 2d array, check if there is path from one beginning point to given endpoint in the matrix</p>
</blockquote>
<pre><code>public class StartToEnd {
// OA: Given a 2d matrix with chars and a target string.
// Check if the matrix contains this target string
// by only going right or down each time from the beginning point.
public static void main(String[] argv) {
int[][] matricesThree ={
{ 0, 0, 0, 1, 0},
{ 1, 0, 1, 1, 1},
{ 0, 0, 0, 1, 0},
{ 1, 0, 0, 0, 0},
{ 0, 0, 1, 0, 0}};
int[][] matrixNo = {{0, 0, 0, -1, 0},
{-1, 0, 0, -1, -1},
{0, 0, 0, -1, 0},
{-1, 0, -1, 0, 0},
{0, 0, -1, 0, 0}};
int[][] matrixYes = {{0, 0, 0, -1, 0},
{-1, 0, 0, -1, -1},
{ 0, 0, 0, -1, 0},
{-1, 0, 0, 0, 0},
{ 0, 0, -1, 0, 0}};
int startingRow = 0;
int startingColumn = 0;
System.out.println(hasPathDfs(matricesThree, startingRow, startingColumn, matricesThree.length-1, matricesThree[0].length-1));
System.out.println(hasPathDfs(matrixYes, startingRow, startingColumn, matrixYes.length-1, matrixYes[0].length-1));
System.out.println(hasPathDfs(matrixNo, startingRow, startingColumn, matrixNo.length-1, matrixNo[0].length-1));
}
public static boolean hasPathDfs(int[][] matrix, int row, int column, int endRow, int endColumn){
if(row == endRow && column == endColumn && matrix[endRow][endColumn] == 0) return true;
if(row <0 || column <0 || row>=matrix.length|| column>= matrix[row].length || 0 != matrix[row][column] ) return false;
int temp = matrix[row][column];
matrix[row][column] = '#';
boolean flag = hasPathDfs(matrix,row+1,column, endRow, endColumn) ||
hasPathDfs(matrix,row, column+1, endRow, endColumn) ||
hasPathDfs(matrix,row-1,column, endRow, endColumn) ||
hasPathDfs(matrix,row, column-1, endRow, endColumn) ;
matrix[row][column] = temp;
return flag;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T06:52:01.270",
"Id": "524873",
"Score": "1",
"body": "how is **beginning point** and **beginning point** defined? What does the assignment in your question have to do with the comments in your class? *OA: Given a 2d matrix with chars and a target string. Check if the matrix contains this target string by only going right or down each time from the beginning point.* ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T07:25:47.637",
"Id": "524875",
"Score": "0",
"body": "Updated a new version for adapting change in given points"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T09:48:25.857",
"Id": "528738",
"Score": "0",
"body": "What do you want to achieve? Do you want to \"check if the matrix contains this target string by only going right or down each time from the beginning point\"?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T06:43:13.947",
"Id": "265718",
"Score": "0",
"Tags": [
"java",
"matrix",
"depth-first-search"
],
"Title": "If maze has path"
}
|
265718
|
<p>These snippets are nothing special, but they remind us to sometimes loop without a <code>for</code> or a <code>while</code> loop. It is even possible to iterate over <code>struct</code> members in a similar manner.</p>
<pre><code>template <typename ...A>
constexpr auto all_loop(A&& ...a) noexcept
{
return [&](auto const f) noexcept(noexcept(
(f(std::forward<decltype(a)>(a)), ...)))
{
(f(std::forward<decltype(a)>(a)), ...);
};
}
template <typename ...A>
constexpr auto cond_loop(A&& ...a) noexcept
{
return [&](auto const f) noexcept(noexcept(
(f(std::forward<decltype(a)>(a)), ...)))
{
return (f(std::forward<decltype(a)>(a)) || ...);
};
}
</code></pre>
<p>Usage:</p>
<pre><code>all_loop(1, 2, 3, false, true, nullptr)([](auto&& v) { std::cout << v << std::endl; });
</code></pre>
<p><a href="https://wandbox.org/permlink/kFnaNn1vPoS0lF4F" rel="nofollow noreferrer">https://wandbox.org/permlink/kFnaNn1vPoS0lF4F</a></p>
|
[] |
[
{
"body": "<h1>No need to return a lambda</h1>\n<p>I don't see the need for returning a lambda which you then have to invoke. Why not pass the function as the first parameter, similar to <a href=\"https://en.cppreference.com/w/cpp/utility/apply\" rel=\"nofollow noreferrer\"><code>std::apply</code></a> and <a href=\"https://en.cppreference.com/w/cpp/utility/functional/invoke\" rel=\"nofollow noreferrer\"><code>std::invoke</code></a>? I would rewrite <code>all_loop()</code> like so:</p>\n<pre><code>template <typename F, typename ...A>\nconstexpr void invoke_all(F f, A&& ...a)\nnoexcept(noexcept((f(std::forward<decltype(a)>(a)), ...)))\n{\n (f(std::forward<decltype(a)>(a)), ...);\n}\n</code></pre>\n<p>And then you can use it like so:</p>\n<pre><code>invoke_all([](auto&& v){std::cout << v << '\\n';}, 1, 2, 3, false, true, nullptr);\n</code></pre>\n<p>If you really need to have it as a lambda, the caller can still do that themselves:</p>\n<pre><code>auto curried = [](auto const f){invoke_all(f, 1, 2, 3, false, true, nullptr);};\ncurried([](auto&& v){std::cout << v << '\\n';});\n</code></pre>\n<h1>Prefer <code>'\\n'</code> over <code>std::endl</code></h1>\n<p>Use <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, which is normally not necessary and might impact performance.</p>\n<h1>Making it "pipeable"</h1>\n<blockquote>\n<p>I wanted to achieve something like <code>pipe(1, 2, 3) | f;</code></p>\n</blockquote>\n<p>You can do that as well, by creating a type that stores the values and overloads <code>operator|</code> to take any function. For example:</p>\n<pre><code>template <typename... A>\nclass pipe\n{\n std::tuple<A...> a;\npublic:\n pipe(A&&... a): a{a...} {}\n auto operator|(auto&& f) {\n std::apply([&](auto&&... a){(f(a), ...);}, a);\n }\n};\n</code></pre>\n<p>(I left all the <code>decltype</code>s and <code>std::forward</code>s as an excercise to the reader.) Then you can indeed write:</p>\n<pre><code>pipe(1, 2, 3, false, true, nullptr) | [](auto&& v) { std::cout << v << '\\n'; };\n</code></pre>\n<p>But I would not use this, and rather stick to the idiomatic way of calling things in C++.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T14:27:05.413",
"Id": "524969",
"Score": "0",
"body": "I wanted to separate the loop \"body\" from the arguments. We usually don't think of this sort of thing as \"looping\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T14:40:45.937",
"Id": "524970",
"Score": "0",
"body": "i.e. I wanted to achieve something like `pipe(1, 2, 3) | f;`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T15:24:49.630",
"Id": "524977",
"Score": "0",
"body": "I updated the answer to show how to do that :) But this looks like you want the language to be different from what it is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T15:28:42.970",
"Id": "524980",
"Score": "0",
"body": "Pipe operator may become more idiomatic in the near future, given that it's now used to compose views in the Ranges library."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T15:31:59.873",
"Id": "524984",
"Score": "0",
"body": "Shouldn't it be `std::tuple<A&&...> a;` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T15:33:32.430",
"Id": "524985",
"Score": "0",
"body": "@TobySpeight Hm, you might be right. But I don't think the Ranges library will support containers of heterogeneous types? At least not in the near future?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T15:35:29.263",
"Id": "524986",
"Score": "1",
"body": "@user1095108 Yes, and then you also need to add the perfect forwarding. That's why I said I left it as an excercise. I think that should not be a problem, you did this correctly in your code!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T15:42:21.543",
"Id": "524987",
"Score": "1",
"body": "Oh, I wasn't claiming that! Only saying that like we got used to `<<` and `>>` not just being bit-shift but also streaming back in the 1980s, and that other libraries have followed that lead, we might start to see use of `|` as a composition operator more widely, following its use in Ranges. I'm not really advocating that in 2021, though - just musing on the way idioms can change."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T15:54:14.700",
"Id": "524989",
"Score": "1",
"body": "if `std::tuple` were more inspired, we could just do `std::forward_as_tuple(1, 2, 3) | f`."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T12:42:34.007",
"Id": "265774",
"ParentId": "265724",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T11:07:38.473",
"Id": "265724",
"Score": "2",
"Tags": [
"c++",
"c++17"
],
"Title": "looping over variables of heterogeneous type"
}
|
265724
|
<p>I'm trying to learn how to multithread with c, and thought that the <a href="https://www.geeksforgeeks.org/longest-palindromic-subsequence-dp-12/" rel="nofollow noreferrer">longest palindromic subsequence problem</a> would be a good place to start.</p>
<p>The idea is that we run two threads and compare their results to find the answer. One thread deals with "odd" subsequences, the other with "even" ones.</p>
<p>Although the code below seems to work, my question is: Could it be better in some way? E.g. reduce space complexity or time complexity while retaining the general idea?</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
struct str{
char* seq;
int len;
};
void *odd(void* arg){
struct str index = *(struct str*)arg;
int maxAns = 1;
for(int i = 1; i < index.len; i++){
int low = i - 1;
int high = i + 1;
int currMax = 1;
while(low >= 0 && high < index.len && index.seq[low] == index.seq[high]){
low--;
high++;
currMax=currMax+2;
}
if(currMax > maxAns){
maxAns = currMax;
}
}
int* res = malloc(sizeof(int));
*res = maxAns;
free(arg);
return (void*)res;
}
void *even(void* arg){
struct str index = *(struct str*)arg;
int maxAns = 0;
for(int i = 0; i < index.len; i++){
int low = i;
int high = i + 1;
int currMax = 0;
while(low >= 0 && high < index.len && index.seq[low] == index.seq[high]){
low--;
high++;
currMax=currMax+2;
}
if(currMax > maxAns){
maxAns = currMax;
}
}
int* res = malloc(sizeof(int));
*res = maxAns;
free(arg);
return (void*)res;
}
int main(void){
char seq0[] = "aaasaaasadaadsdafa";
int len = sizeof(seq0)/sizeof(seq0[0])-1;
struct str* s0 = malloc(sizeof(struct str));
struct str* s1 = malloc(sizeof(struct str));
s0->seq = (char*)seq0;
s1->seq = (char*)seq0;
s0->len = len;
s1->len = len;
pthread_t t0;
pthread_t t1;
int* res0;
int* res1;
if (pthread_create(&t0, NULL, &odd, s0)!=0){
return 0;
}
if (pthread_create(&t1, NULL, &even, s1)!=0){
return 00;
}
if(pthread_join(t0, (void**)&res0)!=0){
return 1;
}
if(pthread_join(t1, (void**)&res1)!=0){
return 11;
}
if(*res0 > *res1){
printf("%d\n", *res0);
}else{
printf("%d\n", *res1);
}
free(s0);
free(s1);
return 0;
}
</code></pre>
<p>EDIT: here is a new version with some improvements as suggested.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
#include <stdint.h>
// main prog
struct str{
char* seq;
int len;
};
void *odd(void* arg){
const struct str *index = arg;
int maxAns = 1;
for(int i = 1; i < index->len; i++){
int low = i - 1;
int high = i + 1;
int currMax = 1;
while(low >= 0 && high < index->len && index->seq[low] == index->seq[high]){
low--;
high++;
currMax=currMax+2;
}
if(currMax > maxAns){
maxAns = currMax;
}
}
return (void *)(intptr_t)maxAns;
}
void *even(void* arg){
const struct str *index = arg;
int maxAns = 0;
for(int i = 0; i < index->len; i++){
int low = i;
int high = i + 1;
int currMax = 0;
while(low >= 0 && high < index->len && index->seq[low] == index->seq[high]){
low--;
high++;
currMax=currMax+2;
}
if(currMax > maxAns){
maxAns = currMax;
}
}
return (void *)(intptr_t)maxAns;
}
// timer
long timediff(clock_t t1, clock_t t2) {
long elapsed;
elapsed = ((double)t2 - t1) / CLOCKS_PER_SEC * 1000000;
return elapsed;
}
int main(void){
// timer
clock_t ti1, ti2;
long elapsed;
ti1 = clock();
// main program
char seq[] = "aaasadsdafasdhjkagsdfjhasjbjflASHBFHJASKBHFKJASBFASSDHJGVAHDGVsakhjfdsakjfuadsfk";
int len = sizeof(seq)/sizeof(seq[0])-1;
struct str s = {seq, len};
pthread_t t0;
pthread_t t1;
intptr_t res0;
intptr_t res1;
if (pthread_create(&t0, NULL, &odd, &s)!=0){
return 0;
}
if (pthread_create(&t1, NULL, &even, &s)!=0){
return 00;
}
if(pthread_join(t0, (void*)&res0)!=0){
return 1;
}
if(pthread_join(t1, (void*)&res1)!=0){
return 11;
}
printf("%d\n", (int)(res0 > res1 ? res0 : res1));
// end timer
ti2 = clock();
elapsed = timediff(ti1, ti2);
printf("elapsed: %ld microseconds\n", elapsed);
return 0;
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<h1>Passing strings to threads</h1>\n<p>You are dynamically allocating <code>struct str</code>s and passing pointers to those structs to the threads. However, the structs could be allocated on the stack instead:</p>\n<pre><code>struct str s0 = {seq0, len};\n...\nif (pthread_create(&t0, NULL, &odd, &s0) != 0) {\n</code></pre>\n<p>Note that you also don't need two different instances of it; the threads are not modifying the strings, so they can both get a pointer to <code>s0</code>.</p>\n<p>Inside <code>odd()</code> and <code>even()</code>, you are making a copy of <code>s0</code> and <code>s1</code>. This is unnecessary. I would write the following:</p>\n<pre><code>void *odd(void *arg) {\n const struct str *index = arg;\n int maxAns = 1;\n for (int i = 1; i < index->len; i++) {\n ...\n</code></pre>\n<p>But you don't actually need to know the length of the string up front. Instead of using <code>struct str</code>, I would just pass a pointer to the string directly:</p>\n<pre><code>if (pthread_create(&t0, NULL, &odd, seq0) != 0) {\n</code></pre>\n<p>And then just check in the <code>for</code> and <code>while</code> loops whether you hit the terminating NUL character:</p>\n<pre><code>void *odd(void* arg){\n const char *str = arg;\n ...\n for (int i = 1; str[i]; i++) {\n ...\n while(low >= 0 && str[high] && str[low] == str[high]) {\n ...\n</code></pre>\n<h1>Returning the answer without allocating memory</h1>\n<p>While the return type of a thread function should be <code>void *</code>, you can actually make it return an integer if you are careful. Make use of the fact that you can cast a pointer to and from <a href=\"https://stackoverflow.com/questions/35071200/what-is-the-use-of-intptr-t\"><code>intptr_t</code></a>:</p>\n<pre><code>#include <stdint.h>\n...\nvoid *odd(void *arg) {\n ...\n return (void *)(intptr_t)maxAns;\n}\n</code></pre>\n<p>The answer is first cast to <code>intptr_t</code> before casting it to a <code>void *</code>; it is possible to do it without the first cast but your compiler might complain then.</p>\n<p>To read the result, write:</p>\n<pre><code>intptr_t res0;\nintptr_t res1;\n...\nif (pthread_join(t0, (void *)&res0) != 0) {\n ...\n}\n...\nprintf("%d\\n", (int)(res0 > res1 ? res0 : res1));\n</code></pre>\n<p>This, combined with the other way of passing strings means you don't have to do any manual memory management anymore, and you got rid of the memory leaks you had in your code.</p>\n<h1>Optimizing the code</h1>\n<p>A lot of CPUs nowadays have more than 2 cores. If you had very large strings to process, you probably want to use all available cores instead of just two. In that case, the best strategy would probably to use a <a href=\"https://en.wikipedia.org/wiki/Thread_pool\" rel=\"nofollow noreferrer\">thread pool</a>, and split up the task of finding the largest palindrome in a way so there are many small tasks. For example, split it up based on the position of the first character, or the middle one like you already have done inside <code>odd()</code> and <code>even()</code>.</p>\n<p>Then, consider that we are not interested in small palindromes, only the longer one, so if we know we found the largest palindrome, we can stop searching for other possibilities. So make it so we first check the largest possible palindrome: <code>i</code> should be in the middle of the string. Use an <a href=\"https://en.cppreference.com/w/c/atomic\" rel=\"nofollow noreferrer\">atomic variable</a> to store the size of the largest palindrome found so far; if a new task starts it checks what the maximum size is of the palindrome it can search for (this depends on <code>i</code>), if this is lower that the maximum so far it can just immediately return.</p>\n<p>There might be other algorithms possible for finding the longest palindrome subsequence, see <a href=\"https://cs.stackexchange.com/questions/2466/fastest-algorithm-for-finding-the-longest-palindrome-subsequence\">this Computer Science question</a>. Last but not least, you might be able to further optimize it by using <a href=\"https://en.wikipedia.org/wiki/SIMD\" rel=\"nofollow noreferrer\">SIMD instructions</a>, but this is outside the C standard.</p>\n<h1>Exit codes</h1>\n<p>You wrote these return statements when something went wrong with thread creation or joining:</p>\n<pre><code>return 0;\nreturn 00;\nreturn 1;\nreturn 11;\n</code></pre>\n<p>That's very strange. The first two <code>return</code> statements will cause the program to exit with exit code 0, which normally means success. You want to return a non-zero exit code in all these cases. It's also good practice to return <a href=\"https://en.cppreference.com/w/c/program/EXIT_status\" rel=\"nofollow noreferrer\"><code>EXIT_SUCCESS</code> and <code>EXIT_FAILURE</code></a> instead of hardcoded numbers.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T14:37:59.460",
"Id": "265736",
"ParentId": "265728",
"Score": "3"
}
},
{
"body": "<h1><code>malloc()</code> can return a null pointer</h1>\n<blockquote>\n<pre><code> int* res = malloc(sizeof(int));\n *res = maxAns;\n</code></pre>\n</blockquote>\n<p>We need to ensure <code>res</code> is not null and not dereference it if so.</p>\n<p>(To those who say "it always succeeds on my platform": it probably doesn't, when you use a more constrained <code>ulimit -v</code>, so get in the habit of coding robustly.</p>\n<hr />\n<h1>Pointless cast</h1>\n<blockquote>\n<pre><code> return (void*)res;\n</code></pre>\n</blockquote>\n<p>We can just <code>return res</code>, since any object-pointer can be assigned to <code>void*</code>.</p>\n<hr />\n<h1>Consider using a higher-level interface</h1>\n<p>Using <code><pthread.h></code> can be good for understanding, and if that's your main interest, by all means continue.</p>\n<p>However, using a higher-level abstraction can give you more for less effort, and many compilers these days offer support for OpenMP. That lets you easily distribute work across available cores, and use dynamic scheduling when the work items vary in size.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T16:33:16.710",
"Id": "265742",
"ParentId": "265728",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "265736",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T12:49:22.763",
"Id": "265728",
"Score": "4",
"Tags": [
"c",
"multithreading",
"palindrome"
],
"Title": "Longest Palindromic Subsequence Multithread in C"
}
|
265728
|
<p>I've done a script to sort fanfics by the bayesian average of views and rating. I've used views because it took much longer to scrape the dlp website for reviews.</p>
<p>I leave all the code so that it works. But I'm most interested in the following functions:</p>
<pre><code>get_percentile(conn, column, nth)
get_top_100(conn)
get_bayesian_ranking(conn)
print_html(rows)
print_markdown(rows)
print_text(rows)
print_database()
</code></pre>
<p>Here is the code:</p>
<pre><code># Formula for the bayesian rating:
# bayesianAverage = (v ÷ (v+m)) × R + (m ÷ (v+m)) × C
# R = average for the fanfic (mean) = rating
# v = number of views for the fanfic = views
# C = minimum votes required to be listed in the Top 100 (10,000)
# m = the mean vote across the whole report
import re
import sqlite3
import requests
import logging
import traceback
from bs4 import BeautifulSoup
dlp_url = 'https://forums.darklordpotter.net/'
def parse_library(cursor):
dlp_forums_url = dlp_url + 'forums/'
parse_forum(cursor, dlp_forums_url + 'almost-recommended.41/')
parse_forum(cursor, dlp_forums_url + 'general-fics.28/')
parse_forum(cursor, dlp_forums_url + 'humor.27/')
parse_forum(cursor, dlp_forums_url + 'the-alternates.16/')
parse_forum(cursor, dlp_forums_url + 'dark-arts.14/')
parse_forum(cursor, dlp_forums_url + 'romance.17/')
parse_forum(cursor, dlp_forums_url + 'restricted-section.35/')
def parse_forum(cursor, web_url: str):
r = requests.get(web_url)
web = BeautifulSoup(r.text, 'lxml')
number_pages = web.find('div', class_='PageNav')['data-last']
parse_page(cursor, web)
for page_number in range(2, int(number_pages) + 1):
page_url = web_url + 'page-' + str(page_number)
r = requests.get(page_url)
page = BeautifulSoup(r.text, 'lxml')
parse_page(cursor, page)
def parse_page(cursor, page):
discussion_list = page.find_all('li', class_='discussionListItem')
for discussion in discussion_list:
parse_discussion(cursor, discussion)
def parse_discussion(cursor, discussion):
if is_sticky(discussion):
return
fic = {}
discussion_main = discussion \
.find('div', class_='listBlock main') \
.find('h3', class_='title') \
.find('a', class_='PreviewTooltip')
href = discussion_main['href']
fic['dlp_url'] = dlp_url + href
discussion_text = discussion_main.text
logging.info(f"Scraping '{discussion_text}'")
parse_status(discussion, fic)
parse_rating(discussion, fic)
parse_views(discussion, fic)
parse_title(discussion_main, fic)
insert_in_database(cursor, fic)
def is_sticky(discussion) -> bool:
if discussion.find('span', class_='fa fa-thumb-tack') is not None:
return True
else:
return False
def parse_status(discussion, fic):
status = ""
try:
status = discussion.find('a', class_='prefixLink').find('span', class_='prefix').text
except AttributeError as e:
logging.warning("No status")
fic['status'] = status
def parse_title(discussion_main, fic):
title = ""
author = ""
age_rating = ""
try:
regex = r"^(?P<title>.*)( by )(?P<author>.*)( - )(?P<age_rating>.*)"
matches = re.search(regex, discussion_main.text)
title = matches.group('title')
author = matches.group('author')
age_rating = matches.group('age_rating')
except Exception as e:
logging.warning(f"Couldn't parse {discussion_main.text}, {fic['status']}, {fic['rating']}, {fic['views']}, {fic['dlp_url']}")
fic['title'] = title
fic['author'] = author
fic['age_rating'] = age_rating
def parse_rating(discussion, fic):
rating = 0.0
try:
rating = float(discussion.find('span', class_='ratings')['title'])
except AttributeError as e:
logging.warning("No rating")
fic['rating'] = rating
def parse_views(discussion, fic):
views = 0
try:
views = int(discussion.find('div', class_='listBlock stats pairsJustified').find('dl', class_='minor').find('dd').text.replace(',', ''))
except AttributeError as e:
logging.warning("No views")
fic['views'] = views
def create_database_schema(cursor):
cursor.execute("DROP TABLE IF EXISTS fic")
sql = '''CREATE TABLE fic(
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
author TEXT,
age_rating INT,
status TEXT,
rating FLOAT,
views INT,
dlp_url TEXT
)'''
cursor.execute(sql)
def insert_in_database(cursor, fic):
if not fic['title']:
return
logging.info(f'Insert {{{fic["title"]}, {fic["author"]}, {fic["age_rating"]}, {fic["status"]}, {fic["rating"]}, {fic["views"]}, {fic["dlp_url"]}}}')
try:
sql = '''INSERT INTO fic(title, author, age_rating, status, rating, views, dlp_url)
VALUES (?,?,?,?,?,?,?)'''
cursor.execute(sql, (fic['title'], fic['author'], fic['age_rating'], fic['status'], fic['rating'], fic['views'], fic['dlp_url']))
except:
logging.error(traceback.print_exception(type(e), e, e.__traceback__))
logging.error(f'Failed to insert {{{fic["title"]}, {fic["author"]}, {fic["age_rating"]}, {fic["status"]}, {fic["rating"]}, {fic["views"]}, {fic["dlp_url"]}}}')
def get_percentile(conn, column, nth):
nth /= 100
# https://stackoverflow.com/a/1123642/13477305
sql = f'''
SELECT {column}
FROM fic
ORDER BY {column} ASC
LIMIT 1
OFFSET ROUND((
SELECT COUNT(*)
FROM fic) * {nth} - 1);
'''
return conn.execute(sql).fetchone()[0]
def get_top_100(conn):
sql = '''
SELECT ROUND((m * c + views * rating) /
(c + views), 2) as bayesian,
title, views, status, age_rating, rating, dlp_url
FROM (
SELECT AVG(rating) OVER () as m,
AVG(views) OVER () as c,
*
FROM fic
WHERE views > 10000
)
ORDER BY bayesian DESC;
'''
return conn.cursor().execute(sql).fetchall()
def get_bayesian_ranking(conn):
_25th_percentile_views = get_percentile(conn, "views", 25)
sql = f'''
SELECT ROUND((m * {_25th_percentile_views} + views * rating) /
({_25th_percentile_views} + views), 2) as bayesian,
rating, views, status, age_rating, title, dlp_url
FROM (
SELECT AVG(rating) OVER () as m,
AVG(views) OVER () as c,
*
FROM fic
)
ORDER BY bayesian DESC;
'''
return conn.cursor().execute(sql).fetchall()
def print_html(rows):
print('<table><tr><td>Bayesian</td><td>Rating</td><td>Views</td>'
'<td>Status</td><td>Title</td></tr>')
for row in rows:
print(f'''
<tr>
<td>{row["bayesian"]}</td>
<td>{row["rating"]}</td>
<td>{row["views"]}</td>
<td>{row["status"]}</td>
<td>[url={row["dlp_url"]}]{row["title"]}[/url]</td>
</tr>
''')
print('</table>')
def print_markdown(rows):
print('| Bayesian | Rating | Views | Status | Title |')
print('| --- | --- | --- | --- | --- |')
for row in rows:
print(f'| {row["bayesian"]} | {row["rating"]} | {row["views"]} '
f'| {row["status"]} | [{row["title"]}]({row["dlp_url"]}) |')
def print_text(rows):
print('Bayesian Rating Views Status Title')
for row in rows:
print(f'{row["bayesian"]} {row["rating"]} {row["views"]} '
f'{row["status"]} {row["title"]}')
def print_database():
conn = sqlite3.connect('dlp.sqlite3')
conn.row_factory = sqlite3.Row
#rows = get_top_100(conn)
rows = get_bayesian_ranking(conn)
#print_html(rows)
print_markdown(rows)
#print_text(rows)
def main():
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[
logging.FileHandler("debug.log"),
logging.StreamHandler()
]
)
conn = sqlite3.connect('dlp.sqlite3')
cursor = conn.cursor()
create_database_schema(cursor)
parse_library(cursor)
insert_missing(cursor)
conn.commit()
conn.close()
if __name__ == "__main__":
#main()
print_database()
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T13:02:27.113",
"Id": "265729",
"Score": "0",
"Tags": [
"python",
"sorting",
"sqlite"
],
"Title": "Bayesian ranking of fanfics with python and sqlite"
}
|
265729
|
<p>I am trying to build on @Reinderien's answer to my previous question over <a href="https://codereview.stackexchange.com/q/265627/242934">here</a> to add page iteration functionality to the code:</p>
<pre class="lang-py prettyprint-override"><code>from base64 import b64encode
from datetime import date
from typing import Iterable, ClassVar, List
from attr import dataclass
from bs4 import BeautifulSoup, SoupStrainer, Tag
from requests import Session
import re
from itertools import count
from urllib.parse import urljoin
BASE_URL = 'https://www.ctwx.tsinghua.edu.cn'
@dataclass
class Result:
caption: str
when: date
path: str
@classmethod
def from_list_item(cls, item: Tag) -> 'Result':
return cls(
caption=item.a.text,
path=item.a['href'],
when=date.fromisoformat(item.find('span', recursive=False).text),
)
class TsinghuaSite:
subdoc: ClassVar[SoupStrainer] = SoupStrainer(name='ul', class_='search_list')
pagination: ClassVar[SoupStrainer] = SoupStrainer(name='table', class_='listFrame')
def __init__(self):
self.session = Session()
def __enter__(self) -> 'TsinghuaSite':
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.session.close()
def search(self, query: str) -> Iterable[List]:
with self.session.post(
urljoin(BASE_URL, 'search.jsp'),
params={'wbtreeid': 1001},
data={
'lucenenewssearchkey': b64encode(query.encode()),
'_lucenesearchtype': '1',
'searchScope': '0',
'x': '0',
'y': '0',
},
) as resp:
resp.raise_for_status()
pages = BeautifulSoup(markup=resp.text, features='html.parser', parse_only=self.pagination)
n_pages_string = list(pages.select_one('td').children)[4]
n_pages = int(re.search(r'\d+', n_pages_string)[0])
if n_pages > 1:
docs = []
for page in count(1):
with self.session.get(
resp.url,
params={
'wbtreeid': 1001,
'newskeycode2': b64encode(query.encode()),
'searchScope': '0',
'currentnum': page,
},
) as resp:
resp.raise_for_status()
doc = BeautifulSoup(markup=resp.text, features='html.parser', parse_only=self.subdoc)
print(f"Scraping page {page}/{n_pages}.")
docs.append(doc)
if page >= n_pages:
yield from docs
break
else:
doc = BeautifulSoup(markup=resp.text, features='html.parser', parse_only=self.subdoc)
yield doc
def yield_results(self, query) -> Iterable[Result]:
doc_gen = self.search(query)
for doc in doc_gen:
for item in doc.find('ul', recursive=False).find_all('li', recursive=False):
yield Result.from_list_item(item)
def main():
with TsinghuaSite() as site:
query = '尹至'
results = tuple(site.yield_results(query))
# assert any(query in r.caption for r in results)
for result in results:
print(result)
if __name__ == '__main__':
main()
</code></pre>
<p>The code seems to be working correctly; but I would still like to seek suggestions on how to improve on it.</p>
<h1>Output:</h1>
<pre class="lang-py prettyprint-override"><code>Scraping page 1/2.
Scraping page 2/2.
Result(caption='出土文献研究与保护中心2020年报', when=datetime.date(2021, 4, 9), path='info/1041/2615.htm')
Result(caption='《战国秦汉文字与文献论稿》出版', when=datetime.date(2020, 7, 17), path='info/1012/1289.htm')
Result(caption='【光明日报】清华简十年:古书重现与古史新探', when=datetime.date(2018, 12, 25), path='info/1072/1551.htm')
Result(caption='《清華簡與古史探賾》出版', when=datetime.date(2018, 8, 30), path='info/1012/1436.htm')
Result(caption='【出土文獻第九輯】鄔可晶:《尹至》“惟(肉哉)虐德暴(身童)亡典”句試解', when=datetime.date(2018, 5, 24), path='info/1073/1952.htm')
Result(caption='【出土文獻第五輯】袁金平:從《尹至》篇“播”字的討論談文義對文字考釋的重要性', when=datetime.date(2018, 4, 26), path='info/1081/2378.htm')
Result(caption='【出土文獻第五輯】袁金平:從《尹至》篇“播”字的討論談文義對文字考釋的重要性', when=datetime.date(2018, 4, 26), path='info/1081/2378.htm')
Result(caption='【出土文獻第二輯】羅 琨:讀《尹至》“自夏徂亳”', when=datetime.date(2018, 4, 12), path='info/1081/2283.htm')
Result(caption='【出土文獻第二輯】羅 琨:讀《尹至》“自夏徂亳”', when=datetime.date(2018, 4, 12), path='info/1081/2283.htm')
Result(caption='《出土文獻》(第九輯)出版', when=datetime.date(2016, 10, 26), path='info/1012/1411.htm')
Result(caption='《出土文獻研究》第十三輯出版', when=datetime.date(2015, 4, 8), path='info/1012/1396.htm')
Result(caption='清華大學藏戰國竹簡第五冊相關研究論文', when=datetime.date(2015, 4, 8), path='info/1081/2215.htm')
Result(caption='清華大學藏戰國竹簡第五冊相關研究論文', when=datetime.date(2015, 4, 8), path='info/1081/2215.htm')
Result(caption='《出土文獻》(第五輯)出版', when=datetime.date(2014, 10, 13), path='info/1012/1393.htm')
Result(caption='清华简入选《国家珍贵古籍名录》', when=datetime.date(2013, 12, 11), path='info/1072/1496.htm')
Result(caption='出土文献研究与保护中心2020年报', when=datetime.date(2021, 4, 9), path='info/1041/2615.htm')
Result(caption='《战国秦汉文字与文献论稿》出版', when=datetime.date(2020, 7, 17), path='info/1012/1289.htm')
Result(caption='【光明日报】清华简十年:古书重现与古史新探', when=datetime.date(2018, 12, 25), path='info/1072/1551.htm')
Result(caption='《清華簡與古史探賾》出版', when=datetime.date(2018, 8, 30), path='info/1012/1436.htm')
Result(caption='【出土文獻第九輯】鄔可晶:《尹至》“惟(肉哉)虐德暴(身童)亡典”句試解', when=datetime.date(2018, 5, 24), path='info/1073/1952.htm')
Result(caption='【出土文獻第五輯】袁金平:從《尹至》篇“播”字的討論談文義對文字考釋的重要性', when=datetime.date(2018, 4, 26), path='info/1081/2378.htm')
Result(caption='【出土文獻第五輯】袁金平:從《尹至》篇“播”字的討論談文義對文字考釋的重要性', when=datetime.date(2018, 4, 26), path='info/1081/2378.htm')
Result(caption='【出土文獻第二輯】羅 琨:讀《尹至》“自夏徂亳”', when=datetime.date(2018, 4, 12), path='info/1081/2283.htm')
Result(caption='【出土文獻第二輯】羅 琨:讀《尹至》“自夏徂亳”', when=datetime.date(2018, 4, 12), path='info/1081/2283.htm')
Result(caption='《出土文獻》(第九輯)出版', when=datetime.date(2016, 10, 26), path='info/1012/1411.htm')
Result(caption='《出土文獻研究》第十三輯出版', when=datetime.date(2015, 4, 8), path='info/1012/1396.htm')
Result(caption='清華大學藏戰國竹簡第五冊相關研究論文', when=datetime.date(2015, 4, 8), path='info/1081/2215.htm')
Result(caption='清華大學藏戰國竹簡第五冊相關研究論文', when=datetime.date(2015, 4, 8), path='info/1081/2215.htm')
Result(caption='《出土文獻》(第五輯)出版', when=datetime.date(2014, 10, 13), path='info/1012/1393.htm')
Result(caption='清华简入选《国家珍贵古籍名录》', when=datetime.date(2013, 12, 11), path='info/1072/1496.htm')
</code></pre>
|
[] |
[
{
"body": "<p>Scraping code is often ugly, and this is no exception. There's not much you can do, but it's important to work extra hard to make it readable.</p>\n<p>Error handling is missing (just throws an error), but that's okay if that's what you want. It makes things more readable.</p>\n<p><code>search</code> is too long and nested too deeply. You should limit the number of layers of indentation much more for readability. Split out the middle into <code>search_page</code> to make the pagination logic easier to understand:</p>\n<pre><code>def search_page(self, url, page_num)\n with self.session.get(\n url,\n params={\n 'wbtreeid': 1001,\n 'newskeycode2': b64encode(query.encode()),\n 'searchScope': '0',\n 'currentnum': page,\n },\n ) as resp:\n resp.raise_for_status()\n return BeautifulSoup(markup=resp.text, features='html.parser', parse_only=self.subdoc)\n\nif n_pages > 1:\n for page in count(1):\n doc = search_page(resp.url, page)\n print(f"Scraping page {page}/{n_pages}.")\n docs.append(doc)\n\n if page >= n_pages:\n yield from docs\n break\n else:\n doc = BeautifulSoup(markup=resp.text, features='html.parser', parse_only=self.subdoc)\n yield doc\n</code></pre>\n<p>You have an error here--you mean to have an <code>if-else</code> clause, not a <a href=\"https://book.pythontips.com/en/latest/for_-_else.html\" rel=\"nofollow noreferrer\">for-else</a> clause, because the else clause can never trigger in the original. You would likely have caught the error with less nesting.</p>\n<p>There is no reason to add the indentation of</p>\n<pre><code>with session.get(...) as resp:\n resp.raise_for_status()\n ...\n</code></pre>\n<p>This is only needed for streaming output. Just use</p>\n<pre><code>resp = session.get(...)\nresp.raise_for_status()\n...\n</code></pre>\n<p>Don't use <code>count</code>. Use <code>range</code> which is more standard. The entire second loop can be replaced with</p>\n<pre><code>if n_pages > 1:\n for page in range(1, n_pages+1):\n print(f"Scraping page {page}/{n_pages}.")\n yield search_page(resp.url, page)\nelse:\n yield BeautifulSoup(markup=resp.text, features='html.parser', parse_only=self.subdoc)\n</code></pre>\n<p>The last change to make here is to simplify out one more layer (and make one less request), by assuming assuming the initial page is the first page of results already:</p>\n<pre><code>print(f"Scraping page 1/{n_pages}.")\nyield BeautifulSoup(markup=resp.text, features='html.parser', parse_only=self.subdoc)\nfor page in range(2, n_pages+1):\n print(f"Scraping page {page}/{n_pages}.")\n yield search_page(resp.url, page)\n</code></pre>\n<p>You can check in your output that you were printing the first page twice (<code>info/1012/1289.htm</code> appears twice for example) so this is better for the user too.</p>\n<p>To clean <code>search</code> further, separate out page fetching and scraping more cleanly--yield up resp.text rather than BeautifulSoup documents, and add a helper function which turns an iterable of HTML strings into an iterable of parsed documents. This removes some repetition.</p>\n<p>Finally, there is some repetition in the parameters between grabbing the main page and the search page. Currently you are using the main page URL to reduce this... this is OK but you could also switch the main page to call <code>search_page(1)</code>, and remove the first set of logic altogether. Whether this works depends on the website, which I'm not familiar with.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T09:10:10.597",
"Id": "266579",
"ParentId": "265730",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T13:05:57.857",
"Id": "265730",
"Score": "0",
"Tags": [
"python",
"web-scraping"
],
"Title": "Adding page iteration capability to Requests scraper"
}
|
265730
|
<p>I'm pretty new to programming and shell and I'm not having any issue with the script below; it's working perfectly but I want to know if I can do better.</p>
<p>I'm inserting the content of some CSV files (<code>value1</code>, <code>value2</code>, <code>value3</code>) into an HTML table. I'm using a <code>while</code> loop (easier for me), but I think there might be a simpler way to do it.</p>
<p>Is it possible to have the script in one single <code>while</code> loop? I want to echo different text depending on the value of the variable.</p>
<pre><code>echo "<!DOCTYPE html>
<html>
<style>
tr, td {
border: 1px solid black;
border-collapse: collapse;
text-align: center;
}
table {
width: 75%;
}
h2 {
color: navy;
text-transform: uppercase;
}
h3 {
color: navy;
text-transform: uppercase;
padding-top:50px;
}
</style>"
var1="value1"
for a1 in $var1; do
echo "<h2>text1</h2>
<table>"
print_header=true
while read INPUT ; do
if $print_header;then
echo "<tr><span style="text-transform:uppercase"><td><b>${INPUT//,/</b></td><td><b>}</b></td></span></tr>";
print_header=false
else
echo "<tr><td>${INPUT//,/</td><td>}</td></tr>" ;
fi
done < $a1;
echo "</table>"
done
var2="value2 value3"
for a2 in $var2; do
echo "<h2>text2</h2>
<table>"
print_header=true
while read INPUT ; do
if $print_header;then
echo "<tr><span style="text-transform:uppercase"><td><b>${INPUT//,/</b></td><td><b>}</b></td></span></tr>";
print_header=false
else
echo "<tr><td>${INPUT//,/</td><td>}</td></tr>" ;
fi
done < $a2 ;
echo "</table>"
done
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T13:43:49.133",
"Id": "265733",
"Score": "0",
"Tags": [
"html",
"csv",
"shell"
],
"Title": "displaying contents from CSV files in an HTML table"
}
|
265733
|
<p>I'm looking for advice on how to improve my code or find some potential bugs. I have a Java app which listen to multiple RabbitMQ queues and process the messages. In the my case I have 5 queues. I have the following consumer class</p>
<pre><code>public class ConsumerWorker extends DefaultConsumer {
private long sleep;
private Channel channel;
private ExecutorService executorService;
final Map<String, Object> sourceListeners;
/**
* Creates a new <code>ConsumerWorker</code> instance.
* @param prefetch
* @param threadExecutor
* @param sleep
* @param channel
* @param queue
* @throws IOException
*/
public ConsumerWorker(final int prefetch,
final ExecutorService threadExecutor, final long sleep,
final Channel channel, final String queue,
final Map<String, Object> sourceListeners) throws IOException {
super(channel);
this.sleep = sleep;
this.channel = channel;
this.sourceListeners = sourceListeners;
this.executorService = threadExecutor;
this.channel.basicQos(prefetch);
this.channel.queueDeclare(queue, true, false, false, null);
this.channel.basicConsume(queue, false, this);
}
@Override
public void handleDelivery(String consumerTag, Envelope envelope,
AMQP.BasicProperties properties, byte[] body) throws IOException {
final String message = new String(body);
DataSourceIdPayload payload = GsonFactory.getGson().fromJson(message,
DataSourceIdPayload.class);
if (properties != null) {
payload.setHeaders(properties.getHeaders());
}
Runnable task = new ScheduledDataSourceProcessor(envelope.getDeliveryTag(), channel,sleep, payload);
executorService.submit(task);
}
}
</code></pre>
<p>and the corresponding class</p>
<blockquote>
<p>ScheduledDataSourceProcessor</p>
</blockquote>
<p>which implements <strong>Runnable</strong>. I creates 3 <strong>ConsumerWorker</strong> for each respective queue.</p>
<pre><code> private static final int DEFAULT_NUM_THREADS = Runtime.getRuntime().availableProcessors() * 2;
private static final int PREFETCH_COUNT = 10;
final ThreadFactory customThreadfactory = new MyCustomThreadFactoryBuilder()
.setNamePrefix("ScheduledSyncDataSource-Thread")
.setDaemon(true)
.build();
ExecutorService threadExecutor = Executors.newFixedThreadPool(DEFAULT_NUM_THREADS, customThreadfactory);
for (int i = 0; i < 3; i++) {
new ConsumerWorker(PREFETCH_COUNT, threadExecutor, 3,
connection.createChannel(),
QueueName1,"");
}
for (int i = 0; i < 3; i++) {
new ConsumerWorker(PREFETCH_COUNT, threadExecutor, 3,
connection.createChannel(),
QueueName2,"");
}
for (int i = 0; i < 3; i++) {
new ConsumerWorker(PREFETCH_COUNT, threadExecutor, 3,
connection.createChannel(),
QueueNameN,"");
}
}
</code></pre>
<p>Is this a good approach?
What can I improve in it?
Do I need to create separate threadPools for each individual queue?
Thanks!</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T13:56:25.040",
"Id": "265734",
"Score": "0",
"Tags": [
"java",
"rabbitmq"
],
"Title": "RabbitMQ multiple queues and process the message"
}
|
265734
|
<p>I'm a new developer just starting out learning HTML, css and JavaScript. Below is my attempt at building a portfolio website.</p>
<p>I am finding it difficult positioning elements the way I want to and finding botched ways to do so when there's probably a more cleaner and efficient way of doing so.</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></p>
<p><a href="https://jackdef10.github.io/Second-portfolio-draft/" rel="nofollow noreferrer">My Web 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" id="nav-text">HOME</a>
<a href="#about-me" class="nav-item" id="nav-text">ABOUT</a>
<a href="#projects" class="nav-item" id="nav-text">PROJECTS</a>
<a href="#skills" class="nav-item" id="nav-text">SKILLS</a>
<a href="#contact" class="nav-item" id="nav-text">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="">
<img src="resources/images/GitHub-Logos/GitHub_Logo_White.png" id="github">
</a>
<a href="">
<img src="resources/images/LinkedIn-Logos/LI-In-Bug.png" id="linkedIn">
</a>
</div>
</header>
<main class="content">
<section class="about-me" id="about-me">
<article class="about-style">
<span class="section-title">ABOUT ME</span>
<div id="about">
<h1>ABOUT ME</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Aliquam a faucibus dolor. Aliquam euismod ac elit a eleifend.
Vivamus in rhoncus ante, ac semper ex. Nam ac lobortis mauris.
Donec et metus dolor. Sed posuere nec ante nec tincidunt.
Aliquam euismod ac elit a eleifend.</p>
</div>
<div id="about2">
<h1>LOREM</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Donec libero justo, bibendum in justo id, mollis maximus odio.
Phasellus purus mauris, tincidunt non turpis eu, fringilla varius justo.
Nam elementum nunc lacus, eu porttitor metus vehicula eget.
Pellentesque sed dictum tortor. </p>
</div>
<div id="about3">
<h1>LOREM</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Donec libero justo, bibendum in justo id, mollis maximus odio.
Phasellus purus mauris, tincidunt non turpis eu, fringilla varius justo.
Nam elementum nunc lacus, eu porttitor metus vehicula eget.
Pellentesque sed dictum tortor. </p>
</div>
</article>
</section>
<section class="projects" id="projects">
<div class="pro-container">
<span class="section-title">PROJECTS</span>
</div>
</section>
<section class="skills" id="skills">
<div class="skills-container">
<span class="section-title">SKILLS</span>
</div>
</section>
<section class="contact" id="contact">
<span class="section-title">CONTACT</span>
<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>
</section>
</main>
</div>
</div>
<script src="./resources/javascript/Navbar.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%;
}
section{
height: 100vh;
display: relative;
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: rgb(63,34,195);
background: linear-gradient(0deg, rgba(63,34,195,1) 10%, rgba(255,99,71,1) 100%);
margin: 0 auto;
position:relative;
}
.projects{
background-color: #0093E9;
background-image: linear-gradient(160deg, #0093E9 0%, #80D0C7 100%);
position:relative;
}
.skills{
background-color: #4158D0;
background-image: linear-gradient(43deg, #4158D0 0%, #C850C0 46%, #FFCC70 100%);
position:relative;
}
.contact{
background: rgb(2,0,36);
background: linear-gradient(90deg, rgba(2,0,36,1) 0%, rgba(26,26,119,1) 45%, rgba(0,212,255,1) 100%);
position:relative;
}
.section-title{
color:whitesmoke;
font-size: 6em;
font-weight:600;
border: 3px solid white;
position: relative;
top: 200px;
padding: 20px;
left:1000px;
}
.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;
}
#nav-text{
font-size:1.5em;
}
.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;
}
/* 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:2em;
top: 150px;
left:100px;
}
}
@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:6em;
top: 200px;
left:240px;
}
.nav-item:before {
height:8px;
}
}
#about {
text-align:center;
width:650px;
height: 800px;
position:relative;
Padding:60px;
font-size:2em;
line-height: 1.5em;
color: white;
background-color:rgba(165, 165, 165, 0.3);
box-shadow: 0px 10px 40px rgba(159, 162, 177, .4);
border: 2px solid white;
border-radius: 2em;
left: 200px;
top: 300px;
letter-spacing: 0.2em;
}
#about2 {
text-align:center;
width:650px;
height: 800px;
position:relative;
Padding:60px;
font-size:2em;
color: white;
background-color:rgba(165, 165, 165, 0.3);
left: 950px;
bottom: 500px;
box-shadow: 0px 10px 40px rgba(159, 162, 177, .4);
border: 2px solid white;
border-radius: 2em;
line-height: 1.5em;
letter-spacing: 0.2em;;
}
#about3 {
text-align:center;
width:650px;
height: 800px;
position:relative;
Padding:60px;
font-size:2em;
color: white;
background-color:rgba(165, 165, 165, 0.3);
left: 1700px;
bottom:1300px;
box-shadow: 0px 10px 40px rgba(159, 162, 177, .4);
border: 2px solid white;
border-radius: 2em;
line-height: 1.5em;
letter-spacing: 0.2em;;
}
/* contact form */
.email-form{
position:relative;
padding-left: 170px;
top:300px;
}
.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:20px;
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: 20px;
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;
}
</code></pre>
<h1>Javascript</h1>
<pre><code>const navigation = document.querySelector(".navbar");
const navText = document.getElementById("nav-text");
window.onscroll = function() {scrollFunction()};
const scrollFuction = () => {
if(document.body.scrollTop > 100 || document.documentElement.scrollTop > 100) {
navigation.style.right = "5%";
navigation.style.padding = "20px 45px";
navText.style.fontSize="0.7em";
} else {
navigation.style.right = "30%";
navigation.style.padding = "40px 90px";
navText.style.fontSize = "1.5em";
}
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T15:39:35.043",
"Id": "524911",
"Score": "0",
"body": "Welcome to Code Review! It would benefit reviewers to have a bit more information about the code in the description. From [the help center page _How to ask_](https://codereview.stackexchange.com/help/how-to-ask): \"_You will get more insightful reviews if you not only provide your code, but also give an explanation of what it does. The more detail, the better._\" You could consider putting the HTML, CSS and JS into a [runnable snippet](https://meta.stackoverflow.com/a/358993/1575353) though you'd have to change the URLs to be absolute - e.g. in bg image in CSS."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T15:43:45.063",
"Id": "524912",
"Score": "0",
"body": "I [changed the title](https://codereview.stackexchange.com/revisions/265735/3) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate."
}
] |
[
{
"body": "<p>Just a few words about the JavaScript:</p>\n<ul>\n<li><p>Don't assign event handlers using <code>on...</code> attributes/properties. Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener\" rel=\"nofollow noreferrer\"><code>addEventListener</code></a>.</p>\n</li>\n<li><p>Don't hard-code and set styles in the JavaScript. Instead toggle a class and put the styles into the style sheet using that class.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T11:22:25.457",
"Id": "265768",
"ParentId": "265735",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T14:26:50.187",
"Id": "265735",
"Score": "2",
"Tags": [
"javascript",
"performance",
"beginner",
"html",
"css"
],
"Title": "developer portfolio website"
}
|
265735
|
<h2>Background</h2>
<p>Recently, I was making some updates to an "older" library that would handle PATCH-style modifications to an object that is persisted in a JSON format on our document-storage databases (e.g., CosmosDB).</p>
<p>I took a fresh approach of this, and started on a blank slate and decided to make use of the <code>DynamicObjectConverter</code> which was introduced back in <a href="https://github.com/dotnet/runtime/pull/42097" rel="nofollow noreferrer">late 2020</a> to the <code>System.Text.Json</code> library.</p>
<p>The goal is to handle a PATCH operation to an existing JSON object.</p>
<p>For example from an existing JSON document with:</p>
<pre class="lang-json prettyprint-override"><code>{
"id": "e001",
"name": "foo"
}
</code></pre>
<p>with a patch operation of</p>
<pre class="lang-json prettyprint-override"><code>{ "name": "bar" }
</code></pre>
<p>the result:</p>
<pre class="lang-json prettyprint-override"><code>{
"id": "e001",
"name": "bar"
}
</code></pre>
<p>I also wanted to be able to handle adding additional new properties to a collection of existing JSON documents (as a sweeping task) making patch updates across various documents that all have different schemas (hail schema-less DBs!). Such as adding a <code>metadata</code>, or <code>isHidden</code> property to all JSON documents.</p>
<h2>The Extension Class</h2>
<p>There are 5 methods to the extension class.</p>
<blockquote>
<p>This question contains the complete class, you just need to put these 5 methods into a single <code>static class</code>.</p>
</blockquote>
<h5>DynamicUpdate() Method</h5>
<p>The main extension method that extends the <code>IDictionary<string, object</code> type (which is commonly found in our code as <code>ExpandoObject</code> type implementation)</p>
<pre class="lang-csharp prettyprint-override"><code>internal static JsonElement DynamicUpdate(
this IDictionary<string, object> entity,
JsonDocument doc,
bool addPropertyIfNotExists = false,
bool useTypeValidation = true,
JsonDocumentOptions options = default)
{
if (doc == null) throw new ArgumentNullException(nameof(doc));
if (doc.RootElement.ValueKind != JsonValueKind.Object)
throw new NotSupportedException("Only objects are supported.");
foreach (JsonProperty jsonProperty in doc.RootElement.EnumerateObject())
{
string propertyName = jsonProperty.Name;
JsonElement newElement = doc.RootElement.GetProperty(propertyName);
bool hasProperty = entity.TryGetValue(propertyName, out object oldValue);
// sanity checks
JsonElement? oldElement = null;
if (oldValue != null)
{
if (!oldValue.GetType().IsAssignableTo(typeof(JsonElement)))
throw new ArgumentException($"Type mismatch. Must be {nameof(JsonElement)}.", nameof(entity));
oldElement = (JsonElement)oldValue;
}
if (!hasProperty && !addPropertyIfNotExists) continue;
entity[propertyName] = GetNewValue(
oldElement, newElement, propertyName,
addPropertyIfNotExists, useTypeValidation, options);
}
using JsonDocument finalDoc = JsonDocument.Parse(JsonSerializer.Serialize(entity));
return finalDoc.RootElement.Clone();
}
</code></pre>
<h5>GetNewValue() Method</h5>
<p>This method gets the value (recursively for object properties) and also deals with validation based on the passed in options as arguments.</p>
<pre class="lang-csharp prettyprint-override"><code>private static JsonElement GetNewValue(
JsonElement? oldElementNullable,
JsonElement newElement,
string propertyName,
bool addPropertyIfNotExists,
bool useTypeValidation,
JsonDocumentOptions options)
{
if (oldElementNullable == null) return newElement.Clone();
JsonElement oldElement = (JsonElement)oldElementNullable;
// type validation
if (useTypeValidation && !IsValidType(oldElement, newElement))
throw new ArgumentException($"Type mismatch. The property '{propertyName}' must be of type '{oldElement.ValueKind}'.", nameof(newElement));
// recursively go down the tree for objects
if (oldElement.ValueKind == JsonValueKind.Object)
{
string oldJson = oldElement.GetRawText();
string newJson = newElement.ToString();
IDictionary<string, object> entity = JsonSerializer.Deserialize<ExpandoObject>(oldJson);
return DynamicUpdate(entity, newJson, addPropertyIfNotExists, useTypeValidation, options);
}
return newElement.Clone();
}
</code></pre>
<h5>IsValidType() Method</h5>
<p>This method handles the validation for types. (i.e. trying to replace a <code>string</code> with an <code>int</code> will return false.</p>
<pre class="lang-csharp prettyprint-override"><code>private static bool IsValidType(JsonElement oldElement, JsonElement newElement)
{
if (newElement.ValueKind == JsonValueKind.Null) return true;
// 'true' --> 'false'
if (oldElement.ValueKind == JsonValueKind.True && newElement.ValueKind == JsonValueKind.False) return true;
// 'false' --> 'true'
if (oldElement.ValueKind == JsonValueKind.False && newElement.ValueKind == JsonValueKind.True) return true;
// type validation
return (oldElement.ValueKind == newElement.ValueKind);
}
</code></pre>
<h5>IsValidJsonPropertyName() Method</h5>
<p>This method just a quick way to make sure there isn't a totally malformed property name.</p>
<pre class="lang-csharp prettyprint-override"><code>private static bool IsValidJsonPropertyName(string value)
{
if (string.IsNullOrEmpty(value)) return false;
// this is validation for our specific use case (C#)
// note that the official docs don't prohibit this though.
// https://datatracker.ietf.org/doc/html/rfc7159
for (int i = 0; i < value.Length; i++)
{
if (char.IsLetterOrDigit(value[i])) continue;
switch (value[i])
{
case '-':
case '_':
default:
break;
}
}
return true;
}
</code></pre>
<h5>Overloaded DynamicUpdate() Method</h5>
<p>An overloaded method so that passing in a JSON string is also possible for tests, etc.</p>
<pre class="lang-csharp prettyprint-override"><code>internal static JsonElement DynamicUpdate(
this IDictionary<string,
object> entity,
string patchJson,
bool addPropertyIfNotExists = false,
bool useTypeValidation = true,
JsonDocumentOptions options = default)
{
using JsonDocument doc = JsonDocument.Parse(patchJson, options);
return DynamicUpdate(entity, doc, addPropertyIfNotExists, useTypeValidation, options);
}
</code></pre>
<h2>How to use it</h2>
<p>Here is a sample snippet to test the extension method.</p>
<pre class="lang-csharp prettyprint-override"><code>string original = @"{""foo"":[1,2,3],""parent"":{""childInt"":1},""bar"":""example""}";
string patch = @"{""foo"":[9,8,7],""parent"":{""childInt"":9,""childString"":""woot!""},""bar"":null}";
Console.WriteLine(original);
// change this value to see the different types of patching method
bool addPropertyIfNotExists = false;
ExpandoObject expandoObject = JsonSerializer.Deserialize<ExpandoObject>(original);
// patch it!
expandoObject.DynamicUpdate(patch, addPropertyIfNotExists);
Console.WriteLine(JsonSerializer.Serialize(expandoObject));
</code></pre>
<blockquote>
<p><strong>Note:</strong> For the example above, the JSON is a string, but in practice reading in the document comes as some form of a UTF8 binary stream, which is where the <code>JsonDocument</code> shines.</p>
</blockquote>
<blockquote>
<p><strong>Important Note:</strong> Keep in mind that property names are case sensitive, so <code>foo</code> and <code>FoO</code> are unique and valid property names. It would be trivial to add a method to support ignoring case, but in my use-case this is the desired use.</p>
</blockquote>
<h1>Question for code review</h1>
<p>It would be interesting to know if there are any better design patterns that can minimize the back-and-fourth of serializing the inner objects and materializing it as a <code>JsonElement</code> that happens in recursive section of the code found in the <code>GetNewValue()</code> method.</p>
<p>For a large object nested JSON object, there is a lot of packing up and cloning of the <code>JsonElement</code> struct. It's quite uncommon to have very "deep" properties in the wild, but I can't help but wonder if there is a smarter approach to this.</p>
<p>Of course, any other feedback is welcome --- always looking to improve the code!</p>
|
[] |
[
{
"body": "<h1>1. Optimize</h1>\n<h2>1.1 Get rid of clones</h2>\n<p>Let's take a look what JsonElement::Clone() does. See <a href=\"https://github.com/dotnet/runtime/blob/b2d5d63e5194265e18c448d7f014585bf0bad2d4/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonElement.cs#L1440\" rel=\"nofollow noreferrer\">JsonElement::Clone()</a>.\nIt calls <a href=\"https://github.com/dotnet/runtime/blob/b2d5d63e5194265e18c448d7f014585bf0bad2d4/src/libraries/System.Text.Json/src/System/Text/Json/Document/JsonDocument.cs#L793\" rel=\"nofollow noreferrer\">JsonDocument:CloneElement(int index)</a>. Which creates new internal JsonDocument & what's important: it doesn't disposes that document. The reason why you need to call <code>Clone()</code> - it's because you call <code>Dispose()</code> (via <code>using statement</code>). So if we stop calling <code>Dispose()</code>, we don't need to call <code>Clone()</code></p>\n<p>Well, you still need to call clone on <code>doc.RootElement</code>, because <code>doc</code> is passed outside - but it's only once in DynamicUpdate.</p>\n<p>See <a href=\"https://github.com/vlova/CodeReviewPatchJson265739/commit/ad2f79b2ed707a6f3564cbb7ec86126e9ceb5cc7\" rel=\"nofollow noreferrer\">diff</a></p>\n<h2>1.2 Get rid of serialize/deserialize newElement</h2>\n<p>So, you have next code:</p>\n<pre><code>string newJson = newElement.ToString();\n…\nreturn DynamicUpdate(entity, newJson, addPropertyIfNotExists, useTypeValidation, options);\n</code></pre>\n<p>So, here we creating <code>newJson</code> from existing data (<code>newElement</code>), because <code>DynamicUpdate</code> accept either <code>string</code> or <code>JsonDocument</code>, but not <code>JsonElement</code>. This can be easily fixed, because your overloads actually doesn't really need full <code>JsonDocument</code> to be present.</p>\n<p>We can also notice that after such refactoring we don't need to pass <code>JsonDocumentOptions options</code> everywhere.</p>\n<p>See <a href=\"https://github.com/vlova/CodeReviewPatchJson265739/commit/d63a11152025b418dae740ffb701c92d804aa7a0\" rel=\"nofollow noreferrer\">diff</a></p>\n<h2>1.3 Get rid of serialize/deserialize oldElement</h2>\n<p>So, now we have next code</p>\n<pre><code>string oldJson = oldElement.GetRawText();\nIDictionary<string, object> entity = JsonSerializer.Deserialize<ExpandoObject>(oldJson);\nreturn DynamicUpdate(entity, newElement, addPropertyIfNotExists, useTypeValidation);\n</code></pre>\n<p>So, <code>DynamicUpdate</code> requires us to pass <code>ExpandoObject</code> as entity. And what we have - is <code>JsonElement</code>.</p>\n<p>There are no way to get rid of such conversion. But we are doing too much during in our existing implementation - serializing & deserializing. What we need - is to touch our top-level properties only (because nested properties will be touched on other rounds of serializing). Let's write our manual implementation:</p>\n<pre><code>private static ExpandoObject ToExpandoObject(JsonElement jsonElement)\n{\n var obj = new ExpandoObject();\n foreach (var property in jsonElement.EnumerateObject())\n {\n (obj as IDictionary<string, object>)[property.Name] = property.Value;\n }\n\n return obj;\n}\n</code></pre>\n<p>See <a href=\"https://github.com/vlova/CodeReviewPatchJson265739/commit/a3f735f929bb99751ab06e7945944337611054e7#diff-e8c9f036b174ca0668defb35667f7482834224e2e14492830e893dcd2be29159\" rel=\"nofollow noreferrer\">diff</a></p>\n<h1>1.4 Get rid of serialize/deserialize entity</h1>\n<p>So, you have next lines:</p>\n<pre><code>JsonDocument finalDoc = JsonDocument.Parse(JsonSerializer.Serialize(entity));\nreturn finalDoc.RootElement;\n</code></pre>\n<p>Why do we need that? Because entity is <code>IDictionary<string, object></code> and inside of <code>GetNewValue</code> we return either <code>JsonElement newElement</code> or updated object, which can't be be <code>JsonElement</code>.</p>\n<p>Let's use <code>object</code> as return type so we don't need to convert anything.</p>\n<p>See <a href=\"https://github.com/vlova/CodeReviewPatchJson265739/commit/e5f142906ac55a12cc72dc934634bffc2a345295\" rel=\"nofollow noreferrer\">diff</a></p>\n<h1>2. Refactor</h1>\n<h2>2.1 Get rid of returning data</h2>\n<p>Returning data violates <a href=\"https://www.wikiwand.com/en/Command%E2%80%93query_separation\" rel=\"nofollow noreferrer\">CQS</a>. And in our case — for nothing.</p>\n<p>Each overload of <code>DynamicUpdate</code> returns data. In two cases (when accepting <code>string</code> or <code>JsonDocument</code>) it's not required. In third case (<code>JsonElement</code>) we "need" that because of next contents in <code>GetNewValue</code>:</p>\n<pre><code>return DynamicUpdate(ToExpandoObject(oldElement), newElement, addPropertyIfNotExists, useTypeValidation);\n</code></pre>\n<p>Well, but <code>DynamicUpdate</code> modifies <code>ToExpandoObject(oldElement)</code>, so we can return it:</p>\n<pre><code>var oldObject = ToExpandoObject(oldElement);\nDynamicUpdate(oldObject, newElement, addPropertyIfNotExists, useTypeValidation);\nreturn oldObject;\n</code></pre>\n<p>See <a href=\"https://github.com/vlova/CodeReviewPatchJson265739/commit/815509bea840901f4cc0559082df221957185f4d#diff-e8c9f036b174ca0668defb35667f7482834224e2e14492830e893dcd2be29159\" rel=\"nofollow noreferrer\">diff</a></p>\n<h2>2.2 Introduce DynamicUpdateOptions</h2>\n<p>So, you have the next parameters:</p>\n<pre><code>bool addPropertyIfNotExists = false,\nbool useTypeValidation = true\n</code></pre>\n<p>These parameters are options/settings. They should be moved into separate class in order to preserve maintainability. Just imagine what will happen in case if you need to add one more option. This also will reduce the number of parameters from 4-5 to 3-4. See <a href=\"https://refactoring.guru/introduce-parameter-object\" rel=\"nofollow noreferrer\">Refactoring: introduce parameter object</a></p>\n<p>See <a href=\"https://github.com/vlova/CodeReviewPatchJson265739/commit/b38a51d6142330d7d2f8d146cca16936d5be34ef#diff-e8c9f036b174ca0668defb35667f7482834224e2e14492830e893dcd2be29159\" rel=\"nofollow noreferrer\">diff</a></p>\n<h1>2.3 Extract resolving JsonProperty</h1>\n<p>Inside of DynamicUpdate you have next lines:</p>\n<pre><code>bool hasProperty = entity.TryGetValue(propertyName, out object oldValue);\n\n// sanity checks\nJsonElement? oldElement = null;\nif (oldValue != null)\n{\n if (!oldValue.GetType().IsAssignableTo(typeof(JsonElement)))\n throw new ArgumentException($"Type mismatch. Must be {nameof(JsonElement)}.", nameof(entity));\n oldElement = (JsonElement)oldValue;\n}\n</code></pre>\n<p>These lines are not good, because they pollute code & violate <a href=\"http://principles-wiki.net/principles:single_level_of_abstraction\" rel=\"nofollow noreferrer\">Single level of abstraction principle</a></p>\n<p>So we will extract this code to new <code>GetJsonProperty</code> method. In order to do that we also need to introduce <code>var hasProperty = entity.ContainsKey(propertyName);</code> inside of <code>DynamicUpdate</code> - because we don't want to <code>GetJsonProperty</code> to return both object & flag.</p>\n<p>See <a href=\"https://github.com/vlova/CodeReviewPatchJson265739/commit/9843c3d86a27ce1332888a019fc03d3c1a27903f#diff-e8c9f036b174ca0668defb35667f7482834224e2e14492830e893dcd2be29159\" rel=\"nofollow noreferrer\">diff</a></p>\n<h1>2.3.1 Reduce nesting in GetJsonProperty</h1>\n<p>We have nested <code>if</code> inside of getting property. This is not good.\nNow, when we have separate method, we can easily refactor it.\nLet's apply <a href=\"https://refactoring.guru/replace-nested-conditional-with-guard-clauses\" rel=\"nofollow noreferrer\">Refactoring "Replace nested conditional with guard clauses"</a>:</p>\n<pre><code>entity.TryGetValue(propertyName, out object oldValue);\n\nif (oldValue == null)\n return null;\n\nif (!oldValue.GetType().IsAssignableTo(typeof(JsonElement)))\n throw new ArgumentException($"Type mismatch. Must be {nameof(JsonElement)}.", nameof(entity));\n\nreturn (JsonElement)oldValue;\n</code></pre>\n<p>See <a href=\"https://github.com/vlova/CodeReviewPatchJson265739/commit/89ee88b8ddecd51c4d8561ac7a374667a7597447#diff-e8c9f036b174ca0668defb35667f7482834224e2e14492830e893dcd2be29159\" rel=\"nofollow noreferrer\">diff</a></p>\n<h1>2.4 Avoid executing redundant code</h1>\n<p>So, your code has next nice line:</p>\n<pre><code>if (!hasProperty && !updateOptions.AddPropertyIfNotExists) continue;\n</code></pre>\n<p>But this line is executed after resolving <code>newElement</code> and <code>oldElement</code>.\nLet's fix it!</p>\n<p>See <a href=\"https://github.com/vlova/CodeReviewPatchJson265739/commit/c193f61c8cc901970fddd46118bb95849d4c9858#diff-e8c9f036b174ca0668defb35667f7482834224e2e14492830e893dcd2be29159\" rel=\"nofollow noreferrer\">diff</a></p>\n<h1>2.5 Do not expose API over IDictionary<string, object></h1>\n<p>So, you built extension over <code>IDictionary<string, object></code>.\nBut your code assumes that nested objects will be of type JsonElement.\nWhat if we will use your code over Newtonsoft.Json deserializer?\nWhat if we will use your code over JsonConverter which performs nested deserialization of ExpandObject (like DynamicJsonConverter in <a href=\"https://www.codetd.com/en/article/8462216\" rel=\"nofollow noreferrer\">https://www.codetd.com/en/article/8462216</a>)?</p>\n<p>Well, your code will fail in runtime. This is really bad for you.</p>\n<p>Instead public instances of this method should accept either <code>JsonDocument</code> or <code>string</code> and return updated content. As we don't know required parsing options, it's better to accept <code>JsonDocument</code>.</p>\n<p>We will return <code>IDictionary<string, object></code> from <code>DynamicUpdate</code>. Maybe it's not totally good idea, because ExpandoObject will contain JsonElements inside — and this is not something that we will expect to see in IDictionary. But I'm afraid that we will do too much work in case if we will choose to return <code>JsonDocument</code> or <code>string</code>.</p>\n<p>By this we also made version of method without side-effects - and this is much way better than previous.</p>\n<p>By this we also can simplify contents of <code>GetNewValue</code>.</p>\n<p>See <a href=\"https://github.com/vlova/CodeReviewPatchJson265739/commit/c8ac91834f633179c1f6ab45bb143b812c4f4ed5#diff-e8c9f036b174ca0668defb35667f7482834224e2e14492830e893dcd2be29159\" rel=\"nofollow noreferrer\">diff</a></p>\n<h1>3. Support more cases</h1>\n<h1>3.1 Support arrays</h1>\n<p>I'm not going to provide code for it. Probably you already know that your implementation doesn't works with arrays properly.</p>\n<h1>4. Beautify</h1>\n<h2>4.1 Naming</h2>\n<ol>\n<li><code>DynamicUpdate</code> → <code>GetPatched</code> / <code>Patch</code>; and:\n<ul>\n<li><code>DynamicUpdateOptions</code> → <code>PatchOptions</code>\n-<code>updateOptions</code> → <code>patchOptions</code></li>\n</ul>\n</li>\n<li><code>entity</code> → <code>toPatch</code></li>\n<li><code>patchJson</code>, <code>doc</code> → <code>patch</code></li>\n<li><code>convertedEntity</code> → <code>patched</code></li>\n<li><code>jsonProperty</code> → <code>patchChildProp</code>:\n<ul>\n<li>Also, <code>newElement</code> is dropped in favor of <code>patchChildProp.Value</code></li>\n</ul>\n</li>\n<li><code>hasProperty</code> → <code>toPatchHasProperty</code></li>\n<li>Inside of <code>DynamicUpdate</code> (which is <code>Patch</code> now): <code>oldElement</code> → <code>toPatchChild</code></li>\n<li><code>GetNewValue</code> → <code>GetPatched</code>, because well, it's really the same as our main method</li>\n<li>Inside of <code>GetNewValue</code> (which is now <code>GetPatched</code>): <code>oldElementNullable</code> → <code>documentToPatch</code>, <code>oldElement</code> → <code>original, </code>oldElement<code>→ </code>newElement<code>→</code>patch`</li>\n</ol>\n<p>See <a href=\"https://github.com/vlova/CodeReviewPatchJson265739/commit/8c1fa1eeaf9b7274053132c411dfd025ce44a0d3#diff-e8c9f036b174ca0668defb35667f7482834224e2e14492830e893dcd2be29159\" rel=\"nofollow noreferrer\">diff</a></p>\n<h2>4.2 var</h2>\n<p>Your code contains variables with explicit types even when they are obvious. See:</p>\n<pre><code>JsonDocument doc = JsonDocument.Parse(patch, jsonDocumentOptions);\nJsonElement oldElement = (JsonElement)toPatch;\n</code></pre>\n<p>Some code styles doesn't allow it, but let's leverage <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/var\" rel=\"nofollow noreferrer\">var</a> everywhere.</p>\n<p>See <a href=\"https://github.com/vlova/CodeReviewPatchJson265739/commit/1733a22bcf31c600787b18a7d6b15d1e96809b5b#diff-e8c9f036b174ca0668defb35667f7482834224e2e14492830e893dcd2be29159\" rel=\"nofollow noreferrer\">diff</a></p>\n<h2>4.3 Comments</h2>\n<p>See <a href=\"https://stackoverflow.blog/2021/07/05/best-practices-for-writing-code-comments/\">Best practices for writing code comments</a></p>\n<p>Inside of your extensions all comments are duplicating code:</p>\n<pre><code>// type validation\nif (patchOptions.UseTypeValidation && !IsValidType(oldElement, patch))\n</code></pre>\n<p>and</p>\n<pre><code>// recursively go down the tree for objects\nif (oldElement.ValueKind == JsonValueKind.Object)\n{\n return GetPatched(oldElement, patch, patchOptions);\n}\n</code></pre>\n<p>Let's drop it.</p>\n<h2>4.4 if/for consistent formatting</h2>\n<p>There are 3 styles of formatting inside of your codebase. You should pick one. I suggest to pick next as most typical for C#-codebase:</p>\n<pre><code>if (…) {\n …\n}\n</code></pre>\n<p>See <a href=\"https://github.com/vlova/CodeReviewPatchJson265739/commit/639a094bc64821087b459542b0e5e561f374de59#diff-e8c9f036b174ca0668defb35667f7482834224e2e14492830e893dcd2be29159\" rel=\"nofollow noreferrer\">diff</a></p>\n<h2>4.5 Consistent null-guards</h2>\n<p>In some cases you have null-guards, in some not.\nLet's do</p>\n<p>See <a href=\"https://github.com/vlova/CodeReviewPatchJson265739/commit/c5849f560fe5c8e6c43e5d9615462460dec317bd#diff-e8c9f036b174ca0668defb35667f7482834224e2e14492830e893dcd2be29159\" rel=\"nofollow noreferrer\">diff</a></p>\n<h1>Alternative solutions</h1>\n<ol>\n<li>Consider implementing <a href=\"https://docs.microsoft.com/en-us/aspnet/core/web-api/jsonpatch?view=aspnetcore-5.0\" rel=\"nofollow noreferrer\">JSON Patch</a></li>\n<li>Consider the next idea:\n<ol>\n<li>Deserialize json into IDictionary<> in deep manner. See <a href=\"https://www.codetd.com/en/article/8462216\" rel=\"nofollow noreferrer\">https://www.codetd.com/en/article/8462216</a>.\n<pre><code>IDictionary<> DeserializeDynamicDeep(string json)` {\n …\n}\n</code></pre>\n</li>\n<li>Write method that merges deeply two IDictionary<>.\n<pre><code>IDictionary<> GetPatched(IDictionary<> toPatch, IDictionary<> patch) {\n …\n}\n</code></pre>\n</li>\n<li>Write sugar method that allows to work you with json/streams\n<pre><code>public static string GetPatched(string toPatch, string patch)\n => GetPatched(\n DeserializeDynamicDeep(toPatch),\n DeserializeDynamicDeep(patch)\n );\n</code></pre>\n</li>\n</ol>\n</li>\n</ol>\n<h1>Final solution</h1>\n<p>You can see it on <a href=\"https://github.com/vlova/CodeReviewPatchJson265739/blob/master/CodeReviewPatchJson265739/JsonExtensions.cs\" rel=\"nofollow noreferrer\">github/CodeReviewPatchJson265739</a> or directly here.</p>\n<p>Code</p>\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Dynamic;\nusing System.Text.Json;\n\nnamespace CodeReviewPatchJson265739\n{\n public static class JsonExtensions\n {\n public static IDictionary<string, object> GetPatched(\n this JsonDocument toPatch,\n string patch,\n PatchOptions patchOptions = default,\n JsonDocumentOptions jsonDocumentOptions = default)\n {\n if (toPatch == null)\n {\n throw new ArgumentNullException(nameof(toPatch));\n }\n\n if (patch == null)\n {\n throw new ArgumentNullException(nameof(patch));\n }\n\n using var doc = JsonDocument.Parse(patch, jsonDocumentOptions);\n return GetPatched(toPatch, doc, patchOptions);\n }\n\n public static IDictionary<string, object> GetPatched(\n this JsonDocument toPatch,\n JsonDocument patch,\n PatchOptions patchOptions = default)\n {\n if (toPatch == null)\n {\n throw new ArgumentNullException(nameof(toPatch));\n }\n\n if (patch == null)\n {\n throw new ArgumentNullException(nameof(patch));\n }\n\n return GetPatched(toPatch.RootElement.Clone(), patch.RootElement.Clone(), patchOptions);\n }\n\n private static IDictionary<string, object> GetPatched(\n JsonElement toPatch,\n JsonElement patch,\n PatchOptions patchOptions)\n {\n var patched = ToExpandoObject(toPatch);\n Patch(patched, patch, patchOptions);\n return patched;\n }\n\n private static void Patch(\n IDictionary<string, object> toPatch,\n JsonElement patch,\n PatchOptions patchOptions)\n {\n patchOptions ??= new PatchOptions();\n\n if (patch.ValueKind != JsonValueKind.Object)\n {\n throw new NotSupportedException("Only objects are supported.");\n }\n\n foreach (var patchChildProp in patch.EnumerateObject())\n {\n var propertyName = patchChildProp.Name;\n var toPatchHasProperty = toPatch.ContainsKey(propertyName);\n if (!toPatchHasProperty && !patchOptions.AddPropertyIfNotExists) continue;\n\n var toPatchChild = GetJsonProperty(toPatch, propertyName);\n toPatch[propertyName] = GetPatched(\n toPatchChild, patchChildProp.Value, propertyName,\n patchOptions);\n }\n }\n\n private static JsonElement? GetJsonProperty(IDictionary<string, object> entity, string propertyName)\n {\n entity.TryGetValue(propertyName, out var oldValue);\n\n if (oldValue == null)\n {\n return null;\n }\n\n if (!oldValue.GetType().IsAssignableTo(typeof(JsonElement)))\n {\n throw new ArgumentException($"Type mismatch. Must be {nameof(JsonElement)}.", nameof(entity));\n }\n\n return (JsonElement)oldValue;\n }\n\n private static object GetPatched(\n JsonElement? toPatch,\n JsonElement patch,\n string propertyName,\n PatchOptions patchOptions)\n {\n if (toPatch == null)\n {\n return patch;\n }\n\n var oldElement = (JsonElement)toPatch;\n\n if (patchOptions.UseTypeValidation && !IsValidType(oldElement, patch))\n {\n throw new ArgumentException($"Type mismatch. The property '{propertyName}' must be of type '{oldElement.ValueKind}'.", nameof(patch));\n }\n\n if (oldElement.ValueKind == JsonValueKind.Object)\n {\n return GetPatched(oldElement, patch, patchOptions);\n }\n\n return patch;\n }\n\n public class PatchOptions\n {\n public bool AddPropertyIfNotExists { get; set; } = false;\n\n public bool UseTypeValidation { get; set; } = true;\n }\n\n private static ExpandoObject ToExpandoObject(JsonElement jsonElement)\n {\n var obj = new ExpandoObject();\n foreach (var property in jsonElement.EnumerateObject())\n {\n (obj as IDictionary<string, object>)[property.Name] = property.Value;\n }\n\n return obj;\n }\n\n private static bool IsValidType(JsonElement oldElement, JsonElement newElement)\n {\n if (newElement.ValueKind == JsonValueKind.Null)\n {\n return true;\n }\n\n if (oldElement.ValueKind == JsonValueKind.True && newElement.ValueKind == JsonValueKind.False)\n {\n return true;\n }\n\n if (oldElement.ValueKind == JsonValueKind.False && newElement.ValueKind == JsonValueKind.True)\n {\n return true;\n }\n\n return (oldElement.ValueKind == newElement.ValueKind);\n }\n }\n}\n</code></pre>\n<p>Usage</p>\n<pre><code>string original = @"{""foo"":[1,2,3],""parent"":{""childInt"":1},""bar"":""example""}";\nstring patch = @"{""foo"":[9,8,7],""parent"":{""childInt"":9,""childString"":""woot!""},""bar"":null}";\nConsole.WriteLine(original);\n\n// change this value to see the different types of patching method\nbool addPropertyIfNotExists = false;\n\n// patch it!\nvar expandoObject = JsonDocument.Parse(original).GetPatched(patch, new JsonExtensions.PatchOptions\n{\n AddPropertyIfNotExists = addPropertyIfNotExists\n});\nConsole.WriteLine(JsonSerializer.Serialize(expandoObject));\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-13T10:54:23.177",
"Id": "266028",
"ParentId": "265739",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T15:24:06.610",
"Id": "265739",
"Score": "1",
"Tags": [
"c#",
"json",
"dynamic-programming"
],
"Title": "Patch a JSON object using dynamic / ExpandoObject with System.Text.Json"
}
|
265739
|
<p>I have been working with postgresql where I am trying to get information from database, update, exists and much more. I have created a context manager for commit and to close whenever it is in finished.</p>
<p>This project is about storing some variables (mostly regarding store and link)</p>
<pre class="lang-py prettyprint-override"><code>#!/usr/bin/python3
# -*- coding: utf-8 -*-
from typing import List, Set, Tuple
import pendulum
import psycopg2
import psycopg2.extras
from config import configuration
DATABASE_CONNECTION = {
"host": configuration.path.database.environment,
"database": configuration.postgresql.database,
"user": configuration.postgresql.user,
"password": configuration.postgresql.password,
}
ps_connection = psycopg2.connect(**DATABASE_CONNECTION)
class QuickConnection:
"""
Function that commits and closes when its done.
Rollbacks if an error happens
"""
def __init__(self):
self.ps_cursor = ps_connection.cursor(cursor_factory=psycopg2.extras.DictCursor)
ps_connection.autocommit = True
def __enter__(self):
return self.ps_cursor
def __exit__(self, err_type, err_value, traceback):
if err_type and err_value:
ps_connection.rollback()
self.ps_cursor.close()
return False
# ------------------------------------------------------------------------------- #
# Exists functions
# ------------------------------------------------------------------------------- #
def link_exists(store: str, link: str) -> bool:
query_params = {
"store": store,
"link": link
}
sql_query = "SELECT EXISTS (SELECT 1 FROM store_items WHERE store=%(store)s AND link=%(link)s);"
with QuickConnection() as ps_cursor:
ps_cursor.execute(sql_query, query_params)
exists, = ps_cursor.fetchone()
return exists
# ------------------------------------------------------------------------------- #
# Insert / Update / Delete / Return value from database
# ------------------------------------------------------------------------------- #
def store_exists(store: str) -> bool:
query_params = {
"store": store
}
sql_query = "INSERT INTO store_config (store) SELECT %(store)s WHERE NOT EXISTS (SELECT 1 FROM store_config WHERE store = %(store)s);"
with QuickConnection() as ps_cursor:
ps_cursor.execute(sql_query, query_params)
return bool(ps_cursor.rowcount)
def register_product(store: str, pageData) -> bool:
query_params = {
"store": store,
"name": pageData.name,
"link": pageData.link,
"image": pageData.image,
"visible": "yes",
"added_date": pendulum.now('Europe/Stockholm').format('YYYY-MM-DD HH:mm:ss.SSSSSS')
}
sql_query = "INSERT INTO store_items (store, name, link, image, visible, added_date) VALUES (%(store)s, %(name)s, %(link)s, %(image)s, %(visible)s, %(added_date)s);"
with QuickConnection() as ps_cursor:
ps_cursor.execute(sql_query, query_params)
return bool(ps_cursor.rowcount)
# ------------------------------------------------------------------------------- #
# Get all functions
# ------------------------------------------------------------------------------- #
def get_all_active_links(store: str) -> List[str]:
query_params = {
"store": store,
"visible": "yes"
}
sql_query = "SELECT link FROM store_items WHERE store = %(store)s AND visible = %(visible)s;"
with QuickConnection() as ps_cursor:
ps_cursor.execute(sql_query, query_params)
return [links["link"] for links in ps_cursor]
def get_feed_urls(store: str) -> List[str]:
query_params = {
"store": store
}
sql_query = "SELECT link FROM feed_urls WHERE store = %(store)s;"
with QuickConnection() as ps_cursor:
ps_cursor.execute(sql_query, query_params)
return [links["link"] for links in ps_cursor]
def get_all_stores() -> List[str]:
sql_query = "SELECT store FROM store_config;"
with QuickConnection() as ps_cursor:
ps_cursor.execute(sql_query)
return [stores["store"] for stores in ps_cursor]
</code></pre>
<p>I wonder if there is anything I could improve :)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T16:59:07.673",
"Id": "524920",
"Score": "1",
"body": "The title isn't very descriptive of what the code achieves and the description is quite brief. Please [edit] to the site standard, which is for the title to simply state the task accomplished by the code, and please expand the description. Please see [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask), as well as [How to get the best value out of Code Review: Asking Questions](https://codereview.meta.stackexchange.com/q/2436/120114) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T17:02:42.993",
"Id": "524921",
"Score": "0",
"body": "@SᴀᴍOnᴇᴌᴀ I have now updated the title :) I hope this should be fine"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T09:37:58.950",
"Id": "524956",
"Score": "0",
"body": "@ProtractorNewbie No, the title is too generic. Please follow out guidelines."
}
] |
[
{
"body": "<p><code>ps_connection</code> existing as a global is ungood. <code>QuickConnection</code> on its own seems like a reasonable way to spin up a cursor, but would be better-modelled with a connection instance that it owns as a member, not referring to a global. This would also (reasonably) require that your query methods accept a <code>QuickConnection</code> as a parameter.</p>\n<p>Consider using a connection pool instead of a single connection.</p>\n<pre><code> ps_connection.autocommit = True\n</code></pre>\n<p>seems counter to your goal of having a transaction-managed cursor that supports rollback. Don't you want autocommit to be disabled, and have a commit in your exit function if no errors are found?</p>\n<p>Whether by threading or coroutines, etc., it may be possible to have two <code>__enter__</code> calls on one <code>QuickConnection</code> before any exit is seen. You should protect against this by throwing on an enter when there is already an active cursor. If you need more than one cursor at a time, this context management approach on its own won't be practical.</p>\n<p><code>link_exists</code> is reasonable, but compare that to the similarly-named <code>store_exists</code> that does a very different operation. The latter needs to be renamed to indicate that it's effectively a fail-safe insert.</p>\n<pre><code>return [links["link"] for links in ps_cursor]\n</code></pre>\n<p>doesn't need to be a list comprehension, and you can make <code>get_all_active_links</code> a generator:</p>\n<pre><code>for link in ps_cursor:\n yield link['link']\n</code></pre>\n<p>This should stream results to the caller as they're loaded from the database, rather than jamming them all into memory at once.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T18:08:36.537",
"Id": "524923",
"Score": "0",
"body": "Hello! Thanks for the information - `ps_connection existing as a global is ungood. QuickConnection on its own....` Im not quite sure if I get this straight. The reason I have the `ps_connection` is to have the postgresql connected at all time but thats how I understood it. - and yes there is high chance that two+ threads could call the `__enter__` - Maybe there is no need of using context manager at all then? Would it be possible if I could get an example on how it could look like?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T18:09:02.270",
"Id": "524924",
"Score": "0",
"body": "Also regarding the link_exists and store. I understood and thank you for the improvements! Will get into it right away :) - However I believe `for link in ps_cursor:\n yield links['link']` should be `link['link']`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T18:17:20.530",
"Id": "524925",
"Score": "0",
"body": "PostgreSQL can still be connected at all times; the challenge at hand is all about object ownership. There's somewhere (we don't know where because you haven't shown us) in the stack that is expected to be long-lived and hold application context, and the connection object should be owned there rather than in the global namespace."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T18:22:53.773",
"Id": "524926",
"Score": "0",
"body": "Hmm I see. Well there is nothing I have hidden really and this is my whole code I am actually running. the idea was basically that I will run multiple threads that will call these different functions calls to the PostgreSQL e.g. `database.get_all_stores()` which returns all the stores that are in the database. My knowledge is abit too little to understand really what you meant regarding the ownership. If there is anything more specific you could tell me that I could provide, I would like too! :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T20:50:26.207",
"Id": "524930",
"Score": "0",
"body": "After been reading around, I saw that there is already in-built with statement for postgres [Postgresql](https://www.psycopg.org/docs/usage.html#with-statement) and I do think I could skip the whole thing with my own context manager and instead use that? This is what a final code I have done now. Would it be something you meant?https://hastebin.com/fiqefitaja.py"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T18:01:14.680",
"Id": "265745",
"ParentId": "265741",
"Score": "3"
}
},
{
"body": "<p>The more I look at the code and the more I think you could have used an <strong>ORM</strong>, for instance SQL Alchemy. And nothing stops you from building the same functions on top of the ORM. Your functions could be replaced by one-liner filter clauses. You would write something like:</p>\n<pre><code>store = session.query(Store).filter(Store.id=10)\n</code></pre>\n<p>This would get you one row (or none). The benefit of this approach is that you will always be dealing with rows whereas your functions have different declarations and return different types. The keyword here is <strong>consistency</strong>.</p>\n<p>To count stores you could do something like:</p>\n<pre><code>session.query(Store).count()\n</code></pre>\n<p>and you can still derive a boolean depending on whether count is zero or greater.</p>\n<p>All that code does nothing fancy, just filter data from tables on certain attributes or insert records. As pointed out by @Reinderien, transaction management is important and the whole point of using a DB class.</p>\n<p>But this is important when adding/updating more than one row in a single batch of related data. If you are adding only one row at a time, it doesn't make a difference - autocommit is implied.</p>\n<p>When inserting a new row, it would make sense to return the ID of newly created row... provided you have ID columns. If you're creating a new store, you might want to retrieve that ID to then add a bunch of products linked to that store by ID. And of course wrap the whole operation in a transaction, so that in case of failure the whole batch is rollbacked and you have no orphan records polluting the DB.</p>\n<p>But there doesn't seem to be a <strong>primary key</strong> in your tables and that is a problem. At least that's my assumption. How will you unambiguously differentiate stores or products that have the same name ? A good <strong>data model</strong> is important because performance depends on good design. A big DB with lots of records will not scale well. Searching will become slower. <strong>Indexes</strong> are always welcome but a sound table structure is still important.</p>\n<p>The point of using functions is to avoid <strong>repetition</strong> but you have not achieved this, in fact they all repeat the same stuff more or less:</p>\n<pre><code>with QuickConnection() as ps_cursor:\n ps_cursor.execute(sql_query, query_params)\n</code></pre>\n<p>So these functions do not bring any added value really. Or you should refactor your code to wrap the stuff that is repetitive in one function and reuse it. I am afraid you are going to add more and more functions, each designed to address a specific need. But that will only amplify repetition and make the code bigger for no benefit.</p>\n<p>You use <code>pendulum.now('Europe/Stockholm')</code> to record the creation date. But timestamps without timezone context are ambiguous.\nI would consider using a <a href=\"https://www.postgresql.org/docs/9.1/datatype-datetime.html\" rel=\"nofollow noreferrer\">timestamptz</a> datatype for the column. Then PG will store timestamps as UTC and you can render datetime values to the client in the desired timezone by applying proper offset (consider daylight saving time too).</p>\n<p>At some point you might change your time zone for whatever reason. For instance if you have a server and decide to host your site at a new location. The server will usually be preconfigured to the local TZ. Then the new datetime values will not have the same meaning as the older ones because the reference TZ is not the same. Hence the benefit of storing all datetime values as UTC.</p>\n<p>PG has a boolean type which would be a better candidate than string for the field "visible".</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T22:50:42.157",
"Id": "524932",
"Score": "0",
"body": "Thank you for the awesome review! It was very well information and funny thing! I was just reading about PeeWee which I believe could be a good suggestion to start look at and I do agree. I do believe I might have setup my database tables wrong and maybe from there I should start from. As you mentioned regarding primary key. My Key is a unique ID that increases of each insert row which is not good idea and instead the link should have been the P. key. I would need to rethink but thanks for the info about time to! Would never think about it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T14:02:22.150",
"Id": "524968",
"Score": "0",
"body": "I have now \"converted\" to PeeWee ORM If you have time I would love to get another codereview from you as you recommended me to use ORM. https://codereview.stackexchange.com/questions/265777/queries-using-orm-and-postgresql / Also I have not forgotten about the time date!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T22:42:26.550",
"Id": "265751",
"ParentId": "265741",
"Score": "2"
}
},
{
"body": "<p>Given that you're using Python 3, you can safely leave out the encoding line since the default encoding <em>is</em> UTF-8.</p>\n<pre><code>-*- coding: utf-8 -*-\n</code></pre>\n<p>Unless you work in a multi-encoding environment or the default encoding on your system is not utf8.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T05:59:05.667",
"Id": "265758",
"ParentId": "265741",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "265745",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T16:30:52.990",
"Id": "265741",
"Score": "2",
"Tags": [
"python-3.x",
"sql"
],
"Title": "Queries for storing and get information from postgreSQL"
}
|
265741
|
<p>I decided to make an extension for Spicetify (modified Spotify client). It generates a playlist of similar songs based on their average audio features.</p>
<pre><code>//@ts-check
// NAME: Feature Shuffle
// AUTHOR: CharlieS1103
// DESCRIPTION: Create a playlist based on the average features of a playlist
/// <reference path="../globals.d.ts" />
(function songstats() {
const {
CosmosAsync,
Player,
LocalStorage,
PlaybackControl,
ContextMenu,
URI
} = Spicetify;
if (!(CosmosAsync && URI)) {
setTimeout(songstats, 300)
return
}
const buttontxt = "Create Feature Based Playlist"
const average = (array) => array.reduce((a, b) => a + b) / array.length;
async function makePlaylist(uris) {
const uri = uris[0];
const uriObj = Spicetify.URI.fromString(uri);
const uriFinal = uri.split(":")[2]
const user = await CosmosAsync.get('https://api.spotify.com/v1/me')
const playlistitems = (await CosmosAsync.get('https://api.spotify.com/v1/playlists/' + uriFinal + '/tracks')).items.map(i => i.track.href);
const avrDanceability = [];
const avrTempo = [];
const avrEnergy = [];
const avrAcousticness = [];
const avrInstrumentalness = [];
const avrSpeechiness = [];
const avrLiveness = [];
var avr2Dance
var avr2Tempo
var avr2Energy
var avr2Acoustic
var avr2Intrumentalness
var avr2Speechiness
var avr2Liveness
for (i = 0; i < playlistitems.length; i++) {
var songuri = playlistitems[i].split("/")[5]
var res;
try {
res = await CosmosAsync.get('https://api.spotify.com/v1/audio-features/' + songuri);
} catch (error) {
//e
}
avrDanceability.push(Math.round(100 * res.danceability) / 100);
avrEnergy.push(Math.round(100 * res.energy) / 100);
avrAcousticness.push(Math.round(100 * res.acousticness) / 100);
avrInstrumentalness.push(Math.round(100 * res.instrumentalness) / 100);
avrSpeechiness.push(Math.round(100 * res.speechiness) / 100);
avrTempo.push(Math.round(100 * res.tempo) / 100);
avrLiveness.push(Math.round(100 * res.liveness) / 100);
}
avr2Dance = average(avrDanceability);
avr2Acoustic = average(avrAcousticness);
avr2Tempo = average(avrTempo)
avr2Energy = average(avrEnergy)
avr2Intrumentalness = average(avrInstrumentalness)
avr2Liveness = average(avrLiveness)
avr2Speechiness = average(avrSpeechiness)
const randomSongrequest = [];
for (var i = 0; i < 21; i++) {
const getRandomSongsArray = ['%25-%25', '-%25', '%25-%25', '-%25', '%25-%25', '-%25', '%25-%25', '-%25'];
const rndInt = Math.floor(Math.random() * 3) + 1
var ranSong = getRandomSongsArray[Math.floor(Math.random() * getRandomSongsArray.length)];
function randAlph(rndInt, ) {
const alphabet = "abcdefghijklmnopqrstuvwxyz"
const letters = []
for (var i = 0; i < rndInt; i++) {
const randomletter = alphabet[Math.floor(Math.random() * alphabet.length)]
letters.push(randomletter)
}
const string = letters.join("")
return (string)
}
const ranString = randAlph(rndInt)
const getRandomSongs = ranSong.replace("-", ranString)
const getRandomOffset = Math.floor(Math.random() * (600 - 1 + 1) + 1)
const url = "https://api.spotify.com/v1/search?q=" + getRandomSongs + '&offset=' + getRandomOffset + "&type=track&limit=1&market=US";
const randomSongrequestToAppend = (await CosmosAsync.get(url)).tracks.items.map(track => track.uri);
if (randomSongrequestToAppend[0] != undefined) {
let res2 = await CosmosAsync.get('https://api.spotify.com/v1/audio-features/' + randomSongrequestToAppend[0].split(":")[2]);
if (Math.round(100 * res2.liveness) / 100 >= avr2Liveness - 20 && Math.round(100 * res2.liveness) / 100 <= avr2Liveness + 20) {
if (res2.tempo >= avr2Tempo - 5 && res2.tempo <= avr2Tempo + 5) {
if (Math.round(100 * res2.instrumentalness) / 100 >= avr2Intrumentalness - 20 && Math.round(100 * res2.instrumentalness) / 100 <= avr2Intrumentalness + 20) {
if (Math.round(100 * res2.energy) / 100 >= avr2Energy - 20 && Math.round(100 * res2.energy) / 100 <= avr2Energy + 20) {
if (Math.round(100 * res2.danceability) / 100 >= avr2Dance - 20 && Math.round(100 * res2.danceability) / 100 <= avr2Dance + 20) {
randomSongrequest.push(randomSongrequestToAppend[0])
console.log("Song passed")
} else {
i--
}
} else {
i--
}
} else {
i--
}
} else {
i--
}
} else {
i--
}
} else {
i--
}
}
const newplaylist = await CosmosAsync.post('https://api.spotify.com/v1/users/' + user.id + '/playlists', {
name: 'New Playlist'
});
const playlisturi = newplaylist.uri.split(":")[2]
const addToPlaylist = CosmosAsync.post('https://api.spotify.com/v1/playlists/' + playlisturi + '/tracks', {
uris: randomSongrequest
});
}
function shouldDisplayContextMenu(uris) {
if (uris.length > 1) {
return false;
}
const uri = uris[0];
const uriObj = Spicetify.URI.fromString(uri);
if (uriObj.type === Spicetify.URI.Type.PLAYLIST_V2) {
return true;
}
return false;
}
const cntxMenu = new Spicetify.ContextMenu.Item(
buttontxt,
makePlaylist,
shouldDisplayContextMenu,
);
cntxMenu.register();
})();
</code></pre>
<p>The actual logistics of how it works doesn't matter that much as the main issue is it looking godawful; if you're interested in seeing how to make Spicetify extensions the only way to learn is to look at the spicetify-cli source code, and utilize already existing extensions' source code as reference.</p>
<p>The fact that there are no tutorials on Spicetify development, and the fact that I neglected to actually learn JavaScript combined to make this a hellish code.</p>
|
[] |
[
{
"body": "<ul>\n<li><p>Repeated code: <code>Math.round(num * 100) / 100</code> is constantly repeated. Extract it to a function</p>\n</li>\n<li><p>Nested <code>if</code> statements: You have an awful lot of nested <code>if</code> statements that could be one simple <code>if</code>:</p>\n<pre class=\"lang-js prettyprint-override\"><code>\nif (something) {\n if (somethingElse) {\n doStuff();\n } else {\n i--;\n }\n} else {\n i--;\n}\n</code></pre>\n<p>Can be rewritten as (in a much more readable way):</p>\n<pre class=\"lang-js prettyprint-override\"><code>if (something\n && somethingElse) {\n doStuff();\n} else {\n i--;\n}\n</code></pre>\n</li>\n<li><p>Unnecessary empty lines: Empty lines are useful if you wish the separate certain parts of the code. But if you add them to every single line, it just makes code harder to read. E.g.</p>\n<pre class=\"lang-js prettyprint-override\"><code>avr2Dance = average(avrDanceability);\n\navr2Acoustic = average(avrAcousticness);\n\navr2Tempo = average(avrTempo)\n\navr2Energy = average(avrEnergy)\n\navr2Intrumentalness = average(avrInstrumentalness)\n\navr2Liveness = average(avrLiveness)\n\navr2Speechiness = average(avrSpeechiness)\n</code></pre>\n<p>Is less readable than:</p>\n<pre class=\"lang-js prettyprint-override\"><code>avr2Dance = average(avrDanceability);\navr2Acoustic = average(avrAcousticness);\navr2Tempo = average(avrTempo)\navr2Energy = average(avrEnergy)\navr2Intrumentalness = average(avrInstrumentalness)\navr2Liveness = average(avrLiveness)\navr2Speechiness = average(avrSpeechiness)\n</code></pre>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T08:22:13.920",
"Id": "265763",
"ParentId": "265747",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T18:47:28.010",
"Id": "265747",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Spicetify extension to generate a playlist of songs with similar audio features"
}
|
265747
|
<p>I've tried to write a version of this problem where it's easy to adapt if there's an additional pair (e. g. Say Bazz for 7). Looking for general advice.</p>
<pre class="lang-ml prettyprint-override"><code>type word = Number of int | Vocable of string
let string_of_word = function
| Number n -> Int.to_string n
| Vocable v -> v
let fizzbuzz vocable_pairs n =
let rec aux acc = function
| [] -> acc
| (d, v) :: rest -> aux (if n % d = 0 then v :: acc else acc) rest
in
let res = aux [] vocable_pairs in
(if List.is_empty res then Number n else Vocable (String.concat res))
|> string_of_word
let (--) init term =
List.init (term - init) (( + ) init)
let fizzbuzzer = List.map ~f:(fizzbuzz [
(7,"Bazz");
(5,"Buzz");
(3,"Fizz");
])
let test = fizzbuzzer (1 -- 64)
</code></pre>
<p>Requires module <code>Base</code>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-05T20:14:21.137",
"Id": "265749",
"Score": "1",
"Tags": [
"fizzbuzz",
"ocaml"
],
"Title": "FizzBuzz in OCaml"
}
|
265749
|
<p>I have written basic insertion sort in java and I would request you to please spend some time on this code and give me your review of code. Is there anything I could have improved:</p>
<pre><code>package elementarySorts;
public class InsertionSort {
InsertionSort(int [] input_array){
System.out.println("Unsorted arrey:");
for(int elem:input_array) {
System.out.print(elem +" ");
}
sort(input_array);
}
public void sort(int [] unsorted_array) {
for(int i=0;i<unsorted_array.length;i++) {
for(int j=i;j>=1;j--) {
if(unsorted_array[j]<unsorted_array[j-1]) {
this.exchange(unsorted_array, j, j-1);
}
}
}
System.out.println("\nsorted arrey:");
for(int elem:unsorted_array) {
System.out.print(elem + " ");
}
}
public void exchange(int [] inArray, int index1,int index2) {
int temp=inArray[index1];
inArray[index1]=inArray[index2];
inArray[index2]=temp;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int [] arr= {10,20,1,3,56,34,23};
InsertionSort insort = new InsertionSort(arr);
}
}
</code></pre>
<p>Hoping to hear your feedback.</p>
|
[] |
[
{
"body": "<blockquote>\n<pre><code> InsertionSort(int [] input_array){\n System.out.println("Unsorted arrey:");\n for(int elem:input_array) {\n System.out.print(elem +" ");\n }\n sort(input_array);\n }\n</code></pre>\n</blockquote>\n<p>This is a bad use of a constructor. This code should be moved into the <code>main</code> method.</p>\n<p>Some quick rules of thumb:</p>\n<ol>\n<li>Don't produce output in a constructor (except for temporary debugging purposes).</li>\n<li><a href=\"https://stackoverflow.com/q/18049710/6660678\">Don't perform actions in a constructor.</a> Instead, perform the actions outside and pass the results to the constructor.</li>\n</ol>\n<p>There may be circumstances where it is appropriate to violate these rules of thumb. But as a practical matter, if that happens, you should have comments explaining why it is necessary. In this case, I would say that it simply is not.</p>\n<blockquote>\n<pre><code> System.out.println("\\nsorted arrey:");\n for(int elem:unsorted_array) {\n System.out.print(elem + " ");\n }\n</code></pre>\n</blockquote>\n<p>Again, this should be done in the <code>main</code> method, not as part of the sorting process. Your method is doing two things. It's better practice to have it only do one thing.</p>\n<p>Nitpick: you misspelled array in the <code>println</code>.</p>\n<blockquote>\n<pre><code> }\n public void sort(int [] unsorted_array) {\n</code></pre>\n</blockquote>\n<p>This would be easier to read if there was a space between the closing <code>}</code> and the next method.</p>\n<pre><code> }\n\n public static void sort(int [] unsorted_array) {\n</code></pre>\n<p>It's also better practice to declare methods that do not change state to <code>static</code> (which means that it can't change state).</p>\n<p>Putting this and other tweaks together:</p>\n<pre><code>class InsertionSorter {\n\n public static void exchange(int[] data, int to, int from) {\n int temp = data[from];\n data[from] = data[to];\n data[to] = temp;\n }\n\n public static void sort(int[] data) {\n for (int i = 1; i < data.length; i++) {\n for (int j = i; j > 0; j--) {\n if (data[j] < data[j - 1]) {\n exchange(data, j, j - 1);\n }\n }\n }\n }\n\n public static void main(String[] args) {\n int[] data = { 10, 20, 1, 3, 56, 34, 23 };\n System.out.println("Unsorted array: " + Arrays.toString(data));\n sort(data);\n System.out.println("Sorted array: " + Arrays.toString(data));\n }\n\n}\n</code></pre>\n<p>We don't need to start the outer loop with 0, as the inner loop does nothing in that case. So we can start with 1.</p>\n<p>This uses the built-in <code>Arrays.toString</code> rather than manually building your own.</p>\n<p>Your class was not an insertion sort itself. Instead, it was the thing that did the sort. So I renamed it.</p>\n<p>Algorithmically, it would probably be more efficient to say</p>\n<pre><code> public static void sort(int[] data) {\n for (int i = 1; i < data.length; i++) {\n int j = i - 1;\n for (; (j >= 0) && (data[i] < data[j]); j--) {\n }\n j++;\n\n if (i > j) {\n int temp = data[i];\n System.arraycopy(data, j, data, j + 1, i - j);\n data[j] = temp;\n }\n }\n }\n</code></pre>\n<p>That changes the loop to just find the correct position and then moves all the elements at once rather than moving each twice. I haven't tested it, but that seems like it should be more efficient. It also may be more efficient to use <code>System.arraycopy</code> rather than doing it manually.</p>\n<p>It also takes advantage of the fact that the array is sorted to stop looking once it has found the correct position. Your version will continue comparing even though it will always be false.</p>\n<p>Of course, this is all reinventing the wheel. The simplest sort would be just</p>\n<pre><code> Arrays.sort(data);\n</code></pre>\n<p>That would be easier to implement and almost certainly faster. But I'm assuming that you already knew that and wanted to implement your own.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T05:18:57.183",
"Id": "265756",
"ParentId": "265752",
"Score": "2"
}
},
{
"body": "<h2>Naming</h2>\n<p>A few comments on naming, in addition to mdfst13's review:</p>\n<p>Packages should be named in a structured manner to avoid name collisions. The recommended way is to use some domain that you are associated to, e.g.</p>\n<pre><code>package com.stackexchange.gss.elementarySorts;\n</code></pre>\n<p>Java source code typically doesn't use underscores in names (with one exception: <code>static final</code> constants), so <code>unsorted_array</code> should better be named <code>unsortedArray</code>.</p>\n<p>That name <code>unsorted_array</code> is misleading, as after the <code>sort()</code> call, its contents are sorted. So, IMHO <code>arrayToBeSorted</code> would be a better name, as that also hints at the fact that the array gets modified by the method, instead of returning a sorted copy of the original array.</p>\n<h2>No Work in constructors</h2>\n<p>I'm not completely in line with a rigorous "no actions in constructors" rule, but in your case it applies.</p>\n<p>You class you've written can be understood as a "worker" specialized in the sorting of arrays. When constructing such a worker, you should prepare everything necessary for fulfilling such a task, and not have him fulfill such a task during construction. So, having the constructor already sort an array violates that rule.</p>\n<p>Look at it from a caller's point of view (a sorting class hardly ever is used on its own, but as a helper within a more complex program). If you need to sort all rows of a 2-dimensional matrix, with your current class you can't write it the "logical" way:</p>\n<pre><code>int[][] matrix = ...;\n\nInsertionSort sorter = new InsertionSort();\nfor (int rownum=0; rownum<matrix.length; rownum++) {\n int[] row = matrix[rownum];\n sorter.sort(row);\n}\n</code></pre>\n<p>Instead, you have to write:</p>\n<pre><code>int[][] matrix = ...;\n\nInsertionSort sorter = new InsertionSort(matrix[0]);\nfor (int rownum = 1; rownum < matrix.length; rownum++) {\n int[] row = matrix[rownum];\n sorter.sort(row);\n}\n</code></pre>\n<p>This is weird, not only does it treat the first row differently than the following ones, but it also runs the risk of an <code>ArrayIndexOutOfBoundsException</code>, if the matrix has zero rows.</p>\n<p>When creating a class, the structure should follow these guidelines:</p>\n<ul>\n<li>What are the tasks of a class instance? These tasks should become methods of the class.</li>\n<li>What needs to be prepared so a class instance can fulfill its tasks? That should go into the constructor (even if this means to do some computation, and that's where I disagree with the "no actions in constructors" rule).</li>\n</ul>\n<p>So, I'd modify the "no actions in constructors" rule to read "prepare for work in the constructor, do the work in methods".</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T08:56:49.580",
"Id": "265764",
"ParentId": "265752",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "265756",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T00:49:54.663",
"Id": "265752",
"Score": "0",
"Tags": [
"java",
"object-oriented",
"insertion-sort"
],
"Title": "Insertion Sort code in Java"
}
|
265752
|
<p>Taking forward the code written for the <a href="https://github.com/suryasis-hub/MathLibrary" rel="noreferrer">math library</a> I'm developing. I wrote templatized functions for mean and variance.</p>
<ol>
<li><p><code>std::accumulate()</code> (or summation in general) is likely to cause overflow. Should I go for an incremental approach?</p>
</li>
<li><p>Another point of concern is for templatized argument, I am forced to use the same type as the return type, which means the mean of integers shall also result in an integer, clearly not a good choice. At the same time if I enforce double as the return type, then extending into multi-dimensional types like vectors or complex numbers will be problematic.</p>
</li>
<li><p>Is the comparison for double appropriate? Is there a way to write a generalized comparison function for all float types?</p>
</li>
</ol>
<h2>CODE</h2>
<pre><code>#include <vector>
#include <numeric>
#include <string>
#include <functional>
namespace Statistics
{
template <typename T>
T average(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(std::vector<T> distributionVector)
{
if (distributionVector.size() == 0)
{
throw std::invalid_argument("Statistics::expectation - The distribution provided is empty");
}
T sumOfSquare = std::accumulate(distributionVector.begin(), distributionVector.end(), T(), [](T a,T b) { return a + b*b; });
T meanOfSquare = sumOfSquare / distributionVector.size();
T squareOfMean = (average(distributionVector)) * (average(distributionVector));
return (meanOfSquare - squareOfMean);
}
}
</code></pre>
<p><strong>Test code</strong></p>
<pre><code>#include "pch.h"
#include <vector>
#include "../MathLibrary/Statistics.h"
void compareDoubles(double a, double b)
{
const double THRESHOLD = 0.01;
ASSERT_TRUE(abs(a - b) < THRESHOLD);
}
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);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T07:26:20.957",
"Id": "524949",
"Score": "2",
"body": "You might want to look at [my implementation of incremental mean and variance](/q/198124/75307), including the reviews I received."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T07:30:49.540",
"Id": "524951",
"Score": "0",
"body": "Question: do you really want to `throw` for this code? I associate `throw` with code that isn't allowed to crash (gaming/nuclear power plant, that sort of thing). In the case of gaming, the program would likely abandon an image or even a whole frame - this way the player can keep going and put up with a single bad frame. For a nuclear power plant you'd make sure that the controls remain operational and sensible (but perhaps not optimal). Personally I'm a massive fan of hard/early crashes. An assert would do the job here. `throw` has hidden efficiency costs too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T15:18:17.763",
"Id": "524974",
"Score": "0",
"body": "@Elliott in library code, you use `throw` so the caller can decide whether to crash, back out of that operation, etc. and how to log the error message."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T15:42:31.477",
"Id": "524988",
"Score": "0",
"body": "@JDługosz, wouldn't that be overly generalising? That's a lot of slow-down for the off-chance this is gonna take-off as the go-to library on basic stats?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T18:05:40.747",
"Id": "524995",
"Score": "2",
"body": "@Elliott: Nearly all modern C++ environments have zero-overhead exception fast path... the cost is only incurred when `throw` is reached. In which case the cost of calling `assert` in a catch block compared to a direct call to `assert` simply does not matter -- the exception handling cost is miniscule compared to the work of logging and process termination. Only when exceptions are repeatedly thrown and caught may the performance become an issue, and calling assert removes the option entirely."
}
] |
[
{
"body": "<h2>Review</h2>\n<p>Welcome to Code Review. There are some suggestions as follows.</p>\n<h3>Answer your questions</h3>\n<blockquote>\n<p><code>std::accumulate()</code>(or summation in general) is likely to cause overflow. Should I go for an incremental approach?</p>\n</blockquote>\n<p>Why you think that <code>std::accumulate</code> is likely to cause overflow? In your test cases it works well. Whether overflow occurs or not depends on the type you choose. Choose type smart and no overflow happen.</p>\n<blockquote>\n<p>I am forced to use the same type as the return type, which means the mean of integers shall also result in an integer, clearly not a good choice.</p>\n</blockquote>\n<p>You noticed that the result <code>Statistics::average(testVector2)</code> in the following code is <code>3</code> not <code>3.3333</code>.</p>\n<pre><code>std::vector<int> testVector2 = { 0, 3, 7 };\nstd::cout << Statistics::average(testVector2) << "\\n";\n</code></pre>\n<p>To solve this issue, one of solutions is to specify the return type. We can use <code>double</code> (as default return type) here because the average of numbers is always a floating number.</p>\n<pre><code>template <typename OutputT = double, typename T>\nOutputT average(std::vector<T> distributionVector)\n{\n if (distributionVector.size() == 0)\n {\n throw std::invalid_argument("Statistics::average - The distribution provided is empty");\n }\n return std::accumulate(distributionVector.begin(), distributionVector.end(), OutputT())\n / (distributionVector.size());\n}\n</code></pre>\n<blockquote>\n<p>Is the comparison for double appropriate? Is there a way to write a generalized comparison function for all float types?</p>\n</blockquote>\n<p>Maybe you can check <a href=\"https://stackoverflow.com/q/17333/6667035\">the post on SO</a>.</p>\n<h3>Input container for <code>average</code> and <code>variance</code> template function</h3>\n<p>You specify the input type in <code>std::vector</code>. How about <code>std::array</code> or <code>std::list</code>?</p>\n<p>Actually, you don't need to specify <code>std::vector<T></code> and can use <code>OutputT average(T distributionVector)</code> only. Moreover, with C++20 you can do this:</p>\n<pre><code>template <typename OutputT = double, std::ranges::input_range T>\nconstexpr OutputT average(const T& distributionVector)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T07:16:00.493",
"Id": "265761",
"ParentId": "265753",
"Score": "4"
}
},
{
"body": "<p>The calculation of variance as Σ(x²)/n - (Σx/n)² doesn't work well for small variances, as it can be a difference of two large numbers, resulting in very poor relative accuracy.</p>\n<p>You'll get more accuracy using the basic definition Σ(x-̅x)²/n. Here's a version I wrote recently for a different project:</p>\n<pre><code>#include <cmath>\n#include <numeric>\n#include <ranges>\n#include <utility>\n\ntemplate<typename Container>\nauto mean_and_stddev(const Container& values)\n{\n auto len = static_cast<double>(values.size());\n auto mean = std::accumulate(values.begin(), values.end(), 0.0) / len;\n auto sdv = // squared differences view\n values\n | std::views::transform([mean](auto d){ auto x = d - mean; return x*x; })\n | std::views::common;\n auto stddev = std::sqrt(std::accumulate(sdv.begin(), sdv.end(), 0.0) / len);\n return std::pair{ mean, stddev };\n}\n</code></pre>\n<p>That's more numerically stable.</p>\n<hr />\n<p>Other issues:</p>\n<ul>\n<li><p>We're passing potentially large containers by value. There's no need for that - pass as const ref instead.</p>\n</li>\n<li><p>We only support <code>std::vector</code> as container, so we can't pass a <code>std::array</code> for example, or a sub-range of a vector. Consider passing start and end iterators instead.</p>\n</li>\n<li><p>Throwing exceptions might not be the best interface for the mean and variance of an empty collection - consider returning a NaN value instead.</p>\n</li>\n<li><p>Still missing necessary headers (<code><cmath></code> for <code>std::abs()</code> (which was misspelt); <code><stdexcept></code> for the exception types, <code><gtest/gtest.h></code> for the test library).</p>\n</li>\n<li><p>Using integer types as return for integer inputs - consider <code>std::common_type_t<T, double></code> for the computation and return value.</p>\n</li>\n<li><p>Users may want both <em>sample</em> and <em>population</em> variances; it's not much work to provide both.</p>\n</li>\n<li><p><code>compareDoubles()</code> loses a lot of debugging information from failures - we don't get the source location, or the actual and expected values. Consider using <code>EXPECT_DOUBLE_EQ()</code>, or examining its implementation if you really need to provide your own.</p>\n</li>\n<li><p>It's hard to see how we obtained the expected variance for <code>testVectorRandom</code>. Prefer to write tests where the results can be calculated with mental arithmetic.</p>\n<p>Example, from my implementation above:</p>\n<pre><code> #include <gtest/gtest.h>\n #include <array>\n TEST(mean_and_stddev, int_values)\n {\n auto [mean, stddev] = mean_and_stddev(std::array{50, 150});\n EXPECT_DOUBLE_EQ(mean, 100.);\n EXPECT_DOUBLE_EQ(stddev, 50.);\n }\n</code></pre>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T17:58:22.360",
"Id": "524992",
"Score": "1",
"body": "Even calculating the mean in the traditional way (here using `std::accumulate`) may have numerical instability issues., since `sum(values[0 .. N-2])` greatly differs in magnitude from values[N-1]`. It may be better to perform summation as a balanced binary tree rather than a list."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T08:14:15.383",
"Id": "265762",
"ParentId": "265753",
"Score": "5"
}
},
{
"body": "<p>I'll just address the concerns about the summation.</p>\n<blockquote>\n<p>std::accumulate() (or summation in general) is likely to cause overflow. Should I go for an incremental approach?</p>\n</blockquote>\n<p>You can query the maximum value for a <code>double</code> using <a href=\"https://en.cppreference.com/w/cpp/types/numeric_limits/max\" rel=\"nofollow noreferrer\"><code>std::numeric_limits<double>::max()</code></a>. This will most likely tell you that it's <span class=\"math-container\">\\$1.79769 \\cdot 10^{308}\\$</span>. Since you are probably not summing more than <span class=\"math-container\">\\$2^{64} \\approx 1.8 \\cdot 10^{19}\\$</span> values, and you are squaring numbers which means doubling their exponent, if the maximum value of the elements in the input is no more than roughly <span class=\"math-container\">\\$10^{\\frac{308-19}{2}} \\approx 10^{144}\\$</span>, you'll be fine.</p>\n<p>However, what is more of a concern is the accuracy of the results. If you add a very small number to a very large one, the limited precision of a <code>double</code> will mean that the contribution of the small number gets lost. If you have a few big values and lots of small ones, this can be a problem. The solution to this problem is to use <a href=\"https://en.wikipedia.org/wiki/Pairwise_summation\" rel=\"nofollow noreferrer\">pairwise summation</a>. Also heed Toby Speight's advice and calculate the variance using the formula <span class=\"math-container\">\\$\\frac{\\sum(x-\\bar x)^2}{n}\\$</span>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T12:44:08.573",
"Id": "524964",
"Score": "1",
"body": "In mathematics, the other formula is exactly equivalent, not an approximation - it's only when translated to the finite arithmetic of computers that it's less accurate."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T11:29:14.303",
"Id": "265769",
"ParentId": "265753",
"Score": "3"
}
},
{
"body": "<h2>overflow checking</h2>\n<p>Generally, all the code in the standard library and elsewhere is written without inserting any overflow checking. Unless you have a special need, don't worry about it in your functions.</p>\n<p>Now that it's a template, the caller could specify an extended-precision integer class, or a "safe" integer class, to get such checking. The checking is <em>part of the type</em> used, and need not be explicitly addressed in your code. It will be built into the <code>operator+</code> etc. for that type. For example, see the videos from the 2021 <a href=\"https://www.youtube.com/user/BoostCon/videos\" rel=\"nofollow noreferrer\">C++now</a> conference — I recall a presentation on <em>Simplest Safe Integers</em>, and there have been others in the past.</p>\n<h2>parameter, return, and other types</h2>\n<blockquote>\n<p>Another point of concern is for templatized argument, I am forced to use the same type as the return type, which means the mean of integers shall also result in an integer, clearly not a good choice. At the same time if I enforce double as the return type, then extending into multi-dimensional types like vectors or complex numbers will be problematic.</p>\n</blockquote>\n<p>No, you are <strong>not</strong> forced to use the same type for the argument as the return.</p>\n<p>You can take the input parameter as <em>another</em> template argument. Using classic syntax:</p>\n<pre><code>template <typename R, typename P>\nR factorial (P x)\n{ ⋯ }\n</code></pre>\n<p>With C++20, you can use Concepts to specify that the template parameters must be integral types.</p>\n<p>Note that you put <code>R</code> first, since you will deduce <code>P</code> from the arguments but must give <code>R</code>. Example use:</p>\n<pre><code>const auto y = factorial<bignum_t>(432);\n</code></pre>\n<p>Likewise, you can take additional template arguments, perhaps with defaults, to use for internal computations if that becomes necessary.</p>\n<p>It's probably much more efficient to use built-in integers for inputs and where you can inside the body of the function, and the extended-precision (or "safe") class for the accumulation of the result.</p>\n<h2>comparison for floating-point</h2>\n<p>That should be built-into the unit testing framework. (<a href=\"https://github.com/catchorg/Catch2/blob/devel/docs/matchers.md#floating-point-matchers\" rel=\"nofollow noreferrer\">example</a>)</p>\n<h1>the new functions</h1>\n<pre><code>template <typename T>\nT average(std::vector<T> distributionVector)\n</code></pre>\n<p>First of all, why is it limited to/specific to <code>vector</code>?<br />\nSecond, why are you passing it <strong>by value</strong>? Do you understand that this <strong>copies</strong> the entire vector?</p>\n<p>Classically, such functions should take a pair of iterators to specify the input. As of C++20, you could use a <em>Range</em>. By taking any parameter that satisfies the Range concept, that includes <code>std::vector</code> and any other sequential collection as well.</p>\n<p>If you change the template declaration to accept any container, that doesn't affect the code! Except... it would work for <code>std::deque</code>, <code>boost::small_vector</code>, etc. but would have trouble when you pass it a raw array, or certain types of range views. For this reason, <strong>use the non-member <code>begin</code>, <code>end</code>, <code>size</code>, etc.</strong> to better abstract the collection/view.</p>\n<p>Classically, this would be done with the "<code>std::</code> two-step". With C++20, just use the newer <a href=\"https://en.cppreference.com/w/cpp/ranges/begin\" rel=\"nofollow noreferrer\"><code>std::ranges::begin</code></a> etc.</p>\n<p><code>if (distributionVector.size() == 0)</code></p>\n<p>Use <code>empty</code> instead of comparing the <code>size</code> with 0. And again, <a href=\"https://en.cppreference.com/w/cpp/ranges/ssize\" rel=\"nofollow noreferrer\">use the non-member</a>.</p>\n<p>When testing, include a plain C array as one of the tests; e.g.</p>\n<pre><code>constexpr int test_val_1[] = { 1,2,3,4,6,8,9,34,45,78,89 };\n ⋮\nconst auto result = variance<double>(test_val_1);\n</code></pre>\n<p>Notice that in this example I also specified that I want a floating-point calculation of the variance, even though the input is integers.</p>\n<h2>the API</h2>\n<p>In many calculators, the stats are computed incrementally. You submit each value (or value pair) as you compute them or enter them, often with a key labeled "Σ+". You can model this with a class that keeps intermediate accumulators but does not need the entire list of input at once. It can be used incrementally.</p>\n<p>The class would use template arguments for the type to use for the accumulators, which IIRC are things like the count of items (n), the sum, the sum of the squares, and more for two-variable input.</p>\n<p>The class would have functions to submit a value, or submit a range of values at once. These member functions can themselves be templates, to be flexible as to the parameter type.</p>\n<p>It would have functions like <code>average</code> and <code>variance</code> that operate on the stored data. This way you can call for multiple stats without having to re-compute things or make multiple passes over the same data.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T14:31:59.540",
"Id": "265779",
"ParentId": "265753",
"Score": "3"
}
},
{
"body": "<p>A common way to avoid overflow (when using integers) or accuracy loss (when using floating point type is to use a <em>guess</em>. If you do not know the exact value of the mean but know it to an order of magnitude, you can use the formula:\n<span class=\"math-container\">\\$\\overline {x - guess} = \\bar x - guess\\$</span>. If you choose your guess wisely, the accuracy gain can be important.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T15:30:53.827",
"Id": "524983",
"Score": "0",
"body": "You don't have to guess, you can just take the mean or median of the input. But I would not subtract the guess, but rather divide by the guess, as the subtraction of two large numbers itself can be a problem, as Toby Speight already mentioned in his answer. A good suggestion otherwise."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T14:38:36.443",
"Id": "265781",
"ParentId": "265753",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T03:04:31.997",
"Id": "265753",
"Score": "6",
"Tags": [
"c++",
"beginner",
"statistics"
],
"Title": "Mean and Variance for Math Library"
}
|
265753
|
<p>I have a piece of code that downloads acupuncture data from Wikipedia and consolidates it into an acupoint, meridian and extraordinary meridian dictionary stored as .pkl files in the working directory.</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
import wikipedia as wp
import json
from hanziconv import HanziConv as hconv
from copy import deepcopy
from os.path import isfile
import itertools
import re
class Jingluo():
def __init__(self):
self.yinyang = ("太陰", "陽明", "少陰", "太陽", "厥陰", "少陽" )
try:
self.zhengjing, self.xunjing = self.read_meridians()
self.qijing = self.read_extraordinary_meridians()
self.xue = self.read_acupoints()
except:
print("Downloading data from Wikipedia...")
self.get_data_from_wikipedia()
self.zhengjing, self.xunjing = self.read_meridians()
self.qijing = self.read_extraordinary_meridians()
self.xue = self.read_acupoints()
@staticmethod
def get_data_from_wikipedia():
"Scrape data from wikipedia and output three dataframes: \
acupoints, meridians and extraordinary meridians."
html = wp.page("List_of_acupuncture_points").html()
df = pd.read_html(html)
# Set meridian, extra meridian and acupoint
meridians = df[0][['Code', 'Chinese Name', 'English']]
extraordinary_meridians = df[1][['Code','Name','Transliteration']]
extraordinary_meridians.columns = ['ID', 'Name', 'Transliteration']
extraordinary_meridians = extraordinary_meridians.set_index('ID')
acupoints = pd.concat(df[2:16])[['Point', 'Name', 'Transliteration']] # standard :16, all :18
acupoints.columns = ['ID', 'Name', 'Transliteration']
acupoints = acupoints.set_index('ID')
# Data cleaning
## Fix meridian data
meridians = deepcopy(meridians)
meridians['Chinese Name'] = [hconv.toTraditional(item) for item in meridians['Chinese Name']]
meridians.loc[11]['Code'] = 'LR'
## Fix acupoint data
as_list = acupoints.index.tolist()
split_list = [item.split('-') for item in as_list]
tag_list = [tag for tag, sn in split_list]
sn_list = [sn for tag, sn in split_list]
tag_list = ["LR" if tag == "Liv" else tag for tag in tag_list]
tag_list = ["GV" if tag == "Du" else tag for tag in tag_list]
tag_list = ["CV" if tag == "Ren" else tag for tag in tag_list]
tag_list = [item.upper() for item in tag_list]
new_idx_list = [tag + sn for tag, sn in zip(tag_list, sn_list)]
acupoints.index = new_idx_list
# Write to disk
acupoints.to_pickle('acupoints.pkl') # save to pickle file
meridians.to_pickle('meridians.pkl')
extraordinary_meridians.to_pickle('extraordinary_meridians.pkl')
print('Done!')
# 穴位
@staticmethod
def read_acupoints():
if isfile('acupoints.pkl'):
ACUPOINTS = pd.read_pickle('acupoints.pkl')
STRING_LABELS = [name + "(" + index + ")" for name, index in zip(list(ACUPOINTS['Name']), list(ACUPOINTS.index))]
# convert to dictionary
acupoint = {name: {"id": index, "label": name + "(" + index + ")"} for name, index in \
zip(list(ACUPOINTS['Name']), list(ACUPOINTS.index))}
return acupoint
else:
print("Acupoints table not found.")
# 經絡
@staticmethod
def read_meridians():
if isfile('meridians.pkl'):
MERIDIANS = pd.read_pickle('meridians.pkl')
limb_list = [ re.search("([手足])(.+?[陰陽明])(.+)經", item).group(1)\
for item in MERIDIANS['Chinese Name']]
yinyang_list = [ re.search("([手足])(.+?[陰陽明])(.+)經", item).group(2)\
for item in MERIDIANS['Chinese Name']]
organ_list = [ re.search("([手足])(.+?[陰陽明])(.+)經", item).group(3)\
for item in MERIDIANS['Chinese Name']]
zhengjing = { organ:{"id": index, "name": name, "short_name": organ + "經",\
"label": name + "(" + index + ")", "limb": limb, "yinyang": yinyang}\
for name, index, limb, yinyang, organ in \
zip(MERIDIANS['Chinese Name'], MERIDIANS['Code'], limb_list, yinyang_list, organ_list)}
xunjing = (item for item in zhengjing) # generator object; use next(xunjing) to simulate circulation.
return zhengjing, xunjing
else:
print("Meridians table not found.")
#奇經
@staticmethod
def read_extraordinary_meridians():
if isfile('extraordinary_meridians.pkl'):
EXTRAORDINARY_MERIDIANS = pd.read_pickle('extraordinary_meridians.pkl')
em_name_list = [item.split('; ')[1] for item in EXTRAORDINARY_MERIDIANS['Name']]
em_name_list = [re.sub('蹺', '蹻', item) for item in em_name_list]
em_list = [re.sub('脈', '', item) for item in em_name_list]
# hand_meridian_list = [ value['臟腑'] for key, value in .items() if '手' in value['肢'] ]
qijing = {short_hand: {"id": index, "name": name, "label": name + "(" + index + ")"} for short_hand, name, index in \
zip(em_list, em_name_list, list(EXTRAORDINARY_MERIDIANS.index))}
return qijing
else:
print("Extraordinary Meridians table not found.")
</code></pre>
<p>You can view the structure of the dataset by running the above initiation code and calling:</p>
<pre class="lang-py prettyprint-override"><code>x= Jingluo()
x.zhengjing # meridians
x.qijing # extraordinary meridians
x.xue # acupoint data
</code></pre>
<p>This is working fine, but I wonder if there a more efficient and effective way of acquiring and storing the above data?</p>
<p>I would like the dataset to be easily extensible. For example, I might want to tag images to show the position of each acupoint in the <code>xue</code> (i.e. acupoint) dictionary.</p>
<p>It seems to me an SQLite relational database might be more useful for this situation.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T08:35:03.823",
"Id": "524954",
"Score": "0",
"body": "Using non-ascii characters for strings and displayable text if ok, but using them for variable names is awful for two reasons: 1- If format is lost, your code may become unrunnable. 2 - If your code will ONLY be read by people who speak your native language, you might write code in that language; but if your code will be read by other people, it should be in english. Specially if the language uses a different character set"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T09:45:50.643",
"Id": "524958",
"Score": "0",
"body": "Removed Chinese characters in variable names."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T13:15:30.667",
"Id": "524966",
"Score": "1",
"body": "@m-alorda Overall your point stands, though \"awful\" is perhaps a stretch, and \"format is lost\" makes no sense to me. Are you suggesting that UTF-8 is going to cease to exist?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T14:46:21.110",
"Id": "524971",
"Score": "0",
"body": "@Reinderien You are right, maybe saying \"awful\" wasn't the best way to describe it. Regarding format, I may not have explained myself good enough. I'm not saying UTF-8 will cease to exist at all. I've come across code that uses non-ascii characters sush as \"ñ\" or \"á\". However, the format was then changed to ascii, and they weren't properly represented (for example \"á\" was then represented by something like \"A~\"). I just don't know exactly how it happened, maybe it was the editor that got the settings messed up, or maybe it was after zipping it and/or uploading to a university app"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T16:44:31.720",
"Id": "524990",
"Score": "0",
"body": "Also, I don't think I deserve to be downvoted just for that. I have actually made an effort to make it clear *contextually* what the variables mean by way of comments, etc."
}
] |
[
{
"body": "<p>This took me a long time to go through.</p>\n<p>First, re. non-ASCII characters for strings - yes(ish), but it's less important to eliminate non-ASCII characters, and more important to make a consistent codebase whose variables are in English for international collaboration purposes. So it's not helping us to replace</p>\n<pre><code>class 經絡():\n</code></pre>\n<p>with</p>\n<pre><code>class Jingluo():\n</code></pre>\n<p>Rather than only <em>romanisation</em>, you should perform <em>translation</em>, so this should instead be</p>\n<pre><code>class Meridian():\n</code></pre>\n<p>When you present your data to the user that's a different story; presentation is where you show localized languages.</p>\n<p><code>wikipedia</code> is not a very helpful library for your purposes. Currently you're using it as a glorified <code>requests</code>, so just use <code>requests</code> instead. More broadly: your current data path is</p>\n<ul>\n<li>Wikipedia's database, in mediawiki markup; to</li>\n<li>Wikipedia's renderer outputting HTML; to</li>\n<li>your Pandas <code>read_html</code> call.</li>\n</ul>\n<p>It roughly works but is non-ideal for a list of reasons:</p>\n<ul>\n<li>HTML is not a data interchange format, and does not represent a stable API.</li>\n<li>The above trip through a presentation markup is information-lossy. Among (many) other things, you're losing the semantic data about alternate language variants like traditional versus simplified Chinese, and heading titles.</li>\n</ul>\n<p>For these reasons you should consider</p>\n<ul>\n<li>Instead of hitting the Wikipedia website, hit their MediaWiki API with Requests</li>\n<li>Parse the returned markup with a mediawiki parsing library</li>\n<li>Pay attention to the heading titles, so that you can more robustly identify where and what your tables are</li>\n<li>Pay attention to the <code>zh</code> template so that you can explicitly select between simplified and traditional Chinese, something I suspect you care about</li>\n</ul>\n<p>Otherwise:</p>\n<ul>\n<li><code>Jingluo</code> is full of statics and thus does not deserve to be a class</li>\n<li><code>self.yinyang</code> is never used and should be deleted</li>\n<li>Never bare <code>except</code>. As a bonus: if you were to pay attention to the thrown exception, it's not (!) throwing a <code>FileNotFoundError</code>; but rather is failing to unpack your <code>None</code> return. So\n<ul>\n<li>do not call <code>isfile</code>;</li>\n<li>do not <code>else / print</code>;</li>\n<li>do not <code>except:</code>;</li>\n<li>let the <code>FileNotFoundError</code> fall through;</li>\n<li>catch it specifically at the outer level.</li>\n</ul>\n</li>\n<li>Don't <code>print('Downloading ...</code>. If you really want to see this, send it to a logger instance instead</li>\n<li>As hinted at above, do not index <code>[0]</code> into your tables sequence; pay attention to the titles in the mediawiki markup. What if a table were inserted between the indices that you currently hard-code?</li>\n<li>Do not hard-code index 11; instead use a Pandas replacement</li>\n<li>The moment you're calling <code>tolist</code>, something in your Pandas usage has probably gone wrong. Don't do this. Call into the vectorized string methods.</li>\n<li>Your <code>split('-')</code> is going to crash for at least two different cases I see in the Wikipedia page. Some names have multiple-dashed-components, and others have no dash separator. One solution is to apply a regex with a digit group and call <code>extractall</code>.</li>\n<li>Do not bake your disk-writing code into the same method as your cleaning code.</li>\n<li>You have this weird disconnect between pre-processing and post-processing, where your pre-processed data are in Pandas dataframes and your post-processed data are in dictionaries; and for whatever reason you do the dictionary conversion on every load of the Pickle file. I don't know why this is being done, so in my suggestion there is no post-conversion at all, and some elements of the post-conversion (e.g. parsing out of limb and organ strings) are included in pre-processing.</li>\n<li>You re-execute your <code>"([手足])(.+?[陰陽明])(.+)經"</code> regex - twice. Don't do this; just use Pandas vectorized <code>extractall</code>.</li>\n<li>I don't understand what you were trying to accomplish with <code>xunjing = (item for item in zhengjing)</code>; making a no-op generator doesn't have any use case that I can think of so you should just return <code>zhengjing</code> itself.</li>\n<li><code>re.sub('蹺', '蹻')</code> does not need the regex module and can just be a Pandas-vectorized <code>replace</code> call.</li>\n</ul>\n<blockquote>\n<p>I would like the dataset to be easily extensible. For example, I might want to tag images to show the position of each acupoint in the xue (i.e. acupoint) dictionary.</p>\n</blockquote>\n<p>This is possible in Pandas itself, which can easily store blobs for images. Your data set is very small so I consider SQL overkill.</p>\n<h2>Suggested</h2>\n<p>Not exactly equivalent, but that's deliberate based on above</p>\n<pre><code>from pprint import pprint\nfrom typing import Tuple, Iterable, Dict, Collection\n\nimport pandas as pd\nimport wikitextparser\nfrom hanziconv import HanziConv as hconv\nfrom os.path import isfile\nimport re\nfrom requests import get\nfrom wikitextparser import Table, Section, WikiText\n\n\n\n# Attempting to translate some terms from\n# https://www.ctcmpao.on.ca/resources/forms-and-documents/Standard_Acupuncture_Nomenclature.pdf\n\n\nFrames = Tuple[\n pd.DataFrame, # meridians\n pd.DataFrame, # extraordinary meridians\n Collection[pd.DataFrame], # acupoints\n]\n\nFramesByTitle = Iterable[Tuple[\n str, # Section title\n pd.DataFrame, # Dataframe derived from table\n]]\n\nFILENAMES = (\n 'acupoints.pkl',\n 'meridians.pkl',\n 'extraordinary_meridians.pkl',\n)\n\nCOLUMN_MAP = {\n 'Code': 'ID',\n 'Point': 'ID',\n}\n\nNORMALIZED_COLS = ['ID', 'Name', 'Transliteration']\n\n\ndef get_wiki(page_name: str) -> WikiText:\n with get(\n 'https://en.wikipedia.org/w/api.php',\n params={\n 'action': 'query',\n 'prop': 'revisions',\n 'rvprop': 'content',\n 'rvslots': 'main',\n 'format': 'json',\n 'titles': page_name,\n },\n ) as resp:\n resp.raise_for_status()\n page, = resp.json()['query']['pages'].values()\n\n text = page['revisions'][0]['slots']['main']['*']\n return wikitextparser.parse(text)\n\n\ndef templates_to_text(row: Iterable[str]) -> Iterable[str]:\n for cell in row:\n parsed = wikitextparser.parse(cell)\n\n if len(parsed.templates) > 0:\n template = parsed.templates[0]\n attrs = {arg.name: arg.value for arg in template.arguments}\n\n if template.name == 'lang':\n # Here you might care to do something special for language metadata\n yield attrs['2']\n elif template.name == 'zh':\n # Here you might want to select between traditional or simplified;\n # in this case we show only simplified which is what you had been\n # doing in em_name_list = [item.split('; ')[1]\n # To show both in Wikipedia style would basically be\n # yield f'{attrs["t"]}; {attrs["s"]}'\n yield attrs['s']\n else:\n yield cell[:template.span[0]]\n continue\n\n if len(parsed.wikilinks) > 0:\n link = parsed.wikilinks[0]\n yield link.text\n continue\n\n yield cell\n\n\ndef get_dataframes(doc: WikiText) -> FramesByTitle:\n table_refs: Dict[\n int, # Starting character index of the table in the document\n Tuple[Section, Table], # Section and the table it contains\n ] = {}\n\n # The following hack is needed because wikitextparser includes non-direct-\n # descendant tables in each section\n\n for section in doc.sections:\n for table in section.tables:\n start, end = table.span\n section_table = table_refs.get(start)\n if section_table is None:\n use = True\n else:\n old_section, old_table = section_table\n use = old_section.level < section.level\n if use:\n table_refs[start] = section, table\n\n for section, table in table_refs.values():\n columns, *rows = table.data()\n yield section.title, pd.DataFrame(\n [\n tuple(templates_to_text(row))\n for row in rows\n ],\n columns=columns,\n )\n\n\ndef assign_frames(frames: FramesByTitle, standard_only: bool = True) -> Frames:\n """\n Scrape data from wikipedia and output three dataframes:\n acupoints, meridians and extraordinary meridians.\n """\n\n all_tables = tuple(frames)\n tables: Dict[str, pd.DataFrame] = {\n title: df for title, df in all_tables\n # Excluded due to duplicate title\n if title != 'Extra points'\n }\n\n if not standard_only:\n deadman, extra = (\n df for title, df in all_tables if title == 'Extra points'\n )\n tables['Extra points (Deadman)'] = deadman\n tables['Extra points'] = extra\n\n return (\n tables.pop('Twelve Primary Meridians'),\n tables.pop('Eight Extraordinary Meridians'),\n tables.values(),\n )\n\n\ndef clean_meridians(meridians: pd.DataFrame) -> pd.DataFrame:\n meridians.drop(\n meridians.columns.difference(['Code', 'Chinese Name', 'English']),\n axis=1, inplace=True,\n )\n meridians['Chinese Name'] = meridians['Chinese Name'].map(hconv.toTraditional)\n meridians.Code[meridians.Code == 'LV'] = 'LR'\n\n groups = meridians['Chinese Name'].str.extractall(\n r'(?P<limb>[手足])'\n r'(?P<yinyang>.+?[陰陽明])'\n r'(?P<organ>.+)經'\n )\n groups.reset_index(drop=True, inplace=True)\n meridians = pd.concat((meridians, groups), axis=1)\n\n return meridians\n\n\ndef normalize(df: pd.DataFrame) -> pd.DataFrame:\n df.rename(columns=COLUMN_MAP, inplace=True)\n df.drop(df.columns.difference(NORMALIZED_COLS), axis=1, inplace=True)\n return df\n\n\ndef clean_extra_meridians(df: pd.DataFrame) -> pd.DataFrame:\n df = normalize(df)\n df.set_index('ID', inplace=True)\n\n df.Name = (\n df.Name\n .str.replace('蹺', '蹻')\n .str.replace('脈', '')\n )\n return df\n\n\ndef clean_acupoints(all_points: Collection[pd.DataFrame]) -> pd.DataFrame:\n for points in all_points:\n if 'Transliteration' not in points.columns:\n points.rename(columns={'Pinyin': 'Transliteration'}, inplace=True)\n\n all_points = [normalize(points) for points in all_points]\n\n acupoints = pd.concat(all_points, ignore_index=True)\n groups = acupoints.ID.str.extractall(\n r'^' # start\n r'(?P<tag>.*?)' # tag portion, non-greedy\n r'-?' # optional separating hyphen\n r'(?P<sn>\\d+)' # serial number portion\n r'$' # end\n )\n groups.reset_index(drop=True, inplace=True)\n acupoints = pd.concat((acupoints, groups), axis=1)\n acupoints.tag = acupoints.tag.str.upper()\n acupoints.tag.replace(\n {\n 'LIV': 'LR',\n 'DU': 'GV',\n 'REN': 'CV',\n },\n inplace=True,\n )\n acupoints.index = acupoints.tag + acupoints.sn\n return acupoints\n\n\ndef download_or_read() -> Frames:\n try:\n return tuple(pd.read_pickle(fn) for fn in FILENAMES)\n except FileNotFoundError:\n pass\n\n doc = get_wiki('List_of_acupuncture_points')\n meridians, extras, points = assign_frames(get_dataframes(doc), standard_only=False)\n\n meridians = clean_meridians(meridians)\n extras = clean_extra_meridians(extras)\n points = clean_acupoints(points)\n\n write_to_disk(meridians, extras, points)\n return meridians, extras, points\n\n\ndef write_to_disk(*args: pd.DataFrame) -> None:\n for filename, df in zip(FILENAMES, args):\n df.to_pickle(filename)\n\n\ndef main():\n download_or_read()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T01:06:12.683",
"Id": "265843",
"ParentId": "265755",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "265843",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T03:35:35.053",
"Id": "265755",
"Score": "1",
"Tags": [
"python",
"database"
],
"Title": "Data storage and processing in Python"
}
|
265755
|
<p>I have been learning SystemVerilog before I go back to school and decided to try and implement a Carry Lookahead Adder. As far as I can tell, it works correctly though I haven't tested extensively, just the tests you see on the testbench. I would like some feedback on best practices, things to avoid, and any other criticisms of the code and design since I am learning out of a textbook and don't have anyone to ask.</p>
<p><strong>Design</strong></p>
<pre><code>`timescale 1ns / 1ps
module full_adder(
input logic a, b, cin,
output logic g, p, s
);
assign g = a & b;
assign p = (a ^ b) & cin;
assign s = cin ^ (a ^ b);
endmodule
module four_bit_cla_logic(
input logic cin,
input logic [3:0] g, p,
output logic [3:0] c,
output logic gg, pg);
assign c[0] = g[0] | (p[0] & cin);
assign c[1] = g[1] | (p[1] & g[0]) | (p[1] & p[0] & cin);
assign c[2] = g[2] | (p[2] & g[1]) | (p[2] & p[1] & g[0]) | (p[2] & p[1] & p[0] & cin);
assign c[3] = g[3] | (p[3] & g[2]) | (p[3] & p[2] & g[1]) | (p[3] & p[2] & p[1] & g[0]) | (p[3] & p[2] & p[1] & p[0] & cin);
assign gg = g[3] | (p[3] & g[2]) | (p[3] & p[2] & g[1]) | (p[3] & p[2] & p[1] & g[0]);
assign pg = (p[3] & p[2] & p[1] & p[0]);
endmodule
module four_bit_cla(
input logic [3:0] a, b,
input logic cin,
output logic [3:0] s,
output logic cout, gg, pg);
logic [3:0] g, p, c;
full_adder fa0(a[0], b[0], cin, g[0], p[0], s[0]);
full_adder fa[3:1](a[3:1], b[3:1], c[2:0], g[3:1], p[3:1], s[3:1]);
four_bit_cla_logic cla(cin, g[3:0], p[3:0], c[3:0], gg, pg);
assign cout = c[3];
endmodule
</code></pre>
<p><strong>Testbench</strong>
(Shamelessly stolen from my textbook and modified for my modules - I've got more learning to do here)</p>
<pre><code>module testbench();
logic clk, reset;
logic [3:0] a, b, s, sexp;
logic cin, cout, gg, pg, coutexp, ggexp, pgexp;
logic [31:0] vectornum, errors;
logic [15:0] testvectors[10000:0];
// instantiate device under test
four_bit_cla dut(a[3:0], b[3:0], cin, s[3:0], cout, gg, pg);
// generate clock
always
begin
clk = 1; #5; clk = 0; #5;
end
// at start of test, load vectors
// and pulse reset
initial
begin
$readmemb("testvectors.tv", testvectors);
vectornum = 0; errors = 0;
reset = 1; #27; reset = 0;
end
// apply test vectors on rising edge of clk
always @(posedge clk)
begin
#1; {a[3:0], b[3:0], cin, sexp[3:0], coutexp, ggexp, pgexp} = testvectors[vectornum];
end
// check results on falling edge of clk
always @(negedge clk)
if (~reset) begin // skip during reset
if ({{s[3:0]}, cout, gg, pg} !== {{sexp[3:0]}, coutexp, ggexp, pgexp}) begin // check result
$display("Error: inputs = %b", {{a[3:0]}, {b[3:0]}, cin});
$display(" outputs = %b (%b expected)", {{s[3:0]}, cout, gg, pg}, {{sexp[3:0]}, coutexp, ggexp, pgexp});
errors = errors + 1;
end
vectornum = vectornum + 1;
if (testvectors[vectornum] === 16'bx) begin
$display("%d tests completed with %d errors",
vectornum, errors);
$finish;
end
end
endmodule
</code></pre>
<p><strong>Test Vectors</strong></p>
<pre><code>1111_1111_0_1110_1_1_0
1001_1100_0_0101_1_1_0
1010_0101_1_0000_1_0_1
0000_0000_0_0000_0_0_0
0000_0000_1_0001_0_0_0
1111_1111_1_1111_1_1_0
1101_1000_0_0101_1_1_0
0110_1110_1_0101_1_1_0
0101_1010_1_0000_1_0_1
0001_1001_1_1011_0_0_0
</code></pre>
|
[] |
[
{
"body": "<p>The layout of your code is good, and you did a good job partitioning the design from the testbench.</p>\n<p>In your design, you could take advantage of the "reduction" operators to make your code more compact and less prone to errors. For example, you could change:</p>\n<pre><code>assign pg = (p[3] & p[2] & p[1] & p[0]);\n</code></pre>\n<p>to:</p>\n<pre><code>assign pg = &p;\n</code></pre>\n<p>Here, <code>&</code> acts as a reduction-AND operator which ANDs all the bits of <code>p</code> together, returning a single bit value.</p>\n<p>When you instantiate modules, you could use connections-by-name instead of connections-by-order. For example, change:</p>\n<pre><code>four_bit_cla dut(a[3:0], b[3:0], cin, s[3:0], cout, gg, pg);\n</code></pre>\n<p>to:</p>\n<pre><code>four_bit_cla dut (\n .a (a),\n .b (b),\n .cin (cin),\n .cout (cout),\n .gg (gg),\n .pg (pg),\n .s (s)\n);\n</code></pre>\n<p>This is much less error prone as the number of ports increases; connection errors are a common Verilog pitfall. Connections-by-name is also self-documenting.</p>\n<p>In the testbench, it is better for debugging if you add <code>$time</code> to your <code>$display</code> messages.</p>\n<p>You could use the auto-increment operator. Change:</p>\n<pre><code> errors = errors + 1;\n</code></pre>\n<p>to:</p>\n<pre><code> errors++;\n</code></pre>\n<p>Also, you can use 2-state types rather than 4-state when you don't need to model <code>x</code> or <code>z</code> values. Change:</p>\n<pre><code> logic [31:0] errors;\n</code></pre>\n<p>to:</p>\n<pre><code> int errors;\n</code></pre>\n<p>You can even omit the initialization since all 2-state types default to 0. There is less to type, and 2-state could result in better simulation performance.</p>\n<p>You should use more indentation levels in your checker code.</p>\n<pre><code>always @(negedge clk)\nif (~reset) begin // skip during reset\n if ({{s[3:0]}, cout, gg, pg} !== {{sexp[3:0]}, coutexp, ggexp, pgexp}) begin // check result\n $display($time, " Error: inputs = %b", {{a[3:0]}, {b[3:0]}, cin});\n $display(" outputs = %b (%b expected)", {{s[3:0]}, cout, gg, pg}, {{sexp[3:0]}, coutexp, ggexp, pgexp});\n errors++;\n end\n vectornum++;\n if (testvectors[vectornum] === 16'bx) begin\n $display($time, " %d tests completed with %d errors", vectornum, errors);\n $finish;\n end\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T12:46:36.853",
"Id": "265775",
"ParentId": "265759",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "265775",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T06:46:18.390",
"Id": "265759",
"Score": "3",
"Tags": [
"verilog",
"hdl",
"fpga"
],
"Title": "Carry Lookahead Adder - SystemVerilog"
}
|
265759
|
<p>I tried to implement a weighted draw. The idea of which is, you can have disproportionate probabilities of drawing different items. In this particular case, I want to cumulatively bias the probability towards drawing undrawn items. That is, the longer an item hasn't been drawn, the higher its chances become.</p>
<p>I'm a python newb and I come from a background of more traditional languages, so I wrote it using generic constructs borrowed from what I'm familiar with (e.g. a prolific use of index-based loops). I'm curious what a more "pythonic" version would look like.</p>
<p>Also, I'm looking for performance optimizations.<br />
The most obvious one I can spot is, the draw can be turned into a binary search taking it down from <code>O(n)</code> to <code>O(log n)</code>. Another point is - when you make it "pythonic" don't make it slower.</p>
<p>(There's a bit of extra, not strictly necessary code related to debugging and some interesting algorithmic stats. For example a comparison to a normal, uniformly random draw. Also, it seems to take 2-2.5x the pool size to draw all items once, using the default weight modifier. Feel free to add insights.)</p>
<pre class="lang-py prettyprint-override"><code>#!/usr/bin/python3
import random
# Draw is [) aka >= start, < end
def draw():
# randy = random.randint(0, startPoints[-1] + weights[-1])
randy = random.random() * startPoints[-1] + weights[-1] # Makes drawing 0 more unlikely than above. But allows multiplication of weights.
for i, startPoint in enumerate(startPoints):
if randy >= startPoint and randy < startPoints[i] + weights[i]:
# if startPoint >= randy: # This works, except for returning the last index (which we can using python's for-else)
return i
def adjustWeight(weight):
return weight + 1 # Varying addition doesn't seem to affect things, but multiplication scales with value.
def adjustWeights(drawnIdx):
for i, weight in enumerate(weights):
if i == drawnIdx:
weights[i] = 1
else:
weights[i] = adjustWeight(weights[i])
if i != 0:
startPoints[i] = startPoints[i-1] + weights[i-1]
def doRound():
global lastnonDupe # Why TF does this need global, but the others dont
singleDraw = draw()
drawn.append(singleDraw)
adjustWeights(singleDraw)
# Independent rando and dupe stats
seenRando()
if singleDraw in seen:
seen[singleDraw] = seen[singleDraw] + 1
# print("Dupe draw " + str(singleDraw) + " after " + str(len(drawn)) + " draws; Len of seen: " + str(len(seen)) + getCompSymbol(len(seen), len(seen2)) + str(len(seen2)))
else:
seen[singleDraw] = 1
nondupeIntervals.append(len(drawn) - lastnonDupe)
lastnonDupe = len(drawn)
def seenRando():
global lastnonDupe2
randy = random.randint(0, poolSize-1)
if randy in seen2:
seen2[randy] = seen2[randy] + 1
else:
seen2[randy] = 1
nondupeIntervals2.append(len(drawn) - lastnonDupe2)
lastnonDupe2 = len(drawn)
def getCompSymbol(val1, val2):
if val1 > val2:
return " > "
if val1 < val2:
return " < "
else:
return " = "
poolSize = 200
weights = list(range(1, poolSize+1))
startPoints = list(range(0, poolSize))
drawn = []
for idx, weight in enumerate(weights):
weights[idx] = 1
extra = []
maxTotal = 0
# Independent rando and dupe stats
seen = {}
seen2 = {}
nondupeIntervals = []
nondupeIntervals2 = []
lastnonDupe = 0
lastnonDupe2 = 0
for x in range(400):
prevTotal = sum(weights)
# print(startPoints)
doRound()
currTotal = sum(weights)
newMax = max(maxTotal, currTotal)
extra.append((sum(weights), sum(weights) - prevTotal, newMax, newMax > maxTotal))
maxTotal = newMax
print("Dupe draw stats")
print((poolSize, len(seen), round(len(seen) / poolSize, 2), len(seen2), round(len(seen2) / poolSize, 2)))
print((sum(nondupeIntervals) / len(nondupeIntervals), sum(nondupeIntervals2) / len(nondupeIntervals2), max(nondupeIntervals), max(nondupeIntervals2))) # Avg/max distance between non-dupes.
print(max(weights))
# print(nondupeIntervals)
# print(nondupeIntervals2)
print("==================================================================================================================================================================")
# print(drawn)
# print(seen)
# print(weights)
# print(extra)
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T01:34:23.113",
"Id": "525019",
"Score": "1",
"body": "Please give a specific formula for what weights you want. Your problem is a little vague, so it will help while reading the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T02:23:36.543",
"Id": "525021",
"Score": "0",
"body": "@ZacharyVance Formula's right there, second function from the top."
}
] |
[
{
"body": "<p>I must admit I have stared at your function for almost an hour now, and I still struggle to comprehend how it works. I think I get the <em>gist</em> of it, but.. Yeah.</p>\n<h3>Readability</h3>\n<p>Global variables are bad in any programming language and hurts readability. See <a href=\"https://stackoverflow.com/a/19158418/1048781\">https://stackoverflow.com/a/19158418/1048781</a> for a deeper dive into it.\nWhen I run your code I get this</p>\n<pre><code> Dupe draw stats\n (200, 193, 0.96, 168, 0.84)\n (2.0259067357512954, 23273809523809526, 20, 15)\n 401\n ================================================================================================================\n</code></pre>\n<p>What does any of this mean? What are your testcases? How does this test how random your draw is? My biggest struggle with your code is figuring out what it does. Would you be able to figure out what your code does in 1 month, let alone 1 year? It can be very wise to write out a battle plan before writing any code. Then you can ponder on the algorithm used instead of gluing together half broken ideas along the way.</p>\n<p>In addition it is strongly encouraged to include docstrings and comments. One important concept in programming is <em>intent</em>. What is your code intended to do, e.g how fast can someone not familiar with your code recognize what it does. This is usually done in steps.</p>\n<ul>\n<li>Modules (Logical classes etc).</li>\n<li>Single purpose functions</li>\n<li>Clear docstrings</li>\n<li>Clear variable names</li>\n<li>Comments</li>\n</ul>\n<p>In that order. We start at the top, and if the intent is not clear we work our way down. Only when we can not express the intent of our code through single purpose functions, clear docstring and variable names should we add comments to clear things up. The other points you should always try to do =)</p>\n<p>Avoid redundant code (this can be helped using a proper editor, which will yell at you). For instance the function below is never used</p>\n<pre><code> def getCompSymbol(val1, val2):\n if val1 > val2:\n return " > "\n if val1 < val2:\n return " < "\n else:\n return " = " \n</code></pre>\n<h3>The Python way and nitpicking</h3>\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\"><strong>PEP 8 - Style Guide for Python Code</strong></a></p>\n<p>Just as learning a new language it is important to learn its <em>grammar</em>. Your speech can be <em>technically</em> correct and understandable, but one can tell it is not your mother tongue. It looks like you have experience from a different language, and I would recommend getting familiar with Python's grammar. When we talk about grammar in the sense of programming languages, we refer to this as syntax. And proper syntax (think of this as proper grammar) is achieved following a <em>style guide</em></p>\n<p>PEP 8 recommends the following <a href=\"https://www.python.org/dev/peps/pep-0008/#prescriptive-naming-conventions\" rel=\"nofollow noreferrer\">naming-conventions</a>:</p>\n<ul>\n<li><code>CAPITALIZED_WITH_UNDERSCORES</code> for constants</li>\n<li><code>UpperCamelCase</code> for class names</li>\n<li><code>lowercase_separated_by_underscores</code> for other names</li>\n</ul>\n<p>So your functions should not follow cammelCase.</p>\n<p><a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\"><strong><code>f-strings</code></strong></a></p>\n<p>f-strings are the new way of formatting strings in Python, and you should usually use them. While your code, in your current state, does not benefit much from them look at my answer to see how to space out the testing data.</p>\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/#id19\" rel=\"nofollow noreferrer\"><strong><code>max line width = 79</code></strong></a></p>\n<p>Python recommends a maximum linewidth of 79. While some prefer this to be a little longer (around 110 or so), it is clear that setting a limit is good for readability.</p>\n<p><a href=\"https://stackoverflow.com/q/419163\"><strong><code>if __name__ == "__main__":</code></strong></a></p>\n<p>Put the parts of your code that are the ones calling for execution behind a <a href=\"https://stackoverflow.com/q/419163\"><code>if __name__ == "__main__":</code></a> guard. This way you can import this python module from other places if you ever want to, and the guard prevents the main code from accidentally running on every import.</p>\n<h2>Small example of a refactor</h2>\n<p>Note that a refactor should first and foremost be to make the <em>intent</em> of the code clearer. I would start with the algorithm used, but here is just another tiny example that highlights some of the points made above. The code below</p>\n<pre><code>print((sum(nondupeIntervals) / len(nondupeIntervals), sum(nondupeIntervals2) / len(nondupeIntervals2), max(nondupeIntervals), max(nondupeIntervals2))) # Avg/max distance between non-dupes.\n</code></pre>\n<p>has two issues. The line below is too long, and the comment is not visible unless we scroll. Using the <code>end</code> keyword, we can restructure the code as follows</p>\n<pre><code> # Avg/max distance between non-dupes.\n print(sum(nondupeIntervals) / len(nondupeIntervals) ), end="")\n print(sum(nondupeIntervals2) / len(nondupeIntervals2), end="") \n print(max(nondupeIntervals), max(nondupeIntervals2))))\n</code></pre>\n<p>Where <code>end=""</code> prevents a newline from being written. The next step\nis to notice we have code duplication, we are performing the same actions on <code>nondupeIntervals</code> and <code>nondupeIntervals</code> (which again should have <code>snake_case</code> according to PEP8.) If we refactor this into a function and sprinkle some <code>f-strings</code> on top we obtain</p>\n<pre><code>def print_intervals(intervals):\n avg_dist_text = f"{'Average distance':>20}"\n max_dist_text = f"{'Maximum distance':>20}"\n interval_text = "interval"\n linebreak = "=" * 79\n print(linebreak)\n print(f" Testing of average distance and maximum distance")\n print(linebreak)\n print(f" {interval_text}{avg_dist_text}{max_dist_text}")\n for i, interval in enumerate(intervals):\n average_distance = sum(interval) / len(interval)\n print(f" {i:>{len(interval_text)}}", end="")\n print(f"{average_distance:{len(avg_dist_text)}f}", end="")\n print(f"{max(interval):{len(max_dist_text)}}")\n</code></pre>\n<p>Which you would invoke by doing</p>\n<pre><code>print_intervals([nondupeIntervals, nondupeIntervals2])\n</code></pre>\n<p>and would print</p>\n<pre><code>===============================================================================\n Testing of average distance and maximum distance\n===============================================================================\n interval Average distance Maximum distance\n 0 2.083333 18\n 1 2.366864 22\n===============================================================================\n</code></pre>\n<p>Which in my eyes is much prettier and more importantly readable. Can we refactor too far? In fact it is very easy to do so! Three signs that you have gone too far</p>\n<ol>\n<li>You have not checked that there exists a library / external solution that can solve the problem.</li>\n<li>Is the code way more general than what is asked for?</li>\n<li>Is the code heavily optimized for speed before you have profiled the code for bottlenecks?</li>\n</ol>\n<p>As an example of a refactor gone too far of the code above would be something like</p>\n<pre><code>def results_2_table(\n results,\n title,\n headers,\n indent=2,\n space_between=4,\n post=None,\n pre=None,\n symbol="~.",\n hlines=[True, True, True],\n):\n headers_ = {}\n if isinstance(post, str):\n post = [post for _ in range(len(results[0]))]\n if isinstance(pre, str):\n pre = [pre for _ in range(len(results[0]))]\n\n for i, header in enumerate(headers):\n headers_[header] = dict()\n headers_[header]["pre"] = "" if pre is None else pre[i]\n headers_[header]["post"] = "" if post is None else post[i]\n headers_[header]["formating"] = str(len(header))\n\n between_str = " " * space_between\n indent_str = " " * indent\n header_str = indent_str + between_str.join(headers)\n title = indent_str + title\n linebreak_length = max(len(header_str), len(title)) + indent\n times, remainder = divmod(linebreak_length, len(symbol))\n linebreak = symbol * times + (symbol[0:remainder] if remainder else "")\n toprule, midrule, bottomrule = hlines\n\n table = []\n if toprule:\n table.append(linebreak)\n table.append(title)\n if midrule:\n table.append(linebreak)\n table.append(header_str)\n for row in results:\n line = []\n for head, value in zip(headers_, row):\n column = headers_[head]\n line.append(f"{value:{column['pre']}{column['formating']}{column['post']}}")\n table.append(indent_str + between_str.join(line))\n if bottomrule:\n table.append(linebreak)\n return "\\n".join(table)\n\n\ndef intervals_2_results(intervals):\n average = lambda x: sum(x) / len(x)\n results = [\n (i, average(interval), max(interval)) for i, interval in enumerate(intervals)\n ]\n return results\n\nintervals = [nondupeIntervals, nondupeIntervals2]\nresults = intervals_2_results(intervals)\ntitle = "Testing of average distance and maximum distance"\nheaders = ["Interval", "Average Distance", "Maximum Distance"]\nsymbol = "~"\n# symbol = "¯\\_(ツ)_/¯"\n\nprint(\n results_2_table(results, title, headers, post=["", "f", ""], pre=">", symbol=symbol)\n)\n</code></pre>\n<p><sup> I dare you to uncomment the shrug Emoji line </sup></p>\n<p>Here we have extracted the construction of results from intervals into its own function (Good!). We have also written a pretty decent function for writing a pretty table for printing the results (Bad!). Why is the <code>results_2_table</code> bad? It has four flaws, the three last ones being worse than the first one</p>\n<ul>\n<li>It is a very general piece of code that does not inherently rely on any piece of existing code (A good sign that it could be extracted into its own module / function)</li>\n<li>It is far more advanced than what is needed. Meaning it would be far more expensive to maintain for a company.</li>\n<li>There exists existing solutions for this problem already. See <a href=\"https://beautifultable.readthedocs.io/en/latest/\" rel=\"nofollow noreferrer\">beautifultable</a>.</li>\n<li>Writing too advanced general code and not relying on external libraries tend to lead to bugs. See if you can find any in the <code>results_2_table</code> function, it should not be too hard.</li>\n</ul>\n<p>Do not reinvent the wheel except for educational purposes =)</p>\n<h3>An attempt at improvement</h3>\n<p>Unfortunately I do not have time to salvage your code, and this is left as\nan exercise for the reader. The most maintainable, readable, and fastest code is no code. Which is why before you start writing your own code, <em>always</em> do a deep search if an existing solution exists. In this case it almost does</p>\n<p><a href=\"https://numpy.org/doc/stable/reference/random/generated/numpy.random.choice.html\" rel=\"nofollow noreferrer\"><code>numpy.random.choice</code></a></p>\n<p>This can be used as <code>numpy.random.choice(elements, p = weights)</code> note that\nweights now have to sum to 1 for it to be a proper probability distribution. The only thing we are left with is increasing the probability for every element we have not picked. But wait.. Why not just <em>decrease</em> the probability for the element we picked? This seems much simpler to implement</p>\n<pre><code>def update_weights(elements, choice, weights)\n new_weights = weights.copy()\n choice_index = np.where(elements == choice)[0][0]\n new_weights[choice_index] *= 0.5\n return new_weights / sum(new_weights)\n</code></pre>\n<p>Again I encourage you to always read the documentation of new functions you encounter. Such as <a href=\"https://numpy.org/doc/stable/reference/generated/numpy.where.html?highlight=where#numpy.where\" rel=\"nofollow noreferrer\"><code>numpy.where</code></a>. Since we are using <code>numpy</code> for the randomization there is no reason not to use numpy arrays throughout our code.\nFor instance to generate the initial weights we can simply do</p>\n<pre><code>weights = np.full(len(elements), 1/len(elements))\n</code></pre>\n<p>Where you of course could have precomputed <code>len(elements)</code> if you feel inclined to do so. To make it more readable it could be better to include everything in a class</p>\n<pre><code>class DrawWeighted:\n def __init__(self, elements, prob_change_on_draw=0.9):\n self.elements = elements\n self.weights = self.default_weights()\n self.prob_change_on_draw = prob_change_on_draw\n\n def draw(self, times=1):\n choices = [""] * times\n for i in range(times):\n choice = np.random.choice(self.elements, p=self.weights)\n choices[i] = choice\n self.update_weights(choice)\n return choices[0] if len(choices) == 1 else choices\n\n def default_weights(self):\n return np.full(len(self.elements), 1 / len(self.elements))\n\n def update_weights(self, choice):\n new_weights = self.weights.copy()\n choice_index = np.where(self.elements == choice)[0][0]\n new_weights[choice_index] *= self.prob_change_on_draw\n self.weights = new_weights / sum(new_weights)\n</code></pre>\n<p>Where I leave it to you to add <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">proper docstrings</a> and sprinkle in comments <em>only</em> where you feel the intent of the code is not clear.</p>\n<h3>A change of perspective</h3>\n<p>The code above is not particularly fast. We still have to update the weights on every draw and yeah, it is actually not the best way to do this.</p>\n<p>If you can accept some <a href=\"https://en.wikipedia.org/wiki/Pseudorandomness\" rel=\"nofollow noreferrer\">pseudorandomness</a> there are better ways of doing this.\nI will show that you essentially end up with the same distribution at the end as well.. Our new algorithm will look as follows</p>\n<ul>\n<li>We create a <code>pool_size</code> which will have size of some multiple of how many items we have (Example <code>pool_size = 5 * len(elements)</code>).</li>\n<li>We <a href=\"https://numpy.org/doc/stable/reference/random/generated/numpy.random.shuffle.html\" rel=\"nofollow noreferrer\">shuffle</a> our list of elements <code>k</code> times where <code>k</code> is our <code>pool_size</code>.\nThese new lists are concatenated (put together) to form our <code>pool</code>.\nIf elements = [1,2,3] and <code>pool_size = 2</code> we could for instance have <code>pool = [1, 2, 3, 3, 1, 2]</code>.</li>\n<li>When we make a draw we pick the <code>n</code>'th element from pool and increase <code>n</code>.</li>\n<li>If <code>n</code>is smaller than some value, or have reached the end of our pool, we generate a new pool and start the process over again.</li>\n</ul>\n<p>This makes it possible to predict the next outcome, but the same can be said for your algorithm. The benefits of this is of course we do not have to make a random selection on every draw, but only when performing our shuffle. Since every element shows up an equal number of times, no element will be left behind. E.g not chosen for a long time (depends on your <code>pool_size</code> of course). A simple implementation is</p>\n<pre><code>class DrawShuffled:\n\n def __init__(self, elements, pool_size=[5, 10], minimal_pool=1):\n self.elements = elements\n self.elements_size = len(elements)\n self.min_pool = pool_size[0]\n self.max_pool = pool_size[1]\n self.minimal_pool = minimal_pool * self.elements_size + 1\n self.index = 0\n self.generate_pool()\n\n def generate_pool(self):\n self.size = np_random.integers(self.min_pool, self.max_pool)\n pool = []\n for _ in range(self.size):\n pool.extend(np_random.permutation(self.elements))\n self.pool = np_random.permutation(pool)\n self.pool_size = len(self.pool)\n self.index = 0\n\n def draw(self, times=1):\n choices = [""] * times\n for i in range(times):\n if self.index > self.pool_size - self.minimal_pool:\n self.generate_pool()\n choices[i] = self.pool[self.index]\n self.index += 1\n return choices[0] if len(choices) == 1 else choices\n</code></pre>\n<p>However.. If all we care about is a fast uniform distribution why not reduce the entire code into one line?</p>\n<pre><code>np.random.choice(letters, 200, replace=True)\n</code></pre>\n<p>Note that here you could run into the problem of some elements appearing more often than others.</p>\n<h3>Testing</h3>\n<p>Whenever one is rewriting code it is a great idea to have some simple testcases.\nI chose to use the alphabet as my list to pull from</p>\n<pre><code>import string\nTEST_DATA = np.array(list(string.ascii_lowercase))\n</code></pre>\n<p>which generates <code>TEST_DATA = ['a', 'b', ..., 'z']</code>. I will then draw 10^x items from each class / method, and compare the least frequent and most frequent drawn item.</p>\n<pre><code> numpy weighted shuffled \n X most least most least most least \n-------- ------ ------- ------ ------- ------ -------\n ````10 2 0 2 0 2 0 \n ```100 7 1 7 1 6 1 \n ``1000 50 23 44 34 46 34 \n `10000 422 360 388 379 404 373 \n 100000 3956 3719 3851 3842 3896 3793 \n</code></pre>\n<p>From the testing it is clear that</p>\n<ol>\n<li><code>numpy</code> (This is what we call <code>np.random.choice(letters, draws, replace=True)</code>) leads to a slightly higher variance</li>\n<li><code>DrawShuffled</code> and <code>DrawWeighted</code> are indistinguishable.</li>\n</ol>\n<p>From an implementation standpoint we have\n<code>DrawWeighted</code> > <code>DrawShuffled</code> >>> <code>numpy</code> for execution speed, but\n<code>numpy</code> > <code>DrawShuffled</code> > <code>DrawWeighted</code> for space complexity (how big are lists we have to store in memory). For me personally, unless there was a very strong reason not to, would just go with the numpy oneliner. Otherwise <code>DrawShuffled</code> seems random enough.</p>\n<p><strong>EDIT:</strong> Based on the comments I realized I had a small error in my testing data. This is now fixed. I have also included a bigger table which shows variance and the least picked element</p>\n<pre><code> numpy weighted shuffled \n X var least var least var least \n----- -------- ------- ------- ------- ------- -------\n ``2 0.071 0 0.071 0 0.071 0 \n ``7 0.274 0 0.274 0 0.197 0 \n `12 0.402 0 0.556 0 0.402 0 \n `17 0.534 0 0.38 0 0.611 0 \n `22 0.746 0 0.592 0 0.822 0 \n `27 0.96 0 0.652 0 1.268 0 \n `32 1.485 0 1.485 0 1.024 0 \n `37 1.321 0 1.013 0 0.859 0 \n `42 1.929 0 0.852 0 1.775 0 \n `47 1.925 0 1.155 0 2.155 0 \n `52 1.615 0 1.538 0 1.308 0 \n `57 1.771 0 1.771 0 1.155 0 \n `62 1.929 0 1.698 0 1.544 0 \n `67 3.859 0 1.706 1 1.09 1 \n `72 3.87 0 2.639 0 2.331 0 \n `77 4.652 0 2.652 1 1.729 0 \n `82 2.13 1 2.207 0 1.592 1 \n `87 2.996 1 1.765 1 1.149 1 \n `92 3.864 0 2.556 1 1.402 0 \n `97 4.043 1 3.735 1 1.812 1 \n 102 3.148 1 2.686 1 2.994 1 \n 107 5.025 1 3.256 1 2.871 1 \n 112 3.059 1 3.905 1 1.905 2 \n 117 4.481 2 5.404 1 0.788 3 \n 122 2.213 2 4.059 1 1.598 2 \n 127 7.487 0 2.102 2 2.179 2 \n 132 3.994 1 4.456 1 1.763 2 \n 137 4.12 2 3.428 2 1.197 3 \n 142 5.402 1 3.325 2 2.556 2 \n 147 2.688 2 4.842 1 3.457 3 \n 152 7.669 1 3.669 2 2.438 2 \n 157 3.806 3 4.729 2 0.806 4 \n 162 6.178 1 3.793 2 0.947 4 \n 167 5.706 1 4.167 0 2.936 3 \n 172 4.544 2 3.237 1 2.467 4 \n 177 7.617 1 2.771 3 1.232 5 \n 182 5.538 3 4.0 4 2.615 2 \n 187 5.54 3 4.617 3 3.848 3 \n 192 5.006 3 4.314 4 2.391 5 \n 197 4.629 3 3.629 4 3.783 4 \n 202 7.254 3 3.562 3 3.793 3 \n 207 5.883 4 4.114 3 1.96 4 \n 212 11.746 3 7.207 2 2.053 6 \n 217 5.226 4 4.303 4 3.072 4 \n 222 8.402 3 5.095 3 3.633 5 \n 227 6.658 3 5.351 4 3.197 5 \n 232 8.84 2 4.225 6 4.302 4 \n 237 9.025 2 5.564 3 2.794 6 \n 242 12.059 4 3.982 6 3.751 5 \n 247 7.404 5 4.865 3 3.865 6 \n 252 5.905 4 8.213 4 0.982 8 \n 257 12.256 4 8.102 5 1.256 8 \n</code></pre>\n<hr />\n<p>Do note that in my actual implementation I use</p>\n<pre><code>from numpy.random import default_rng\nnp_random = default_rng()\nnp_random. (function goes here)\n</code></pre>\n<p>instead of</p>\n<pre><code>import numpy as np\nnp.random. (function goes here)\n</code></pre>\n<p>per <a href=\"https://numpy.org/doc/stable/reference/random/index.html#random-quick-start\" rel=\"nofollow noreferrer\">numpy's recommendation</a>. Similarly my actual printing of tables is for the most part done with <a href=\"https://beautifultable.readthedocs.io/en/latest/\" rel=\"nofollow noreferrer\">beautifultables</a>.</p>\n<h3>Things left for the reader to explore:</h3>\n<ul>\n<li>Add <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">typing hints: PEP 484</a></li>\n<li>Add <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstrings</a></li>\n<li>Add comments where neccecary</li>\n</ul>\n<h3>Code with testing</h3>\n<pre><code>import string\nimport collections\nimport numpy as np\nfrom numpy.random import default_rng\n\nfrom beautifultable import BeautifulTable\n\nnp_random = np.random.default_rng()\n\nTEST_DATA = np.array(list(string.ascii_lowercase))\n\n\nclass DrawWeighted:\n def __init__(self, elements, prob_change_on_draw=0.90):\n self.elements = elements\n self.weights = self.default_weights()\n self.prob_change_on_draw = prob_change_on_draw\n\n def draw(self, times=1):\n choices = [""] * times\n for i in range(times):\n choices[i] = np_random.choice(self.elements, p=self.weights)\n self.update_weights(choices[i])\n return choices[0] if len(choices) == 1 else choices\n\n def default_weights(self):\n return np.full(len(self.elements), 1 / len(self.elements))\n\n def update_weights(self, choice):\n new_weights = self.weights.copy()\n choice_index = np.where(self.elements == choice)[0][0]\n new_weights[choice_index] *= self.prob_change_on_draw\n self.weights = new_weights / sum(new_weights)\n\n\nclass DrawShuffled:\n # Regenerates poolsize if less than 1 * minimal pool\n\n def __init__(self, elements, pool_size=[5, 10], minimal_pool=1):\n self.elements = elements\n self.elements_size = len(elements)\n self.min_pool = pool_size[0]\n self.max_pool = pool_size[1]\n self.minimal_pool = minimal_pool * self.elements_size + 1\n self.index = 0\n self.generate_pool()\n\n def generate_pool(self):\n self.size = np_random.integers(self.min_pool, self.max_pool)\n pool = []\n for _ in range(self.size):\n pool.extend(np_random.permutation(self.elements))\n self.pool = np_random.permutation(pool)\n self.pool_size = len(self.pool)\n self.index = 0\n\n def draw(self, times=1):\n choices = [""] * times\n for i in range(times):\n if self.index > self.pool_size - self.minimal_pool:\n self.generate_pool()\n choices[i] = self.pool[self.index]\n self.index += 1\n return choices[0] if len(choices) == 1 else choices\n\n\ndef numpy_draw(draws):\n return np_random.choice(TEST_DATA, draws, replace=True)\n\n\ndef run_testcases(test_cases, methods, data=TEST_DATA):\n results = {}\n for test_case in test_cases:\n results[test_case] = []\n for method in methods:\n counts = collections.Counter(dict.fromkeys(data, 0))\n for draw in method(test_case):\n counts[draw] += 1\n results[test_case].append(sorted(counts.values(), reverse=True))\n return results\n\n\ndef average(data):\n return sum(data) / len(data)\n\n\ndef variance(data):\n n = len(data)\n mean = sum(data) / n\n deviations = [(x - mean) ** 2 for x in data]\n variance = sum(deviations) / n\n return variance\n\n\ndef pretty_print(test_cases, test_results, method_names):\n avg = lambda x: sum(x) / len(x)\n\n def improve_table():\n table.set_style(BeautifulTable.STYLE_COMPACT)\n\n # The entire purpose of this part is to center "numpy, weighted and shuffled"\n header, *body = str(table).split("\\n")\n space = body[0].find(" ")\n header, body = "X".center(space + 1) + header[space + 1 :], "\\n".join(body)\n starts = [i for i, char in enumerate(header) if char == "m"]\n stops = [\n i for i, char in enumerate(header) if char == "t" and i - 3 not in starts\n ]\n extra_header = " " * len(header)\n for i, (start, end) in enumerate(zip(starts, stops)):\n extra_header = (\n extra_header[:start]\n + method_names[i].center(end - start)\n + extra_header[end + 1 :]\n )\n return "\\n".join([extra_header, header, body])\n\n longest_case = len(str(max(test_cases)))\n # print("=" * 79)\n print(f"Draws X elements from '{string.ascii_lowercase}' and")\n print("compares the most frequent and least frequent element drawn\\n")\n\n table = BeautifulTable()\n table.columns.header = ["most", "least"] * len(method_names)\n table.rows.header = [\n f"{'`' * (longest_case - len(str(case)))}{case}" for case in test_cases\n ]\n first, last = 0, -1\n for i, row in enumerate(test_results):\n table.rows[i] = row\n table.columns.alignment = BeautifulTable.ALIGN_RIGHT\n\n print(improve_table())\n\n\nif __name__ == "__main__":\n\n test_cases = [10 ** i for i in range(1, 6)]\n data = TEST_DATA\n\n methods = [numpy_draw, DrawWeighted(data).draw, DrawShuffled(data).draw]\n method_names = ["numpy", "weighted", "shuffled"]\n test_draw = run_testcases(test_cases, methods, data)\n results = []\n for draw in test_draw.values():\n row = []\n for method_result in draw:\n # Feel free to change max/min to average/variance\n row.append(max(method_result))\n row.append(min(method_result))\n results.append(row)\n\n pretty_print(test_cases, results, method_names)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T23:18:22.737",
"Id": "525078",
"Score": "0",
"body": "First, a question: *Should I have left out the debug code?* Much of your answer centers on it, when it is largely tangential and makes code significantly harder to understand. I tried to separate it from the algorithm implementation (which based on your feedback did not appreciably increase readability). Though it did yield relevant suggestions. Would have used f-strings everywhere, had I known they existed. (I'm not sure subjecting you to code comprehension torture is worth that one insight. My apologies.) I never leave debug code around because a week later I will have no idea what it does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T23:41:15.557",
"Id": "525079",
"Score": "0",
"body": "On style: I will have to disagree with you on global variables. \"Global\" is a matter of scope. A more correct advice is \"Declare variables in the scopes you intend to use them in.\" Which is what I have done. I have merely dispensed with the boilerplate of a class and use the file/module as a scope. You didn't answer this, but I think I found why some of my globals require the `global` keyword and others don't - reassigning requires it. All this is hacking things together in my spare time for educational purposes (hence wheel reinventing) and is not intended to resemble enterprise-grade code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T00:33:26.533",
"Id": "525084",
"Score": "0",
"body": "On the meat of the problem: You encourage me to look up unfamiliar functions, but that is the LEAST problem there. `update_weights` hides so much numpy arcana. You fail to even hint at how it overloads the comparison and division operators. Note that your algorithm isn't strictly equivalent to mine (yours is like `weight *= 2` in my code). And you can't do simple addition (though arguably that's also the least interesting weight adjustment). Your alternative algo is an interesting idea. Do you have any insights on the `O()` complexity? What's `np.random.choice`? Continued..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T00:49:59.427",
"Id": "525087",
"Score": "0",
"body": "The shuffle also changes the behaviour (if I'm reading it correctly) - you always draw each element once before you can draw a duplicate of it. If you have 200 elements and 200 draws, you will never get a duplicate. If you have 400 elements, you will always get 2 dupe draws. Also, I think you have an error - no way you ran `1e+100000` iterations of these algorithms."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T00:58:53.440",
"Id": "525088",
"Score": "0",
"body": "You also seem to be missing the point of the exercise. Where the weighted algorithm's performance is most interesting is when the draw count is similar to the pool size. Draws orders of magnitudes higher obliterates the differences and just makes you essentially draw sets of shuffled elements. Basically the weighted draw emulates the behaviour of the shuffle for draws >>> pool size. In a sense the misleading part is your `0.5` weight modifier, which is incredibly heavy."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T01:00:05.410",
"Id": "525089",
"Score": "0",
"body": "For example with your alphabet pool, just 4 extra draws(30 total) is enough to make the chance of not drawing each element once vanishingly small. TBH the mathematics of how this works is super fascinating to me, and I'd love to discuss it further, but is probably off topic here. Anyway, I have now also spent an hour examining your code which kind of makes us even. "
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T09:45:04.430",
"Id": "525096",
"Score": "0",
"body": "The proper way of handling state in python is using classes not global variables. Also I did run 10^5 simulations, what is wrong with that? Numpy is fast (C written), so low O(). If you want to allow repeated draws in Shuffle, just change `self.pool = nd.array(pool)` to `self.pool = np_random.permutation(np.array(pool))`. I picked the draw weight on random, making it close to 1 makes it act as `numpy.choice`, setting it close to 0 makes it act as `numpy.shuffle`, pick your poison =) Also using `self.X = X / sum(X)` is far more readable (and faster) than `self.X = [x / sum(X) for x in X]`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T13:09:59.557",
"Id": "525105",
"Score": "0",
"body": "Heheh... see, with your new testing data weighted and shuffled become different. Also, 10^5 and 10^100000 are different (you say 10^x and x=100000). :) And you did not answer the very top comment question I posed. I suppose I should bite the bullet and get into numpy finally. It's pretty close to being python's \"killer app\" anyway."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T13:36:10.647",
"Id": "525108",
"Score": "0",
"body": "Debugging should not be in the code, but tests are fine. I recommend using [doctests](https://docs.python.org/3/library/doctest.html) to unit test everything =)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-17T22:26:10.320",
"Id": "525719",
"Score": "0",
"body": "@martixy This can be done without `numpy`. [`random.choices()`](https://docs.python.org/3/library/random.html#random.choices) in the standard library takes a `weights` or `cum_weights` parameter. But, I would hazard a guess that `numpy` is faster."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T17:42:52.497",
"Id": "265833",
"ParentId": "265765",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T10:05:20.863",
"Id": "265765",
"Score": "2",
"Tags": [
"python",
"performance",
"python-3.x"
],
"Title": "Weighted draw/raffle (biased towards undrawn)"
}
|
265765
|
<p>I am trying to learn Go concurrency patterns and best practices on my own.<br/>
I have invented a simple task for myself.<br/>
I want to process a slice of integers in a parallel manner by dividing it into sub-slices and process each with a goroutine.<br/>
Below is the solution I have at the moment, I seek constructive code review.<br/>
If you have any questions or clarifications/updates are needed, please leave a comment.<br/></p>
<pre><code>// TASK:
// given the slice of integers, multiply each element by 10
// apply concurrency to solve this task by splitting slice into subslices and feeding them to goroutines
// EXAMPLE:
// input -> slice := []int{ 1, 2, 3, 4, 5, 6, 7, 8 }
// output -> slice := []int{ 10, 20, 30, 40, 50, 60, 70, 80 }
package main
import (
"fmt"
"sync"
"time"
)
func simulate_close_signal(quit chan bool, wg *sync.WaitGroup) {
defer close(quit)
defer wg.Done() // maybe I can remove this?
for {
select {
case <-time.After(1 * time.Second):
fmt.Println("Close signal sent")
return
}
}
}
func process_subslice(quit chan bool,
wg *sync.WaitGroup,
original_slice []int,
subslice_starting_index int,
subslice_ending_index int,
timeout func()) {
defer wg.Done()
for {
select {
case <-quit:
fmt.Println("Goroutine: received request to close, quiting...")
return
default:
// do I need mutex here? I think I don't since each goroutine processes independent subslice...
original_slice[subslice_starting_index] = original_slice[subslice_starting_index] * 10
subslice_starting_index++
if subslice_starting_index >= subslice_ending_index {
return
}
timeout() // added so I can test close signal
}
}
}
func main() {
slice := []int{1, 2, 3, 4, 5, 6, 7, 8}
fmt.Println("Starting slice: ", slice)
quit := make(chan bool)
wg := sync.WaitGroup{}
for i := 0; i < 2; i++ {
wg.Add(1)
go process_subslice(quit,
&wg,
slice,
i*4, // this way slice is divided
(1+i)*4, // in two subslices with indexes [0, 3] and [4,7]
func() { time.Sleep(1 * time.Second) }) // pass empty func to test normal execution
}
wg.Add(1)
go simulate_close_signal(quit, &wg)
wg.Wait()
fmt.Println("Processed slice: ", slice)
}
</code></pre>
<p><a href="https://play.golang.org/p/mSAE-HCAmZj" rel="nofollow noreferrer">The Go Playground</a></p>
|
[] |
[
{
"body": "<p>Looks fine, as you wrote, you don't need <code>simulate_close_signal</code> to be in the wait group since the <code>wg.Wait</code> call will already synchronise the access to <code>slice</code> later for the other two goroutines that write to it.</p>\n<p>Other than that, you might as well make the <code>quit</code> channel a <code>chan struct{}</code>, since there's nothing being written, or read from it, the only purpose is to be able to <code>close</code> it, so you can just make that explicit.</p>\n<p>Dividing up the slice like this is of course doable, though I'd really suggest you simply create an actual subslice instead of passing around the indexes, that's what they're for (they'll all share the underlying array, just point to different parts of it). Alternatively you could create an actual array with the fixed dimensions if you don't need the slice capabilities (e.g. <code>[8]int{1, 2, 3, 4, 5, 6, 7, 8}</code>).</p>\n<p>Edit: Mind you, now I actually ran it in the playground. The version you posted consistently gives <code>[10 20 3 4 50 60 7 8]</code> as the result? Have you tried it before posting?</p>\n<p>The non-blocking read from <code>quit</code> doesn't work quite as you'd like it to. If you simply print something in the multiplication part you'll notice it enters that block twice - that can happen, as nothing is being read from the <code>quit</code> channel yet. Normally I'd say you can simply drop the <code>select</code>, it serves no purpose here. Alternatively you'd have to deal with the <code>default</code> case being executed once, twice, more, or even never!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T09:00:56.247",
"Id": "525145",
"Score": "1",
"body": "Thank you for answering! Regarding your edit: it seemed OK to me, since there is 1 second period before goroutines receive termination signal. I thought that in that period both routines had time to start and process part of the subslice. `default` case being executed arbitrary number of times (or never) is fine in this scenario."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-12T13:29:05.743",
"Id": "525395",
"Score": "1",
"body": "Upvoted, added bounty and officially accepted. Thanks."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T04:36:49.553",
"Id": "265872",
"ParentId": "265766",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "265872",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T10:46:35.853",
"Id": "265766",
"Score": "1",
"Tags": [
"go"
],
"Title": "Concurrent processing of a slice"
}
|
265766
|
<p><a href="https://archive.ics.uci.edu/ml/datasets/iris" rel="nofollow noreferrer">Iris Data Set</a> consists of three classes in which versicolor and virginica are not linearly separable from each other.</p>
<p>I constructed a subset for these two classes, here is the code</p>
<pre><code>from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
import numpy as np
iris = load_iris()
x_train = iris.data[50:]
y_train = iris.target[50:]
y_train = y_train - 1
x_train, x_test, y_train, y_test = train_test_split(
x_train, y_train, test_size=0.33, random_state=2021)
</code></pre>
<p>and then I built a Logistic Regression model for this binary classification</p>
<pre><code>def sigmoid(z):
s = 1 / (1 + np.exp(-z))
return s
class LogisticRegression:
def __init__(self, eta=.05, n_epoch=10, model_w=np.full(4, .5), model_b=.0):
self.eta = eta
self.n_epoch = n_epoch
self.model_w = model_w
self.model_b = model_b
def activation(self, x):
z = np.dot(x, self.model_w) + self.model_b
return sigmoid(z)
def predict(self, x):
a = self.activation(x)
if a >= 0.5:
return 1
else:
return 0
def update_weights(self, x, y, verbose=False):
a = self.activation(x)
dz = a - y
self.model_w -= self.eta * dz * x
self.model_b -= self.eta * dz
def fit(self, x, y, verbose=False, seed=None):
indices = np.arange(len(x))
for i in range(self.n_epoch):
n_iter = 0
np.random.seed(seed)
np.random.shuffle(indices)
for idx in indices:
if(self.predict(x[idx])!=y[idx]):
self.update_weights(x[idx], y[idx], verbose)
else:
n_iter += 1
if(n_iter==len(x)):
print('model gets 100% train accuracy after {} epoch(s)'.format(i))
break
</code></pre>
<p>I added the param <code>seed</code> for reproduction.</p>
<pre><code>import time
start_time = time.time()
w_mnist = np.full(4, .1)
classifier_mnist = LogisticRegression(.05, 1000, w_mnist)
classifier_mnist.fit(x_train, y_train, seed=0)
print('model trained {:.5f} s'.format(time.time() - start_time))
y_prediction = np.array(list(map(classifier_mnist.predict, x_train)))
acc = np.count_nonzero(y_prediction==y_train)
print('train accuracy {:.5f}'.format(acc/len(y_train)))
y_prediction = np.array(list(map(classifier_mnist.predict, x_test)))
acc = np.count_nonzero(y_prediction==y_test)
print('test accuracy {:.5f}'.format(acc/len(y_test)))
</code></pre>
<p>The accuracy is</p>
<pre><code>train accuracy 0.95522
test accuracy 0.96970
</code></pre>
<p>the <a href="https://github.com/albert10jp/deep-learning/blob/main/LR_on_not_linearly_separable_data.ipynb" rel="nofollow noreferrer">link</a> is my github repo</p>
|
[] |
[
{
"body": "<p>This is a very nice little project but there are some thing to upgrade here :)</p>\n<hr />\n<p><strong>Code beautification</strong></p>\n<ol>\n<li>Split everything to functions, there is no reason to put logic outside of a function, including the prediction part (this will remove the code duplication) and call everything from a <code>main</code> function. For example a loading function:</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>def load_and_split_iris(data_cut: int=50, train_test_ratio: float=0,333)\n iris = load_iris()\n x_train = iris.data[data_cut:]\n y_train = iris.target[data_cut:]\n y_train = y_train - 1\n x_train, x_test, y_train, y_test = train_test_split(\n x_train, y_train, test_size=train_test_ratio, random_state=2021)\n return x_train, x_test, y_train, y_test\n</code></pre>\n<ol start=\"2\">\n<li>Magic numbers make your code look bad, turn them into a <code>CODE_CONSTANTS</code>.</li>\n<li>I really like type annotations, it will make your code more understandable for future usage and you will not confuse with the types. I added them in the code example in 1. Another example: <code>def fit(self, x: np.array, y: np.array, verbose: bool=False, seed: int=None):</code>. Type annotation can also declare return type, read into that.</li>\n<li>String formatting, this: <code>'model gets 100% train accuracy after {} epoch(s)'.format(i)</code> and turn into <code>f'model gets 100% train accuracy after {i} epoch(s)'</code>.</li>\n</ol>\n<p><strong>Bug</strong></p>\n<p>You reset the seed every loop (<code>LogisticRegression.fit</code>), in case you are passing <code>None</code> this is fine (since the OS will generate random for you) but if you pass a specific seed the numbers will be the same each time you shuffle. Take the seed setting outside of the loop.</p>\n<p><strong>Future work</strong></p>\n<p>If you are looking to continue the work I recommend to try and create a multiclass logistic regression.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T11:59:48.500",
"Id": "265773",
"ParentId": "265767",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "265773",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T11:00:03.783",
"Id": "265767",
"Score": "0",
"Tags": [
"python",
"machine-learning"
],
"Title": "Logistic Regression for non linearly separable data"
}
|
265767
|
<p>I work at an application that receives data from user and I try to write a validator function for it, but I'm not sure if this is the correct way to proceed.</p>
<p>Example: The user will input a number (as string, don't ask why I don't use an int, let it be a string), let's say "103", and I'will use this number inside a function, but first, at the beginning of that function I call a validator function:</p>
<pre><code>private bool ValidateCommandCode(string code)
{
bool isValid = false;
byte commandByte = new byte();
if (byte.TryParse(code, out commandByte))
{
isValid = true;
}
else
{
Log.Error($"Command number {CommandCode} for the request is not valid!");
isValid = false;
}
return isValid;
}
private async void MainFunction()
{
if (ValidateCommandCode(CommandCode) == false)
return;
// ... do the magic with the CommandCode ...
}
</code></pre>
<p>in the same manner, I want to validate another field filled by the user: e.g of data: 000A000B</p>
<pre><code>private bool ValidateRequestData(string data)
{
bool isValid = false;
if (!String.IsNullOrEmpty(Payload) && !String.IsNullOrWhiteSpace(Payload))
{
if (Payload.Trim().Replace(" ", "").Length % 2 != 0)
{
Log.Error($"Payload (Data) {Payload} for the request doesn't have an even number of bytes!");
isValid = false;
}
else
{
isValid = true;
}
}
else
{
isValid = true;
}
return isValid;
}
</code></pre>
<p>Is this a good way to proceed? Aren't so many flags "isValid" too confusing?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T12:33:43.997",
"Id": "524963",
"Score": "0",
"body": "\"an application that receives data from user\" -- what kind of application? In many cases you would be far better off with a relevant NuGet package. Also, why did you tag this \"unit testing\"? This has got nothing to do with that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T12:50:58.877",
"Id": "524965",
"Score": "1",
"body": "I removed [tag:unit-testing], as you haven't shown us the unit-tests for this code."
}
] |
[
{
"body": "<p>First off, in here</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>if (!String.IsNullOrEmpty(Payload) && !String.IsNullOrWhiteSpace(Payload))\n</code></pre>\n<p>You only need to do</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>if(!String.IsNullOrWhiteSpace(Payload))\n</code></pre>\n<p>There is a lot of nesting going on and you can simplify your code to make it easier to read by doing this instead</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>private static bool ValidateRequestData(string data, string payload)\n{\n if (String.IsNullOrWhiteSpace(data)) return false; // or throw\n if (String.IsNullOrWhiteSpace(payload)) return false;\n\n if (payload.Trim().Replace(" ", "").Length % 2 != 0)\n {\n //Log.Error(...);\n return false;\n }\n \n return true\n}\n</code></pre>\n<p>If you also notice, we are passing in the <code>payload</code> as an argument and also make this a <code>static</code> method. This is generally a safer design as the state of your member <code>Payload</code> is likely not guaranteed to remain the same (or at least it's not obvious).</p>\n<p>I would also recommend changing the method name from <code>ValidateRequestData()</code> to <code>IsValidRequestData()</code>.</p>\n<hr />\n<p>As an extra. We can also clean up you other method</p>\n<pre class=\"lang-csharp prettyprint-override\"><code>private static bool ValidateCommandCode(string code)\n{\n if (!byte.TryParse(code, out byte commandByte))\n {\n //Log.Error(...);\n return false;\n }\n\n return true;\n}\n</code></pre>\n<p>Although, keep in mind the <code>Parse</code> could probably have happened somewhere else. It doesn't seem very efficient to do a parse only for the purpose of validation and not making any use of the result.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T12:06:26.030",
"Id": "524962",
"Score": "0",
"body": "Great! Thank you for the help! It's a lot cleaner now."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T11:56:32.503",
"Id": "265772",
"ParentId": "265770",
"Score": "5"
}
},
{
"body": "<p>You can simplify it further like this :</p>\n<pre><code>private bool ValidateRequestData(string data)\n{\n return !string.IsNullOrWhiteSpace(Payload) && Payload.Trim().Replace(" ", "").Length % 2 != 0;\n}\n\nprivate bool ValidateCommandCode(string code)\n{\n return byte.TryParse(code, out byte commandByte);\n}\n</code></pre>\n<p>and for the logging, I would suggest you keep it outside the validation itself, so you know which part of your code has logged it, and in this way, you can control the logging to which part of your code should log the validation.</p>\n<pre><code>private async void MainFunction()\n{\n if(!ValidateCommandCode(CommandCode))\n {\n Log.Error($"Command number {CommandCode} for the request is not valid!"); \n }\n else\n {\n // ... do the magic with the CommandCode ... \n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T20:52:41.347",
"Id": "525003",
"Score": "0",
"body": "You have the same method signature twice: `ValidateRequestData(string)`. I assume one of them was meant to be named differently?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T21:23:46.597",
"Id": "525004",
"Score": "0",
"body": "@BrianJ good catch, yes you're right, they're different, but my clipboard thoughts not ;). fixed it though."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T19:45:02.430",
"Id": "265796",
"ParentId": "265770",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "265772",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T11:33:10.857",
"Id": "265770",
"Score": "3",
"Tags": [
"c#",
"validation"
],
"Title": "Input Data Validator (good practice)"
}
|
265770
|
<p>Compared to my another post <a href="https://codereview.stackexchange.com/q/265767/233283">Logistic Regression for non linearly separable data</a> which uses one-layer net, i.e. Logistic Regression to classify the iris data set, this post is to discuss the tensorflow method.</p>
<pre><code>iris = load_iris()
x_train, x_test, y_train, y_test = train_test_split(
iris.data, iris.target, test_size=0.33, random_state=2021)
y_train=np_utils.to_categorical(y_train, num_classes=3)
y_test=np_utils.to_categorical(y_test, num_classes=3)
model = tf.keras.Sequential([
tf.keras.layers.Dense(500, input_dim=4, activation='relu'),
tf.keras.layers.Dense(256, activation='relu'),
tf.keras.layers.Dense(256, activation='relu'),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(3, activation='softmax')
])
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
model.fit(x_train,y_train, validation_data=(x_test,y_test), batch_size=20,epochs=30,verbose=0)
prediction=model.predict(x_train)
length=len(prediction)
y_label=np.argmax(y_train,axis=1)
predict_label=np.argmax(prediction,axis=1)
accuracy=np.sum(y_label==predict_label)/length * 100
print("Accuracy of the dataset",accuracy )
prediction=model.predict(x_test)
length=len(prediction)
y_label=np.argmax(y_test,axis=1)
predict_label=np.argmax(prediction,axis=1)
accuracy=np.sum(y_label==predict_label)/length * 100
print("Accuracy of the dataset",accuracy )
</code></pre>
<p>The accuracy is</p>
<pre><code>Accuracy of the dataset 99.0
Accuracy of the dataset 94.0
</code></pre>
<p>I've tried several times, this is the best performance.</p>
<p>I also tried more and less neurons and layers, the one above is the best.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T12:08:34.870",
"Id": "525039",
"Score": "0",
"body": "As I understand from your post (and previous post) you are not looking for a code review, you are looking for a model review. I believe this is not the correct platform for you to look for answers. Consider looking online for [Hyper-parameter Tuning Techniques](https://towardsdatascience.com/hyper-parameter-tuning-techniques-in-deep-learning-4dad592c63c8)."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T11:48:19.897",
"Id": "265771",
"Score": "1",
"Tags": [
"python",
"machine-learning",
"tensorflow"
],
"Title": "The best tensorflow neural net I got so far for iris dataset"
}
|
265771
|
<p>I am a beginner in C and am learning linked lists. I have made a program to implement a linked list, allowing certain operations on the linked list.</p>
<p>There are 3 functions:</p>
<ul>
<li><code>addnode()</code> adds node to end of list</li>
<li><code>printlist()</code> prints the whole linked list</li>
<li><code>insertnode()</code> inserts a node after a specified node</li>
</ul>
<h2>addnode():</h2>
<pre><code>void addnode(struct node **head)
{
if (*head == NULL)
{
struct node *newNode = (struct node*) malloc(sizeof(struct node));
*head = newNode;
printf("enter data: ");
scanf("%d",&((*head)->data));
(*head)->node = NULL;
}
else
{
struct node *newNode = (struct node*) malloc(sizeof(struct node));
printf("enter data: ");
scanf("%d", &(newNode->data));
newNode->node = NULL;
struct node *temp = *head;
while (temp->node != NULL)
{
temp = temp->node;
}
temp->node = newNode;
}
}
</code></pre>
<h2>printlist():</h2>
<pre><code>void printlist(struct node **head)
{
struct node *temp = *head;
while (temp->node != NULL)
{
printf("%d--", temp->data);
temp = temp->node;
}
printf("NULL\n");
}
</code></pre>
<h2>insertnode():</h2>
<pre><code>int insertnode(struct node **head)
{
int i, j = 0;
printf("enter what node you want to insert node after: ");
scanf("%d", &i);
struct node *temp = *head;
while (temp->node != NULL)
{
if (i-1 == j)
{
struct node *newNode = (struct node*) malloc(sizeof(struct node));
printf("enter data: ");
scanf("%d", &i);
newNode->data = i;
newNode->node = temp->node;
temp->node = newNode;
break;
}
temp = temp->node; j++;
}
return 0;
}
</code></pre>
<p>How well have I implemented these functions?</p>
<p>Is my code easy to read?</p>
<p>What could I improve?</p>
<p>Does it abide by popular good coding practices?</p>
<p>Here is my <code>main()</code> function and function prototypes:</p>
<pre><code>struct node
{
int data;
struct node *node;
};
void addnode(struct node **head);
void printlist(struct node **head);
int insertnode(struct node **head);
int main()
{
struct node *head = NULL;
addnode(&head);
addnode(&head);
addnode(&head);
addnode(&head);
printlist(&head);
insertnode(&head);
printlist(&head);
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>We're missing includes of the library headers which provide function prototypes:</p>\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n</code></pre>\n<hr />\n<p>A popular naming convention is to use a distinctive prefix (rather than a suffix) for the function names, so that they appear together in alphabetical lists: <code>node_add()</code>, <code>node_insert()</code>, <code>node_print()</code>.</p>\n<hr />\n<p>We're missing a function to return the memory we're using. If we run under Valgrind, we see that we leak the memory we allocated, so we really need a <code>node_free()</code> function.</p>\n<hr />\n<p><code>addnode()</code> performs two functions: reading user input and inserting the node. It would be more useful if we separate the functions:</p>\n<pre><code>addnode(struct node **head, int value);\n</code></pre>\n<p>The same is true for <code>insertnode()</code>.</p>\n<hr />\n<p><code>insertnode()</code> always returns 0. It looks like you were anticipating a different return value when the target node wasn't found, but didn't implement that.</p>\n<hr />\n<p><code>printnode()</code> would be better if it weren't restricted to writing only to standard output. Users might want to write to standard error, or a file, a device or a socket.</p>\n<hr />\n<p>We are not robust when allocating memory:</p>\n<blockquote>\n<pre><code> struct node *newNode = (struct node*) malloc(sizeof(struct node));\n newNode->data = i;\n newNode->node = temp->node;\n</code></pre>\n</blockquote>\n<p><code>malloc()</code> returns a <code>void*</code>, which can be assigned directly to any object-pointer type without needing a cast. A good practice for computing the required size is to measure the size of the pointed-to value, rather than its type:</p>\n<pre><code> struct node *newNode = malloc(sizeof *newNode);\n</code></pre>\n<p>Then we need a test before we dereference the pointer:</p>\n<pre><code> if (!newNode) {\n return NODE_FAILURE;\n }\n</code></pre>\n<hr />\n<p>The other area where we need to be more robust is user input. We're ignoring the return value from <code>scanf()</code>, but that means we have no idea whether it succeeded or not. That leads to unpredictable behaviour, as Valgrind reveals:</p>\n<pre class=\"lang-none prettyprint-override\"><code>valgrind --leak-check=full ./265776 <<<''\n==2932516== Memcheck, a memory error detector\n==2932516== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.\n==2932516== Using Valgrind-3.16.1 and LibVEX; rerun with -h for copyright info\n==2932516== Command: ./265776\n==2932516== \n==2932516== Conditional jump or move depends on uninitialised value(s)\n==2932516== at 0x48DE29F: __vfprintf_internal (vfprintf-internal.c:1687)\n==2932516== by 0x48C9D9A: printf (printf.c:33)\n==2932516== by 0x1092E7: printlist (265776.c:66)\n==2932516== by 0x1091B0: main (265776.c:19)\n==2932516== \n==2932516== Use of uninitialised value of size 8\n==2932516== at 0x48C3EFB: _itoa_word (_itoa.c:179)\n==2932516== by 0x48DD8B7: __vfprintf_internal (vfprintf-internal.c:1687)\n==2932516== by 0x48C9D9A: printf (printf.c:33)\n==2932516== by 0x1092E7: printlist (265776.c:66)\n==2932516== by 0x1091B0: main (265776.c:19)\n==2932516== \n==2932516== Conditional jump or move depends on uninitialised value(s)\n==2932516== at 0x48C3F0C: _itoa_word (_itoa.c:179)\n==2932516== by 0x48DD8B7: __vfprintf_internal (vfprintf-internal.c:1687)\n==2932516== by 0x48C9D9A: printf (printf.c:33)\n==2932516== by 0x1092E7: printlist (265776.c:66)\n==2932516== by 0x1091B0: main (265776.c:19)\n==2932516== \n==2932516== Conditional jump or move depends on uninitialised value(s)\n==2932516== at 0x48DE660: __vfprintf_internal (vfprintf-internal.c:1687)\n==2932516== by 0x48C9D9A: printf (printf.c:33)\n==2932516== by 0x1092E7: printlist (265776.c:66)\n==2932516== by 0x1091B0: main (265776.c:19)\n==2932516== \n==2932516== Conditional jump or move depends on uninitialised value(s)\n==2932516== at 0x48DDA2E: __vfprintf_internal (vfprintf-internal.c:1687)\n==2932516== by 0x48C9D9A: printf (printf.c:33)\n==2932516== by 0x1092E7: printlist (265776.c:66)\n==2932516== by 0x1091B0: main (265776.c:19)\n==2932516== \nenter data: enter data: enter data: enter data: 0--0--0--NULL\n==2932516== Conditional jump or move depends on uninitialised value(s)\n==2932516== at 0x109362: insertnode (265776.c:83)\n==2932516== by 0x1091BC: main (265776.c:21)\n==2932516== \n==2932516== Conditional jump or move depends on uninitialised value(s)\n==2932516== at 0x48DE29F: __vfprintf_internal (vfprintf-internal.c:1687)\n==2932516== by 0x48C9D9A: printf (printf.c:33)\n==2932516== by 0x1092E7: printlist (265776.c:66)\n==2932516== by 0x1091C8: main (265776.c:22)\n==2932516== \n==2932516== Conditional jump or move depends on uninitialised value(s)\n==2932516== at 0x48DE660: __vfprintf_internal (vfprintf-internal.c:1687)\n==2932516== by 0x48C9D9A: printf (printf.c:33)\n==2932516== by 0x1092E7: printlist (265776.c:66)\n==2932516== by 0x1091C8: main (265776.c:22)\n==2932516== \n==2932516== Conditional jump or move depends on uninitialised value(s)\n==2932516== at 0x48DDA2E: __vfprintf_internal (vfprintf-internal.c:1687)\n==2932516== by 0x48C9D9A: printf (printf.c:33)\n==2932516== by 0x1092E7: printlist (265776.c:66)\n==2932516== by 0x1091C8: main (265776.c:22)\n==2932516== \nenter what node you want to insert node after: 0--0--0--NULL\n==2932516== \n==2932516== HEAP SUMMARY:\n==2932516== in use at exit: 64 bytes in 4 blocks\n==2932516== total heap usage: 6 allocs, 2 frees, 5,184 bytes allocated\n==2932516== \n==2932516== 64 (16 direct, 48 indirect) bytes in 1 blocks are definitely lost in loss record 4 of 4\n==2932516== at 0x483877F: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)\n==2932516== by 0x1091F1: addnode (265776.c:37)\n==2932516== by 0x109180: main (265776.c:14)\n==2932516== \n==2932516== LEAK SUMMARY:\n==2932516== definitely lost: 16 bytes in 1 blocks\n==2932516== indirectly lost: 48 bytes in 3 blocks\n==2932516== possibly lost: 0 bytes in 0 blocks\n==2932516== still reachable: 0 bytes in 0 blocks\n==2932516== suppressed: 0 bytes in 0 blocks\n</code></pre>\n<hr />\n<p>With some care, we don't need a separate code path for an empty list:</p>\n<pre><code>int node_add(struct node **head, int value)\n{\n while (*head) {\n head = &(*head)->node;\n }\n\n struct node *newNode = malloc(sizeof *newNode);\n if (!newNode) {\n return 1;\n }\n\n newNode->data = value;\n newNode->node = NULL;\n *head = newNode;\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T15:26:09.653",
"Id": "524979",
"Score": "0",
"body": "thanks for this insightful look into my programs pros and cons i appreciate it a lot ! =)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T14:37:48.927",
"Id": "265780",
"ParentId": "265776",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "265780",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T12:50:20.367",
"Id": "265776",
"Score": "2",
"Tags": [
"c",
"linked-list",
"pointers"
],
"Title": "Linked list - append, insert, print"
}
|
265776
|
<p>After yesterday suggestions, I was told... recommended to move over to ORM and I did. I choosed to use <strong>PeeWee</strong> together with PostgreSQL. <a href="https://codereview.stackexchange.com/questions/265741/queries-for-storing-and-get-information-from-postgresql?noredirect=1#comment524956_265741">Queries for storing and get information from postgreSQL</a></p>
<p>This is how my currenty code looks like:</p>
<pre><code>import pendulum
from peewee import (
Model,
TextField,
IntegerField,
DateTimeField, BooleanField, CompositeKey
)
from playhouse.pool import PooledPostgresqlDatabase
from config import configuration
postgres_pool = PooledPostgresqlDatabase(
configuration.postgresql.database,
host=configuration.path.database.environment,
user=configuration.postgresql.user,
password=configuration.postgresql.password,
max_connections=100,
stale_timeout=60,
)
# ------------------------------------------------------------------------------- #
# store_config table
# ------------------------------------------------------------------------------- #
class Stores(Model):
id = IntegerField(column_name='store_id')
store = TextField(column_name='store')
class Meta:
database = postgres_pool
db_table = "store_config"
primary_key = CompositeKey('store')
@classmethod
# All stores found in the database
def all_stores(cls):
try:
return cls.select(cls.id, cls.store).order_by(cls.id)
except Stores.DoesNotExist:
return None
@classmethod
# Insert new row if not in the database
def getsert(cls, store_name):
try:
return cls.get_or_create(store=store_name)
except Stores.IntegrityError:
return None
# ------------------------------------------------------------------------------- #
# feed_urls table
# ------------------------------------------------------------------------------- #
class Feeds(Model):
store = TextField(column_name='store')
link = TextField(column_name='link')
class Meta:
database = postgres_pool
db_table = "feed_urls"
@classmethod
# Get all feeds url that is in given store
def all_feed_urls(cls, store):
try:
return cls.select().where(cls.store.contains(store))
except Feeds.DoesNotExist:
return None
# ------------------------------------------------------------------------------- #
# sample_keywords table
# ------------------------------------------------------------------------------- #
class Keywords(Model):
filter_type = BooleanField(column_name='filter_type')
keyword = TextField(column_name='keyword')
class Meta:
database = postgres_pool
db_table = "sample_keywords"
@classmethod
# Return all keywords stored in the database
def all_keywords(cls):
try:
return cls.select()
except Keywords.DoesNotExist:
return None
# ------------------------------------------------------------------------------- #
# store_items table
# ------------------------------------------------------------------------------- #
class Products(Model):
id = IntegerField(column_name='id')
store = TextField(column_name='store')
name = TextField(column_name='name')
link = TextField(column_name='link')
image = TextField(column_name='image')
visible = TextField(column_name='visible')
added_date = DateTimeField(column_name='added_date')
class Meta:
database = postgres_pool
db_table = "store_items"
@classmethod
# Check if given store and link exists in the database
def store_url_exists(cls, store, link):
try:
return cls.select().where((cls.store.contains(store)) & (cls.link.contains(link))).store_url_exists()
except Products.DoesNotExist:
return None
@classmethod
# Return all urls that contains the store and has the visible set to "yes"
def active_urls(cls, store):
try:
return cls.select().where((cls.store.contains(store)) & (cls.visible == "yes"))
except Products.DoesNotExist:
return None
@classmethod
# Add product to the database
def add_product(cls, store, pageData):
try:
return cls.insert(
store=store,
name=pageData.name,
link=pageData.link,
image=pageData.image,
visible="yes",
added_date=pendulum.now('Europe/Stockholm').format('YYYY-MM-DD HH:mm:ss.SSSSSS')
).execute()
except Products.DoesNotExist:
return None
</code></pre>
<p>For my eyes it starts to look pretty and I do like the new changes I have done however there is still probably more to be improved and yet there is some stuff that I am concerned about that was mentioned in previous thread.</p>
<ol>
<li><p>I do have a primary key but that was created straight when I created table in postgreSQL. I did put the Primary key as ID (with auto increment) but I do starting to understand that it is not a good option to do that since there is a chance that a I coud have multiple same URL inserted to the database which could get caught by primary key but I did not. I do believe there should be some improvement here</p>
</li>
<li><p>In class Products, I use <code>store_url_exists</code> which basically should be together with <code>add_product</code> and the reason of it is basically that if the URL is not in the database then we should add it and now I have created two queries and I believe it would be better to have it as one but not sure how...?</p>
</li>
<li><p>Bad labeling for @classmethod?</p>
</li>
</ol>
<p>I do hope you have seen my improvements and hopefully you do see that those recommendation you have given me is what I do take with me and trying to improve :)</p>
<p>Looking forward!</p>
|
[] |
[
{
"body": "<p>I am not familiar with that ORM so at this time I will only provide superficial comments.</p>\n<p>Suggestions anyway:</p>\n<p>Keep all your imports and from ... import on top of the file and group them together.</p>\n<p>Keep your <strong>data model</strong> in a <strong>separate</strong> Python file, and import it. The point is to better separate the different components of your program.\nThus your data model can be imported by other scripts. Larger applications are usually divided in multiple Python files anyway.</p>\n<p>Regarding the functions like store_url_exists etc, in my opinion they don't belong to your class. Just keep what is strictly necessary for the functioning of your class. But you could move those functions to another helper file. You import it when you need it.</p>\n<p>Restructuring your app this way will declutter the main routine and the code will become more compact and more clear as a result :)</p>\n<p>I think you should also start taking the habit of <strong>logging</strong> events, especially <strong>exceptions</strong>. It doesn't hurt to have a default <strong>exception handler</strong> for your application.</p>\n<p>For instance you have this function:</p>\n<pre><code>def getsert(cls, store_name):\n try:\n return cls.get_or_create(store=store_name)\n except Stores.IntegrityError:\n return None\n</code></pre>\n<p>In case of errors it returns None, but you have zero details about the underlying error. You <strong>swallowed</strong> it. So you cannot immediately investigate and troubleshoot the issue because you have no trace. At least we hope you will check that the function did not return None.</p>\n<p>This is not an event you should be ignoring, instead you should log the details of the error to a file for persistence, and notify the user something did go wrong. When something that bad happens you don't continue. Because the program is going to behave badly and unpredictably.</p>\n<p>In my eyes this is a critical error, in fact I would probably not even bother handling IntegrityError within that function, but I would instead let the default exception handler take over and terminate the application gracefully.</p>\n<p>If the error is recoverable then you can try to rectify the situation. For example if the connection to the DB was lost because of a network failure, you could reconnect automatically. This is actually expected from a mature application. Restoring a connection is more user-friendly than having to close the program and start it again.</p>\n<p>Regarding this function:</p>\n<pre><code>def all_feed_urls(cls, store):\n try:\n return cls.select().where(cls.store.contains(store))\n except Feeds.DoesNotExist:\n return None\n</code></pre>\n<p>Have you tested that it triggers DoesNotExist if now rows are found ? DoesNotExist is mentioned in the <a href=\"http://docs.peewee-orm.com/en/latest/peewee/api.html#Model.select\" rel=\"nofollow noreferrer\">documentation</a> with regards to the .get method but I am not sure how it applies to .Select. My question is whether .Select would return an iterator of rows that is empty or raise DoesNotExist. I cannot test it on my end but encourage you to do so. Always test edge cases :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T14:39:03.177",
"Id": "525045",
"Score": "0",
"body": "Appreciate the awesome feedback once again!! Was much needed as I wanted and appreciate it again! :) Thank you"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T22:47:19.247",
"Id": "265803",
"ParentId": "265777",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "265803",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T13:23:20.757",
"Id": "265777",
"Score": "1",
"Tags": [
"python-3.x",
"postgresql",
"peewee"
],
"Title": "Queries using ORM and PostgreSQL"
}
|
265777
|
<p>I've written this <code>Email</code> component which obfuscates the email until the user hovers over it:</p>
<pre><code>import React, {
AnchorHTMLAttributes,
DetailedHTMLProps,
ReactNode,
useState,
} from "react";
import { percentEncodeParams } from "./utils";
function obfuscateEmail(email: string): JSX.Element {
const [username, domain] = email.split("@");
return (
<>
<style
dangerouslySetInnerHTML={{
__html: `
a>span.roe::after {
content: "@";
}
`,
}}
/>
{username}
<span className="roe" />
{domain}
</>
);
}
type Props = DetailedHTMLProps<
AnchorHTMLAttributes<HTMLAnchorElement>,
HTMLAnchorElement
> & {
/** blind carbon copy e-mail addresses */
bcc?: string[];
/** body of e-mail */
body?: string;
/** carbon copy e-mail addresses */
cc?: string[];
children?: ReactNode;
/** e-mail recipient address */
email: string;
/** subject of e-mail */
subject?: string;
};
export function Email({
bcc = [],
body = "",
cc = [],
children,
email,
subject = "",
...props
}: Props): JSX.Element {
const [hovered, setHovered] = useState(false);
const emailUrl = new URL(`mailto:${email}`);
// https://github.com/whatwg/url/issues/18#issuecomment-369865339
emailUrl.search = percentEncodeParams({ bcc, body, cc, subject });
function handleHover() {
setHovered(true);
}
const displayText = children || email;
const obfuscatedText = children || obfuscateEmail(email);
return (
<a
href={hovered ? emailUrl.href : "#"}
onFocus={handleHover}
onMouseOver={handleHover}
{...props}
>
{hovered ? displayText : obfuscatedText}
</a>
);
}
</code></pre>
<p>This is <code>utils.js</code>:</p>
<pre><code>type StringParam = [string, string];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function isValidStringParam(param: any): param is StringParam {
const [, value] = param;
return typeof value === "string" && value.length > 0;
}
function paramToStringParam([key, value]: [
string,
string | string[]
]): StringParam {
return Array.isArray(value) ? [key, value.join(",")] : [key, value];
}
/*
Do not use URLSearchParams.
URLSearchParams turns spaces into '+':
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams#examples
Some email clients on mobile devices don't replace the '+' with spaces.
According to the mailto spec, spaces should be percent encoded:
https://datatracker.ietf.org/doc/html/rfc6068#ref-STD66
*/
export function percentEncodeParams(params: {
bcc?: string[];
body?: string;
cc?: string[];
subject?: string;
}): string {
return Object.entries(params)
.map(paramToStringParam)
.filter(isValidStringParam)
.map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
.join("&");
}
</code></pre>
<p>The idea is to strip out the <code>@</code> symbol and use CSS to render it until the user hovers over it, in which case it swaps it for the original email so the user can copy paste it or interact with it.</p>
<p>Any drawbacks to this approach or ideas to make it more robust and bullet proof?</p>
<p>Any a11y issues?</p>
<p>Any feedback in general is appreciated.</p>
<p>CodeSandbox working example: <a href="https://codesandbox.io/s/hopeful-hamilton-oolrz" rel="nofollow noreferrer">https://codesandbox.io/s/hopeful-hamilton-oolrz</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-24T08:56:14.820",
"Id": "526149",
"Score": "1",
"body": "Would you be so kind a provide a codesandbox.io working example?\nthats helps aaaaaaaaaalot"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-24T20:51:31.840",
"Id": "526204",
"Score": "0",
"body": "@flx Thanks for the suggestion! Included a link to a codesandbox.io working example."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T05:45:41.290",
"Id": "526211",
"Score": "0",
"body": "The only drawback I can is that you are using `dangerouslySetInnerHTML` and that \"hover\" and mobile devices are not the best friends. Another thing that MIGHT (probably not) happen is if a browser tries to transform your email automatically to a link it won't be able to as it's not recognized as such"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T14:59:31.293",
"Id": "265782",
"Score": "0",
"Tags": [
"react.js",
"typescript",
"jsx"
],
"Title": "Obfuscate email React component"
}
|
265782
|
<p>I don't have a lot of experience creating/managing an active directory environment. This will be more of a lab environment where a solution could be tested. It will not have lots of regular users etc, just some test internal type users.</p>
<p>Part of that, I need to set up a domain controller quickly on Windows 2016 and Windows 2019 OS. Rather than doing all the steps manually, I try to create a script. I followed different online tutorials with a mix of luck. After a few hits and tries, the following script worked for me on a Windows 2019 machine. I haven't tested it yet on a Windows 2016 though.</p>
<pre><code>Add-WindowsFeature AD-Domain-Services
Install-ADDSForest -DomainName myTestDomain -InstallDNS
Install-WindowsFeature AD-Certificate
Add-WindowsFeature Adcs-Cert-Authority -IncludeManagementTools
Install-AdcsCertificationAuthority -CAType EnterpriseRootCA
</code></pre>
<p>At this point, I was able to login to this machine under myTestDomain domain.</p>
<p>Given I don't have much experience with IT management, I am hoping to get some suggestions in case I may have missed something here. Any suggestions to improve this script will be highly appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T17:27:36.933",
"Id": "524991",
"Score": "2",
"body": "you may want to look at some of the results from a net search for `powershell autolab`. there appear to be several AD setup routines available. [*grin*]"
}
] |
[
{
"body": "<p>Looking good, thankfully there aren't really any "traps" when creating a new domain via Powershell.</p>\n<p>Couple things to note though:</p>\n<ul>\n<li><p>You may want to install management tools for <code>AD-Domain-Services</code> unless you plan to manage the server remotely only (as you should, but you may need them later and it doesn't really cost anything).</p>\n</li>\n<li><p>The default functional domain level is 2008R2, if you don't have any compatibility concerns and all your DCs will be running 2016 or higher you may want to raise it to get all modern AD features (for example, the AD recycle bin):</p>\n</li>\n</ul>\n<pre><code>Install-ADDSForest -DomainName myTestDomain -DomainMode 7 -ForestMode 7 -InstallDNS\n</code></pre>\n<ul>\n<li>You aren't installing a DHCP server. If you plan on installing it on another machine it's perfectly fine, I'm just mentioning that as (in my experience) a majority of domains have DHCP hosted on the DC. It's a bit more verbose:</li>\n</ul>\n<pre><code> Install-WindowsFeature -Name DHCP -IncludeManagementTools\n # Create security groups:\n netsh dhcp add securitygroups\n # Restart service so that the new security groups are used:\n Restart-Service dhcpserver\n # Authenticate the DHCP in AD:\n Add-DhcpServerInDC -DnsName mydc.myTestDomain -IPAddress x.x.x.x\n # Server manager will bother you about authenticating the DHCP in AD even though you've just done it, tell it to shut up:\n Set-ItemProperty -Path registry::HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\ServerManager\\Roles\\12 -Name ConfigurationState -Value 2\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T09:13:24.837",
"Id": "267621",
"ParentId": "265783",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "267621",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T15:21:23.257",
"Id": "265783",
"Score": "0",
"Tags": [
"windows",
"powershell",
"active-directory"
],
"Title": "powershell script for creating a Domain Controller"
}
|
265783
|
<p>I have a for which loops for X files, if the current file is the file Y i have to skip it if the condition <code>dcc.payload.v[0].dn === dcc.payload.v[0].sd && dcc.payload.v[0].dn > 1</code> is true, else i have to make my checks and return the result.</p>
<p>The issue is that after adding that new condition my code even if it's small become very unwatchable..</p>
<p>I would to simplify it in some way, which would be the best way to do so?</p>
<pre><code>for (const ruleFile of ruleFiles) {
if (ruleFile === 'VR-DE-0003.json') {
if (dcc.payload.v[0].dn === dcc.payload.v[0].sd && dcc.payload.v[0].dn > 1) {
}else {
const rule = Rule.fromFile(`./data/rules/${ruleFile}`, {
valueSets,
validationClock: new Date().toISOString(),
});
const result = await rule.evaluateDCC(dcc);
if (result === false) {
return res.status(200).json({
nome: dcc.payload.nam.gn,
cognome: dcc.payload.nam.fn,
data_nascita: dcc.payload.dob,
dosi: `${dcc.payload.v[0].dn}/${dcc.payload.v[0].sd}`,
message: rule.getDescription("it"),
valid: result,
});
}
}
}else {
const rule = Rule.fromFile(`./data/rules/${ruleFile}`, {
valueSets,
validationClock: new Date().toISOString(),
});
const result = await rule.evaluateDCC(dcc);
if (result === false) {
return res.status(200).json({
nome: dcc.payload.nam.gn,
cognome: dcc.payload.nam.fn,
data_nascita: dcc.payload.dob,
dosi: `${dcc.payload.v[0].dn}/${dcc.payload.v[0].sd}`,
message: rule.getDescription("it"),
valid: result,
});
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T15:26:05.993",
"Id": "524978",
"Score": "5",
"body": "Please, update the title so that it shows what your code does, and not what you intend to change about it. That title is too loose for a site like this"
}
] |
[
{
"body": "<p>To reduce duplicated code, just change the condition:</p>\n<pre class=\"lang-js prettyprint-override\"><code>for (const ruleFile of ruleFiles) {\n if (ruleFile !== 'VR-DE-0003.json') \n || dcc.payload.v[0].dn !== dcc.payload.v[0].sd\n || dcc.payload.v[0].dn <= 1) {\nconst rule = Rule.fromFile(`./data/rules/${ruleFile}`, {\n valueSets,\n validationClock: new Date().toISOString(),\n });\n const result = await rule.evaluateDCC(dcc);\n \n if (result === false) {\n return res.status(200).json({\n nome: dcc.payload.nam.gn,\n cognome: dcc.payload.nam.fn,\n data_nascita: dcc.payload.dob,\n dosi: `${dcc.payload.v[0].dn}/${dcc.payload.v[0].sd}`,\n message: rule.getDescription("it"),\n valid: result,\n });\n } \n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T15:37:57.473",
"Id": "265786",
"ParentId": "265784",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "265786",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T15:21:58.150",
"Id": "265784",
"Score": "-2",
"Tags": [
"javascript"
],
"Title": "How to prevent repetitive returns for almost same contitions in IF and ELSE?"
}
|
265784
|
<p>My generic 3 median quicksort:</p>
<pre><code>
public class Util {
final static int CUTOFF = 27;
public static <T extends Comparable<? super T>> void quicksort(T[] a) {
quicksort(a, 0, a.length - 1);
}
private static <T extends Comparable<? super T>> void quicksort(T[] a, int low, int high) {
if (low + CUTOFF > high) {
insertionSort(a);
} else {
int middle = (low + high) / 2;
if (a[middle].compareTo(a[low]) < 0) {
swapReferences(a, low, middle);
}
if (a[high].compareTo(a[low]) < 0) {
swapReferences(a, low, high);
}
if (a[high].compareTo(a[middle]) < 0) {
swapReferences(a, middle, high);
}
swapReferences(a, middle, high - 1);
T pivote = a[high - 1];
int i, j;
for (i = low, j = high - 1;;) {
while (a[++i].compareTo(pivote) < 0);
while (pivote.compareTo(a[--j]) < 0);
if (i >= j) {
break;
}
swapReferences(a, i, j);
}
swapReferences(a, i, high - 1);
quicksort(a, low, i - 1);
quicksort(a, i + 1, high);
}
}
private static <T extends Comparable<? super T>> void swapReferences(T a[], int x, int y) {
T temp = a[x];
a[x] = a[y];
a[y] = temp;
}
private static <T extends Comparable<? super T>> void insertionSort(T a[]) {
for (int p = 1; p < a.length; p++) {
T tmp = a[p];
int j = p;
for (; j > 0 && tmp.compareTo(a[j - 1]) < 0; j--) {
a[j] = a[j - 1];
}
a[j] = tmp;
}
}
}
</code></pre>
<p>My testing code</p>
<pre><code>import java.util.Random;
import java.util.Arrays;
public class PruebaTiempo {
private static <T extends Comparable<? super T>> int binarySearch(T a[], T x) {
int low = 0;
int high = a.length - 1;
int mid = 0;
while (low <= high) {
mid = (low + high) / 2;
int cmp = a[mid].compareTo(x);
if (cmp < 0) {
low = mid + 1;
} else if (cmp > 0) {
high = mid - 1;
} else {
return mid;
}
}
return -1;
}
private static <T extends Comparable<? super T>> int linearSearch(T a[], T x) {
for (int i = 0; i < a.length; i++) {
if (a[i].compareTo(x) == 0) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
Random rd = new Random();
long t1, t2;
for (int k = 50000; k <= 1000000; k += 50000) {
int arr[] = rd.ints(k, 10000, 1000000).toArray();
Integer array[] = Arrays.stream(arr).boxed().toArray(Integer[]::new);
Integer array2[]=Arrays.copyOf(array, array.length);
t1 = System.currentTimeMillis();
Util.quicksort(array);
t2 = System.currentTimeMillis();
System.out.println("Tiempo quicksort: " + (t2 - t1) + "ms");
t1 = System.currentTimeMillis();
Arrays.sort(array2);
t2 = System.currentTimeMillis();
System.out.println("Tiempo sort: " + (t2 - t1) + "ms");
}
}
}
</code></pre>
<p>I know they are different sorts, but they should have similar running times.
In my PC the results are:</p>
<pre class="lang-none prettyprint-override"><code>Tiempo quicksort: 1663ms
Tiempo sort: 21ms
Tiempo quicksort: 14986ms
Tiempo sort: 71ms
Tiempo quicksort: 27422ms
Tiempo sort: 186ms
</code></pre>
|
[] |
[
{
"body": "<p>The error was in this line:</p>\n<pre><code> if (low + CUTOFF > high) {\n insertionSort(a);\n</code></pre>\n<p>It should had been</p>\n<pre><code>if (low + CUTOFF > high) {\n insertionSort(a,low,high);\n</code></pre>\n<p>And the corresponding change to insertionSort</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T16:50:03.667",
"Id": "265790",
"ParentId": "265788",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "265790",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T16:22:55.337",
"Id": "265788",
"Score": "1",
"Tags": [
"java",
"array",
"quick-sort"
],
"Title": "Java generic 3-median quicksort"
}
|
265788
|
<p>I made an infinite map in Ursina. The game freezes for a second every time I press 'l' to generate a new area.</p>
<p>My <code>Face</code> code:</p>
<pre><code>class Face(Button):
def __init__(self, position = (0,0,0),block = generate_block((0,0,0))):
super().__init__(
parent = scene,
position = position,
model = 'face.obj',
origin_y = 0.5,
texture = generate_texture(block),
color = color.white,
highlight_color = color.white)
def input(self,key):
if self.hovered:
if key == 'right mouse down':
if block_pick == 1:
face = Face(position = self.position + mouse.normal,block = 'grass')
if block_pick == 2:
face = Face(position = self.position + mouse.normal,block = 'steel')
if block_pick == 3:
face = Face(position = self.position + mouse.normal,block = 'stone')
if block_pick == 4:
face = Face(position = self.position + mouse.normal,block = 'diamond')
if block_pick == 5:
face = Face(position = self.position + mouse.normal,block = 'wood')
if block_pick == 6:
face = Face(position = self.position + mouse.normal,block = 'leaves')
if block_pick == 7:
spawner = Spawner(position = self.position + mouse.normal)
if key == 'left mouse down':
destroy(self)
print("Broke")
if held_keys['shift']:
player.speed = 5
def update(self):
if self.x < player.x - 10:
if self.z < player.z - 10:
destroy(self)
</code></pre>
<p>My chunk generation:</p>
<pre><code>def generate_chunk(player):
for x in range(round(player.x),round(player.x) + 5):
for z in range(round(player.z),round(player.z) + 5):
for y in range(1):
y = .25 + noise([x, z])
face = Face(position=(x,y,z),block = generate_block((x + 1,y,z + 1)))
</code></pre>
<p>My game loop:</p>
<pre><code> global prevx
global prevz
global f
global cat
f +=1
global txt
destroy(txt)
global block_pick
global hostiles
if held_keys['1']: block_pick = 1
if held_keys['2']: block_pick = 2
if held_keys['3']: block_pick = 3
if held_keys['4']: block_pick = 4
if held_keys['5']: block_pick = 5
if held_keys['6']: block_pick = 6
if held_keys['7']: block_pick = 7
if held_keys['c']: random_tp()
txt = Text(text="""
\n x = """ + str(player.x) + """
\n y = """ + str(player.y) + """
\n z = """ + str(player.z),
scale=1.1, x=-.8, y=.5, color = color.black)
if held_keys['r']:
player.position = cat.position
if held_keys['k']:
respawn(player,(0,1,0))
if player.y < -90:
kill(player,(0,-500,0))
if held_keys['l']:
generate_chunk(player)
</code></pre>
<p>How could I make a seamless transition?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T16:44:37.337",
"Id": "265789",
"Score": "0",
"Tags": [
"python",
"performance"
],
"Title": "Infinite map in Ursina"
}
|
265789
|
<pre><code>#!/bin/sh
#Path where to store saved urls.
URL_FILE="$QUTE_CONFIG_DIR/saved_urls"
#Arguments are appended to the url (ie for comments)
printf "$QUTE_URL $*\n" >> "$URL_FILE"
printf "tab-close" >> "$QUTE_FIFO"
</code></pre>
<p>I often have lot of tabs open, so thought it'd be useful to make a script to do this.</p>
<p>I don't feel very comfortable hardcoding the <code>URL_FILE</code> path, since it could happen that there was already such a file in that directory with that name, so I feel it's a bad practice, but not sure what to do instead. I'm also concerned about potential corruption of the file where I'm saving the URLs, but making this automatically backup seems like too much effort for such a simple script.</p>
<p>Also, I made it so additional arguments are appended as "comments" at the end of line of each URL. The simple syntax I used has the side effect that running it with no arguments results in a empty space at end of each line. It could be fixed but it'd make the code uglier; I'm not sure what's the best practice here.</p>
|
[] |
[
{
"body": "<blockquote>\n<pre><code>printf "$QUTE_URL $*\\n"\n</code></pre>\n</blockquote>\n<p>This will want to consume (nonexistent) arguments if the expansion contains a <code>%</code> format specifier, such as <code>%c</code>, <code>%d</code> or <code>%f</code>.</p>\n<p>Instead use <code>printf '%s\\n' "$QUTE_URL $*"</code> or <code>echo "$QUTE_URL $*"</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T18:55:48.083",
"Id": "265795",
"ParentId": "265791",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "265795",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T17:22:41.573",
"Id": "265791",
"Score": "2",
"Tags": [
"sh"
],
"Title": "Short (user)script to store current URL and close tab in qutebrowser"
}
|
265791
|
<p><sub><a href="https://github.com/Greedquest/CodeReviewFiles/blob/master/MVVM_Comparer.xlsm?raw=true" rel="nofollow noreferrer">download</a></sub></p>
<hr />
<p>Bit of an esoteric title, but let me explain. I wanted to create an IComparer that can be supplied to a sorting algorithm, which rather than using the <code>>, <, =</code> comparison operators on the two values, or some custom property of 2 objects like this fantastic <a href="https://codereview.stackexchange.com/q/180937/146810">PropertyComparer class</a>, instead lets the user decide <em>manually</em> which of 2 items is "better" and should be ranked higher in the list.</p>
<p>At the same time I wanted to dip my toes in the <a href="https://github.com/rubberduck-vba/MVVM" rel="nofollow noreferrer">MVVM framework</a> that @Matt posted a while back by creating a really simple form that just presents the two options <code>x</code> and <code>y</code> being compared and lets the user click on the one they want. Here's how it turned out:</p>
<p><a href="https://i.stack.imgur.com/nbhxh.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nbhxh.gif" alt="Fuzzy gif" /></a></p>
<p>By using mscorlib.ArrayList which implements the QuickSort algorithm, and adding a cache to save the result of every comparison in case it comes up again, a minimal number of comparisons is required to sort the list.</p>
<h2>MVVM</h2>
<p>The simplest place to start is the View <strong><code>TextRepresentableThingsView</code></strong>:</p>
<pre><code>'@Folder "ThingComparer"
Option Explicit
Implements IView
Implements ICancellable
Private Type TState
Context As MVVM.IAppContext
ViewModel As ThingComparisonViewModel
IsCancelled As Boolean
End Type
Private this As TState
Implements IThingComparisonViewFactory
'@Description "Creates a new instance of this form."
Private Function IThingComparisonViewFactory_Create(ByVal Context As MVVM.IAppContext, ByVal ViewModel As ThingComparisonViewModel) As IView
Dim result As TextRepresentableThingsView
Set result = New TextRepresentableThingsView
Set result.Context = Context
Set result.ViewModel = ViewModel
Set IThingComparisonViewFactory_Create = result
End Function
Public Property Get Context() As MVVM.IAppContext
Set Context = this.Context
End Property
Public Property Set Context(ByVal RHS As MVVM.IAppContext)
Set this.Context = RHS
End Property
Friend Property Set ViewModel(ByVal RHS As Object)
Set this.ViewModel = RHS
End Property
Private Sub OnCancel()
this.IsCancelled = True
Me.Hide
End Sub
Private Sub InitializeView()
With this.Context.Bindings
'these are just captions so only need one way
.BindPropertyPath this.ViewModel, "ThingX", Me.ThingXLabel, Mode:=OneTimeBinding
.BindPropertyPath this.ViewModel, "ThingY", Me.ThingYLabel, Mode:=OneTimeBinding
End With
With this.Context.Commands
.BindCommand this.ViewModel, Me.ThingXLabel, this.ViewModel.SelectXCommand(Me)
.BindCommand this.ViewModel, Me.ThingYLabel, this.ViewModel.SelectYCommand(Me)
End With
this.Context.Bindings.Apply this.ViewModel
End Sub
Private Property Get ICancellable_IsCancelled() As Boolean
ICancellable_IsCancelled = this.IsCancelled
End Property
Private Sub ICancellable_OnCancel()
OnCancel
End Sub
Private Sub IView_Hide()
Me.Hide
End Sub
Private Sub IView_Show()
InitializeView
Me.Show vbModal
End Sub
Private Function IView_ShowDialog() As Boolean
InitializeView
Me.Show vbModal
IView_ShowDialog = Not this.IsCancelled
End Function
Private Property Get IView_ViewModel() As Object
Set IView_ViewModel = this.ViewModel
End Property
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = VbQueryClose.vbFormControlMenu Then
Cancel = True
OnCancel
End If
End Sub
</code></pre>
<p>... which is the code-behind for a userform with 2 labels - <code>ThingXLabel</code> and <code>ThingYLabel</code> in a frame with some instructions.
<a href="https://i.stack.imgur.com/kv0pv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kv0pv.png" alt="Userform snap" /></a></p>
<p>It is a <em><code>TextRepresentable</code></em><code>ThingsView</code> because I envisage an <code>ImagesView</code> or a <code>ClassFooView</code> could also be used which allow different things to be displayed*, whilst still sticking to the fundamental "choose one or the other" behaviour, defined, incidentally, in the ViewModel <strong><code>ThingComparisonViewModel</code></strong>:</p>
<pre><code>'@Folder "ThingComparer"
Option Explicit
'Implements INotifyPropertyChanged
Private Type TState
ThingX As String
ThingY As String
Handler As IHandlePropertyChanged
Choice As ComparisonResult
End Type
Public Enum ComparisonResult
xChosen
yChosen
CancelChosen
End Enum
Private this As TState
Public Property Get Choice() As ComparisonResult
Choice = this.Choice
End Property
Public Property Let Choice(ByVal RHS As ComparisonResult)
this.Choice = RHS
End Property
'@Ignore ProcedureNotUsed: Called by name by MVVM framework
Public Property Get ThingX() As String
ThingX = this.ThingX
End Property
Public Property Let ThingX(ByVal RHS As String)
this.ThingX = RHS
End Property
'@Ignore ProcedureNotUsed
Public Property Get ThingY() As String
ThingY = this.ThingY
End Property
Public Property Let ThingY(ByVal RHS As String)
this.ThingY = RHS
End Property
Public Property Get SelectXCommand(ByVal View As IView) As ICommand
Set SelectXCommand = SelectOptionCommand.Create(ThingXClick, View)
End Property
Public Property Get SelectYCommand(ByVal View As IView) As ICommand
Set SelectYCommand = SelectOptionCommand.Create(ThingYClick, View)
End Property
'Private Sub INotifyPropertyChanged_OnPropertyChanged(ByVal Source As Object, ByVal PropertyName As String)
' this.Handler.HandlePropertyChanged Source, PropertyName
'End Sub
'
'Private Sub INotifyPropertyChanged_RegisterHandler(ByVal Handler As IHandlePropertyChanged)
' Set this.Handler = Handler
'End Sub
</code></pre>
<p>Considering Matt's article says the ViewModel is where the bulk of the work is, I'm slightly worried there isn't much going on here. All it does is holds the two items being compared, and the result of the comparison. It provides some custom <code>Select[X|Y]Commands</code> which are instances of the <strong><code>SelectOptionCommand</code></strong>:</p>
<pre><code>'@Folder "ThingComparer"
'@PredeclaredID
Option Explicit
Implements ICommand
Public Enum CommandType
ThingXClick
ThingYClick
End Enum
Private Type TState
View As IView
ClickType As CommandType
End Type
Private this As TState
Public Function Create(ByVal ClickType As CommandType, ByVal View As IView) As SelectOptionCommand
Dim result As SelectOptionCommand
Set result = New SelectOptionCommand
result.ClickType = ClickType
Set result.View = View
Set Create = result
End Function
Friend Property Let ClickType(ByVal RHS As CommandType)
this.ClickType = RHS
End Property
Friend Property Set View(ByVal RHS As IView)
GuardClauses.GuardDefaultInstance Me, SelectOptionCommand
GuardClauses.GuardDoubleInitialization this.View, TypeName(Me)
Set this.View = RHS
End Property
Private Function ICommand_CanExecute(ByVal Context As Object) As Boolean
ICommand_CanExecute = True
End Function
Private Property Get ICommand_Description() As String
ICommand_Description = "Click to select"
End Property
Private Sub ICommand_Execute(ByVal Context As Object)
Dim ViewModel As ThingComparisonViewModel
Set ViewModel = Context 'REVIEW: Or this.View.ViewModel
'just need to save click result
Select Case this.ClickType
Case ThingXClick: ViewModel.Choice = xChosen
Case ThingYClick: ViewModel.Choice = yChosen
End Select
this.View.Hide
End Sub
</code></pre>
<p>I found a bit weird the way they need a reference to <code>View</code> which might create a circular reference, but I guess it's okay as long as the View holds references to the Commands, the ViewModel just acts as a factory.</p>
<p>*<sub>my default instinct would be to make the things <code>IDrawable</code>, but I think multiple views is closer to the MVVM paradigm?</sub></p>
<h2>API</h2>
<p>Speaking of factories, I made the View implement its own strongly typed factory method <strong><code>IThingComparisonViewFactory</code></strong>:</p>
<pre><code>'@Folder "ThingComparer"
Option Explicit
Public Function Create(ByVal Context As MVVM.IAppContext, ByVal ViewModel As ThingComparisonViewModel) As IView
End Function
</code></pre>
<p>... that way I know that all <code>IView</code>s will really be more like <code>IView<ThingComparisonViewModel></code> as opposed to generic ones (this is something I find weird in MVVM, how do we enforce a View implementation will be compatible with a particular ViewModel?).</p>
<p>The factory is used by the MVVM coordinator which constructs the Context, ViewModel and View objects. It is also the top level API which implements <code>IComparable</code> <strong><code>GUIComparer</code></strong>:</p>
<pre><code>'@Folder "ThingComparer"
'@PredeclaredId
Option Explicit
Implements mscorlib.IComparer
Private Type TGUIComparer
View As IView
End Type
Private this As TGUIComparer
Private Property Get View() As IView
Set View = this.View
End Property
Friend Property Set View(ByVal RHS As IView)
Set this.View = RHS
End Property
Public Function Create(Optional ByVal ViewFactory As IThingComparisonViewFactory) As GUIComparer
GuardClauses.GuardNonDefaultInstance Me, GUIComparer
Dim result As GUIComparer
Set result = New GUIComparer
Dim Context As IAppContext
Set Context = AppContext.Create()
Dim ViewModel As ThingComparisonViewModel
Set ViewModel = New ThingComparisonViewModel
If ViewFactory Is Nothing Then Set ViewFactory = TextRepresentableThingsView
Set result.View = ViewFactory.Create(Context, ViewModel)
Set Create = result
End Function
Private Function IComparer_Compare(ByVal x As Variant, ByVal y As Variant) As Long
GuardClauses.GuardDefaultInstance Me, GUIComparer 'cache won't be clear in the default instance
GuardClauses.GuardNullReference View, Message:="Class must be Created with the .Create Method not `New`"
'short circuit default condition
'our list has no dupes but arraylist asserts x.compareTo(x) = 0
If x = y Then IComparer_Compare = 0: Exit Function
'only need to check x & y as reverse is already in cache by default
Static cache As New Scripting.Dictionary
If TryGetComparisonResult(cache, x, y, IComparer_Compare) Then Exit Function
With View
Dim ViewModel As ThingComparisonViewModel
Set ViewModel = .ViewModel
ViewModel.ThingX = x
ViewModel.ThingY = y
'show dialog so we can capture cancellation
If Not .ShowDialog Then Err.Raise 5, , "Cancelled"
Select Case ViewModel.Choice
Case xChosen
IComparer_Compare = -1
Case yChosen
IComparer_Compare = 1
Case Else
Err.Raise 5, , "Invalid Selection"
End Select
End With
CacheComparisonResult cache, x, y, IComparer_Compare
End Function
'TODO revisit this cache. It wants to be a map<(variant,variant):bool> where the variants are commutative
'Right now this won't work with objects, only value types, so it is tightly coupled to the TextRepresentableThingsView
Private Function TryGetComparisonResult(ByVal cache As Dictionary, ByVal x As Variant, ByVal y As Variant, ByRef outValue As Long) As Boolean
Dim key As String
key = x & vbNullChar & y
If Not cache.Exists(key) Then Exit Function
TryGetComparisonResult = True
outValue = cache.Item(key)
End Function
Private Sub CacheComparisonResult(ByVal cache As Dictionary, ByVal x As Variant, ByVal y As Variant, ByVal result As Long)
cache.Add x & vbNullChar & y, result
cache.Add y & vbNullChar & x, -result
End Sub
</code></pre>
<p>Using the IComparer is very simple as you could see in the video, but some example code:</p>
<pre><code>Sub SortSelection()
Dim list As New mscorlib.ArrayList
Dim rangeToSort As Range
Set rangeToSort = Selection
Dim item As Range
For Each item In rangeToSort
list.Add item.Value
Next item
list.sort_2 GUIComparer.Create(ViewFactory:=TextRepresentableThingsView)
dumpList list, dumpWhere:=rangeToSort
End Sub
Private Sub dumpList(ByVal list As ArrayList, Optional ByVal dumpWhere As Range)
If dumpWhere Is Nothing Then Set dumpWhere = ThisWorkbook.Sheets.Add().Range("A1")
dumpWhere.Resize(list.Count, 1).Value = WorksheetFunction.Transpose(list.ToArray)
End Sub
</code></pre>
<p>Try it out in <a href="https://github.com/Greedquest/CodeReviewFiles/blob/master/MVVM_Comparer.xlsm?raw=true" rel="nofollow noreferrer">this download workbook</a></p>
<h3>Thoughts</h3>
<ul>
<li>MVVM framework is truly magic</li>
<li>I was wondering, instead of having a <code>SelectOptionCommand</code> to hide the view and update the state, I could just have an <code>AcceptCommand</code> wired up to each label, then use a property binding to see what control has focus. Not sure how to do that or what is more idiomatic?</li>
<li>As mentioned, not sure what's the best way to handle things that need a different kind of representation. For example if I am sorting a list of filepaths to photos, which need to be displayed differently.
<ul>
<li>Should my View be clever enough to detect the types of <code>ViewModel.ThingX</code> and draw accordingly</li>
<li>Should I inject a different view for each type as I have outlined now</li>
<li>Should I be getting <code>IDrawable</code> things fed into the Comparer so I only need one View implementation which can have drawing method dictated to it by the types supplied by the ViewModel (i.e. <code>Thing[X/Y]</code> manage their own representation.)</li>
</ul>
</li>
<li>Finally, I want to add some more GUI juice, specifically a hoverover animation - should this be in command bindings or property bindings?</li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T18:08:32.473",
"Id": "265793",
"Score": "0",
"Tags": [
"design-patterns",
"vba",
"sorting",
"mvvm",
"rubberduck"
],
"Title": "GUIComparer with MVVM dialog to allow user input in ArrayList sorting algorithm"
}
|
265793
|
<p>I was solving a question on a coding website and this website has a limit for execution time of code. My code takes 1.01 sec but the limit is 1 sec.
I am unable to find any changes in my code that can decrease the execution time. Here is the link for the question :-
<a href="https://www.codechef.com/AUG21C/problems/CHFINVNT" rel="nofollow noreferrer">https://www.codechef.com/AUG21C/problems/CHFINVNT</a></p>
<blockquote>
<p>Chef is trying to invent the light bulb that can run at room temperature without electricity. So he has <span class="math-container">\$N\$</span> gases numbered from <span class="math-container">\$0\$</span> to <span class="math-container">\$N−1\$</span> that he can use and he doesn't know which one of the <span class="math-container">\$N\$</span> gases will work but we do know it.</p>
<p>Now Chef has worked on multiple search algorithms to optimize search.
For this project, he uses a modulo-based search algorithm that he invented himself. So first he chooses an integer K and selects all indices <span class="math-container">\$i\$</span> in increasing order such that <span class="math-container">\$i \bmod K = 0\$</span> and test the gases on such indices, then all indices <span class="math-container">\$i\$</span> in increasing order such that <span class="math-container">\$i \bmod K = 1\$</span>, and test the gases on such indices, and so on.</p>
<p>Given <span class="math-container">\$N\$</span>, the index of the gas <span class="math-container">\$p\$</span> that will work, and <span class="math-container">\$K\$</span>, find after how much time will he be able to give Chefland a new invention assuming that testing 1 gas takes 1 day.</p>
<p>For example, consider <span class="math-container">\$N=5\$</span>, <span class="math-container">\$p=2\$</span> and <span class="math-container">\$K=3\$</span>.</p>
<ul>
<li>On the 1st day, Chef tests gas numbered <span class="math-container">\$0\$</span> because <span class="math-container">\$0 \bmod 3 = 0\$</span>.</li>
<li>On the 2nd day, Chef tests gas numbered <span class="math-container">\$3\$</span> because <span class="math-container">\$3 \bmod 3=0\$</span>.</li>
<li>On the 3rd day, Chef tests gas numbered <span class="math-container">\$1\$</span> because <span class="math-container">\$1 \bmod 3=1\$</span>.</li>
<li>On the 4th day, Chef tests gas numbered <span class="math-container">\$4\$</span> because <span class="math-container">\$4 \bmod 3=1\$</span>.</li>
<li>On the 5th day, Chef tests gas numbered <span class="math-container">\$2\$</span> because <span class="math-container">\$2 \bmod 3=2\$</span>.</li>
</ul>
<p>So after 5 days, Chef will be able to give Chefland a new invention</p>
</blockquote>
<p>How is my code slow (by .01 sec)?</p>
<pre><code>#include <stdio.h>
int main(void) {
int T;
scanf("%d",&T);
while(T--){
int n,p,k;
int j,remain,r=0,day=0;
scanf("%d %d %d",&n,&p,&k);
for(j=0;j<n;j++){
remain = j%k;
if(remain==r){
day++;
if(j==p) break;
}
if(j==n-1){
j=0;
r++;
}
}
printf("%d\n",day);
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T18:19:58.370",
"Id": "524996",
"Score": "2",
"body": "Codechef likely stopped executing your code after the 1 second mark, meaning your code didn't actually take 1.01 seconds. You'll need to try a different algorithm."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T18:22:25.220",
"Id": "524997",
"Score": "0",
"body": "You are right but I think my algo works well , it uses only one for statement and three necessary if(s) statements, can you provide a hint or something for another algo?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T18:32:30.023",
"Id": "524999",
"Score": "1",
"body": "WIth your current algorithm, you loop through all numbers. With the bound of the questions, your code takes around about 10^5 * 10^9 operations. On average, a computer can do 10^9 operations a second. You'll still need to do 10^5 operations to loop through the input, but to bring down the 10^9 part, you'll need some math."
}
] |
[
{
"body": "<p>This algorithm is <span class=\"math-container\">\\$\\mathcal{O}(nk)\\$</span> but could be <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span>.</p>\n<p>It is <span class=\"math-container\">\\$\\mathcal{O}(nk)\\$</span> because you reset <code>j</code> <code>k</code> times with <code>j</code> bounded by <code>n</code>. This makes it very much like having two <code>for</code> loops. Consider something like</p>\n<pre><code>int day = 0;\nfor (int r = 0; r < k; r++) {\n for (int j = 0; j < n; j += k) {\n day++;\n\n if (j == p) {\n printf("%d\\n", day);\n r = k - 1;\n break;\n }\n }\n}\n</code></pre>\n<p>The <code>- 1</code> may not be necessary if <code>k</code> is not the maximum positive value for <code>int</code>.</p>\n<p>That would actually be <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span>, because the outer loop runs <code>k</code> times and the inner loop is <span class=\"math-container\">\\$\\mathcal{O}(n/k)\\$</span>. In this case, using two loops can be faster than your single loop.</p>\n<p>It's also possible that the intent is to do this in constant time: <span class=\"math-container\">\\$\\mathcal{O}(1)\\$</span>. You should be able to calculate <code>day</code> from the remainders and quotients. Something like</p>\n<pre><code>day = (p % k) * (n / k);\n</code></pre>\n<p>That may not be complicated enough. Consider if it matters if <span class=\"math-container\">\\$p\\bmod k \\gt n \\bmod k\\$</span> and perhaps the result of <code>p / k</code>. But I'm relatively sure that this is calculable in some way. I.e. that there is some formula that will give <code>day</code> in terms of <code>n</code>, <code>p</code>, and <code>k</code>, which you know. The following may provide insight</p>\n<pre><code>printf("%d %d %d %d\\n", day, (p % k) * (n / k), (p / k), ((p % k) > (n % k)));\n</code></pre>\n<p>You would replace the original <code>printf</code> with that one and see what it gives. Try various formulas until you find one that works.</p>\n<p>Another option would be to try to replace the inner loop with a formula. That would be <span class=\"math-container\">\\$\\mathcal{O}(k)\\$</span> time.</p>\n<pre><code>int day = 0;\nfor (int r = 0; r < k; r++) {\n if (r == p % k) {\n day += p / k;\n printf("%d\\n", day);\n break;\n }\n\n day += n / k;\n}\n</code></pre>\n<p>None of these are tested. They are just things that come to mind as possibilities. I am most confident about the first one returning the same results as your original algorithm. But all of them should be faster for large <code>k</code> and <code>n</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T01:16:50.130",
"Id": "265806",
"ParentId": "265794",
"Score": "3"
}
},
{
"body": "<p>Throwing everything directly into <code>main()</code> makes it harder to test the program. Let's split into a unit-testable function and the challenge harness:</p>\n<pre><code>static int days(int n, int p, int k)\n{\n int day = 0;\n int r = 0;\n for (int j = 0; j < n; ++j) {\n int remain = j % k;\n if (remain == r) {\n ++day;\n if (j == p) break;\n }\n if (j == n - 1) {\n j = 0;\n ++r;\n }\n }\n return day;\n}\n</code></pre>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n\nint main(void)\n{\n int t;\n if (scanf("%d", &t) != 1) {\n return EXIT_FAILURE;\n }\n while (t--) {\n int n, p, k;\n if (scanf("%d %d %d", &n, &p, &k) != 3) {\n return EXIT_FAILURE;\n }\n printf("%d\\n", days(n, p, k));\n }\n}\n</code></pre>\n<p>Whilst editing here, I added the missing check that <code>scanf()</code> successfully converted the expected values.</p>\n<p>Now we can add unit tests. Let's start with the example given in the question:</p>\n<pre><code>#ifdef TEST\n\n#include <gtest/gtest.h>\n\nTEST(days, question_example)\n{\n EXPECT_EQ(days(5, 2, 3), 5);\n}\n\n#else\n\nint main(void)\n{\n ⋮\n}\n\n#endif\n</code></pre>\n<p>We should add more tests as and when we think of them.</p>\n<hr />\n<p>Let's look at the algorithm. We're looping <code>j</code> over ever integer, testing each one for divisibility by <code>k</code>. That's an expensive way to loop over all multiples of <code>k</code>; it's much more efficient to increment <code>j</code> by <code>k</code> each time, and not need any division:</p>\n<pre><code>static int days(int n, int p, int k)\n{\n int day = 0;\n int r = 0;\n for (int j = 0; r < n; j += k) {\n if (j >= n) {\n j = ++r;\n }\n ++day;\n if (j == p) break;\n }\n return day;\n}\n</code></pre>\n<p>Or more clearly, iterating over the possible remainders:</p>\n<pre><code>static int days(int n, int p, int k)\n{\n int day = 0;\n for (int r = 0; r < n; ++r) {\n for (int j = r; j < n; j += k) {\n ++day;\n if (j == p) { return day; };\n }\n }\n /* shouldn't happen */\n return day;\n}\n</code></pre>\n<hr />\n<p>That algorithm is still slow, since we're still looping and counting each day individually. We don't need to do that, since we should be able to <em>calculate</em> how many days it will take to reach <code>p</code>.</p>\n<p>Let's look at the example again, and lay out the numbers as we'll visit them:</p>\n<pre><code>0 → 3 ⤶\n1 → 4 ⤶\n2\n</code></pre>\n<p>Or perhaps a larger example, (18, <em>p</em>, 4):</p>\n<pre><code>0 → 4 → 8 → 12 → 16 ⤶\n1 → 5 → 9 → 13 → 17 ⤶\n2 → 6 → 10 → 14 ⤶\n3 → 7 → 11 → 15\n</code></pre>\n<p>We know that we will have to do <code>p%k</code> full runs over the <code>N</code> elements. Each of those runs will contribute <code>N/k</code> or <code>N/k + 1</code> days to the total, depending on <code>N%k</code>. The final, partial, run will contribute <code>p/k</code> days:</p>\n<pre><code>static int days(int n, int p, int k)\n{\n int full_runs = p % k;\n int long_full_runs = n % k;\n if (long_full_runs > full_runs) {\n long_full_runs = full_runs;\n }\n\n return 1\n + full_runs * (n / k)\n + long_full_runs\n + p / k;\n}\n</code></pre>\n<p>That satisfies all the tests, including the (18, <em>p</em>, 4) set I added:</p>\n<pre><code>EXPECT_EQ(days(18, 0, 4), 1);\nEXPECT_EQ(days(18, 4, 4), 2);\nEXPECT_EQ(days(18, 16, 4), 5);\nEXPECT_EQ(days(18, 1, 4), 6);\nEXPECT_EQ(days(18, 17, 4), 10);\nEXPECT_EQ(days(18, 2, 4), 11);\nEXPECT_EQ(days(18, 14, 4), 14);\nEXPECT_EQ(days(18, 3, 4), 15);\n</code></pre>\n<p>And now there's no loop, so this runs in constant time, i.e. it scales as O(1) rather than O(nk) as before.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T09:31:03.577",
"Id": "265846",
"ParentId": "265794",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "265846",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T18:18:06.557",
"Id": "265794",
"Score": "2",
"Tags": [
"c",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "How to do modulo thing fast (less execution time)"
}
|
265794
|
<p>I'm trying to learn the golfing language <a href="https://github.com/Vyxal/Vyxal" rel="noreferrer">Vyxal</a> because I occasionally contribute to it, and I'm slightly ashamed I can't even use it. To do this, I started with implementing the Sieve of Eratosthenes in Vyxal. I'd like to know how to make this code more readable and idiomatic, and, if there are issues with time or memory, more efficient.</p>
<p>Please note that I am <em>not</em> looking for tips on golfing it. If there's a way to make it clearer by making it shorter, that's fine, but making it terser is not the goal here, just making it more readable.</p>
<pre><code>3$ṡ→sieve ⟨2⟩→primes 2→x {←sieve L0> | ←sieve'←x%;: h:→x ←primes$J→primes 1ȯ→sieve} ←primes
</code></pre>
<p><a href="https://lyxal.pythonanywhere.com?flags=&code=3%24%E1%B9%A1%E2%86%92sieve%20%E2%9F%A82%E2%9F%A9%E2%86%92primes%202%E2%86%92x%20%7B%E2%86%90sieve%20L0%3E%20%7C%20%E2%86%90sieve%27%E2%86%90x%25%3B%3A%20h%3A%E2%86%92x%20%E2%86%90primes%24J%E2%86%92primes%201%C8%AF%E2%86%92sieve%7D%20%E2%86%90primes&inputs=30&header=&footer=" rel="noreferrer">Try it Online!</a></p>
<p>An integer (> 2) is given as input. An inclusive range from 3 to that integer is made and stored in the variable <code>sieve</code>. Then, the variable <code>primes</code>, which will be returned at the end, is initialized as the list <code>[2]</code>, and the current prime number to filter out composite numbers with, <code>x</code>, is set to <code>2</code>.</p>
<p>While <code>sieve</code> is non-empty, a list of numbers in <code>sieve</code> that aren't divisible by <code>x</code> is constructed. Then, the head of that list is assigned to <code>x</code> and appended to <code>primes</code>, and the rest is assigned to <code>sieve</code>. I'm unsatisfied with <code>h:→x ←primes$J→primes</code> because <code>ḣ</code> should've worked to split the list in two but is buggy, and I can't find a nicer alternative. Also <code>←primes$J→primes</code> is like saying <code>primes = primes + [x]</code> instead of simply saying <code>primes.append(x)</code> (in Python), but I can't find an alternative to that either.</p>
<p>Might I also be overusing variables?</p>
<p>Thanks for your feedback.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T19:55:05.580",
"Id": "525060",
"Score": "1",
"body": "Please also have a look at https://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf"
}
] |
[
{
"body": "<p>It is probably more efficient to work with a boolean array (which is the idea behind the sieve anyway - a boolean mask that you build up to filter out all of the non-primes in the range). Instead of a <code>sieve</code> and a <code>primes</code> variable, we just have a single <code>isprime</code> array which we modify as we go along. There are two advantages to this. Firstly, it is easier to understand. Secondly, it is actually more memory-efficient because we only need to alter one list and can actually keep it on the stack, meaning we don't need to assign it to a variable, and so we can modify the list in-place.</p>\n<p>We can initialize the array like so: <code>⟨0 | 0⟩ 1 ←input ‹ ẋ f J</code> (prepend <code>[0, 0]</code> to a list of <code>input - 1</code> <code>1</code>s), which initially just says that <span class=\"math-container\">\\$0\\$</span> and <span class=\"math-container\">\\$1\\$</span> are not prime. So far so good.</p>\n<p>Then, we want to start our loop at <span class=\"math-container\">\\$2\\$</span> since that's the lowest prime, and we want to end it at the square root of the input, since that's the maximum value you need to scan when doing sieve. If you insert a <code>:,</code> after the <code>←sieve</code> in the body of your while loop, you'll notice that you don't stop here, so you waste <span class=\"math-container\">\\$O(n)\\$</span> steps just looping through the remaining primes and dequeueing the list repeatedly.</p>\n<p>To do this, we can just do <code>←input √ ⌈ 2$ ṡ (x|</code> - square root the input, ceiling (although I <em>think</em> floor works too? using ceiling just to be safe), and produce a range from 2. Note that you could also just do the for loop directly since <code>0</code> and <code>1</code> will be skipped by the following condition anyway. We then do a for loop, saving our current value as <code>x</code>.</p>\n<p>We first want to duplicate the current top-of-stack, which is the prime array, because we will be popping it to check if <code>x</code> is prime. So, we do <code>:</code> followed by <code>←x i [</code> - get <code>isprime[x]</code> and if it's prime, run the next block.</p>\n<p>Then, we just want to mark <code>2x, 3x, 4x, ...</code> as composite. So, we floor divide the input by <code>x</code>, take the exclusive range, increment it (to get <code>2, 3, ..., input/x</code>), and then multiply each one by <code>x</code>: <code>←input ←x ḭ ɽ › ←x *</code>. Finally, we set <code>isprime[n]</code> to <code>0</code> for each one: <code>(n 0 Ȧ)</code>.</p>\n<p>At the end, this will produce a boolean array, so we simply use the "truthy indices" element to get the list of prime numbers: <code>T</code>.</p>\n<p>Here is the final program, which should be approximately optimal time complexity, but may still have some constant optimizations possible:</p>\n<pre><code>→input\n⟨0 | 0⟩ 1 ←input ‹ ẋ f J\n←input √ ⌈ 2$ ṡ (x|\n : ←x i [\n ←input ←x ḭ ɽ › ←x * (n 0 Ȧ)\n ]\n)\nT\n</code></pre>\n<p>This is (mostly) equivalent pseudocode:</p>\n<pre><code>save input to `input`\n[0, 0] -join- flatten(1 repeated (`input` - 1) times)\nfor each `x` in 2..ceil(sqrt(`input`))\n dup\n if `isprime`[`x`]\n for n in x * 2..floor(`input` ÷ `x`)\n `isprime`[n] = false\nget truthy indices of `isprime`\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T21:47:54.387",
"Id": "525005",
"Score": "0",
"body": "Thanks! I'll need some time to process this, because Vyxal is very much a read-only language for me (don't tell lyxal I said that :P). I don't know if flooring the square root would for 3, since that'd give a range from 1 to 2, and 3's divisible by 1."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T21:53:37.940",
"Id": "525006",
"Score": "0",
"body": "@user but since `1` is not a prime (and the `isprime` list is initialized as such) it would get skipped"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T21:57:20.483",
"Id": "525007",
"Score": "0",
"body": "@user I've added some roughly equivalent pseudocode - hopefully this is a bit more digestable"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T21:58:27.330",
"Id": "525008",
"Score": "4",
"body": "Ah, thanks! Vyxal is already pretty easy to digest, what with it being gluten free, but this tree nut-free code is even better :P"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T21:41:23.423",
"Id": "265800",
"ParentId": "265797",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "265800",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T20:41:25.273",
"Id": "265797",
"Score": "13",
"Tags": [
"primes",
"sieve-of-eratosthenes",
"vyxal"
],
"Title": "Sieve of Eratosthenes in Vyxal"
}
|
265797
|
<p>I was trying to fetch some data (daily new cases and daily new deaths) from <a href="https://www.worldometers.info/coronavirus/" rel="nofollow noreferrer">Worldometers</a> and I came up with this:</p>
<pre><code>import requests
from bs4 import BeautifulSoup as bs
import numpy as np
import matplotlib.pyplot as plt
# Plotting Function
def plot(data , country):
fontsize = 10
csfont = {'fontname':'Times New Roman'}
plt.plot(data)
plt.xlabel(f'Days since the beginning of the COVID-19 Pandemic in {country}',fontsize=fontsize, fontweight='bold',**csfont)
plt.ylabel('Daily new Cases',fontsize=fontsize, fontweight='bold',**csfont)
plt.tight_layout()
plt.show()
# Daily New Cases
def DNC(country,Plot = False):
url = f"https://www.worldometers.info/coronavirus/country/{country}/"
r = requests.get(url)
htmlcontent = r.content
soup = str(bs(htmlcontent, "html.parser"))
n = soup.find("name: 'Daily Cases',")
n2 = soup[n:].find("data:")
m = soup[n:].find(']')
data = np.array(soup[n+n2+7:n+m].replace('null','0').split(','),dtype=int)
if Plot == True:
plot(data,country)
return data
# Daily New Deaths
def DND(country,Plot = False):
url = f"https://www.worldometers.info/coronavirus/country/{country}/"
r = requests.get(url)
htmlcontent = r.content
soup = str(bs(htmlcontent, "html.parser"))
n = soup.find("name: 'Daily Deaths',")
n2 = soup[n:].find("data:")
m = soup[n:].find(']')
data = np.array(soup[n+n2+7:n+m].replace('null','0').split(','),dtype=int)
if Plot == True:
plot(data,country)
return data
if __name__ == '__main__':
DNC('us',Plot=True)
DND('us',Plot=True)
</code></pre>
<p>Which technically works, <strong>but I'm not happy with how it finds the data in the HTML</strong> (I think I have used the dumbest idea, to convert the soup to string and then find it there with counting letters and so on). Is there a better way to do this?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T01:41:57.700",
"Id": "525020",
"Score": "0",
"body": "You should make your link match the URLs in your code."
}
] |
[
{
"body": "<p>Sure. One way would be to use another source. Another might be to separate out the "script" tag (for example, using a bs selector) and at least only use that as the string. Unless you want to run javascript, there's not a much better way to read the data from inside the script.</p>\n<p>I do recommend replacing your string parsing of the array with <a href=\"https://docs.python.org/3/library/json.html\" rel=\"nofollow noreferrer\">json</a>.loads though</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T21:36:19.853",
"Id": "525127",
"Score": "1",
"body": "_Unless you want to run javascript_ - You don't need to run it; you just need to parse it. You can get an AST from something like `slimit`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T20:35:49.877",
"Id": "525190",
"Score": "0",
"body": "That's a neat suggestion. I actually didn't know it was possible. That said, I think the current regex method is probably more stable against future changes, than either running or parsing the javascript"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T01:45:13.433",
"Id": "265807",
"ParentId": "265798",
"Score": "0"
}
},
{
"body": "<p>Overall it's an interesting (if a little strange) idea. Why are you re-plotting data locally when the plots have already been rendered to downloadable SVG elements on the website in question? Effectively you're writing a scraper and converter from JavaScript Highcharts library calls to Matplotlib calls.</p>\n<p>Assuming that this is a good idea at all (I'm not convinced that this is true), your methods - whereas they're a good start, for learning purposes - are somewhat inefficient, non-generalized, fragile and buggy.</p>\n<p>From the top:</p>\n<ul>\n<li><code>plot()</code> is buggy because it claims <code>Daily new cases</code> regardless of whether that's true for the current call.</li>\n<li><code>plot()</code> does not properly use the <code>matplotlib</code> date formatting support on the x-axis. "Days since" is a far less intuitive axis than simply showing dates.</li>\n<li><code>DNC</code> should not be abbreviated and should instead read <code>daily_new_cases</code></li>\n<li><code>Plot = False</code> should not be capitalized and should be <code>plot</code></li>\n<li>Do not bake plotting into your scraping functions</li>\n<li>Check your <code>requests</code> response for failure, which you don't do currently</li>\n<li>You load into BeautifulSoup (good) but then re-flatten it to a single string, which... what? Why?</li>\n<li>Do not pass <code>r.content</code> to BeautifulSoup; pass <code>r.text</code> which is encoding-aware</li>\n<li>Look at script tags only, rather than the entire response text</li>\n<li>Use a JavaScript parsing library like <code>slimit</code> to navigate to the actual chart data in the syntax tree, rather than attempting to guess your way through the string</li>\n<li>You download the page all over again for every chart type; don't do this - only download it once</li>\n<li>Don't use integers for your series: there are float elements in the site's markup</li>\n<li>Use a <code>SoupStrainer</code> to pre-select only the elements you care about</li>\n<li>You can represent each chart as a class instance</li>\n<li>Consider a generic method that parses out all of the charts on the page, not just hard-coded for two</li>\n</ul>\n<h2>Suggested</h2>\n<pre><code>import re\nfrom dataclasses import dataclass\nfrom datetime import datetime, timedelta\nfrom typing import Iterable, Optional, Tuple, Dict\n\nimport requests\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom bs4 import BeautifulSoup, SoupStrainer\nfrom matplotlib.axes import Axes\nfrom matplotlib.dates import num2date\nfrom matplotlib.figure import Figure\nfrom slimit.ast import ExprStatement, Node, Assign, Object, Number, UnaryOp, Null\nfrom slimit.parser import Parser\n\n\nSCRIPTS = SoupStrainer(\n name='script',\n type='text/javascript',\n)\n\nCHART_PAT = re.compile(r'Highcharts\\.chart'),\n\n# Using this as a naive, assumed-local-timezone date is dubious, but\n# Worldometers has left ambiguous their date boundaries\nEPOCH = datetime.fromtimestamp(0)\nDAY = timedelta(days=1)\n\n\ndef get_chart_props(parser: Parser, script: str) -> Iterable[\n Tuple[\n str, # chart name\n Dict[\n str, # property name\n Node, # property node value - an Object or an Array\n ],\n ]\n]:\n tree = parser.parse(script)\n\n for node in tree.children():\n if (\n isinstance(node, ExprStatement)\n and node.expr.identifier.node.value == 'Highcharts'\n and node.expr.identifier.identifier.value == 'chart'\n ):\n name_arg, chart_arg, *_ = node.expr.args\n name = name_arg.value.strip("'")\n props = {\n prop.left.value: prop.right\n for prop in chart_arg.properties\n }\n yield name, props\n\n\ndef get_prop(obj: Object, key: str) -> Node:\n for prop in obj.properties:\n if isinstance(prop, Assign) and prop.left.value == key:\n return prop.right\n raise ValueError(f'Key {key} not found')\n\n\ndef to_float(x: Node) -> float:\n if isinstance(x, Number):\n return float(x.value)\n if isinstance(x, UnaryOp) and x.op == '-':\n return -float(x.value.value)\n if isinstance(x, Null):\n return float('NaN')\n raise ValueError(f'Not a float: {x}')\n\n\n@dataclass\nclass Chart:\n country: str\n name: str\n title: str\n subtitle: Optional[str]\n y_title: str\n\n # Epoch days as floats; see https://matplotlib.org/stable/api/dates_api.html\n x_data: np.ndarray\n # floats\n y_data: Dict[str, np.ndarray]\n\n @classmethod\n def from_script(cls, country: str, name: str, props: Dict[str, Node]) -> 'Chart':\n title = props['title'].properties[0].right.value.strip("'")\n\n subtitle_props = props.get('subtitle')\n subtitle = subtitle_props and get_prop(\n subtitle_props, 'text',\n ).value.strip("'")\n\n y_title = get_prop(\n get_prop(props['yAxis'], 'title'), 'text'\n ).value.strip("'")\n\n x_array = get_prop(props['xAxis'], 'categories').items\n x_data = [\n (\n datetime.strptime(item.value, '"%b %d, %Y"')\n - EPOCH\n ) / DAY\n for item in x_array\n ]\n\n series = {\n get_prop(obj, 'name').value.strip("'"):\n np.array([\n to_float(x) for x in get_prop(obj, 'data').items\n ])\n for obj in props['series'].items\n }\n\n chart = cls(\n country=country,\n name=name,\n title=title,\n subtitle=subtitle,\n x_data=np.array(x_data),\n y_data=series,\n y_title=y_title,\n )\n return chart\n\n def plot(self) -> Figure:\n fig: Figure\n ax: Axes\n fig, ax = plt.subplots()\n fig.suptitle(self.title)\n if self.subtitle is not None:\n ax.set_title(self.subtitle)\n ax.set_ylabel(self.y_title)\n\n for name, series in self.y_data.items():\n ax.plot(num2date(self.x_data), series, label=name)\n\n fig.autofmt_xdate()\n fig.legend()\n return fig\n\n\ndef download_data(country: str) -> BeautifulSoup:\n with requests.get(\n url=f"https://www.worldometers.info/coronavirus/country/{country}/"\n ) as resp:\n resp.raise_for_status()\n return BeautifulSoup(resp.text, "html.parser", parse_only=SCRIPTS)\n\n\ndef load_all(soup: BeautifulSoup, country: str) -> Iterable[Chart]:\n scripts = soup.find_all(text=CHART_PAT)\n parser = Parser()\n for script in scripts:\n for name, props in get_chart_props(parser, script):\n yield Chart.from_script(country=country, name=name, props=props)\n\n\ndef main() -> None:\n country = 'canada'\n doc = download_data(country)\n charts = tuple(load_all(doc, country))\n\n for chart in charts:\n chart.plot()\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<h2>Output</h2>\n<p>Here are two of the example charts produced by the above:</p>\n<p><a href=\"https://i.stack.imgur.com/qu4Jh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/qu4Jh.png\" alt=\"example plots\" /></a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T21:02:26.730",
"Id": "265861",
"ParentId": "265798",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "265861",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T21:25:27.200",
"Id": "265798",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"html",
"covid-19"
],
"Title": "A better way to extract COVID data from Worldometers"
}
|
265798
|
<p>Get a list of popular Arch Linux packages with a popularity greater or equal than the given one.</p>
<p>It asks for the popularity if it isn't given. Then gets the total number of packages and iterates until it gets the whole list of packages - one thousand at a time, because if I try to grab them all the API gives an error.</p>
<pre><code>#!/usr/bin/env bash
function get_popularity() {
local popularity
if [ $# -gt 0 ]; then
popularity=$1
else
read -rp "Popularity [0-100]: " popularity
fi
while [[ $popularity -lt 0 || $popularity -gt 100 ]] ; do
read -rp "Popularity [0-100]: " popularity
done
echo $popularity
}
function get_total_pkgs() {
local total
total=$(curl -sX "GET" -H "accept: application/json" \
"https://pkgstats.archlinux.de/api/packages?limit=1&offset=0" \
| jq ".total")
echo $total
}
function get_popular_packages() {
local x total popularity packages limit
total=$1
popularity=$2
packages=()
x=0
limit=1000
while [ $x -le $total ]; do
packages+=$(curl -sX "GET" -H "accept: application/json" \
"https://pkgstats.archlinux.de/api/packages?limit=$limit&offset=$x" \
| jq ".packagePopularities[]" \
| jq "select( .popularity >= $popularity )" \
| jq ".name")
x=$(($x+$limit))
done
echo "${packages[@]}"
}
function main () {
popularity=$(get_popularity "$@")
packages=$(get_popular_packages $(get_total_pkgs) $popularity)
}
main "$@"
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T17:05:57.133",
"Id": "525051",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T20:47:21.750",
"Id": "525191",
"Score": "0",
"body": "If you are asking for help writing against an API, link the API docs: https://pkgstats.archlinux.de/api/doc"
}
] |
[
{
"body": "<p>First, as someone who writes a lot of bash, I would recommend rewriting this in something other than bash. You're using bash as a programming language (and trying quite hard to make it readable), but it's simply not the best programming language.</p>\n<ul>\n<li>The basic idea of gluing together a bunch of curl and jq commands seems solid.</li>\n<li>I would contact the maintainer of the API, and politely ask them to document the API limit or remove it.</li>\n<li>You're repeatedly using <code>\\</code> at the end of a line, followed by <code>|</code> on the next line. Instead just put <code>|</code> at the end of the first line.</li>\n<li>Separate out the logic of getting all the API responses (<code>get_all_package_json</code>) and restricting to the popular ones (<code>get_popular_packages</code>). jq can take one JSON object per line.</li>\n<li>I would recommend outputting the packages via <code>sort -u</code> to avoid errors and for user convenience.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T08:16:52.387",
"Id": "525027",
"Score": "2",
"body": "``\\``⤶`|` is arguably a style choice - I happen to like it, because it makes pipeline continuation lines quite obvious when scanning the line starts (we don't want to keep indenting for each line here - I've been known to have 10-20 lines in one pipe). When I do that, I don't indent the pipeline continuations the same as the argument continuations, though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T23:56:51.413",
"Id": "525081",
"Score": "1",
"body": "It's definitely a style choice. I don't like trailing \\, because you if you accidentally add a space after it, everything silently breaks but looks fine."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T02:09:43.820",
"Id": "265808",
"ParentId": "265799",
"Score": "3"
}
},
{
"body": "<p>You should probably address these Shellcheck issues:</p>\n<pre class=\"lang-none prettyprint-override\"><code>265799.sh:32:9: warning: Use array+=("item") to append items to an array. [SC2179]\n265799.sh:37:14: note: $/${} is unnecessary on arithmetic variables. [SC2004]\n265799.sh:37:17: note: $/${} is unnecessary on arithmetic variables. [SC2004]\n265799.sh:44:5: warning: Variable was used as an array but is now assigned a string. [SC2178]\n265799.sh:44:37: warning: Quote this to prevent word splitting. [SC2046]\n265799.sh:44:55: note: Double quote to prevent globbing and word splitting. [SC2086]\n</code></pre>\n<hr />\n<p>The implementation doesn't match the description. "Popularity greater or equal than the given one" implies that we are to give a package name as argument, but the program wants a number. I'm guessing that's a mistake in the description, but it emphasises the need to be clear and unambiguous in program documentation (an aspect often overlooked).</p>\n<hr />\n<p>I don't like the command asking for input if the argument is missing - I'd prefer a clear error message showing how to use the command correctly. That makes it easier to debug its use in scripts, for example.</p>\n<hr />\n<p>It's not necessary to use three invocations of <code>jq</code> in the pipe:</p>\n<blockquote>\n<pre><code> | jq ".packagePopularities[]" \\\n | jq "select( .popularity >= $popularity )" \\\n | jq ".name"\n</code></pre>\n</blockquote>\n<p>It's more efficient to use its internal pipelining:</p>\n<pre><code> | jq ".packagePopularities[] | select(.popularity >= $popularity) | .name"\n</code></pre>\n<p>That saves the program having to serialise and deserialise the data twice in the middle.</p>\n<hr />\n<p>There's no need to store results like this:</p>\n<blockquote>\n<pre><code>packages=()\nwhile [ $x -le $total ]; do\n packages+=$(command …)\ndone\necho "${packages[@]}"\n</code></pre>\n</blockquote>\n<p>We can simply print as we go:</p>\n<pre><code>while [ $x -le $total ]; do\n command …\ndone\n</code></pre>\n<p>That means we don't need any Bash functionality, and can write a portable (POSIX) shell script instead. That's likely to be leaner in operation (e.g. if system shell is Dash, which is much lower overhead than Bash).</p>\n<hr />\n<p>The <code>main</code> function captures the output of <code>get_popular_packages</code> into a variable, but then finishes it without using it for anything. I expected something more like</p>\n<pre><code>popularity=$(get_popularity "$@")\nget_popular_packages $(get_total_pkgs) $popularity\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T17:10:13.713",
"Id": "525052",
"Score": "0",
"body": "I don't know why it breaks when I use the internal pipelining of qd.\n\nI'm going to echo the list of packages so I can source this script from another one and install the packages in the other script."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T19:15:04.873",
"Id": "525056",
"Score": "0",
"body": "Sorry I can't help with that - I just believed what I read on the man page. I've barely used jq myself."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T10:10:57.440",
"Id": "265818",
"ParentId": "265799",
"Score": "3"
}
},
{
"body": "<p>After implementing the suggestions. Nobody suggested to stop downloading when the packages have lesser popularity than the given one.</p>\n<pre><code>#!/usr/bin/env bash\n\nfunction usage() {\n cat <<EOF\nUsage: get_popular_packages.sh popularity\nEOF\n exit 1\n}\n\nfunction get_popularity() {\n if [ $# -gt 0 ]; then\n echo $1\n else\n usage\n fi\n}\n\nfunction get_total_packages() {\n curl -sX "GET" -H "accept: application/json" \\\n "https://pkgstats.archlinux.de/api/packages?limit=1&offset=0" \\\n | jq ".total"\n}\n\nfunction get_packages() {\n curl -sX "GET" -H "accept: application/json" \\\n "https://pkgstats.archlinux.de/api/packages?limit=$2&offset=$3" \\\n | jq ".packagePopularities[]" \\\n | jq "select( .popularity >= $1 )" \\\n | jq ".name"\n}\n\nfunction get_popular_packages() {\n local x total limit\n popularity=$(get_popularity "$@")\n total=$(get_total_packages)\n x=0\n limit=2000\n while [ $x -le $total ]; do\n get_packages $popularity $limit $x\n x=$(($x+$limit))\n done\n}\n\nget_popular_packages "$@"\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T19:19:35.717",
"Id": "525057",
"Score": "0",
"body": "You probably want to `usage >&2` in the error case, so the message appears on the error stream."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T20:47:55.660",
"Id": "525192",
"Score": "0",
"body": "Are the packages returned in order of popularity? It's not clear to me that they are."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-10T18:21:51.273",
"Id": "525264",
"Score": "0",
"body": "I just tried it, and I can confirm that the packages are sorted by popularity. I hadn't really checked it before, that's why I didn't mention it when I opened the question."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T17:12:48.900",
"Id": "265832",
"ParentId": "265799",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "265818",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T21:33:43.690",
"Id": "265799",
"Score": "4",
"Tags": [
"bash"
],
"Title": "Get popular Arch packages"
}
|
265799
|
<p>I've made some code that generates cursed error messages like this, for my new language <a href="https://github.com/chunkybanana/javastack" rel="noreferrer">Javastack</a>:</p>
<pre class="lang-none prettyprint-override"><code>BadError on line 58:
S(Y5YN6c/$sIcI\"h>mH424`Ihkt&!3aolsjBHZ%\\J|
^
The problem isn't with the code. It's with you.
</code></pre>
<p>By cursed, I mean that they are random, out of context, useless, and have absolutely nothing to do with your code except for the fact that your code errored, so one of these is showing up.</p>
<p>And the code:</p>
<pre class="lang-js prettyprint-override"><code>function genCursedError(){
let rand = x => x[~~(Math.random() * x.length)], h, q, v;
return `${rand(['Syntax','Reference','Type','Internal','You','Java','Error','Meta','Not An ','Interpreter','Random','Range','Muffin','Potential','Invisible','Bad'])}Error on line ${~~(Math.random() * 100)}:`+'\n\n'+
`${[...Array(z = ~~(Math.random() * 50 + 30))].map(x=>String.fromCharCode(~~(Math.random() * 95 + 32))).join``}`+'\n'+
`${' '.repeat(~~(Math.random() * z))}^`+'\n\n'+
rand([
`${rand(['This','Commas','Life','Screwdrivers','Water','Semicolons','You'])} cannot be used to ${rand(q=['eat','yeet','dissolve','use','remove','convert'])} ${rand(v=['potatoes','semicolons','you','peanuts','coffee','the digestive system'])}`,
`Please don't ${rand(q)} ${rand(v)} - it causes ${rand(['cursed error messages like this one','bad puns','deconfrickulation of apioforms','Vitamin C','5th of July fireworks'])}.`,
`Why did you do it? It's ruined I tell you, ruined!`,
`Golfing tip: Use '${rand(h=['thrice','four','dynamite','add','concat','lyxal','rearrange','permutations'])}' instead of '${rand(h)}'.`,
`The problem isn't with the code. It's with you.`,
])
}
</code></pre>
<p>It uses this basic template:</p>
<pre class="lang-none prettyprint-override"><code>[Random error name]Error on line [Random number]
[Random ASCII]
[Pointer pointing to random location in ASCII]
[One of:
[Random noun] cannot be used to [random verb] [random noun]
Please don't [random verb] [random noun] - it causes [random thing].
Why did you do it? It's ruined I tell you, ruined!
Golfing tip: Use [random thing] instead of [random thing].
The problem isn't with the code. It's with you.
]
</code></pre>
<p>Note that this code is in an imported module so has to be run in strict mode.</p>
<p>Is there anything I can do to make this code more readable and/or efficient?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T17:15:30.350",
"Id": "525054",
"Score": "0",
"body": "Note that strings encased in backticks can go on for multiple lines, so you don't need the `+'\\n\\n'+` stuff. However, it may be better to declare variables like `const errorName = ...` and then use those variables in the string instead of the expressions directly. (I'd write an answer, but I don't have much more advice and don't know JS)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T20:44:56.777",
"Id": "525065",
"Score": "1",
"body": "@user Thanks! According to CR policy, I'm not supposed to fix it here tho."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T20:46:38.110",
"Id": "525066",
"Score": "0",
"body": "I know, just suggesting some changes because I don't have enough for an answer."
}
] |
[
{
"body": "<h2>Efficiency</h2>\n<p>Since there is no real algorithm here to speak of, all optimizations are micro-optimizations and boil down to avoiding unnecessary object allocations.</p>\n<p>Every call to <code>genCursedError</code> allocates and deallocates a function <code>rand</code>. This function is generic, so I'd move it to an enclosing scope, probably a separate module in a large project.</p>\n<p>There are also arrays that are allocated on every call but don't change, <code>['This','Commas','Life'...]</code> and so forth. Moving these to an enclosing scope is less urgent than <code>rand</code> because they don't do much good for any other function (as far as we know).</p>\n<p>These could be default parameters, which are still allocated per call, but at least there's modularity there to justify the allocation. If your specification is fixed, as it seems to be, making them parameters seems premature.</p>\n<p>Another option is a separate configuration object containing all of the string arrays organized by key.</p>\n<p>I'd focus on maintainability and design principles rather than performance here.</p>\n<h2>Template readability</h2>\n<p>Based on the code, it's difficult to tell what the template is relative to the raw version, which is much easier to understand and modify.</p>\n<p>Again, I'm not sure how generic this string should be -- as with the arrays of choices, it's basically baked into the function, which probably makes sense for your needs, but could be turned into a parameter. It'd be cool if the template string was basically verbatim as in the raw bottom quote and the values you wanted were injected without harming readability.</p>\n<p>It's probably overkill, but if you're doing this sort of thing often, <a href=\"https://mustache.github.io/\" rel=\"nofollow noreferrer\">mustache</a> is a lightweight templating library that might save work and improve readability, using established conventions like the <code>{{ something }}</code> syntax.</p>\n<p>Short of that, I'd either parse the braces in the string (prioritizing readability of the template at the risk of introducing parsing logic) or use intermediate variables rather than inlining all of the random generation code.</p>\n<h2>Declarations and variable names</h2>\n<p>In most languages, like Ruby and C, <code>rand</code> doesn't choose a random element from an array, it generates a random float between 0 and 1, between 0 and an upper bound or between two bounds. I'd name this function <code>choice</code> (Python) or <code>sample</code> (Ruby).</p>\n<p>Consider:</p>\n<pre class=\"lang-js prettyprint-override\"><code>let rand = x => x[~~(Math.random() * x.length)], h, q, v;\n</code></pre>\n<p>One letter variables are generally poor practice, and it's pretty hard to make heads or tails of the intent here, other than <code>rand</code> and <code>x</code>. Always use <code>const</code> instead of <code>let</code>, unless you absolutely have to.</p>\n<p>Avoid comma declaration lists. Each variable should be on its own line, and there's no need for forward declarations at the top of functions like ANSI C. Scope data as tightly as possible.</p>\n<h2>Avoid reassignments, especially in-line ones</h2>\n<p>Making matters worse, <code>h</code>, <code>q</code> and <code>v</code> are assigned later on inlined in the template in a function call to <code>rand</code>. I see no benefit of this approach over assigning those variables up front -- it's hard to tell when they're assigned and to what values. As a programmer, <code>const</code> gives me some assurance about the intent and state of the variable over time, so I don't need to trace control flow to determine what's what when. Immutability is even better, so if you <code>Object.freeze</code> your arrays, you have much stronger guarantees about what state the data is in at any given program point.</p>\n<p>In fact, there's another variable, <code>z</code>, which is assigned inline but wasn't declared, meaning this is a global variable. If another function uses this variable, calling this function introduces a potentially very nasty bug due to the corrupted state. I'd check your strict mode declarations you claim to be using, because your original code should be rejected:</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>\"use strict\"; // <-- only thing added\n\nfunction genCursedError(){\n let rand = x => x[~~(Math.random() * x.length)], h, q, v;\n return `${rand(['Syntax','Reference','Type','Internal','You','Java','Error','Meta','Not An ','Interpreter','Random','Range','Muffin','Potential','Invisible','Bad'])}Error on line ${~~(Math.random() * 100)}:`+'\\n\\n'+\n `${[...Array(z = ~~(Math.random() * 50 + 30))].map(x=>String.fromCharCode(~~(Math.random() * 95 + 32))).join``}`+'\\n'+\n `${' '.repeat(~~(Math.random() * z))}^`+'\\n\\n'+\n rand([\n `${rand(['This','Commas','Life','Screwdrivers','Water','Semicolons','You'])} cannot be used to ${rand(q=['eat','yeet','dissolve','use','remove','convert'])} ${rand(v=['potatoes','semicolons','you','peanuts','coffee','the digestive system'])}`,\n `Please don't ${rand(q)} ${rand(v)} - it causes ${rand(['cursed error messages like this one','bad puns','deconfrickulation of apioforms','Vitamin C','5th of July fireworks'])}.`,\n `Why did you do it? It's ruined I tell you, ruined!`,\n `Golfing tip: Use '${rand(h=['thrice','four','dynamite','add','concat','lyxal','rearrange','permutations'])}' instead of '${rand(h)}'.`,\n `The problem isn't with the code. It's with you.`,\n ])\n}\n\ngenCursedError()</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Using <code>const</code> across the board eliminates the temptation to be overly-clever and make a mess with assignments inside expressions.</p>\n<h2>Avoid golfing idioms (unless you're actually golfing)</h2>\n<p>Don't abuse <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates\" rel=\"nofollow noreferrer\">tagged templates</a> for function calls to save 2 characters: <code>join("")</code> is the normal way; <code>x=>String</code> should be <code>x => String</code>; array elements should be separated by a single whitespace after commas; <code>(){</code> should be <code>() {</code>; etc.</p>\n<p>I'm also in the habit of using <code>~~()</code> for flooring but it's better to use <code>Math.floor</code>. Anyway, this should only happen once in the code because you'll surely want to write a wrapper on <code>Math.random()</code> to give an integer between bounds.</p>\n<p>You can avoid the rather ugly <code>+ '\\n\\n' +</code> by merging the newlines into the nearest template literal.</p>\n<h2>Rewrite suggestion</h2>\n<p>This isn't a perfect rewrite; just a first pass attempt at refactoring for maintainability.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const randInt = n => Math.floor(Math.random() * n);\n\nconst sample = a => a[randInt(a.length)];\n\nconst randomString = n => [...Array(n)]\n .map(() => String.fromCharCode(randInt(95) + 32))\n .join(\"\")\n;\n\nconst cursedErrors = {\n errorNames: [\n 'Syntax', 'Reference', 'Type', 'Internal', 'You', 'Java',\n 'Error', 'Meta', 'Not An ', 'Interpreter', 'Random', \n 'Range', 'Muffin', 'Potential', 'Invisible', 'Bad'\n ],\n nouns: {\n upper: [\n 'This', 'Commas', 'Life', 'Screwdrivers',\n 'Water', 'Semicolons', 'You'\n ],\n lower: [\n 'potatoes', 'semicolons', 'you', 'peanuts',\n 'coffee', 'the digestive system'\n ],\n },\n verbs: [\n 'eat', 'yeet', 'dissolve', 'use', 'remove', 'convert'\n ],\n phenomena: [\n 'cursed error messages like this one',\n 'bad puns', 'deconfrickulation of apioforms',\n 'Vitamin C', '5th of July fireworks'\n ],\n golfingTips: [\n 'thrice', 'four', 'dynamite', 'add', 'concat',\n 'lyxal', 'rearrange', 'permutations'\n ],\n randomSentence() { \n return sample([\n `${sample(this.nouns.upper)} cannot be used to ${sample(this.verbs)} ${sample(this.nouns.lower)}`,\n `Please don't ${sample(this.verbs)} ${sample(this.verbs)} - it causes ${sample(this.phenomena)}.`,\n `Why did you do it? It's ruined I tell you, ruined!`,\n `Golfing tip: Use '${sample(this.golfingTips)}' instead of '${sample(this.golfingTips)}'.`,\n `The problem isn't with the code. It's with you.`,\n ]);\n },\n};\n\nconst generateCursedError = () => {\n const errorName = sample(cursedErrors.errorNames);\n const line = randInt(100);\n const ascii = randomString(randInt(50));\n const caretSpace = ' '.repeat(randInt(ascii.length));\n return `${errorName}Error on line ${line}:\\n\\n` +\n `${ascii}\\n${caretSpace}^\\n\\n${cursedErrors.randomSentence()}`\n ; \n};\n\nconsole.log(generateCursedError());</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T23:29:56.510",
"Id": "265841",
"ParentId": "265801",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "265841",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T21:52:25.447",
"Id": "265801",
"Score": "7",
"Tags": [
"javascript"
],
"Title": "Cursed error generator in Javascript"
}
|
265801
|
<p>This is my WIP attempt at an open-source web demo for exploring <a href="https://en.wikipedia.org/wiki/Word_embedding" rel="nofollow noreferrer">word vectors</a> as part of my research. The functionality will be explained separately from the site. It is also my first time using HTML, JavaScript, and CSS in a non-trivial manner, and I am making use of modern HTML and JS features (Plotly only works with recent browsers anyway). There are several parts of my code that don't feel right to me as a programmer and in my experience lead to less clean code:</p>
<ul>
<li><p>Heavy use of global variables: My rationale originally was that many javascript functions needed to access global variables so that they could be called by my HTML buttons. I don't think this is true but I'm not sure how I would refactor the code to avoid globals. Maybe an overarching class with attributes instead of globals? I am more familiar with OOP style but a God object may be too big?</p>
</li>
<li><p>CSS naming: I came up with some custom CSS naming schemes but I am sure there are better ways to name things than trying to use a unique ID for everything, in particular in javascript querySelector by CSS selectors.</p>
</li>
<li><p>Naming in general: I used terminology that I have seen before, but I'm not sure if it is the most accurate (ex. "process", "compute")</p>
</li>
<li><p>Documentation through commenting functions is still a bit lacking</p>
</li>
<li><p>Duplicated data throughout due to changes</p>
</li>
<li><p>Use of async: the only explicitly async parts are loading the main model data. The whole main function runs as async and I'm not sure this is the right approach.</p>
</li>
</ul>
<p>I am looking to make my code cleaner and more maintainable. Hopefully answers can address my concerns above. Most computation is done beforehand so performance should not be an issue for any of the demo functions here. To run the code locally download <a href="https://github.com/jxu/Word2VecDemo/releases/tag/code-review" rel="nofollow noreferrer">this pre-release</a>.</p>
<p>index.html</p>
<pre><code><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Word2Vec Demo</title>
<link rel="stylesheet" href="style.css" />
<script src="https://d3js.org/d3.v7.min.js"></script>
<script src="https://cdn.plot.ly/plotly-2.2.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pako/2.0.3/pako.min.js"></script>
<script src="vector.js"></script>
<script src="word2vec.js"></script>
</head>
<body>
<h1>Word2Vec Demo</h1>
<div id="plots-wrapper">
<div id="scatter-wrapper">
<div id="plotly-scatter"> </div>
<div id="scatter-buttons">
<button id="scatter-button0" onclick="selectAxis(0)">Age</button>
<button id="scatter-button1" onclick="selectAxis(1)">Gender</button>
</div>
</div>
<div id="plotly-magnify"></div>
<div id="plotly-vector"> </div>
</div>
<div id="plots-status-bar">
<span id="loading-text"></span>
<form id="word-entry">
<input id="modify-word-input" type="text">
<button formaction="javascript:modifyWord();" type="submit">Add/Remove Word</button>
</form>
<span id="modify-word-message"></span>
</div>
<details>
<summary>Vector analogy arithmetic</summary>
<div id="analogy-bar">
<!-- autocomplete off to disable Firefox from saving form entries -->
<form id="analogy-form" action="javascript:processAnalogy()" autocomplete="off">
<!-- TODO: add proper spacing for equation -->
<input id="analogy-word-b" type="text" placeholder="king">
-
<input id="analogy-word-a" type="text" placeholder="man">
+
<input id="analogy-word-c" type="text" placeholder="woman">
=
<input id="analogy-word-wstar" type="text" readonly="readonly" placeholder="queen">
<button type="submit">Submit</button>
</form>
</div>
</details>
<form id="user-dimension-wrapper" action="javascript:processDimensionInput();plotScatter()">
<div class="user-dimension-area">
<div class="user-dimension-input">
<label for="user-dimension-feature1-name">Dimension Name</label>
<!-- TODO: better naming scheme in CSS -->
<input class="user-dimension-name" id="user-dimension-feature1-name" type="text">
</div>
<div class="user-dimension-entry">
<textarea class="user-dimension-feature-set" id="user-dimension-feature1-set1" rows="16"></textarea>
<textarea class="user-dimension-feature-set" id="user-dimension-feature1-set2" rows="16"></textarea>
</div>
</div>
<div class="user-dimension-area">
<div class="user-dimension-input">
<label for="user-dimension-feature1-name">Dimension Name</label>
<input class="user-dimension-name" id="user-dimension-feature2-name" type="text">
</div>
<div class="user-dimension-entry">
<textarea class="user-dimension-feature-set" id="user-dimension-feature2-set1" rows="16"></textarea>
<textarea class="user-dimension-feature-set" id="user-dimension-feature2-set2" rows="16"></textarea>
</div>
</div>
<button type="submit">Submit</button>
</form>
</body>
</html>
</code></pre>
<p>style.css</p>
<pre><code>h1 {
text-align: center;
}
#plots-wrapper {
/* default width 100% */
height: 70vh;
display: grid;
grid-template-columns: 50% 15% 35%;
}
#scatter-wrapper {
display: flex;
flex-direction: column;
}
#plotly-scatter {
flex-grow: 1;
}
#plots-status-bar {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
}
#modify-word-input {
width: 50%
}
/* bind vector axis click */
.yaxislayer-above {
cursor: pointer;
pointer-events: all;
}
#user-dimension-wrapper {
display: grid;
grid-template-columns: 1fr 1fr;
}
.user-dimension-area {
display: flex;
flex-direction: column;
}
.user-dimension-entry {
display: grid;
grid-template-columns: 1fr 1fr;
margin: 5px;
}
.user-dimension-feature-set {
margin: 5px;
}
</code></pre>
<p>word2vec.js (main functionality)</p>
<pre><code>"use strict";
const MAGNIFY_WINDOW = 5; // range for magnified view
const HEATMAP_MIN = -0.2; // min and max for heatmap colorscale
const HEATMAP_MAX = 0.2;
// to be used for naming features
let feature1Name;
let feature2Name;
// words to be used for creating dimensions
let feature1Set1, feature1Set2, feature2Set1, feature2Set2;
// Word pairs used to compute features
const FEATURE1_PAIRS =
[
["man", "woman"],
["king", "queen"],
["prince", "princess"],
["husband", "wife"],
["father", "mother"],
["son", "daughter"],
["uncle", "aunt"],
["nephew", "niece"],
["boy", "girl"],
["male", "female"]
];
const FEATURE2_PAIRS =
[
["man", "boy"],
["woman", "girl"],
["king", "prince"],
["queen", "princess"],
["father", "son"],
["mother", "daughter"],
["uncle", "nephew"],
["aunt", "niece"]
];
// Residual words made up from words in gender and age pairs
const RESIDUAL_WORDS = [...new Set(FEATURE1_PAIRS.flat().concat(FEATURE2_PAIRS.flat()))];
// global variables for various plotting functionality
// words plotted on scatter plot
// changes from original demo: replace "refrigerator" with "chair" and "computer"
let scatterWords = ['man', 'woman', 'boy', 'girl', 'king', 'queen', 'prince', 'princess', 'nephew', 'niece',
'uncle', 'aunt', 'father', 'mother', 'son', 'daughter', 'husband', 'wife', 'chair', 'computer'];
// words involved in the computation of analogy in scatter plot (#12)
let analogyScatterWords = [];
// words to show in vector display
let vectorWords = ["queen", "king", "girl", "boy", "woman", "man"];
// selected word in scatterplot (empty string represents nothing selected)
let selectedWord = "";
// saved hoverX for use in magnify view
let hoverX = MAGNIFY_WINDOW;
// main word to vector Map (may include pseudo-word vectors like "man+woman")
let vecs = new Map();
// Set of actual words found in model
let vocab = new Set();
let vecsDim; // word vector dim
let nearestWords; // nearest words Map
// vector calculations and plotting, including residual (issue #3)
let feature1, feature2, residualFeature;
// read raw model text and write to vecs and vocab
function processRawVecs(text) {
const lines = text.trim().split(/\n/);
for (const line of lines) {
const entries = line.trim().split(' ');
vecsDim = entries.length - 1;
const word = entries[0];
const vec = new Vector(entries.slice(1).map(Number)).unit(); // normalize word vectors
vocab.add(word);
vecs.set(word, vec);
}
// sanity check for debugging input data
RESIDUAL_WORDS.forEach(word => console.assert(vecs.has(word),word + " not in vecs"));
}
function processNearestWords(text) {
let nearestWords = new Map();
const lines = text.trim().split(/\n/);
for (const line of lines) {
const entries = line.trim().split(' ');
const target = entries[0];
const words = entries.slice(1);
nearestWords.set(target, words);
}
return nearestWords;
}
// create feature dimension vectors
function createFeature(vecs, wordSet1, wordSet2) {
// for each pair of words, subtract vectors
console.assert(wordSet1.length === wordSet2.length);
const subVecs = wordSet1.map((word1, i) => vecs.get(word1).sub(vecs.get(wordSet2[i])));
// average subtracted vectors into one unit feature vector
return subVecs.reduce((a,b) => a.add(b)).unit();
}
// plot each word on a 3D scatterplot projected onto gender, age, residual features
function plotScatter(newPlot=false) {
// populate feature vectors
feature1 = createFeature(vecs, feature1Set1, feature1Set2);
feature2 = createFeature(vecs, feature2Set1, feature2Set2);
const allFeatureWords = feature1Set1.concat(feature1Set2).concat(feature2Set1).concat(feature2Set2);
const residualWords = [...new Set(allFeatureWords)];
// residual dim calculation described in #3
residualFeature = residualWords.map(word => {
const wordVec = vecs.get(word);
const wordNoFeature1 = wordVec.sub(feature1.scale(wordVec.dot(feature1)));
const wordResidual = wordNoFeature1.sub(feature2.scale(wordNoFeature1.dot(feature2)));
return wordResidual;
}
).reduce((a,b) => a.add(b)).unit(); // average over residual words and normalize
// add features as pseudo-words
// TODO: not hard-code
vecs.set("[age]", feature2);
vecs.set("[gender]", feature1);
// words to actually be plotted (so scatterWords is a little misleading)
const plotWords = [...new Set(scatterWords.concat(analogyScatterWords))];
// x, y, z are simply projections onto features
// use 1 - residual for graphical convention (#3)
const x = plotWords.map(word => 1 - vecs.get(word).dot(residualFeature));
const y = plotWords.map(word => vecs.get(word).dot(feature1));
const z = plotWords.map(word => vecs.get(word).dot(feature2));
// color points by type with priority (#12)
const color = plotWords.map(word =>
(word === selectedWord) ? "#FF0000"
: (word === analogyScatterWords[3]) ? "#FF8888"
: (word === analogyScatterWords[4]) ? "#00FF00"
: (analogyScatterWords.includes(word)) ? "#0000FF"
: "#000000"
);
// For each point, include numbered list of nearest words in hovertext
const hovertext = plotWords.map(target =>
`Reference word:<br>${target}<br>` +
"Nearest words:<br>" +
nearestWords.get(target)
.map((word, i) => `${i+1}. ${word}`)
.join("<br>")
);
const data = [
{
x: x,
y: y,
z: z,
mode: "markers+text",
type: "scatter3d",
marker: {
size: 4,
opacity: 0.8,
color: color
},
text: plotWords,
hoverinfo: "text",
hovertext: hovertext
}
];
const ZOOM = 0.8;
// save previous camera code (workaround for #9)
let camera;
if (newPlot) {
camera = {eye: {x: -2.5*ZOOM, y: -0.75*ZOOM, z: 0.5*ZOOM}};
} else { // save camera
const plotly_scatter = document.getElementById("plotly-scatter");
camera = plotly_scatter.layout.scene.camera;
}
console.log("Using camera", camera);
const layout = {
title: {text: "Word vector projection"},
//uirevision: "true",
scene: {
xaxis: {title: "Residual", dtick: 0.1},
yaxis: {title: "Gender", dtick: 0.1},
zaxis: {title: "Age", dtick: 0.1},
camera: camera
},
margin: {l:0, r:0, t:30, b:0}, // maximize viewing area
font: {size: 12}
};
// always make new plot (#9)
// replotting scatter3d produces ugly error (#10)
Plotly.newPlot("plotly-scatter", data, layout);
// bind scatter click event
let plotly_scatter = document.getElementById("plotly-scatter");
plotly_scatter.on("plotly_click", (data) => {
const ptNum = data.points[0].pointNumber;
const clickedWord = plotWords[ptNum];
if (clickedWord === selectedWord) { // deselect
selectedWord = "";
console.log("Deselected", clickedWord);
} else { // select
selectedWord = clickedWord;
console.log("Selected", selectedWord);
}
// replot with new point color
plotScatter();
});
}
function selectAxis(axis) {
// TODO: cleanup
console.log("button", axis);
const axisNames = ["[age]", "[gender]"];
if (selectedWord === axisNames[axis]) { // deselect word
selectedWord = "";
} else { // select word
selectedWord = axisNames[axis];
}
// TODO: move updating button color to own function that is also called on scatter click
for (const i of [0,1]) {
const buttonID = "scatter-button" + i;
document.getElementById(buttonID).style.color = (selectedWord === axisNames[i]) ? "red" : "black";
}
plotScatter(); // replot selected word
}
function updateHeatmapsOnWordClick() {
// affects all heatmaps since they all have .yaxislayer-above!
// https://stackoverflow.com/a/47400462
console.log("Binding heatmap click event");
d3.selectAll(".yaxislayer-above").selectAll("text")
.on("click", (d) => {
const idx = d.target.__data__.x;
console.log("Clicked on", idx);
if (selectedWord) {
// modify vector view to show selected word and then deselect
vectorWords[idx] = selectedWord;
selectedWord = "";
// replot all
plotScatter();
plotVector();
}
});
}
// plot vector and magnify views
function plotVector(newPlot=false) {
// heatmap plots matrix of values in z
const z = vectorWords.map(word => vecs.get(word));
const data = [
{
// can't use y: vectorWords since the heatmap won't display duplicate words
z: z,
zmin: HEATMAP_MIN,
zmax: HEATMAP_MAX,
type: "heatmap",
ygap: 5
}
];
const layout = {
title: {text: "Vector visualization"},
xaxis: {
title: "Vector dimension",
dtick: 10,
zeroline: false,
fixedrange: true
},
yaxis: {
title: "Words",
tickvals: d3.range(vectorWords.length),
ticktext: vectorWords,
fixedrange: true,
tickangle: 60
},
margin: {t:30},
//dragmode: false
};
if (newPlot) {
Plotly.newPlot("plotly-vector", data, layout);
const plotly_vector = document.getElementById("plotly-vector");
// bind axis click to replace word in vector display after plot
plotly_vector.on("plotly_afterplot", updateHeatmapsOnWordClick);
plotly_vector.on("plotly_hover", data => {
hoverX = data.points[0].x;
console.log("Hover " + hoverX);
plotMagnify();
});
plotMagnify(true);
}
else {
Plotly.react("plotly-vector", data, layout);
plotMagnify();
}
}
function plotMagnify(newPlot=false) {
// ensure hoverX will produce proper plot
// bounds are inclusive
const lo = hoverX - MAGNIFY_WINDOW;
const hi = hoverX + MAGNIFY_WINDOW;
if (!(0 <= lo && hi < vecsDim))
return;
// heatmap with subset of z
const z = vectorWords.map(word =>
vecs.get(word).slice(lo, hi + 1));
const data = [
{
x: d3.range(lo, hi + 1),
z: z,
zmin: HEATMAP_MIN,
zmax: HEATMAP_MAX,
type: "heatmap",
ygap: 5,
showscale: false
}
];
const layout = {
title: {text: "Magnified view"},
xaxis: {
title: "Vector dimension",
dtick:1,
zeroline: false,
fixedrange: true
},
yaxis: {
//title: "Words",
tickvals: d3.range(vectorWords.length),
ticktext: vectorWords,
fixedrange: true,
tickangle: 60
},
margin: {r:5, t:30} // get close to main vector view
};
if (newPlot) {
Plotly.newPlot("plotly-magnify", data, layout);
// bind axis click after plot, similar to vector
const plotly_magnify = document.getElementById("plotly-magnify");
plotly_magnify.on("plotly_afterplot", updateHeatmapsOnWordClick);
}
else Plotly.react("plotly-magnify", data, layout);
}
function modifyWord() {
const word = document.getElementById("modify-word-input").value;
let wordModified = false;
if (scatterWords.includes(word)) { // remove word
scatterWords = scatterWords.filter(item => item !== word);
document.getElementById("modify-word-message").innerText = `"${word}" removed`;
selectedWord = ""; // remove selected word
wordModified = true;
}
else { // add word if in wordvecs
if (vecs.has(word)) {
scatterWords.push(word);
document.getElementById("modify-word-message").innerText = `"${word}" added`;
selectedWord = word; // make added word selected word
wordModified = true;
}
else { // word not found
document.getElementById("modify-word-message").innerText = `"${word}" not found`;
// no replot or change to selected word
}
}
if (wordModified) {
plotScatter(); // replot to update scatter view
document.getElementById("modify-word-input").value = ""; // clear word
}
}
// compute 3COSADD word analogy
// also write arithmetic vectors to vector view and add nearest neighbors to result (#14)
// "Linguistic Regularities in Continuous Space Word Representations" (Mikolov 2013)
// Analogy notation for words: a:b as c:d, with d unknown
// vector y = x_b - x_a + x_c, find w* = argmax_w cossim(x_w, y)
function processAnalogy() {
const wordA = document.getElementById("analogy-word-a").value;
const wordB = document.getElementById("analogy-word-b").value;
const wordC = document.getElementById("analogy-word-c").value;
const inputWords = [wordA, wordB, wordC];
// TODO: handle more gracefully telling user if words not available
if (!(vecs.has(wordB) && vecs.has(wordA) && vecs.has(wordC))) {
console.warn("bad word");
return;
}
const vecA = vecs.get(wordA);
const vecB = vecs.get(wordB);
const vecC = vecs.get(wordC);
// vector arithmetic, scale to unit vector
const vecBMinusA = vecB.sub(vecA);
const wordBMinusA = `${wordB}-${wordA}`;
const vecY = vecBMinusA.add(vecC).unit();
const wordY = `${wordB}-${wordA}+${wordC}`;
// find most similar words for analogy
let wordAnalogyPairs = [...vocab]
.filter(word => !inputWords.includes(word)) // don't match words used in arithmetic (#12)
.map(word => [word, vecY.dot(vecs.get(word))]);
wordAnalogyPairs.sort((a,b) => b[1] - a[1]);
const nearestAnalogyWords = wordAnalogyPairs.slice(0, 10).map(pair => pair[0]);
const wordWstar = nearestAnalogyWords[0];
// add nearest words to Y to nearest word list (#12)
nearestWords.set(wordY, nearestAnalogyWords);
// write out most similar word to text box
document.getElementById("analogy-word-wstar").value = wordWstar;
// write arithmetic vectors to vector view
vecs.set(wordBMinusA, vecBMinusA);
vecs.set(wordY, vecY);
// set analogy words to display in scatter (#12) in specific order:
analogyScatterWords = [wordB, wordA, wordC, wordY, wordWstar];
plotScatter();
// write arithmetic vectors to vector view (#14)
vectorWords = [wordB, wordA, wordBMinusA, wordC, wordY, wordWstar].reverse();
plotVector();
}
// inflate option to:"string" freezes browser, see https://github.com/nodeca/pako/issues/228
// TextDecoder may hang browser but seems much faster
function unpackVectors(vecsBuf) {
return new Promise((resolve, reject) => {
const vecsUint8 = pako.inflate(vecsBuf);
const vecsText = new TextDecoder().decode(vecsUint8);
return resolve(vecsText);
});
}
// fill in default words used to define semantic dimensions for scatterplot
function fillDimensionDefault() {
document.getElementById("user-dimension-feature1-set1").textContent =
"man\nking\nprince\nhusband\nfather\nson\nuncle\nnephew\nboy\nmale";
document.getElementById("user-dimension-feature1-set2").textContent =
"woman\nqueen\nprincess\nwife\nmother\ndaughter\naunt\nniece\ngirl\nfemale";
document.getElementById("user-dimension-feature2-set1").textContent =
"man\nwoman\nking\nqueen\nfather\nmother\nuncle\naunt";
document.getElementById("user-dimension-feature2-set2").textContent =
"boy\ngirl\nprince\nprincess\nson\ndaughter\nnephew\nniece";
}
function processDimensionInput() {
const feature1Set1Input = document.getElementById("user-dimension-feature1-set1").value.split('\n');
const feature1Set2Input = document.getElementById("user-dimension-feature1-set2").value.split('\n');
const feature2Set1Input = document.getElementById("user-dimension-feature2-set1").value.split('\n');
const feature2Set2Input = document.getElementById("user-dimension-feature2-set2").value.split('\n');
// TODO: user validation
feature1Set1 = feature1Set1Input;
feature1Set2 = feature1Set2Input;
feature2Set1 = feature2Set1Input;
feature2Set2 = feature2Set2Input;
console.log(feature1Set1, feature1Set2, feature2Set1, feature2Set2);
}
// fetch wordvecs locally (no error handling) and process
async function main() {
// fill default feature for scatterplot
fillDimensionDefault();
// lo-tech progress indication
const loadingText = document.getElementById("loading-text");
loadingText.innerText = "Downloading model...";
// note python's http.server does not support response compression Content-Encoding
// browsers and servers support content-encoding, but manually compress to fit on github (#1)
const vecsResponse = await fetch("wordvecs50k.vec.gz");
const vecsBlob = await vecsResponse.blob();
const vecsBuf = await vecsBlob.arrayBuffer();
// async unpack vectors
loadingText.innerText = "Unpacking model...";
const vecsText = await unpackVectors(vecsBuf);
loadingText.innerText = "Processing vectors...";
processRawVecs(vecsText);
// fetch nearest words list
const nearestWordsResponse = await fetch("nearest_words.txt");
const nearestWordsText = await nearestWordsResponse.text();
nearestWords = processNearestWords(nearestWordsText);
loadingText.innerText = "Model processing done";
processDimensionInput();
// plot new plots for the first time
plotScatter(true);
plotVector(true);
}
// Main function runs as promise after DOM has loaded
document.addEventListener("DOMContentLoaded", () => {
main().catch(e => console.error(e));
});
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>This a pretty big submission, so I'm going to focus on what I think is most important.</p>\n<p>The feeling I got from skimming the code:</p>\n<ul>\n<li>Good formatting and good use of modern javascript overall.</li>\n<li>Seems to be fairly easy to read overall, though a bit hard to follow the globals.</li>\n<li>Good use of domain specific names etc.</li>\n<li>No overly clever bits even when there is plenty of opportunity.</li>\n<li>Some functions seem to be unused, unsure about those.</li>\n</ul>\n<p>I think where it falls a bit short is mainly in the architecture (you allude to this with your comment about globals),\nand also a bit about commenting.</p>\n<h3>Architecture</h3>\n<ul>\n<li><code>processRawVecs</code> and <code>processNearestWords</code> use the word "process" in the name.\nThe former doesn't return anything. It stores the result in global variables.\nThe latter is a pure function.\nThis is a sign to me that the word "process" doesn't have any particular meaning.\nIt could just as well be "doStuff".\nI would recommend changing all pure function names to something more tangible, like <code>getNearestWords</code>.\nThe goal is to create separate abstractions for separate things.</li>\n<li>While we're at it, most of <code>processRawVecs</code> can be written as a pure function as well.\nThe part where you add to global state can be moved out of this function.\nIn fact, if you do this aggressively across all your functions you will get to a\npoint where most of the logic is contained in pure functions,\nand where the rest of the code simply organizes the state changes.\nIf you end up here, you most likely won't need global variables (they can go in a function or class intead),\nbut even if you do, you will have less places that touch them (most usages of the globals will be as function parameters, not globals)\nThe technique is called "functional core, imperative shell".</li>\n<li><code>plotScatter</code> is another example.\nThere's quite a lot of logic, all of which cannot run without also displaying the plot.\nOne consequence of this is that it's hard or impossible to test in isolation.\nIf it's hard to test in isolation, it's often hard to think about in isolation as well.</li>\n</ul>\n<p>To summarize: I would recommend that you organize your code such that</p>\n<ul>\n<li>The code touching the dom (plotting etc) only does stuff related to that. Move the logic to pure functions.</li>\n<li>Try to extract as much as possible away from the functions that touches the globals. Make pure functions where it makes sense.</li>\n<li>Sandwich the pure functions (which will be most of the logic in your case) in between code that mutates the state and renders the plot.</li>\n<li>Consider splitting each of view, logic, and state into three separate files to really hammer home the differences.</li>\n</ul>\n<p>The result will hopefully be that you have more control over the global state, as well as more testable and understandable code.\nThe benefits will of course depend on how large the application becomes in the end.</p>\n<h3>Comments and names</h3>\n<ul>\n<li>There's a large amount of comments. Some of them are good.\nFor example <code>// to be used for naming features</code> is good because I would otherwise delete the unused variables below.\nMost of the comments I think are indications of unclear abstractions, missing functions, too short function names, or are just unecessary.</li>\n</ul>\n<p>Snippet 1:</p>\n<pre><code>// create feature dimension vectors\nfunction createFeature\n</code></pre>\n<p>It's interesting to ask why this comment needs to exist.\nI can see at least three possibilities:</p>\n<ol>\n<li>The name should have been "createFeatureDimensionVectors",\nbecause that is simply what it does (that is, a "feature" is not the correct name for this abstraction).\nThis seems unlikely since the name "feature" is repeated all over in the rest of the code.</li>\n<li>The name "feature" is the correct name, but the abstraction is a little too fuzzy or too general,\nso you feel compelled to further clarify. If this is the case, the abstraction might need some more work.</li>\n<li>The comment is pointless, and can be removed</li>\n</ol>\n<p>Snippet 2:</p>\n<pre><code>// populate feature vectors\n feature1 = createFeature(vecs, feature1Set1, feature1Set2);\n</code></pre>\n<p>Again I'm wondering what this comment is trying to achieve.</p>\n<p>There's a bunch more of these.\nI would recommend reading through the comments to see if they're necessary.\nMaybe change a few variable names and extract a function or two as well.\nI think this will improve readability and reduce noise.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T21:56:04.820",
"Id": "525070",
"Score": "0",
"body": "Thank you for your comments. I'll try to separate the state changing parts because I think there is a lot of inter dependencies. Briefly: is the use of async proper? I just wrapped the entire main function as async."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-08T08:18:22.427",
"Id": "525093",
"Score": "0",
"body": "Yes, looks good to me :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T20:04:12.983",
"Id": "525188",
"Score": "0",
"body": "What do you think about putting all my globals and functions into one Demo class? I feel like this organizes things better, even if with one class it is almost equivalent to having global variables everywhere."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T21:23:51.123",
"Id": "265836",
"ParentId": "265802",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T22:31:35.523",
"Id": "265802",
"Score": "3",
"Tags": [
"javascript",
"html",
"css",
"data-visualization"
],
"Title": "Javascript Word Vectors Demo"
}
|
265802
|
<p>So this code is yet another attempt at solving the <a href="https://projecteuler.net/index.php?section=problems&id=2" rel="nofollow noreferrer">second Project Euler problem</a> to improve my handling of Python. The purpose of the code is to solve the problem below</p>
<blockquote>
<p>Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will
be:</p>
<pre><code>1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
</code></pre>
<p>By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.</p>
</blockquote>
<hr />
<h3>Method</h3>
<p>However, I wanted to do it as fast as possible meaning:</p>
<ul>
<li>Cache small values and use a fast lookup table (bisection lookup)</li>
<li>For larger values iterate over the even fibonacci values directly using
the linear recurrence relation <code>E(n) = 4 E(n-1) + E(n - 2)</code> with <code>E(0)=0</code> and <code>E(1)=2</code>.</li>
</ul>
<hr />
<h3>Questions / Wanted feedback</h3>
<p>In particular I wanted to know if my general definition of a recurrence relation could be improved. In particular <code>values[:-1], values[-1] = values[1:], last</code>
feels quite unpythonic to me. Secondly I am wondering if my docstrings are clear enough. I tried to strictly follow the Google Docstring style.</p>
<p>As a side note <code># fmt: on</code> and <code>#fmt: off</code> are strictly neccecary to make sure my formater does not format my lookup tables.</p>
<hr />
<h3>Code</h3>
<pre><code>"""
This code solves Project Euler Problem 2:
Each new term in the Fibonacci sequence is generated by adding the previous
two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not
exceed four million, find the sum of the even-valued terms.
See https://projecteuler.net/index.php?section=problems&id=2 for details
"""
import bisect
EvenFibSum = int
Limit = int
PE_002_LIMIT = 4 * 10 ** 6
# fmt: off
EVEN_FIBS = [
0, 2, 8, 34, 144, 610, 2584, 10946, 46368, 196418, 832040, 3524578,
14930352, 63245986, 267914296, 1134903170, 4807526976, 20365011074,
86267571272, 365435296162, 1548008755920, 6557470319842, 27777890035288,
117669030460994, 498454011879264, 2111485077978050, 8944394323791464,
37889062373143906, 160500643816367088, 679891637638612258,
2880067194370816120, 12200160415121876738
]
# fmt: on
EVEN_FIBS_ = set(EVEN_FIBS)
# fmt: off
EVEN_FIBS_CUMSUM = [
0, 2, 10, 44, 188, 798, 3382, 14328, 60696, 257114, 1089154, 4613732,
19544084, 82790070, 350704366, 1485607536, 6293134512, 26658145586,
112925716858, 478361013020, 2026369768940, 8583840088782, 36361730124070,
154030760585064, 652484772464328, 2763969850442378, 11708364174233842,
49597426547377748, 210098070363744836, 889989708002357094,
3770056902373173214, 15970217317495049952
]
# fmt: on
def linear_reccurence(constants: list[int], initials: list[int]) -> int:
"""Returns a generator for a linear recucurence relation
A linear recurrence relation is of the form
A(n) = c0 * A(n-1) + c0 * A(n-2) + ... + ck * A(n - k);
A(0) = I0, A(1) = I1, ..., A(k) = Ik
and would correspond to ``constants = [ck ..., c1, c0]`` and ``initials =
[Ik, ..., I1, I0]``. Note that the values here are stored in ascending order
Args:
constants: Defines the constants in the recucurence relation.
initials: The initial values for the recurrence relation.
Yields:
The next value in the recucurence relation.
Examples:
Returns the Fibonacci numbers ``F(n) = F(n-1) + F(n-2)`` with ``F(0)=0``, ``F(1)=1``.
>>> fibonacci = linear_reccurence([1, 1], [0, 1])
>>> print([next(fibonacci) for _ in range(10)])
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Returns the Lucas numbers ``L(n) = L(n-1) + L(n-2)`` with ``L(0)=1``, ``L(1)=3``.
>>> lucas = linear_reccurence([1, 1], [1, 3])
>>> print([next(lucas) for _ in range(10)])
[1, 3, 4, 7, 11, 18, 29, 47, 76, 123]
"""
values = initials.copy()
for value in values:
yield value
while True:
last = sum(const * value for const, value in zip(constants, values))
values[:-1], values[-1] = values[1:], last
yield last
def PE_002(limit: Limit = PE_002_LIMIT) -> EvenFibSum:
"""Sums all even fibonacci numbers under some limit
Args:
limit: Sums all even fibonacci numbers less than this limit
Returns:
The sum of all even fibonacci numbers less than some limit
Examples:
>>> limits = [0, 2, 8, 10, 10**8]
>>> print([PE_002(lim) for lim in limits])
[0, 2, 10, 10, 82790070]
>>> print(PE_002(2**65-1))
15970217317495049952
"""
def _even_fib_sum_large(limit: Limit) -> EvenFibSum:
total = EVEN_FIBS_CUMSUM[-1] - EVEN_FIBS[-2] - EVEN_FIBS[-1]
# The linear recurrence relation for the even fibonacci numbers is
# E(n) = 4 * E(n - 1) + 1 * E(n - 2); E(0) = 0, E(1) = 2
# See https://math.stackexchange.com/questions/94359/need-help-deriving-recurrence-relation-for-even-valued-fibonacci-numbers
even_fibonacci = linear_reccurence([1, 4], [EVEN_FIBS[-2], EVEN_FIBS[-1]])
while (even_fib := next(even_fibonacci)) < limit:
total += even_fib
return total
def _even_fib_sum_small(limit: Limit) -> EvenFibSum:
# The code performs a lookup to find the largest index such that EVEN_FIBS[index] <= limit.
# The lookup is done in O(log n) using a basic bisection algorithm.
# The offset is added because bisection performs < and we need <=
offset = 0 if limit in EVEN_FIBS_ else 1
index = bisect.bisect_left(EVEN_FIBS, limit)
return EVEN_FIBS_CUMSUM[index - offset]
if limit > EVEN_FIBS[-1]:
return _even_fib_sum_large(limit)
return _even_fib_sum_small(limit)
if __name__ == "__main__":
import doctest
import argparse
doctest.testmod()
parser = argparse.ArgumentParser(
description="Solves Project Euler 2; Sums all even fibonacci numbers less than limit"
)
parser.add_argument(
dest="limit",
nargs="?",
type=int,
default=PE_002_LIMIT,
help="Sums all even fibonacci numbers less than this number",
)
args = parser.parse_args()
print(PE_002(args.limit))
</code></pre>
|
[] |
[
{
"body": "<p>Disclaimer 1: This is not a review, but an extended comment.</p>\n<p>Disclaimer 2: ProjectEuler is not about programming. It is about math. As long as you understand what the problem is about, an actual computation is supposed to be very simple.</p>\n<blockquote>\n<p>I wanted to do it as fast as possible</p>\n</blockquote>\n<p>You can do it much faster.</p>\n<p>Observation #1: a parity of Fibonacci numbers follows the pattern of</p>\n<pre><code>odd even odd\nodd even odd\n...\n</code></pre>\n<p>(more or less obvious, but still try to prove it) so the sum of even-valued terms is the sum of every third term.</p>\n<p>Observation #2: since Fibonacci numbers (as any linear recurrence) have a nice <a href=\"https://mathworld.wolfram.com/BinetsFibonacciNumberFormula.html\" rel=\"noreferrer\">closed-form representation</a>, observe that the answer is a sum of two geometric progressions. With a little work you may express it in terms of a couple of larger Fibonacci numbers.</p>\n<p>Observation $3: computing an <code>n</code>th Fibonacci number (as any linear recurrence) does not need to be linear in <code>n</code>. A (matrix) <a href=\"https://www.geeksforgeeks.org/matrix-exponentiation/\" rel=\"noreferrer\">exponentiation-by-squaring</a> let you do it in a logarithmic time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T00:40:35.773",
"Id": "525013",
"Score": "0",
"body": "Here is a code implementing most of your ideas https://pastebin.com/TFNQBHVx. The reason I decided to try to implement it using recurrence relations and bisections is more for mostly for learning. My only issue with your comment is that we need to figure out how many terms we need to sum to take advantage of the closed forms. This leads to rounding off errors for large values unfortunately. Secondly taking advantage of maths is very specific to this particular problem and hard to generalize."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T00:42:25.490",
"Id": "525014",
"Score": "0",
"body": "`This leads to rounding off errors for large values unfortunately` - with a correct implementation it should not. Pay attention to the Observation #2."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T00:49:35.170",
"Id": "525015",
"Score": "0",
"body": "@vpn Did you check out my pastebin? If you use Bennets formula you still need to solve `F(3n) < limit` for `n` to figure out how many terms to sum. In addition there are far faster algorithms for finding the nth fibonacci number than matrix multiplication. The pastebin uses the one from here https://stackoverflow.com/a/48171368/1048781."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T01:06:37.500",
"Id": "525016",
"Score": "0",
"body": "Solving `F(3n) < limit` is more or less \\$O(\\log \\log {limit})\\$. The SO answer you linked is still \\$\\log{n}\\$ as far as I can tell (`n` being properly defined of course)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T01:09:20.920",
"Id": "525017",
"Score": "0",
"body": "Solving `F(3n) < limit` is what causes the rounding errors"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T00:21:06.367",
"Id": "265805",
"ParentId": "265804",
"Score": "5"
}
},
{
"body": "<p>I can't comment on your algorithm, but your code seems very readable from my perspective. Just a few small comments:</p>\n<p><strong>1. Type aliases</strong></p>\n<p>These two lines confused me at first:</p>\n<pre><code>EvenFibSum = int\nLimit = int\n</code></pre>\n<p>After I read further down, it became clear that the purpose of these two lines was to create type aliases for clearer annotations. However, you could maybe consider adding a comment above these two lines to explain what's going on. Alternatively, consider using <code>typing.Annotated</code> or <code>typing.NewType</code>. (Personally, I'm a fan of <code>typing.Annotated</code>.)</p>\n<p>For example, perhaps:</p>\n<pre><code>from typing import Annotated\n\nEvenFibSum = Annotated[\n int, \n "A positive integer representing the sum "\n "of all even Fibonacci numbers below some limit"\n]\n\nLimit = Annotated[\n int, \n "A positive integer representing the limit "\n "below which all even Fibonacci numbers are to be summed"\n]\n</code></pre>\n<p><strong>2. [Edited]: Consider choosing more distinct names for <code>EVEN_FIBS</code> and <code>EVEN_FIBS_</code>, as discussed in the comments.</strong></p>\n<p><strong>3. Consider moving your <code>argpars</code>ing to a separate function.</strong></p>\n<p>Suggested refactoring of your <code>if __name__ == '__main__'</code> block:</p>\n<pre><code>def get_cmd_args():\n from argparse import ArgumentParser\n \n parser = ArgumentParser(\n description="Solves Project Euler 2; Sums all even fibonacci numbers less than limit"\n )\n\n parser.add_argument(\n dest="limit",\n nargs="?",\n type=int,\n default=PE_002_LIMIT,\n help="Sums all even fibonacci numbers less than this number",\n )\n\n return parser.parse_args()\n\n\nif __name__ == "__main__":\n import doctest\n doctest.testmod()\n args = get_cmd_args()\n print(PE_002(args.limit))\n</code></pre>\n<p>Your docstrings look great to me!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T13:03:25.923",
"Id": "525158",
"Score": "1",
"body": "Thanks for the great feedback! Could you perhaps add an example on how to implement the `Annotations`? I can not seem to figure out a good value for the metadata `x` in `Annotated[T, x]`. Also how would the code work if `EVEN_FIBS` is removed? Do note that I use `EVEN_FIBS_` (underscore) as a lookup and `EVEN_FIBS` as a list. For instance I traverse this list in the bisection part. I thought `variable_` was the standard way of defining the set / dict conterpart for a list? Lastly, would `get_cmd_args` be better as a \"private method\" (`_get_cmd_args`)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T13:14:28.053",
"Id": "525160",
"Score": "1",
"body": "My apologies, I hadn't noticed that `EVEN_FIBS` and `EVEN_FIBS_` were different variables. I wasn't aware of that convention regarding trailing underscore names — personally, I think I would always go for more distinct names, but that's just my opinion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T13:29:19.237",
"Id": "525161",
"Score": "1",
"body": "I've added some suggestions regarding the `Annotations`, though it's obviously fairly opinionated! Can see the argument for `get_cmd_args` being a private method."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-09T12:16:01.677",
"Id": "265879",
"ParentId": "265804",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "265879",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-06T23:27:02.830",
"Id": "265804",
"Score": "4",
"Tags": [
"python",
"performance",
"python-3.x",
"programming-challenge"
],
"Title": "Bisection, linear recurrences and even Fibonacci numbers"
}
|
265804
|
<p>CodeSignal put out a challenge by Uber that involves writing a "fare estimator" that involves a function dependent on cost per minute, cost per mile, ride time and ride distance.</p>
<p>The formula is along the lines of...</p>
<p>Given that: cₐ stands for cost per minute, rₐ stands for ride time, cₑ stands for cost per mile and rₑ ride distance, the estimation formula is: <span class="math-container">$$E = c_a \cdot r_a + c_e \cdot r_e $$</span></p>
<p>My solution:</p>
<pre class="lang-cpp prettyprint-override"><code>/* CodeSignal Company Challenges
*
* A solution to Uber's "fareEstimator" challenge
* By A. S. "Aleksey" Ahmann, hackermaneia@riseup.net
*
*/
double estimation_forumla(int ride_time, int ride_distance, double cost_per_minute, double cost_per_mile) {
return (cost_per_minute * ride_time) + (cost_per_mile * ride_distance);
}
vector<double> fareEstimator(int ride_time, int ride_distance, vector<double> cost_per_minute, vector<double> cost_per_mile) {
vector<double> estimates;
for (int i = 0; i < cost_per_minute.size(); i++)
estimates.insert(estimates.end(), estimation_forumla(ride_time, ride_distance, cost_per_minute[i], cost_per_mile[i]));
return estimates;
}
</code></pre>
<p>I initially <a href="/q/263636">solved this in Python</a> and ported it to C++ whilst taking into account the feedback of other programmers on that question.</p>
<p>They recommended not using any fancy code golf, as shorter code usually implies difficulty to maintain but does not imply faster. In C++, it's more difficult to "code golf" my solution, so no fancy tricks there (I hope). They also recommended that I use better names to my variables. Do you feel that I did a decent job naming my variables?</p>
<p>Finally, they recommended that I use type hints. I believe that the newer versions of C++ allow for type inference (though please correct me on that if I'm wrong :P), but I decided to declare variables by their type.</p>
<p>Do you feel that I was able to follow the advice given and did better than <a href="/q/263636">my initial attempt</a>? Also, just give me any feedback that you have for my code. What could I have done better? What did you like (or dislike) about it? Let me know!</p>
<p>You can check out the <a href="https://app.codesignal.com/company-challenges/uber/HNQwGHfKAoYsz9KX6" rel="nofollow noreferrer">full challenge</a> (but you might need to sign up).</p>
<p>And here's <a href="https://github.com/Alekseyyy/ctfs/blob/master/programming/codesignal/companies/Uber/fareEstimator/solution.cpp" rel="nofollow noreferrer">my solution on GitHub</a> if you're interested.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T19:23:36.757",
"Id": "525058",
"Score": "1",
"body": "I'm not sure who \"they\" are, but recommending type hints makes sense for Python, being a duck-typed language. What you have done here (explicit typing) seems perfectly appropriate in C++."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T20:00:38.097",
"Id": "525062",
"Score": "0",
"body": "@TobySpeight this is who I meant by \"they\": https://codereview.stackexchange.com/q/263636"
}
] |
[
{
"body": "<p>There isn't much code to review here.</p>\n<ol>\n<li><p>Use correct spelling. <code>estimation_forumla</code> should be <code>estimation_formula</code>.</p>\n</li>\n<li><p>Use consistent naming conventions. <code>estimation_forumla</code> is snake case, while <code>fareEstimator</code> is camel case.</p>\n</li>\n<li><p>Pass vectors by const reference:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>vector<double> fareEstimator(int ride_time, int ride_distance, const vector<double>& cost_per_minute, const vector<double>& cost_per_mile)\n</code></pre>\n<p>This avoids an unnecessary copy.</p>\n</li>\n<li><p>Instead of using <code>insert</code> with the <code>end</code> iterator, just use <code>push_back</code> to insert elements into the vector.</p>\n</li>\n<li><p>Since you know what the size of the resulting vector will be, you can reserve that memory in advance by calling <code>estimates.reserve(cost_per_minute.size())</code>. This will avoid any unnecessary resizing of the vector.</p>\n</li>\n<li><p>Use <code>std::size_t</code> instead of <code>int</code> for indexes.</p>\n</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T14:25:14.310",
"Id": "265829",
"ParentId": "265810",
"Score": "4"
}
},
{
"body": "<p>It appears that there's a hidden <code>using std::vector</code>. In most cases, I think it's better to write the type name in full and omit the <code>using</code>. The namespace name <code>std</code> is very short! Definitely don't <code>using namespace std</code> - that's quite harmful.</p>\n<p>Regardless, we need <code>#include <vector></code> for this to compile on most systems - if it compiles for you without, then that may mislead you - the include is not optional!</p>\n<p>This kind of code is very easy to unit test. You should include the tests with the code.</p>\n<p>It's not clear from the description whether the interface is forced upon you. Two parallel vectors is a very poor choice - a vector of <code>std::pair</code> would be significantly better, though the ideal would be a vector of a struct that gives meaningful names to the two rates. If you're really stuck with the parallel vectors, it may be wise to anticipate being passed vectors of different lengths - either throw an exception in that case, or use the <code>std::min()</code> of the two lengths.</p>\n<p>And all the things in <a href=\"/a/265829/75307\">Rish's answer</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T19:39:20.690",
"Id": "265834",
"ParentId": "265810",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "265829",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T03:10:48.677",
"Id": "265810",
"Score": "2",
"Tags": [
"c++",
"algorithm",
"programming-challenge",
"reinventing-the-wheel",
"vectors"
],
"Title": "An implementation of Uber's “Fare Estimator”"
}
|
265810
|
<p>This is a mythical beast we discussed in <a href="/q/265724/75307">a previous question</a>:</p>
<pre><code>template <typename F, class Tuple>
constexpr void operator|(Tuple&& t, F f) noexcept(noexcept(f(std::get<0>(t))))
{
[&]<auto ...I>(std::index_sequence<I...>) noexcept(noexcept(f(std::get<0>(t))))
{
(f(std::get<I>(t)), ...);
}
(std::make_index_sequence<std::tuple_size_v<std::remove_reference_t<Tuple>>>());
}
</code></pre>
<p>Usage:</p>
<pre><code>std::forward_as_tuple(1, 2, 3) | [](auto&& v) { std::cout << v << std::endl; };
</code></pre>
<p><a href="https://wandbox.org/permlink/WMd80R2njgpubRvi" rel="nofollow noreferrer">https://wandbox.org/permlink/WMd80R2njgpubRvi</a></p>
<p>You could pipe all sorts of things into a function, not just a tuple. Arrays, containers, variants, ..., even structs.</p>
|
[] |
[
{
"body": "<p>I don't see a great need for this in normal (clear, obvious) code;\nI believe that most C++ users would expect an ordinary function (in the pattern of <code>std::for_each()</code>, perhaps), rather than overloading the <code>|</code> operator. In the future, <code>|</code> become recognised as a composition operator, but that is not the case in 2021, and so it will be harder for readers to comprehend than the plain function. This is clearly a matter of opinion where reasonable folk may differ, of course, and will likely change as time passes.</p>\n<p>I suppose it's <em>arguably</em> similar to <code>| std::views::transform()</code> - except that it can only be a sink of values, because it returns <code>void</code> instead of a tuple of the results. If <code>f()</code> returns <code>void</code>, that may be appropriate, but when <code>f()</code> is a value-returning function, we'll want access to those results (perhaps to pipe into another transform).</p>\n<p>Why are we not perfect-forwarding the tuple elements? I'm not convinced that this will work with functions that accept (mutable) references and update the values.</p>\n<p>No unit tests are presented. I would expect quite a large suite of tests for a template function such as this, and they should have been in the review request. I certainly wouldn't accept this code into a project unless the tests were in the same submission.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T07:55:46.617",
"Id": "525024",
"Score": "0",
"body": "we could accommodate all of these concerns, I suppose, by optionally returning another tuple. But this is not a serious idea."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T08:02:28.213",
"Id": "525026",
"Score": "0",
"body": "Yes, that's what I would recommend - but only when `f()` applied to _all_ the input types is non-void (remember it can have many overloads). It's probably simpler to just convert the tuple to a `std::array<std::variant>` and then use a transform using `std::visit`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T08:27:15.233",
"Id": "525029",
"Score": "0",
"body": "a return value could also indicate, that a conditional pipe is desired, i.e. stop piping when the return value is `true` or `false`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T08:39:53.717",
"Id": "525030",
"Score": "0",
"body": "But when you say piping `std::tuple`s is unclear, I don't see any clear/standard ways of doing this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T09:44:43.863",
"Id": "525034",
"Score": "0",
"body": "I believe that most C++ users would expect an ordinary function (in the pattern of `std::for_each()`, perhaps), rather than overloading the `|` operator. As I said in the other question, `|` may _in future_ become recognised as a composition operator, but it is not so in 2021. That's clearly a matter of opinion where reasonable folk may differ, so I don't see any value in arguing the point!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T09:48:09.367",
"Id": "525035",
"Score": "0",
"body": "Someone needs to write a well thought-out library along the lines of `<ranges>`. Until then we are free to roll our own thing."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T07:40:59.520",
"Id": "265813",
"ParentId": "265811",
"Score": "5"
}
},
{
"body": "<h1>Incorrect <code>noexcept</code> clause</h1>\n<p>In the <code>noexcept</code> clause, you are only checking if the function applied to the first element of the tuple is <code>noexcept</code>. But overloads that handle the other elements might not be. So we need to check that they are <em>all</em> <code>noexcept</code>. The OP's code in the previous question handled this correctly.</p>\n<h1>Use concepts</h1>\n<p>The problem with your <code>operator|()</code> is that it matches a lot of things that it shouldn't. It would be better to make it match only <code>std::tuple</code>s and other things that you can use <code>std::get<>()</code> for the first argument, and function-like things that accept the types in the tuple as the second argument.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T15:02:01.580",
"Id": "265830",
"ParentId": "265811",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-07T07:22:00.917",
"Id": "265811",
"Score": "2",
"Tags": [
"c++",
"functional-programming",
"c++20"
],
"Title": "piping a std::tuple into a function"
}
|
265811
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.