body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>The code below creates an animated, four-cornered gradient with vertex and fragment shaders in WebGl. When I run it in the browser, the fans on my MacBookPro (2.2 GHz Quad-Core Intel Core i7 with Intel Iris Pro 1536 MB) sound like the laptop is preparing for takeoff. I've included screenshots from the Activity Monitor below. I am hesitant to put this code on the web for others. Is there something I could do to make it more efficient?</p>
<p>Here is the code:</p>
<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">
<title>webgl-test</title>
</head>
<body>
<canvas id="glCanvas" style="width: 100vw; height: 100vh;"></canvas>
</body>
<script>
var time0 = new Date().getTime();
var speed = 3; // lower is faster
const verts = [
-1, -1,
1, -1,
1, 1,
-1, 1
];
const corners = [
0, 1,
2, 0,
2, 3
];
// vertex shader to establish 2x2 texture so that each pixel is interpolated across four colors
// instead of over two triangles
const vs = `
attribute vec2 verts;
varying vec2 coord2D;
void main() {
coord2D = verts * 0.5 + 0.5; // convert to quad space 0,0 <=> 1, 1
gl_Position = vec4(verts, 1, 1);
}
`;
// hard coding the colors to be more efficient
const fs = `
precision mediump float;
varying vec2 coord2D;
uniform float uTime;
vec3 tl0 = vec3(0.93725,0.16471,0.75686); // rose
vec3 tl1 = vec3(1.0,0.611765,0.0); // saffron
vec3 tr0 = vec3(0.11765,0.69804,1.0); // ocean
vec3 tr1 = vec3(0.76471,0.90196,0.54510); // lime
vec3 bl0 = vec3(0.26275,0.33333,0.78431); // sapphire
vec3 bl1 = vec3(0.81176,0.60392,0.67843); // lavender
// vec3 br0 = vec3(1.0,0.78039,0.0); // sun
vec3 br0 = vec3(1.0,0.611765,0.0); // saffron
vec3 br1 = vec3(1.0,0.67451,0.43137); // turmeric
void main() {
float pct = abs(sin(uTime));
vec4 pixel = vec4(vec3(mix(
mix(mix(bl0, br0, coord2D.x), mix(bl1, br1, coord2D.x), pct),
mix(mix(tl0, tr0, coord2D.x), mix(tl1, tr1, coord2D.x), pct),
coord2D.y
)), 1);
gl_FragColor = pixel;
}
`;
// create and compile the shaders
function loadShader(gl, type, source) {
const shader = gl.createShader(type);
//send source to the shader object
gl.shaderSource(shader, source);
//compile the shader program
gl.compileShader(shader);
// check
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
console.log('An error occurred compiling the shaders: ' + gl.getShaderInfoLog(shader));
gl.deleteShader(shader);
return null;
}
return shader;
}
// initialize shader program and attach the shaders
function initShaderProgram(gl, vsSource, fsSource) {
const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);
const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);
const shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
// check
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
console.log('Unable to initialize the shader program: ' + gl.getProgramInfoLog(shaderProgram));
return null;
}
return shaderProgram;
}
function main() {
const canvas = document.querySelector("#glCanvas");
const gl = canvas.getContext("webgl");
var loc;
if (canvas.width !== innerWidth || canvas.height !== innerHeight) {
[canvas.width, canvas.height] = [innerWidth, innerHeight];
gl.viewport(0, 0, canvas.width, canvas.height);
}
const program = initShaderProgram(gl, vs, fs);
// create buffers
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gl.createBuffer());
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint8Array(corners), gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(verts), gl.STATIC_DRAW);
// setup attribute
gl.enableVertexAttribArray(loc = gl.getAttribLocation(program, "verts"));
gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0);
// setup uniform
const timeLoc = gl.getUniformLocation(program, 'uTime');
// draw loop
function draw() {
let newTime = new Date().getTime() / 1000 - time0 /1000;
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.useProgram(program);
gl.uniform1f(timeLoc, newTime/speed);
gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_BYTE, 0);
}
function render(now) {
draw();
requestAnimationFrame(render);
}
requestAnimationFrame(render);
}
main();
</script>
</html>
</code></pre>
<p><a href="https://i.stack.imgur.com/Fydew.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Fydew.png" alt="Activity Monitor when running in Firefox" /></a></p>
<p><a href="https://i.stack.imgur.com/ovM91.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ovM91.png" alt="Activity Monitor when running in Chrome" /></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-24T19:34:13.363",
"Id": "526199",
"Score": "1",
"body": "Your title, stating the concerns you have about your code, applies to tooany questions on this site. Please consider making it more specific, simply stating what your code does would suffice."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-24T18:37:28.730",
"Id": "266360",
"Score": "0",
"Tags": [
"javascript",
"webgl",
"shaders"
],
"Title": "More efficient webgl animated color interpolation?"
}
|
266360
|
<h4>The Problem</h4>
<p>I'm updating a system to use OOP where a <em>major</em> process of the system is to translate data between many providers. The translations happen in a many to many fashion. So provider A, B and C all have their own definitions of what a <code>Corgi</code> object is. For example;</p>
<pre><code>public struct CorgiA { public int FluffLevel { get; set; } }
public struct CorgiB { public short MuchFluff { get; set; } }
public struct CorgiC { public int Fluff { get; set; } }
</code></pre>
<p>The business requirement are:</p>
<ul>
<li>Use concrete types.</li>
<li>Ensure data models for a given provider, <em>match</em> their respective documentation.
<ul>
<li>This includes naming and type specification.</li>
</ul>
</li>
</ul>
<p>As a result, typical interfaces won't work due to naming and type mismatch possibilities. I recently asked this question on Software Engineering to get some alternatives and the answer I accepted is what I've decided to proceed with, at least for now, as a solution.</p>
<h4>The Current Solution</h4>
<p>I have a simple translation setup that involves an interface that takes two type arguments:</p>
<pre><code>public interface ITranslatable<T1, T2> {
T2 Translate();
T1 Translate(T2 input);
}
</code></pre>
<p>This is implemented on models that I want to translate, for example:</p>
<pre><code>public struct Corgi {
public int FluffLevel { get; set; }
public Corgi(int fluffLevel) => FluffLevel = fluffLevel;
}
public sealed class MyCorgi : ITranslatable<MyCorgi, Corgi> {
public int FluffLevel { get; set; }
public MyCorgi(int fluffLevel) => FluffLevel = fluffLevel;
public Corgi Translate() => new(FluffLevel);
public MyCorgi Translate(Corgi input) => new(input.FluffLevel);
}
public sealed class YourCorgi : ITranslatable<YourCorgi, Corgi> {
public int MuchFluff { get; set; }
public YourCorgi(int muchFluff) => MuchFluff = muchFluff;
public Corgi Translate() => new(MuchFluff);
public YourCorgi Translate(Corgi input) => new(input.FluffLevel);
}
</code></pre>
<p>The usage is rather straightforward (executed in the main of a console application):</p>
<pre><code>var myCorgi = new MyCorgi(100);
var yourCorgi = new YourCorgi(-1);
yourCorgi = yourCorgi.Translate(myCorgi.Translate());
Console.WriteLine(JsonConvert.SerializeObject(yourCorgi));
</code></pre>
<h4>An Example Implementation</h4>
<p>I've created the following example implementation to demonstrate a use case. Keep in mind however, since this has no implementation currently, I've used the corgi models from above. This example has a "registration service" that fetches corgi data from one provider, and registers it with another.</p>
<pre><code>using System;
using System.Collections.Generic;
#region Framework Assembly
public interface ITranslatable<T1, T2> {
T2 Translate();
T1 Translate(T2 input);
}
public struct Corgi {
public int FluffLevel { get; set; }
public Corgi(int fluffLevel) => FluffLevel = fluffLevel;
}
public interface ICorgiRegistrationServiceHandler {
bool TryFetchCorgis(out IEnumerable<Corgi> corgis);
void ProcessCorgi(Corgi corgi);
}
#endregion
#region My Corgi Provider Assembly
public sealed class MyCorgi : ITranslatable<MyCorgi, Corgi> {
public int FluffLevel { get; set; }
public MyCorgi(int fluffLevel) => FluffLevel = fluffLevel;
public Corgi Translate() => new(FluffLevel);
public MyCorgi Translate(Corgi input) => new(input.FluffLevel);
}
// The fact that this is static is part of another task. Ignore that fact for the purposes of this review.
public static class MyCorgiService {
private static Random _random = new Random();
public static IEnumerable<MyCorgi> FetchCorgis(int numberOfCorgis) {
var result = new List<MyCorgi>();
for (int i = 0; i < numberOfCorgis; i++)
result.Add(new MyCorgi(_random.Next(30, 100)));
return result;
}
}
#endregion
#region Your Corgi Provider Assembly
public sealed class YourCorgi : ITranslatable<YourCorgi, Corgi> {
public int MuchFluff { get; set; }
public YourCorgi(int muchFluff) => MuchFluff = muchFluff;
public Corgi Translate() => new(MuchFluff);
public YourCorgi Translate(Corgi input) => new(input.FluffLevel);
}
// The fact that this is static is part of another task. Ignore that fact for the purposes of this review.
public static class YourCorgiService {
public static bool RegisterCorgi(YourCorgi corgi, out string result) {
result = $"Successfully registered corgi `{Guid.NewGuid()}` with a much fluff of `{corgi.MuchFluff}`.";
return true;
}
}
#endregion
#region My to Your Corgi Service Assembly
public class MyToYourCorgiRegistrationServiceHandler : ICorgiRegistrationServiceHandler {
public bool TryFetchCorgis(out IEnumerable<Corgi> corgis) {
var myCorgis = MyCorgiService.FetchCorgis(5);
var translatedCorgis = new List<Corgi>();
foreach (var corgi in myCorgis)
translatedCorgis.Add(corgi.Translate());
corgis = translatedCorgis;
return true;
}
public void ProcessCorgi(Corgi corgi) {
var yourCorgi = new YourCorgi(-1);
yourCorgi = yourCorgi.Translate(corgi);
if (YourCorgiService.RegisterCorgi(yourCorgi, out string registrationResult))
Console.WriteLine(registrationResult);
}
}
#endregion
#region Primary Service Assembly
public class CorgiRegistrationService {
private ICorgiRegistrationServiceHandler _corgiServiceHandler;
public CorgiRegistrationService(ICorgiRegistrationServiceHandler corgiServiceHandler) => _corgiServiceHandler = corgiServiceHandler;
public void RegisterCorgis() {
if (_corgiServiceHandler.TryFetchCorgis(out IEnumerable<Corgi> corgis))
foreach (var corgi in corgis)
_corgiServiceHandler.ProcessCorgi(corgi);
}
}
public class Program {
public static void Main() {
var _registrationService = new CorgiRegistrationService(new MyToYourCorgiRegistrationServiceHandler());
_registrationService.RegisterCorgis();
}
}
#endregion
</code></pre>
<p>The expected output of this example is five lines of text with different GUIDs and "fluff levels":</p>
<pre><code>Successfully registered corgi `6d7afc29-4602-4815-95cb-1b36ab2c7359` with a much fluff of `69`.
Successfully registered corgi `13b9c564-a15f-4669-aaae-7908b5b7bd6e` with a much fluff of `80`.
Successfully registered corgi `4e8a8236-5251-48c1-af3c-32bb651841d3` with a much fluff of `82`.
Successfully registered corgi `78f5dcad-96cb-4764-be1d-adc2e1cf45cd` with a much fluff of `94`.
Successfully registered corgi `721d21fd-87c4-4530-9e24-b068a236ab53` with a much fluff of `79`.
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-24T20:38:56.280",
"Id": "526203",
"Score": "3",
"body": "What you're looking for seems to be extension methods. Unfortunately those are ... somewhat annoying with regards to polymorphism. Overall it seems like the underlying issue is the fact that you need to translate between multiple disjoint interfaces. That makes for a bad review on the code you presented, though, because it's obvious that your actual code looks completely different... Please reread [Why pseudocode is off-topic](https://codereview.meta.stackexchange.com/q/6080/)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T14:13:50.920",
"Id": "526254",
"Score": "1",
"body": "@Vogel612 I've updated the post to clarify the issue and my solution to that issue. Additionally, the code has no *true* implementation yet, and this is a proof of concept so I've created data models and processes to support the proof of concept. The goal isn't to create extension methods but rather simplify how the translation happens on demand."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-24T19:49:50.903",
"Id": "266363",
"Score": "1",
"Tags": [
"c#"
],
"Title": "How can I make my model translator usage more concise?"
}
|
266363
|
<p>I am attempting to create a table for placing images in LaTeX. The first column is the (image) index, the second and third columns are images from different folder. For example, in the row with index = 1, the two images from the path <code>Images/1/1.png</code> and <code>Images/2/1.png</code> are placed in the second and third column locations. In the row with index = 2, the two images from the path <code>Images/1/2.png</code> and <code>Images/2/2.png</code> are placed in the second and third column locations. Just like this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th style="text-align: center;">Index</th>
<th style="text-align: center;">Image Frames Input</th>
<th style="text-align: center;">Image Frames Output</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align: center;">1</td>
<td style="text-align: center;"><code>Images/1/1.png</code></td>
<td style="text-align: center;"><code>Images/2/1.png</code></td>
</tr>
<tr>
<td style="text-align: center;">2</td>
<td style="text-align: center;"><code>Images/1/2.png</code></td>
<td style="text-align: center;"><code>Images/2/2.png</code></td>
</tr>
</tbody>
</table>
</div>
<pre><code>\newcounter{it} \setcounter{it}{0}
\newtoks\tabtoks
\newcommand\addtabtoks[1]{\tabtoks\expandafter{\the\tabtoks#1}}
\newcommand*\resettabtoks{\tabtoks{}}
\newcommand*\printtabtoks{\the\tabtoks}
\resettabtoks
\newcounter{counterB} \setcounter{counterB}{0}
\loop\ifnum\theit<6
\addtabtoks{
\addtocounter{counterB}{1} % increment
\thecounterB
&
<span class="math-container">\begin{minipage}{.45\textwidth}
\includegraphics[width=\linewidth]{Images/1/\thecounterB.png}
\end{minipage}</span>
&
<span class="math-container">\begin{minipage}{.45\textwidth}
\includegraphics[width=\linewidth]{Images/2/\thecounterB.png}
\end{minipage}</span> \\ \hline
}
\stepcounter{it}
\repeat
<span class="math-container">\begin{table}[ht!]
\centering
\begin{tabular}{ | c | c | c | }
\hline
Index & Image Frames Input & Image Frames Output \\ \hline
\printtabtoks
\end{tabular}
\caption{The experimental results}\label{tbl:TheExperimentalResults}
\end{table}</span>
</code></pre>
<h1></h1>
<p><strong>The output looks like this:</strong></p>
<p><a href="https://i.stack.imgur.com/fhXAa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fhXAa.png" alt="Output" /></a></p>
<p>All suggestions are welcome.</p>
<h2>Reference:</h2>
<ul>
<li><p>Big Buck Bunny</p>
<p><a href="https://peach.blender.org/" rel="nofollow noreferrer">https://peach.blender.org/</a></p>
</li>
</ul>
|
[] |
[
{
"body": "<p>Instead of keeping track of row numbers manually, you could use the <code>nicematrix</code> package which keeps track of these numbers for you:</p>\n<pre><code>\\documentclass{article}\n\\usepackage{nicematrix}\n\\usepackage{graphicx}\n\n\\begin{document}\n\n\\noindent%\n<span class=\"math-container\">\\begin{NiceTabular}[width=\\textwidth,first-row,hvlines]{\n >{\\arabic{iRow}}c\n >{\\includegraphics[width=\\linewidth]{Images/1/\\arabic{iRow}.png}}X\n >{\\includegraphics[width=\\linewidth]{Images/2/\\arabic{iRow}.png}}X\n }\n\\hline\n\\multicolumn{1}{|c}{Index} & \n\\multicolumn{1}{|c}{Input} & \\multicolumn{1}{|c|}{Output}\\\\\n& & \\\\\n& & \\\\\n\\end{NiceTabular}</span>\n\n\\end{document}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T10:28:35.503",
"Id": "266377",
"ParentId": "266369",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "266377",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-24T23:57:37.713",
"Id": "266369",
"Score": "2",
"Tags": [
"image",
"data-visualization",
"tex"
],
"Title": "Creating table for placing images in LaTeX"
}
|
266369
|
<p>I found abandoned <a href="https://github.com/jruizgit/rules" rel="nofollow noreferrer">project</a> on GitHub and curious is it possible to implement part of it on just Python?</p>
<p>Here is most close <a href="https://github.com/jruizgit/rules/blob/master/README.md#python-2" rel="nofollow noreferrer">example of processing</a> I would like to implement:</p>
<pre class="lang-py prettyprint-override"><code>from durable.lang import *
with ruleset('test'):
@when_all(m.subject.matches('3[47][0-9]{13}'))
def amex(c):
print ('Amex detected {0}'.format(c.m.subject))
@when_all(m.subject.matches('4[0-9]{12}([0-9]{3})?'))
def visa(c):
print ('Visa detected {0}'.format(c.m.subject))
@when_all(m.subject.matches('(5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|2720)[0-9]{12}'))
def mastercard(c):
print ('Mastercard detected {0}'.format(c.m.subject))
assert_fact('test', { 'subject': '375678956789765' })
assert_fact('test', { 'subject': '4345634566789888' })
assert_fact('test', { 'subject': '2228345634567898' })
</code></pre>
<p><strong>Goal</strong>:</p>
<ul>
<li>Call functions only under some condition.</li>
<li>Track matches and inner function execution in uniformed way.</li>
<li>Reuse variables from the same scope to be more flexible with inner functions calls.</li>
</ul>
<p>I have <a href="https://stackoverflow.com/questions/68912078/is-there-a-better-way-of-conditional-execution-in-python">PoC</a> working, but I wonder is any better <strong>algorithmic</strong> approach to do the same in Python? Most obvious way to do something similar to bellow code. But is there more elegant way to get rid of repeating <code>if ...: processed = True</code> pattern and have this code more <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself" rel="nofollow noreferrer">DRY</a>?</p>
<pre class="lang-py prettyprint-override"><code>def boo(a, c):
# do something
return True
def foo(a, b, c):
# do something more
return True
def setup(a, b, c):
processed = False
matched = False
if a == "boo" and c == 1:
matched = True
processed = bool(boo(a, c))
if a == "boo" and (c == 2 or b == 3):
matched = True
processed = bool(foo(a, b, c))
...
if not matched:
logger.warning("Couldn't match any rule")
return processed
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T07:24:09.687",
"Id": "526216",
"Score": "1",
"body": "Hey welcome to Code Review! It looks like your linked Stack Overflow post contains the actual code you want reviewed and what you've posted here is just the alternative code if you were doing it by hand is that right? In that case you actually need to post the code you want reviewed here rather than linking to it. Also edit your post to say _why_ you want this at all, what problem does it solve? That will provide the necessary context to say whether your solution is suitable and how it might be improved."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T07:41:24.270",
"Id": "526220",
"Score": "0",
"body": "(The *something* most *similar* to *bellow* should be to *bark*…?!;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T08:47:21.653",
"Id": "526226",
"Score": "0",
"body": "@Greedo I'm not sure which one is better approach. I added an example to clarify idea."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T08:49:59.677",
"Id": "526227",
"Score": "0",
"body": "@greybeard oh, well. Thanks for catching this. I added missing noun."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T12:01:54.750",
"Id": "526241",
"Score": "1",
"body": "Code review is for code that you wrote and that you know is working. This question seems to indicate that someone else wrote the code and that you don't have it working the way you want to yet."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T14:59:01.423",
"Id": "526259",
"Score": "0",
"body": "@pacmaninbw that's wrong assumption."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T15:04:24.250",
"Id": "526260",
"Score": "0",
"body": "Also, why it was marked as off-topic. Could someone explain please?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T15:09:13.160",
"Id": "526261",
"Score": "0",
"body": "Here is the [help page for on-topic questions](https://codereview.stackexchange.com/help/on-topic)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T15:11:14.820",
"Id": "526262",
"Score": "0",
"body": "5 people closed the question, however, the moderator changed the reason for closure and became the only person to close the question (makes 6 people that closed the question)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T15:11:39.923",
"Id": "526263",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/128933/discussion-between-su1tan-and-pacmaninbw)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T20:45:19.180",
"Id": "526283",
"Score": "0",
"body": "(It's rather that `bellow` isn't anything like the opposite of *above* - *below* is.)"
}
] |
[
{
"body": "<p><strong>Bitwise Operators</strong></p>\n<p>While your use of bitwise operators works fine as far as I can tell, I wouldn't expect them to be used like this in Python. So instead of</p>\n<pre><code>if ((a == "boo") & ((c == 2) | (b == 3))):\n</code></pre>\n<p>I'd prefer</p>\n<pre><code>if a == "boo" and (c == 2 or b == 3):\n</code></pre>\n<p>Also note that you don't need as many parantheses.</p>\n<hr />\n<p><strong><code>processed = True</code></strong></p>\n<pre><code>if boo(a, c):\n processed = True\n</code></pre>\n<p>can be replaced by</p>\n<pre><code>processed = boo(a, c)\n</code></pre>\n<p>as long as <code>boo</code> (or any other relevant function) returns a <code>bool</code>. If it returns something else you can convert it to a <code>bool</code> explicitly:</p>\n<pre><code>processed = bool(boo(a, c))\n</code></pre>\n<hr />\n<p><strong>EDIT:</strong></p>\n<ul>\n<li>You do not need <code>matched</code>, simply use an <code>if - elif - else</code>-construct</li>\n<li>You <em>can</em> replace <code>processed</code> by storing the matching function call in a variable. I'm not sure if you should though.</li>\n</ul>\n<pre><code>from functools import partial\n\n\ndef setup(a, b, c):\n function_call = lambda: False\n\n if a == "boo" and c == 1:\n function_call = partial(boo, a, c) # alt: lambda: boo(a, c)\n elif a == "boo" and (c == 2 or b == 3):\n function_call = partial(foo, a, b, c) # alt: lambda: foo(a, b, c)\n else:\n logger.warning("Couldn't match any rule")\n\n return bool(function_call())\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T09:57:57.500",
"Id": "526233",
"Score": "0",
"body": "thanks! But there is a problem: I don't want to be dependent on inner function implementation. Also, if I want to track matches together with function return? Adding more `matched = True` in each step? (sorry, for not being more specific at the beginning)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T11:32:06.593",
"Id": "526239",
"Score": "0",
"body": "I updated my original question with your proposal. But the code is not as DRY as it could be..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T11:46:04.233",
"Id": "526240",
"Score": "1",
"body": "In general, please refrain from editing suggestions from answers into your existing question. Prefer posting a new question with the updated code. I've included some pointers for decreasing repetition in your edited code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T12:06:42.327",
"Id": "526242",
"Score": "0",
"body": "Thanks for `partial` hint!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T09:25:32.370",
"Id": "266375",
"ParentId": "266370",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "266375",
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T06:35:50.140",
"Id": "266370",
"Score": "1",
"Tags": [
"python",
"reinventing-the-wheel"
],
"Title": "Implementing conditional execution in Python"
}
|
266370
|
<p>(See <a href="https://codereview.stackexchange.com/questions/266344/a-java-ee7-web-application-for-counting-views-in-a-static-html-page">the initial and previous version</a>.)</p>
<p>This time, I have incorporated all the good points made by <a href="https://codereview.stackexchange.com/users/125850/mtj">mtj</a>. See what I have:</p>
<p><strong><code>com.github.coderodde.weblog.viewcounter.CountViewServlet.java:</code></strong></p>
<pre><code>package com.github.coderodde.weblog.viewcounter;
import static com.github.coderodde.weblog.viewcounter.Util.objects;
import com.google.gson.Gson;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URISyntaxException;
import java.sql.SQLException;
import java.time.ZonedDateTime;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* This servlet is responsible for storing the IP-address and the timestamp of
* a view in at <a href="http://coderodde.github.io/weblog/">coderodde's weblog</a>.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Aug 21, 2021)
* @since 1.6 (Aug 21, 2021)
*/
@WebServlet(name="CountViewServlet", urlPatterns={"/countView"})
public class CountViewServlet extends HttpServlet {
private static final Gson GSON = new Gson();
private static final Logger LOGGER =
Logger.getLogger(CountViewServlet.class.getName());
@Inject private DataAccessObject dataAccessObject;
@Override
protected void doPost(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse)
throws ServletException, IOException {
// Allow the weblog page to get the response from this servlet:
httpServletResponse.setHeader("Access-Control-Allow-Origin",
"coderodde.github.io");
JSONResponseObject jsonResponseObject = new JSONResponseObject();
jsonResponseObject.succeeded = false;
try {
dataAccessObject.createTablesIfNeeded();
ZonedDateTime mostRecentViewTime =
dataAccessObject.getMostRecentViewTime();
if (mostRecentViewTime != null) {
jsonResponseObject.mostRecentViewTime =
mostRecentViewTime.toString();
}
dataAccessObject.addView(httpServletRequest);
jsonResponseObject.numberOfViews = dataAccessObject.getViewCount();
// Mark as successful:
jsonResponseObject.succeeded = true;
} catch (SQLException ex) {
LOGGER.log(
Level.SEVERE,
"SQL failed: {0}, caused by: {1}",
objects(ex.getMessage(), ex.getCause()));
} catch (URISyntaxException ex) {
LOGGER.log(
Level.SEVERE,
"Bad DB URI: {0}, caused by: {1}",
objects(ex.getMessage(), ex.getCause()));
}
try (PrintWriter printWriter = httpServletResponse.getWriter()) {
printWriter.print(GSON.toJson(jsonResponseObject));
}
}
}
</code></pre>
<p><strong><code>com.github.coderodde.weblog.viewcounter.DataAccessObject.java:</code></strong></p>
<pre><code>package com.github.coderodde.weblog.viewcounter;
import static com.github.coderodde.weblog.viewcounter.Util.objects;
import com.github.coderodde.weblog.viewcounter.sql.SQLStatements;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.enterprise.context.RequestScoped;
import javax.servlet.http.HttpServletRequest;
import org.apache.tomcat.jdbc.pool.DataSource;
/**
* This class implements the data access object for the view counter.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Aug 22, 2021)
*/
@RequestScoped
public class DataAccessObject {
private static final Logger LOGGER =
Logger.getLogger(DataAccessObject.class.getName());
private static final String EUROPE_HELSINKI_ZONE_ID = "Europe/Helsinki";
private static final ZoneId ZONE_ID = ZoneId.of(EUROPE_HELSINKI_ZONE_ID);
private static final String DB_URL_ENVIRONMENT_VARIABLE_NAME =
"CLEARDB_DATABASE_URL";
private static final DataSource dataSource = new DataSource();
private static final DataAccessObject INSTANCE = new DataAccessObject();
public static DataAccessObject getInstance() {
return INSTANCE;
}
/**
* Makes sure that the main table is created.
*
* @throws java.sql.SQLException if the SQL layer fails.
* @throws java.net.URISyntaxException if the DB URI is invalid.
*/
public void createTablesIfNeeded() throws SQLException, URISyntaxException {
try (Connection connection = getConnection()) {
connection.createStatement()
.executeUpdate(SQLStatements
.ViewTable
.Create
.CREATE_MAIN_TABLE);
}
}
/**
* Adds a new view data to the database.
*
* @param httpServletRequest the request object.
*
* @throws java.sql.SQLException if the SQL layer fails.
* @throws java.net.URISyntaxException if the DB URI is invalid.
*/
public void addView(HttpServletRequest httpServletRequest)
throws SQLException, URISyntaxException {
String host = httpServletRequest.getRemoteHost();
int port = httpServletRequest.getRemotePort();
String remoteAddress = httpServletRequest.getHeader("X-FORWARDED-FOR");
if (remoteAddress == null) {
remoteAddress = httpServletRequest.getRemoteAddr();
}
try (Connection connection = getConnection();
PreparedStatement statement =
connection.prepareStatement(
SQLStatements.ViewTable.Insert.INSERT_VIEW)) {
statement.setString(1, remoteAddress);
statement.setString(2, host);
statement.setInt(3, port);
ZonedDateTime nowZonedDateTime = ZonedDateTime.now(ZONE_ID);
Timestamp nowTimestamp =
Timestamp.from(nowZonedDateTime.toInstant());
statement.setTimestamp(4, nowTimestamp);
statement.executeUpdate();
}
}
/**
* Returns the total number of views.
*
* @return the total number of views so far.
*
* @throws java.sql.SQLException if the SQL layer fails.
* @throws java.net.URISyntaxException if the DB URI is invalid.
*/
public int getViewCount() throws SQLException, URISyntaxException {
try (Connection connection = getConnection();
Statement statement = connection.createStatement()) {
try (ResultSet resultSet =
statement.executeQuery(
SQLStatements
.ViewTable
.Select
.GET_NUMBER_OF_VIEWS)) {
if (!resultSet.next()) {
throw new IllegalStateException(
"Could not read the number of views.");
}
return resultSet.getInt(1);
}
}
}
/**
* Returns the most recent view time stamp.
* @return the most recent view time.
*
* @throws java.sql.SQLException if the SQL layer fails.
* @throws java.net.URISyntaxException if the DB URI is invalid.
*/
public ZonedDateTime getMostRecentViewTime()
throws SQLException, URISyntaxException {
try (Connection connection = getConnection();
Statement statement = connection.createStatement()) {
try (ResultSet resultSet =
statement.executeQuery(
SQLStatements
.ViewTable
.Select
.GET_MOST_RECENT_VIEW_TIME)) {
if (!resultSet.next()) {
return null;
}
Timestamp mostRecentViewTimestamp = resultSet.getTimestamp(1);
if (mostRecentViewTimestamp == null) {
return null;
}
ZonedDateTime mostRecentViewZonedDateTime =
ZonedDateTime.ofInstant(
mostRecentViewTimestamp.toInstant(),
ZONE_ID);
return mostRecentViewZonedDateTime;
}
}
}
private static void loadJDBCDriverClass() {
try {
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
} catch (ClassNotFoundException ex) {
LOGGER.log(
Level.SEVERE,
"com.mysql.cj.jdbc.Driver class not found: {0}, " +
"caused by: {1}",
objects(ex, ex.getCause()));
throw new RuntimeException(
"com.mysql.cj.jdbc.Driver not found.",
ex);
} catch (InstantiationException ex) {
LOGGER.log(
Level.SEVERE,
"com.mysql.cj.jdbc.Driver could not be instantiated: {0}," +
" caused by: {1}",
objects(ex, ex.getCause()));
throw new RuntimeException(
"com.mysql.cj.jdbc.Driver could not be instantiated.",
ex);
} catch (IllegalAccessException ex) {
LOGGER.log(
Level.SEVERE,
"com.mysql.cj.jdbc.Driver could not be accessed: {0}, " +
"caused by: {1}",
objects(ex, ex.getCause()));
throw new RuntimeException(
"com.mysql.cj.jdbc.Driver could not be accessed.",
ex);
}
}
static {
loadJDBCDriverClass();
}
private Connection getConnection() throws SQLException, URISyntaxException {
URI databaseURI =
new URI(System.getenv(DB_URL_ENVIRONMENT_VARIABLE_NAME));
String username = databaseURI.getUserInfo().split(":")[0];
String password = databaseURI.getUserInfo().split(":")[1];
String databaseURL =
"jdbc:mysql://" + databaseURI.getHost() + databaseURI.getPath();
return DriverManager.getConnection(databaseURL, username, password);
}
}
</code></pre>
<p><strong><code>com.github.coderodde.weblog.viewcounter.JSONResponseObject.java:</code></strong></p>
<pre><code>package com.github.coderodde.weblog.viewcounter;
/**
* This POJO class type defines a simple object for reporting to the front-end.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Aug 22, 2021)
* @since 1.6 (Aug 22, 2021)
*/
public class JSONResponseObject {
public boolean succeeded;
public int numberOfViews;
public String mostRecentViewTime;
}
</code></pre>
<p><strong><code>com.github.coderodde.weblog.viewcounter.Util.java:</code></strong></p>
<pre><code>package com.github.coderodde.weblog.viewcounter;
/**
* This class contains common utility methods.
*
* @author Rodion "rodde" Efremov
* @version 1.61 (Aug 25, 2021)
* @since 1.61 (Aug 25, 2021)
*/
public class Util {
/**
* Allows writing {@code method(arg1, ..., argn)}.
*
* @param objects the objects.
* @return same array.
*/
public static Object[] objects(Object... objects) {
return objects;
}
}
</code></pre>
<p>The entire repository is <a href="https://github.com/coderodde/WeblogViewCounter" rel="nofollow noreferrer">here</a>. You can see the servlet in action <a href="http://coderodde.github.io/weblog" rel="nofollow noreferrer">here</a> (scroll down to the very bottom in order to see the counter).</p>
<h2>Critique request</h2>
<p>Please, tell me how to further improve my work.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T09:48:16.100",
"Id": "526231",
"Score": "0",
"body": "Where can I put the \"ready to merge\" checkmark on this pull-request? ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T10:51:28.020",
"Id": "526236",
"Score": "0",
"body": "@mtj Haha, you are funny, Sir. :-D"
}
] |
[
{
"body": "<p>Couple of thing that I've noticed are:</p>\n<ol>\n<li><strong>Total views</strong> is getting updated every-time when the page is refreshed. So it does not shows number of unique visitors - suppose this is expected behaviour.</li>\n<li><strong>Last visit time</strong> is showing local time of the visitor. It could have been updated to use UTC format, or the timezone can be displayed.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T12:21:33.030",
"Id": "267624",
"ParentId": "266373",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T09:18:32.373",
"Id": "266373",
"Score": "0",
"Tags": [
"java",
"mysql",
"servlets"
],
"Title": "A Java EE7 web application for counting views in a static HTML page - follow-up"
}
|
266373
|
<p>is there a better way to optimize this piece of code?? I am checking if each item in the collection has property classID , then do my logic. Any better way where I do an enumerate only for documents having the property</p>
<pre><code>if( source != null && source.Count > 0 )
{
foreach( var item in source )
{
string customerName = string.Empty;
var jsonContent = (JObject)JsonConvert.DeserializeObject( item.ToString() );
if( !string.IsNullOrEmpty( (string)jsonContent["ClassId"] ) )
{....my logic....
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T13:02:30.690",
"Id": "526247",
"Score": "0",
"body": "Do you need other data than `ClassId` from each `item`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T13:04:55.170",
"Id": "526248",
"Score": "0",
"body": "yes i need a check on classID but later on i need 2 more item from the document. i am actually moving the document from one place to another and i need to move one with classId in it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T13:08:25.847",
"Id": "526249",
"Score": "0",
"body": "With [LINQ to JSON](https://www.newtonsoft.com/json/help/html/LINQtoJSON.htm) you define a query like this: `from data in source let item = JObject.Parse(data) where !string.IsNullOrEmpty((string)item[\"ClassId\"]) select data;`. Then you can call the `foreach` on this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T13:11:34.983",
"Id": "526250",
"Score": "0",
"body": "if you are sure , can you please frame it properly as an answer, i should do foreach for which collection here? data?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T22:17:56.677",
"Id": "526289",
"Score": "1",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
}
] |
[
{
"body": "<p>You can extract the filtering logic like this via <a href=\"https://www.newtonsoft.com/json/help/html/LINQtoJSON.htm\" rel=\"nofollow noreferrer\">LINQ to JSON</a>:</p>\n<pre><code>var filteredData = from data in source\n let item = JObject.Parse(data)\n where !string.IsNullOrEmpty((string)item["ClassId"])\n select data;\n</code></pre>\n<p>Then you can iterate through the filtered data with a simple <code>foreach</code> loop</p>\n<pre><code>foreach (var record in filteredData)\n{\n //your logic\n}\n</code></pre>\n<hr />\n<p>I've assumed that your <code>source</code> is a <code>IEnumerable<string></code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T13:23:43.463",
"Id": "526251",
"Score": "0",
"body": "also can you tell me if I do this way will it work (from data in source\n let trigger = data.GetPropertyValue<bool?>( \"ClassId\" )\n where !trigger.HasValue || trigger == true)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T13:24:03.103",
"Id": "526252",
"Score": "1",
"body": "source is IReadOnlyList<Document>"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T13:26:17.397",
"Id": "526253",
"Score": "0",
"body": "@ZZZSharePoint Yes it might work. You can simplify `|| trigger == true` to `|| trigger`"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T13:14:53.940",
"Id": "266381",
"ParentId": "266380",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "266381",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T12:56:49.737",
"Id": "266380",
"Score": "-2",
"Tags": [
"c#"
],
"Title": "how can i optimize this method"
}
|
266380
|
<p>I made a simple password-generating app with a GUI written in Python and the <code>tkinter</code> library.</p>
<p>Here's how the GUI looks like:</p>
<p><a href="https://i.stack.imgur.com/FR5CP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FR5CP.png" alt="GUI of the app" /></a></p>
<p>The passwords are strings composed of random characters. The user can choose the length of the password, and the characters that are allowed to be in it.</p>
<p>Here's the source code:</p>
<pre><code>import string
import tkinter as tk
from tkinter import ttk
import random
from tkinter.constants import DISABLED, E, END, NORMAL, NW, VERTICAL
class GUI(tk.Frame):
def __init__(self, master):
super().__init__(master)
self.pack()
self.widget_vars()
self.create_widgets()
self.style()
def generate_password(self):
passw = Password(self.length.get(), self.lower.get(), self.upper.get(),
self.digits.get(), self.punct.get())
# You can only insert to Text if the state is NORMAL
self.password_text.config(state=NORMAL)
self.password_text.delete("1.0", END) # Clears out password_text
self.password_text.insert(END, passw.password)
self.password_text.config(state=DISABLED)
def widget_vars(self):
self.length = tk.IntVar(self, value=16)
self.lower = tk.BooleanVar(self, value=True)
self.upper = tk.BooleanVar(self, value=True)
self.digits = tk.BooleanVar(self, value=True)
self.punct = tk.BooleanVar(self, value=True)
def create_widgets(self):
# Define widgets
self.lower_checkbtn = ttk.Checkbutton(self, variable=self.lower)
self.lower_label = ttk.Label(self, text="string.ascii_lower")
self.upper_checkbtn = ttk.Checkbutton(self, variable=self.upper)
self.upper_label = ttk.Label(self, text="string.ascii_upper")
self.digits_checkbtn = ttk.Checkbutton(self, variable=self.digits)
self.digits_label = ttk.Label(self, text="string.digits")
self.punct_checkbtn = ttk.Checkbutton(self, variable=self.punct)
self.punct_label = ttk.Label(self, text="string.punctuation")
self.length_spinbox = ttk.Spinbox(self, from_=1, to=128, width=3,
textvariable=self.length)
self.length_label = ttk.Label(self, text="Password length")
self.separator = ttk.Separator(self, orient=VERTICAL)
self.generate_btn = ttk.Button(self, text="Generate password",
command=self.generate_password)
self.password_text = tk.Text(self, height=4, width=32, state=DISABLED)
# Place widgets on the screen
self.length_label.grid(column=0, row=0, rowspan=4, sticky=E)
self.length_spinbox.grid(column=1, row=0, rowspan=4, padx=4, pady=2)
self.lower_label.grid(column=3, row=0, sticky=E, padx=4)
self.lower_checkbtn.grid(column=4, row=0, padx=4, pady=2)
self.upper_label.grid(column=3, row=1, sticky=E, padx=4)
self.upper_checkbtn.grid(column=4, row=1, padx=4, pady=2)
self.digits_label.grid(column=3, row=2, sticky=E, padx=4)
self.digits_checkbtn.grid(column=4, row=2, padx=4, pady=2)
self.punct_label.grid(column=3, row=3, sticky=E, padx=4)
self.punct_checkbtn.grid(column=4, row=3, padx=4, pady=2)
self.separator.grid(column=2, row=0, rowspan=4, ipady=45)
self.generate_btn.grid(columnspan=5, row=4, padx=4, pady=2)
self.password_text.grid(columnspan=5, row=6, padx=4, pady=2)
self.grid(padx=10, pady=10)
def style(self):
self.style = ttk.Style(self)
self.style.theme_use("clam")
class Password:
def __init__(self, length: int,
allow_lowercase: bool,
allow_uppercase: bool,
allow_digits: bool,
allow_punctuation: bool) -> None:
self.length = length
self.allow_lowercase = allow_lowercase
self.allow_uppercase = allow_uppercase
self.allow_digits = allow_digits
self.allow_punctuation = allow_punctuation
self.allowed_chars = self.gen_allowed_chars()
self.password = self.gen_password()
def gen_allowed_chars(self) -> str:
# I use a string, because random.choice doesn't work with sets:
chars = ''
if self.allow_lowercase:
chars += string.ascii_lowercase
if self.allow_uppercase:
chars += string.ascii_uppercase
if self.allow_digits:
chars += string.digits
if self.allow_punctuation:
chars += string.punctuation
return chars
def gen_password(self) -> str:
password = ''
for _ in range(self.length):
password += random.choice(self.allowed_chars)
return password
if __name__ == '__main__':
root = tk.Tk()
root.title("Password Generator")
app = GUI(root)
app.mainloop()
</code></pre>
<p>Can this code be improved in any way? Does this code follow common best practices? I'd appreciate some advice, especially on the <code>GUI</code> class (I'm new to <code>tkinter</code>).</p>
<p>Thank You in advance.</p>
|
[] |
[
{
"body": "<p>I don't think <code>Password</code> needs to be a class. <code>__init__</code> is calling <code>gen_password</code>, so this really could be boiled down to a single function call:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def gen_password(length: int, lowercase: bool, uppercase: bool, digits: bool, punctuation: bool) -> str:\n char_groups = {\n 'lowercase': string.ascii_lowercase,\n 'uppercase': string.ascii_uppercase,\n 'digits': string.digits,\n 'punctuation': string.punctuation\n }\n\n # gets the corresponding keys for any True arguments in the\n # function call\n groups = (grp for grp, arg in zip(\n ('lowercase', 'uppercase', 'digits', 'punctuation'), \n (lowercase, uppercase, digits, punctuation)\n ) if arg)\n\n # your set of allowed chars gets generated here\n allowed_chars = ''.join((char_groups[group] for group in groups))\n\n # instead of the for loop, just sample the chars\n return ''.join(random.sample(allowed_chars, k=length))\n</code></pre>\n<p>Which changes your <code>generate_password</code> function to look like:</p>\n<pre class=\"lang-py prettyprint-override\"><code> def generate_password(self):\n # I'd use keywords here for clarity\n passw = gen_password(\n length=self.length.get(), \n lowercase=self.lower.get(), \n uppercase=self.upper.get(),\n digits=self.digits.get(), \n punctuation=self.punct.get()\n )\n # You can only insert to Text if the state is NORMAL\n self.password_text.config(state=NORMAL)\n self.password_text.delete("1.0", END) # Clears out password_text\n self.password_text.insert(END, passw)\n self.password_text.config(state=DISABLED)\n \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T17:37:47.693",
"Id": "266429",
"ParentId": "266388",
"Score": "2"
}
},
{
"body": "<ul>\n<li>Don't use <code>random</code> for passwords, use <code>secrets</code></li>\n<li>"has-a-root" is a cleaner pattern here, I think, than "is-a-root"; in other words, don't inherit - instantiate</li>\n<li>Cut down the repetition in your options by generalizing to a collection of strings, each expected to be an attribute name on the <code>string</code> module. Represent this name consistently between the UI and the module lookup logic.</li>\n<li>Type-hint your method signatures.</li>\n<li>Prefer <code>''.join()</code> over successive concatenation</li>\n<li>Try to avoid assigning new class members outside of <code>__init__</code>.</li>\n<li>Where possible, reduce the number of references you keep on your GUI class. Almost none of your controls actually need to have references kept.</li>\n<li>Do not call <code>mainloop</code> on your frame; call it on your root</li>\n<li>Name your variables</li>\n<li>Sort your grid declarations according to column and row</li>\n<li>Your <code>Password</code> is not a very useful representation of a class. Whether or not it is kept as-is, it should be made immutable. Also, distinguish between a password and a password <em>generator</em>. A password generator knowing all of its generator parameters but having no actual password state would be more useful. After such a representation is implemented, you could change your TK logic to trace on all of your options variables, and only upon such a change trace, re-initialize your generator. Repeat clicks on 'Generate' will reuse the same generator instance.</li>\n<li><a href=\"https://www.theserverside.com/feature/Why-GitHub-renamed-its-master-branch-to-main\" rel=\"nofollow noreferrer\">Don't call things master</a>. In this case "parent" is more appropriate.</li>\n</ul>\n<h2>Suggested</h2>\n<pre class=\"lang-py prettyprint-override\"><code>import secrets\nimport string\nimport tkinter as tk\nfrom dataclasses import dataclass, field\nfrom tkinter import ttk\nfrom tkinter.constants import DISABLED, E, END, NORMAL, VERTICAL\nfrom typing import Iterable, Collection, Protocol, Literal\n\n\nTraceMode = Literal[\n 'r', # read\n 'w', # write\n 'u', # undefine\n 'a', # array\n]\n\n\nclass TkTrace(Protocol):\n def __call__(self, name: str, index: str, mode: TraceMode): ...\n\n\nclass OptControl:\n NAMES = ('ascii_lowercase', 'ascii_uppercase', 'digits', 'punctuation')\n\n def __init__(self, parent: tk.Widget, name: str, trace: TkTrace) -> None:\n self.name = name\n self.var = tk.BooleanVar(parent, name=name, value=True)\n self.var.trace(mode='w', callback=trace)\n self.label = ttk.Label(parent, text=name)\n self.check = ttk.Checkbutton(parent, variable=self.var)\n\n @classmethod\n def make_all(cls, parent: tk.Widget, trace: TkTrace) -> Iterable['OptControl']:\n for name in cls.NAMES:\n yield cls(parent, name, trace)\n\n\nclass GUI:\n def __init__(self, parent: tk.Tk):\n self.root = tk.Frame(parent)\n self.root.pack()\n self.length = tk.IntVar(self.root, value=16)\n self.length.trace('w', self.opt_changed)\n self.opts = tuple(OptControl.make_all(self.root, self.opt_changed))\n self.password_text = self.create_widgets()\n self.style()\n self.opt_changed()\n\n @property\n def selected_opts(self) -> Iterable[str]:\n for opt in self.opts:\n if opt.var.get():\n yield opt.name\n\n def generate_password(self) -> None:\n # You can only insert to Text if the state is NORMAL\n self.password_text.config(state=NORMAL)\n self.password_text.delete('1.0', END) # Clears out password_text\n self.password_text.insert(END, self.generator.gen_password())\n self.password_text.config(state=DISABLED)\n\n def opt_changed(self, *args) -> None:\n self.generator = PasswordGenerator(\n length=self.length.get(),\n opts=tuple(self.selected_opts),\n )\n\n def create_widgets(self) -> tk.Text:\n length_label = ttk.Label(self.root, text='Password length')\n length_label.grid(column=0, row=0, rowspan=4, sticky=E)\n\n generate_btn = ttk.Button(\n self.root, text='Generate password', command=self.generate_password)\n generate_btn.grid(column=0, row=4, columnspan=5, padx=4, pady=2)\n\n password_text = tk.Text(self.root, height=4, width=32, state=DISABLED)\n password_text.grid(column=0, row=6, columnspan=5, padx=4, pady=2)\n\n length_spinbox = ttk.Spinbox(\n self.root, from_=1, to=128, width=3, textvariable=self.length)\n length_spinbox.grid(column=1, row=0, rowspan=4, padx=4, pady=2)\n\n separator = ttk.Separator(self.root, orient=VERTICAL)\n separator.grid(column=2, row=0, rowspan=4, ipady=45)\n\n for row, opt in enumerate(self.opts):\n opt.label.grid(column=3, row=row, sticky=E, padx=4)\n opt.check.grid(column=4, row=row, padx=4, pady=2)\n\n self.root.grid(padx=10, pady=10)\n\n return password_text\n\n def style(self) -> None:\n style = ttk.Style(self.root)\n style.theme_use('clam')\n\n\n@dataclass(frozen=True)\nclass PasswordGenerator:\n length: int\n opts: Collection[str]\n allowed_chars: str = field(init=False)\n\n def __post_init__(self):\n super().__setattr__('allowed_chars', ''.join(self._gen_allowed_chars()))\n\n def gen_password(self) -> str:\n return ''.join(self._gen_password_chars())\n\n def _gen_allowed_chars(self) -> Iterable[str]:\n for opt in self.opts:\n yield getattr(string, opt)\n\n def _gen_password_chars(self) -> Iterable[str]:\n for _ in range(self.length):\n yield secrets.choice(self.allowed_chars)\n\n\nif __name__ == '__main__':\n root = tk.Tk()\n root.title('Password Generator')\n GUI(root)\n root.mainloop()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T22:16:29.433",
"Id": "266460",
"ParentId": "266388",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "266460",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T16:10:50.417",
"Id": "266388",
"Score": "4",
"Tags": [
"python",
"object-oriented",
"tkinter"
],
"Title": "Simple password generator with a GUI"
}
|
266388
|
<p><em>example:</em></p>
<pre><code>exports.products = (req, res) => {
// var1
const ITEM_LIMIT = 4;
// var2
const page = +req.query.p || 1;
// unimportant part
productModel.getProdCount().then(([count]) => {
const totalItems = count[0]['COUNT(id)'];
productModel.fetchAllProd((page - 1) * ITEM_LIMIT, ITEM_LIMIT).then(([rows]) => {
res.render('general/products', {
prods: rows,
title: 'Products Page',
path: '/products',
currPage: page,
hasNextPage: ITEM_LIMIT * page < totalItems,
havePrevPage: page > 1,
prevPage: page - 1,
nextPage: page + 1,
lastPage: Math.ceil(totalItems / ITEM_LIMIT),
});
});
});
};
</code></pre>
<p>As you see I have var1 and var2.</p>
<p>Is it ok to define them as sync like this?</p>
<p>Should I create an async structure for them? What is best practice.</p>
<p>If I use it heavily in this way, for example, if 10 million users run the same function, I think the event loop may get blocked.</p>
|
[] |
[
{
"body": "<p>Your code is a perfectly fine non-blocking async code, now lets talk about your questions one by one.</p>\n<blockquote>\n<p>Is it ok to define them as sync like this?</p>\n</blockquote>\n<p>Yes its perfectly fine to have variables declared in a non async function as you have it above.</p>\n<blockquote>\n<p>Should I create an async structure for them?</p>\n</blockquote>\n<p>You may choose to for improving code readability or if thats your style however it will make no difference other than changing return type of your function <code>products</code> from void to <code>Promise</code>.</p>\n<blockquote>\n<p>If I use it heavily in this way, for example, if 10 million users run the same function, I think the event loop may get blocked.</p>\n</blockquote>\n<p>No, event loop will not get blocked, please note Javascript is single threaded so at any point only one resolved promise code will be available in execution stack rest resolved Promises will be waiting in queue for their turn, however if you have a large userbase as the number you mentioned you may wanna look into <a href=\"https://nodejs.org/api/cluster.html\" rel=\"nofollow noreferrer\">Node clusters</a> which basically creates multiple instance of your application thus giving you option of utilizing full potential of your CPU and handling multiple requests simultaneously.</p>\n<p><strong>Also Note:</strong></p>\n<p>The variables in your code will be created each time function <code>products()</code> is called and will be a closure to inner promises however they wont be shared across multiple executions, i.e if <code>products()</code> is executed more than once (typically for another request) both executions will have values independent of each other.</p>\n<p>However if you choose to declare a variable outside of function something like :</p>\n<pre><code>// var1\nconst ITEM_LIMIT = 4;\nexports.products = (req, res) => {\n //...\n</code></pre>\n<p>Each execution of this function will share same value of ITEM_LIMIT, which again will not be an issue depending on number if issues, however can cause logical issues say you update the value but need original value in next execution.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T17:58:38.747",
"Id": "266393",
"ParentId": "266391",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "266393",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T17:34:05.550",
"Id": "266391",
"Score": "1",
"Tags": [
"javascript",
"asynchronous",
"express.js"
],
"Title": "Is this good practice to declare variables freely inside async function?"
}
|
266391
|
<p>I am learning Java, so I am beginner. I know I can do this with split function but I want to improve my algorithm knowledge.</p>
<p>I will be glad if you help me. Thanks.</p>
<ul>
<li>inputStr variable is contains the string entered by the user.</li>
<li>stopPos variable is contains the order of wanted the word.</li>
<li>parseWith variable is contains which char to parse the string.</li>
</ul>
<pre><code> public static String parseStr(String inputStr, int stopPos, char parseWith) {
String toReturn = "";
int unitCount = 0;
for(int Iterator = 0; Iterator < inputStr.length(); Iterator = Iterator + 1){
if (inputStr.charAt(Iterator) == parseWith){
if (unitCount == stopPos) break;
toReturn = "";
continue;
}
if (toReturn == "") unitCount = unitCount + 1;
toReturn += inputStr.charAt(Iterator);
}
try{
return toReturn;
} catch(Exception e){
return null;
}
}
</code></pre>
<p>Here's an example of using:</p>
<pre><code>public static void main(String[] args) {
Scanner userEntry = new Scanner(System.in);
System.out.print("Enter two numbers separated by space: ");
String inputStr = userEntry.nextLine();
int frstPart = Integer.parseInt(parseStr(inputStr, 1, ' '));
int scndPart = Integer.parseInt(parseStr(inputStr, 2, ' '));
}
</code></pre>
<p><strong>EDIT</strong></p>
<p>I have changed some things from first part of code in here.</p>
<pre><code>try{
return toReturn;
} catch(Exception e){
return null;
}
</code></pre>
<p>to</p>
<pre><code>toReturn = (unitsCounter == stopPos) ? toReturn : null;
return toReturn;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T20:15:17.110",
"Id": "527787",
"Score": "0",
"body": "I have rolled back Rev 4 → 3. Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers)."
}
] |
[
{
"body": "\n<ul>\n<li><p>First of all, I see two problems with your choice of name for the <code>int</code> variable <code>Iterator</code>. For one thing, it goes against the Java coding convention of variable names starting with a lower case letter. And for another, and this might admittedly be more subjective than the first argument, there exists an interface named <code>Iterator</code> in the java.util package, and naming a primitive variable after an interface might be confusing to the reader, especially if the interface is from the package java.util which contains many commonly used classes and interfaces.</p>\n<p>Generally, with primitive variables like this one that only serve as a means to count loop iterations, it is common to only give them one-letter names, typically <code>i</code> or, in the case of nested loops, <code>j</code> etc., so unless you can think of a more descriptive or informative name, I suggest that you simply rename this variable to <code>i</code>.</p>\n</li>\n<li><p>There is a shortcut for <code>i = i + 1</code>, which is <code>++i</code>. In fact, there is also <code>i++</code>, which is subtly different from <code>++i</code>, but this difference is not relevant for the two occurrences of this code pattern in your question (with <code>Iterator</code> and <code>unitCount</code>), so I won't explain this difference here but simply point out that you can replace both of the aforementioned occurrences with either the pre- or the post-increment expression, which is more concise and might therefore be easier to read.</p>\n</li>\n<li><p>You are checking for reference equality with <code>if (toReturn == "")</code> when in fact you only want to compare the content of two <code>String</code> objects (if you are confused about what I mean, I found <a href=\"https://www.baeldung.com/java-comparing-objects\" rel=\"nofollow noreferrer\">this article</a> which might be helpful). So what you are actually interested in is <code>if (toReturn.equals(""))</code>, or, even simpler in this special case, <code>if (toReturn.isEmpty())</code>.</p>\n</li>\n<li><p>Next, about the structure of your code. You use <code>break</code> and <code>continue</code>, which means that the control flow of your program is not evident from its structure alone. This has the potential of making the code difficult to read, although this is not necessarily always true. But in your case, you have to read through the whole <code>if</code>-block containing the <code>continue</code> statement in order to find out under which conditions the subsequent two lines are executed. To avoid this complication, I would get rid of the <code>continue</code> statement and instead place the two lines after the large <code>if</code> block in an <code>else</code> block.</p>\n<p>While I cannot think of a better alternative to the <code>break</code> statement per se, the code might be easier to read if you put the remaining statement <code>toReturn = "";</code> in an <code>else</code> block (the corresponding <code>if</code> block of which is the one that contains the <code>break</code> statement).</p>\n</li>\n<li><p>This:</p>\n<pre class=\"lang-java prettyprint-override\"><code>toReturn = (unitsCounter == stopPos) ? toReturn : null;\n</code></pre>\n<p>is more complicated than it needs to be because it explicitly instructs the compiler to assign <code>toReturn</code> to itself under specific circumstances, which is pointless and therefore confusing. Instead, you could just write this:</p>\n<pre class=\"lang-java prettyprint-override\"><code>if (unitsCounter != stopPos) {\n toReturn = null;\n}\n</code></pre>\n</li>\n<li><p><code>String</code>s are immutable, so every time you append a single character to the output string or clear the entire string, you are effectively creating a new object. Since you are doing this many times but only need to return an actual <code>String</code> object once, you would be better of with a <code>StringBuilder</code> for your internal appending and resetting operations.</p>\n</li>\n<li><p>I think what also made the code a bit difficult to understand for me is your variable names, because I find some of them not really to the point. For example, <code>toReturn</code> is confusing because this string variable is frequently reset to 0 characters and populated anew before it is returned. A more fitting name would be <code>currentUnit</code>, in accordance with <code>unitCount</code>, in my opinion. <code>parseWith</code> is also not very descriptive, because the meaning of the preposition "with" seems to me to be ambiguous. An unambiguous alternative would be <code>delimiter</code>. I also found <code>stopPos</code> confusing, because "pos" sounds to me like a fixed-size unit, for example a character, but in your case, it concerns a variable-size unit (a sequence of characters). Maybe "segment" would be better, or "subsequence". Also, speaking of this variable, it would probably help if, whatever term you opt for, you also use this term in the variable currently named <code>unitCount</code>, for consistency.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T11:24:09.180",
"Id": "526308",
"Score": "0",
"body": "Thanks a lot. I will consider it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T00:52:25.807",
"Id": "266405",
"ParentId": "266394",
"Score": "2"
}
},
{
"body": "<p>Stingy makes many good points, though I'd disagree about calling any variable "i" - in my opinion you should always try to find a meaningful name for anything in your program.</p>\n<p>In this case, I think the variable represents a character position in the string, so I'd probably call it something like "currentCharPos" (I'd even consider "currentCharPosition").</p>\n<p>Building up Strings, even if you use StringBuilder, seems inelegant to me. If you find the start and end positions of "tokens" in the input String, you can use String.subString() to extract them much more simply.</p>\n<p>If you're going to produce something that does this, it would be natural for it to implement the Iterable interface, I think.</p>\n<p>Here's a simple example based on those ideas - note that my version assumes spaces as delimiters and assumes you can discard multiple spaces :</p>\n<pre><code>import java.util.Iterator;\n\npublic class StringSplit implements Iterator<String>, Iterable<String> {\n\n private final String toSplit; // the string we're going to tokenize\n private int currentCharPos = 0; // where we are in the string at any point in time\n String nextWord = null; // the next token to be returned\n\n public StringSplit(String toSplit) {\n this.toSplit = toSplit;\n nextWord = getNextWord(); // the easiest approach is probably to pre-load the next token\n }\n\n private String getNextWord() {\n // find the first non-space\n while (currentCharPos < toSplit.length()) {\n if (toSplit.charAt(currentCharPos) != ' ') {\n break;\n }\n currentCharPos += 1;\n }\n\n if (currentCharPos >= toSplit.length()) { // end of string before we found one\n return null;\n }\n\n int startPos = currentCharPos;\n\n // Find next space (or end of string)\n while (currentCharPos < toSplit.length()) {\n if (toSplit.charAt(currentCharPos) == ' ') {\n break;\n }\n currentCharPos += 1;\n }\n\n return toSplit.substring(startPos, currentCharPos);\n }\n\n @Override // From the Iterator interface\n public boolean hasNext() {\n return nextWord != null;\n }\n\n @Override // From the Iterator interface\n public String next() {\n String result = nextWord; // remember what we need to return\n nextWord = getNextWord(); // pre-load the next token\n return result;\n }\n\n @Override // From the Iterable interface\n public Iterator<String> iterator() {\n return this;\n }\n\n // Do some basic testing\n public static void main(String[] args) {\n StringSplit splitter = new StringSplit("My hat it has three corners");\n int wordNumber = 0;\n for (String word : splitter) {\n System.out.format("word %d is '%s'%n", wordNumber++, word);\n }\n }\n}\n</code></pre>\n<p>Historically you might have used the StringTokenizer class for the purpose - the class is still around, and its source code is available, so you might find it instructive to review that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T19:54:54.367",
"Id": "527786",
"Score": "0",
"body": "Thanks a lot. My goal is simplify it as much as possible. So I have changed some things. I am sorry to say this but my English level not enough."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T13:43:19.873",
"Id": "266591",
"ParentId": "266394",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T18:14:34.273",
"Id": "266394",
"Score": "1",
"Tags": [
"java",
"strings",
"parsing"
],
"Title": "Parsing words from string"
}
|
266394
|
<p>I have a short bit of TypeScript code that looks like the following:</p>
<pre class="lang-js prettyprint-override"><code>world.rooms = world.rooms.map((room) => {
room = { ...defaultRoom, ...room };
room.contents = room.contents!.map((thing) => ({
...defaultThing,
...thing,
}));
return room;
});
</code></pre>
<p>Basically, I have a <code>world</code> object, which has a property <code>rooms</code> which is an array of <code>room</code> objects, each of which has a <code>contents</code> property consisting of an array of <code>thing</code> objects. For each room and thing, I want to assign some default properties. The code I wrote above works correctly, but it's not very readable. Is there a more concise way to write this code?</p>
|
[] |
[
{
"body": "<p>You can embed the <code>contents</code> bit</p>\n<pre><code>world.rooms = world.rooms.map(room => ({ \n ...defaultRoom, ...room, \n contents: room.contents.map( \n thing => ({ ...defaultThing, thing }) \n ) \n}));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T22:10:38.637",
"Id": "526286",
"Score": "2",
"body": "You have made `room.contents` a mandatory property of rooms, If passed `room` with no `contents` array your function will throw an error. One assumes that `defaultRoom` in OPs code would have an empty (or some default things) `contents` array to prevent this error."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T20:03:30.640",
"Id": "266400",
"ParentId": "266395",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T18:41:50.800",
"Id": "266395",
"Score": "1",
"Tags": [
"javascript",
"array",
"typescript"
],
"Title": "How can I rewrite this typescript map to be more concise?"
}
|
266395
|
<p>I decided using a C++ <code>map</code> or <code>unordered_map</code> is the most appropriate option to store 'Regions' where which can be loaded in arbitrary patterns</p>
<p>The rest of the project is written in C, so I made a C interface:</p>
<pre><code>#include <unordered_map>
#include "Region.hpp"
static std::unordered_map<uint64_t, void *> Regions;
extern "C" {
void *GetRegion(const uint16_t X, const uint16_t Z, const unsigned char Y) {
const uint64_t Key = X|((uint64_t)Z<<16)|((uint64_t)Y<<32);
return Regions.count(Key) ? Regions.at(Key) : NULL;
}
void *CreateRegion(const uint16_t X, const uint16_t Z, const unsigned char Y) {
const uint64_t Key = X|((uint64_t)Z<<16)|((uint64_t)Y<<32);
if (Regions.count(Key)) {
return Regions.at(Key);
}
void *const Region = GenerateARegion(X, Z, Y);
Regions.insert({Key, Region});
return Region;
}
bool DeleteRegion(const uint16_t X, const uint16_t Z, const unsigned char Y) {
return Regions.erase(X|((uint64_t)Z<<16)|((uint64_t)Y<<32)) != 0;
}
}
</code></pre>
<p>I am wondering if there is an elegant way to eliminate the repeated <code>X|((uint64_t)Z<<16)|((uint64_t)Y<<32)</code></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T08:12:18.460",
"Id": "526298",
"Score": "0",
"body": "\"where which can be loaded\"? I'm struggling to parse that - could you edit to clarify, please?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T15:08:56.027",
"Id": "526325",
"Score": "0",
"body": "Easy: make it a (presumably inlined) helper function. It should be local to this CPP file."
}
] |
[
{
"body": "<p>The use of the global variable <code>Regions</code> rings alarm bells for me. It will make it hard to write independent unit tests for these functions. Prefer passing an opaque pointer through your C function interface. In any case, it will be better to declare its value type explicitly rather than <code>void*</code>, to give us suitable checking when we insert elements.</p>\n<p>The computation of <code>Key</code> in each function is repetitive, and needs to be consistent. It's really worth extracting that as a function. I'd probably split the interface from the implementation here:</p>\n<pre><code>// header\n#ifndef REGION_H\n#define REGION_H\n\n#ifdef __cplusplus__\nextern "C" {\n#else\n#include <stdbool.h>\n#endif\n\nvoid *GetRegion(uint16_t X, uint16_t Z, unsigned char Y);\nvoid *CreateRegion(uint16_t X, uint16_t Z, unsigned char Y);\nbool DeleteRegion(uint16_t X, uint16_t Z, unsigned char Y);\n\n#ifdef __cplusplus__\n}\n#endif\n#endif\n</code></pre>\n\n<pre><code>// implementation\n#include "region.h"\n#include "Region.hpp"\n#include <unordered_map>\n\nstatic std::unordered_map<uint64_t, void *> Regions;\n\nstatic std::unordered_map<uint64_t, void *> Regions;\n\nstatic uint64_t key_for(uint16_t x, uint64_t z, uint64_t y)\n{\n return x | z << 16 | y << 32;\n}\n\nvoid *GetRegion(const uint16_t x, const uint16_t z, const unsigned char y) {\n auto const key = key_for(x, y, z);\n ⋮\n}\n\nvoid *CreateRegion(const uint16_t x, const uint16_t z, const unsigned char y) {\n auto const key = key_for(x, y, z);\n ⋮\n}\n\nbool DeleteRegion(const uint16_t x, const uint16_t z, const unsigned char y) {\n auto const key = key_for(x, y, z);\n ⋮\n}\n</code></pre>\n<hr />\n<p>Consider using a different key type, rather than using arithmetic to compose it. For instance,</p>\n<pre><code>using Key = std::tuple(unsigned char, uint16_t, uint16_t);\n\nstatic Key key_for(uint16_t x, uint16_t z, unsigned char y)\n{\n return {y, z, x};\n}\n</code></pre>\n<p>This should give the same sort order if we change to <code>std::map</code>.</p>\n<hr />\n<p>In <code>GetRegion()</code>, we look up the key twice here:</p>\n<blockquote>\n<pre><code>return Regions.count(Key) ? Regions.at(Key) : NULL;\n</code></pre>\n</blockquote>\n<p>It's better to find it just once and reuse the iterator:</p>\n<pre><code>auto const key = key_for(x, y, z);\nauto it = Regions.find(key);\nreturn it == Regions.end() : nullptr : it->second;\n</code></pre>\n<p>The same logic can be used in <code>CreateRegion()</code>.</p>\n<hr />\n<p>In <code>DeleteRegion()</code> we drop the pointer from the map, but who is responsible for releasing its resources? Is there a <code>region_free()</code> function we need to be calling?</p>\n<hr />\n<h1>Modified code</h1>\n<p>Untested, as we're missing <code>GenerateARegion()</code> and <code>FreeARegion()</code>.</p>\n<pre><code>#include "region.h"\n#include "Region.hpp"\n#include <tuple>\n#include <unordered_map>\n\nusing Key = std::tuple(unsigned char, uint16_t, uint16_t);\nstatic std::unordered_map<Key, Region*> regions;\n\nstatic Key key_for(uint16_t x, uint16_t z, unsigned char y)\n{\n return {y, z, x};\n}\n\nvoid *GetRegion(const uint16_t x, const uint16_t z, const unsigned char y)\n{\n auto const key = key_for(x, y, z);\n auto const it = regions.find(key);\n return it == regions.end() : nullptr : it->second;\n}\n\nvoid *CreateRegion(const uint16_t x, const uint16_t z, const unsigned char y) {\n auto const key = key_for(x, y, z);\n auto it = regions.find(key);\n if (it == regions.end()) {\n it = regions.emplace(key, GenerateARegion(x, z, y))->first;\n }\n return it->second;\n}\n\nbool DeleteRegion(const uint16_t x, const uint16_t z, const unsigned char y) {\n auto const key = key_for(x, y, z);\n auto const it = regions.find(key);\n if (it == regions.end()) {\n return false;\n }\n FreeARegion(it->second);\n return regions.erase(it) != 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T15:10:58.500",
"Id": "526326",
"Score": "0",
"body": "Is it guaranteed that C++ `bool` is the same size as C's `_Bool`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T15:59:05.677",
"Id": "526331",
"Score": "0",
"body": "I honestly don't know; I just accepted from the code under review that a `bool`-returning function can be `extern \"C\"`. If you're interested in the answer, it's probably worth looking on [so]. If we can't depend on that, I guess `int` is the appropriate fallback."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T19:38:05.337",
"Id": "526406",
"Score": "1",
"body": "It might be true for the specific compiler, or part of the ABI, so can be counted on given the context, though not part of the ISO standard. I didn't find any mention at cppreference so thought I'd query."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T07:39:43.457",
"Id": "526429",
"Score": "1",
"body": "Over on SO: [Getting bool from C to C++ and back](//stackoverflow.com/q/40020423/4850040). Of course it's more than just _size_ that matters - in theory, C++ `bool` and C `_Bool` could have different representations, though in practice that's probably too perverse; in practice, the platform ABI should make them the same, and lacking that, using compilers from the same suite (e.g. gcc and g++) gives the best chance of interoperability."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T08:10:22.947",
"Id": "266411",
"ParentId": "266403",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "266411",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T22:57:28.923",
"Id": "266403",
"Score": "1",
"Tags": [
"c++",
"c"
],
"Title": "Providing a C interface to a 'Region' map"
}
|
266403
|
<p>I am trying to print out the squares of n numbers, n which is a value retrieved from the user. I want to know if there is a better way to do this:</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
int main(void){
int i, n;
printf("This program prints a table of squares.\n");
printf("Enter a number of entries in table: ");
scanf("%d", &n);
getchar();
for(i = 1; i <= n; i++){
printf("%10d%10d\n", i, i*i);
if(i % 24 == 0){
printf("Press Enter to continue...");
if(getchar() == '\n'){
continue;
}
}
}
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>Intent here is to print square of consecutive integer number. As square of (N-1) is already computed in previous iteration, square of N can be computed by</p>\n<pre><code>N*N = (N-1)*(N-1) + 2*(N-1) + 1 = (N-1)*(N-1) + ((N-1) << 1) + 1\n\n</code></pre>\n<p>So essentially we need <strong>one shift and two add operation</strong> rather than multiplication. For smaller values of N, performance difference will be negligible but for large value of N it can be beneficial.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T04:58:46.307",
"Id": "266406",
"ParentId": "266404",
"Score": "1"
}
},
{
"body": "<h1>Input handling</h1>\n<blockquote>\n<pre><code>scanf("%d", &n);\n</code></pre>\n</blockquote>\n<p>We can't safely use <code>n</code> unless <code>scanf()</code> successfully converted at least one value (and it can't convert more, because we only asked for one conversion). Therefore:</p>\n<pre><code>if (scanf("%d", &n) != 1) {\n fputs("Input should be numeric!\\n", stderr);\n return EXIT_FAILURE;\n}\n</code></pre>\n<p>Consider also checking that <code>n</code> is positive.</p>\n<p>We could loop until we get a valid input. Personally, I would take the number to generate as a command-line argument:</p>\n<pre><code>#include <stdlib.h>\n\nint main(int argc, char **argv)\n{\n if (argc != 2) {\n fprintf(stderr, "Usage: %s NUMBER\\n", argv[0]);\n return EXIT_FAILURE;\n }\n char *end;\n long n = strtol(argv[1], &end, 0);\n if (n < 1 || !*end) {\n fprintf(stderr, "Usage: %s NUMBER\\n", argv[0]);\n return EXIT_FAILURE;\n }\n ⋮\n}\n</code></pre>\n<p>Or we could just generate an "infinite" list, and let users filter with standard tools (<code>head</code>) to get the length required. When I say "infinite" list in quotes like that, I mean that we should stop it only when <code>i * i</code> would overflow its type. We could change <code>i</code> to <code>unsigned long long</code> (or even <code>uintmax_t</code> from <code><stdint.h></code>) if we will really need the extra range.</p>\n<hr />\n<h1>Paging</h1>\n<blockquote>\n<pre><code> if(i % 24 == 0){\n printf("Press Enter to continue...");\n if(getchar() == '\\n'){\n continue;\n }\n }\n</code></pre>\n</blockquote>\n<p>It seems inconvenient to have output stop every 24 lines, even when I'm using a much larger (virtual) terminal, or writing output to a file. It would be better if we adapted better to the terminal size (e.g. using <code>getenv("ROWS")</code> if that's present). However, this is something that we have standard tools for, and interactive users will probably want to use their own choice of pager. So my recommendation is to not duplicate that functionality in one's own programs.</p>\n<p>In any case, there's a bug. If the input character is not a newline, then the behaviour is no different to when it is - <code>continue</code> at the end of a loop skips nothing!</p>\n<hr />\n<h1>Minor bits</h1>\n<p>For very large integers, the format string <code>%10d%10d</code> will run the numbers into each other. It's a good idea to have at least one space so that when the minimum width overflows, they are still separated.</p>\n<p>In <code>main()</code> (and only that function), we can omit <code>return 0;</code> at the end.</p>\n<hr />\n<h1>Simplified program</h1>\n<p>The result is greatly pared down:</p>\n<pre><code>#include <stdint.h>\n#include <stdio.h>\n\nint main(void)\n{\n for (int i = 1; i <= INT_MAX/i; ++i) {\n printf("%10d %10d\\n", i, i*i);\n }\n}\n</code></pre>\n<p>We can use this in pipelines:</p>\n<pre><code>squares | head -n 20 >twenty_squares\n</code></pre>\n<p>And interactively:</p>\n<pre><code>squares | head -n 200 | more\n</code></pre>\n<p>Or interactively until we get bored:</p>\n<pre><code>squares | more\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T07:23:54.377",
"Id": "266409",
"ParentId": "266404",
"Score": "3"
}
},
{
"body": "<p><strong>Overflow</strong></p>\n<p><code>i*i</code> can overflow (given a pause every 24, it would take a lot of <em>enters</em>).</p>\n<p>To prevent overflow, use a wider type for the multiplicaiton.</p>\n<pre><code>#include <stdint.h>\n\n// printf("%10d%10d\\n", i, i*i);\nprintf("%10d %10lld\\n", i, 1LL*i*i);\n// or better\nprintf("%10d %10jd\\n", i, (intmax_t)i*i);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T13:36:33.040",
"Id": "526322",
"Score": "0",
"body": "@TobySpeight Interesting. I pulled `<inttypes.h>` from C spec 7.8.1 7 example. Perhaps the C spec example needs improvement to also include `<stdint.h>` or maybe that gets pulled in by `<inttypes.h>`?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T13:16:40.333",
"Id": "266422",
"ParentId": "266404",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-25T23:59:48.140",
"Id": "266404",
"Score": "0",
"Tags": [
"c"
],
"Title": "Printing out the squares of n numbers in C"
}
|
266404
|
<pre><code>def collatz(n, counter):
if n == 1:
return counter
elif n % 2 == 0:
return collatz(n/2, counter + 1)
else:
return collatz(3*n + 1, counter + 1)
print(int(collatz(15, 0)))
</code></pre>
<p>Is there any way to improve this code? The two arguments passed on the <code>collatz()</code> function rubs me the wrong way. Tells me that should only be one, but I don't know better.</p>
<p>My question is an attempt to improving my Python vocabulary as I just barely started. So, what useful Python tool could I have used here to make the code better?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T07:38:44.730",
"Id": "526293",
"Score": "0",
"body": "Do Python implementations typically eliminate tail-calls? If not, you're heading for a stack overflow by using recursion..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T15:21:33.407",
"Id": "526328",
"Score": "4",
"body": "@TobySpeight CPython, the reference implementation, doesn't perform any form of tail call elimination"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T16:23:54.723",
"Id": "526333",
"Score": "2",
"body": "See https://tobiaskohn.ch/index.php/2018/08/28/optimising-python-3/ for more information @TobySpeight"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T22:47:22.883",
"Id": "526347",
"Score": "3",
"body": "@Jasmijn: It's not just CPython. Guido van Rossum has said that *NO* Python implementation is allowed to eliminate tail calls. So, any implementation that eliminates tail calls is non-compliant, and thus *by definition* not a Python implementation. Therefore, it is impossible that there is a Python implementation that eliminates tail calls, because if it did, it wouldn't be a Python implementation. (Personally, I find that quite insane: not eliminating tail calls is essentially a memory leak, so why would you *force* implementors to leak memory?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T09:37:10.917",
"Id": "526367",
"Score": "0",
"body": "@JörgWMittag Where do you store traceback information if TCO is allowed? In another stack? Isn't the point that tracebacks are more important than allowing you to use recursion to loop? If you need such levels of recursion you can normally quite easily convert away from an FP approach."
}
] |
[
{
"body": "<p><strong>Formatting / Spacing</strong></p>\n<p>There should be spaces around operators, such as <code>n / 2</code> or <code>3 * n</code>. Some IDEs can handle this for you through an auto-formatting option (e.g. <kbd>Ctrl</kbd> + <kbd>Alt</kbd> + <kbd>L</kbd> for PyCharm on Windows).</p>\n<hr />\n<p><strong>Type hints</strong></p>\n<p>It's useful to provide type hints for arguments and function return values. This increases readability and allows for easier and better error checking. Refer to <a href=\"https://www.python.org/dev/peps/pep-0484/\" rel=\"nofollow noreferrer\">PEP484</a> for more information.</p>\n<pre><code>def collatz(n: int, counter: int) -> int:\n # function body here\n</code></pre>\n<hr />\n<p><strong>Return values</strong></p>\n<p>Adding these type hints will help us identify the first improvement. As the Collatz sequence only contains integers, our <code>collatz</code> function should only take an integer as the <code>n</code> argument. <code>collatz(n / 2, counter + 1)</code> passes a float, so to keep it consistent we should probably convert it to an <code>int</code> before passing it: <code>collatz(int(n / 2), counter + 1)</code>. Even better, we can use the floor division operator <code>//</code>: <code>collatz(n // 2, counter + 1)</code></p>\n<p>Please note that you do not need to convert the function output to an <code>int</code>, as it will only ever return an <code>int</code> value.</p>\n<hr />\n<p><strong>Default arguments</strong></p>\n<p>There are multiple approaches to improving the handling of the <code>counter</code> argument, which rubs you the wrong way. This is good intuition on your part. With default arguments, Python offers one really concise option:</p>\n<pre><code>def collatz(n: int, counter: int = 0) -> int:\n if n == 1:\n return counter\n elif n % 2 == 0:\n return collatz(n // 2, counter + 1)\n else:\n return collatz(3 * n + 1, counter + 1)\n</code></pre>\n<p>As you can see, the only addition we need to implement is <code>counter = 0</code>, which makes <code>0</code> the default argument for <code>counter</code>. This means that <code>counter</code> will be set to <code>0</code> if the argument is not provided by the caller.</p>\n<p>You can now simply call</p>\n<pre><code>print(collatz(15))\n</code></pre>\n<p>More on <a href=\"https://www.geeksforgeeks.org/default-arguments-in-python/\" rel=\"nofollow noreferrer\">default arguments in Python</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T07:58:43.470",
"Id": "526295",
"Score": "5",
"body": "I would also recommend using `cache` from `itertools`, it will dramatically speed up the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T08:01:37.863",
"Id": "526296",
"Score": "0",
"body": "@N3buchadnezzar I agree, good recommendation!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T08:01:59.287",
"Id": "526297",
"Score": "2",
"body": "The type hints are certainly useful, and I definitely miss it coming from C. Do Python programmers regularly use them? Or is it something that goes away when you're already comfortable using Python?\nThe `counter` variable initialization was my problem; I could not find where it should be put. And so my solution was just to pass it to the function. I know that's not how it should be because I admit my Python knowledge is still very limited. \nYou provided me with easy-to-understand explanations. Thank you :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T08:34:23.537",
"Id": "526302",
"Score": "1",
"body": "Glad to help! I'd say type hints are useful at any level of Python proficiency, as they allow for easier debugging and maintainability. They do probably provide the biggest benefit to beginner and intermediate Pythonistas though =)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T08:48:46.573",
"Id": "526303",
"Score": "0",
"body": "Btw why do we care about keeping track of `counter`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T10:12:03.417",
"Id": "526306",
"Score": "0",
"body": "@N3buchadnezzar the goal of the code is to print the length of the collatz sequence. Could you elaborate as to why you asked? I have a beginner understanding of Python, and just programming in general (never touched a DSA topic before)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T21:36:30.720",
"Id": "526344",
"Score": "0",
"body": "@N3buchadnezzar: Because testing the Collatz conjecture isn't just about infinite loop or not; counting the iterations is interesting. https://en.wikipedia.org/wiki/Collatz_conjecture#Empirical_data / https://en.wikipedia.org/wiki/Collatz_conjecture#Visualizations. (Besides visualizations, results may provide some insight into algorithmic optimizations to short-circuit the basic steps; see various answers on [Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?](https://stackoverflow.com/q/40354978) that focus on the algorithm instead of asm)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T21:52:41.800",
"Id": "526345",
"Score": "0",
"body": "(Although I think you already know that based on your comments on your own answer; maybe I misunderstood what you were asking. Maybe you meant why we want a 2nd arg at all, when your answer shows a way to do it with non-tail calls where the eventual count just ends up in a return value. That's good too, but defeats tail-call optimization for languages / implementations that can do that.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T22:24:18.643",
"Id": "526346",
"Score": "0",
"body": "Unless I'm mistaken Python doesn't actually have function overloading, usually it's faked with default arguments or some `*args` trickery. Maybe make that more clear?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T00:30:55.857",
"Id": "526348",
"Score": "0",
"body": "@PeterCordes your second comment hit the nail right on the head about the meaning of my comment. I wrote it in the middle of an lecture, so I had to keep it brief. I elaborated as you said when I got home in my answer =)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T09:28:33.803",
"Id": "526365",
"Score": "0",
"body": "@ToddSewell Thanks for your comment, I cleared it up. That's what happens when you edit previously working code while writing the answer without re-running it."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T07:36:01.633",
"Id": "266410",
"ParentId": "266408",
"Score": "9"
}
},
{
"body": "<h3>Sequence vs counting</h3>\n<p>As stated in the comments</p>\n<blockquote>\n<p>the goal of the code is to print the length of the Collatz sequence. Could you elaborate as to why you asked?</p>\n</blockquote>\n<p>As OP mentions, he is <em>not</em> interested in the sequence itself, but its <em>length</em>. As such we actually do not need the values from the sequence itself. We <em>only</em> need to count how many iterations it takes to reach 1. The following code does precisely that: every time the function is called we increment by one:</p>\n<pre><code>def collatz(n: int) -> int:\n if n == 1:\n return 1\n elif n % 2 == 0:\n return 1 + collatz(n // 2)\n else: # n % 2 == 1:\n return 1 + collatz(3 * n + 1)\n</code></pre>\n<p>Spend some time thinking about this. Recursion is <em>hard</em>. Go through the code above by hand for the number 5 and see what it returns and how. As a minor point, it is better to be explicit than implicit in Python. Compare</p>\n<pre><code>if n == 1:\n return n\n</code></pre>\n<p>vs</p>\n<pre><code>if n == 1:\n return 1\n</code></pre>\n<p>While trivial, it is a good mindset to get into.</p>\n<h3>Cache</h3>\n<p>It can be very wise to cache previous calls to the function to save time. Assume we try to calculate <code>collatz(23)</code>:</p>\n<pre><code>23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1 \n</code></pre>\n<p>So <code>collatz(23) = 15</code>. Now assume we want to calculate <code>collatz(61)</code>:</p>\n<pre><code> 61, 184, 92, 46, (23)\n</code></pre>\n<p>Notice how we stop early: <code>23</code> is already saved so we only have to do 4 iterations instead of 19. This can, for instance, be implemented as follows:</p>\n<pre><code>cache = {1: 0}\n\ndef collatz(n: int) -> int:\n if n in cache:\n return cache[n]\n else:\n if n % 2 == 0:\n m = n // 2\n else:\n m = 3 * n + 1\n res = collatz(m) + 1\n cache[n] = res\n return res\n</code></pre>\n<p>However. there are builtins for handling <a href=\"https://en.wikipedia.org/wiki/Memoization\" rel=\"nofollow noreferrer\">memoization</a> in Python.\nIntroducing the decorator <a href=\"https://docs.python.org/3/library/functools.html#functools.cache\" rel=\"nofollow noreferrer\"><code>itertools.cache</code></a>.</p>\n<pre><code>import functools\n\n\n@functools.cache\ndef collatz(n: int) -> int:\n if n == 1:\n return 1\n elif n % 2 == 0:\n return 1 + collatz(n // 2)\n else: # n % 2 == 1:\n return 1 + collatz(3 * n + 1)\n</code></pre>\n<p>Let us add a test function to benchmark how much quicker our function is with memoization:</p>\n<pre><code>def longest_collatz(limit: int) -> int:\n longest = 0\n for i in range(1, limit):\n current = collatz(i)\n if current > longest:\n longest = current\n return longest\n\n\ndef main():\n limit = 10 ** 4\n with cProfile.Profile() as pr:\n longest_collatz(limit)\n\n stats = pstats.Stats(pr)\n stats.strip_dirs()\n stats.sort_stats(pstats.SortKey.CALLS)\n stats.print_stats()\n</code></pre>\n<p>Here we simply compare how many function calls it takes to find the longest Collatz sequence amongst the first 10 000 numbers. I wanted to try with higher values but your version took too long to complete...</p>\n<pre><code>859639 function calls (10002 primitive calls) in 12.444 seconds\n 21667 function calls ( 4330 primitive calls) in 0.332 seconds\n</code></pre>\n<p>Of course it is much smarter to just iterate over the odd values, but this is just for comparison. To compare the versions I just commented the <code>@functools.cache</code> bit.</p>\n<h3>Full code</h3>\n<pre><code>import functools\nimport cProfile\nimport pstats\n\n@functools.cache\ndef collatz(n: int) -> int:\n if n == 1:\n return n\n elif n % 2 == 0:\n return 1 + collatz(n // 2)\n else: # n % 2 == 1:\n return 1 + collatz(3 * n + 1)\n\ndef longest_collatz(limit: int) -> int:\n longest = 0\n for i in range(1, limit):\n current = collatz(i)\n if current > longest:\n longest = current\n return longest\n\ndef main():\n limit = 10 ** 4\n with cProfile.Profile() as pr:\n longest_collatz(limit)\n\n stats = pstats.Stats(pr)\n stats.strip_dirs()\n stats.sort_stats(pstats.SortKey.CALLS)\n stats.print_stats()\n\nif __name__ == "__main__":\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T15:23:45.427",
"Id": "526329",
"Score": "1",
"body": "I could imagine it would be an awesome feeling to go back to this answer when I can finally understand every concept you put here. I highly appreciate how you optimized the code and explained it in a way that's not daunting. The runtime data is the icing on the cake. Thank you :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T16:21:55.213",
"Id": "526332",
"Score": "0",
"body": "Note that we could have done this _even_ faster if our goal was not to generate the length of the sequence, but the longest one. I wrote some bad (but super fast) code for solving this a bunch of years ago https://github.com/Oisov/Project-Euler/blob/master/Problems/PE_014/Python/PE_014.py. In python 2, but it can easily be rewritten. The next step up after understanding this answer, is understanding this code. The final step is improving the code with typing hints, doctests and proper docstring + comments."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T16:28:47.693",
"Id": "526334",
"Score": "1",
"body": "As a final comment the github link also avoids the _tail call recursion_ issue by simply implementing a iterative instead of recursive version =)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T08:51:46.310",
"Id": "266413",
"ParentId": "266408",
"Score": "15"
}
}
] |
{
"AcceptedAnswerId": "266410",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T06:40:30.310",
"Id": "266408",
"Score": "10",
"Tags": [
"python",
"recursion",
"collatz-sequence"
],
"Title": "My recursive attempt at Collatz Sequence in Python"
}
|
266408
|
<p>Wrote this for getting the content of image from the given URL. It accepts a URL and returns an array of shape <code>number_of_channels image_height image_width</code>. Each "row" represents a pixel, and each element is within the range of 0 to 1.</p>
<ul>
<li>What are some issues with my implementation?</li>
<li>Is there a better way to turn the data from <code>HttpCommand.Get</code> into image?</li>
<li>Is there a better way to handle different image format?</li>
<li>How to make it more portable?</li>
</ul>
<p> </p>
<pre><code>∇ r←GetImg url ;ns
'ns'⎕NS'url'
:With ns
⎕SE.SALT.Load'HttpCommand'
valueOf←{⊃(,¯1↑⍉⍵)/⍨(⊂⍺)≡¨,1↑⍉⍵}
split←{⍵⊆⍨~⍺=⍵}
tmp_path←(⊢2 ⎕NQ # 'GetEnvironment',⊂)'tmp'
res←HttpCommand.Get url
(type fmt)←'/'split'Content-Type'valueOf res.Headers
tmp_ft←(tmp_path,'\tmp.',fmt)(⎕NCREATE⍠('Unique' 1))0
tmp_name←⊃⎕NINFO tmp_ft
res.Data ⎕NREPLACE tmp_ft 0
⎕NUNTIE tmp_ft
'bm'⎕WC'Bitmap'('File'tmp_name)
⎕NDELETE tmp_name
:EndWith
r←255÷⍨256(⊥⍣¯1)ns.bm.CBits
∇
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>Your use of <code>:With</code> is a clever way to avoid having to localise names, but you should be aware of the peculiarities of <code>:With</code> to avoid frustration in the future. Even inside the <code>:With</code> block, you can access <code>r</code> and in this case also <code>url</code>, but if the argument was an object, you <em>would</em> have to mention it explicitly, so you're doing the right thing here. Since you can access <code>r</code>, you can move the last line inside the block:<pre>r←255÷⍨256(⊥⍣¯1)bm.CBits</pre></p>\n</li>\n<li><p>You do not need the <code>ns</code> local, as you can give <code>:With</code> an anonymous namespace:<pre>:With ⎕NS'url'</pre></p>\n</li>\n<li><p>Since you're only using <code>HttpCommand</code> once, you can create an anonymous instance of it, which is then used (and discarded) immediately:<pre>res←(⎕SE.SALT.New'HttpCommand'('Get' url)).Run</pre></p>\n</li>\n<li><p><code>valueOf</code> can be simplified a lot:<pre>valueOf←{(⊢/⍵)⊃⍨(⊣/⍵)⍳⊂⍺}</pre></p>\n</li>\n<li><p>I strongly recommend <a href=\"https://abrudz.github.io/style/#nc\" rel=\"nofollow noreferrer\" title=\"APL Style: Naming Conventions\">a strict naming convention</a>. I'd personally name functions with initial Capital and variables with initial minuscule: <code>ValueOf</code> and <code>Split</code></p>\n</li>\n<li><p><code>Split</code> could use <code>≠</code> instead of inverting <code>~</code> the equality <code>=</code>. You could also consider using a <a href=\"https://aplwiki.com/wiki/Tacit_programming#Trains\" rel=\"nofollow noreferrer\" title=\"Tacit programming: Trains - APL Wiki\">train</a>:<pre>Split←≠⊆⊢</pre></p>\n</li>\n<li><p><a href=\"https://aplcart.info?q=tmp\" rel=\"nofollow noreferrer\" title=\"APLcart: tmp\">There's an I-beam</a> to get a proper temporary directory, which will allow your function to work even if there's no <code>tmp</code> environment variable:<pre>tmp_path←739⌶0</pre></p>\n</li>\n<li><p>I personally try to avoid parentheses, especially to govern order of execution, so I'd write the <code>tmp_ft</code> line as:<pre>tmp_ft←0 ⎕NCREATE⍠'Unique' 1⍨tmp_path,'\\tmp.',fmt</pre></p>\n</li>\n<li><p>The final expression that computes the result is the only real bug you have. You're using <code>⊥⍣¯1</code> to automatically determine how many base-256 "digits" to use. However, if your image has no red (or no red and no green) signal at all, you will end up with only two "digits", and the format will be all wrong. E.g. if the image was entirely cyan (<span class=\"math-container\">\\$\\color{#0FF}{⬤}\\$</span> #00FFFF), all the the pixels would be encoded as 65535, which would become <code>255 255</code> instead of <code>255 255 255</code>. You must therefore specify the full radix:<pre>r←255÷⍨bm.CBits⊤⍨3⍴256</pre></p>\n</li>\n</ol>\n<p>Here is your function with all my suggested changes:</p>\n<pre><code> r←GetImg url\n :With ⎕NS'url'\n ValueOf←{(⊢/⍵)⊃⍨(⊣/⍵)⍳⊂⍺}\n Split←≠⊆⊢\n\n tmp_path←739⌶0\n\n res←(⎕SE.SALT.New'HttpCommand'('Get'url)).Run\n\n (type fmt)←'/'Split'Content-Type'ValueOf res.Headers\n tmp_ft←0 ⎕NCREATE⍠'Unique' 1⍨tmp_path,'\\tmp.',fmt\n tmp_name←⊃⎕NINFO tmp_ft\n res.Data ⎕NREPLACE tmp_ft 0\n ⎕NUNTIE tmp_ft\n 'bm'⎕WC'Bitmap'('File'tmp_name)\n ⎕NDELETE tmp_name\n r←255÷⍨bm.CBits⊤⍨3⍴256\n :EndWith\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T03:02:51.100",
"Id": "526350",
"Score": "0",
"body": "Thank you. One thing I want to ask is that, for the last point (9th), I did it that way to handle images with transparency, which will have an additional alpha channel in the front. After reading your answer, I used this which seems to be working: \n`r←255÷⍨bm.CBits⊤⍨256⍴⍨3+24≤2⍟⌈/,bm.CBits`\nBut is there a better way to do that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T12:02:26.290",
"Id": "526373",
"Score": "0",
"body": "@leo3065 I'm frankly surprised that this works, and I'll take it up with the colleague that deals with this, but he's on holiday until Wednesday."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T13:07:48.220",
"Id": "266421",
"ParentId": "266414",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "266421",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T09:20:34.543",
"Id": "266414",
"Score": "2",
"Tags": [
"apl"
],
"Title": "A TradFn for loading an image from a URL in Dyalog APL"
}
|
266414
|
<p>With this data I am returning one object per <code>keyword</code> prioritising <code>preferedDomain</code> string on domain and then its higher <code>rank</code> value, it is already ordered by rank so returning one object per keyword will take care of that.</p>
<p>This does work and I have done some performance checks and found out that doing a for loop will take longer than this.</p>
<p>Is there a better approach to tackle this problem?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const preferedDomain = 'prefered'
const data = [
{ keyword: 'hey', domain: 'apple', rank: 1},
{ keyword: 'hey', domain: 'apple', rank: 2},
{ keyword: 'hey', domain: 'prefered', rank: 46},
{ keyword: 'foo', domain: 'amazon', rank: 1},
{ keyword: 'foo', domain: 'amazon', rank: 2},
{ keyword: 'foo', domain: 'amazon', rank: 3},
{ keyword: 'bla', domain: 'prefered', rank: 1},
{ keyword: 'bla', domain: 'prefered', rank: 2},
{ keyword: 'bla', domain: 'prefered', rank: 3}
]
// Object map with prefered objects only
const prefered = data.reduce((acc, obj) => {
if (!acc[obj.keyword] && obj.domain === preferedDomain) acc[obj.keyword] = obj
return acc
}, {})
// If keyword is on prefered object use that, otherwise the first entry
const res = Object.values(
data.reduce((acc, obj) => {
if (!acc[obj.keyword]) acc[obj.keyword] = prefered[obj.keyword] ?? obj
return acc
}, {})
)
console.log(res)</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T08:13:50.177",
"Id": "526357",
"Score": "0",
"body": "you can do just one pass, if you overwrite existing object (in the keyword map) when it is not prefered and the currently iterated item is. if the input was not sorted you could also just overwrite existing object when rank is better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T09:13:02.863",
"Id": "526363",
"Score": "0",
"body": "Thanks for your response, could you demostrate the single pass option? I tried something like that but when it overwrites I always ended up with the last rank."
}
] |
[
{
"body": "<p>To do the job in a single pass you can do it like this:</p>\n<pre><code>const preferedDomain = 'prefered'\n\nconst data = [\n { keyword: 'hey', domain: 'apple', rank: 1},\n { keyword: 'hey', domain: 'apple', rank: 2},\n { keyword: 'hey', domain: 'prefered', rank: 46},\n\n { keyword: 'foo', domain: 'amazon', rank: 1},\n { keyword: 'foo', domain: 'amazon', rank: 2},\n { keyword: 'foo', domain: 'amazon', rank: 3},\n\n { keyword: 'bla', domain: 'prefered', rank: 1},\n { keyword: 'bla', domain: 'prefered', rank: 2},\n { keyword: 'bla', domain: 'prefered', rank: 3}\n]\n\nconst res = Object.values(\n data.reduce((acc, obj) => {\n const best = acc[obj.keyword]\n if (best) {\n const bestDomainIsPrefered = best.domain === preferedDomain\n const objDomainIsPrefered = obj.domain === preferedDomain\n if (\n (objDomainIsPrefered && !bestDomainIsPrefered)\n ||\n (objDomainIsPrefered === bestDomainIsPrefered && obj.rank < best.rank)\n ) {\n acc[obj.keyword] = obj\n }\n } else {\n acc[obj.keyword] = obj\n }\n return acc\n }, {})\n)\n\nconsole.log(res)\n</code></pre>\n<p>Also it might be worth to sacrifice a little performace using a foreach for the sake of readability... Even a Map instead of plain object could help here.</p>\n<pre><code>const map = new Map()\nfor (const obj of data) {\n const best = map.get(obj.keyword)\n if (!best || ...) {\n map.set(obj.keyword, obj)\n }\n}\n\nreturn [ ...map.values() ]\n</code></pre>\n<p>On other hand if you are obsessed with performance, you might want to avoid comparing the <code>best.domain</code> to <code>preferedDomain</code> more then once by storing the <code>objDomainIsPrefered</code> into the map along with the object. But I'm not sure at what point, if at all, the gain would overcome the loss for having to create more objects.</p>\n<pre><code>const map = new Map()\nfor (const obj of data) {\n const best = map.get(obj.keyword)\n if (!best || ...) {\n map.set(obj.keyword, { obj, isDomainPrefered: objDomainIsPrefered })\n }\n}\n\nreturn [ ...map.values() ].map((envelope) => envelope.obj)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T14:02:31.013",
"Id": "526377",
"Score": "0",
"body": "Thanks, what does `if (!best || ...)` means? I get an error with that: `SyntaxError: Unexpected token '...'`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T19:05:32.903",
"Id": "526405",
"Score": "0",
"body": "@Álvaro hehe thats Just a placeholder for the conditions from the first snippet. I didn't want to write them again..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T12:09:39.147",
"Id": "266443",
"ParentId": "266415",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T09:35:58.967",
"Id": "266415",
"Score": "1",
"Tags": [
"javascript",
"object-oriented",
"array"
],
"Title": "Best way to cherry pick objects from array of objects"
}
|
266415
|
<p>In order to add basic translation capabilities in an old c++98 program
I've come up to a basic and shameless code summarized by this
<a href="https://gcc.godbolt.org/z/GPT15751z" rel="nofollow noreferrer">snippet</a>:</p>
<pre><code>#include <string>
#include <iostream>
// Translation ids
enum
{
TR_RELOAD =0,
TR_SAVE,
TR_MSGWARNRESET,
TR_MSGAPPLYCHANGES
};
// (Returning an array reference)
const std::string (&resolve_translation(const std::string& lang))[]
{
static const std::string tr_en[] =
{
"Reload", // TR_RELOAD
"Save", // TR_SAVE
"Current values will be lost, are you sure?", // TR_MSGWARNRESET
"Apply changes to material %s?" // TR_MSGAPPLYCHANGES
};
static const std::string tr_it[] =
{
"Ricarica", // TR_RELOAD
"Salva", // TR_SAVE
"I valori correnti saranno persi, sei sicuro?", // TR_MSGWARNRESET
"Applicare modifiche al materiale %s?" // TR_MSGAPPLYCHANGES
};
static const std::string tr_es[] =
{
"Recargar", // TR_RELOAD
"Salvar", // TR_SAVE
"Los valores actuales se perderán, está seguro?", // TR_MSGWARNRESET
"¿Aplicar cambios al material %s?" // TR_MSGAPPLYCHANGES
};
static const std::string tr_fr[] =
{
"Recharger", // TR_RELOAD
"Enregistrer", // TR_SAVE
"Les valeurs actuelles seront perdues, êtes-vous sûr?", // TR_MSGWARNRESET
"Appliquer les modifications au matériau %s?" // TR_MSGAPPLYCHANGES
};
if(lang=="en") return tr_en;
if(lang=="it") return tr_it;
if(lang=="fr") return tr_fr;
if(lang=="es") return tr_es;
return tr_en; // default
}
int main()
{
std::string lang = "it"; // unknown at compile time
const std::string (&tr)[] = resolve_translation(lang);
std::cout << tr[TR_RELOAD] << '\n';
std::cout << tr[TR_MSGWARNRESET] << '\n';
}
</code></pre>
<p>The usage is cumbersone because needs a local call to <code>resolve_translation</code>,
however I can compile it in bcc and g++ and is working,
but I'm not sure why does not compile with clang and msvc,
I fear that there's some major problem under the rug.</p>
<p>I'm seeking some advices to improve it.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T15:16:47.490",
"Id": "526327",
"Score": "0",
"body": "I'm sure Clang and MSVC give some kind of error message and location, right? You might include that detail so someone might be able to tell you want it means."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T15:50:22.863",
"Id": "526330",
"Score": "0",
"body": "@JDługosz Yes! I didn't want to stuff too many things, but opted to include the compiler explorer link exactly for that reason"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T19:40:57.020",
"Id": "526407",
"Score": "0",
"body": "I didn't follow the link; assumed it was a Stack Exchange _snippet_ that was equivalent to the listing with maybe some boilerplate that's not shown below."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T07:48:42.573",
"Id": "526431",
"Score": "1",
"body": "GCC shows the same error when invoked in a standards-conformant mode: `g++ -std=c++98 -Wpedantic -Wall -Wextra` - \"_warning: conversions to arrays of unknown bound are only available with `-std=c++2a` or `-std=gnu++2a`_\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T15:15:30.507",
"Id": "526627",
"Score": "0",
"body": "You must not edit the code in a Code Review after it has been posted and answered. If you have a new revision, you can post it in another Question, and refer back to this one, and you can edit this one to note that there is a newer one too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T15:55:35.303",
"Id": "526629",
"Score": "0",
"body": "@JDługosz Even though the changes are just aesthetic and don't affect the replies?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T16:04:10.770",
"Id": "526630",
"Score": "0",
"body": "@MatG yes, I've gotten rolled back for adding whitespace and fixing typos in comments! In general, we can't tell that the changes are cosmetic, and even if they are that might have been mentioned in an answer."
}
] |
[
{
"body": "<p>Improvements:</p>\n<p>The return type is strange and awkward enough that it needs a comment to explain it! What benefit does returning a reference to an array have over simply returning a pointer to the first element?</p>\n<p>It would be <em>better</em> to return an object. It might simply contain a pointer and length, but it means you could update it to support dynamically loaded tables or other new features, and do error checking on the <code>operator[]</code>, and use a strong type for the subscript as well (that is, it requires the enumeration constant, not just any old integer).</p>\n<p>Building an array of <code>std::string</code> is inefficient since it copies all of the literals into the <code>string</code> object at run time. If you're compiling as C++98 you don't have <code>string_view</code> built in, but you could supply your own as part of the program, or make it an array of plain <code>char*</code> instead. I guess it depends on how the return values are being used: if it repeatedly needs to convert that to a <code>string</code> you'd rather have it done and remembered. But you don't need to copy and consume memory for all the unused tables. That's another reason to make it an abstract object, as it can be optimized and improved "under the hood" later without changing the usage.</p>\n<h1>the compiler error</h1>\n<blockquote>\n<p>reference to incomplete type 'const std::string []' could not bind to an lvalue of type 'const std::string [4]'</p>\n</blockquote>\n<p>The function's type is declared without bounds. It's not like an initializer where the actual array in the <code>return</code> statement will inform it; though apparently g++ accepts that as an extension (sort of an implicit partial <code>auto</code>). From <a href=\"https://en.cppreference.com/w/cpp/language/array#Arrays_of_unknown_bound\" rel=\"nofollow noreferrer\">cppreference</a>: (emphasis mine)</p>\n<blockquote>\n<p>If expr is omitted in the declaration of an array, the type declared is "array of unknown bound of T", which is a kind of incomplete type, <strong>except when used in a declaration with an aggregate initializer</strong>.<br />\n⋮<br />\nReferences and pointers to arrays of unknown bound can be formed, <strong>but cannot be initialized or assigned from arrays and pointers to arrays of known bound</strong>.</p>\n</blockquote>\n<p>Your code is actually illegal in standard C++.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T06:02:01.593",
"Id": "526352",
"Score": "1",
"body": "All your points make sense, I'll consider each one to straighten up this mess."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T07:44:17.617",
"Id": "526430",
"Score": "1",
"body": "The return type \"needs a comment\" - or perhaps a name? Giving it a name leads naturally towards the next paragraph, a user-defined object type."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T09:09:46.447",
"Id": "526438",
"Score": "0",
"body": "@TobySpeight In other words, a `typedef` would improve the readability, that's a valuable observation. Specifying also the array size would make the code more conformant. I'll try to smooth the rough edges keeping the runtime overhead as minimum ad possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T10:05:00.207",
"Id": "526443",
"Score": "0",
"body": "@MatG, does C++98 not have `using`? If not, then `typedef` would have to do."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T15:23:50.987",
"Id": "266425",
"ParentId": "266416",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "266425",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T09:39:42.130",
"Id": "266416",
"Score": "0",
"Tags": [
"c++",
"strings",
"static",
"c++98"
],
"Title": "Improving poor man's translations mechanism in c++98 program"
}
|
266416
|
<p>I'm using this function to read a certain set of data in a hidden <code>Sheet1</code> to do encryption based on the selection by the user. It's all working fine, but its kinda slow, I need to apply this to 160.000 rows.</p>
<p>ATM it goes through every letter of every word of every selected range.</p>
<p>(Function below is used to encrypt letters, based on the "data set" in the hidden <code>Sheet1</code>.)</p>
<pre><code>Public Function enc_Letter(mtext As String)
Dim mChr As String
Dim mResult As String
For i = 1 To Len(mtext)
mChr = Mid(mtext, i, 1)
For j = 1 To 53
If j = 53 Then
mResult = "Encryption_Error"
GoTo err
End If
If mChr = Sheet1.Cells(j, 1) Then
mResult = mResult & Sheet1.Cells(j, 2)
Exit For
End If
Next j
Next i
err:
enc_Letter = mResult
End Function
</code></pre>
<p>Edit: I have added the Sub mabye this helps in finding a solution:</p>
<pre><code>Sub LetEnc()
Dim mrange As Range
Dim mtext As String
On Error GoTo errHandler
Set mrange = Application.InputBox("Select cells to encrypt", , , , , , , 8)
If Not mrange.HasFormula Then
mrange.Value = Trim(mrange.Value)
End If
errHandler:
If err.Number = 424 Then
Exit Sub
End If
Dim ss As Range
For Each ss In mrange
ss.NumberFormat = "@"
mtext = ss.text
ss = enc_Letter(mtext)
Next ss
End Sub
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T11:50:15.617",
"Id": "526309",
"Score": "1",
"body": "Welcome to Code Review. What do you mean with 160k rows? Calling this method 160k times?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T11:52:34.000",
"Id": "526310",
"Score": "0",
"body": "160.000 records in excel. So Im using this code to encrypt a large amount of records (rows) in Excel. Sometimes I also select a large selection to use it. https://www.google.nl/search?q=excel+row&source=lnms&tbm=isch&sa=X&ved=2ahUKEwjBkKPnz87yAhUhgP0HHXeYBcAQ_AUoAXoECAEQAw&biw=1664&bih=937#imgrc=wl8yw4OFCOp68M"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T12:21:27.053",
"Id": "526316",
"Score": "1",
"body": "Is this encryption just substituting a character by a different character? Are the values for 1<j<53 in Sheet1.Cells(j, 1) all unique and as well in Sheet1.Cells(j, 2)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T12:46:47.433",
"Id": "526317",
"Score": "0",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T18:01:22.327",
"Id": "526337",
"Score": "3",
"body": "That's not encryption. Rule #1 of encryption is to never attempt to invent your own algorithm unless you are in to high level maths. You can leverage known encryption libraries. See [this question](https://stackoverflow.com/questions/3038504/aes-encrypting-a-microsoft-access-field-via-vba) for a discussion on the topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T21:24:58.697",
"Id": "526341",
"Score": "0",
"body": "@Heslacher Yes it is!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T06:59:58.177",
"Id": "526355",
"Score": "1",
"body": "@HackSlash `That's not encryption.` is incorrect. See https://en.wikipedia.org/wiki/Substitution_cipher . It is just a weak encryption. Nevertheless you are correct about the rest of your statement."
}
] |
[
{
"body": "<p>If I assume correctly you have in Sheet1 something like below:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Column 1 | Column 2 \na | x \nb | c \nc | k \n</code></pre>\n<p>then you can take advantage of an <a href=\"https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/dictionary-object\" rel=\"nofollow noreferrer\">dictionary-object</a> by filling this dictionary-object once like so (keep in mind that my vba/vb knowledge is very rusty)</p>\n<pre><code>'declare at class/module level\nDim dict As New Scripting.Dictionary\n\nPrivate Sub FillSubstitutionDictioanry()\n For j = 1 To 52\n dict.Add Sheet1.Cells(j, 1), Sheet1.Cells(j, 2)\n Next j\nEnd Sub\n</code></pre>\n<p>which can be used in your function like so</p>\n<pre><code>Public Function enc_Letter(mtext As String) as String\n \n Dim mChr As String\n Dim mResult As String\n \n For i = 1 To Len(mtext)\n \n mChr = Mid(mtext, i, 1)\n if dict.Exists(mChr) then\n mResult = mResult & dict.Item(mChar)\n Else\n enc_Letter = "Encryption_Error"\n Exit Function\n End If\n Next i\n enc_Letter = mResult\n \nEnd Function\n</code></pre>\n<p><strong>Edit</strong></p>\n<p>Like I said, my vba is very rusty.</p>\n<p>First, you should always place <code>Option Explicit</code> at the top of each module/class you use.<br />\nSee <a href=\"https://stackoverflow.com/a/10238790/2655508\">What are the pros to using “option explict”</a></p>\n<blockquote>\n<p>Yes, it will prevent some types of mistakes. One of the most obvious\nones is if you make a typo and spell the variable name incorrectly, it\nwill flag that the mistyped variable doesn't exist.</p>\n</blockquote>\n<p>It then would have been obvious that in the line <code>mResult = mResult & dict.Item(mChar)</code> the variable <code>mChar</code> would be unkown.</p>\n<p>My mistake had also been that adding to a dict like <code>dict.Add Sheet1.Cells(j, 1), Sheet1.Cells(j, 2)</code> would not add the value of these cells but the cells itself.</p>\n<p>So I have cleaned this up, like so</p>\n<pre><code>Option Explicit\nDim dict As New Scripting.Dictionary\nDim dictionaryIsFilled As Boolean\n\nPrivate Sub FillSubstitutionDictioanry()\n If dictionaryIsFilled Then Exit Sub\n\n Dim j As Integer\n For j = 1 To 52\n dict.Add Sheet1.Cells(j, 1).value, Sheet1.Cells(j, 2).value\n Next j\n \n dictionaryIsFilled = True\n \nEnd Sub\nPublic Function enc_Letter(mtext As String) As String\n \n FillSubstitutionDictioanry\n \n Dim mChr As String\n Dim i As Integer\n \n For i = 1 To Len(mtext)\n \n mChr = Mid(mtext, i, 1)\n If dict.Exists(mChr) Then\n enc_Letter = enc_Letter & dict(mChr)\n Else\n enc_Letter = "Encryption_Error"\n Exit Function\n End If\n \n Next i\n \nEnd Function\n</code></pre>\n<p>which can be called just from your <code>LetEnc</code> sub. The dictionary is only initialized once.</p>\n<p>Make sure to have a reference to <code>Microsoft Scripting Runtime</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T21:25:42.340",
"Id": "526342",
"Score": "0",
"body": "I have put the first part into a module and the second code I replaced with my own it doesn't replace te letters anymore with the second new code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T21:28:53.603",
"Id": "526343",
"Score": "0",
"body": "With the dictionary-object I basically build what I have in Sheet1 in code right? Using the dictionary-object is that what you mean? Because I did not do that (yet)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T06:55:32.930",
"Id": "526354",
"Score": "0",
"body": "The dictionary object contains the values of the first column for rows 1..52 as dictionary-keys and the values of the second column for rows 1..52 as dictionary-valus. I have edited the answer to show where the mistakes had been. This is tested at least for my workbook."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T08:53:19.050",
"Id": "526360",
"Score": "0",
"body": "thanks I do have one question more so as you already suspected Sheet1 looks like you assumed, but I do have a column 3 and 4 with the numbers inside from 1 to 10. I'm trying to use your code with the number encryption but I keep getting this error: This key is already associated with an element of this collection (Error 457). I suspect because sheet1 is already used? How can I solve this to use the same collection but with column 3 and 4?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T09:06:34.753",
"Id": "526362",
"Score": "0",
"body": "Just use a second dictionary. I assume you do a loop from 1..10 having as keys 0,1,2,3...9 and the values distributed different."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T10:48:47.590",
"Id": "526372",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/129005/discussion-between-ulquiorra-schiffer-and-heslacher)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T12:33:48.630",
"Id": "526374",
"Score": "0",
"body": "FWIW I think this substitution dictionary could be implemented even more cleanly as a Static Function which returns the dictionary from a private variable and fills it if that variable was Nothing. That gets rid of the global dict and Boolean variable. The one drawback is if the cache becomes invalid, because the mapping in the worksheet is changed, then it's a little tricky to clear the private static variable. But your current method also suffers from cache invalidation so I think the trade-off makes sense."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T14:46:29.567",
"Id": "526378",
"Score": "0",
"body": "All resolved in chat! Thanks everybody!"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T12:35:52.397",
"Id": "266420",
"ParentId": "266418",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "266420",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T11:06:49.003",
"Id": "266418",
"Score": "1",
"Tags": [
"performance",
"vba",
"excel"
],
"Title": "Simple encryption function for Excel sheets"
}
|
266418
|
<p>Here's a proposal implementation of websocket using <code>boost::asio::beast</code> that is thread-safe to parallel writes.</p>
<p>In this example below, the <code>async_write</code> can be triggered in response to server notification (I) or from periodic keepalive calls implemented on a dedicated thread (II).
I'd like to here your comments regarding my implementation and especially to the use of <code>strand</code> in order to serialize the async_writes and make them thread-safe.</p>
<p>Thanks !</p>
<pre class="lang-cpp prettyprint-override"><code>
#pragma once
#include <memory>
#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/asio/strand.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/beast/http.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/asio/io_service.hpp>
#include <functional>
#include <iostream>
#include <string>
#include <mutex>
#include <thread>
#include <cstdlib>
class ServerCommunication {
public:
explicit ServerCommunication(const char *host, const char *port);
void Stop();
void Run(std::vector<std::thread> &v);
void Send(std::string data);
private:
void ConnectAndListen(const boost::asio::yield_context &yield);
void SenderService(const boost::asio::yield_context &yield);
bool is_connected_ = false;
std::string ip_;
std::string port_;
boost::asio::io_context io_context_;
void on_write(boost::system::error_code ec, std::size_t bytes_transferred);
boost::asio::strand<boost::asio::io_context::executor_type> strand_;
boost::beast::websocket::stream<boost::beast::tcp_stream> ws_;
boost::beast::error_code ec_;
void fail(char const* op) { std::cerr << op << ": " << ec_.message() << "\n"; }
};
ServerCommunication::ServerCommunication(const char *ip, const char *port)
: ip_(ip), port_(port) , ws_(io_context_) , strand_(boost::asio::make_strand(io_context_)) { }
void ServerCommunication::Stop() {
boost::asio::spawn(
io_context_,
[this](const boost::asio::yield_context &yield) {
ws_.async_close(boost::beast::websocket::close_code::normal, yield[ec_]);
if(ec_) {
return fail("close");
}
});
io_context_.stop();
}
void ServerCommunication::ConnectAndListen(const boost::asio::yield_context &yield) {
boost::beast::get_lowest_layer(ws_).expires_after(std::chrono::seconds(30));
boost::asio::ip::tcp::resolver resolver(io_context_);
auto const results = resolver.async_resolve(ip_, port_, yield[ec_]);
auto ep = boost::beast::get_lowest_layer(ws_).async_connect(results, yield[ec_]);
if(ec_) return fail("connect");
// Update the host_ string. This will provide the value of the
// Host HTTP header during the WebSocket handshake.
// See https://tools.ietf.org/html/rfc7230#section-5.4
auto address = ip_ + std::to_string(ep.port());
// Turn off the timeout on the tcp_stream, because
// the websocket stream has its own timeout system.
boost::beast::get_lowest_layer(ws_).expires_never();
// Set suggested timeout settings for the websocket
ws_.set_option(
boost::beast::websocket::stream_base::timeout::suggested(
boost::beast::role_type::client));
// Set a decorator to change the User-Agent of the handshake
ws_.set_option(boost::beast::websocket::stream_base::decorator(
[](boost::beast::websocket::request_type& req)
{
req.set(boost::beast::http::field::user_agent,
std::string(BOOST_BEAST_VERSION_STRING) +
" websocket-client-me");
}));
// Perform the websocket handshake
ws_.async_handshake(address, "/ws", yield[ec_]);
if(ec_) return fail("handshake");
is_connected_ = true;
for (;;) {
boost::beast::flat_buffer buffer;
// Read a message into our buffer
ws_.async_read(buffer, yield[ec_]);
if(ec_) return fail("read");
std::cout << boost::beast::make_printable(buffer.data()) << std::endl;
//### The first async_write is triggered from incoming server data (I).
Send("Ack");
}
}
void ServerCommunication::Run(std::vector<std::thread> &v) {
boost::asio::spawn(io_context_,
[this](const boost::asio::yield_context &yield) {
this->ConnectAndListen(yield);
});
v.emplace_back([this] {
this->io_context_.run();
});
}
void ServerCommunication::on_write(
boost::system::error_code ec,
std::size_t bytes_transferred)
{
}
void ServerCommunication::Send(std::string data) {
ws_.async_write(boost::asio::buffer(data),
boost::asio::bind_executor(strand_, [this] (boost::system::error_code ec,
std::size_t bytes_transferred)
{ this->on_write(ec, bytes_transferred);}));
if(ec_) { fail("write"); }
}
int main() {
std::vector<std::thread> v;
v.reserve(1);
// Connect to local server that listen to arbitrary port 44444
ServerCommunication serverCommunication_("0.0.0.0" , "44444");
serverCommunication_.Run(v);
sleep(5);
std::thread t([&] () {
for (;;) {
sleep(1);
// ### this will simulate the on-demand async_writes (II).
serverCommunication_.Send("ZZZZZ");
}
});
t.join();
return 0;
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T13:44:25.450",
"Id": "266423",
"Score": "2",
"Tags": [
"c++",
"asynchronous",
"boost",
"websocket"
],
"Title": "Implement Websocket using boost::asio::beast with serialized writes"
}
|
266423
|
<pre><code>void largest_row(void)
{
int largest_row, temp = 0, sum = 0;
for (int i = 0; i < row_count; i++)
{
for (int j = 0; j < row_count; j++)
{
sum += array[i][j]; //Array referenced here is globally defined
if (sum > temp)
{
largest_row = i;
}
temp = sum;
}
}
printf("%i\n", largest_row);
return;
}
</code></pre>
<p>The function <code>largest_row()</code> prints the index number of the row in a 2d array having the largest sum.</p>
<p>In what areas could my code or algorithm be improved (e.g. a recursive implementation)? I think there is a better way, and I want to get exposed to well-designed code and more efficient algorithms as I continue to learn to program.</p>
<p>As of now, I think I depend too much on loops and that limits my programming experience. Is it even right to think that way? For reference, and if you guys are familiar, I'm currently in week 3 of CS50x (infamous Tideman problem). I'm almost done with it but I want my code to be better. That's the goal of my question at least if any of these is too vague already.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T19:06:55.237",
"Id": "526338",
"Score": "1",
"body": "The code doesn't work as intended. If the array is {{2,2},{1,1}}, it says row 1 ({1,1}) is the largest."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T07:23:09.987",
"Id": "526426",
"Score": "1",
"body": "Next time you post, you can make life easier for reviewers by showing a _complete_ program (with all the necessary `#include` lines, variable definitions, and a `main()` that exercises the function). [Don't edit the code](/help/someone-answers) now that you have answers here, but consider that for future review requests, as that will likely attract better responses."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T10:15:15.157",
"Id": "526444",
"Score": "0",
"body": "this site is for code review of working code. The posted code does not compile! and has a logic flaw."
}
] |
[
{
"body": "<p>Unless we're told the array is a <em>square</em> array, we have a bug. I'm guessing that should be <code>j < column_count</code> (or whatever the appropriate global is called, since you haven't shown the declarations).</p>\n<p>We have another bug where we update the <code>largest_row</code> before we have finished adding values from the row. It's possible that the rest of the elements are sufficiently negative that this isn't the largest row so far, after all - leave the <code>sum > temp</code> test until the <code>j</code> loop is finished.</p>\n<p>It would be better to accept the array and dimensions as arguments, and return the result, rather than reading from global variables and writing output directly. For larger programs, we tend to want functions with a single responsibility, so that we can compose programs from the individual pieces.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T15:55:31.920",
"Id": "266426",
"ParentId": "266424",
"Score": "1"
}
},
{
"body": "<h2>Some guess</h2>\n<p>The code you provide is missing important information that we must guess.</p>\n<p>Being a programmer means being able to present the problem and the solution without ambiguity. Here is one important and some pedantic ambiguities listed.</p>\n<ul>\n<li><p>What type are the items referenced by <code>array</code>?</p>\n<p>We can assume they are <code>int</code> but depending on the compiler settings your code could still work for other types. The problem may be hidden behind warnings that we can not see.</p>\n<p>If for example the array contains <code>unsigned int</code> then adding what is a positive value (in the array) can be subtracted if the top bit is 1</p>\n</li>\n<li><p>What is <code>row_count</code>, is it a static typed value, a defined value (has no type), or ...?</p>\n</li>\n<li><p>You provided no library references, eg <code>#include <stdio.h></code> Yes it is a very standard include associated with <code>printf</code> but we are still left to guess this is a fact.</p>\n</li>\n</ul>\n<h2>Rewrite</h2>\n<p>Taking your code at face value</p>\n<h3>Two bugs</h3>\n<ol>\n<li><p>Sum will <code>sum</code> all rows as you do not reset its value for each row.</p>\n</li>\n<li><p>The max value <code>temp</code> is initialized with the wrong value. It should have the lowest possible value. That means that <code>largest_row</code> may never get a value.</p>\n<p>Depending on the compiler setting what is printed could be a random value, or zero.</p>\n</li>\n</ol>\n<h3>Poor design</h3>\n<p>The code is inefficient and the naming is poor.</p>\n<ul>\n<li><p><code>largest_row</code> is a function so give it a capital <code>Largest_row</code></p>\n</li>\n<li><p><code>largest_row</code> is not what the function does. It prints the index of the largest row. Using <code>PrintIdxLargestRowSum</code> would be better however it is too long. If we make the function return the largest row, the name could be <code>IdxLargestSum</code></p>\n</li>\n<li><p>It is a little odd as you are checking for a max value as you are summing the row.</p>\n<p>First sum the row, then check for the max value.</p>\n</li>\n<li><p>Keep variables scoped as close as possible to the code they are used in. Declare sum inside the first loop.</p>\n</li>\n</ul>\n<p>Using your code as a template we get</p>\n<pre><code>// Assumes global row_count > 0\nint Idx_largest_row(void) {\n int idx, max;\n for (int i = 0; i < row_count; i++) {\n int sum = 0\n for (int j = 0; j < row_count; j++) {\n sum += array[i][j]; \n }\n if (i == 0 || (i > 0 && sum > max)) {\n max = sum;\n idx = i;\n }\n }\n return idx;\n}\n\n// use as\nprintf("%i\\n", Idx_largest_row());\n</code></pre>\n<h2>Example</h2>\n<p>The above rewrite is still rather poor in my view.</p>\n<ul>\n<li><p>There should be two functions, one to sum a row the other to find the max sum.</p>\n</li>\n<li><p>The array and row counts should be an argument</p>\n</li>\n<li><p>The inner arrays should be of defined length</p>\n</li>\n</ul>\n<pre><code>#include <stdio.h>\n\n#define COL_COUNT 5\n#define uint unsigned int\n\nint rows[][COL_COUNT] = {\n {10, 2, 320, 344, -130},\n {30, 12, 330, 444, -160},\n {100, 2, 123, 207, 50},\n {102, 82, 530, 544, -150},\n {103, 72, 730, 444, -140}\n};\n\nint SumRow(int *row, uint count) {\n int sum = 0;\n for (uint i = 0; i < count; i++) { sum += row[i]; }\n return sum;\n}\nuint LargestRowIdx(int rows[][COL_COUNT], uint rowCount) {\n uint idx = 0;\n int max = SumRow(rows[0], COL_COUNT);\n for (uint i = 1; i < rowCount; i++) {\n int sum = SumRow(rows[i], COL_COUNT);\n if (sum > max) { \n max = sum; \n idx = i;\n }\n }\n return idx;\n}\n\nvoid main() {\n printf("Index of largest sum: %u\\n", LargestRowIdx(rows, 5));\n return;\n}\n</code></pre>\n<p><sub> <strong>Note</strong> that the number of rows is a magic number <code>5</code>, however you should use a defined value or variable</sub></p>\n<p><sub> <strong>Note</strong> I use <code>unsigned int</code> when indexing and rather than have to type all that I use the the defined <code>#define uint unsigned int</code>. There is no reason you can not use an <code>int</code> for indexes</sub></p>\n<p><sub> <strong>Note</strong> I use <code>camelCase</code> names rather than <code>snake_case</code>. Which to use is up to you</sub></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T08:55:12.520",
"Id": "526361",
"Score": "1",
"body": "Why do you use PascalCase for your function names? That's very unidiomatic in C."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T09:56:28.227",
"Id": "526368",
"Score": "0",
"body": "You may use ìnt max = INT_MIN` from `limits.h` and then start iteration on index 0."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T13:21:13.913",
"Id": "526375",
"Score": "0",
"body": "Why `#define uint unsigned int` instead of `typedef unsigned uint;`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T17:39:36.803",
"Id": "526393",
"Score": "1",
"body": "@TobySpeight I find the more compact camelCase and PascalCase easier to read and more congruent with modern languages. Idiomatic C is very old school and I feel without people actively pushing a change, nothing will change. Note I did add a note about name style at bottom of answer.,"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T17:43:15.877",
"Id": "526394",
"Score": "0",
"body": "@avans Why add a library when setting `max` to the first sum (example snippet) is simpler."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T17:46:25.780",
"Id": "526396",
"Score": "0",
"body": "@L.F. I don't often post C answers here so playing it safe."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T19:41:05.853",
"Id": "526408",
"Score": "1",
"body": "@Blindman: The library is just a header file and contains compile time macro definitions. Your initialization of max and sum is an unnecessary code repetition and conflicts with D.R.Y. paradigm (don't repeat yourself)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T02:12:06.340",
"Id": "526416",
"Score": "2",
"body": "`#define` is actively discouraged over alternatives such as `typedef`, so it isn't really \"safer\". It is generally recommended to avoid macro names whenever possible (in this case, avoiding `uint` and writing `unsigned` directly might be preferred)."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T19:48:46.883",
"Id": "266432",
"ParentId": "266424",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T15:03:05.887",
"Id": "266424",
"Score": "-1",
"Tags": [
"beginner",
"algorithm",
"c",
"array"
],
"Title": "Find the matrix row having the largest sum"
}
|
266424
|
<p>I'm working on keyboard testing web application. As a mechanical keyboard enthusiast, I need to test that all the keys on my keyboard work whenever I build one, or change the firmware for one. Eventually, I'd also like to implement some typing tests that are similar to <a href="https://monkeytype.com" rel="nofollow noreferrer">MonkeyType</a>. This isn't a particularly new problem that's unsolved, but I thought it was a good chance to learn some Vue and TypeScript.</p>
<p>So far the codebase is only 3 files (that I've added on top of whatever Vue generates), but I have some questions. Full codebase is on <a href="https://github.com/hahuang65/type-test" rel="nofollow noreferrer">GitHub</a> if you'd like to run it</p>
<p>I'm brand new to Vue and TypeScript, so the things I'd like to know are:</p>
<ul>
<li>Am I doing things idiomatically?</li>
<li>Am I sending events from <code>Keyboard</code> to <code>Key</code> in a way that makes sense?
<ul>
<li>This is my biggest question. Coming from other OOP languages, it made sense to make <code>Key</code> it's own component, but I feel like in Vue, there are going to be communication difficulties between <code>Keyboard</code> and <code>Key</code>. It's hard to decide where the state information (such as key position, not implemented yet) should go.</li>
</ul>
</li>
<li>Is there a better way to structure my components, given that I may also need to add more attributes to <code>Key</code> (things such as location on a keyboard grid, size of the button, etc)?</li>
<li>When should I be using <code>setup()</code> vs <code>data()</code> or <code>created()</code> or <code>mounted()</code> etc.
<ul>
<li>It's quite confusing all the different things I've read only for using <code>const state = reactive({...})</code> and <code>...toRefs(state)</code> vs individual <code>ref</code>s vs just using <code>data()</code> etc.</li>
</ul>
</li>
<li>If I'm using TypeScript, should I still be using vanilla Javascript functions like <code>Object.fromEntries()</code>?</li>
</ul>
<p>The 3 files of interest are the following:</p>
<p><code>src/App.vue</code>:</p>
<pre><code><template>
<h1>{{ state.appName }}</h1>
<Keyboard />
</template>
<script lang="ts">
import { defineComponent, reactive } from 'vue';
import Keyboard from "@/components/Keyboard.vue";
export default defineComponent({
name: 'App',
components: { Keyboard },
setup() {
const state = reactive({
appName: "Type Test"
})
return { state }
}
});
</script>
<style>
/* Used by Equal */
@import url("https://fonts.googleapis.com/css?family=Material+Icons|Material+Icons+Outlined");
@import url("https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;900&display=swap");
</style>
</code></pre>
<p><code>src/components/Keyboard.vue</code>:</p>
<pre><code><template>
<div v-on:keyup="keyPressed" class="keyboard" tabindex="0">
<!-- tabindex is set to make the div focus-able, which is required to respond to keypress events -->
<Key v-for="(data, name) in state.keys" :key="name" :name="name" :pressed="data.pressed"/>
</div>
<it-button @click="resetKeys" type="danger">Reset</it-button>
</template>
<script lang="ts">
import { defineComponent, reactive } from 'vue';
import Key from '@/components/Key.vue';
export default defineComponent({
name: "Keyboard",
components: { Key },
setup() {
const state = reactive({
keys: Object.fromEntries(
[
"q",
"w",
"e",
"r",
"t",
"y",
"u",
"i",
"o",
"p",
"[",
"]",
"\\",
"a",
"s",
"d",
"f",
"g",
"h",
"j",
"k",
"l",
";",
"'",
"Enter",
"Shift",
"z",
"x",
"c",
"v",
"b",
"n",
"m",
",",
".",
"/"
].map(name => [name, { pressed: false }])
)
})
return { state }
},
methods: {
keyPressed(event: KeyboardEvent) {
console.log("Pressed: " + event.key);
console.log("Code: " + event.key);
console.log("Location: " + event.location);
if (this.state.keys[event.key]) {
this.state.keys[event.key]['pressed'] = true;
}
event.preventDefault();
},
resetKeys() {
let keys = Object.keys(this.state.keys)
for (let key of keys) {
this.state.keys[key]['pressed'] = false;
}
}
}
});
</script>
</code></pre>
<p><code>src/components/Key.vue</code>:</p>
<pre><code><template>
<it-button class="key" :type="pressed ? 'primary' : ''">
{{ name }}
</it-button>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
name: "Key",
props: {
name: {
type: String,
required: true
},
pressed: {
type: Boolean,
default: false
}
}
});
</script>
<style scoped>
.key {
display: inline-block;
margin: 1px;
}
.key.pressed {
background-color: aquamarine;
}
</style>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T16:56:23.030",
"Id": "266428",
"Score": "2",
"Tags": [
"typescript",
"vue.js"
],
"Title": "Keyboard Tester Web Application in Vue 3 + TypeScript"
}
|
266428
|
<p>I'm writing this as an exercise. I would probably use a vector as a buffer internally (the extra capacity pointer overhead is not important enough). Primarily it's an exercise in writing copy/move constructors and assignment operators.</p>
<p>What are some of the pitfalls of defining these operators explicitly? What could go wrong?</p>
<pre><code>#include <algorithm>
#include <span>
struct header_t { /* some fields... */ };
struct packet_t { /* some fields... */ };
const header_t default_header() { return header_t{ /* some init... */ }; }
class message_combiner {
char* payload{nullptr};
size_t size{0};
public:
std::pair<char*, size_t> get() const { return {payload, size}; };
message_combiner(const std::span<packet_t>& data, const header_t& hdr = default_header())
: size{sizeof(header_t) + data.size() * sizeof(packet_t)}
{
payload = new char[size];
auto hdr_ptr = reinterpret_cast<header_t*>(payload);
*hdr_ptr = hdr;
auto data_ptr = reinterpret_cast<packet_t*>(hdr_ptr + 1);
std::copy(data.begin(), data.end(), data_ptr);
}
message_combiner(const message_combiner& other) { *this = other; }
message_combiner(message_combiner&& other) { *this = other; }
message_combiner& operator=(const message_combiner& other)
{
size = other.size;
payload = new char[size];
std::copy(other.payload, other.payload + size, payload);
return *this;
}
message_combiner& operator=(message_combiner&& other)
{
std::swap(size, other.size);
std::swap(payload, other.payload);
return *this;
}
~message_combiner() { if (payload != nullptr) delete [] payload; }
/// other functions that do useful things
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T19:29:11.140",
"Id": "526339",
"Score": "3",
"body": "This does not compile. You should preferably put up code that's working when you ask for a review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T18:19:56.617",
"Id": "526467",
"Score": "0",
"body": "Hm, I forgot about the “must be part of a **concrete** project” requirement when I reviewed this (I figured a learning project is a project, but this clearly isn’t a *concrete* project). Oh well. But I disagree with the “not working” objection: it’s wrong, for sure, but it could certainly *appear* to be working on many platforms."
}
] |
[
{
"body": "<blockquote>\n<p>What are some of the pitfalls of defining these operators explicitly? What could go wrong?</p>\n</blockquote>\n<p>The best code you can write is no code.</p>\n<p>Every single line of code—every statement, every expression, every single character—introduces potential bugs, and needs to be inspected, tested, or both. The only possible way to have no potential for bugs is to not write any code.</p>\n<p>That is why, whenever it is possible, you should let the compiler generate code for you. In theory, the compiler may have bugs… but even if it does, your final program will have <em>more</em> bugs if it has <em>both</em> the compiler bugs <em>and</em> the bugs you introduce. In practice, the compiler is <em>much</em> more rigorously tested, and regularly reviewed by many, many coders way, <em>way</em> better than you or I ever will be, so it will be a very, <em>very</em> rare thing to discover a bug in the compiler… whereas finding bugs in your own code will happen multiple times every day.</p>\n<p>And, in point of fact, your implementation of these operators is <em>riddled</em> with bugs. Your code would be much better if you’d used something like <code>std::vector</code>, and let the copy/move operations be automatically generated. But even then, there are <em>lot</em> of problems with this class.</p>\n<h1>Code review</h1>\n<pre><code>#include <algorithm>\n#include <span>\n</code></pre>\n<p>You are using <code>std::pair</code>, but missing the <code><utility></code> header.</p>\n<pre><code> char* payload{nullptr};\n</code></pre>\n<p>Okay, let’s set aside that you are using a naked pointer for ownership semantics for now. Even allowing for that, there are still piles of problems here.</p>\n<p>You haven’t given nearly enough information about what this type is really supposed to be about, other than some vague, hand-wavey something-something about putting a header and a variable number of packets in it. What is <code>message_combiner</code> <em>for</em>? What is it supposed to <em>do</em>? Not knowing these things, I am forced to make guesses about what is going on here.</p>\n<p>I see two possibilities for what you are trying to do.</p>\n<ol>\n<li><p>You want to copy the memory representation of a <code>header_t</code> and zero or more <code>packet_t</code> objects into a bunch of bytes. I can’t imagine <em>why</em> you would want to do this… it kinda looks like you might have some sort of data transmission in mind, but this would be <em>wildly</em> unportable. Depending on a lot of factors, not only will it be dangerous to share this data between different computers, it might not even work for sharing data between different processes on the same machine… hell, it might not even work for different processes <em>of the same program</em> compiled with the same compiler.</p>\n</li>\n<li><p>You want to actually create real <code>header_t</code> and <code>packet_t</code> objects in a single memory buffer. There <em>might</em> be good reasons for this, like enforcing memory locality. But that’s more limited than you might think. And a <em>lot</em> harder to do right.</p>\n</li>\n</ol>\n<p>All in all, while what you’re doing <em>looks</em> like an absolutely terrible idea… and completely wrong… because you haven’t given enough information about what it’s supposed to be doing, I can’t be <em>sure</em>.</p>\n<p>So I’ll just accept that you have a legitimate, sensible reason for this type. I seriously doubt you do, but I’ll give you the benefit of the doubt.</p>\n<p>Okay, so you’re copying junk from memory into a byte array. For that, <code>char*</code> is the type you’d use… <em>before</em> C++20.</p>\n<p>You are using C++20. <a href=\"https://en.cppreference.com/w/cpp/types/byte\" rel=\"nofollow noreferrer\">In C++20, there is <code>std::byte</code></a>. This is now the correct type to use for this kind of thing.</p>\n<p>So <em>at the very least</em>, this data member should be:</p>\n<pre><code> std::byte* payload{nullptr};\n</code></pre>\n<p>But this is still terrible. I would refuse this in any of my projects, without even so much as a second glance.</p>\n<p><code>std::vector<std::byte></code> should be your default choice for this, but if you don’t need the resizeability power of <code>std::vector</code>, you could go for <code>std::unique_ptr<std::byte[]></code> instead. You’d have to manually keep track of the size, but if you’re not changing it after initialization, this isn’t a big problem.</p>\n<p>Either way, not using a smart pointer or container of some kind is simply unacceptable in modern C++.</p>\n<pre><code> std::pair<char*, size_t> get() const { return {payload, size}; };\n</code></pre>\n<p>This function smells like a terrible idea. First, is it really necessary to give everyone access to the buffer? Second, if it <em>is</em> necessary… why not use a span?</p>\n<pre><code> message_combiner(const std::span<packet_t>& data, const header_t& hdr = default_header())\n : size{sizeof(header_t) + data.size() * sizeof(packet_t)}\n {\n payload = new char[size];\n auto hdr_ptr = reinterpret_cast<header_t*>(payload);\n *hdr_ptr = hdr;\n auto data_ptr = reinterpret_cast<packet_t*>(hdr_ptr + 1);\n std::copy(data.begin(), data.end(), data_ptr);\n }\n</code></pre>\n<p>Okay, let’s start at the top.</p>\n<p>Never pass view types like <code>std::span</code> by <code>const&</code>. That’s just silly. The whole point of <code>std::span</code> is that it’s a cheap view of a span of data. It’s meant to be copied around. (Hopefully it will be passed in registers, but even if not, it will be passed by-value, avoiding unnecessary indirection, and the compiler can optimize aggressively because it doesn’t need to worry about aliasing.)</p>\n<p>Personally, I am not a fan of default arguments. They cause way more problems than they’re worth. You would do better to have two constructors, with one delegating to the other:</p>\n<pre><code> explicit message_combiner(std::span<packet_t> data)\n : message_combiner(data, default_header())\n {}\n\n message_combiner(std::span<packet_t> data, const header_t& hdr)\n // ...\n</code></pre>\n<p>Note also the <code>explicit</code> there. It’s not clear in your code because of the default arguments, but that constructor is potentially a converting constructor. Those almost always should be marked <code>explicit</code>.</p>\n<p>Okay, now we get to the first UB bug in your code:</p>\n<pre><code> auto hdr_ptr = reinterpret_cast<header_t*>(payload);\n *hdr_ptr = hdr;\n</code></pre>\n<p>So you cast your pointer to a <code>header_t</code> pointer, and then do a copy. The problem? You didn’t make sure that the <em><strong>ALIGNMENT</strong></em> of what <code>payload</code> points to matches the alignment of a <code>header_t</code>. If you’re not lucky, when you try to copy <code>hdr</code> into <code>*hdr_ptr</code>, it’s going to trigger a misaligned data fault, and… crash (if you’re lucky; with UB like this, you could get a whole lot worse than a mere crash).</p>\n<p>The thing is, I don’t even know if aligning the payload properly is the right fix, because I can’t make sense of what you’re trying to do.</p>\n<p>If your goal is <em>just</em> to copy the memory representation of a <code>header_t</code>… then do that. If your goal is to have your <code>payload</code> actually <em>be</em> a <code>header_t</code> (plus other stuff)… for whatever reason… then do that <em>instead</em>. They are two very, very different things.</p>\n<pre><code> auto data_ptr = reinterpret_cast<packet_t*>(hdr_ptr + 1);\n</code></pre>\n<p>Why all the casting and pointer arithmetic? <code>data_ptr</code> is just <code>payload + sizeof(header_t)</code>.</p>\n<p>Now, casting that to a <code>packet_t</code> pointer creates the same problem as above: you haven’t guaranteed that the alignment is correct for <code>packet_t</code>. Which means:</p>\n<pre><code>std::copy(data.begin(), data.end(), data_ptr);\n</code></pre>\n<p>More UB.</p>\n<p>I still don’t know what you think you’re doing here. Either you’re copying the memory representation of these objects into a byte array, or you’re trying to create a single chunk of memory that has an actual <code>header_t</code> followed by zero or more <code>packet_t</code> objects. Either option is… kinda silly, and totally unportable. So I can’t tell which flavour of silly you’re actually going for.</p>\n<p>If you’re copying <em><strong>MEMORY REPRESENTATIONS</strong></em>, then you just have to do:</p>\n<pre><code> // allocate the memory\n //\n // alignment doesn't matter if you're just copying the REPRESENTATIONS\n // of the objects\n payload = new std::byte[sizeof(header_t) + (sizeof(packet_t) * data.size())];\n\n // copy the header representation\n std::copy_n(static_cast<std::byte const*>(&hdr), sizeof(header_t), payload);\n\n // copy the representations of the packets, if any\n //\n // note that we just add the size of the header to skip past it\n std::copy_n(as_bytes(data), sizeof(packet_t) * data.size(), payload + sizeof(header_t));\n</code></pre>\n<p>Simple.</p>\n<p>If you actually want to have <em><strong>ACTUAL OBJECTS</strong></em>… <em>not</em> just representations, but actual objects… things get <em>much</em> trickier.</p>\n<ol>\n<li><p>First, you need to calculate the size of the memory to allocation… and this is <em>not</em> trivial. To calculate the size, you have to:</p>\n<p>a. Start with the size of <code>header_t</code>. That’s the starting value, and the minimum size.\nb. If there are packets, then make sure the current value matches the alignment of <code>packet_t</code>. If not, increase the value until it does.\nc. Now add <code>sizeof(packet_t) * data.size()</code>.</p>\n<p>As you can see, the really tricky part is in the middle, where you have to account for the alignment of <code>packet_t</code>.</p>\n</li>\n<li><p>When you allocate the memory, you need to align it to the alignment of a <code>header_t</code> (because that will be the first object). So something like: <code>payload = new (std::align_val_t{alignof(header_t)}) std::byte[/*size*/]</code>.</p>\n</li>\n<li><p>You can just copy with <code>*static_cast<header_t*>(payload) = hdr</code> because it is now properly aligned.</p>\n</li>\n<li><p>For the packets, you first need to find the offset to the first packet (if any). It’s the same logic as when calculating the size. Once you have the offset of the first packet, you can just do: <code>std::uninitialized_copy(data.begin(), data.end(), static_cast<packet_t>(payload + offset))</code>. Note that you have to use <code>uninitialized_copy()</code>… not <code>copy()</code>. Why? Because <code>copy()</code> only works when you are copying over existing objects. But you don’t have existing objects, you have raw, uninitialized memory.</p>\n</li>\n<li><p>If anything throws an exception, you need to be able to handle it. The most dangerous point is after you have copied the header, because if anything else fails, it’s on you to destroy it.</p>\n</li>\n</ol>\n<p>This might look something like this:</p>\n<pre><code> // allocate the memory\n //\n // alignment DOES matter; payload must be aligned as a header_t\n //\n // packet_offset is just the offset to the first packet, calculated as\n // described above\n if (data.empty())\n payload = new std::byte (std::align_val_t{alignof(header_t)}) [sizeof(header_t)];\n else\n payload = new std::byte (std::align_val_t{alignof(header_t)}) [packet_offset + data.size()];\n\n // if anything after this throws, you need to free the memory\n try\n {\n // copy the header\n *static_cast<header_t*>(payload) = hdr;\n\n // if anything after this throws, you need to destroy the header\n try\n {\n if (not data.empty())\n std::uninitialized_copy(data.begin(), data.end(), static_cast<packet_t*>(payload + packet_offset));\n }\n catch (...)\n {\n std::destroy_at(static_cast<header_t*>(payload));\n }\n }\n catch (...)\n {\n delete[] payload;\n\n throw;\n }\n</code></pre>\n<p>That is <em><strong>UGLY</strong></em>, largely because <code>payload</code> is not a smart pointer.</p>\n<p>Note that if you go this route, you are <em><strong>COMPLETELY</strong></em> responsible for managing the header and packet objects. That means you have to manually delete them in the destructor, manually copy them in the copy constructor, and so on. (If you are just working with representations, you don’t need to worry about that stuff.)</p>\n<pre><code> message_combiner(const message_combiner& other) { *this = other; }\n</code></pre>\n<p>This is a bad way to do copy construction. It is not just misguided, it is inefficient.</p>\n<p>In order to use copy assignment, you must have a fully-constructed object. So if you wanted to do it this way you would first have to properly construct the object… and <em>then</em> do the assignment:</p>\n<pre><code> message_combiner(message_combiner const& other)\n : message_combiner() // default construct this object first\n {\n // now that you have a fully (default) constructed object, you can assign\n *this = other;\n }\n</code></pre>\n<p>Right now, your copy constructor “works” because the member initializers roughly approximate a default consturctor. But that’s just for now… if you change the class, that may no longer be true.</p>\n<p>If you do copy construction this way, you are completely constructing an object… and then immediately obliterating it by copying over it. That’s silly. That’s why C++ coders generally do it the other way around: they write a proper copy constructor, then write copy assignment in terms of that.</p>\n<pre><code> message_combiner(message_combiner&& other) { *this = other; }\n</code></pre>\n<p>All the same problems as the copy constructor, plus more.</p>\n<p>First, that should be a move assignment.</p>\n<p>Second, move ops should be <code>noexcept</code> wherever possible. (And that’s certainly possible here.)</p>\n<pre><code> message_combiner& operator=(const message_combiner& other)\n {\n size = other.size;\n payload = new char[size];\n std::copy(other.payload, other.payload + size, payload);\n return *this;\n }\n</code></pre>\n<p>First, you are failing to delete the existing payload before allocating a new one.</p>\n<p>Second, everything else in the function is wrong, because it should all be more or less identical to regularly constructing the object.</p>\n<p>In theory, copy assignment is just:</p>\n<ol>\n<li>destruction; followed by</li>\n<li>copy constructing over the ashes of the old object.</li>\n</ol>\n<p>That’s the pattern you are attempting to write. But that’s a dangerous pattern, because if anything fails in the second step, you have already destroyed the original. Your object, and likely your program by extension, will now be in a broken state.</p>\n<p>A safer pattern is the copy-and-swap pattern:</p>\n<pre><code> auto operator=(message_combiner const& other) -> message_combiner&\n {\n auto temp = other; // copy\n\n std::ranges::swap(*this, temp); // swap - normally this will be no-fail\n\n return *this;\n }\n</code></pre>\n<p>If the copy fails, then the original object is untouched.</p>\n<p>This is why you should write the copy constructor properly, and then do copy assignment in terms of copy construction… not the other way around.</p>\n<pre><code> message_combiner& operator=(message_combiner&& other)\n {\n std::swap(size, other.size);\n std::swap(payload, other.payload);\n return *this;\n }\n</code></pre>\n<p>This is fine, but it could be <code>noexcept</code>.</p>\n<p>Also, you should really consider writing a swap function, and then writing move assignment (and copy assignment, and move construction) in terms of that. If you do it the way you are doing now, then swapping becomes ridiculously over-complicated. On the other hand, if you write a proper swap, then that will be efficient… and everything that <em>uses</em> swapping will also be.</p>\n<pre><code> ~message_combiner() { if (payload != nullptr) delete [] payload; }\n</code></pre>\n<p>If you are just storing representations of the header and packets, then this is fine.</p>\n<p>But the way you’ve written the code, where you actually create real header and packet objects within the memory <code>payload</code> points to, this is not good enough. If you have real header and packet objects, they need to be destroyed. You can’t just delete the memory out from under them.</p>\n<h1>Summary</h1>\n<p>There is a <em>lot</em> of conceptual confusion here: quite frankly, I don’t think you really know what you’re doing.</p>\n<p>You can’t just copy the memory representation of objects around willy-nilly. This is C++; not C. (And even in C, the way you’re copying representations around would be clumsy and ill-formed.) Objects should be treated like actual objects, not just a bag of bytes in memory. They should be properly constructed, and they should be properly destroyed. Even if the constructor and destructor are no-ops, which is often the case for simple types, you still have to <em>treat</em> them like they do actual stuff.</p>\n<p>So you can’t just allocate a chunk of memory and then copy objects into it. You either have to first initialize that memory properly (by constructing objects in it with placement <code>new</code>, for example), or you have to use the uninitialized memory algorithms (which basically just use placement <code>new</code> or <code>construct_at()</code> under the hood).</p>\n<p>And even if you <em>could</em> just allocate a chunk of memory and copy objects into it, you’d still need to respect things like alignment.</p>\n<p>And <em>even if</em> you managed to fix <em>all</em> the problems here, one way or the other—either by just using memory representations, or by properly initializing real objects in the uninitialized memory and then managing them properly—there doesn’t seem to be any point to it all, because you couldn’t really <em>do</em> anything with the class. It’s useless; the whole idea behind it is misguided. Whether it’s memory representations or actual objects, it won’t work for data transfer, and would be <em>really</em> dodgy for serialization. As I said, I don’t think you really know what you’re doing.</p>\n<p>You said your focus was on the copy and move operations. Well, they’re all wrong, but I can’t even tell you how to fix them properly, because I can’t make sense of what you’re trying to do. But you basically have two options:</p>\n<ol>\n<li><p>If you are just storing the memory representations of a header and a bunch of packets, then your copy/move ops are <em>close</em> to correct. There are some things that need fixing, but you have the general idea right.</p>\n</li>\n<li><p>If you are storing actual objects… then no, all of your copy/move ops are just tragically wrong; not even close to correct. What you would have to do in this case is manually handle the copying/moving of every object in your payload. For example, to copy a <code>message_combiner</code>, you would first have to allocate the same amount of memory, and then manually copy the header, and then manually copy all the packets. And in your destructor, you would have to manually destroy the header, and then manually destroy all the packets, and then free the memory. All of that is a <em>lot</em> of work.</p>\n</li>\n</ol>\n<p>Generally, the copy/move ops should be done like this:</p>\n<pre><code>class whatever\n{\npublic:\n // ... other stuff in the class ...\n\n whatever(whatever const& other)\n {\n // properly copy-construct from other\n }\n\n whatever(whatever&& other) noexcept : whatever{}\n {\n std::ranges::swap(*this, other);\n }\n\n auto operator=(whatever const& other) -> whatever&\n {\n auto temp = other;\n std::ranges::swap(*this, temp);\n return *this;\n }\n\n auto operator=(whatever&& other) noexcept -> whatever&\n {\n std::ranges::swap(*this, other);\n return *this;\n }\n\n friend auto swap(whatever& a, whatever& b) noexcept\n {\n // for each data member:\n std::ranges::swap(a./*...*/, b./*...*/);\n }\n};\n</code></pre>\n<p>You just need to write:</p>\n<ol>\n<li>a proper (cheap, no-fail) default constructor (or properly initialize to some default state in the move constructor before swapping)</li>\n<li>a proper copy constructor; and</li>\n<li>a proper swap function (usually just a bunch of swaps of the data members)</li>\n</ol>\n<p>That’s the general pattern. The only places the details really change are in the copy constructor. Everything else is more-or-less boilerplate.</p>\n<p>If your ultimate goal is to sent messages across the wire, then you are barking up the completely wrong tree. You need to look at <em>proper</em> serialization of types, which is <em>not</em> just <code>memcpy()</code>ing the memory representations.</p>\n<p>I guess the bottom line is this: If you really want to learn how to write proper copy/move operations, you should first start with something that you understand a little better, and write good copy/move ops for <em>that</em>. (And that is not necessarily easy! Writing <em>good</em> copy/move ops can be <em>hard</em>.) Trying to learn how to write good copy/move ops for such a muddled, incoherent idea as this… you’re not helping yourself. Master one thing at a time; start with simple types, and learn how to write copy/move ops for them… and <em>then</em> consider moving on to more complex types, like this… whatever this “<code>message_combiner</code>” is actually supposed to be.</p>\n<h1>Questions</h1>\n<h2>Usage of <code>std::unique_ptr<std::byte[]></code></h2>\n<p><code>std::unique_ptr<std::byte></code> would be a pointer to a single byte:</p>\n<pre><code>auto p = std::unique_ptr<std::byte>{new std::byte{}};\n// or\nauto p = std::unique_ptr{new std::byte{}};\n// or\nauto p = std::make_unique<std::byte>();\n\n// or, if you want default initialization:\nauto p = std::unique_ptr<std::byte>{new std::byte};\n// or\nauto p = std::unique_ptr{new std::byte};\n// or\nauto p = std::make_unique_for_overwrite<std::byte>();\n</code></pre>\n<p>And the usage would be pretty much the same as for any pointer:</p>\n<pre><code>// get the value\nauto val = *p;\n\n// set the value\n*p = std::byte(42);\n\n// and so on\nif (p != nullptr) ...\n</code></pre>\n<p><code>std::unique_ptr<std::byte[]></code> would be a pointer to an array of bytes:</p>\n<pre><code>// allocates an array of 100 value-initialized bytes\nauto p_bytes = std::unique_ptr<std::byte[]>{new std::byte[100]{}};\n// or\nauto p_bytes = std::make_unique<std::byte[]>(100);\n\n// or, if you want default initialization:\nauto p_bytes = std::unique_ptr<std::byte[]>{new std::byte[100]};\n// or\nauto p_bytes = std::make_unique_for_overwrite<std::byte[]>(100);\n</code></pre>\n<p>And the usage would be pretty much the same as for any pointer-to-array:</p>\n<pre><code>// get the 33rd element's value\nauto val = p_bytes[33];\n\n// set the 33rd element's value\np_bytes[33] = std::byte(42);\n\n// get the pointer to the start of the array\nauto p_begin = p_bytes.get();\nauto p_end = p_begin + 100;\n</code></pre>\n<p>Let’s assume <code>payload</code> is defined like this:</p>\n<pre><code>std::unique_ptr<std::byte[]> payload = nullptr;\n</code></pre>\n<p>Then your constructor might look like:</p>\n<pre><code>message_combiner(std::span<packet_t> data, header_t const& hdr = default_header())\n{\n // this could be a private class constant\n constexpr auto packet_offset = /* calculate offset to first packet somehow */;\n\n // determine the size\n if (data.empty())\n size = sizeof(header_t);\n else\n size = packet_offset + (data.size() + sizeof(packet_t));\n\n // allocate (note alignment is handled)\n payload = new (std::align_val_t(alignof(header_t))) std::byte[size];\n\n // if there are any errors after this, no problem, unique_ptr will\n // automatically free the memory\n\n // construct the header\n std::construct_at(static_cast<header_t*>(payload.get()), hdr);\n\n try\n {\n // construct the packets\n std::ranges::uninitialized_copy(data,\n std::span{static_cast<packet_t*>(payload.get() + packet_offset), data.size()});\n }\n catch (...)\n {\n // you have to manually destroy the header\n std::destroy_at(static_cast<header_t*>(payload.get()));\n\n throw;\n }\n}\n</code></pre>\n<p>Which, as you can see, aside from the <code>.get()</code>s, is no different from when <code>payload</code> is a naked <code>std::byte*</code>… except that there’s one less <code>try-catch</code> level, because <code>unique_ptr</code> will automatically clean itself up. (Unfortunately, without something like <code>scope_fail</code>, you can’t avoid the <code>try-catch</code> block to clean up the header.)</p>\n<h2>What does a proper copy constructor look like?</h2>\n<p>The answer depends on your class.</p>\n<p>The general form of the move constructor, move assignment, and copy assignment don’t change from class to class. The default implementations will <em>always</em> be right (though may not be the most efficient, in some rare scenarios, like if you’re expecting a lot of self-assignments… or, of course, if they could have been left default-generated).</p>\n<p>The copy constructor, however, is <em>very</em> specific for each class. If it can’t be default-generated, then it will usually be the hardest part of all the fundamental operations to write.</p>\n<p>For example, in your case, what you’d have to do is:</p>\n<ol>\n<li>allocate the memory (which will be the same size as <code>other</code>’s memory allocation)</li>\n<li><code>std::construct_at()</code> the header as a copy of <code>other</code>’s header; then</li>\n<li><code>std::uninitialized_copy()</code> the packets.</li>\n</ol>\n<p>This is basically the same as the regular constructor. Indeed, you could write the copy constructor as:</p>\n<pre><code>// assuming you have the following member functions:\n// * header(), which returns a const& to the header in the payload\n// * packets(), which returns a span<packet_t> view of the packets, if any\n\nmessage_combiner(message_combiner const& other)\n : message_combiner{other.packets(), other.header()}\n{}\n</code></pre>\n<p>This <em>happens</em> to work well for <em>this</em> class, but for other classes the same pattern will sometimes be very inefficient (or really silly to have a constructor that makes it possible, because it would be exposing internal stuff).</p>\n<h2>Won’t <code>*this = other;</code> get optimized to <code>*this = std::move(other);</code>?</h2>\n<p>No. <code>x = y</code> will <em>never</em> get optimized to <code>x = std::move(y)</code>.</p>\n<p>To see why this would be a terrible idea, imagine if your move constructor wanted to do something with <code>other</code> after the assignment:</p>\n<pre><code>message_combiner(message_combiner&& other) noexcept\n : message_combiner{}\n{\n *this = other;\n\n do_something(other); // oops, other was silently moved away from\n}\n</code></pre>\n<p>Compare that to this:</p>\n<pre><code>message_combiner(message_combiner&& other) noexcept\n : message_combiner{}\n{\n *this = std::move(other);\n\n do_something(other); // other was moved away from... but you can\n // clearly see that, so this mistake is easy to\n // spot\n}\n</code></pre>\n<p>You could argue that the compiler can “see” whether <code>other</code> will be used after the assignment, and if not, then it’s safe to move. But that would be sketchy at least, because moving and copying may do very different things (I mean, you would be foolish if you made a class that did that… but people do a lot of foolish things in C++, and the language and compiler need to account for that). To have exactly the same code do different things depending on stuff that happens <em>elsewhere</em> would be daft (yes, people write code that does that sometimes… but it’s not a good idea).</p>\n<p>You could also think of it like this: moving an object is basically destroying it, so it should <em>never</em> happen invisibly. It should always be crystal clear when you’re ripping the guts out of an object, like with an explicit <code>move()</code>, or when it’s being destroyed anyway, like when you’re returning an object (which can <em>never</em> be used after, so really is safe to always move and never copy).</p>\n<p>To <em>understand</em> what’s happening, remember that the easiest way to distinguish between an lvalue and an rvalue is that if you can take the address of something, it’s an lvalue; if not, it’s an rvalue.</p>\n<p>Can you take the address of <code>other</code>? Of course:</p>\n<pre><code>message_combiner(message_combiner&& other) noexcept\n : message_combiner{}\n{\n if (this != &other) // silly because it will never be false... but you can do it, so it illustrates the point\n *this = other;\n}\n</code></pre>\n<p>Since you can take the address of <code>other</code>, other is an lvalue. So <code>*this = other</code> is an lvalue assignment… that is, a copy assignment.</p>\n<p>(Another trick some people use to distinguish lvalues and rvalues is: if it has a name, it’s an lvalue… otherwise it’s an rvalue. <code>other</code> has a name—that name is “other”—so it’s an lvalue.)</p>\n<p>If you want a move assignment, you need to cast <code>other</code> to an rvalue, which is what <code>std::move()</code> does.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T08:03:28.220",
"Id": "526356",
"Score": "0",
"body": "A few follow ups... could you elaborate on the usage of *std::unique_ptr<std::byte[]>*? what does a proper copy constructor look like? you were pretty explicit with the move ctor. Also, disregarding the other issues, wont **this = other;* get optimized to **this = std::move(other);* anyway?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T19:36:55.900",
"Id": "526473",
"Score": "0",
"body": "The answers take a bit of explanation, so I’ll extend the answer above, and add them there."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T00:06:08.287",
"Id": "266435",
"ParentId": "266430",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "266435",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T19:16:14.880",
"Id": "266430",
"Score": "0",
"Tags": [
"c++",
"reinventing-the-wheel",
"memory-management",
"c++20"
],
"Title": "Writing a buffer that takes a header and a variable number of packets and makes a payload"
}
|
266430
|
<p>I need to manipulate data found in multiple data files (~100,000 files). One single data file has ~60,000 rows and looks something like this:</p>
<pre><code> ITEM: TIMESTEP
300
ITEM: NUMBER OF ATOMS
64000
ITEM: BOX BOUNDS xy xz yz pp pp pp
7.1651861306114756e+02 7.6548138693885244e+02 0.0000000000000000e+00
7.1701550555416179e+02 7.6498449444583821e+02 0.0000000000000000e+00
7.1700670287454318e+02 7.6499329712545682e+02 0.0000000000000000e+00
ITEM: ATOMS id mol mass xu yu zu
1 1 1 731.836 714.006 689.252
5 1 1 714.228 705.453 732.638
6 2 1 736.756 704.069 693.386
10 2 1 744.066 716.174 708.793
11 3 1 715.253 679.036 717.336
. . . . . .
. . . . . .
. . . . . .
</code></pre>
<p>I need to extract the x coordinate of the first 20,000 lines and group it together with the x coordinates found in the other data files.</p>
<p>Here is the working code:</p>
<pre><code>import numpy as np
import glob
import natsort
import pandas as pd
data = []
filenames = natsort.natsorted(glob.glob("CoordTestCode/ParticleCoordU*"))
for f in filenames:
files = pd.read_csv(f,delimiter=' ', dtype=float, skiprows=8,usecols=[3]).values
data.append(files)
lines = 20000
x_pos = np.zeros((len(data),lines))
for i in range(0,len(data)):
for j in range(0,lines):
x_pos[i][j]= data[i][j]
np.savetxt('x_position.txt',x_pos,delimiter=' ')
</code></pre>
<p>The problem is of course the time it will take to do this for all the 100,000 files. I was able to significantly reduce the time by switching from <code>np.loadtxt</code> to <code>pandas.read_csv</code>, however is still too inefficient. Is there a better approach to this? I read that maybe using I/O streams can reduce the time but I am not familiar with that procedure. Any suggestions?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T12:06:44.313",
"Id": "526448",
"Score": "0",
"body": "what do you mean by too inefficient? How long does it take and how much time do you have? How close to the hardware (read limit of your harddrive) are you?"
}
] |
[
{
"body": "<p>Some quick thoughts:</p>\n<p>In <code>pd.read_csv</code> you skip the first 8 rows. But you could also use the <code>nrows</code> parameter to limit to the 20000 first lines in order not to read more lines than necessary. Or an offset of 20000 + 8 if you want.</p>\n<p>The second loop feeds an array, and you save the array to a file at the end (<code>np.savetxt</code>). But why not open the file x_position.txt in write mode at the beginning of the loop, and then write to it directly as you loop on the rows. Feeding the array is overhead. If you're dealing with large files this could make a difference. And if an error occurs in the middle, then you could always discard the file and start again.</p>\n<p>As for the first loop, I would get rid of <code>data.append(files)</code>. Just process the files one by one. Don't build huge lists.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T20:58:41.623",
"Id": "266433",
"ParentId": "266431",
"Score": "6"
}
},
{
"body": "<p>Avoid iterating over rows of a dataframe or array. Avoid copying data.</p>\n<p>Process one file at a time...read then write data for each file. There is no need to build a list of all the data.</p>\n<p>Perhaps use <code>np.loadtxt()</code> instead of <code>pd.read_csv()</code>. Use <code>skip</code> and <code>max_rows</code> to limit the amount of data read and parsed by <code>np.loadtxt()</code>. Use <code>unpack=True</code> and <code>ndmin=2</code> so it returns a row instead of a column. Then <code>np.savetxt()</code> will append a <code>'\\n'</code> after each row.</p>\n<p>Something like this (untested):</p>\n<pre><code>import numpy as np\nimport glob\nimport natsort\n\nwith open('x_position.txt', 'a') as outfile:\n\n filenames = natsort.natsorted(glob.glob("CoordTestCode/ParticleCoordU*"))\n\n for f in filenames:\n data = np.loadtxt(f, skiprows=9, max_rows=20000, usecols=3, unpack=True, ndmin=2)\n\n np.savetxt(outfile, data, fmt="%7.3f")\n</code></pre>\n<p>Presuming the data is stored on hard drives, the average rotational latency for a 7200 rpm hard drive is 4.17ms. 100k files at 4.17ms each is about 417 seconds = almost 7 minutes just to seek to the first sector of all those files. Perhaps using <a href=\"https://docs.python.org/3.9/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor\" rel=\"noreferrer\"><code>concurrent.futures.ThreadPoolExecutor</code></a> would let you overlap those accesses and cut down that 7 minutes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T15:25:31.670",
"Id": "526380",
"Score": "0",
"body": "Thank you so much for the useful reply! However, I read in multiple forums that pandas is way faster than numpy.loadtxt due to the fact that the padas library is built in C. Any specific reason you recommend for switching back to np.loadtxt ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T15:46:39.147",
"Id": "526384",
"Score": "0",
"body": "How would ThreadPoolExecutor get around IO latency? I think it should only help with CPU-bound jobs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T16:20:09.923",
"Id": "526387",
"Score": "0",
"body": "@AlessandroPerego Mostly, I was trying to avoid the need tp copy the data from a DataFrame to an ndarray. Try it both ways and see which is faster."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T16:30:03.930",
"Id": "526388",
"Score": "1",
"body": "@Seb The idea is that when one thread is waiting for IO, another thread can do some non-IO processing. For example, when one thread is waiting for the hard drive to return the next chunk of data, another thread can be parsing a chunk of data it read from a different file. Generally, use threads for IO-bound jobs and processes for CPU-bound jobs, but it depends on the actual workload. Try threads and processes and see which is faster. Another possibility is async using something like the `aiofile` library, but I haven't used it."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T01:35:28.813",
"Id": "266437",
"ParentId": "266431",
"Score": "10"
}
},
{
"body": "<p>On Windows we can speed up iterating over many files by typically 100x by doing a <code>sleep()</code> after every 10 to 100 file reads and allowing the garbage collection time to close unneeded files and free file handles.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T08:28:33.793",
"Id": "526358",
"Score": "5",
"body": "This may be true and helpful, but it would be more of a code review if you refocused it on the code at hand. I.e. point out that it doesn't allow time for garbage collection (preferably with a link to a reference explaining how that works) and show how the code would have to change."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T07:37:56.093",
"Id": "266439",
"ParentId": "266431",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T19:27:10.023",
"Id": "266431",
"Score": "6",
"Tags": [
"python",
"performance",
"python-3.x",
"io"
],
"Title": "Reading 100,000 data files in Python"
}
|
266431
|
<p>I tried speeding up my Graph class, so I removed the Node class and Edge class, and decided to use arrays and <code>ArrayList</code>s. My 2 implementations seem very similar, but for some reason have a 10x performance speed difference that I cannot figure out.</p>
<p>For both of these, the constructor takes N = # nodes, M = # edges, and 2 arrays of length M that represent the endpoints of the edges.</p>
<p>Here is the first one that I found the pseudo-code for online, and implemented myself. Basically, it stores the edges with endpoints, all of them together in one array. Each node stores l and r, which represent the interval of its edges. I suspect this is for better cache performance, because everything is close together in memory.</p>
<pre><code>class Graph1 {
int[] edgeEndpoints;
int[] l, r;
public Graph1(int N, int M, int[] edgeArr1, int[] edgeArr2) {
edgeEndpoints = new int[2*M];
l = new int[N];
r = new int[N];
//calculate d
int[] nodeDegrees = new int[N];
for(int ele : edgeArr1)
{
nodeDegrees[ele]++;
}
for(int ele : edgeArr2)
{
nodeDegrees[ele]++;
}
//similar to N array lists. have a pointer cnt for each node. The interval of each node is already calculated
int[] cnt = new int[N];
l[0] = 0;
r[0] = nodeDegrees[0]-1;
for(int i=1; i<N; i++) {
l[i] = r[i-1] + 1;
r[i] = l[i] + nodeDegrees[i] - 1;
cnt[i] = l[i];
}
for(int i=0; i<N; i++) {
int a = edgeArr1[i];
int b = edgeArr2[i];
edgeEndpoints[cnt[a]] = b;
edgeEndpoints[cnt[b]] = a;
cnt[a]++;
cnt[b]++;
}
}
}
</code></pre>
<p>I thought this was needlessly complicated, so I tried making simple adjacency list implementation:</p>
<pre><code>class Graph2 {
ArrayList<Integer>[] edgeEndpoints;
public Graph2(int N, int M, int[] arr1, int[] arr2) {
edgeEndpoints = new ArrayList[N];
for(int i=0; i<N; i++) {
edgeEndpoints[i] = new ArrayList<>();
}
for(int i=0; i<M; i++) {
int a = arr1[i];
int b = arr2[i];
edgeEndpoints[a].add(b);
edgeEndpoints[b].add(a);
}
}
}
</code></pre>
<p>I then tested both of these with a randomly generated list of edges, with 1 million nodes and 4 million edges. The first version built in ~100ms, while the second one built in ~1500ms. What is causing this huge difference? I suspect it is due to memory access patterns, but even in the first example, some of it is still random.</p>
<p>Also, there might be some formatting errors; I just whipped these up in a few hours. I'm only worried about performance for now, and I will fix the formatting / clean up the code myself later, after I figure out why there is a performance difference.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T01:48:11.677",
"Id": "526349",
"Score": "4",
"body": "It's not always clear to people how this site works. \"I'm only worried about performance for now, and I will fix the formatting / clean up the code myself later\" That's not it. If you put it here for review, any and all aspects of the code are up for review. We're not really a \"call your shot\" kind of site. \"Questions\" here are simply the code that you want reviewed. \"Answers\" are reviews. Unlike other sites, you don't ask questions that you want answered, even though we use the same format. Code Review is not really a Q&A site."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T06:46:37.603",
"Id": "526353",
"Score": "1",
"body": "While formatting problems may not matter to you, they make the actual review more difficult because the code is less readable than it should be. So it comes out as a bit arrogant when you skip the work that you know that you should have done and thus make the volunteers work harder for you."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-26T21:31:39.050",
"Id": "266434",
"Score": "1",
"Tags": [
"java",
"performance",
"comparative-review",
"graph"
],
"Title": "Graph stored as adjacency list or as endpoints and intervals"
}
|
266434
|
<pre><code>const {body} = require('express-validator/check');
exports.hasName = body("name")
.isLength({min: 5})
.withMessage("Name is required. Min Length 5 characters")
</code></pre>
<p>This is my validator.js file</p>
<pre><code>const { validationResult } = require("express-validator/check");
module.exports = req => {
const validationErrors = validationResult(req);
if(!validationErrors.isEmpty()) {
const error = new Error('validation Failed');
error.statusCode = 422;
error.validation = validationErrors.array();
throw error;
}
}
</code></pre>
<p>This is my validationErrorHandler.js file. I am not sure if this is the best way to implement this or if there's anything that can be improved upon. Should I do anything with it to make it more portable across different node.js applications for instance? Because this implementation requires that the error handler middleware has a statusCode and validation parameter in its error object.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T03:18:22.820",
"Id": "266438",
"Score": "0",
"Tags": [
"node.js"
],
"Title": "Validation handler in node.js"
}
|
266438
|
<h1>Disclaimer</h1>
<p>I've created this post not only for the code review, but rather because I think it would be helpful for the users of the CAEN V2718 module.</p>
<h1>Problem description</h1>
<p>I have a VME board (V2718) which may be used as a square form generator. To set the frequency and duty cycle user must specify three parameters :</p>
<ol>
<li><p>The period <em><strong>N</strong></em> (in terms of the number of time-steps) :
<span class="math-container">$$
1 \leq N \leq 255 \tag{1a}\label{1a}
$$</span></p>
</li>
<li><p>The duty cycle <em><strong>D</strong></em> (in terms of the number of time-steps) :
<span class="math-container">$$
1 \leq D \leq N-1 \tag{1b}\label{1b}
$$</span></p>
</li>
<li><p>The time-step <em><strong>d</strong></em> (used to express the period and duty cycle) which may be either of the following :
<span class="math-container">$$
d_1 = 25n\text{s},\, d_2 = 1600n\text{s},\, d_3 = 410\mu\text{s},\, d_4 = 104m\text{s}
$$</span></p>
</li>
</ol>
<p>For example, to generate the 100 Hz square (50% d.c.) one can choose the following configuration:
<span class="math-container">$$
d = d_3,\,N = 24,\, D=N/2\quad \Rightarrow\quad T = d N\approx 0.01\text{ s}
$$</span></p>
<p>Usually the primary quantities are <em>frequency</em> and <em>duty cycle</em> --- not <em>period</em> and <em>duty cycle</em>. And, of course, people don't want to specify some strange parameters like <em><strong>N</strong></em>, <em><strong>D</strong></em>, and <em><strong>d</strong></em> --- they want frequencies and duties! So the problem is to write a function that chooses the raw parameters to generate the desirable square waveform.</p>
<h1>Algorithm</h1>
<p>To find the closest possible frequency to the desirable frequency <em><strong>f_set</strong></em> we need to find the closest possible period corresponding to the <em><strong>f_set</strong></em>. Given <em><strong>f_set</strong></em> the algorithm is the following</p>
<ol>
<li>Find two <em><strong>T-</strong></em> and <em><strong>T+</strong></em> which can be obtained by the module such that :
<span class="math-container">$$
T_{set} \in [T_{-}, T_{+})
$$</span></li>
</ol>
<ul>
<li>If either of <em><strong>T</strong></em>'s is absent then let the absent one be equal to the present one</li>
<li>If both of <em><strong>T</strong></em>'s are absent then return <code>false</code></li>
</ul>
<ol start="2">
<li><p>Calculate the errors :
<span class="math-container">$$
e_{+} := |f_{\text{set}} - f_{+}|,\quad e_{-} := |f_{\text{set}} - f_{-}|
$$</span></p>
</li>
<li><p>Choose the corresponding <em><strong>T</strong></em> based on the errors' values.</p>
</li>
</ol>
<p>The picture shows the idea (although see the <strong>Useful notes</strong>):</p>
<p><a href="https://i.stack.imgur.com/qR69r.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qR69r.png" alt="enter image description here" /></a></p>
<h2>Useful notes:</h2>
<ul>
<li><em><strong>N</strong></em> cannot be 1. See(\ref{1b})</li>
<li><em><strong>T+</strong></em> and <em><strong>T-</strong></em> can be expressed by using different time-steps (in other words, the red triangles on the picture may be the ticks of the different time scales)</li>
</ul>
<h2>Code</h2>
<pre><code>bool V2718Pulser::SetSquare( uint32_t freq, uint8_t duty )
{
struct { double expo; double num; CVTimeUnits unit; } ss[4] = { { 1000000000., 25., cvUnit25ns },
{ 10000000., 16., cvUnit1600ns },
{ 100000., 41., cvUnit410us },
{ 1000., 104., cvUnit104ms } };
const uint32_t MAX_PERIOD = 0xff; // MAX_N
const uint32_t MIN_PERIOD = 0x02; // MIN_N
struct { uint32_t n; int u; } sPlus, sMinus; // T+, T-
uint32_t n0 = 0;// The reference point
if( freq > 0 )
{
for( int i = 0; i < 4; ++i )
{
n0 = std::floor( ss[i].expo / ss[i].num / freq );
if( (n0 >= MIN_PERIOD) && (n0 < MAX_PERIOD) )
{
// T_set falls between the ticks of the same time-scale
sMinus = { n0, i };
sPlus = { n0 + 1, i };
break;
}
else if( n0 == 1 )
{
// Bad value because of the duty cycle --- should be changed
if( i > 0 )
{
sMinus = { MAX_PERIOD, i - 1 }; // the last tick of the finer time-scale
sPlus = { n0 + 1, i }; // use the current time-scale, but the next tick
}
else
{
// There is no finer time-scale
sPlus = sMinus = { n0 + 1, i };
}
break;
}
else if( n0 == MAX_PERIOD )
{
if( i < 3 )
{
sMinus = { n0, i };
sPlus = { MIN_PERIOD, i + 1 }; // use the 2-th tick of the coarser time-scale
}
else
{
// The is no coarser time-scale
sPlus = sMinus = { n0, i };
}
break;
}
}
if( n0 != 0 )
{
double errorPlus = std::fabs( freq - ss[sPlus.u].expo / ss[sPlus.u].num / sPlus.n );
double errorMinus = std::fabs( freq - ss[sMinus.u].expo / ss[sMinus.u].num / sMinus.n );
if( errorPlus < errorMinus )
{
n0 = sPlus.n;
fTimeUnit = ss[sPlus.u].unit; // d
}
else
{
n0 = sMinus.n;
fTimeUnit = ss[sMinus.u].unit; // d
}
duty = ((duty > 0) ? ((duty < 100) ? duty : 99) : 1);
uint32_t width = n0 * duty / 100;// < MAX_PERIOD
width = (width > 0) ? width : 1;
if( width < n0 )
{
fPeriod = n0; // N
fWidth = width; // D
return true;
}
}
}
return false;
}
</code></pre>
<h1>Result</h1>
<p>I created the "frequency error graph" of this module for the frequencies from 1 to 10000000 Hz:</p>
<p><a href="https://i.stack.imgur.com/uf6Lk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uf6Lk.png" alt="enter image description here" /></a></p>
<h2>Bad frequencies</h2>
<p>You can see that there are frequencies with a very big error (~30%). One of such frequency is 1836 Hz. Indeed,</p>
<p><span class="math-container">$$
T_{\text{bad}} = \frac{1}{1836} = 0.000544662 = 544.662 \times 10^{-6}\text{s} = 544.662 \mu\text{s}
$$</span></p>
<p>which means the closest times are
<span class="math-container">$$
T_{-} = 255 \times 1600n\text{s} = 408\mu\text{s},\quad T_{+} = 2 \times 410\mu\text{s} = 820\mu\text{s}
$$</span></p>
<p>so</p>
<p><span class="math-container">$$
f_{-} = 2450.98\text{ Hz},\quad f_{+} = 1219.51\text{ Hz}
$$</span></p>
<h2>Very bad frequencies</h2>
<p>There are 2 frequencies (2440, 2441) that even "don't exist" (the function returns <code>false</code>), i.e. neither <em><strong>T+</strong></em> nor <em><strong>T-</strong></em> were found. Indeed,</p>
<p><span class="math-container">$$
T_{\text{very bad}} = \frac{1}{2440} = 0.000409836 = 409.836\mu\text{s}
$$</span></p>
<p>and</p>
<p><span class="math-container">$$
255 \times 1600n\text{s} < T_{\text{very bad}} < 410\mu\text{s}
$$</span></p>
<p>so</p>
<p><span class="math-container">$$
\left\lfloor \frac{T_{\text{very bad}}}{d_{i}} \right\rfloor \text{is either 0 or } >255
$$</span></p>
<p>and the algorithm fails to find <em><strong>T</strong></em>'s.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T00:46:02.847",
"Id": "526415",
"Score": "0",
"body": "If N cannot be 1, then your bounds statement at the beginning is incorrect."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T12:15:47.810",
"Id": "526449",
"Score": "0",
"body": "@Reinderien, You're right. But the word \"cannot\" here is equal to \"useless\" because formally it can be 1 but in this case what the ***D*** can be : either 0 or 1. In this case the module just don't generate anything :)"
}
] |
[
{
"body": "<p><code>ss</code> is neither <code>static</code> nor <code>const</code>, and a stack-based variable will be initialized each time the function is called. It appears that you don't modify this array at all but only refer to it. If that's correct, make it <code>constexpr</code>.</p>\n<pre><code>const uint32_t MAX_PERIOD = 0xff; // MAX_N\nconst uint32_t MIN_PERIOD = 0x02; // MIN_N\n</code></pre>\n<p>With a modern compiler, use <code>constexpr</code> generally for this. <code>const</code> variables <em>might</em> be compile-time constants if the initializer is a constant expression, but there's no warning if that's not the case. The newer <code>constexpr</code> is more demanding and means that it <em>will be</em> a compile-time constant.</p>\n<pre><code>sPlus, sMinus; // T+, T-\n</code></pre>\n<p>The name is confusing since it doesn't match the comment: S+ vs T+.</p>\n<p>I see they are uninitialized, and the following rather large and complexly-nested block seems to have the sole purpose of setting these values. <strong>Break that out into its own function</strong>, and then as well as removing a "meander" from the code, you can write them as initialized constants:</p>\n<p><code>const auto [n0, sPlus, sMinus] = find_T();</code></p>\n<p>That will make the function much easier to understand too; it's not easy to see where the "real code" is after the nested blocks that set up these values.</p>\n<pre><code>if( n0 != 0 )\n{\n // entire meat of the function goes here\n return true;\n}\nreturn false;\n</code></pre>\n<p>Both the test for <code>n0</code> and the earlier test for <code>freq</code> should be written as <em>preconditions</em>. Put reverse the sense of the test and return <code>false</code> if it fails the condition. The body of the function is then the "main line" and not under a conditional. Since this is nested, you'll "write to the left" quite a bit more in this case!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T12:17:08.757",
"Id": "526450",
"Score": "1",
"body": "Thank you for your answer, I'll take it into account."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T19:18:42.340",
"Id": "266454",
"ParentId": "266442",
"Score": "2"
}
},
{
"body": "<p>@JDługosz has you covered in terms of C++ syntax. Algorithmically, a quick bit of Python illustrates where your method can be improved. Basically your iteration through all four timescales is correct, but your plus/minus logic is not, leading to the degenerate cases you've already identified. You don't need any explicit conditions at all, and can run through all of the timescales with defined minima and maxima, accounting for error in each case:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from typing import NamedTuple, Iterable, Tuple\n\nd_opts = (25e-9, 1.6e-6, 410e-6, 104e-3)\n\n\nclass Config(NamedTuple):\n f: float\n f_act: float\n f_err: float\n duty: float\n duty_act: float\n duty_err: float\n N: int\n D: int\n d: float\n\n @classmethod\n def approximate(cls, f: float, duty: float, d: float) -> 'Config':\n # Forward\n N_float = 1 / f / d\n N = max(2, min(255, round(N_float)))\n D_float = duty * N\n D = max(1, min(N-1, round(D_float)))\n\n # Backward\n f_act = 1 / N / d\n duty_act = D / N\n\n return cls(\n f=f, f_act=f_act, f_err=f_act/f - 1,\n duty=duty, duty_act=duty_act, duty_err=duty_act/duty - 1,\n N=N, D=D, d=d,\n )\n\n @classmethod\n def all_approx(cls, f: float, duty: float) -> Iterable[Tuple[\n float, # total error\n 'Config',\n ]]:\n for d in d_opts:\n config = cls.approximate(f, duty, d)\n err = config.f_err**2 + config.duty_err**2\n yield err, config\n\n @classmethod\n def closest(cls, f: float, duty: float) -> 'Config':\n err, config = min(cls.all_approx(f, duty))\n return config\n\n def __str__(self) -> str:\n return (\n f'{self.f:7g} Hz @ {self.duty:.0%} ~ '\n f'{self.f_act:9.5g} Hz @ {self.duty_act:.2%}, '\n f'Δ {self.f_err:+.1e}, {self.duty_err:+.1e}, '\n f'N={self.N:3}, D={self.D:3}, d={self.d:.2e} s'\n )\n\n\nprint('A selection of frequencies:')\nfor f, duty in (\n (100, 0.5),\n (1836, 0.5),\n (2440, 0.5),\n (2441, 0.5),\n (96e6, 0.37),\n):\n print(Config.closest(f, duty))\nprint()\n\nprint('One frequency, best to worst config:')\nfor err, config in sorted(Config.all_approx(f=2441, duty=0.5)):\n print(config)\n</code></pre>\n<p>outputs much happier results for your degenerate cases:</p>\n<pre class=\"lang-none prettyprint-override\"><code>A selection of frequencies:\n 100 Hz @ 50% ~ 101.63 Hz @ 50.00%, Δ +1.6e-02, +0.0e+00, N= 24, D= 12, d=4.10e-04 s\n 1836 Hz @ 50% ~ 2451 Hz @ 50.20%, Δ +3.3e-01, +3.9e-03, N=255, D=128, d=1.60e-06 s\n 2440 Hz @ 50% ~ 2451 Hz @ 50.20%, Δ +4.5e-03, +3.9e-03, N=255, D=128, d=1.60e-06 s\n 2441 Hz @ 50% ~ 2451 Hz @ 50.20%, Δ +4.1e-03, +3.9e-03, N=255, D=128, d=1.60e-06 s\n9.6e+07 Hz @ 37% ~ 2e+07 Hz @ 50.00%, Δ -7.9e-01, +3.5e-01, N= 2, D= 1, d=2.50e-08 s\n\nOne frequency, best to worst config:\n 2441 Hz @ 50% ~ 2451 Hz @ 50.20%, Δ +4.1e-03, +3.9e-03, N=255, D=128, d=1.60e-06 s\n 2441 Hz @ 50% ~ 1219.5 Hz @ 50.00%, Δ -5.0e-01, +0.0e+00, N= 2, D= 1, d=4.10e-04 s\n 2441 Hz @ 50% ~ 4.8077 Hz @ 50.00%, Δ -1.0e+00, +0.0e+00, N= 2, D= 1, d=1.04e-01 s\n 2441 Hz @ 50% ~ 1.5686e+05 Hz @ 50.20%, Δ +6.3e+01, +3.9e-03, N=255, D=128, d=2.50e-08 s\n</code></pre>\n<h2>Hardware deficiencies</h2>\n<p>A more stable algorithm will fix the cases where no configuration was found; but for some worst-case values like 1836 Hz nothing can be done because the hardware doesn't have very good resolution. 1836 is in fact not a coincidence; it's the average of the gap between the second and third ranges. The two worst errors will thus be found at these frequencies (assuming that the original range values are lies and are actually exact multiples of 256 that the vendor has rounded in their documentation):</p>\n<p><span class=\"math-container\">$$\n\\frac 1 2 \\left(\n\\frac 1 {255 \\times 1.6 \\times 10^{-6}} +\n\\frac 1 {2 \\times 409.6 \\times 10^{-6}}\n\\right) \\approx 1835.842\n$$</span></p>\n<p><span class=\"math-container\">$$\n\\frac 1 2 \\left(\n\\frac 1 {255 \\times 409.6 \\times 10^{-6}} +\n\\frac 1 {2 \\times 0.1048576}\n\\right) \\approx 7.171257\n$$</span></p>\n<p>In each case you're forced to choose between -33% error or +33% error based on the higher or lower range.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T07:50:55.877",
"Id": "526432",
"Score": "0",
"body": "First of all, thank you for your answer. 1) I see you define the error as a f^2 + D^2. But I actually don't mind about precision of the duty cycle. More over, it is not obvious that the frequency and duty cycle have to be included \"symmetrically\" in the error formula. 2) I agree that your approach to run through all ranges followed by picking the closest frequency is better here. 3) Yes, I think you're right about the actual values of ranges -- it makes sense, more over, I see this on my oscilloscope."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T07:55:15.767",
"Id": "526433",
"Score": "0",
"body": "BTW, I think that Python is redundant here. You could explain all of this stuff in words and formulas."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T08:36:44.973",
"Id": "526435",
"Score": "0",
"body": "I guess I could do that? But it wouldn't be as useful of an answer. Having actual code execute an alternate algorithm is somewhat far from redundant, particularly since I wouldn't be confident in my results otherwise."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T01:10:48.850",
"Id": "266462",
"ParentId": "266442",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T11:36:16.193",
"Id": "266442",
"Score": "4",
"Tags": [
"c++"
],
"Title": "Find the closest possible frequency of a pulser that uses limited number of fixed time intervals to generate the signal (CAEN V2718)"
}
|
266442
|
<p>Like the title suggests, I wrote a script in Python that uses the <code>python3-lxc</code> library to automate the creation of Linux LXC containers. I realised that containers can be great when I'm writing (and even installing other) apps and setting up FreeBSD-ish* jail environments to organise my workspaces for whatever project that I'm up to.</p>
<p>Setting up LXC containers can be a pain in the you-know-what, so I decided to automate the task with Python and came up with this:</p>
<pre class="lang-py prettyprint-override"><code># Generic Python3 development environment
# - Automated LXC container setup script
# By Aleksey <hackermaneia@riseup.net>
# - GitHub: https://github.com/Alekseyyy
import lxc
import sys
import argparse
parser = argparse.ArgumentParser(description="Use LXC to setup a Python3 development environment")
parser.add_argument("--name", action="store", type=str, default="python3-dev", help="the name of the container")
parser.add_argument("--user", action="store", type=str, default="dev", help="the user's ssh username")
args = parser.parse_args()
container = lxc.Container(args.name)
# Check to see if container already exists
if container.defined:
print("Container of the name %s already exists. Exiting..." % name)
sys.exit(1)
# Create and start the container
if not container.create("download", lxc.LXC_CREATE_QUIET, {"dist":"ubuntu",
"release":"bionic",
"arch":"amd64"}):
print("Failed to create the Python3 development container. Exiting... ")
sys.exit(1)
print("Created the Python3 development container!")
if not container.start():
print("Failed to start the Python3 development container")
sys.exit(1)
print("Started the Python3 development container!")
# Setup the container
print("Setting up the container...")
container.get_ips(timeout=30) #wait a bit :P
setup_commands = [
["apt", "update"],
["apt", "dist-upgrade"],
["apt", "install", "python3"],
["apt", "install", "python3-pip"],
["apt", "install", "ssh"],
["useradd", args.user],
["mkdir", "/home/%s" % args.user]
]
for k in setup_commands:
container.attach_wait(lxc.attach_run_command, k)
print("\nFinished setting up! (don't forget to set a password for %s" % args.user)
print("Container state: %s" % container.state)
print("Container PID: %s\n" % container.init_pid)
</code></pre>
<p>The script works like:</p>
<ol>
<li>Importing the necessary libraries</li>
<li>Parsing arguments to be used in creating the image</li>
<li>Creating and starting up the container</li>
<li>"Attaching" to the container to set up any prerequisites</li>
<li>Finally printing out the process ID and state of the container</li>
</ol>
<p>Because I'm lazy, this sets up a privileged container that requires the <code>sudo</code> command to run (which is insecure for production systems if I'm not mistaken, but should be fine for users who just want a container to work in).</p>
<ul>
<li>Can you recommend a better way to deploy LXC containers?</li>
<li>Can you recommend ways coding practices to improve my script?</li>
<li>I noticed that I can't automatically set a password for the lower-privileged user that I created and that some images can't download (possibly because of some GPG keyserver error). I should ask this in StackOverflow, but do you have any advice to solve this?</li>
<li>Do you have any other advice regarding LXC-based containers, containers in general or Python programming?</li>
</ul>
<p>Also, you can check out my other Python-automated LXC scripts if you're interested here: <a href="https://github.com/Alekseyyy/InfoSec/tree/master/lxc" rel="nofollow noreferrer">https://github.com/Alekseyyy/InfoSec/tree/master/lxc</a></p>
<p>*I'm sure that there are technical differences between FreeBSD jails and LXC containers, plz go easy on me :P</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T18:47:12.997",
"Id": "526401",
"Score": "1",
"body": "Why not use the `lxc-create` command to create the container? It looks like you just wrote a Python wrapper around an already existing command line tool. Note that for some distros, the `lxc-create` commands also allows you to specify a list of packages you want added onto the base image."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T18:58:25.373",
"Id": "526402",
"Score": "0",
"body": "Yeah but this is sort of like a Dockerfile (but for LXC) defining how the container should be setup. Mostly cos' it would take forever to setup (some) containers (I have more complex setups besides this) and would like to just automate all the things :P Also, I'm gonna forget what packages that I need to install, so it's nice to keep them in Python script ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T19:02:02.667",
"Id": "526403",
"Score": "1",
"body": "Fair enough. I would recommend switching to shell scripts though, as they require less dependencies to be installed. That said, once complexity goes up it might be better to stick with Python."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T19:03:31.903",
"Id": "526404",
"Score": "0",
"body": "Yeah, but I'm very bad at shell scripting @G. Sliepen, thanks for advices tho :D"
}
] |
[
{
"body": "<p>I don't blame you for favouring Python over Bash, which I find spooky and awkward. This is mostly due to my inexperience, but the syntax seems to me inconsistent and unintuitive.</p>\n<p>I find <code>Exiting...</code> to be redundant - the user will notice that the script has exited when it has exited.</p>\n<p>Particularly since this is being run as a script from the shell, you should prefix your script with a shebang:</p>\n<pre><code>#!/usr/bin/env python3\n</code></pre>\n<p>It's good that you're using <code>argparse</code>. Keep doing that.</p>\n<p>For your error message <code>print</code> calls, consider including <code>file=stderr</code>.</p>\n<p>Interpolated "f-strings" are more syntactically sugary than percent notation:</p>\n<pre><code>f'Container named {name} already exists'\n</code></pre>\n<p>I find</p>\n<pre><code>if not container.create("download", lxc.LXC_CREATE_QUIET, {"dist":"ubuntu",\n "release":"bionic",\n "arch":"amd64"}):\n</code></pre>\n<p>to be easier to read when formatted as</p>\n<pre><code> if not container.create(\n "download", lxc.LXC_CREATE_QUIET, \n {\n "dist": "ubuntu",\n "release": "bionic",\n "arch": "amd64",\n },\n ):\n</code></pre>\n<p>Is "the user's SSH username" as used in the path <code>/home/{args.user}</code> able to be implied by <code>~</code>? That would be preferable.</p>\n<pre><code>container.get_ips(timeout=30) #wait a bit :P\n</code></pre>\n<p>is icky. What if it takes far less (bad) or more (worse) than 30 seconds? Instead write a polling loop that is able to detect when the container is set up.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T09:20:21.760",
"Id": "526609",
"Score": "1",
"body": "Thanks for dat advices @Reinderien :D"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T23:55:19.597",
"Id": "266461",
"ParentId": "266451",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "266461",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T17:57:50.880",
"Id": "266451",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"linux",
"collections",
"installer"
],
"Title": "Python script to automate the creation of Linux LXC containers"
}
|
266451
|
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/256850/231235">Batch Insert Figures Into Powerpoint Slides with VBA</a>. I appreciate <a href="https://codereview.stackexchange.com/a/257198/231235">PeterT's answer</a>. Besides the single image replacement, I am attempting to make <code>InsertFiguresDetail</code> function to perform the operation of inserting for handling multiple figures.</p>
<p><strong>The experimental implementation</strong></p>
<p>The main entry method is <code>InsertFigures</code>.</p>
<pre><code>Option Explicit
Sub InsertFigures()
'Reference: (Show object name) https://stackoverflow.com/a/52088805
'Reference: (Replace image) https://stackoverflow.com/a/18083223
Dim baseSlideNumber As Long
Dim startNum As Long
Dim endNum As Long
startNum = 2
endNum = 6
baseSlideNumber = 1
Dim loopNumber As Long
Dim newSlide As SlideRange
For loopNumber = startNum To endNum
Set newSlide = ActivePresentation.Slides(baseSlideNumber).Duplicate
Next loopNumber
For loopNumber = startNum To endNum
Dim NewPictureFilename1 As String
Dim NewPictureFilename2 As String
NewPictureFilename1 = "F:\Input\" & CStr(loopNumber) & ".bmp" ' Source Image Path1
NewPictureFilename2 = "F:\Output\" & CStr(loopNumber) & ".png" ' Source Image Path2
Dim TargetSlideNumber As Long
TargetSlideNumber = baseSlideNumber + (loopNumber - startNum + 1)
Dim shapeName1 As String
Dim shapeName2 As String
shapeName1 = "Picture 1"
shapeName2 = "Picture 2"
Dim result1 As String: result1 = InsertFiguresDetail(NewPictureFilename1, shapeName1, shapeName1, TargetSlideNumber)
Dim result2 As String: result2 = InsertFiguresDetail(NewPictureFilename2, shapeName2, shapeName2, TargetSlideNumber)
Next loopNumber
End Sub
Function InsertFiguresDetail(NewPictureFilename As String, shapeName As String, shapeNewName As String, TargetSlideNumber As Long) As String
Dim topProperty As Double
Dim leftProperty As Double
Dim heightProperty As Double
Dim widthProperty As Double
Dim softEdgeProperty As Double
'Capture properties of exisitng picture such as location and size
Dim objectForGettingProperties As Shape
Set objectForGettingProperties = GetShapeByName(shapeName, TargetSlideNumber)
With objectForGettingProperties
topProperty = .Top
leftProperty = .Left
heightProperty = .Height
widthProperty = .Width
'SoftEdgeProperty = .SoftEdge
End With
objectForGettingProperties.Delete ' Delete origin placeholder
Dim newImageObject As Object
Set newImageObject = ActivePresentation.Slides(TargetSlideNumber) _
.Shapes.AddPicture(NewPictureFilename, _
msoFalse, msoTrue, _
leftProperty, _
topProperty, _
widthProperty, _
heightProperty)
newImageObject.Name = shapeNewName
InsertFiguresDetail = "true"
End Function
Function GetShapeByName(ByVal shapeName As String, ByVal Slide As Long) As Shape
'Reference: https://stackoverflow.com/a/5527604
Set GetShapeByName = ActivePresentation.Slides(Slide).Shapes(shapeName)
End Function
</code></pre>
<p>All suggestions are welcome.</p>
<p>The summary information:</p>
<ul>
<li><p>Which question it is a follow-up to?</p>
<p><a href="https://codereview.stackexchange.com/q/256850/231235">Batch Insert Figures Into Powerpoint Slides with VBA</a></p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<p>I am attempting to make <code>InsertFiguresDetail</code> function to perform the operation of inserting for handling multiple figures.</p>
</li>
<li><p>Why a new review is being asked for?</p>
<p>If there is any possible improvement, please let me know.</p>
</li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T18:12:58.847",
"Id": "266452",
"Score": "0",
"Tags": [
"beginner",
"vba",
"file",
"image",
"powerpoint"
],
"Title": "Batch Insert Multiple Figures into Powerpoint Slides with VBA"
}
|
266452
|
<p>I want to reduce time complexity of my code that solves the following problem.</p>
<blockquote>
<p>The program receives a positive distance d followed by a sequence of n
events: An event can be either that a person appeared at some position, or that a person disappeared
from some position. After each event, your program should output
"red" if there are currently at least two persons at distance exactly
d, and "yellow" otherwise. Note that initially (before the first
event) all positions are empty. The events are given as a 2D array
<code>event[0..n-1][0..1]</code>, where <code>event[i][0]</code> is "1" if a person appeared at position <code>event[i][1]</code> (on the x-axis), and
"-1" if a person disappeared from that position. The output is an
array <code>light[0..n-1]</code> of strings, where <code>light[i]</code> is the color directly
after <code>event[i]</code>.</p>
</blockquote>
<p>I used the following code to solve this problem.</p>
<pre><code>def cal_dis(d,pairs):
found = False
for i in range(0, len(pairs)-1):
if(pairs[i+1]- pairs[i]) == d:
found = True
break
return "red" if found else "yellow"
def tracker(n,d,event):
ret = [""] * n
pairs = []
for i in range(0,n):
if event[i][0] == 1:
pairs.append(event[i][1])
ret[i]= cal_dis(d,sorted(pairs))
else:
pairs.remove(event[i][1])
ret[i]= cal_dis(d,sorted(pairs))
return ret
</code></pre>
<h2>Sample Input</h2>
<blockquote>
<p>first row: n d</p>
<p>next n rows: two integers; the first one is either -1
or 1, the second one is nonnegative (these n rows correspond to the
array "event")</p>
</blockquote>
<pre><code>7 4
1 2
1 10
1 6
-1 2
-1 6
1 9
1 14
</code></pre>
<h2>Sample Output</h2>
<blockquote>
<p>n rows each consisting of either the string "red" or "yellow".</p>
</blockquote>
<pre><code>yellow
yellow
red
red
yellow
yellow
red
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T09:20:44.543",
"Id": "526439",
"Score": "1",
"body": "In one place the input is called a two-dimensional array, and later it seems to be a file-like. Are the input and output stdin/stdout, or actually in-memory lists?"
}
] |
[
{
"body": "<p>IMO this is an algorithms practice question, and I don't think you want a review of your code. You just want the answer. Since this is doubtless from a practice site, why not just read the sample answers there?</p>\n<p>That said, here is a hint on the answer: COUNT the number of pairs of people at distance exactly d as you go.</p>\n<p>Whenever you update whether a person is at a particular location, check to the left d places, and to the right d places. If it helps, you can pad the array with d empty places to the left and right when you start.</p>\n<p>This reduces the running time to linear, instead of quadratic.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T11:24:19.877",
"Id": "526446",
"Score": "0",
"body": "can you point me to the practice website that you're talking about?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T00:04:00.417",
"Id": "526482",
"Score": "0",
"body": "Where did you get this problem? That's the website I mean."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T00:34:16.600",
"Id": "526484",
"Score": "0",
"body": "I didn't get it on a website for God's sake. A friend sent it to me to help him solve it. I was able write the code in a few minutes but I ran out of ideas to optimize it. If you know a website that has this question, then I can just see the sample solution and that's it. Why would someone post it here if they already could see the solution on a website?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T20:34:38.677",
"Id": "526536",
"Score": "0",
"body": "Code review is /filled/ with competitive coders \"why is my code too slow for this competitive algorithms question from a site\". That, together with the highly unnatural nature of this problem, made me think you got it from a site. Now I think your friend got it from a site or as an interview question. If this is a just a problem one of you ran into, great job on writing it up in a very clear way!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T23:15:13.177",
"Id": "526548",
"Score": "0",
"body": "Thanks for understanding"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T23:54:31.110",
"Id": "526553",
"Score": "0",
"body": "@PsyLogic Where did your friend get it from?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-30T12:05:06.300",
"Id": "526584",
"Score": "0",
"body": "@don'ttalkjustcode he said he found the question on Fiver. He's a freelancer"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T09:17:32.953",
"Id": "266471",
"ParentId": "266456",
"Score": "0"
}
},
{
"body": "<h3>Use understandable names</h3>\n<p><code>cal_dis</code>? Do you mean <code>calculate_distance</code>? But it doesn't calculate. Maybe <code>find_at_distance</code> or just <code>find_distance</code> will be better? And <code>d</code> is also too short (but if all the project is these two functions, it may ok). Maybe <code>dist</code> could be better? And <code>event</code> is a list, not a single event. Should it be called <code>events</code>? And <code>pairs</code> are <code>positions</code>, right?</p>\n<h3>Some simplifications</h3>\n<p>In <code>cal_dis</code> - when you find the element at distance <code>d</code>, you don't need to break the loop - you just need to return "red", and return "yellow" after the loop. Drop the <code>found</code> flag.</p>\n<p>More Pythonic way to write this is something like</p>\n<pre><code>return "red" if any(b - a == d for a, b in zip(pairs, pairs[1:])) else "yellow"\n</code></pre>\n<p>but I'm not sure it's more readable, especially for beginners.</p>\n<p>In <code>tracker</code> - you don't need to create <code>ret</code> full of empty values, you can append elements unto it. The last line of both <code>if-else</code> branches is the same, so you can move if out of <code>if-else</code>:</p>\n<pre><code>if event[i][0] == 1:\n pairs.append(...)\nelse:\n pairs.remove(...)\nret.append(d, sorted(pairs))\n</code></pre>\n<p>Now, do we need <code>i</code>? It is used only to address elements of <code>event</code> list, so we can iterate this list:</p>\n<pre><code>for action, position in events:\n if action==1:\n pairs.append(position)\n...\n</code></pre>\n<p>All together:</p>\n<pre><code>def find_distance(dist, positions):\n positions = sorted(positions)\n for i in range(len(positions) - 1):\n if positions[i+1] - positions[i] == d:\n return "red"\n return "yellow"\n\ndef tracker(_, dist, events): #first argument is excessive, we have len(events)\n result = []\n positions = []\n for action, position in events:\n if action == 1:\n positions.append(position)\n else:\n positions.remove(position)\n result.append(find_distance(dist, positions))\n return result\n</code></pre>\n<h3>Better algorithm ideas</h3>\n<ul>\n<li><p>you can track current state. If there was a removal, the result can't switch from "yellow" to "red", and if data was added, "red" can't switch to "yellow".</p>\n</li>\n<li><p>if all positions are unique, you may keep them in a <code>set</code> instead of <code>list</code>, if they are not - use <code>collections.Counter</code>. This way you'll avoid sorting the <code>positions</code> every event, and checking if addition switched to "red" will be done in one check:</p>\n<p><code>if (position - dist) in positions or (position + dist) in positions:</code></p>\n</li>\n<li><p>to efficiently check if the removal switches state to "yellow" you should keep track on every existing pair with distance <code>dist</code> in the <code>set</code> of pairs. Doing this for non-unique positions (with Counter) will be a bit tricky.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T16:20:24.623",
"Id": "266483",
"ParentId": "266456",
"Score": "1"
}
},
{
"body": "<p>For a faster algorithm, update a count of neighboring pairs at distance D as you go.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from collections import defaultdict\n\ndef num_at_distance(d, pairs):\n # Keep track of whether each position is occupied or not.\n # Accepts a distance and a number of positions to update. Each position is a 2-tuple of:\n # - -1 for not-occupied or 1 for occupied\n # - A position which changed.\n # Returns [yellow, yellow, red...] as a generator\n\n # 'occupied' maps a position to whether it's occupied.\n # Everything is unoccupied to start (False).\n # For slightly faster performance you could switch to an array.\n occupied = defaultdict(bool)\n num_at_distance_d = 0\n for now_occupied, position in pairs:\n # A is the position D to the left of the update\n # i is the updated position\n # B is the position D to the right of the update\n a, i, b = position-d, position, position+d\n now_occupied = bool(now_occupied==1)\n\n if occupied[i] != now_occupied:\n occupied[i] = now_occupied\n if occupied[i]:\n # Use the fact that python's True and False are 1 and 0 for some math\n num_at_distance_d += occupied[a] + occupied[b]\n else:\n num_at_distance_d -= occupied[a] + occupied[b]\n if num_at_distance_d == 0:\n yield "yellow"\n else:\n yield "red"\n\nif __name__=='__main__':\n input = 4, [(1,2), (1,10), (1,6), (-1, 2), (-1, 6), (1, 9), (1,4)]\n output = list(num_at_distance(*input))\n print(output)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T23:15:52.590",
"Id": "526549",
"Score": "0",
"body": "Works perfectly!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T20:58:09.923",
"Id": "266506",
"ParentId": "266456",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "266506",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T19:44:55.643",
"Id": "266456",
"Score": "1",
"Tags": [
"python",
"performance",
"python-3.x"
],
"Title": "Encode event results as colors"
}
|
266456
|
<p>I'm starting to create data models and one of the models I need should represent a mailing/billing address. While I reside in the United States, I recognize that there are different terms utilized in different parts of the world. As such, I wanted to define the properties of my model to be more <em>generic</em> in the sense that they can apply no matter which part of the world you're in:</p>
<pre><code>/// <summary>
/// A postal code for use in company systems.
/// </summary>
public struct PostalCode
{
/// <summary>
/// The five digit postal code.
/// </summary>
public string Value { get; set; }
/// <summary>
/// The four digit segment code.
/// </summary>
public string Segment { get; set; }
}
/// <summary>
/// A universal structure for representing physical/mailing addresses.
/// </summary>
public struct Address
{
/// <summary>
/// The structure number and street name this address represents.
/// </summary>
string StreetAddress { get; set; }
/// <summary>
/// Data representative of a typical secondary address line.
/// </summary>
/// <remarks>Examples of valid data are PO boxes, room numbers, attention to descriptions, etc.
string AdditionalDetails { get; set; }
/// <summary>
/// The city, town, etc. that this address resides in.
/// </summary>
string Municipality { get; set; }
/// <summary>
/// The state, province, etc. that this address resides in.
/// </summary>
string Domain { get; set; }
/// <summary>
/// The country this address resides in.
/// </summary>
string Country { get; set; }
/// <summary>
/// The division of land this address resides in. Synonymous with county, parish, borough, etc.
/// </summary>
string Shire { get; set; }
/// <summary>
/// A series of letters, digits or both, sometimes including spaces or punctuation, included in this address.
/// </summary>
PostalCode PostalCode { get; set; }
}
</code></pre>
<p><em><strong>Edit</strong>: I should've initially pointed out, I do need all of the properties listed; I'm mostly focused on naming and documentation.</em></p>
<hr />
<p>Is my address model to broad or "over the top"?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T20:47:21.747",
"Id": "526410",
"Score": "1",
"body": "Keep it simple, Address, Country, City, Postal Code . these should be enough"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T20:54:36.410",
"Id": "526411",
"Score": "0",
"body": "@iSR5 I updated my question with some details; essentially, I need all of the listed properties; my question is focused on the naming and documentation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T21:10:23.147",
"Id": "526412",
"Score": "0",
"body": "Some properties comments are like explaining a hot chocolate is chocolate ! meaning, if the property name is clear enough, then there is no need to add comments on it (you could add the property name as comment)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T21:25:01.240",
"Id": "526413",
"Score": "0",
"body": "I had thought interfaces were off-topic. However my search indicates [interfaces are on-topic](https://codereview.meta.stackexchange.com/q/2308)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-30T06:41:42.330",
"Id": "526570",
"Score": "0",
"body": "When we had to design a similar domain model we have started our investigation at the giants: [Google Maps Platform's GeoCoding Api](https://developers.google.com/maps/documentation/geocoding/overview#Types), [Microsoft Bing Maps' Location Api](https://docs.microsoft.com/en-us/bingmaps/rest-services/locations/find-a-location-by-address), [Here Maps' GeoCoding Api](https://developer.here.com/documentation/geocoding-search-api/dev_guide/topics/result-types-address.html)"
}
] |
[
{
"body": "<h2>Review</h2>\n<h3>Explanation of details</h3>\n<blockquote>\n<p>my question is focused on the naming</p>\n</blockquote>\n<p>The names of the variables and code elements are good, they are following the international standard which is good practice, the full class was not shared, but the code presented is ok</p>\n<p>Yes, the structure property names are fine and clean</p>\n<blockquote>\n<p>documentation</p>\n</blockquote>\n<p>The comments are great, but it's a personal opinion, are you commenting the code to facilitate reading or creating the documentation in an automated way?</p>\n<p>If it's just for visual explanation to improve the understanding of variables, it's too verbose and instead of facilitating</p>\n<p>On the other hand, if you use some software to generate the documentation automatically, and it needs to be in this format then that's fine, it's a mandatory format to generate the PDF or HTML with the documentation, but regardless of that it would be interesting to focus on short descriptions, and there are fields that its purpose is obvious, there is no need to comment</p>\n<pre><code>Sorry if my explanation got a little confused\n\nI'm using Google Translate, I hope it's understandable\n</code></pre>\n<h3>Extra tip</h3>\n<p>I would like to recommend Doxygen software to create your software documentation, you just need to comment the methods / procedures / structures etc and it will generate the HTML and PDF page containing the documentation</p>\n<p><strong>Doxygen:</strong> <br>\n<a href=\"https://www.doxygen.nl/download.html\" rel=\"nofollow noreferrer\">https://www.doxygen.nl/download.html</a></p>\n<p><strong>Required format when commenting:</strong> <br>\n<a href=\"https://www.doxygen.nl/manual/commands.html\" rel=\"nofollow noreferrer\">https://www.doxygen.nl/manual/commands.html</a></p>\n<p><strong>Youtube C# Doxygen Tutorials:</strong> <br>\n<a href=\"https://www.youtube.com/watch?v=-V_vHZPOZfY\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=-V_vHZPOZfY</a>\n<br><br>\n<a href=\"https://www.youtube.com/watch?v=TtRn3HsOm1s\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=TtRn3HsOm1s</a><br>\n<br>https://www.youtube.com/watch?v=px4PTEFwioU</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T04:05:58.077",
"Id": "266464",
"ParentId": "266459",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "266464",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-27T20:44:15.400",
"Id": "266459",
"Score": "0",
"Tags": [
"c#"
],
"Title": "Is my address model too broad or \"over the top\"?"
}
|
266459
|
<p>A little program I wrote because I had nothing better to do: a README reader.<br />
Run <code>readme</code> to print the first lines of the README file (or README.md or README.org...) either in the current directory or on a directory up in the directory hierarchy.<br />
Run <code>readme -e</code> to edit that file.</p>
<p>Manual:</p>
<pre class="lang-none prettyprint-override"><code>README(1) General Commands Manual README(1)
NAME
readme - README reader
SYNOPSIS
readme [-cep] [dir]
DESCRIPTION
readme displays to the standard output the header of the first found
README* file in the current directory or in a directory up in the
directory hierarchy. If a directory is given as argument, use it in
place of the current directory.
The options are as follows:
-c Cat mode. Rather than display only the head of the README file,
displays it entirely.
-e Editor mode. Edit the README file rather than displaying it.
-p Pager mode. Display the README file in pager.
All options are mutually exclusive.
ENVIRONMENT
The following environment variables affect the execution of readme
EDITOR, VISUAL
Specifies an editor to use. If both EDITOR and VISUAL are set,
VISUAL takes precedence. If neither EDITOR nor VISUAL are set,
the default is vi(1).
PAGER Specifies the pager to use. If it is not set, use more(1).
README(1)
</code></pre>
<p>code:</p>
<pre class="lang-c prettyprint-override"><code>#include <ctype.h>
#include <err.h>
#include <glob.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#define MAXLINES 22
#define MAXCHARS 1024
#define DEFEDITOR "vi"
#define DEFPAGER "more"
#define VISUAL "VISUAL"
#define EDITOR "EDITOR"
#define PAGER "PAGER"
enum {
MODE_HEADER,
MODE_CAT,
MODE_EDITOR,
MODE_PAGER
};
/* show usage and exit */
static void
usage(void)
{
(void)fprintf(stderr, "usage: readme [-cep] [dir]\n");
exit(1);
}
/* search for a README* file in dir or up in the directory hierarchy */
static char *
readme(char *file, char *dir)
{
glob_t g;
char *s;
for (;;) {
(void)snprintf(file, PATH_MAX, "%s/README*", dir);
if (glob(file, 0, NULL, &g) != 0)
return NULL;
if (g.gl_pathc > 0) {
(void)snprintf(file, PATH_MAX, "%s", g.gl_pathv[0]);
file[PATH_MAX - 1] = '\0';
globfree(&g);
return file;
} else {
globfree(&g);
}
if ((s = strrchr(dir, '/')) != NULL)
*s = '\0';
else
break;
}
return NULL;
}
/* print the header of file */
static void
cat(const char *file, int head)
{
FILE *fp;
int nlines, nchars;
int ch, prev;
int blank;
if ((fp = fopen(file, "r")) == NULL)
err(1, "%s", file);
prev = '\0';
blank = 0;
nchars = nlines = 0;
while ((ch = getc(fp)) != EOF) {
if (iscntrl((unsigned char)ch) && !isspace((unsigned char)ch))
continue;
if (ch == '\n' && head) {
nlines++;
if (prev == '\n') {
blank++;
}
}
if (head) {
nchars++;
if (blank > 1 || nchars >= MAXCHARS || nlines >= MAXLINES)
return;
prev = ch;
}
putchar(ch);
}
}
/* call editor on file */
static void
editor(const char *file)
{
char *prog;
if ((prog = getenv(VISUAL)) == NULL)
if ((prog = getenv(EDITOR)) == NULL)
prog = DEFEDITOR;
execlp(prog, prog, file, NULL);
}
/* call pager on file */
static void
pager(const char *file)
{
char *prog;
if ((prog = getenv(PAGER)) == NULL)
prog = DEFPAGER;
execlp(prog, prog, file, NULL);
}
/* readme: print README file for current project */
int
main(int argc, char *argv[])
{
int mode;
int ch;
char dir[PATH_MAX];
char file[PATH_MAX];
mode = MODE_HEADER;
while ((ch = getopt(argc, argv, "cep")) != -1) {
switch (ch) {
case 'c':
mode = MODE_CAT;
break;
case 'e':
mode = MODE_EDITOR;
break;
case 'p':
mode = MODE_PAGER;
break;
default:
usage();
break;
}
}
argc -= optind;
argv += optind;
if (argc > 1)
usage();
if (argc == 1) {
if (realpath(*argv, dir) == NULL) {
err(1, "%s", *argv);
}
} else if (getcwd(dir, sizeof(dir)) == NULL) {
err(1, NULL);
}
if (readme(file, dir) == NULL)
return 1;
switch (mode) {
case MODE_HEADER:
cat(file, 1);
break;
case MODE_CAT:
cat(file, 0);
break;
case MODE_EDITOR:
editor(file);
break;
case MODE_PAGER:
pager(file);
break;
}
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>Looks good here. You've avoided some of the usual traps (e.g. passing plain <code>char</code> to <code><ctype.h></code> functions), so well done.</p>\n<p>Some things I'd suggest changing:</p>\n<blockquote>\n<pre><code>(void)fprintf(stderr, "usage: readme [-cep] [dir]\\n");\n</code></pre>\n</blockquote>\n<p><code>fprintf()</code> isn't usually tagged "nodiscard", so I wouldn't be explicit about ignoring the return value unless your local coding standard <em>really</em> insists on it. Consider using <code>fputs()</code> instead for a single constant string.</p>\n<blockquote>\n<pre><code>exit(1);\n</code></pre>\n</blockquote>\n<p>That makes it hard to reuse the same function for explicitly-requested help.</p>\n<blockquote>\n<pre><code>glob_t g;\nchar *s;\n</code></pre>\n</blockquote>\n<p>Modern C allows mixing declarations and statements, so consider moving the declarations to where they are initialised, which removes some opportunity for error. In any case, the scope can be reduced to within the body of the loop, which helps clarify that the values are independent in each iteration.</p>\n<blockquote>\n<pre><code> if (glob(file, 0, NULL, &g) != 0)\n return NULL;\n</code></pre>\n</blockquote>\n<p>Oops - we missed <code>globfree()</code> from that code path. And this prevents searching parent directories (because we get <code>GLOB_NOMATCH</code> if not found in current dir).</p>\n<blockquote>\n<pre><code>(void)snprintf(file, PATH_MAX, "%s/README*", dir);\n</code></pre>\n</blockquote>\n<p>Instead of ignoring the return value here, we should be checking that it is strictly less than <code>PATH_MAX</code>, and abort with <code>ENAMETOOLONG</code> instead of silently truncating.</p>\n<blockquote>\n<pre><code> if (g.gl_pathc > 0) {\n ⋮\n return file;\n } else {\n globfree(&g);\n }\n</code></pre>\n</blockquote>\n<p>Given that the first block leaves the function, the <code>else</code> case can simply follow:</p>\n<pre><code> if (g.gl_pathc > 0) {\n ⋮\n return file;\n }\n globfree(&g);\n</code></pre>\n<blockquote>\n<pre><code> if ((s = strrchr(dir, '/')) != NULL)\n</code></pre>\n</blockquote>\n<p>This explicit comparison to NULL is very wordy - almost Java-esque. Trust the C language definition that all non-null pointers are true:</p>\n<pre><code> char *s = strrchr(dir, '/');\n if (!s) {\n break;\n }\n *s = '\\0';\n</code></pre>\n<p>I would add a big fat warning that the function modifies <code>dir</code> rather than trusting that the absence of <code>const</code> makes that obvious.</p>\n<p>With all the checking we really need, it might be simpler to just change our working directory in the search function, and return a relative file name. This tail-recursive implementation works and is much more robust:</p>\n<pre><code>/* search for a README* file in dir or up in the directory hierarchy */\n/* file must point to storage of at least PATH_MAX chars */\n/* dir will be modified, and the current working directory updated */\n/* returns null on any error, or if no matches found */\nstatic char *\nreadme(char *file)\n{\n glob_t g;\n int status = glob(FILEPATTERN, 0, NULL, &g);\n if (status == GLOB_NOMATCH) {\n globfree(&g);\n char curr_dir[2]; /* big enough for "/" but nothing else */\n if (getcwd(curr_dir, sizeof curr_dir) || errno != ERANGE) {\n /* this is the root directory */\n return NULL;\n }\n /* else recurse up to parent directory */\n if (chdir("..")) {\n err(EXIT_FAILURE, "chdir");\n }\n return readme(file);\n }\n if (status) {\n err(EXIT_FAILURE, "glob");\n }\n assert(g.gl_pathc > 0);\n assert(strlen(g.gl_pathv[0]) < PATH_MAX);\n strcpy(file, g.gl_pathv[0]);\n globfree(&g);\n return file;\n}\n</code></pre>\n<p>It seems strange that we use <code>exec()</code> for editing and paging, but want to reimplement <code>cat</code> and <code>head</code> ourselves. There's a slight complication in that we need a pipeline of two <code>head</code> processes to limit both lines and characters, but that's easily arranged (I'm assuming GNU <code>head</code> here, since POSIX doesn't standardise <code>head -c</code>):</p>\n<pre><code> int pp[2];\n if (pipe(pp) < 0) {\n err(1, "pipe");\n }\n int child = fork();\n if (child < 0) {\n err(1, "fork");\n }\n if (!child) {\n /* read file and writes to pipe */\n close(pp[0]);\n dup2(pp[1], 1);\n execlp("head", "head", "-c", MAXCHARS, file, NULL);\n } else {\n /* read pipe and write to stdout */\n close(pp[1]);\n dup2(pp[0], 0);\n execlp("head", "head", "-n", MAXLINES, NULL);\n }\n</code></pre>\n<p>With separate functions for <code>head</code> and <code>cat</code>, we have a unified interface, and can replace the enum with a function pointer:</p>\n<pre><code>void (*handler)(const char*) = head;\nint ch;\nwhile ((ch = getopt(argc, argv, "cep")) != -1) {\n switch (ch) {\n case 'c':\n handler = cat;\n break;\n case 'e':\n handler = editor;\n break;\n case 'p':\n handler = pager;\n break;\n</code></pre>\n<p>It seems a bit odd that we can invoke the program with multiple contradictory arguments. But it's a valid choice, and it's consistent with some standard programs (e.g. that's what <code>head</code> does if given both <code>-c</code> and <code>-n</code> arguments).</p>\n<hr />\n<h1>Modified code</h1>\n<p>Incorporating all the improvements I suggested above:</p>\n<pre><code>#include <assert.h>\n#include <err.h>\n#include <errno.h>\n#include <glob.h>\n#include <limits.h>\n#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <unistd.h>\n\n#define FILEPATTERN "README*"\n#define MAXLINES "22"\n#define MAXCHARS "1024"\n#define DEFEDITOR "vi"\n#define DEFPAGER "more"\n#define VISUAL "VISUAL"\n#define EDITOR "EDITOR"\n#define PAGER "PAGER"\n\n/* show usage to appropriate stream */\nstatic int\nusage(int return_code)\n{\n fputs("usage: readme [-cep] [dir]\\n", return_code ? stderr : stdout);\n return return_code;\n}\n\n/* search for a README* file in dir or up in the directory hierarchy */\n/* file must point to storage of at least PATH_MAX chars */\n/* dir will be modified, and the current working directory updated */\n/* returns null on any error, or if no matches found */\nstatic char *\nreadme(char *file)\n{\n glob_t g;\n int status = glob(FILEPATTERN, 0, NULL, &g);\n if (status == GLOB_NOMATCH) {\n globfree(&g);\n char curr_dir[2]; /* big enough for "/" but nothing else */\n if (getcwd(curr_dir, sizeof curr_dir) || errno != ERANGE) {\n /* this is the root directory */\n return NULL;\n }\n /* else recurse up to parent directory */\n if (chdir("..")) {\n err(EXIT_FAILURE, "chdir");\n }\n return readme(file);\n }\n if (status) {\n err(EXIT_FAILURE, "glob");\n }\n assert(g.gl_pathc > 0);\n assert(strlen(g.gl_pathv[0]) < PATH_MAX);\n strcpy(file, g.gl_pathv[0]);\n globfree(&g);\n return file;\n}\n\n/* print the header of file */\nstatic void\nhead(const char *file)\n{\n int pp[2];\n if (pipe(pp) < 0) {\n err(1, "pipe");\n }\n int child = fork();\n if (child < 0) {\n err(1, "fork");\n }\n if (!child) {\n /* read file and writes to pipe */\n close(pp[0]);\n dup2(pp[1], 1);\n execlp("head", "head", "-c", MAXCHARS, file, NULL);\n } else {\n /* read pipe and write to stdout */\n close(pp[1]);\n dup2(pp[0], 0);\n execlp("head", "head", "-n", MAXLINES, NULL);\n }\n}\n\n/* print the whole file */\nstatic void\ncat(const char *file)\n{\n execlp("cat", "cat", file, NULL);\n}\n\n/* call editor on file */\nstatic void\neditor(const char *file)\n{\n const char *prog = getenv(VISUAL);\n if (!prog) {\n prog = getenv(EDITOR);\n }\n if (!prog) {\n prog = DEFEDITOR;\n }\n execlp(prog, prog, file, NULL);\n}\n\n/* call pager on file */\nstatic void\npager(const char *file)\n{\n const char *prog = getenv(PAGER);\n if (!prog) {\n prog = DEFPAGER;\n }\n execlp(prog, prog, file, NULL);\n}\n\n\n\ntypedef void (*handler)(const char*);\n\n/* readme: print README file for current project */\nint\nmain(int argc, char *argv[])\n{\n void (*handler)(const char*) = head;\n int ch;\n while ((ch = getopt(argc, argv, "cep")) != -1) {\n switch (ch) {\n case 'c':\n handler = cat;\n break;\n case 'e':\n handler = editor;\n break;\n case 'p':\n handler = pager;\n break;\n case 'h':\n return usage(EXIT_SUCCESS);\n default:\n return usage(EXIT_FAILURE);\n }\n }\n argc -= optind;\n argv += optind;\n if (argc > 1) {\n return usage(EXIT_FAILURE);\n }\n\n if (argc == 1 && chdir(*argv)) {\n err(EXIT_FAILURE, "chdir");\n }\n\n char file[PATH_MAX];\n if (!readme(file)) {\n fputs("No README file found\\n", stderr);\n return EXIT_FAILURE;\n }\n\n handler(file);\n /* if we get here, exec() failed */\n err(EXIT_FAILURE, "exec");\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T10:01:48.893",
"Id": "266473",
"ParentId": "266463",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "266473",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T01:48:19.143",
"Id": "266463",
"Score": "3",
"Tags": [
"c"
],
"Title": "README reader program"
}
|
266463
|
<p>It's a dice game between 2 people using tricky dice. For example,three dice [[1, 1, 4, 6, 7, 8], [2, 2, 2, 6, 7, 7], [3, 3, 3, 5, 5, 8]].</p>
<p>The code will decide, in order to win, who chooses the dice first and which die to play. Say if you choose a die first, return the index of the die. Say if you decide to be the second one to choose a die, then specify for each die that your opponent may take, and the die that you would take in return.</p>
<p>The code works but please tell me what you think or how to improve it!</p>
<pre><code>from itertools import product
def count_wins(dice1, dice2):
assert len(dice1) == 6 and len(dice2) == 6
dice1_wins, dice2_wins = 0, 0
for p in product(dice1,dice2):
if p[0]>p[1]:
dice1_wins += 1
elif p[0]<p[1]:
dice2_wins += 1
return (dice1_wins, dice2_wins)
def find_the_best_dice(dices):
assert all(len(dice) == 6 for dice in dices)
adj=[[]for _ in range(len(dices))]
for i in range(len(dices)-1):
for j in range(i+1,len(dices)):
a,b=count_wins(dices[i],dices[j])
print('ij',i,j,'ab',a,b)
if a<b:
adj[i].append(j)
elif a>b:
adj[j].append(i)
else:
adj[j].append(i)
adj[i].append(j)
ans=-1
for i in range(len(adj)):
if len(adj[i])==0:
ans=i
return ans,adj
def compute_strategy(dices):
assert all(len(dice) == 6 for dice in dices)
ans,adj=find_the_best_dice(dices)
print(ans,adj)
strategy = dict()
strategy["choose_first"] = True
strategy["first_dice"] = 0
if ans!=-1:
strategy["first_dice"] = ans
else:
strategy.pop("first_dice")
strategy["choose_first"] = False
for i in range(len(dices)):
for k in adj[i]:
a,b=count_wins(dices[i],dices[k])
if a!=b:
strategy[i]=k
break
return strategy
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T08:41:41.360",
"Id": "526437",
"Score": "1",
"body": "The plural of \"die\" is \"dice\", and \"dices\" is not a word (yes, English is ridiculous)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T11:23:08.083",
"Id": "526445",
"Score": "0",
"body": "Thanks I didn't know!!"
}
] |
[
{
"body": "<h3>Variable names</h3>\n<p>Some names are not clear enough. What <code>p</code> means, a pair? You don't need a pair:</p>\n<p><code>for p in product(dice1,dice2):</code> => <code>for side1, side2 in product(dice1,dice2):</code></p>\n<p><code>a,b=count_wins(dices[i],dices[j])</code> => <code>wins1, wins2 = count_wins(dices[i],dices[j])</code></p>\n<p>What 'adj' means? "Adjacent"? Maybe it should be "wins" or something like this. Make the code readable.</p>\n<h3>Type hints</h3>\n<p>Use them.</p>\n<h3>Indents are important not only in the beginning</h3>\n<p>Put spaces at least right to commas and on the both sides of operators - or at least do it consistently. Sometimes you do, sometimes you don't. That irritating.</p>\n<h3>Use Python features more intensively</h3>\n<pre><code>assert len(dice1) == 6 == len(dice2) #chain compare\n....\nadj=[[] for _ in dices] #you don't need range(len()) if you don't need a number\n....\nfor i, wins in enumerate(adj): #"enumerate" generates index-value pairs\n if not wins: #"len(...) == 0" is just "not ..."\n ans = i\n</code></pre>\n<p>You can make <code>count_wins</code> function much shorter and readable, counting only wins, not losses. This will make you call it twice, but <span class=\"math-container\">\\$O(2n)==2O(n)==O(n)\\$</span>, and <span class=\"math-container\">\\$n\\$</span> is 6, so you lose nothing.</p>\n<pre><code>def count_wins(dice1, dice2):\n assert len(dice1) == 6 and len(dice2) == 6\n return sum(1 for side1, side2 in product(dice1,dice2) if side1>side2)\n</code></pre>\n<p>Or you can do this twice inside <code>count_wins</code> - both ways.</p>\n<h3>Unnecessary and insufficient <code>assert</code>s</h3>\n<p>This code looks like there's only one entry point, at <code>compute_strategy</code>. So other functions probably shouldn't check for list sizes. On the other hand, you don't check many other things like type of input - is it a list of lists of integers? Can there be negative values? There's nothing wrong in extra checking, but if you are validating data - validate it, not just check one assertion several times.</p>\n<p>You can make it a class to make sure all inputs would go through an <code>__init__</code> method.</p>\n<h3>Remove debugging output before showing your code to others</h3>\n<p>I don't think <code>print</code>s belong here, though they could be very useful while debugging.</p>\n<h3>Optimization ideas</h3>\n<p>I don't think comparing 6-element lists needs an optimization, but you still can sort the sides and then bisect search the number of elements less than the other side. This will give you <span class=\"math-container\">\\$O(n*log(n))\\$</span> time instead of yours <span class=\"math-container\">\\$O(n^2)\\$</span> product. Once again - just FYI.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T06:31:48.060",
"Id": "266468",
"ParentId": "266465",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "266468",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T05:00:00.873",
"Id": "266465",
"Score": "3",
"Tags": [
"python",
"dice"
],
"Title": "Tricky dice game in Python"
}
|
266465
|
<p>I've implemented this out of curiosity, and I'd like to know if I've implemented everything correctly, and/or see if anyone has suggestions. This caches some metadata for a game, so:</p>
<ul>
<li>Infrequent writes (a few hundred entries are added during application startup)</li>
<li>Frequent reads (ten thousand or more per second)</li>
<li>No updates or deletes, the data is read-only once it is added</li>
<li>Accessed from around ten threads</li>
<li><code>T</code> is a struct, and is typically larger than one word</li>
</ul>
<p>I was previously using <code>ConcurrentDictionary<int, T></code>, but I wanted to see if I could implement something better suited for my use case.</p>
<pre><code>using System.Threading;
/// <summary>
/// A non-blocking append-only collection of read-only values.
/// </summary>
internal class ConcurrentIndex<T>
{
private readonly object _lock = new object();
private volatile T[] _values;
private volatile int _index = -1;
/// <summary>
/// Creates a new instance with the specified capacity.
/// </summary>
/// <param name="capacity">The initial capacity of the collection</param>
public ConcurrentIndex(int capacity)
{
_values = new T[capacity];
}
/// <summary>
/// Gets an element from the collection by its index.
/// </summary>
/// <remarks>
/// There is no bounds check here, I'll only ever use an index returned by the 'Add' function
/// </remarks>
/// <param name="index">The index of the element</param>
/// <returns>The element.</returns>
public T this[int index]
{
get
{
return _values[index];
}
}
/// <summary>
/// Adds an element to the collection, and returns the index of the element.
/// </summary>
/// <remarks>
/// This method is thread safe, and only blocks if the collection needs to be resized.
/// </remarks>
/// <param name="value">The value to add</param>
/// <returns>The index of the value.</returns>
public int Add(T value)
{
var index = Interlocked.Increment(ref _index);
// We might need to resize the array, and we might not be the only thread trying to do so
if (index >= _values.Length)
{
lock (_lock)
{
if (index >= _values.Length)
{
int length = _values.Length * 2;
while (length <= index)
length *= 2;
var copy = new T[length];
Array.Copy(_values, copy, _values.Length);
_values = copy;
Monitor.PulseAll(_lock);
}
}
}
var values = _values;
values[index] = value;
// The array could have been resized while we were writing, in which case our write would
// have been lost so try again
while (_index >= values.Length)
{
lock (_lock)
{
// If another resize is pending, wait for it to complete
if (_index >= _values.Length)
Monitor.Wait(_lock);
values = _values;
}
values[index] = value;
}
return index;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T16:16:51.103",
"Id": "526528",
"Score": "1",
"body": "No, that's not thread-safe, at least here `public T this[int index]`. Also consider to implement `ICollection<T>` or better `IProducerConsumerCollection<T>` and `IEnumerable<T>` to use the collection in `foreach` loop or Linq queries."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T16:25:26.387",
"Id": "526529",
"Score": "0",
"body": "[Here's some code example](https://ru.stackoverflow.com/a/1261366/373567) implemented by me on Russian StackOverflow, just for reference of Reader-Writer Lock usage which is more performant than regular `lock` because it allows concurrent reads. Probably not best-implemented but truly thread-safe and working code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T21:48:27.843",
"Id": "526539",
"Score": "0",
"body": "@aepot can you explain *why* it's not thread-safe? An element will not be accessed by index before it has been written completely by the `Add` function, as that is how we get the index, so there shouldn't be a race between the read and the write. The only thing that might be changed is the underlying array, but because the values are never modified, it's ok if we are reading from an old array"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T21:51:19.613",
"Id": "526540",
"Score": "0",
"body": "@aepot ideally, can you demonstrate a sequence where this would behave unexpectedly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T22:16:34.537",
"Id": "526541",
"Score": "0",
"body": "Easy. Ok, I missed that's read only but here's another way. Two threads are calling `Add()`: (1) `var values = _values;` (2) `_values = copy;` (1) `values[index] = value;` - as result the value was added to the already abandoned array."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T22:35:50.680",
"Id": "526543",
"Score": "0",
"body": "At the end of the `Add()` function, there is a `while` loop, which waits for any pending resizes to complete, then it adds it to the new array. If another resize happens before that iteration completes, it will go through the loop and do it again"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T23:34:35.543",
"Id": "526551",
"Score": "0",
"body": "Ok, you won. Nice lock-free solution. RW-lock ~10 times slower. I'll play with it a bit more with various number of reading/writing threads."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-30T00:10:17.970",
"Id": "526554",
"Score": "0",
"body": "About optimizations: is T is an unmanaged struct or mixed one?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-30T00:17:26.140",
"Id": "526555",
"Score": "0",
"body": "T is managed, it contains a reference to a `Type`. I could make it unmanaged by storing the id instead"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-30T00:20:41.977",
"Id": "526557",
"Score": "0",
"body": "In case the collection has many items, probably you can add `where T : struct` constraint and introduce `readonly int _itemSize = Marshal.SizeOf(typeof(T));`, then use `Buffer.BlockCopy(_values, 0, copy, 0, _values.Length * _itemSize);` instead of `Array.Copy`. I'm not pretty sure but in can be a bit faster."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-30T00:23:02.587",
"Id": "526558",
"Score": "0",
"body": "The difference on umanaged struct: you can compute or set explicitly it's size at compile time. But there's no special benefits on it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T00:33:32.843",
"Id": "526604",
"Score": "0",
"body": "I did some reading, it looks like [`Buffer.BlockCopy` is actually slower than `Array.Copy`](https://stackoverflow.com/a/33865267/2363967), the main time it's faster is when copying between arrays of different types which is not the case here"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T00:43:08.273",
"Id": "526606",
"Score": "0",
"body": "that's an old post. Too old. I suggest to perform some related benchmarks in the real environment with real data types before making the conclusion."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T06:09:19.437",
"Id": "266466",
"Score": "0",
"Tags": [
"c#",
"concurrency",
"locking"
],
"Title": "Is my non-blocking collection actually thread-safe?"
}
|
266466
|
<p>I managed to get this <code>ggplotly</code> graphic:</p>
<p><a href="https://i.stack.imgur.com/iq3B4.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iq3B4.gif" alt="enter image description here" /></a></p>
<p>It uses the layout option <code>hovermode = "x unified"</code> (see <a href="https://plotly.com/r/hover-text-and-formatting/" rel="nofollow noreferrer">https://plotly.com/r/hover-text-and-formatting/</a>).</p>
<p>To get the value of <code>Time</code> (x) in the tooltip, I had to add this transparent <code>geom_line</code> in my code:</p>
<pre><code> geom_line(aes(
y = NA,
text = paste0(
"Time: ", Time
),
), alpha = 0) +
</code></pre>
<p>Here is the full code:</p>
<pre><code>library(plotly)
dat <- data.frame(
Time = 1:10,
Average = rnorm(10),
Std = rgamma(10, 10, 10)
)
dat <- transform(dat, Ymin = Average - Std)
dat <- transform(dat, Ymax = Average + Std)
gg <- ggplot(
dat,
aes(
x = Time,
group = 1
)
) +
geom_line(aes(
y = NA,
text = paste0(
"Time: ", Time
),
), alpha = 0) +
geom_line(aes(
y = Average,
linetype = "Average",
colour = "Average",
text = paste0(
"Average: ", Average
)
)) +
geom_line(aes(
y = Ymin,
linetype = "Ymin",
colour = "Ymin",
text = paste0(
"Ymin: ", Ymin
)
)) +
geom_line(aes(
y = Ymax,
linetype = "Ymax",
colour = "Ymax",
text = paste0(
"Ymax: ", Ymax
)
)) +
scale_linetype_manual(
values = c(Ymin = "dashed", Average = "solid", Ymax = "dashed")
) +
scale_colour_manual(
values = c(Ymin = "green", Average = "red", Ymax = "green")
) +
guides(
colour = guide_legend(title = ""),
linetype = guide_legend(title = "")
)
ggplotly(gg, tooltip = "text") %>%
layout(hovermode = "x unified")
</code></pre>
<p>Do you have a simpler solution?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T08:20:35.240",
"Id": "266470",
"Score": "0",
"Tags": [
"r",
"data-visualization"
],
"Title": "R ggplotly with hovermode = \"x unified\""
}
|
266470
|
<p>I view users by city using this SQL query:</p>
<pre><code>SELECT
ROW_NUMBER() OVER(ORDER BY Reputation DESC) AS [#],
Id AS [User Link],
Reputation
FROM
Users
WHERE
LOWER(Location) LIKE 'sulaimani, iraq' or LOWER(Location) LIKE 'erbil, iraq'
ORDER BY
Reputation DESC;
</code></pre>
<p>This works.</p>
<p>I don't like the repetition of the <code>LIKE</code> clause - this could get unwieldy if I want to include many more locations (but not the whole country).</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T11:48:01.293",
"Id": "526447",
"Score": "2",
"body": "Does SEDE not support `LOWER(Location) IN ('sulaimani, iraq', 'erbil, iraq')`? That would be a little bit more manageable. I think that the `Location` value is free-form anyway, so could be difficult unless users are consistent and don't make spelling errors!"
}
] |
[
{
"body": "<blockquote>\n<pre><code> LOWER(Location) LIKE 'sulaimani, iraq' or LOWER(Location) LIKE 'erbil, iraq'\n</code></pre>\n</blockquote>\n<p>It is not necessary to use <code>LIKE</code> if you want an exact match. The <code>=</code> is sufficient in that case.</p>\n<pre><code> LOWER(Location) = 'sulaimani, iraq' or LOWER(Location) = 'erbil, iraq'\n</code></pre>\n<p>And as @TobySpeight already <a href=\"https://codereview.stackexchange.com/questions/266474/se-data-explorer-users-by-city#comment526447_266474\">commented</a>, you can then change it to an <code>IN</code>.</p>\n<pre><code> LOWER(Location) IN ('sulaimani, iraq', 'erbil, iraq')\n</code></pre>\n<p>That won't work if you want to actually use <code>LIKE</code> to do a fuzzier match, e.g.</p>\n<pre><code> LOWER(Location) LIKE '%, iraq'\n</code></pre>\n<p>But in that case, you could create a <a href=\"https://data.stackexchange.com/meta.stackoverflow/query/5646/temporary-tables-indexes-and-procedures-work\" rel=\"nofollow noreferrer\">temporary table</a> with the data as you want and query that, possibly joining the original table. By "data as you want", I mean lowercased and possible only the part after the ", " in this case. For other queries, you might have different requirements.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T12:22:03.883",
"Id": "266475",
"ParentId": "266474",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "266475",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T10:23:28.883",
"Id": "266474",
"Score": "3",
"Tags": [
"sql",
"stackexchange"
],
"Title": "SE Data Explorer: Users by City"
}
|
266474
|
<p>I have created this interface as part of my C++ learning path. <a href="/q/17793298">This post</a> inspired me a lot.</p>
<p>The idea is to use its concrete implementations to perform some actions before and after any change of the wrapped variable.</p>
<p>In the same fashion, by overriding <code>getValue()</code> a mock can be created for unit testing.</p>
<p>For instance an implementation may notify an observer when the underlying variable changes, another one could be used as a mock for unit testing and so on.</p>
<pre><code>#pragma once
#define CREATE_MEMORY_CELL_IMPLEMENTATION(NAME) \
template<class T> \
class NAME : public MemoryManager::IMemoryCell<T> \
{ \
public: \
using MemoryManager::IMemoryCell<T>::operator=; \
using MemoryManager::IMemoryCell<T>::value; \
NAME(T v) : IMemoryCell<T>(v) {} \
protected: \
void setValue(const T& val) override; \
T getValue() const override; \
};
namespace MemoryManager{
template<class T>
class IMemoryCell {
public:
IMemoryCell(T v): value(v) {}
operator T() const { return getValue(); }
// modifiers
IMemoryCell& operator=(T v) { setValue(v); return *this; }
IMemoryCell& operator+=(T v) { setValue(value + v); return *this; }
IMemoryCell& operator-=(T v) { setValue(value - v); return *this; }
IMemoryCell& operator*=(T v) { setValue(value * v); return *this; }
IMemoryCell& operator/=(T v) { setValue(value / v); return *this; }
IMemoryCell& operator%=(T v) { setValue(value % v); return *this; }
IMemoryCell& operator&=(T v) { setValue(value & v); return *this; }
IMemoryCell& operator|=(T v) { setValue(value | v); return *this; }
IMemoryCell& operator^=(T v) { setValue(value ^ v); return *this; }
IMemoryCell& operator<<=(T v) { setValue(value << v); return *this; }
IMemoryCell& operator>>=(T v) { setValue(value >> v); return *this; }
// increment & decrement
IMemoryCell& operator++() { setValue(value + 1); return *this; } // prefix increment
IMemoryCell& operator--() { setValue(value - 1); return *this; } // prefix decrement
T operator++(int) { T old = value; setValue(value + 1); return old; } // postfix increment
T operator--(int) { T old = value; setValue(value - 1); return old; } // postfix decrement
protected:
T value;
virtual void setValue(const T& val) = 0;
virtual T getValue() const { return value; }
};
}
</code></pre>
<p>Here is an example of its usage:</p>
<pre><code>CREATE_MEMORY_CELL_IMPLEMENTATION(testMemory)
template <class T> void testMemory<T>::setValue(const T& val) {
std::cout << "Old value: " << value << std::endl;
value = val;
std::cout << "New value: " << value << std::endl;
};
template <class T> T testMemory<T>::getValue() const {
return 0x61;
};
</code></pre>
<p>What I don't like is that the derived class must explicitly declare the use of the base class assignment operator and <code>value</code> member. As you can see my first idea was to use a macro to create a skeleton for the implementation.</p>
<p>This approach has two major drawbacks:</p>
<ol>
<li>It limits the possibilities in terms of concrete implementation class. For instance a new member cannot be defined inside the skeleton.</li>
<li>The definition of the overridden methods is cumbersome.</li>
</ol>
<p>What do you think?</p>
<p>An alternative could be to define it as a concrete class and to pass <code>getValue()</code> and <code>setValue()</code> as function pointers into the constructor. Do you think that could be a better approach?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T14:46:39.453",
"Id": "526453",
"Score": "0",
"body": "Welcome to the Code Review Community. I think this question could be a good question, but currently it borders on being too theoretical which is [off-topic](https://codereview.stackexchange.com/help/on-topic) on Code Review. I don't see a unit test here so I don't know why you added the unit-testing flag. Is the code working in one of your projects? 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-28T14:48:48.977",
"Id": "526454",
"Score": "0",
"body": "Please edit the question to have enough details to allow an adequate answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-30T13:43:30.913",
"Id": "526590",
"Score": "0",
"body": "I replaced [tag:unit-testing] with [tag:mocks] as that seems more appropriate and specific."
}
] |
[
{
"body": "<h1>Answers to your questions</h1>\n<blockquote>\n<p>As you can see my first idea was to use a macro to create a skeleton for the implementation.\n[...]\nWhat do you think?</p>\n</blockquote>\n<p>I think this is a bad idea. Macros should be avoided where possible. Manually creating a new class that inherits from <code>MemoryManager::IMemoryCell</code> is not much more work than calling the macro and then providing two out-of-class definitions for <code>getValue()</code> and <code>setValue()</code>.</p>\n<blockquote>\n<p>An alternative could be to define it as a concrete class and to pass the getValue and setValue as function pointers into the constructor. Do you think that it can be a better approach?</p>\n</blockquote>\n<p>Yes, just like you can pass a comparator function to a <code>std::map</code>.</p>\n<p>That said:</p>\n<h1>It will never be perfect</h1>\n<p>You will never be able to perfectly wrap a base type and have getter/setter functions that will always be called. It works in simple situations, but consider a function that takes a pointer or reference to a fundamental type, and performs operations via this pointer / reference. The type system will not allow an implicit cast from pointer-to-wrapper to pointer-to-fundamental-type. And if you would somehow provide a conversion operator to do so, then because the type information is lost, the getter and setter functions will no longer be called.</p>\n<p>I think the best course of action here is to stop wanting to wrap fundamental types this way, and find other ways to do mocking or notification.</p>\n<p>Apart from this, there are a few small things:</p>\n<h1>Incorrect constructor in macro</h1>\n<p>The constructor of <code>class NAME</code> is wrong, to access the base class you have to provide the whole type name of the base class:</p>\n<pre><code>NAME(T v) : MemoryManager::IMemoryCell<T>(v) {}\n</code></pre>\n<h1>Missing default constructor</h1>\n<p>Your classes don't have default constructors, so the following won't compile:</p>\n<pre><code>testMemory<int> x;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-30T13:12:26.087",
"Id": "266527",
"ParentId": "266477",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T12:42:55.963",
"Id": "266477",
"Score": "3",
"Tags": [
"c++",
"template",
"wrapper",
"observer-pattern",
"mocks"
],
"Title": "Abstract wrapper for fundamental types"
}
|
266477
|
<p><a href="https://leetcode.com/problems/combination-sum-iv/" rel="nofollow noreferrer">Problem Statement</a></p>
<pre><code>Given an array of distinct integers nums and a target integer target, return the number of possible combinations that add up to target.
The answer is guaranteed to fit in a 32-bit integer.
Input: nums = [1,2,3], target = 4
Output: 7
Explanation:
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
</code></pre>
<p>I am new to dynamic programming and am trying to implement a top-down memoization approach instead of using a bottom up tabulation approach as per usual practice. This is my attempt at implementing. Have also left the Map and Javascript object variants in the code in case it is useful for discussion.</p>
<pre><code>var combinationSum4 = function(nums, target) {
// const myDict = {};
const myDict = new Map();
const ans = memoCombinationSum4(nums, target, myDict)
return ans;
}
var memoCombinationSum4 = function(nums, target, myDict) {
if (target === 0) {
myDict[target] = 1;
// myDict.set(target, 1);
return 1;
} else if (target < 0) {
return 0;
}
let total = 0;
for (let ele of nums) {
if (!myDict[target - ele]) {
total+= memoCombinationSum4(nums, target - ele, myDict)
} else {
total += myDict[target - ele]
// total += myDict.get(target - ele);
}
}
// myDict.set(target, total);
myDict[target] = total;
return total;
}
</code></pre>
<p>It passes all basic test cases and got “Time Limit Exceeded” at the following input</p>
<pre><code>var nums = [10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200,210,220,230,240,250,260,270,280,290,300,310,320,330,340,350,360,370,380,390,400,410,420,430,440,450,460,470,480,490,500,510,520,530,540,550,560,570,580,590,600,610,620,630,640,650,660,670,680,690,700,710,720,730,740,750,760,770,780,790,800,810,820,830,840,850,860,870,880,890,900,910,920,930,940,950,960,970,980,990,111];
var target = 999
</code></pre>
<p>Can anyone tell me what I’m missing out here? Not sure whether I have implemented my modification from the naïve recursive approach correctly or there is something about Javascript I have missed out which is causing the time limit to be exceeded. Let me know if more information is required to solve the problem.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T17:38:54.763",
"Id": "526459",
"Score": "0",
"body": "Please add a problem statement."
}
] |
[
{
"body": "<p>If you tried logging what happens you would probably be able to figure it out :D</p>\n<p>The good part is that it has nothing to do with your program, but it has to do with JS.</p>\n<pre><code> if (!myDict[target - ele]) {\n total+= memoCombinationSum4(nums, target - ele, myDict)\n }\n</code></pre>\n<p>If myDict = { 1: 0 }, then !myDict[1] is true. Welcome to the world of pain that is JS.</p>\n<p>The solution is:</p>\n<pre><code> if (myDict[target - ele] === undefined) {\n total += memoCombinationSum4(nums, target - ele, myDict)\n }\n</code></pre>\n<p>It still takes some seconds (I have no idea what is the time constraint), but at least it completes :D</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T04:48:14.613",
"Id": "530056",
"Score": "0",
"body": "Thank you for your answer, your suggestion works for me. Do you mind adding the reasons why my initial code is causing the slowness?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T22:46:10.303",
"Id": "530137",
"Score": "0",
"body": "They were not causing slowness, you literally had infinite recursion, because some elements in myDict had value 0. In other words - if (!myDict[target - ele]) always executed, because if(!0) is true."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-07T23:48:58.227",
"Id": "530138",
"Score": "0",
"body": "Ok I see, so even with cases of `target - ele` having value 0, which was computed before, the code before change will call the recursion instead of using the cached valued in the object. I guess my next question will be why you said this is a \"pain that is JS\". Not sure if it's an algorithm flaw now or something unique about JS that I'm not knowing about."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T10:35:28.747",
"Id": "530161",
"Score": "0",
"body": "Because js does not have types. What you meant by !map[key] is something like !map.isSet(key) (basically if the key does not yet exist - a null check). You probably went over this multiple times, and didn't notice the bug, because each time you said to your self \"if key does not exist, do recursion\", came to the end of the program and was like WTF. JS has falsey values - null, undefined, 0, Nan, false AND \"\", which basically resolve to false in an if statement. With !map[key] this is a null check only if you are sure that the value is an object."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-08T10:44:00.497",
"Id": "530162",
"Score": "0",
"body": "So it is a falsey check and not a null check. And it is easy to forget that because it works most of the time. But JS does not care. As it does not care for something like 5 + '3' and just happily concatenates to '53'. In a typed language you wouldn't have this issue."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-18T12:40:49.907",
"Id": "268114",
"ParentId": "266478",
"Score": "0"
}
},
{
"body": "<h3>Making memoziation super-easy to read</h3>\n<p>The common pattern of memoization looks something like this:</p>\n<pre><code>const fun = function(param) {\n if (memo[param] !== undefined) return memo[param];\n\n // compute the actual answer, for "param"\n let answer = ...\n\n memo[param] = answer;\n return answer;\n};\n</code></pre>\n<p>That is, the first thing that happens in the function is checking if the answer is already in the memoization cache. If yes, return it, otherwise carry on with the regular computation. At the end of the function, put the answer into the cache, and then return it. The memoization cache is not referenced anywhere else in the function, only at the very beginning and at the very end. This is very easy to understand.</p>\n<p>The posted code can be refactored to fit this pattern, and it will be easier to focus on the main logic of the computation.</p>\n<p>And I recommend renaming <code>myDict</code> to <code>memo</code> or <code>cache</code>.</p>\n<h3>Using a local function</h3>\n<p>Instead of passing around <code>nums</code> and <code>myDict</code> as function parameters, you could make <code>memoCombinationSum4</code> a local function, and let it use those variables in its context:</p>\n<pre><code>const memo = new Map();\nmemo[0] = 1;\n\nconst memoCombinationSum4 = function(target) {\n // use memo as in the earlier example\n // ...\n\n // nums is available from the enclosing context\n // ...\n};\n\nreturn memoCombinationSum4(target);\n</code></pre>\n<h3>Stop trying targets that are too high</h3>\n<p>Notice that if <code>nums</code> is sorted, then when an element is higher than the target, you don't need to check the renaming values:</p>\n<pre><code>var combinationSum4 = function(nums, target) {\n const sorted = [...nums].sort((a, b) => a - b);\n\n const memo = new Map();\n memo[0] = 1;\n\n const memoCombinationSum4 = function(target) {\n if (memo[target] !== undefined) {\n return memo[target];\n }\n\n let total = 0;\n for (const num of sorted) {\n if (target < num) break;\n total += memoCombinationSum4(target - num);\n }\n\n memo[target] = total;\n return total;\n };\n\n return memoCombinationSum4(target);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-18T20:56:44.270",
"Id": "269109",
"ParentId": "266478",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T13:32:07.707",
"Id": "266478",
"Score": "1",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"time-limit-exceeded",
"dynamic-programming"
],
"Title": "Leetcode 377. Combination Sum IV Javascript Memoization attempt"
}
|
266478
|
<p>I found interesting the way <a href="https://docs.python-requests.org" rel="nofollow noreferrer">Python's requests</a> library does the <code>status_code</code> data structure initialization (see <a href="https://github.com/psf/requests/blob/aae78010e987a414c176bddbf474cd554505219c/requests/status_codes.py#L107" rel="nofollow noreferrer">code here</a>). I am reusing it in a hobby project, but instead of using just one configuration variable I want it to initialize a few of them, code below:</p>
<pre><code>from .models import LookupDict
# Copying Requests data structure and some refactor to data initialization
network_types = LookupDict(name='network_types')
_network_types = {
1: ('GSM',),
2: ('UMTS',),
3: ('LTE',)
}
def _fill(_globals_var, globals_var):
for value, titles in _globals_var.items():
for title in titles:
setattr(globals_var, title, value)
def _init():
for _globals_var, globals_var in [
(_network_types, network_types)
]:
_fill(_globals_var, globals_var)
_init()
</code></pre>
<p>So far it's just defined <code>network_types</code> variable but it could initialize as many as you want with both functions <code>_init</code> and <code>_fill</code>.</p>
<p><code>LookupDict</code> is pretty much the same as the <code>requests</code> implementation (see <a href="https://github.com/psf/requests/blob/aae78010e987a414c176bddbf474cd554505219c/requests/structures.py#L89" rel="nofollow noreferrer">code here</a>)</p>
<p>Any comments would be very appreciated. Thanks in advance!</p>
|
[] |
[
{
"body": "<p>With no usage shown, no implementation for <code>LookupDict</code> shown and nothing other than your network type values, this is overdesigned and offers nothing beyond</p>\n<pre><code>class NetworkType(Enum):\n GSM = 1\n UMTS = 2\n LTE = 3\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T18:15:32.397",
"Id": "526465",
"Score": "0",
"body": "I agree with you it is overdesigned if I won't use the purpose this was originally designed for by `requests`, but I just hate to write this, following your example: `NetworkType.GSM.value` every time I will use any of the config values"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T18:28:29.740",
"Id": "526469",
"Score": "0",
"body": "Wouldn't it just be `NetworkType.GSM`? That seems pretty straightforward and readable. The value isn't important in enums, so if your use case is to actually use it, just omit the `(Enum)` from the class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T19:00:10.270",
"Id": "526472",
"Score": "0",
"body": "I actually need the value, thanks for the last tip, I didn't think about it that way"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T21:37:48.083",
"Id": "526480",
"Score": "0",
"body": "PS: LookupDict definition is in the last link"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T16:36:02.963",
"Id": "266484",
"ParentId": "266479",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "266484",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T14:34:06.797",
"Id": "266479",
"Score": "0",
"Tags": [
"python",
"python-3.x"
],
"Title": "Config Variables Initialization | Python"
}
|
266479
|
<p>Made this basic calculator for travel visa calculation since I was tired of doing it by hand multiple times and online calculators gave mixed results. It prints every day the visa is valid and displays how many days are left.</p>
<p>The basic rules:</p>
<ul>
<li>You start out with 90 days.</li>
<li>After using (traveling) a day, it'll only become available again after 180 days.</li>
<li>After not traveling at all for 90 days, your available days reset.</li>
</ul>
<p>This was all we needed, there are far more complications and exceptions to these rules. <strong>Disclaimer: Nobody should use this as sole validation, always double check!</strong></p>
<p>I know input handling is poor, but that isn't much of an issue for my uses.
Mainly interested in improvements to the logic.</p>
<pre><code>from datetime import date, timedelta
# Starting variables
start_days = 90
days_reset_delay = timedelta(days=180)
days_full_reset = 90
planned_trips = []
days_left = start_days
days_not_traveled = 0
# Handle inputs assuming proper values
visa_start_input = input("Enter visa start date (YYYY,MM,DD eg: 2020,11,6): ")
visa_start_input_split = visa_start_input.split(",")
visa_start = date(int(visa_start_input_split[0]), int(visa_start_input_split[1]), int(visa_start_input_split[2]))
visa_end = visa_start + timedelta(days=365)
print("Enter planned/completed trips. Enter \"end\" to stop.")
while True:
trip_input = input("Enter trip start and end date (YYYY,MM,DD eg: 2020,11,8-2020,12,28): ")
if trip_input.lower() == "end":
break
trip_input_split = trip_input.split("-")
trip_start = trip_input_split[0].split(",")
trip_end = trip_input_split[1].split(",")
planned_trips.append([date(int(trip_start[0]), int(trip_start[1]), int(trip_start[2])),
date(int(trip_end[0]), int(trip_end[1]), int(trip_end[2]))])
# Day by day logic and result
for i in range((visa_end - visa_start).days + 1):
day = visa_start + timedelta(days=i)
days_not_traveled += 1
for trip in planned_trips:
if trip[0] <= day <= trip[1]:
days_left -= 1
days_not_traveled = 0
if day == trip[0] + days_reset_delay:
days_left += 1
if trip[0] < trip[1]:
trip[0] += timedelta(days=1)
if days_not_traveled >= days_full_reset:
days_left = start_days
if day + timedelta(days=days_left) == visa_end - timedelta(days=1):
print("VVV Optimal day to travel VVV ---------------------------------------------------------------------")
print(day, "-- Days left:", days_left)
</code></pre>
|
[] |
[
{
"body": "<p>Interesting start to what seems a very useful utility. Future improvements could include console calendar-style formatting for much easier reading, or a desktop or web UI.</p>\n<p>Your <code>YYYY,MM,DD</code> format is unusual. A slight adjustment to use hyphens instead of commas will bring it in line with ISO 8601 which will be more familiar, I think, to users. Or if you don't want to use that, you should use your locale's own date format, <a href=\"https://docs.python.org/3.8/library/locale.html#locale.D_FMT\" rel=\"nofollow noreferrer\">whatever that may be</a>.</p>\n<p>You should separate your <code>Enter trip start and end date</code> into two separate <code>input</code> calls.</p>\n<p>Don't do this:</p>\n<pre><code>visa_start_input_split = visa_start_input.split(",")\nvisa_start = date(int(visa_start_input_split[0]), int(visa_start_input_split[1]), int(visa_start_input_split[2]))\n</code></pre>\n<p>Instead, use <code>date.fromisoformat</code> or <code>datetime.strptime(...).date()</code>.</p>\n<p><code>timedelta(days=365)</code> is not accurate, and unfortunately there's no easy built-in way to do this right. <code>relativedelta(years=1)</code> from <code>dateutil</code> will do the trick.</p>\n<p>I haven't taken the time to understand your algorithm, but mutating your trip data here:</p>\n<pre><code>trip[0] += timedelta(days=1)\n</code></pre>\n<p>is not a good idea, and you should find some other way that preserves the trip data as immutable. If you're able to make it immutable, then this:</p>\n<pre><code>for trip in planned_trips:\n</code></pre>\n<p>should become</p>\n<pre><code>for trip_start, trip_end in planned_trips:\n</code></pre>\n<p>One alternative algorithm is to represent the days-left adjustments as addend vectors in Numpy. This has the potential to execute more quickly, though for the scale of these data that won't matter that much. Numpy has some neat tricks like being able to construct an array of increasing dates in one call to <code>arange</code>. Having separated addends allows your trip data to remain immutable.</p>\n<p>You really should have unit tests, and your unit tests should include a case that exercises the 180-day restoral logic - which your current example does not.</p>\n<h2>Example implementation</h2>\n<p>This includes:</p>\n<ul>\n<li>Unit tests for your own example</li>\n<li>Unit tests for an extended, multi-trip example that exercises the 180-day restoral logic</li>\n<li>Support for input+output date localisation</li>\n<li>Refactored support for output matching your current format (<code>print_flat</code>)</li>\n<li>Support for a calendar-like output (<code>print_calendar</code>)</li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>from dataclasses import dataclass\nfrom datetime import date, timedelta, datetime\nfrom dateutil.relativedelta import relativedelta, SU\nfrom itertools import chain\nfrom locale import setlocale, nl_langinfo, D_FMT, LC_ALL\nfrom typing import Optional, Tuple, Iterable, Collection, Dict\nimport numpy as np\n\n# Calling setlocale(LC_ALL, '') lets it use the default locale as defined by\n# the LANG variable.\nsetlocale(LC_ALL, '')\nDATE_FMT = nl_langinfo(D_FMT)\nfrom calendar import day_abbr, SUNDAY\n\nSTART_DAYS = 90\nDAYS_FULL_RESET = START_DAYS\nDAYS_RESET_DELAY = 180\nONE_DAY = timedelta(days=1)\n\nVISA_LENGTH = relativedelta(\n years=1,\n # needed if the visa is to include e.g. the day of 2021-11-06 when it had\n # started on 2020-11-06\n days=1,\n)\n\n\ndef input_date(title: str, terminate: Optional[str] = None) -> Optional[date]:\n if terminate:\n suffix = f' or "{terminate}"'\n else:\n suffix = ''\n s = input(f'Enter {title} date ({DATE_FMT}){suffix}: ')\n if s == terminate:\n return None\n return datetime.strptime(s, DATE_FMT).date()\n\n\n@dataclass(frozen=True)\nclass Trip:\n # As is standard for Python, this forms a half-closed interval\n start: date # inclusive\n end: date # exclusive\n\n @property\n def n_days(self) -> int:\n return (self.end - self.start).days\n\n def bounds(self, epoch: date) -> Tuple[\n int, # start of decline\n int, # end of decline\n int, # start of include\n int, # end of incline\n ]:\n a = (self.start - epoch).days\n b = (self.end - epoch).days\n return a, b, a + DAYS_RESET_DELAY, b + DAYS_RESET_DELAY\n\n @classmethod\n def from_stdin(cls) -> Iterable['Trip']:\n while True:\n inclusive_start = input_date('trip start', 'end')\n if inclusive_start is None:\n return\n # Assume that the user-provided end date is inclusive ("last day")\n exclusive_end = input_date('trip end') + ONE_DAY\n yield cls(inclusive_start, exclusive_end)\n\n def __lt__(self, other: 'Trip') -> bool:\n return (\n self.start < other.start\n or (self.start == other.start and self.end < other.end)\n )\n\n\n@dataclass(frozen=True)\nclass TripDatabase:\n visa_start: date # inclusive\n visa_end: date # exclusive\n trips: Collection[Trip]\n\n @classmethod\n def from_stdin(cls) -> 'TripDatabase':\n start = input_date('visa start')\n return cls(start, start + VISA_LENGTH, sorted(Trip.from_stdin()))\n\n @property\n def n_days(self) -> int:\n return (self.visa_end - self.visa_start).days\n\n @property\n def n_trips(self) -> int:\n return len(self.trips)\n\n @property\n def days_left(self) -> np.ndarray:\n addends = np.zeros((self.n_trips, self.n_days), dtype=np.int16)\n in_trip = np.zeros((self.n_days + 1,), dtype=bool)\n in_trip[-1] = True # Edge value needed to calculate last run\n\n for i, trip in enumerate(self.trips):\n dec_start, dec_end, inc_start, inc_end = trip.bounds(self.visa_start)\n in_trip[dec_start: dec_end] = True\n\n # Declining through each trip\n addends[i, dec_start: dec_end] = np.arange(-1, -1-trip.n_days, -1)\n # Constant days-used after the trip ...\n addends[i, dec_end: inc_start] = -trip.n_days\n # ... until the recovery period, inclining back to 0\n addends[i, inc_start: inc_end] = np.arange(-trip.n_days, 0, 1)\n\n # Find all of the indices where a reset occurs\n trip_idx = np.flatnonzero(in_trip)\n trip_runs = np.diff(trip_idx) - 1\n # We're too late\n resets = trip_idx[:-1][trip_runs > DAYS_FULL_RESET] + DAYS_FULL_RESET\n\n starts = np.array(\n [\n (trip.start - self.visa_start).days\n for trip in self.trips\n ],\n dtype=np.int16,\n )\n\n # For every reset index, for every trip, if the start index of the trip\n # is prior to the reset index, set all entries after the reset index to\n # 0.\n for reset in resets:\n addends[reset > starts, reset:] = 0\n\n days_left = START_DAYS + np.sum(addends, axis=0)\n return days_left\n\n @property\n def indexed_days_left(self) -> Dict[date, int]:\n return {\n when.astype('O'): left\n for when, left in zip(self.visa_dates, self.days_left)\n }\n\n @property\n def visa_dates(self) -> np.ndarray:\n return np.arange(self.visa_start, self.visa_end)\n\n @property\n def flat_lines(self) -> Iterable[str]:\n for when, days_left in zip(self.visa_dates, self.days_left):\n when_str = when.astype('O').strftime(DATE_FMT)\n yield f'{when_str} -- Days left: {days_left}'\n\n def print_flat(self) -> None:\n print('\\n'.join(self.flat_lines))\n\n @property\n def padding_prefix(self) -> np.ndarray:\n month_start = self.visa_start.replace(day=1)\n return np.arange(month_start, self.visa_start)\n\n @property\n def padding_suffix(self) -> np.ndarray:\n if self.visa_end.day == 1:\n month_end = self.visa_end\n else:\n # The first day of the next month\n month_end = self.visa_end + relativedelta(months=1, day=1)\n\n return np.arange(self.visa_end, month_end)\n\n @property\n def padded_dates(self) -> Iterable[date]:\n for day in chain(self.padding_prefix, self.visa_dates, self.padding_suffix):\n yield day.astype('O')\n\n @property\n def padded_when(self) -> Iterable[str]:\n for day in self.padded_dates:\n yield f'{day.day:3d}'\n\n @property\n def padded_left(self) -> Iterable[str]:\n for _ in self.padding_prefix:\n yield ' '\n for left in self.days_left:\n yield f'{left:3d}'\n for _ in self.padding_suffix:\n yield ' '\n\n @staticmethod\n def print_week(\n day: date,\n cells: Iterable[str],\n first_week_epoch: Optional[date] = None,\n ) -> date:\n if first_week_epoch is None:\n row_day = day\n else:\n row_day = first_week_epoch\n\n if first_week_epoch is not None:\n while row_day < day:\n print(' ', end='')\n row_day += ONE_DAY\n\n for cell in cells:\n print(cell, end='')\n row_day += ONE_DAY\n if row_day.weekday() == SUNDAY or row_day.month != day.month:\n break\n print()\n\n return row_day\n\n def print_calendar(self) -> None:\n iso_days = (6, *range(6))\n week_header = ''.join(f'{day_abbr[d][:2]:>3}' for d in iso_days)\n\n whens = self.padded_when\n lefts = self.padded_left\n day, *_, end_day = self.padded_dates\n\n while day <= end_day:\n print(\n f'{day:%B %Y}\\n'\n f'{week_header}'\n )\n # The Sunday before or on the first day of the given day's month\n month_start = day + relativedelta(day=1, weekday=SU(-1))\n\n self.print_week(day, whens, month_start)\n day = self.print_week(day, lefts, month_start)\n\n while True:\n self.print_week(day, whens)\n next_day = self.print_week(day, lefts)\n month_end = day.month != next_day.month\n day = next_day\n if month_end:\n break\n print()\n\n\ndef test_op() -> None:\n db = TripDatabase(\n visa_start=date(2020, 11, 6),\n visa_end=date(2021, 11, 7),\n trips=(\n Trip(\n date(2020, 11, 8),\n # one day later than OP example due to being exclusive\n date(2020, 12, 29),\n ),\n ),\n )\n days = db.indexed_days_left\n\n assert date(2020, 11, 5) not in days\n assert days[date(2020, 11, 6)] == 90 # visa start\n assert days[date(2020, 11, 7)] == 90\n assert days[date(2020, 11, 8)] == 89 # trip start\n assert days[date(2020, 12, 27)] == 40\n assert days[date(2020, 12, 28)] == 39 # trip end\n assert days[date(2021, 3, 27)] == 39\n assert days[date(2021, 3, 28)] == 90 # reset\n assert days[date(2021, 11, 6)] == 90 # visa end\n assert date(2021, 11, 7) not in days\n\n\ndef test_180() -> None:\n db = TripDatabase(\n visa_start=date(2020, 1, 1),\n visa_end=date(2021, 1, 1),\n trips=(\n Trip(date(2020, 1, 3), date(2020, 2, 1)), # 29 days\n Trip(date(2020, 3, 1), date(2020, 3, 8)), # 7 days\n Trip(date(2020, 6, 1), date(2020, 6, 8)), # 7 days\n ),\n )\n days = db.indexed_days_left\n\n # Visa start\n assert date(2019, 12, 31) not in days\n assert days[date(2020, 1, 1)] == 90\n\n # Trip A\n assert days[date(2020, 1, 2)] == 90\n assert days[date(2020, 1, 3)] == 89\n assert days[date(2020, 1, 30)] == 62\n assert days[date(2020, 1, 31)] == 61\n\n # In this idle period, there's neither enough time to reset nor to restore\n # individual days\n\n # Trip B\n assert days[date(2020, 2, 29)] == 61\n assert days[date(2020, 3, 1)] == 60\n assert days[date(2020, 3, 6)] == 55\n assert days[date(2020, 3, 7)] == 54\n\n # Idle period: same story\n\n # Trip C\n assert days[date(2020, 5, 29)] == 54\n assert days[date(2020, 6, 1)] == 53\n assert days[date(2020, 6, 6)] == 48\n assert days[date(2020, 6, 7)] == 47\n\n # Restoral from trip A\n assert days[date(2020, 7, 1)] == 47\n assert days[date(2020, 7, 2)] == 48\n assert days[date(2020, 7, 29)] == 75\n assert days[date(2020, 7, 30)] == 76\n\n # Restoral from trip B\n assert days[date(2020, 8, 28)] == 76\n assert days[date(2020, 8, 29)] == 77\n\n # In the middle of trip B restoral, reset occurs\n assert days[date(2020, 9, 4)] == 83\n assert days[date(2020, 9, 5)] == 90\n\n\nif __name__ == '__main__':\n # db = TripDatabase.from_stdin() - if you want to enter this manually\n # db.print_flat() or print_calendar() for visual comparison\n test_op()\n test_180()\n</code></pre>\n<h2>Calendar output (180 case)</h2>\n<pre class=\"lang-none prettyprint-override\"><code>January 2020\n Su Mo Tu We Th Fr Sa\n 1 2 3 4\n 90 90 89 88\n 5 6 7 8 9 10 11\n 87 86 85 84 83 82 81\n 12 13 14 15 16 17 18\n 80 79 78 77 76 75 74\n 19 20 21 22 23 24 25\n 73 72 71 70 69 68 67\n 26 27 28 29 30 31\n 66 65 64 63 62 61\n\nFebruary 2020\n Su Mo Tu We Th Fr Sa\n 1\n 61\n 2 3 4 5 6 7 8\n 61 61 61 61 61 61 61\n 9 10 11 12 13 14 15\n 61 61 61 61 61 61 61\n 16 17 18 19 20 21 22\n 61 61 61 61 61 61 61\n 23 24 25 26 27 28 29\n 61 61 61 61 61 61 61\n\nMarch 2020\n Su Mo Tu We Th Fr Sa\n 1 2 3 4 5 6 7\n 60 59 58 57 56 55 54\n 8 9 10 11 12 13 14\n 54 54 54 54 54 54 54\n 15 16 17 18 19 20 21\n 54 54 54 54 54 54 54\n 22 23 24 25 26 27 28\n 54 54 54 54 54 54 54\n 29 30 31\n 54 54 54\n\nApril 2020\n Su Mo Tu We Th Fr Sa\n 1 2 3 4\n 54 54 54 54\n 5 6 7 8 9 10 11\n 54 54 54 54 54 54 54\n 12 13 14 15 16 17 18\n 54 54 54 54 54 54 54\n 19 20 21 22 23 24 25\n 54 54 54 54 54 54 54\n 26 27 28 29 30\n 54 54 54 54 54\n\nMay 2020\n Su Mo Tu We Th Fr Sa\n 1 2\n 54 54\n 3 4 5 6 7 8 9\n 54 54 54 54 54 54 54\n 10 11 12 13 14 15 16\n 54 54 54 54 54 54 54\n 17 18 19 20 21 22 23\n 54 54 54 54 54 54 54\n 24 25 26 27 28 29 30\n 54 54 54 54 54 54 54\n 31\n 54\n\nJune 2020\n Su Mo Tu We Th Fr Sa\n 1 2 3 4 5 6\n 53 52 51 50 49 48\n 7 8 9 10 11 12 13\n 47 47 47 47 47 47 47\n 14 15 16 17 18 19 20\n 47 47 47 47 47 47 47\n 21 22 23 24 25 26 27\n 47 47 47 47 47 47 47\n 28 29 30\n 47 47 47\n\nJuly 2020\n Su Mo Tu We Th Fr Sa\n 1 2 3 4\n 47 48 49 50\n 5 6 7 8 9 10 11\n 51 52 53 54 55 56 57\n 12 13 14 15 16 17 18\n 58 59 60 61 62 63 64\n 19 20 21 22 23 24 25\n 65 66 67 68 69 70 71\n 26 27 28 29 30 31\n 72 73 74 75 76 76\n\nAugust 2020\n Su Mo Tu We Th Fr Sa\n 1\n 76\n 2 3 4 5 6 7 8\n 76 76 76 76 76 76 76\n 9 10 11 12 13 14 15\n 76 76 76 76 76 76 76\n 16 17 18 19 20 21 22\n 76 76 76 76 76 76 76\n 23 24 25 26 27 28 29\n 76 76 76 76 76 76 77\n 30 31\n 78 79\n\nSeptember 2020\n Su Mo Tu We Th Fr Sa\n 1 2 3 4 5\n 80 81 82 83 90\n 6 7 8 9 10 11 12\n 90 90 90 90 90 90 90\n 13 14 15 16 17 18 19\n 90 90 90 90 90 90 90\n 20 21 22 23 24 25 26\n 90 90 90 90 90 90 90\n 27 28 29 30\n 90 90 90 90\n\nOctober 2020\n Su Mo Tu We Th Fr Sa\n 1 2 3\n 90 90 90\n 4 5 6 7 8 9 10\n 90 90 90 90 90 90 90\n 11 12 13 14 15 16 17\n 90 90 90 90 90 90 90\n 18 19 20 21 22 23 24\n 90 90 90 90 90 90 90\n 25 26 27 28 29 30 31\n 90 90 90 90 90 90 90\n\nNovember 2020\n Su Mo Tu We Th Fr Sa\n 1 2 3 4 5 6 7\n 90 90 90 90 90 90 90\n 8 9 10 11 12 13 14\n 90 90 90 90 90 90 90\n 15 16 17 18 19 20 21\n 90 90 90 90 90 90 90\n 22 23 24 25 26 27 28\n 90 90 90 90 90 90 90\n 29 30\n 90 90\n\nDecember 2020\n Su Mo Tu We Th Fr Sa\n 1 2 3 4 5\n 90 90 90 90 90\n 6 7 8 9 10 11 12\n 90 90 90 90 90 90 90\n 13 14 15 16 17 18 19\n 90 90 90 90 90 90 90\n 20 21 22 23 24 25 26\n 90 90 90 90 90 90 90\n 27 28 29 30 31\n 90 90 90 90 90\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T00:46:29.713",
"Id": "526485",
"Score": "1",
"body": "I mutated it to check for the days_reset_delay. Which seems like a poor way of doing it. Instead it should check if the date 180 days prior was part of a trip. But only once per day instead of per trip.\nWondering if there's a better way of looking up a date within a range than using the for loop on trips.\nThanks for the great tips btw!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T03:31:29.670",
"Id": "526607",
"Score": "1",
"body": "@SimonJ Rather than checking if the current day was part of a trip 180 days ago, you can just form an addend range that - 180 days after the trip start - recovers the allotted days, as vectorized with numpy."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T16:12:07.503",
"Id": "266482",
"ParentId": "266480",
"Score": "6"
}
},
{
"body": "<p>modular:</p>\n<ul>\n<li>use <code>if __name__ == "__main__"</code> guard to execute code, to allow imports</li>\n<li>use functions to encapsulate the logic and prevent unnecessary globals</li>\n<li>use class(es) to encapsulate the state -</li>\n<li>use constants as globals or class variables - the whole <code># Starting variables</code> block</li>\n<li>consider naming the file <code>__main__.py</code> and adding a <code>setup.py</code> thus after installation you'll be able to do <code>python -m <package name from setup.py></code> to start your program even without knowing the location</li>\n</ul>\n<p>logical:</p>\n<ul>\n<li><code>trip_input.lower() == "end":</code> can be replaced by just <code>.strip() == ""</code> and then you can do the common double-return/enter to end the input like for SMTP or likes and prevents relying on a specific, locale specific, string</li>\n<li>use standard format e.g. <code>yyyy-mm-dd</code> or likes that are defined for the whole world, such as ISO and you'll have less problems with parsing or converting to proper types - which will break e.g. when using a wide-character input methods (e.g. for Japanese) <code>int(1)</code> vs <code>datetime.strptime("1", "%S")</code> (<code>%S Second as a decimal number [00,61]</code>)</li>\n<li>don't use indicies when not necessary, instead use unpacking because you <em>might</em> encounter a missing index thus <code>IndexError</code></li>\n<li>move numbers such as <code>365</code> and strings such as <code>"-"</code> i.e. constants to constants - class/global variables because those are not changing which will allow you not to make a typo in the logic</li>\n<li>consider using <a href=\"https://docs.python.org/3/library/dataclasses.html\" rel=\"nofollow noreferrer\">dataclasses</a> for the <code>planned_trips.append(...)</code> unless you can utilize <code>datetime</code> object directly with parsing from ISO format</li>\n</ul>\n<p>visual:</p>\n<ul>\n<li>replace <code>print()</code> with <a href=\"https://docs.python.org/3/howto/logging.html#logging-advanced-tutorial\" rel=\"nofollow noreferrer\"><code>logging</code></a></li>\n<li>use proper quotes where required - don't use <code>\\</code> as if you're in bash, use e.g. <code>'Hello "world"'</code> or <code>"Hello 'world'"</code> strings instead</li>\n<li>use longer variables than <code>i</code> even for indicies, it'll actually help you later on if you know what that index actually represents; or if it's not an index then just use <code>for _ in range(...)</code> to "remove" the variable completely</li>\n<li><code>Ctrl-C</code> will break your <code>while True</code> but also your program - consider using <code>except KeyboardInterrupt</code> or signal handling to exit from the program properly/cleanly and perhaps with a message</li>\n<li>nesting loops is ugly, consider moving it to functions that are named cleanly e.g. <code>calculate_days_left()</code> for the inner <code>for</code>?</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T08:26:10.457",
"Id": "266497",
"ParentId": "266480",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T14:52:57.423",
"Id": "266480",
"Score": "12",
"Tags": [
"python",
"datetime"
],
"Title": "Python EU travel visa calculator"
}
|
266480
|
<p>I work on asp.net core 2.2 web API using C# language</p>
<p>I need to rewrite function below with best syntax and with best practice</p>
<p>web API below get Excel file from upload and return Excel file</p>
<p>it working without any issue but I need to rewrite it with best syntax and practice</p>
<p>some points I need to changes :</p>
<p>concatenate path is best thing using</p>
<p>are streaming using correctly</p>
<p>are memory copying file is correct</p>
<pre><code>[HttpPost, DisableRequestSizeLimit]
[Route("Upload")]
public IActionResult Upload()
{
try
{
var DisplayFileName = Request.Form.Files[0];
string fileName = DisplayFileName.FileName.Replace(".xlsx", "-") + Guid.NewGuid().ToString() + ".xlsx";
string Month = DateTime.Now.Month.ToString();
string DirectoryCreate = myValue1 + "\\" + Month + "\\" + fileName;
string exportDirectory = myValue2 + "\\" + Month;
string exportPath = myValue2 + "\\" + Month + "\\" + fileName;
string FinalPath = exportPath;
if (!Directory.Exists(DirectoryCreate))
{
Directory.CreateDirectory(DirectoryCreate);
}
if (!Directory.Exists(exportDirectory))
{
Directory.CreateDirectory(exportDirectory);
}
CExcel ex = new CExcel();
if (DisplayFileName.Length > 0)
{
var filedata = ContentDispositionHeaderValue.Parse(Request.Form.Files[0].ContentDisposition).FileName.Trim('"');
var dbPath = Path.Combine(DirectoryCreate, fileName);
using (var stream = new FileStream(dbPath, FileMode.Create))
{
Request.Form.Files[0].CopyTo(stream);
stream.Flush();
stream.Close();
}
GC.Collect();
string error = "";
int rowCount = 0;
string inputTemplatePath = "";
var InputfilePath = System.IO.Path.Combine(GetFilesDownload, "DeliveryGeneration_Input.xlsx");
bool areIdentical = ex.CompareExcel(dbPath, InputfilePath, out rowCount, out error);
if (areIdentical == true)
{
List<InputExcel> inputexcellist = new List<InputExcel>();
inputexcellist = ex.Import(dbPath);
List<string> mods = new List<string>();
mods = inputexcellist.Select(x => x.ModuleName).Distinct().ToList();
var OutputfilePath = System.IO.Path.Combine(GetFilesDownload, "DeliveryGeneration_Output.xlsx");
if (System.IO.Directory.Exists(Path.Combine(exportDirectory, fileName)))
{
throw new Exception("Ok so the error message IS right.");
}
System.IO.File.Copy(OutputfilePath, Path.Combine(exportDirectory, fileName), true);
SqlConnection con;
foreach (var m in mods)
{
List<InputExcel> inputmodulelist = new List<InputExcel>();
inputmodulelist = inputexcellist.Where(x => x.ModuleName == m).ToList();
var dtimport = DatatableConversion.ToDataTable(inputmodulelist);
DataTable dtexport = new DataTable();
dtexport = _deliveryService.LoadExcelToDataTable(_connectionString, dtimport);
ex.Export(dtexport, m, exportPath);
}
}
var memory2 = new MemoryStream();
using (var stream = new FileStream(exportPath, FileMode.Open))
{
stream.CopyTo(memory2);
}
memory2.Position = 0;
return File(memory2, "text/plain", Path.GetFileName(exportPath));
}
else
{
return BadRequest();
}
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex}");
}
}
</code></pre>
<p><strong>Update original post</strong></p>
<p>function above get excel file as input with some data</p>
<p>then I search on database for matched data input</p>
<p>then get matched data on database on output file</p>
<p>then on last download it with output data</p>
<p>I using name space</p>
<pre><code>using ClosedXML.Excel;
using OfficeOpenXml;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T17:38:17.620",
"Id": "526458",
"Score": "0",
"body": "wait a minute, how does it work ? I can see you're storing the file in a directory, and in the end you're loading an excel from the database. Is the file stored twice ? as it seems you're getting a full `DataTable` from the database, not some metadata that could reference the actual file. please give us more details."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T17:40:51.170",
"Id": "526460",
"Score": "0",
"body": "1-get Excel file I uploaded from front end\n2- create folder path as input\n3-get data from database and export data to excel sheet with multi tab\n4-then download out file multi tab it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T17:43:38.240",
"Id": "526461",
"Score": "0",
"body": "I get input file then fill it with data from database then output Excel file with data come from database"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T17:54:37.943",
"Id": "526463",
"Score": "0",
"body": "What Excel library are you using ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T18:23:52.187",
"Id": "526468",
"Score": "0",
"body": "i updated original post"
}
] |
[
{
"body": "<h2><strong>Naming Convention</strong></h2>\n<p>current code is not using <code>camelCase</code> naming convention on local <code>variables</code>, and also is not given a good naming to some variables like <code>DisplayFileName</code>, <code>Month</code>, <code>DirectoryCreate</code> ..etc.it should be cameled-case.</p>\n<p>Some variables have wrong naming like <code>DisplayFileName</code> it should be <code>file</code> because it's used for <code>Request.Form.Files[0]</code> and not to <code>Request.Form.Files[0].FileName</code>. <code>dbPath</code> is not best name for explaining a file that is related to the stored one. It could be changed to <code>fileToComparePath</code> since it's going to be compared with the input file and the <code>exportPath</code> can be <code>fileExportPath</code>.</p>\n<p>it's important to always differs between <code>Directory</code> and <code>File</code> paths by either suffix the <code>file</code> or <code>dir</code> to the name, otherwise, it won't be a clear enough to other developers.</p>\n<p>When dealing with <code>paths</code> you should always use the built-in methods for like <code>System.IO.File</code> and <code>System.IO.Directory</code>. This would ensure the compatibility with the current system requirements.</p>\n<p>Short names are fast to type, easy to miss, and hard to follow. So, try to avoid short names like <code>CExcel ex = new CExcel();</code> it would be better to name it <code>excel</code> rather than <code>ex</code>, and also <code>var m in mods</code> in the <code>foreach</code> loop.</p>\n<p>Always give your variables a good explainable naming.</p>\n<h2><strong>using</strong></h2>\n<p>with <code>using</code> clause, there is no need to <code>Flush</code> or <code>Close</code> or <code>Dispose</code>, as it would automatically do that at the end of the block.</p>\n<p>So this :</p>\n<pre><code>using (var stream = new FileStream(dbPath, FileMode.Create))\n{\n Request.Form.Files[0].CopyTo(stream);\n stream.Flush();\n stream.Close();\n}\n</code></pre>\n<p>should be like this :</p>\n<pre><code>using (var stream = new FileStream(dbPath, FileMode.Create))\n{\n // you should use Write(stream) instead, or reset the stream position.\n Request.Form.Files[0].CopyTo(stream); \n}\n</code></pre>\n<p><strong>Unused variables</strong>\n<code>FinalPath</code>, <code>filedata</code>, <code>inputTemplatePath</code>, <code>con</code> why they're still there ? you should remove unused variables.</p>\n<p><strong>Other Notes</strong></p>\n<ul>\n<li>When working with files and directories, it would be wise to use the built-in methods <code>Directory</code>, <code>File</code> and <code>Path</code> to avoid any unexcepted exceptions that have been already covered by them.</li>\n<li>with <code>if</code> conditions, don't put the exception or the error at the <code>else</code>, keep it at the top as it would be clearer than to be at the end of the code.</li>\n<li>when doing <code>ToList()</code> it'll return a new <code>List</code>.</li>\n<li>with <code>Stream</code> always use <code>Write</code> instead of <code>CopyTo</code> as <code>Write</code> is specific use and optimized for <code>Stream</code>, while <code>CopyTo</code> is built for all compatible collections types.</li>\n</ul>\n<p><strong>Code Comments</strong></p>\n<p>here is some comments on the code (code has been shorten for brevity).</p>\n<pre><code>if (DisplayFileName.Length > 0) // should be inverted.\n{\n// var filedata = ContentDispositionHeaderValue.Parse(Request.Form.Files[0].ContentDisposition).FileName.Trim('"'); //unused \n \n var dbPath = Path.Combine(DirectoryCreate, fileName); // this would return ../path/month/fileName-SomeGUID.xlsx/fileName-SomeGUID.xlsx\n\n using (var stream = new FileStream(dbPath, FileMode.Create))\n {\n Request.Form.Files[0].CopyTo(stream);\n // the Flush() and Close are handled by the `using` blocks\n// stream.Flush();\n// stream.Close();\n }\n \n// GC.Collect(); // unnecessary\n \n string error = ""; // use null;\n \n int rowCount = 0;\n \n// string inputTemplatePath = ""; //unused\n \n var InputfilePath = System.IO.Path.Combine(GetFilesDownload, "DeliveryGeneration_Input.xlsx");\n \n bool areIdentical = ex.CompareExcel(dbPath, InputfilePath, out rowCount, out error); // rowCount and error have never been checked. what happens if they have values ? \n\n\n if (areIdentical == true)\n {\n// List<InputExcel> inputexcellist = new List<InputExcel>();// unnecessary\n \n List<InputExcel> inputexcellist = ex.Import(dbPath);\n \n// List<string> mods = new List<string>(); // unnecessary\n \n // it could be used in the foreach directlry \n List<string> mods = inputexcellist.Select(x => x.ModuleName).Distinct().ToList();\n \n var OutputfilePath = System.IO.Path.Combine(GetFilesDownload, "DeliveryGeneration_Output.xlsx");\n \n // This is unnecessary as the `File.Copy` ovewrite flag is true.\n // Although Directory.Exists should be File.Exists \n // if (System.IO.Directory.Exists(Path.Combine(exportDirectory, fileName)))\n // {\n // throw new Exception("Ok so the error message IS right.");\n // }\n\n // Path.Combine(exportDirectory, fileName) has the same value of exportPath \n System.IO.File.Copy(OutputfilePath, Path.Combine(exportDirectory, fileName), true);\n\n\n// SqlConnection con; // unused\n\n foreach (var m in mods) // m should be moduleName or name\n {\n// List<InputExcel> inputmodulelist = new List<InputExcel>(); // unnecessary\n\n List<InputExcel> inputmodulelist = inputexcellist.Where(x => x.ModuleName == m).ToList();\n\n DataTable dtimport = DatatableConversion.ToDataTable(inputmodulelist); \n \n// DataTable dtexport = new DataTable(); // unnecessary\n\n DataTable dtexport = _deliveryService.LoadExcelToDataTable(_connectionString, dtimport);\n\n ex.Export(dtexport, m, exportPath);\n\n }\n }\n \n \n var memory2 = new MemoryStream();\n \n using (var stream = new FileStream(exportPath, FileMode.Open))\n {\n stream.CopyTo(memory2);\n }\n \n memory2.Position = 0;\n \n \n // Path.GetFileName(exportPath) is equal to fileName\n // "text/plain" ? why ? you should use the appropriate mime type for Excel \n // for .xls = application/vnd.ms-excel\n // for .xlsx = application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\n // or just use the ClosedXML Web API Extension\n return File(memory2, "text/plain", Path.GetFileName(exportPath)); \n\n}\nelse\n{\n // invert the if, and move this at the top of blocks \n return BadRequest();\n}\n</code></pre>\n<p><strong>Suggested Revision</strong></p>\n<pre><code>if(Request.Form.Files.Length == 0)\n{\n throw new InvalidOperationException(" No Files"); \n}\n\nvar file = Request.Form.Files[0];\n\nvar fileName = $"{Path.GetFileNameWithoutExtension(file.FileName)}-{Guid.NewGuid()}.xlsx";\n\nFunc<string, string> generateFilePath = (path) => \n !string.IsNullOrWhiteSpace(path) && !string.IsNullOrWhiteSpace(fileName) \n ? Path.Combine(Directory.CreateDirectory(path).FullName, DateTime.Today.Month.ToString() , fileName) \n : null;\n\nvar fileToComparePath = generateFilePath(myValue1);\n\nvar fileToExportPath = generateFilePath(myValue2);\n\nif(fileToComparePath == null)\n{\n throw new ArgumentNullException(nameof(fileToComparePath));\n}\n\nif(fileToExportPath == null)\n{\n throw new ArgumentNullException(nameof(fileToExportPath));\n}\n\nusing(var fileStream = File.Create(dbPath))\n{\n fileStream.Write(file);\n}\n\nif(!ex.CompareExcel(fileToComparePath, Path.Combine(GetFilesDownload, "DeliveryGeneration_Input.xlsx"), out int rowCount, out string error))\n{\n return BadRequest();\n}\n\nFile.Copy(Path.Combine(GetFilesDownload, "DeliveryGeneration_Output.xlsx"), fileToExportPath, true);\n\nCExcel excel = new CExcel();\n\nforeach (var moduleName in excel.Import(dbPath).Select(x => x.ModuleName).Distinct())\n{\n var inputModuleList = inputexcellist.Where(x => x.ModuleName == moduleName).ToList();\n\n var tableImport = DatatableConversion.ToDataTable(inputModuleList);\n \n var tableExport = _deliveryService.LoadExcelToDataTable(_connectionString, tableImport);\n\n excel.Export(tableExport, moduleName, fileToExportPath);\n}\n\nMemoryStream excelFileStream = new MemoryStream();\n\nusing(var fileStream = File.Open(fileToExportPath, FileMode.Open))\n{\n fileStream.Write(excelFileStream);\n}\n\nreturn File(excelFileStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName); \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T07:04:57.607",
"Id": "526489",
"Score": "0",
"body": "thank you very much for your advices but there are more things i need to ask 1-string exportDirectory = myValue2 + \"\\\\\" + Month; so my question are there are another way to concate path without using \"\\\\\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T07:07:26.787",
"Id": "526490",
"Score": "0",
"body": "also another thing how to avoid error The process cannot access the file because it is being used by another process when create new file on my code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T14:14:22.453",
"Id": "526518",
"Score": "0",
"body": "@ahmedbarbary use `Path.Combine` to concatenate paths as of my example above. For file processing, you should consider using `SafeFileHandle` https://docs.microsoft.com/en-us/dotnet/api/microsoft.win32.safehandles.safefilehandle?view=net-5.0"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T15:57:12.670",
"Id": "526526",
"Score": "0",
"body": "can you please help me how to use safefilehandle according to code above please only that what i need how to use safe file handle on code above. can you please help me"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-30T06:22:34.530",
"Id": "526569",
"Score": "0",
"body": "also how to use async task on web api above"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T23:27:13.173",
"Id": "266493",
"ParentId": "266481",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T15:03:16.180",
"Id": "266481",
"Score": "0",
"Tags": [
"c#",
"asp.net-core",
"asp.net-web-api",
"asp.net-mvc-4",
"asp.net-core-webapi"
],
"Title": "Web Api to upload excel file"
}
|
266481
|
<p>I am attempting to extract the absolute differences image between two input images and then enhance the intensity (brightness) channel in HSV color space with the given times. The workflow is like below.</p>
<p><a href="https://i.stack.imgur.com/0zVma.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0zVma.png" alt="MainWorkflow" /></a></p>
<p>The processing of a batch of files is considered. Thus, the input is path strings <code>input_path1</code> and <code>input_path2</code>. The third parameter is the times for multiplying on intensity channel. As the result, with the input paths <code>./1/</code> and <code>./2/</code>, the image pair <code>./1/1.png</code> and <code>./2/1.png</code> will be taken as the inputs and the next image pair is <code>./1/2.png</code> and <code>./2/2.png</code>.</p>
<p><strong>The experimental implementation</strong></p>
<pre><code>template<typename T>
void difference_and_enhancement(std::string input_path1, std::string input_path2, T enhancement_times,
std::string output_path, bool output_leading_zero, std::string filename_extension = ".png")
{
// Clear output
std::filesystem::remove_all(output_path);
std::filesystem::create_directory(output_path);
for (std::size_t i = 1; i <= 1000; i++)
{
std::string filename1 = input_path1 + std::to_string(i) + filename_extension;
if (std::filesystem::is_regular_file(filename1) == false)
{
std::cout << filename1 << " is not a regular file." << "\n";
return;
}
std::string filename2 = input_path2 + std::to_string(i) + filename_extension;
if (std::filesystem::is_regular_file(filename2) == false)
{
std::cout << filename2 << " is not a regular file." << "\n";
return;
}
std::cout << "Read " << filename1 << "\n";
auto image1 = cv::imread(filename1, cv::ImreadModes::IMREAD_COLOR);
std::cout << "Read " << filename2 << "\n";
auto image2 = cv::imread(filename2, cv::ImreadModes::IMREAD_COLOR);
char buff[100];
if (output_leading_zero)
{
snprintf(buff, sizeof(buff), "%s%03d%s", output_path.c_str(), i, filename_extension.c_str());
}
else
{
snprintf(buff, sizeof(buff), "%s%d%s", output_path.c_str(), i, filename_extension.c_str());
}
std::cout << "Output filename = " << buff << "\n";
// Difference
cv::Mat diffImage;
cv::absdiff(image1, image2, diffImage);
cv::Mat img_hsv;
cvtColor(diffImage, img_hsv, CV_RGB2HSV);
std::vector<cv::Mat> hsv_channels;
cv::split(img_hsv, hsv_channels);
cv::Mat h_image = hsv_channels[0];
cv::Mat s_image = hsv_channels[1];
cv::Mat v_image = hsv_channels[2];
cv::Mat output_hsv;
std::vector<cv::Mat> hsv_channels_output;
hsv_channels_output.push_back(h_image);
hsv_channels_output.push_back(s_image);
v_image.forEach<double>([&](double element, const int* position) { return element * static_cast<decltype(element)>(enhancement_times); });
hsv_channels_output.push_back(v_image);
cv::merge(hsv_channels_output, output_hsv);
cv::Mat output;
cvtColor(output_hsv, output, CV_HSV2RGB);
std::cout << "size = " << output.size() << "\n";
cv::imwrite(std::string(buff), output);
}
}
</code></pre>
<p><strong>The usage example</strong></p>
<pre><code>int main()
{
difference_and_enhancement(
"./1/",
"./2/",
100,
"./OutputImages/",
false);
return 0;
}
</code></pre>
<p>All suggestions are welcome.</p>
|
[] |
[
{
"body": "<p>The biggest simplification and speed improvement would be to avoid using the <code>split</code> function. I would suggest just multiplying the 3-channel image directly. Something like this:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>cv::multiply(img_hsv, Scalar(1, 1, enhancement_times), img_hsv);\n</code></pre>\n<p>Of course, we can’t know for sure which is faster until we compare the running time for each of the alternatives.</p>\n<p>In general, try to avoid creating new image variables when you transform the image. Use the same memory block for both the input and the output of the function, like I did above. You have <code>diffImage</code>, <code>img_hsv</code>, <code>output_hsv</code> and <code>output</code>, as well as the two arrays with single-channel images. But all these operations are single-pixel operations that can be performed in-place, without needing the additional memory. In-place operations not only save on memory, they are faster too, as there is less memory being mapped into the processor’s cache.</p>\n<p>If you do want to use the split (it might be faster?), make sure you don’t create a second array for the modified images:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>cv::split(img_hsv, hsv_channels);\nhsv_channels[2].forEach<double>([&](double element, const int* position) { return element * static_cast<decltype(element)>(enhancement_times); });\ncv::merge(hsv_channels, img_hsv);\n</code></pre>\n<p>The multiplication can be written more concisely (for better readability) as this:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>hsv_channels[2] *= enhancement_times;\n</code></pre>\n<p>(Apparently the <code>*=</code> operator doesn’t work for multi-channel images.)</p>\n<p>Instead of <code>"\\n"</code> use <code>'\\n'</code>, since this is a single character.</p>\n<p><code>cv::imread()</code> returns <a href=\"https://docs.opencv.org/4.5.2/d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56\" rel=\"nofollow noreferrer\">an invalid image</a> if the reading fails for whatever reason. You should always check the image to make sure it was read.</p>\n<p>I am confused as to why <code>enhancement_times</code> needs a templated type. If you make it <code>double</code>, your function doesn’t need to be a template. You later cast it to <code>double</code> anyway (<code>decltype(element)</code> is <code>double</code>). I don’t see anyone using an integer multiplier here that cannot be exactly represented in a <code>double</code> either.</p>\n<p><code>cvtColor</code> is used twice without the <code>cv::</code> namespace decorator. This works because one of the inputs is a type defined in that namespace, but it’s nice to be explicit about what function you use. Likewise <code>snprintf</code> doesn’t have a namespace.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T08:43:04.650",
"Id": "526496",
"Score": "0",
"body": "Yes, avoid making OpenCV allocate the pixel storage! That simple observation has rescued my own programs' performance so many times. It's often worth creating a structure with `cv::Mat` members to enable re-use of the intermediate images across multiple calls."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T23:04:12.387",
"Id": "266492",
"ParentId": "266486",
"Score": "4"
}
},
{
"body": "<p>This function has <strong>too many responsibilities</strong>, as is evident by the number and variety of arguments. We have mixed filesystem and image processing, making a function that's hard to reuse (e.g. in a GUI program, where we might want to preview the result before saving) and hard to unit-test. If we split it, we have smaller, more readable functions.</p>\n<hr />\n<h2>Other specific issues</h2>\n<p>We probably don't want to abandon processing when one of the image pairs is unsuccessful - just keep a note of the error and continue.</p>\n<p>When we compose the output filename, we're using the wrong format specifier for <code>i</code> - it's a <code>std::size_t</code>, so we should be using <code>%zu</code> (that said, <code>unsigned</code> should be sufficient for the small numbers we're using).</p>\n<p><code>buff</code> is far to generic a name for the variable, and the arbitrary size (100 chars) may be insufficient. It's easy to check the return from <code>std::snprintf()</code> to see whether truncation occurred, yet this isn't done. Personally, I'd use <code>std::ostringstream</code> composition instead.</p>\n<p>Logging output should go to <code>std::clog</code> and error messages to <code>std::cerr</code>.</p>\n<p>We should cast the result of the multiplication, not the multiplicand. Otherwise values such as <code>1.5</code> won't have the expected outcome (and the function wouldn't need to be a template). And we know the type of <code>element</code> is <code>double</code>, so we can use that directly, rather than <code>decltype()</code>. That said, I don't see any reason not to simply use <code>cv::Mat</code>'s <code>operator*=()</code>.</p>\n<p><code>std::array</code> is more efficient than <code>std::vector</code> for the <code>cv::split</code>.</p>\n<p><code>diffImage</code> follows a different naming pattern than the rest of the variables.</p>\n<hr />\n<h1>Modified code</h1>\n<p>Incorporating the above advice, but not making full reuse of the image storage:</p>\n<pre><code>#include <array>\n#include <filesystem>\n#include <iostream>\n#include <string>\n\n#include <opencv2/core.hpp>\n#include <opencv2/imgcodecs.hpp>\n#include <opencv2/imgproc.hpp>\n\ncv::Mat read_file(const std::string& filename)\n{\n if (!std::filesystem::is_regular_file(filename)) {\n std::clog << filename << " is not a regular file.\\n";\n return {};\n }\n auto image = cv::imread(filename, cv::ImreadModes::IMREAD_COLOR);\n if (image.empty()) {\n std::cerr << filename << " could not be decoded.\\n";\n }\n return image;\n}\n\ntemplate<typename T>\ncv::Mat difference_and_enhancement(const cv::Mat& image1, const cv::Mat& image2, T enhancement_times)\n{\n // Difference\n cv::Mat img_diff;\n cv::absdiff(image1, image2, img_diff);\n cv::Mat img_hsv;\n cv::cvtColor(img_diff, img_hsv, cv::COLOR_RGB2HSV);\n\n std::array<cv::Mat,3> hsv_channels;\n cv::split(img_hsv, hsv_channels);\n\n hsv_channels[2] *= enhancement_times; // V channel\n\n cv::merge(hsv_channels, img_hsv);\n cv::cvtColor(img_hsv, img_diff, cv::COLOR_HSV2RGB);\n return img_diff;\n}\n\ntemplate<typename T>\nunsigned difference_and_enhancement(std::string input_path1, std::string input_path2,\n T enhancement_times,\n std::string output_path,\n bool output_leading_zero, std::string filename_extension = ".png")\n{\n // Clear output\n std::filesystem::remove_all(output_path);\n std::filesystem::create_directory(output_path);\n\n unsigned error_count = 0;\n\n for (unsigned i = 1; i <= 1000; ++i) {\n auto image1 = read_file(input_path1 + std::to_string(i) + filename_extension);\n if (image1.empty()) continue;\n auto image2 = read_file(input_path2 + std::to_string(i) + filename_extension);\n if (image2.empty()) continue;\n\n auto output = difference_and_enhancement(image1, image2, enhancement_times);\n\n std::ostringstream out_name(output_path, std::ios_base::ate);\n if (output_leading_zero) {\n out_name << std::setfill('0') << std::setw(3);\n }\n out_name << i << filename_extension;\n std::clog << out_name.str() << " size = " << output.size() << '\\n';\n cv::imwrite(out_name.str(), output);\n }\n\n return error_count;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T09:45:00.233",
"Id": "266499",
"ParentId": "266486",
"Score": "2"
}
},
{
"body": "<h2>Naming</h2>\n<p>The technique looks like unsharp mask, but performed on the most intense channel of RGB pixel (V component). Although <code>unbrighten_mask</code> might sound like a German word (I don't know any German), I believe it better fits since the code performs similar actions.</p>\n<h2>Unclear usage</h2>\n<p>At the moment the code has contradictory interface. On one hand, it seems like an utility program, but then the arguments are hardcoded. On the other hand, it cannot be used as a library function as it is too specific.</p>\n<p>Usually a function that does something similar would be expected to return by value, but since OpenCV does not really play well with standard C++, it is probably better to just modify the input <code>cv::Mat</code>, as <a href=\"https://codereview.stackexchange.com/users/151754/cris-luengo\">Cris</a> suggested. I'm also unsure about usefulness of the template parameter. If linkage was an issue, <code>static</code> specifier would fit well (the function is too big for <code>inline</code> for my taste).</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>static void unbrighten_mask(cv::Mat lhs_image, cv::Mat rhs_image, double v_coefficient) {\n /* implementation */\n}\n</code></pre>\n<p>Since OpenCV does shallow copy anyway (without atomic reference counting, by the way!), accepting by value should do just fine since users can either pass the object itself or use <code>.clone()</code></p>\n<h2>Input validation</h2>\n<p>The difference function expects the type and the dimensions to be the same. At the moment it seems like the responsibility falls on the user. If OpenCV doesn't have internal validation and good error messages, then notifying about the error would be great.</p>\n<pre><code>if (lhs_image.type() != rhs_image.type() || lhs_image.size != rhs_image.size)\n{\n throw std::invalid_argument("Either types or dimensions of input images are not the same");\n}\n</code></pre>\n<p>Notice that in the original code, type mismatch case is not possible (I believe <code>cv::imread</code> always returns <code>CV_8UC3</code> typed matrix for colored images), but size check is still needed.</p>\n<h2>Implementation</h2>\n<p>Notice that the optimization <a href=\"https://codereview.stackexchange.com/users/151754/cris-luengo\">Cris</a> suggested can only be performed if the input is interleaved layout. It is worth adding documentation to specify that the image is expected to be in RGB interleaved form. YUV formats, for example, do not have interleaved counterparts, they are always planar.</p>\n<p>I would go one step further from what <a href=\"https://codereview.stackexchange.com/users/75307/toby-speight\">Toby</a> said and would use <a href=\"https://en.cppreference.com/w/cpp/utility/format/format\" rel=\"nofollow noreferrer\"><code>std::format</code></a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-30T17:45:28.480",
"Id": "526595",
"Score": "0",
"body": "Oh yes, `std::format` - I still need to remind myself that exists!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-30T17:23:40.620",
"Id": "266531",
"ParentId": "266486",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "266492",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T17:39:27.610",
"Id": "266486",
"Score": "2",
"Tags": [
"c++",
"strings",
"file",
"image",
"opencv"
],
"Title": "Batch extracting differences between two images with enhancement using opencv"
}
|
266486
|
<p>I created some tooltips using <code>javascript</code> but after writing the code I found it a lot more complicated and hard to read/understand is there any way to shortened my code and make it more logical and efficient.</p>
<pre class="lang-javascript prettyprint-override"><code>var tooltip = (function () {
'use strict';
const PREFIX = 'data-tooltip';
const SUFFIX = ['pointer-direction', 'position', 'content'];
const REQUIRED_ATTRIBUTES = [];
SUFFIX.forEach((item) => {
REQUIRED_ATTRIBUTES.push(PREFIX + '-' + item);
});
const POSITIONS = [
'top-left-corner',
'top-center',
'top-right-corner',
'right-center',
'bottom-right-corner',
'bottom-center',
'bottom-left-corner',
'left-center',
'middle',
];
const DIRECTIONS = [
'top-start',
'top',
'top-end',
'right-start',
'right',
'right-end',
'bottom-start',
'bottom',
'bottom-end',
'left-start',
'left',
'left-end',
];
DIRECTIONS.forEach((direction, position) => {
if (direction === 'top-start') {
if (POSITIONS[position] === 'top-left-corner') {
} else if (POSITIONS[position] === 'top-center') {
} else if (POSITIONS[position] === 'top-right-corner') {
} else if (POSITIONS[position] === 'right-center') {
} else if (POSITIONS[position] === 'bottom-right-corner') {
} else if (POSITIONS[position] === 'bottom-center') {
} else if (POSITIONS[position] === 'bottom-left-corner') {
} else if (POSITIONS[position] === 'left-center') {
} else if (POSITIONS[position] === 'middle') {
}
} else if (direction === 'top') {
if (POSITIONS[position] === 'top-left-corner') {
} else if (POSITIONS[position] === 'top-center') {
} else if (POSITIONS[position] === 'top-right-corner') {
} else if (POSITIONS[position] === 'right-center') {
} else if (POSITIONS[position] === 'bottom-right-corner') {
} else if (POSITIONS[position] === 'bottom-center') {
} else if (POSITIONS[position] === 'bottom-left-corner') {
} else if (POSITIONS[position] === 'left-center') {
} else if (POSITIONS[position] === 'middle') {
}
} else if (direction === 'top-end') {
if (POSITIONS[position] === 'top-left-corner') {
} else if (POSITIONS[position] === 'top-center') {
} else if (POSITIONS[position] === 'top-right-corner') {
} else if (POSITIONS[position] === 'right-center') {
} else if (POSITIONS[position] === 'bottom-right-corner') {
} else if (POSITIONS[position] === 'bottom-center') {
} else if (POSITIONS[position] === 'bottom-left-corner') {
} else if (POSITIONS[position] === 'left-center') {
} else if (POSITIONS[position] === 'middle') {
}
}
if (direction === 'right-start') {
if (POSITIONS[position] === 'top-left-corner') {
} else if (POSITIONS[position] === 'top-center') {
} else if (POSITIONS[position] === 'top-right-corner') {
} else if (POSITIONS[position] === 'right-center') {
} else if (POSITIONS[position] === 'bottom-right-corner') {
} else if (POSITIONS[position] === 'bottom-center') {
} else if (POSITIONS[position] === 'bottom-left-corner') {
} else if (POSITIONS[position] === 'left-center') {
} else if (POSITIONS[position] === 'middle') {
}
} else if (direction === 'right') {
if (POSITIONS[position] === 'top-left-corner') {
} else if (POSITIONS[position] === 'top-center') {
} else if (POSITIONS[position] === 'top-right-corner') {
} else if (POSITIONS[position] === 'right-center') {
} else if (POSITIONS[position] === 'bottom-right-corner') {
} else if (POSITIONS[position] === 'bottom-center') {
} else if (POSITIONS[position] === 'bottom-left-corner') {
} else if (POSITIONS[position] === 'left-center') {
} else if (POSITIONS[position] === 'middle') {
}
} else if (direction === 'right-end') {
if (POSITIONS[position] === 'top-left-corner') {
} else if (POSITIONS[position] === 'top-center') {
} else if (POSITIONS[position] === 'top-right-corner') {
} else if (POSITIONS[position] === 'right-center') {
} else if (POSITIONS[position] === 'bottom-right-corner') {
} else if (POSITIONS[position] === 'bottom-center') {
} else if (POSITIONS[position] === 'bottom-left-corner') {
} else if (POSITIONS[position] === 'left-center') {
} else if (POSITIONS[position] === 'middle') {
}
}
if (direction === 'bottom-start') {
if (POSITIONS[position] === 'top-left-corner') {
} else if (POSITIONS[position] === 'top-center') {
} else if (POSITIONS[position] === 'top-right-corner') {
} else if (POSITIONS[position] === 'right-center') {
} else if (POSITIONS[position] === 'bottom-right-corner') {
} else if (POSITIONS[position] === 'bottom-center') {
} else if (POSITIONS[position] === 'bottom-left-corner') {
} else if (POSITIONS[position] === 'left-center') {
} else if (POSITIONS[position] === 'middle') {
}
} else if (direction === 'bottom') {
if (POSITIONS[position] === 'top-left-corner') {
} else if (POSITIONS[position] === 'top-center') {
} else if (POSITIONS[position] === 'top-right-corner') {
} else if (POSITIONS[position] === 'right-center') {
} else if (POSITIONS[position] === 'bottom-right-corner') {
} else if (POSITIONS[position] === 'bottom-center') {
} else if (POSITIONS[position] === 'bottom-left-corner') {
} else if (POSITIONS[position] === 'left-center') {
} else if (POSITIONS[position] === 'middle') {
}
} else if (direction === 'bottom-end') {
if (POSITIONS[position] === 'top-left-corner') {
} else if (POSITIONS[position] === 'top-center') {
} else if (POSITIONS[position] === 'top-right-corner') {
} else if (POSITIONS[position] === 'right-center') {
} else if (POSITIONS[position] === 'bottom-right-corner') {
} else if (POSITIONS[position] === 'bottom-center') {
} else if (POSITIONS[position] === 'bottom-left-corner') {
} else if (POSITIONS[position] === 'left-center') {
} else if (POSITIONS[position] === 'middle') {
}
}
if (direction === 'left-start') {
if (POSITIONS[position] === 'top-left-corner') {
} else if (POSITIONS[position] === 'top-center') {
} else if (POSITIONS[position] === 'top-right-corner') {
} else if (POSITIONS[position] === 'right-center') {
} else if (POSITIONS[position] === 'bottom-right-corner') {
} else if (POSITIONS[position] === 'bottom-center') {
} else if (POSITIONS[position] === 'bottom-left-corner') {
} else if (POSITIONS[position] === 'left-center') {
} else if (POSITIONS[position] === 'middle') {
}
} else if (direction === 'left') {
if (POSITIONS[position] === 'top-left-corner') {
} else if (POSITIONS[position] === 'top-center') {
} else if (POSITIONS[position] === 'top-right-corner') {
} else if (POSITIONS[position] === 'right-center') {
} else if (POSITIONS[position] === 'bottom-right-corner') {
} else if (POSITIONS[position] === 'bottom-center') {
} else if (POSITIONS[position] === 'bottom-left-corner') {
} else if (POSITIONS[position] === 'left-center') {
} else if (POSITIONS[position] === 'middle') {
}
} else if (direction === 'left-end') {
if (POSITIONS[position] === 'top-left-corner') {
} else if (POSITIONS[position] === 'top-center') {
} else if (POSITIONS[position] === 'top-right-corner') {
} else if (POSITIONS[position] === 'right-center') {
} else if (POSITIONS[position] === 'bottom-right-corner') {
} else if (POSITIONS[position] === 'bottom-center') {
} else if (POSITIONS[position] === 'bottom-left-corner') {
} else if (POSITIONS[position] === 'left-center') {
} else if (POSITIONS[position] === 'middle') {
}
}
});
})();
</code></pre>
<blockquote>
<p>I know the code is quite huge but it is what it is.</p>
</blockquote>
<p>Apart that, How can I check which elements <strong>inside body</strong> have same attribute presented in <code>REQUIRED_ATTRIBUTES</code> array.</p>
<p><strong>You can see or download the entire code from github <a href="https://gist.github.com/KunalTanwar/bb01947f112febede391fd64bc8f1f81" rel="nofollow noreferrer">gist</a></strong></p>
<p><strong>P.S</strong> I don't want to use <code>jQuery</code>.</p>
<p>Below is the example of</p>
<pre class="lang-html prettyprint-override"><code><button data-tooltip="true" data-tooltip-pointer-direction="bottom" data-tooltip-content="Copy to Clipboard" data-tooltip-position="top-center">
Copy
</button>
</code></pre>
<p><strong>OUTPUT</strong></p>
<p><a href="https://i.stack.imgur.com/dT0fZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dT0fZ.png" alt="Reference Image" /></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T18:15:12.707",
"Id": "526464",
"Score": "2",
"body": "Welcome to Code Review! Please post your entire code in the question itself, rather than as an external link. The way you have made the excerpt, the code doesn't make sense, so according to our rules we can't review it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T01:26:12.423",
"Id": "526486",
"Score": "1",
"body": "Welcome to CR! All of the bodies of these `if`/`else if` chains are empty. Is that intentional? What happens inside of those blocks is pretty important for refactoring the code to use a loop or data structure. If there are common patterns to the actions, then it's much easier to simplify than if there aren't regular patterns, and what those patterns are exactly would dictate how to actually simplify it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T07:28:48.070",
"Id": "526492",
"Score": "0",
"body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T07:30:33.617",
"Id": "526493",
"Score": "0",
"body": "As far as I can see, the `DIRECTIONS.forEach()` statement does precisely nothing - lots of tests and no actions. Is the code unfinished?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T10:41:28.430",
"Id": "526499",
"Score": "0",
"body": "`the code is […] what it is` The code presented is not what is kept on GitHub."
}
] |
[
{
"body": "<p>There are quite a number of things that can be done to simplify the code.</p>\n<h1>Consistency</h1>\n<p>It is important to be consistent in your code. If you express the same thing in two different ways, a reader will assume that there is an important difference between the two. For example, <a href=\"https://tc39.es/ecma262/#sec-literals-string-literals\" rel=\"nofollow noreferrer\">you can write strings with double quotes or single quotes</a>, and if you use double quotes for some strings and single quotes for other strings, then a reader will assume that these are two different kinds of strings that mean two different things.</p>\n<p>In your code, some of your variables are <code>const</code> and some are <code>var</code>. Some of your anonymous functions are <a href=\"https://tc39.es/ecma262/#sec-arrow-function-definitions\" rel=\"nofollow noreferrer\">fat arrow literals</a> and some are <a href=\"https://tc39.es/ecma262/#prod-FunctionExpression\" rel=\"nofollow noreferrer\"><code>function</code> expressions</a>. Make sure that you actually want to express two different things when you do that!</p>\n<h1><code>const</code> over <code>let</code>, never use <code>var</code></h1>\n<p>You should prefer to make all variables <a href=\"https://tc39.es/ecma262/#sec-let-and-const-declarations\" rel=\"nofollow noreferrer\"><code>const</code></a> as much as possible. Only if you absolute must mutate the binding, and there is no way around it, may you use <code>let</code>. Never use <a href=\"https://tc39.es/ecma262/#sec-variable-statement\" rel=\"nofollow noreferrer\"><code>var</code></a>. It is simply a vestige of a bad decision made early on in the language design and cannot be removed because of backwards-compatibility. You should just pretend it never existed.</p>\n<p>So, <code>tooltip</code> should be a <code>const</code>, not a <code>var</code>.</p>\n<h1>Conditionals with empty bodies</h1>\n<pre class=\"lang-ecmascript prettyprint-override\"><code>if (POSITIONS[position] === 'middle') {}\n</code></pre>\n<p>This conditional statement will do the following: it checks whether the condition is true or false. When the condition is false, it will execute nothing. And when the condition is true, it will execute the body, which, however, is empty! So, actually in both cases, nothing gets executed.</p>\n<p>Therefore, it is simply equivalent to just running</p>\n<pre class=\"lang-ecmascript prettyprint-override\"><code>POSITIONS[position] === 'middle'\n</code></pre>\n<p>And since you are not using the result of this expression anywhere, and this expression also does not have any side-effects, it is actually not doing anything at all, and can be removed without changing the result of the code. If we apply this iteratively and recursively, we end up with this:</p>\n<h1>Empty loop</h1>\n<pre class=\"lang-ecmascript prettyprint-override\"><code>DIRECTIONS.forEach((direction, position) => {});\n</code></pre>\n<p>The first thing we will notice is that the parameters are not actually used, so we can simplify this to</p>\n<pre class=\"lang-ecmascript prettyprint-override\"><code>DIRECTIONS.forEach(() => {});\n</code></pre>\n<p>Next, we will notice that the function that is passed to <a href=\"https://tc39.es/ecma262/#sec-array.prototype.foreach\" rel=\"nofollow noreferrer\"><code>Array.prototype.forEach</code></a> does not return anything and has no side-effects, so the loop is actually not doing anything at all, and we can just remove it altogether.</p>\n<h1>Unused variables</h1>\n<p>Once we have removed the loop, we notice that <code>DIRECTIONS</code> and <code>POSITIONS</code> are no longer used in the code and can be safely removed. This leaves us with the following code:</p>\n<pre class=\"lang-ecmascript prettyprint-override\"><code>const tooltip = (() => {\n 'use strict';\n const PREFIX = 'data-tooltip';\n const SUFFIX = ['pointer-direction', 'position', 'content'];\n const REQUIRED_ATTRIBUTES = [];\n\n SUFFIX.forEach((item) => {\n REQUIRED_ATTRIBUTES.push(PREFIX + '-' + item);\n });\n})();\n</code></pre>\n<h1>Higher-level iterators over loops</h1>\n<p>ECMAScript's standard library provides a number of higher-level iteration methods on the <a href=\"https://tc39.es/ecma262/#sec-properties-of-the-array-prototype-object\" rel=\"nofollow noreferrer\"><code>Array.prototype</code> object</a>. You should generally prefer those methods over manual loops.</p>\n<p>For example, when you simply want to map each item of an array to a different item, that's what the <a href=\"https://tc39.es/ecma262/#sec-array.prototype.map\" rel=\"nofollow noreferrer\"><code>Array.prototype.map</code></a> method is for:</p>\n<pre class=\"lang-ecmascript prettyprint-override\"><code>const REQUIRED_ATTRIBUTES = SUFFIX.map((item) => PREFIX + '-' + item);\n</code></pre>\n<p>However, once we make this change, we notice that <code>REQUIRED_ATTRIBUTES</code> is not actually used and can be safely removed. And when we remove <code>REQUIRED_ATTRIBUTES</code>, <code>PREFIX</code> and <code>SUFFIX</code> also become unused.</p>\n<p>Which leaves us with this:</p>\n<pre class=\"lang-ecmascript prettyprint-override\"><code>const tooltip = (() => {\n 'use strict';\n})();\n</code></pre>\n<h1>Final cleanup</h1>\n<p>The body of this IIFE does not return any value nor does it have any side-effect, and thus simply evaluates to <code>undefined</code> and can safely be replaced with this:</p>\n<pre class=\"lang-ecmascript prettyprint-override\"><code>const tooltip = undefined;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T08:48:33.373",
"Id": "266498",
"ParentId": "266487",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T18:03:20.323",
"Id": "266487",
"Score": "0",
"Tags": [
"javascript",
"object-oriented"
],
"Title": "Is there any way to make my JavaScript code more logical and efficient? How to convert functional to OOP in JS?"
}
|
266487
|
<p>For parsing astronomical datasets (mostly images) I have written a parser that reads .fits files in C# .net5.0.</p>
<p>The content part of the file basically constists of a blob (byte array) that holds all the datapoints in a certain order.</p>
<p>What this parser does is read in all those values from the content part. However, since the datatype can be either <code>byte</code>, <code>int16</code>, <code>int32</code>, <code>int64</code>, <code>float</code>, <code>double</code> the data has to be parsed accordingly.</p>
<p>So, here is the code:</p>
<pre class="lang-csharp prettyprint-override"><code>using System;
using System.Buffers;
using System.Buffers.Binary;
using System.IO;
using System.IO.Pipelines;
using System.Linq;
using System.Threading.Tasks;
using FitsLibrary.DocumentParts;
using FitsLibrary.Extensions;
namespace FitsLibrary.Deserialization
{
public class ContentDeserializer : IContentDeserializer
{
private const int ChunkSize = 2880;
public Task<Memory<object>?> DeserializeAsync(PipeReader dataStream, Header header)
{
if (header.NumberOfAxisInMainContent == 0)
{
return Task.FromResult<Memory<object>?>(null);
}
var numberOfBytesPerValue = Math.Abs((int)header.DataContentType / 8);
var numberOfAxis = header.NumberOfAxisInMainContent;
var axisSizes = Enumerable.Range(1, numberOfAxis)
.Select(axisIndex => Convert.ToUInt64(header[$"NAXIS{axisIndex}"])).ToArray();
var axisSizesSpan = new ReadOnlySpan<ulong>(axisSizes);
var totalNumberOfValues = axisSizes.Aggregate((ulong)1, (x, y) => x * y);
Memory<object> dataPointsMemory = new object[totalNumberOfValues];
var dataPoints = dataPointsMemory.Span;
var contentSizeInBytes = numberOfBytesPerValue * Convert.ToInt32(totalNumberOfValues);
var totalContentSizeInBytes = Math.Ceiling(Convert.ToDouble(contentSizeInBytes) / Convert.ToDouble(ChunkSize)) * ChunkSize;
var contentDataType = header.DataContentType;
Span<byte> currentValueBuffer = stackalloc byte[numberOfBytesPerValue];
var bytesRead = 0;
var currentValueIndex = 0;
while (bytesRead < contentSizeInBytes)
{
var chunk = ReadContentDataStream(dataStream).GetAwaiter().GetResult();
var blockSize = Math.Min(ChunkSize, contentSizeInBytes - bytesRead);
bytesRead += blockSize;
for (var i = 0; i < blockSize; i += numberOfBytesPerValue)
{
chunk.Buffer.Slice(i, numberOfBytesPerValue).CopyTo(currentValueBuffer);
dataPoints[currentValueIndex++] = ParseValue(contentDataType, currentValueBuffer);
}
dataStream.AdvanceTo(chunk.Buffer.GetPosition(blockSize), chunk.Buffer.End);
}
return Task.FromResult<Memory<object>?>(dataPointsMemory);
}
private static object ParseValue(DataContentType dataContentType, ReadOnlySpan<byte> currentValueBytes)
{
return dataContentType switch
{
DataContentType.DOUBLE => BinaryPrimitives.ReadDoubleBigEndian(currentValueBytes),
DataContentType.FLOAT => BinaryPrimitives.ReadSingleBigEndian(currentValueBytes),
DataContentType.BYTE => currentValueBytes[0],
DataContentType.SHORT => BinaryPrimitives.ReadInt16BigEndian(currentValueBytes),
DataContentType.INTEGER => BinaryPrimitives.ReadInt32BigEndian(currentValueBytes),
DataContentType.LONG => BinaryPrimitives.ReadInt64BigEndian(currentValueBytes) as object,
_ => throw new InvalidDataException("Invalid data type"),
};
}
private static async Task<ReadResult> ReadContentDataStream(PipeReader dataStream)
{
return await dataStream.ReadAsync().ConfigureAwait(false);
}
}
}
</code></pre>
<p>Now I also wrote some benchmarks for the code:</p>
<pre><code>| Method | Mean | Error | StdDev | Median | Gen 0 | Gen 1 | Gen 2 | Allocated |
|------------------------ |----------:|----------:|----------:|-----------:|----------:|----------:|------:|-----------:|
| WithEmptyContentStream | 1.452 ms | 2.209 ms | 2.949 ms | 0.0068 ms | - | - | - | 488 B |
| With10IntValues | 3.422 ms | 5.172 ms | 6.905 ms | 0.0354 ms | - | - | - | 1456 B |
| With1MillionFloatValues | 79.357 ms | 13.250 ms | 17.688 ms | 70.2609 ms | 4000.0000 | 1000.0000 | - | 34849504 B |
</code></pre>
<p>The benchmarks can be found here: <a href="https://github.com/RononDex/FitsLibrary/blob/development/FitsLibrary.Tests/Benchmarking/ContentDeserializerBenchmarks.cs" rel="nofollow noreferrer">https://github.com/RononDex/FitsLibrary/blob/development/FitsLibrary.Tests/Benchmarking/ContentDeserializerBenchmarks.cs</a></p>
<p>As you can see, the test with 1 Million Float Values (= 4Mb of data) ends up allocating almost 35Mb of data.</p>
<p>Is there any way the above code could be optimised further?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T12:41:46.177",
"Id": "526503",
"Score": "0",
"body": "There's something useful for you in the [upcoming .NET 6](https://devblogs.microsoft.com/dotnet/performance-improvements-in-net-6/) like [Generic Math](https://devblogs.microsoft.com/dotnet/preview-features-in-net-6-generic-math/)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T13:01:07.060",
"Id": "526510",
"Score": "0",
"body": "thanks, that actually looks awesome"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-30T07:06:32.103",
"Id": "526577",
"Score": "0",
"body": "Why don't you `await` the `ReadContentDataStream` call?"
}
] |
[
{
"body": "<p>In general, the optimization problems are supposed to be solved using a profiler, which is more effective than the people looking at the code for the first time. In this case I'd also add that before starting to optimize we would want to ask ourselves if the problem is really there. There are very few situations when a supposedly rare operation consuming 35Mb of memory would be a problem.\nAs for the code,</p>\n<ul>\n<li>You are stating that its purpose is to read files. So how did they end up in a pipe?</li>\n<li>Your function is supposedly async, only it's not. And I don't see a good reason why not, your pipe interface is async, sprinkling async/await as needed should not be too difficult. Or if it is not needed, it'd be better to drop the Tasks</li>\n<li>The return value is weird. I have trouble understanding how a Memory can be conveniently used in the calling code when it does not even know the data type. And since it is still an array, returning Memory gives you nothing, unless the calling code requires it of course.</li>\n<li>The types are there for a reason. By using an array of objects effectively circumventing the type system, you not only make the life of the calling code difficult, you are increasing the memory usage and decrease the performance, since the values need to be boxed to fit into the array of objects.</li>\n<li>Why are you checking the type for each value? It is not going to change.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T12:53:23.663",
"Id": "526505",
"Score": "0",
"body": "Thanks for your reply and time. To answer your questions: The document consists of different parts, header, content an extension headers. All of them are made up of chunks of 2880 bytes length. Usually the bigest part of the document is the content (like a 20MP photo for example). So the content parser is by far the most important part performance wise.\n\nYes I am aware of the async await part, however, other parsers for different document parts can correctly make use of it and its part of the interface, which is why this is marked as async"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T12:54:24.063",
"Id": "526506",
"Score": "0",
"body": "3. The returned data from the parser is not directly accesable to the caller. There are generic helper functions for dealing with this"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T12:54:44.717",
"Id": "526508",
"Score": "0",
"body": "4. That actually sounds like a good idea (not having to check for datatype for every data value). However, I don't see a way how I could just check once, there would still be some kind of if logic somewhere?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T13:40:59.963",
"Id": "526515",
"Score": "0",
"body": "The idea is that since the caller will need to have separate processing for different datatypes anyway, you could create a generic function Deserialize<T> which can work with Memory<T> and in doing so both avoid the boxing overhead and make the code safer and easier to comprehend."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T14:18:40.630",
"Id": "526519",
"Score": "0",
"body": "I already tried using generics, the problem is there is no generic to parse byte streams into the generic type (`BinaryPrimitives` does not support generics). However, you gave me an idea on how to have the `switch` statement only run once, and not for each data type, I might try that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T12:47:57.790",
"Id": "526618",
"Score": "0",
"body": "@RononDex, maybe I did not state it my answer clearly: without the profiler data, my best guess for the reason of the memory consumption would be boxing. It is of course a guess, since profiling it in my mind is quite difficult. But if it is the case, you are not going to fix it until you get rid of your object[]."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T22:47:49.367",
"Id": "266491",
"ParentId": "266489",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-28T21:20:47.897",
"Id": "266489",
"Score": "1",
"Tags": [
"c#",
"performance",
".net-5"
],
"Title": "Performance optimisations using Span<T>"
}
|
266489
|
<p>I am learning JavaScript and this is a simple todo application I made which uses local storage. It is currently running at: <a href="https://koraytugay.github.io/vanillatodo/#" rel="nofollow noreferrer">https://koraytugay.github.io/vanillatodo/#</a>. The code is as follows. I am open to any suggestions on how the structure / architecture or implementation details should/can be improved. Can be cloned from: <a href="https://github.com/koraytugay/vanillatodo/tree/f0b2b263bf9033d9c3ed1dd6acbe027c86cdab6f" rel="nofollow noreferrer">https://github.com/koraytugay/vanillatodo</a> and it looks like this:</p>
<p><a href="https://i.stack.imgur.com/DdP7x.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DdP7x.png" alt="screenshot" /></a></p>
<p><strong>index.html</strong></p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>VanillaTodo</title>
<link rel="stylesheet" href="style.css"/>
</head>
<body>
<div id="container">
<input id="new-todo-input" type="text">
<h2>To Do Items</h2>
<div id="todo-items"></div>
<hr/>
<a href="#" id="delete-all-todo-items">Delete All</a>
</div>
<script type="module" src="src/todoController.js"></script>
</body>
</html>
</code></pre>
<p><strong>todoItemStorageService.js</strong></p>
<pre><code>export default (function() {
const todoItems = 'todo-items';
const idCounter = 'id-counter';
function getTodoItems() {
if (localStorage.getItem(todoItems) === null) {
localStorage.setItem(todoItems, JSON.stringify([]));
localStorage.setItem(idCounter, '1');
}
return JSON.parse(localStorage.getItem(todoItems));
}
function getNextTodoItemId() {
const nextTodoItemId = parseInt(localStorage.getItem(idCounter));
localStorage.setItem(idCounter, '' + (nextTodoItemId + 1));
return nextTodoItemId;
}
function setTodoItems(items) {
localStorage.setItem(todoItems, JSON.stringify(items));
}
function deleteTodoItem(id) {
setTodoItems(getTodoItems().filter(todoItem => todoItem.id !== id));
}
function deleteTodoItems() {
setTodoItems([]);
}
function addTodoItem(todoItem) {
setTodoItems([...getTodoItems(), todoItem]);
}
function getTodoItem(id) {
return getTodoItems().filter(todoItem => todoItem.id === id)[0];
}
function updateTodoItem(todoItem) {
const allTodoItems = getTodoItems();
const itemIndex = allTodoItems.findIndex(item => item.id === todoItem.id);
allTodoItems[itemIndex].text = todoItem.text;
allTodoItems[itemIndex].id = todoItem.id;
allTodoItems[itemIndex].completed = todoItem.completed;
setTodoItems(allTodoItems);
}
return {
getNextTodoItemId,
addTodoItem,
getTodoItems,
getTodoItem,
updateTodoItem,
deleteTodoItem,
deleteTodoItems
}
}());
</code></pre>
<p><strong>todoService.js</strong></p>
<pre><code>import todoItemsStorageService from './todoItemsStorageService.js';
export default (function() {
function Todo(text) {
this.text = text;
this.id = `todo-item-${todoItemsStorageService.getNextTodoItemId()}`;
this.completed = false;
todoItemsStorageService.addTodoItem(this);
}
function toggleTodoItemCompletedStatus(id) {
const todoItem = todoItemsStorageService.getTodoItem(id);
todoItem.completed = !todoItem.completed;
todoItemsStorageService.updateTodoItem(todoItem);
}
const getTodoItems = () => todoItemsStorageService.getTodoItems();
const deleteTodoItem = (id) => todoItemsStorageService.deleteTodoItem(id);
const deleteTodoItems = () => todoItemsStorageService.deleteTodoItems();
return {
Todo,
getTodoItems,
toggleTodoItemCompletedStatus,
deleteTodoItem,
deleteTodoItems
};
}());
</code></pre>
<p><strong>todoController.js</strong></p>
<pre><code>
(function() {
const findById = id => document.querySelector(`#${id}`);
const createElement = (tag, options) => document.createElement(tag, options);
window.addEventListener('load', function() {
refreshUi();
});
findById('new-todo-input').addEventListener('keydown', e => {
if ('Enter' === e.key && e.target.value) {
new todoService.Todo(e.target.value);
e.target.value = '';
refreshUi();
}
});
findById('delete-all-todo-items').addEventListener('click', e => {
todoService.deleteTodoItems();
refreshUi();
});
function toggleTodoCompleteStatus(id) {
todoService.toggleTodoItemCompletedStatus(id);
refreshUi();
}
function deleteTodoItem(id) {
todoService.deleteTodoItem(id);
refreshUi();
}
function createTodoDiv(todoItem) {
const todoDiv = createElement('div');
todoDiv.id = todoItem.id;
const markAsDoneCheckbox = createElement('input');
markAsDoneCheckbox.setAttribute('type', 'checkbox');
markAsDoneCheckbox.addEventListener('click', () => toggleTodoCompleteStatus(todoItem.id));
const todoSpan = createElement('span');
todoSpan.innerText = todoItem.text;
const deleteTodoItemLink = createElement('a');
deleteTodoItemLink.setAttribute('href', '#');
deleteTodoItemLink.addEventListener('click', () => deleteTodoItem(todoItem.id));
deleteTodoItemLink.innerText = '❌';
if (todoItem.completed) {
todoSpan.classList.add('done');
markAsDoneCheckbox.setAttribute('checked', 'checked');
}
todoDiv.appendChild(markAsDoneCheckbox);
todoDiv.appendChild(todoSpan);
todoDiv.appendChild(deleteTodoItemLink);
return todoDiv;
}
function refreshUi() {
const todoItemsDiv = findById('todo-items');
todoItemsDiv.innerHTML = '';
todoService.getTodoItems().forEach(todoItem => todoItemsDiv.appendChild(createTodoDiv(todoItem)));
}
})();
</code></pre>
|
[] |
[
{
"body": "<h2>Poor naming</h2>\n<p>The thing that stood out to me was your naming. Way to wordy. Names only need meaning within the scope they exist in.</p>\n<h2>General points</h2>\n<ul>\n<li><p><code>window</code> is the default object. You don't use <code>window.document</code> or <code>window.window</code> (LOL to be consistent) so why use it for <code>window.addEventListener</code> ?</p>\n</li>\n<li><p>Do not use <code>.setAttribute</code> or <code>.getAttribute</code> for properties that are defined by the DOM.</p>\n</li>\n<li><p>Naming</p>\n<p>Many of the names you have created are just too long. Try to keep them to less than 20 characters, and use no more than 2 words.</p>\n<p>Capitalize acronyms. UI is an acronym of User Interface, thus <code>refreshUi</code> should be <code>refreshUI</code></p>\n</li>\n<li><p>Use arrow function for anon functions.</p>\n</li>\n<li><p>Don't create a function just to redirect to a function</p>\n<p>Example you have <code>window.addEventListener('load', function() { refreshUi(); });</code> can be <code>addEventListener("load", refreshUI)</code></p>\n</li>\n<li><p>Use <code>HTMLElement.textContent</code> rather than <code>HTMLElement.innerText</code></p>\n</li>\n<li><p>You started adding functions to reduce DOM API verbosity but stopped short. Much of your code is just repeated name reference noise.</p>\n</li>\n<li><p><code>localStorage</code> can be accessed via dot or bracket notation. You don't need to use <code>setItem</code> or <code>getItem</code></p>\n</li>\n</ul>\n<h2>Example</h2>\n<p>Rather than rewriting your code I have created an example that removes much of the verbosity by using functions.</p>\n<p>It still works about the same way. Each change to any todo item refreshes the store and repaints the display.</p>\n<h3>Snippet notes</h3>\n<ul>\n<li>As CR snippets do not do modules the code does not include them.</li>\n<li>No access to <code>localStorage</code> so replaces it with Object.</li>\n</ul>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const Tag = (name, props = {}) => Object.assign(document.createElement(name), props);\nconst listener = (el, eName, call, opts ={}) => (el.addEventListener(eName, call, opts), el);\nconst append = (par, ...sibs) => sibs.reduce((p, sib) => (p.append(sib), p), par);\n\nconst localStore = (() => { try { return localStorage } catch(e) { return {} } })();\n\n\nconst todoStorage = (() => {\n const todos = new Map();\n function reset() {\n todos.clear();\n save();\n localStore.UId = 1;\n }\n const save = () => localStore.todoItems = JSON.stringify([...todos.values()]);\n function load() {\n if (!localStore.todoItems) { reset() }\n JSON.parse(localStore.todoItems).forEach(todo => todos.set(todo.id, todo));\n }\n load();\n return Object.freeze({\n get UId() { return Number(localStore.UId = Number(localStore.UId) + 1) },\n delete(id) {\n todos.delete(id);\n save();\n },\n add(...items) {\n for(const todo of items) { todos.set(todo.id, {...todo}) }\n save();\n },\n byId(id) { return todos.has(id) ? {... todos.get(id)} : undefined },\n asArray() { return [...todos.values()].map(todo => ({...todo})) },\n reset, \n });\n})();\n\nconst todoService = (() => {\n const store = todoStorage;\n return Object.freeze({\n Todo(text, completed = false) {\n const todo = { text, completed, id: store.UId };\n store.add(todo);\n return todo;\n },\n get all() { return store.asArray() },\n toggleComplete(id) {\n const todo = store.byId(id);\n if (todo) {\n todo.completed = !todo.completed;\n store.add(todo);\n }\n },\n delete: todoStorage.delete,\n reset: todoStorage.reset,\n });\n})();\n\n(() => {\n const UIEvent = (call, ...args) => e => (call(e, ...args) !== false && refreshUI());\n const actions = {\n enter(e) {\n if (e.key === \"Enter\") {\n service.Todo(e.target.value);\n e.target.value = '';\n } else { return false }\n },\n toggleComplete(e, id) { service.toggleComplete(id) },\n delete(e, id) { service.delete(id) }\n };\n const service = todoService;\n addEventListener('load', refreshUI); \n listener(newTodoInput, \"keydown\", UIEvent(actions.enter));\n listener(deleteAllTodoItems, \"click\", UIEvent(service.reset)); \n function createTodo({id, text, completed}) { \n return append( \n Tag(\"div\"),\n listener( \n Tag(\"input\", {type: \"checkbox\", checked: completed}), \n \"click\", UIEvent(actions.toggleComplete, id)\n ),\n Tag(\"span\", {textContent: text, className: completed ? \"done\" : \"\"}),\n listener(\n Tag(\"a\", {href: \"#\", textContent: \"❌\"}), \n \"click\", UIEvent(actions.delete, id)\n )\n );\n }\n function refreshUI() {\n todoItems.innerHTML = \"\";\n append(todoItems, ...service.all.map(createTodo));\n }\n})();</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.done {\n color: red;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div>\n <input id=\"newTodoInput\" type=\"text\">\n <h2>To Do Items</h2>\n <div id=\"todoItems\"></div>\n <hr/>\n <a href=\"#\" id=\"deleteAllTodoItems\">Delete All</a>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-30T23:45:05.503",
"Id": "526602",
"Score": "0",
"body": "Thank you for your valuable time and your response. Definitely there are many points that I can apply to my code. If it is ok with you, there are some points I do not agree with. (Once I told something like this and it was not well received by a reviewer.) I am trying to understand the code you written now and will be applying most of your suggestions to my own implementation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T00:14:43.403",
"Id": "526603",
"Score": "0",
"body": "I applied some of the suggestions you made: https://github.com/koraytugay/vanillatodo/pull/1/files in case you are interested. For some of your suggestions, I prefer otherwise. I again thank you for your valuable input."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-30T00:13:56.037",
"Id": "266512",
"ParentId": "266494",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "266512",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T00:26:17.860",
"Id": "266494",
"Score": "2",
"Tags": [
"javascript",
"beginner",
"to-do-list"
],
"Title": "Todo App with JavaScript"
}
|
266494
|
<p>I work on a project that is dealing with two databases (Mysql Db on Internet + Sqlite Local Db).
I will explain what I do with my project to build the codes:</p>
<ul>
<li><p>firstly I have (Class "ClsMysql") that contains the following methods and I have the same for "SQLite" (Class "ClsSqlite"):</p>
<pre><code> Public Sub DtFill(ByVal SqlStr As String, ByVal xDt As DataTable, ByVal xPar() As
MySqlParameter)
Dim xCmd As New MySqlCommand() With {
.CommandType = CommandType.Text,
.CommandText = SqlStr,
.Connection = _ServerConnStr
}
If xPar IsNot Nothing Then
For i As Integer = 0 To xPar.Length - 1
xCmd.Parameters.Add(xPar(i))
Next
End If
Dim xDa As New MySqlDataAdapter(xCmd)
xDa.Fill(xDt)
xCmd.Dispose()
xDa.Dispose()
End Sub
'Execute NoN Query Data
Public Sub ExecuteNonQSql(ByVal SqlStr As String, ByVal xPar() As MySqlParameter)
Dim xCmd As New MySqlCommand() With {
.CommandType = CommandType.Text,
.CommandText = SqlStr,
.Connection = _ServerConnStr
}
If xPar IsNot Nothing Then
For i As Integer = 0 To xPar.Length - 1
xCmd.Parameters.Add(xPar(i))
Next
End If
xCmd.ExecuteNonQuery()
xCmd.Dispose()
End Sub
'Execute Scalar Data
Public Function ExecuteScalarSql(ByVal SqlStr As String, ByVal xPar() As MySqlParameter) As Integer
Dim xCmd As New MySqlCommand() With {
.CommandType = CommandType.Text,
.CommandText = SqlStr,
.Connection = _ServerConnStr
}
If xPar IsNot Nothing Then
For i As Integer = 0 To xPar.Length - 1
xCmd.Parameters.Add(xPar(i))
Next
End If
ExecuteScalarSql = xCmd.ExecuteScalar()
xCmd.Dispose()
End Function
</code></pre>
</li>
<li><p>and I have a class for the "Currencies Table" contains the following methods:</p>
<pre><code>Public Sub UpdateRecord()
Try
Select Case _ConnType
'Server
Case 0
'Check Conn
If CheckServerConn() = False Then
xBgwStatus = False
Else
'Check if there is duplication
Select Case CheckExistUpdate_MySql()
Case True
xBgwStatus = False
'Start Update
Case False
Dim xPar(4) As MySqlParameter
xPar(0) = New MySqlParameter("@CurrencyID", MySqlDbType.Int32) With {
.Value = CurrencyID}
xPar(1) = New MySqlParameter("@CurrencyName", MySqlDbType.VarChar) With {
.Value = CurrencyName}
xPar(2) = New MySqlParameter("@CurrencyType", MySqlDbType.VarChar) With {
.Value = CurrencyType}
xPar(3) = New MySqlParameter("@CurrencyPrice1", MySqlDbType.Double) With {
.Value = CurrencyPrice1}
xPar(4) = New MySqlParameter("@CurrencyPrice2", MySqlDbType.Double) With {
.Value = CurrencyPrice2}
xClsMySql.ExecuteNonQSql(xSqlUpdate, xPar)
xBgwStatus = True
End Select
End If
'Local
Case 1
'Check Conn
If CheckLocalConn() = False Then
xBgwStatus = False
Else
'Check if there is duplication
Select Case CheckExistUpdate_Sqlite()
Case True
xBgwStatus = False
'Start Update
Case False
Dim xPar(4) As SQLiteParameter
xPar(0) = New SQLiteParameter("@CurrencyID", MySqlDbType.Int32) With {
.Value = CurrencyID}
xPar(1) = New SQLiteParameter("@CurrencyName", MySqlDbType.VarChar) With {
.Value = CurrencyName}
xPar(2) = New SQLiteParameter("@CurrencyType", MySqlDbType.VarChar) With {
.Value = CurrencyType}
xPar(3) = New SQLiteParameter("@CurrencyPrice1", MySqlDbType.Double) With {
.Value = CurrencyPrice1}
xPar(4) = New SQLiteParameter("@CurrencyPrice2", MySqlDbType.Double) With {
.Value = CurrencyPrice2}
xClsSqlite.ExecuteNonQSql(xSqlUpdate, xPar)
xBgwStatus = True
End Select
End If
End Select
Catch ex As Exception
xBgwStatus = False
MsgBox(Me_MsgErrorStr + vbNewLine + vbNewLine + ex.Message, Me_MsgInfoStyle, Me_MsgCaptionStr)
Finally
_LocalConnStr.Close()
_ServerConnStr.Close()
End Try
End Sub
'SQLite check the duplications
Public Function CheckExistInsert_Sqlite() As Boolean
Dim xPar(0) As SQLiteParameter
xPar(0) = New SQLiteParameter("@CurrencyName", MySqlDbType.VarChar) With {
.Value = CurrencyName}
If xClsSqlite.ExecuteScalarSql(xSqlExistInsert, xPar) > 0 Then
MsgBox("The Record is already exist", Me_MsgInfoStyle, Me_MsgCaptionStr)
Return True
Else
Return False
End If
End Function
'MySQL check the duplications
Public Function CheckExistUpdate_MySql() As Boolean
Dim xPar(1) As MySqlParameter
xPar(0) = New MySqlParameter("@CurrencyID", MySqlDbType.Int32) With {
.Value = CurrencyID}
xPar(1) = New MySqlParameter("@CurrencyName", MySqlDbType.VarChar) With {
.Value = CurrencyName}
If xClsMySql.ExecuteScalarSql(xSqlExistInsert, xPar) > 0 Then
MsgBox("The Record is already exist", Me_MsgInfoStyle, Me_MsgCaptionStr)
Return True
Else
Return False
End If
End Function
</code></pre>
</li>
<li><p>_ConnType will be either "Local" neither "Server".</p>
</li>
</ul>
<p>my question is my way to build the classes and the methods are right or there is better than that way?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T11:37:02.160",
"Id": "526502",
"Score": "0",
"body": "Hi. Welcome to Code Review! It would be helpful if you could provide more details about what your code is supposed to do. What problem is the code meant to solve? What input does it take? What output should it produce? Also, you have plenty of room to post more code. Ideally you'd post your entire program. But at minimum given your question, I think that we should have the entirety of all three classes and any interfaces that they implement. Titles should reflect what the code does, not what is wanted from review."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T10:57:34.477",
"Id": "266500",
"Score": "0",
"Tags": [
"mysql",
"vb.net",
"sqlite"
],
"Title": "Database operations classes and currencies class"
}
|
266500
|
<p>I tried to make a calculator using the Strategy pattern in ASP.Net Core MVC (following an example from the Internet)</p>
<p>Please review my code and tell me what could be wrong and how to make it better?</p>
<p>My interface:</p>
<pre><code>public interface ICalculator
{
double Calculate(double FirstNumber, double SecondNumber);
}
</code></pre>
<p>I also have 4 classes (<code>Addition</code>, <code>Multiplication</code>, <code>Division</code>, <code>Subtraction</code>)
I will attach only one of them because they are almost identical.</p>
<pre><code>public class Addition : ICalculator
{
public double Calculate(double FirstNumber, double SecondNumber)
{
return FirstNumber + SecondNumber;
}
</code></pre>
<p>Also here is my Context class.</p>
<pre><code> public class Context
{
private ICalculator calculator;
public Context (ICalculator operation)
{
calculator = operation;
}
public double execute (double FirstNumber, double SecondNumber)
{
return calculator.Calculate(FirstNumber, SecondNumber);
}
}
</code></pre>
<p>Now here are my MVC elements.
Here is my model and controller.</p>
<pre><code>public class CalcModel
{
public double FirstNumber { get; set; }
public double SecondNumber { set; get; }
public double Result { get; set; }
public CalculationMethod calculationMethod { get; set; }
public enum CalculationMethod
{
Addition = '+',
Substraction = '-',
Multiplication ='*',
Division = '/'
}
}
</code></pre>
<p>Controller:</p>
<pre><code> public IActionResult IndexCalculator()
{
return View(new CalcModel());
}
[HttpPost]
public async Task<IActionResult> IndexCalculator(CalcModel model)
{
ModelState.Clear();
switch (model.calculationMethod)
{
case CalculationMethod.Addition:
Context myAddition = new Context(new Addition());
model.Result = myAddition.execute(model.FirstNumber, model.SecondNumber);
break;
case CalculationMethod.Division:
Context myDivision = new Context(new Division());
model.Result = myDivision.execute(model.FirstNumber, model.SecondNumber);
break;
case CalculationMethod.Multiplication:
Context myMultiplication = new Context(new Multiplication());
model.Result = myMultiplication.execute(model.FirstNumber, model.SecondNumber);
break;
case CalculationMethod.Substraction:
Context mySubstraction = new Context(new Substraction());
model.Result = mySubstraction.execute(model.FirstNumber, model.SecondNumber);
break;
}
return View(model);
}
</code></pre>
|
[] |
[
{
"body": "<p>Here are my observations:</p>\n<h3><code>ICalculator</code></h3>\n<ul>\n<li>As far I as I understand this code's main purpose is to educate yourself. The whole strategy pattern for this extremely simple problem seems an overkill for me. You have written a lots of boilerplate code just to implement something really basic.</li>\n<li>Without knowing the concrete requirements <code>double</code> might be an overkill, with its 8 bytes.\n<ul>\n<li>My advice is to try to restrict the possible value range as much as possible, so in your case a <code>float</code> might be a suitable option as well</li>\n</ul>\n</li>\n<li><code>FirstNumber</code>: In C# we usually name the method's parameters with camelCasing rather than PascalCasing</li>\n<li>In the context of calculator it might make more sense to rename your parameters:\n<ul>\n<li><code>leftHandSide</code> and <code>rightHandSide</code></li>\n<li><code>lhsOperand</code> and <code>rhsOperand</code></li>\n<li>etc.</li>\n</ul>\n</li>\n</ul>\n<h3><code>Addition</code></h3>\n<ul>\n<li>I would advice to use <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members#methods\" rel=\"nofollow noreferrer\">expression bodied methods</a> to make your implementations more concise</li>\n</ul>\n<pre><code>public float Calculate(float lhsOperand, float rhsOperand) => lhsOperand + rhsOperand;\n</code></pre>\n<ul>\n<li>Your strategies have a lots of boiler plate code just to define the <strong>operator</strong>:</li>\n</ul>\n<pre><code>public float Calculate(float lhsOperand, float rhsOperand) => lhsOperand + rhsOperand;\npublic float Calculate(float lhsOperand, float rhsOperand) => lhsOperand - rhsOperand;\npublic float Calculate(float lhsOperand, float rhsOperand) => lhsOperand / rhsOperand;\npublic float Calculate(float lhsOperand, float rhsOperand) => lhsOperand * rhsOperand;\n</code></pre>\n<ul>\n<li>If your problem scope would not be this extremely simple then your strategy should only contain the thing which differs and apply that in the context.</li>\n</ul>\n<pre><code>public float Execute(float lhsOperand, float rhsOperand)\n{\n // Common logic\n ...\n\n // Different logic based on the chosen strategy\n float intermittentResult = calculator.ApplyOperator(lhsOperand, rhsOperand);\n\n // Common logic\n ...\n \n return finalResult;\n}\n</code></pre>\n<h3><code>Context</code></h3>\n<ul>\n<li><code>calculator</code>: This member should be marked as <code>readonly</code> to avoid unintentional replacement</li>\n<li><code>ICalculation operation</code>: Please try to stick to the same terminology everywhere to make your code more readable. Using different terms interchangeably might confuse the code maintainer.</li>\n<li><code>execute</code>: Please use PascalCasing for method names >> <code>Execute</code></li>\n</ul>\n<h3><code>CalcModel</code></h3>\n<ul>\n<li>This abbreviation is absolutely unnecessary and it breaks the consistency / coherence >> <code>CalculationModel</code></li>\n<li><code>CalculationMethod</code>: Here the terminology is again confusing. In math this is called <em>operator</em>. In the <code>Context</code> class you have referred to the interface implementation as <code>operation</code>. Please try to use consistent naming.</li>\n<li>Based on the provided code the values of the enum members do not matter. So, you could omit them without breaking anything.</li>\n<li><code>calculationMethod</code>: In C# property names are usually using PascalCasing, please use consistent naming.</li>\n</ul>\n<h3><code>IndexCalculator</code></h3>\n<ul>\n<li>90% of all the branches share the same code\n<ul>\n<li>This could (and should) be fairly easily refactored:</li>\n</ul>\n</li>\n</ul>\n<pre><code>ICalculator calculator = null;\nswitch (model.calculationMethod)\n{\n case CalculationMethod.Addition:\n calculator = new Addition();\n break;\n case CalculationMethod.Division:\n calculator = new Division();\n break;\n case CalculationMethod.Multiplication:\n calculator = new Multiplication();\n break;\n case CalculationMethod.Substraction:\n calculator = new Substraction();\n break;\n default:\n throw new NotSupportedException($"The provided operator ('{model.calculationMethod}') is unknown.");\n}\n\nContext ctx = new Context(calculator);\nmodel.Result = ctx.execute(model.FirstNumber, model.SecondNumber);\n</code></pre>\n<ul>\n<li>As you can see the common code is extracted and the switch case focuses only on the differences</li>\n<li>I've also added a <code>default</code> branch to handle the unknown operator case</li>\n<li>Since C# 8 you can use <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/switch-expression\" rel=\"nofollow noreferrer\">switch expression</a> which makes your branching more concise:</li>\n</ul>\n<pre><code>ICalculator calculator = model.calculationMethod switch\n{\n CalculationMethod.Addition => new Addition(),\n CalculationMethod.Division => new Division(),\n CalculationMethod.Multiplication => new Multiplication(),\n CalculationMethod.Substraction => new Substraction(),\n _ => throw new NotSupportedException($"The provided operator ('{model.calculationMethod}') is unknown."),\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-30T09:29:55.307",
"Id": "526582",
"Score": "0",
"body": "Thank you so much for such a review! Yes, I used the strategy for educational purposes."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-30T08:20:41.023",
"Id": "266520",
"ParentId": "266507",
"Score": "0"
}
},
{
"body": "<p>This is clearly a training exercise, and reviews on those are notable different because it makes no sense to address the overkill pattern for the simple implementation of mathematical operations. The implementations is simple specifically because the focus here is on the pattern.</p>\n<p>Overall, pattern-wise your code is on the right path.</p>\n<p>Naming-wise, I think you've missed the mark. <code>Context</code> seems to be the <strong>calculator</strong> here, as it performs the calculation. What I mean by that is that you could use a <code>Context</code> object repeatedly, to perform the same mathematical operation of different sets of inputs. In that sense, the <code>Context</code> performs each individual calculation (by passing it down to the specific operation that it was set to perform).<br />\n<code>ICalculation</code> would be better renamed to be <code>IOperation</code>, and <code>Context</code> should be <code>Calculator</code>. It makes more sense from a semantical point of view. My code assumes this name change has occurred.</p>\n<p>One thing that does stick out to me, though, is the controller action. It should not contain the <code>switch</code>, because it violates SRP.</p>\n<p>The purpose of a controller method is to <strong>map</strong> the incoming request to (and outgoing response from) your business logic. It should not contain your business logic itself, because this leads to difficult to read code.</p>\n<p>A more elegant refactoring would be:</p>\n<pre><code>[HttpPost]\npublic async Task<IActionResult> IndexCalculator(CalcModel model)\n{\n ModelState.Clear();\n\n var operation = GetOperation(model.calculationMethod);\n var calculator = new Calculator(operation);\n\n model.Result = calculator.Calculate(model.FirstNumber, model.SecondNumber);\n\n return View(model);\n}\n</code></pre>\n<p>This method body is much clearer to read, from the perspective of the controller action. The controller doesn't care how you decide which operation to calculate with. It cares <em>that</em> you get an operation (decided by some other submethod), and that you then set the model's property based on said calculation.</p>\n<p>Being vague about the specifics of which operation is being chosen here is actually <em>beneficial</em> to the readability of this controller action.</p>\n<p>To achieve this <code>GetOperation</code> can be separated into a submethod of its own. For simplicity, I chose to use a private method in the controller here, but you could definitely abstract this further into a class of its own when the logic is complex enough to warrant it.</p>\n<p>Generally speaking, this kind of logic belongs to the business layer, but it's so trivial in this case that creating an entire business layer for it is a bit overkill (and not the focus of the exercise either).</p>\n<pre><code>private IOperation GetOperation (CalculationMethod calcMethod)\n => calcMethod switch\n {\n CalculationMethod.Addition => new Addition(),\n CalculationMethod.Subtraction => new Subtraction(),\n CalculationMethod.Multiplication => new Multiplication(),\n CalculationMethod.Division => new Division(),\n _ => throw new NotImplementedException($"{nameof(GetOperation)} - CalculationMethod.{calcMethod} was not mapped to an operation!");\n };\n</code></pre>\n<p>I made use of C# 8's new switch pattern (and expression-bodied methods) here because it fits the use case. However, there were several possible ways of implementing this. You could've used the traditional <code>switch</code>, or a <code>Dictionary<CalculationMethod, Func<IOperation></code> as a collection of factory methods, or even an <code>OperationFactory</code> altogether. But this is not the focus of the training exercise you're doing here, so I went with what was shortest and sweetest.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-30T10:16:47.337",
"Id": "266524",
"ParentId": "266507",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T20:59:37.293",
"Id": "266507",
"Score": "1",
"Tags": [
"c#",
"calculator",
"asp.net-mvc",
"strategy-pattern"
],
"Title": "Strategy Design Pattern in ASP.Net Core MVC Project"
}
|
266507
|
<p>I'm using the following code to grab user info from my MySQL database via PHP by using <code>exec</code> to invoke a Python script.</p>
<pre><code><?php
$username = $_GET['username'];
// Clean the username to prevent XSS & hacking attacks
$cleaned_username = htmlspecialchars($username);
// Connect to mysql database via python & return user info
function get_user_info($username) {
$userinfo = exec("python2 get_user_info.py ".$username);
return $userinfo;
}
// Echo the users information
echo get_user_info($_GET['username']);
?>
</code></pre>
<p>But the website keeps lagging out if too many people are using website at once. Having issues with php + python lagging website I check my process list and I see a lot of PHP codes executing at once, is this normal? Do I just need more beefy good server?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-30T07:01:15.697",
"Id": "526576",
"Score": "1",
"body": "\"I check my process list and I see a lot of PHP codes executing at once, is this normal?\" That would seem to be more of a Server Fault question than a Code Review question. Note that you also might want to tell them how many users and what a \"lot\" is."
}
] |
[
{
"body": "<blockquote>\n<pre><code> $userinfo = exec("python2 get_user_info.py ".$username);\n</code></pre>\n</blockquote>\n<p>PHP is perfectly capable of connecting to a MySQL database on its own. Look at the mysqli and PDO extensions. PDO is easier to learn if you are starting from scratch.</p>\n<p>Alternately, Python is capable of generating web pages.</p>\n<p>By doing things the way that you are, you are creating a PHP process that then invokes a shell process that invokes a Python script that calls the database. That's three separate processes for each time this code is called (and that is skipping the Apache/Nginx and MySQL processes). You only need one, either the PHP or the Python, not both. And the shell process is pure waste.</p>\n<p>The <a href=\"https://stackoverflow.com/q/13426541/6660678\">PHP exec is slower</a> than running the same command in the shell directly. It is not meant to be used this way. I don't know but wouldn't be surprised if the PHP process was better about sharing resources when it calls MySQL directly. This is because many people use PHP to call MySQL, so that path is relatively optimized. I'm not sure that <code>exec</code> is nearly as well optimized. In particular, I don't know that it knows that it can pass control back to Apache while the shell script runs. But even if it does know, there is additional overhead at every step.</p>\n<ol>\n<li>PHP has to invoke the shell and wait for a response.</li>\n<li>Shell has to invoke Python and wait for a response.</li>\n<li>Python has to invoke the MySQL server and wait for a response.</li>\n</ol>\n<p>And each of those "wait for a response" may not resume immediately on the response. As the server is doing other things at the same time and these waits are not linked. So when the MySQL server responds, Python gets the information and sends a message that is ready to respond. But the server may do other things before it relays that to shell, adding more overhead. Now the shell passes information to PHP. The server now needs to shut down the Python and shell processes. But we only needed one wait.</p>\n<p>PHP needs information. The MySQL server has it. If they communicate directly, you only have that overhead for a single connection. You don't need the extra two.</p>\n<p>I don't know if this will fix your server problems, but it can't hurt. Note that the overhead here is more likely to make your server memory bound than CPU bound. If CPU or network bound, you probably have a different underlying problem. Although this would increase CPU as well as memory. It's just that it increases memory by more.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-30T07:43:15.957",
"Id": "266519",
"ParentId": "266509",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-29T22:31:46.423",
"Id": "266509",
"Score": "-2",
"Tags": [
"performance",
"php"
],
"Title": "Grab user info from database via exec"
}
|
266509
|
<p>This is my first non-trivial program in my Python. I am coming from a Java background and I might have messed up or ignored some conventions. I would like to hear feedback on my code.</p>
<pre><code>
import nltk
import random
file_name = input()
file = open(file_name, "r", encoding="utf-8")
# nltk.trigrams returns a list of 3-tuples
trigrams = list(nltk.trigrams(file.read().split()))
file.close()
model = {}
for trigram in trigrams:
head = trigram[0] + " " + trigram[1]
tail = trigram[2]
model.setdefault(head, {})
model[head].setdefault(tail, 0)
model[head][tail] += 1
possible_starting_heads = []
sentence_ending_punctuation = (".", "!", "?")
for key in model.keys():
if key[0].isupper() and not key.split(" ")[0].endswith(sentence_ending_punctuation):
possible_starting_heads.append(key)
# Generate 10 pseudo-sentences based on model
for _ in range(10):
tokens = []
# Chooses a random starting head from list
head = random.choice(possible_starting_heads)
# print("Head: ", head)
tokens.append(head)
while True:
possible_tails = list(model[head].keys())
weights = list(model[head].values())
# Randomly select elements from list taking their weights into account
most_probable_tail = random.choices(possible_tails, weights, k=1)[0]
# print("Most probable tail: ", most_probable_tail)
if most_probable_tail.endswith(sentence_ending_punctuation) and len(tokens) >= 5:
tokens.append(most_probable_tail)
# print("Chosen tail and ending sentence: ", most_probable_tail)
break
elif not most_probable_tail.endswith(sentence_ending_punctuation):
tokens.append(most_probable_tail)
# print("Chosen tail: ", most_probable_tail)
head = head.split(" ")[1] + " " + most_probable_tail
elif most_probable_tail.endswith(sentence_ending_punctuation) and len(tokens) < 5:
# print("Ignoring tail: ", most_probable_tail)
tokens = []
head = random.choice(possible_starting_heads)
tokens.append(head)
pseudo_sentence = " ".join(tokens)
print(pseudo_sentence)
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>In the following, I assume that you use Python3 rather than Python2, though I can't say for sure that it makes a difference.</p>\n<p>First, when you parse your file, you could use a context manager:</p>\n<pre><code>file_name = input()\nwith open(file_name, "r", encoding="utf-8") as file:\n # nltk.trigrams returns a list of 3-tuples\n trigrams = list(nltk.trigrams(file.read().split()))\n</code></pre>\n<p>That way, even if an exception is raised by the assignment to trigrams (in either of the 4 method calls), the file stream is properly closed.</p>\n<p>You could simplify your model generation using <code>defaultdict</code> from the <code>collections</code> package. Your way of doing it is actually wrong and I can't say for sure that this option is more pythonic but it might be interesting to know.</p>\n<pre><code>import collections\nmodel = collections.defaultdict(lambda : collections.defaultdict(int))\nfor trigram in trigrams:\n head = trigram[0] + " " + trigram[1]\n tail = trigram[2]\n model[head][tail] += 1\n</code></pre>\n<p>This does not change the behavior of your algorithm, it just feels a bit simpler to me.</p>\n<p>But you can do something more memory-efficient:</p>\n<pre><code>import collections\nmodel = collections.defaultdict(lambda : collections.defaultdict(int))\nfile_name = input()\nwith open(file_name, "r", encoding="utf-8") as file:\n # nltk.trigrams returns a list of 3-tuples\n trigrams = nltk.trigrams(file.read().split())\n for trigram in trigrams:\n head = trigram[0] + " " + trigram[1]\n tail = trigram[2]\n model[head][tail] += 1\n</code></pre>\n<p>Since <code>nltk.trigrams</code> returns an iterator, and since you only use it once, you don't actually need to store it in a list (an operation that will take some time and memory to copy everything from the iterator into the list) before iterating over it. You could even completely remove the <code>trigrams</code> variable and directly do <code>for... in nltk.trigrams...</code>.</p>\n<p>Finally, in your <code>while</code> loop, your <code>most_probable_tail</code> is misnamed: it is not the most probable one, it is the one your algorithm randomly selected using a possibly non-uniform law. I would rather call it <code>candidate_tail</code>, or <code>selected_tail</code>, or, even better, simply <code>tail</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-30T19:28:04.600",
"Id": "266534",
"ParentId": "266521",
"Score": "1"
}
},
{
"body": "<p>Here's a kinda stream-of-consciousness review:</p>\n<h3>reading the file</h3>\n<p><code>input()</code> takes an argument, typically a prompt or question, so the user knows enter something. You could also check <code>sys.argv</code> for a filename on the command line.</p>\n<p>Avoid using names of built in functions (e.g., <code>file</code>) for a variable name.</p>\n<p><code>open()</code> is a context manager, so it can be used in a <code>with</code> statement. In the current code, an exception anywhere in <code>list(nltk.trigrams(file.read().split()))</code> could result in the file being left open. Using a <code>with</code> statement ensures the file is closed:</p>\n<pre><code>with open(file_name, "r", encoding="utf-8") as input_file:\n # nltk.trigrams returns a list of 3-tuples\n trigrams = list(nltk.trigrams(input_file.read().split()))\n</code></pre>\n<h3><code>model</code> data structure</h3>\n<p>Get to know the <code>collections</code> module in the standard library. Here, <code>defaultdict</code> and <code>Counter</code> would be useful.</p>\n<p>A tuple can be a dictionary key, so concatenating the first two items in a trigram is not necessary.</p>\n<pre><code>import collections\n\nmodel = collections.defaultdict(collections.Counter)\n\nfor trigram in trigrams:\n model[trigram[:2]].update(trigram[2:])\n</code></pre>\n<p>Or, to be a little clearer:</p>\n<pre><code>for word1, word2, word3 in trigrams:\n model[(word1, word2)].update((word3,))\n</code></pre>\n<p>Then, first words can be collected at the same time:</p>\n<pre><code>possible_starting_heads = collections.Counter()\n\nfor word1, word2, word3 in trigrams:\n model[(word1, word2)].update((word3,))\n\n if word1[0].isupper() and not word1.endswith(sentence_ending_punctuation):\n possible_starting_heads.update((word1, word2))\n</code></pre>\n<h3>generating sentences</h3>\n<p>If you intend to make lots of sentences, recreating lists of candidate tails and their weights every time may slow things down. Consider restructuring the model to better suit the end use. This can be done all at once:</p>\n<pre><code>new_model = {}\nfor key, counter in model.items():\n new_model[key] = (list(counter.keys()), list(accumulate(counter.values())))\n</code></pre>\n<p><code>most_probable_tail</code> is a misnomer; it's the chosen tail.</p>\n<p>The logic of the <code>if ... elif ... elif</code> statement is not easy to follow, and <code>.endswith(sentence_ending_punctuation)</code> potentially gets called three times.</p>\n<pre><code>tokens = []\n# Chooses a random starting head from list\nhead = random.choice(possible_starting_heads)\n# print("Head: ", head)\ntokens.append(head)\n\nwhile True:\n possible_tails, weights = model[head]\n\n chosen_tail = random.choices(possible_tails, cum_weights=weights, k=1)\n\n if not chosen_tail.endswith(sentence_ending_punctuation):\n tokens.append(most_probable_tail)\n head = (head[1], chosen_tail)\n\n else:\n if len(tokens) >= 5:\n tokens.append(chosen_tail)\n break\n\n else:\n tokens = []\n head = random.choice(possible_starting_heads)\n tokens.append(head)\n\npseudo_sentence = " ".join(tokens)\n</code></pre>\n<h3>other thoughts</h3>\n<p>You can store the first word of a sentence in the model with a key of ('', '') and the second word with a key of ('', word1). Then they don't need to be handled separately when generating the sentences.</p>\n<p>NLTK has a function <code>word_tokenize()</code> that might be helpful. It breaks text into tokens such as words, numbers, and punctuation. It recognized things like <code>Dr.</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T21:00:11.083",
"Id": "526661",
"Score": "0",
"body": "I double-checked after reading your answer, and `file` has been removed from the built-in functions somewhere between Python 2.7 and 3.5, neither of which is still supported. There's no harm avoiding using it as a variable using a somewhat recent version of Python but it shouldn't wreck havoc when that happens."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-30T20:51:49.017",
"Id": "266536",
"ParentId": "266521",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-30T09:32:48.960",
"Id": "266521",
"Score": "2",
"Tags": [
"python",
"beginner",
"random",
"natural-language-processing",
"markov-chain"
],
"Title": "Markov text generator program in Python"
}
|
266521
|
<p>It's the first thing I've created using flexbox and Javascript so I feel like my code could probably improve a lot. Any feedback would be greatly appreciated!</p>
<p><a href="https://codepen.io/dee91/pen/jOwbQmd" rel="nofollow noreferrer">https://codepen.io/dee91/pen/jOwbQmd</a></p>
<p>html:</p>
<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" />
<title>Skills section</title>
<link rel="stylesheet" href="style.css" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
</head>
<body>
<section class="skills">
<div class="skills-left">
<h2>Skills</h2>
<h3 class="skill-title">HTML & CSS</h3>
<div class="skill-bar">
<div class="html-css"><p>80/100</p></div>
</div>
<h3 class="skill-title">JAVASCRIPT</h3>
<div class="skill-bar">
<div class="javascript"><p>85/100</p></div>
</div>
<h3 class="skill-title">PHP</h3>
<div class="skill-bar">
<div class="php"><p>70/100</p></div>
</div>
<h3 class="skill-title">SEO</h3>
<div class="skill-bar">
<div class="seo"><p>95/100</p></div>
</div>
</div>
<div class="skills-right">
<h2>Summary</h2>
<div class="desc active">
<h3 >HTML & CSS</h3>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quia rem
excepturi sit dolore fuga tenetur. Lorem, ipsum dolor sit amet
consectetur adipisicing elit. Praesentium quisquam tempore, quis ex
eum maxime vitae repudiandae! Rerum consectetur provident soluta, id
iure harum voluptatum aspernatur libero illo recusandae deleniti!
</p>
<p>
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Iste, necessitatibus dolorem assumenda ipsum autem, hic, dolorum ipsa quisquam aut saepe maxime.
</p>
<ul>
<li>Lorem ipsum dolor sit amet consectetur.</li>
<li>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quia.</li>
<li>Lorem, ipsum dolor.</li>
<li>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam dolor molestias fugiat!</li>
<li>Lorem ipsum dolor sit amet consectetur.</li>
</ul>
<p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Natus doloremque provident aut fugiat rem aliquid qui laboriosam eaque. Rerum, eum!</p>
</div>
<div class="desc">
<h3 >JAVASCRIPT</h3>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quia rem
excepturi sit dolore fuga tenetur. Lorem, ipsum dolor sit amet
consectetur adipisicing elit. Praesentium quisquam tempore, quis ex
eum maxime vitae repudiandae! Rerum consectetur provident soluta, id
iure harum voluptatum aspernatur libero illo recusandae deleniti!
</p>
<img src="https://venturebeat.com/wp-content/uploads/2018/01/javascript.jpg" alt="" srcset="">
<p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Ab soluta quaerat dolorem tempore laboriosam eaque minus nobis quibusdam sunt officiis minima doloribus esse, nihil distinctio necessitatibus. Molestias enim dolorem veritatis in deserunt dolore quia earum iste magnam dolor nisi, minima, accusamus saepe ea fugiat? Possimus.</p>
</div>
<div class="desc">
<h3 >PHP</h3>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quia rem
excepturi sit dolore fuga tenetur. Lorem, ipsum dolor sit amet
consectetur adipisicing elit. Praesentium quisquam tempore, quis ex
eum maxime vitae repudiandae! Rerum consectetur provident soluta, id
iure harum voluptatum aspernatur libero illo recusandae deleniti!
</p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Velit minima nesciunt iste animi iure, minus ducimus nostrum. Vitae, blanditiis aspernatur.</p>
<p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Laborum rem, porro recusandae consectetur fugit accusantium corporis quis quam officia. Earum at aperiam quasi voluptates provident eum. Ducimus dignissimos laudantium distinctio magni fugiat id ea. Maiores dolore corrupti molestias illo officia? Asperiores rem consequuntur nam culpa!</p>
</div>
<div class="desc">
<h3 >SEO</h3>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quia rem
excepturi sit dolore fuga tenetur. Lorem, ipsum dolor sit amet
consectetur adipisicing elit. Praesentium quisquam tempore, quis ex
eum maxime vitae repudiandae! Rerum consectetur provident soluta, id
iure harum voluptatum aspernatur libero illo recusandae deleniti!
</p>
<img src="https://www.easisell.com/wp-content/uploads/2021/03/seoimage-2.jpg" alt="" srcset="">
</div>
</section>
<script src="javascript.js"></script>
</body>
</html>
</code></pre>
<p>CSS:</p>
<pre><code>body {
margin: 0;
padding: 0;
font-family: "Montserrat", sans-serif;
}
.skills {
display: flex;
flex-direction: row;
justify-content: space-around;
background: linear-gradient(to right, #c9d6ff, #e2e2e2);
height: 45rem;
padding: 4rem 0 4rem 0;
}
.skills h2 {
text-align: center;
margin-bottom: 4rem;
}
.skills-left {
width: 40%;
}
.skills-right {
width: 40%;
position: relative;
}
.skill-title {
cursor: pointer;
}
.skill-container {
display: flex;
flex-direction: column;
}
.skill-bar {
color: aliceblue;
background-color: whitesmoke;
border: black solid 1px;
display: flex;
flex-direction: row;
}
.skill-bar p {
font-size: 1.4rem;
text-align: right;
margin-right: 1.5rem;
}
.html-css {
width: 80%;
background: linear-gradient(to right, #00b4db, #0083b0);
opacity: 0.8;
}
.html-css:hover {
opacity: 1;
transition: 0.6s;
cursor: pointer;
}
.javascript {
width: 85%;
background: linear-gradient(to right, #00b4db, #0083b0);
transition: background-color 4s;
opacity: 0.8;
}
.javascript:hover {
opacity: 1;
transition: 0.6s;
cursor: pointer;
}
.php {
width: 75%;
background: linear-gradient(to right, #00b4db, #0083b0);
transition: background-color 4s;
opacity: 0.8;
}
.php:hover {
opacity: 1;
transition: 0.6s;
cursor: pointer;
}
.seo {
width: 95%;
background: linear-gradient(to right, #00b4db, #0083b0);
transition: background-color 4s;
opacity: 0.8;
}
.seo:hover {
opacity: 1;
transition: 0.6s;
cursor: pointer;
}
.desc {
opacity: 0;
position: absolute;
}
.desc img {
width: 100%;
}
.desc.active {
opacity: 1;
transition: all 800ms ease-in-out;
}
@media (max-width: 768px) {
.skills {
flex-direction: column;
justify-content: initial;
padding: 2rem 4rem;
background-color: white;
height: 100vh;
}
.skills-left {
width: 100%;
}
.skills-right {
margin-top: 20rem;
width: 100%;
}
}
</code></pre>
<p>Javascript:</p>
<pre><code>let skillBar = document.getElementsByClassName("skill-bar");
let desc = document.getElementsByClassName("desc");
let skillsRight = document.getElementsByClassName("skills-right")[0];
let skillTitle = document.getElementsByClassName("skill-title");
for (let i = 0; i < skillBar.length; i++) {
skillBar[i].addEventListener("click", function () {
skillsRight.getElementsByClassName("active")[0].classList.remove("active");
desc[i].classList.add("active");
});
skillTitle[i].addEventListener("click", function () {
skillsRight.getElementsByClassName("active")[0].classList.remove("active");
desc[i].classList.add("active");
});
}
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-30T09:51:33.327",
"Id": "266522",
"Score": "0",
"Tags": [
"javascript",
"html",
"css"
],
"Title": "Skill section with flexbox and javascript. Clicking on certain skill will change the summary"
}
|
266522
|
<p>Take the following INSERT query. Using <code>knex</code> (JS) just for abstractions</p>
<pre class="lang-js prettyprint-override"><code>function addUser() {
return knex.insert({username: 'newuser'}).into('users')
}
</code></pre>
<p>Now, by default, <code>knex</code> will internally create a connection to execute this query. But there may be situations where I want to reuse a connection (e.g: transaction) instead of using a connection pool.</p>
<p>How would you write this function in that case? One option I can think of is</p>
<pre class="lang-js prettyprint-override"><code>function addUser(connection) {
const conn = connection? connection || knex;
return conn.insert({username: 'newuser'}).into('users')
}
</code></pre>
<p>If we don't pass any connection object, it will use the connection pool by default. This works, but this feels ugly. Is there any other functional pattern that you know of that can take care of this issue?</p>
|
[] |
[
{
"body": "<h2>One function, multiple signatures</h2>\n<p>There is no other pattern, you either pass a connection or you don't.</p>\n<p>However JS is a very expressive language so there are many ways to achieve the same result.</p>\n<p>Using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript Function default parameters\">default parameters</a> and the best option.</p>\n<pre><code>function addUser(con = knex) {\n return con.insert({username: 'newuser'}).into('users');\n}\n</code></pre>\n<p>Using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. Nullish coalescing operator\">?? (Nullish coalescing operator)</a></p>\n<pre><code>function addUser(con) {\n return (con ?? knex).insert({username: 'newuser'}).into('users');\n}\n</code></pre>\n<p>Using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. Conditional operator\">? (Conditional operator)</a></p>\n<pre><code>function addUser(con) {\n return (con ? con : knex).insert({username: 'newuser'}).into('users');\n}\n</code></pre>\n<p>Or the same again as <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript Functions Arrow functions\">arrow functions</a></p>\n<pre><code>const addUser = (con = knex) => con.insert({username: 'newuser'}).into('users');\n</code></pre>\n<pre><code>const addUser = con => (con ?? knex).insert({username: 'newuser'}).into('users');\n</code></pre>\n<pre><code>const addUser = con => (con ? con : knex).insert({username: 'newuser'}).into('users');\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T22:34:08.120",
"Id": "266566",
"ParentId": "266529",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-30T15:40:10.133",
"Id": "266529",
"Score": "0",
"Tags": [
"javascript",
"design-patterns"
],
"Title": "Function pattern for running DB queries using pool or transaction"
}
|
266529
|
<p><a href="https://codereview.stackexchange.com/questions/241021">SecureADODB</a> is a very instructive VBA OOP demo. I have played with SecureADODB for a while and plan to integrate it into the prototype of my database manager application. In my previous <a href="https://codereview.stackexchange.com/questions/266178">post</a>, I showed ContactEditor's class diagram with the <em>ADOlib</em> class encapsulated into the <em>DataTableADODB</em> backend. The <em>ADOlib</em> class contains a few very basic wrappers around the ADODB library, and I created it as a stub to focus on other components of the db manager app. Now, I would like to replace <em>ADOlib</em> with SecureADODB. In preparation, I forked SecureADODB, slightly <a href="https://pchemguy.github.io/SecureADODB-Fork/" rel="nofollow noreferrer">refactored</a> the original codebase, and incorporated additional functionality from <em>ADOlib</em>. The focus of this question is on several modifications, particularly the <em>DbManager</em> class and two helper classes.</p>
<hr />
<p><strong>Class diagram of this SecureADODB fork (inteface classes not shown)</strong></p>
<p><img src="https://raw.githubusercontent.com/pchemguy/SecureADODB-Fork/8be62ed4/UML%20Class%20Diagrams/SecureADODB%20-%20ADODB%20Class%20Mapping.svg" alt="Class Diagram" /></p>
<p><strong>DbManager (renamed UnitOfWork)</strong></p>
<pre class="lang-vb prettyprint-override"><code>'@Folder "SecureADODB.DbManager"
'@ModuleDescription("An object that encapsulates a database transaction.")
'@PredeclaredId
'@Exposed
Option Explicit
Implements IDbManager
Private Type TDbManager
DbMeta As DbMetaData
DbConnStr As DbConnectionString
Connection As IDbConnection
CommandFactory As IDbCommandFactory
UseTransactions As Boolean
LogController As ILogger
End Type
Private this As TDbManager
'@Ignore ProcedureNotUsed
'@Description("Returns class reference")
Public Property Get Class() As DbManager
Set Class = DbManager
End Property
'@Description("Default factory")
Public Function Create(ByVal db As IDbConnection, _
ByVal factory As IDbCommandFactory, _
Optional ByVal UseTransactions As Boolean = True, _
Optional ByVal LogController As ILogger = Nothing) As IDbManager
Dim Instance As DbManager
Set Instance = New DbManager
Instance.Init db, factory, UseTransactions, LogController
Set Create = Instance
End Function
'@Description("Default constructor")
Friend Sub Init(ByVal db As IDbConnection, _
ByVal factory As IDbCommandFactory, _
Optional ByVal UseTransactions As Boolean = True, _
Optional ByVal LogController As ILogger = Nothing)
Guard.NullReference factory
Guard.NullReference db
Guard.Expression db.State = adStateOpen, Source:="DbManager", Message:="Connection should be open."
Set this.LogController = LogController
Set this.Connection = db
Set this.CommandFactory = factory
this.UseTransactions = UseTransactions
End Sub
'''' Factory for file-based databases.
''''
'''' Args:
'''' DbType (string):
'''' Type of the database: "sqlite", "csv", "xls"
''''
'''' DbFileName (string, optional, ""):
'''' Database file name. If not provided, ThisWorkbook.VBProject.Name
'''' will be used. Extension is added based on the database type:
'''' "sqlite" - "db" or "sqlite"
'''' "csv" - "xsv" or "csv"
'''' "xls" - "xls
''''
'''' ConnectionOptions (variant, optional, Empty):
'''' Connection options. If Empty, default values is selected based on the
'''' database type (see DbConnectionString constructor code for details).
''''
'''' N.B.: "xls" backend support is not currently implemented
''''
'@Description "Factory for file-based databases"
Public Function CreateFileDb( _
ByVal DbType As String, _
Optional ByVal DbFileName As String = vbNullString, _
Optional ByVal ConnectionOptions As String = vbNullString, _
Optional ByVal UseTransactions As Boolean = True, _
Optional ByVal LoggerType As LoggerTypeEnum = LoggerTypeEnum.logGlobal _
) As IDbManager
Dim LogController As ILogger
Select Case LoggerType
Case LoggerTypeEnum.logDisabled
Set LogController = Nothing
Case LoggerTypeEnum.logGlobal
Set LogController = Logger
Case LoggerTypeEnum.logPrivate
Set LogController = Logger.Create
End Select
Dim provider As IParameterProvider
Set provider = AdoParameterProvider.Create(AdoTypeMappings.Default)
Dim baseCommand As IDbCommandBase
Set baseCommand = DbCommandBase.Create(provider)
Dim factory As IDbCommandFactory
Set factory = DbCommandFactory.Create(baseCommand)
Dim DbConnStr As DbConnectionString
Set DbConnStr = DbConnectionString.CreateFileDb(DbType, DbFileName, , ConnectionOptions)
Dim db As IDbConnection
Set db = DbConnection.Create(DbConnStr.ConnectionString, LogController)
Dim Instance As DbManager
Set Instance = DbManager.Create(db, factory, UseTransactions, LogController)
Set Instance.DbConnStr = DbConnStr
Set Instance.DbMeta = DbMetaData.Create(DbConnStr)
Set CreateFileDb = Instance
End Function
'@Ignore ProcedureNotUsed
Public Property Get DbConnStr() As DbConnectionString
Set DbConnStr = this.DbConnStr
End Property
Public Property Set DbConnStr(ByVal Instance As DbConnectionString)
Set this.DbConnStr = Instance
End Property
'@Ignore ProcedureNotUsed
Public Property Get DbMeta() As DbMetaData
Set DbMeta = this.DbMeta
End Property
Public Property Set DbMeta(ByVal Instance As DbMetaData)
Set this.DbMeta = Instance
End Property
'@Description("Returns class reference")
Public Property Get IDbManager_Class() As DbManager
Set IDbManager_Class = DbManager
End Property
Private Property Get IDbManager_LogController() As ILogger
Set IDbManager_LogController = this.LogController
End Property
Private Property Get IDbManager_DbConnStr() As DbConnectionString
Set IDbManager_DbConnStr = this.DbConnStr
End Property
Private Property Get IDbManager_DbMeta() As DbMetaData
Set IDbManager_DbMeta = this.DbMeta
End Property
Private Property Get IDbManager_Connection() As IDbConnection
Set IDbManager_Connection = this.Connection
End Property
Private Function IDbManager_Command() As IDbCommand
Set IDbManager_Command = this.CommandFactory.CreateInstance(this.Connection)
End Function
Private Function IDbManager_Recordset( _
Optional ByVal Scalar As Boolean = False, _
Optional ByVal Disconnected As Boolean = True, _
Optional ByVal CacheSize As Long = 10, _
Optional ByVal CursorType As ADODB.CursorTypeEnum = -1, _
Optional ByVal AsyncMode As Boolean = False, _
Optional ByVal AsyncOption As ADODB.ExecuteOptionEnum = 0) As IDbRecordset
Dim cmd As IDbCommand
Set cmd = this.CommandFactory.CreateInstance(this.Connection)
Set IDbManager_Recordset = DbRecordset.Create( _
cmd, Scalar, Disconnected, CacheSize, CursorType, AsyncMode, AsyncOption)
End Function
Private Sub IDbManager_Begin()
Guard.Expression this.UseTransactions, Source:="DbManager", Message:="Transactions are disabled by the caller."
this.Connection.BeginTransaction
End Sub
Private Sub IDbManager_Commit()
Guard.Expression this.UseTransactions, Source:="DbManager", Message:="Transactions are disabled by the caller."
this.Connection.CommitTransaction
End Sub
Private Sub IDbManager_Rollback()
Guard.Expression this.UseTransactions, Source:="DbManager", Message:="Transactions are disabled by the caller."
this.Connection.RollbackTransaction
End Sub
</code></pre>
<hr />
<p>While this <em>DbManager</em> class is functionally similar to the UnitOfWork class in RD SecureADODB, I added two helper classes to simplify specific tasks.</p>
<p><strong>DbConnectionString</strong></p>
<p>During the prototyping stage, I do not want to worry about config files and connection string issues. So using this class for file-based databases (currently SQLite and CSV backends are supported), I can simply indicate the type of the database and get a connection string with sane defaults.</p>
<pre class="lang-vb prettyprint-override"><code>'@Folder "SecureADODB.DbManager.DbConnectionString"
'@ModuleDescription "Helper routines for building connection strings"
'@PredeclaredId
'@Exposed
''''
'''' The module incorporates routines, which facilitate construction of
'''' connection strings for the ADODB library. Presently, a distinction is made
'''' between file-based databases, such as sqlite, csv, xls, etc., and network
'''' based databases. A file-based database is accessed based on its type and
'''' file pathname.
'''' CreateFileDB/InitFileDB pair is used for file based databases.
''''
Option Explicit
Option Compare Text
Private Type TDbConnectionString
DbType As String
DbPath As String
Options As String
Driver As String
ConnectionString As String
End Type
Private this As TDbConnectionString
'''' Factory for file-based databases.
''''
'''' Args:
'''' FileType (string, optional, "sqlite"):
'''' Type of the database: "sqlite", "csv", "xls"
''''
'''' FileName (string, optional, ""):
'''' Database file name. If not provided, ThisWorkbook.VBProject.Name
'''' will be used. Extension is added based on the database type:
'''' "sqlite" - "db" or "sqlite"
'''' "csv" - "xsv" or "csv"
'''' "xls" - "xls
''''
'''' Driver (variant, optional, Empty):
'''' Database driver. If Empty, default values is selected based on
'''' the database type (see constructor code for details).
''''
'''' ConnectionOptions (variant, optional, Empty):
'''' Connection options. See above for details.
''''
'''' N.B.: "xls" backend support is not currently implemented
''''
'''' Examples:
'''' >>> ?DbConnectionString.CreateFileDB("sqlite").ConnectionString
'''' "Driver=SQLite3 ODBC Driver;Database=<Thisworkbook.Path>\SecureADODB.db;SyncPragma=NORMAL;FKSupport=True;"
''''
'''' >>> ?DbConnectionString.CreateFileDB("sqlite").QTConnectionString
'''' "OLEDB;Driver=SQLite3 ODBC Driver;Database=<Thisworkbook.Path>\SecureADODB.db;SyncPragma=NORMAL;FKSupport=True;"
''''
'''' >>> ?DbConnectionString.CreateFileDB("csv").ConnectionString
'''' "Driver={Microsoft Text Driver (*.txt; *.csv)};DefaultDir=<Thisworkbook.Path>;"
''''
'''' >>> ?DbConnectionString.CreateFileDB("xls").ConnectionString
'''' NotImplementedErr
''''
'@Description "Factory for file-based databases"
Public Function CreateFileDb(Optional ByVal FileType As String = "sqlite", _
Optional ByVal FileName As String = vbNullString, _
Optional ByVal Driver As Variant = Empty, _
Optional ByVal ConnectionOptions As Variant = Empty _
) As DbConnectionString
Dim Instance As DbConnectionString
Set Instance = New DbConnectionString
Instance.InitFileDB FileType, FileName, Driver, ConnectionOptions
Set CreateFileDb = Instance
End Function
'@Description "Constructor for file-based databases"
Friend Sub InitFileDB(Optional ByVal FileType As String = "sqlite", _
Optional ByVal FileName As String = vbNullString, _
Optional ByVal Driver As String = vbNullString, _
Optional ByVal ConnectionOptions As Variant = Empty)
With this
.DbType = LCase$(FileType)
.Driver = Driver
.Options = ConnectionOptions
Select Case .DbType
Case "sqlite"
If Len(Driver) = 0 Then
.Driver = "SQLite3 ODBC Driver"
End If
If IsEmpty(ConnectionOptions) Then
.Options = "SyncPragma=NORMAL;FKSupport=True;"
End If
.DbPath = VerifyOrGetDefaultPath(FileName, Array("db", "sqlite"))
.ConnectionString = "Driver=" + .Driver + ";" + _
"Database=" + .DbPath + ";" + _
.Options
Case "worksheet", "wsheet"
.DbPath = VerifyOrGetDefaultPath(FileName, Array("xls"))
.ConnectionString = .DbPath
Case "csv"
.DbPath = VerifyOrGetDefaultPath(FileName, Array("xsv", "csv"))
Dim DbFileName As String
DbFileName = Dir$(.DbPath, vbArchive + vbNormal + vbHidden + vbReadOnly + vbSystem)
.DbPath = Left$(.DbPath, Len(.DbPath) - Len(DbFileName) - 1)
#If Win64 Then
.Driver = "Microsoft Access Text Driver (*.txt, *.csv)"
#Else
.Driver = "{Microsoft Text Driver (*.txt; *.csv)}"
#End If
.ConnectionString = "Driver=" + .Driver + ";" + _
"DefaultDir=" + .DbPath + ";"
Case Else
.ConnectionString = vbNullString
End Select
End With
If this.ConnectionString = vbNullString Then
Dim errorDetails As TError
With errorDetails
.Number = ErrNo.NotImplementedErr
.Name = "NotImplementedErr"
.Source = "DbConnectionString"
.Description = "Unsupported backend: " & FileType
.Message = .Description
End With
RaiseError errorDetails
End If
End Sub
Public Property Get ConnectionString() As String
ConnectionString = this.ConnectionString
End Property
Public Property Get QTConnectionString() As String
QTConnectionString = "OLEDB;" & this.ConnectionString
End Property
</code></pre>
<p><em>DbConnectionString</em> relies on the <em>VerifyOrGetDefaultPath</em> routine, which takes a file pathname candidate (possibly blank) and an array of default extensions. Then it attempts to locate the file, checking default directories and file naming conventions.</p>
<pre class="lang-vb prettyprint-override"><code>'''' Resolves file pathname
''''
'''' This helper routines attempts to interpret provided pathname as
'''' a reference to an existing file:
'''' 1) check if provided reference is a valid absolute file pathname, if not,
'''' 2) construct an array of possible file locations:
'''' - ThisWorkbook.Path & Application.PathSeparator
'''' - Environ("APPDATA") & Application.PathSeparator &
'''' & ThisWorkbook.VBProject.Name & Application.PathSeparator
'''' construct an array of possible file names:
'''' - FilePathName
'''' - ThisWorkbook.VBProject.Name & Ext (Ext comes from the second argument
'''' 3) loop through all possible path/filename combinations until a valid
'''' pathname is found or all options are exhausted
''''
'''' Args:
'''' FilePathName (string):
'''' File pathname
''''
'''' DefaultExts (string or string/array):
'''' 1D array of default extensions or a single default extension
''''
'''' Returns:
'''' String:
'''' Resolved valid absolute pathname pointing to an existing file.
''''
'''' Throws:
'''' Err.FileNotFoundErr:
'''' If provided pathname cannot be resolved to a valid file pathname.
''''
'''' Examples:
'''' >>> ?VerifyOrGetDefaultPath(Environ$("ComSpec"), "")
'''' "C:\Windows\system32\cmd.exe"
''''
'@Description "Resolves file pathname"
Public Function VerifyOrGetDefaultPath(ByVal FilePathName As String, ByVal DefaultExts As Variant) As String
Dim PATHuSEP As String: PATHuSEP = Application.PathSeparator
Dim PROJuNAME As String: PROJuNAME = ThisWorkbook.VBProject.Name
Dim FileExist As Variant
Dim PathNameCandidate As String
'''' === (1) === Check if FilePathName is a valid path to an existing file.
If Len(FilePathName) > 0 Then
'''' If matched, Dir returns Len(String) > 0;
'''' otherwise, returns vbNullString or raises an error
PathNameCandidate = FilePathName
On Error Resume Next
FileExist = FileLen(PathNameCandidate)
On Error GoTo 0
If FileExist > 0 Then
VerifyOrGetDefaultPath = PathNameCandidate
Exit Function
End If
End If
'''' === (2a) === Array of prefixes
Dim Prefixes As Variant
Prefixes = Array( _
ThisWorkbook.Path & PATHuSEP, _
Environ$("APPDATA") & PATHuSEP & PROJuNAME & PATHuSEP _
)
'''' === (2b) === Array of filenames
Dim NameCount As Long
NameCount = 0
If Len(FilePathName) > 1 And InStr(FilePathName, PATHuSEP) = 0 Then
NameCount = NameCount + 1
End If
If VarType(DefaultExts) = vbString Then
If Len(DefaultExts) > 0 Then NameCount = NameCount + 1
ElseIf VarType(DefaultExts) >= vbArray Then
NameCount = NameCount + UBound(DefaultExts, 1) - LBound(DefaultExts, 1) + 1
Debug.Assert VarType(DefaultExts(0)) = vbString
End If
If NameCount = 0 Then
VBA.Err.Raise _
Number:=ErrNo.FileNotFoundErr, _
Source:="CommonRoutines", _
Description:="File <" & FilePathName & "> not found!"
End If
Dim FileNames() As String
ReDim FileNames(0 To NameCount - 1)
Dim ExtIndex As Long
Dim FileNameIndex As Long
FileNameIndex = 0
If Len(FilePathName) > 1 And InStr(FilePathName, PATHuSEP) = 0 Then
FileNames(FileNameIndex) = FilePathName
FileNameIndex = FileNameIndex + 1
End If
If VarType(DefaultExts) = vbString Then
If Len(DefaultExts) > 0 Then
FileNames(FileNameIndex) = PROJuNAME & "." & DefaultExts
End If
ElseIf VarType(DefaultExts) >= vbArray Then
For ExtIndex = LBound(DefaultExts, 1) To UBound(DefaultExts, 1)
FileNames(FileNameIndex) = PROJuNAME & "." & DefaultExts(ExtIndex)
FileNameIndex = FileNameIndex + 1
Next ExtIndex
End If
'''' === (3) === Loop through pathnames
Dim PrefixIndex As Long
On Error Resume Next
For PrefixIndex = 0 To UBound(Prefixes)
For FileNameIndex = 0 To UBound(FileNames)
PathNameCandidate = Prefixes(PrefixIndex) & FileNames(FileNameIndex)
FileExist = FileLen(PathNameCandidate)
Err.Clear
If FileExist > 0 Then
VerifyOrGetDefaultPath = Replace$(PathNameCandidate, _
PATHuSEP & PATHuSEP, PATHuSEP)
Exit Function
End If
Next FileNameIndex
Next PrefixIndex
On Error GoTo 0
VBA.Err.Raise _
Number:=ErrNo.FileNotFoundErr, _
Source:="CommonRoutines", _
Description:="File <" & FilePathName & "> not found!"
End Function
</code></pre>
<hr />
<p><strong>DbMetaData</strong></p>
<p><em>DbMetaData</em> currently provides a routine, which takes a table name and returns field names, types, and a mapping from field name to its position.</p>
<pre class="lang-vb prettyprint-override"><code>'@Folder "SecureADODB.DbManager.DbMetaData"
'@ModuleDescription "Database introspection functionality"
'@PredeclaredId
'@Exposed
Option Explicit
Private Type TDbMeta
DbConnStr As DbConnectionString
End Type
'@Ignore MoveFieldCloserToUsage: Follow the standard pattern
Private this As TDbMeta
'@Description "Default factory"
Public Function Create(ByVal DbConnStr As DbConnectionString) As DbMetaData
Dim Instance As DbMetaData
Set Instance = New DbMetaData
Instance.Init DbConnStr
Set Create = Instance
End Function
'@Description "Default constructor"
Friend Sub Init(ByVal DbConnStr As DbConnectionString)
Guard.NullReference DbConnStr
Set this.DbConnStr = DbConnStr
End Sub
'@Ignore ParameterCanBeByVal: False positive
'@Description "Query table field metadata via the ADOX library"
Public Sub QueryTableADOXMeta(ByVal TableName As String, _
ByRef FieldNames As Variant, _
ByRef FieldTypes As Variant, _
ByVal FieldMap As Scripting.Dictionary)
Dim Catalog As ADOX.Catalog
Set Catalog = New ADOX.Catalog
Catalog.ActiveConnection = this.DbConnStr.ConnectionString
Dim Table As ADOX.Table
'@Ignore IndexedDefaultMemberAccess
Set Table = Catalog.Tables(TableName)
Dim FieldCount As Long
FieldCount = Table.Columns.Count
ReDim FieldNames(1 To FieldCount)
ReDim FieldTypes(1 To FieldCount)
Dim Column As ADOX.Column
Dim FieldIndex As Long
For FieldIndex = 1 To FieldCount
'@Ignore IndexedDefaultMemberAccess
Set Column = Table.Columns(FieldIndex - 1)
FieldNames(FieldIndex) = Column.Name
FieldTypes(FieldIndex) = Column.Type
'@Ignore IndexedDefaultMemberAccess
FieldMap(Column.Name) = FieldIndex
Next FieldIndex
End Sub
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-30T16:35:58.340",
"Id": "266530",
"Score": "2",
"Tags": [
"object-oriented",
"vba",
"database",
"adodb"
],
"Title": "Extending the SecureADODB library"
}
|
266530
|
<p>I would like some feedback on trying to implement SOLID principles to my Katamari Damacy-style game, I have provided below the 'original' script which accomplished a variety of tasks, and then the 'new' scripts that accomplish the same things while trying to be more SOLID friendly. In no way do I consider these scripts finished or perfect, I am looking for tips to improve SOLID conformity.</p>
<p>Original scripts:</p>
<pre><code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cinemachine;
public class BallController : MonoBehaviour
{
[SerializeField] private BoostBar boostBar;
[SerializeField] private Transform cameraTransform;
[SerializeField] private float rollSpeed;
private float originalRollSpeed;
[SerializeField] private Rigidbody rb;
[SerializeField] private bool isGrounded;
[Header("Size stats:")]
[SerializeField] private float size = 0;
[SerializeField] private float sizeNeeded = 0;
[SerializeField] private CinemachineFreeLook cineMachine;
[SerializeField] private SphereCollider physicalSphere;
[SerializeField] private SphereCollider triggerSphere;
private bool boostJump;
private float originalOrbit;
private float desiredOrbit;
void Start()
{
originalRollSpeed = rollSpeed;
originalOrbit = cineMachine.m_Orbits[0].m_Radius;
desiredOrbit = originalOrbit + 0.2f;
Cursor.lockState = CursorLockMode.Locked;
size = gameObject.GetComponent<MeshRenderer>().bounds.size.x +
gameObject.GetComponent<MeshRenderer>().bounds.size.y +
gameObject.GetComponent<MeshRenderer>().bounds.size.z;
sizeNeeded = size / 2;
}
void Update()
{
InputReciever();
}
void FixedUpdate()
{
MovePlayer();
TryBoost();
TryGround();
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Prop") && collision.gameObject.GetComponent<MeshRenderer>().bounds.size.x +
collision.gameObject.GetComponent<MeshRenderer>().bounds.size.y +
collision.gameObject.GetComponent<MeshRenderer>().bounds.size.z <= size - sizeNeeded && collision.gameObject.GetComponent<PropScript>().canPickUp == true)
{
//The larger the sizeNeeded amount, the smaller the object must be
Destroy(collision.gameObject.GetComponent<Rigidbody>());
if (collision.gameObject.GetComponent<SphereCollider>())
{
collision.gameObject.GetComponent<SphereCollider>().enabled = false;
//collision.gameObject.GetComponent<SphereCollider>().enabled = true;
}
if (collision.gameObject.GetComponent<CapsuleCollider>())
{
//collision.gameObject.GetComponent<CapsuleCollider>().enabled = true;
collision.gameObject.GetComponent<CapsuleCollider>().enabled = false;
}
if (collision.gameObject.GetComponent<BoxCollider>())
{
collision.gameObject.GetComponent<BoxCollider>().enabled = false;
//collision.gameObject.GetComponent<BoxCollider>().enabled = false;
}
collision.gameObject.transform.SetParent(this.gameObject.transform);
size += (collision.gameObject.GetComponent<MeshRenderer>().bounds.size.x +
collision.gameObject.GetComponent<MeshRenderer>().bounds.size.y +
collision.gameObject.GetComponent<MeshRenderer>().bounds.size.z) / 8;
triggerSphere.radius += size / 72;
physicalSphere.radius += size / 120;
sizeNeeded = size / 2;
collision.gameObject.GetComponent<PropScript>().canPickUp = false;
StartCoroutine(LerpCameraOrbit());
}
}
private void OnCollisionStay(Collision collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
Invoke("GroundedTrue", 0.5f);
}
}
private void GroundedTrue()
{
isGrounded = true;
}
void OnCollisionExit(Collision collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
isGrounded = false;
}
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Prop"))
{
other.gameObject.GetComponent<PropScript>().canPickUp = true;
}
}
private void OnTriggerStay(Collider other)
{
if (other.gameObject.CompareTag("Prop"))
{
other.gameObject.GetComponent<PropScript>().canPickUp = true;
}
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject.CompareTag("Prop"))
{
other.gameObject.GetComponent<PropScript>().canPickUp = false;
}
}
IEnumerator LerpCameraOrbit()
{
float timeElapsed = 0f;
float lerpDuration = 3f;
float lerpStartValue = originalOrbit;
float lerpEndValue = desiredOrbit;
//EVENTUALLY MAKE THIS NICELY IN PROPORTION TO SIZE OF OBJECT COLLECTED
originalOrbit += 0.2f;
desiredOrbit += 0.2f;
//----------------------------------------------------------------------
while (timeElapsed < lerpDuration)
{
cineMachine.m_Orbits[0].m_Radius = Mathf.Lerp(lerpStartValue, lerpEndValue, timeElapsed / lerpDuration);
cineMachine.m_Orbits[1].m_Radius = Mathf.Lerp(lerpStartValue, lerpEndValue, timeElapsed / lerpDuration);
cineMachine.m_Orbits[2].m_Radius = Mathf.Lerp(lerpStartValue, lerpEndValue, timeElapsed / lerpDuration);
timeElapsed += Time.deltaTime;
yield return null;
}
cineMachine.m_Orbits[0].m_Radius = lerpEndValue;
cineMachine.m_Orbits[1].m_Radius = lerpEndValue;
cineMachine.m_Orbits[2].m_Radius = lerpEndValue;
}
void InputReciever()
{
if (Input.GetButtonDown("Boost"))
{
//will attempt to use boost
boostBar.useBoost = true;
boostBar.currentBoost -= (boostBar.boostChangeAmount);
boostJump = true;
rollSpeed = rollSpeed * 1.3f;
}
if (Input.GetButtonUp("Boost"))
{
boostBar.useBoost = false;
rollSpeed = originalRollSpeed;
}
}
void MovePlayer()
{
Vector3 playerInput = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
Vector3 playerMovement = (playerInput.z * cameraTransform.forward) + (playerInput.x * cameraTransform.right);
rb.AddForce(playerMovement * rollSpeed * Time.fixedDeltaTime * (size / 2));
}
void TryBoost()
{
if (boostJump == true)
{
Vector3 boostJumpVector = new Vector3(0f, 1f, 0f);
rb.AddForce(boostJumpVector, ForceMode.Impulse);
boostJump = false;
}
}
void TryGround()
{
if (!isGrounded)
{
rb.AddForce(Vector3.down * 5);
}
}
}
</code></pre>
<pre><code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class BatteryBar : MonoBehaviour
{
[SerializeField] private Slider batteryBarSlider;
[SerializeField] private Image fillImage;
[SerializeField] private byte[] fullColor;
[SerializeField] private byte[] lowColor;
[SerializeField] private byte[] boostColor;
[SerializeField] private float maxBattery;
public float batteryChangeAmount;
public float currentBattery;
private bool isBoosting;
void Start()
{
currentBattery = maxBattery;
batteryBarSlider.maxValue = maxBattery;
batteryBarSlider.value = maxBattery;
}
public void Update()
{
if (!isBoosting)
{
currentBattery -= Time.deltaTime * batteryChangeAmount;
batteryBarSlider.value = currentBattery;
if (batteryBarSlider.value <= maxBattery / 4)
{
fillImage.color = new Color32(lowColor[0], lowColor[1], lowColor[2], lowColor[3]);
}
else
{
fillImage.color = new Color32(fullColor[0], fullColor[1], fullColor[2], fullColor[3]);
}
} else
{
currentBattery -= Time.deltaTime * (batteryChangeAmount + (batteryChangeAmount/2));
batteryBarSlider.value = currentBattery;
fillImage.color = new Color32(boostColor[0], boostColor[1], boostColor[2], boostColor[3]);
}
//later on functionality will be added to gain back charge from picking up certain items
//
//
//
}
public void BoostDrain(bool boosting)
{
if (boosting)
{
isBoosting = true;
} else
{
isBoosting = false;
}
}
}
</code></pre>
<pre><code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class BoostBar : MonoBehaviour
{
[SerializeField] private Slider boostBarSlider;
[SerializeField] private Image fillImage;
[SerializeField] private byte[] fillColor;
[SerializeField] private byte[] emptyFillColor;
[SerializeField] private BatteryBar batteryBar;
public float boostChangeAmount;
private float maxBoost = 100f;
public float currentBoost;
public bool useBoost;
public float maxCooldownTime;
public float cooldownTime;
[SerializeField] private bool isCool = true;
void Start()
{
cooldownTime = maxCooldownTime;
currentBoost = maxBoost;
boostBarSlider.maxValue = maxBoost;
boostBarSlider.value = maxBoost;
}
public void Update()
{
if(useBoost == false)
{
batteryBar.BoostDrain(false);
}
if (useBoost && isCool)
{
if (currentBoost - boostChangeAmount >= 0)
{
fillImage.color = new Color32(fillColor[0], fillColor[1], fillColor[2], fillColor[3]);
currentBoost -= Time.deltaTime * boostChangeAmount;
//Debug.Log(boostChangeAmount);
boostBarSlider.value = currentBoost;
batteryBar.BoostDrain(true);
}
else
{
fillImage.color = new Color32(emptyFillColor[0], emptyFillColor[1], emptyFillColor[2], emptyFillColor[3]);
isCool = false;
cooldownTime = 0;
}
}
if (cooldownTime < maxCooldownTime && !isCool)
{
batteryBar.BoostDrain(false);
fillImage.color = new Color32(emptyFillColor[0], emptyFillColor[1], emptyFillColor[2], emptyFillColor[3]);
currentBoost += Time.deltaTime * boostChangeAmount;
boostBarSlider.value = currentBoost;
cooldownTime += Time.deltaTime * boostChangeAmount;
} else
{
isCool = true;
}
if (!useBoost && isCool && currentBoost < maxBoost)
{
fillImage.color = new Color32(fillColor[0], fillColor[1], fillColor[2], fillColor[3]);
currentBoost += Time.deltaTime * boostChangeAmount;
boostBarSlider.value = currentBoost;
}
}
public void UseBoost()
{
useBoost = true;
}
}
</code></pre>
<p>New scripts:</p>
<pre><code>using UnityEngine;
public class PlayerInput : MonoBehaviour
{
private BallBoost ballBoost;
private void Start()
{
ballBoost = GetComponent<BallBoost>();
}
void Update()
{
InputReciever();
}
public void InputReciever()
{
if (Input.GetButtonDown("Boost"))
{
ballBoost.StartBoost();
}
if (Input.GetButtonUp("Boost"))
{
ballBoost.StopBoost();
}
}
}
</code></pre>
<pre><code>using UnityEngine;
public class BallBoost : MonoBehaviour
{
public float boostChangeAmount;
public float maxBoost = 100f;
public float currentBoost;
private bool boostJump;
private BoostBarUI boostBarUI;
private BallPhysics ballPhysics;
private void Start()
{
currentBoost = maxBoost;
boostBarUI = GetComponent<BoostBarUI>();
ballPhysics = GetComponent<BallPhysics>();
boostBarUI.boostBarSlider.maxValue = maxBoost;
boostBarUI.boostBarSlider.value = maxBoost;
}
private void FixedUpdate()
{
TryBoostJump();
}
public void TryBoostJump()
{
if (boostJump == true && ballPhysics.isGrounded)
{
Vector3 boostJumpVector = new Vector3(0f, 1f, 0f);
ballPhysics.rb.AddForce(boostJumpVector, ForceMode.Impulse);
boostJump = false;
}
}
public void StopBoost()
{
boostBarUI.StopBoost();
ballPhysics.rollSpeed = ballPhysics.originalRollSpeed;
}
public void StartBoost()
{
if (currentBoost - boostChangeAmount >= 0 && boostBarUI.isCool)
{
boostBarUI.UseBoost();
currentBoost -= (boostChangeAmount);
boostJump = true;
ballPhysics.rollSpeed = ballPhysics.rollSpeed * 1.3f;
boostBarUI.BoostingUI();
}
else
{
boostBarUI.EmptyBoostUI();
ballPhysics.rollSpeed = ballPhysics.originalRollSpeed;
}
}
public void AddBoost()
{
currentBoost += Time.deltaTime * boostChangeAmount;
}
}
</code></pre>
<pre><code>using UnityEngine;
using UnityEngine.UI;
public class BoostBarUI : MonoBehaviour
{
public bool useBoost;
public bool isCool = true;
public float maxCooldownTime;
public float cooldownTime;
public Slider boostBarSlider;
public Image fillImage;
[SerializeField] private byte[] fillColor;
[SerializeField] private byte[] emptyFillColor;
[SerializeField] private BatteryBar batteryBar;
private BallBoost ballBoost;
void Start()
{
ballBoost = GetComponent<BallBoost>();
Cursor.lockState = CursorLockMode.Locked;
cooldownTime = maxCooldownTime;
}
public void Update()
{
if(useBoost == false)
{
batteryBar.BoostDrain(false);
} else
{
if (ballBoost.currentBoost >= 0)
{
NegateBoostUI();
} else
{
EmptyBoostUI();
}
}
if (cooldownTime < maxCooldownTime && !isCool)
{
CoolDownTime();
ballBoost.AddBoost();
} else
{
isCool = true;
}
if (!useBoost && isCool && ballBoost.currentBoost < ballBoost.maxBoost)
{
AddBoostUI();
}
}
public void UseBoost()
{
useBoost = true;
}
public void StopBoost()
{
useBoost = false;
}
public void AddBoostUI()
{
fillImage.color = new Color32(fillColor[0], fillColor[1], fillColor[2], fillColor[3]);
ballBoost.AddBoost();
boostBarSlider.value = ballBoost.currentBoost;
}
public void NegateBoostUI()
{
ballBoost.currentBoost -= Time.deltaTime * ballBoost.boostChangeAmount;
boostBarSlider.value = ballBoost.currentBoost;
}
public void BoostingUI()
{
fillImage.color = new Color32(fillColor[0], fillColor[1], fillColor[2], fillColor[3]);
boostBarSlider.value = ballBoost.currentBoost;
batteryBar.BoostDrain(true);
}
public void EmptyBoostUI()
{
useBoost = false;
ballBoost.StopBoost();
fillImage.color = new Color32(emptyFillColor[0], emptyFillColor[1], emptyFillColor[2], emptyFillColor[3]);
useBoost = false;
isCool = false;
cooldownTime = 0;
}
public void CoolDownTime()
{
batteryBar.BoostDrain(false);
fillImage.color = new Color32(emptyFillColor[0], emptyFillColor[1], emptyFillColor[2], emptyFillColor[3]);
boostBarSlider.value = ballBoost.currentBoost;
cooldownTime += Time.deltaTime * ballBoost.boostChangeAmount;
}
}
</code></pre>
<pre><code>using UnityEngine;
using UnityEngine.UI;
public class BatteryBar : MonoBehaviour
{
public float batteryChangeAmount;
public float currentBattery;
[SerializeField] private Slider batteryBarSlider;
[SerializeField] private Image fillImage;
[SerializeField] private byte[] fullColor;
[SerializeField] private byte[] lowColor;
[SerializeField] private byte[] boostColor;
[SerializeField] private float maxBattery;
private bool isBoosting;
void Start()
{
currentBattery = maxBattery;
batteryBarSlider.maxValue = maxBattery;
batteryBarSlider.value = maxBattery;
}
public void Update()
{
if (!isBoosting)
{
BatteryDrain();
} else
{
BoostBatteryDrain();
}
//later on functionality will be added to gain back charge from picking up certain items
//
//
//
}
public void BoostDrain(bool boosting)
{
if (boosting)
{
isBoosting = true;
}
else
{
isBoosting = false;
}
}
private void BatteryDrain()
{
currentBattery -= Time.deltaTime * batteryChangeAmount;
batteryBarSlider.value = currentBattery;
if (batteryBarSlider.value <= maxBattery / 4)
{
fillImage.color = new Color32(lowColor[0], lowColor[1], lowColor[2], lowColor[3]);
}
else
{
fillImage.color = new Color32(fullColor[0], fullColor[1], fullColor[2], fullColor[3]);
}
}
private void BoostBatteryDrain()
{
currentBattery -= Time.deltaTime * (batteryChangeAmount * 2 /*+ (batteryChangeAmount/2)*/);
batteryBarSlider.value = currentBattery;
fillImage.color = new Color32(boostColor[0], boostColor[1], boostColor[2], boostColor[3]);
}
}
</code></pre>
<pre><code>using UnityEngine;
public class BallPhysics : MonoBehaviour
{
public Rigidbody rb;
public float rollSpeed;
public float originalRollSpeed;
public bool isGrounded;
public bool isGroundedTimer;
private BallController ballController;
private CameraController cameraController;
void Start()
{
ballController = GetComponent<BallController>();
cameraController = GetComponent<CameraController>();
originalRollSpeed = rollSpeed;
rb = GetComponent<Rigidbody>();
}
private void FixedUpdate()
{
MovePlayer();
TryGround();
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Trash") && collision.gameObject.GetComponent<MeshRenderer>().bounds.size.x +
collision.gameObject.GetComponent<MeshRenderer>().bounds.size.y +
collision.gameObject.GetComponent<MeshRenderer>().bounds.size.z <= ballController.size - ballController.sizeNeeded
&& collision.gameObject.GetComponent<PropScript>().canPickUp == true)
{
ProcessTrash(collision);
}
}
private void OnCollisionStay(Collision collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
GroundedTrue();
Invoke("GroundedTimerTrue", 0.5f);
}
}
private void GroundedTrue()
{
isGrounded = true;
}
private void GroundedTimerTrue()
{
isGroundedTimer = true;
}
void OnCollisionExit(Collision collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
isGrounded = false;
isGroundedTimer = false;
}
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Trash"))
{
other.gameObject.GetComponent<PropScript>().canPickUp = true;
}
}
private void OnTriggerStay(Collider other)
{
if (other.gameObject.CompareTag("Trash"))
{
other.gameObject.GetComponent<PropScript>().canPickUp = true;
}
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject.CompareTag("Trash"))
{
other.gameObject.GetComponent<PropScript>().canPickUp = false;
}
}
void MovePlayer()
{
Vector3 playerInput = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
Vector3 playerMovement = (playerInput.z * cameraController.cameraTransform.forward) + (playerInput.x * cameraController.cameraTransform.right);
rb.AddForce(playerMovement * rollSpeed * Time.fixedDeltaTime * (ballController.size / 2));
}
void TryGround()
{
if (!isGroundedTimer)
{
rb.AddForce(Vector3.down * 5);
}
}
void ProcessTrash(Collision collision)
{
//The larger the sizeNeeded amount, the smaller the object must be
Destroy(collision.gameObject.GetComponent<Rigidbody>());
if (collision.gameObject.GetComponent<MeshCollider>())
{
collision.gameObject.GetComponent<MeshCollider>().enabled = false;
}
if (collision.gameObject.GetComponent<SphereCollider>())
{
collision.gameObject.GetComponent<SphereCollider>().enabled = false;
}
if (collision.gameObject.GetComponent<CapsuleCollider>())
{
collision.gameObject.GetComponent<CapsuleCollider>().enabled = false;
}
if (collision.gameObject.GetComponent<BoxCollider>())
{
collision.gameObject.GetComponent<BoxCollider>().enabled = false;
}
collision.gameObject.transform.SetParent(this.gameObject.transform);
ballController.size += (collision.gameObject.GetComponent<MeshRenderer>().bounds.size.x +
collision.gameObject.GetComponent<MeshRenderer>().bounds.size.y +
collision.gameObject.GetComponent<MeshRenderer>().bounds.size.z) / 8;
ballController.IncreaseSize(collision.gameObject);
}
}
</code></pre>
<pre><code>using UnityEngine;
public class BallController : MonoBehaviour
{
public float size = 0;
public float sizeNeeded = 0;
public SphereCollider physicalSphere;
public SphereCollider triggerSphere;
//The higher this value is, the smaller the ball will grow each time
private float growthSizeFraction = 400;
private CameraController cameraController;
void Start()
{
cameraController = GetComponent<CameraController>();
size = gameObject.GetComponent<MeshRenderer>().bounds.size.x +
gameObject.GetComponent<MeshRenderer>().bounds.size.y +
gameObject.GetComponent<MeshRenderer>().bounds.size.z;
sizeNeeded = size / 2;
}
public void IncreaseSize(GameObject collidedObject)
{
triggerSphere.radius += size / (growthSizeFraction / 2);
physicalSphere.radius += size / growthSizeFraction;
sizeNeeded = size / 2;
collidedObject.GetComponent<PropScript>().canPickUp = false;
StartCoroutine(cameraController.LerpCameraOrbit());
}
}
</code></pre>
<pre><code>using System.Collections;
using UnityEngine;
using Cinemachine;
public class CameraController : MonoBehaviour
{
public Transform cameraTransform;
[SerializeField] private CinemachineFreeLook cineMachine;
private float originalOrbit;
private float desiredOrbit;
private void Start()
{
originalOrbit = cineMachine.m_Orbits[0].m_Radius;
desiredOrbit = originalOrbit + 0.2f;
}
public IEnumerator LerpCameraOrbit()
{
float timeElapsed = 0f;
float lerpDuration = 3f;
float lerpStartValue = originalOrbit;
float lerpEndValue = desiredOrbit;
//EVENTUALLY MAKE THIS NICELY IN PROPORTION TO SIZE OF OBJECT COLLECTED
originalOrbit += 0.2f;
desiredOrbit += 0.2f;
//----------------------------------------------------------------------
while (timeElapsed < lerpDuration)
{
cineMachine.m_Orbits[0].m_Radius = Mathf.Lerp(lerpStartValue, lerpEndValue, timeElapsed / lerpDuration);
cineMachine.m_Orbits[1].m_Radius = Mathf.Lerp(lerpStartValue, lerpEndValue, timeElapsed / lerpDuration);
cineMachine.m_Orbits[2].m_Radius = Mathf.Lerp(lerpStartValue, lerpEndValue, timeElapsed / lerpDuration);
timeElapsed += Time.deltaTime;
yield return null;
}
cineMachine.m_Orbits[0].m_Radius = lerpEndValue;
cineMachine.m_Orbits[1].m_Radius = lerpEndValue;
cineMachine.m_Orbits[2].m_Radius = lerpEndValue;
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-30T17:50:31.077",
"Id": "266532",
"Score": "0",
"Tags": [
"c#",
"object-oriented",
"design-patterns",
"unity3d"
],
"Title": "Two sets of scripts for a Katamari Damacy-style game"
}
|
266532
|
<p>A DNI (Spain's National Identification Document) is formed by 8 digits and a letter, and they are related to one another as follows:</p>
<pre class="lang-py prettyprint-override"><code>number % 23 -> letter_index
</code></pre>
<p>Where the sequence of letters to be indexed is <code>TRWAGMYFPDXBNJZSQVHLCKET</code></p>
<p>The following program allows calculating the letter given the number, finding some missing numbers, and finding all possible DNIs given some of the numbers and the letter:</p>
<pre class="lang-py prettyprint-override"><code>from dataclasses import dataclass, field
from typing import Optional, List
@dataclass
class Dni:
LENGTH_NUMS_ONLY = 8
LENGTH = LENGTH_NUMS_ONLY + 1
number: Optional[int] = None
letter: Optional[str] = None
missing_digits: List[int] = field(default_factory=lambda: [])
def get_number_as_str(self) -> str:
'''Return the number representing unknown digits as "?"
For example, if number=11_011_111 and missing_digits=[2],
returned value is "11?11111"
'''
number = self.number if self.number is not None else 0
number_as_str = str(number).zfill(Dni.LENGTH_NUMS_ONLY)
# number is converted to list so that missing digits can be replaced
number_as_list = list(number_as_str)
if self.missing_digits:
for missing_digit in self.missing_digits:
number_as_list[missing_digit] = '?'
return ''.join(number_as_list)
def get_letter_as_str(self) -> str:
'''Return the letter or "?" if lettter is not known'''
return self.letter.upper() if self.letter else '?'
def __str__(self):
return self.get_number_as_str() + self.get_letter_as_str()
@classmethod
def from_dni(clss, dni):
return Dni(dni.number, dni.letter, [i for i in dni.missing_digits])
</code></pre>
<pre class="lang-py prettyprint-override"><code>from typing import Iterable, Generator, Optional
import itertools
from dni_calculator import Dni
class DniCalculator:
_LETTERS = 'TRWAGMYFPDXBNJZSQVHLCKET'
def find_letter(self, dni: Dni) -> Optional[Dni]:
'''Find the letter corresponding to the given dni
Example:
find_letter(Dni(11111111)) -> 11111111H
Args:
dni: The dni whose letter is to be found.
All of its digits have to be present
'''
if dni.missing_digits and len(dni.missing_digits) != 0:
print(f'Invalid dni given: "{dni}". '
+ 'There cannot be missing numbers when finding a letter')
return None
if dni.letter is not None:
if self._check_valid(dni):
print(f'The given dni is already complete and valid: "{dni}"')
return Dni.from_dni(dni)
else:
print(f'Letter provided. Wont look for it "{dni}"')
return None
res_dni = Dni.from_dni(dni)
res_dni.letter = self._get_letter(dni.number)
return res_dni
def _get_letter(self, dni_number: int) -> str:
'''Return the letter corresponding to the given dni_number'''
return self._LETTERS[dni_number % 23]
def _check_valid(self, dni: Dni) -> bool:
'''Check whether the given dni is valid
Args:
dni: A Dni with all digits and letter present
Example: Dni(11_111_111, 'H')
'''
return self._get_letter(dni.number) == dni.letter
def find_missing_num(self, dni: Dni) -> Optional[Dni]:
'''Find the first complete dni valid for the given dni
Args:
dni: The dni for which to find the missing numbers
It should have at least one missing digit.
It also has to contain the letter.
Examples:
Dni(11_111_011, 'H', [5])
Dni(11_100_111, 'H', [3, 4])
'''
return next(self.find_all_possible_dnis(dni), None)
def find_all_possible_dnis(self, dni: Dni) -> Generator[Dni, None, None]:
'''Find the all of the valid dnis for the given dni
Args:
dni: The dni for which to find the missing numbers
It should have at least one missing digit.
It also has to contain the letter.
Examples:
Dni(11_111_011, 'H', [5])
Dni(11_100_111, 'H', [3, 4])
'''
if dni.letter is None:
print(f'Cannot fing missing numbers if no letter is given: "{dni}"')
return None
num_missing_digits = len(dni.missing_digits)
if num_missing_digits == 0:
if self._check_valid(dni):
print(f'The given dni is already complete and valid: "{dni}"')
yield Dni.from_dni(dni)
return None
else:
print(f'All digits provided. Unable to find missing ones "{dni}"')
return None
res_dni = Dni.from_dni(dni)
missing_digits = res_dni.missing_digits
res_dni.missing_digits = []
prev_digits_to_check = 0
for digits_to_check in self._get_generator_for_digits(missing_digits):
res_dni.number -= prev_digits_to_check
res_dni.number += digits_to_check
prev_digits_to_check = digits_to_check
if self._check_valid(res_dni):
yield Dni.from_dni(res_dni)
def _get_generator_for_digit(self, digit_pos: int) -> Generator[int, None, None]:
'''Return the different value the digit at position digit_pos can have
Examples:
digit_pos=7 -> 0, 1, 2, ..., 8, 9
digit_pos=6 -> 0, 10, 20, ..., 80, 90
digit_pos=0 -> 0, 10_000_000, ..., 90_000_000
Args:
digit_pos: A number from 0 to 9
'''
power = Dni.LENGTH_NUMS_ONLY - digit_pos
for number in range(0, 10 ** power, 10 ** (power-1)):
yield number
def _get_generator_for_digits(self, digits_pos: Iterable[int]) -> Generator[int, None, None]:
'''Returns all combinations of values the digits at position digits_pos can have
Examples:
digit_pos=(7,) -> 0, 1, 2, ..., 8, 9
digit_pos=(6,) -> 0, 10, 20, ..., 80, 90
digit_pos=(0,) -> 0, 10_000_000, ..., 90_000_000
digit_pos=(6, 7) -> 0, 1, 2, ..., 98, 99
digit_pos=(5, 7) -> 0, 1, 2, ..., 9, 100, 101, ... 109, 200, ..., 908, 909
digit_pos=(0, 5) -> 0, 10_000_000, 10_000_100, 10_000_200, ..., 90_000_900
Args:
digits_pos: An iterable whose values have to be between 0 and 9
For the output to be in an expectable order, the iterable
has to return the numbers in increasing order.
For example, if digits_pos=(7, 6), the yielded values will be:
0, 10, 20, 30, ... 90, 1, 11, 21, ...
'''
digits_generators = [self._get_generator_for_digit(digit_pos)
for digit_pos in digits_pos]
digits_generator = itertools.product(*digits_generators)
# return digits_generator
return map(sum, digits_generator)
</code></pre>
<p>And here are some tests:</p>
<pre class="lang-py prettyprint-override"><code>from dni_calculator import Dni, DniCalculator
dni_calc = DniCalculator()
assert dni_calc.find_letter(Dni(11_111_111)) == Dni(11_111_111, 'H')
assert dni_calc.find_letter(Dni(71_091_510)) == Dni(71_091_510, 'M')
assert dni_calc.find_letter(Dni(82_416_679)) == Dni(82_416_679, 'C')
assert dni_calc.find_missing_num(Dni(11_111_011, 'H', missing_digits=[5])) == Dni(11_111_111, 'H')
assert dni_calc.find_missing_num(Dni(75_623_008, 'E', missing_digits=[5])) == Dni(75_623_608, 'E')
assert dni_calc.find_missing_num(Dni(20_602_203, 'M', missing_digits=[3, 6])) == Dni(20_612_283, 'M')
dnis_generator = dni_calc.find_all_possible_dnis(Dni(5240700, 'Q', missing_digits=[6, 7]))
expected_results = (
Dni(5240704, 'Q'),
Dni(5240727, 'Q'),
Dni(5240750, 'Q'),
Dni(5240773, 'Q'),
Dni(5240796, 'Q'),
)
for dni, expected_result in zip(dnis_generator, expected_results):
assert dni == expected_result
</code></pre>
<p>The full code providing a simple CLI interface using <a href="https://github.com/google/python-fire" rel="noreferrer">fire</a> can be found at <a href="https://github.com/m-alorda/dni_calculator" rel="noreferrer">m-alorda/dni_calculator</a></p>
|
[] |
[
{
"body": "<h2>Basics</h2>\n<p><a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">PEP257</a> asks for double quotes and not single quotes for docstrings.</p>\n<p>These:</p>\n<pre><code>LENGTH_NUMS_ONLY = 8\nLENGTH = LENGTH_NUMS_ONLY + 1\n</code></pre>\n<p>should be type-hinted as <code>ClassVar[int]</code>.</p>\n<p>By convention the class reference variable for class methods is <code>cls</code>, not <code>clss</code>.</p>\n<p><code>from_dni</code> does not actually refer to <code>cls</code>, but it should: rather than constructing via <code>Dni</code>, you should construct <code>cls</code>. Beyond that, though, I'd sooner expect this to be an instance method <code>copy</code> that returns a copy of <code>self</code>.</p>\n<p>Ideally <code>Dni</code> should be made immutable by passing <code>frozen=true</code> to its decorator. This will reveal some design warts: currently <code>DniCalculator</code> is responsible for mutating <code>Dni.missing_digits</code>, but it should not be.</p>\n<p><code>_get_generator_for_digit</code> may be static, or better yet a class method on <code>Dni</code> itself.</p>\n<p>This:</p>\n<pre><code>print(f'Invalid dni given: "{self}". '\n + 'There cannot be missing numbers when finding a letter')\n</code></pre>\n<p>doesn't need the <code>+</code> and can use implicit concatenation.</p>\n<p><code>find_letter</code> should <code>raise</code> instead of <code>print</code>. Printing can be done at the outer level.</p>\n<p>Typo: <code>lettter</code> -> <code>letter</code></p>\n<p><code>[i for i in dni.missing_digits]</code> can just be <code>list(dni.missing_digits)</code>.</p>\n<p><code>_check_valid</code> would be more natural as a <code>@property is_valid</code> on <code>Dni</code> itself.</p>\n<p>This test:</p>\n<pre><code>for dni, expected_result in zip(dnis_generator, expected_results):\n</code></pre>\n<p>hides a failure mode where there is a length mismatch. Using <code>zip_longest</code> will fix this.</p>\n<h2>Congruential acceleration</h2>\n<p>Recognize that a problem such as finding all numbers for</p>\n<pre><code>052407??Q\n</code></pre>\n<p>is really a <a href=\"https://en.wikipedia.org/wiki/Modular_arithmetic#Congruence\" rel=\"nofollow noreferrer\">congruence relation</a> of the form</p>\n<p><span class=\"math-container\">$$\n5,240,700 + 10x + y \\equiv 16 \\mod 23\n$$</span></p>\n<p>You should be able to apply equivalence relation identities such that you find all answers analytically rather than by brute force; for your example:</p>\n<p><span class=\"math-container\">$$ y \\equiv 16 - 5,240,700 \\mod 23 $$</span>\n<span class=\"math-container\">$$ y \\equiv 4 \\mod 23 $$</span>\n<span class=\"math-container\">$$ y = 4 + 23 n, 0 \\le n \\le 4 $$</span></p>\n<p>I've not shown this in the implementation below.</p>\n<h2>Suggested</h2>\n<pre class=\"lang-py prettyprint-override\"><code>from dataclasses import dataclass\nfrom typing import Iterable, Optional, ClassVar, Tuple, Sequence\nimport itertools\n\n\n@dataclass(frozen=True)\nclass Dni:\n LETTERS: ClassVar[str] = 'TRWAGMYFPDXBNJZSQVHLCKE'\n LENGTH_NUMS_ONLY: ClassVar[int] = 8\n LENGTH: ClassVar[int] = LENGTH_NUMS_ONLY + 1\n\n digits: Tuple[Optional[int], ...]\n letter: Optional[str] = None\n\n @classmethod\n def from_number(cls, x: int, letter: Optional[str] = None) -> 'Dni':\n if x >= 10**cls.LENGTH_NUMS_ONLY:\n raise ValueError(f'{x} has incorrect length')\n return cls(\n digits=tuple(int(c) for c in str(x)),\n letter=letter,\n )\n\n @classmethod\n def parse(cls, s: str) -> 'Dni':\n *digits, letter = s\n if len(digits) != cls.LENGTH_NUMS_ONLY:\n raise ValueError(f'{s} has incorrect length')\n\n return cls(\n digits=tuple(\n None if d == '?' else int(d) for d in digits\n ),\n letter=None if letter == '?' else letter,\n )\n\n @property\n def is_complete(self) -> bool:\n return (\n self.letter is not None and\n not any(d is None for d in self.digits)\n )\n\n @property\n def number(self) -> int:\n x = 0\n for digit in self.digits:\n if digit is None:\n raise ValueError('Partial number cannot be linearised')\n x = 10*x + digit\n return x\n\n @property\n def number_as_str(self) -> str:\n """Return the number representing unknown digits as "?"\n\n For example, if number=11_011_111 and missing_digits=[2],\n returned value is "11?11111"\n """\n\n number_as_list = []\n for d in self.digits:\n number_as_list += '?' if d is None else str(d)\n\n return ''.join(number_as_list)\n\n @property\n def letter_as_str(self) -> str:\n """Return the letter or "?" if letter is not known"""\n if self.letter is None:\n return '?'\n return self.letter\n\n def __str__(self) -> str:\n return self.number_as_str + self.letter_as_str\n\n def copy(self) -> 'Dni':\n return Dni(self.digits)\n\n @classmethod\n def _get_letter(cls, number: int) -> str:\n return cls.LETTERS[number % len(cls.LETTERS)]\n\n @property\n def expected_letter(self) -> str:\n """Find the letter corresponding to the given dni\n\n Example:\n expected_letter(Dni(11111111)) -> 11111111H\n\n Args:\n dni: The dni whose letter is to be found.\n All of its digits have to be present\n """\n return self._get_letter(self.number)\n\n @classmethod\n def _get_generator_for_digit(cls, digit_pos: int) -> Sequence[int]:\n """Return the different value the digit at position digit_pos can have\n\n Examples:\n digit_pos=7 -> 0, 1, 2, ..., 8, 9\n digit_pos=6 -> 0, 10, 20, ..., 80, 90\n digit_pos=0 -> 0, 10_000_000, ..., 90_000_000\n\n Args:\n digit_pos: A number from 0 to 9\n """\n power = cls.LENGTH_NUMS_ONLY - digit_pos\n return range(0, 10**power, 10**(power - 1))\n\n @classmethod\n def _get_generator_for_digits(cls, digits_pos: Iterable[int]) -> Iterable[int]:\n """Returns all combinations of values the digits at position digits_pos can have\n\n Examples:\n digit_pos=(7,) -> 0, 1, 2, ..., 8, 9\n digit_pos=(6,) -> 0, 10, 20, ..., 80, 90\n digit_pos=(0,) -> 0, 10_000_000, ..., 90_000_000\n digit_pos=(6, 7) -> 0, 1, 2, ..., 98, 99\n digit_pos=(5, 7) -> 0, 1, 2, ..., 9, 100, 101, ... 109, 200, ..., 908, 909\n digit_pos=(0, 5) -> 0, 10_000_000, 10_000_100, 10_000_200, ..., 90_000_900\n\n Args:\n digits_pos: An iterable whose values have to be between 0 and 9\n For the output to be in an expectable order, the iterable\n has to return the numbers in increasing order.\n\n For example, if digits_pos=(7, 6), the yielded values will be:\n 0, 10, 20, 30, ... 90, 1, 11, 21, ...\n """\n digits_generators = (cls._get_generator_for_digit(digit_pos)\n for digit_pos in digits_pos)\n digits_generator = itertools.product(*digits_generators)\n return map(sum, digits_generator)\n\n @property\n def missing_num(self) -> Optional['Dni']:\n """Find the first complete dni valid for the given dni\n\n Args:\n dni: The dni for which to find the missing numbers\n\n It should have at least one missing digit.\n It also has to contain the letter.\n\n Examples:\n Dni(11_111_011, 'H', [5])\n Dni(11_100_111, 'H', [3, 4])\n """\n return next(self.all_possible_dnis, None)\n\n @property\n def all_possible_dnis(self) -> Iterable['Dni']:\n """Find the all of the valid dnis for the given dni\n\n Args:\n dni: The dni for which to find the missing numbers\n\n It should have at least one missing digit.\n It also has to contain the letter.\n\n Examples:\n Dni(11_111_011, 'H', [5])\n Dni(11_100_111, 'H', [3, 4])\n """\n\n base = sum(\n 0 if d is None else d * 10**(self.LENGTH_NUMS_ONLY - i)\n for i, d in enumerate(self.digits, 1)\n )\n\n digits_pos = [i for i, d in enumerate(self.digits) if d is None]\n for addend in self._get_generator_for_digits(digits_pos):\n number = addend + base\n letter = self._get_letter(number)\n if self.letter is None or letter == self.letter:\n yield Dni.from_number(number, letter)\n\n\ndef test():\n assert Dni.from_number(11_111_111).expected_letter == 'H'\n assert Dni.from_number(71_091_510).expected_letter == 'M'\n assert Dni.from_number(82_416_679).expected_letter == 'C'\n\n dni = Dni.parse('11111?11H').missing_num\n assert dni.letter == 'H'\n assert dni.number == 11_111_111\n\n dni = Dni.parse('75623?08E').missing_num\n assert dni.letter == 'E'\n assert dni.number == 75_623_608\n\n dni = Dni.parse('206?22?3M').missing_num\n assert dni.letter == 'M'\n assert dni.number == 20_612_283\n\n dnis_generator = Dni.parse('052407??Q').all_possible_dnis\n expected_numbers = (\n 5240704,\n 5240727,\n 5240750,\n 5240773,\n 5240796,\n )\n for dni, expected_number in itertools.zip_longest(dnis_generator, expected_numbers):\n assert dni.number == expected_number\n assert dni.letter == 'Q'\n\n\nif __name__ == '__main__':\n test()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T18:48:11.117",
"Id": "526644",
"Score": "0",
"body": "Thank you for taking the time to write all of this helpful feedback. I also knew there had to be a better way to find all possible dnis, but I did not know about congruence relations. Lastly, there is something I'm not sure of: Why do you think using property is better than methods? For simple things like `number`, `number_as_str` or even `expected_letter`, I can understand. But for some others, like `all_possible_dnis` I feel like properties hide the fact that some actual (even expensive) calculation is being done (`Dni.parse('????????H').all_possible_dnis`)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T18:50:23.200",
"Id": "526645",
"Score": "0",
"body": "If you're worried about property computation expense, apply an LRU cache. `@property` is just syntax sugar and is more convenient to invoke than the equivalent function notation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T23:10:35.407",
"Id": "526730",
"Score": "0",
"body": "I agree with @m-alorda - when creating objects, `.methods()` are actions the class undertakes on itself, and `.properties` are characteristics of the object. Conventions help to faciliate communicate between developers."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T14:53:17.360",
"Id": "266555",
"ParentId": "266535",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "266555",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-30T20:10:20.547",
"Id": "266535",
"Score": "5",
"Tags": [
"python"
],
"Title": "DNI (National ID) Calculator"
}
|
266535
|
<p>todo(1) is a program that lists the next tasks in decreasing order of urgency (most urgent tasks first).<br />
"Next" tasks are those which are not blocked by a task it depends that is still not set as done.</p>
<p>I think I'm using a convoluted solution, because I create five different data structures in the program.<br />
First, I collect tasks in a hash table (1) and an unsorted list (2).<br />
While I'm collecting tasks, I get its dependencies and build a graph of tasks (3).<br />
Then, I free the hash table (I use it only to get the dependencies without having to loop over the unsorted list all the time).<br />
Then, I iterate over the unsorted list of tasks to visit each node in the graph and create a topologically sorted list of tasks (4).<br />
Then, I iterate over that sorted list and extract those tasks that are not blocked into an array (5) of unblocked tasks. I sort this array based on the urgency of the tasks.<br />
Finally, I print that array.</p>
<p>To compute the urgency, I do the following:<br />
I compute the difference of days between the deadline and today.<br />
Then I compute the log2 of this difference.<br />
Then I subtract the result by the priority (1 for A, 0 for B, -1 for C).<br />
The result of the subtraction is the urgency. The lower the better.</p>
<p>Here's the manual with a example of usage:</p>
<pre class="lang-none prettyprint-override"><code>TODO(1) General Commands Manual TODO(1)
NAME
todo - print next tasks
SYNOPSIS
todo [-dl] file...
DESCRIPTION
todo reads files for tasks, one task per line; and writes to the
standard output those tasks that should be done, and that are not
blocked by other undone tasks. The tasks are ordered in decrescend
order of urgency (the most urgent task is the first listed). If a
hyphen (-) is provided as argument or the argument is absent, todo
reads from the standard input. The options are as follows:
-d Consider tasks whose deadline has already passed as done, even
if they are not explicitly set as done.
-l Long format. Display tasks with its internal name, priority and
deadline.
Each event must begin with an optional status. Two status are
possible: TODO (which defines a uncompleted task) or DONE (which
defines a completed task). If no status is supplied, it is considered
as TODO.
After the optional status comes the optional priority. The priority is
a single uppercase letter between parentheses. The letter must be A, B
or C. The lower the letter, the higher the priority; so “A” is the
higher priority.
After the optional priority comes the obligatory task name. The task
name is a single alphanumeric word without spaces that names the task.
The task name must be followed by a colon.
After the task name comes the optional task description. The task
description spans from the space after the colon that ends the task
name to the beginning of the first property.
After the optional task description comes the properties. Properties
are a space-delimited list of name-value pairs separated by colon. The
following property names and their respective values are listed below.
due A property of the form due:YYYY-MM-DD specifies the deadline of
the task.
deps A property of the form deps:dep1,dep2,…,depN specifies a comma-
delimited list of tasks that this task depends on.
If a task line ends in a backslash (\), the task continues in the next
line. If a line does not match the format of a task specification,
that line is ignored and a warning is printed to stderr.
EXAMPLES
Consider the following input.
DONE graph: (B) Learn graphs.
TODO manual: (C) Write manual for todo(1).
TODO sort: (B) Learn how to do topological sorting. deps:graph
TODO data: (A) Implement data structures for tasks.
TODO parser: (B) Write code for parsing tasks. deps:data
TODO algor: (A) Implement algorithm for sorting tasks. deps:data,sort
TODO todo: (B) Write the todo(1) utility. deps:parser,algor
TODO release: (C) Release todo(1). deps:todo,manual
Running todo with the option -l on this input would print the
following:
data: (A) Implement data structures for tasks.
sort: (B) Learn how to do topological sorting.
manual: (C) Write manual for todo(1).
SEE ALSO
calendar(1), schedule(1)
TODO(1)
</code></pre>
<p>Here's the code:</p>
<pre class="lang-c prettyprint-override"><code>#include <sys/time.h>
#include <ctype.h>
#include <err.h>
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#define SECS_PER_DAY ((time_t)(24 * 60 * 60))
#define DAYS_PER_WEEK 7
#define MIDDAY 12 /* 12:00 */
#define NHASH 128 /* size of hash table */
#define MULTIPLIER 31 /* multiplier for hash table */
#define NCOLS 10 /* number of collumns reserved for task name in long format */
#define TODO "TODO"
#define DONE "DONE"
#define PROP_DEPS "deps"
#define PROP_DUE "due"
/* task structure */
struct Task {
struct Task *hnext; /* pointer for hash table linked list */
struct Task *unext; /* pointer for unsorted linked list */
struct Task *snext; /* pointer for sorted linked list */
struct Edge *deps; /* linked list of dependency edges */
time_t due; /* due date, at 12:00 */
int pri; /* priority */
int visited; /* whether node was visited while sorting */
int done; /* whether task is marked as done */
char *date; /* due date, in format YYYY-MM-DD*/
char *name; /* task name */
char *desc; /* task description */
};
/* dependency link */
struct Edge {
struct Edge *next; /* next edge on linked list */
struct Task *to; /* task the edge links to */
};
/* list and table of tasks */
struct Agenda {
struct Task **htab; /* hash table of tasks */
struct Task **array; /* array of sorted, unblocked tasks */
struct Task *unsort; /* head of unsorted list of tasks */
struct Task *shead, *stail; /* head and tail of sorted list of tasks */
size_t nunblock; /* number of unblocked tasks */
};
/* time for today, 12:00 */
static time_t today;
/* option flags */
static int dflag; /* whether to consider tasks with passed deadline as done */
static int lflag; /* whether to display tasks in long format */
/* show usage and exit */
static void
usage(void)
{
(void)fprintf(stderr, "usage: todo [-ld] [file...]\n");
exit(1);
}
/* call malloc checking for error */
static void *
emalloc(size_t size)
{
void *p;
if ((p = malloc(size)) == NULL)
err(1, "malloc");
return p;
}
/* call calloc checking for error */
static void *
ecalloc(size_t nmemb, size_t size)
{
void *p;
if ((p = calloc(nmemb, size)) == NULL)
err(1, "calloc");
return p;
}
/* call strdup checking for error */
static char *
estrdup(const char *s)
{
char *t;
if ((t = strdup(s)) == NULL)
err(1, "strdup");
return t;
}
/* get time for today, at 12:00 */
static time_t
gettoday(void)
{
struct tm *tmorig;
struct tm tm;
time_t t;
if ((t = time(NULL)) == -1)
err(1, NULL);
if ((tmorig = localtime(&t)) == NULL)
err(1, NULL);
tm = *tmorig;
tm.tm_hour = MIDDAY;
tm.tm_min = 0;
tm.tm_sec = 0;
tm.tm_isdst = -1;
if ((t = mktime(&tm)) == -1)
err(1, NULL);
return t;
}
/* compute hash value of string */
static size_t
hash(const char *s)
{
size_t h;
unsigned char *p;
h = 0;
for (p = (unsigned char *)s; *p != '\0'; p++)
h = MULTIPLIER * h + *p;
return h % NHASH;
}
/* find name in agenda, creating if does not exist */
static struct Task *
lookup(struct Agenda *agenda, const char *name)
{
size_t h;
struct Task *p;
h = hash(name);
for (p = agenda->htab[h]; p != NULL; p = p->hnext)
if (strcmp(name, p->name) == 0)
return p;
p = emalloc(sizeof(*p));
p->name = estrdup(name);
p->hnext = agenda->htab[h];
p->unext = agenda->unsort;
agenda->htab[h] = p;
agenda->unsort = p;
return p;
}
/* create agenda and hash table */
static struct Agenda *
newagenda(void)
{
struct Agenda *agenda;
agenda = ecalloc(1, sizeof(*agenda));
agenda->htab = ecalloc(NHASH, sizeof(*(agenda->htab)));
return agenda;
}
/* add dependencies to task; we change s */
static void
adddeps(struct Agenda *agenda, struct Task *task, char *s)
{
struct Task *tmp;
struct Edge *edge;
char *t;
for (t = strtok(s, ","); t != NULL; t = strtok(NULL, ",")) {
tmp = lookup(agenda, t);
edge = emalloc(sizeof(*edge));
edge->next = task->deps;
edge->to = tmp;
task->deps = edge;
}
}
/* add deadline to task */
static void
adddue(struct Task *task, char *s)
{
struct tm *tmorig;
struct tm tm;
time_t t;
char *ep;
if ((tmorig = localtime(&today)) == NULL) {
warn(NULL);
return;
}
tm = *tmorig;
ep = strptime(s, "%Y-%m-%d", &tm);
if (ep == NULL || *ep != '\0') {
errno = EINVAL;
warn("%s", s);
return;
}
tm.tm_hour = MIDDAY;
tm.tm_min = 0;
tm.tm_sec = 0;
tm.tm_isdst = -1;
if ((t = mktime(&tm)) == -1) {
warn(NULL);
return;
}
task->date = estrdup(s);
task->due = t;
if (dflag && task->due < today) {
task->done = 1;
}
}
/* parse s for a new task and add it into agenda; we change s */
static void
addtask(struct Agenda *agenda, char *s)
{
struct Task *task;
size_t len;
int done;
char *name, *prop, *val;
char *t, *end, *colon;
int pri;
while (isspace(*(unsigned char *)s))
s++;
done = 0;
if (strncmp(s, TODO, sizeof(TODO) - 1) == 0) {
s += sizeof(TODO) - 1;
} else if (strncmp(s, DONE, sizeof(DONE) - 1) == 0) {
done = 1;
s += sizeof(DONE) - 1;
}
while (isspace(*(unsigned char *)s))
s++;
name = NULL;
for (t = s; *t != '\0' && !isspace(*(unsigned char *)t); t++) {
if (*t == ':') {
name = s;
*t = '\0';
s = t + 1;
break;
}
}
if (name == NULL)
return;
while (isspace(*(unsigned char *)s))
s++;
pri = 0;
if (s[0] == '(' && s[1] >= 'A' && s[1] <= 'C' && s[2] == ')') {
switch (s[1]) {
case 'A':
pri = +1;
break;
default:
pri = 0;
break;
case 'C':
pri = -1;
break;
}
s += 3;
}
task = lookup(agenda, name);
task->pri = pri;
task->done = done;
while (isspace(*(unsigned char *)s))
s++;
len = strlen(s);
for (t = &s[len - 1]; t >= s; t--) {
colon = NULL;
while (t >= s && isspace(*(unsigned char *)t))
t--;
end = t + 1;
while (t >= s && !isspace(*(unsigned char *)t)) {
if (*t == ':') {
colon = t;
*colon = '\0';
}
t--;
}
if (colon) {
*t = '\0';
*end = '\0';
prop = t + 1;
val = colon + 1;
if (strcmp(prop, PROP_DUE) == 0) {
adddue(task, val);
} else if (strcmp(prop, PROP_DEPS) == 0) {
adddeps(agenda, task, val);
} else {
warnx("unknown property \"%s\"", prop);
}
} else {
break;
}
}
len = strlen(s);
for (t = &s[len - 1]; isspace(*(unsigned char *)t) && t >= s; t--)
*t = '\0';
free(task->desc);
task->desc = estrdup(s);
}
/* read tasks from fp into agenda */
static void
readtasks(FILE *fp, struct Agenda *agenda)
{
char buf[BUFSIZ];
while (fgets(buf, sizeof(buf), fp) != NULL) {
addtask(agenda, buf);
}
}
/* visit task and their dependencies */
static void
visittask(struct Agenda *agenda, struct Task *task)
{
struct Edge *edge;
if (task->visited > 1)
return;
if (task->visited == 1)
errx(1, "cyclic dependency between tasks");
task->visited = 1;
for (edge = task->deps; edge != NULL; edge = edge->next)
visittask(agenda, edge->to);
task->visited = 2;
if (agenda->shead == NULL)
agenda->shead = task;
if (agenda->stail != NULL)
agenda->stail->snext = task;
agenda->stail = task;
}
/* compare tasks */
static int
comparetask(const void *a, const void *b)
{
struct Task *taska, *taskb;
time_t timea, timeb;
time_t tmpa, tmpb;
taska = *(struct Task **)a;
taskb = *(struct Task **)b;
tmpa = (taska->due != 0) ? (taska->due - today) / SECS_PER_DAY : DAYS_PER_WEEK;
tmpb = (taskb->due != 0) ? (taskb->due - today) / SECS_PER_DAY : DAYS_PER_WEEK;
timea = timeb = 0;
if (tmpa < 0) {
tmpa = -tmpa;
while (tmpa >>= 1) {
--timea;
}
} else {
while (tmpa >>= 1) {
++timea;
}
}
if (tmpb < 0) {
tmpb = -tmpb;
while (tmpb >>= 1) {
--timeb;
}
} else {
while (tmpb >>= 1) {
++timeb;
}
}
timea -= taska->pri;
timeb -= taskb->pri;
if (timea < timeb)
return -1;
if (timea > timeb)
return +1;
return 0;
}
/* perform topological sort on agenda */
static void
sorttasks(struct Agenda *agenda)
{
struct Task *task;
struct Edge *edge;
size_t ntasks;
int cont;
free(agenda->htab);
ntasks = 0;
for (task = agenda->unsort; task != NULL; task = task->unext) {
if (!task->visited)
visittask(agenda, task);
ntasks++;
}
agenda->array = ecalloc(ntasks, sizeof(*agenda->array));
for (task = agenda->shead; task != NULL; task = task->snext) {
if (task->done)
continue;
if (task->deps != NULL) {
cont = 0;
for (edge = task->deps; edge != NULL; edge = edge->next) {
if (!edge->to->done) {
cont = 1;
break;
}
}
if (cont) {
continue;
}
}
agenda->array[agenda->nunblock++] = task;
}
qsort(agenda->array, agenda->nunblock, sizeof(*agenda->array), comparetask);
}
/* print sorted tasks */
static void
printtasks(struct Agenda *agenda)
{
struct Task *task;
size_t i;
int n;
for (i = 0; i < agenda->nunblock; i++) {
task = agenda->array[i];
if (lflag) {
n = printf("%s", task->name);
n = (n > 0 && n < NCOLS) ? NCOLS - n : 0;
(void)printf(":%*c (%c) %s", n, ' ', (task->pri < 0 ? 'C' : (task->pri > 0 ? 'A' : 'B')), task->desc);
if (task->date != NULL) {
(void)printf(" due:%s", task->date);
}
} else {
(void)printf("%s", task->desc);
}
printf("\n");
}
}
/* free agenda and its tasks */
static void
freeagenda(struct Agenda *agenda)
{
struct Task *task, *ttmp;
struct Edge *edge, *etmp;
for (task = agenda->unsort; task != NULL; ) {
for (edge = task->deps; edge != NULL; ) {
etmp = edge;
edge = edge->next;
free(etmp);
}
ttmp = task;
task = task->unext;
free(ttmp->name);
free(ttmp->desc);
free(ttmp->date);
free(ttmp);
}
free(agenda->array);
free(agenda);
}
/* todo: print next tasks */
int
main(int argc, char *argv[])
{
static struct Agenda *agenda;
FILE *fp;
int exitval, ch;
today = gettoday();
while ((ch = getopt(argc, argv, "dl")) != -1) {
switch (ch) {
case 'd':
dflag = 1;
break;
case 'l':
lflag = 1;
break;
default:
usage();
break;
}
}
argc -= optind;
argv += optind;
exitval = 0;
agenda = newagenda();
if (argc == 0) {
readtasks(stdin, agenda);
} else {
for (; *argv != NULL; argv++) {
if (strcmp(*argv, "-") == 0) {
readtasks(stdin, agenda);
continue;
}
if ((fp = fopen(*argv, "r")) == NULL) {
warn("%s", *argv);
exitval = 1;
continue;
}
readtasks(fp, agenda);
fclose(fp);
}
}
sorttasks(agenda);
printtasks(agenda);
freeagenda(agenda);
return exitval;
}
</code></pre>
<p><strong>EDIT:</strong> I removed the topological sort and released todo(1) <a href="https://github.com/phillbush/orgutils" rel="nofollow noreferrer">on github</a> with another utility of mine.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T20:22:06.993",
"Id": "526656",
"Score": "0",
"body": "To handle 16-bit systems, (since code not tagged *nix), `((time_t)(24 * 60 * 60))` should be `((time_t) 24 * 60 * 60)` to avoid overflow. `(taska->due - today) / SECS_PER_DAY` assumes `time_T` is a count of seconds. Use `difftime()` for portability."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T22:14:23.073",
"Id": "526664",
"Score": "0",
"body": "I didn't know `time_t` could not be a count of seconds in some platforms. But difftime returns a double... I'll try it but... that's unusual. The return of difftime(3) is guaranteed to be in seconds, so I can divide it by `SECS_PER_DAY` and get the number of days between tasks due date and today? I just discovered timespecsub(3), a BSD innovation, but I won't use it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T23:10:59.597",
"Id": "526665",
"Score": "0",
"body": "C's time functions are lacking - sigh - no `mkgmtime()`, timezone weaknesses, ..."
}
] |
[
{
"body": "<h1>About the manpage</h1>\n<p>The manpage looks very nice! There's a few small improvements that could be made:</p>\n<ul>\n<li>Spelling: "decrescend" should be "decreasing".</li>\n<li>Some conflicting statements are made, like "Each event <strong>must</strong> begin with an <strong>optional</strong> status." Consider rewriting this to avoid any confusion. Perhaps also start with a single line showing the syntax of each line, like so:\n<pre><code>[status] [priority] task-name: [description] [name:value]...\n</code></pre>\n</li>\n<li>Also, the description says the priority comes after status and before the task name, but the example shows the priority coming after the task name.</li>\n<li>Put the description of the file format in its own section.</li>\n<li>Show off all features in the examples section, in particular I am not seeing the "due" option being used, nor line continuation using backslashes.</li>\n</ul>\n<h1>Avoid using <code>#define</code> if a <code>static const</code> variable will do</h1>\n<p>Instead of defining constants using <code>#define</code>, prefer declaring them as <code>static const</code> variables instead. This avoids having to deal with macro issues like needing lots of parentheses, and ensures those constants also have a type associated with them. For example:</p>\n<pre><code>static const time_t SECS_PER_DAY = 24 * 60 * 60;\nstatic const int DAYS_PER_WEEK = 7;\n...\nstatic const char PROP_DUE[] = "due";\n</code></pre>\n<h1>Reduce the number of data structures</h1>\n<blockquote>\n<p>I think I'm using a convoluted solution, because I create five different data structures in the program.</p>\n</blockquote>\n<p>Indeed, it's a bit much, and you could get rid of some. Instead of having hash maps and linked lists, you could store everything in arrays: one array of <code>struct Task</code>s, and perhaps some others with pointers to <code>Task</code>s if necessary. This whole array can then be sorted using <code>qsort()</code>, and then you can do <span class=\"math-container\">\\$\\mathcal{O}(\\log N)\\$</span> lookups using <a href=\"https://en.cppreference.com/w/c/algorithm/bsearch\" rel=\"noreferrer\"><code>bsearch()</code></a>.</p>\n<p>While hash maps are the fastest for sufficiently large numbers of tasks, a sorted array will probably outperform it for a small number of tasks.</p>\n<p>Another option is to not use your own hash map implementation, but use the POSIX <a href=\"https://linux.die.net/man/3/hcreate\" rel=\"noreferrer\"><code>hcreate()</code></a> and related functions.</p>\n<h1>Unnecessary topological sort</h1>\n<p>You mention you do a topological sort of the tasks, then iterate over that sorted list and print out all the unblocked tasks. However, just determining whether tasks are blocked or not does not require a topological sort at all. Instead, just add a flag <code>bool blocked</code> to <code>struct Task</code>, make sure it is <code>false</code> when a new <code>Task</code> is created. Then after reading in all the tasks, just iterate over all of them, and for each task check its dependencies. If it depends on a task that is not yet DONE, then just set <code>blocked = true</code>. Then do another pass to print out only the tasks that have <code>blocked == false</code>. If you only allow dependencies on tasks that have already been read in, then you can even do the check of being blocked inside <code>addtask()</code>.</p>\n<h1>Rename <code>lookup()</code> to <code>lookup_or_create()</code></h1>\n<p>The <code>lookup</code> function also is used to create new tasks, so I would rename it <code>lookup_or_create()</code>. Alternatively, have separate <code>lookup()</code> and <code>newtask()</code> functions.</p>\n<h1>Initialize all elements when creating a new <code>Task</code></h1>\n<p>In <code>lookup()</code>, when you create a new <code>Task</code>, you only initialize some of the elements of this struct. I recommend you ensure all of them are properly initialized, by just using <code>ecalloc()</code> instead of <code>emalloc()</code>. This will avoid surprises.</p>\n<h1>Add comments to or split up long functions</h1>\n<p>The function <code>addtask()</code> is quite long. Try to separate it into several sections and add a comment to each section describing what is done. It should look something like this:</p>\n<pre><code>// Strip leading spaces\nwhile (isspace((unsigned char)*s))\n s++;\n\n// Check for the optional state\ndone = 0;\nif (strncmp(s, TODO, sizeof(TODO) - 1) == 0) {\n ...\n}\n...\n\n// Read the task name\n...\n\n// And so on...\n</code></pre>\n<p>Even better would be to create separate functions for each section, so that <code>addtask()</code> would look like this instead:</p>\n<pre><code>done = readstatus(&s);\n\nname = readname(&s);\nif (name == NULL)\n return;\n...\n</code></pre>\n<p>Where for example <code>readstatus()</code> would look like:</p>\n<pre><code>static void skipspaces(char **s) {\n while (isspace((unsigned char)**s))\n ++*s;\n}\n\nstatic bool readstatus(char **s) {\n skipspace(s);\n\n if (strncmp(*s, ...)) {\n *s += ...;\n } else if (...) {\n ...\n return true;\n }\n\n return false;\n}\n</code></pre>\n<h1>Missing error checking</h1>\n<p>You check whether files are opened correctly, but you don't check if the files were read correctly. After reading in all the lines, use <a href=\"https://en.cppreference.com/w/c/io/feof\" rel=\"noreferrer\"><code>feof()</code></a> to check whether you actually reached the end of the file. If not, something has gone wrong.</p>\n<p>Also consider exitting the program immediately upon any read error, instead of just setting <code>exitval = 1</code>. The user might not notice the non-zero exit code, and you are printing potentially incorrect data.</p>\n<p>Furthermore, also consider exitting with an error message and non-zero exit code if parsing the lines failed, and if other errors are detected such as cyclical dependencies.</p>\n<p>You might also want to check that printing the tasks was done succesfully. Consider someone redirecting standard output to a file on a file system that is nearly full. In case writing fails, you again want to print an error message to standard error, and exit with a non-zero exit code. To do this correctly, I recommend you do this right at the end of <code>main()</code> by first calling <code>fflush()</code>, then using <a href=\"https://en.cppreference.com/w/c/io/ferror\" rel=\"noreferrer\"><code>ferror()</code></a> to check if any error was encountered while writing to <code>stdout</code>.</p>\n<p>I also recommend you use <a href=\"https://en.cppreference.com/w/c/program/EXIT_status\" rel=\"noreferrer\"><code>EXIT_SUCCESS</code> and <code>EXIT_FAILURE</code></a> as the exit codes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T13:25:03.730",
"Id": "526625",
"Score": "0",
"body": "Thanks for the answer! I edited the OP to add a link to a github repo with an updated version of todo(1). Indeed, the topological sort was unnecessary so I removed it. I'm not using hsearch(1) because OpenBSD's implementation seems to differ from Linux's in how the key element of `ENTRY` must be allocated (but I might be wrong)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T13:41:28.173",
"Id": "526626",
"Score": "0",
"body": "btw, I'm not exiting on a read error because I want to follow cat(1)'s behavior of ignoring nonexistent files and just print an error to stderr(4) and exit with nonzero status after processing all the other files."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T10:14:31.787",
"Id": "266547",
"ParentId": "266538",
"Score": "10"
}
},
{
"body": "<blockquote>\n<pre><code> agenda->htab = ecalloc(NHASH, sizeof(*(agenda->htab)));\n</code></pre>\n</blockquote>\n<p>GCC's static analyzer can't find a corresponding call to <code>free()</code> for this allocation. It gets through Valgrind at runtime, but that's only because <code>sorttasks()</code> has been called, which is fragile. And if <code>sorttasks()</code> gets called more than once, we'll be accessing freed memory, which is UB.</p>\n<p>I would modify <code>sorttasks</code> to set <code>agenda->htab = NULL</code> after freeing the memory, and add <code>free(agenda->htab)</code> to <code>freeagenda()</code>. That will make the code much more robust (and keep the static analysis on our side).</p>\n<p>Also, it's a poor assumption that <code>calloc()</code> produces null pointers - that's not universally true for all architectures.</p>\n<hr />\n<p>The order of functions in the file makes it harder to find things. In particular, I would expect <code>newagenda()</code> and <code>freeagenda()</code> to be adjacent.</p>\n<p>In <code>freeagenda()</code>, there's no need for the variables to be at function scope. They can be reduced to where they are used (and given better names):</p>\n<pre><code>static void\nfreeagenda(struct Agenda *agenda)\n{\n for (struct Task *task = agenda->unsort; task; ) {\n struct Task *next_task = task->unext;\n for (struct Edge *edge = task->deps; edge; ) {\n struct Edge *next_edge = edge->next;\n free(edge);\n edge = next_edge;\n }\n free(task->name);\n free(task->desc);\n free(task->date);\n free(task);\n task = next_task;\n }\n free(agenda->array);\n free(agenda);\n}\n</code></pre>\n<hr />\n<blockquote>\n<pre><code>static void\nusage(void)\n{\n (void)fprintf(stderr, "usage: todo [-ld] [file...]\\n");\n exit(1);\n}\n</code></pre>\n</blockquote>\n<p>This usage message is useful only as an error. We could adapt it to provide <code>--help</code>:</p>\n<pre><code>static void __attribute__((noreturn))\nusage(int is_err)\n{\n fputs("usage: todo [-ld] [file...]\\n", is_err ? stderr : stdout);\n exit(is_err);\n}\n</code></pre>\n<hr />\n<p>It's a shame not to see the unit tests for the parsing. There's a lot of problem cases to consider, and I would expect the tests to be present, to give confidence in future changes. I wouldn't accept this without the accompanying test suite.</p>\n<hr />\n<p>(This is a partial review - I got a higher-priority interrupt and not sure whether I'll return to this.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T16:49:12.483",
"Id": "526633",
"Score": "0",
"body": "\"it's a poor assumption that calloc() produces null pointers\" is curious. Why poor? C spec does have \"The calloc function returns either a null pointer or a pointer to the allocated space.\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T16:52:50.073",
"Id": "526635",
"Score": "1",
"body": "Re; `freeagenda()`, perhaps tolerate `freeagenda(NULL)`, just like `free(NULL)` is OK. Easier to do clean-up."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T20:56:51.537",
"Id": "526659",
"Score": "1",
"body": "@chux-ReinstateMonica I think they mean after successful `calloc`, the return value has length all-bits-zero, *not* guaranteed to be a null-pointer. I see only `struct Task` that has 2 fields which would be affected."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T21:01:54.937",
"Id": "526662",
"Score": "0",
"body": "@Neil Fair point. Yes,some esoteric platforms do not have a pointer of all zero bits as a _null pointer_. I suspect Darwinian code pressure has lead to their extinction - even if allowed by spec."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T06:59:45.780",
"Id": "526671",
"Score": "0",
"body": "@chux, yes Neil's interpretation is what I meant. Sorry for not being clearer. I've never used a platform where all-zeros isn't a null pointer (or even any where there are other null pointers), but thought I should point out the lack of guarantee."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T11:31:20.263",
"Id": "266551",
"ParentId": "266538",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "266547",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-30T23:53:31.237",
"Id": "266538",
"Score": "8",
"Tags": [
"c",
"unix",
"to-do-list",
"topological-sorting"
],
"Title": "Task manager with dependencies"
}
|
266538
|
<p>I want to locate urls without protocols in the text, and then add the protocol before them. This means I don't want urls that begin with <code>http(s)://</code> or <code>http(s)://www.</code>, only the kind of <code>example.com</code>. I'm aware that I might accidentally match with any <code>text1.text2</code> if I forgot to add a space after a period, so I came up with some rules to make it more like an actual url:</p>
<pre><code>(?<=^|\s)(\w*-?\w+\.[a-z]{2,}\S*)
</code></pre>
<hr />
<ul>
<li><code>(?<=^|\s)</code> The URL should be after the newline or a space.</li>
<li><code>\w*-?\w+</code> The domain part, could have a dash (-) or not. Since it's after a newline or space, it removes the protocol.</li>
<li><code>[a-z]{2,}</code> The extension, should be more than 2 letters</li>
<li><code>\S*</code> The rest of the URL</li>
</ul>
<p>It works well to match <code>example.com</code> or <code>example.com/x1/x2</code> and not <code>https://example.com</code>. But I think it's a bit clumsy, and it fails if there is . or , after the url.</p>
<p>How can I achieve the same goal more elegantly? I don't need to match urls like <code>1.1.1.1</code>. Are there some loopholes in the above rules that I haven't yet considered?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T08:00:50.843",
"Id": "526673",
"Score": "0",
"body": "Duplicate of this stack overflow question: https://stackoverflow.com/questions/3809401/what-is-a-good-regular-expression-to-match-a-url"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T17:29:39.900",
"Id": "527782",
"Score": "0",
"body": "`(?<!\\S)` in place of `(?<=^|\\s)` (with this simple negation you avoid the alternation). If you want to avoid a dot (that ends a sentence), change the last `\\S*` to `\\S*(?<![.])`. (But whatever you do, don't dream, it can't be perfect even if your pattern fully and precisely describes the URL syntax."
}
] |
[
{
"body": "<p>For elegance, I would put at least one line of comment pointing to this;\n<a href=\"https://datatracker.ietf.org/doc/html/rfc1034#section-3.5\" rel=\"nofollow noreferrer\">https://datatracker.ietf.org/doc/html/rfc1034#section-3.5</a></p>\n<p>You will notice that there is no limit on the top level domain (Belgian, Dutch, and French domains would like to have a word with .be, .nl, and .fr)</p>\n<p>It's unclear if your regex deals well with subdomains</p>\n<p>Personally, I would break out the regex in to it's components, following the URL I provided.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T09:37:39.347",
"Id": "266545",
"ParentId": "266539",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T01:45:59.053",
"Id": "266539",
"Score": "0",
"Tags": [
"javascript",
"regex",
"url"
],
"Title": "Regex detect URL without http(s):// and www"
}
|
266539
|
<p>Can I get a review of my code which compares 2 dictionaries and display unique changes.</p>
<pre><code>import time
from random import randrange
temp_data = [{"Name":"SuperFish","KeyID":"SecretCodeFish"},
{"Name":"CowMan","KeyID":"SecretCodeCow"}]
def check_data(Names):
temp_key = "SpecialKey"
temp_list = []
for item in Names:
Users = {
'Name': item['Name'],
'Status':(randrange(2))}
temp_list.append(Users)
return temp_list
def display_data(data):
for i in data:
print("===")
print (i)
print("===")
Prev = check_data(temp_data)
Curr = check_data(temp_data)
New = []
# Runs Repeteadly
while True:
Curr = check_data(temp_data)
time.sleep(3)
for item in Curr:
if item not in (Prev):
New.append(item)
if len(New)>0:
Prev = Curr
display_data(New)
New = []
else:
print("NO CHANGES DETECTED")
</code></pre>
<p>I'm mainly wondering if there is a cleaner way to write my solution.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T23:45:52.897",
"Id": "526666",
"Score": "2",
"body": "It's doubtful that you should be using a dictionary the way that you are, and should be passing around a stronger type like a named tuple or class instance, but your question is too hypothetical to answer. Surely you're not _actually_ doing what `check_data` is doing every three seconds, but you haven't described your real use case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T18:23:00.753",
"Id": "526715",
"Score": "0",
"body": "Welcome to Code Review! I have rolled back Rev 3 → 2. Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T12:34:36.477",
"Id": "527803",
"Score": "0",
"body": "What's with all the temp data and hardcoded values?"
}
] |
[
{
"body": "<p><strong>General</strong></p>\n<p>Variable names and function arguments should be lowercase.</p>\n<p>You should wrap your main procedure in a main function, as well as a <code>if __name__ == '__main__'</code> guard. <a href=\"https://stackoverflow.com/a/419185/9173379\">More info</a>.</p>\n<p>Function and variable naming are important for readability of your code. The clearer and more accurate your naming, the quicker and easier your code can be understood. For example: <code>check_data</code> does not check any data.\n<br>\nIts argument <code>names</code> is not a list of names, but a list of dictionaries that have a name and an id.\n<br>\nIf I only see that function signature, I would expect to be able to do <code>for name in names</code> and get one name (probably as <code>str</code>) after another. Instead I get a <code>dict</code>, that has a <code>"Name"</code> field. <code>for item in names</code> should be an indicator, that <code>names</code> should be called something like <code>items</code>.</p>\n<p>Type hints also make your code easier to read and understand, use them. <a href=\"https://www.python.org/dev/peps/pep-0484/\" rel=\"nofollow noreferrer\">PEP 484</a> | <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">Python Docs</a></p>\n<hr />\n<p><strong><code>check_data</code></strong></p>\n<p>It's not quite clear why this function does what it does. Documentation (comments / docstrings) as to why this function is implemented this way would help.</p>\n<p><code>temp_key</code> is never used, delete it.</p>\n<p>In its current state, the function can easily be cut down to a single line using a list comprehension:</p>\n<pre><code>def change_data(items: list[dict]) -> list[dict]:\n return [{'Name': item['Name'], 'Status': randrange(2)} for item in items]\n</code></pre>\n<p>If you're not familiar with list comprehensions and generator expressions I would recommend learning about them. They're a useful (and often very efficient) tool.</p>\n<p>But beware that a one-liner is not always the best option. If the creation of the dictionaries gets more complex it's probably better to move it to its own function.</p>\n<p>Also note that <code>'Status': (randrange(2))</code> does not need as many parentheses: <code>'Status': randrange(2)</code>.</p>\n<hr />\n<p><strong><code>display_data</code></strong></p>\n<p>I'd recommend cutting this down to a single <code>print</code> statement per loop iteration:</p>\n<pre><code>def display_data(data: list) -> None:\n for i in data:\n print("===", i, "===", sep="\\n")\n</code></pre>\n<p>or even better</p>\n<pre><code>def display_data(data: list) -> None:\n line_sep = "==="\n for i in data:\n print(line_sep, i, line_sep, sep="\\n")\n</code></pre>\n<hr />\n<p><strong><code>main</code></strong></p>\n<p>Your first initialization of <code>curr</code> is immediately overwritten inside the loop, delete it.</p>\n<p><code>if item not in (prev)</code>, does not need parentheses: <code>if item not in prev</code>.</p>\n<p>There are better (more readable and more efficient) ways to create <code>new</code>, which should be called <code>new_items</code> or <code>changed_items</code>:\n<br></p>\n<ul>\n<li>List comprehension: <code>new_items = [item for item in curr if item not in prev]</code></li>\n<li>Functional approach: <code>new_items = list(filter(lambda item: item not in prev, curr))</code></li>\n</ul>\n<p>This also allows you to get rid of both <code>new = []</code> assignments, as these approaches will create an empty list if there are no new items.</p>\n<p>You can replace <code>if len(new_items) > 0</code> by <code>if new_items</code>. <a href=\"https://www.freecodecamp.org/news/truthy-and-falsy-values-in-python/\" rel=\"nofollow noreferrer\">More about truthy and falsy values in Python</a></p>\n<hr />\n<p><strong>Complete code</strong></p>\n<pre><code>import time\nfrom random import randrange\n\ntemp_data = [{"Name": "SuperFish", "KeyID": "SecretCodeFish"},\n {"Name": "CowMan", "KeyID": "SecretCodeCow"}]\n\n\ndef change_data(items: list[dict]) -> list[dict]:\n return [{'Name': item['Name'], 'Status': randrange(2)} for item in items]\n\n\ndef display_data(data: list) -> None:\n line_sep = "==="\n for i in data:\n print(line_sep, i, line_sep, sep="\\n")\n\n\ndef main():\n prev = change_data(temp_data)\n\n while True:\n time.sleep(3)\n\n curr = change_data(temp_data)\n\n new_items = [item for item in curr if item not in prev]\n\n if new_items:\n prev = curr\n display_data(new_items)\n else:\n print("NO CHANGES DETECTED")\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<hr />\n<p><strong>Approach</strong></p>\n<p>Please note that the current algorithm runs in O(n^2). Unfortunately <code>dict</code> is an unhashable type in Python. Therefore we cannot use <code>set</code>s to get around this, which would run in O(n). More on that approach <a href=\"https://stackoverflow.com/questions/6486450/compute-list-difference\">here</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T10:08:31.280",
"Id": "266546",
"ParentId": "266540",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "266546",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T02:15:44.983",
"Id": "266540",
"Score": "3",
"Tags": [
"python",
"performance",
"python-3.x",
"hash-map"
],
"Title": "Better way of comparing two lists of dictionaries and display unique changes"
}
|
266540
|
<p>(See the <a href="https://codereview.stackexchange.com/questions/266570/a-simple-java-integer-hash-set-follow-up">next version</a>.)</p>
<p>The following data structure implements a hash table based set for <code>int</code> values:</p>
<p><strong><code>com.github.coderodde.util.IntHashSet</code></strong></p>
<pre><code>package com.github.coderodde.util;
/**
* This class implements a simple hash set for non-negative {@code int} values.
* It is used in the {@link com.github.coderodde.util.LinkedList} in order to
* keep track of nodes that are being pointed to by fingers.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Aug 29, 2021)
* @since 1.6 (Aug 29, 2021)
*/
class IntHashSet {
private static final int INITIAL_CAPACITY = 8;
private static final float MAXIMUM_LOAD_FACTOR = 0.75f;
static final class IntHashTableCollisionChainNode {
IntHashTableCollisionChainNode next;
int integer;
IntHashTableCollisionChainNode(
int integer,
IntHashTableCollisionChainNode next) {
this.integer = integer;
this.next = next;
}
@Override
public String toString() {
return "Chain node, integer = " + integer;
}
}
void add(int integer) {
if (contains(integer)) {
return;
}
size++;
if (shouldExpand())
expand();
final int targetCollisionChainIndex = integer & mask;
final IntHashTableCollisionChainNode newNode =
new IntHashTableCollisionChainNode(
integer,
table[targetCollisionChainIndex]);
newNode.next = table[targetCollisionChainIndex];
table[targetCollisionChainIndex] = newNode;
}
boolean contains(int integer) {
final int collisionChainIndex = integer & mask;
IntHashTableCollisionChainNode node = table[collisionChainIndex];
while (node != null) {
if (node.integer == integer) {
return true;
}
node = node.next;
}
return false;
}
void remove(int integer) {
if (!contains(integer)) {
return;
}
size--;
if (shouldContract())
contract();
final int targetCollisionChainIndex = integer & mask;
IntHashTableCollisionChainNode current =
table[targetCollisionChainIndex];
IntHashTableCollisionChainNode previous = null;
while (current != null) {
IntHashTableCollisionChainNode next = current.next;
if (current.integer == integer) {
if (previous == null) {
table[targetCollisionChainIndex] = next;
} else {
previous.next = next;
}
return;
}
previous = current;
current = next;
}
}
public void clear() {
size = 0;
table = new IntHashTableCollisionChainNode[INITIAL_CAPACITY];
mask = table.length - 1;
}
private IntHashTableCollisionChainNode[] table =
new IntHashTableCollisionChainNode[INITIAL_CAPACITY];
private int size = 0;
private int mask = INITIAL_CAPACITY - 1;
// Keep add(int) an amortized O(1)
private boolean shouldExpand() {
return size > table.length * MAXIMUM_LOAD_FACTOR;
}
// Keep remove(int) an amortized O(1)
private boolean shouldContract() {
if (table.length == INITIAL_CAPACITY) {
return false;
}
return MAXIMUM_LOAD_FACTOR * size * 4 < table.length;
}
private void expand() {
IntHashTableCollisionChainNode[] newTable =
new IntHashTableCollisionChainNode[table.length * 2];
rehash(newTable);
table = newTable;
mask = table.length - 1;
}
private void contract() {
IntHashTableCollisionChainNode[] newTable =
new IntHashTableCollisionChainNode[table.length / 4];
rehash(newTable);
table = newTable;
mask = table.length - 1;
}
private void rehash(IntHashTableCollisionChainNode[] newTable) {
for (IntHashTableCollisionChainNode node : table) {
while (node != null) {
final IntHashTableCollisionChainNode next = node.next;
final int rehashedIndex = rehash(node.integer, newTable);
node.next = newTable[rehashedIndex];
newTable[rehashedIndex] = node;
node = next;
}
}
}
private static int rehash(
int integer,
IntHashTableCollisionChainNode[] newTable) {
return integer & (newTable.length - 1);
}
}
</code></pre>
<p><strong><code>com.github.coderodde.util.IntHashSetTest</code></strong></p>
<pre><code>package com.github.coderodde.util;
import java.util.Random;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
public class IntHashSetTest {
private final IntHashSet set = new IntHashSet();
@Before
public void beforeTest() {
set.clear();
}
@Test
public void add() {
for (int i = 0; i < 500; i++) {
set.add(i);
}
for (int i = 0; i < 500; i++) {
assertTrue(set.contains(i));
}
for (int i = 500; i < 1_000; i++) {
assertFalse(set.contains(i));
}
for (int i = 450; i < 550; i++) {
set.remove(i);
}
for (int i = 450; i < 1_000; i++) {
assertFalse(set.contains(i));
}
for (int i = 0; i < 450; i++) {
assertTrue(set.contains(i));
}
}
@Test
public void contains() {
set.add(10);
set.add(20);
set.add(30);
for (int i = 1; i < 40; i++) {
if (i % 10 == 0) {
assertTrue(set.contains(i));
} else {
assertFalse(set.contains(i));
}
}
}
@Test
public void remove() {
set.add(1);
set.add(2);
set.add(3);
set.add(4);
set.add(5);
set.remove(2);
set.remove(4);
set.add(2);
assertFalse(set.contains(4));
assertTrue(set.contains(1));
assertTrue(set.contains(2));
assertTrue(set.contains(3));
assertTrue(set.contains(5));
}
@Test
public void clear() {
for (int i = 0; i < 100; i++) {
set.add(i);
}
for (int i = 0; i < 100; i++) {
assertTrue(set.contains(i));
}
set.clear();
for (int i = 0; i < 100; i++) {
assertFalse(set.contains(i));
}
}
@Test
public void bruteForceAdd() {
long seed = System.currentTimeMillis();
System.out.println(
"--- IntHashSetTest.bruteForceAdd: seed = " + seed + " ---");
Random random = new Random(seed);
int[] data = new int[10_000];
for (int i = 0; i < data.length; i++) {
int datum = random.nextInt(5_000);
data[i] = datum;
set.add(datum);
}
for (int i = 0; i < data.length; i++) {
assertTrue(set.contains(data[i]));
}
}
@Test
public void bruteForceRemove() {
long seed = System.currentTimeMillis();
System.out.println(
"--- IntHashSetTest.bruteForceRemove: seed = " + seed + " ---");
Random random = new Random(seed);
int[] data = new int[10_000];
for (int i = 0; i < data.length; i++) {
int datum = random.nextInt(5_000);
data[i] = datum;
set.add(datum);
}
shuffle(data, random);
for (int i = 0; i < data.length; i++) {
int datum = data[i];
if (set.contains(datum)) {
set.remove(datum);
}
assertFalse(set.contains(datum));
}
}
private static void shuffle(int[] data, Random random) {
for (int i = data.length - 1; i > 0; --i) {
final int j = random.nextInt(i + 1);
swap(data, i, j);
}
}
private static void swap(int[] data, int i, int j) {
int tmp = data[i];
data[i] = data[j];
data[j] = tmp;
}
}
</code></pre>
<h2>Critique request</h2>
<p>Please, tell me anything that comes to mind! ^^</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T10:31:02.483",
"Id": "526610",
"Score": "2",
"body": "Hiding fields between public methods and private methods is really weird to me. Does this follow some specific coding standard? I do get the point of public methods being the interface and thus the most important part, but the interface is documented in the JavaDocs and the source code should try to be as clear as possible instead of trying to disguise the fields (I did spend a while wondering where the mask variable came from as I read the code)."
}
] |
[
{
"body": "<p>Just an unordered list of things that came to my mind:</p>\n<ul>\n<li><p>You have two <code>rehash()</code> methods doing very different things, an <code>int</code>-returning one computing the index for a content integer, and the other <code>void</code> one doing the rehashing process.</p>\n</li>\n<li><p>You have (at least) two places where you compute the array index for a content integer, one being inside the <code>add()</code> method, the other being the <code>int rehash()</code> method.</p>\n</li>\n<li><p>You re-invented the wheel. Functionally, a <code>HashSet<Integer></code> does the job and is well-tested and optimized. Probably, you did your own implementation for efficiency reasons, but I doubt your class outperforms <code>HashSet<Integer></code> regarding execution time or memory footprint. But if you have performance data, I'd be curious to see them.</p>\n</li>\n<li><p>Your "hashing" by using a bit mask can lead to unnecessary collisions in some (quite plausible) use cases.</p>\n</li>\n<li><p>You use a singly-linked list in the buckets. In your test cases for the <code>remove()</code> method, I didn't find explicit ones for the edge cases: removing the first entry and removing the last entry from the list. The random tests might cover that as well with some probability, but "some probability" is a bad idea for testing.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T16:59:30.057",
"Id": "526636",
"Score": "1",
"body": "The JDK builtin `HashSet<Integer>` is actually a rather poorly optimized implementation. Not only does it waste time and memory due to primitive (un)boxing, but it's actually a `HashMap` in disguise and thus also wastes space to store pointers to the unused map values and time to update them. It's also quite prone to collisions, and while it does deal with them decently well (essentially falling back to a `TreeMap`), that in itself adds quite a bit of complexity and performance overhead. Something like [HPPC](https://github.com/carrotsearch/hppc) `IntHashSet` would be a much better comparison."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T11:02:13.370",
"Id": "266549",
"ParentId": "266541",
"Score": "5"
}
},
{
"body": "<h2>Bug: array shrinks too much</h2>\n<p>The logic in <code>shouldContract</code> looks like it is intended to prevent the size from shrinking below <code>INITIAL_CAPACITY</code>, but it doesn't do that. For example, suppose the current table size is 16, then <code>table.length == INITIAL_CAPACITY</code> is false and <code>MAXIMUM_LOAD_FACTOR * size * 4 < table.length</code> can be true, so a resize is performed and the new size is 4. Then <code>table.length == INITIAL_CAPACITY</code> is <em>still false</em>, and <code>MAXIMUM_LOAD_FACTOR * size * 4 < table.length</code> can be true again if more items are removed, and the next size is 1. You can see where this is headed: the next size after this is going to be zero. That then causes the rehash to fail.</p>\n<p>Code to reproduce:</p>\n<pre><code>for (int i = 0; i < 9; i++)\n set.add(i);\nfor (int i = 0; i < 9; i++)\n set.remove(i);\n</code></pre>\n<h2>Access modifiers are inconsistent</h2>\n<p><code>clear</code> is <code>public</code> but the rest of the "public interface" has the default access level, which might be OK but then why is <code>clear</code> public. I recommend picking one of them.</p>\n<h2>Non-negative?</h2>\n<p>The description says that it's a set for non-negative integers, but it seems to do fine with any integer.</p>\n<h2>Weak hash (identity hash)</h2>\n<p>Identity-hashing (ie using the value <em>as</em> the hash, only applying range reduction) for integers mostly works, but can easily cause values to some distribute unevenly across buckets. For example, if all values are even (or all odd) then only half the buckets are used. Or if all values are a multiple of 256, then only 1 in 256 buckets can be used. In many cases that will simply not happen because input is well-distributed, but a set of integers that are a multiple of a power of two is not a rarity. The danger could be mitigated (not removed entirely, but the sets of values that trigger bad behaviour <em>with</em> hashing are quite unusual sets) by applying some "diffusive" bijective transformation to the value before range-reducing it, for example (borrowing the "hash finalizer" from MurmurHash3):</p>\n<pre><code>static int hash(int x) {\n x ^= x >>> 16;\n x *= 0x85ebca6b;\n x ^= x >>> 13;\n x *= 0xc2b2ae35;\n x ^= x >>> 16;\n return x;\n}\n\n// elsewhere in the code ...\nint targetCollisionChainIndex = hash(integer) & mask;\n</code></pre>\n<p>There is a trade-off there of course, that hash isn't free to evaluate.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T11:12:23.833",
"Id": "266550",
"ParentId": "266541",
"Score": "7"
}
},
{
"body": "<ol>\n<li><p><code>IntHashTableCollisionChainNode</code> is already nested within <code>IntHashSet</code>, making the <code>IntHashTable</code> part of its name redundant. Plus the fact that it's part of a "chain" is kind of implied by how it's used, it's not really a property of the class itself.</p>\n<p>Consider perhaps just <code>IntHashSet.Node</code>.</p>\n</li>\n<li><p><code>IntHashTableCollisionChainNode</code> can be <code>private</code></p>\n</li>\n<li><p>You didn't mention which Java version you're using, but if it's higher than 10, you should use <code>var</code> for type inference on local variables. It'll reduce the incidence rate of things like:</p>\n<pre><code>final IntHashTableCollisionChainNode newNode = \n new IntHashTableCollisionChainNode(\n integer, \n table[targetCollisionChainIndex]);\n</code></pre>\n<p>Which can just become:</p>\n<pre><code>final var newNode = new Node(integer, table[targetCollisionChainIndex]);\n</code></pre>\n</li>\n<li><p>Marking local variables in Java is pretty tedious. IMO, it's a lot of noise without much return. Take a look at the keywords used to declare constants vs variables in various langauges:</p>\n<pre class=\"lang-markdown prettyprint-override\"><code> Language | Constant keyword | Mutable keyword\n------------|------------------+-----------------\n Java | final | <blank>\n JavaScript | const | let\n Swift | let | var\n Rust | let | let mut\n</code></pre>\n<p>Notice the big difference: the other languages make it practically just as easy to declare a constant as it is to declare a variable. In Java, it's additive, and really tedious. Given that Java's <code>final</code> also has no bearing on the mutability on the referenced object (it only cares about the immutability of the reference itself), I think it's quite low-value, and not worth the spam to use it on all local variables.</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T11:39:34.273",
"Id": "526678",
"Score": "0",
"body": "Nice one, but I have to disagree on `final`: if nothing else, it documents that a variable/reference is not changed in the current method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T12:15:56.120",
"Id": "526681",
"Score": "0",
"body": "@coderodde I’m aware, but I just don’t think it’s that useful compared to its cost. Particularly when it doesn’t stop you from mutating the referenced object."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T03:44:40.573",
"Id": "266573",
"ParentId": "266541",
"Score": "2"
}
},
{
"body": "<h2>Performance</h2>\n<p>If one considers speed (which seems to be a goal since no safety net is put in place such as <code>HashSet</code> has), I'd say that you're in good spot, but some improvements can be done.</p>\n<ul>\n<li>Checking <code>contains</code> inside of <code>add</code> and <code>removes</code> makes the code loop twice through the nodes when an element is absent. Consider checking later in your <code>add</code> and <code>remove</code> method.</li>\n<li>Consider caching heavily used numbers, such as <code>table.length * MAXIMUM_LOAD_FACTOR</code> (=<code>nextExpandSize</code>?).</li>\n</ul>\n<h2>Readability</h2>\n<p>I have a hard time reading the code. I've read several performance-related code, and they're much more legible.</p>\n<ul>\n<li>Consider renaming <code>IntHashTableCollisionChainNode</code> to just <code>Node</code>. It expresses exactly the same, but is much shorter.</li>\n<li>We're now close to Java 17. Just use <code>var</code> instead of the full type name.</li>\n<li>Remove the <code>final</code> for local variables. There's absolutely zero added value to it in your code, especially since Java now has the concept of effectively final variables.</li>\n<li>Consider merging <code>expand</code> and <code>contract</code> into <code>resize</code> with a parameter: the code is absolutely identical except for the new size.</li>\n<li>OR consider merging <code>shouldExpand</code> and <code>expand</code> together (<code>expandIfNeeded</code>), as well as <code>shouldContract</code> and <code>contract</code> (<code>contractIfNeeded</code>).</li>\n<li>There are magic numbers such as <code>4</code> and <code>2</code>. Express them as constants such as <code>EXPAND_FACTOR</code> and <code>CONTRACT_FACTOR</code>.</li>\n</ul>\n<h2>Testing</h2>\n<ul>\n<li>The <code>bruteForceAdd</code> and <code>bruteForceRemove</code> tests are not reproducible because the seed is the current timestamp. If your implementation is buggy, you might have the same test that sometimes succeeds and sometimes fails. Tests are about reproducibility. So it's better to have a seed that is constant.</li>\n<li>The <code>bruteForceRemove</code> is even more problematic because there is a conditional remove. I would write it like this:</li>\n</ul>\n<pre><code>for (int i = 0; i < 10000; i++) {\n data[i] = i;\n set.add(i);\n}\n\nshuffle(data);\n\nfor (var i : data) {\n assumeTrue(data.contains(i)); // not assert.\n data.remove(i);\n assertFalse(data.contains(i));\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T09:28:14.600",
"Id": "266581",
"ParentId": "266541",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "266550",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T05:22:04.760",
"Id": "266541",
"Score": "6",
"Tags": [
"java",
"unit-testing",
"integer",
"set",
"hashcode"
],
"Title": "A simple Java integer hash set"
}
|
266541
|
<p>I'm new to Python and just started to learn about scraping and pandas library. Here is a little scraper I wrote. I'd like to know what's a professional code for this would look like. I have a sense my code has a lot of redundancy but I don't know where to improve.</p>
<pre><code>import pandas as pd
from bs4 import BeautifulSoup as bs
import requests
url = 'https://vancouver.craigslist.org/d/baby-kid-stuff/search/baa'
html_file = requests.get(url)
soup = bs(html_file.text, 'lxml')
#print(soup.prettify())
postings = soup.find_all('li', class_ = 'result-row')
locations = list()
prices = list()
names = list()
for posting in postings:
location = posting.find('span', class_ = 'result-hood').text
price = posting.find('span', class_ = 'result-price').text
name = posting.find('h3', class_= 'result-heading').text.strip()
locations.append(location)
prices.append(price)
names.append(name)
list_of_tuples = list(zip(locations,prices,names))
df = pd.DataFrame(list_of_tuples, columns= ['locations', 'prices', 'names'])
print(df)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T07:25:03.363",
"Id": "526672",
"Score": "2",
"body": "As a warning, craigslist is incredibly aggressive about blocking scrapers."
}
] |
[
{
"body": "<ul>\n<li>Don't hard-code your URL - slice it up into parameters accepted by a function</li>\n<li>Omit the friendly <code>baby-kid-stuff</code>. There is a corresponding product category code, <code>baa</code>, that is more important to the requests and less redundant.</li>\n<li>Pass a <a href=\"https://www.crummy.com/software/BeautifulSoup/bs4/doc/#parsing-only-part-of-a-document\" rel=\"nofollow noreferrer\"><code>parse_only</code></a> strainer to <code>BeautifulSoup</code>.</li>\n<li>Move your code out of the global namespace.</li>\n<li>Why are you using Pandas? Currently it seems to be just for printing; so don't use it at all; don't flatten your data. Keep it in well-typed structures.</li>\n<li>Consider supporting sortation criteria, a query string, an enumeration for known product codes, a "sub-area" code (e.g. <code>rch</code> for Richmond), parametric category codes, and including the item URL and timestamp in your results.</li>\n<li>Use a session to preserve cross-request cookies and set common headers.</li>\n<li>Set semi-realistic browser-like request headers and cookies.</li>\n<li>Use the response in a <code>with</code>, and check for failures via <a href=\"https://docs.python-requests.org/en/master/api/#requests.Response.raise_for_status\" rel=\"nofollow noreferrer\"><code>raise_for_status</code></a>.</li>\n<li>Do not leave your price as a string; make a <a href=\"https://docs.python.org/3/library/decimal.html#decimal.Decimal\" rel=\"nofollow noreferrer\"><code>Decimal</code></a>.</li>\n</ul>\n<h2>Suggested</h2>\n<pre class=\"lang-py prettyprint-override\"><code>from dataclasses import dataclass\nfrom datetime import datetime\nfrom decimal import Decimal\nfrom enum import Enum\nfrom typing import Optional, Iterable\n\nfrom bs4 import SoupStrainer, BeautifulSoup\nfrom requests import Session\n\n\nclass Sort(Enum):\n TIME_DESC = 'date'\n PRICE_ASC = 'priceasc'\n PRICE_DESC = 'pricedesc'\n RELEVANT_DESC = 'rel'\n\n\nclass Category(Enum):\n ALL_FOR_SALE = 'sss'\n FURNITURE = 'fua'\n HOUSEHOLD = 'hsa'\n GENERAL = 'foa'\n BABY_KIDS = 'baa'\n HEALTH_BEAUTY = 'haa'\n # etc.\n\n\nRESULT_STRAIN = SoupStrainer('li', class_='result-row')\n\n\ndef search(\n session: Session,\n area: str,\n sub_area: Optional[str] = None,\n category: Category = Category.ALL_FOR_SALE,\n sort: Sort = Sort.TIME_DESC,\n query: Optional[str] = None,\n) -> str:\n url = f'https://{area}.craigslist.org/search'\n if sub_area is not None:\n url += f'/{sub_area}'\n url += f'/{category.value}'\n\n params = {'sort': sort.value}\n if query is not None:\n params['query'] = query\n\n thumb_list = f'{Category.ALL_FOR_SALE.value}:pic'\n\n with session.get(\n url,\n params=params,\n cookies={\n 'cl_def_hp': area,\n 'cl_tocmode': thumb_list,\n },\n headers = {\n 'Referer': f'https://{area}.craigslist.org/',\n },\n ) as resp:\n resp.raise_for_status()\n return resp.text\n\n\n@dataclass(frozen=True)\nclass Result:\n url: str\n when: datetime\n title: str\n neighbourhood: str\n price: Decimal\n\n @classmethod\n def parse(cls, html: str) -> Iterable['Result']:\n doc = BeautifulSoup(html, features='lxml', parse_only=RESULT_STRAIN)\n for item in doc.find_all('li', recursive=False):\n anchor = item.select_one('a.result-title')\n yield cls(\n url=anchor['href'],\n when=datetime.strptime(item.time['datetime'], '%Y-%m-%d %H:%M'),\n title=anchor.text,\n neighbourhood=item.select_one('span.result-hood').text,\n price=Decimal(item.select_one('span.result-price').text.removeprefix('$')),\n )\n\n def __str__(self):\n return self.title\n\n def print(self) -> None:\n print(\n f'{self.title}'\n f'\\n{self.url}'\n f'\\n{self.neighbourhood}'\n f'\\n${self.price}'\n f'\\n{self.when.strftime("%c")}'\n f'\\n'\n )\n\n\ndef main():\n with Session() as session:\n session.headers = {\n 'User-Agent':\n 'Mozilla/5.0 (X11; Linux x86_64; rv:91.0) '\n 'Gecko/20100101 '\n 'Firefox/91.0',\n 'Accept': 'text/html,application/xhtml+xml'\n }\n\n for item in Result.parse(search(\n session, area='vancouver', category=Category.BABY_KIDS,\n )):\n item.print()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<h2>Output</h2>\n<pre><code>Like new pricess pinky rain boots with lining size: 2\nhttps://vancouver.craigslist.org/bnc/bab/d/new-westminster-southwest-like-new/7363474417.html\n (New Westminster burnaby/newwest )\n$20\nThu Sep 2 11:06:00 2021\n\n# etc.\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-21T07:57:29.213",
"Id": "533605",
"Score": "0",
"body": "Thank you for your time sir"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T18:35:11.233",
"Id": "267636",
"ParentId": "266544",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "267636",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T09:24:15.943",
"Id": "266544",
"Score": "1",
"Tags": [
"python",
"beginner",
"web-scraping",
"pandas"
],
"Title": "Scrape from Craigslist"
}
|
266544
|
<p>In python, I sometimes write a while statement like</p>
<pre class="lang-py prettyprint-override"><code>i = 0
while <condition that involves i>:
i += 1
</code></pre>
<p>The goal is, of course, to check the number of time the condition is true.
I was wondering if there's a more simple, pythonic way to do it ? something like <code>i = while <condition that involves i></code>, maybe with the walrus operator ?</p>
<p>Here's a more concrete example:</p>
<pre class="lang-py prettyprint-override"><code>def get_word_num_with_character_index(string: str, index: int) -> int:
"""
returns the number of the word containing a character, specified by an index
:param string: the string to analyze
:param index: the index of the character
:return: the number of the word containing the specified character
"""
split_string = string.split(" ")
i = 0
while len(" ".join(split_string[:i])) <= index:
i += 1
return i - 1
print(get_word_num_with_character_index("jean de la fontaine", 8))
# prints 2, the index of the word containing the 8th character
</code></pre>
<p>How to simplify it ?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T11:07:59.620",
"Id": "526611",
"Score": "0",
"body": "You *can* use the walrus operator here, but I don't think you should: `i = -1`, `while len(\" \".join(split_string[:(i := i + 1)])) <= index: pass`. It's neither simpler nor clearer, it just moves even more logic into the condition without saving a line."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T11:09:07.393",
"Id": "526612",
"Score": "0",
"body": "Just to confirm, you're not looking into using enumerate (returns a counter as part of a `for` loop) or using slicing, such as `\"jean de la fontaine\"[8]` - correct?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T11:34:35.853",
"Id": "526613",
"Score": "0",
"body": "thanks @riskypenguin, but as you pointed out, it only makes the code more complex, so it's not really what I'm looking for. I was just mentioning the walrus operator as a possible idea"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T11:44:42.330",
"Id": "526614",
"Score": "0",
"body": "@C.Harley no, this is just an exemple but i'm trying to get the value of `i` in only one line, using the given condition, in order to get the number of the word in the string where the specified letter is (here, ̀\"jean de la fontaine\"[8]`). Sorry, I know it's not very clear but I don't see how I can explain the function more clearly than in its docstring"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T11:55:21.777",
"Id": "526615",
"Score": "1",
"body": "`sum(1 for _ in itertools.takewhile(lambda i: PREDICATE, itertools.count()))`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T17:49:22.427",
"Id": "526642",
"Score": "0",
"body": "What about `return string[:index+1].count(\" \")` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T18:21:21.163",
"Id": "526643",
"Score": "0",
"body": "thanks @SylvainD , but this is an example, and I'm looking for a global solution"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T19:53:24.117",
"Id": "526652",
"Score": "0",
"body": "To be honest, I have the feeling that it works pretty well. I'd be interested in cases that are not handled properly."
}
] |
[
{
"body": "<p>You <em>could</em> replace your</p>\n<pre><code> i = 0\n while len(" ".join(split_string[:i])) <= index:\n i += 1\n</code></pre>\n<p>with the oneliner using <a href=\"https://docs.python.org/3/library/itertools.html#itertools.count\" rel=\"noreferrer\"><code>itertools.count</code></a></p>\n<pre><code> i = next(i for i in count() if len(" ".join(split_string[:i])) > index)\n</code></pre>\n<p>or more readably spread over two physical lines (still just one <a href=\"https://docs.python.org/3/reference/lexical_analysis.html#logical-lines\" rel=\"noreferrer\">logical line</a>:</p>\n<pre><code> i = next(i for i in count()\n if len(" ".join(split_string[:i])) > index)\n</code></pre>\n<p>Both have advantages. The <code>while</code> solution has less clutter, the <code>next</code> solution makes it clearer that the whole point of the snippet is to compute <code>i</code>.</p>\n<p>If you already have a function for the condition, a good alternative would be <a href=\"https://docs.python.org/3/library/itertools.html#itertools.dropwhile\" rel=\"noreferrer\"><code>itertools.dropwhile</code></a>:</p>\n<pre><code> def condition(i):\n return len(" ".join(split_string[:i])) <= index\n\n i = next(dropwhile(condition, count()))\n</code></pre>\n<p>As a oneliner, just to see how long/ugly it is in this case:</p>\n<pre><code> i = next(dropwhile(lambda i: len(" ".join(split_string[:i])) <= index, count()))\n</code></pre>\n<p>So I'd likely really only use it if I had it as a function already.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T13:00:39.833",
"Id": "526619",
"Score": "0",
"body": "Thanks a lot! `itertools.count()` is what I needed right now, but I keep `dropwhile()` in mind, it is also very relevant.\nI'm always open to other ideas.\nBut the word \"could\" in your message suggests that this is not a good idea. It's true that it's not very clear. So you recommend not to use it, but to leave the \"while\" as it is?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T13:05:29.020",
"Id": "526620",
"Score": "0",
"body": "I meant that as there's nothing wrong with the while loop. In this particular case, I'm undecided which I prefer, while or next. So you *could* switch, but you really don't have to."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T13:09:20.023",
"Id": "526621",
"Score": "0",
"body": "Ok, I will keep this in mind, thank you !"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T13:12:14.153",
"Id": "526622",
"Score": "2",
"body": "Put differently: Many Python beginners will write or see `while` loops and see experienced coders point out that they're horrible and that it should be done differently, and misunderstand that as \"while loops are *always* horrible\" rather than the meant \"this particular while loop is horrible\". Similar to the misconception \"to be pythonic, I must write this code as a oneliner\" :-)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T12:30:25.130",
"Id": "266552",
"ParentId": "266548",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "266552",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T10:31:59.630",
"Id": "266548",
"Score": "2",
"Tags": [
"python"
],
"Title": "Counting how many times a condition is met in Python"
}
|
266548
|
<p>Here's a function <code>save_document()</code>, <strong>that polls the pressing of a <code>Extract PDF</code> button in an external program</strong> and saves a tmp PDF file in a USB drive.</p>
<pre><code>import time
import os
import shutil
def save_document():
print("\n\nPreparing to save the document...", end = "\r")
TEMP_PDF_DIR = "C:/Users/TUN/tp3/workspace/tmp" # temporary pdfs are stored in this directory
while not os.listdir(TEMP_PDF_DIR): # wait until the "Extract PDF" button is pressed and a file will be created in directory TEMP_PDF_DIR
time.sleep(0.5)
continue
file_path = "C:/Users/TUN/tp3/workspace/tmp" + "/" + os.listdir(TEMP_PDF_DIR)[0]
shutil.move(file_path, find_drive_id()) # move the file in the USB drive directory
print("Document PDF was saved successfully.")
</code></pre>
<p>And the <code>find_drive()</code> function, which looks for a storage device with a given <strong>serial number</strong> and returns its path (path letter like D:, F:, etc.)</p>
<pre><code>import wmi
def find_drive_id():
local_machine_connection = wmi.WMI()
DRIVE_SERIAL_NUMBER = "88809AB5" # serial number is like an identifier for a storage device determined by system
'''.Win32.LogicalDisk returns list of wmi_object objects, which include information
about all storage devices and discs (C:, D:)'''
for storage_device in local_machine_connection.Win32_LogicalDisk():
if storage_device.VolumeSerialNumber == DRIVE_SERIAL_NUMBER:
return storage_device.DeviceID
return False
</code></pre>
<p>Is there a better way to save a just created temporary PDF file?</p>
<p>Also, the polling loop is bothering me...I believe, there's a more elegant approach.</p>
|
[] |
[
{
"body": "<h1>General comments</h1>\n<p>Personally the polling seems fine, a standard way of doing this is using <a href=\"https://pypi.org/project/watchdog/\" rel=\"nofollow noreferrer\"><code>watchdog</code></a>. I'll just point out some bits and bobs I find odd about your code.</p>\n<hr />\n<p><strong><code>imports</code></strong></p>\n<p>A common way in Python is to split your imports into three sections: builtin modules, community modules and local. So this</p>\n<pre><code>import time\n\nimport os\nimport shutil\n</code></pre>\n<p>Should really be this</p>\n<pre><code>import time\nimport os\nimport shutil\n</code></pre>\n<p>Because <code>time</code>, <code>os</code> and <code>shutil</code> all live in the <a href=\"https://docs.python.org/3/library/\" rel=\"nofollow noreferrer\">standard library</a>.</p>\n<hr />\n<p><strong><code>descriptive function names</code></strong></p>\n<p>Naming this is hard, but it is very important to think carefully about what you name things; especially functions, classes and modules. The main reason why</p>\n<p><code>save_document()</code>: and <code>find_drive_id()</code></p>\n<p>Are bad names is because they do not do what they say they do. Save document does not save a document, it moves an <em>already saved</em> document to a different folder. Similarly <code>find_drive_id</code> does not find a drive ID but returns the path to a drive.</p>\n<hr />\n<p><strong><code>hardcoded paths</code></strong></p>\n<p>This is a 2 for 1 deal. First paths are better handled using the <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"nofollow noreferrer\"><strong><code>pathlib</code></strong></a> module (again in the standard library). In addition we are using this path multiple times, so it ought to be extracted into it's own global constant</p>\n<pre><code>import pathlib\n\nDIRECTORY_TO_WATCH = pathlib.PureWindowsPath("c:/Users/TUN/tp3/workspace/tmp")\n</code></pre>\n<p>Similarly <code>DRIVE_SERIAL_NUMBER = "88809AB5"</code> should probably be a global constant as well.</p>\n<hr />\n<p><a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\"><strong><code>docstrings</code></strong></a></p>\n<p>Triple quotes are usually reserved for <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstrings</a>. In addition this</p>\n<pre><code>'''.Win32.LogicalDisk returns list of wmi_object objects, which include information\nabout all storage devices and discs (C:, D:)'''\n</code></pre>\n<p>is more of a comment than a quote, and can be converted to <code>#</code>. In addition you should add docstrings explaining what each function does.</p>\n<hr />\n<p><a href=\"https://stackoverflow.com/questions/9979970/why-does-python-use-else-after-for-and-while-loops\"><strong><code>for else</code></strong></a></p>\n<p>This is really nitpicky, but we can write</p>\n<pre><code>for storage_device in local_machine_connection.Win32_LogicalDisk():\n if storage_device.VolumeSerialNumber == DRIVE_SERIAL_NUMBER:\n return storage_device.DeviceID\nelse:\n return False\n</code></pre>\n<p>Which I find clearer to read. If we do not break or return in the <code>for loop</code> the <code>else</code> clause is triggered. You can also think of the <code>else</code> as <code>then</code>.</p>\n<hr />\n<p><a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><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/questions/419163/what-does-if-name-main-do\"><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<h1>Example code</h1>\n<p>Here is a mock-up of how a watchdog implementation <code>could</code> look. Note that I am on Linux and have no chance to check the details if everything is implemented correctly. However, it ought to be a good starting point =)</p>\n<pre><code>import time\nimport pathlib\nimport shutil\n\nimport wmi\nfrom watchdog.observers import Observer\nfrom watchdog.events import FileSystemEventHandler\n\nDIRECTORY_TO_WATCH = pathlib.PureWindowsPath("c:/Users/TUN/tp3/workspace/tmp")\n# serial number is like an identifier for a storage device determined by system\nDRIVE_SERIAL_NUMBER = "88809AB5"\nSLEEP_TIME = 5\n\n\nclass Watcher:\n DIRECTORY_TO_WATCH = DIRECTORY_TO_WATCH\n SLEEP_TIME = SLEEP_TIME\n\n def __init__(self):\n self.observer = Observer()\n\n def run(self):\n event_handler = Handler()\n self.observer.schedule(event_handler, self.DIRECTORY_TO_WATCH, recursive=True)\n self.observer.start()\n try:\n while True:\n time.sleep(self.SLEEP_TIME)\n except:\n self.observer.stop()\n print("Error")\n\n self.observer.join()\n\n\nclass Handler(FileSystemEventHandler):\n @staticmethod\n def on_any_event(event):\n if event.is_directory:\n return None\n\n elif event.event_type == "created":\n # Take any action here when a file is first created.\n # move the file in the USB drive directory\n file_path = pathlib.PureWindowsPath(event.src_path)\n shutil.move(file_path, get_usb_path())\n print("Document PDF was saved successfully.")\n\n\ndef get_usb_path():\n local_machine_connection = wmi.WMI()\n # Win32.LogicalDisk returns list of wmi_object objects, which include\n # information about all storage devices and discs (C:, D:)\n for storage_device in local_machine_connection.Win32_LogicalDisk():\n if storage_device.VolumeSerialNumber == DRIVE_SERIAL_NUMBER:\n return storage_device.DeviceID\n else:\n return False\n\n\nif __name__ == "__main__":\n w = Watcher()\n w.run()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T19:30:30.903",
"Id": "266562",
"ParentId": "266553",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T13:01:56.390",
"Id": "266553",
"Score": "4",
"Tags": [
"python",
"python-3.x"
],
"Title": "Save temporary PDF files in a USB flash from an external app"
}
|
266553
|
<p>I am looking for some feedback on my implementation of binary search tree in rust and I would appreciate someone taking the time to go through it and suggest any improvements or corrections as they see fit. More specifically I am concerned about if I should have <code>Clone</code> derives in the <code>BST</code> and <code>Node</code> structs since I am not using them here.</p>
<pre class="lang-rust prettyprint-override"><code>#![allow(unused)]
use std::fmt::Debug;
fn main() {
let mut bst = BST::new(3_i32);
bst.append(4);
bst.append(1);
bst.append(12);
bst.display();
}
#[derive(Debug)]
pub struct BST<T> {
root: Box<Node<T>>,
}
#[derive(Clone, Debug)]
pub struct Node<T> {
val: T,
left: Option<Box<Node<T>>>,
right: Option<Box<Node<T>>>,
}
impl<T> BST<T>
where
T: PartialOrd + Debug + Clone,
{
pub fn new(val: T) -> Self {
let root = Box::new(Node {
val,
left: None,
right: None,
});
Self { root }
}
pub fn append(&mut self, new_val: T) {
let new_node = Box::new(Node {
val: new_val,
left: None,
right: None,
});
Self::push_node(new_node, &mut self.root);
}
// Private and recursive method
// recursively search through every node until the value is inserted
fn push_node(new_node: Box<Node<T>>, current_node: &mut Box<Node<T>>) {
let ref new_val = new_node.val;
let ref current_val = current_node.val;
if *current_val <= *new_val {
if let Some(ref mut left) = current_node.left {
Self::push_node(new_node, left);
} else {
current_node.left = Some(new_node);
}
} else if *current_val > *new_val {
if let Some(ref mut right) = current_node.right {
Self::push_node(new_node, right);
} else {
current_node.right = Some(new_node);
}
}
}
fn display(&self) {
println!("{:#?}", self);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>This looks good for a first project. Most of the review to follow ranges from debatable to nitpicky.</p>\n<h3>Representation</h3>\n<p>It's unusual that <code>BST</code> can't represent an empty tree because it always has at least one <code>Node</code> in it. Most data structures have no problem representing emptiness. You use <code>Option<_></code> inside <code>Node</code>; there's no apparent reason not to use it in <code>BST</code> as well. Doing this also lets you simplify <code>push_node</code> by making the non-recursive case – an empty <code>Option</code> – the same between left and right trees.</p>\n<p>If you have not already, please read <a href=\"https://rust-unofficial.github.io/too-many-lists/index.html\" rel=\"nofollow noreferrer\">Learning Rust With Entirely Too Many Linked Lists</a>. This short book will cover a lot of mistakes you may make or have already made when trying to create data structures in Rust.</p>\n<h3>Traits</h3>\n<p>What traits to implement is really up to you. That said, it's a good idea to implement <code>Clone</code>, <code>Debug</code> and <code>Default</code> for almost all types. <code>Clone</code> and <code>Debug</code> can be <code>#[derive]</code>d; <code>Default</code> needs its own <code>impl</code> because <a href=\"https://github.com/rust-lang/rust/issues/26925\" rel=\"nofollow noreferrer\">the derived bounds on <code>T</code> are too conservative</a>.</p>\n<p><code>Eq</code>, <code>Hash</code>, <code>Ord</code>, <code>PartialEq</code>, and <code>PartialOrd</code> also seem to make sense here and all can be <code>#[derive]</code>d.</p>\n<p>For a challenge, implement <code>FromIterator</code> and <code>IntoIterator</code>, which are as close as Rust has to a "collections" API. Again, the too-many-lists book will help you here.</p>\n<h3>Construction</h3>\n<p>By convention (<a href=\"https://rust-lang.github.io/api-guidelines/interoperability.html#types-eagerly-implement-common-traits-c-common-traits\" rel=\"nofollow noreferrer\">C-COMMON-TRAITS</a>), <code>new</code> (if it exists) should usually take no arguments and do the same thing as the <code>Default</code> trait (if implemented). If you implement <code>Default</code> on <code>BST</code>, you can write <code>new</code> by just calling <code>Default::default()</code>. Additional constructors should be named descriptively: a constructor that creates a BST with one element might be called <code>from_value</code>.</p>\n<h3><code>impl</code> bounds</h3>\n<p>In general, only write bounds for the functions where they are used. <code>new</code> and <code>append</code> clearly don't need <code>T: Debug</code> and none of them need <code>T: Clone</code>. You can either put the specific bounds on the functions themselves, or split the functions among <code>impl</code> blocks with different bounds.</p>\n<h3><code>PartialOrd</code> vs. <code>Ord</code></h3>\n<p>Partial ordering is not a strong enough guarantee for a binary search tree: if items cannot be ordered relative to each other, they can't be reliably inserted or retrieved from the tree. Therefore the traversal algorithms should require <code>T: Ord</code>, not <code>T: PartialOrd</code>.</p>\n<h3><code>append</code></h3>\n<p>In Rust, <code>append</code> usually means a method of the signature <code>fn(&mut self, other: &mut Self)</code>; that is, one that cannibalizes another data structure of the same type. (As far as I know, this meaning is unique to Rust.) The function you call <code>append</code> would probably be called <code>insert</code> (as in <code>HashSet</code>, for example). There's also an <code>Extend</code> trait that you might implement in any of several ways; see the <a href=\"https://doc.rust-lang.org/std/iter/trait.Extend.html\" rel=\"nofollow noreferrer\">standard library</a> for examples.</p>\n<h3><code>ref</code> patterns</h3>\n<p>You use a number of <code>ref</code> patterns that are not really necessary. Some people dislike all <code>ref</code> patterns. I don't personally have an issue with them in an <code>if let</code> or <code>match</code>, even though they technically aren't needed due to the questionably named "pattern ergonomics" feature (you can use <code>if let Some(f) = &mut foo</code> instead of <code>if let Some(ref mut f) = foo</code>; the <code>Some</code> becomes transparent). However, I recommend against using <code>ref</code> in a trivial case like <code>let new_val = &new_node.val</code>.</p>\n<h3><code>if let</code> and <code>match</code></h3>\n<p>If you have an <code>if let</code> with an <code>else</code> clause, consider turning it into a <code>match</code>, especially if one or both branches are short.</p>\n<h3><code>std::cmp::Ordering</code></h3>\n<p>Instead of an <code>if</code> chain where you test separately <code>a <= b</code> and <code>a > b</code>, call <code>a.cmp(&b)</code> (or <code>T::cmp(&a, &b)</code>) and <code>match</code> on the <a href=\"https://doc.rust-lang.org/stable/std/cmp/enum.Ordering.html\" rel=\"nofollow noreferrer\"><code>Ordering</code></a>. This reduces the chance of accidentally writing a comparison backwards or forgetting a case. Note also that in the original version of <code>push_node</code>, if the values were incomparable, the <code>new_node</code> would have been simply lost. Using <code>Ord</code> instead of <code>PartialOrd</code> means this is not possible.</p>\n<h3><code>BST</code></h3>\n<p>Conventional capitalization is <code>Bst</code> (<a href=\"https://rust-lang.github.io/api-guidelines/naming.html\" rel=\"nofollow noreferrer\">C-CASE</a>).</p>\n<h3><code>display</code></h3>\n<p>This method is not useful. Besides having a misleading name (since it uses the <code>Debug</code> trait, not <code>Display</code>), it's both less obvious in its function and less flexible than simply writing <code>println!("{:#?}", bst)</code> (or even shorter: <code>dbg!(bst)</code>). There's no particular reason to have a dedicated method for it.</p>\n<p>If you mean to have a text representation of a tree for display purposes, but not necessarily the same as the <code>Debug</code> implementation, that's precisely what the <code>Display</code> trait is for. Implementing <code>Display</code> will make <code>Bst</code> work in any formatting macro (<code>format!</code>, <code>write!</code>, etc.), and gives some other conveniences like <code>.to_string()</code>.</p>\n<h3><code>pub struct Node<T></code></h3>\n<p>There is probably not a good reason for <code>Node</code> to be <code>pub</code>. It is dubious for external code to be mucking about with "raw" nodes. If you intend to provide an API that allows back-and-forth traversal, or insertion-at-a-point, consider using a new struct (a cursor) for that so that you can more easily make changes to the internal <code>Node</code> type without changing the API.</p>\n<h3>Whitespace</h3>\n<p>It looks like you're using <code>rustfmt</code>, which is great. Also consider putting empty lines between items (functions, structs, <code>impl</code> blocks) to create whitespace around the important program elements and make the code more pleasant to read, in the same way that paragraphs and section headings have whitespace around them in written text.</p>\n<h3><code>#[allow(unused)]</code></h3>\n<p><code>allow(unused)</code> might be OK when prototyping so that you don't lose track of important warnings among the trivial ones. But once you have something that is relatively complete, you should not continue to hide unused code warnings: those are bugs waiting to happen.</p>\n<p>Even while prototyping, I recommend using <code>allow(dead_code)</code> (which just allows unused non-<code>pub</code> items) instead of the more general <code>allow(unused)</code>, which hides a lot more warnings, many of which are helpful at any stage of development.</p>\n<h2><a href=\"https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=a99c0d96abb664b4be044c259bddaa3f\" rel=\"nofollow noreferrer\">Code with all suggested changes</a></h2>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-10T11:39:22.587",
"Id": "528192",
"Score": "0",
"body": "Thanks for the valuable feedback. I'll keep these tips in mind."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-08T18:49:46.617",
"Id": "267802",
"ParentId": "266554",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "267802",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T13:38:40.967",
"Id": "266554",
"Score": "5",
"Tags": [
"rust",
"binary-search-tree"
],
"Title": "BST implementation in rust"
}
|
266554
|
<p>This is my first big project that I started after completing the Pygame Shmup guide put together by KidsCanCode. I'm starting to feel like it's very close to being finished so wanted to post my code here to find out what could be improved or what isn't up to standard.
Brownie points for whoever can figure out why the alien animation bugs after reinforcements are generated!</p>
<p>Any comments and/or feedback would be greatly appreciated :)</p>
<p>Github link: <a href="https://github.com/Dreadnought88111/Space-WIP" rel="nofollow noreferrer">https://github.com/Dreadnought88111/Space-WIP</a></p>
<pre><code># Space WIP
# By Elias
# things to implement
# boss introduction cinematic
# announ. boss sound
# victory sound
# have aliens jump down vertically rather than diagonally
# known issues:
# aliens speed up when reinforcements are being dropped
# boss and bossvessel rect can be coliided with in level 1 despite them not being generated yet
# temporary fix introduced in the check collisions function not checking collision until level > 9
import math
import pygame
import random
import sys
from os import path
pygame.init()
pygame.mixer.init()
# asset folders
FONT_DIR = path.join(path.dirname(__file__), "fonts")
IMAGE_DIR = path.join(path.dirname(__file__), "images")
SOUND_DIR = path.join(path.dirname(__file__), "sounds")
# screen
WIDTH = 800
HEIGHT = 600
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('Space WIP')
pygame.display.set_icon(pygame.image.load(path.join(IMAGE_DIR, "logo.png")).convert_alpha())
FPS = 60
# colours
BLACK = (0, 0, 0)
BLUE = (0, 255, 240)
GREEN = (0, 255, 0)
ORANGE = (255, 173, 0)
PURPLE = (255, 0, 255)
RED = (255, 0, 0)
WHITE = (255, 255, 255)
# fonts
FONT = path.join(FONT_DIR, '8-BitMadness.ttf')
LOGOFONT = path.join(FONT_DIR, "edunline.ttf")
STARTFONT = path.join(FONT_DIR, "upheavtt.ttf")
# images
alien2_1 = pygame.image.load(path.join(IMAGE_DIR, "enemy2_1.png")).convert_alpha()
alien2_2 = pygame.image.load(path.join(IMAGE_DIR, "enemy2_2.png")).convert_alpha()
alien_images = [pygame.transform.scale(alien2_1, (40, 35)), pygame.transform.scale(alien2_2, (40, 35))]
alien3_1 = pygame.image.load(path.join(IMAGE_DIR, "enemy3_1.png")).convert_alpha()
alien3_2 = pygame.image.load(path.join(IMAGE_DIR, "enemy3_2.png")).convert_alpha()
alien_backup_images = [pygame.transform.scale(alien3_1, (40, 35)), pygame.transform.scale(alien3_2, (40, 35))]
alien1_1 = pygame.image.load(path.join(IMAGE_DIR, "enemy1_1.png")).convert_alpha()
alien1_2 = pygame.image.load(path.join(IMAGE_DIR, "enemy1_2.png")).convert_alpha()
alien_elite_images = [pygame.transform.scale(alien1_1, (40, 35)), pygame.transform.scale(alien1_2, (40, 35))]
# music
MUSICVOLUME = 0.5
BACKGROUND1 = path.join(SOUND_DIR, 'Background1.ogg')
BACKGROUND2 = path.join(SOUND_DIR, 'Background2.ogg')
# sounds
SOUNDVOLUME = 0.2
ALIENAPPEAR = pygame.mixer.Sound(path.join(SOUND_DIR, 'AlienAppear.wav'))
ALIENAPPEAR.set_volume(SOUNDVOLUME)
ALIENEXPLOSIONSOUND = pygame.mixer.Sound(path.join(SOUND_DIR, 'AlienExplosion.wav'))
ALIENEXPLOSIONSOUND.set_volume(SOUNDVOLUME)
ALIENMOVESOUND = pygame.mixer.Sound(path.join(SOUND_DIR, 'AlienMove.wav'))
ALIENMOVESOUND.set_volume(SOUNDVOLUME)
GAMEOVER = pygame.mixer.Sound(path.join(SOUND_DIR, 'GameOver.wav'))
GAMEOVER.set_volume(MUSICVOLUME) # not an error
LASERSOUND = pygame.mixer.Sound(path.join(SOUND_DIR, 'Laser.wav'))
LASERSOUND.set_volume(SOUNDVOLUME)
MYSTERYEXPLOSION = pygame.mixer.Sound(path.join(SOUND_DIR, 'MysteryExplosion.wav'))
MYSTERYEXPLOSION.set_volume(SOUNDVOLUME)
PLAYERHIT = pygame.mixer.Sound(path.join(SOUND_DIR, 'PlayerHit.wav'))
PLAYERHIT.set_volume(SOUNDVOLUME)
POWERUPGENERATED = pygame.mixer.Sound(path.join(SOUND_DIR, 'PowerupGenerated.wav'))
POWERUPGENERATED.set_volume(SOUNDVOLUME)
POWERUPPICKEDUP = pygame.mixer.Sound(path.join(SOUND_DIR, 'PowerupPickedUp.wav'))
POWERUPPICKEDUP.set_volume(SOUNDVOLUME)
SATELLITEANNOUNCE = pygame.mixer.Sound(path.join(SOUND_DIR, 'Satelliteannounce.wav'))
SATELLITEANNOUNCE.set_volume(SOUNDVOLUME)
SATELLITEEXPLOSION = pygame.mixer.Sound(path.join(SOUND_DIR, 'SatelliteExplosion.wav'))
SATELLITEEXPLOSION.set_volume(SOUNDVOLUME)
# sprite groups
alien_group = pygame.sprite.Group()
alien_backup_group = pygame.sprite.Group()
alien_elite_group = pygame.sprite.Group()
alien_master_group = pygame.sprite.Group()
alien_reinforcements_group = pygame.sprite.Group()
alien_laser_group = pygame.sprite.Group()
barrier_master_group = pygame.sprite.Group()
boss_group = pygame.sprite.Group()
bossvessel_group = pygame.sprite.Group()
bossvessel_laser_group = pygame.sprite.Group()
explosion_group = pygame.sprite.Group()
laser_group = pygame.sprite.Group()
mystery_group = pygame.sprite.Group()
player_group = pygame.sprite.Group()
powerup_group = pygame.sprite.Group()
satellite_group = pygame.sprite.Group()
star_group = pygame.sprite.Group()
# miscellaneous
should_aliens_drop = False
should_aliens_move = False
ALIENBACKUPSCORE = 20
ALIENDROP = 20
ALIENELITESCORE = 30
ALIENSCORE = 10
ALIENSPEED = 10
ALIENSTARTYPOS = 65
BOSSVESSELDISTANCE = 90
BOSSVESSELMAXHEALTH = 100
LASERSPEED = 5
MYSTERYSCORE = 100
MYSTERYSPEED = 5
MYSTERYTIME = 10
MYSTERYXPOS = -75
PLAYERSPEED = 7
POWERUPSPEED = 2
SATELLITESPEED = -5
SATELLITETIME = 3
SATELLITEXPOS = WIDTH + 31
STARSPEED = 1
time_last_hit = 0
class Player(pygame.sprite.Sprite):
# the text in between brackets above ensure my class Player inherits from
# the pygame Sprite class
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(path.join(IMAGE_DIR, "ship.png")).convert()
self.image = pygame.transform.scale(self.image, (45, 45))
self.rect = self.image.get_rect(topleft=(300, 540))
self.speed = PLAYERSPEED
self.lives = 5
self.score = 0
self.last_shot = pygame.time.get_ticks() / 1000
self.cool_down = 0.5
self.radius = 21
self.double_shot = False
def update(self, keys):
if keys[pygame.K_LEFT] and self.rect.left >= 0:
self.rect.x -= self.speed
if keys[pygame.K_RIGHT] and self.rect.right <= WIDTH:
self.rect.x += self.speed
class Alien(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.index = 0
self.image = alien_images[self.index]
self.rect = self.image.get_rect()
self.alien_last_moved = 0
self.speed = ALIENSPEED
def update(self, now):
global should_aliens_drop
global should_aliens_move
if now - self.alien_last_moved >= 0.5:
self.alien_last_moved = now
if self.rect.right + self.speed >= (WIDTH - 10) or self.rect.left + self.speed <= 10:
should_aliens_drop = True
else:
should_aliens_move = True
class AlienBackup(Alien):
def __init__(self):
super().__init__()
self.image = alien_backup_images[Alien().index]
class AlienElite(Alien):
def __init__(self):
super().__init__()
self.image = alien_elite_images[Alien().index]
class Barrier(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((5, 5))
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
def update(self, keys, *args):
pass
class Boss(Alien):
def __init__(self):
super().__init__()
self.index = 0
self.image = alien_images[self.index]
self.rect = self.image.get_rect()
self.alien_last_moved = 0
self.speed = ALIENSPEED
def update(self, now, *args):
global should_aliens_drop
global should_aliens_move
if now - self.alien_last_moved >= 0.5:
self.alien_last_moved = now
if self.rect.right + (bossvessel.width / 2) + self.speed >= (WIDTH - 10) \
or self.rect.left - (bossvessel.width / 2) + self.speed <= 10:
should_aliens_drop = True
else:
should_aliens_move = True
class Bossvessel(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.width = 220
self.height = 200
self.image = pygame.image.load(path.join(IMAGE_DIR, "boss.png")).convert_alpha()
self.image = pygame.transform.scale(self.image, (self.width, self.height)) # 11, 10
self.rect = self.image.get_rect()
self.health = BOSSVESSELMAXHEALTH
def update(self):
self.rect.centerx = boss.rect.centerx
self.rect.centery = boss.rect.centery + BOSSVESSELDISTANCE
class ExplosionBlue(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(path.join(IMAGE_DIR, "explosionblue.png")).convert_alpha()
self.image = pygame.transform.scale(self.image, (45, 45))
self.rect = self.image.get_rect()
self.rect.x = x - 5
self.rect.y = y - 7
self.timer = pygame.time.get_ticks()
def update(self, current_time):
passed = (current_time * 1000) - self.timer
if passed >= 200:
self.kill()
class ExplosionGreen(ExplosionBlue):
def __init__(self, x, y):
super().__init__(x, y)
self.image = pygame.image.load(path.join(IMAGE_DIR, "explosiongreen.png")).convert_alpha()
self.image = pygame.transform.scale(self.image, (45, 45))
class ExplosionPurple(ExplosionBlue):
def __init__(self, x, y):
super().__init__(x, y)
self.image = pygame.image.load(path.join(IMAGE_DIR, "explosionpurple.png")).convert_alpha()
self.image = pygame.transform.scale(self.image, (45, 45))
class ExplosionRed(ExplosionBlue):
def __init__(self, x, y):
super().__init__(x, y)
self.image = pygame.image.load(path.join(IMAGE_DIR, "explosionred.png")).convert_alpha()
self.image = pygame.transform.scale(self.image, (45, 45))
class Laser(pygame.sprite.Sprite):
def __init__(self, x, y, speed, colour):
pygame.sprite.Sprite.__init__(self)
self.width = 2
self.height = 4
self.image = pygame.Surface((self.width, self.height))
self.colour = colour
self.image.fill(self.colour)
self.rect = self.image.get_rect()
self.speed = speed
self.rect.centerx = x
self.rect.centery = y
def update(self):
self.rect.y -= self.speed
if self.rect.y + (self.height / 2) <= 0 or self.rect.y - (self.height / 2) >= HEIGHT:
self.kill()
class Mystery(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.width = 75
self.height = 35
self.image = pygame.image.load(path.join(IMAGE_DIR, "mystery.png")).convert_alpha()
self.image = pygame.transform.scale(self.image, (self.width, self.height))
self.rect = self.image.get_rect()
self.speed = MYSTERYSPEED
self.last_appeared = 0
self.last_stopped = 0
self.rect.x = MYSTERYXPOS
self.rect.y = 25
def update(self, level, levelstarttime, now):
if len(mystery_group) == 1:
self.rect.x += self.speed
# Past lvl 3 when hit after it never returns due to speed never being reset to 5
if not ((WIDTH / 2) - 2 <= self.rect.centerx <= (WIDTH / 2) + 2):
self.speed = MYSTERYSPEED
if self.rect.x >= WIDTH:
self.last_stopped = 0
self.kill()
if 11 > level >= 6 and 60 >= (now - levelstarttime) >= 30:
if self.speed == 0 and (now - self.last_stopped) >= 3 and len(mystery_group) == 1 \
and (WIDTH / 2) - 2 <= self.rect.centerx <= (WIDTH / 2) + 2:
generate_alien_reinforcements()
ALIENAPPEAR.play()
self.rect.centerx = (WIDTH / 2) + 3
self.speed = MYSTERYSPEED
self.last_appeared = now
self.rect.x = (WIDTH / 2) + 6
if self.speed != 0 and (WIDTH / 2) - 2 <= self.rect.centerx <= (WIDTH / 2) + 2:
self.speed = 0
self.last_stopped = now
class Powerup(pygame.sprite.Sprite):
def __init__(self, x, y, colour):
pygame.sprite.Sprite.__init__(self)
self.width = 4
self.height = 20
self.image = pygame.Surface((self.width, self.height))
self.colour = colour
self.image.fill(self.colour)
self.rect = self.image.get_rect()
self.speed = POWERUPSPEED
self.generated_this_level = False
self.rect.centerx = x
self.rect.y = y
def update(self):
self.rect.y += self.speed
if self.rect.top >= HEIGHT:
self.kill()
class Satellite(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(path.join(IMAGE_DIR, "satellite.png")).convert_alpha()
self.image = pygame.transform.scale(self.image, (106, 40))
self.rect = self.image.get_rect()
self.speed = SATELLITESPEED
self.rect.x = SATELLITEXPOS
self.rect.y = 25
self.powerup_generated = False
self.last_stopped = 0
self.stopped_this_level = False
def update(self, now):
self.rect.x += self.speed
if self.rect.right <= 0:
self.kill()
if len(satellite_group) > 0 and self.rect.right <= WIDTH and self.rect.left >= 0 \
and not self.stopped_this_level:
if random.randint(1, 200) == 1:
self.last_stopped = pygame.time.get_ticks() / 1000
self.speed = 0
self.stopped_this_level = True
if 2 > now - self.last_stopped > 1 and len(powerup_group) == 0:
generate_powerup()
POWERUPGENERATED.play()
self.powerup_generated = True
if now - self.last_stopped >= 3:
self.speed = SATELLITESPEED
class Star(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface([1, 1])
self.image.fill(WHITE)
self.rect = self.image.get_rect()
self.speed = STARSPEED
def update(self):
self.rect.y += self.speed
if self.rect.y >= HEIGHT:
self.rect.y = 0
# functions
def alien_drop():
for alien in alien_master_group:
alien.rect.y += ALIENDROP
alien.speed *= -1
def alien_move():
if len(boss_group) == 0:
for alien in alien_master_group:
alien.rect.x += alien.speed
for alien in alien_group:
alien.index += 1
if alien.index >= 2:
alien.index = 0
alien.image = alien_images[alien.index]
for alien in alien_backup_group:
alien.index += 1
if alien.index >= 2:
alien.index = 0
alien.image = alien_backup_images[alien.index]
for alien in alien_elite_group:
alien.index += 1
if alien.index >= 2:
alien.index = 0
alien.image = alien_elite_images[alien.index]
else:
for alien in alien_master_group:
alien.rect.x += alien.speed
for alien in alien_group:
alien.index += 1
if alien.index >= 2:
alien.index = 0
alien.image = alien_images[alien.index]
def alien_shoot():
if len(alien_laser_group) <= math.trunc(len(alien_group) / 10) and len(alien_group) > 0:
alien = random.choice(list(alien_group))
laser = Laser(alien.rect.centerx, alien.rect.centery, -LASERSPEED, BLUE)
alien_laser_group.add(laser)
if len(alien_laser_group) <= math.trunc(len(alien_backup_group) / 5) and len(alien_backup_group) > 0:
alien = random.choice(list(alien_backup_group))
laser = Laser(alien.rect.centerx, alien.rect.centery, -LASERSPEED, GREEN)
alien_laser_group.add(laser)
if len(alien_laser_group) <= math.trunc(len(alien_elite_group) / 2) and len(alien_elite_group) > 0:
alien = random.choice(list(alien_elite_group))
laser = Laser(alien.rect.centerx, alien.rect.centery, -LASERSPEED, PURPLE)
alien_laser_group.add(laser)
if len(alien_laser_group) <= math.trunc(len(alien_reinforcements_group) / 2) and len(
alien_reinforcements_group) > 0:
alien = random.choice(list(alien_reinforcements_group))
laser = Laser(alien.rect.centerx, alien.rect.centery, -LASERSPEED, PURPLE)
alien_laser_group.add(laser)
def bossvessel_shoot():
if len(bossvessel_group) > 0 and bossvessel.health > 0 and len(bossvessel_laser_group) < random.randint(0, 9):
laser = Laser(bossvessel.rect.left + (random.randint(0, 6) * 35), bossvessel.rect.y + bossvessel.height,
-LASERSPEED, RED)
bossvessel_laser_group.add(laser)
def check_collisions(now, bossgrouplen):
global time_last_hit
for alien in alien_master_group:
for barrier in barrier_master_group:
if alien.rect.colliderect(barrier.rect):
barrier.kill()
if alien.rect.colliderect(player.rect):
explosion_group.add(ExplosionGreen(alien.rect.x, alien.rect.y))
explosion_group.add(ExplosionGreen(player.rect.x, player.rect.y))
player.lives = 0
alien.kill()
ALIENEXPLOSIONSOUND.play()
player.kill()
pygame.sprite.groupcollide(alien_laser_group, barrier_master_group, True, True)
pygame.sprite.groupcollide(bossvessel_laser_group, barrier_master_group, True, True)
pygame.sprite.groupcollide(laser_group, barrier_master_group, True, True)
for laser in laser_group:
for alien in alien_group:
if laser.rect.colliderect(alien.rect):
explosion_group.add(ExplosionBlue(alien.rect.x, alien.rect.y))
player.score += ALIENSCORE
laser.kill()
alien.kill()
ALIENEXPLOSIONSOUND.play()
time_last_hit = now
for alien in alien_backup_group:
if laser.rect.colliderect(alien.rect):
explosion_group.add(ExplosionGreen(alien.rect.x, alien.rect.y))
player.score += ALIENBACKUPSCORE
laser.kill()
alien.kill()
ALIENEXPLOSIONSOUND.play()
time_last_hit = now
for alien in alien_elite_group:
if laser.rect.colliderect(alien.rect):
explosion_group.add(ExplosionPurple(alien.rect.x, alien.rect.y))
player.score += ALIENELITESCORE
laser.kill()
alien.kill()
ALIENEXPLOSIONSOUND.play()
time_last_hit = now
for alien in alien_reinforcements_group:
if laser.rect.colliderect(alien.rect):
explosion_group.add(ExplosionPurple(alien.rect.x, alien.rect.y))
player.score += ALIENELITESCORE
laser.kill()
alien.kill()
ALIENEXPLOSIONSOUND.play()
time_last_hit = now
if bossgrouplen > 0:
if laser.rect.colliderect(boss.rect):
laser.kill()
time_last_hit = now
if laser.rect.colliderect(bossvessel.rect):
bossvessel.health -= 1
if bossvessel.health <= 0:
explosion_group.add(ExplosionGreen(boss.rect.centerx, boss.rect.y))
boss.kill()
explosion_group.add(ExplosionRed(bossvessel.rect.centerx, bossvessel.rect.y))
bossvessel.kill()
laser.kill()
time_last_hit = now
if laser.rect.colliderect(mystery.rect):
explosion_group.add(ExplosionRed(mystery.rect.centerx, mystery.rect.y))
player.score += MYSTERYSCORE
mystery.rect.x = MYSTERYXPOS
laser.kill()
mystery.kill()
MYSTERYEXPLOSION.play()
time_last_hit = now
if laser.rect.colliderect(satellite.rect):
explosion_group.add(ExplosionBlue(satellite.rect.centerx, satellite.rect.y))
satellite.rect.x = SATELLITEXPOS
laser.kill()
satellite.kill()
SATELLITEEXPLOSION.play()
time_last_hit = now
for laser in alien_laser_group:
hits = pygame.sprite.spritecollide(laser, player_group, False, pygame.sprite.collide_circle)
for hit in hits:
player_hit()
laser.kill()
time_last_hit = now
if player.lives == 0:
explosion_group.add(ExplosionGreen(player.rect.x, player.rect.y))
player.kill()
for laser in bossvessel_laser_group:
hits = pygame.sprite.spritecollide(laser, player_group, False, pygame.sprite.collide_circle)
for hit in hits:
player_hit()
laser.kill()
time_last_hit = now
if player.lives == 0:
explosion_group.add(ExplosionGreen(player.rect.x, player.rect.y))
player.kill()
for powerup in powerup_group:
if powerup.rect.colliderect(player.rect):
powerup.kill()
POWERUPPICKEDUP.play()
if player.lives < 5:
randnumber = random.randint(1, 3)
if randnumber == 1:
player.double_shot = True
elif randnumber == 2:
num = random.randint(0, 3)
generate_barrier(num, num + 1)
else:
player.lives += 1
elif player.lives == 5:
randnumber = random.randint(1, 2)
if randnumber == 1:
player.double_shot = True
else:
num = random.randint(0, 3)
generate_barrier(num, num + 1)
def draw_boss_health_bar(screen):
pygame.draw.rect(screen, RED, pygame.Rect(5, HEIGHT - 10, WIDTH - 10, 10), 2)
pygame.draw.rect(screen, RED,
pygame.Rect(5, HEIGHT - 10, (WIDTH - 10) * (bossvessel.health / BOSSVESSELMAXHEALTH), 10))
def draw_lives(surf, x, y, lives, img):
for i in range(lives):
img_rect = img.get_rect()
img_rect.x = x + 30 * i
img_rect.y = y
surf.blit(img, img_rect)
def draw_text(surf, font, size, text, colour, x, y, location):
font = pygame.font.Font(font, size)
text_surface = font.render(text, True, colour)
text_rect = text_surface.get_rect()
if location == 'center':
text_rect.center = (x, y)
elif location == 'left':
text_rect.midleft = (x, y)
surf.blit(text_surface, text_rect)
def generate_barrier(num1, num2):
for i in range(num1, num2):
for x in range(20):
for y in range(10):
barrier = Barrier(50 + (x * 5) + (200 * i), 525 - (y * 5))
barrier_master_group.add(barrier)
def generate_aliens_lvl1():
for x in range(10):
for y in range(2):
alien = Alien()
alien.rect.x = 50 + (x * 50)
alien.rect.y = ALIENSTARTYPOS + (y * 45)
alien_group.add(alien)
alien_master_group.add(alien)
def generate_aliens_lvl2():
for x in range(10):
for y in range(4):
if y in (0, 1):
alien = AlienBackup()
alien.rect.x = 50 + (x * 50)
alien.rect.y = ALIENSTARTYPOS + (y * 45)
alien_backup_group.add(alien)
alien_master_group.add(alien)
elif y in (2, 3):
alien = Alien()
alien.rect.x = 50 + (x * 50)
alien.rect.y = ALIENSTARTYPOS + (y * 45)
alien_group.add(alien)
alien_master_group.add(alien)
def generate_aliens_lvl3():
for x in range(10):
for y in range(5):
if y == 0:
alien = AlienElite()
alien.rect.x = 50 + (x * 50)
alien.rect.y = ALIENSTARTYPOS + (y * 45)
alien_elite_group.add(alien)
alien_master_group.add(alien)
elif y in (1, 2):
alien = AlienBackup()
alien.rect.x = 50 + (x * 50)
alien.rect.y = ALIENSTARTYPOS + (y * 45)
alien_backup_group.add(alien)
alien_master_group.add(alien)
elif y in (3, 4):
alien = Alien()
alien.rect.x = 50 + (x * 50)
alien.rect.y = ALIENSTARTYPOS + (y * 45)
alien_group.add(alien)
alien_master_group.add(alien)
def generate_alien_reinforcements():
for x in range(5):
alien = AlienElite()
alien.rect.x = ((WIDTH / 2) - 120) + (x * 50)
alien.rect.y = ALIENSTARTYPOS
alien_reinforcements_group.add(alien)
alien_master_group.add(alien)
def generate_boss():
boss.rect.centerx = WIDTH / 2
boss.rect.y = ALIENSTARTYPOS
alien_group.add(boss)
alien_master_group.add(boss)
boss_group.add(boss)
def generate_boss_vessel():
bossvessel.rect.centerx = boss.rect.centerx
bossvessel.rect.centery = boss.rect.centery + BOSSVESSELDISTANCE
bossvessel_group.add(bossvessel)
def generate_mystery():
mystery.rect.x = MYSTERYXPOS
mystery_group.add(mystery)
mystery.last_appeared = pygame.time.get_ticks() / 1000
def generate_powerup():
powerup = Powerup(satellite.rect.centerx, satellite.rect.centery, ORANGE)
if powerup.generated_this_level is False:
powerup.generated_this_level = True
powerup_group.add(powerup)
def generate_satellite():
satellite.rect.x = SATELLITEXPOS
satellite_group.add(satellite)
def generate_stars():
for i in range(random.randint(80, 120)):
x = random.randint(1, WIDTH - 1)
y = random.randint(1, HEIGHT - 1)
star = Star()
star.rect.x = x
star.rect.y = y
star_group.add(star)
def intermission_screen(screen, image_name, image_scale_x, image_scale_y, screen_pos_x, screen_pos_y,
text, text_pos_x, text_pos_y, text_loc):
load_screen_image = pygame.image.load(path.join(IMAGE_DIR, image_name)).convert_alpha()
image = pygame.transform.scale(load_screen_image, (image_scale_x, image_scale_y))
screen.blit(image, (screen_pos_x, screen_pos_y))
draw_text(screen, FONT, 52, text, WHITE, text_pos_x, text_pos_y, text_loc)
def pauze_background_music():
pygame.mixer.music.pause()
def play_background_music():
if random.randint(1, 2) == 1:
pygame.mixer.music.load(BACKGROUND1)
else:
pygame.mixer.music.load(BACKGROUND2)
pygame.mixer.music.set_volume(MUSICVOLUME)
pygame.mixer.music.play(-1)
def player_hit():
player.lives -= 1
PLAYERHIT.play()
def unpauze_background_music():
pygame.mixer.music.unpause()
# miscellaneous
player = Player()
player_group.add(player)
boss = Boss()
bossvessel = Bossvessel()
mystery = Mystery()
satellite = Satellite()
class SpaceInvaders(object):
def __init__(self):
pygame.init()
self.clock = pygame.time.Clock()
self.fps = self.clock.get_fps()
self.screen = SCREEN
self.now = pygame.time.get_ticks() / 1000
self.levelstarttime = 0
self.level = 1
self.menu()
def game_over(self, endgame):
pygame.mixer.music.stop()
if endgame == 0:
endgametext = "GAME OVER"
endgamecolour = RED
else:
endgametext = "VICTORY"
endgamecolour = GREEN
pygame.time.wait(2000)
draw_text(self.screen, FONT, 64, endgametext, endgamecolour, WIDTH / 2, HEIGHT / 2, 'center')
GAMEOVER.play()
pygame.display.update()
pygame.time.wait(2000)
draw_text(self.screen, FONT, 32, "Press space bar to restart", WHITE, WIDTH / 2, (HEIGHT / 2) + 50, 'center')
draw_text(self.screen, FONT, 32, "or press escape to quit", WHITE, WIDTH / 2, (HEIGHT / 2) + 100, 'center')
pygame.display.update()
pygame.time.wait(2000)
SCREEN.fill(BLACK)
draw_text(self.screen, FONT, 64, endgametext, endgamecolour, WIDTH / 2, HEIGHT / 2, 'center')
draw_text(self.screen, FONT, 32, "Press space bar to restart", WHITE, WIDTH / 2, (HEIGHT / 2) + 50, 'center')
draw_text(self.screen, FONT, 32, "or press escape to quit", WHITE, WIDTH / 2, (HEIGHT / 2) + 100, 'center')
pygame.display.update()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
self.level = 1
self.new_game()
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
def intermission(self):
pauze_background_music()
pygame.time.wait(2000)
self.screen.fill(BLACK)
if 11 > self.level >= 1:
intermission_screen(self.screen, "ship.png", 45, 45, 50, (HEIGHT * 0.25) + 50,
'= Player', 100, (HEIGHT * 0.25) + 75, 'left')
intermission_screen(self.screen, "enemy2_1.png", 45, 45, (WIDTH / 2) + 50, (HEIGHT * 0.25) + 50,
'= ' + str(ALIENSCORE) + ' points', (WIDTH / 2) + 100, (HEIGHT * 0.25) + 75, 'left')
if 11 > self.level >= 2:
intermission_screen(self.screen, "enemy3_2.png", 45, 45, 50, (HEIGHT * 0.25) + 150,
'= ' + str(ALIENBACKUPSCORE) + ' points', 100, (HEIGHT * 0.25) + 175, 'left')
if 11 > self.level >= 3:
intermission_screen(self.screen, "enemy1_1.png", 45, 45, (WIDTH / 2) + 50, (HEIGHT * 0.25) + 150
, '= ' + str(ALIENELITESCORE) + ' points', (WIDTH / 2) + 100, (HEIGHT * 0.25) + 175, 'left')
if 11 > self.level >= 4:
intermission_screen(self.screen, "mystery.png", 75, 35, 35, (HEIGHT * 0.25) + 250,
'= ' + str(MYSTERYSCORE) + ' points', 110, (HEIGHT * 0.25) + 275, 'left')
if 11 > self.level >= 5:
intermission_screen(self.screen, "satellite.png", 106, 40, (WIDTH / 2) + 20, (HEIGHT * 0.25) + 250
, "= don't shoot", (WIDTH / 2) + 125, (HEIGHT * 0.25) + 275, 'left')
intermission_screen(self.screen, "powerup.png", 8, 40, (WIDTH / 2) + 75, (HEIGHT * 0.25) + 350
, "= powerup", (WIDTH / 2) + 100, (HEIGHT * 0.25) + 375, 'left')
if self.level == 6:
draw_text(self.screen, FONT, 52, 'Watch out for reinforcements', RED, WIDTH / 2, 50, 'center')
if self.level <= 10:
draw_text(self.screen, FONT, 52, 'level ' + str(int(self.level)), GREEN, WIDTH / 2, (HEIGHT * 0.25), 'center')
elif self.level == 11:
draw_text(self.screen, FONT, 52, 'FINAL BOSS', RED, WIDTH / 2, (HEIGHT / 2), 'center')
pygame.display.update()
pygame.time.wait(3000)
unpauze_background_music()
def menu(self):
generate_stars()
while True:
button = pygame.Rect((WIDTH / 2) - 100, (HEIGHT / 2), 200, 100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if button.collidepoint(event.pos):
pygame.time.wait(2000)
self.intermission()
self.new_game()
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
self.intermission()
self.new_game()
keys = pygame.key.get_pressed()
self.screen.fill(BLACK)
pygame.draw.rect(self.screen, BLACK, button)
star_group.update()
star_group.draw(self.screen)
draw_text(self.screen, STARTFONT, 64, 'START', WHITE, button.centerx, button.centery, 'center')
draw_text(self.screen, LOGOFONT, 80, 'SPACE INVADERS', GREEN, WIDTH / 2, (HEIGHT / 2) - 100, 'center')
draw_text(self.screen, FONT, 25, 'Or press SPACE to start the game', WHITE, WIDTH / 2,
(HEIGHT - 100), 'center')
draw_text(self.screen, FONT, 25, 'Use arrow keys to move and space bar to shoot', WHITE, WIDTH / 2,
(HEIGHT - 50), 'center')
pygame.display.flip()
self.clock.tick(FPS)
def new_game(self):
global alien_group
alien_group = pygame.sprite.Group()
global alien_backup_group
alien_backup_group = pygame.sprite.Group()
global alien_elite_group
alien_elite_group = pygame.sprite.Group()
global alien_master_group
alien_master_group = pygame.sprite.Group()
global alien_reinforcements_group
alien_reinforcements_group = pygame.sprite.Group()
global alien_laser_group
alien_laser_group = pygame.sprite.Group()
global boss_group
boss_group = pygame.sprite.Group()
global bossvessel_group
bossvessel_group = pygame.sprite.Group()
global explosion_group
explosion_group = pygame.sprite.Group()
global laser_group
laser_group = pygame.sprite.Group()
global mystery_group
mystery_group = pygame.sprite.Group()
global powerup_group
powerup_group = pygame.sprite.Group()
global satellite_group
satellite_group = pygame.sprite.Group()
if self.level == 1:
global barrier_master_group
barrier_master_group = pygame.sprite.Group()
global player_group
player_group = pygame.sprite.Group()
global star_group
star_group = pygame.sprite.Group()
global player
player = Player()
player_group.add(player)
player.lives = 5
player.score = 0
generate_aliens_lvl1()
elif self.level == 2:
generate_aliens_lvl2()
elif 11 > self.level >= 3:
generate_aliens_lvl3()
if self.level <= 3:
generate_barrier(0, 4)
if self.level == 11:
generate_boss()
generate_boss_vessel()
generate_stars()
play_background_music()
mystery.last_appeared = pygame.time.get_ticks() / 1000
satellite.appeared_this_level = False
self.game_loop()
def game_start(self):
self.menu()
def game_loop(self):
while True:
self.now = (pygame.time.get_ticks() / 1000)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.K_SPACE and player.lives == 0:
SpaceInvaders()
global should_aliens_drop
should_aliens_drop = False
global should_aliens_move
should_aliens_move = False
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE]:
if player.lives > 0:
if self.now - player.last_shot >= player.cool_down and not player.double_shot:
player.last_shot = self.now
laser = Laser(player.rect.centerx, player.rect.y, LASERSPEED, GREEN)
laser_group.add(laser)
LASERSOUND.play()
if self.now - player.last_shot >= player.cool_down and player.double_shot:
player.last_shot = self.now
laser = Laser(player.rect.centerx - 15, player.rect.y + 20, LASERSPEED, GREEN)
laser_group.add(laser)
laser = Laser(player.rect.centerx + 15, player.rect.y + 20, LASERSPEED, GREEN)
laser_group.add(laser)
LASERSOUND.play(1)
self.screen.fill(BLACK)
star_group.update()
star_group.draw(self.screen)
alien_master_group.update(self.now)
alien_master_group.draw(self.screen)
if should_aliens_drop:
alien_drop()
should_aliens_drop = False
if should_aliens_move:
alien_move()
should_aliens_move = False
alien_laser_group.update()
alien_laser_group.draw(self.screen)
barrier_master_group.update(keys)
barrier_master_group.draw(self.screen)
bossvessel_group.update(keys)
bossvessel_group.draw(self.screen)
bossvessel_laser_group.update(keys)
bossvessel_laser_group.draw(self.screen)
if self.level >= 10 and len(boss_group) == 1:
draw_boss_health_bar(self.screen)
explosion_group.update(self.now)
explosion_group.draw(self.screen)
laser_group.update()
laser_group.draw(self.screen)
mystery_group.update(self.level, self.levelstarttime, self.now)
mystery_group.draw(self.screen)
if self.level >= 4 and len(mystery_group) == 0 and (self.now - mystery.last_appeared) >= MYSTERYTIME:
generate_mystery()
player_group.update(keys)
player_group.draw(self.screen)
powerup_group.update(keys)
powerup_group.draw(self.screen)
satellite_group.update(self.now)
satellite_group.draw(self.screen)
if self.level >= 5 and len(satellite_group) == 0 and random.randint(1, 750) == 1 \
and not satellite.powerup_generated:
generate_satellite()
SATELLITEANNOUNCE.play()
check_collisions(self.now, len(boss_group))
# print(len(bossvessel_group))
draw_text(self.screen, FONT, 32, 'FPS ' + str(int(self.clock.get_fps())), WHITE, WIDTH - 60, 14, 'center')
draw_text(self.screen, FONT, 32, 'SCORE ' + str(int(player.score)), WHITE, WIDTH / 2, 14, 'center')
draw_lives(self.screen, 10, 5, player.lives, pygame.transform.scale(player.image, (18, 18)))
if player.lives == 0 and self.now - time_last_hit >= 2:
self.game_over(len(player_group))
if len(alien_master_group) == 0 and self.now - time_last_hit >= 2:
satellite.stopped_this_level = False
self.level += 1
self.levelstarttime = self.now
player.double_shot = False
self.intermission()
self.new_game()
if len(boss_group) == 0:
alien_shoot()
else:
bossvessel_shoot()
pygame.display.flip()
self.clock.tick(FPS)
if __name__ == '__main__':
# Make a game instance, and run the game.
game = SpaceInvaders()
# game.game_loop()
game.menu()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T19:22:52.360",
"Id": "526647",
"Score": "1",
"body": "`pygame.display.set_icon(pygame.image.load(path.join(IMAGE_DIR, \"logo.png\")).convert_alpha()) FileNotFoundError: No such file or directory.` You'll need to post the assets somewhere (perhaps on github/gitlab?) so we can see how the game runs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T20:37:10.823",
"Id": "526657",
"Score": "1",
"body": "I will add a link with all the assets tomorrow"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T09:48:27.520",
"Id": "526676",
"Score": "1",
"body": "Just added a Github link"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T21:44:13.313",
"Id": "526726",
"Score": "0",
"body": "Thanks, yes, the code works, I'll look into a review. Small note though, I was hit multiple times but didn't die, and when I did (a hit on the wings), I wasn't able to use any of my ships - it went straight to the end of the game. No matter though, let's look at your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T07:08:21.243",
"Id": "527743",
"Score": "0",
"body": "The way I programmed it is that you start with 5 lives (represented by each ship in the upper left corner) and every time you get hit you lose one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T15:28:13.123",
"Id": "527777",
"Score": "0",
"body": "Your Github link is dead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-04T08:58:04.880",
"Id": "527831",
"Score": "0",
"body": "Didn't think anyone else would be having a look at it, made it visible again @Reinderien"
}
] |
[
{
"body": "<p>and thanks for your post. From a quick scan of your code, these issues jump out at me:</p>\n<ul>\n<li>Configurations inside the code instead of in an ini file, breaking the Open/Close Principle,</li>\n<li>Many instances of MAGIC_STRINGS and MAGIC_VALUES, these should be loaded from a configuration file, and restricted to the class or domain where they're used, not as globals,</li>\n<li>Not using enums when using common items such as colors,</li>\n<li>Missing functions for repeated actions, these can be brought into a single call instead, such as alien images and the sound effects,</li>\n<li>Importing globals inside classes - state is no longer encapsulated to a single location. If classes require injected configuration into them, inherit from another class or bring them in like a mixin,</li>\n<li>Extended lines of code that require lots of calculation to understand what is happening. Wrap those into a single function which explains in plain English to other coders what the math is attempting to produce,</li>\n<li>References in classes that inherit Alien() base class, but refer to the parent class when defining index instead of self,</li>\n<li>Unknown references to .speed in the Sprite class (lines 448, 454, 472),</li>\n<li>Calling sys.exit in the middle of a while True loop. Make the loop evaluate if the user wants to quit, not inside it,</li>\n<li>Creation of the sprite groups outside the SpaceInvaders class, then importing the via global, but then overwriting them immediately? Why not just create them inside the class?</li>\n<li>Lines 444 (#functions) through 815 look like they operate on objects inside the game, yet they're separate (with no reference to <code>self</code>), I assume they're designed as helper functions. The problem with that is, there's no reference being passed to them "as functions" so, how do you really know which alien or laser beam - in the example of <code>check_collisions</code> and my experience of being hit multiple times yet not exploding - is working correctly? Without a proper reference or action being allocated to an object, state can go missing, as I've seen when playing the game.</li>\n</ul>\n<p>These are the most obvious issues in terms of code that jump out at me without making this post too long.</p>\n<p>Let's go through them.</p>\n<h2>Configuration</h2>\n<p>The Open/Close Principle states that your code should be open for extension, but closed for modifications. If you want to change the starting location for the alien ships, you would need to go through your entire program and modify various numbers. If you make a mistake and change a number incorrectly, you would need to go back through your entire program, line by line, to find the specific number that is in error.\nThis is what the principle means. It's part of S.O.L.I.D to help you reduce unnecessary errors and produce code which is cleaner and reduce a lot of the 'WTF?' coders say, when looking at other programmers code.</p>\n<h2>Enum</h2>\n<p>Enum came about as it's easier to refer to words than numbers, and using the "." between Color and the color you want, intellisense in your IDE gives you a drop-down to make selection easier. To explain it:</p>\n<pre><code>>>> from enum import Enum\n>>> class Color(Enum):\n... Black = (0,0,0)\n... Blue = (0, 255, 240)\n... \n>>> print(Color.Black)\nColor.Black\n>>> Color.Blue\n<Color.Blue: (0, 255, 240)>\n>>> Color.Blue.value\n(0, 255, 240)\n>>> \n</code></pre>\n<p>Colors would be defined in the configuration file, imported into the code as an enum, and your code would refer to it then. A reason is, certain computers display certain colors slightly different (hardware chips, glass panels, etc). If you want to have perfect colors across all units, you might have a different configuration file with slightly different values. It's better to use a config file than modify the code for every instance out there.</p>\n<pre><code>self.image.fill(GREEN)\n</code></pre>\n<p>Would become:</p>\n<pre><code>self.image.fill(Color.Green.value)\n</code></pre>\n<h2>Repeated Actions</h2>\n<pre><code>class ExplosionGreen(ExplosionBlue):\n def __init__(self, x, y):\n super().__init__(x, y)\n self.image = pygame.image.load(path.join(IMAGE_DIR, "explosiongreen.png")).convert_alpha()\n self.image = pygame.transform.scale(self.image, (45, 45))\n \n</code></pre>\n<p>In this example, you're inheriting ExplosionBlue, however you're still doing many of the steps manually. ExplosionGreen, which inherits ExplosionBlue, is a manual class for what should just be instantiating an explosion. Let me demonstrate:</p>\n<pre><code>class Explosion(pygame.sprite.Sprite):\n def __init__(self, image_filename, location_x, location_y):\n pygame.sprite.Sprite.__init__(self)\n self.explosion_height = config_explosion_height\n self.explosion_width = config_explosion_width\n self.x_image_overlay = config_x_image_overlay\n self.y_image_overlay = config_y_image_overlay\n self.image = pygame.image.load(load_image_file(image_filename)).convert_alpha()\n self.image = pygame.transform.scale(self.image, (self.explosion_height, self.explosion_width))\n self.rect = self.image.get_rect()\n self.rect.x = location_x - self.x_image_overlay\n self.rect.y = location_y - self.y_image_overlay\n\n self.timer = pygame.time.get_ticks()\n\n def update(self, current_time):\n passed = (current_time * config_second_in_ms) - self.timer\n if passed >= config_explosion_timeout:\n self.kill()\n \n</code></pre>\n<p>Now you can create any explosion with a simple:</p>\n<pre><code>explosion_green = Explosion(config_explosion_image_green, location_x, location_y)\n</code></pre>\n<p>Making code like:</p>\n<pre><code>if alien.rect.colliderect(player.rect):\n explosion_group.add(ExplosionGreen(alien.rect.x, alien.rect.y))\n explosion_group.add(ExplosionGreen(player.rect.x, player.rect.y))\n</code></pre>\n<p>into</p>\n<pre><code>for x,y in ((alien.rect.x, alien.rect.y), (player.rect.x, player.rect.y)):\n explosion_group.add(Explosion(config_explosion_image_green, x,y))\n</code></pre>\n<h2>Importing globals inside classes</h2>\n<p>Using global is a bad thing to do because you lose control of variable state, and where a variable can be altered from another location, and you bring that value in, can produce weird outcomes, you can spend days tracking down a bug. Try to break your habit of using it.\nIt also leads to sloppy code such as in new_game:</p>\n<pre><code> def new_game(self):\n global alien_group\n alien_group = pygame.sprite.Group()\n global alien_backup_group\n alien_backup_group = pygame.sprite.Group()\n \n</code></pre>\n<p>You've already spent time creating all these variables at the top of your code, yet you're overwriting them in this statement. Where should the creation take place? The code makes it clear you're not really sure.</p>\n<h2>Extended lines of code</h2>\n<p>Seeing code like:</p>\n<pre><code>if self.rect.right + self.speed >= (WIDTH - 10) or self.rect.left + self.speed <= 10:\n should_aliens_drop = True\nelse:\n should_aliens_move = True\n</code></pre>\n<p>makes me go hmm... if.. right of the rectangle plus the speed is greater than the WIDTH.. what's the WIDTH of? [searches entire code for WIDTH] ah, the width of the screen, okay, screen width less 10, or, or the rectangle, left of the rectangle plus speed is less than or equal to 10... okay, they drop else they move. okay...</p>\n<p>The code would be better if you had:</p>\n<pre><code> if self.alien_at_max_right() or self.alien_at_max_left():\n should_aliens_drop = True\n else:\n should_aliens_move = True\n</code></pre>\n<p>with these functions of course:</p>\n<pre><code>def alien_at_max_right(self):\n return self.rect.right + self.speed >= (config_screen_width - config_screen_edge)\ndef alien_at_max_left(self):\n return self.rect.left + self.speed <= config_screen_edge\n \n</code></pre>\n<p>This is infinitely better - now I say hmmm... okay, if the alien is at the max right, or at the max left, the alien should drop. Okay, sounds good. Else they move - of course, makes sense.</p>\n<p>If another coder wants to dig into the particulars of the math, they can do that. But usually they only read your code to fix a bug or to extend it.</p>\n<p>Now, don't go overboard with this - if you only have a single line that is very simple like "okay, the circle is the pi times, yeah I know this" then that should be fine to leave it in - or - if the function is only ever called once in the entire code - there's no need to extract that into it's own function unless it's a horribly long formula. The goal is readability of your code.</p>\n<h2>References in classes that inherit Alien()</h2>\n<pre><code>class AlienBackup(Alien):\n def __init__(self):\n super().__init__()\n self.image = alien_backup_images[Alien().index]\n \n</code></pre>\n<p>The problem here is using the index on the parent class instead of the class itself. I'm not sure if you did this intentionally, but if you create a child-class, you should always refer to the state variables of that child class itself and not the state of the parent class, which might be modified by other children, again we're trying to reduce instances of weird behavior.\nAnother small point is you're creating a new <code>Alien()</code> parent class in every call to determine the index.</p>\n<h2>Unknown references to .speed</h2>\n<pre><code>def alien_drop():\n for alien in alien_master_group:\n alien.rect.y += ALIENDROP\n alien.speed *= -1\n \n</code></pre>\n<p><code>alien.speed</code> doesn't exist in the class Sprite. Again, be mindful of which class you're referencing. I suggest improving your IDE, try the community version of PyCharm unless you've got memory constraints (java can be a memory hog).</p>\n<h2>Calling sys.exit</h2>\n<pre><code>def game_loop(self):\n while True:\n\n self.now = (pygame.time.get_ticks() / 1000)\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n \n</code></pre>\n<p>In this instance, what you should do is create a control variable, which decides if it's time to exit the game loop. Such as:</p>\n<pre><code>def game_loop(self):\n play_game = True\n while play_game:\n ...\n if event.type == pygame.QUIT:\n play_game = False\n \n</code></pre>\n<p>when the loop finishes, the game will exit the loop, and you can call pygame.quit() outside the loop (where it's meant to be).</p>\n<h2>Creation of the sprite groups outside the SpaceInvaders class</h2>\n<p>We covered this a little earlier when talking about <code>new_game</code> but that was about using global. Here we're discussing the location for creation of the sprite groups. Where would be the most appropriate location?</p>\n<p>Currently you create them outside at the start of your code, then you recreate them at the start of the new_game function.\nWouldn't it be best to create them during the <strong>init</strong> of the SpaceInvaders (SI) class?</p>\n<p>Of course you can define them outside the SI class as they require many lines of definitions, and instantiate them during the init.</p>\n<p>Do they require a reset? That functionality can be added to the base class, removing the commands individually from their <strong>init</strong>, and placed into a <code>def _reset(self):</code> function, which init will call.\nI hope this point is isn't too confusing?</p>\n<h2>Lines 444 (#functions) through 815</h2>\n<p>These functions are part of certain objects - like the aliens themselves. <code>alien_drop()</code> <code>alien_move()</code> <code>alien_shoot()</code> etc. They belong in the alien class as methods.</p>\n<p>Drawing lives, generating the barriers, writing the text - they're all part of the game - and should be created as part of the SpaceInvader class (the game engine itself).</p>\n<p>It's important for operations that belong to objects stay with the objects to help understand the links between them, and avoid unfortunate references, should someone accidently reference (contrived example here): <code>alien_shoot(player)</code> where an alien would shoot upwards and destroy another alien.</p>\n<h2>Ending Comments</h2>\n<p>So Dreadnought, I hope most of this makes sense? If not, I can suggest a book named "Code Complete" which can show you a lot of these mistakes and it can help to improve your coding, if it's something that you enjoy.</p>\n<p>Nevertheless, it's a good effort, I had fun playing your game. Please keep it up, and see if you can incorporate these lessons into your code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T12:44:43.180",
"Id": "267626",
"ParentId": "266556",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "267626",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T15:04:27.373",
"Id": "266556",
"Score": "2",
"Tags": [
"python",
"pygame"
],
"Title": "Invaders clone made with Pygame"
}
|
266556
|
<p>I'm new to elixir and would really like some feedback on my code. MY background has been node -> laravel -> ruby / rails -> go -> elixir. I'm building an SMTP client and would like to make sure I'm using common patterns before I continue.</p>
<p>Any feedback would be appreciated.</p>
<pre><code>defmodule Client do
@moduledoc """
Documentation for `Smtpclient`.
"""
use Agent
def start_link(_opts) do
Agent.start_link(fn -> %{} end, name: __MODULE__)
end
def connect(pid, tld) do
set_value(pid, "tld", tld)
{:ok, records} = DNS.resolve(tld, :mx)
Enum.sort_by(records, fn(r) -> elem(r, 0) end)
sock = do_connect(records, 0)
set_socket(pid, sock)
set_value(pid, "hostname", tld)
{:ok, sock}
end
@spec helo(any) :: any
def helo(pid) do
already_helloed = get_value(pid, "already_helloed")
if already_helloed do # if already helloed return early
{:error, "already helloed"}
end
sock = get_socket(pid)
tld = get_value(pid, "tld")
sock |> Socket.Stream.send!("HELO #{tld}")
set_value(pid, "already_helloed", true)
sock |> Socket.Stream.recv!
end
def noop(pid) do
try do
sock = get_socket(pid)
sock |> Socket.Stream.send!("NOOP")
sock |> Socket.Stream.recv!
rescue
Socker.Error -> {:error, :no_connection}
end
end
def quit(sock) do
try do
sock |> Socket.Stream.send!("QUIT")
sock |> Socket.Stream.recv!
sock |> Socket.close!()
rescue
Socket.Error -> {:error, "something is wrong"}
end
end
def rctp_to(pid, email) do
try do
sock = get_socket(pid)
sock |> Socket.Stream.send!("RCPT_TO #{email}")
sock |> Socket.Stream.recv!
rescue
Socker.Error -> {:error, "something is wrong"}
end
end
defp set_socket(pid, sock) do
Agent.update(pid, &Map.put(&1, "socket", sock))
end
defp get_socket(pid) do
Agent.get(pid, &Map.get(&1, "socket"))
end
defp set_value(pid, key, value) do
Agent.update(pid, &Map.put(&1, key, value))
end
defp get_value(pid, key) do
Agent.get(pid, &Map.get(&1, key))
end
defp do_connect(hostnames, i) do
try do
host = elem(Enum.at(hostnames, i), 1)
Socket.TCP.connect!(to_string(host), 25, packet: :line)
rescue
Socket.Error ->
if Enum.at(hostnames, i) == nil do
{:error, "all mx servers down"}
end
do_connect(hostnames, i + 1)
end
end
end
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T15:33:38.850",
"Id": "526628",
"Score": "1",
"body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T15:23:45.750",
"Id": "266557",
"Score": "0",
"Tags": [
"elixir"
],
"Title": "New to Elixir would like some feedback"
}
|
266557
|
<p>I have got a new answer while trying the URLify question from <strong>Cracking the Coding Interview</strong> book. My answer is completely different from the approach shown in the book.</p>
<p><strong>Problem</strong></p>
<p>Take a string that may contain spaces and return a string where all consecutive spaces are replaced by a single %20.</p>
<p><em>My solution is</em>:</p>
<pre><code>def URLfy(string):
result = ''
prev = ''
for s in string.strip():
if s != ' ':
result += s
if s ==' ':
if prev == ' ':
continue
result += '%20'
last = s
return result
</code></pre>
<p>The time complexity is the same <em>i.e</em> <span class="math-container">\$\mathcal{O}(n)\$</span>.</p>
<p>Can someone verify my solution?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T17:28:20.240",
"Id": "526639",
"Score": "5",
"body": "Should `last = s` be `prev = s`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T17:43:51.320",
"Id": "526641",
"Score": "2",
"body": "Note that as written, this code won't work. Because `prev` will never be a space."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T19:13:07.463",
"Id": "526646",
"Score": "0",
"body": "You might want to revisit your understanding of O complexity, as you perform multiple checks per character in a loop - every action is counted per iteration, as well as you extend the string either with the character itself, or with %20. There are multiple operations performed by the system when this occurs, because strings in Python are immutable. Keep studying :-)"
}
] |
[
{
"body": "<p>If <code>result += s</code> is a constant-time operation, this will run in <span class=\"math-container\">\\$O(n)\\$</span> time. In python <a href=\"https://stackoverflow.com/questions/37133547/time-complexity-of-string-concatenation-in-python\">this can be true</a> but I wouldn't rely on it.</p>\n<p>As pointed out in the comments, your code has an error. Test code before getting it reviewed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T10:23:00.620",
"Id": "266584",
"ParentId": "266559",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T17:08:01.943",
"Id": "266559",
"Score": "-2",
"Tags": [
"python"
],
"Title": "Cracking the Coding Interview URLify: encoding spaces as %20"
}
|
266559
|
<p>As a follow-up to <a href="https://codereview.stackexchange.com/q/266416/241620">this question</a>
that was an <a href="https://gcc.godbolt.org/z/s35885qos" rel="nofollow noreferrer">attempt</a>
to add basic translation capabilities in an old c++98 program
for the sake of the community, I'm posting here the first iteration
of my <a href="https://gcc.godbolt.org/z/dW6qG8ecE" rel="nofollow noreferrer">code</a>
after applying some of the points that emerged from the previous question:</p>
<pre><code>#include <string>
#include <iostream>
// Not nested in class definition to avoid class namespace in code
enum
{
TR_RELOAD=0,
TR_SAVE,
TR_SIZ
};
class PoorMansTranslations
{
private:
std::string i_tr[TR_SIZ]; // Actual translation strings
// Here to be near the enum, consistency is by hand!
typedef char tr_chars_t[TR_SIZ][16]; // Translation string tables with static linkage
static const tr_chars_t& resolve_lang(const std::string& lang) throw()
{
static const tr_chars_t tr_en =
{
"Reload", // TR_RELOAD
"Save" // TR_SAVE
};
static const tr_chars_t tr_it =
{
"Ricarica", // TR_RELOAD
"Salva" // TR_SAVE
};
static const tr_chars_t tr_es =
{
"Recargar", // TR_RELOAD
"Salvar", // TR_SAVE
};
static const tr_chars_t tr_fr =
{
"Recharger", // TR_RELOAD
"Enregistrer" // TR_SAVE
};
if(lang=="en") return tr_en;
else if(lang=="it") return tr_it;
else if(lang=="fr") return tr_fr;
else if(lang=="es") return tr_es;
return tr_en; // Fallback lang
}
public:
const std::string& operator[](const std::size_t idx) const throw() { return i_tr[idx]; }
void select_lang(const std::string& lang) throw()
{
const tr_chars_t& tr_arr = resolve_lang(lang);
// Constructing the strings on demand
for(int i=0; i<TR_SIZ; ++i) i_tr[i] = std::string(tr_arr[i]);
}
} tr;
int main()
{
std::string lang = "it"; // note: unknown at compile time
tr.select_lang(lang);
std::cout << tr[TR_RELOAD] << ", " << tr[TR_SAVE] << '\n';
lang = "bad";
tr.select_lang(lang);
std::cout << tr[TR_RELOAD] << ", " << tr[TR_SAVE] << '\n';
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<h1>Avoid hardcoding translation strings to 16 bytes</h1>\n<p>There's no need to set the size of the strings to 16 bytes, just store them as pointers to <code>const char</code> instead of arrays of <code>char</code>:</p>\n<pre><code>typedef const char *tr_chars_t[TR_SIZ];\n</code></pre>\n<h1>Store all languages in an array</h1>\n<p>For each language you have a separate variable holding the translations strings, and you have a long if-then-chain to find the right variable given the languages name. You can make the code more generic by storing all languages in an array, like so:</p>\n<pre><code>static const tr_chars_t &resolve_lang(const std::string &lang) throw()\n{\n static const struct {\n const char *lang;\n const tr_chars_t translations;\n } languages[] = {\n {\n "en", {\n "Reload", // TR_RELOAD\n "Save" // TR_SAVE\n }\n },\n {\n "it", {\n "Ricarica", // TR_RELOAD\n "Salva" // TR_SAVE\n }\n },\n ...\n };\n\n static const std::size_t n_languages = sizeof languages / sizeof * languages;\n\n for (std::size_t i = 0; i < n_languages; ++i) {\n if (lang == languages[i].lang) {\n return languages[i].translations;\n }\n }\n\n return languages[0].translations; // Fallback lang\n}\n</code></pre>\n<p>This way, when adding a language, you only have to add an entry to the array <code>languages[]</code>, and not change any other code.</p>\n<p>You could even improve it a bit by ensuring the languages are ordered alphabetically, so you can do a binary search.</p>\n<h1>Consider using STL algorithms</h1>\n<p>Copying the C strings in to the array of <code>std::string</code>s can be done with <a href=\"https://en.cppreference.com/w/cpp/algorithm/copy\" rel=\"nofollow noreferrer\"><code>std::copy()</code></a>:</p>\n<pre><code>void select_lang(const std::string &lang) throw()\n{\n const tr_chars_t &tr_arr = resolve_lang(lang);\n std::copy(tr_arr, tr_arr + TR_SIZ, i_tr);\n}\n</code></pre>\n<p>You could also use <code>std::find()</code> or <code>std::lower_bound()</code> to replace the for-loop in my version of <code>resolve_lang()</code>, but it's a bit awkward in C++98 since you can't use a lambda for the comparator.</p>\n<h1>Consider storing the translation strings in <code>std::string</code>s</h1>\n<p>Instead of storing the translation strings in arrays of regular C strings, you can also consider storing them in arrays of <code>std::string</code>s. The drawback is that they will all be initialized once at runtime, but then you can just return a reference to that array, instead of copying the C strings into <code>i_tr</code>. Which method is best depends on how many languages you want to support versus how often you switch languages in your code multiplied by the number of strings in a language.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T13:42:33.007",
"Id": "526690",
"Score": "0",
"body": "A compromise is to make an array of `string_view` which avoids copying the bytes but give the performance of knowing the actual length without scanning for the terminator. As I noted in my earlier answer, with C++98 you can include such a class as part of your project even if it's not in your copy of the standard library that's old enough to drink."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T14:07:05.980",
"Id": "526692",
"Score": "0",
"body": "I'll definitely apply the first points (not sure where post the code update), regarding storing all in `std::string` I think the advantage depends on how frequent is the switching between langs, in my use case it occurs once at start."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T21:20:34.013",
"Id": "527820",
"Score": "0",
"body": "Here's the [next version](https://gcc.godbolt.org/z/xWsrhWebz)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T21:43:23.477",
"Id": "527821",
"Score": "0",
"body": "If you want the next version reviewed, you're welcome to post it as a new question on CodeReview!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T21:12:48.657",
"Id": "266564",
"ParentId": "266561",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "266564",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T18:43:37.837",
"Id": "266561",
"Score": "1",
"Tags": [
"c++",
"strings",
"static",
"c++98"
],
"Title": "Improving poor man's translations mechanism in c++98 program (follow-up)"
}
|
266561
|
<p>I am a network engineer and started playing with Python as a way to supplement some downtime in the job. We have no automation at the company so I was playing around with making a GUI to run simple commands to our equipment and give the output in a separate window. The main window (root) stays active the whole time so that you can change the connected device, credentials, IP, etc which makes it "faster" to scout issues.</p>
<p>I never took any Python classes and each part of the code was picked up on the fly from different sources, but I picked up enough to figure out what I needed.</p>
<p>I don't really have a problem with the code other than scrollbars not working, but I know why so not a problem at the moment.</p>
<p>Since I have nobody on my team that can tell me if this code is good or bad I was curious to see if someone could just look at the code and tell me what they think.</p>
<pre><code>#Imported packages. You may need to run "pip install <package>" where <package> is the package listed below. If you are
#unsure how to install Python packages then try looking at instructions here:
# https://packaging.python.org/tutorials/installing-packages/#
from netmiko import (
ConnectHandler,
NetmikoTimeoutException,
NetmikoAuthenticationException,
)
from getpass import getpass
from tkinter import *
#Sets up the main window#
root = Tk()
root.title("Cisco Troubleshooter")
root.configure(background="black")
root.iconbitmap('cisco.ico')
def on_device_click(event):
"""function that gets called whenever entry is clicked"""
if device.get() == "Enter the IP/Hostname you want to connect to":
device.delete(0, "end") # delete all the text in the entry
device.insert(0, '') # Insert blank for user input
device.config(fg='black')
#Displays red text if the box is clicked on, not filled out, then exited#
def on_device_focusout(event):
if device.get() == '':
device.insert(0, "Enter the IP/Hostname you want to connect to")
device.config(fg="red")
def on_UN_click(event):
if UN.get() == "Enter your username":
UN.delete(0, "end") # delete all the text in the entry
UN.insert(0, '') # Insert blank for user input
UN.config(fg='black')
#Displays red text if the box is clicked on, not filled out, then exited#
def on_UN_focusout(event):
if UN.get() == '':
UN.insert(0, "Enter your username")
UN.config(fg="red")
def on_PW_click(event):
if PW.get() == "*":
PW.delete(0, "end") # delete all the text in the entry
PW.insert(0, '') # Insert blank for user input
PW.config(fg='black')
elif PW.get() == "Enter your password":
PW.delete(0, "end") # delete all the text in the entry
PW.insert(0, '') # Insert blank for user input
PW.config(fg='black')
#Displays red text if the box is clicked on, not filled out, then exited#
def on_PW_focusout(event):
if PW.get() == '':
PW.insert(0, "Enter your password")
PW.config(fg="red")
def on_IP_click(event):
if IP.get() == "Enter IP for commands":
IP.delete(0, "end") # delete all the text in the entry
IP.insert(0, '') # Insert blank for user input
IP.config(fg='black')
#Displays red text if the box is clicked on, not filled out, then exited#
def on_IP_focusout(event):
if IP.get() == '':
IP.insert(0, "Enter IP for commands")
IP.config(fg="green")
def on_INT_click(event):
if INT.get() == "Enter Int/MAC/VLAN for commands":
INT.delete(0, "end") # delete all the text in the entry
INT.insert(0, '') # Insert blank for user input
INT.config(fg='black')
#Displays red text if the box is clicked on, not filled out, then exited#
def on_INT_focusout(event):
if INT.get() == '':
INT.insert(0, "Enter Int/MAC/VLAN for commands")
INT.config(fg="green")
#Sets up the "show active calls" button payload#
def active_click():
try:
# Sets up the SSH payload#
cisco_payload = {
"device_type": "cisco_ios",
"host": device.get(),
"username": UN.get(),
"password": PW.get(),
"port": 22,
}
# Sets the SSH payload to a variable to be used for running commands#
ssh = ConnectHandler(**cisco_payload)
# Commands section for this button#
active = (ssh.send_command("sh call active voice comp"))
# Binds the commands being run into a variable so that they can be printed neatly#
results = (active)
# Prints the output in the Python window for QA purposes#
print(active)
# Disconnects from the SSH session#
ssh.disconnect()
# Sets up the new window once the button is clicked#
output = Toplevel(root)
output.title("Output Window")
output.iconbitmap('cisco.ico')
# Creates the scrollbar#
scroll = Scrollbar(output, orient=VERTICAL)
scroll.grid(row=0, column=1, sticky="nsew")
# Creates the section in the new window where the text will be printed then prints it#
label = Label(output, text=results, relief=SUNKEN, bg="black", fg="light green", justify=LEFT)
label.grid(row=0, column=0, sticky=NS)
# Handles error exceptions and prints out the error#
except(KeyError, KeyboardInterrupt, IndexError, NetmikoTimeoutException, NetmikoAuthenticationException) as error:
output = Toplevel(root)
output.title("Output Window")
output.iconbitmap('cisco.ico')
label = Label(output, text=error, relief=SUNKEN, bg="black", fg="light green")
label.grid(row=0, column=0, sticky=NSEW)
#Sets up the "show bgp summary" button payload#
def bgpsumm_click():
try:
# Sets up the SSH payload#
cisco_payload = {
"device_type": "cisco_ios",
"host": device.get(),
"username": UN.get(),
"password": PW.get(),
"port": 22,
}
# Sets the SSH payload to a variable to be used for running commands#
ssh = ConnectHandler(**cisco_payload)
# Commands section for this button#
bgpsumm = (ssh.send_command("sh bgp summ | beg Neigh"))
# Binds the commands being run into a variable so that they can be printed neatly#
results = (bgpsumm)
# Prints the output in the Python window for QA purposes#
print(bgpsumm)
# Disconnects from the SSH session#
ssh.disconnect()
# Sets up the new window once the button is clicked#
output = Toplevel(root)
output.title("Output Window")
output.iconbitmap('cisco.ico')
# Creates the scrollbar#
scroll = Scrollbar(output, orient=VERTICAL)
scroll.grid(row=0, column=1, sticky="nsew")
# Creates the section in the new window where the text will be printed then prints it#
label = Label(output, text=results, relief=SUNKEN, bg="black", fg="light green", justify=LEFT)
label.grid(row=0, column=0, sticky="nsew")
#Handles error exceptions and prints out the error#
except(KeyError, KeyboardInterrupt, IndexError, NetmikoTimeoutException, NetmikoAuthenticationException) as error:
output = Toplevel(root)
output.title("Output Window")
output.iconbitmap('cisco.ico')
label = Label(output, text=error, relief=SUNKEN, bg="black", fg="light green")
label.grid(row=0, column=0, sticky="nsew")
#Sets up the "show cdp neighbors" button payload#
def cdp_click():
try:
# Sets up the SSH payload#
cisco_payload = {
"device_type": "cisco_ios",
"host": device.get(),
"username": UN.get(),
"password": PW.get(),
"port": 22,
}
# Sets the SSH payload to a variable to be used for running commands#
ssh = ConnectHandler(**cisco_payload)
# Commands section for this button. Pulls any entries from the interface entry box#
if INT.get() == "Enter interface for commands":
cdp = (ssh.send_command("sh cdp neigh "))
else:
cd= ssh.send_command("sh cdp neigh " + INT.get())
# Binds the commands being run into a variable so that they can be printed neatly#
results = (cdp)
# Prints the output in the Python window for QA purposes#
print(cdp)
# Disconnects from the SSH session#
ssh.disconnect()
# Sets up the new window once the button is clicked#
output = Toplevel(root)
output.title("Output Window")
output.iconbitmap('cisco.ico')
# Creates the scrollbar#
scroll = Scrollbar(output, orient=VERTICAL)
scroll.grid(row=0, column=1, sticky="nsew")
# Creates the section in the new window where the text will be printed then prints it#
label = Label(output, text=results, relief=SUNKEN, bg="black", fg="#08bc08", justify=LEFT)
label.grid(row=0, column=0)
# Handles error exceptions and prints out the error#
except(KeyError, KeyboardInterrupt, IndexError, NetmikoTimeoutException, NetmikoAuthenticationException) as error:
output = Toplevel(root)
output.title("Output Window")
output.iconbitmap('cisco.ico')
label = Label(output, text=error, relief=SUNKEN, bg="black", fg="light green")
label.grid(row=0, column=0, sticky="nsew")
#Sets up the "show error-disabled" button payload#
def errdisable_click():
try:
# Sets up the SSH payload#
cisco_payload = {
"device_type": "cisco_ios",
"host": device.get(),
"username": UN.get(),
"password": PW.get(),
"port": 22,
}
# Sets the SSH payload to a variable to be used for running commands#
ssh = ConnectHandler(**cisco_payload)
# Commands section for this button#
errdisabled = (ssh.send_command("sh int status | i err"))
# Binds the commands being run into a variable so that they can be printed neatly#
results = (errdisabled)
# Prints the output in the Python window for QA purposes#
print(errdisabled)
# Disconnects from the SSH session#
ssh.disconnect()
# Sets up the new window once the button is clicked#
output = Toplevel(root)
output.title("Output Window")
output.iconbitmap('cisco.ico')
# Creates the scrollbar#
scroll = Scrollbar(output, orient=VERTICAL)
scroll.grid(row=0, column=1, sticky="nsew")
# Creates the section in the new window where the text will be printed then prints it#
label = Label(output, text=results, relief=SUNKEN, bg="black", fg="light green", justify=LEFT)
label.grid(row=0, column=0, sticky=NS)
# Handles error exceptions and prints out the error#
except(KeyError, KeyboardInterrupt, IndexError, NetmikoTimeoutException, NetmikoAuthenticationException) as error:
output = Toplevel(root)
output.title("Output Window")
output.iconbitmap('cisco.ico')
label = Label(output, text=error, relief=SUNKEN, bg="black", fg="light green")
label.grid(row=0, column=0, sticky=NSEW)
#Sets up the "show interfaces" button payload#
def showint_click():
try:
#Sets up the SSH payload#
cisco_payload = {
"device_type": "cisco_ios",
"host":device.get(),
"username": UN.get(),
"password": PW.get(),
"port": 22,
}
#Sets the SSH payload to a variable to be used for running commands#
ssh = ConnectHandler(**cisco_payload)
#Commands section for this button#
up = (ssh.send_command("sh ip int bri | i up"))
down = (ssh.send_command("sh ip int bri | i down"))
#Binds the commands being run into a variable so that they can be printed neatly#
results= ("Up Interfaces\n\n" + up + "\n\nDown Interfaces\n\n" + down + "\n")
#Prints the output in the Python window for QA purposes#
print("Up Interfaces\n\n" + up + "\n\nDown Interfaces\n\n" + down + "\n")
#Disconnects from the SSH session#
ssh.disconnect()
#Sets up the new window once the button is clicked#
output = Toplevel(root)
output.title("Output Window")
output.iconbitmap('cisco.ico')
#Creates the scrollbar#
scroll = Scrollbar(output, orient=VERTICAL)
scroll.grid(row=0, column=1, sticky="nsew")
# Creates the section in the new window where the text will be printed then prints it#
label = Label(output, text=results, relief=SUNKEN, bg="black", fg="light green", justify=LEFT)
label.grid(row=0, column=0, sticky=NS)
#Handles error exceptions and prints out the error#
except(KeyError, KeyboardInterrupt, IndexError, NetmikoTimeoutException, NetmikoAuthenticationException) as error:
output = Toplevel(root)
output.title("Output Window")
output.iconbitmap('cisco.ico')
label = Label(output, text=error, relief=SUNKEN)
label.grid(row=0, column=0, sticky=NSEW)
def iparp_click():
try:
#Sets up the SSH payload#
cisco_payload = {
"device_type": "cisco_ios",
"host":device.get(),
"username": UN.get(),
"password": PW.get(),
"port": 22,
}
#Sets the SSH payload to a variable to be used for running commands#
ssh = ConnectHandler(**cisco_payload)
#Commands section for this button#
if IP.get() == "Enter IP for commands":
iparp = (ssh.send_command("sh ip arp "))
else:
iparp = (ssh.send_command("sh ip arp " + IP.get()))
#Binds the commands being run into a variable so that they can be printed neatly#
results= (iparp)
#Prints the output in the Python window for QA purposes#
print(iparp)
#Disconnects from the SSH session#
ssh.disconnect()
#Sets up the new window once the button is clicked#
output = Toplevel(root)
output.title("Output Window")
output.iconbitmap('cisco.ico')
#Creates the scrollbar#
scroll = Scrollbar(output, orient=VERTICAL)
scroll.grid(row=0, column=1, sticky="nsew")
# Creates the section in the new window where the text will be printed then prints it#
label = Label(output, text=results, relief=SUNKEN, bg="black", fg="light green", justify=LEFT)
label.grid(row=0, column=0, sticky=NS)
#Handles error exceptions and prints out the error#
except(KeyError, KeyboardInterrupt, IndexError, NetmikoTimeoutException, NetmikoAuthenticationException) as error:
output = Toplevel(root)
output.title("Output Window")
output.iconbitmap('cisco.ico')
label = Label(output, text=error, relief=SUNKEN)
label.grid(row=0, column=0, sticky=NSEW)
#Sets up the "show isdn status" button payload#
def isdn_click():
try:
# Sets up the SSH payload#
cisco_payload = {
"device_type": "cisco_ios",
"host":device.get(),
"username": UN.get(),
"password": PW.get(),
"port": 22,
}
# Sets the SSH payload to a variable to be used for running commands#
ssh = ConnectHandler(**cisco_payload)
# Commands section for this button#
isdn = (ssh.send_command("sh isdn status"))
# Binds the commands being run into a variable so that they can be printed neatly#
results = (isdn)
# Prints the output in the Python window for QA purposes#
print(isdn)
# Disconnects from the SSH session#
ssh.disconnect()
# Sets up the new window once the button is clicked#
output = Toplevel(root)
output.title("Output Window")
output.iconbitmap('cisco.ico')
# Creates the scrollbar#
scroll = Scrollbar(output, orient=VERTICAL)
scroll.grid(row=0, column=1, sticky="nsew")
# Creates the section in the new window where the text will be printed then prints it#
label = Label(output, text=results, relief=SUNKEN, bg="black", fg="light green", justify=LEFT)
label.grid(row=0, column=0, sticky=NS)
#Handles error exceptions and prints out the error#
except(KeyError, KeyboardInterrupt, IndexError, NetmikoTimeoutException, NetmikoAuthenticationException) as error:
output = Toplevel(root)
output.title("Output Window")
output.iconbitmap('cisco.ico')
label = Label(output, text=error, relief=SUNKEN, bg="black", fg="light green")
label.grid(row=0, column=0, sticky="nsew")
#Sets up the "show mac address" button payload#
def mac_click():
try:
# Sets up the SSH payload#
cisco_payload = {
"device_type": "cisco_ios",
"host": device.get(),
"username": UN.get(),
"password": PW.get(),
"port": 22,
}
# Sets the SSH payload to a variable to be used for running commands#
ssh = ConnectHandler(**cisco_payload)
# Commands section for this button#
if INT.get() == "Enter Int/MAC/VLAN for commands":
mac = (ssh.send_command("show mac address-table"))
else:
mac = ssh.send_command("show mac address-table address " + INT.get())
# Binds the commands being run into a variable so that they can be printed neatly#
results = (mac)
# Prints the output in the Python window for QA purposes#
print(results)
# Disconnects from the SSH session#
ssh.disconnect()
# Sets up the new window once the button is clicked#
output = Toplevel(root)
output.title("Output Window")
output.iconbitmap('cisco.ico')
# Creates the scrollbar#
scroll = Scrollbar(output, orient=VERTICAL)
scroll.grid(row=0, column=1, sticky="nsew")
# Creates the section in the new window where the text will be printed then prints it#
label = Label(output, text=results, relief=SUNKEN, bg="black", fg="#08bc08", justify=LEFT)
label.grid(row=0, column=0)
# Handles error exceptions and prints out the error#
except(KeyError, KeyboardInterrupt, IndexError, NetmikoTimeoutException, NetmikoAuthenticationException) as error:
output = Toplevel(root)
output.title("Output Window")
output.iconbitmap('cisco.ico')
label = Label(output, text=error, relief=SUNKEN, bg="black", fg="light green")
label.grid(row=0, column=0, sticky="nsew")
#Sets up the "show temperature" button payload#
def temp_click():
try:
# Sets up the SSH payload#
cisco_payload = {
"device_type": "cisco_ios",
"host": device.get(),
"username": UN.get(),
"password": PW.get(),
"port": 22,
}
# Sets the SSH payload to a variable to be used for running commands#
ssh = ConnectHandler(**cisco_payload)
# Commands section for this button#
temp = (ssh.send_command("sh envi temp"))
# Binds the commands being run into a variable so that they can be printed neatly#
results = (temp)
# Prints the output in the Python window for QA purposes#
print(temp)
# Disconnects from the SSH session#
ssh.disconnect()
# Sets up the new window once the button is clicked#
output = Toplevel(root)
output.title("Output Window")
output.iconbitmap('cisco.ico')
# Creates the scrollbar#
scroll = Scrollbar(output, orient=VERTICAL)
scroll.grid(row=0, column=1, sticky="ns")
# Creates the section in the new window where the text will be printed then prints it#
label = Label(output, text=results, relief=SUNKEN, bg="black", fg="#08bc08", justify=LEFT)
label.grid(row=0, column=0)
# Handles error exceptions and prints out the error#
except(KeyError, KeyboardInterrupt, IndexError, NetmikoTimeoutException, NetmikoAuthenticationException) as error:
output = Toplevel(root)
output.title("Output Window")
output.iconbitmap('cisco.ico')
label = Label(output, text=error, relief=SUNKEN, bg="black", fg="light green")
label.grid(row=0, column=0, sticky="nsew")
#Sets up the "show uptime" button payload#
def uptime_click():
try:
# Sets up the SSH payload#
cisco_payload = {
"device_type": "cisco_ios",
"host": device.get(),
"username": UN.get(),
"password": PW.get(),
"port": 22,
}
# Sets the SSH payload to a variable to be used for running commands#
ssh = ConnectHandler(**cisco_payload)
# Commands section for this button#
uptime = (ssh.send_command("sh ver | i uptime"))
# Binds the commands being run into a variable so that they can be printed neatly#
results = (uptime)
# Prints the output in the Python window for QA purposes#
print(uptime)
# Disconnects from the SSH session#
ssh.disconnect()
# Sets up the new window once the button is clicked#
output = Toplevel(root)
output.title("Output Window")
output.iconbitmap('cisco.ico')
# Creates the scrollbar#
scroll = Scrollbar(output, orient=VERTICAL)
scroll.grid(row=0, column=1, sticky="ns")
# Creates the section in the new window where the text will be printed then prints it#
label = Label(output, text=results, relief=SUNKEN, bg="black", fg="#08bc08", justify=LEFT)
label.grid(row=0, column=0)
# Handles error exceptions and prints out the error#
except(KeyError, KeyboardInterrupt, IndexError, NetmikoTimeoutException, NetmikoAuthenticationException) as error:
output = Toplevel(root)
output.title("Output Window")
output.iconbitmap('cisco.ico')
label = Label(output, text=error, relief=SUNKEN, bg="black", fg="light green")
label.grid(row=0, column=0, sticky="nsew")
#Sets up the "show vlan" button payload#
def vlan_click():
try:
# Sets up the SSH payload#
cisco_payload = {
"device_type": "cisco_ios",
"host": device.get(),
"username": UN.get(),
"password": PW.get(),
"port": 22,
}
# Sets the SSH payload to a variable to be used for running commands#
ssh = ConnectHandler(**cisco_payload)
# Commands section for this button#
vlan = (ssh.send_command("sh vlan"))
# Binds the commands being run into a variable so that they can be printed neatly#
results = (vlan)
# Prints the output in the Python window for QA purposes#
print(vlan)
# Disconnects from the SSH session#
ssh.disconnect()
# Sets up the new window once the button is clicked#
output = Toplevel(root)
output.title("Output Window")
output.iconbitmap('cisco.ico')
# Creates the scrollbar#
scroll = Scrollbar(output, orient=VERTICAL)
scroll.grid(row=0, column=1, sticky="nsew")
# Creates the section in the new window where the text will be printed then prints it#
label = Label(output, text=results, relief=SUNKEN, bg="black", fg="#08bc08", justify=LEFT)
label.grid(row=0, column=0)
# Handles error exceptions and prints out the error#
except(KeyError, KeyboardInterrupt, IndexError, NetmikoTimeoutException, NetmikoAuthenticationException) as error:
output = Toplevel(root)
output.title("Output Window")
output.iconbitmap('cisco.ico')
label = Label(output, text=error, relief=SUNKEN, bg="black", fg="light green")
label.grid(row=0, column=0, sticky="nsew")
#Sets up the command to exit the program on button click#
def quit_click():
root.destroy()
#IP/Hostname entry field#
device = Entry(root, width=60, borderwidth=20, fg="black")
device.insert(0, "Enter the IP/Hostname you want to connect to")
device.bind("<FocusIn>", on_device_click)
device.bind("<FocusOut>", on_device_focusout)
device.grid(row=0, column=0, columnspan=2, sticky="nsew")
#Username entry field#
UN = Entry(root, width=60, borderwidth=20, fg="black")
UN.insert(0, "Enter your username")
UN.bind("<FocusIn>", on_UN_click)
UN.bind("<FocusOut>", on_UN_focusout)
UN.config(fg="gray")
UN.grid(row=1, column=0, columnspan=2, sticky="nsew")
#Password entry field#
PW = Entry(root, show="*", width=60, borderwidth=20, fg="black")
PW.insert(0, "*")
PW.bind("<FocusIn>", on_PW_click)
PW.bind("<FocusOut>", on_PW_focusout)
PW.config(fg="gray")
PW.grid(row=2, column=0, columnspan=2, sticky="nsew")
#IP for commands entry field#
IP = Entry(root, width=30, borderwidth=20, fg="black")
IP.insert(0, "Enter IP for commands")
IP.bind("<FocusIn>", on_IP_click)
IP.bind("<FocusOut>", on_IP_focusout)
IP.config(fg="gray")
IP.grid(row=3, column=0, sticky="nsew")
#Interface entry field#
INT = Entry(root, width=30, borderwidth=20, fg="black")
INT.insert(0, "Enter Int/MAC/VLAN for commands")
INT.bind("<FocusIn>", on_INT_click)
INT.bind("<FocusOut>", on_INT_focusout)
INT.config(fg="gray")
INT.grid(row=3, column=1, sticky="nsew")
#Creates the "show active calls" button#
active = Button(root, text="Show Active Calls", width=30, bg="#08bc08", pady=2, fg="black", borderwidth=10, command=active_click)
active.grid(row=4, column=0, sticky="nsew")
#Creates the "show bgp summary" button#
bgpsumm = Button(root, text="Show BGP Summary", width=30, bg="#08bc08", pady=2, fg="black", borderwidth=10, command=bgpsumm_click)
bgpsumm.grid(row=4, column=1, sticky="nsew")
#Creates the "show cdp neighbors" button#
cdp = Button(root, text="Show CDP neighbors", width=30, bg="#08bc08", pady=2, fg="black", borderwidth=10, command=cdp_click)
cdp.grid(row=5, column=0, sticky="nsew")
#Creates the "show error-disabled" button#
errdisable = Button(root, text="Show Err-Disabled Interfaces", width=30, bg="#08bc08", pady=2, fg="black", borderwidth=10, command=errdisable_click)
errdisable.grid(row=5, column=1, sticky="nsew")
#Creates the "show interfaces" button#
showint = Button(root, text="Show Interfaces", width=30, bg="#08bc08", pady=2, fg="black", borderwidth=10, command=showint_click)
showint.grid(row=6, column=0, sticky="nsew")
#"show ip arp" button"
isdn = Button(root, text="Show IP ARP", width=30, bg="#08bc08", pady=2, fg="black", borderwidth=10, command=iparp_click)
isdn.grid(row=6, column=1, sticky="nsew")
#"show isdn status" button"
isdn = Button(root, text="Show ISDN Status", width=30, bg="#08bc08", pady=2, fg="black", borderwidth=10, command=isdn_click)
isdn.grid(row=7, column=0, sticky="nsew")
#Creates the "show mac" button#
mac = Button(root, text="Show MAC Address", width=30, bg="#08bc08", pady=2, fg="black", borderwidth=10, command=mac_click)
mac.grid(row=7, column=1, sticky="nsew")
#Creates the "show temperature" button#
temp = Button(root, text="Show Temperature", width=30, bg="#08bc08", pady=2, fg="black", borderwidth=10, command=temp_click)
temp.grid(row=8, column=0, sticky="nsew")
#Creates the "show uptime" button#
uptime = Button(root, text="Show Uptime", width=30, bg="#08bc08", pady=2, fg="black", borderwidth=10, command=uptime_click)
uptime.grid(row=8, column=1, sticky="nsew")
#Creates the "show VLAN" button#
vlan = Button(root, text="Show VLAN", width=30, bg="#08bc08", pady=2, fg="black", borderwidth=10, command=vlan_click)
vlan.grid(row=9, column=0, sticky="nsew")
#Creates the "quit" button#
quit = Button(root, text="Quit", width=30, bg="red", fg="black", borderwidth=10, command=quit_click)
quit.grid(row=10, column=1, sticky="nsew")
#Row number buttons start at. Used for start of button auto re-size loop#
button_row_num = 4
#Creates button list#
button_list = [active, bgpsumm, cdp, errdisable, showint, isdn, temp, vlan, quit]
for button in button_list:
Grid.rowconfigure(root, button_row_num, weight=1)
Grid.columnconfigure(root, 0, weight=1)
Grid.columnconfigure(root, 1, weight=1)
button_row_num +=1
#Runs the app#
root.mainloop()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T20:50:34.743",
"Id": "526658",
"Score": "0",
"body": "Welcome to Code Review! I [changed the title](https://codereview.stackexchange.com/revisions/266563/2) 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. I also added the [tag:beginner] tag but if you feel you aren't a beginner anymore then feel free to remove it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T20:57:23.093",
"Id": "526660",
"Score": "1",
"body": "Thanks for having me and making the title more relevant.\n\nI will leave the beginner flag because I don't even think I am good enough to be a beginner right now :D"
}
] |
[
{
"body": "<p>Consider replacing this:</p>\n<pre><code>#Imported packages. You may need to run "pip install <package>" where <package> is the package listed below. If you are\n#unsure how to install Python packages then try looking at instructions here:\n# https://packaging.python.org/tutorials/installing-packages/#\n</code></pre>\n<p>with an actual <code>requirements.txt</code> consumable by <code>pip install -r</code>, and spelling out what your package requirements are. You can even drop a comment in there showing how to pass the file to <code>pip</code>; but your comment as it stands is less than helpful because it doesn't actually say what your requirements are.</p>\n<p>Try to remove <code>root</code> from the global namespace so that your code can be re-entrant. The most typical approach to this is to put it in a class. Likewise, nothing after <code>#IP/Hostname entry field#</code> should be left global.</p>\n<p>Does your program support entering the password (literally) <code>Enter your password</code>? I suspect not. You could get really fancy and have change tracing enabled to know when someone has entered their own text, but the easier and less surprising thing to do is to remove the placeholder text from the textbox and put it in a separate label.</p>\n<p>There's not really a point to forming the dictionary <code>cisco_payload</code>, since you only use it for one set of kwargs. Instead, just</p>\n<pre class=\"lang-py prettyprint-override\"><code>ssh = ConnectHandler(\n device_type='cisco_ios',\n host=device.get(),\n username=UN.get(),\n password=PW.get(),\n port=22,\n)\n</code></pre>\n<p>Also note that <code>UN</code> and <code>PW</code> should be neither capitalized nor abbreviated.</p>\n<p>Neither of these:</p>\n<pre><code> active = (ssh.send_command("sh call active voice comp"))\n results = (active)\n</code></pre>\n<p>should be parenthesized.</p>\n<p>This block:</p>\n<pre><code> # Sets the SSH payload to a variable to be used for running commands#\n ssh = ConnectHandler(**cisco_payload)\n\n # Commands section for this button#\n active = (ssh.send_command("sh call active voice comp"))\n\n # Binds the commands being run into a variable so that they can be printed neatly#\n results = (active)\n\n # Prints the output in the Python window for QA purposes#\n print(active)\n\n # Disconnects from the SSH session#\n ssh.disconnect()\n</code></pre>\n<p>should guarantee a disconnect:</p>\n<pre><code># Sets the SSH payload to a variable to be used for running commands#\nssh = ConnectHandler(**cisco_payload)\n \ntry:\n # Commands section for this button#\n active = (ssh.send_command("sh call active voice comp"))\n\n # Binds the commands being run into a variable so that they can be printed neatly#\n results = (active)\n\n # Prints the output in the Python window for QA purposes#\n print(active)\n\nfinally:\n # Disconnects from the SSH session#\n ssh.disconnect()\n</code></pre>\n<p>You should get out of the habit of adding a <code>#</code> suffix to all of your comments.</p>\n<p>There's a lot of repetition in your functions, for instance in your setup of a top-level output window like this:</p>\n<pre><code> # Handles error exceptions and prints out the error#\n except(KeyError, KeyboardInterrupt, IndexError, NetmikoTimeoutException, NetmikoAuthenticationException) as error:\n output = Toplevel(root)\n output.title("Output Window")\n output.iconbitmap('cisco.ico')\n\n label = Label(output, text=error, relief=SUNKEN, bg="black", fg="light green")\n label.grid(row=0, column=0, sticky="nsew")\n</code></pre>\n<p>If you want to make a generic handler that does the above for any callers, make a context manager:</p>\n<pre><code>@contextlib.contextmanager\ndef handle_and_output():\n try:\n yield\n except(KeyError, KeyboardInterrupt, IndexError, NetmikoTimeoutException, NetmikoAuthenticationException) as error:\n output = Toplevel(root)\n output.title("Output Window")\n output.iconbitmap('cisco.ico')\n\n label = Label(output, text=error, relief=SUNKEN, bg="black", fg="light green")\n label.grid(row=0, column=0, sticky="nsew")\n\n# ...\n\nwith handle_and_output():\n # do something risky\n</code></pre>\n<p>However, repeating the creation of a top-level window seems suspicious, and there should probably just be one instance whose reference you reuse, setting its label text.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T08:13:18.650",
"Id": "526674",
"Score": "1",
"body": "+1 Biggest problem with this code is that it's unnecessarily long. Repetitive code is bad because it's harder to read (longer and less meaningful), harder to change (multiple places need updated), and more error-prone (easy to update one place and forget others, for example). A common programming principle is: Don't Repeat Yourself. It's a reasonable goal to have no blocks of 2+ lines repeated or nearly-repeated, maybe even 1 line."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T12:46:30.273",
"Id": "526684",
"Score": "1",
"body": "Thank you both for your advice. I am going through the script and trying to make each of the changes suggested. I ain't bright enough to call functions in functions yet, but will work on making it happen.\n\nI agree the code is unnecessarily long and needs a trim. It made sense for me at the time to copy and adjust what I already had working as I was the only one modifying anything.\n\nThis script has a long way to go and you both have given me the advice needed to make it better."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T00:04:50.943",
"Id": "266568",
"ParentId": "266563",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "266568",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T20:46:05.657",
"Id": "266563",
"Score": "5",
"Tags": [
"python",
"beginner"
],
"Title": "Cisco equipment troubleshooter tool"
}
|
266563
|
<p>I'm in no way a skilled developer (or even a developer at that!) but I did want to take a go at writing a script that fetched one endpoint's data, extracted some data, sent if off to be geocoded, then saved both the original (with geocodes) and the geocoded data to file. On subsequent requests, it would look up the geocoded data on file to check if anything matched, and pull data from there, otherwise trigger the fetch request again.</p>
<p>I think it works - at least it's been working from what I can tell but I'd love a review (or improvement if that's your thing) :)</p>
<pre class="lang-js prettyprint-override"><code>#!/usr/bin/env node
'use strict';
//
// MARK: - modules
//
const fs = require('fs');
const fetch = require('node-fetch');
//
// MARK: create the variables / constants
//
// get the command line arguments
const args = (function(argv) {
// remove `node` and `script` name
argv = argv.slice(2);
// returned object
var args = {};
var argName, argValue;
// loop through each argument
argv.forEach(function(arg, index) {
// seperate argument, for a key/value return
arg = arg.split('=');
// retrieve the argument name
argName = arg[0];
// remove "--" or "-"
if (argName.indexOf('-') === 0) {
argName = argName.slice(
argName.slice(0, 2).lastIndexOf('-') + 1
);
}
// associate defined value or initialize it to "true" state
argValue = (arg.length === 2) ?
// check if argument is valid number
parseFloat(arg[1]).toString() === arg[1]
?
+arg[1]: arg[1]
:
true;
// finally add the argument to the args set
args[argName] = argValue;
});
return args;
})(process.argv);
// api key checks
const apiKey = function() {
// api not declared
if (!args.api) {
return 1;
}
// declared but empty
if (args.api === true) {
return 2;
}
// all good
if (args.api && args.api !== true) {
return args.api;
}
}(args);
//
// MARK: - check the files and directories we need
//
const req = (() => {
// where we store things
const directory = './docs';
const datavic = `${ directory }/datavic.json`;
const database = `./database.json`;
// checks and creation
if (!fs.existsSync(directory)) {
fs.mkdirSync(directory);
}
// array of items
return {
dir: directory,
api: datavic,
db: database
}
})();
//
// MARK: - the script initialiser
//
function init() {
console.time();
fetchExposures();
console.timeEnd();
}
//
// MARK: - 1. fetch the data from datavic
//
function fetchExposures() {
// api check
if (apiKey === 1) {
return console.error(
'[x] Exiting: API argument not declared!'
);
}
if (apiKey === 2) {
return console.error(
'[x] Exiting: API key not provided!'
);
}
// url: Data Victoria API
const url = new URL(
'https://discover.data.vic.gov.au/api/3/action/datastore_search'
);
// url: parameters
url.searchParams.append(
'resource_id', 'afb52611-6061-4a2b-9110-74c920bede77'
);
url.searchParams.append(
'limit', '10000'
);
// fetch the data
fetch(url)
.then(res => res.json())
.then(async data => {
// send off data to be checked against database
const valid = await validateData(data);
// send off data to be checked against database
const database = await checkDatabase(valid);
// fetch the coordinates
const coordinates = await fetchCoordinates(database);
// add the coordinates to api file
const api = await addCoordinates(data, coordinates);
// write items to file
await writeFiles(api, coordinates);
})
.catch(err => {
console.error(`[x] Error: ${ err }`);
});
}
//
// MARK: - 2. remove the bad characters
//
function validateData(input) {
const sanitised = JSON.stringify(input, null, 2)
.replace(/\\t/g, '')
.replace(/\\r/g, '')
.replace(/\\n/g, '')
.replace(/\\v/g, '')
.replace(/\\h/g, '');
return JSON.parse(sanitised);
}
//
// MARK: - 3. check if any of the results are in the database
//
function checkDatabase(input) {
// 3a. exlude any that have null address or postcode
const inputNoNull = input.result.records.filter(item => {
if (!(item.Site_streetaddress === null ||
item.Site_postcode === null)) {
return item
}
})
// -- select only certain fields
.map(item => ({
Suburb: item.Suburb,
Site_streetaddress: item.Site_streetaddress,
Site_state: item.Site_state,
Site_postcode: item.Site_postcode
}))
// -- sort by ID
.sort((a, b) => {
return a._id - b._id;
});
// -- get the unique data
const data = [...new Set(
inputNoNull.map(item1 =>
item1.Suburb +
item1.Site_streetaddress +
item1.Site_state +
item1.Site_postcode
)
)].map(
item1 => inputNoNull.find(
item2 =>
item2.Suburb +
item2.Site_streetaddress +
item2.Site_state +
item2.Site_postcode ==
item1
)
);
// -- read the database
const db = fs.readFileSync(req.db);
const database = db ? JSON.parse(db) : {};
// append new items
const mergeJSON = ((file1, file2) =>
Object.values([...file1, ...file2]
.reduce((left, right) => {
const key = `${right.Suburb} ${right.Site_streetaddress} ${right.Site_state} ${right.Site_postcode}`;
left[key] = left[key] || right;
return left;
}, {})
)
);
// return it
return mergeJSON(database, data);
}
//
// MARK: - 4. loop all items in database, fetch the coordinates
//
async function fetchCoordinates(input) {
let geocodedSites = [];
// loop over the locations
for (let x = 0; x < input.length; x++) {
try {
const result = await getGeocode(input[x]);
geocodedSites.push(result);
} catch (err) {
console.log(`[x] Error: ${ err }`);
}
}
// return it
return geocodedSites;
}
//
// MARK: - 5. re-check the results are in the database
//
function addCoordinates(data, coordinates) {
const dataapi = data.result.records;
let arr = [];
// loop over the locations
for (let x = 0; x < dataapi.length; x++) {
coordinates.filter(item2 => {
if (dataapi[x].Suburb === item2.Suburb &&
dataapi[x].Site_streetaddress === item2.Site_streetaddress &&
dataapi[x].Site_state === item2.Site_state &&
dataapi[x].Site_postcode === item2.Site_postcode
) {
// -- append the coordinates to the items
const fulldata = {
...dataapi[x],
latitude: item2.latitude,
longitude: item2.longitude
}
arr.push(fulldata);
}
});
}
// return it
return arr;
}
//
// MARK: - 6. write files to system
//
function writeFiles(file1, file2) {
// stringify the inputs
const stringFile1 = JSON.stringify(file1, undefined, 2);
const stringFile2 = JSON.stringify(file2, undefined, 2);
// write them to disk
fs.writeFileSync(req.api, stringFile1);
fs.writeFileSync(req.db, stringFile2);
}
//
// MARK: - function: get the coordinates
//
async function getGeocode(site) {
// build the address
const query = `${site.Site_streetaddress} ${site.Suburb } ${site.Site_postcode } ${site.Site_state} Australia`;
// 1. skip any with existing coordinates
if (site.latitude && site.longitude || site.skip) {
console.error(`[✔] Skipping: ${ query }`);
return Promise.resolve(site);
}
// 2. fetch only missing items
console.log(`[⦿] Geocoding: ${ query }`);
// url: Data Victoria API
const url = new URL(
'http://api.positionstack.com/v1/forward'
);
// url: parameters
url.searchParams.append(
'access_key', apiKey
);
url.searchParams.append(
'region', 'Victoria'
);
url.searchParams.append(
'country', 'AU'
);
url.searchParams.append(
'limit', '1'
);
// build the search query
url.searchParams.append(
'query', query
)
// fetch the data
return fetch(url)
.then(res => res.json())
.then(data => {
const latitude = data.data[0].latitude;
const longitude = data.data[0].longitude;
const label = data.data[0].label;
const confidence = data.data[0].confidence;
return {
...site,
confidence,
latitude,
longitude,
label
}
})
.catch(err => {
console.log(` [x] Failed: ${ query }`);
return {...site,
skip: true
}
});
}
//
// MARK: - success: if we got to here
//
init();
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-08-31T22:57:00.700",
"Id": "266567",
"Score": "3",
"Tags": [
"javascript",
"node.js",
"json"
],
"Title": "Fetching data from endpoint, retrieving coordinates, then merging into an output"
}
|
266567
|
<p>I have this program in <a href="https://github.com/coderodde/ds4mac" rel="nofollow noreferrer">GitHub</a>. It is used for switching to directories via custom tags. Here is the main bash script:</p>
<pre><code>out_file=$(mktemp)
~/.ds/ds_engine $@ > $out_file
command_type=$(head -n 1 $out_file)
if [ $# -eq 0 ]; then
next_path=$(tail -n 1 $out_file)
~/.ds/ds_engine --update-previous $(pwd)
cd $next_path
else
if [ "$command_type" == "switch_directory" ]; then
next_path=$(tail -n 1 $out_file)
if [ ! -d "$next_path" ]; then
echo 2> "Directory \"$next_path\" does not exist."
exit 1
fi
~/.ds/ds_engine --update-previous $(pwd)
cd $next_path
elif [ "$command_type" == "show_tag_entry_list" ]; then
tail -n +2 $out_file
else
echo "Unknown command: $command_type"
fi
fi
rm $out_file
</code></pre>
<h2>See also</h2>
<ol>
<li>The <a href="https://codereview.stackexchange.com/questions/266572/ds4mac-directory-switcher-for-macos-linux-the-installer-script">installer script</a></li>
<li>The <a href="https://codereview.stackexchange.com/questions/266571/ds4mac-directory-switcher-for-macos-linux-the-tag-engine">tag engine</a></li>
</ol>
<h2>Critique request</h2>
<p>Please, tell me anything that comes to mind. ^^</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T02:04:25.253",
"Id": "266569",
"Score": "0",
"Tags": [
"bash",
"console"
],
"Title": "ds4mac - directory switcher for macOS/Linux: the script"
}
|
266569
|
<p>(See the <a href="https://codereview.stackexchange.com/questions/266541/a-simple-java-integer-hash-set">previous version</a>.)</p>
<p>(See the <a href="https://codereview.stackexchange.com/questions/267614/a-simple-java-integer-integer-hash-set-follow-up-2">next version</a>.)</p>
<p>After incorporating changes in the previous post, I came up with this implementation. However, I left hashing as it is.</p>
<p><strong><code>com.github.coderodde.util.IntHashSet</code>:</strong></p>
<pre><code>package com.github.coderodde.util;
/**
* This class implements a simple hash set for non-negative {@code int} values.
* It is used in the {@link com.github.coderodde.util.LinkedList} in order to
* keep track of nodes that are being pointed to by fingers.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Aug 29, 2021)
* @since 1.6 (Aug 29, 2021)
*/
public class IntHashSet {
private static final int INITIAL_CAPACITY = 8;
private static final float MAXIMUM_LOAD_FACTOR = 0.75f;
private static final class IntHashTableCollisionChainNode {
IntHashTableCollisionChainNode next;
int integer;
IntHashTableCollisionChainNode(
int integer,
IntHashTableCollisionChainNode next) {
this.integer = integer;
this.next = next;
}
@Override
public String toString() {
return "Chain node, integer = " + integer;
}
}
private IntHashTableCollisionChainNode[] table =
new IntHashTableCollisionChainNode[INITIAL_CAPACITY];
private int size = 0;
private int mask = INITIAL_CAPACITY - 1;
@Override
public String toString() {
return "size = " + size;
}
public void add(int integer) {
if (contains(integer)) {
return;
}
size++;
if (shouldExpand())
expand();
final int targetCollisionChainIndex = integer & mask;
final IntHashTableCollisionChainNode newNode =
new IntHashTableCollisionChainNode(
integer,
table[targetCollisionChainIndex]);
newNode.next = table[targetCollisionChainIndex];
table[targetCollisionChainIndex] = newNode;
}
public boolean contains(int integer) {
final int collisionChainIndex = integer & mask;
IntHashTableCollisionChainNode node = table[collisionChainIndex];
while (node != null) {
if (node.integer == integer) {
return true;
}
node = node.next;
}
return false;
}
public void remove(int integer) {
if (!contains(integer)) {
return;
}
size--;
if (shouldContract())
contract();
final int targetCollisionChainIndex = integer & mask;
IntHashTableCollisionChainNode current =
table[targetCollisionChainIndex];
IntHashTableCollisionChainNode previous = null;
while (current != null) {
IntHashTableCollisionChainNode next = current.next;
if (current.integer == integer) {
if (previous == null) {
table[targetCollisionChainIndex] = next;
} else {
previous.next = next;
}
return;
}
previous = current;
current = next;
}
}
public void clear() {
size = 0;
table = new IntHashTableCollisionChainNode[INITIAL_CAPACITY];
mask = table.length - 1;
}
// Keep add(int) an amortized O(1)
private boolean shouldExpand() {
return size > table.length * MAXIMUM_LOAD_FACTOR;
}
// Keep remove(int) an amortized O(1)
private boolean shouldContract() {
if (table.length == INITIAL_CAPACITY) {
return false;
}
final int maxCurrentQuota = (int)(table.length * MAXIMUM_LOAD_FACTOR);
final int minCurrentQuota = maxCurrentQuota / 4;
return size < minCurrentQuota;
}
private void expand() {
IntHashTableCollisionChainNode[] newTable =
new IntHashTableCollisionChainNode[table.length * 2];
rehash(newTable);
table = newTable;
mask = table.length - 1;
}
private void contract() {
IntHashTableCollisionChainNode[] newTable =
new IntHashTableCollisionChainNode[table.length / 4];
rehash(newTable);
table = newTable;
mask = table.length - 1;
}
private void rehash(IntHashTableCollisionChainNode[] newTable) {
for (IntHashTableCollisionChainNode node : table) {
while (node != null) {
final IntHashTableCollisionChainNode next = node.next;
final int rehashedIndex = getHashValue(node.integer, newTable);
node.next = newTable[rehashedIndex];
newTable[rehashedIndex] = node;
node = next;
}
}
}
private static int getHashValue(
int integer,
IntHashTableCollisionChainNode[] newTable) {
return integer & (newTable.length - 1);
}
}
</code></pre>
<p><strong><code>com.github.coderodde.util.IntHashSetTest</code>:</strong></p>
<pre><code>package com.github.coderodde.util;
import java.util.Random;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
public class IntHashSetTest {
private final IntHashSet set = new IntHashSet();
@Before
public void beforeTest() {
set.clear();
}
@Test
public void removeBug() {
for (int i = 0; i < 9; i++)
set.add(i);
for (int i = 0; i < 9; i++)
set.remove(i);
}
@Test
public void removeFirstMiddleLast() {
// All three ints will end up in the same collision chain:
set.add(1); // 0b00001
set.add(9); // 0b01001
set.add(17); // 0b10001
assertTrue(set.contains(1));
assertTrue(set.contains(9));
assertTrue(set.contains(17));
set.remove(1);
assertFalse(set.contains(1));
assertTrue(set.contains(9));
assertTrue(set.contains(17));
set.remove(17);
assertFalse(set.contains(1));
assertTrue(set.contains(9));
assertFalse(set.contains(17));
set.remove(9);
assertFalse(set.contains(1));
assertFalse(set.contains(9));
assertFalse(set.contains(17));
}
@Test
public void add() {
for (int i = 0; i < 500; i++) {
set.add(i);
}
for (int i = 0; i < 500; i++) {
assertTrue(set.contains(i));
}
for (int i = 500; i < 1_000; i++) {
assertFalse(set.contains(i));
}
for (int i = 450; i < 550; i++) {
set.remove(i);
}
for (int i = 450; i < 1_000; i++) {
assertFalse(set.contains(i));
}
for (int i = 0; i < 450; i++) {
assertTrue(set.contains(i));
}
}
@Test
public void contains() {
set.add(10);
set.add(20);
set.add(30);
for (int i = 1; i < 40; i++) {
if (i % 10 == 0) {
assertTrue(set.contains(i));
} else {
assertFalse(set.contains(i));
}
}
}
@Test
public void remove() {
set.add(1);
set.add(2);
set.add(3);
set.add(4);
set.add(5);
set.remove(2);
set.remove(4);
set.add(2);
assertFalse(set.contains(4));
assertTrue(set.contains(1));
assertTrue(set.contains(2));
assertTrue(set.contains(3));
assertTrue(set.contains(5));
}
@Test
public void clear() {
for (int i = 0; i < 100; i++) {
set.add(i);
}
for (int i = 0; i < 100; i++) {
assertTrue(set.contains(i));
}
set.clear();
for (int i = 0; i < 100; i++) {
assertFalse(set.contains(i));
}
}
@Test
public void bruteForceAdd() {
long seed = System.currentTimeMillis();
System.out.println(
"--- IntHashSetTest.bruteForceAdd: seed = " + seed + " ---");
Random random = new Random(seed);
int[] data = new int[10_000];
for (int i = 0; i < data.length; i++) {
int datum = random.nextInt(5_000);
data[i] = datum;
set.add(datum);
}
for (int i = 0; i < data.length; i++) {
assertTrue(set.contains(data[i]));
}
}
@Test
public void bruteForceRemove() {
long seed = System.currentTimeMillis();
System.out.println(
"--- IntHashSetTest.bruteForceRemove: seed = " + seed + " ---");
Random random = new Random(seed);
int[] data = new int[10_000];
for (int i = 0; i < data.length; i++) {
int datum = random.nextInt(5_000);
data[i] = datum;
set.add(datum);
}
shuffle(data, random);
for (int i = 0; i < data.length; i++) {
int datum = data[i];
if (set.contains(datum)) {
set.remove(datum);
}
assertFalse(set.contains(datum));
}
}
private static void shuffle(int[] data, Random random) {
for (int i = data.length - 1; i > 0; --i) {
final int j = random.nextInt(i + 1);
swap(data, i, j);
}
}
private static void swap(int[] data, int i, int j) {
int tmp = data[i];
data[i] = data[j];
data[j] = tmp;
}
}
</code></pre>
<h2>Critique request</h2>
<p>Please, tell me, is there anything to improve?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T03:06:25.363",
"Id": "266570",
"Score": "1",
"Tags": [
"java",
"unit-testing",
"integer",
"set",
"hash"
],
"Title": "A simple Java integer hash set - follow-up"
}
|
266570
|
<p>I have <a href="https://github.com/coderodde/ds4mac" rel="nofollow noreferrer">this program in GitHub</a>. It is used for switching to directories via custom tags. Here is the tag engine:</p>
<p><strong><code>com::github::coderodde::ds4mac::DirectoryTagEntry.h</code>:</strong></p>
<pre><code>//// ///////////////////////////////////////////// ////
// Created by Rodion "rodde" Efremov on 19.11.2020. //
//// ////////////////////////////////////////////// ////
#ifndef COM_GITHUB_CODERODDE_DS4MAC_DIRECTORY_TAG_ENTRY_H
#define COM_GITHUB_CODERODDE_DS4MAC_DIRECTORY_TAG_ENTRY_H
#include <fstream>
#include <iostream>
#include <string>
namespace com::github::coderodde::ds4mac {
class DirectoryTagEntry {
private:
std::string tagName;
std::string directoryName;
public:
DirectoryTagEntry(std::string tagName, std::string directoryName);
const std::string& getTagName() const;
const std::string& getDirectoryName() const;
void setTagName(const std::string& newTagName);
void setDirectoryName(const std::string& newDirectoryName);
size_t getLevenshteinDistance(std::string str) const;
friend void operator>>(std::ifstream& ifs, DirectoryTagEntry& dte) {
std::string readTagName;
std::string readDirectoryName;
std::getline(ifs, readDirectoryName);
dte.setTagName(readTagName);
dte.setDirectoryName(readDirectoryName);
}
friend void operator<<(std::ofstream& ofs, const DirectoryTagEntry& dte) {
ofs << dte.getTagName() << " " << dte.getDirectoryName();
}
static struct {
bool operator()(DirectoryTagEntry const& a, DirectoryTagEntry const& b) {
return a.getTagName() < b.getTagName();
}
} tagComparator;
static struct {
bool operator()(DirectoryTagEntry const& a, DirectoryTagEntry const& b) {
return a.getDirectoryName() < b.getDirectoryName();
}
} directoryComparator;
};
}
#endif // COM_GITHUB_CODERODDE_DS4MAC_DIRECTORY_TAG_ENTRY_H
</code></pre>
<p><strong><code>com::github::coderodde::ds4mac::DirectoryTagEntry.cpp</code>:</strong></p>
<pre><code>//// ////////////////////////////////////////////// ////
// Created by Rodion "rodde" Efremov on 19.11.2020. //
//// ////////////////////////////////////////////// ////
#include "DirectoryTagEntry.h"
#include <utility>
#include <vector>
namespace com::github::coderodde::ds4mac {
using std::size_t;
DirectoryTagEntry::DirectoryTagEntry(
std::string tagName_,
std::string directoryName_) :
tagName{std::move(tagName_)},
directoryName{std::move(directoryName_)} {}
const std::string& DirectoryTagEntry::getTagName() const {
return tagName;
}
const std::string& DirectoryTagEntry::getDirectoryName() const {
return directoryName;
}
void DirectoryTagEntry::setTagName(const std::string& newTagName) {
tagName = newTagName;
}
void DirectoryTagEntry::setDirectoryName(const std::string& newDirectoryName) {
directoryName = newDirectoryName;
}
size_t DirectoryTagEntry::getLevenshteinDistance(const std::string str) const {
const size_t len1 = str.length() + 1;
const size_t len2 = tagName.length() + 1;
std::vector<std::vector<size_t>> distanceMatrix(len1);
for (size_t i = 0; i < len1; i++) {
std::vector<size_t> row(len2);
distanceMatrix[i] = row;
}
for (size_t i = 1; i < len1; i++) {
distanceMatrix[i][0] = i;
}
for (size_t i = 1; i < len2; i++) {
distanceMatrix[0][i] = i;
}
for (size_t i1 = 1; i1 < len1; i1++) {
for (size_t i2 = 1; i2 < len2; i2++) {
size_t cost = (str[i1 - 1] == tagName[i2 - 1] ? 0 : 1);
distanceMatrix[i1][i2] =
std::min(
std::min(distanceMatrix[i1 - 1][i2] + 1,
distanceMatrix[i1][i2 - 1] + 1),
distanceMatrix[i1 - 1][i2 - 1] + cost);
}
}
return distanceMatrix[len1 - 1][len2 - 1];
}
}
</code></pre>
<p><strong><code>com::github::coderodde::ds4mac::DirectoryTagEntryList.h</code>:</strong></p>
<pre><code>//// ///////////////////////////////////////////// ////
// Created by Rodion "rodde" Efremov on 20.11.2020. //
//// ////////////////////////////////////////////// ////
#ifndef COM_GITHUB_CODERODDE_DS4MAC_DIRECTORY_TAG_ENTRY_LIST_H
#define COM_GITHUB_CODERODDE_DS4MAC_DIRECTORY_TAG_ENTRY_LIST_H
#include "DirectoryTagEntry.h"
#include <vector>
namespace com::github::coderodde::ds4mac {
class DirectoryTagEntryList {
private:
std::vector<DirectoryTagEntry> entries;
public:
const size_t size() const;
DirectoryTagEntryList& operator<<(DirectoryTagEntry const& directoryTagEntry);
DirectoryTagEntry at(size_t index) const;
DirectoryTagEntry* operator[](std::string const& targetDirectoryName);
void operator<<(std::ifstream& ifs);
void sortByTags();
void sortByDirectories();
void listTags();
void listTagsAndDirectories();
friend void operator>>(std::ifstream&, DirectoryTagEntryList&);
friend void operator>>(DirectoryTagEntryList const&,
std::ofstream&);
};
}
#endif // COM_GITHUB_CODERODDE_DS4MAC_DIRECTORY_TAG_ENTRY_LIST_H
</code></pre>
<p><strong><code>com::github::coderodde::ds4mac::DirectoryTagEntryList.cpp</code>:</strong></p>
<pre><code>//// ////////////////////////////////////////////// ////
// Created by Rodion "rodde" Efremov on 20.11.2020. //
//// ////////////////////////////////////////////// ////
#include "DirectoryTagEntry.h"
#include "DirectoryTagEntryList.h"
#include <algorithm>
#include <limits>
#include <string>
//#include <linux/limits.h>
using com::github::coderodde::ds4mac::DirectoryTagEntry;
using std::getline;
using std::string;
namespace com::github::coderodde::ds4mac {
const size_t DirectoryTagEntryList::size() const {
return entries.size();
}
DirectoryTagEntryList& DirectoryTagEntryList::operator<<(
const DirectoryTagEntry &directoryTagEntry) {
entries.push_back(directoryTagEntry);
return *this;
}
DirectoryTagEntry DirectoryTagEntryList::at(size_t index) const {
return entries.at(index);
}
DirectoryTagEntry* DirectoryTagEntryList::operator[](
const std::string& targetDirectoryName) {
DirectoryTagEntry* ptrBestDirectoryEntry;
size_t bestLevenshteinDistance = std::numeric_limits<size_t>::max();
for (DirectoryTagEntry& dte : entries) {
size_t levenshteinDistance = dte.getLevenshteinDistance(targetDirectoryName);
if (levenshteinDistance == 0) {
return &dte;
}
if (bestLevenshteinDistance > levenshteinDistance) {
bestLevenshteinDistance = levenshteinDistance;
ptrBestDirectoryEntry = &dte;
}
}
return ptrBestDirectoryEntry;
}
void DirectoryTagEntryList::operator<<(std::ifstream& ifs) {
using std::string;
}
void DirectoryTagEntryList::sortByTags() {
std::stable_sort(entries.begin(), entries.end(), DirectoryTagEntry::tagComparator);
}
void DirectoryTagEntryList::sortByDirectories() {
std::stable_sort(entries.begin(), entries.end(), DirectoryTagEntry::directoryComparator);
}
// trim from start (in place)
static inline void ltrim(std::string &s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) {
return !std::isspace(ch);
}));
}
// trim from end (in place)
static inline void rtrim(std::string &s) {
s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) {
return !std::isspace(ch);
}).base(), s.end());
}
// trim from both ends (in place)
static inline void trim(std::string &s) {
ltrim(s);
rtrim(s);
}
void operator>>(
std::ifstream& ifs,
DirectoryTagEntryList& directoryTagEntryList) {
while (ifs.good() && !ifs.eof()) {
string tag;
ifs >> tag;
trim(tag);
// Grab the rest of the line.
// We need this isntead of >> in order to obtain
// the space characters in the directory names.
string dir;
getline(ifs, dir);
trim(dir);
DirectoryTagEntry newDirectoryEntry(tag, dir);
directoryTagEntryList << newDirectoryEntry;
}
}
void operator>>(DirectoryTagEntryList const& directoryTagEntryList,
std::ofstream& ofs) {
for (size_t i = 0, sz = directoryTagEntryList.size();
i < sz;
i++) {
DirectoryTagEntry const& dte = directoryTagEntryList.at(i);
ofs << dte.getTagName() << " " << dte.getDirectoryName() << "\n";
}
}
}
</code></pre>
<p><strong><code>main.cpp</code>:</strong></p>
<pre><code>#include "DirectoryTagEntry.h"
#include "DirectoryTagEntryList.h"
#include <iomanip>
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
#include <cstring>
#include <pwd.h>
#include <unistd.h>
#include <vector>
using com::github::coderodde::ds4mac::DirectoryTagEntry;
using com::github::coderodde::ds4mac::DirectoryTagEntryList;
using std::cerr;
using std::cout;
using std::ifstream;
using std::ofstream;
using std::setw;
using std::string;
//// ///////////////////
// Operation names: //
/////////////////// ////
const string OPERATION_SWITCH_DIRECTORY = "switch_directory";
const string OPERATION_DESCRIPTOR_SHOW_TAG_ENTRY_LIST =
"show_tag_entry_list";
//// /////////////////
// All the flags: //
///////////////// ////
const string FLAG_LIST_TAGS = "-l";
const string FLAG_LIST_BOTH = "-L";
const string FLAG_LIST_TAGS_SORTED = "-s";
const string FLAG_LIST_BOTH_SORTED = "-S";
const string FLAG_LIST_BOTH_SORTED_DIRS = "-d";
const string FLAG_UPDATE_PREVIOUS = "--update-previous";
const string PREV_TAG_NAME = "__dt_previous";
// The path to the tag file, relative to the home directory:
const string RELATIVE_TAG_FILE_PATH = "/.ds/tags";
//// ///////////////////////////////////////////
// Returns the entire path to the tag file. //
/////////////////////////////////////////// ////
static const string getTagFilePath() {
char* c_home_directory = getpwuid(getuid())->pw_dir;
size_t str_len = strlen(c_home_directory) + 1;
char* c_home_directory_copy = (char*) std::malloc(str_len);
std::strncpy(c_home_directory_copy,
c_home_directory,
str_len);
string path(c_home_directory_copy);
return path += RELATIVE_TAG_FILE_PATH;
}
//// /////////////////////////////////////////
// Returns the current working directory: //
///////////////////////////////////////// ////
static string getCurrentWorkingDirectory() {
char* working_dir = new char[PATH_MAX];
working_dir = getcwd(working_dir, PATH_MAX);
string rv = working_dir;
delete[] working_dir;
return rv;
}
//// //////////////////////////////////////
// Returns the maximum length of tags: //
////////////////////////////////////// ////
static const size_t getMaximumTagLength(DirectoryTagEntryList const& dtel) {
size_t maximumTagLength = 0;
for (size_t index = 0, sz = dtel.size(); index < sz; index++) {
maximumTagLength =
std::max(maximumTagLength,
dtel.at(index).getTagName().length());
}
return maximumTagLength;
}
//// //////////////////////////////////
// Updates the previous directory: //
////////////////////////////////// ////
static string updatePreviousDirectory(
DirectoryTagEntryList& directoryTagEntryList,
string& newDirectoryName) {
DirectoryTagEntry* dte = directoryTagEntryList[PREV_TAG_NAME];
if (dte->getTagName().compare(PREV_TAG_NAME) == 0) {
string rv = dte->getDirectoryName();
dte->setDirectoryName(newDirectoryName);
return rv;
} else {
DirectoryTagEntry ndte(PREV_TAG_NAME, newDirectoryName);
directoryTagEntryList << ndte;
return getCurrentWorkingDirectory();
}
}
//// //////////////////////////////////////////////////
// Returns the home directory of the current user: //
////////////////////////////////////////////////// ////
static string getHomeDirectory() {
return string(getpwuid(getuid())->pw_dir);
}
//// //////////////////////////////////////////////////////////////////////
// Changes the leading tilde to the name of the user's home directory: //
////////////////////////////////////////////////////////////////////// ////
static string convertDirectoryNameToExactDirectoryName(string dir) {
if (dir.size() == 0) {
throw "The directory name is empty. This should not happen.";
}
if (dir[0] != '~') {
// Nothing to do.
return dir;
}
string homeDirectory = getHomeDirectory();
auto iter = dir.cbegin();
std::advance(iter, 1);
for (auto it = iter; it != dir.cend(); ++it) {
homeDirectory.push_back(*it);
}
return homeDirectory;
}
static void checkIfstream(ifstream& ifs) {
if (!ifs.is_open()) {
throw "Could not open the tag file for reading.";
}
if (!ifs.good()) {
throw "The tag file input stream is not good.";
}
}
static void checkOfstream(ofstream& ofs) {
if (!ofs.is_open()) {
throw "Could not open the tag file for writing.";
}
if (!ofs.good()) {
throw "The tag file output stream is not good.";
}
}
//// //////////////////////////////////////////////////////////////////
// Jumps to the directory to which dt was switching most recently: //
////////////////////////////////////////////////////////////////// ////
static void jumpToPreviousDirectory() {
string tagFilePath = getTagFilePath();
ifstream ifs;
ifs.open(tagFilePath, std::ifstream::in);
checkIfstream(ifs);
DirectoryTagEntryList directoryTagEntryList;
ifs >> directoryTagEntryList;
DirectoryTagEntry* directoryTagEntry = directoryTagEntryList[PREV_TAG_NAME];
string nextPath;
string currentWorkingDirectory = getCurrentWorkingDirectory();
if (directoryTagEntry->getTagName().compare(PREV_TAG_NAME) == 0) {
nextPath = updatePreviousDirectory(directoryTagEntryList,
currentWorkingDirectory);
} else {
DirectoryTagEntry prevTagEntry(PREV_TAG_NAME,
currentWorkingDirectory);
directoryTagEntryList << prevTagEntry;
nextPath = currentWorkingDirectory;
}
ofstream ofs;
ofs.open(tagFilePath, ofstream::out);
checkOfstream(ofs);
directoryTagEntryList >> ofs;
ofs.close();
cout << OPERATION_SWITCH_DIRECTORY
<< '\n'
<< convertDirectoryNameToExactDirectoryName(nextPath)
<< std::flush;
}
//// /////////////////////////////
// Switches to the directory: //
///////////////////////////// ////
static void switchDirectory(std::string const& tag) {
DirectoryTagEntryList directoryTagEntryList;
std::ifstream ifs;
std::string tagFilePath = getTagFilePath();
ifs.open(tagFilePath, std::ifstream::in);
checkIfstream(ifs);
ifs >> directoryTagEntryList;
string currentWorkingDirectory = getCurrentWorkingDirectory();
if (directoryTagEntryList.size() == 0) {
string nextDirectory =
updatePreviousDirectory(
directoryTagEntryList,
currentWorkingDirectory);
std::ofstream ofs;
ofs.open(getTagFilePath(), std::ofstream::out);
checkOfstream(ofs);
directoryTagEntryList >> ofs;
ofs.close();
cout << OPERATION_SWITCH_DIRECTORY
<< '\n'
<< convertDirectoryNameToExactDirectoryName(nextDirectory);
}
if (directoryTagEntryList.size() == 1) {
cout << OPERATION_SWITCH_DIRECTORY
<< "\n"
<< directoryTagEntryList[0]->getDirectoryName();
updatePreviousDirectory(directoryTagEntryList,
currentWorkingDirectory) ;
std::ofstream ofs;
ofs.open(getTagFilePath(), std::ofstream::out);
checkOfstream(ofs);
directoryTagEntryList >> ofs;
ofs.close();
}
DirectoryTagEntry* bestMatch = directoryTagEntryList[tag];
std::ofstream ofs;
ofs.open(getTagFilePath(), std::ofstream::out);
checkOfstream(ofs);
updatePreviousDirectory(directoryTagEntryList,
currentWorkingDirectory);
directoryTagEntryList >> ofs;
ofs.close();
// New line?
cout << OPERATION_SWITCH_DIRECTORY
<< '\n'
<< convertDirectoryNameToExactDirectoryName(
bestMatch->getDirectoryName());
}
//// //////////////////////////////////////
// Lists taga without the directories: //
////////////////////////////////////// ////
static void listTagsOnly(
DirectoryTagEntryList const& directoryTagEntryList) {
cout << OPERATION_DESCRIPTOR_SHOW_TAG_ENTRY_LIST << '\n';
for (size_t index = 0, sz = directoryTagEntryList.size();
index < sz;
index++) {
cout << directoryTagEntryList.at(index).getTagName() << "\n";
}
}
//// //////////////////////////////
// Lists taga and directories: //
////////////////////////////// ////
static void listTagsAndDirectories(
DirectoryTagEntryList const& directoryTagEntryList) {
cout << OPERATION_DESCRIPTOR_SHOW_TAG_ENTRY_LIST << '\n';
size_t maxTagLength = getMaximumTagLength(directoryTagEntryList);
for (size_t index = 0, sz = directoryTagEntryList.size();
index < sz;
index++) {
DirectoryTagEntry const& directoryTagEntry =
directoryTagEntryList.at(index);
std::cout << std::setw(maxTagLength + 1)
<< directoryTagEntry.getTagName()
<< ' '
<< directoryTagEntry.getDirectoryName()
<< '\n';
}
}
//// /////////////////////////////////
// Decided how to print the tags: //
///////////////////////////////// ////
static void listTags(std::string const& flag) {
std::ifstream ifs;
ifs.open(getTagFilePath(), std::ifstream::in);
checkIfstream(ifs);
DirectoryTagEntryList directoryTagEntryList;
ifs >> directoryTagEntryList;
if (flag == FLAG_LIST_TAGS_SORTED
|| flag == FLAG_LIST_BOTH_SORTED) {
directoryTagEntryList.sortByTags();
} else if (flag == FLAG_LIST_BOTH_SORTED_DIRS) {
directoryTagEntryList.sortByDirectories();
}
if (flag == FLAG_LIST_TAGS_SORTED
|| flag == FLAG_LIST_TAGS) {
listTagsOnly(directoryTagEntryList);
} else if (flag == FLAG_LIST_BOTH
|| flag == FLAG_LIST_BOTH_SORTED
|| flag == FLAG_LIST_BOTH_SORTED_DIRS) {
listTagsAndDirectories(directoryTagEntryList);
}
}
//// ///////////////////////////////
// Processes a single flag/tag: //
/////////////////////////////// ////
static void processSingleFlag(std::string const& arg) {
if (arg == FLAG_LIST_BOTH
|| arg == FLAG_LIST_TAGS
|| arg == FLAG_LIST_TAGS_SORTED
|| arg == FLAG_LIST_BOTH_SORTED
|| arg == FLAG_LIST_BOTH_SORTED_DIRS) {
listTags(arg);
} else {
switchDirectory(arg);
}
}
static void processUpdatePrevious(string& dir) {
string tagFilePath = getTagFilePath();
DirectoryTagEntryList directoryTagEntryList;
ifstream ifs;
ifs.open(tagFilePath, ifstream::in);
checkIfstream(ifs);
ifs >> directoryTagEntryList;
ifs.close();
DirectoryTagEntry* previousEntryCandidate =
directoryTagEntryList[PREV_TAG_NAME];
string nextPath;
if (previousEntryCandidate->getTagName().compare(PREV_TAG_NAME) == 0) {
nextPath = previousEntryCandidate->getDirectoryName();
previousEntryCandidate->setDirectoryName(dir);
} else {
DirectoryTagEntry prevDirectoryTagEntry(PREV_TAG_NAME, dir);
nextPath = getCurrentWorkingDirectory();
directoryTagEntryList << prevDirectoryTagEntry;
}
ofstream ofs;
ofs.open(getTagFilePath(), ofstream::out);
checkOfstream(ofs);
directoryTagEntryList >> ofs;
ofs.close();
// return nextPath;
}
int main(int argc, char *argv[]) {
try {
if (argc == 1) {
jumpToPreviousDirectory();
} else if (argc == 2) {
processSingleFlag(argv[1]);
} else if (argc == 3) {
string flag = argv[1];
if (flag.compare(FLAG_UPDATE_PREVIOUS) != 0) {
string errorMsg = "Flag ";
errorMsg = errorMsg.append(flag);
errorMsg = errorMsg.append(" not recognized.");
throw errorMsg.data();
}
string dir = argv[2];
processUpdatePrevious(dir);
}
} catch (char *const msg) {
cerr << msg << '\n';
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
</code></pre>
<p><strong><code>Makefile</code></strong></p>
<pre><code>all: DirectoryTagEntry.cpp DirectoryTagEntryList.cpp main.cpp
g++ -std=c++17 -Wall -Werror -pedantic -o ds_engine DirectoryTagEntry.cpp DirectoryTagEntryList.cpp main.cpp
install:
chmod 500 installer.sh
installer.sh
</code></pre>
<h2>See also</h2>
<ol>
<li>The <a href="https://codereview.stackexchange.com/questions/266569/ds4mac-directory-switcher-for-macos-linux-the-script">bash script</a></li>
<li>The <a href="https://codereview.stackexchange.com/questions/266572/ds4mac-directory-switcher-for-macos-linux-the-installer-script">installer script</a></li>
</ol>
<h2>Critique request</h2>
<p>Especially, <code>main.cpp</code> looks like cr*p to me. How could I C++:fy it?</p>
|
[] |
[
{
"body": "<h1>Creating a matrix</h1>\n<p>You can initialize a nested <code>std::vector</code> with the right size in one go like so:</p>\n<pre><code>std::vector<std::vector<size_t>> distanceMatrix(len1, std::vector<size_t>(len2));\n</code></pre>\n<p>Since <a href=\"https://en.cppreference.com/w/cpp/language/class_template_argument_deduction\" rel=\"nofollow noreferrer\">C++17</a> you can even omit the template parameter for the outer <code>std::vector</code>:</p>\n<pre><code>std::vector distanceMatrix(len1, std::vector<size_t>(len2));\n</code></pre>\n<p>However, nested vectors are not great for performance, it is better to have a flat vector with <code>len1 * len2</code> elements.</p>\n<h1>Wrong operator overloads for <code>DirectoryTagEntryList</code>?</h1>\n<p>You have declared:</p>\n<pre><code>friend void operator>>(DirectoryTagEntryList const&, std::ofstream&);\n</code></pre>\n<p>But the normal way is to overload the left shift operator instead, and have the arguments reversed. Furthermore, these operators should take an <code>std::ostream</code> reference, not <code>std::ofstream</code>, so they are even more generic. Finally, these operators should not be <code>void</code> but return the <code>std::ostream</code> reference. So the declaration should instead look like:</p>\n<pre><code>friend std::ostream& operator<<(std::ostream&, DirectoryTagEntryList const&);\n</code></pre>\n<p>The same goes for the <code>friend operator>>(std::ifstream&, ...)</code> declarations.</p>\n<p>There is also a member function <code>operator<<(std::ifstream& ifs)</code> which doesn't do anything, and should be removed.</p>\n<h1>Useless <code>const</code> return value</h1>\n<p>It makes no sense to declare the return value of a function <code>const</code>, unless you are returning a pointer or reference. So the first <code>const</code> in the declaration of <code>DirectoryTagEntryList::size()</code> can be removed.</p>\n<h1>Declarations of functions without an implementation</h1>\n<p>I see that <code>DirectoryTagEntryList</code> has declared member functions <code>listTags()</code> and <code>listTagsAndDirectories()</code>, but there are no implementations of these functions. I see you have static functions in <code>main.cpp</code> that do the printing, which makes me think you should just remove the useless declarations of the member functions.</p>\n<h1>Avoid C string manipulation</h1>\n<p>In <code>getFilePath()</code>, you do some string manipulation using C string functions before finally creating a <code>std::string</code> of it. You created a memory leak while doing so. I suggest that you convert C strings to <code>std::string</code> as early as possible, and then do all the string manipulation using C++ functions:</p>\n<pre><code>static string getTagFilePath() {\n std::string home_directory = getpwuid(getuid())->pw_dir;\n return home_directory + RELATIVE_TAG_FILE_PATH;\n}\n</code></pre>\n<p>However, also note that <code>getpwuid()</code> might fail and return <code>NULL</code>. Note that you should check <code>getenv("HOME")</code> first, as is mentioned in the <a href=\"https://linux.die.net/man/3/getpwuid\" rel=\"nofollow noreferrer\">manpage of <code>getpwuid()</code></a>.</p>\n<h1>Use <code>std::filesystem</code> functions</h1>\n<p>I see you are compiling your code with <code>std=c++17</code>. In that case, use C++17's <a href=\"https://en.cppreference.com/w/cpp/filesystem\" rel=\"nofollow noreferrer\">filesystem library</a> instead of C functions. For example, getting the current directory can be done with <a href=\"https://en.cppreference.com/w/cpp/filesystem/current_path\" rel=\"nofollow noreferrer\"><code>std::filesystem::current_path()</code></a> instead of <code>getcwd()</code>. You can also consider storing pathnames in <code>std::fileystem::path</code>s instead of <code>std::string</code>s.</p>\n<h1>Missing error checking</h1>\n<p>I see you only check for errors right after opening a file for reading or writing. However, I/O errors can happen at any time. Luckily, you don't have to error check every I/O operation, instead you can just check the state of the stream right before closing it.</p>\n<p>For reading, check at the end that <code>ifs.eof()</code> is <code>true</code>. If not, something obviously went wrong before reaching the end of the file.\nFor writing, after calling <code>ofs.close()</code>, check that <code>ofs.fail()</code> is <code>false</code>.</p>\n<p>You could even consider not checking the state of the stream right after opening it.</p>\n<h1>Make your classes suitable for range-for loops</h1>\n<p>Instead of:</p>\n<pre><code>for (size_t index = 0, sz = directoryTagEntryList.size(); index < sz; index++) {\n cout << directoryTagEntryList.at(index).getTagName() << "\\n";\n}\n</code></pre>\n<p>It would be much nicer if you could just write:</p>\n<pre><code>for (auto &entry: directoryTagEntryList) {\n cout << entry.getTagName() << "\\n";\n}\n</code></pre>\n<p>You can do this by adding <code>begin()</code> and <code>end()</code> member functions to <code>class DirectoryTagEntryList</code>, like so:</p>\n<pre><code>class DirectoryTagEntryList {\n std::vector<DirectoryTagEntry> entries;\n\npublic:\n auto begin() const {\n return entries.begin();\n }\n\n auto end() const {\n return entries.end();\n }\n ...\n};\n</code></pre>\n<h1>Don't <code>throw</code> raw strings</h1>\n<p>Use an <a href=\"https://en.cppreference.com/w/cpp/error/exception\" rel=\"nofollow noreferrer\">existing exception type</a> or create one yourself that inherits an existing type. There's also no need to catch exceptions if you are going to print them and exit with a non-zero exit code anyway, the same thing will be done automatically if you don't catch them. So:</p>\n<pre><code>int main(...) {\n if (argc == 1) {\n ...\n } else if (argc == 2) {\n ...\n } else if (argc == 3) {\n ...\n throw std::invalid_argument("Flag " + flag + " not recognized");\n ...\n }\n}\n</code></pre>\n<p>Also note that you don't need the explicit <code>return EXIT_SUCCESS</code> at the end of <a href=\"https://en.cppreference.com/w/cpp/language/main_function\" rel=\"nofollow noreferrer\"><code>main()</code></a> in C++.</p>\n<p>If you want to avoid the program aborting and potentially causing a core dump for minor errors, then catching the exceptions makes since. But I would then add the <code>try</code> before the body of <code>main()</code>, like so:</p>\n<pre><code>int main(...) try {\n // as above\n ...\n} catch (const std::exception &ex) {\n std::cerr << ex.what() << "\\n";\n return EXIT_FAILURE;\n}\n</code></pre>\n<h1>Use <code>getopt_long()</code> for option parsing</h1>\n<p>Instead of parsing options yourself, I recommend you just use <a href=\"https://linux.die.net/man/3/getopt_long\" rel=\"nofollow noreferrer\"><code>getopt_long()</code></a>. It will ensure parsing is done exactly the same way as most UNIX tools. Unfortunately, it's not standard, but it is included in the standard library of most operating systems, the most notable exception being Windows. There are also many C and C++ libraries available that provide you with equivalent functionality.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T13:35:12.907",
"Id": "527762",
"Score": "0",
"body": "Awesome review! Thanks a lot!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T10:46:47.363",
"Id": "267622",
"ParentId": "266571",
"Score": "1"
}
},
{
"body": "<h4>The Makefile</h4>\n<p>You are not utilizing the power of Make. Each <code>make</code> invocation will compile the source files and link the binary, no matter if that is necessary or not. The dependencies in</p>\n<pre><code>all: DirectoryTagEntry.cpp DirectoryTagEntryList.cpp main.cpp\n</code></pre>\n<p>do not help because no file named “all” is ever created. It is better to make the actual target file dependent on the sources (and the included headers).</p>\n<p>There is also some duplication (the source files are listed twice) which is error-prone.</p>\n<p>The first part of the Makefile then looks like this:</p>\n<pre><code>all: ds_engine\n\nSOURCES = DirectoryTagEntry.cpp DirectoryTagEntryList.cpp main.cpp\nHEADERS = DirectoryTagEntry.h DirectoryTagEntryList.h\n\nds_engine: $(SOURCES) $(HEADERS)\n g++ -std=c++17 -Wall -Werror -pedantic -o $@ $(SOURCES)\n</code></pre>\n<p>For larger projects this should be improved further (compile only the necessary source files, generate dependencies automatically), but here it might be sufficient.</p>\n<hr />\n<p>Setting the mode of the installer shell script to <code>500</code> in the install rule looks strange to me: It makes the file read-only even for its owner. Which means that after calling “make install” once you cannot edit it anymore without reverting that change.</p>\n<p>Common choices are <code>755</code> (readable and executable for all, writeable only for the owner) or perhaps <code>700</code> (full access for the owner, no access for all others). With a “symbolic mode” (e.g. <code>rwxr-xr-x</code>) you can make the intention even clearer.</p>\n<p>But actually I would avoid changing the mode of a file under source control at at all. With</p>\n<pre><code>install:\n sh installer.sh\n</code></pre>\n<p>this is no longer needed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-04T13:28:38.557",
"Id": "267684",
"ParentId": "266571",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "267684",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T03:31:41.397",
"Id": "266571",
"Score": "2",
"Tags": [
"c++",
"console"
],
"Title": "ds4mac - directory switcher for macOS/Linux: the tag engine"
}
|
266571
|
<p>In this post, I present the bash script for installing the ds4mac:</p>
<pre><code>#!/usr/bin/env bash
script_magic="alias ds='source ~/.ds/ds_script'"
echo "Installing ds..."
grep "$script_magic" ~/.bashrc
if [ $? != 0 ]; then
echo "$script_magic" >> ~/.bashrc
echo "~/.bashrc updated!"
else
echo "~/.bashrc is already updated."
fi
# Create files:
echo "Creating files..."
mkdir -p ~/.ds
echo "Created the .ds directory."
make > /dev/null
cp ds_engine ~/.ds/ds_engine
echo "Built the ds_engine."
tag_file=~/.ds/tags
touch $tag_file
add_tag_to_file () {
grep $1 $tag_file > /dev/null
if [ $? != 0 ]; then
echo $1 $2 >> $tag_file
echo Setting the tag $1 to directory $2 done.
fi
}
# Populate the default
echo "Populating the tag file with default tags..."
add_tag_to_file "docs" "~/Documents"
add_tag_to_file "down" "~/Downloads"
add_tag_to_file "root" "/"
add_tag_to_file "home" "~"
add_tag_to_file "ds" "~/.ds"
echo "Done populating the tag file with default tags."
echo "Copying the script..."
cp ds_script ~/.ds/ds_script
echo "Done! ds will be available for use in your next shell session. :-]"
</code></pre>
<p>(The entire project is <a href="https://github.com/coderodde/ds4mac" rel="nofollow noreferrer">here</a>.)</p>
<h2>See also</h2>
<ol>
<li>The <a href="https://codereview.stackexchange.com/questions/266569/ds4mac-directory-switcher-for-macos-linux-the-script">main script</a></li>
<li>The <a href="https://codereview.stackexchange.com/questions/266571/ds4mac-directory-switcher-for-macos-linux-the-tag-engine">tag engine</a></li>
</ol>
<h2>Critique request</h2>
<p>Please, tell me anything that comes to mind. ^^</p>
|
[] |
[
{
"body": "<p>Patterns like:</p>\n<pre><code>grep $1 $tag_file > /dev/null\nif [ $? != 0 ]; then \n ...\nfi\n</code></pre>\n<p>Can be rewritten as:</p>\n<pre><code>if grep -q $1 $tag_file; then\n ...\nfi\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T02:33:16.617",
"Id": "267645",
"ParentId": "266572",
"Score": "2"
}
},
{
"body": "<p>The installer script should not ignore errors. As an example, in</p>\n<pre class=\"lang-bsh prettyprint-override\"><code>make > /dev/null\ncp ds_engine ~/.ds/ds_engine\n</code></pre>\n<p>the <code>make</code> command can fail (if no compiler is installed, if there are syntax errors in the program, etc.). In such a case it makes no sense to copy the binary to the installation directory, or to execute any of the subsequent commands. That will only produce more error messages which hide the actual problem.</p>\n<p>A simple solution is to set the "-e" flag in the script:</p>\n<pre class=\"lang-bsh prettyprint-override\"><code>#!/usr/bin/env bash\nset -e\n</code></pre>\n<p>From "man bash" (this applies to other shells as well):</p>\n<pre>\n-e Exit immediately if a simple command ... exits with a non-zero status\n</pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T07:19:00.393",
"Id": "267648",
"ParentId": "266572",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "267648",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T03:37:42.793",
"Id": "266572",
"Score": "1",
"Tags": [
"bash",
"installer"
],
"Title": "ds4mac - directory switcher for macOS/Linux: the installer script"
}
|
266572
|
<p>I'm programming a checkers game in typescript.
I'd like to explain some important details to understand how the following code works.
In my game coordinates are a string, like "b4".
I want to get the neighbors of a piece coordinates, but only the neighbors that make sense depending on the player and if the piece in these coordinates is a king or not.
For example, if on "b4" it's player one, I want to get only "a5" and "c5" as possible neighbors.</p>
<p>I wrote the following code to find the neighbors of given coordinates:</p>
<pre><code> type CornerType = {
[key: string]: string | null;
}
const getPieceCornersCoordinates = (coordinates: string, piece: Piece) => {
const {row, col} = convertStringCoordinatesToNumberCoordinates(coordinates);
const columnLeft = ((col - 1) >= 0) ? String.fromCharCode((col - 1) + 97) : false;
const columnRight = col +1 <= 7 ? String.fromCharCode((col + 1) + 97) : false;
const rowUpper = row +1 < 9 ? row +1 : false;
const rowLower = row -1 > 0 ? row -1 : false;
let corners : CornerType = {};
if(piece.isKing){
corners.leftUpper = columnLeft !== false && rowUpper !== false ? columnLeft + rowUpper : null;
corners.rightUpper = columnRight !== false && rowUpper !== false ? columnRight + rowUpper : null;
corners.leftLower = columnLeft !== false && rowLower !== false ? columnLeft + rowLower : null;
corners.rightLower = columnRight !== false && rowLower !== false ? columnRight + rowLower : null;
} else if(piece.player === "Player One"){
corners.leftLower = columnLeft !== false && rowLower !== false ? columnLeft + rowLower : null;
corners.rightLower = columnRight !== false && rowLower !== false ? columnRight + rowLower : null;
} else {
corners.leftUpper = columnLeft !== false && rowUpper !== false ? columnLeft + rowUpper : null;
corners.rightUpper = columnRight !== false && rowUpper !== false ? columnRight + rowUpper : null;
}
deleteNullCorners(corners);
return corners;
}
const deleteNullCorners = (corners: CornerType) => {
for(let key in corners){
if(corners[key] === null){
delete corners[key];
}
}
}
</code></pre>
<p>I think this code is not well written, how can I improve it?</p>
|
[] |
[
{
"body": "<p>First, post your entire code file (a working checkers game), not just this one function, if you want to know how to improve your code. It's hard to suggest improvements for just one function.</p>\n<p>This function doesn't do anything clear, and should probably be renamed or split up or merged with other functions. At best, it returns all the possible moves which aren't captures. If that's what you want (unlikely) name it better to match that.</p>\n<p>I recommend not using a string for coordinates. Just use a pair of numbers. You can convert to display it to the user, etc where needed.</p>\n<p>Return an array of coordinates or an array of directions, not a dict of <code>directionName -> coordinate</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T07:44:58.353",
"Id": "266575",
"ParentId": "266574",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T06:04:14.100",
"Id": "266574",
"Score": "1",
"Tags": [
"javascript",
"react.js",
"typescript",
"checkers-draughts"
],
"Title": "Find coordinates of neighbors out of given coordinates"
}
|
266574
|
<p>I work at a major Swedish insurance company. I'm in charge of a service that matches bank payments with invoices. I will not show the details of that match logic. But one outcome of the match is that amount on payment differs from amount on invoice. We have a <code>IAmountDeviationStrategy</code> that is tagged on each invoice. Here is the <code>RefundStrategy</code></p>
<pre><code>public class RefundStrategy : IAmountDeviationStrategy
{
public AmountDeviationStrategy Strategy => AmountDeviationStrategy.Refund;
public PaymentInvoiceMatchResult Execute(MatchJob job)
{
if (job.Diff < 0)
return new PaymentInvoiceMatchResultBuilder(job)
.PaymentCategory(PaymentCategory.WrongPayment)
.RefundAll(RefundReason.UnderPaid);
var invoiceAmount = Math.Abs(job.Invoice.Amount);
var payingPayments = GetPaymentsComboClosestToInvoiceAmount(job.Payments, invoiceAmount);
var refunds = job.Payments.Except(payingPayments).ToList();
var result = new PaymentInvoiceMatchResultBuilder(job, refunds)
.PaymentCategory(PaymentCategory.WrongPayment)
.Refund(refunds);
if (payingPayments.Sum(p => p.Amount) != invoiceAmount)
result.Refund<RefundSplitPaymentCommand>(payingPayments.First(p => p.Amount >= job.Diff), split => split.Amount = payingPayments.Sum(p => p.Amount) - invoiceAmount);
return result
.QueueCommand(new MapInvoicePaymentsCommand { InvoiceId = job.Invoice.ExternalId, Payments = payingPayments.Select(p => p.ExternalId) });
}
private IReadOnlyCollection<IPaymentMatchInfo> GetPaymentsComboClosestToInvoiceAmount(IReadOnlyCollection<IPaymentMatchInfo> payments, decimal invoiceAmount)
{
var combos = Enumerable.Range(1, payments.Count)
.SelectMany(i => new Combinations<IPaymentMatchInfo>(payments, new ReferenceCompare<IPaymentMatchInfo>(), i))
.ToList();
var payingPayments = combos
.Where(c => c.Sum(p => p.Amount) >= invoiceAmount)
.OrderBy(combo => Math.Abs(combo.Sum(p => p.Amount) - invoiceAmount))
.First();
return payingPayments;
}
</code></pre>
<p>If the payment underpays the invoice we simlply refund the payment. If its overpaid the fun starts. There can be multiple payments. Most common is the customer have paid once and overpaid. Second most common is he have double paid, ie two payments which sums to 2x the invoice. Third and uncommon is multiple payments that overpays randomly (not double the amount).</p>
<p>Anyway, I bruteforce this problem. I find all combos of payments using a little Combination class <a href="https://pastebin.com/BDvRmmgD" rel="nofollow noreferrer">https://pastebin.com/BDvRmmgD</a> (Not written by me)</p>
<p>Once I have all combos I take the one combo closest to the invoice amount. I refund all others. I then check if the paying payments sum up to the amount (which they do in double paid scenario). If they dont sum up I split one of the payments and refund the overpaid part.</p>
<p>I then rerun the matching command <code>MapInvoicePaymentsCommand</code>. This time the invoice and payment will hit the Paid outcome path instead.</p>
<p>I think the brute force part is pretty elegant. There will never be more payments than a few so it will not be a performance problem.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T05:19:58.067",
"Id": "527733",
"Score": "0",
"body": "Consider a title that [describes the program rather than asking a question](https://codereview.meta.stackexchange.com/questions/735/meaningful-question-titles). Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T08:21:32.623",
"Id": "527745",
"Score": "0",
"body": "@ggorlen Ok. I dont agree the new title is better. But there you go"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T14:36:23.053",
"Id": "527767",
"Score": "0",
"body": "Thanks for your flexibility! Looks great to me. If you browse https://codereview.stackexchange.com for a few pages, it might convince you that it fits the site better. There's a push to [remove the word \"this\" from titles](https://codereview.meta.stackexchange.com/questions/735/meaningful-question-titles), because it doesn't really tell you what you're clicking on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T14:52:38.543",
"Id": "527770",
"Score": "0",
"body": "It would be more helpful with feedback on the actual code/domain problem :P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T14:57:27.543",
"Id": "527772",
"Score": "1",
"body": "Ah, but this is part of what _gets_ you better feedback on the actual code/domain problem. Posts that are less on topic and have an unclear title => fewer upvotes, less attention, worse (or no) reviews... if it's off-topic and unclear enough, downvotes and closure ensue. If you have a crisper title and topic, you get more upvotes, more attention and better reviews. Also, Stack Exchange sites are about the _community benefit_ foremost -- it's about curating a resource for future visitors and building a body of knowledge that helps everyone learn."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T15:08:14.703",
"Id": "527773",
"Score": "0",
"body": "I think the original title was better. It shows more what I asks for in the review. I ask if brute force is a good approach for my domain problem"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T15:15:55.283",
"Id": "527774",
"Score": "1",
"body": "Based on the old title, what's your problem domain? Your \"use case\" might be brute-forcing a password, brute forcing a chess puzzle, brute forcing a Project Euler or Leetcode problem... who knows? In fact, it's misleading, because I'm more interested in those algorithmic topics than in enterprise C# business logic, while others who might be interested in a business app would have more reason to visit post-update. It goes without saying that you're asking for review of your approach (\"is this an elegant approach?\"). That applies to every post on CR and provides no differentiating value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T15:20:03.403",
"Id": "527775",
"Score": "0",
"body": "As an aside, I'm not sure there's enough context here to provide a review; almost all of these classes aren't provided and the specification for the routine seems unclear to me, but it got a couple of upvotes so I hope you get the review \nyou're looking for soon."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T15:24:55.377",
"Id": "527776",
"Score": "0",
"body": "All the relevant code is in GetPaymentsComboClosestToInvoiceAmount its there"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T15:28:46.483",
"Id": "527778",
"Score": "0",
"body": "What's an `IReadOnlyCollection<IPaymentMatchInfo> payments`, for example? Anyway, I can clean up this thread any time to reduce noise from all the back-and-forth -- just tag me or flag the posts as \"no longer needed\" since you've seen them."
}
] |
[
{
"body": "<p>Maybe it's elegant maybe not, but IMHO it's <strong>not predicted behavior</strong>.</p>\n<p>Let's say my invoice is for 100$.\nFor some circumstances I paid in the following order:</p>\n<ul>\n<li>$60</li>\n<li>$100</li>\n<li>$70</li>\n</ul>\n<p><strong>What is predicted behavior here?</strong></p>\n<p>The software is going to fill the invoice in chronological order (as my payments were). So my first $60 payment should be confirmed for sure, next from my $100 payment $40 should be confirmed (as it was remaining to fill invoice) and other $60 should be refunded as well as my 3rd payment because <strong>by the time I did the 3'rd payment invoice was already filled</strong>.</p>\n<p>If it's not an explicit business requirement I suggest, simply ordering payments in chronological order and 1 by 1 filling the invoice. When it gets filled, refund everything remained.</p>\n<p>Just imagine how many "Why this was refunded?" questions will arise and how much time will spend accountant on brute-forcing in his/her head while looking on the refunds spreadsheet.</p>\n<p>It's both predictable for customers and for your future college who is going to work in this code.</p>\n<p><strong>Again if there is no specific business reason for that.</strong></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-24T10:54:59.257",
"Id": "529092",
"Score": "0",
"body": "In your example it will keep the 100 USD and refund the two others. I think its the most correct approuch. Otherwise it would take 60 from the first 40 from the second and refund 70 + 60. Thats more strange to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-24T19:02:28.557",
"Id": "529186",
"Score": "0",
"body": "\"Fill invoice as payments arrive.\" vs \"Decide what amounts are perfectly matching for the invoice amount.\"\n\nWhy? Imho you should keep simple as far as there is no other concern. To me, the first approach seems simplest."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-24T22:22:30.023",
"Id": "529193",
"Score": "0",
"body": "It's by design and per requirements"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T21:32:08.727",
"Id": "268309",
"ParentId": "266577",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T08:40:34.777",
"Id": "266577",
"Score": "3",
"Tags": [
"c#",
"complexity"
],
"Title": "Brute force to solve refund amount in a payment/invoice domain"
}
|
266577
|
<p>My code snippet represents a way of handling chained errors. I need a code-review to understand whether my way is idiomatic and relevant for the 2021?</p>
<p>My personal requirements:</p>
<ol>
<li>I want each package of my project to have an <code>errors.go</code> file with defined sentinel-style errors. This, in my opinion, hugely improves readability/maintainability.</li>
<li>I want to utilize new <code>errors.Is/As</code> functionality.</li>
<li>I want to hide implementation details of underlying packages. In my code snippet - I don't want the <code>web</code> package to know anything about <code>repository.NotFoundError</code> and <code>repository.DatabaseError</code>. But I do want my top-level web error to have full chain of underlying error strings (possibly, error contexts) for describing them in logs, HTTP responses, etc.</li>
</ol>
<p>Here is my humble snippet (one may launch it with go test):</p>
<pre class="lang-golang prettyprint-override"><code>
package main
import (
"errors"
"fmt"
"testing"
)
// the code below should be kept in some kind of common place
type CustomError struct {
Message string
Child error
}
func (cerr *CustomError) Error() string {
if cerr.Child != nil {
return fmt.Sprintf("%s: %s", cerr.Message, cerr.Child.Error())
}
return cerr.Message
}
func (cerr *CustomError) Unwrap() error {
return cerr.Child
}
func (cerr *CustomError) Wrap(child error) error {
cerr.Child = child
return cerr
}
func CustomErrorBuilder(message string, child error) *CustomError {
return &CustomError{Message: message, Child: child}
}
// the code below represents the 'repository' package
var (
NotFoundError = CustomErrorBuilder("NotFoundError", nil)
DatabaseError = CustomErrorBuilder("DatabaseError", nil)
)
func QueryUser(id int) (string, error) {
if id == 0 {
return "User 0", nil
}
if id == 1 {
return "User 1", nil
}
if id == 100 {
return "", DatabaseError
}
return "", NotFoundError
}
// the code below represents the 'core' package
var (
InfrastructureError = CustomErrorBuilder("InfrastructureError", nil)
BusinessLogicError = CustomErrorBuilder("BusinessLogicError", nil)
)
func UserHasName(id int, name string) (bool, error) {
userName, err := QueryUser(id)
if err != nil {
if errors.Is(err, NotFoundError) {
return false, BusinessLogicError.Wrap(NotFoundError)
}
if errors.Is(err, DatabaseError) {
return false, InfrastructureError.Wrap(DatabaseError)
}
}
if userName == name {
return true, nil
} else {
return false, nil
}
}
// the code below represents the 'web' package
func Handler(id int, name string) (int, string) {
result, err := UserHasName(id, name)
if err != nil {
if errors.Is(err, BusinessLogicError) {
return 404, fmt.Sprintf("NOT FOUND %v", err)
}
if errors.Is(err, InfrastructureError) {
return 500, fmt.Sprintf("INTERNAL SERVER ERROR %v", err)
}
}
return 200, fmt.Sprintf("OK %t", result)
}
// This test checks errors wrapping
func TestHandler(t *testing.T) {
testCases := []struct {
userId int
userName string
expectedStatus int
expectedBody string
}{
{userId: 0, userName: "User 0", expectedStatus: 200, expectedBody: "OK true"},
{userId: 1, userName: "User 0", expectedStatus: 200, expectedBody: "OK false"},
{userId: 2, userName: "", expectedStatus: 404, expectedBody: "NOT FOUND BusinessLogicError: NotFoundError"},
{userId: 100, userName: "", expectedStatus: 500, expectedBody: "INTERNAL SERVER ERROR InfrastructureError: DatabaseError"},
}
for i, tcase := range testCases {
t.Run(fmt.Sprintf("Case %v", i), func(t *testing.T) {
status, body := Handler(tcase.userId, tcase.userName)
if status != tcase.expectedStatus {
t.Fatalf("%v != %v", status, tcase.expectedStatus)
}
if body != tcase.expectedBody {
t.Fatalf("%s != %s", body, tcase.expectedBody)
}
})
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>A couple of things:</p>\n<hr />\n<p>If you are not returning any rich data in your errors (beyond an extra error string), then a custom error may be overkill. One can achieve the same with:</p>\n<pre><code>if errors.Is(err, NotFound) {\n return fmt.Errorf("Business Logic Error: %w", err)\n}\n</code></pre>\n<p><code>fmt.Errorf</code> with the <code>%w</code> wrap-verb wraps a new error with the added error message - preserving the original error if one needs to unwrap or use <code>errors.Is</code> for matching.</p>\n<hr />\n<p>In <code>UserHasName</code> there's a fall-through bug:</p>\n<pre><code>if err != nil {\n if errors.Is(err, NotFoundError) { return /* */ }\n if errors.Is(err, DatabaseError) { return /* */ }\n \n // if err matches neither of the above checks, then the error is lost\n}\n</code></pre>\n<hr />\n<p>Applying the above refactoring/bug-fixes: <a href=\"https://play.golang.org/p/N5_PAiJKzRh\" rel=\"nofollow noreferrer\">https://play.golang.org/p/N5_PAiJKzRh</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T08:20:57.733",
"Id": "527744",
"Score": "0",
"body": "Thanks for the example. I agree, that the `fmt.Errorf(\"Business Logic Error: %w\", err)` could partially solve my problem, but as far as I understand in that case I will be forced to keep `\"Business Logic Error:\"` error string in two places: `BusinessLogicError = CustomErrorBuilder(\"BusinessLogicError\", nil)` and `fmt.Errorf(\"Business Logic Error: %w\", err)` My point was to avoid that duplication and using sentinel-style errors only"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T11:02:58.307",
"Id": "527750",
"Score": "0",
"body": "In the playground link I provided, the error string is defined only once (line 14) and reused (line 35)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T11:45:55.833",
"Id": "527753",
"Score": "0",
"body": "Oh, I see. That makes sense. Thank you!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T18:55:42.377",
"Id": "266603",
"ParentId": "266578",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "266603",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T08:59:40.730",
"Id": "266578",
"Score": "1",
"Tags": [
"go"
],
"Title": "Example of handling chained errors in Go with help of CustomError object"
}
|
266578
|
<p>I'm writing an html5 canvas game for the first time. To start with, I decided to make the below class so I can check for inputs every update loop. The class can detect key/mouse down/up events and track mouse position. I plan to add mouse scroll if needed later.</p>
<p>All opinions/suggestions are welcome!</p>
<p><strong>Explanation</strong></p>
<p>After initialization, the class will listen to key/mouse up/down events and record them in the <code>state</code> property. <code>state</code> has format <code>{[inputname]: {[press], [trigger], [release]}}</code>. This records <code>Date.now()</code> when the input was last pressed/triggered/released. <code>press</code> updates only when a button is first pressed. <code>trigger</code> updates any time mouse/key down is called (note only keydown events repeat when a key is already pressed). <code>state</code> also stores <code>mousePosition: {x, y}</code>.</p>
<p>The object keys representing each button have the format <code>`mouse${[MouseEvent.button]}`</code> or <code>`key${[KeyboardEvent.code]}`</code>. I store commonly used keys as statics, but the intention is to allow users to configure their own controls, so only the 'commonly' used keys are needed for setting defaults.</p>
<p><strong>Usage</strong></p>
<ul>
<li><p>Initialize with <code>new Input(target)</code>. <code>target</code> is the DOM part you want to listen for inputs (default <code>document</code>).</p>
</li>
<li><p>To check inputs, use the <code>check(...)</code> and <code>mousePosition()</code> methods. <code>check</code> takes 3 arguments - <code>hash</code>, <code>type</code>, <code>buttonState</code> and returns a bool.</p>
<p><code>hash</code> is the input representation as above.<br>
<code>type</code> is <code>Input.START</code> or <code>Input.CURRENT</code>. <code>START</code> checks if the input was pressed/triggered/released starting from this frame. <code>CURRENT</code> just checks if the input is currently pressed/released (note <code>CURRENT</code> pressed is the same as <code>CURRENT</code> triggered).<br>
<code>buttonState</code> is <code>Input.PRESS</code>, <code>Input.TRIGGER</code> or <code>Input.RELEASE</code> - whichever state you're checking the input is in.</p>
<p>Eg. to check if the return key triggered this frame, call <code>.check(Input.KEYENTER, Input.START, Input.TRIGGER)</code>.</p>
</li>
<li><p>After checking inputs, <code>doneCheck()</code> needs to be called every frame. Internally the class keeps track of <code>Date.now()</code> every time it is called. This way double handling inputs can be avoided.</p>
</li>
</ul>
<p><strong>Code</strong></p>
<pre class="lang-js prettyprint-override"><code>class Input {
static START = 0
static CURRENT = 1
static PRESS = 0
static TRIGGER = 1
static RELEASE = 2
static MOUSE = 'mouse'
static KEY = 'key'
static MOUSELEFT = `${Input.MOUSE}${0}`
static MOUSEMIDDLE = `${Input.MOUSE}${1}`
static MOUSERIGHT = `${Input.MOUSE}${2}`
static KEYDOWN = `${Input.KEY}${'ArrowDown'}`
static KEYLEFT = `${Input.KEY}${'ArrowLeft'}`
static KEYRIGHT = `${Input.KEY}${'ArrowRight'}`
static KEYUP = `${Input.KEY}${'ArrowUp'}`
static KEYENTER = `${Input.KEY}${'Enter'}`
static KEYSPACE = `${Input.KEY}${'Space'}`
static KEYABC(letter) {
return `${Input.KEY}Key${letter}`
}
constructor(target = document) {
this.doneCheck()
this.state = {mousePosition: {x: 0, y: 0}}
Object.entries({
'keydown': e => this.press(e, Input.KEY, e.code),
'keyup': e => this.release(e, Input.KEY, e.code),
'mousedown': e => this.press(e, Input.MOUSE, e.button),
'mouseup': e => this.release(e, Input.MOUSE, e.button),
'mousemove': e => this.mouseMove(e, e.x, e.y),
}).forEach(([eventType, func]) => target.addEventListener(eventType, e => func(e)))
}
//Input
press(e, type, input) {
const hash = `${type}${input}`
this.state[hash] = this.state[hash] || {[Input.PRESS]: 0, [Input.TRIGGER]: 0, [Input.RELEASE]: 0}
this.state[hash][Input.TRIGGER] = Date.now()
if (this.state[hash][Input.RELEASE] >= this.state[hash][Input.PRESS]) this.state[hash][Input.PRESS] = this.state[hash][Input.TRIGGER]
}
release(e, type, input) {
const hash = `${type}${input}`
this.state[hash] = this.state[hash] || {[Input.PRESS]: 0, [Input.TRIGGER]: 0, [Input.RELEASE]: 0}
this.state[hash][Input.RELEASE] = Date.now()
}
mouseMove(e, x, y) {
this.state.mousePosition.x = x
this.state.mousePosition.y = y
}
//Check
check(
hash,
type = Input.START, //START, CURRENT
buttonState = Input.PRESS, //PRESS, TRIGGER, RELEASE
) {
return (type === Input.START && this.state[hash] && this.checked < this.state[hash][buttonState]) ||
(type === Input.CURRENT && (buttonState === Input.PRESS) === (this.state[hash] && this.state[hash][Input.RELEASE] < this.state[hash][Input.PRESS]))
}
doneCheck() {
this.checked = Date.now()
}
mousePosition() {
return this.state.mousePosition
}
}
</code></pre>
<p>What it might look like during usage:</p>
<p><a href="https://i.stack.imgur.com/nCN7s.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nCN7s.png" alt="enter image description here" /></a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T13:06:29.987",
"Id": "266590",
"Score": "0",
"Tags": [
"javascript",
"game"
],
"Title": "Class for handling key/mouse inputs"
}
|
266590
|
<p>Here's the problem.</p>
<blockquote>
<p>Return a copy of x, where the minimum value along each row has been
set to 0.</p>
<p>For example, if x is:</p>
<pre><code>x = torch.tensor([[
[10, 20, 30],
[ 2, 5, 1]
]])
</code></pre>
<p>Then y = zero_row_min(x) should be:</p>
<pre><code>torch.tensor([
[0, 20, 30],
[2, 5, 0]
])
</code></pre>
<p>Your implementation should use reduction and indexing operations;
you should not use any explicit loops. The input tensor should not
be modified.</p>
<p>Inputs:</p>
<ul>
<li>x: Tensor of shape (M, N)</li>
</ul>
<p>Returns:</p>
<ul>
<li>y: Tensor of shape (M, N) that is a copy of x, except the minimum value
along each row is replaced with 0.</li>
</ul>
</blockquote>
<p>It has been hinted at that <a href="https://pytorch.org/docs/stable/generated/torch.clone.html#torch.clone" rel="nofollow noreferrer">clone</a> and <a href="https://pytorch.org/docs/stable/generated/torch.argmin.html#torch.argmin" rel="nofollow noreferrer">argmin</a> should be used.</p>
<p>I'm having trouble understanding how to do this without a loop and my current code below (although it gets the problem right) is crude. I'm looking for a better way to solve this problem.</p>
<pre><code> x0 = torch.tensor([[10, 20, 30], [2, 5, 1]])
x1 = torch.tensor([[2, 5, 10, -1], [1, 3, 2, 4], [5, 6, 2, 10]])
func(x0)
func(x1)
def func(x):
y = None
# g = x.argmin(dim=1)
g = x.min(dim=1)[1]
if x.shape[0] == 2:
x[0,:][g[0]] = 0
x[1,:][g[1]] = 0
elif x.shape[0] == 3:
x[0,:][g[0]] = 0
x[1,:][g[1]] = 0
x[2,:][g[2]] = 0
y = x
return y
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T16:21:35.987",
"Id": "526703",
"Score": "0",
"body": "The idea should be `copy_of_array[argmin_indices] = 0`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T17:33:11.607",
"Id": "526707",
"Score": "0",
"body": "Can you provide expected shape for each of your variables? e.g. `(1000, 2, 12)` or whatever."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T17:44:20.073",
"Id": "526708",
"Score": "1",
"body": "@Reinderien Sure, `x0 = torch.tensor([[10, 20, 30], [2, 5, 1]])` and `x1 = torch.tensor([[2, 5, 10, -1], [1, 3, 2, 4], [5, 6, 2, 10]])`. I've added them to the original post for clarification as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T17:55:56.567",
"Id": "526709",
"Score": "0",
"body": "@Andrew I believe that's similar to the way I went about solving it. It works, but I have to manually iterate over each row to mutate the min() value."
}
] |
[
{
"body": "<p>Not much of a code review, but this should work:</p>\n<pre><code>def zero_min(x):\n y = x.clone()\n y[torch.arange(x.shape[0]), torch.argmin(x, dim=1)] = 0\n return y\n</code></pre>\n<p>In each row, if the minimum is not unique, then only the occurrence with the smallest index will be zeroed out.</p>\n<p>To zero out all the occurrences, you could do something like the following:</p>\n<pre><code>def zero_em_all_min(x):\n y = x.clone()\n y[x == x.min(dim=1, keepdims=True).values] = 0\n return y\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T18:24:07.987",
"Id": "526716",
"Score": "0",
"body": "Thanks, didn't think to use `torch.arange` to iterate through the rows. I'll ask on regular SE in the future."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T18:26:02.620",
"Id": "526717",
"Score": "0",
"body": "@Ryan I'm happy it could be answered, but perhaps that is indeed the better platform for a similar question!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T18:16:27.703",
"Id": "266602",
"ParentId": "266597",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "266602",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T15:47:59.910",
"Id": "266597",
"Score": "0",
"Tags": [
"python",
"pytorch"
],
"Title": "Set min value of each row of a tensor to zero without using explicit loops"
}
|
266597
|
<p>This is the question I tried <a href="https://leetcode.com/problems/string-compression/" rel="nofollow noreferrer">Leetcode: String Compression</a></p>
<blockquote>
<p>Given an array of characters chars, compress it using the following algorithm:</p>
<p>Begin with an empty string s. For each group of consecutive repeating characters in chars:</p>
<p>If the group's length is 1, append the character to s. Otherwise, append the character followed by the group's length. The compressed string s should not be returned separately, but instead, be stored in the input character array chars. Note that group lengths that are 10 or longer will be split into multiple characters in chars.</p>
<p>After you are done modifying the input array, return the new length of the array.</p>
<p>You must write an algorithm that uses only constant extra space.</p>
</blockquote>
<p>I tried to solve this solution in <strong>O(n)</strong> time complexity.
Even though I did it, it is a lot slower.</p>
<pre><code> def compress(self, chars: List[str]) -> int:
i = 0
while i < len(chars):
count = 0
for char in chars[i:]:
if char != chars[i]:
break
count += 1
if count != 1:
list_appending = list(str(count))
chars[i+1:i+count] = list_appending
i += 1 + len(list_appending)
else:
i += 1
return len(chars)
</code></pre>
<p>Please can you give the reason why my solution is not so fast?? Why is my O(n) solution for Leetcode (443) String Compression not optimal?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T16:57:34.453",
"Id": "526705",
"Score": "1",
"body": "It is not \\$O(n)\\$. List slicing itself is linear in the length of the slice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T06:32:45.827",
"Id": "527737",
"Score": "0",
"body": "Pardon me for that I didn't notice."
}
] |
[
{
"body": "<p>It's not <span class=\"math-container\">\\$O(n)\\$</span> but <span class=\"math-container\">\\$O(n^2)\\$</span>, because:</p>\n<ul>\n<li><code>chars[i:]</code> takes <span class=\"math-container\">\\$O(n)\\$</span> time and space. You could instead move a second index <code>j</code> forwards until the last occurrence and then compute the length as <code>j - i + 1</code>.</li>\n<li><code>chars[i+1:i+count] = list_appending</code> takes <span class=\"math-container\">\\$O(n)\\$</span> time. Instead of replacing all <code>count</code> equal characters, better replace exactly as many as you need for the digits. Then the remaining characters don't get moved and it's <span class=\"math-container\">\\$O(1)\\$</span> (amortized).</li>\n</ul>\n<p>You shrink the list. I'd say you're not supposed to. If you were supposed to shrink the list, why would they want you to return the list length? I think you're supposed to write the compressed data into a prefix of the list and return where that compressed data ends. Like they requested in an <a href=\"https://leetcode.com/problems/remove-duplicates-from-sorted-array/\" rel=\"nofollow noreferrer\">earlier problem</a>.</p>\n<p>Converting <code>str(count)</code> to a list is unnecessary. And I'd find <code>digits</code> a more meaningful name than <code>list_appending</code>.</p>\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/#pet-peeves\" rel=\"nofollow noreferrer\">PEP 8</a> suggests to write <code>chars[i+1:i+count]</code> as <code>chars[i+1 : i+count]</code> (and I agree).</p>\n<p>This is essentially a job for <a href=\"https://docs.python.org/3/library/itertools.html#itertools.groupby\" rel=\"nofollow noreferrer\"><code>itertools.groupby</code></a>, here's a solution using that:</p>\n<pre><code> def compress(self, chars: List[str]) -> int:\n def compress():\n for c, g in groupby(chars):\n yield c\n k = countOf(g, c)\n if k > 1:\n yield from str(k)\n for i, chars[i] in enumerate(compress()):\n pass\n return i + 1\n</code></pre>\n<p>Just for fun a bad but also fast regex solution:</p>\n<pre><code> def compress(self, chars: List[str]) -> int:\n chars[:] = re.sub(\n r'(.)\\1+',\n lambda m: m[1] + str(len(m[0])),\n ''.join(chars))\n return len(chars)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T06:30:00.883",
"Id": "527736",
"Score": "0",
"body": "I really appreciate your efforts. And thanks for the information I would follow rule about clean coding too.\nBut still that code ran so slow only about beating 20% users.\nCan I know why??"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T15:34:52.563",
"Id": "527779",
"Score": "0",
"body": "It's not much slower than the faster ones, if at all. Look at the time distribution graph. And LeetCode's timing is unstable. How often did you submit it, and what were the individual results?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T22:00:54.627",
"Id": "266610",
"ParentId": "266598",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T15:48:26.747",
"Id": "266598",
"Score": "0",
"Tags": [
"python",
"time-limit-exceeded"
],
"Title": "Leetcode (443) String Compression"
}
|
266598
|
<p>Input consists of 2 lists</p>
<p>Products: [[20, 'discount1', 'discount2']], [15, 'discount2'], [10, 'NONE', 'discount1']]</p>
<p>Discounts: [['discount1', 1, 30], ['discount2', 2, 5.5]]</p>
<p>= = =</p>
<p>Each product list consist of [product-price, discount-name, discount-name, ....]</p>
<p>Each discount list consist of [discount-name, discount-type, discount-amount]</p>
<p>= = = =</p>
<p>Discount-type 1: Take the discount amount as percentage and subtract it from product price</p>
<p>Discount-type 2: Take the discount amount as discount price and subtract it from product price</p>
<p>= = =</p>
<p>The goal is to determine optimal price for each product and sum it to total price. As each optimal price is calculated, I round it to the nearest integer.</p>
<p>Ex: (using the above 2 lists)</p>
<p>Take product 1, which is $20. Apply 'discount1'. 'discount1' is type 1 so do the following
20 - 20(.30) = 14 -> Math.round(14) = 14</p>
<p>Now apply 'discount2'. 'discount2' is type 2 so do the following
20 - 5.5 = 14.5 -> Math.round(14.5) = 15</p>
<p>Since 14 < 15, I take 14 as the optimal price for product 1 and add it to a finalPrice variable. I do this for the rest of the products</p>
<pre><code>public class Solution {
static class DisHelper {
int type;
double d;
DisHelper(int type, double d) {
this.type=type;
this.d=d;
}
}
public static int Price(List<List<String>> products, List<List<String>> discounts) {
int finalPrice=0;
HashMap<String, DisHelper> map = new HashMap<>();
for(List<String> list: discounts) {
map.put(list.get(0), new DisHelper(Integer.parseInt(list.get(1)), Double.parseDouble(list.get(2))));
}
for(List<String> list: products) {
double originalPrice = Double.parseDouble(list.get(0));
double optimalPrice = originalPrice;
for(int i=1;i<list.size();i++) {
if(list.get(i).equals("NONE")) {
continue;
}
double price1=originalPrice;
DisHelper subDisObj = map.get(list.get(i));
if(subDisObj.type==1) {
price1=Math.round(price1-(price1*(subDisObj.d/(double)100)));
} else if(subDisObj.type==2) {
price1=Math.round(price1-subDisObj.d);
}
optimalPrice=Math.min(optimalPrice, price1);
}
finalPrice+=(int)optimalPrice;
}
return finalPrice;
}
public static void main(String[] args) {
List<List<String>> products = new ArrayList<>();
List<List<String>> discounts = new ArrayList<>();
products.add(new ArrayList<>(List.of("20", "discount1", "discount2")));
products.add(new ArrayList<>(List.of("15", "discount2")));
products.add(new ArrayList<>(List.of("10", "NONE", "discount1")));
discounts.add(new ArrayList<>(List.of("discount1", "1", "30")));
discounts.add(new ArrayList<>(List.of("discount2", "2", "5.5")));
System.out.println(Price(products, discounts));
}
}
</code></pre>
<p><strong>Analysis</strong>
Say we have M products, N discounts, and k discount names for each product.</p>
<p>Populating HashMap: O(N)</p>
<p>Going through each product: O(M)</p>
<p>Going through each discount (for each product) O(M * k)</p>
<p>Time complexity: O(max(N, M * k))</p>
<p>Space Complexity: O(N) for Hashmap.</p>
<p><strong>Are the time and space complexities correct?</strong></p>
<p><strong>Can I optimize this code?</strong></p>
|
[] |
[
{
"body": "<p>Your time and space complexities are correct. You could also write your time complexity as O(N+M*k), which is equivalent.</p>\n<p>There are a few things that could be improved in your code but it shouldn't change its runtime perfs much.</p>\n<h2>Naming conventions</h2>\n<p>Most of your variable are slightly misnamed or have not-quite-helpful names, and so does <code>DisHelper</code>. I assume that you're doing an online challenge where the <code>Price</code> method is an imposed signature so I'll ignore it.</p>\n<p>Calling <code>DisHelper</code> that way instead of <code>DiscountHelper</code>, you spare 4 characters in exchange for code clarity.</p>\n<p>Your <code>finalPrice</code> really is more a <code>totalPrice</code>, since it is the sum of all your optimal prices. At first glance, with this name, I expected it to contain the final price of the current product.</p>\n<p>Those are two examples but <code>price1</code>, <code>subDisObj</code> and <code>list</code> share similar issues.</p>\n<h2>Coding against the interface</h2>\n<p>You should (almost) never explicitly declare a variable as a <code>HashMap</code>. Since you only use the <code>Map</code> interface, you should instead do <code>Map<String, DisHelper> map = new HashMap<>();</code>. That way, changing from a <code>HashMap</code> to any other type of <code>Map</code> will have less impact on your code.</p>\n<h2>Number handling</h2>\n<p>It seems that your originalPrice will always be an <code>int</code> but you parse it as a <code>double</code>. Then, you cast it back to an <code>int</code> at the last moment, when adding it to <code>finalPrice</code>.</p>\n<p>Instead, you could only keep it as an <code>int</code>, and cast the result of the discount as as an <code>int</code>. You could save an infinitesimal amount of time comparing two <code>int</code> (32 bits) instead of two <code>double</code> (64 bits). With a very large number of test cases on an online challenge, that could potentially save you some milliseconds, but probably not much more.</p>\n<p>One way to do that would be to replace</p>\n<pre><code> double price1=originalPrice;\n DisHelper subDisObj = map.get(list.get(i));\n if(subDisObj.type==1) {\n price1=Math.round(price1-(price1*(subDisObj.d/(double)100)));\n } else if(subDisObj.type==2) {\n price1=Math.round(price1-subDisObj.d);\n }\n optimalPrice=Math.min(optimalPrice, price1);\n</code></pre>\n<p>by</p>\n<pre><code> int currentPrice;\n DisHelper subDisObj = map.get(list.get(i));\n if (subDisObj.type==1) {\n currentPrice = (int) Math.round(originalPrice*(1-subDisObj.d/100.0));\n } else if (subDisObj.type==2) {\n currentPrice = (int) Math.round(originalPrice-subDisObj.d);\n }\n optimalPrice=Math.min(optimalPrice, currentPrice);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T20:45:56.027",
"Id": "526723",
"Score": "0",
"body": "There is excellent feedback. Would you say I have the optimal solution? For each product, I'm traversing through each discount name. This part takes O(M*k). I'm wondering if I can do something here to reduce the time complexity. It seems like I can't do much for space complexity as I have to use a HashMap to retrieve discount type and value in O(1) instead of O(n)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T17:35:29.133",
"Id": "527783",
"Score": "0",
"body": "I can't prove that it is optimal, so I won't say it but it does look like it. If your input was built differently (for each product, two different lists, one with type 1 discounts and one with type 2 discounts, both of them sorted by amount of reduction), then you could reduce it down to O(M) instead of O(M*k), but that would be cheating. :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T19:51:18.120",
"Id": "266606",
"ParentId": "266600",
"Score": "1"
}
},
{
"body": "<h1>The mess you are in</h1>\n<p>Below are the initial comments. Mostly naming, but I also added code explanation comments for the purpose of the next part of refactoring. You seem to mix different levels of abstraction in a single line. For example when you iterate over the list of products, each item in the list is a product, not a "list" just because a product is represented as a list.</p>\n<p>Also notice, that your method has multiple levels of indentation. This is a sign, that the method does more than it says it does. Each explanation comment is basically saying what the method does.</p>\n<pre><code>...\n // Minor naming: Seems like Discount would be more appropriate\n static class DisHelper {\n int type;\n // Major naming: why not amount?\n double d;\n DisHelper(int type, double d) {\n this.type=type;\n this.d=d;\n }\n }\n\n // Minor naming: method names should be in camel case\n // Minor naming: method does not really say what it does (there is no verb in the name and it isn't a getter either)\n public static int Price(List<List<String>> products, List<List<String>> discounts) {\n int finalPrice=0;\n\n // Major naming: discountMap instead of map\n // Explanation: this block builds the map out of discount list\n HashMap<String, DisHelper> map = new HashMap<>();\n // Major naming: why list? discount would be a better name\n for(List<String> list: discounts) {\n map.put(list.get(0), new DisHelper(Integer.parseInt(list.get(1)), Double.parseDouble(list.get(2))));\n }\n\n // Explanation: this block sums the total price\n // Major naming: same as above: list is not a good name\n for(List<String> list: products) {\n double originalPrice = Double.parseDouble(list.get(0));\n double optimalPrice = originalPrice;\n\n // Explanation: this block calculates the optimal price\n for(int i=1;i<list.size();i++) {\n if(list.get(i).equals("NONE")) {\n continue;\n }\n\n // Explanation: this block calculates the price with discount\n // Minor naming: priceWithDiscount\n double price1=originalPrice;\n // Minor naming: discount\n DisHelper subDisObj = map.get(list.get(i));\n if(subDisObj.type==1) {\n price1=Math.round(price1-(price1*(subDisObj.d/(double)100)));\n } else if(subDisObj.type==2) {\n price1=Math.round(price1-subDisObj.d);\n }\n\n optimalPrice=Math.min(optimalPrice, price1);\n }\n\n finalPrice+=(int)optimalPrice;\n }\n return finalPrice;\n }\n...\n</code></pre>\n<h1>Fix the names</h1>\n<p>Next step is removing the naming comments. And also, we'll make the code breathe (notice the code has more space and is easier to read - full credit to IDE formatting tool, I didn't do this by hand).</p>\n<pre><code> static class Discount {\n int type;\n double amount;\n\n Discount(int type, double amount) {\n this.type = type;\n this.amount = amount;\n }\n }\n\n public static int calculateOptimalPrice(List<List<String>> products, List<List<String>> discounts) {\n int finalPrice = 0;\n\n // Explanation: this block builds the map out of discount list\n HashMap<String, Discount> discountMap = new HashMap<>();\n for (List<String> list : discounts) {\n discountMap.put(list.get(0), new Discount(Integer.parseInt(list.get(1)), Double.parseDouble(list.get(2))));\n }\n\n // Explanation: this block sums the total price\n for (List<String> product : products) {\n double originalPrice = Double.parseDouble(product.get(0));\n double optimalPrice = originalPrice;\n\n // Explanation: this block calculates the optimal price\n for (int i = 1; i < product.size(); i++) {\n if (product.get(i).equals("NONE")) {\n continue;\n }\n\n // Explanation: this block calculates the price with discount\n double priceWithDiscount = originalPrice;\n Discount discount = discountMap.get(product.get(i));\n if (discount.type == 1) {\n priceWithDiscount = Math.round(priceWithDiscount - (priceWithDiscount * (discount.amount / (double) 100)));\n } else if (discount.type == 2) {\n priceWithDiscount = Math.round(priceWithDiscount - discount.amount);\n }\n\n optimalPrice = Math.min(optimalPrice, priceWithDiscount);\n }\n\n finalPrice += (int) optimalPrice;\n }\n return finalPrice;\n }\n</code></pre>\n<h1>Break things up</h1>\n<p>Next is converting explanation comments into methods. Make sure that the names are meaningful and explain what the method does.</p>\n<pre><code> public static int calculateOptimalPrice(List<List<String>> products, List<List<String>> discounts) {\n HashMap<String, Discount> discountMap = buildDiscountMap(discounts);\n /*\n If you want to impress friends\n return products.stream()\n .mapToInt(product -> calculateOptimalProductPrice(discountMap, product))\n .sum();\n */\n int finalPrice = 0;\n\n for (List<String> product : products) {\n finalPrice += calculateOptimalProductPrice(discountMap, product);\n }\n\n return finalPrice;\n }\n\n private static int calculateOptimalProductPrice(HashMap<String, Discount> discountMap, List<String> product) {\n double originalPrice = Double.parseDouble(product.get(0));\n double optimalPrice = originalPrice;\n\n for (int i = 1; i < product.size(); i++) {\n if (product.get(i).equals("NONE")) {\n continue;\n }\n\n Discount discount = discountMap.get(product.get(i));\n double discountedPrice = calculateDiscountedProductPrice(discount, originalPrice);\n\n optimalPrice = Math.min(optimalPrice, discountedPrice);\n }\n\n return (int) optimalPrice;\n }\n\n // Major OO: you need to pass discount and original price in just to calculate based on type\n // It would be better to move this method into Discount class\n private static double calculateDiscountedProductPrice(Discount discount, double originalPrice) {\n if (discount.type == 1) {\n return Math.round(originalPrice - (originalPrice * (discount.amount / (double) 100)));\n } else if (discount.type == 2) {\n return Math.round(originalPrice - discount.amount);\n } else {\n throw new IllegalArgumentException("Unknown discount type");\n }\n }\n\n private static HashMap<String, Discount> buildDiscountMap(List<List<String>> discounts) {\n HashMap<String, Discount> discountMap = new HashMap<>();\n for (List<String> discount : discounts) {\n discountMap.put(discount.get(0), new Discount(Integer.parseInt(discount.get(1)), Double.parseDouble(discount.get(2))));\n }\n return discountMap;\n }\n</code></pre>\n<h1>Small details make the difference</h1>\n<p>This is already enough for what this code does, but just for the sake of it, let's refactor to remove the new OO comment.</p>\n<pre><code> private static class Discount {\n private final int type;\n private final double amount;\n\n Discount(int type, double amount) {\n this.type = type;\n this.amount = amount;\n }\n\n public double apply(double originalPrice) {\n if (this.type == 1) {\n return Math.round(originalPrice - (originalPrice * (this.amount / (double) 100)));\n } else if (this.type == 2) {\n return Math.round(originalPrice - this.amount);\n } else {\n throw new IllegalArgumentException("Unknown discount type");\n }\n }\n }\n\n ...\n Discount discount = discountMap.get(product.get(i));\n double discountedPrice = discount.apply(originalPrice);\n\n optimalPrice = Math.min(optimalPrice, discountedPrice);\n ...\n</code></pre>\n<h1>You can never over engineer</h1>\n<p>Now that the comment is removed, I wonder what would happen if we applied the same concept to the product. Let's make product a class the same way you did with discount.</p>\n<pre><code>private static class Product {\n private final int price;\n private final List<Discount> discounts;\n\n public Product(int price, List<Discount> discounts) {\n this.price = price;\n this.discounts = discounts;\n }\n\n public int optimalPrice() {\n /*\n To show off\n discounts.stream()\n .mapToInt(discount -> (int) discount.apply(this.price))\n .min();\n */\n\n int price = this.price;\n\n for (Discount discount : discounts) {\n price = Math.min(price, (int) discount.apply(this.price));\n }\n\n return price;\n }\n }\n\n private static List<Product> buildProducts(List<List<String>> productsInput, HashMap<String, Discount> discountMap) {\n return productsInput.stream()\n .map(productInput -> mapInputToProduct(productInput, discountMap))\n .toList();\n }\n\n private static Product mapInputToProduct(List<String> product, Map<String, Discount> discountMap) {\n int price = Integer.parseInt(product.get(0));\n List<Discount> discounts = new ArrayList<>();\n\n for (int i = 1; i < product.size(); i++) {\n if (product.get(i).equals("NONE")) {\n continue;\n }\n\n Discount discount = discountMap.get(product.get(i));\n discounts.add(discount);\n }\n\n return new Product(price, discounts);\n }\n\n...\n for (Product product : products) {\n finalPrice += product.optimalPrice();\n }\n...\n</code></pre>\n<h1>As I said, never!</h1>\n<p>As you can see, building the product (essentialy parsing the input) is the only messy part. It could probably be refactored further, but it is good enough. The important part is that Product is clean.</p>\n<p>Looking at what we have now you might say: But what if I add different types of discounts in the future, that will use different criteria to apply the discount. Coding this way you will need to expand the apply method with additional if statements. Let's fix this by making Discount an interface and change how discount input is being parsed.</p>\n<pre><code> interface Discount {\n double apply(double amount);\n }\n\n private static class PercentageDiscount implements Discount {\n private final double amount;\n\n public PercentageDiscount(double amount) {\n this.amount = amount;\n }\n\n @Override\n public double apply(double originalPrice) {\n return Math.round(originalPrice - (originalPrice * (this.amount / (double) 100)));\n }\n }\n\n private static class PriceDiscount implements Discount {\n private final double amount;\n\n public PriceDiscount(double amount) {\n this.amount = amount;\n }\n\n @Override\n public double apply(double originalPrice) {\n return Math.round(originalPrice - this.amount);\n }\n }\n\n...\n\n private static HashMap<String, Discount> buildDiscountMap(List<List<String>> discounts) {\n HashMap<String, Discount> discountMap = new HashMap<>();\n for (List<String> discount : discounts) {\n discountMap.put(discount.get(0), mapInputToDiscount(discount));\n }\n return discountMap;\n }\n\n private static Discount mapInputToDiscount(List<String> discount) {\n int type = Integer.parseInt(discount.get(1));\n double amount = Double.parseDouble(discount.get(2));\n\n if(type == 1) {\n return new PercentageDiscount(amount);\n } else if(type == 2) {\n return new PriceDiscount(amount);\n } else {\n throw new IllegalArgumentException("Unknown discount type");\n }\n }\n...\n</code></pre>\n<h1>But maybe I can...</h1>\n<p>This is as far as you can go refactoring your code I think. You can notice that most of the work is actually parsing the input into something "readable", after that it is pretty much self explainatory.</p>\n<p>I have applied a few cleanups to parsing and this is what the final result looks like:</p>\n<pre><code> public static int calculateOptimalPrice(List<Product> products) {\n return products.stream()\n .mapToInt(Product::optimalPrice)\n .sum();\n }\n</code></pre>\n<p>...But there is a lot of stuff going on in the background. When lookig at it, focus on the main method and explore what each that is invoked looks like. Don't start reading from top to bottom as your head will start spinning.</p>\n<p>This is actually what the final result is:</p>\n<pre><code>public class Solution {\n\n interface Discount {\n double apply(double amount);\n }\n\n private static class PercentageDiscount implements Discount {\n private final double amount;\n\n public PercentageDiscount(double amount) {\n this.amount = amount;\n }\n\n @Override\n public double apply(double originalPrice) {\n return Math.round(originalPrice - (originalPrice * (this.amount / (double) 100)));\n }\n }\n\n private static class PriceDiscount implements Discount {\n private final double amount;\n\n public PriceDiscount(double amount) {\n this.amount = amount;\n }\n\n @Override\n public double apply(double originalPrice) {\n return Math.round(originalPrice - this.amount);\n }\n }\n\n private static class Product {\n private final int price;\n private final List<Discount> discounts;\n\n public Product(int price, List<Discount> discounts) {\n this.price = price;\n this.discounts = discounts;\n }\n\n public int optimalPrice() {\n return discounts.stream()\n .mapToInt(discount -> (int) discount.apply(this.price))\n .min()\n .orElse(this.price);\n }\n }\n\n private static class ProductMapper {\n private final Map<String, Discount> discountMap;\n\n public ProductMapper(Map<String, Discount> discountMap) {\n this.discountMap = discountMap;\n }\n\n public Product toProduct(List<String> input) {\n int price = Integer.parseInt(input.get(0));\n input.remove(0);\n\n List<Discount> discounts = findAssociatedDiscounts(input);\n\n return new Product(price, discounts);\n }\n\n public List<Product> toProductList(List<List<String>> productsInput) {\n return productsInput.stream()\n .map(this::toProduct)\n .toList();\n }\n\n private List<Discount> findAssociatedDiscounts(List<String> discounts) {\n return discounts.stream()\n .map(discountMap::get)\n .filter(Objects::nonNull)\n .toList();\n }\n }\n\n private static class DiscountMapper {\n public Discount toDiscount(List<String> input) {\n int type = Integer.parseInt(input.get(1));\n double amount = Double.parseDouble(input.get(2));\n\n if(type == 1) {\n return new PercentageDiscount(amount);\n } else if(type == 2) {\n return new PriceDiscount(amount);\n } else {\n throw new IllegalArgumentException("Unknown discount type");\n }\n }\n\n public Map<String, Discount> toDiscountMap(List<List<String>> discounts) {\n HashMap<String, Discount> discountMap = new HashMap<>();\n for (List<String> discount : discounts) {\n discountMap.put(discount.get(0), this.toDiscount(discount));\n }\n return discountMap;\n }\n }\n\n public static int calculateOptimalPrice(List<Product> products) {\n return products.stream()\n .mapToInt(Product::optimalPrice)\n .sum();\n }\n\n public static void main(String[] args) {\n\n List<List<String>> productsInput = new ArrayList<>();\n List<List<String>> discountsInput = new ArrayList<>();\n productsInput.add(new ArrayList<>(List.of("20", "discount1", "discount2")));\n productsInput.add(new ArrayList<>(List.of("15", "discount2")));\n productsInput.add(new ArrayList<>(List.of("10", "NONE", "discount1")));\n discountsInput.add(new ArrayList<>(List.of("discount1", "1", "30")));\n discountsInput.add(new ArrayList<>(List.of("discount2", "2", "5.5")));\n\n // Moved input parsing out of the total price calculation\n Map<String, Discount> discountMap = new DiscountMapper().toDiscountMap(discountsInput);\n List<Product> products = new ProductMapper(discountMap).toProductList(productsInput);\n\n System.out.println(calculateOptimalPrice(products));\n\n }\n}\n</code></pre>\n<p>The code is longer, it is probably slower, is more complex architecturaly and still only prints 31. But each part only does one job and is easy to change and to understand what the change will affect. The biggest change from the original is probably that Discount and Product are classes now, which makes it way easier to manage.</p>\n<p>Another benefit from this approach is that you can represent the input differently, but you will only need to change the parsing - the "business rules" are isolated and don't know about how original input looked like.</p>\n<p>Hopefully this wasn't too much at once :) I tried to split everything in small steps to be easier to understand how your code trippled in size. If you take anything away from this, let it be naming and asking yourself what a block of code does so you can extract it into a new method (the first two improvements).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-02T00:51:01.203",
"Id": "268585",
"ParentId": "266600",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268585",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T17:23:58.090",
"Id": "266600",
"Score": "1",
"Tags": [
"java",
"performance"
],
"Title": "Optimal Price of Products after Discounts"
}
|
266600
|
<h3>Preface</h3>
<p>I have been trying to find out "How to make Client-side Prediction and Server Reconciliation" from scratch with an easy-to-understand code in C#.
So I decided to make my own implementation of Client-side Prediction and Server Reconciliation.
The Client-side Prediction and Server Reconciliation system I want to make is one that everyone can use.
I'd appreciate if you could discuss with me to find the a better way or a way that everyone would understand.</p>
<h3>Original Files</h3>
<p>Client Side: PlayerController.cs, ClientSend.cs and ClientHandler.cs <a href="https://github.com/tom-weiland/tcp-udp-networking/tree/tutorial-part11/GameClient/Assets/Scripts" rel="nofollow noreferrer">Tom Weiland GitHub Link</a>.<br />
Server Side: Server.cs, ServerHandler.cs and ServerSend.cs: <a href="https://github.com/tom-weiland/tcp-udp-networking/tree/tutorial-part11/UnityGameServer/Assets/Scripts" rel="nofollow noreferrer">Tom Weiland GitHub Link</a>.<br />
The link that I read to try to make my own implementation: <a href="https://github.com/spectre1989/unity_physics_csp/blob/d0a1f2e5642e5833d373d8b2c1ce2ac5eb438b3b/Assets/Logic.cs" rel="nofollow noreferrer">spectre1989 GitHub Link</a></p>
<h3>Code</h3>
<p>First off, the spectre1989 code has server and client in the same code and Tom Weiland doesn't, so I had to adapt the code. Secondly, spectre1989 code uses a type of tick, but since the server and client are in the same code, the tick in the client and server starts to count at the same time and because of that the tick works, but in the Tom Weiland code, the client and the server initiate in different time, because they are separated, so a tick system would not work (or could, but I don't now how to achieve this), so I made it use the current time instead.</p>
<p><code>PlayerController.cs</code></p>
<pre><code>private void Update()
{
float dt = Time.fixedDeltaTime;
float client_timer = this.client_timer;
client_timer += Time.deltaTime;
if (client_state_buffer.Any()) {client_state_buffer = client_state_buffer.Distinct().ToList();}
if (client_state_msgs.Any()) {client_state_msgs = client_state_msgs.Distinct().ToList();}
if (client_state_buffer.Any())
{
foreach (PlayerState state in client_state_buffer)
{
DateTime newDateTime = new DateTime();
newDateTime = newDateTime + (DateTime.Now - state.time);
if (newDateTime > Convert.ToDateTime("00:00:30"))
{
client_state_buffer.Remove(state);
}
}
}
if (client_state_msgs.Any())
{
foreach (PlayerState state in client_state_msgs)
{
DateTime newDateTime = new DateTime();
newDateTime = newDateTime + (DateTime.Now - state.time);
if (newDateTime > Convert.ToDateTime("00:00:30"))
{
client_state_msgs.Remove(state);
}
}
}
while(client_timer >= dt)
{
client_timer -= dt;
bool[] PlayerInput = CheckForInput();
DateTime TimeNow = Convert.ToDateTime(DateTime.Now.ToString("HH:mm:ss"));
InputState state = new InputState();
state.time = TimeNow;
state.inputs = PlayerInput;
if (!client_input_buffer.Contains(state) && PlayerInput.Contains(true)) {client_input_buffer.Add(state);}
PlayerState playerState = new PlayerState();
playerState.position = controller.gameObject.transform.position;
playerState.rotation = controller.gameObject.transform.rotation;
playerState.time = TimeNow;
Move(CalculateInputDirection(PlayerInput), controller, PlayerInput);
if (!client_state_buffer.Contains(playerState) && PlayerInput.Contains(true)) {client_state_buffer.Add(playerState);}
if (PlayerInput.Contains(true)) {ClientSend.PlayerMovement(state);}
}
this.client_timer = client_timer;
while (ClientHasStateMessage(client_state_msgs))
{
PlayerState server_state = client_state_msgs.OrderByDescending(x => x.time).FirstOrDefault();
PlayerState prev_state = client_state_buffer.OrderByDescending(x => x.time).FirstOrDefault();
if (server_state.time <= prev_state.time)
{
Vector3 position_error = Vector3.zero;
float rotation_error = 0f;
position_error = server_state.position - prev_state.position;
rotation_error = 1.0f - Quaternion.Dot(server_state.rotation, prev_state.rotation);
if (position_error.sqrMagnitude > 0.0000001f || rotation_error > 0.00001f)
{
gameObject.transform.position = server_state.position;
gameObject.transform.rotation = server_state.rotation;
}
client_state_msgs.Remove(server_state);
client_state_buffer.Remove(prev_state);
}
else
{
client_state_msgs.Remove(server_state);
}
}
}
</code></pre>
<p><code>ClientSend.cs</code></p>
<pre><code>public static void PlayerMovement(PlayerController.InputState state)
{
using (Packet _packet = new Packet((int)ClientPackets.playerMovement))
{
_packet.Write(state.time.ToString());
_packet.Write(state.inputs.Length);
foreach (bool input in state.inputs)
{
_packet.Write(input);
}
SendUDPData(_packet);
}
}
</code></pre>
<p><code>ClientHandle.cs</code></p>
<pre><code>public static void PlayerPosition(Packet _packet)
{
int _id = _packet.ReadInt();
DateTime time = Convert.ToDateTime(_packet.ReadString());
Vector3 _position = _packet.ReadVector3();
Quaternion _rotation = _packet.ReadQuaternion();
PlayerController.PlayerState state = new PlayerController.PlayerState();
state.time = time;
state.position = _position;
state.rotation = _rotation;
if (GameManager.players.TryGetValue(_id, out PlayerManager _player))
{
if (_player.gameObject.GetComponent<PlayerController>() != null)
{
_player.gameObject.GetComponent<PlayerController>().client_state_msgs.Add(state);
}
else
{
_player.transform.position = _position;
}
}
}
</code></pre>
<p><code>ServerHandle.cs</code></p>
<pre><code>public static void PlayerMovement(int _fromClient, Packet _packet)
{
string time = _packet.ReadString();
bool[] inputs = new bool[_packet.ReadInt()];
for (int i = 0; i < inputs.Length; i++)
{
inputs[i] = _packet.ReadBool();
}
Server.InputState state = new Server.InputState();
state.time = time;
state.inputs = inputs;
Server.SimulatePlayerInput(state, _fromClient);
}
</code></pre>
<p><code>ServerSend.cs</code></p>
<pre><code>public static void PlayerPosition(Player _player, Server.PlayerState state_msg)
{
using (Packet _packet = new Packet((int)ServerPackets.playerPosition))
{
_packet.Write(_player.id);
_packet.Write(state_msg.time);
_packet.Write(state_msg.position);
_packet.Write(state_msg.rotation);
SendUDPDataToAll(_packet);
}
}
</code></pre>
<p><code>Server.cs</code></p>
<pre><code>public static void SimulatePlayerInput(InputState state, int _fromClient)
{
MovePlayer(CalculateInputDirection(state.inputs), clients[_fromClient].player, state.inputs);
PlayerState state_msg = new PlayerState();
state_msg.time = DateTime.Now.ToString("HH:mm:ss");
state_msg.position = clients[_fromClient].player.gameObject.transform.position;
state_msg.rotation = clients[_fromClient].player.gameObject.transform.rotation;
ServerSend.PlayerPosition(clients[_fromClient].player, state_msg);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T18:16:29.173",
"Id": "526714",
"Score": "3",
"body": "Welcome to Code Review ガブリエル Gabriel, I have edited your question to be more inline with the type of question Code Review would expect. Please be mindful that some of the language you used before can make your question sound off-topic so I'd recommend reading our [help]. However if you think I've changed your question to something you don't want please feel free to overrule any edits I've made."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T18:33:10.933",
"Id": "526718",
"Score": "0",
"body": "@Peilonrayz Its ok, Sorry for the inconvenience."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-06T00:20:53.847",
"Id": "527916",
"Score": "0",
"body": "@Peilonrayz Why nobody wants to help me?"
}
] |
[
{
"body": "<p><strong>A better way, in which way ?</strong></p>\n<blockquote>\n<p>I'd appreciate if you could discuss with me to find the a better way [...]</p>\n</blockquote>\n<p>That's a tricky one. Make it easier to read, optimize it, make the maintenance later on easier ? The better way is way too vague to know how you want it better. What is better to your eyes ?</p>\n<blockquote>\n<p>[...] or a way that everyone would understand.</p>\n</blockquote>\n<p>This one is magic, please understand that. Who is everyone ? Your boss, the next student that will have to fix a bug in your software, your teacher, your manager, your CEO, the guy that cleans the office when everyone is gone ?</p>\n<p>But since I like to discuss, let's discuss. I will talk about the points that I think are important :</p>\n<ul>\n<li>Your code can be undesrtood by yourself in a year or two, when you will have forgotten about how you made it in the first place. That's not everyone, just you is a really good start.</li>\n<li>Your code respects some standards you have in your company, your department or just with yourself. That will help on understanding your code by others. That includes general C# coding standards.</li>\n<li>Your code can be documented easily if needed (and it should be needed...)</li>\n</ul>\n<p>So I won't talk about optimization here, since your problem is not in my domain.</p>\n<p><strong>1. Comment you code</strong></p>\n<p>In all your code, there is not a single comment. This already goes against your claim to be understood by everyone. You are already limiting this to "anyone who can read and understand C#" (that generally excludes the CEO...).</p>\n<p>There are two ways, to insert valuable comments :</p>\n<ol>\n<li>Above a method or a class, that's XML Documentation</li>\n<li>Inside the method.</li>\n</ol>\n<p>XML Documentation is used by Intellisense in Visual Studio to help you. It is also used by software that build documentation packages.</p>\n<p>To create it, add three slashes before a method. There you can input the method description and anything there is to know about it.</p>\n<p>Inside the method you should put comments that will help understand your algorythm.</p>\n<p><strong>2. No long methods</strong></p>\n<p>Your update method is very long, and doing lots of stuff. Wouldn't it be better, for the sake of readability, to split this into smaller methods, each of them doing one little thing ?</p>\n<p><strong>3. Naming conventions consistency</strong></p>\n<p>There are at least a million different naming conventions. And a million debates that justify each of them. Some are good, some seem better. Truth is, it doesn't really matter.</p>\n<p>The only thing that matters is to stick to one naming convention. Make it the same for all your code, your department, your company (usually the company tells you the convention)...</p>\n<p>Here you declare this :</p>\n<p><code>public static void SimulatePlayerInput(InputState state, int _fromClient)</code>.</p>\n<p>Why is one parameter starting with a lower case and the next one with an underscore ? Maybe you have a good reason, maybe not. But I do not understand your naming convention from that.</p>\n<p><strong>4. BUGS</strong></p>\n<p>I'm sorry to disappoint you, but your code as stated will generate errors...</p>\n<pre><code>client_state_buffer.Remove(state);\n</code></pre>\n<p>This is in an iterator loop, so the moment this instruction will be reached an exception will be thrown because you cannot modify a collection that you are iterating through. You need to use <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.removeall?redirectedfrom=MSDN&view=net-5.0#System_Collections_Generic_List_1_RemoveAll_System_Predicate__0__\" rel=\"nofollow noreferrer\">Linq RemoveAll method</a>.</p>\n<p><strong>5. The code</strong></p>\n<p>Let's analyse your Update method (I will leave it to you to adapt what I'm saying here for the rest):</p>\n<p>You start by initializing variables you will only use in a while loop. We will move these along in a new method, with the loop.</p>\n<p><code>if (client_state_buffer.Any())</code> (and the following ifs)</p>\n<p>So basically, first you remove duplicates, then you remove messages older than 30 seconds. For messages and buffer... We could make a cleaning method, then call it twice, couldn't we ? Why ? Because <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">Don't Repeat Yourself</a>, that's why. The method would look like this :</p>\n<pre><code>/// <summary>\n/// Remove duplicates and entries older than 30 seconds in a given List<PlayerState>.\n/// </summary>\n/// <param name="states">The list to cleanup</param>\nprivate void CleanupStateList(List<PlayerState> states)\n{\n if (!state.Any())\n return; //We leave early if state is empty\n\n //Remove duplicates\n states = states.Distinct().ToList();\n\n //Remove all items older that 30 seconds\n //See Linq RemoveAll method\n states.RemoveAll(state => (DateTime.Now - state.time) > Convert.ToDateTime("00:00:30"));\n}\n</code></pre>\n<p>Then the start of our upload method is just two calls to this method...</p>\n<p>The first while loop should go in a separate method. Since the timer variable you declared earlier is only used in this loop, it will declared in the new method. I won't discuss what is done here but rather how it is presented :</p>\n<pre><code>private void HandlePlayerInput()\n{\n //I removed the dt variable, only used twice in a row... Unless Unity updates this variable between two iterations.\n //I name clientTimer differently from the instance variable, because it is dangerous.\n //If you forget the this keyword, you can get nasty bugs, hard to debug...\n float clientTimer = this.client_timer + Time.deltaTime;\n while(clientTimer >= Time.fixedDeltaTime)\n { \n clientTimer -= Time.fixedDeltaTime;\n \n //[...]\n //The rest of the loop is untouched\n } \n \n this.client_timer = clientTimer;\n}\n</code></pre>\n<p>That leaves us with the last while loop, which again we put in a new method :</p>\n<pre><code>private void CheckClientStateMessages()\n{\n //Just a copy/Paste of the whole while loop, as I don't discuss the algorythm.\n}\n</code></pre>\n<p>All in all, your big huge Update method looks like this now :</p>\n<pre><code>private void Update()\n{\n CleanupStateList(client_state_buffer);\n CleanupStateList(client_state_msgs);\n\n HandlePlayerInput();\n\n CheckClientStateMessages();\n}\n</code></pre>\n<p>OK, I think you may have catched the philosophy here... Hope this helps.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-10T10:08:39.627",
"Id": "267855",
"ParentId": "266601",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T16:14:26.630",
"Id": "266601",
"Score": "3",
"Tags": [
"unity3d",
"c#",
"networking"
],
"Title": "Creating a Client-Side Prediction and Server Reconciliation"
}
|
266601
|
<p>I do not receive files on holidays; I only receive files on regular days—i.e., non-holidays. I want to skip 2021-09-06 since that's a holiday (Labor Day) and I know I will not receive any files. Instead, I want to get a new file on 2021-09-07, since I will receive a file on that day.</p>
<p>I created an automated skip logic function for holidays which runs fine in SQL. Now, I want to call that same function from C#, and I want to make sure the C# code is correct.</p>
<p>This is the scalar-valued SQL function. I ran the function in SQL, and it returns the new date 2021-09-07.</p>
<pre><code>IF OBJECT_ID('dbo.usfGetMGAHolidayCalendar') IS NOT NULL
DROP FUNCTION dbo.usfGetMGAHolidayCalendar;
GO
CREATE FUNCTION dbo.usfGetMGAHolidayCalendar(@HolidayDate DATE)
RETURNS DATE
AS
BEGIN
DECLARE @MGAID INT = 1,
@SCJMGAID INT=8,
@ARSMGAID INT=16,
@MaskDate DATETIME = '2021-09-06', /*Single day holiday example*/
--@MaskDate DATETIME = '2021-11-25', /*Two day holiday example*/
@NewMaskDate DATETIME,
@IsMGAHolidayCalendar INT = 0;
SET @IsMGAHolidayCalendar=
(
SELECT COUNT(HolidayDate)
FROM xml.MGAHolidayCalendar
WHERE HolidayDate = @MaskDate
);
IF @IsMGAHolidayCalendar > 0
SET @NewMaskDate= DATEADD(dd, 1,@MaskDate)
ELSE
SET @NewMaskDate=@MaskDate
SET @IsMGAHolidayCalendar =
(
SELECT COUNT(HolidayDate)
FROM xml.MGAHolidayCalendar
WHERE HolidayDate=@NewMaskDate
);
IF @IsMGAHolidayCalendar = 1
SET @NewMaskDate = DATEADD(dd, 1,@NewMaskDate)
ELSE
SET @NewMaskDate = @NewMaskDate
RETURN @NewMaskDate;
END;
GO
</code></pre>
<p>Now, I'm calling that function from C#. I want the function to return the <code>NewFileMask</code> in this date format, <code>mm-dd-yyyy</code>. I don't want the time to be included in the date.</p>
<p>This is what I did, but I am not sure if this is correct.</p>
<pre><code>static void Main(string[] args)
{
// Set the connection string//
string connString = @"Server=.\SQL2k17; Database = SampleDB; Trusted_Connection = True;";
try
{
// sql connection object
using (SqlConnection conn = new SqlConnection(connString))
{
// define the query text
string query = @"SELECT DISTINCT dbo.usfGetMGAHolidayCalendar(@HolidayDate) AS NewFileMask;";
// define the SqlCommand object
SqlCommand cmd = new SqlCommand(query, conn);
// parameter value will be set from command line
SqlParameter param1 = new SqlParameter();
param1.ParameterName = "@HolidayDate";
param1.SqlDbType = SqlDbType.Date;
param1.Value = "2021-09-07";
// pass parameter to the SQL Command
cmd.Parameters.Add(param1);
// open connection
conn.Open();
// execute the SQLCommand
DateTime functionResult = (DateTime)cmd.ExecuteScalar();
Console.WriteLine(Environment.NewLine + "Retrieving data from database..." + Environment.NewLine);
Console.WriteLine("Retrieved result:");
// display retrieved result
Console.WriteLine("NewFileMask:{0}", functionResult.ToString("MM-dd-yyyy"));
// close connection
conn.Close();
}
}
catch (Exception ex)
{
// display error message
Console.WriteLine("Exception: " + ex.Message);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T22:47:58.373",
"Id": "526728",
"Score": "2",
"body": "1. You don't need to explicitly `.Close()` the connection as the `using` statement will take care of that for you. However, 2. `SqlCommand` is also `IDisposable`, so its usage lifetime should be wrapped in `using` as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T13:18:11.790",
"Id": "527761",
"Score": "0",
"body": "Your code seems a bit error-prone with `DateTime.Parse` and `(DateTime)`. Please prefer `TryParse` method and `as` or `is` operators."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T14:03:54.203",
"Id": "527765",
"Score": "1",
"body": "Make your life simpler and use Dapper instead of ADO.NET."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T00:54:37.763",
"Id": "527793",
"Score": "0",
"body": "`functionResult.ToString(\"MM-dd-yyyy)` seems to be missing a quote."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T08:55:56.710",
"Id": "528734",
"Score": "0",
"body": "A question that start with \"I do not received files on holidays\" is pretty puzzling. What files, how/where do you receive them, why not receive them anyway and process them later? In other words, it needs background. Maybe the problem also needs *abstraction*, i.e. reduction to function that is independent of whichever process it serves. As far as I can see it, you only need a function that returns the first date that's not in a holiday and is on or after a given date. Just a date, not \"maskdate\". The consumer of the function decides what to use it for."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T08:08:21.993",
"Id": "529004",
"Score": "0",
"body": "(@JesseC.Slicer: Try and refrain from pointing out insights about the code presented for review in comments: Even a single useful insight constitutes a useful CR answer, especially if well presented.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T08:26:03.150",
"Id": "529008",
"Score": "0",
"body": "`I want to make sure the C# code is correct` That calls for an automated test. If you are somewhat experienced in setting up such in general, but find it difficult to tell correct from erroneous for the current task, the specification of the latter may need more work. You tagged both [tag:c#] and [tag:sql]: do you want *open-ended feedback* for both snippets? Does the code presented, to the best of your knowledge, work as intended? Else, it was [off topic](https://codereview.stackexchange.com/help/on-topic)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-23T08:31:17.033",
"Id": "529009",
"Score": "0",
"body": "I’m voting to close this question because I'm under the impression that addressing points besides correctness of results is not welcome."
}
] |
[
{
"body": "<p>Your SQL function would only covers 1-day holiday, how about multi-day holidays like Memorial Day, Thanksgiving ..etc.?</p>\n<p>To cover them, you will need to get the maximum total holidays in your company, and use that number to your query.</p>\n<p>For example, say your company's holidays are usually 1-3 days, and only one holiday that is 9-day holiday. Then, what you can do in your function, is to get the given date <code>@HolidayDate</code>, add 9 days to it, then create a list of dates using <code>CTE</code> covering these 9 days range. Then, check them against <code>xml.MGAHolidayCalendar</code> excluding any matched dates. Finally, get the minimum date (which will be the next working day).</p>\n<p>Here is an example :</p>\n<pre><code>DECLARE\n -- this should be the official max of total holidays in your company for a particular holiday.\n -- here I added 9 days as example of Christmas holiday + New Year (from dec 25th, to Jan 3)\n @EndDate DATE = DATEADD(DAY, 9, @HolidayDate) \n, @Result DATE \n\n;WITH CTE AS (\n\n SELECT @StartDate WorkingDay\n UNION ALL \n SELECT DATEADD(DAY, 1, WorkingDay) WorkingDay \n FROM CTE \n WHERE WorkingDay < @EndDate\n)\nSELECT\n @Result = MIN(WorkingDay)\nFROM CTE \nWHERE \n WorkingDay NOT IN (\n SELECT\n HolidayDate \n FROM \n xml.MGAHolidayCalendar\n WHERE\n HolidayDate >= @HolidayDate \n AND HolidayDate <= @EndDate\n)\n\n/*\n IF the given @HolidayDate is not present in xml.MGAHolidayCalendar\n Then it's a working day and the @Result should be NULL\n*/\n\nRETURN ISNULL(@Result, @HolidayDate)\n</code></pre>\n<p>For the C# part, your work is fine, however, there some points needs to be mention here :</p>\n<ol>\n<li>you should always have a better naming for your variables, and avoid shortcuts, like <code>conn</code> should be <code>connection</code>, <code>cmd</code> should be <code>command</code> ..etc. the reason is short names are easy to miss, and may not be readable enough.</li>\n<li>Don't use <code>Close()</code>, <code>Dispose()</code> inside <code>using</code> blocks. as the <code>using</code> blocks will do that for you.</li>\n<li>Don't cast <code>object</code> without validating its value first. as the object might have a different value that is not compatible with the casting type.</li>\n<li>Since you're calling a scalar function, it would be better if you create a method that accepts <code>DateTime</code> and return <code>DateTime</code>, this would make it reusable.</li>\n</ol>\n<p>Here is a revision proposal :</p>\n<pre><code>try\n{\n using(var connection = new SqlConnection(connString))\n using(var command = = new SqlCommand("SELECT DISTINCT dbo.usfGetMGAHolidayCalendar(@HolidayDate) AS NewFileMask;", connection))\n {\n // parameter value will be set from command line\n SqlParameter param1 = new SqlParameter();\n param1.ParameterName = "@HolidayDate";\n param1.SqlDbType = SqlDbType.Date;\n param1.Value = "2021-09-07";\n \n // pass parameter to the SQL Command\n command.Parameters.Add(param1);\n \n connection.Open();\n var functionResult = cmd.ExecuteScalar();\n\n Console.WriteLine(Environment.NewLine + "Retrieving data from database..." + Environment.NewLine);\n Console.WriteLine("Retrieved result:");\n \n if(DateTime.TryParse(functionResult?.ToString(), out DateTime parsedResult))\n {\n // display retrieved result\n Console.WriteLine("NewFileMask:{0}", parsedResult.ToString("MM-dd-yyyy"));\n }\n else\n {\n Console.WriteLine("Error parsing the returned value : {0}", functionResult?.ToString());\n }\n \n }\n\n}\ncatch (Exception ex)\n{\n // display error message\n Console.WriteLine("Exception: " + ex.Message);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-13T14:08:41.153",
"Id": "267966",
"ParentId": "266607",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T20:23:36.223",
"Id": "266607",
"Score": "1",
"Tags": [
"c#",
"sql",
"datetime",
"sql-server"
],
"Title": "Get result of a scalar-valued SQL function from C#"
}
|
266607
|
<p>I have been using WOW.js to animate my elements for some time now. I've noticed that when a page visitor reloads the page, animations that have already "been scrolled into view" by the browser remembering the scroll position will execute when scrolling up. This is not my desired behaviour since we can assume that the visitor has already seen all the animations.</p>
<p>So far I've got the following working with success:</p>
<pre class="lang-js prettyprint-override"><code>$(function () {
function isScrolledAlready(elem) {
var docViewTop = $(window).scrollTop();
var elemTop = $(elem).offset().top;
return (elemTop >= docViewTop);
}
$('.wow').each(function () {
if (!isScrolledAlready(this)) {
$(this).removeClass('wow');
}
});
new WOW().init();
}
</code></pre>
<h3>Example</h3>
<p>Elements above <code>$(window).scrollTop()</code> should no longer execute WOW.js animations.</p>
<pre class="lang-html prettyprint-override"><code><div class="wow fadeIn" data-wow-duration="1s" data-wow-delay="0.5s">...</div>
<div class="wow fadeIn" data-wow-duration="1s" data-wow-delay="0.5s">...</div>
<div class="wow fadeIn" data-wow-duration="1s" data-wow-delay="0.5s">...</div>
// scrollTop is here, animations above here should no longer execute on a reload of the page
<div class="wow fadeIn" data-wow-duration="1s" data-wow-delay="0.5s">...</div>
<div class="wow fadeIn" data-wow-duration="1s" data-wow-delay="0.5s">...</div>
<div class="wow fadeIn" data-wow-duration="1s" data-wow-delay="0.5s">...</div>
</code></pre>
<p>I was wondering if, perhaps, there's a more performance friendly manner of approaching this problem. For pages with just a few animations this is fine, but one can imagine that a page with many <code>.wow</code>'s can become problematic.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T20:55:50.547",
"Id": "266608",
"Score": "0",
"Tags": [
"javascript",
"jquery"
],
"Title": "Stopping WOW.js animations from happening when the element is positioned before the current scroll position"
}
|
266608
|
<p>I've just created a fully working calculator for my portfolio, and I would like to get a code review. Does that code looks good, or maybe I should refactor it? Is it good enough to be a part of a portfolio of Junior Front-end Developer?</p>
<p>Here is the working page with it: <a href="https://prmk01.github.io/Calculator" rel="noreferrer">https://prmk01.github.io/Calculator</a>
(There is an option to use the keyboard instead of clicking on a buttons)</p>
<p><a href="https://github.com/PRMK01/Calculator" rel="noreferrer">The whole project is available on my GitHub.</a> I would appreciate reviewing my whole project. But I'm posting most of the Javascript here, because every post have to contain at least 3 lines of code:</p>
<pre><code>const activatedButtons = document.querySelectorAll('.inactive');
const topRow = document.querySelector('.screen-top-part');
const bottomRow = document.querySelector('.screen-bottom-part');
const basicOperators = /\+|-|÷|×/;
let expression = '';
let bottomRowActive = true;
let memory = '';
function memoryUpdate (target) {
bottomRowActive = false;
for (button of activatedButtons) {
button.classList.remove('inactive');
}
switch (target.innerText) {
case 'MC': {
memory = '';
for (button of activatedButtons) {
button.classList.add('inactive');
}
break
} case 'MR': {
clearEntry();
bottomRow.innerText = memory;
break
} case 'M+': {
memory = eval(+memory + +bottomRow.innerText).toString();
break
} case 'M-': {
memory = eval(+memory - +bottomRow.innerText).toString();
break
} case 'MS': {
memory = bottomRow.innerText;
break
}
}
}
function appendNumber (target) {
if (topRow.innerText.includes('=')) {
topRow.innerText = '';
expression = '';
}
if (bottomRowActive) {
if (bottomRow.innerText.length === 1 && bottomRow.innerText == '0') {
bottomRow.innerText = target.innerText;
} else if (bottomRow.innerText.length >= 15) {
} else {
bottomRow.innerText = bottomRow.innerText + target.innerText;
}
return
}
bottomRowActive = true;
bottomRow.innerText = target.innerText;
}
function clearAll () {
bottomRowActive = false;
topRow.innerText = '';
bottomRow.innerText = '0';
expression = '';
}
function clearEntry () {
bottomRowActive = false;
if (topRow.innerText.includes('=')) {
clearAll();
} else {
bottomRow.innerText = '0';
}
}
function deleteLast () {
if (bottomRowActive) {
if (bottomRow.innerText == '0') {
return
} else if ((bottomRow.innerText.length === 3 && bottomRow.innerText.includes('.') && bottomRow.innerText.includes('-')) || (bottomRow.innerText.length === 2 && bottomRow.innerText.includes('-')) || bottomRow.innerText.length === 1) {
bottomRow.innerText = '0';
} else {
bottomRow.innerText = bottomRow.innerText.slice(0, bottomRow.innerText.length - 1)
}
}
}
function basicOperation (target) {
if (bottomRowActive) {
expression = `(${expression}(${bottomRow.innerText}))`;
topRow.innerText = evaluate() + ' ' + target.innerText;
expression += target.dataset.value;
bottomRowActive = false;
} else {
if (basicOperators.test(topRow.innerText.slice(-1))) {
topRow.innerText = topRow.innerText.slice(0, -1) + target.innerText;
expression = expression.slice(0, -1) + target.dataset.value;
} else {
topRow.innerText = evaluate() + ' ' + target.innerText;
expression += target.dataset.value;
}
}
}
function equals () {
bottomRowActive = false;
if (topRow.innerText.includes('=')) {
return
}
if (bottomRow.innerText.includes('-')) {
topRow.innerText = `${topRow.innerText} (${bottomRow.innerText}) =`;
} else {
topRow.innerText = `${topRow.innerText} ${bottomRow.innerText} =`;
}
expression = `(${expression}(${bottomRow.innerText}))`;
bottomRow.innerText = evaluate();
}
function decimalPoint () {
if (!bottomRowActive) {
bottomRow.innerText = '0.';
bottomRowActive = true;
} else if (bottomRow.innerText.length >= 14) {
} else if (!bottomRow.innerText.includes('.')) {
bottomRow.innerText += '.';
}
}
function minus () {
if (bottomRow.innerText == '0') {
return
} else if (bottomRow.innerText.includes('-')) {
bottomRow.innerText = bottomRow.innerText.slice(1, bottomRow.innerText.length);
} else {
bottomRow.innerText = '-' + bottomRow.innerText;
}
}
function evaluate () {
let result = eval(expression);
let resultRounded = +parseFloat(result).toFixed(8);
if (resultRounded.toString().length >= 18) {
resultRounded = resultRounded.toExponential();
}
resultRounded = resultRounded.toString();
if (resultRounded.includes('e')) {
let number = resultRounded.split('e')[0];
let numberRounded = (+parseFloat(number).toFixed(8)).toString();
resultRounded = numberRounded + 'e' + resultRounded.split('e')[1];
}
return resultRounded;
}
</code></pre>
|
[] |
[
{
"body": "<p>So I'm looking at it from a structural perspective.</p>\n<p>I think you underuse parameters for your functions, and use too much global state. You could benefit from using some Javascript classes to encapsulate it.</p>\n<p>You also use <code>eval()</code> which shouldn't ever be used with user controlled input. Don't get in the habit of using it. It's not a big deal on it's own, but it kind of takes away from the point of writing a calculator because you aren't writing any of the parsing yourself.</p>\n<p>Your use of JavaScript <code>this</code> could confuse some modern developers, because there's so many ways to end up clobbering it. Most people try to avoid using it as much as possible because of the confusion around it.</p>\n<p>Finally you have some empty branches in your code for if conditionals.</p>\n<p>Overall, it's a decent first attempt. You may benefit by setting up Github pages to show off your attempt. It's free static hosting and would allow us to view it in action.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T22:48:11.920",
"Id": "526729",
"Score": "0",
"body": "Thank you for a quick and thorough review! I wonder, how could I replace eval() then, since I thought it is perfect for that kind of things.\nHere is the working page: \nhttps://prmk01.github.io/Calculator/"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T22:22:29.480",
"Id": "266613",
"ParentId": "266609",
"Score": "3"
}
},
{
"body": "<h2>General points</h2>\n<ul>\n<li><p>DO NOT use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript statement reference. let\">let</a> in global scope as it's behavior is non intuitive. If you must use <code>let</code> ensure you create them in a higher scope than global.</p>\n</li>\n<li><p>DO NOT add code directly in markup. Eg <code><button onclick="foo()"></button></code> use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener\" rel=\"nofollow noreferrer\" title=\"MDN Web API's EventTarget addEventListener\">EventTarget.addEventListener</a> to add event listeners and ensure that the page will work even when there is 3rd party code running, Eg adverts, extensions.</p>\n</li>\n<li><p>HSchmale's <a href=\"https://codereview.stackexchange.com/a/266613/120556\">answer</a> tells you</p>\n<blockquote>\n<p><em>"...<code>eval()</code> which shouldn't ever be used with user controlled input..."</em>.</p>\n</blockquote>\n<p>In this case there is nothing wrong with using <code>eval</code> as there is no way for it to be used as a vector for attack.</p>\n<p>The user (client) can execute any code they wish, they don't need <code>eval</code> to do so.</p>\n<p>You should NOT use <code>eval</code> when the content being evaluated comes from a 3rd person / party / domain / email / API / etc...</p>\n<p><code>eval</code> is a useful tool and remains in the ECMAScript standard because it is such a useful tool (A calculator is an example of its usefulness)</p>\n</li>\n<li><p>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent\" rel=\"nofollow noreferrer\" title=\"MDN Web API's Node textContent\">textContent</a> rather than <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText\" rel=\"nofollow noreferrer\" title=\"MDN Web API's HTMLElement innerText\">innerText</a></p>\n</li>\n</ul>\n<h2>Design</h2>\n<h3>Markup and State</h3>\n<p>Decouple the Markup from the codes state. You are using the markup to store values. Rather store all the values in code and the markup is just a mirror of the values as stored in code.</p>\n<p>The example has the function <code>updateDisplay</code> which is called after each click event. It takes the internal calculator state and displays it.</p>\n<h3>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset\" rel=\"nofollow noreferrer\" title=\"MDN Web API's HTMLElement dataset\">HTMLElement.dataset</a></h3>\n<p>You started using the data attributes to define button functions (Great) however you did not complete this.</p>\n<p>Generally what is displayed on the page should not be used as defined inputs as there is no guarantee that it will be what you expect.</p>\n<p>The <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset\" rel=\"nofollow noreferrer\" title=\"MDN Web API's HTMLElement dataset\">HTMLElement.dataset</a> attribute will not be changed by translations, extensions, what not.</p>\n<h3>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id\" rel=\"nofollow noreferrer\" title=\"MDN Web HTML Global attributes id\">id</a> to identify elements</h3>\n<p>Avoid using class names to identify elements.</p>\n<p>Class names can change when you make layout and visual changes, they can also often be modified by extensions.</p>\n<p>Any changes to the class names means you need to also change the code to accommodate or the app will simply not work.</p>\n<p>Rather use <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id\" rel=\"nofollow noreferrer\" title=\"MDN Web HTML Global attributes id\">id</a> to identify elements</p>\n<h3>Keep code simple</h3>\n<p>Use a single listener rather than many independent listeners. This will reduce the code complexity and runtime overheads.</p>\n<p>The example uses <code>dataset.value</code> to select a calculator function. The <code>dataset</code> is passed to the function if there is additional data needed to complete the function. For example <code><button class="button dark" data-func="num" data-num="5">5</button></code> the function is 'num', and the number is '5'</p>\n<h2>Example</h2>\n<p>The code below is not a rewrite as it does not behave as your code does (and likely to have some bugs). Rather it is an example of how you could have organised your code.</p>\n<h3>Notes</h3>\n<ul>\n<li>There is only one event listener <code>buttonClicked</code>.</li>\n<li>Button functions are defined by the object functions where the function to call is in the event targets <code>dataset.func</code> property. Each function is passed the <code>dataset</code> if needed for additional context.</li>\n<li>The display is updated after each click <code>updateDisplay</code>, where the value of <code>result</code>, and <code>current</code> are displayed in the appropriate elements. This is where you would round the displayed numbers etc.</li>\n<li><code>updateDisplay</code> also checks and updates <code>disabled</code> status of the memory buttons when needed.</li>\n</ul>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>;(()=>{ // to keep code out of the global scope\n \"use strict\";\n var result = \"\";\n var current = \"0\";\n var memory;\n var memState = \"\";\n var error = false; \n\n function updateDisplay() {\n function updateMemory() {\n memState = memory;\n const disable = memory === undefined;\n memRecall.disabled = disable;\n memClear.disabled = disable;\n }\n \n calculatorResult.textContent = error ? \"Error!\" : result;\n error = false;\n calculatorCurrent.textContent = current;\n memory !== memState && updateMemory(); \n }\n const functions = {\n MC() { \n memory = undefined;\n },\n MR() { \n current = \"\" + memory;\n },\n MPlus() { \n current = \"\" + ((isNaN(current) ? 0 : Number(current)) + (memory ?? 0)); \n },\n MSub() { \n current = \"\" + ((isNaN(current) ? 0 : Number(current)) - (memory ?? 0)); \n },\n MS() { \n memory = isNaN(current) ? 0 : Number(current);\n },\n C() { \n current = \"0\";\n },\n CE() {\n current = \"0\";\n result = \"\";\n },\n back() { \n current = current.slice(0,-1);\n },\n equ() { \n if (!result.includes(\"=\")) {\n try {\n const val = eval(result + current);\n result = result + current + \"=\";\n current = \"\" + val;\n } catch(e) {\n error = true;\n }\n \n }\n },\n op(data) { \n result = current + data.operator; \n current = \"\";\n },\n pluMinus() { \n current = \"\" + (current !== \"0\" ? -Number(current) : current);\n },\n dot() { \n current += current.includes(\".\") ? \"\" : \".\"; \n },\n num(data) { \n current = (current !== \"0\" ? current : \"\") + data.num;\n },\n };\n function buttonClicked(e) {\n const target = e.target;\n functions[target.dataset.func]?.(target.dataset); \n updateDisplay();\n }\n calculatorPanel.addEventListener(\"click\", buttonClicked);\n updateDisplay();\n})();</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"calculator-body\">\n <div class=\"calculator-screen\" >\n <div class=\"screen-top-part\" id=\"calculatorResult\"></div>\n <div class=\"screen-bottom-part\" id=\"calculatorCurrent\">0</div>\n </div>\n <div class=\"calculator-panel\" id=\"calculatorPanel\">\n <div class=\"panel-top-part\" >\n <button class=\"button top inactive\" id=\"memClear\" data-func=\"MC\">MC</button>\n <button class=\"button top inactive\" id=\"memRecall\" data-func=\"MR\">MR</button>\n <button class=\"button top\" data-func=\"MPlus\">M+</button>\n <button class=\"button top\" data-func=\"MSub\">M-</button>\n <button class=\"button top\" data-func=\"MS\">MS</button>\n </div>\n <div class=\"panel-bottom-part\" id=\"bottomPanel\">\n <button class=\"button clear\" data-func=\"C\">C</button>\n <button class=\"button\" data-func=\"CE\">CE</button>\n <button class=\"button\" data-func=\"back\">←</button>\n <button class=\"button operator\" data-func=\"op\" data-operator=\"/\">÷</button><br>\n <button class=\"button dark\" data-func=\"num\" data-num=\"7\">7</button>\n <button class=\"button dark\" data-func=\"num\" data-num=\"8\">8</button>\n <button class=\"button dark\" data-func=\"num\" data-num=\"9\">9</button>\n <button class=\"button operator\" data-func=\"op\" data-operator=\"*\">×</button><br>\n <button class=\"button dark\" data-func=\"num\" data-num=\"4\">4</button>\n <button class=\"button dark\" data-func=\"num\" data-num=\"5\">5</button>\n <button class=\"button dark\" data-func=\"num\" data-num=\"6\">6</button>\n <button class=\"button operator\" data-func=\"op\" data-operator=\"-\">-</button><br>\n <button class=\"button dark\" data-func=\"num\" data-num=\"1\">1</button>\n <button class=\"button dark\" data-func=\"num\" data-num=\"2\">2</button>\n <button class=\"button dark\" data-func=\"num\" data-num=\"3\">3</button>\n <button class=\"button operator\" data-func=\"op\" data-operator=\"+\">+</button><br>\n <button class=\"button dark\" data-func=\"pluMinus\">±</button>\n <button class=\"button dark\" data-func=\"num\" data-num=\"0\">0</button>\n <button class=\"button dark\" data-func=\"dot\">.</button>\n <button class=\"button operator equals\" data-func=\"equ\">=</button>\n </div>\n </div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-07T21:35:26.253",
"Id": "528006",
"Score": "0",
"body": "Thank you for that in-depth review! Today I was working on applying a few changes to my code, according to your advice. I would be grateful if you could tell me what you think about this now. \nDo you think code like this is worth Junior Front-end Developer? Cheers!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-08T21:08:36.067",
"Id": "528099",
"Score": "1",
"body": "@PRMK Re question: From the code you have presented you have the skill set to be a programmer. Junior Front-end as part of a supervised team, Yes."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T20:19:44.103",
"Id": "267665",
"ParentId": "266609",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "267665",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T21:55:51.720",
"Id": "266609",
"Score": "6",
"Tags": [
"javascript",
"html",
"css",
"calculator"
],
"Title": "Calculator with JavaScript"
}
|
266609
|
<p>I'm learning how to use DynamoDB and various AWS services, so I decided to write a simple hit counter application for my education of how to use DynamoDB. This application deduplicates hits from the same client for the same page by storing a hash of their user agent and ip address. It also stores 1 entry of hits per day, and accumulates them over the time domain. I'm looking for feedback on how I structured the dynamo calls and potential issues that it has. I suspect that I might be using a consistent read when I don't need to. I'm also curious if I used the right pattern to handle an upsert in dynamodb.</p>
<p>The dynamo db table has a hash key of the "url" and a sort field called "as_of_when" which says roughly when the hits occured.</p>
<pre><code>"""
A simple hit counter stuff to learn the various apis of dynamodb.
"""
import datetime
import os
import hashlib
import base64
import boto3
from botocore.exceptions import ClientError
from aws_xray_sdk.core import xray_recorder
from aws_xray_sdk.core import patch_all
from pybadges import badge
patch_all()
TABLE_NAME = os.getenv("TABLE_NAME", "hit_counts")
dynamo = boto3.client('dynamodb')
def get_today() -> str:
"""
Gets a formatted date string
"""
return datetime.datetime.now().strftime("%Y-%m-%d")
def get_full_timestamp() -> str:
"""
Gets a complete date string
"""
return datetime.datetime.now().strftime("%Y%m%d%H%M%S")
def get_previous_total(url:str):
"""
Gets the most recent known total. Should be used before inserting a new instance
"""
response = dynamo.query(
TableName=TABLE_NAME,
Select='ALL_ATTRIBUTES',
Limit=1,
KeyConditionExpression="the_url=:urlval",
ScanIndexForward=False,
ExpressionAttributeValues={
":urlval": {
"S": url
}
}
)
if response['Count'] == 0:
return 0
return response['Items'][0]['accumulated_count']['N']
@xray_recorder.capture('insert_new_entry')
def insert_new_entry(url:str, as_of_when : str, user_hash : str, user_id : str):
the_count = str(int(get_previous_total(url)) + 1)
result = dynamo.put_item(
TableName=TABLE_NAME,
Item={
'the_url': {
'S': url
},
'as_of_when': {
'S': as_of_when
},
'today_count': {
'N': '1'
},
'accumulated_count': {
'N': the_count
},
'user_id_hashes': {
'SS': [user_hash]
},
'user_hashes': {
'SS': [user_id]
}
},
ReturnValues='ALL_OLD',
ReturnItemCollectionMetrics='SIZE',
ReturnConsumedCapacity='TOTAL',
ConditionExpression='attribute_not_exists(the_url) and attribute_not_exists(as_of_when)'
)
print('insert_result', result)
return result
@xray_recorder.capture('update_existing_entry')
def update_existing_entry(url:str, as_of_when : str, user_hash : str, user_id : str):
result = dynamo.execute_statement(
Statement=f"""
UPDATE {TABLE_NAME}
SET today_count = today_count + 1
SET accumulated_count = accumulated_count + 1
SET user_hashes = set_add(user_hashes, ?)
SET user_id_hashes = set_add(user_id_hashes, ?)
WHERE the_url = ? AND as_of_when = ? RETURNING ALL NEW *
""",
Parameters=[
{
"SS": [user_id]
},
{
"SS": [user_hash]
},
{
"S": url
},
{
"S": as_of_when
}
]
)
return result
@xray_recorder.capture('get_todays_entry')
def get_todays_entry(url:str, as_of_when : str):
result = dynamo.get_item(
TableName=TABLE_NAME,
Key={
'the_url': {
'S': url
},
'as_of_when': {
'S': as_of_when
}
},
AttributesToGet=[
'today_count',
'accumulated_count',
'user_hashes',
'user_id_hashes'
],
ConsistentRead=True
)
print('get_todays_entry', result)
if 'Item' in result:
return result['Item']
return None
def increment_hit_count(url:str, as_of_when : str, user_hash : str, user_id : str):
"""
increments a counter instance in the dynamo table
"""
current_hits = get_todays_entry(url, as_of_when)
if current_hits is None:
# Insert new entry
x = insert_new_entry(url, as_of_when, user_hash, user_id)
current_hits = {
'accumulated_count': {
'N': "1"
}
}
else:
# Check for existence in existing object
print(current_hits['user_id_hashes'])
print(user_id)
if user_hash not in current_hits['user_id_hashes']['SS']:
result = update_existing_entry(url, as_of_when, user_hash, user_id)
if 'Items' in result:
current_hits = result['Items'][0]
print(result)
return current_hits['accumulated_count']['N']
def hash_api_gateway_event(event : dict):
reqContext = event['requestContext']['http']
reqString = ':'.join((reqContext['sourceIp'], reqContext['protocol'] + reqContext['userAgent']))
m = hashlib.md5()
m.update(reqString.encode('utf-8'))
return base64.b64encode(m.digest()).decode('utf-8'), reqString
def handler(event : dict, context):
"""
# Invoked via query string parameters from an image tag
# Returns a SVG unless text parameter is set.
"""
print(event)
print("hello")
user_hash, og_user_id = hash_api_gateway_event(event)
print(user_hash, og_user_id)
if 'queryStringParameters' in event:
url = event['queryStringParameters']['url']
result = increment_hit_count(url, get_today(), user_hash, og_user_id)
print(result)
body = badge(left_text="Total Views", right_text=result)
return {
"statusCode": 200,
"isBase64Encoded": False,
"headers": {
"Content-Type": "image/svg+xml"
},
"body": body
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T11:55:53.203",
"Id": "527754",
"Score": "1",
"body": "Alex Waygood covered everything I would have said, so I'll only add that getting into the habit of running pylint, pycodestyle, and mypy really helps get into the groove of things with python, they really did the trick for me"
}
] |
[
{
"body": "<p>[Edited following discussion in the comments]</p>\n<p>A few brief notes on your code:</p>\n<ol>\n<li>Your type hints could be more complete/descriptive. You don't have any return annotations; the <code>context</code> parameter in your <code>handler</code> function has no type hint; and annotating your <code>event</code> parameter in <code>handler</code> and <code>hash_api_gateway_event</code> with a bare <code>dict</code> tells the type-checker extremely little. It would be much better to annotate these parameters with a parameterised <code>dict</code> that informs the type-checker about the expected types of the dictionary keys and values. You could also consider <code>typing.TypedDict</code>, which allows you to specify the type of the value you expect to be associated with individual keys in a dictionary.</li>\n<li>It would be nice to have docstrings in all your public functions, even if it's just a brief one-liner describing what your function achieves.</li>\n<li>"Flat is better than nested", so consider using <code>from datetime import datetime</code> and <code>from base64 import bs4encode</code> instead of <code>import datetime</code> and <code>import base64</code>. In both cases, you only use a single class/function from their respective module; it makes your code more succinct and readable without introducing any ambiguity about what the functions/classes do; and it's marginally more performant to not have to look up the <code>datetime</code> class in the <code>datetime</code> module whenever you want to use it.</li>\n</ol>\n<p>I know little about DynamoDB, so can't comment on what your code is trying to accomplish, but with that (large) caveat, and other than the points I've mentioned above, your code appears pretty clean from my perspective.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T11:01:42.970",
"Id": "267623",
"ParentId": "266612",
"Score": "7"
}
},
{
"body": "<p>For your date format,</p>\n<pre><code>datetime.datetime.now().strftime("%Y-%m-%d")\n</code></pre>\n<p>is more directly expressed as</p>\n<pre><code>datetime.date.today().isoformat()\n</code></pre>\n<p>For this expression:</p>\n<pre><code>return response['Items'][0]['accumulated_count']['N']\n</code></pre>\n<p>if you know there's only one item in the response, then</p>\n<pre><code>item, = response['Items']\nreturn item['accumulated_count']['N']\n</code></pre>\n<p>will be more explicit, and offer for free an assertion that exactly one item was returned.</p>\n<p>This method:</p>\n<pre><code>def insert_new_entry(url:str, as_of_when : str, user_hash : str, user_id : str):\n</code></pre>\n<p>has inconsistent spacing around your type hints; it should look like <code>url: str</code>. Also, you're missing a return typehint, which in this case is the same as the type from <code>dynamo.put_item</code>.</p>\n<p><code>print('insert_result', result)</code> and similar should be converted to a logging call.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T14:59:04.500",
"Id": "267633",
"ParentId": "266612",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T22:10:18.743",
"Id": "266612",
"Score": "7",
"Tags": [
"python",
"database",
"lambda",
"amazon-web-services",
"nosql"
],
"Title": "A Hit Counter For AWS Python Lambda powered with DynamoDB"
}
|
266612
|
<p>I am trying to use Selenium for website automation testing tasks and I am new to Selenium testing framework. The the situation I faced is to wait the website components loading and then do the related operations with the target components. The <code>WaitFor</code> method with <code>xpath</code> and <code>waitingTimes</code> input parameters are designed as below.</p>
<p><strong>The experimental implementation</strong></p>
<pre><code>private static bool WaitFor(IWebDriver driver, string xpath, uint waitingTimes = 100)
{
log.Info("Wait for " + xpath);
uint count = 0;
while (IsElementExists(driver, xpath) == false)
{
if (count >= waitingTimes)
{
return false;
}
Thread.Sleep(1000);
count++;
}
return true;
}
private static bool IsElementExists(IWebDriver driver, string xpath)
{
try
{
var element = driver.FindElement(By.XPath(xpath));
return true;
}
catch (Exception ex)
{
log.Info(ex.Message);
}
return false;
}
</code></pre>
<p>The usage of <code>WaitFor</code> method:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Text;
using System.Threading;
using log4net;
using log4net.Appender;
using log4net.Config;
using log4net.Repository.Hierarchy;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace WaitForMethodSeleniumWebDriver
{
class Program
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private static BackgroundWorker backgroundWorkerForLogging = new BackgroundWorker();
static void Main(string[] args)
{
LogHandler();
log.Info("Main method");
IWebDriver driver = new ChromeDriver(@".\");
driver.Url = "https://codereview.stackexchange.com/";
WaitFor(driver, ".//*[@id='content']");
// perform next step operation
// ...
driver.Close();
driver.Quit();
}
// Reference: https://stackoverflow.com/a/4172968/6667035
private static void LogHandler()
{
Hierarchy hierarchy = (Hierarchy)LogManager.GetRepository(System.Reflection.Assembly.GetEntryAssembly());
XmlConfigurator.Configure(hierarchy, new FileInfo("log4net.config"));
FileAppender fileAppender = new FileAppender();
fileAppender.AppendToFile = true;
fileAppender.LockingModel = new FileAppender.MinimalLock();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder = stringBuilder.Append("log").Append(DateTime.UtcNow.ToString("_MM-dd-yyyy_hh_mm_ss")).Append(".txt");
fileAppender.File = stringBuilder.ToString();
log4net.Layout.PatternLayout pl = new log4net.Layout.PatternLayout();
pl.ConversionPattern = "%d [%2%t] %-5p [%-10c] %m%n";
pl.ActivateOptions();
fileAppender.Layout = pl;
fileAppender.ActivateOptions();
BasicConfigurator.Configure(fileAppender);
// Reference: https://stackoverflow.com/a/2077767/6667035
backgroundWorkerForLogging.DoWork += (sender, e) =>
{
UDPListener();
};
// Start BackgroundWorker
backgroundWorkerForLogging.RunWorkerAsync();
}
// launch this in a background thread
private static void UDPListener()
{
System.Net.IPEndPoint remoteEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0);
var udpClient = new System.Net.Sockets.UdpClient(10001);
while (true)
{
var buffer = udpClient.Receive(ref remoteEndPoint);
var loggingEvent = System.Text.Encoding.Unicode.GetString(buffer);
Console.WriteLine(loggingEvent);
}
}
private static bool WaitFor(IWebDriver driver, string xpath, uint waitingTimes = 100)
{
log.Info("Wait for " + xpath);
uint count = 0;
while (IsElementExists(driver, xpath) == false)
{
if (count >= waitingTimes)
{
return false;
}
Thread.Sleep(1000);
count++;
}
return true;
}
private static bool IsElementExists(IWebDriver driver, string xpath)
{
try
{
var element = driver.FindElement(By.XPath(xpath));
return true;
}
catch (Exception ex)
{
log.Info(ex.Message);
}
return false;
}
}
}
</code></pre>
<p>All suggestions are welcome.</p>
|
[] |
[
{
"body": "<h3><code>WaitFor</code></h3>\n<ul>\n<li>This method name is kinda weird for me\n<ul>\n<li>If I would be your API's consumer then I would except from this naming that it would return with a <code>IWebElement</code> instance (or <code>null</code>) rather than a <code>boolean</code> value.</li>\n</ul>\n</li>\n<li>But, if you want to stick to this existence check API then I would suggest:</li>\n</ul>\n<pre><code>static bool CheckElementExistence(this IWebDriver driver, string elementXPath, byte waitUntilInSeconds = 10)\n</code></pre>\n<ul>\n<li>I've renamed your <code>xpath</code> parameter to a more meaningful one</li>\n<li>The <code>waitingTimes</code> in my opinion is really bad parameter\n<ul>\n<li>You have to know some implementation detail (<code>Thread.Sleep(1000)</code>) to be able to determine this parameter's value</li>\n<li>That's why I would suggest to use some other concept, like <code>waitUntil</code>\n<ul>\n<li>It is usually a good practice to include the time unit in the name as\nwell to be able to use the API without scrutinizing the documentation\n(whether it is a milliseconds or seconds)</li>\n</ul>\n</li>\n</ul>\n</li>\n<li><code>IsElementExists(driver, xpath) == false</code>: I know some people does not like the usage of <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/boolean-logical-operators#logical-negation-operator-\" rel=\"nofollow noreferrer\">logical negation operator</a> because it is easy to oversee, but you can rewrite your loop to avoid the usage of <code>== false</code></li>\n</ul>\n<pre><code>private static bool CheckElementExistence(this IWebDriver driver, string elementXPath, byte waitUntilInSeconds = 10)\n{\n log.Info("Checking existence of " + elementXPath);\n byte remainingSeconds = waitUntilInSeconds;\n while (remainingSeconds > 0)\n {\n if (DoesElementExist(driver, elementXPath)) return true;\n \n Thread.Sleep(1000);\n remainingSeconds--;\n }\n return false;\n}\n</code></pre>\n<ul>\n<li>It might make sense to make your method async and use <code>Task.Delay</code> rather than <code>Thread.Sleep</code></li>\n</ul>\n<h3><code>IsElementExists</code></h3>\n<ul>\n<li>I would suggest to rename your method to <code>DoesElementExist</code></li>\n<li>I would also recommend to handle only <code>NoSuchElementException</code> rather than any <code>Exception</code>.\n<ul>\n<li>For example if the provided xpath is malformed or null the <code>FindElement</code> might throw <code>ArgumentException</code> (that's just an assumption, I don't know). You can handle that case differently</li>\n</ul>\n</li>\n<li><code>var element</code>: if you are not using this variable then you can simple use the <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/discards\" rel=\"nofollow noreferrer\">discard operator</a></li>\n</ul>\n<pre><code>private static bool DoesElementExist(IWebDriver driver, string elementXPath)\n{\n try\n {\n _ = driver.FindElement(By.XPath(elementXPath));\n return true;\n }\n catch (NoSuchElementException ex)\n {\n log.Info(ex.Message);\n return false;\n } \n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T16:37:41.187",
"Id": "527811",
"Score": "1",
"body": "from your `DoesElementExist` method there is a small trap, `FindElement` uses the drivers search wait time and sit there until it times out or finds it. if your timeout in in minuets and the calling functions timeout may be in assumed seconds. but `remainingSeconds` in your example is just a counter for number of attempts to recheck.\n\nas is .... if you set `waitUntilInSeconds` to 20, driver timeout is 30 seconds, then if we never find the control, we sit here 620 seconds"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T17:27:03.990",
"Id": "527813",
"Score": "0",
"body": "Quite frankly I haven't used the .net library. I've used the js lib several years ago. I assumed that the FindElement is instant, it does not wait for a particular time. With that in mind my design has that problem that you have described. Thanks for pointing out. Is there a FindElementAsync method which receives a cancellationToken?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T17:29:48.517",
"Id": "527814",
"Score": "0",
"body": "the closest thing for immediate results is `FindElements` which returns a collection. then check the count."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T07:26:47.723",
"Id": "267619",
"ParentId": "266615",
"Score": "2"
}
},
{
"body": "<p>This is a bit of a reimagining, but I think it will help.</p>\n<p>Selenium actually has a smart wait helper package called <code>DotNetSeleniumExtras.WaitHelpers</code>.</p>\n<p>With it, you can greatly simplify your code to just:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>private void WaitFor(IWebDriver driver, By by, TimeSpan wait)\n{\n var smartWait = new WebDriverWait(driver, wait);\n smartWait.Until(ExpectedConditions.ElementExists(by));\n}\n</code></pre>\n<p>Usage:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>WaitFor(driver, By.XPath(".//*[@id='content']"), TimeSpan.FromSeconds(10));\n</code></pre>\n<p>This way, you are able to keep all of the parameters as open as you need them to be. The driver is always necessary. The search criteria still let you use any available search patterns—e.g., by CSS class or by id—and the explicit timespan lets you understand the delay time at a glance.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T16:55:25.307",
"Id": "267660",
"ParentId": "266615",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "267619",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-01T23:59:07.833",
"Id": "266615",
"Score": "1",
"Tags": [
"c#",
"beginner",
"selenium",
"integration-testing",
"webdriver"
],
"Title": "WaitFor method for website automation testing with Selenium WebDriver"
}
|
266615
|
<p>(See the <a href="https://codereview.stackexchange.com/questions/266570/a-simple-java-integer-hash-set-follow-up">previous version</a>.)</p>
<p>Now I have this:</p>
<p><strong><code>com.github.coderodde.util.IntHashSet</code>:</strong></p>
<pre><code>package com.github.coderodde.util;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
/**
* This class implements a simple hash set for non-negative {@code int} values.
* It is used in the {@link com.github.coderodde.util.LinkedList} in order to
* keep track of nodes that are being pointed to by fingers.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Aug 29, 2021)
* @since 1.6 (Aug 29, 2021)
*/
public class IntHashSet {
private static final int INITIAL_CAPACITY = 8;
private static final class Node {
Node next;
int integer;
Node(int integer, Node next) {
this.integer = integer;
this.next = next;
}
@Override
public String toString() {
return "Chain node, integer = " + integer;
}
}
private Node[] table = new Node[INITIAL_CAPACITY];
private int size = 0;
private int mask = INITIAL_CAPACITY - 1;
@Override
public String toString() {
return "size = " + size;
}
public void add(int integer) {
int targetCollisionChainIndex = integer & mask;
Node node = table[targetCollisionChainIndex];
while (node != null) {
if (node.integer == integer) {
return;
}
node = node.next;
}
size++;
if (size > table.length) {
Node[] newTable = new Node[2 * table.length];
mask = newTable.length - 1;
for (Node currentNode : table) {
while (currentNode != null) {
Node nextNode = currentNode.next;
int newTableHash = currentNode.integer & mask;
currentNode.next = newTable[newTableHash];
newTable[newTableHash] = currentNode;
currentNode = nextNode;
}
}
table = newTable;
targetCollisionChainIndex = integer & mask;
}
Node newNode = new Node(integer, table[targetCollisionChainIndex]);
table[targetCollisionChainIndex] = newNode;
}
public boolean contains(int integer) {
final int collisionChainIndex = integer & mask;
Node node = table[collisionChainIndex];
while (node != null) {
if (node.integer == integer) {
return true;
}
node = node.next;
}
return false;
}
public void remove(int integer) {
int targetCollisionChainIndex = integer & mask;
Node node = table[targetCollisionChainIndex];
Node prev = null;
while (node != null) {
if (node.integer == integer) {
break;
}
prev = node;
node = node.next;
}
if (node == null)
return;
size--;
if (size * 4 <= table.length && table.length >= INITIAL_CAPACITY * 4) {
Node[] newTable = new Node[table.length / 4];
mask = newTable.length - 1;
for (Node currentNode : table) {
while (currentNode != null) {
if (currentNode == node) {
// Omit the node with the target integer:
currentNode = currentNode.next;
continue;
}
Node nextNode = currentNode.next;
int newTableHash = currentNode.integer & mask;
currentNode.next = newTable[newTableHash];
newTable[newTableHash] = currentNode;
currentNode = nextNode;
}
}
table = newTable;
} else if (prev == null) {
table[targetCollisionChainIndex] =
table[targetCollisionChainIndex].next;
} else {
prev.next = prev.next.next;
}
}
public void clear() {
size = 0;
table = new Node[INITIAL_CAPACITY];
mask = table.length - 1;
}
private static final int DATA_LENGTH = 5_000_000;
public static void main(String[] args) {
Random random = new Random(10L);
int[] addData = getAddData(random);
int[] containsData = getContainsData(random);
int[] removeData = getRemoveData(random);
for (int iter = 0; iter < 5; iter++) {
System.out.println(">>> Iteration: " + (iter + 1) + "/5");
IntHashSet myset = new IntHashSet();
Set<Integer> set = new HashSet<>();
long start = System.currentTimeMillis();
for (int i : addData) {
myset.add(i);
}
long end = System.currentTimeMillis();
System.out.println(" IntHashSet.add in " + (end - start));
start = System.currentTimeMillis();
for (int i : addData) {
set.add(i);
}
end = System.currentTimeMillis();
System.out.println(" HashSet.add in " + (end - start) + "\n");
start = System.currentTimeMillis();
for (int i : containsData) {
myset.contains(i);
}
end = System.currentTimeMillis();
System.out.println(" IntHashSet.contains in " + (end - start));
start = System.currentTimeMillis();
for (int i : containsData) {
set.contains(i);
}
end = System.currentTimeMillis();
System.out.println(" HashSet.contains in " + (end - start) +
"\n");
start = System.currentTimeMillis();
for (int i : removeData) {
myset.remove(i);
}
end = System.currentTimeMillis();
System.out.println(" IntHashSet.remove in " + (end - start));
start = System.currentTimeMillis();
for (int i : removeData) {
set.remove(i);
}
end = System.currentTimeMillis();
System.out.println(" HashSet.remove in " + (end - start) + "\n");
}
}
private static int[] getAddData(Random random) {
return getData(DATA_LENGTH, 3 * DATA_LENGTH / 2, random);
}
private static int[] getContainsData(Random random) {
return getData(DATA_LENGTH, 3 * DATA_LENGTH / 2, random);
}
private static int[] getRemoveData(Random random) {
return getData(DATA_LENGTH, 3 * DATA_LENGTH / 2, random);
}
private static int[] getData(int length, int maxValue, Random random) {
int[] data = new int[length];
for (int i = 0; i < length; i++) {
data[i] = random.nextInt(maxValue + 1);
}
return data;
}
}
</code></pre>
<p><strong><code>com.github.coderodde.util.IntHashSetTest</code>:</strong></p>
<pre><code>package com.github.coderodde.util;
import java.util.Random;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
public class IntHashSetTest {
private final IntHashSet set = new IntHashSet();
@Before
public void beforeTest() {
set.clear();
}
@Test
public void removeFromCollisionChainBug() {
bar("removeFromCollisionChainBug");
set.add(0b00001); // 1
set.add(0b01001); // 9
set.add(0b10001); // 17
set.remove(1); // remove from tail
set.add(0b00001); // 1
set.add(0b01001); // 9
set.add(0b10001); // 17
set.remove(1); // remove from head
set.add(0b00001); // 1
set.add(0b01001); // 9
set.add(0b10001); // 17
set.remove(17); // remove from middle
bar("removeFromCollisionChainBug done!");
}
@Test
public void removeBug() {
bar("removeBug");
for (int i = 0; i < 9; i++)
set.add(i);
for (int i = 0; i < 9; i++)
set.remove(i);
bar("removeBug done!");
}
@Test
public void removeFirstMiddleLast() {
bar("removeFirstMiddleLast");
// All three ints will end up in the same collision chain:
set.add(1); // 0b00001
set.add(9); // 0b01001
set.add(17); // 0b10001
assertTrue(set.contains(1));
assertTrue(set.contains(9));
assertTrue(set.contains(17));
set.remove(1);
assertFalse(set.contains(1));
assertTrue(set.contains(9));
assertTrue(set.contains(17));
set.remove(17);
assertFalse(set.contains(1));
assertTrue(set.contains(9));
assertFalse(set.contains(17));
set.remove(9);
assertFalse(set.contains(1));
assertFalse(set.contains(9));
assertFalse(set.contains(17));
bar("removeFirstMiddleLast done!");
}
@Test
public void add() {
bar("add");
for (int i = 0; i < 500; i++) {
set.add(i);
}
for (int i = 0; i < 500; i++) {
assertTrue(set.contains(i));
}
for (int i = 500; i < 1_000; i++) {
assertFalse(set.contains(i));
}
for (int i = 450; i < 550; i++) {
set.remove(i);
}
for (int i = 450; i < 1_000; i++) {
assertFalse(set.contains(i));
}
for (int i = 0; i < 450; i++) {
assertTrue(set.contains(i));
}
bar("add done!");
}
@Test
public void contains() {
bar("contains");
set.add(10);
set.add(20);
set.add(30);
for (int i = 1; i < 40; i++) {
if (i % 10 == 0) {
assertTrue(set.contains(i));
} else {
assertFalse(set.contains(i));
}
}
bar("contains done!");
}
@Test
public void remove() {
bar("remove");
set.add(1);
set.add(2);
set.add(3);
set.add(4);
set.add(5);
set.remove(2);
set.remove(4);
set.add(2);
assertFalse(set.contains(4));
assertTrue(set.contains(1));
assertTrue(set.contains(2));
assertTrue(set.contains(3));
assertTrue(set.contains(5));
bar("remove done!");
}
@Test
public void clear() {
bar("clear");
for (int i = 0; i < 100; i++) {
set.add(i);
}
for (int i = 0; i < 100; i++) {
assertTrue(set.contains(i));
}
set.clear();
for (int i = 0; i < 100; i++) {
assertFalse(set.contains(i));
}
bar("clear done!");
}
@Test
public void bruteForceAdd() {
bar("bruteForceAdd");
Random random = new Random(13L);
int[] data = new int[10_000];
for (int i = 0; i < data.length; i++) {
int datum = random.nextInt(5_000);
data[i] = datum;
set.add(datum);
}
for (int i = 0; i < data.length; i++) {
assertTrue(set.contains(data[i]));
}
bar("bruteForceAdd done!");
}
@Test
public void bruteForceRemove() {
bar("bruteForceRemove");
Random random = new Random(100L);
int[] data = new int[10_000];
for (int i = 0; i < data.length; i++) {
int datum = random.nextInt(5_000);
data[i] = datum;
set.add(datum);
}
shuffle(data, random);
for (int i = 0; i < data.length; i++) {
int datum = data[i];
if (set.contains(datum)) {
set.remove(datum);
if (set.contains(datum))
System.out.println("found i = " + i);
}
assertFalse(set.contains(datum));
}
bar("bruteForceRemove done!");
}
private static void shuffle(int[] data, Random random) {
for (int i = data.length - 1; i > 0; --i) {
final int j = random.nextInt(i + 1);
swap(data, i, j);
}
}
private static void swap(int[] data, int i, int j) {
int tmp = data[i];
data[i] = data[j];
data[j] = tmp;
}
private static void bar(String text) {
System.out.println("--- " + text);
}
}
</code></pre>
<h3>Performance figures:</h3>
<pre><code>>>> Iteration: 1/5
IntHashSet.add in 818
HashSet.add in 1306
IntHashSet.contains in 150
HashSet.contains in 321
IntHashSet.remove in 250
HashSet.remove in 263
>>> Iteration: 2/5
IntHashSet.add in 607
HashSet.add in 1130
IntHashSet.contains in 151
HashSet.contains in 280
IntHashSet.remove in 179
HashSet.remove in 203
>>> Iteration: 3/5
IntHashSet.add in 577
HashSet.add in 1060
IntHashSet.contains in 159
HashSet.contains in 292
IntHashSet.remove in 189
HashSet.remove in 229
>>> Iteration: 4/5
IntHashSet.add in 522
HashSet.add in 891
IntHashSet.contains in 166
HashSet.contains in 316
IntHashSet.remove in 193
HashSet.remove in 233
>>> Iteration: 5/5
IntHashSet.add in 665
HashSet.add in 940
IntHashSet.contains in 160
HashSet.contains in 349
IntHashSet.remove in 199
HashSet.remove in 232
</code></pre>
<h3>Critique request</h3>
<p>Please, tell me anything that comes to mind! ^^</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T08:48:38.813",
"Id": "527746",
"Score": "1",
"body": "I just wonder why you did not update your previous version? You can change the question and improve the code as long as it has no answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-04T03:04:49.600",
"Id": "527823",
"Score": "0",
"body": "This one should not contain bugs."
}
] |
[
{
"body": "<h1>Main Code</h1>\n<h2>Readability</h2>\n<p>For me, whilst you've addressed some bugs since you're initial version it looks like the code structure within your <code>IntHashSet</code> has moved in a less readable direction. Whilst you started out having a <code>contract</code> method which was responsible for reducing the size of the table now all of this logic sits within your <code>remove</code> method. This makes the <code>remove</code> method quite large. Instead, I'd have preferred the introduction of additional methods to help break the code up.</p>\n<p>For example, one way to remove the need for comments is to add a new method to give a piece of functionality a name. So rather than:</p>\n<blockquote>\n<pre><code>if (currentNode != node) {\n // Omit the node with the target integer:\n</code></pre>\n</blockquote>\n<p>Perhaps this would be more descriptive</p>\n<pre><code>if (isNodeToBeRemoved(currentNode, nodeToBeRemoved)) {\n</code></pre>\n<h2>Continue</h2>\n<p>I generally don't mind using <code>continue</code>, however often the code can be rearranged to remove the need for it. Sometimes this can make the code easier to read. So, rather than:</p>\n<blockquote>\n<pre><code>while (currentNode != null) {\n if (currentNode == node) {\n // Omit the node with the target integer:\n currentNode = currentNode.next;\n continue;\n }\n\n Node nextNode = currentNode.next;\n\n int newTableHash = currentNode.integer & mask;\n currentNode.next = newTable[newTableHash];\n newTable[newTableHash] = currentNode;\n\n currentNode = nextNode;\n}\n</code></pre>\n</blockquote>\n<p>Consider:</p>\n<pre><code>while (currentNode != null) {\n Node nextNode = currentNode.next;\n\n if (notNodeBeingRemoved(currentNode, nodeToRemove)) {\n int newTableHash = currentNode.integer & mask;\n currentNode.next = newTable[newTableHash];\n newTable[newTableHash] = currentNode;\n }\n\n currentNode = nextNode;\n}\n</code></pre>\n<p>I'd probably go further and extract a method <code>addToTable(newTable, currentNode)</code> for:</p>\n<pre><code>int newTableHash = currentNode.integer & mask;\ncurrentNode.next = newTable[newTableHash];\nnewTable[newTableHash] = currentNode;\n</code></pre>\n<h2>Duplication</h2>\n<p>The <code>addToTable</code> logic above is an example of a section of duplicate logic within the code. There's also some duplication between <code>add</code> and <code>contains</code>. Having <code>add</code> call contains would be a simple change. There's also similar logic in <code>remove</code>. Adding something like a private <code>findNodeAndPrev</code> method which performed the search and then returned the node containing the target item and its predecessor would allow the logic to be shared between all three methods, rather than being duplicated, although this might introduce unnecessary complexity.</p>\n<h1>Testing</h1>\n<h2>Test Noise</h2>\n<p>All of your tests start and end with calls to <code>bar</code>. This seems really tedious, error prone and adds noise to the actual test code, for very little value. Consider removing them. If you really need them to be there, then whilst I haven't tested it there seems to be a way of doing this more generically using a <a href=\"https://stackoverflow.com/a/13987909/592182\"><code>TestWatcher/Watchman</code></a> in Junit 4. Alternately, with JUnit 5 you can create a simple extension that allows you to do this sort of thing:</p>\n<pre><code>@ExtendWith(IntHashSetTest.InvocationLogger.class)\npublic class IntHashSetTest {\n\n static class InvocationLogger implements BeforeEachCallback, AfterEachCallback {\n\n @Override\n public void afterEach(ExtensionContext extensionContext) throws Exception {\n bar(extensionContext.getDisplayName());\n }\n\n @Override\n public void beforeEach(ExtensionContext extensionContext) throws Exception {\n bar(extensionContext.getDisplayName() + " done!");\n }\n\n private static void bar(String text) {\n System.out.println("--- " + text);\n }\n }\n</code></pre>\n<h2>Testing What?</h2>\n<p>I found it very difficult to tell just from the names what it was your tests were testing. Names like <code>removeBug</code> really don't say anything. Looking at the evolution of the code, it looks like it's testing if contracting works as expected when reducing the size of the set to 0. There's no assertions so looking at the code, it looks like it's saying can I put some stuff in, and take it back out again without an exception being thrown.</p>\n<h2>Coupling</h2>\n<p>There is a high degree of coupling between your tests and the code under test. This can be necessary, however typically the way it would work is that changes to the code break the tests where as several of your tests have hidden coupling. Some tests for boundary cases assume a known initial size for the set. If that initial size is changed then the conditions that the tests are attempting to test don't occur. So, for example <code>removeFromCollisionChainBug</code> assumes that all of the items added are added to the same bucket. If I doubled the initial size, this would no longer be the case. Whilst the test continues to pass, it's no longer testing the same thing. When you have tests that need to be coupled to the implementation consider making this coupling explicit, so that the test can continue to work as expected, or break. An obvious way to do that here would be to add an overloaded constructor to allow the initial tablesize to be passed into your set.</p>\n<h2>Testing too much</h2>\n<p>When tests are focused on testing one thing, they're usually more straightforward and easier to understand. Adding extra assertions might seem like a good idea, but if they're not focused on the purpose of the test then they just add noise and obscure the core intention of what's being tested.</p>\n<p>So, in your <code>add</code> test for example, after you add the items and assert that they have been added to the set you then loop asserting that the next 500 numbers aren't in the set.</p>\n<pre><code>for (int i = 500; i < 1_000; i++) {\n assertFalse(set.contains(i));\n}\n</code></pre>\n<p>Does this really add value? Why stop at 1000? The test then goes on to remove items and validate that the removal has worked... this seems like a totally different test.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-17T22:06:26.623",
"Id": "268100",
"ParentId": "267614",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "268100",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T02:13:19.910",
"Id": "267614",
"Score": "1",
"Tags": [
"java",
"unit-testing",
"integer",
"set",
"hashcode"
],
"Title": "A simple Java integer integer hash set - follow-up 2"
}
|
267614
|
<p>It is a classic problem to handle ever changing requirements in a cleaner way without using too many nested if statements.
Here is my current code in JavaScript.</p>
<pre><code>fetchApiData(url){
//log before start
Logger.logFetchStartedEvent();
try {
data = backendApi.get(url);
Logger.logFetchSucceededEvent();
return data;
} catch (error) {
Logger.logFetchFailedEvent();
}
}
</code></pre>
<p>Everything was going on a happy path. But I received a requirement that for some specific URLs we do not want to log at all.</p>
<p>No problem. I added a flag and switch and called it a day.</p>
<pre><code>fetchApiData(url, shouldLog){
//log before start
if(shouldLog) {
Logger.logFetchStartedEvent();
}
try {
data = backendApi.get(url);
if(shouldLog) {
Logger.logFetchSucceededEvent();
}
return data;
} catch (error) {
if(shouldLog) {
Logger.logFetchFailedEvent();
}
}
}
</code></pre>
<p>And it didn't stop there.
New requirement drops in and asked to change to accommodate following requirements</p>
<ul>
<li>some url will log everything</li>
<li>some url will log only error</li>
<li>some url will log only if the API call url is an external site</li>
<li>in some cases logging of fetchSucceeded event is needed, in some cases it is not needed.</li>
</ul>
<p>I think you got the point.
I can add countless nested if/else conditionals and get it done but now I am sure there must be a better way for this type of issue. Now I feel like one method will become a whole if/else state machine god method.</p>
<p>This is what I came up with</p>
<pre><code>fetchApiData(url,logOnStart, logOnSuccess, logOnFailure, logOnlyExternalLink){
//log on start
if(logOnStart) {
if(logOnlyExternalLink) {
if(isExternalLink(url)) {
Logger.logFetchStartedEvent();
}
} else {
Logger.logFetchStartedEvent();
}
}
try {
data = backendApi.get(url);
//log on success
if(logOnSuccess) {
// may need external url check again
Logger.logFetchSucceededEvent();
}
return data;
} catch (error) {
if(logOnFailure) {
if(errorType(error) === TimeOut)
{
Logger.logFetchFailedTimeOutEvent();
} else if (errorType(error) === 404) {
Logger.logFetchFailed404Event();
} else {
Logger.logFetchFailedEvent();
}
}
}
}
</code></pre>
<p>I did read a lot of questions about nested if/else problem but most of them end up with a foo/bar type examples and vague explanation which make no practical sense to me due to lack of experience.</p>
<p>Please point me to the right direction.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T06:59:54.833",
"Id": "527742",
"Score": "0",
"body": "Welcome to Code Review! We need to know *what the code is intended to achieve*. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](//meta.codereview.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](//meta.codereview.stackexchange.com/q/2436), rather than your concerns about the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T09:19:04.453",
"Id": "527747",
"Score": "0",
"body": "I edited your question to better fit site standards. You may want to make additional changes to better describe your code. Note that your existing code makes no use of dependency injection or design patterns in general. Nor is it object-oriented in itself. If you posted more code, e.g. the `Logger` class, that might make it object-oriented. Consider if you can post the entire code, as that is normally preferred. People may want to recommend you move logic into the `Logger` class to simplify `fetchApiData`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T09:28:52.947",
"Id": "527749",
"Score": "1",
"body": "@TobySpeight Your comment is using the old meta.codereview links rather than the newer codereview.meta links. So [what your code is for](https://codereview.meta.stackexchange.com/q/1226) and [state the task](https://codereview.meta.stackexchange.com/q/2436) will simply be broken in many browsers. If that's a template that you copy and paste, you may want to edit it in the template."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T11:14:28.870",
"Id": "527751",
"Score": "1",
"body": "Thanks @mdfst13 - I'll review and update my [SE-AutoReviewComments](https://github.com/Benjol/SE-AutoReviewComments) templates."
}
] |
[
{
"body": "<p>When requirements are prone to change, passing a function as a parameter lets you offset the filtering logic to the caller.</p>\n<pre class=\"lang-javascript prettyprint-override\"><code>import fetch from 'node-fetch' \n \nconst log = (url,eventName) => console.log(`${url}: ${eventName}`) \nconst makeLogger = shouldLog => url => eventName => { \n if (shouldLog(url,eventName)) log(url,eventName) \n} \n \nconst isExternalLink = url => !url.includes('localhost') \n \nconst neverLog = (url,eventName) => false \nconst alwaysLog = (url,eventName) => true \nconst logError = (url,eventName) => eventName === 'error' \nconst logExternalOrError = (url,eventName) => \n eventName === 'error' || isExternalLink(url) \n \nconst errorType = error => 'error' \n \nasync function fetchApiData(url, shouldLog) { \n const logger = makeLogger(shouldLog)(url) \n logger('start') \n try { \n const response = await fetch(url) \n logger('success') \n return response \n } \n catch (error) { \n logger(errorType(error)) \n } \n} \n \nasync function main() { \n await fetchApiData('http://localhost:8080', neverLog) // no log \n await fetchApiData('http://www.google.ca', alwaysLog) // full log \n await fetchApiData('http://localhost:8080', logError) // log error only \n await fetchApiData('http://localhost:8080', logExternalOrError) \n} \n \nmain()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T00:29:07.547",
"Id": "527792",
"Score": "0",
"body": "Thanks Ted, this is awesome. Looking at the comments on the question by moderators, I was actually waiting for it to get deleted. You saved my life. Thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T17:32:38.177",
"Id": "267635",
"ParentId": "267615",
"Score": "3"
}
},
{
"body": "<h2>Minimize function's role.</h2>\n<p>It is the <code>Logger</code> that should be filtering log events not <code>fetchApiData</code>.</p>\n<p>However I suspect there is a design problem as I can not see how the logger knows the URL. EG <code>Logger.logFetchStartedEvent()</code> is not passed the URL</p>\n<p>What needs to be done is for the logger to know what URL it is logging and that it filters log events according to what ever rules are current. That way your first snippet will is the correct code, and it also means any other code that is logging events can do so without needing to track a logging rule set.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T19:15:55.980",
"Id": "267638",
"ParentId": "267615",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "267635",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T05:44:03.383",
"Id": "267615",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Implement complex, intersecting limitations on when and when not to log"
}
|
267615
|
<p>I'm learning C and I just had the exercise to write a function that checks for the lower one of two floating-points.
So I thought, I either could use pointer and also return the pointer of the lower value - otherwise, I simply could use the values and return the lower value.</p>
<pre class="lang-c prettyprint-override"><code>double* pointer_min_value(double* first, double* second){
return *first > *second ? second : first;
}
double calc_min_value(double first, double second){
return first > second ? second : first;
}
int main() {
printf("Enter two numbers to define the minimum!\n");
double first, second;
scanf("%lf%lf", &first, &second);
printf("The lower value is %lf", *pointer_min_value(&first, &second));
printf("The lower value is %lf", calc_min_value(first, second));
return 0;
}
</code></pre>
<p>they both work, but what would make more sense? should I use pointer only if I want to change the value (I mean, I should not change any of the parameters in a "get me the lowest number"-funtion), or would it be better in any other view (resources, performance,...).</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T14:57:14.010",
"Id": "527771",
"Score": "1",
"body": "This will probably be a candidate for a `static` modifier, thus with optimization, I suspect the assembler would probably be the same."
}
] |
[
{
"body": "<h2>Versatility</h2>\n<p>The pointer version is less versatile.</p>\n<p>If the two values come from expressions like in <code>min_value(x + 13, 2 * y)</code>, you can't use the pointer version, as neither <code>x + 13</code> nor <code>2 * y</code> exist as pointable memory locations, only as temporary values.</p>\n<h2>Surprises</h2>\n<p>The pointer version might give surprising results in the long run.</p>\n<p>If now <code>first</code> is lower than <code>second</code>, the function will return a pointer to <code>first</code>. If you later change the content of the <code>first</code> variable, the value of the result changes as well.</p>\n<p>If <code>first</code> and <code>second</code> are local variables declared inside a function <code>foo()</code>, and you happen to return the <code>pointer_min_value()</code> result (the pointer), then, after leaving <code>foo()</code>, the variables no longer exist, and your result points to garbage memory.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T12:48:54.267",
"Id": "527755",
"Score": "2",
"body": "Note that using `const` references avoids those surprises, and gives you [value *semantics*](https://en.wikipedia.org/wiki/Value_semantics), while still technically using pointers under the hood. This is for example what [`std::min()`](https://en.cppreference.com/w/cpp/algorithm/min) does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T12:55:38.433",
"Id": "527756",
"Score": "1",
"body": "so using plain value / `double` would be the more \"correct\" / better version in this case?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T12:58:37.673",
"Id": "527757",
"Score": "4",
"body": "@MatthiasBurger Yes. Generally, that depends on the intended usages of the function, but I can't imagine a convincing one in favor of the pointers version."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T12:02:04.583",
"Id": "527799",
"Score": "3",
"body": "@G.Sliepen this is C, not C++. Though, `const` pointers would still be relevant indeed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-07T19:14:52.180",
"Id": "528001",
"Score": "0",
"body": "\" you can't use the pointer version\" is amiss. To use `x + 13`, `2 * y` with the pointer version, code can use compound literals `min_value(&(double){x + 13}, &(double){2 * y})`, not that I _reccomend_ it."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T12:44:55.020",
"Id": "267627",
"ParentId": "267625",
"Score": "16"
}
},
{
"body": "<p>It's a good practice to always pass primitive variables by values. Passing pointers should be reserved for objects that take more space such as arrays or structs. It also makes functions and their calls more readable. If you nitpick, you could also make an argument that something like an <code>int</code> usually uses 4 bytes of memory while a pointer usually uses 8, so the function is slightly more memory hungry.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T12:53:36.833",
"Id": "267628",
"ParentId": "267625",
"Score": "5"
}
},
{
"body": "<h3>Some beautifying</h3>\n<p>I think <code>first < second ? first : second</code> is a tiny bit more readable. First comes first.</p>\n<h3>Double problems</h3>\n<p>Floating points are tricky. What will happen if one of doubles will be NaN? Of course, you can always say that the function assumes both values are valid, but you should consider this too.</p>\n<h3>Pointer problems</h3>\n<p>Pointers are also tricky. <code>pointer_min_value(NULL, NULL)</code> will cause UB. Once again, adding a comment "no NULLs allowed" is ok - but neglecting this possibility isn't.</p>\n<h3>Making sure the values, passed by pointers, won't change</h3>\n<p>You can add <code>const</code> modifier to arguments and returning value to do this, if you mean this.</p>\n<h3>Performance considerations</h3>\n<p>Passing a huge argument by value can be a bad idea; but doubles are only 8 bytes - like pointers on 86x64 architecture; pointers on 86x32 are 4 bytes, so you can save 8 bytes of stack space with <code>pointer_min_value</code>. But who cares with modern RAM sizes?</p>\n<p>On the other hand, dereferencing pointers isn't free, so <code>calc_min_value</code> will be a bit faster, but who cares with modern CPU/RAM speeds and cache sizes?</p>\n<h3>Chief difference</h3>\n<p>The only thing <code>pointer_min_value</code> does that <code>calc_min_value</code> doesn't - it returns a pointer. Why is this important? Because you can change the returned value!</p>\n<pre><code>*pointer_min_value(&first, &second) = 0.0;\n</code></pre>\n<p>changes lesser one to 0.0. That's the greatest difference.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T13:14:58.663",
"Id": "527760",
"Score": "2",
"body": "Oh the chief difference is nice.. I like!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T12:05:45.333",
"Id": "527801",
"Score": "3",
"body": "Modern calling conventions pass `double`s in registers (if there are few enough of floating-point parameters), which makes the question of their size not too relevant."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T13:04:31.193",
"Id": "267629",
"ParentId": "267625",
"Score": "10"
}
},
{
"body": "<p>Both compare functions lack good handling of all <code>double</code> values.</p>\n<p>Troublesome cases involve -0.0 and <a href=\"https://en.wikipedia.org/wiki/NaN\" rel=\"nofollow noreferrer\">not a number</a>:</p>\n<ol>\n<li><p><code>calc_min_value(-0.0, +0.0)</code> returns 0.0. OK, but not clear from the function specification. -0.0 is reasonable - but worth the effort?</p>\n</li>\n<li><p><code>calc_min_value(NotANumber, 42.0)</code> returns 42.0 - seems reasonable.</p>\n</li>\n<li><p><code>calc_min_value(42.0, NotANumber)</code> returns NotANumber - inconsistent with #2. I'd expect #2 & #3 to return the same.</p>\n</li>\n<li><p><code>calc_min_value(NotANumberA, NotANumberB)</code> returns NotANumberB. Rare case when 2 NANs are present. Slightly more common to return the first when both quiet or both signaling NANs, else the signaling one.</p>\n</li>\n</ol>\n<p>Using a return of a pointer does allow returning of the <code>first</code> address, <code>second</code> address, or <code>NULL</code> - perhaps for NAN cases. Yet a three way return may be clumsy for the user.</p>\n<hr />\n<p>FP functions are most commonly handled with numeric parameters and return - not an address.</p>\n<p>Note: Compare of numeric values often involves a <em>constant</em>. Forming the address is <a href=\"https://codereview.stackexchange.com/questions/267625/minimum-of-two-floating-point-numbers/267763#comment528001_267627\">more work</a>.</p>\n<hr />\n<p>Consider returning the lesser of the two when they have different <em>values</em>, -0.0 when tied with 0.0, else the first when equal and the non-NAN when one of them is NAN.</p>\n<p>Possibly may want to return -NAN over a NAN when both NAN (not shown).</p>\n<p>Pedantic code checks for NAN-ness first as <code>first < second</code> is not specified by C concerning NANs, yet that compare is very commonly <code>false</code>.</p>\n<pre><code>// More robust\ndouble calc_min_value(double first, double second) {\n if (isnan(first)) {\n if (isnan(second)) return first;\n return second;\n }\n if (isnan(second)) {\n return first;\n }\n if (first < second) return first;\n if (second < first) return second;\n\n // If both the same sign, return the first.\n if (!signbit(first) == !signbit(second)) return first;\n return signbit(first) ? first : second;\n}\n</code></pre>\n<hr />\n<p>Research also <code>isless()</code></p>\n<blockquote>\n<p>The <code>isless</code> macro determines whether its first argument is less than its second argument. The value of <code>isless(x,y)</code> is always equal to (x)< (y); however, unlike (x)< (y), <code>isless(x,y)</code> does not raise the "invalid" floating-point exception when x and y are unordered and neither is a signaling NaN.</p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-07T18:49:59.987",
"Id": "267763",
"ParentId": "267625",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "267627",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T12:24:42.560",
"Id": "267625",
"Score": "6",
"Tags": [
"c",
"pointers"
],
"Title": "Minimum of two floating-point numbers"
}
|
267625
|
<p>I'm new to C++, and I wanted to add a way to log in a fancy way. As such, I created a small bit of code to do so, but I'm wondering how I can improve my code, especially the fact that <code>DebugColors</code> consists of two files, and regarding my use of templates, as I don't think the <code>adder</code> method(s) of the Debug struct is the best way to concatenate strings.</p>
<p>Additionally, I'm unsure if I should be using a struct in order to contain the methods, or if I should use a namespace for it, as I only want to be able to access the public methods from outside the struct.</p>
<p><strong>DebugColors.hpp</strong></p>
<pre><code>#ifndef DEBUG_COLORS
#define DEBUG_COLORS
#include <string>
namespace DebugColors {
extern std::string reset;
extern std::string red;
extern std::string green;
extern std::string yellow;
extern std::string blue;
}
#endif
</code></pre>
<p><strong>DebugColors.cpp</strong></p>
<pre class="lang-cpp prettyprint-override"><code>#include "DebugColors.hpp"
namespace DebugColors {
std::string reset = "\x1b[0m";
std::string red = "\x1b[31m";
std::string green = "\x1b[32m";
std::string yellow = "\x1b[33m";
std::string blue = "\x1b[34m";
}
</code></pre>
<p><strong>Debug.hpp</strong></p>
<pre><code>#ifndef DEBUG_HPP
#define DEBUG_HPP
#include <string>
#include <iostream>
#include "DebugColors.hpp"
struct Debug {
private:
template<typename T>
static T adder(T v) {
return v;
}
template<typename T, typename ...Args>
static T adder(T first, Args ...args) {
return first + " " + adder<std::string>(args...);
}
template<typename ...T>
static void LogMessage(T&... args) {
std::string message = adder<std::string>(args...);
std::cout << message << std::endl;
}
public:
template<typename ...T>
static void Log(T&... args) {
LogMessage(args...);
}
template<typename ...T>
static void Info(T&... args) {
LogMessage(DebugColors::blue, "[INFO]", args..., DebugColors::reset);
}
template<typename ...T>
static void Warning(T&... args) {
LogMessage(DebugColors::yellow, "[WARN]", args..., DebugColors::reset);
}
template<typename ...T>
static void Error(T&... args) {
LogMessage(DebugColors::red, "[ERROR]", args..., DebugColors::reset);
}
template<typename ...T>
static void Success(T&... args) {
LogMessage(DebugColors::green, "[SUCCESS]", args..., DebugColors::reset);
}
};
#endif
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<h2>Using <code>namespaces</code></h2>\n<p>We can put everything into a <code>namespace</code> which would enable us to use <code>using</code>.</p>\n<p>Consider this example,</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>using Debug::Log; //Error if it's a static member function\n // Error msg: error: ‘Debug’ is not a namespace or unscoped enum\n\nnamespace Debug{\n Type Func(){ ... };\n}\n\nusing Debug::Func; // No error\n\nFunc(); // Calls `Debug::Func`\n</code></pre>\n<p>Since, <code>Log</code>, <code>Info</code>, <code>Error</code>, <code>Warning</code> and <code>Success</code> are just standalone utility functions. I see no reason to put them in a class.</p>\n<p>We can put private functions into a different <code>namespace</code> say <code>impl</code>, a namespace which would contain private functions of <code>Debug</code> class.</p>\n<pre><code>namespace impl{\n std::string add(...) {...}\n void LogMessage(...) {...}\n}\n\nnamespace Debug{\n void Log(...) { impl::LogMessage(...) }\n void Info(...) { impl::LogMessage(...) }\n void Error(...) { impl::LogMessage(...) }\n}\n</code></pre>\n<h2>Use <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/to_string\" rel=\"nofollow noreferrer\"><code>std::to_string</code></a> to print <code>int</code>s and <code>float</code>s</h2>\n<p>Create a <code>to_str</code> function which would call <code>std::string</code>. Why this is necessary is explained in the below paragraphs.</p>\n<pre><code>namespace impl {\n\ntemplate<typename T>\nstd::string to_str(const T& val){\n return std::to_string(val);\n}\n\nstd::string to_str(const std::string& val){\n return val;\n}\n\nstd::string to_str(const char * str){\n return std::string(str);\n}\n\n} // namespace impl\n</code></pre>\n<h2><a href=\"https://en.cppreference.com/w/cpp/language/fold\" rel=\"nofollow noreferrer\">Fold Expression since C++17</a></h2>\n<p>We can leverage fold expression when working with variadic functions. We can rewrite the <code>adder</code> as such.</p>\n<pre><code>namespace impl{\n\ntemplate <typename... Args>\nstd::string adder(Args... args) {\n return ((to_str(args) + " ") + ...);\n}\n\n}\n</code></pre>\n<h2><a href=\"https://stackoverflow.com/questions/56842571/is-a-forwarding-reference-still-an-rvalue-reference-or-not\">forwarding reference</a></h2>\n<p>Your current implementation we can only use <em>lvalues</em> with functions. Using forwarding reference we can pass both <em>lvalues</em> and <em>rvalues</em>.</p>\n<pre><code>namespace Debug{\n\ntemplate <typename... T>\nvoid Log(T&&... args) {\n impl::LogMessage(args...);\n}\n// Similarly for other functions too.\n}\n</code></pre>\n<hr />\n<h2>Full code</h2>\n<p><code>Debug.hpp</code></p>\n<pre><code>#ifndef DEBUG_HPP\n#define DEBUG_HPP\n\n#include <iostream>\n#include <string>\n\n#include "DebugColors.h"\n\nnamespace impl {\n\ntemplate<typename T>\nstd::string to_str(const T& val){\n return std::to_string(val);\n}\n\nstd::string to_str(const std::string& val){\n return val;\n}\n\nstd::string to_str(const char * str){\n return std::string(str);\n}\n\ntemplate <typename... Args>\nstd::string adder(Args&&... args) {\n return ((to_str(args) + " ") + ...);\n}\n\ntemplate <typename... T>\nvoid LogMessage(T&&... args) {\n std::string message = adder(args...);\n\n std::cout << message << std::endl;\n}\n} // namespace impl\n\nnamespace Debug {\ntemplate <typename... T>\nvoid Log(T&&... args) {\n impl::LogMessage(args...);\n}\n\ntemplate <typename... T>\nvoid Info(T&&... args) {\n impl::LogMessage(DebugColors::blue, "[INFO]", args..., DebugColors::reset);\n}\n\ntemplate <typename... T>\nvoid Warning(T&&... args) {\n impl::LogMessage(DebugColors::yellow, "[WARN]", args..., DebugColors::reset);\n}\n\ntemplate <typename... T>\nvoid Error(T&&... args) {\n impl::LogMessage(DebugColors::red, "[ERROR]", args..., DebugColors::reset);\n}\n\ntemplate <typename... T>\nvoid Success(T&&... args) {\n impl::LogMessage(DebugColors::green, "[SUCCESS]", args...,\n DebugColors::reset);\n}\n\n} // namespace Debug\n\n#endif\n</code></pre>\n<hr />\n<p><code>test.cpp</code></p>\n<pre><code>include "Debug.hpp"\n\nusing Debug::Error;\nint main(){\n int t = 10;\n Error("Danger", 20, t, 3.14);\n}\n</code></pre>\n<p>Output:</p>\n<p><a href=\"https://i.stack.imgur.com/TDbqc.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/TDbqc.png\" alt=\"enter image description here\" /></a></p>\n<hr />\n<p>You can use <a href=\"https://clang.llvm.org/docs/ClangFormat.html\" rel=\"nofollow noreferrer\"><code>clang-format</code></a> for formatting your code files.</p>\n<p>Terminal command:</p>\n<pre><code>clang-format -style=Google -i files\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T13:49:10.873",
"Id": "527805",
"Score": "0",
"body": "Good review! What do you think about also mentioning `std::string_view` for the color codes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T16:33:27.403",
"Id": "527809",
"Score": "0",
"body": "@Edward I would suggest that too. But this rewritten code would unnecessarily convert it to `string` each time. It also converts `const char*`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T16:35:40.007",
"Id": "527810",
"Score": "0",
"body": "@Ch3steR instead of `to_str` call it `wrap` or something that does not imply a specific return type. Use `string_view` as returns for `const char*` and `string_view` itself, as well as `string` so you don't have to copy it. But keep `string` return for numbers and such where it allocates memory as part of the conversion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T17:37:31.187",
"Id": "527815",
"Score": "0",
"body": "@Edward Thank you. Yes `string_view` is much better."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T17:39:05.710",
"Id": "527816",
"Score": "1",
"body": "@JDługosz Yes agreed, `to_str` is unnecessarily creating copies. I'm not near my laptop. Can you add it an answer since it's very good suggestion?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T21:10:42.327",
"Id": "267641",
"ParentId": "267630",
"Score": "4"
}
},
{
"body": "<h2>Everything @Ch3steR said</h2>\n<h2>Const Correctness</h2>\n<p>You don't want some other developer breaking your code by accidentally changing the value of your color variables. So you should make them costant (that will make sure the compiler does not allow any alterations:</p>\n<pre><code>namespace DebugColors {\n extern std::string const reset;\n extern std::string const red;\n extern std::string const green;\n extern std::string const yellow;\n extern std::string const blue;\n}\n</code></pre>\n<p>You can also use <code>std::string</code> literals (rather than C-String literals that call the constructor).</p>\n<pre><code>namespace DebugColors {\n\n using namespace std::string_literals;\n\n std::string const reset = "\\x1b[0m"s; // Notice the s\n std::string const red = "\\x1b[31m"s;\n std::string const green = "\\x1b[32m"s;\n std::string const yellow = "\\x1b[33m"s;\n std::string const blue = "\\x1b[34m"s;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-04T18:13:43.013",
"Id": "267693",
"ParentId": "267630",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "267641",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T13:56:05.987",
"Id": "267630",
"Score": "8",
"Tags": [
"c++",
"beginner"
],
"Title": "Simple debug logging"
}
|
267630
|
<p>I'm looking forward for any feedback to help improve in any way this React component that will render an emoji from GitHub, Twitter or OpenEmoji:</p>
<pre><code>import React from "react";
const placeholder = "{unicode}";
const sources = {
GitHub: {
src: `https://github.githubassets.com/images/icons/emoji/unicode/${placeholder}.png?v8`,
upperCase: false,
},
Twitter: {
src: `https://twemoji.maxcdn.com/v/latest/svg/${placeholder}.svg`,
upperCase: false,
},
OpenMoji: {
src: `https://www.openmoji.org/data/color/svg/${placeholder}.svg`,
upperCase: true,
},
};
export type SemojiProps = {
className?: string;
emoji: string;
height?: string;
source: keyof typeof sources;
};
export function Semoji({
className = "",
emoji,
height = "1em",
source,
}: SemojiProps): JSX.Element | null {
const unicode = emoji.codePointAt(0)?.toString(16);
if (!unicode) {
return null;
}
const { src, upperCase } = sources[source];
return (
<span style={{ lineHeight: 0 }}>
<img
alt={emoji}
className={className}
src={src.replace(
placeholder,
upperCase ? unicode.toUpperCase() : unicode
)}
style={{ display: "inline-block", height }}
/>
</span>
);
}
export default Semoji;
</code></pre>
<p>The code is straightforward, but any insights to improve it are very appreciated. I'm specifically concern about a11y, semantic markup, and styling issues.</p>
<p>CodeSandbox example: <a href="https://codesandbox.io/s/sleepy-sun-cz47o" rel="nofollow noreferrer">https://codesandbox.io/s/sleepy-sun-cz47o</a></p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T14:40:27.183",
"Id": "267632",
"Score": "0",
"Tags": [
"css",
"react.js",
"typescript",
"html5",
"jsx"
],
"Title": "React component to display emojis from different sources"
}
|
267632
|
<p>I've written this little helper function, that will block the current thread until any of a given list of signals is emitted by an object or until an optional timeout is reached.
It can be used to synchronize network communication or the likes.</p>
<p>I'm not happy that you have to explicitly specify <code>std::tuple</code> on the call site (see usage below) but I didn't see any way that would still allow the trailing optional timeout argument.
Also I only use it in background threads that don't have any event loop yet, possibly this could mess with the main event loop if used in the main thread.</p>
<p><a href="https://godbolt.org/z/fvoMPx9K7" rel="nofollow noreferrer">Compiler explorer link</a></p>
<p><strong>Implementation</strong></p>
<pre><code>/*!
* \brief waitForSignals
* waits until any of the given signals is emitted by the given sender or the timeout is reached (if given)
* \param src
* source object to monitor
* \param sigs
* the signals to listen for
* \param timeoutMs
* maximum time to listen for the signal before returning. if this is negative, no timeout is used
* \return
* true if one of the signals got emitted. false if the operation timed out
*/
template< typename Sender, typename ...Signal,
std::enable_if_t<
std::is_base_of_v<QObject, Sender> &&
(sizeof...(Signal) > 0) &&
(std::is_member_function_pointer_v<Signal> && ...) >* = nullptr >
bool waitForSignals(Sender *src, std::tuple<Signal...> sigs , int timeoutMs = -1)
{
QEventLoop loop;
std::apply([&loop, src](auto... s){
(QObject::connect(src, s, &loop, &QEventLoop::quit), ...);
}, sigs);
QTimer timer;
bool aborted = false;
if(timeoutMs >= 0)
{
QObject::connect(&timer, &QTimer::timeout, [&](){ aborted = true; });
QObject::connect(&timer, &QTimer::timeout, &loop, &QEventLoop::quit);
timer.setSingleShot(true);
timer.start(timeoutMs);
}
loop.exec();
return timeoutMs < 0 || !aborted;
}
/*!
* \brief waitForSignal
* like \a waitForSignals but only waits for the one signal insead of a list
* \sa waitForSignals
*/
template< typename Sender, typename Signal>
bool waitForSignal(Sender *src, Signal sig , int timeoutMs = -1)
{
return waitForSignals(src, std::tuple{sig}, timeoutMs);
}
</code></pre>
<p><strong>Usage</strong></p>
<pre><code>MyObject obj;
waitForSignal(&obj, &MyObject::mySignalOne);
waitForSignal(&obj, &MyObject::mySignalOne, 100);
waitForSignals(&obj, std::tuple{&MyObject::mySignalOne, &MyObject::mySignalTwo});
waitForSignals(&obj, std::tuple{&MyObject::mySignalOne, &MyObject::mySignalTwo}, 100);
</code></pre>
|
[] |
[
{
"body": "<h1>Avoiding the <code>std::tuple</code></h1>\n<blockquote>\n<p>I'm not happy that you have to explicitly specify <code>std::tuple</code> on the call site (see usage below) but I didn't see any way that would still allow the trailing optional timeout argument.</p>\n</blockquote>\n<p>There is a way by converting the function to a <code>class</code> that does all the work in its constructor, and then provide a deduction guide, as shown in <a href=\"https://stackoverflow.com/a/57548488/5481471\">this StackOverflow answer</a>.</p>\n<p>You are <a href=\"https://www.cppstories.com/2021/non-terminal-variadic-args/\" rel=\"nofollow noreferrer\">not the first</a> to run into this issue, and it might be fixed in C++23, perhaps having the compiler automatically deduce the right thing, or maybe by allowing deduction guides for free functions.</p>\n<h1>No need to connect two actions to the timer</h1>\n<p>Connecting two actions to the timer is not necessary. You could have the lambda quit the event loop, but even better is to only have the timer quit the event loop, and not set the variable <code>aborted</code>, but instead just check for <code>timer.isActive()</code> after the loop ended.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T08:20:54.830",
"Id": "527795",
"Score": "0",
"body": "That's a neat trick with the deduction guide"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T18:47:50.803",
"Id": "267637",
"ParentId": "267634",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "267637",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T15:17:10.617",
"Id": "267634",
"Score": "1",
"Tags": [
"c++",
"c++17",
"qt"
],
"Title": "Blocking until one or multiple signals is emitted"
}
|
267634
|
<p><a href="https://sourceforge.net/p/p7zip/discussion/383044/thread/8066736d/" rel="nofollow noreferrer">It appears that 7z can't write to a pipe</a>, so I wrote the following bash function to emulate this functionality.</p>
<p>I know this is a simple problem, but this is my first bash function and I feel like it's really easy to write faulty code in bash, so any feedback is appreciated.</p>
<pre><code>function 7z2pipe () (
local out_dir=$(mktemp -d)
local out_file="${out_dir}"/temp.7z
local log_file="${out_dir}"/"outz.txt"
7z -p"weak_password" -mhe=on a "${out_file}" "$@" &> "${log_file}"
if [ $? -ne 0 ]; then
cat "${log_file}"
return $?
fi
cat "${out_file}"
)
</code></pre>
|
[] |
[
{
"body": "<h3>Do you want to make persistent temporary files?</h3>\n<p>Note that while the default settings for <code>mktemp</code> put things in /tmp so that it will eventually get garbage collected, it doesn't immediately get garbage collected. Things can persist in /tmp for days.</p>\n<h3><code>cat</code> has a return code</h3>\n<p>I'm not sure why are returning the return code from <code>cat</code>. Wouldn't it make more sense to return the return code from <code>7z</code>?</p>\n<h3>Alternative code</h3>\n<pre><code> local return_code=$?\n if [ ${return_code} -ne 0]; then\n cat "${log_file}"\n else\n cat "${out_file}"\n fi\n\n rm -rf ${out_dir}\n return ${return_code}\n</code></pre>\n<p>That will leave things as you found them, with no extra temporary directories or files.</p>\n<p>It will always return the return code from <code>7z</code>.</p>\n<p>It will output either the log file or the output file, as you originally did it.</p>\n<h3>Redirect to <code>stderr</code></h3>\n<p>I'm not sure that your approach is what I would do. An alternative to creating the log file would be to redirect <code>stdout</code> to <code>stderr</code>.</p>\n<pre><code> local out_file=$(mktemp --suffix .7z)\n 7z -p"weak_password" -mhe=on a "${out_file}" "$@" 1>&2\n\n local return_code=$?\n\n cat "${out_file}"\n rm -f ${out_file}\n\n return ${return_code}\n</code></pre>\n<p>Now <code>stdout</code> will contain the compressed file and <code>stderr</code> will have all the output from the command.</p>\n<p>Note: I do not normally use Bash functions, so don't take anything I say as validation of function syntax.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-05T11:01:55.887",
"Id": "527879",
"Score": "0",
"body": "Actually, `mktemp` will put its file into `$TMPDIR` if that's set (this is how `pam_tmpdir` implements per-user temporary directories). The point still stands that it's good practice to add a `trap` to clean up, of course."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T23:35:01.370",
"Id": "267643",
"ParentId": "267639",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-02T20:01:51.263",
"Id": "267639",
"Score": "2",
"Tags": [
"bash"
],
"Title": "bash function to \"wrap\" 7z"
}
|
267639
|
<p>Since I have barely used inheritance in Python, I wanted to make something that would make use of it so I have attempted to create a game of chess, where each piece uses inheritance. I also did this just for fun.</p>
<p>I have not added anything related to Checks, Turns (you can move any piece of any colour), game over conditions, en passant or even checking if the square you selected to move is a valid piece (it will just throw invalid move and do nothing instead). Currently it is just all of the pieces, validating moves, pawn promotion and taking other pieces.</p>
<p>The code is currently working quite well and I plan to add what it is missing at a later stage, but I thought it would be a good idea to get it looked over now, just in case I am doing something completely wrong that will cause more issues later.</p>
<p>The folder structure is as follows (if you want to run it yourself):</p>
<pre><code>+ main.py
+ board.py
/ Pieces
+ __init__.py
+ bishop.py
+ king.py
+ knight.py
+ pawn.py
+ piece.py
+ queen.py
+ rook.py
</code></pre>
<p><strong>main.py</strong></p>
<pre><code>from board import Board
LETTERS = "ABCDEFGH"
NUMBERS = "12345678"
if __name__ == "__main__":
board = Board()
print(board.board[8:0, 7:9])
while True:
board.display()
while True:
start = input("What piece would you like to move? (eg. A2)\n")
if len(start) == 2:
if start[0].upper() in LETTERS and start[1] in NUMBERS:
break
print("Please write the coordinate in the form A2 (Letter)(Number)")
while True:
end = input("What square would you like to move to? (eg. A3)\n")
if len(end) == 2:
if end[0].upper() in LETTERS and end[1] in NUMBERS:
break
print("Please write the coordinate in the form A2 (Letter)(Number)")
board.movePiece(start.upper(), end.upper())
</code></pre>
<p><strong>board.py</strong></p>
<pre><code>from typing_extensions import TypedDict
import Pieces as p
import numpy as np
class Coordinate(TypedDict):
x: int
y: int
class Board():
def __init__(self):
self.board = np.full((8, 8), p.Piece("", -1, -1), dtype=p.Piece)
self.setBoard()
def setBoard(self):
""""Initialise the board by creating and placing all pieces for both colours"""
colours = ["black", "white"]
for i in range(8):
self.board[1][i] = p.Pawn("black", i, 1)
self.board[6][i] = p.Pawn("white", i, 6)
for j in (0, 1):
pos = j * 7
for i in (0, 7):
self.board[pos][i] = p.Rook(colours[j], i, pos)
for i in (1, 6):
self.board[pos][i] = p.Knight(colours[j], i, pos)
for i in (2, 5):
self.board[pos][i] = p.Bishop(colours[j], i, pos)
self.board[pos][3] = p.Queen(colours[j], 3, pos)
self.board[pos][4] = p.King(colours[j], 4, pos)
def display(self):
"""Print the board with borders"""
print("-" * len(self.board) * 3)
for i in range(len(self.board)):
print('|' + '|'.join(map(str, self.board[i])) + '|')
print("-" * len(self.board) * 3 + '-')
def convertToCoords(self, position: str) -> Coordinate:
"""Convert coordinates from the Chess Syntax (ie. A2) to usable array coordinates"""
letters = "ABCDEFGH"
return {"y": abs(int(position[1]) - 8), "x": letters.find(position[0])}
def convertToAlphaCoords(self, coord: Coordinate) -> str:
"""Convert coordinates from usable array coordinates to the Chess Syntax coordinates (ie. A2)"""
letters = "ABCDEFGH"
return letters[coord["x"]] + str(abs(coord["y"] - 8))
def checkCollisions(self, piece: p.Piece, victim: p.Piece, start: dict, end: dict):
"""Check whether a move will collide with a piece.
This function only applies to Rooks, Bishops and Queens."""
minY = min(start["y"], end["y"])
maxY = max(start["y"], end["y"])
minX = min(start["x"], end["x"])
maxX = max(start["x"], end["x"])
rookMove = False
if isinstance(piece, p.Rook) or isinstance(piece, p.Queen):
if start["x"] == end["x"]:
claim = self.board[minY:maxY, start["x"]]
rookMove = True
elif start["y"] == end["y"]:
claim = self.board[start["y"], minX:maxX]
rookMove = True
if rookMove:
for i in claim:
if i != piece and i != victim:
if i.initialised:
block = self.convertToAlphaCoords({"x": i.x, "y": i.y})
raise p.InvalidMove(f"This move is blocked by a piece at {block}")
if isinstance(piece, p.Bishop) or isinstance(piece, p.Queen):
claim = []
for i in range(minX, maxX):
for j in range(minY, maxY):
if abs(i - start["x"]) == abs(j - start["y"]):
claim.append(self.board[j][i])
for i in claim:
if i != piece and i != victim:
if i.initialised:
block = self.convertToAlphaCoords({"x": i.x, "y": i.y})
raise p.InvalidMove(f"This move is blocked by a piece at {block}")
def movePiece(self, start: str, end: str):
"""Move a piece. It takes a starting position and an ending position,
checks if the move is valid and then moves the piece"""
start = self.convertToCoords(start)
end = self.convertToCoords(end)
piece = self.board[start["y"]][start["x"]]
victim = self.board[end["y"]][end["x"]]
try:
piece.checkMove(end["x"], end["y"], victim)
self.checkCollisions(piece, victim, start, end)
piece.move(end)
if isinstance(piece, p.Pawn):
if end["y"] == 7 or end["y"] == 0:
piece = piece.promote()
self.board[end["y"]][end["x"]] = piece
self.board[start["y"]][start["x"]] = p.Piece("", -1, -1)
except p.InvalidMove as e:
print(e.message)
</code></pre>
<p><strong>__init__.py</strong></p>
<pre><code>"""Taken from https://stackoverflow.com/a/49776782/12115915"""
import os
import sys
dir_path = os.path.dirname(os.path.abspath(__file__))
files_in_dir = [f[:-3] for f in os.listdir(dir_path)
if f.endswith('.py') and f != '__init__.py']
for f in files_in_dir:
mod = __import__('.'.join([__name__, f]), fromlist=[f])
to_import = [getattr(mod, x) for x in dir(mod) if isinstance(getattr(mod, x), type)] # if you need classes only
for i in to_import:
try:
setattr(sys.modules[__name__], i.__name__, i)
except AttributeError:
pass
</code></pre>
<p><strong>piece.py</strong></p>
<pre><code>class Piece():
def __init__(self, team: str, x: int, y: int, initisalised: bool = False):
self.team = team
self.x = x
self.y = y
self.initialised = initisalised
self.moved = False
def __str__(self) -> str:
return " "
def checkMove(self, x: int, y: int, other):
raise InvalidMove("You cannot move an empty square")
def move(self, coord: dict):
self.x = coord["x"]
self.y = coord["y"]
self.moved = True
class InvalidMove(Exception):
def __init__(self, message):
self.message = message
super().__init__(message)
def __str__(self) -> str:
return self.message
</code></pre>
<p><strong>bishop.py</strong></p>
<pre><code>from .piece import Piece
from .piece import InvalidMove
class Bishop(Piece):
def __init__(self, team: str, x: int, y: int):
Piece.__init__(self, team, x, y, True)
self.promoted = False
def __str__(self) -> str:
if self.team == "white":
return "wB"
return "bB"
def checkMove(self, x: int, y: int, other):
if self.x == x and self.y == y:
raise InvalidMove("You cannot move to the same spot")
if other.team == self.team:
raise InvalidMove("Bishops cannot take their own pieces")
if abs(self.x - x) != abs(self.y - y):
raise InvalidMove("Bishops can only move diagonally")
</code></pre>
<p><strong>king.py</strong></p>
<pre><code>from .piece import Piece
from .piece import InvalidMove
class King(Piece):
def __init__(self, team: str, x: int, y: int):
Piece.__init__(self, team, x, y, True)
self.promoted = False
def __str__(self) -> str:
if self.team == "white":
return "wK"
return "bK"
def checkMove(self, x: int, y: int, other):
if self.x == x and self.y == y:
raise InvalidMove("You cannot move to the same spot")
if other.team == self.team:
raise InvalidMove("Kings cannot take their own pieces")
if abs(x - self.x) > 1 or abs(y - self.y) > 1:
raise InvalidMove("Kings can only move one space in any direction")
</code></pre>
<p><strong>knight.py</strong></p>
<pre><code>from .piece import Piece
from .piece import InvalidMove
class Knight(Piece):
def __init__(self, team: str, x: int, y: int):
Piece.__init__(self, team, x, y, True)
self.promoted = False
def __str__(self) -> str:
if self.team == "white":
return "wN"
return "bN"
def checkMove(self, x: int, y: int, other):
if self.x == x and self.y == y:
raise InvalidMove("You cannot move to the same spot")
if other.team == self.team:
raise InvalidMove("Knights cannot take their own pieces")
minMove = min(abs(x - self.x), abs(y - self.y))
maxMove = max(abs(x - self.x), abs(y - self.y))
if minMove != 1 or maxMove != 2:
raise InvalidMove("Knights can only move in an L shape (2 in one direction, 1 in another)")
</code></pre>
<p><strong>pawn.py</strong></p>
<pre><code>from .piece import Piece
from .piece import InvalidMove
from .rook import Rook
from .bishop import Bishop
from .knight import Knight
from .queen import Queen
class Pawn(Piece):
def __init__(self, team: str, x: int, y: int):
Piece.__init__(self, team, x, y, True)
self.promoted = False
def __str__(self) -> str:
if self.team == "white":
return "wP"
return "bP"
def promote(self) -> Piece:
self.promoted = True
promotions = "RNBQ"
while True:
choice = input("What would you like to promote the Pawn to? (R, N, B, Q) ").upper()
if choice in promotions:
if choice == "R":
return Rook(self.team, self.x, self.y)
elif choice == "N":
return Knight(self.team, self.x, self.y)
elif choice == "B":
return Bishop(self.team, self.x, self.y)
elif choice == "Q":
return Queen(self.team, self.x, self.y)
def checkMove(self, x: int, y: int, other):
if self.x == x and self.y == y:
raise InvalidMove("You cannot move to the same spot")
if other.team == self.team:
raise InvalidMove("Pawns cannot take their own pieces")
moveDist = abs(y - self.y)
if self.x != x:
if moveDist != 1:
raise InvalidMove("Pawns cannot move sideways unless taking another piece diagonally one space away")
if not other.initialised:
raise InvalidMove("Pawns cannot move diagonally into an empty space")
else:
if other.initialised:
raise InvalidMove("Pawns cannot take pieces in front of them")
if moveDist > 2:
raise InvalidMove("Pawns can only move 1 space (or two if it is their first move)")
if moveDist == 2:
if self.moved:
raise InvalidMove("Pawns can only move two spaces on their first move")
if self.team == "white":
if y > self.y:
raise InvalidMove("White Pawns cannot move down")
else:
if y < self.y:
raise InvalidMove("Black Pawns cannot move up")
</code></pre>
<p><strong>queen.py</strong></p>
<pre><code>from .piece import Piece
from .piece import InvalidMove
class Queen(Piece):
def __init__(self, team: str, x: int, y: int):
Piece.__init__(self, team, x, y, True)
self.promoted = False
def __str__(self) -> str:
if self.team == "white":
return "wQ"
return "bQ"
def checkMove(self, x: int, y: int, other):
if self.x == x and self.y == y:
raise InvalidMove("You cannot move to the same spot")
if other.team == self.team:
raise InvalidMove("Queens cannot take their own pieces")
if not ((self.x == x or self.y == y) or (abs(self.x - x) == abs(self.y - y))):
raise InvalidMove("Queens can only move diagonally, horizontally or vertically any amount")
</code></pre>
<p><strong>rook.py</strong></p>
<pre><code>from .piece import Piece
from .piece import InvalidMove
class Rook(Piece):
def __init__(self, team: str, x: int, y: int):
Piece.__init__(self, team, x, y, True)
self.promoted = False
def __str__(self) -> str:
if self.team == "white":
return "wR"
return "bR"
def checkMove(self, x: int, y: int, other):
if self.x == x and self.y == y:
raise InvalidMove("You cannot move to the same spot")
if other.team == self.team:
raise InvalidMove("Rooks cannot take their own pieces")
if self.x != x and self.y != y:
raise InvalidMove("Rooks can only move in one direction, not diagonally")
</code></pre>
<p>Any feedback would be greatly appreciated!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T18:24:56.127",
"Id": "527817",
"Score": "0",
"body": "This is not about your code, but might be interesting for you. Maybe have a look at bitboards as an efficient and fast method for storing the board and calculating moves https://www.chessprogramming.org/Bitboards"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-08T07:38:18.413",
"Id": "528038",
"Score": "0",
"body": "@jjj I did consider using bitboards however I wanted to make this as a fun little project that implements class inheritance somewhat between the pieces. As far as I know, bitboards do not really use a form of class inheritance for the pieces so I didn't look much further into it. I may be wrong though, so please do correct me if I am."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-08T08:22:10.833",
"Id": "528039",
"Score": "0",
"body": "I mainly wanted to point the the possibility of using them. You can combine classes and bitboards, but if all you want is a playable game it's probably now worth it (the human player is way slower anyway). I would recommend using bitboards when you implement a chess engine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-08T23:05:32.393",
"Id": "528113",
"Score": "0",
"body": "Oh I see. Well, if I eventually get around to making a chess engine, I will definitely look into bitboards more. Thanks!"
}
] |
[
{
"body": "<p>I think this looks pretty good. A few things I would recommend:</p>\n<ol>\n<li>parts of your checkCollision logic should be move into your piece subclasses. Usually when your logic includes isinstance checks, that's a good sign its in the wrong place and not OO.</li>\n<li>There's some duplication in the checkMove validation. No piece should be able to move on itself or take out its own team, so common validations should go in the base class.</li>\n<li>There's potential for the Queen to use multi-inheritance or expose some of the Bishop/Rook logic as a mixin so it can be reused by the Queen</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T03:53:53.507",
"Id": "527794",
"Score": "1",
"body": "Thanks for that. With your first point, I was considering putting the checkCollision logic in each class but I didn't think passing the board through to each piece was a good idea but it does make more sense. With the checkMove validation, I couldn't figure out how to do something like that. Do you have a link to somewhere that I can read up on that while also keeping the default exception if it is called from the base piece class itself? Finally, I didn't even think about multi-inheritance but this does fall into the same thing as the checkMove about not understanding how. Thanks again!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T03:05:38.890",
"Id": "267647",
"ParentId": "267644",
"Score": "10"
}
},
{
"body": "<p>You commonly would not have checkMove method in a chess program instead you would have getValidMoves for each piece and then base checkMove on getValidMoves. The getValidMoves would return a list of possible moves which can be used in a simple computer chess engine. Also the base class Piece is missing logic to allow subclasses to describe actual movement by directions or similar simple logic, consider adding a move class.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T13:43:17.980",
"Id": "267655",
"ParentId": "267644",
"Score": "2"
}
},
{
"body": "<ul>\n<li>Refractor the variable naming to fit Python's usual style: checkMove -> check_move (and similar for all methods and variables)</li>\n<li>Package names should be lowercase. <code>Pieces</code> -> <code>pieces</code></li>\n<li>Further, variable names should be significative: <code>import Pieces as p</code> -> <code>import Pieces</code></li>\n<li><code>main.py</code> is repeating a lot of logic which could be in functions.</li>\n</ul>\n<pre><code>\n def ask_square():\n while True:\n square = input("What piece would you like to move? (eg. A2)\\n")\n if len(start) == 2:\n if square[0].upper() in LETTERS and square[1] in NUMBERS:\n return square\n print("Please write the coordinate in the form A2 (Letter)(Number)")\n \n \n if __name__ == "__main__":\n board = Board()\n print(board.board[8:0, 7:9])\n \n while True:\n board.display()\n start = ask_square()\n end = ask_square()\n board.movePiece(start.upper(), end.upper())\n\n</code></pre>\n<ul>\n<li>Consider using a named tuple instead of a full-blown class for Coordinate. <a href=\"https://stackoverflow.com/a/51673969/9415337\">more about it here</a></li>\n<li><code>colours = ["black", "white"]</code> is being used as a constant. Move it outside the method and as <code>COLOURS = ('black', 'white')</code> (proper naming, use of immutable tuple instead of list)</li>\n<li>Use of enumerate? <code>for j in (0, 1):</code> -> <code>for j, colour in enumerate(colours):</code></li>\n<li><code>convertToCoords</code> and similar methods are only used within the class Board. Why not make them private? Call them <code>_convertToCoords</code> (or following proper naming convention: <code>_convert_to_coords</code>.</li>\n<li>Pass it through black or a similar code formatter to have it cleaned (black.vercel.app/).</li>\n<li>Avoid use of inline magic values. Instead create constants. E.g., <code>BLACK = 'black', WHITE = 'white', COLOURS = (BLACK, WHITE)</code> and use them in places like:</li>\n</ul>\n<pre><code>\n def __str__(self) -> str:\n if self.team == "white":\n return "wR"\n return "bR"\n\n</code></pre>\n<ul>\n<li>If all pieces can be promoted, why not move that to the Piece class to avoid code duplication?</li>\n</ul>\n<pre><code>\n def __init__(self, team: str, x: int, y: int):\n Piece.__init__(self, team, x, y, True)\n self.promoted = False # move this to super and remove in all pieces\n\n</code></pre>\n<ul>\n<li>Again, avoid the use of magic, non-constant, inline values.</li>\n</ul>\n<pre><code>\n def promote(self) -> Piece:\n self.promoted = True\n promotions = "RNBQ"\n while True:\n choice = input("What would you like to promote the Pawn to? (R, N, B, Q) ").upper()\n if choice in promotions:\n if choice == "R":\n return Rook(self.team, self.x, self.y)\n elif choice == "N":\n return Knight(self.team, self.x, self.y)\n elif choice == "B":\n return Bishop(self.team, self.x, self.y)\n elif choice == "Q":\n return Queen(self.team, self.x, self.y)\n\n</code></pre>\n<ul>\n<li>On a more general scope, in regards to the previous code snippet as well, you are mixing the user control with the piece model. These "should" be two separate layers to ease decoupling and e.g. easy replacement to use CLI or a WEB or some UI. Further, this makes it more testable (the way your code is designed mixing user control with the model and logic makes it difficult to unit test). In other words, you should have</li>\n</ul>\n<pre><code> def promote(self, piece: type(Piece)) -> Piece\n</code></pre>\n<p>e.g.</p>\n<pre><code> queen = pawn.promote(Queen)\n</code></pre>\n<p>And have another class in charge of calling this method and asking input to the user.</p>\n<ul>\n<li>There is surely more, but this is enough for one CR! Post again the cleaned code whenever you feel like it.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T16:33:39.913",
"Id": "267659",
"ParentId": "267644",
"Score": "5"
}
},
{
"body": "<p>I have one big piece of advice for you: <a href=\"https://youtu.be/EiOglTERPEo\" rel=\"nofollow noreferrer\">learn to love <code>super()</code></a>.</p>\n<p>When writing classes in python, the <code>super()</code> function allows a child class to delegate part (or all) of a method call to a parent class*. For example, if I have classes <code>Base</code> and <code>Derived</code>, like so:</p>\n<pre><code>class Base:\n def greet_user(self):\n print('Hello! Nice to meet you.')\n\nclass Derived(Base):\n def greet_user(self):\n super().greet_user()\n print("Isn't the weather nice today?")\n</code></pre>\n<p>Then, if I instantiate an instance of <code>Derived</code> and call <code>greet_user</code>, you'll see the following output:</p>\n<pre><code>>>> d = Derived()\n>>> d.greet_user()\nHello! Nice to meet you.\nIsn't the weather nice today?\n</code></pre>\n<p><code>Derived.greet_user()</code> has successfully delegated part of its method call to <code>Base.greet_user()</code>.</p>\n<p>With this in mind, we can significantly cut down on a lot of the repetitive code in your game at the moment. Your <code>Piece</code> class can be refactored to the following, incorporating the logic in the <code>.checkMove()</code> method that's common to all subclasses:</p>\n<pre><code>class Piece:\n def __init__(self, team: str, x: int, y: int, initisalised: bool = False) -> None:\n self.team = team\n self.x = x\n self.y = y\n self.initialised = initisalised\n self.moved = False\n\n def __str__(self) -> str:\n return " "\n \n def checkMove(self, x: int, y: int, other):\n if self.x == x and self.y == y:\n raise InvalidMove("You cannot move to the same spot")\n\n if other.team == self.team:\n raise InvalidMove(\n f"{self.__class__.__name__}s cannot take their own pieces"\n )\n\n def move(self, coord: dict):\n self.x = coord["x"]\n self.y = coord["y"]\n self.moved = True\n</code></pre>\n<p>Now, your <code>King</code> class can be made much shorter:</p>\n<pre><code>class King(Piece):\n def __init__(self, team: str, x: int, y: int):\n Piece.__init__(self, team, x, y, True)\n self.promoted = False\n\n def __str__(self) -> str:\n if self.team == "white":\n return "wK"\n return "bK"\n\n def checkMove(self, x: int, y: int, other):\n super().checkMove(x, y, other)\n\n if abs(x - self.x) > 1 or abs(y - self.y) > 1:\n raise InvalidMove("Kings can only move one space in any direction")\n</code></pre>\n<p>And all your other classes that subclass <code>Piece</code> can be refactored in much the same way.</p>\n<hr />\n<p>*It's important to note that when multiple inheritance is in play, it doesn't <em>always</em> delegate to a direct parent (it sometimes delegates to a sibling) — but that's beyond the scope of this answer.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-04T08:42:10.273",
"Id": "267673",
"ParentId": "267644",
"Score": "4"
}
},
{
"body": "<ol>\n<li>Pieces do not need to store their own locations. You can send both the start and end squares to the <code>checkMove()</code> method. Let the <code>Board</code> class handle positions.</li>\n<li>For the coordinate class, use domain-specific names: <code>file</code> and <code>rank</code>.</li>\n<li>Don't break apart structures so often. In <code>checkMoves()</code>, don't send the <code>x</code> and <code>y</code> coordinates as separate arguments. Send a <code>Coordinate</code> instance. Keep structures together until you actually need the individual data members. This will make your code easier to read. Instead of <code>piece.checkMove(end["x"], end["y"], victim)</code>, write <code>piece.checkMove(end, victim)</code>. Or, with suggestion #1, <code>piece.checkMove(start, end, victim)</code>.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-04T15:09:39.333",
"Id": "267687",
"ParentId": "267644",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "267659",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T01:52:57.443",
"Id": "267644",
"Score": "15",
"Tags": [
"python",
"python-3.x",
"chess"
],
"Title": "First attempt at chess in Python"
}
|
267644
|
<pre><code>var fs = require('fs');
const requestHandler = require('../validations/requestHandler');
exports.index = (req, res) => {
try {
requestHandler(req);
var options = {
'method': 'GET',
'hostname': 'products.torrent.com',
'path': '/torrent/product',
'headers': {
'accept': 'text/plain',
'WebServiceToken': '3A4SnowWqg+Xf0TgMoTEZ12B4AJ1='
},
'maxRedirects': 20
};
var body = null;
var request = https.request(options, function (result) {
var chunks = [];
result.on("data", function (chunk) {
chunks.push(chunk);
});
result.on("end", function (chunk) {
body = Buffer.concat(chunks);
console.log(body.toString());
});
result.on("error", function (error) {
console.error(error);
});
});
request.end();
res.json(body);
} catch(err) {
next(err);
}
}
</code></pre>
<p>I don't use ES6, so don't point it out, I don't want to set it up just yet, but I am wondering if we can cut down on some code, because this doesn't seem clean at all. I am not sure if there's a better library for handling requests, because I feel this is way too wordy.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-06T16:14:33.170",
"Id": "527933",
"Score": "0",
"body": "Just FYI: You don't need to \"setup\" ES6. Node supports most of it out of the box. You can just use it. See https://node.green/"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T02:40:03.203",
"Id": "267646",
"Score": "1",
"Tags": [
"node.js"
],
"Title": "basic node.js controller action with get request"
}
|
267646
|
<p>I am writing a program that takes user input and writes it to a CSV file. I am also checking to see if what they have input is a duplicate of whatever is in that CSV file. So far, the flow of this code snippet is:</p>
<ul>
<li>Get user input -></li>
<li>Iterate through the CSV file and assign it to a list -></li>
<li>If the list is empty (null) or if it doesn't contain a username -></li>
<li>Write data to CSV.</li>
<li>If user input is a duplicate -> don't write</li>
</ul>
<p>I'm a bit new to OOP and C# in general, so any tips would be appreciated.</p>
<pre><code>private string writeUser()
{
string filePath = "usernames.csv";
List<string> users = new List<string>();
try
{
using (StreamReader sr = new StreamReader(filePath))
{
while (sr.Peek() >= 0) // iterate through the csv and add it to our users list
{
users.Add(sr.ReadLine());
}
sr.Close();
}
using (StreamWriter sw = new StreamWriter(filePath, true))
{
if (users == null | !users.Contains(this.username)) // write to csv if users is empty, or if it doesnt contain the typed username
{
sw.WriteLine(this.username);
sw.Close();
}
else if (users.Contains(this.username))
{
Console.WriteLine("username already exists");
sw.Close();
}
}
}
catch (Exception e)
{
Console.WriteLine("Some Error Occured: \n" + e.Message);
Console.ReadLine();
}
return this.username;
}
</code></pre>
<p>How can I simplify this/make what I have better?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T09:48:53.657",
"Id": "527796",
"Score": "0",
"body": "This question has nothing to do with OOP. You have a single function which utilizes built-in classes and functionalities."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T09:50:25.430",
"Id": "527797",
"Score": "1",
"body": "BTW `using` blocks will take care of the `Close` method calls, you don't have to call `sr.Close` and `sw.Close` explicitly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T11:47:03.543",
"Id": "527798",
"Score": "1",
"body": "Why you store usernames in the list? In your code you just check on this list if the user is exists. You do work twice. Better just read the username form the file and check if current username exists. No need to open stream writer when user exists because it is pointless operation."
}
] |
[
{
"body": "<p>We can rewrite this to be more declarative. Not to mention <code>StreamReader</code> and <code>StreamWriter</code> are fairly low level types, in most cases there is a different call to make to express your intent better.</p>\n<pre><code>private string writeUser()\n{\n string filePath = "usernames.csv";\n var found = false;\n //we don't modify the existing list, don't store it\n //if storing, I would use HastSet<> for better duplicate checking\n if(File.Exists(filePath))\n foreach(var user in File.ReadLines(filePath))\n //declare you want to process each line, but not necessarily \n //read the whole file like below \n {\n if(user == username)\n {\n found = true;\n break;//found it, stop looping\n }\n }\n\n if(!found)\n {\n //AppendText will also Create the file for you too if not there\n //skip boolean values that you need to check what the parameter affect\n using (StreamWriter sw = File.AppendText(filePath))\n {\n sw.WriteLine(username);\n }\n }\n return username;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-05T05:24:14.287",
"Id": "527872",
"Score": "0",
"body": "The file can be huge! It is not a good idea to read all file (ReadAllLines method reads whole file to the memory)... Otherwise, I completely agree"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-07T20:46:19.333",
"Id": "528003",
"Score": "0",
"body": "@AlexeyNis updated for better line by line handling"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T17:26:08.900",
"Id": "267661",
"ParentId": "267649",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "267661",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T09:20:57.337",
"Id": "267649",
"Score": "0",
"Tags": [
"c#",
"object-oriented",
"csv"
],
"Title": "Writing data to CSV, checking for duplicates"
}
|
267649
|
<p>If you have this inheritance:</p>
<pre><code>public class A
{
private readonly object _someParameter;
private readonly object _anotherParameter;
public A(object someParameter, object anotherParameter)
{
_someParameter = someParameter;
_anotherParameter = anotherParameter;
}
}
public class B : A
{
public B(object someParameter, object anotherParameter) : base(someParameter, anotherParameter)
{
}
}
public class C : A
{
public C(object someParameter, object anotherParameter) : base(someParameter, anotherParameter)
{
}
}
</code></pre>
<p>and you want to add another parameter to the constructor of <code>A</code>. Then you will have to pass this through <code>B</code> and <code>C</code> also.</p>
<p>To avoid changing a lot I am often using another approach where you create another class that holds all the parameters for <code>A</code> as properties:</p>
<pre><code>public class PropertiesOfA
{
public object SomeParameter { get; }
public object AnotherParameter { get; }
public PropertiesOfA(object someParameter, object anotherParameter)
{
SomeParameter = someParameter;
AnotherParameter = anotherParameter;
}
}
public class A
{
private readonly object _someParameter;
private readonly object _anotherParameter;
public A(PropertiesOfA propertiesOfA)
{
_someParameter = propertiesOfA.SomeParameter;
_anotherParameter = propertiesOfA.AnotherParameter;
}
}
public class B : A
{
public B(PropertiesOfA propertiesOfA) : base(propertiesOfA)
{
}
}
public class C : A
{
public C(PropertiesOfA propertiesOfA) : base(propertiesOfA)
{
}
}
</code></pre>
<p>This approach has the advantage that all the derived classes does not need to be updated to add another parameter for <code>A</code>. This avoids a lot of code changes, especially when using IoC containers.</p>
<p>What is this approach called and what is the class <code>PropertiesOfA</code> called?</p>
<p>It is not really a Factory nor a Facade.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T12:05:37.863",
"Id": "527800",
"Score": "3",
"body": "This type of refactoring is called \"Introduce Parameter Object\", see e.g. [Introduce Parameter Object](https://refactoring.com/catalog/introduceParameterObject.html). Ideally, the grouped parameters should be coherent enough to be meaningful without referring to the usage in the name."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T11:49:11.467",
"Id": "267651",
"Score": "1",
"Tags": [
"c#"
],
"Title": "One class that exists only to initialize instances of another class"
}
|
267651
|
<p>I have a component that I am updating from running a plain function on every render, to one that only runs when some components update:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// dummy functions to simulate calling a service asynchronously
const timeout = ms => new Promise(resolve => setTimeout(resolve, ms));
const sleep = async fn => {
await timeout(3000);
return fn();
};
// imitation of the function
const {useState, useEffect, useCallback} = React;
const CHECKOUT_COUNT_STATE = {NONE:'none', COUNTING:'counting', SUBMITTED:'submitted'};
const Example = () => {
const [count, setCount] = useState(-1); //uses a redux selector in the real code
const [countState, setCountState] = useState(CHECKOUT_COUNT_STATE.NONE); //uses a redux selector in the real code
const [checkoutComponent, setCheckoutComponent] = useState(
<span> Estimated Stock Count:
<strong data-co="stock count">Not calculated</strong>
</span>
);
useEffect(()=> {
if(countState === CHECKOUT_COUNT_STATE.SUBMITTED){
setCheckoutComponent(<strong>Stock request being submitted&hellip;</strong>)
} else {
setCheckoutComponent(
<span>Estimated Stock Count: {
countState === CHECKOUT_COUNT_STATE.COUNTING?
<strong>Calculating&hellip;</strong> :
<strong data-co="stock count">{count !== -1? count : 'Not Calculated'}</strong>
}
</span>
);
}
}, [count, countState])
// dummy code to simulate async call
const checkStock = useCallback(async () => {
await sleep(()=>{
setCount(Math.floor(Math.random() * (101)));
setCountState(CHECKOUT_COUNT_STATE.NONE);
});
});
return (
<div>
<p>Stock Counter</p>
<div>{checkoutComponent}</div>
<button onClick={()=>{
setTimeout(setCountState(CHECKOUT_COUNT_STATE.COUNTING), 0); checkStock()}
}>
Check Stock
</button>
<button onClick={() => setCountState(CHECKOUT_COUNT_STATE.SUBMITTED)}>Submit Request</button>
</div>
);
};
// Render it
ReactDOM.render(
<Example title="Example using Hooks:" />,
document.getElementById("react")
);</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.25/browser-polyfill.min.js"></script>
</head>
<body>
<div id="react"></div>
</body></code></pre>
</div>
</div>
</p>
<p>I've seen stackoverflow questions that recommend against this, but without making the jsx part of the component more complicated, with various parts being conditionally rendered I can't think of a better way to get the same behaviour.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T12:05:29.120",
"Id": "267652",
"Score": "0",
"Tags": [
"javascript",
"react.js",
"jsx",
"redux"
],
"Title": "Setting a complex component via useEffect and useState?"
}
|
267652
|
<p>I have an order model and a client model. A client has many orders, an order belongs to a single client.</p>
<p>In the client model I keep track of how much money a client paid (<code>total_generated_revenue</code>), how many orders he has cancelled (<code>orders_cancelled</code>), and how many of his orders were completed (<code>orders_got</code>).</p>
<p>In the order model I have a status attribute and a total attribute (and the <code>client_id</code> attribute, of course).</p>
<p>When status of an order changes, I change other properties of the object with respect to the exact change that happened in status. Actions on each change are different. Status can either be 0, 1, or 2, so there are 6 possible changes in status. I handle this with 7 <code>if</code> statements:</p>
<pre><code>public function updated(Order $order)
{
$unchanged_order = $order->getOriginal();
if($unchanged_order->status == $order->status)
{
// skip if status wasn't changed. I use this skip so that we don't have to check all of the following.
}
elseif($unchanged_order->status == 0 && $order->status == 1)
{
$order->client->total_generated_revenue += $order->total;
$order->client->orders_got += 1;
}
elseif($unchanged_order->status == 0 && $order->status == 2)
{
$order->client->orders_cancelled += 1;
}
elseif($unchanged_order->status == 1 && $order->status == 2)
{
$order->client->total_generated_revenue -= $order->total;
$order->client->orders_got -= 1;
$order->client->orders_cancelled += 1;
}
elseif($unchanged_order->status == 1 && $order->status == 0)
{
$order->client->total_generated_revenue -= $order->total;
$order->client->orders_got -= 1;
}
elseif($unchanged_order->status == 2 && $order->status == 1)
{
$order->client->total_generated_revenue += $order->total;
$order->client->orders_got += 1;
$order->client->orders_cancelled -= 1;
}
elseif($unchanged_order->status == 2 && $order->status == 0)
{
$order->client->orders_cancelled -= 1;
}
$order->client->save();
}
</code></pre>
<p>Is it considered a bad practice? If so, how can I refactor this code?</p>
<p>Does the name <code>$unchanged_order</code> reflect well enough that I mean the version before change? Should I rename it into <code>$order_before_change</code>?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T12:59:48.670",
"Id": "527804",
"Score": "1",
"body": "Originally posted at Stack Overflow: https://stackoverflow.com/q/69044629/2943403"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-04T05:56:48.983",
"Id": "527825",
"Score": "0",
"body": "Can you clarify what the \"magic numbers\" `0`, `1`, and `2` mean within your application?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-04T08:15:02.533",
"Id": "527828",
"Score": "0",
"body": "@mickmackusa 0 means in progress, 1 means completed, 2 means cancelled"
}
] |
[
{
"body": "<h3>Nine status combinations</h3>\n<blockquote>\n<p>Status can either be 0, 1, or 2, so there are 8 possible changes in status.</p>\n</blockquote>\n<p>There are nine (three states multiplied by three states) possible "changes" (state combinations). Although three of them are to stay the same. This is why you need seven <code>if</code> statements (and actually you don't, the last could be a simple <code>else</code>): six to cover the possible changes and one to cover the three possible ways to stay the same. If there were only two statuses, this would be four (two times two) and three (one plus two times one). If four, then sixteen (four times four) and thirteen (one plus four times three).</p>\n<p>In general if there are <span class=\"math-container\">\\$n\\$</span> states, then there will be <span class=\"math-container\">\\$n^2\\$</span> combinations and <span class=\"math-container\">\\$1 + n(n - 1) = n^2 -n + 1\\$</span> conditions. There are <span class=\"math-container\">\\$n\\$</span> combinations that stay the same. So the total number of combinations minus the number where the status stays the same plus one for all those where the status stays the same.</p>\n<h3>Naming</h3>\n<blockquote>\n<pre><code> $unchanged_order = $order->getOriginal();\n</code></pre>\n</blockquote>\n<p>I would find <code>$original_order</code> clearer.</p>\n<blockquote>\n<pre><code> // skip if status wasn't changed. I use this skip so that we don't have to check all of the following. \n</code></pre>\n</blockquote>\n<p>Rather than commenting, it would be simpler just to <code>return</code> in that case. As there is no reason to update the client if nothing has changed.</p>\n<pre><code> // Nothing changed; nothing to do. \n</code></pre>\n<p>Alternatively, this comment is shorter and better explains what's happening.</p>\n<h3>Alternative</h3>\n<pre><code> if ($original_order->state === $order->state) {\n return;\n }\n\n if ($original_order->state === 1) {\n $order->client->total_generated_revenue -= $order->total;\n $order->client->orders_got -= 1;\n } elseif ($original_order->state === 2) {\n $order->client->orders_cancelled -= 1;\n }\n\n if ($order->state === 1) {\n $order->client->total_generated_revenue += $order->total;\n $order->client->orders_got += 1;\n } elseif ($order->state === 2) {\n $order->client->orders_cancelled += 1;\n }\n</code></pre>\n<p>If you work it out, this will have all the same results but with only five comparisons rather than the seven that you used.</p>\n<p>It doesn't make much difference with two states, but you could also use two <code>switch</code> statements instead of two <code>if</code>/<code>elseif</code> structures.</p>\n<h3>Status objects</h3>\n<p>A more advanced form would be to use objects or classes as the states rather than primitive integers. Then you could replace both structures (not the first <code>if</code>) with something like</p>\n<pre><code> $original_order->status->leave($order);\n $order->status->enter($order);\n</code></pre>\n<p>Then you could make simpler methods, like</p>\n<pre><code>namespace Order\\Status;\n\nclass Cancelled implements \\Order\\Status\n{\n\n public function enter($order)\n {\n $order->client->orders_cancelled++;\n }\n</code></pre>\n<p>No <code>if</code>/<code>else</code> scaffolding.</p>\n<p>That would make it easier to add a status, as you'd just have to create one file and implement the required methods. This makes the <code>update</code> code simpler at the cost of making the status more complex.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T14:13:33.257",
"Id": "267656",
"ParentId": "267653",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T12:43:31.090",
"Id": "267653",
"Score": "2",
"Tags": [
"php",
"laravel",
"observer-pattern",
"php7"
],
"Title": "Adjusting variables on change of status attribute of my Order Laravel model on the updated event in observer"
}
|
267653
|
<p><a href="https://github.com/pillboxer/Assembler" rel="noreferrer">This</a> is the implementation of the Assembler required to parse source code written in the <a href="https://zhangruochi.com/Machine-Language/2019/09/22/#the-hack-language-specification" rel="noreferrer">Hack Machine Language</a> and output it to a 16-bit binary file.</p>
<p>After writing one go in Swift, I decided I wanted to give it a go writing it in C as a challenge to myself to become more comfortable with the language as well as taking the opportunity to write my own hash table.</p>
<p>I'd love any feedback on any aspect of the code but I'm particularly looking for areas of improvement with regards to pointers and memory management. I don't believe Valgrind is supported on M1 Mac machines, therefore the memory allocation and deallocation was written somewhat blind.</p>
<p>I'd also appreciate any pointers (no pun intended) on how I can improve adherence to C conventions.</p>
<p><strong>Assembler.c</strong></p>
<pre><code>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "error/Error.h"
#include "components/Stripper.h"
#include "components/Parser.h"
#define MAX_ASSEMBLED_SIZE 1048576
static void assemble(const char *file, char *output_name);
// Entry point for program
int main(int argc, char** argv) {
switch (argc) {
case 2:
// No file name specified - revert to "assembled.hack"
assemble(argv[1], NULL);
break;
case 3:
// Use client-specified file name
assemble(argv[1], argv[2]);
break;
default:
// ❌
exit_with_error(INCORRECT_ARGUMENT_COUNT);
}
return 0;
}
// Assembles a file into binary code
static void assemble(const char *file_name, char *output_name) {
long size_in_bytes;
char* file_to_assemble;
printf("Starting assembly of file %s\n", file_name);
// Check if the file exists
FILE *file = fopen(file_name, "r");
if (file == NULL) {
exit_with_error(FILE_NOT_FOUND);
}
else {
// Create a HashMap to store variables and label definitions
HashMap* hash_map = hash_map_create();
// Retrieve the size of the file (max 500k)
fseek(file, 0, SEEK_END);
size_in_bytes = ftell(file);
if (size_in_bytes > MAX_ASSEMBLED_SIZE / 2) {
exit_with_error(FILE_TOO_LARGE);
}
fseek(file, 0, SEEK_SET);
file_to_assemble = malloc(size_in_bytes + 1);
if (file_to_assemble) {
// Read the contents of the file into the buffer
fread(file_to_assemble, 1, size_in_bytes, file);
char no_comments[size_in_bytes + 1];
char no_spaces[size_in_bytes + 1];
char no_labels[size_in_bytes + 1];
char parsed[MAX_ASSEMBLED_SIZE + 1];
// Remove comments and blank spaces. Save and remove labels, save variables
strip_comments(no_comments, file_to_assemble);
strip_spaces(no_spaces, no_comments);
strip_labels(no_labels, no_spaces, hash_map);
save_variables(no_labels, hash_map);
// Translate the remaining assembly code to binary
parse(parsed, no_labels, hash_map);
char output_file_name[256];
// If the client chose a custom output name
if (output_name != NULL) {
strcpy(output_file_name, output_name);
}
else {
strcpy(output_file_name, "assembled.hack");
}
// Write the file
FILE *output = fopen(output_file_name, "w");
fwrite(parsed, 1, strlen(parsed), output);
fclose(file);
hash_map_free(hash_map);
printf("Assembly complete");
}
else {
// Could not open file. Bail
exit_with_error(FILE_READ_ERROR);
}
}
}
</code></pre>
<p><strong>Stripper.c</strong></p>
<pre><code>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
#include "HashMap.h"
#include "Parser.h"
#define SCREEN_ADDRESS 16384
#define KBD_ADDRESS 24576
#define SP_ADDRESS 0
#define LCL_ADDRESS 1
#define ARG_ADDRESS 2
#define THIS_ADDRESS 3
#define THAT_ADDRESS 4
// Removes extraneous white space and blank lines
void strip_spaces (char* dst, const char* src) {
bool have_reached_printable_char = false;
int count = 0;
int length = strlen(src);
while(*src != '\0') {
if (count == length - 1 && *src == '\n')
break;
have_reached_printable_char = have_reached_printable_char ? true : isprint(*src);
if(have_reached_printable_char && (*src == '\n' || !isspace(*src))) {
*dst = *src; // then copy
dst++;
}
count++;
src++;
}
*dst = '\0';
}
// Remove comments (like this!) from file
void strip_comments(char* dst, const char* src) {
bool copy = true;
for (int i = 0; i < strlen(src); i++) {
if (src[i] == '\n')
copy = true;
if (src[i] == '/' && src[i+1] == '/')
copy = false;
if (copy) {
*dst = src[i];
dst++;
}
}
*dst = '\0';
}
// Map particular variables to corresponding address
static void map_reserved_variables(HashMap* hash_map) {
hash_map_put(hash_map, "screen", SCREEN_ADDRESS);
hash_map_put(hash_map, "kbd", KBD_ADDRESS);
hash_map_put(hash_map, "sp", SP_ADDRESS);
hash_map_put(hash_map, "lcl", LCL_ADDRESS);
hash_map_put(hash_map, "arg", ARG_ADDRESS);
hash_map_put(hash_map, "this", THIS_ADDRESS);
hash_map_put(hash_map, "that", THAT_ADDRESS);
for (int i = 0; i < 16; i++) {
int length = i < 10 ? 2 : 3;
char reg[length + 1];
reg[0] = 'r';
sprintf(reg + 1, "%d", i);
hash_map_put(hash_map, reg, i);
}
}
// Remove label definitions and replace them with corresponding line number of
// logic following the definition
void strip_labels(char* dst, const char* src, HashMap* hash_map) {
map_reserved_variables(hash_map);
int current_command = 0;
bool save_command = false;
bool new_command = true;
bool copy = true;
char current_label[256];
int current_label_index = 0;
char last_copied;
while(*src != '\0') {
if (*src == '\n') {
new_command = true;
if (last_copied == '\n') {
src++;
}
current_command++;
copy = true;
}
if (*src == ')' && save_command) {
save_command = false;
current_label[current_label_index] = '\0';
// Move backwards to go back to the command we were dealing with
current_command--;
for (int i = 0; i <= strlen(current_label); i++) {
char lowered = tolower(current_label[i]);
current_label[i] = lowered;
}
// Now move forward one line and save whatever command number that is
hash_map_put(hash_map, current_label, current_command+1);
current_label_index = 0;
}
if (save_command) {
current_label[current_label_index++] = *src;
}
if (new_command && *src == '(') {
save_command = true;
copy = false;
}
if (copy) {
*dst = *src;
dst++;
last_copied = *src;
}
src++;
}
*dst = '\0';
}
// Save any user declared variables
void save_variables(char* dst, HashMap* hash_map) {
bool is_a_variable_declaration = false;
char current_variable[256];
int current_variable_index = 0;
int current_variable_address = 16;
while(*dst != '\0') {
if (*dst == '\n') {
if (is_a_variable_declaration) {
is_a_variable_declaration = false;
current_variable[current_variable_index] = '\0';
current_variable_index = 0;
if (!is_integral_string(current_variable)) {
if (hash_map_contains(hash_map, current_variable)) {
// It's a label declaration that we've already saved in the method above
continue;
}
else {
hash_map_put(hash_map, current_variable, current_variable_address++);
}
}
}
}
if (is_a_variable_declaration) {
current_variable[current_variable_index++] = tolower(*dst);
}
if (*dst == '@') {
char next = tolower(*(++dst));
if (next != 'r' && next != '0') {
is_a_variable_declaration = true;
}
dst--;
}
dst++;
}
}
</code></pre>
<p><strong>Parser.c</strong></p>
<pre><code>#include <stdbool.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "HashMap.h"
#include "Parser.h"
#include "../error/Error.h"
#define VALID_DESTINATION_COUNT 7
#define VALID_COMPUTATION_COUNT 28
#define VALID_JUMP_COUNT 7
#define WORD_LENGTH 16
#define A_START 0
#define C_A_OR_M_START 3
#define C_A_OR_M_BIT_LENGTH 1
#define C_DEFAULTS_START 0
#define C_DEFAULTS_BIT_LENGTH 3
#define C_DEFAULTS_ADDRESS 7
#define C_COMP_START 4
#define C_COMP_BIT_LENGTH 6
#define C_JUMP_START 13
#define C_JUMP_BIT_LENGTH 3
#define C_DEST_BIT_LENGTH 3
#define C_DEST_START 10
// Declarations
static bool is_a_command(const char* str);
static int jump_address(const char* str);
static int destination_address(const char* str);
static int get_computation_address(const char* cmd);
static int get_jump_address(const char* cmd, int jump_operation_position);
static int get_destination_address(const char* cmd, int assignment_operation_position);
static void parse_c_command(char* dst, const char* cmd);
static void parse_command(char* dst, const char *cmd, HashMap* hash_map);
static void parse_a_command(char* dst, const char* cmd, HashMap* hash_map);
static void to_bin(char* cmd, int address, int number_of_places, int starting_position);
static void get_positions(const char* cmd, int* assignment, int* computation, int *termination, int* jump);
// *********** CONSTANTS ************** //
// Allowed destinations in C instruction
const char* valid_destinations[VALID_DESTINATION_COUNT] = { "M", "D", "MD", "A", "AM", "AD", "AMD" };
// Allowed computations in C instruction
const char* valid_computations[VALID_COMPUTATION_COUNT] = { "0", "1", "-1", "D", "A", "!D", "!A", "-D",
"-A", "D+1", "A+1", "D-1", "A-1", "D+A", "D-A",
"A-D", "D&A", "D|A", "M", "!M", "-M", "M+1",
"M-1", "D+M", "D-M", "M-D", "D&M", "D|M" };
// Denary representation of a valid computation.
// For example the instruction D|M (see above) corresponds to 21 -> (101001)
const int valid_computation_integers[VALID_COMPUTATION_COUNT] = { 42, 63, 58, 12, 48, 13, 49, 15,
51, 31, 55, 14, 50, 2, 19,
7, 0, 21, 48, 49, 51,
55, 50, 2, 19, 7, 0, 21 };
// Allowed jump commands in C instruction
const char* valid_jumps[VALID_JUMP_COUNT] = { "JGT", "JEQ", "JGE", "JLT", "JNE", "JLE", "JMP" };
// *********** PARSING ************** //
// Parse a source asm file that has been stripped of whitespace and comments
void parse(char* dst, char* src, HashMap* hash_map) {
char current_label[256];
int current_label_position = 0;
int dest_position = 0;
for (int i = 0; i <= strlen(src); i++) {
if (src[i] == '\n' || src[i] == '\0') {
// We've either reached a line break or EOF
current_label[current_label_position] = '\0';
char parsed[WORD_LENGTH + 1];
to_bin(parsed, 0, WORD_LENGTH, 0);
parsed[WORD_LENGTH] = '\0';
// Parse the current command
parse_command(parsed, current_label, hash_map);
for (int j = 0; j < strlen(parsed); j++) {
// Add the newly parsed command to the output file
dst[dest_position++] = parsed[j];
}
// Reset label posiion and add \n or \0 to output
current_label_position = 0;
dst[dest_position++] = src[i];
continue;
}
current_label[current_label_position++] = src[i];
}
// Done, make sure to end with null terminator
dst[dest_position] = '\0';
}
static void parse_command(char* dst, const char *cmd, HashMap* hash_map) {
// Can either be A command ("@command") or C command ("D=D+1;JGE")
if (is_a_command(cmd)) {
parse_a_command(dst, cmd, hash_map);
}
else {
parse_c_command(dst, cmd);
}
}
static void parse_c_command(char* dst, const char* cmd) {
int assignment_operation_position = 0;
int computation_operation_position = 0;
int jump_operation_position = 0;
int computation_termination_position = 0;
// Fill in parts of parsed command that are common to all C instructions
to_bin(dst, C_DEFAULTS_ADDRESS, C_DEFAULTS_BIT_LENGTH, C_DEFAULTS_START);
get_positions(cmd, &assignment_operation_position, &computation_operation_position, &computation_termination_position, &jump_operation_position);
// Split the command into destination (if applicable), computation and jump (if applicable)
if (assignment_operation_position != 0) {
int address = get_destination_address(cmd, assignment_operation_position);
if (address == -1) {
exit_with_error(MALFORMED_DESTINATION);
}
else {
to_bin(dst, address, C_DEST_BIT_LENGTH, C_DEST_START);
}
}
int computation_string_length = computation_termination_position - computation_operation_position;
char computation_string[computation_string_length + 1];
strncpy(computation_string, cmd+computation_operation_position, computation_string_length);
computation_string[computation_string_length] = '\0';
int computation_address = get_computation_address(computation_string);
if (computation_address == -1) {
exit_with_error(MALFORMED_COMPUTATION);
}
else {
to_bin(dst, computation_address, C_COMP_BIT_LENGTH, C_COMP_START);
for (int i = computation_operation_position; i < computation_termination_position; i++) {
if (tolower(cmd[i]) == 'm') {
to_bin(dst, 1, C_A_OR_M_BIT_LENGTH, C_A_OR_M_START);
}
}
}
if (jump_operation_position != 0) {
int address = get_jump_address(cmd, jump_operation_position);
if (address == -1) {
exit_with_error(MALFORMED_JUMP);
}
else {
to_bin(dst, address, C_JUMP_BIT_LENGTH, C_JUMP_START);
}
}
}
static void parse_a_command(char* dst, const char* cmd, HashMap* hash_map) {
size_t cmd_length = strlen(cmd);
char lowered[cmd_length];
int index = 0;
// Disregard '@' by starting at index 1
for (size_t i = 1; i <= cmd_length; i++) {
lowered[index++] = tolower(cmd[i]);
}
if (!is_integral_string(lowered)) {
// It's a user-declared variable
int value = hash_map_get(hash_map, lowered);
to_bin(dst, value, WORD_LENGTH, A_START);
}
else {
// It's a direct address (eg '@42')
char address_string[cmd_length];
strncpy(address_string, lowered, cmd_length);
int address = atoi(address_string);
to_bin(dst, address, WORD_LENGTH, A_START);
}
}
// *********** ADDRESSES ************** //
// Retreive generic address from array
static int get_address(const char* str, const char** argv, unsigned int count) {
for (int i = 0; i < count; i++) {
if (strcmp(str, argv[i]) == 0) {
return i + 1;
}
}
return -1;
}
// Retrieve destination address from C instruction
static int get_destination_address(const char* cmd, int assignment_operation_position) {
char destination[assignment_operation_position + 1];
strncpy(destination, cmd, assignment_operation_position);
destination[assignment_operation_position] = '\0';
return destination_address(destination);
}
static int destination_address(const char* str) {
return get_address(str, valid_destinations, VALID_DESTINATION_COUNT);
}
// Retrieve computation address from C instruction
static int get_computation_address(const char* cmd) {
for (int i = 0; i < VALID_COMPUTATION_COUNT; i++) {
if (strcmp(valid_computations[i], cmd) == 0) {
return valid_computation_integers[i];
}
}
return -1;
}
// Retrieve jump address from C instruction
static int get_jump_address(const char* cmd, int jump_operation_position) {
int jump_operation_length = strlen(cmd) - jump_operation_position;
char jump_operation[jump_operation_length + 1];
strncpy(jump_operation, cmd+jump_operation_position, jump_operation_length);
jump_operation[jump_operation_length] = '\0';
return jump_address(jump_operation);
}
static int jump_address(const char* str) {
return get_address(str, valid_jumps, VALID_JUMP_COUNT);
}
// *********** HELPER ************** //
static bool is_a_command(const char* str) {
return str[0] == '@' && strlen(str) > 1;
}
// Is the command pure integers?
bool is_integral_string(char *str) {
size_t length = strlen(str);
for (int i = 0; i < length; i++) {
if (!isdigit(str[i])) {
return false;
}
}
return true;
}
// Retrieve positions of assignment, computation,
// and jump instructions as well as the point of termination of a computation
static void get_positions(const char* cmd, int* assignment, int* computation, int *termination, int* jump) {
size_t length = strlen(cmd);
for (int i = 0; i < length; i++) {
if (cmd[i] == '=') {
*assignment = i;
*computation = i+1;
}
if (cmd[i] == ';') {
*jump = i+1;
*termination = i;
}
}
if (*termination == 0) {
*termination = length;
}
}
// Convert an address to binary padding with number of places,
// starting (0 being the 'end' of the string) at starting_position
static void to_bin(char* cmd, int address, int number_of_places, int starting_position) {
int quo = address;
int index = number_of_places + starting_position - 1;
int rem;
for (int i = 0; i < number_of_places; i++) {
rem = quo % 2;
cmd[index--] = rem == 1 ? '1' : '0';
quo = quo / 2;
}
}
</code></pre>
<p><strong>HashMap.c</strong></p>
<pre><code>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "HashMap.h"
// Hashing function, courtesy of
// http://www.cse.yorku.ca/~oz/hash.html
static int hashed(char* arg) {
unsigned long hash = 5381;
int c;
while ((c = *arg++))
hash = ((hash << 5) + hash) + c;
return hash % NUM_BUCKETS;
}
// Create a HashMap (caller to free)
HashMap* hash_map_create() {
HashMap *hash_map = malloc(sizeof(HashMap));
for (int i = 0; i < NUM_BUCKETS; i++)
hash_map->buckets[i] = NULL;
return hash_map;
}
// Insert into HashMap (assumes non-negative value)
void hash_map_put(HashMap* hash_map, char* key, int value) {
int hashed_key = hashed(key);
int result = hash_map_get(hash_map, key);
if (result != -1) {
// Overwrite old value
Node *current = hash_map->buckets[hashed_key];
while (current->key != key) {
current = current->next;
}
current->value = value;
}
else {
if (hash_map->buckets[hashed_key] == NULL) {
// Insert at first node in bucket
hash_map->buckets[hashed_key] = malloc(sizeof(Node));
hash_map->buckets[hashed_key]->key = malloc(sizeof(char) * (strlen(key) + 1));
strcpy(hash_map->buckets[hashed_key]->key, key);
hash_map->buckets[hashed_key]->value = value;
hash_map->buckets[hashed_key]->next = NULL;
}
else {
// Collision, traverse to end of linked list
Node *current = hash_map->buckets[hashed_key];
Node *new = malloc(sizeof(Node));
new->key = malloc(sizeof(char) * (strlen(key) + 1));
strcpy(new->key, key);
new->value = value;
new->next = NULL;
while (current->next != NULL) {
current = current->next;
}
current->next = new;
}
}
}
bool hash_map_contains(HashMap* hash_map, char* key) {
return hash_map_get(hash_map, key) != -1;
}
// Retrieve value for key from HashMap
int hash_map_get(HashMap* hash_map, char* key) {
int hashed_key = hashed(key);
Node *current = hash_map->buckets[hashed_key];
int returned = -1;
while (current != NULL) {
if (strcmp(current->key, key) == 0) {
returned = current->value;
break;
}
current = current->next;
}
return returned;
}
// Remove value for key in HashMap
void hash_map_remove(HashMap* hash_map, char* key) {
int hashed_key = hashed(key);
if (hash_map_get(hash_map, key) != -1) {
Node *current = hash_map->buckets[hashed_key];
if (current->key == key) {
// Remove from head node
Node *new_current = current->next;
current = NULL;
hash_map->buckets[hashed_key] = new_current;
}
else {
// Traverse and remove when found
while (current->next->key != key) {
current = current->next;
}
Node *old_next = current->next;
Node *new_next = current->next->next;
current->next = new_next;
old_next = NULL;
}
}
}
// Free HashMap
void hash_map_free(HashMap* hash_map) {
free(hash_map);
}
</code></pre>
<p><strong>Error.c</strong></p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include "Error.h"
void error_string_for_code(int code, char **star);
void exit_with_error(int code) {
char *str = "";
error_string_for_code(code, &str);
printf("Exiting with error: '%s'\n", str);
exit(code);
}
void error_string_for_code(int code, char **str) {
switch (code) {
case INCORRECT_ARGUMENT_COUNT:
*str = "Incorrect argument count";
break;
case FILE_NOT_FOUND:
*str = "The file doesn't exist";
break;
case FILE_READ_ERROR:
*str = "Could not read file";
break;
case NULL_POINTER:
*str = "Null pointer found";
break;
case UNKNOWN_COMMAND:
*str = "Unrecognized command";
break;
case MALFORMED_DESTINATION:
*str = "Invalid destination received";
break;
case MALFORMED_COMPUTATION:
*str = "Received a missing computation";
break;
case MALFORMED_JUMP:
*str = "Invalid jump received";
break;
case FILE_TOO_LARGE:
*str = "File too large, please ensure it is less than 500kb";
break;
default:
*str = "Unknown error.";
break;
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-05T13:55:33.513",
"Id": "527898",
"Score": "0",
"body": "Thanks to both reviewers for their thorough answers. Working through the recommended changes [here](https://github.com/pillboxer/Assembler/issues/17)"
}
] |
[
{
"body": "<h1>Alternatives to Valgrind for memory allocation checking</h1>\n<blockquote>\n<p>I don't believe Valgrind is supported on M1 Mac machines, therefore the memory allocation and deallocation was written somewhat blind.</p>\n</blockquote>\n<p>Luckily there are other ways to check whether you have memory leaks. In particular, Clang includes support for the <a href=\"https://clang.llvm.org/docs/AddressSanitizer.html\" rel=\"nofollow noreferrer\">AddressSanitizier</a>. Compile and link your program with <code>fsanitize=address</code>, and then it will print out any leaks and other potential issues at runtime.</p>\n<h1>Avoid unnecessary forward declarations</h1>\n<p>You can avoid forward declaration by changing the order in which functions are defined in your source files. This way, you don't have to repeat yourself, and if you change the function name or parameters, you only have to do it in one place.</p>\n<h1>Reporting errors</h1>\n<p>It's nice to have a single function that prints an error and exits the program with a non-zero exit code. There are a few problems with your implementation though.</p>\n<p>First, ensure you write error messages to <code>stderr</code>. This ensures they don't get mingled with regular output written to <code>stdout</code>, which is especially important if output is redirected. Furthermore, I recommend you use <a href=\"https://en.cppreference.com/w/c/program/EXIT_status\" rel=\"nofollow noreferrer\"><code>EXIT_FAILURE</code></a> as the exit code for all errors. Other values are non-standard.</p>\n<p>Also, having to maintain a list of enums and their corresponding error messages is a bit of work, and it's not very flexible. I recommend you either use the BSD function <a href=\"https://linux.die.net/man/3/err\" rel=\"nofollow noreferrer\"><code>err()</code></a> or reimplement it yourself. This way, you can report errors like so:</p>\n<pre><code>if (size_in_bytes > MAX_ASSEMBLED_SIZE / 2) {\n err(EXIT_FAILURE, "File too large, make sure it is less than %d bytes", MAX_ASSEMBLED_SIZE / 2);\n}\n</code></pre>\n<h1>Consider allowing input from <code>stdin</code> and output to <code>stdout</code></h1>\n<p>Instead of always reading from a file and writing the result to another file, consider allowing <code>stdin</code> and <code>stdout</code> to be used. This allows your assembler to be used in more complicated command lines, where for example the assembly is generated by one program and can then be piped directly into your assembler. This is quite normal on any UNIX-like operating system, but even Windows supports input and output redirection like that.</p>\n<p>In particular, if the program is called with zero arguments, read from <code>stdin</code> and write to <code>stdout</code>. If it is called with one argument, read from the provided filename and write to <code>stdout</code>.</p>\n<p>Also ensure you don't print any diagnostics to <code>stdout</code> where it could get mingled with the assembly output. Use <code>stderr</code> for any progress updates, or consider just not printing any information at all if things go well.</p>\n<h1>Unnecessary file size limitation?</h1>\n<p>I see the Hack machine language supports 32 bit pointers so it should be able to address up to 4 GB. I think the reason you limit the maximum assembled size to 1 megabyte is because you are allocating potentially very large arrays on the stack in <code>assemble()</code>. Use <code>malloc()</code> for to allocate those arrays instead, that way you don't exhaust the limited amount of stack space.</p>\n<h1>Give correct error messages</h1>\n<p>If <code>malloc()</code> fails, your program currently prints the error message "Could not read file", which is misleading. Make sure error messages clearly describe the actual error that occurred.</p>\n<h1>Avoid arbitrary limits for filenames</h1>\n<p>You declare the string <code>output_file_name</code> as an array of 256 <code>char</code>s. But filenames can be longer than that. Don't assume any limit. Either use <a href=\"https://man7.org/linux/man-pages/man3/strdup.3.html\" rel=\"nofollow noreferrer\"><code>strdup()</code></a> (which unfortunately is not standard C <em>yet</em>), or <code>malloc(strlen(...) + 1)</code>, or even better avoid having to allocate anything at all:</p>\n<pre><code>FILE *output = fopen(output_name ? output_name : "assembled.hack", "w");\n</code></pre>\n<h1>Missing error checking</h1>\n<p>I/O errors can happen at any time, not just when opening a file. Check the return value of <code>fread()</code>, <code>fwrite()</code> and <code>fclose()</code>, and make sure you report an error to <code>stderr</code> and exit the program with <code>EXIT_FAILURE</code> in case there was an error.</p>\n<p>Furthermore, there are several calls to <code>malloc()</code> in the code where the return value is not checked.</p>\n<h1>Reducing the number of passes over the input</h1>\n<p>You are processing the input several times, each time doing one thing, like removing comments. This takes time, and you are also using a lot of temporary storage space for each pass. Ideally, you would parse everything in a single pass.</p>\n<p>Parsing the input in a single pass can be done by changing the bookkeeping of labels. Parse each line, strip spaces and comments. If anything is remaining, check if it's a variable or label. If it's a reference to a label you have seen defined before, you can just immediately substitute it by its line number. Otherwise, you have to remember that you have to insert the line number here when you reach the line where the label is defined. When you encounter a label definition, check if you have to fix up any line numbers in earlier output.</p>\n<h1>Naming things</h1>\n<p>"Stripper.c" might not be the best choice of a file name, especially if it does more than just stripping things: it also deals with variables.</p>\n<p>I think you did a great job with the function and variables names. Some minor issues:</p>\n<ul>\n<li><code>dst</code> in <code>save_variables()</code> should probably be renamed to <code>src</code>, and be made <code>const</code> while you are at it.</li>\n<li>In the forward declaration of <code>error_string_for_code()</code>, <code>star</code> should be <code>str</code>.</li>\n</ul>\n<h1>Correct use of <code>tolower()</code> and <code>isdigit()</code></h1>\n<p>The functions from <code><ctype.h></code> expect an <code>int</code> as the argument, not a <code>char</code>. Also, they expect the value to be greater than or equal to zero for all valid characters. The correct way to use them is to cast the <code>char</code> to <code>unsigned char</code> before using it as an argument, like so:</p>\n<pre><code>if (!isdigit((unsigned char)str[i])) {\n return false;\n}\n</code></pre>\n<h1>Prefer <code>strtol()</code> over <code>atoi()</code></h1>\n<p>Use <a href=\"https://en.cppreference.com/w/c/string/byte/strtol\" rel=\"nofollow noreferrer\"><code>strtol()</code></a> instead of <code>atoi()</code>, and use the second argument to check that the whole number was read correctly.</p>\n<h1>Better way to pass sizes to <code>malloc()</code></h1>\n<p>Instead of:</p>\n<pre><code>Node *new = malloc(sizeof(Node));\n</code></pre>\n<p>It is generally preferred to write:</p>\n<pre><code>Node *new = malloc(sizeof *new);\n</code></pre>\n<p>This avoids having to repeat the type twice. Furthermore, <code>sizeof(char)</code> is guaranteed to be 1 by the C standard, so instead of:</p>\n<pre><code>new->key = malloc(sizeof(char) * (strlen(key) + 1));\n</code></pre>\n<p>You can just write:</p>\n<pre><code>new->key = malloc(strlen(key) + 1);\n</code></pre>\n<h1>Memory leak when freeing the hash map</h1>\n<p><code>hash_map_free()</code> only frees the array of pointers to buckets, not the contents of the buckets themselves.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-05T13:58:37.353",
"Id": "527899",
"Score": "0",
"body": "Thanks for this, G. Slowly implementing these changes. Appreciate the heads up about `fsanitize=address` - I do indeed have memory issues!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T20:01:21.667",
"Id": "267664",
"ParentId": "267654",
"Score": "4"
}
},
{
"body": "<p>Here are some things that may help you improve your program.</p>\n<h2>Fix the bug</h2>\n<p>In <code>assemble()</code> the file is read with <code>fread</code> which is appropriate, but later when the buffer is being processed to strip comments, the code makes the invalid assumption that the buffer is terminated with a <code>NUL</code> character. To fix that, explicitly terminate the string:</p>\n<pre><code>// Read the contents of the file into the buffer\nfread(file_to_assemble, 1, size_in_bytes, file);\n// assure the buffer is terminated\nfile_to_assemble[size_in_bytes] = '\\0';\n</code></pre>\n<h2>Don't leak memory</h2>\n<p>The <code>hash_map_free()</code> function frees the overall <code>HashMap</code> but fails to free the memory of each of the <code>Node</code>'s <code>key</code> and <code>*next</code> values. Likewise within <code>hash_map_remove</code>, the removed node pointer is set to <code>NULL</code> which is fine, but the memory is not freed which is not fine. Here's one way to rewrite <code>hash_map_free()</code>:</p>\n<pre><code>void hash_map_free(HashMap* hash_map) {\n if (hash_map) {\n for (int i = 0; i < NUM_BUCKETS; ++i) {\n for (Node* curr = hash_map->buckets[i]; curr; ) {\n Node* victim = curr;\n curr = curr->next;\n free(victim->key);\n free(victim);\n }\n }\n }\n free(hash_map);\n}\n</code></pre>\n<p>Similarly, you'll have to make the corresponding changes in <code>hash_map_remove</code>.</p>\n<h2>Understand C idiom</h2>\n<p>The <code>strip_comments</code> function works, but it uses an indexed variable <code>s[i]</code> instead of a plain pointer. Here's an alternative version that skips the call to <code>strlen</code> and mostly avoids the use of indexing.</p>\n<pre><code>void strip_comments(char* dst, const char* src) {\n for (bool copy = true; *src; ++src) {\n if (*src == '\\n') {\n copy = true;\n }\n else if (*src == '/' && src[1] == '/') {\n copy = false;\n }\n if (copy) {\n *dst++ = *src;\n }\n }\n *dst = '\\0';\n}\n</code></pre>\n<p>Other enhancements are to use <code>else</code> since both statements are mutually exclusive and to add <code>{}</code> to each clause for safety. Also, this code uses another very common idiom: <code>*dst++ = *src;</code>.</p>\n<h2>Use consistent formatting</h2>\n<p>In the <code>Stripper.c</code> file, the formatting of the three functions is slightly different. It helps the reader if the formatting is consistent.</p>\n<h2>Simplify expressions</h2>\n<p>The <code>strip_spaces</code> function currently has this line:</p>\n<pre><code>have_reached_printable_char = have_reached_printable_char ? true : isprint(*src);\n</code></pre>\n<p>It looks a bit peculiar to me and took me a moment to see what it was doing. I think a clearer way of doing this would be this:</p>\n<pre><code>have_reached_printable_char |= isprint(*src);\n</code></pre>\n<h2>Use <code>const</code> where practical</h2>\n<p>Many of the functions correctly use <code>const</code> as part of their signatures, which is good. More can be done, however, such as declaring <code>length</code> within <code>strip_spaces()</code> as <code>const</code>.</p>\n<h2>Prefer <code>for</code> to <code>while</code> where practical</h2>\n<p>The <code>strip_spaces</code> function has a <code>while</code> loop that I think would be better written as a <code>for</code> loop. The <code>for</code> loop has the advantages that the scope of <code>count</code> is reduced to only within the loop (scope reduction is good because it both helps the compiler allocate registers and makes it easier for humans to understand) and it makes clear which values are unconditionally updated each loop. In this case, I'd write it like this:</p>\n<pre><code>for (int count = 0; *src != '\\0'; ++count, ++src) {\n</code></pre>\n<h2>Simplify your functions</h2>\n<p>The <code>for</code> loop within <code>map_reserved_variables</code> is a bit more complex than it needs to be. First, we don't really care how large the buffer is as long as it has the capacity to store the maximum size register name. Second, the name always starts with <code>r</code>. We can simplify by writing the loop like this:</p>\n<pre><code>char reg_name[5];\nfor (int i = 0; i < 16; ++i) {\n snprintf(reg_name, 5, "r%d", i);\n hash_map_put(hash_map, reg_name, i);\n}\n</code></pre>\n<p>Note also the use of <code>snprintf</code> for additional safety.</p>\n<h2>Reduce the use of "magic numbers"</h2>\n<p>There are a few numbers in the code, such as <code>16</code> and <code>256</code> that have a specific meaning in their particular context. By using named constants such as <code>NUM_REGISTERS</code> or <code>MAX_LABEL_SIZE</code>, the program becomes easier to read and maintain. Also, it's generally better to use <code>const int</code> than <code>#define</code> for numeric values.</p>\n<h2>Use <code>struct</code> to associate related items</h2>\n<p>During parsing, the <code>get_computation_address()</code> function is called. It's currently like this:</p>\n<pre><code>static int get_computation_address(const char* cmd) {\n for (int i = 0; i < VALID_COMPUTATION_COUNT; i++) {\n if (strcmp(valid_computations[i], cmd) == 0) {\n return valid_computation_integers[i];\n }\n }\n return -1;\n}\n</code></pre>\n<p>It relies on three separate things, <code>VALID_COMPUTATION_COUNT</code> which is a constant, <code>valid_computations</code> which is an array of command strings, and <code>valid_computation_integers</code> which is an array of numbers associated with each command. Instead of three separate items with only a loose binding among them, I'd suggest using a <code>struct</code>:</p>\n<pre><code>const struct computation {\n const char *text;\n int value;\n} Computations[] = {\n { "0", 42 }, { "1", 63 }, { "-1", 58 }, { "D", 12 }, { "A", 48 }, \n { "!D", 13 }, { "!A", 49 }, { "-D", 15 }, { "-A", 51 }, {"D+1", 31 }, \n {"A+1", 55 }, {"D-1", 14 }, {"A-1", 50 }, {"D+A", 2 }, {"D-A", 19 },\n { "A-D", 7 }, {"D&A", 0 }, {"D|A", 21 }, {"M", 48 }, {"!M", 49 }, \n {"-M", 51 }, {"M+1", 55 }, { "M-1", 50 }, {"D+M", 2 }, {"D-M", 19 }, \n {"M-D", 7 }, {"D&M", 0 }, {"D|M", 21 },\n { NULL, -1 } // end of list\n};\n</code></pre>\n<p>The corresponding code is also simple:</p>\n<pre><code>static int get_computation_address(const char* cmd) {\n const struct computation* comp = Computations;\n for ( ; comp->text && strcmp(cmd, comp->text) != 0; ++comp) {\n }\n return comp->value;\n}\n</code></pre>\n<p>Now it's easy for a human to see the associated mnemonics and values and no explicit count is needed because a sentinel value is used instead.</p>\n<h2>Simplify instruction creation</h2>\n<p>Right now there are a lot of calls to <code>to_bin</code> which does all sorts of work getting values into the right location for the final instruction. Instead, why not just compute in binary and use a bitwise-or operation to assemble the instruction? An example, if we have the values for <code>a</code>, <code>comp</code>, <code>dest</code> and <code>jmp</code>, we can easily construct a C-instruction:</p>\n<pre><code>int inst = 0xE000 | (a << 12) | (comp << 6) | (dest << 3) | jmp;\n</code></pre>\n<p>Even better, since the values of <code>a</code> and <code>comp</code> are implicit from the mnemonic, we could use the table structure above to contain both and put them into the table as the value we'll need <em>already shifted into place</em>. So the table would be:</p>\n<pre><code>const struct computation {\n const char *text;\n int value;\n} Computations[] = {\n { "0", 42<<6 }, { "1", 63<<6 }, { "-1", 58<<6 }, { "D", 12<<6 }, { "A", 48<<6 }, \n { "!D", 13<<6 }, { "!A", 49<<6 }, { "-D", 15<<6 }, { "-A", 51<<6 }, {"D+1", 31<<6 }, \n {"A+1", 55<<6 }, {"D-1", 14<<6 }, {"A-1", 50<<6 }, {"D+A", 2<<6 }, {"D-A", 19<<6 },\n { "A-D", 7<<6 }, {"D&A", 0<<6 }, {"D|A", (64|21)<<6 }, {"M", (64|48)<<6 }, {"!M", (64|49)<<6 }, \n {"-M", (64|51)<<6 }, {"M+1", (64|55)<<6 }, { "M-1", (64|50)<<6 }, {"D+M", (64|2)<<6 }, {"D-M", (64|19)<<6 }, \n {"M-D", (64|7)<<6 }, {"D&M", (64|0)<<6 }, {"D|M", (64|21)<<6 },\n { NULL, -1 } // end of list\n};\n</code></pre>\n<p>Now we can fetch the value directly from here, use <code>|</code> to compose the instruction in binary and convert to an ASCII string once.</p>\n<h2>Simplify conversion to ASCII</h2>\n<p>A small, simple way to convert a 16-bit <code>int</code> into binary is like this:</p>\n<pre><code>for (int mask = 0x8000; mask; mask >>= 1) {\n *dst++ = (mask & instruction) ? '1' : '0';\n}\n</code></pre>\n<h2>Avoid copying strings</h2>\n<p>In the <code>parse</code> command, instead of parsing to a temporary string and then copying from there to the destination, why not just put it directly in place? Here's a rewrite that shows how this might look:</p>\n<pre><code>void parse(char* dst, const char* src, HashMap* hash_map) {\n static char label_buffer[256];\n char *current_label = label_buffer;\n\n for (bool working = true ; working; ++src) {\n if (*src == '\\n' || *src == '\\0') {\n // We've either reached a line break or EOF\n *current_label = '\\0';\n // Parse the current command\n parse_command(dst, label_buffer, hash_map);\n dst += WORD_LENGTH;\n // Reset label posiion and add \\n or \\0 to output\n current_label = label_buffer;\n *dst++ = *src;\n working = *src;\n } else {\n *current_label++ = *src;\n }\n }\n // Done, make sure to end with null terminator\n *dst = '\\0';\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-05T13:32:41.563",
"Id": "527893",
"Score": "0",
"body": "Thanks you so much. I'm so grateful for this. I'm in the process of making the changes. My test suite is failing when making your last change (**Avoid copying strings**) - the `current_label` appears to have garbage values in it, although `label_buffer` is correct. Any idea why that would be?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-05T13:39:33.087",
"Id": "527894",
"Score": "0",
"body": "Make sure you are passing `label_buffer` to `parse_command` and not `current_label`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-05T13:47:02.983",
"Id": "527896",
"Score": "0",
"body": "I am; did a direct copy-paste... I'll keep investigating!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T21:38:50.970",
"Id": "267667",
"ParentId": "267654",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T13:35:39.017",
"Id": "267654",
"Score": "7",
"Tags": [
"c",
"memory-management",
"pointers",
"assembly"
],
"Title": "Hack machine language assembler as required for project 6 of Nand2Tetris"
}
|
267654
|
<p>One year ago I learned some Python 3 in Highschool, but I haven't really programmed anything since then. I decided to start a new project to try and practice a bit before entering the first year of an IT degree. I tried to create my own cloud storage system in a console application using the Socket library, i.e. a program which can send file to a server and retreive them later. I wrote both the client and the server script. It was intended to be only an exercise at first, but I may end up actually using it if I can make it good enough.</p>
<p>Since I wasn't at all familiar with the Socket library, I based my code off of <a href="https://www.thepythoncode.com/article/send-receive-files-using-sockets-python" rel="nofollow noreferrer">this tutorial</a>, but I now think I've made the code different enough to call it my own.</p>
<p>I've put quite some time into this project and now that I got everything working, I'd really like some feedback. In particular, and in order of importance :</p>
<ul>
<li>Did I pick up any bad habbits ?</li>
<li>Could I make this look cleaner, for exemple by modifing synthax, or adding or fusing fuctions ?</li>
<li>Is my commenting any good ? Should I comment more or less ? Is it clear enough ?</li>
<li>Is there any way to optimize the transfer ?</li>
</ul>
<p>Of course, any criticism is good to take so any remark regarding anything is welcome.</p>
<p>Notes:</p>
<ul>
<li>This program is meant to transfer file only and trying to download a directory from the server will cause an error. It is however a non-issue as you cannot select a directory to upload from the the client and the server's storage directory should not contain anything that wasn't sent by the client under normal circumstances.
<ul>
<li>If you decide to manually add files in the server's storage directory, keep in mind that directories are not supported.</li>
<li>Modifying the content of the server's storage directory after selecting the option to download files on the client and before you canceled the selection or all downloads are complete may result in an error</li>
</ul>
</li>
<li>I will be the only person using this app so it isn't useful to make it able to handle multiple requests at the same time.</li>
<li>Both the computers I use are connected to the same network.</li>
<li>The app has been tested and works on both Windows and Linux.
<ul>
<li>The client needs to run in an environment capable of showing a GUI as I use tkinter's filedialog to select the files to send to the server. This not the case for the server.</li>
</ul>
</li>
<li>I use python 3.8.2</li>
</ul>
<hr />
<p>Here is server script:</p>
<pre><code>import socket
import tqdm
import os
import pickle
import sys
##Setup connection with client
#Set storage directory
workDir = "Insert path to server's storage directory"
os.chdir(workDir)
#Set global variable
SERVER_HOST = "0.0.0.0"
SERVER_PORT = 5001
BUFFER_SIZE = 1024
SEPARATOR = "<SEPARATOR>"
#Start listening for connection attempt and perform the action chosen by the client
def start_listening():
#Accept the connexion of the client
s = socket.socket()
s.bind((SERVER_HOST, SERVER_PORT))
s.listen(1)
print(f"-------------------------\nListening to {SERVER_HOST}:{SERVER_PORT}")
client_socket, CLIENT_HOST = s.accept()
print(f"{CLIENT_HOST} is connected.")
#Perform the action chosen by the client
actionID = client_socket.recv(BUFFER_SIZE).decode()
client_socket.send('0'.encode())
if actionID == '1':
receive_file_choice(client_socket)
if actionID == '2':
send_file_choice(client_socket)
if actionID == '3':
client_socket.close()
s.close()
sys.exit()
#Restart the script to perform another action
client_socket.send('0'.encode())
client_socket.close()
s.close()
start_listening()
##Download
#Receive the number, names and sizes of the files to download
def receive_file_choice(client_socket):
fileNumber = int(client_socket.recv(BUFFER_SIZE).decode())
client_socket.send('0'.encode())
#Control the receive_file() function
for i in range(fileNumber):
received = client_socket.recv(BUFFER_SIZE).decode()
fileName, fileSize = received.split(SEPARATOR)
fileName = os.path.basename(fileName)
fileSize = int(fileSize)
client_socket.send('0'.encode())
print(f"\nDownloading {fileName} ({fileSize} bytes)")
receive_file(client_socket, fileName, fileSize)
#Download the file sent by the client and store them in workDir
def receive_file(client_socket, fileName, fileSize):
client_socket.send('0'.encode())
with open(fileName, "wb") as f:
downloadSize = 0
timeOutFlag = 0
#Setting a time out here ensure the the script can continue even if a packet was lost
client_socket.settimeout(10)
#Receive packets of size BUFFER_SIZE bytes
for i in tqdm.tqdm(range(fileSize//BUFFER_SIZE)):
try:
downloadSize += f.write(client_socket.recv(BUFFER_SIZE))
except (socket.timeout):
print('Error : Download timed out')
timeOutFlag = 1
break
#Tell the client it can send the next packet
client_socket.send('0'.encode())
#Receive remainig bytes
if timeOutFlag == 0:
try:
downloadSize += f.write(client_socket.recv(fileSize%BUFFER_SIZE))
except socket.timeout:
pass
client_socket.settimeout(None)
#Warn the user if data has been lost during the transfer
if downloadSize == fileSize:
print("Done")
else:
print(f"Warning: '{fileName}' does not match expected size\n(Received {downloadSize} bytes instead of {fileSize} - {fileSize - downloadSize} bytes difference)")
#Acknowledge that the download as ended. Send a '1' instead of '0' so that the client don't confuse it with the 'packet received' acknowledgement
client_socket.send('1'.encode())
##Upload
#Send a list of available files and retreive client's choice
def send_file_choice(client_socket):
print('Sending a list of available files to client')
tempFileList = os.listdir(workDir)
#If files are available to download for the client
if len(tempFileList) >= 1:
fileList = [(i, tempFileList[i], os.path.getsize(tempFileList[i])) for i in range(len(tempFileList))]
sentFileList = pickle.dumps(fileList)
client_socket.send(str(len(sentFileList)).encode())
client_socket.recv(1)
client_socket.send(sentFileList)
print('Waiting for client response')
choiceList = client_socket.recv(BUFFER_SIZE).decode()
#Return if the client has chosen to cancel the download
if choiceList.lower() == "-c":
print('Request canceled')
return
choiceList = choiceList.split(',')
client_socket.send('0'.encode())
for i in range(len(choiceList)):
choiceList[i] = int(choiceList[i])
fileNumber = len(choiceList)
client_socket.send(str(fileNumber).encode())
client_socket.recv(1)
control_upload(client_socket, fileList, choiceList)
#Return if no file was found
else:
client_socket.send(pickle.dumps('0'))
print('No file was found')
return
#Operates the send_file() function
def control_upload(client_socket, fileList, choiceList):
for i in choiceList:
fileName, fileSize = fileList[i][1], fileList[i][2]
client_socket.send(f"{fileName}{SEPARATOR}{fileSize}".encode())
client_socket.recv(1)
print(f"\nUploading {fileName} ({fileSize} bytes)")
send_file(client_socket, fileName, fileSize)
#Send requested file to the client
def send_file(client_socket, fileName, fileSize):
client_socket.recv(1)
with open(fileName, "rb") as f :
#Upload the file divided in packet of size BUFFER_SIZE bytes
for i in tqdm.tqdm(range(fileSize//BUFFER_SIZE)):
bytes_read = f.read(BUFFER_SIZE)
client_socket.sendall(bytes_read)
client_socket.recv(1)
#Send the remaining bytes
bytes_read = f.read(fileSize%BUFFER_SIZE)
client_socket.sendall(bytes_read)
#Wait for the server to acknowledge it has ended downloading the file
while True:
if client_socket.recv(1).decode() == '1':
break
print("Done")
if __name__ == '__main__':
start_listening()
</code></pre>
<p>Here is client script:</p>
<pre><code>import tkinter as tk
from tkinter import filedialog
import os
import tqdm
import socket
import pickle
from time import sleep
##Set up connection with server
#Set storage directory
workDir = "Insert path to your download directory here"
os.chdir(workDir)
#Set global variables
SERVER_HOST = "Insert server's IP adress here"
SERVER_PORT = 5001
BUFFER_SIZE = 1024
SEPARATOR = "<SEPARATOR>"
#Start the connection with the server, choose the action to perfmorm
def start_connection():
#Connect to the server
s = socket.socket()
print(f"-------------------------\nConnecting to {SERVER_HOST}:{SERVER_PORT}")
#Setting a timeout here prevent the client from trying to connect forever
s.settimeout(30)
try:
s.connect((SERVER_HOST, SERVER_PORT))
except socket.timeout:
print("Error : Connection timed out")
return
#Maintaining the timeout past this point could cause an error if the user took a long time to decide what he want to do. timeout is therefore set to None.
s.settimeout(None)
print("Connected")
#Ask for the user to choose the action to perform until he enter a valid action
while True:
actionID = input("\nChoose action to perform:\n1. Upload\n2. Download\n3. Close server\n4. Exit\n-> ")
if actionID in ['1','2','3','4']:
break
else:
print('Invalid action')
#Perform the requested action
if actionID == '1':
get_file_list(s)
if actionID == '2':
receive_file_choice(s)
if actionID == '3':
confirm = input("Do you want to procede? You won't be able to restart the server without physical access. (y/n)\n-> ")
if confirm == 'y' or confirm == 'Y':
s.send('3'.encode())
print("Server closed")
return
else:
print("Server was not closed")
return
if actionID == '4':
print('Exited')
return
#Restart the script to perform another action
s.recv(1)
sleep(0.2)
s.close()
start_connection()
##Upload
#Make the user choose the files to upload
def get_file_list(s):
s.send('1'.encode())
s.recv(1)
#Open the file selection window
selectionWindow = tk.Tk()
selectionWindow.withdraw()
fileNames = filedialog.askopenfilenames(parent=selectionWindow, initialdir=os.getcwd(), title='Please select file(s)')
fileNumber = len(fileNames)
fileSizes = tuple([os.path.getsize(fileNames[i]) for i in range(fileNumber)])
selectionWindow.destroy()
#Control the send_file() function
s.send(str(fileNumber).encode())
s.recv(1)
for i in range(fileNumber):
fileName, fileSize = fileNames[i], fileSizes[i]
s.send(f"{fileName}{SEPARATOR}{fileSize}".encode())
s.recv(1)
print(f"\nUploading {fileName} ({fileSize} bytes)")
send_file(s, fileName, fileSize)
#Send a file to the server
def send_file(s, fileName, fileSize):
s.recv(1)
with open(fileName, "rb") as f :
#Upload the file divided in packet of size BUFFER_SIZE bytes
for i in tqdm.tqdm(range(fileSize//BUFFER_SIZE)):
bytes_read = f.read(BUFFER_SIZE)
s.sendall(bytes_read)
s.recv(1)
#Send the remaining bytes
bytes_read = f.read(fileSize%BUFFER_SIZE)
s.sendall(bytes_read)
#Wait for the server to acknowledge it has ended downloading the file
while True:
if s.recv(1).decode() == '1':
break
print("Done")
##Download
#Ask for the user to choose the files to download
def receive_file_choice(s):
s.send('2'.encode())
s.recv(1)
#Receive the list of all available files on the server
print('Waiting for a list of available files')
fileListSize = int(s.recv(BUFFER_SIZE).decode())
s.send('0'.encode())
sentFileList = s.recv(fileListSize)
sentFileList = pickle.loads(sentFileList)
#Return if no file is available
if sentFileList == '0':
print('No file is available')
return
else:
print('\nID ; Name ; Size\n----------------')
possibleChoiceList = []
for i in range(len(sentFileList)):
print(f"{sentFileList[i][0]} ; {sentFileList[i][1]} ; {sentFileList[i][2]}")
possibleChoiceList.append(str(sentFileList[i][0]))
#Ask for the user to chose file until a valid entry is given
while True:
choiceListStr = input('\nEnter the IDs of the files to request separated with commas\nEnter "-c" to cancel\n-> ')
#Return if the user wants to cancel the download
if choiceListStr.lower() == "-c":
print('Request canceled')
s.send(choiceListStr.encode())
return
choiceList = choiceListStr.split(',')
#Check if the entry contains something that is not associated with a file (e.g., a negative number, a random letter...)
if not set(choiceList).issubset(set(possibleChoiceList)):
print('You cannot choose a file that is not listed')
#Check if a file is requested twice
elif len(choiceList) != len(set(choiceList)):
print('You cannot choose a file more than once')
#Break the loop if the entry is valid
else:
break
s.send(choiceListStr.encode())
s.recv(1)
control_download(s)
#Operate the receive_file() function
def control_download(s):
print('Waiting for the server to send files')
fileNumber = s.recv(BUFFER_SIZE).decode()
fileNumber = int(fileNumber)
s.send('0'.encode())
print(f"Downloading {fileNumber} files")
for i in range(fileNumber):
receive = s.recv(BUFFER_SIZE).decode()
fileName, fileSize = receive.split(SEPARATOR)
fileName = os.path.basename(fileName)
fileSize = int(fileSize)
s.send('0'.encode())
print(f"\nDownloading {fileName} ({fileSize} bytes)")
receive_file(s, fileName, fileSize)
#Receive a file from the server and store it in workDir
def receive_file(s, fileName, fileSize):
s.send('0'.encode())
with open(fileName, "wb") as f:
downloadSize = 0
timeOutFlag = 0
#Setting a timeout here ensure the the script can continue even if a packet was lost
s.settimeout(10)
#Receive packets of size BUFFER_SIZE bytes
for i in tqdm.tqdm(range(fileSize//BUFFER_SIZE)):
try:
downloadSize += f.write(s.recv(BUFFER_SIZE))
except socket.timeout :
print("\nError : Download timed out")
timeOutFlag = 1
break
#Tell the server it can send the next packet
s.send('0'.encode())
#Receive the remainig bytes
if timeOutFlag == 0:
try:
downloadSize += f.write(s.recv(fileSize%BUFFER_SIZE))
except socket.timeout:
pass
s.settimeout(None)
#Warn the user if data has been lost during the transfer
if downloadSize == fileSize:
print("Done")
else:
print(f"Warning: '{fileName}' does not match expected size\n(Received {downloadSize} bytes instead of {fileSize} - {fileSize - downloadSize} bytes difference)")
#Acknowledge that the download as ended. Send a '1' instead of '0' so that the server don't confuse it with the 'packet received' acknowledgement
s.send('1'.encode())
if __name__ == "__main__":
start_connection()
</code></pre>
<hr />
<p>When choosing the files to download on the client, you should see something like this</p>
<pre><code>ID ; Name ; Size
----------------
0 ; 3tseT.txt ; 7
1 ; Script1.py ; 5102
2 ; Script2.py ; 4835
3 ; NicePDF.pdf ; 193721
4 ; Test1.txt ; 22
5 ; Test2.txt ; 16
6 ; Test3bis.txt ; 1
Enter the IDs of the files to request separated with commas
Enter "-c" to cancel
->
</code></pre>
<p>If you want to select the files 0, 1, 4 and 5, enter <code>0,1,4,5</code> in the console.</p>
<hr />
<p>I tried transfering files using</p>
<pre><code>with open(filename, "rb") as f:
while True:
bytes_read = f.read(BUFFER_SIZE)
if not bytes_read:
break
s.sendall(bytes_read)
</code></pre>
<p>and</p>
<pre><code>with open(filename, "wb") as f:
while True:
bytes_read = client_socket.recv(BUFFER_SIZE)
if not bytes_read:
break
f.write(bytes_read)
</code></pre>
<p>which would have been simpler, but it ended up fusing files together when downloading multiple at once, so I opted for what you can see above.</p>
<p>Also, even though the <code>send('0'.encode())</code> and <code>recv(1)</code> significantly slow the transfer down, they are necessary to ensure that the client and the server work synchonously, and getting rid of them causes data loss. Increasing the buffer size can help speed up the process but setting it too high causes data loss as well.</p>
<hr />
<p>Finally, as english isn't my native language, I apology for any mistake I could have made. Feel free to correct me or ask for clarification.</p>
<p>Thanks for your time and have a nice day.</p>
<hr />
<p>Edit: Created a <a href="https://github.com/Lucas-Labouret/CloudPy" rel="nofollow noreferrer">github repository</a> to update the code as I receive suggestions.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T15:52:31.607",
"Id": "527807",
"Score": "1",
"body": "Hi, welcome! I suggest fixing the variable naming (you are mixing fileName, client_socket,...). Python does not use camel case (camelCase), but separates by _: file_name. I also suggest passing it through black or similar black.vercel.app/ for code formatting. Ping me then and we can continue!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T16:45:20.830",
"Id": "527812",
"Score": "0",
"body": "@miquelvir Hi, thanks for your help ! I just passed my code through Black and changed all my variables to this_style instead of thisOne as you suggested. I am new here, so please let me know if I should upload the edited version somewhere. In any case, I am ready to continue !"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-04T09:16:14.837",
"Id": "527832",
"Score": "1",
"body": "Yes! Would be nice if you update the question adding the updated code, and we can continue to more advanced feedback!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-04T09:57:56.083",
"Id": "527834",
"Score": "0",
"body": "@miquelvir I added the updated code in a github repository."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-04T10:14:35.013",
"Id": "527835",
"Score": "1",
"body": "Okey, I will CR it now :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-05T12:39:38.710",
"Id": "527890",
"Score": "0",
"body": "@miquelvir Thanks, your reply was very helpful ! I changed my code quite a lot and updated the github page.\n- I renamed some of my variables and my files/\n I put my constants into a separate file/\n I created a package containing server.py, client.py and ui.py/\n I breaked down fuctions with more than one purpose/\n I should be PEP8 compliant/\nHowever I still have some things I'm not sure about\n- I'm not sure what you meant by \"inline magic values\", I hoped I fixed that/\n When separating the logic and ui I only extracted the parts that required user interaction, not sure if it's enough"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-05T13:01:22.177",
"Id": "527891",
"Score": "1",
"body": "Good work! With \"magic values\" I mean the differenc action ids (1, 2, 3...). Instead of using that value there, which is quite arbitrary, define the constant e.g. ACTION_READ, and then use this everywhere where you need that id."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-05T13:06:08.943",
"Id": "527892",
"Score": "1",
"body": "There is still some design issues. Notice that `start_connection()` is not only starting the connection, it also chooses an action by calling `chose_action()`. And you are still using magic value sin places like `client_socket.send(\"1\".encode())`... Create a constant for that value, e.g. OK, or RECEPCTION_OK, or ACK_OK."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-05T15:36:25.630",
"Id": "527905",
"Score": "0",
"body": "@miquelvir Thanks! This should be fixed now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-05T22:09:10.737",
"Id": "527914",
"Score": "1",
"body": "still full of it! `action_id == \"UPLOAD\":\n return \"UPLOAD\"` and many other similar ones"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-06T16:14:59.063",
"Id": "527934",
"Score": "0",
"body": "@miquelvir Oh ok, I thought \"magic values\" only refered to values like \"1\" or \"2\". If you're not bored of me yet, which I would completely understand, it is fixed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-06T18:51:15.587",
"Id": "527937",
"Score": "1",
"body": "I edited my answer with more. There are surely still things I have missed and/or left out because that was enough for one CR... But feel free to ping me again if you fix all of that!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-10T16:17:40.103",
"Id": "528204",
"Score": "1",
"body": "Hey Lucas! Really good job. Your code is improving a lot. Hope you are learning! The topics you are onto now, are more complicated, but that's an awesome learning opportunity. Let me know if you get stuck, I can help you! (I have added an updated batch of review in my answer)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-10T21:30:18.523",
"Id": "528218",
"Score": "0",
"body": "@miquelvir Thanks ! Regarding the custom errors part, should I put them in a separate file like [your first link](https://www.programiz.com/python-programming/user-defined-exception) suggests or is it better if I just put them in `config.py` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-10T21:56:47.940",
"Id": "528224",
"Score": "0",
"body": "Usually the standard is have them in a file like `exceptions.py` or something like this!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-10T22:01:23.273",
"Id": "528225",
"Score": "0",
"body": "by the way, this is getting now a bit out of the CR! its more like mentoring... ping me on discord @miquelvir#6567 and lets leave the comments section!"
}
] |
[
{
"body": "<ul>\n<li>Let's start with the easy stuff. Naming. <code>CloudPy-Client.py</code> is not, by any means, a Pythonic name. <code>cloudpy_client.py</code> is what one would expect. Same for server.</li>\n<li>Client and Server both belong to CloudPy. Why not create a package and avoid the name clutter?</li>\n</ul>\n<pre><code>/cloudpy\n - __init__.py\n - client.py\n - server.py\n</code></pre>\n<ul>\n<li>If a variable is a constant, it should by all uppercase. <code>work_dir</code> -> <code>WORK_DIR</code>.</li>\n<li>Statically defining the working directory is not nice. If I want to run it, I need to change it. Check out <a href=\"https://stackoverflow.com/a/3430395/9415337\">this</a>.</li>\n<li>Again, this does not follow Python's naming convention. <code>action_ID</code> -> <code>action_id</code></li>\n<li>Why code repetition in both files for constants? Move it to a <code>config.py</code> or <code>constants.py</code> and share it betweent he two files.</li>\n</ul>\n<pre><code>SERVER_HOST = "192.168.1.10"\nSERVER_PORT = 5001\nBUFFER_SIZE = 1024\nSEPARATOR = "<SEPARATOR>"\n</code></pre>\n<ul>\n<li>PEP8 specifies functions in Python should have two blank lines above for style. E.g., CloudPy-Server.py line 20. Are you not using an IDE like Pycharm? It warns you of all of these style "errors".</li>\n<li>Avoid inline magic values.</li>\n</ul>\n<pre><code> if action_ID == "1":\n receive_file_choice(client_socket)\n if action_ID == "2":\n send_file_choice(client_socket)\n if action_ID == "3":\n client_socket.close()\n s.close()\n sys.exit()\n</code></pre>\n<p>-></p>\n<pre><code> if action_ID == ACTION_RECEIVE:\n receive_file_choice(client_socket)\n if action_ID == ACTION_SEND:\n send_file_choice(client_socket)\n if action_ID == ACTION_CLOSE:\n client_socket.close()\n s.close()\n sys.exit()\n</code></pre>\n<ul>\n<li>Python has a maximum recursion depth. Recursion is expensive. Why use recursion when you can use a while loop?</li>\n</ul>\n<pre><code>def start_listening():\n ...\n start_listening()\n</code></pre>\n<pre><code>def main():\n while True:\n start_listening()\n</code></pre>\n<ul>\n<li>Again, style, your IDE should be warning you about this. No blank line at the end of file.</li>\n<li>Again, style, <code>##Setup connection with client</code> -> <code># setup connection with client</code>.</li>\n<li>This is important. Mixing UI with logic is a terrible idea and signals you are picking up bad practices (of course, might not be true, this is my guess). Separate your UI and program flow, from the logic. <code>client_ui.py</code> could be in charge of <code>askopenfile_names</code> and then, once that is done, reach out to <code>client.py</code> with the files the user has chosen and do the logic there.</li>\n<li>Remember SRP. One function ideally does one thing. Start connection should start a connection, not start a connection, ask an action id, ......... Divide them. Use auxiliary functions, e.g., <code>ask_action</code>, <code>get_connection</code>, etc.</li>\n<li>What does this sleep do? Why is it there? <code>sleep(0.2)</code> Add a comment for non-trivial stuff!</li>\n<li>If a variable is unused, convention says we should use <code>_</code> as its name. <code>for i in tqdm.tqdm(range(file_size // BUFFER_SIZE)):</code> -> <code>for _ in tqdm.tqdm(range(file_size // BUFFER_SIZE)):</code>.</li>\n</ul>\n<p>There surely is a lot more, but I feel like this is enough for now... If you fix all of this and want more, ping me on the comments!</p>\n<hr />\n<p>On to more!</p>\n<ul>\n<li>File structure, again.\n<ol>\n<li>How does the name modules help you? Trivially, a package will contain modules. Let's choose more informative names. E.g., <code>backend</code> or <code>hosts</code>.</li>\n<li>What does ui.py have in common with client.py or server.py? If we have 2 "UIs" in cloudpy.py, wouldn't it make more sense to have <code>server_cli.py</code> and <code>client_cli.py</code>?</li>\n<li>Why is the logic of <code>def client_side():</code> and <code>def server_side():</code> with the UI? What is the difference? I buy that <code>def chose_side():</code> is a common entry point, so that makes sense as a separate file, but the other two would make much more sense with their respective UIs. If you want to have common utils between <code>server_cli.py</code> and <code>client_cli.py</code>, you can add it <code>/controllers/common.py</code> or similar.</li>\n</ol>\n</li>\n</ul>\n<pre><code>/modules\n - __init__.py\n - client.py\n - server.py\n - ui.py\ncloudpy.py\nconfig.py\n</code></pre>\n<pre><code>/hosts\n - __init__.py\n - client.py\n - server.py\n/controllers\n - __init__.py\n - client_cli.py\n - server_cli.py\n - common_cli.py\ncloudpy.py\nconfig.py\n</code></pre>\n<p>or if you plan in building a non-cli UI:</p>\n<pre><code>/hosts\n - __init__.py\n - client.py\n - server.py\n/controllers\n - __init__.py\n /cli\n - __init__.py\n - client_cli.py\n - server_cli.py\n - common_cli.py\ncloudpy.py\nconfig.py\n</code></pre>\n<ul>\n<li>Avoid wildcard imports. Read about it <a href=\"https://stackoverflow.com/a/3615206/9415337\">here</a> and/or <a href=\"https://docs.quantifiedcode.com/python-anti-patterns/maintainability/from_module_import_all_used.html\" rel=\"nofollow noreferrer\">here</a>.</li>\n<li><code>print</code> works well for prototyping or putting something together quickly. Printing makes sense in the cli UI (e.g. <code>ui.py</code>, or the new modules in <code>client_cli.py</code> and similar). There we are outputting text as a means to output text. If instead what we are doing is logging, like in <code>client.py</code> or <code>server.py</code>, then use a <code>log</code> and not a <code>print</code>! Read more about it <a href=\"https://docs.python.org/3/howto/logging.html\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://realpython.com/python-logging/\" rel=\"nofollow noreferrer\">here</a>.</li>\n<li>If you end up using them as sets, why declare them as lists? <code>choice_list</code> and <code>possible_choice_list</code>. Just have sets from the beginning.</li>\n<li><code>receive_file_choice()</code> is poorly architected. <code>receive_file_choice</code> is supposed to be part of the logic functions (it is in <code>client.py</code>!). Thus, it should not be asking for input to the user in <code>ui.get_download_file_list(sent_file_list)</code>. It must be the other way around, the UI (i.e. <code>client_cli.py</code>) must call <code>receive_file_choice(server_socket, choice_list_str, choice_list)</code> with everything it needs. Same in any other similar place.</li>\n<li>Same later down the function: the UI should be doing all of this validation and printing, and then calling some <code>cancel()</code> or whatever.</li>\n</ul>\n<pre><code>if choice_list_str.lower() == CANCEL_DOWNLOAD:\n print("Request canceled")\n server_socket.send(choice_list_str.encode())\n return CANCEL\n</code></pre>\n<ul>\n<li>Add type hinting! Good for checking for finding stupid mistakes with the IDE, code autocompletion and suggestions, and having a self-documenting code. Read about it <a href=\"https://realpython.com/lessons/type-hinting/\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">here</a>.</li>\n<li>What is this function doing? Does not follow SRP and is unclear. Is it choosing an action or acting upon it? For <code>UPLOAD</code> and <code>DOWNLOAD</code> it seems to be just returning the id. While for <code>CLOSE_SERVER</code> it does not return anything and instead performs an action!</li>\n</ul>\n<pre><code># Perform the action chosen by the client\ndef chose_action(client_socket):\n action_id = client_socket.recv(BUFFER_SIZE).decode()\n client_socket.send("0".encode())\n\n if action_id == UPLOAD:\n return UPLOAD\n\n if action_id == DOWNLOAD:\n return DOWNLOAD\n\n if action_id == CLOSE_SERVER:\n print("Closing server")\n sys.exit()\n</code></pre>\n<ul>\n<li>Simplify your code making use of exceptions. I.e., just raise a <code>ValueError</code>. Or implement your custom error (e.g. <code>class NoFileError(ValueError)</code>) and raise that. Then you can catch it later. We don't need to be having some return codes like <code>CANCEL</code>, we can just raise an exception if something did not work as we expected and catch it wherever we can print feedback on that exception to the cli or any other UI.</li>\n</ul>\n<pre><code>else:\n sent_file_list = pickle.dumps(NO_FILE)\n client_socket.send(str(len(sent_file_list)).encode())\n client_socket.recv(1)\n client_socket.send(sent_file_list)\n print("No file was found")\n return CANCEL\n</code></pre>\n<ul>\n<li>You mentioned</li>\n</ul>\n<blockquote>\n<p>I will be the only person using this app so it isn't useful to make it able to handle multiple requests at the same time.</p>\n</blockquote>\n<p>That is IMO not true. Handling multiple requests at the same time makes sense even with 1 user. If a user wants multiple files, it is """equivalent""" to multiple users wanting one file. Using threading (or possibly asyncio, but would have to check in the case of asyncio if it actually can help) you would be able to speed it up for 1+ files, since the bottleneck is the network and the file reading... Let me know if you are interested in exploring this in the future. <a href=\"https://serverfault.com/questions/202813/why-was-the-ftp-protocol-designed-to-use-more-than-one-port\">This</a> might interest you anyway.</p>\n<p>There are still more things for sure, but I feel this is, once again, more than enough for one CR!</p>\n<hr />\n<p>Let's see more, now that it is cleaner!</p>\n<ul>\n<li><p><code>config.py</code> is supposed to be only a file for some constants. Opening and making files or directories is not good. Why? Every time we <code>import config</code> we will run the whole script to check if the path exists, create dirs or files, etc. How can we fix it? Is log and storage for the client or server? Put it in the UI, which is the client that runs. There is where creating dirs/files should be. Plus, then you can control and make sure it only happens when the user starts the client/server, and not every time we <code>import config</code>.</p>\n</li>\n<li><p>If something in the config file is different for client and server. Maybe <code>WORK_DIR</code> or <code>LOG_FILE</code> it shouldn't be in the same config. Either it is not being used or it is missleading. You can have a config for the client and server specific settings, and the common one.</p>\n</li>\n<li><p>You can add a <code>if __name__ == '__main__'</code> in both <code>controllers/cli/client_cli.py</code> and <code>controllers/cli/server_cli.py</code>, so that you can directly run each of the components without choosing side. Not strictly necessary, but makes sense and is useful. E.g., for the client you would have <code>if __name__ == '__main__': client_side()</code>.</p>\n</li>\n<li><p>Naming for <code>def server_side():</code> and <code>def client_side():</code> is not the most self-explanatory. Maybe <code>def run_client():</code> and <code>def run_server():</code>, or just <code>def main():</code> to clearly indicate that it is the entry point to the client/server app.</p>\n</li>\n<li><p>Now let's go into a more advance topic and explanation about this design and responsibilities.</p>\n</li>\n</ul>\n<p>TLDR: using <code>sys.exit()</code> in the logic side (in the hosts) is definitely not recommended.</p>\n<p>Remember, we have split in one side the UI (cli in this case), and in the other all the logic. This way we can reuse the logic, or change the UI, and keep the two independent. Who is in charge of running the client/server and the application flow? The controller! Not the logic function. <code>start_connection()</code> should only start a connection, not start a connection and exit the program if it doesn't work.</p>\n<p>Imagine you have a boss, and you find out there is a security bug somewhere. In this metaphor, you would raise your concern to your boss, who in his place would raise it to the ultimate boss, who might decide to e.g. stop the servers until is resolved. You would not just go to the ultimate boss, or pull the plug on the server. That's not your responsibility!</p>\n<p>Same happens in code. In this case we have something like this:</p>\n<pre><code>+------------------------+------------+---+-------------+\n| | user | | file system |\n+------------------------+------------+---+-------------+\n| | ↑ ↓ | | ↑ ↓ |\n+------------------------+------------+---+-------------+\n| UI layer (controllers) | CLIENT_CLI | | SERVER_CLI |\n+------------------------+------------+---+-------------+\n| | ↑ ↓ | | ↑ ↓ |\n+------------------------+------------+---+-------------+\n| logic layer (hosts) | client | ↔ | server |\n+------------------------+------------+---+-------------+\n</code></pre>\n<p>What you are doing by calling <code>sys.exit()</code> in <code>hosts/client.py</code> (logic layer) is effectively going beyond the responsibilities of your layer. Something like this:</p>\n<pre><code>+------------------------+------------+---+-------------+\n| | user | | file system |\n+------------------------+------------+---+-------------+\n| |↗ ↑ ↓ | | ↑ ↓ |\n+------------------------+------------+---+-------------+\n| UI layer (controllers) |↑CLIENT_CLI | | SERVER_CLI |\n+------------------------+------------+---+-------------+\n| |↑ ↑ ↓ | | ↑ ↓ |\n+------------------------+------------+---+-------------+\n| logic layer (hosts) |↖ client | ↔ | server |\n+------------------------+------------+---+-------------+\n</code></pre>\n<p>HOW TO SOLVE IT? If you have an error in <code>hosts/client.py</code>, raise an exception to notify to the UI layer that something went wrong. And the upper layer can catch it, and then <code>sys.exit()</code>, since it is their responsibility.</p>\n<ul>\n<li><p>Same happens in <code>close_server()</code>. <code>close_server()</code> should notify to the server he should close, not close the server AND exit the client.</p>\n</li>\n<li><p>Similarly, why would we have <code>exit_client()</code> in <code>hosts/client.py</code>, exiting the app is responsibility of the CLI GUI layer.</p>\n</li>\n<li><p>In <code>request_action() -> str</code>, again, you violate SRP. <code>request_action</code> should request an action. And since it only requests an action, how can we know if it was executed successfully? Printing <code>server closed</code> or <code>exited</code> there makes no sense, since we don't know whether it actually performed the action correctly or not. So this should be printed somewhere, probably in <code>client_side</code>.</p>\n</li>\n<li><p><code>hosts/client.py def chose_action(socket, action_id)</code> makes no sense (the name). You are not choosing and action, but performing the action which was already chosen. Plus there is a typo in chose.</p>\n</li>\n<li><p>The log file is ok, but usually we add the date to the log file, so that you have one log file per day. Or something like this.</p>\n</li>\n<li><p>I think you can now implement custom errors to fix the sys.exit issue in the logic layer. Read <a href=\"https://www.programiz.com/python-programming/user-defined-exception\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://stackoverflow.com/questions/1319615/proper-way-to-declare-custom-exceptions-in-modern-python\">here</a>.</p>\n</li>\n<li><p>And also threading to speed things up.</p>\n<ol>\n<li>First read a bit about the options for concurrency in Python: <a href=\"https://stackoverflow.com/a/66834007/9415337\">here</a>, <a href=\"https://realpython.com/python-concurrency/\" rel=\"nofollow noreferrer\">here</a>. And remember your problem is an <a href=\"https://newbedev.com/what-do-the-terms-cpu-bound-and-i-o-bound-mean\" rel=\"nofollow noreferrer\">I/O bound problem</a>, since the bottleneck is sending the files, not doing anything computationally expensive with them.</li>\n<li>Now, how to do this?</li>\n</ol>\n</li>\n</ul>\n<pre><code>+------------+--------------------+--------------------------------------------------------------------+\n| | PORT | DESCRIPTION |\n+------------+--------------------+--------------------------------------------------------------------+\n| control | SERVER_PORT (5001) | used for communicating between client <-> server |\n| | | |\n| | | This requests jobs and does all the logistics |\n| | | (closing server, cancelling downloads, requesting downloads...). |\n| | | |\n| | | Once the logistics are done and everything is ready for the actual |\n| | | file transfer, it send assigns an *operation* port where |\n| | | the actual file transfer gets done. |\n+------------+--------------------+--------------------------------------------------------------------+\n| operations | 5002 - 5020 | Used for a concrete expensive operation, like sending one file. |\n+------------+--------------------+--------------------------------------------------------------------+\n</code></pre>\n<p>E.g., client requests to download a folder called <code>john</code>.</p>\n<pre><code>\\john\n - test1.txt\n - test2.txt\n - test3.txt\n</code></pre>\n<p>The process would go like follows:\n- client requests the folder to the server in the control port, i.e. 5001\n- server allocates some new parallel threads to send the file in some specific ports, e.g. 5002 - 5004\n- client allocates some new parallel threads for each job, and requests each file in parallel to each of the ports the server allocated for the jobs\n- once everything is done, e.g., the user chooses to close the server, so the client sends an exit message to the server through the control port (5001)</p>\n<pre><code>+--------+--------------------------------+---+---------------------------------------------------------+-------------+\n| | CLIENT | | SERVER | SERVER_PORT |\n+--------+--------------------------------+---+---------------------------------------------------------+-------------+\n| 0 | I want to download dir '\\john' | > | | 5001 |\n+--------+--------------------------------+---+---------------------------------------------------------+-------------+\n| 1 | | < | Ok! It has 3 files. Request each one individually here: | 5001 |\n| | | | { | |\n| | | | 'test1.txt': 5002, | |\n| | | | 'test2.txt': 5003, | |\n| | | | 'test3.txt': 5004 | |\n| | | | } | |\n+--------+--------------------------------+---+---------------------------------------------------------+-------------+\n| 2 | ACK! | > | | 5001 |\n+--------+--------------------------------+---+---------------------------------------------------------+-------------+\n| 3 | Can we start downloading? | > | | 5002 |\n+--------+--------------------------------+---+---------------------------------------------------------+-------------+\n| 4 | Can we start downloading? | > | | 5003 |\n+--------+--------------------------------+---+---------------------------------------------------------+-------------+\n| 5 | Can we start downloading? | > | | 5004 |\n+--------+--------------------------------+---+---------------------------------------------------------+-------------+\n| 6 - 8 | | < | Sure! | 5002 |\n+--------+--------------------------------+---+---------------------------------------------------------+-------------+\n| 6 - 8 | | < | Sure! | 5003 |\n+--------+--------------------------------+---+---------------------------------------------------------+-------------+\n| 6 - 8 | | < | Sure! | 5004 |\n+--------+--------------------------------+---+---------------------------------------------------------+-------------+\n| 9 - 10 | | < | {test1.txt} | 5002 |\n+--------+--------------------------------+---+---------------------------------------------------------+-------------+\n| 9 - 10 | | < | {test2.txt} | 5003 |\n+--------+--------------------------------+---+---------------------------------------------------------+-------------+\n| 9 - 10 | | < | {test3.txt} | 5004 |\n+--------+--------------------------------+---+---------------------------------------------------------+-------------+\n| 11 | Close server! | > | | 5001 |\n+--------+--------------------------------+---+---------------------------------------------------------+-------------+\n| 12 | | < | Ok, bye! | 5001 |\n+--------+--------------------------------+---+---------------------------------------------------------+-------------+\n</code></pre>\n<p>I hope this makes some sense and helps you get started! If you get stuck, just ping me :)</p>\n<p><a href=\"https://realpython.com/python-concurrency/#threading-version\" rel=\"nofollow noreferrer\">This example</a> using a <code>ThreadPoolExecutor</code> will help you. <a href=\"https://www.digitalocean.com/community/tutorials/how-to-use-threadpoolexecutor-in-python-3\" rel=\"nofollow noreferrer\">This one</a> and <a href=\"https://tutorialedge.net/python/concurrency/python-threadpoolexecutor-tutorial/\" rel=\"nofollow noreferrer\">this one</a> are also nice!</p>\n<ul>\n<li>Finally, what about adding encryption so that the file transfer does not travel unencrypted directly on the wire? Check <a href=\"https://gist.github.com/Oborichkin/d8d0c7823fd6db3abeb25f69352a5299\" rel=\"nofollow noreferrer\">this</a> and <a href=\"https://stackoverflow.com/a/63278147/9415337\">this</a>!</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-06T19:37:57.810",
"Id": "527939",
"Score": "0",
"body": "Thanks again ! Before I start editing, I'm not sure of what you mean by \"cli UI\" ? Also, there is a lot of new concepts to learn here so it might take me a while to implement everything. In particular, I never used a class or worked with more than one thread before (at least conciously), but i'll try to make that happen."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-06T19:39:48.933",
"Id": "527940",
"Score": "1",
"body": "\"In particular, I never used a class or worked with more than one thread before (at least conciously), but i'll try to make that happen.\" I would suggest against doing this rn! Try to go for the rest of things. What I mean is lets get all the other code nice and clean, and then we can try to implement this more advanced feature over a solid basis. I would not suggest doing this until the basis is really solid and clean!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-06T19:41:04.620",
"Id": "527941",
"Score": "1",
"body": "\"Before I start editing, I'm not sure of what you mean by \"cli UI\" \" in this case, the user interface (UI) is simply input/print from the command line (CLI). I.e., the UI is the CLI. With the same backend logic you have to send files, you could have the CLI UI, a web UI, a desktop (Tkinter) UI, etc... Does that make sense now?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-06T19:41:48.223",
"Id": "527942",
"Score": "1",
"body": "Do ping me again if you have any question!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-06T19:51:03.440",
"Id": "527943",
"Score": "0",
"body": "BTW please consider marking my answer as valid if the CR has been helpful!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-10T13:46:12.600",
"Id": "528196",
"Score": "0",
"body": "Hi, sorry if it took me too long ! Apart from the classes and threading, I think I worked everything out. If the code is clean enough, I'll try to learn about classes and thread next."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-10T16:59:46.547",
"Id": "528206",
"Score": "0",
"body": "see my comment in the original question :)"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-04T10:31:58.550",
"Id": "267680",
"ParentId": "267657",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "267680",
"CommentCount": "16",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T14:43:14.733",
"Id": "267657",
"Score": "4",
"Tags": [
"python",
"beginner",
"python-3.x",
"network-file-transfer"
],
"Title": "Cloud storage using python Socket library"
}
|
267657
|
<p>I have a file of the form -</p>
<blockquote>
<p>>SDF123.1 blah blah</p>
<p>ATCTCTGGAAACTCGGTGAAAGAGAGTAT</p>
<p>AGTGATGAGGATGAGTGAG...</p>
<p>>SBF123.1 blah blah</p>
<p>ATCTCTGGAAACTCGGTGAAAGAGAGTAT</p>
<p>AGTGATGAGGATGAGTGAG....</p>
</blockquote>
<p>And I want to extract the various sections of this file into individual files (like <a href="https://stackoverflow.com/questions/21476033/splitting-a-multiple-fasta-file-into-separate-files-keeping-their-original-names">here</a></p>
<p>I wrote the following code, but it runs too slow, as compared to when I did not have the <code>close</code> command in it. I had to incorporate the <code>close</code> command, since without it, I was getting the awk error - <code>too many open files</code>.</p>
<p>Here is the code -</p>
<pre><code>cat C1_animal.fasta | awk -F ' ' '{
if (substr($0, 1, 1)==">") {filename=(substr($1,2) ".fa")}
print $0 >> filename; close (filename)
}'
</code></pre>
<p>How can I make this code more time efficient? I am new to awk.</p>
|
[] |
[
{
"body": "<p>Try to close your <code>filename</code> only when it's necessary:</p>\n<p>File <code>actg.awk</code></p>\n<pre><code>BEGIN {\n FS=" "\n}\n/^>/ {\n if (filename != "") {\n close(filename)\n }\n filename = substr($1,2) ".fa"\n next\n}\nfilename != "" {\n print $0 > filename\n}\nEND {\n close (filename)\n}\n</code></pre>\n<p>With shell command:</p>\n<pre class=\"lang-bsh prettyprint-override\"><code>awk -f actg.awk C1_animal.fasta\n</code></pre>\n<p>Note: if you are sure there is no line before the first "<code>> ...</code>", you can skip the <code>filename != " "</code> test</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-06T05:54:04.907",
"Id": "527918",
"Score": "0",
"body": "Thank you, this code worked nicely and was quite faster. Could you explain a little how this code works? I am still trying to laern awk"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-04T17:16:13.413",
"Id": "267692",
"ParentId": "267662",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "267692",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T18:17:44.907",
"Id": "267662",
"Score": "1",
"Tags": [
"performance",
"awk"
],
"Title": "Extract sections of a file into separate files"
}
|
267662
|
<p>Note: this is not the solution for the "Character Picture Grid" problem from Automate the Boring Stuff. Instead, this is an expansion of that problem simply for the sake of understanding nested loops, lists within lists, and iterating through values in order to print a picture on the screen.</p>
<p>Thanks to anyone who takes the time to review this. Should I comment more throughout my code so that it's easier to read? Are there ways to shorten this program so that it could run faster? I'm still quite new to programming.</p>
<pre><code># This is an expanded version of the Character Picture Grid
# problem from Al Sweigart's book, Automate the Boring Stuff With Python.
# This function takes in user input to determine what direction to print
# the arrow.
rightArrow = [['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['O', 'O', 'O', 'O', 'O', '.'],
['.', 'O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O', 'O', 'O', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['.', '.', '.', '.', '.', '.']]
def printArrow(list):
rowLength = len(list[0]) # length of x plane coordinates
columnLength = len(list) # length of y plane coordinates
print('Welcome to Arrow Pointer v1.0!')
while True:
#main program loop
print('\n\nType in one of the following:\n\nup, down, left, right, or end to exit the program.')
#user determines direction of arrow to be printed
userInput = input()
if userInput.lower() == 'right':
for i in range(columnLength):
for j in range(rowLength):
#first loop iterates through main list
#nested loop iterates through inner list elements
print(list[i][j] + ' ', end='')
print('\n')
if userInput.lower() == 'left':
for i in range(columnLength):
for j in range(rowLength - 1, -1, -1):
#iterate backwards to print arrow in opposite direction
print(list[i][j] + ' ', end='')
print('\n')
if userInput.lower() == 'down':
for i in range(rowLength):
for j in range(columnLength):
print(list[j][i] + ' ', end='')
print('\n')
if userInput.lower() == 'up':
for i in range(rowLength-1, -1, -1):
for j in range(columnLength-1, -1, -1):
print(list[j][i] + ' ', end='')
print('\n')
if userInput.lower() == 'end':
quit()
printArrow(rightArrow)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-04T04:14:48.490",
"Id": "527824",
"Score": "0",
"body": "https://codereview.stackexchange.com/a/254846/25834 for reference"
}
] |
[
{
"body": "<ul>\n<li>Let's start with the basics. Always use if <code>__name__ == "__main__": printArrow(rightArrow)</code> instead of directly calling your function (<code>printArrow(rightArrow)</code>) to avoid running it if importing the function in the future from another module.</li>\n<li>A function called <code>printArrow</code> should print an arrow, not ask a user for input, print an arrow, and control the flow of the program. Divide it into def print_arrow(list, direction), main(), etc.</li>\n<li>Instead of using <code>quit()</code> which controls the global execution flow, you can use a plain <code>return</code> when inside a function. Cleaner and follows SRP.</li>\n<li>Naming! In python we don't usually use camelCase for functions; use instead: print_arrow. Same for variables like <code>rowLength</code> -> <code>row_length</code>.</li>\n<li>Pass your code through black or similar to have it nicely formatted (black.vercel.app/), otherwise the small human "errors" show up :)</li>\n<li>Constants in Python, by convention, use all upper case and don't need to be passed into functions (the only exception when globals are generally acceptable). So use <code>rightArrow</code> -> <code>RIGHT_ARROW</code> and <code>def printArrow(list):</code> -> <code>def printArrow():</code>.</li>\n<li>Use comments for the important stuff (the one which I can't trivially deduce from the code itself). What is this arbitrary amount of spaces? <code>' '</code>? Put it into a constant and comment why that many if it has a meaning. E.g., <code>SEPARATOR = ' '</code>.</li>\n<li>There is some code repetition, can't you put this into a function <code>def _print_arrow_auxiliary(x_start: int, x_end: int, x_step: int, y_start: int, y_end: int, y_step: int) -> None:</code>?</li>\n</ul>\n<pre><code>for i in range(rowLength-1, -1, -1):\n for j in range(columnLength-1, -1, -1):\n print(list[j][i] + ' ', end='')\n print('\\n')\n</code></pre>\n<ul>\n<li>It is a matter of taste, but type-hinting your functions does give you many advantages (self-explanatory code, better IDE highlights and suggestions, etc.)...\n<code>def printArrow(list):</code> -> <code>def printArrow(list: List[List[str]]) -> None:</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-04T17:00:56.310",
"Id": "527847",
"Score": "0",
"body": "Thanks for this response. There are a few things I need clairification on. I don't understand the following line: __name__ == \"__main__\": printArrow(rightArrow). Also, your second point about separating the function into print_arrow(list, direction), main(), etc. What is the purpose of 'main()' in this context?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-04T17:34:51.690",
"Id": "527851",
"Score": "0",
"body": "First question is answered [here](https://stackoverflow.com/questions/419163/what-does-if-name-main-do), this is a basic in Python, so I suggest you spend some time and make sure you get it! As for separation functions, in general we try to follow [SRP](https://en.wikipedia.org/wiki/Single-responsibility_principle), each function should only do one thing. So print_arrow should do only that, print the arrow, not have the main program loop or ask the user for input. It is a convention to have a function called main() which has the program main loop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-04T21:43:43.953",
"Id": "527862",
"Score": "0",
"body": "Thanks! Last question, how did you determine that I had constants in my code? I'm not aware of the difference between a constant and a variable in Python. I know in JavaScript, the declaration is either var, const, or let, but as far as I know, every variable in Python is a variable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-04T22:22:19.890",
"Id": "527865",
"Score": "2",
"body": "Well, yes. In Python there are no constants. That is, there is no way to enforce a variable is actually constant and never changes. However, us, as ✨responsible programmers✨ do use some variables which we intend to use as constants. If we want to show that a variable is intended to be use as a constant, in Python we use all uppercase like SOME_CONSTANT. In your case, e.g., rightArrow is used but never modified, so let's make it explicit by using the naming convention for constants!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-03T18:34:29.540",
"Id": "532202",
"Score": "0",
"body": "If you have a moment and it's not too much trouble, would you be willing to take a look at the final product? The only problem I encountered was being unable to create a single function that prints the arrow in all four directions, so I created two functions, one for \"left right\" and one for \"up down\": https://github.com/ajoh504/Automate-The-Boring-Stuff-Exercises/blob/main/CH%204%20Lists/10_character_picture_grid2.py"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-04T08:06:17.277",
"Id": "532233",
"Score": "0",
"body": "Maybe consider calling lower on user_input just once and storing it instead of repeating it. So: `user_input = input().lower()`. The rest seems fine!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-04T09:30:40.540",
"Id": "267676",
"ParentId": "267666",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "267676",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-03T21:20:10.730",
"Id": "267666",
"Score": "1",
"Tags": [
"python",
"performance",
"beginner"
],
"Title": "Expanding on a problem from Automate the Boring Stuff"
}
|
267666
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.