body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I have the following code that aims to filter those <code>pid</code> (1 and 4) that have at least <code>before_threshold</code> (2) rows with a value of <code>before</code> in the <code>day_type</code> column and at least <code>after_threshold</code> (2) rows with a value of <code>after</code> in the same <code>day_type</code> column. </p>
<p>Is there a more succinct way of doing this using the tidyverse packages?</p>
<pre class="lang-r prettyprint-override"><code>library(tidyr)
before_threshold = 2
after_threshold = 2
data <- data.frame(pid = c(rep("1", 5), rep("2",5), rep("3", 1), rep("4", 4)),
day_type = c(rep("before", 3), rep("after", 2), rep("before", 5), rep("after", 1), rep("before", 2), rep("after", 2)),
stringsAsFactors = F)
data <- data %>%
group_by(pid) %>%
add_count(pid, day_type) %>%
mutate(count_before = ifelse(day_type == "before", n, NA),
count_after = ifelse(day_type == "after", n, NA)) %>%
fill(count_before, .direction = "downup") %>%
fill(count_after, .direction = "downup") %>%
filter(count_before >= before_threshold & count_after >= after_threshold)
print(data)
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-20T21:14:16.217",
"Id": "240895",
"Score": "1",
"Tags": [
"r"
],
"Title": "Keeping groups based on the row count of a second column"
}
|
240895
|
<p>I'm making a chess game. On the board the columns go from a-h and rows from 8-1. I made this simple function so when someone inputs 'a' for the row it will give me the right row on an array same goes for columns, 7a would be [1][0]. Is there an easier way someone could point out for me? </p>
<p>Thanks in advance.</p>
<p><strong>update:added small working sample of function.</strong></p>
<pre><code>#include <stdio.h>
int getColRow(char input)
{
int val = 0;
switch (input)
{
//row
case 97:
val = 0;
break;
case 98:
val = 1;
break;
case 99:
val = 2;
break;
case 100:
val = 3;
break;
case 101:
val = 4;
break;
case 102:
val = 5;
break;
case 103:
val = 6;
break;
case 104:
val = 7;
break;
//col
case 49:
val = 7;
break;
case 50:
val = 6;
break;
case 51:
val = 5;
break;
case 52:
val = 4;
break;
case 53:
val = 3;
break;
case 54:
val = 2;
break;
case 55:
val = 1;
break;
case 56:
val = 0;
break;
default:
break;
}
return val;
}
int main(int argc, char *argv[])
{
char a = 'a';
char b = 'b';
char c = 'c';
char d = 'd';
char e = 'e';
char f = 'f';
char g = 'g';
char h = 'h';
char one = '1';
char two = '2';
char three = '3';
char four = '4';
char five = '5';
char six = '6';
char seven = '7';
char eight = '8';
printf("value of %c is %d ",a,getColRow(a));
printf("\nvalue of %c is %d ",b,getColRow(b));
printf("\nvalue of %c is %d ",c,getColRow(c));
printf("\nvalue of %c is %d ",d,getColRow(d));
printf("\nvalue of %c is %d ",e,getColRow(e));
printf("\nvalue of %c is %d ",f,getColRow(f));
printf("\nvalue of %c is %d ",g,getColRow(g));
printf("\nvalue of %c is %d \n",h,getColRow(h));
printf("\nvalue of %c is %d ",one,getColRow(one));
printf("\nvalue of %c is %d ",two,getColRow(two));
printf("\nvalue of %c is %d ",three,getColRow(three));
printf("\nvalue of %c is %d ",four,getColRow(four));
printf("\nvalue of %c is %d ",five,getColRow(five));
printf("\nvalue of %c is %d ",six,getColRow(six));
printf("\nvalue of %c is %d ",seven,getColRow(seven));
printf("\nvalue of %c is %d \n",eight,getColRow(eight));
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-20T22:14:51.067",
"Id": "472629",
"Score": "3",
"body": "It would help if we saw more of the program, especially any functions that call this function. Does this code work, that is a requirement here on code review. I ask because based on the description at the top, there should be 2 switch statements, not one. There is an easier way, simple subtraction can calculate the numbers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-20T23:57:26.577",
"Id": "472642",
"Score": "0",
"body": "@pacmaninbw its pretty basic code, I updated the post to include a small working version"
}
] |
[
{
"body": "<p>What you are doing is very basic, and the question really belongs on stackoverflow.com, but it has probably already been answered there, and therefore would be marked as a duplicate.</p>\n\n<p>As I mentioned in the comment, this can be done using simple subtraction of characters when you <code>include ctype.h></code>, you don't need a switch statement or anything that complcated. The example below should execute faster than the version with the switch statement, and it is a lot less code.</p>\n\n<pre><code>#include <ctype.h>\n\nint getColRow(char input)\n{\n int val = 0;\n unsigned char testValue = (unsigned char) input;\n\n if (isdigit(testValue))\n {\n return testValue - '0';\n }\n else if (isalpha(testValue))\n {\n testValue = tolower(testValue);\n return testValue - 'a';\n }\n\n fprintf(stderr, \"Invalid character %c in getColRow(char input)\\n\", input);\n return val;\n}\n</code></pre>\n\n<p>Most of the functions / macros in ctype.h take unsigned integers, and it is safer to use unsigned values. The unsigned char should automatically be promoted to an unsigned integer.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T00:28:00.320",
"Id": "472645",
"Score": "0",
"body": "Like I said, its very basic code. I appreciate your help, thank you very much for your input."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T00:31:02.263",
"Id": "472646",
"Score": "1",
"body": "If you want to continue using the switch statement, don't translate to the ASCII codes, use the actual characters in the cases, case 'a': ... case 'h': It is a lot more readable and more portable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T00:35:26.403",
"Id": "472647",
"Score": "0",
"body": "Awesome thanks for the tips. Pretty new at c"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T11:21:08.443",
"Id": "473008",
"Score": "1",
"body": "\"macros in ctype.h take unsigned integers\" is more like \"macros in ctype.h take unsigned char values\" - all those functions take an `int` type. \"... automatically be promoted to an unsigned integer.\" is amiss too. `unsigned char` tend to promote to `int`. Good idea about `unsigned char testValue = (unsigned char) input;` though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T11:26:52.533",
"Id": "473009",
"Score": "0",
"body": "Suggest adding `#include <ctype.h>`"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T00:19:44.560",
"Id": "240904",
"ParentId": "240896",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "240904",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-20T21:21:55.057",
"Id": "240896",
"Score": "1",
"Tags": [
"c"
],
"Title": "Simplifying function"
}
|
240896
|
<p>Turned in a project a few days ago, and I needed a way to filter and format values off a file. I decided to go for a bash script since it seemed like a good option, and I came up with the following:</p>
<pre><code>#!/bin/bash
amount=100
awk '{
if($i == "data: 1"){
getline;
getline;
print $2}}' sensordata.txt > temp1.txt
awk -v m=$amount 'NR<=m' temp1.txt > temp12.txt
maxval1=$(awk -v val=0 '{
if($i>val)
val=$i;};
END {print val}' temp12.txt)
minval1=$(awk -v val=1024 '{
if($i<val)
val=$i;};
END {print val}' temp12.txt)
awk -v max=$maxval1 -v min=$minval1 '{
if($i!=max && $i!=min)
print $0}' temp12.txt > data1.txt
avgval1=$(awk -v avg=0 '{
avg+=$i;};
END {
avg/=NR;
print avg}' data1.txt)
rm temp1.txt
rm temp12.txt
</code></pre>
<p>This is used 3 times for different files as I need to filter it 3 times.</p>
<p>The original file contains several values I need to filter, all of which have a "title" ("data: 1"), and all lines are separated by a "---". It'd look something like this:</p>
<pre><code>data: 1
<--->
data: 111
<--->
data: 2
<--->
data: 222
</code></pre>
<p>and so on.</p>
<p>My script copies all values 2 lines below the "title" into another file, moves a certain amount of lines to another file, finds the maximum and minimum value, then moves all values different to max and min to a last file, from which the average of all values is calculated. Then it's graphed using GNUPLOT.</p>
<p>I was wondering if there was a better way of achieving this, as I quite clearly abused the AWK command, and everything seems quite messy from my perspective, specially because I'm constantly moving values from the original file into a new one. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T06:47:48.437",
"Id": "472657",
"Score": "2",
"body": "This sort of question demands an exact output that you would like to produce for the given sample input. And Yes, all your `awk` commands can be simplified into one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T19:49:13.403",
"Id": "472736",
"Score": "0",
"body": "(While I think this should work, it sure *looks* like it shouldn't.)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-20T22:57:47.853",
"Id": "240900",
"Score": "3",
"Tags": [
"bash",
"linux",
"awk"
],
"Title": "Merging multiple awk commands while retaining functionality"
}
|
240900
|
<p>I'm trying to interact with a bash shell on a router to automate some CLI commands using SSH.NET. I'm not sure if the approach I'm taking is the best one and would like to get some recommendations on how to improve my methology. Although this code does indeed work correctly and does produced consistent results, the timeout involved makes the entire operation take a long time.</p>
<p>Here's the class I wrote to consume the ShellStream:</p>
<pre><code>using System;
using System.Diagnostics;
using System.Text;
using System.Threading;
using Renci.SshNet;
public class InteractiveShellStream : IDisposable
{
private const int TIMEOUT = 3000;
private bool disposed = false;
private readonly Stopwatch wait;
private readonly ShellStream shell;
public InteractiveShellStream(ShellStream shellStream)
{
wait = new Stopwatch();
shell = shellStream;
wait.Start();
while (!shell.DataAvailable && wait.ElapsedMilliseconds < TIMEOUT)
Thread.Sleep(200);
wait.Stop();
}
public void Write(string command)
{
shell.Write(command);
}
public void WriteLine(string command)
{
shell.WriteLine(command);
}
public string Read()
{
return shell.Read();
}
public string ReadLine()
{
return shell.ReadLine();
}
public string ReadWithTimeout()
{
StringBuilder buffer = new StringBuilder();
wait.Restart();
while (!shell.DataAvailable && wait.ElapsedMilliseconds < TIMEOUT)
Thread.Sleep(100);
wait.Stop();
while (shell.DataAvailable)
{
buffer.Append(shell.Read());
wait.Restart();
while (!shell.DataAvailable && wait.ElapsedMilliseconds < TIMEOUT)
Thread.Sleep(200);
wait.Stop();
}
return buffer.ToString();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
shell.Dispose();
}
disposed = true;
}
~InteractiveShellStream()
{
Dispose(false);
}
}
</code></pre>
<p>And here's how I use it:</p>
<pre><code>SshClient client = new SshClient(hostname, port, username, password);
client.Connect();
InteractiveShellStream shell = new InteractiveShellStream(client.CreateShellStream("xterm-mono", 80, 24, 800, 600, 2000));
Console.Write(shell.ReadWithTimeout());
shell.WriteLine("configure");
Console.Write(shell.ReadWithTimeout());
shell.WriteLine("delete firewall group address-group Monitored");
Console.Write(shell.ReadWithTimeout());
shell.WriteLine("commit");
Console.Write(shell.ReadWithTimeout());
shell.WriteLine("exit");
Console.Write(shell.ReadWithTimeout());
shell.Dispose();
client.Disconnect();
client.Dispose();
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-20T23:54:00.487",
"Id": "240903",
"Score": "3",
"Tags": [
"c#",
"bash",
"console"
],
"Title": "Using SSH.NET to interact with a Bash shell"
}
|
240903
|
<p>On StackOverflow I got a great <a href="https://stackoverflow.com/a/61242262/25197">answer to a question I had about creating a Date object from an ISO 8601 string with the ability to reposition into local time</a>.</p>
<p>From there I wanted to see if I could make it any faster. We process a ton of dates in batches of 10,000 or more sometimes on slow phones.</p>
<p>This is the best I could do.</p>
<pre><code>const isoToDate = (iso8601, ignoreTimezone = false) => {
// Differences from default `new Date()` are...
// - Returns a local datetime for all without-timezone inputs, including date-only strings.
// - ignoreTimezone processes datetimes-with-timezones as if they are without-timezones.
// - Accurate across all mobile browsers. https://stackoverflow.com/a/61242262/25197
const dateTimeParts = iso8601.match(
/(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2}):(\d{2})(?:\.(\d{0,7}))?(?:([+-])(\d{2}):(\d{2}))?)?/,
);
// Create a "localized" Date.
// If you create a date (without specifying time), you get a date set in UTC Zulu at midnight.
// https://www.diigo.com/0hc3eb
const date = new Date(
dateTimeParts[1], // year
dateTimeParts[2] - 1, // month (0-indexed)
dateTimeParts[3] || 1, // day
dateTimeParts[4] || 0, // hours
dateTimeParts[5] || 0, // minutes
dateTimeParts[6] || 0, // seconds
dateTimeParts[7] || 0, // milliseconds
);
const sign = dateTimeParts[8];
if (sign && !ignoreTimezone) {
const direction = sign === '+' ? 1 : -1;
const hoursOffset = dateTimeParts[9] || 0;
const minutesOffset = dateTimeParts[10] || 0;
const offset = direction * (hoursOffset * 60 + minutesOffset * 1);
date.setMinutes(date.getMinutes() - offset - date.getTimezoneOffset());
}
return date;
};
</code></pre>
<p>It's about double the speed of the SO answer and 4-6x faster than <code>moment.js</code> and <code>date-fns</code> packages.</p>
<p>The key difference is a single regex that returns all the matching groups at once.</p>
<p><img src="https://www.debuggex.com/i/lqBZDyW2hXUUv_RA.png" alt="Regular expression visualization"></p>
<p><a href="https://regex101.com/r/WKZFZ1/1" rel="nofollow noreferrer">Here's a regex101</a> with some examples of it matching/grouping.</p>
<p><br />
Is there anything obvious that can be improved upon here? Thanks! </p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T01:12:08.317",
"Id": "240906",
"Score": "2",
"Tags": [
"javascript",
"datetime",
"regex"
],
"Title": "Fastest conversion of ISO 8601 string into javascript Date object"
}
|
240906
|
<p>I am trying to write a function to determine whether an array contains consecutive numbers for at least N numbers. For example, the input is <code>[1,5,3,4]</code> and <code>3</code>, it turns <code>true</code> because the array has <code>3</code> consecutive numbers, which is <code>[3,4,5]</code></p>
<p>Here this function requires sorting beforehand and it is not the most eloquent solution in my opinion. Can someone take a look and suggest some improvements on this?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function hasConsecutiveNums(array, N) {
if (array.length < N) return false;
if (N === 0) return true;
const sortedArray = array.slice().sort((a, b) => a - b);
let count = 0;
let prev = null;
for (const num of sortedArray) {
if (prev && num === prev + 1) {
count++;
} else {
count = 1;
}
if (count === N) return true;
prev = num;
}
return false;
}
console.log(hasConsecutiveNums([1, 4, 5, 6], 3)) // true
console.log(hasConsecutiveNums([1, 4, 5, 6], 4)) // false</code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T08:56:15.250",
"Id": "472670",
"Score": "1",
"body": "Would the case `[1, 4, 5, 5, 6], 3` be expected to return true? in the current code it doesn't"
}
] |
[
{
"body": "<p>Some quick remarks:</p>\n\n<pre><code>if (N === 0) return true;\n</code></pre>\n\n<p>can be replaced by </p>\n\n<pre><code>if (N <= 1) return true;\n</code></pre>\n\n<p>because in a non-empty array each element is a single “consecutive number.” This saves the sorting of the array in the case <span class=\"math-container\">\\$ N = 1 \\$</span>.</p>\n\n<p>Then it suffices to check the count again only if it has been incremented. </p>\n\n<p>The comparison with the previous number (or <code>null</code>) can be simplified slightly.</p>\n\n<pre><code> for (const num of sortedArray) {\n if (prev === num - 1) {\n count++;\n if (count === N) return true;\n } else {\n count = 1;\n }\n prev = num;\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T08:24:18.360",
"Id": "240917",
"ParentId": "240914",
"Score": "1"
}
},
{
"body": "<p>One issue to consider: what if an element in the array is 0, and thus falsey? Then <code>if (prev &&</code> will not be fulfilled:</p>\n\n<pre><code>console.log(hasConsecutiveNums([-1, 0, 1], 3)) // false... oops\n</code></pre>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function hasConsecutiveNums(array, N) {\n if (array.length < N) return false;\n if (N === 0) return true;\n const sortedArray = array.slice().sort((a, b) => a - b);\n let count = 0;\n let prev = null;\n for (const num of sortedArray) {\n if (prev && num === prev + 1) {\n count++;\n } else {\n count = 1;\n }\n if (count === N) return true;\n prev = num;\n }\n\n return false;\n}\n\nconsole.log(hasConsecutiveNums([-1, 0, 1], 3)) // false... oops</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Another tweak to make the code a bit more elegant would be to assign <code>prev</code> to the first element of the array first, and initialize <code>count</code> to <code>1</code>, thus starting comparison on the <em>second</em> element rather than on the first, avoiding the need to compare against <code>null</code>.</p>\n\n<p>With this method, you also need to return <code>true</code> immediately if the array's length is only 1, like the other answer recommends, otherwise there won't be any iterations within which <code>return true</code> could be reached:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function hasConsecutiveNums(array, N) {\n if (array.length < N) return false;\n if (N <= 1) return true;\n const sortedArray = array.slice().sort((a, b) => a - b);\n let prev = sortedArray.shift();\n let count = 1; // first element of the array is already in prev\n for (const num of sortedArray) {\n if (num === prev + 1) {\n count++;\n } else {\n count = 1;\n }\n if (count === N) return true;\n prev = num;\n }\n\n return false;\n}\n\nconsole.log(hasConsecutiveNums([1, 4, 5, 6], 3)) // true\nconsole.log(hasConsecutiveNums([1, 4, 5, 6], 4)) // false\nconsole.log(hasConsecutiveNums([-1, 0, 1], 3)) // true</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>If, as the comment notes, you'd want <code>[1, 2, 2, 3]</code> to return <code>true</code>, de-duplicate the numbers with a Set:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function hasConsecutiveNums(array, N) {\n if (array.length < N) return false;\n if (N <= 1) return true;\n const sortedArray = [...new Set(array.slice().sort((a, b) => a - b))];\n let prev = sortedArray.shift();\n let count = 1; // first element of the array is already in prev\n for (const num of sortedArray) {\n if (num === prev + 1) {\n count++;\n } else {\n count = 1;\n }\n if (count === N) return true;\n prev = num;\n }\n\n return false;\n}\n\nconsole.log(hasConsecutiveNums([1, 4, 5, 6], 3)) // true\nconsole.log(hasConsecutiveNums([1, 4, 5, 6], 4)) // false\nconsole.log(hasConsecutiveNums([-1, 0, 1], 3)) // true\nconsole.log(hasConsecutiveNums([1, 2, 2, 3], 3)) // true</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T11:22:27.967",
"Id": "472840",
"Score": "0",
"body": "Thanks for incorporating my comment into you answer, keeps my lazy butt for having to write my own :P"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T08:47:58.267",
"Id": "240918",
"ParentId": "240914",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "240918",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T06:50:29.447",
"Id": "240914",
"Score": "3",
"Tags": [
"javascript",
"algorithm",
"array"
],
"Title": "Write a function to determine whether an array contains consecutive numbers for at least N numbers"
}
|
240914
|
<p>I have written a program on Pig Latin converter which I've attached herewith Pastebin. I am still a beginner, and I know that the code works perfectly, but can we make some improvements in this code cause I don't like using break statements too much. Also, is there any way to make this code smaller. Looking for your kind suggestions. Thanks.</p>
<pre><code>'''Pig Latin is a language constructed by transforming English words. While the ori-
gins of the language are unknown, it is mentioned in at least two documents from
the nineteenth century, suggesting that it has existed for more than 100 years. The
following rules are used to translate English into Pig Latin:
• If the word begins with a consonant (including y), then all letters at the beginning of
the word, up to the first vowel (excluding y), are removed and then added to the end
of the word, followed by ay. For example, computer becomes omputercay
and think becomes inkthay.
• If the word begins with a vowel (not including y), then way is added to the end
of the word. For example, algorithm becomes algorithmway and office
becomes officeway.
Write a program that reads a line of text from the user. Then your program should
translate the line into Pig Latin and display the result. You may assume that the string
entered by the user only contains lowercase letters and spaces.
'''
def pig_latin(word):
word = word.strip().lower()
const_tail = 'ay'
vow_tail = 'way'
pig_latin =''
vowel = ['a','e','i','o','u']
for i in range(len(word)):
if word[0] in vowel:
pig_latin+=word+vow_tail
break
else:
if word[i] in vowel:
pig_latin+=word[i:]+word[0:i]+const_tail
break
return pig_latin
def main():
word = str(input('Enter the word: '))
print('The pig latin translation of the string is',pig_latin(word))
if __name__ == "__main__":
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T09:12:23.800",
"Id": "472676",
"Score": "0",
"body": "Please check your indentation. This is Python. If the indentation is off, the code doesn't work. I strongly suspect everything from the line with the `if` to the `return` need another level."
}
] |
[
{
"body": "<h2>Unnecessary Check</h2>\n\n<p>We don't have to check the first letter every iteration, let's treat this any other letter in the word until it matters, then check our index.\nOnce we find a vowel(if there is one) we then check if it was our first letter to determine if we use the vowel tail or not. Then break after the index condition checks.</p>\n\n<pre><code>def pig_latin(word):\n word = word.strip().lower()\n const_tail = 'ay'\n vow_tail = 'way'\n pig_latin =''\n vowel = ['a','e','i','o','u']\n for i in range(len(word)):\n if word[i] in vowel:\n if i==0:\n pig_latin+=word+vow_tail\n else:\n pig_latin+=word[i:]+word[0:i]+const_tail\n break\n return pig_latin\n</code></pre>\n\n<h2>Additional Code Simplification</h2>\n\n<p>By only adding the W to the end of a string starting with a vowel we can also eliminate the else case and apply it's code to every string that makes it there.</p>\n\n<p>Also an option, but not shown below is removing the break and returning the restructured string from within the for.</p>\n\n<pre><code>def pig_latin(word):\n word = word.strip().lower()\n pig_latin =''\n vowel = ['a','e','i','o','u']\n for i in range(len(word)):\n if word[i] in vowel:\n if i==0:\n word+=\"w\"\n pig_latin+=word[i:]+word[0:i]+\"ay\"\n break\n return pig_latin\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T09:33:03.607",
"Id": "472680",
"Score": "0",
"body": "Thanks, it looks very good now. I hope I am heading towards the right path now."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T09:20:21.450",
"Id": "240921",
"ParentId": "240916",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "240921",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T08:07:53.443",
"Id": "240916",
"Score": "0",
"Tags": [
"python"
],
"Title": "Pig Latin Converter"
}
|
240916
|
<p>I am trying to solve a problem on GeekTrust, called Tame of Thrones (<a href="https://www.geektrust.in/coding-problem/backend/tame-of-thrones" rel="nofollow noreferrer">here</a>)</p>
<blockquote>
<p>Shan, the gorilla king of the Space kingdom wants to rule all Six
Kingdoms in the universe of Southeros.</p>
<p>There is no ruler today and pandemonium reigns. Shan is sending secret
messages to all kingdoms to ask for their allegiance. Your coding
challenge is to help King Shan send the right message to the right
kingdom to win them over. Each kingdom has their own emblem and the
secret message should contain the letters of the emblem in it. Once
Shan has the support of 3 other kingdoms, he is the ruler!</p>
</blockquote>
<p>And would like to get my code reviewed.</p>
<p>I am trying to achieve the badges for Functional/OO Modelling and Extensibility.</p>
<p>Following are all the primary classes involved in the solution that I need to get reviewed.</p>
<pre><code>public class Kingdom {
public final String name;
public final String emblem;
private final Set<String> allies;
private Ruler ruler;
private PostService postService;
public Kingdom(@NotNull String emblem, @NotNull String name) {
Objects.requireNonNull(emblem, ErrorMessages.EMBLEM_NOT_NULL_ERROR_MESSAGE);
Objects.requireNonNull(name, ErrorMessages.NAME_NOT_NULL_ERROR_MESSAGE);
this.emblem = emblem;
this.name = name;
this.allies = new LinkedHashSet<>();
}
public void sendMessage(String to, String body) {
Message message = new Message(this.name, to, body);
Message response = this.postService.exchange(message);
if (this.hasOtherKingdomAllied(response)) {
this.allies.add(response.from);
}
}
private boolean hasOtherKingdomAllied(Message message) {
try {
Cipher cipher = Ciphers.cipher(Ciphers.SEASAR_CIPHER_TYPE, this.postService.getEmblemFor(message.from)
.length());
String decryptedMessage = cipher.decrypt(message.body);
return MessageResponses.POSITIVE_RESPONSE.equalsIgnoreCase(decryptedMessage);
} catch (NoSuchAlgorithmException e) {
return false;
}
}
public Message allyRequest(Message message) {
Message response;
try {
Cipher cipher = Ciphers.cipher(Ciphers.SEASAR_CIPHER_TYPE, this.emblem.length());
String decryptedMessage = cipher.decrypt(message.body);
String shouldWeAlly = this.shouldWeAlly(decryptedMessage) ? MessageResponses.POSITIVE_RESPONSE:
MessageResponses.NEGATIVE_RESPONSE;
String responseBody = cipher.encrypt(shouldWeAlly);
response = new Message(this.name, message.from, responseBody);
} catch (NoSuchAlgorithmException e) {
return new Message(this.name, message.from, MessageResponses.NEGATIVE_RESPONSE);
}
return response;
}
private boolean shouldWeAlly(String message) {
return StringCompareUtils.containsIndexInsensitive(message, this.emblem);
}
public void setPostService(@NotNull PostService postService) {
Objects.requireNonNull(ruler);
this.postService = postService;
}
public Set<String> getAllies() {
return new LinkedHashSet<>(this.allies);
}
public Ruler getRuler() {
return ruler;
}
public void setRuler(@NotNull Ruler ruler) {
Objects.requireNonNull(ruler);
this.ruler = ruler;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Kingdom kingdom = (Kingdom) o;
return emblem.equals(kingdom.emblem);
}
@Override
public int hashCode() {
return Objects.hash(emblem);
}
}
</code></pre>
<pre><code>public class Universe {
private static Universe universe;
private final Set<Kingdom> kingdoms;
private Kingdom rulingKingdom;
private Universe(@NotNull Set<Kingdom> kingdoms) {
Objects.requireNonNull(kingdoms);
this.kingdoms = kingdoms;
}
public static Universe getInstance() {
if (universe == null) {
synchronized (Universe.class) {
Universe.universe = new Universe(new HashSet<>(IOUtils.getAllKingdoms()));
}
}
return universe;
}
public Kingdom getRulingKingdom() {
return this.rulingKingdom;
}
public void setRulingKingdom(@NotNull Kingdom kingdom) {
Objects.requireNonNull(kingdom, ErrorMessages.RULING_KINGDOM_NOT_NULL_ERROR_MESSAGE);
this.rulingKingdom = kingdom;
}
public Set<Kingdom> getKingdoms() {
return this.kingdoms;
}
public Kingdom getKingdom(String name) {
return this.kingdoms.stream()
.filter(kingdom -> kingdom.name.equals(name))
.findFirst()
.orElseThrow(() -> new RuntimeException(String.format(ErrorMessages.KINGDOM_NOT_FOUND_ERROR_MESSAGE_FORMAT, name)));
}
}
</code></pre>
<pre><code>public class PostService {
private final AddressRegistry addressRegistry;
public PostService(@NotNull Collection<Kingdom> kingdoms) {
Objects.requireNonNull(kingdoms, ErrorMessages.KINGDOMS_NOT_NULL_ERROR_MESSAGE);
this.addressRegistry = new AddressRegistry(kingdoms);
}
public Message exchange(Message message) {
Kingdom to = this.addressRegistry.getKingdomFromAddress(message.to);
return to.allyRequest(message);
}
public String getEmblemFor(String name) {
return this.addressRegistry.getKingdomFromAddress(name).emblem;
}
}
</code></pre>
<pre><code>class AddressRegistry {
private final Map<String, Kingdom> registry;
AddressRegistry(Collection<Kingdom> kingdoms) {
this.registry = kingdoms.stream()
.collect(Collectors.toMap(kingdom -> kingdom.name, Function.identity()));
}
Kingdom getKingdomFromAddress(String address) {
return this.registry.get(address);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T09:31:46.690",
"Id": "472678",
"Score": "1",
"body": "With regards to the following: \" I'm not sure how to paste all of that code in here, is it ok to share a Github link?\" The code to be reviewed must be [present in the question.](//codereview.meta.stackexchange.com/q/1308) Please add the code you want reviewed in your question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T09:53:20.837",
"Id": "472682",
"Score": "0",
"body": "I have added all the classes that are to be reviewed"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T09:59:04.333",
"Id": "472683",
"Score": "2",
"body": "That's a good start, thank you. The point is that the question should stand on its own. So the problem description and all relevant code should be posted in the question itself, not behind links. If it's behind a link, it's not up for review."
}
] |
[
{
"body": "<p>Thanks for sharing your code.</p>\n\n<p>I just took a short look at it and this are my thoughts:</p>\n\n<h1>Avoid the <em>Java Singelton Pattern</em></h1>\n\n<p>Your class <code>Universe</code> implements the <em>Java Singelton Pattern</em> and as many others before you fail with that by not taking concurrency into account.\nBut That is not the problem!</p>\n\n<p>The Problem with the <em>Java Singelton Pattern</em> is that it makes the instance of your class <code>Universe</code> a <strong>global variable</strong>. You may have heard before that <em>global variables</em> are considered harmful. (<a href=\"https://algorithmsandme.com/five-reasons-why-not-to-use-global-variables/\" rel=\"nofollow noreferrer\">https://algorithmsandme.com/five-reasons-why-not-to-use-global-variables/</a>) But especially in Java they force <em>tight coupling</em> between the Singelton and its users. They are the opposite of the <em>Open/Closed principle</em>.</p>\n\n<p>Attention: This does not mean that the <em>Singelton as a</em> <strong>concept</strong> is bad. This means that the application (the <em>injection framework</em> by any chance) should assure that only one instance is created at the applications runtime. </p>\n\n<p>For more on this read here:<br>\n<a href=\"https://williamdurand.fr/2013/07/30/from-stupid-to-solid-code/\" rel=\"nofollow noreferrer\">https://williamdurand.fr/2013/07/30/from-stupid-to-solid-code/</a></p>\n\n<h1>duplicated checks</h1>\n\n<p>In your constructors you use <code>@NotNull</code> annotations at the parameters and then you explicitly do a not null check. </p>\n\n<p>Why? Given that your <em>dependency injection framework</em> works properly at the runtime of your application the additional check will never fail...</p>\n\n<p>In you Method <code>Kingdom.setPostService()</code> you even miss to check the parameter the second time an check a member variable instead. This will lead to strange error messages at runtime. </p>\n\n<h1>avoid <em>getter</em> and <em>setter</em> on classes implementing <em>business logic</em></h1>\n\n<p><em>getter</em> and <em>setter</em> should only be used on <em>Data Transfer Objects</em> or <em>Value Objects</em> that only contain data and <strong>no</strong> <em>business logic</em> (at most some very simple validations).</p>\n\n<p>On classes implementing business logic <em>getter</em> and <em>setter</em> are violations of the <em>encapsulation</em> aka <em>information hiding principle</em>.</p>\n\n<hr>\n\n<p><strong>Addendum</strong> </p>\n\n<h1>limit scope of variables</h1>\n\n<p>In <code>Kingdom.allyRequest()</code> you declare <code>response</code> before the <code>try/catch</code> block but you only access it within the <code>try</code> part. You only need this declaration there for the <code>return</code> statement after the <code>catch</code> block. </p>\n\n<p>But doing anything after a <code>catch</code> block is a <em>code smell</em> itself. So you should return the <code>response</code> as the last statement inside the <code>try</code> block. Then you can also move the declaration of the variable <code>response</code> to the line where you actually assign it a value.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T12:54:54.687",
"Id": "473148",
"Score": "1",
"body": "Hey, thanks for your answer. I do have a follow up question though. Is it bad to have Classes that represent data (Model classes) in object oriented design?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T17:19:34.123",
"Id": "473175",
"Score": "0",
"body": "@AditA.Pillai *\"Is it bad to have Classes that represent data (Model classes) in object oriented design?\"* **---** No. In fact it is good. But you should clearly separate \"model Classes\" carrying data from classes that provide *business logic*."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T16:34:52.640",
"Id": "240942",
"ParentId": "240919",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "240942",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T09:02:06.067",
"Id": "240919",
"Score": "1",
"Tags": [
"java",
"object-oriented",
"library"
],
"Title": "GeekTrust: Tame of Thrones OO"
}
|
240919
|
<p>I implemented a class for relationships with the user (deletion, name change, check for existence), I created this class to remove extra logic from the activity class. Could you talk about how my code can be improved?</p>
<pre><code>class UserActionManager @Inject constructor(private val repository : BaseAppRepository,
private val sharedPreferences : JsonSharedPreferences) {
fun editUserName(user: User,newUserName: String) {
Completable.fromAction {
val userObjective:Objective? = sharedPreferences.loadObject(GlobalConstants.OBJECTIVE_SAVE_KEY + user.userName,Objective::class.java)
val userProfile:Profile? = sharedPreferences.loadObject(GlobalConstants.PROFILE_SAVE_KEY + user.userName,Profile::class.java)
sharedPreferences.saveObject<Objective>(GlobalConstants.OBJECTIVE_SAVE_KEY + newUserName, userObjective)
sharedPreferences.saveObject<Profile>(GlobalConstants.PROFILE_SAVE_KEY + newUserName, userProfile)
repository.updateUserName(user.userName, newUserName)
user.userName = newUserName
repository.updateUser(user)
}.subscribeOn(Schedulers.io()).subscribe()
}
fun deleteUser(user: User) {
Completable.fromAction { repository.deleteUser(user) }.subscribeOn(Schedulers.io()).subscribe()
sharedPreferences.saveObject<Objective>(GlobalConstants.OBJECTIVE_SAVE_KEY + user.userName, null)
sharedPreferences.saveObject<Profile>(GlobalConstants.PROFILE_SAVE_KEY + user.userName, null)
}
fun isEmptyUser(userName: String): Single<Boolean> {
return repository.getUserByUserName(userName)
.subscribeOn(Schedulers.io())
.isEmpty
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T11:14:31.757",
"Id": "472835",
"Score": "1",
"body": "Search for kotlin - coroutines. This is the Kotlin-version for RX with a lot of syntactic sugar maybe https://medium.com/@daptronic/migrate-from-rxjava-to-kotlin-coroutines-a-step-by-step-guide-488d039744cc can help"
}
] |
[
{
"body": "<ul>\n<li>Extract your preferences code into extra class or create extension functions to get those objects. Ex. <code>sharedPreferences.loadObject(GlobalConstants.OBJECTIVE_SAVE_KEY + user.userName,Objective::class.java)</code> should have it's own method. Ex. <code>loadUserByName</code>.</li>\n<li>You are using kotlin, use it's strengths like non-nullables by default. Does <code>repository.updateUserName()</code> really accept nullables? That seems wrong. I'd use it for example with elvis operator <code>loadUserByName(user.username) ?: error(\"username not found\")</code></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-11T20:53:11.850",
"Id": "242097",
"ParentId": "240923",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "242097",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T09:57:51.617",
"Id": "240923",
"Score": "2",
"Tags": [
"android",
"kotlin",
"rx-java"
],
"Title": "Class for user actions"
}
|
240923
|
<p>This is my solution for the Credit problem on CS50's (Introduction to CS course) Pset1. It involves using Luhn's Algorithm to test the validity of the Credit Card Number entered and based on a few conditions attempts to identify the Credit Card Company.</p>
<p><code>check_length</code> attempts to find the length of the number entered. <code>check_company</code> attempts to ID the company. <code>check_luhn</code> validates the number based on Luhn's Algorithm.</p>
<p>Lunh's Algorithm:</p>
<p>The formula verifies a number against its included check digit, which is usually appended to a partial account number to generate the full account number. This number must pass the following test:</p>
<p>From the rightmost digit and moving left, double the value of every second digit. If the result of this doubling operation is greater than 9 (e.g., 8 × 2 = 16), then add the digits of the result (e.g., 16: 1 + 6 = 7, 18: 1 + 8 = 9) or, alternatively, the same final result can be found by subtracting 9 from that result (e.g., 16: 16 − 9 = 7, 18: 18 − 9 = 9).
Take the sum of all the digits.
If the total modulo 10 is equal to 0 (if the total ends in zero) then the number is valid according to the Luhn formula; otherwise it is not valid.
I am not very comfortable with the so many if-else conditions. I'd like to know if they can be eliminated. Any other changes are also welcome.</p>
<pre><code>#include <stdio.h>
#include <cs50.h>
#include <stdbool.h>
int check_length(long);
void check_company(int,long);
bool check_luhn(long,int);
int length;
int main(void)
{
long c = get_long("Enter Credit Card Number: ");
check_length(c);
check_luhn(c,length);
if(check_luhn(c,length)==true)
{
check_company(length,c);
}
else printf("INVALID\n");
}
int check_length(long w)
{
for(int i=12;i<16;i++)
{
long power = 1;
for (int k=1;k<i+1;k++)
{
power = power * 10;
}
int scale = w/power;
if (scale<10 && scale>0)
{
length = i+1;
}
}
return length;
}
void check_company(int x,long z)
{
if(x == 15)
{
int y = z/10000000000000; //z/10^13
if(y==34||y==37)
{
printf("AMEX\n");
}
else
{
printf("INVALID\n");
}
}
else if(x==13)
{
int y = z/100000000000; //z/10^11
if(y==4)
{
printf("VISA\n");
}
}
else if(x==16)
{
int q = z/1000000000000000;
int y = z/100000000000000;
if(y==51||y==52||y==53||y==54||y==55)
{
printf("MASTERCARD\n");
}
else
if(q==4)
{
printf("VISA\n");
}
else printf("INVALID\n");
}
else printf("INVALID\n");
}
bool check_luhn(long a,int b)
{
int f = 0;
int j=0;
for(int d=1;d<b+1;d++)
{
int e = a%10;
a = a/10;
if(d%2==1)
{
f = f+e;
}
else
{
int m = 2*e;
int g = m%10;
int h = m/10;
j = j+g+h;
}
}
int l = j + f;
if(l%10==0)
{
return true;
}
else return false;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T12:10:41.677",
"Id": "472691",
"Score": "6",
"body": "Why the focus on the line count? Can you tell us more about the challenge you completed? Questions should stand on their own, with all relevant information included."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T14:34:39.240",
"Id": "472705",
"Score": "2",
"body": "Please add a brief description of Luhn's Algorithm. We don't know what CS50 is and don't have access to it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T03:36:38.280",
"Id": "472779",
"Score": "1",
"body": "@Mast Thanks for the comment. I want to know if the code can be made simpler. I wasn't very comfortable because I'd used a lot of if-else statements. I'd like to minimze those. Any other changes would be welcome. This was not a challenge, it was a problem on an introductory CS course."
}
] |
[
{
"body": "<p>Instead of all the if-else statements, you could use a switch statement, like so:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>switch (x) {\n case 15:\n int y = z/10000000000000;\n if (y==34||y==37)\n ...\n ...\n ...\n break;\n case 13:\n...\n...\n...\n default:\n printf(\"INVALID\\n\");\n}\n</code></pre>\n\n<p>Also to make your code look cleaner, eliminate any curly brackets around <code>if</code> statements that execute only one statement, for example,</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>if (l%10==0)\n{\n return true;\n}\n</code></pre>\n\n<p>could be:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>if (l%10==0) return true;\n</code></pre>\n\n<p>Additionally, instead of</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>if (y==51||y==52||y==53||y==54||y==55)\n</code></pre>\n\n<p>use</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>if (y>=51&&y<=55)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T10:55:03.823",
"Id": "473134",
"Score": "1",
"body": "Optionally OP could `return (l%10==0)`, this would eliminate the else"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T10:40:50.883",
"Id": "241131",
"ParentId": "240924",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T11:54:28.463",
"Id": "240924",
"Score": "1",
"Tags": [
"c"
],
"Title": "Verify a credit card with Luhn"
}
|
240924
|
<p>I have designed this by using the stack data structure (similar to balanced parentheses problem) checking if the previous element is decreasing the number or not.</p>
<pre><code>package test;
import main.algorithms.RomanConversion;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class RomanConversionTest {
RomanConversion romanConversion;
@Before
public void setUp(){
romanConversion = new RomanConversion();
}
@Test
public void testRomanConversion(){
Assert.assertEquals(154, romanConversion.convert("CLIV"));
Assert.assertEquals(101, romanConversion.convert("CI"));
Assert.assertEquals(43, romanConversion.convert("XLIII"));
}
}
package main.algorithms;
import java.util.HashMap;
import java.util.Stack;
public class RomanConversion {
public HashMap createMap(){
HashMap<String, Integer> romanMap = new HashMap<>();
romanMap.put("I" , 1);
romanMap.put("IV",4);
romanMap.put("V" ,5);
romanMap.put("IX",9);
romanMap.put("X" ,10);
romanMap.put("XL",40);
romanMap.put("L" ,50);
romanMap.put("XC",90);
romanMap.put("C" ,100);
romanMap.put("CD",400);
romanMap.put("D" ,500);
romanMap.put("CM",900);
romanMap.put("M" ,1000);
return romanMap;
}
public int convert(String letter) {
int result=0;
HashMap<String, Integer> map = new HashMap<>();
map = createMap();
String str;
char[] array = letter.toCharArray();
Stack<Character> stack = new Stack<>();
for(char c: array){
if(stack.isEmpty()){
result += map.get(String.valueOf(c));
stack.push(c);
}else{
char lastElement= stack.peek();
if(map.containsKey(lastElement+""+c)) {
result -= map.get(String.valueOf(lastElement));
result += map.get(String.valueOf(lastElement) + String.valueOf(c));
stack.push(c);
}else{
result += map.get(String.valueOf(c));
stack.push(c);
}
}
}
return result;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T15:28:29.017",
"Id": "472713",
"Score": "1",
"body": "I'd create the romanMap in the class constructor, so it's only created once. Call the createMap method from the class constructor. And yes, the map result would be a class variable."
}
] |
[
{
"body": "<p>I think your code is - in general - good. Your algorithm is working correctly and I really like the idea of using a Hashmap to save the values of the roman numbers.</p>\n\n<hr>\n\n<p>One thing I miss is the handling of edge cases. Especially you should think about the following edge cases:</p>\n\n<ul>\n<li>letter == null</li>\n<li>Empty String</li>\n<li>Strings that aren't valid roman numbers (for example \"IXI\" or \"MMMM\" aren't valid)</li>\n</ul>\n\n<p>The first two problems are pretty easy to solve:</p>\n\n<pre><code>if(letter == null || letter.equals(\"\")) {\n return -1;\n}\n</code></pre>\n\n<p>The third part is a bit more difficult to solve:</p>\n\n<pre><code>if(!letter.matches(\"M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$\")) {\n return -1;\n}\n</code></pre>\n\n<p>As you can see, you can use a regular expression to validate if the string <code>letter</code> contains a valid roman number (as explained for example <a href=\"https://stackoverflow.com/a/267405\">here</a>).</p>\n\n<hr>\n\n<p>One thought about your testing-class: You are using <code>JUnit</code>, which is good, but I think you are testing much too little (remember the edge cases!). </p>\n\n<p>I wrote a test myself with the following values:</p>\n\n<pre><code>String[] input = {null, \"\", \"I\", \"V\", \"XXXIII\", \"DCCXLVII\", \"CMXXIX\", \"MCCXXXII\", \"MMMCMXCIX\", \"MMMMXI\", \"KMXI\", \"VX\", \"VL\", \"VC\", \"VD\", \"VM\",\"LC\", \"LD\", \"LM\", \"DM\", \"IL\", \"IC\", \"ID\", \"IM\", \"XD\", \"XM\", \"CXLV\", \"MIXI\", \"IXI\", \"MXIII\", \"MMMM\", \"IIII\"}; \n\nint[] expectedOutput = {-1, -1, 1, 5, 33, 747, 929, 1232, 3999, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 145, -1, -1, 1013, -1, -1};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T13:53:42.400",
"Id": "472863",
"Score": "0",
"body": "\"MMMM\" is 4000, unless I'm missing something?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T14:32:11.827",
"Id": "472872",
"Score": "0",
"body": "No, MMMM is not valid because in roman numbers there are only three same letters in a row allowed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T14:40:59.613",
"Id": "472875",
"Score": "0",
"body": "So what is 4000?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T14:42:09.150",
"Id": "472876",
"Score": "0",
"body": "Well, 3999 is the highest roman number if you follow these strict rules!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T15:16:45.063",
"Id": "472881",
"Score": "0",
"body": "Fair enough, I assume the Romans had some way around that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T22:10:25.943",
"Id": "472947",
"Score": "0",
"body": "There is no strict rule like \"only three same letters in a row allowed\". `IIII` and `XXXX` are completely valid representations of 4 and 40. And there have been historical cases of 5 and even 6 written as `IIIII` and `IIIIII`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T06:27:12.443",
"Id": "472981",
"Score": "0",
"body": "Well, when you are using the widely used \"subtractive\" notation (IX = 9), it just doesn't make sense to say VIIII = 9, because it is longer than IX and it just doesn't make sense to have more than one representation for one number. Also, the Romans themselves started pretty early to write IX instead of VIIII, although I have to admit that these conventions were used widely but not universally."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T17:08:51.063",
"Id": "240946",
"ParentId": "240925",
"Score": "3"
}
},
{
"body": "<h3>Technical</h3>\n\n<ul>\n<li>The local variable <code>String str</code> is never used eirhin method <code>convert</code>. So can be removed.</li>\n<li>Since the map is not supposed to change, make it a <code>static final</code> field, initialized directly or in static constructor.</li>\n</ul>\n\n<h3>Stylistic</h3>\n\n<ul>\n<li>Central method not only <em>converts</em>, rather than <em>parses</em> a string representation (using a predifined rule set/grammar). So would rename it to more expressive <code>parseRomanNumeral</code> or <code>parseToInt</code> or similar.</li>\n</ul>\n\n<h3>Current Approach: Add Values & Undo</h3>\n\n<p>You are using the concept of a <strong>lookup-table</strong> implemented as map of symbols. This solves mainly the translation of roman symbols to arabic numbers (note: <em>whole number values</em> that can be added; not <em>single numeric digits</em> that represent an 10-based exponential magnitude).</p>\n\n<p>The fact that two sorts of <em>special numbers</em> (i.e. 4, 9; 40, 90; 400, 900) can be represented by two symbols is solved by the <strong>stack memory structure</strong> that allows to memorize the last character (single push and pop, stack size = 1). This memo will serve like an <strong>undo operation</strong>, that will reduce the running sum by its previous addition in order to correctly add the <em>special number</em> (e.g. if signaling <code>V</code> translated to 5 then previously added <code>I</code> translated to 1 will be subtracted, in order to add 4).</p>\n\n<p>That 2 data-structures (<em>map</em> and <em>stack</em>) used by 2 behavioural concepts (<em>lookup</em> and <em>undo</em>) form the \"meat\", whereas iterating char by char, adding translated values left as the \"bones\" (algorithmic skeleton).</p>\n\n<p>The stack is not needed since all symbols of the input string can be accessed by their position in char-array.</p>\n\n<h3>Alternative: Grammar for Calculating Numbers</h3>\n\n<p>What if you think of <a href=\"https://en.m.wikipedia.org/wiki/Roman_numerals\" rel=\"nofollow noreferrer\">roman numerals</a> as a, numerical system, formed by a <strong>grammar</strong> for <strong>calculating</strong> numberical values, which form the <em>vocabulary</em>:</p>\n\n<ol>\n<li>The vocabulary of roman symbols (<code>I</code>,<code>V</code>) can be translated to numbers (1, 5). </li>\n<li>The grammar consists of rules for <em>adding</em> (<code>III</code> = <code>1+1+1</code>) or <em>subtracting</em> (<code>IV</code> = <code>-1+5</code>) values. </li>\n<li>each symbol belongs to a <strong>group of unit or magnitude</strong> (ones 10^1, hundreds 10^2, thousands 10^3) wich require to be in a <strong>specific sequence</strong> in order to form a <em>valid</em> roman numeral. Generally from higher to lower magnitude (e.g. <code>MCDVI</code>), except the special cases of powers-to-4 (e.g. <code>CMIV</code>).</li>\n<li>Dependent on the symbol's valid position within its magnitude the mathematical operands are evaluated (either plus or minus).</li>\n<li>There is also a limit of maximum consecutives for each symbol, = 3 (e.g. <code>III</code> for 3, but not more, because 4 is <code>IV</code>)</li>\n<li>Iteratively translated symbols may be used to build a valid <strong>mathematical sum-expression</strong> (e.g. <code>-100 +1000 -1 +5</code>).</li>\n<li>The resulting sum will be the finaly parsed integer (e.g. 904).</li>\n</ol>\n\n<h3>Edge cases</h3>\n\n<p>Validation is done by rules inherent to the roman numerical system (some explained above).\nThere is also a symbol for zero : <code>N</code> used standalone.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T11:12:16.020",
"Id": "240999",
"ParentId": "240925",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "240946",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T12:00:33.980",
"Id": "240925",
"Score": "1",
"Tags": [
"java",
"roman-numerals"
],
"Title": "Roman Numeral Conversion in Java"
}
|
240925
|
<p>As I added more features to my chess game, such as an endgame screen. I eventually ended up having a lot of duplicate code, and complex logic with lots of nested if statements in loops. The usual advice is to add more functions, but I cannot think of ways to reorganise this code such that each part has a highly specific role so that it can be turned into a function. I also could try to split this over multiple event listeners, but that may become too complicated.</p>
<p>If any extra pieces of code, or clarification about the question is needed, feel free to ask.</p>
<p>Here is the code:</p>
<pre><code>let movedCastlesAndKings = {
hasWKMoved: false,
hasWKSCMoved: false,
hasWQSCMoved: false,
hasBKMoved: false,
hasBKSCMoved: false,
hasBQSCMoved: false
};
let castlingPerms = {
WKSC: false,
WQSC: false,
BKSC: false,
BQSC: false
};
let boardHistory = [];
let lastDoubledPawnMove, enpassantSquare;
let humanPlayer = "w";
let humanPieces = WP;
let AIPlayer = "b";
let AIPieces = BP;
let currentPlayer = humanPlayer;
let currentPieces = humanPieces;
let movesForThisPiece, clickPosition, currentPlayerKingPosition, isCurrentPlayerInCheck, promotedPawnPosition;
let isCheckMate, hashIndex, isHighlightSquare, isHighlightPossibleMoves, hasClickedBefore, oppositePlayer, elementToEdit;
let legalMoves = generateLegalMoves(enpassantSquare, castlingPerms, initKingPosition, board, "w");
let lastMoveFromAndToSQ = {
from: undefined,
to: undefined
}
let threatningPieces = [];
function updateGameLoop(event) {
clickPosition = getBoardCellFromClick(event);
if (!hasClickedBefore) {
if (clickPosition.x < 8 && clickPosition.y < 8) {
boardItem = board[clickPosition.y][clickPosition.x];
if (boardItem != " ") isHighlightSquare = true;
if (currentPieces.includes(board[clickPosition.y][clickPosition.x])) {
moves = generateMovesForThisPiece(legalMoves, clickPosition);
isHighlightPossibleMoves = true;
}
hasClickedBefore = true;
}
} else {
if (isHighlightPossibleMoves) {
let moveItem, toSQ;
for (move = 0; move < moves.length; move++) {
moveItem = moves[move];
toSQ = moveItem.to;
if (toSQ.x == clickPosition.x && toSQ.y == clickPosition.y) {
board = moveItem.node;
switchSides();
currentPlayer == "w" ? oppositePlayer = "b" : oppositePlayer = "w";
promotedPawnPosition = findPromotedPawns(board, oppositePlayer);
if (promotedPawnPosition) {
if (oppositePlayer == "w" ) {
document.getElementById("whitePromotionSelection").style.display = "inline";
} else {
document.getElementById("blackPromotionSelection").style.display = "inline";
}
window.promotePawns = function (piece) {
board[promotedPawnPosition.y][promotedPawnPosition.x] = piece;) {
document.getElementById("whitePromotionSelection").style.display = "none";
} else {
document.getElementById("blackPromotionSelection").style.display = "none";
}
currentPlayerKingPosition = findKing(board, currentPlayer);
movedCastlesAndKings = updateMovedCastlesAndKings(movedCastlesAndKings, board);
enpassantSquare = getEnpassantSquare(moveItem.doublePawnMove, board, currentPlayer);
castlingPerms = castlingPermissions(movedCastlesAndKings, board);
hashIndex = makeHashTableIndex(castlingPerms, enpassantSquare, board, currentPlayer);
legalMoves = generateLegalMoves(enpassantSquare, castlingPerms, currentPlayerKingPosition, board, currentPlayer);
lastMoveFromAndToSQ.from = moveItem.from;
lastMoveFromAndToSQ.to = toSQ;
threatningPieces = getThreatningPieces(board, currentPlayer);
isCurrentPlayerInCheck = isSquareUnderAttack(currentPlayerKingPosition, board, currentPlayer);
isCheckMate = isCheckmate(legalMoves.length, isCurrentPlayerInCheck);
if (isCheckMate && currentPlayer == humanPlayer) {
document.getElementById("gameover").style.display = "inline";
document.removeEventListener('click', updateGameLoop);
}
promotedPawnPosition = undefined;
}
} else {
currentPlayerKingPosition = findKing(board, currentPlayer);
movedCastlesAndKings = updateMovedCastlesAndKings(movedCastlesAndKings, board);
enpassantSquare = getEnpassantSquare(moveItem.doublePawnMove, board, currentPlayer);
castlingPerms = castlingPermissions(movedCastlesAndKings, board);
hashIndex = makeHashTableIndex(castlingPerms, enpassantSquare, board, currentPlayer);
legalMoves = generateLegalMoves(enpassantSquare, castlingPerms, currentPlayerKingPosition, board, currentPlayer);
lastMoveFromAndToSQ.from = moveItem.from;
lastMoveFromAndToSQ.to = toSQ;
threatningPieces = getThreatningPieces(board, currentPlayer);
isCurrentPlayerInCheck = isSquareUnderAttack(currentPlayerKingPosition, board, currentPlayer);
isCheckMate = isCheckmate(legalMoves.length, isCurrentPlayerInCheck);
if (isCheckMate && currentPlayer == humanPlayer) {
document.getElementById("gameover").style.display = "inline";
document.removeEventListener('click', updateGameLoop);
}
}
break;
}
}
}
isHighlightPossibleMoves = false;
isHighlightSquare = false;
hasClickedBefore = false;
}
}
<span class="math-container">````</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T14:16:01.733",
"Id": "472703",
"Score": "0",
"body": "`board[promotedPawnPosition.y][promotedPawnPosition.x] = piece;) {` looks like a typo, there's no `(` to end with `)`, did you miss a character or a line?"
}
] |
[
{
"body": "<p>You declare a lot of variables up front. It's a <a href=\"https://softwareengineering.stackexchange.com/a/388055\">good idea to constrain a variable's scope as much as possible</a>. If a variable is declared at some block level, make sure it's required at that level (like with <code>hasClickedBefore</code>, which needs to be persistent) - otherwise, it'll be easier to read the code if the variable is only declared and used in the inner block that it's used in. Having large numbers of separate variables declared at a certain point means that much more cognitive overhead required when reading the code later. To take one example, rather than:</p>\n\n<pre><code>let clickPosition;\nfunction updateGameLoop(event) {\n clickPosition = getBoardCellFromClick(event);\n // do stuff with clickPosition\n</code></pre>\n\n<p>Consider instead, if <code>clickPosition</code> isn't being used elsewhere:</p>\n\n<pre><code>function updateGameLoop(event) {\n const clickPosition = getBoardCellFromClick(event);\n // do stuff with clickPosition\n</code></pre>\n\n<p>Another benefit of this is that it allows you to declare variables with <code>const</code>, which is far preferable to <code>let</code> whenever possible. (<code>const</code> does not permit reassignment, unlike <code>let</code> - so, when you declare a variable with <code>const</code>, you'll always be certain of what it refers to without having to search through all intervening lines to make sure it didn't get reassigned to something else somewhere)</p>\n\n<p>Whenever you have a large number of ending brackets <code>}</code> at the end of a script, <em>often</em> that's a sign that things can be refactored to make things more readable. Here, instead of an <code>if</code> followed by a very long <code>else</code>, consider an <code>if</code> which <code>return</code>s at the end - that way, there's no need for a separate block for the <code>else</code>. So, this:</p>\n\n<pre><code>function updateGameLoop(event) {\n clickPosition = getBoardCellFromClick(event);\n if (!hasClickedBefore) {\n // handle first click\n } else {\n if (isHighlightPossibleMoves) {\n // lots and lots of code\n }\n\n isHighlightPossibleMoves = false;\n isHighlightSquare = false;\n hasClickedBefore = false;\n }\n}\n</code></pre>\n\n<p>can turn into:</p>\n\n<pre><code>function updateGameLoop(event) {\n clickPosition = getBoardCellFromClick(event);\n if (!hasClickedBefore) {\n // handle first click\n return;\n }\n // these 3 variables aren't used elsewhere below, might as well reassign them now:\n isHighlightSquare = false;\n hasClickedBefore = false;\n if (!isHighlightPossibleMoves) {\n return;\n }\n isHighlightPossibleMoves = false;\n // lots and lots of code\n // or even better, a function call instead here\n}\n</code></pre>\n\n<p>You do</p>\n\n<pre><code>boardItem = board[clickPosition.y][clickPosition.x];\nif (boardItem != \" \") isHighlightSquare = true;\nif (currentPieces.includes(board[clickPosition.y][clickPosition.x])) {\n</code></pre>\n\n<p>Since <code>boardItem</code> has already retrieved the item at that position, might as well use that instead of looking it up again:</p>\n\n<pre><code>boardItem = board[clickPosition.y][clickPosition.x];\nif (boardItem !== \" \") isHighlightSquare = true;\nif (currentPieces.includes(boardItem)) {\n</code></pre>\n\n<p>Since you're using ES6+ syntax (which is great!), you can replace the ugly manual iteration required by an ordinary <code>for</code> loop with <code>for..of</code>, it's much cleaner:</p>\n\n<pre><code>for (const moveItem of moves) {\n</code></pre>\n\n<p>But, since you're trying to find an item in the array which matches a condition, <code>Array.prototype.find</code> would be even better. (see below for full code)</p>\n\n<p>The conditional operator probably shouldn't be abused as a replacement for <code>if</code>/<code>else</code> (the below will also throw the linting error <a href=\"https://eslint.org/docs/2.0.0/rules/no-unused-expressions\" rel=\"nofollow noreferrer\">no-unused-expressions</a>):</p>\n\n<pre><code>currentPlayer == \"w\" ? oppositePlayer = \"b\" : oppositePlayer = \"w\";\n</code></pre>\n\n<p>You <em>can</em> use the conditional operator here, by putting <code>oppositePlayer</code> on the left:</p>\n\n<pre><code>oppositePlayer = currentPlayer === 'w' ? 'b' : 'w';\n</code></pre>\n\n<p>You could also consider making toggling between players easier by using a boolean instead, eg <code>currentPlayerIsWhite = true</code>.</p>\n\n<p>(Remember to use strict equality with <code>===</code>, not <code>==</code> - <code>==</code> behaves <a href=\"https://stackoverflow.com/q/359494\">pretty strangely</a> when comparing expressions of different types. Even if you happen not to be working with different types, the use of <code>==</code> will <em>worry</em> people that you may be doing so.)</p>\n\n<p>You can save a reference to the selected <code>whitePromotionSelection</code> elements instead of selecting them twice to be more DRY. (<code>const whitePromotionSelection = document.getElementById(\"whitePromotionSelection\")</code>). Or, even better - it seems likely that you have a typo there with <code>board[promotedPawnPosition.y][promotedPawnPosition.x] = piece;) {</code>, and that you want to set the piece on the board, then either change <code>whitePromotionSelection</code> or <code>blackPromotionSelection</code>, depending on who the active player is. If this is the case, then use the conditional operator upfront to identify which element needs to be displayed inline / hidden (see below).</p>\n\n<p>Now, for the most important part: most of the code in the <code>window.promotePawns</code> and the next <code>else</code> block is identical. Put the identical parts into a function instead, and call that function twice instead of writing the code again. That part of the code handles checking the state of the game after a move is finished, so maybe call it <code>handlePostMove</code>. Putting it all together:</p>\n\n<pre><code>function updateGameLoop(event) {\n const clickPosition = getBoardCellFromClick(event);\n\n if (!hasClickedBefore) {\n if (clickPosition.x < 8 && clickPosition.y < 8) {\n const boardItem = board[clickPosition.y][clickPosition.x];\n if (boardItem !== \" \") isHighlightSquare = true;\n if (currentPieces.includes(boardItem)) {\n moves = generateMovesForThisPiece(legalMoves, clickPosition);\n isHighlightPossibleMoves = true;\n }\n hasClickedBefore = true;\n }\n return;\n }\n isHighlightSquare = false;\n hasClickedBefore = false;\n if (!isHighlightPossibleMoves) {\n return;\n }\n isHighlightPossibleMoves = false;\n // Use `.find` here, instead of a `for` loop:\n const moveItem = moves.find((moveItem) => {\n const toSQ = moveItem.to;\n return toSQ.x === clickPosition.x && toSQ.y === clickPosition.y;\n });\n if (!moveItem) {\n return;\n }\n const toSQ = moveItem.to;\n board = moveItem.node;\n switchSides();\n\n oppositePlayer = currentPlayer === 'w' ? 'b' : 'w';\n promotedPawnPosition = findPromotedPawns(board, oppositePlayer);\n\n const handlePostMove = () => {\n currentPlayerKingPosition = findKing(board, currentPlayer);\n movedCastlesAndKings = updateMovedCastlesAndKings(movedCastlesAndKings, board);\n enpassantSquare = getEnpassantSquare(moveItem.doublePawnMove, board, currentPlayer);\n castlingPerms = castlingPermissions(movedCastlesAndKings, board);\n hashIndex = makeHashTableIndex(castlingPerms, enpassantSquare, board, currentPlayer);\n legalMoves = generateLegalMoves(enpassantSquare, castlingPerms, currentPlayerKingPosition, board, currentPlayer);\n\n lastMoveFromAndToSQ.from = moveItem.from;\n lastMoveFromAndToSQ.to = toSQ;\n threatningPieces = getThreatningPieces(board, currentPlayer);\n isCurrentPlayerInCheck = isSquareUnderAttack(currentPlayerKingPosition, board, currentPlayer);\n isCheckMate = isCheckmate(legalMoves.length, isCurrentPlayerInCheck);\n\n if (isCheckMate && currentPlayer === humanPlayer) {\n document.getElementById(\"gameover\").style.display = \"inline\";\n document.removeEventListener('click', updateGameLoop);\n }\n };\n if (!promotedPawnPosition) {\n handlePostMove();\n return;\n }\n // promotedPawnPosition is true:\n const promotionSelection = document.getElementById(oppositePlayer === \"w\" ? \"whitePromotionSelection\" : 'blackPromotionSelection');\n promotionSelection.style.display = \"inline\";\n\n window.promotePawns = function (piece) {\n board[promotedPawnPosition.y][promotedPawnPosition.x] = piece;\n promotionSelection.style.display = \"none\";\n handlePostMove();\n promotedPawnPosition = undefined;\n };\n}\n</code></pre>\n\n<p>You could also consider splitting up the larger chunks of the game loop into separate functions. A 70 line function, while better than a 96 line function, is still a bit smelly. Maybe make a function for the <code>!hasClickedBefore</code> block, and one for handling a found move item (everything below the <code>.find</code>), and one for handling a pawn promotion.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T14:42:42.663",
"Id": "240933",
"ParentId": "240927",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "240933",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T13:23:22.750",
"Id": "240927",
"Score": "0",
"Tags": [
"javascript",
"event-handling",
"chess"
],
"Title": "Cleaning up Javascript event listener that manages game-loop"
}
|
240927
|
<p><strong>Details:</strong></p>
<p>I have a code, which does the following:</p>
<ul>
<li>Get data from CSV and insert it into MySQL table</li>
<li>Get data from SQL Server and insert it into MySQL table</li>
<li>Run this code every 240 seconds - to refresh the data, in order to have up to date infromation.</li>
</ul>
<p>I'd like to know whether the code below, I am about to provide, can be improved? In terms of performance and whether the code is readable or anything can be changed.</p>
<pre><code>import pyodbc
import csv
import mysql.connector
import time
#MySQL connection
MySQLdb = mysql.connector.connect(
host="SVR",
user="root",
passwd="",
database="production"
)
#SQL Sevrer
sqlServerData = pyodbc.connect(
"Driver={SQL Server Native Client 11.0};"
"Server=svr;"
"Database=SQL_Server;"
"Trusted_Connection=yes;")
input("Press Enter to continue...")
starttime=time.time()
while True:
try:
print("---START---")
#MySQL cursor
MySQLtruncateCSV = MySQLdb.cursor()
MySQLtruncateSQL_Server = MySQLdb.cursor()
MySQLcursor = MySQLdb.cursor()
MySQLcursor2 = MySQLdb.cursor()
#SQL Server Cursor
SqlData = sqlServerData.cursor()
#Truncate MySQL Tables
CSVTruncate = 'Truncate CSV;'
SQL_ServerTruncate = 'Truncate SQL_Server;'
print("Truncate Table CSV...")
#CSV table
MySQLtruncateCSV.execute(CSVTruncate)
MySQLtruncateCSV.close()
MySQLdb.commit()
print("Truncate Table SQL_Server...")
#SQL_Server table
MySQLtruncateSQL_Server.execute(SQL_ServerTruncate)
MySQLtruncateSQL_Server.close()
MySQLdb.commit()
print("Receiving data from CSV...")
print("Sending to MySQL..")
#Insert CSV file into MySQL database
with open('G:/Technical/Labels/Production/Data/CSVExport.csv', 'r') as f:
data = csv.reader(f)
next(data, None) #Skip header
for row in data:
MySQLcursor.execute('insert into CSV (customer_code,customer_logo, product_code,product_description,allergen_info, barcode_inner,barcode_outer) VALUES (%s,%s,%s,%s,%s,%s,%s);', row)
MySQLdb.commit()
MySQLcursor.close()
print("Receiving SQL_Server data...")
#Get data from SQL_Server
SqlData.execute("select p.id, p.code,p.description, p.searchRef1, so.number, c.code, c.name \
from salesorderline sol join \
salesorder so \
on sol.salesorderid = so.id join \
product p \
on sol.productid = p.id join \
customer c \
on so.customerid = c.id \
where so.orderdate > dateadd(dd,-10,cast(getdate() as date));")
print("Sending to MySQL..")
#Send SQL_Server data into MySQL
for x in SqlData.fetchall():
a,b,c,d,e,f,g = x
MySQLcursor2.execute("insert into SQL_Server (product_id, product_code, product_description, product_weight, \
salesorder_number, customer_code, customer_name) values (%s,%s,%s,%s,%s,%s,%s);", (a,b,c,d,e,f,g))
SqlData.close()
MySQLdb.commit()
MySQLcursor2.close()
print("---END---")
time.sleep(240 - ((time.time() - starttime) % 240))
except:
print("An error has occured.. Please contact Technical")
break
</code></pre>
|
[] |
[
{
"body": "<h2>Externalize your connection strings</h2>\n\n<p>This information:</p>\n\n<pre><code> host=\"SVR\",\n user=\"root\",\n passwd=\"\",\n database=\"production\"\n\n \"Driver={SQL Server Native Client 11.0};\"\n \"Server=svr;\"\n \"Database=SQL_Server;\"\n \"Trusted_Connection=yes;\")\n\n'G:/Technical/Labels/Production/Data/CSVExport.csv'\n</code></pre>\n\n<p>should not be baked into your program, for multiple reasons:</p>\n\n<ul>\n<li>configurability and maintainability</li>\n<li>security</li>\n</ul>\n\n<p>Put these into a configuration file, a command-line argument, or an environmental variable.</p>\n\n<h2>Typo</h2>\n\n<p><code>#SQL Sevrer</code> -> <code>#SQL Server</code></p>\n\n<h2>Context management</h2>\n\n<p>Doing a search through the <a href=\"https://github.com/mysql/mysql-connector-python/search?q=__exit__&unscoped_q=__exit__\" rel=\"nofollow noreferrer\">MySQL Connector Python source code</a> as well as their <a href=\"https://bugs.mysql.com/bug.php?id=89113\" rel=\"nofollow noreferrer\">bug tracker</a>, it seems that the library has a deficiency where cursors cannot be used as context managers. You can do the next-best thing: <code>try</code>/<code>finally</code> whenever you make a connection or cursor that needs to be closed, or (probably better) make your <a href=\"https://docs.python.org/3.8/library/contextlib.html#contextlib.contextmanager\" rel=\"nofollow noreferrer\">own small context manager utilities</a> for such cases.</p>\n\n<p>The situation for <code>pyodbc</code> <a href=\"https://stackoverflow.com/a/3783252/313768\">seems to be better</a>. Connections and cursors should be used in <code>with</code> statements.</p>\n\n<p>In all cases you should prefer this to explicit <code>close()</code> calls.</p>\n\n<h2>Multi-line strings</h2>\n\n<p>Since this is SQL:</p>\n\n<pre><code> SqlData.execute(\"select p.id, p.code,p.description, p.searchRef1, so.number, c.code, c.name \\\n from salesorderline sol join \\\n salesorder so \\\n on sol.salesorderid = so.id join \\\n product p \\\n on sol.productid = p.id join \\\n customer c \\\n on so.customerid = c.id \\\n where so.orderdate > dateadd(dd,-10,cast(getdate() as date));\")\n</code></pre>\n\n<p>Indentation does not matter. Your current string literal includes indentation, and it might as well stay that way but losing the continuation escapes and using a multi-line string:</p>\n\n<pre><code> SqlData.execute(\"\"\"\n select p.id, p.code,p.description, p.searchRef1, so.number, c.code, c.name\n from salesorderline sol\n join salesorder so on sol.salesorderid = so.id\n join product p on sol.productid = p.id\n join customer c on so.customerid = c.id\n where so.orderdate > dateadd(dd,-10,cast(getdate() as date));\n \"\"\")\n</code></pre>\n\n<p>I also think it is clearer and more logical to line-break before the <code>join</code> keyword rather than after, and include the <code>on</code> with its corresponding <code>join</code>.</p>\n\n<h2>Unpacking</h2>\n\n<p>This:</p>\n\n<pre><code>a,b,c,d,e,f,g = x\n</code></pre>\n\n<p>is not helpful. Either give these meaningful names, or don't unpack at all:</p>\n\n<pre><code>MySQLcursor2.execute(\"\"\"\n insert into SQL_Server (\n product_id, product_code, product_description, product_weight,\n salesorder_number, customer_code, customer_name\n ) values (%s,%s,%s,%s,%s,%s,%s);\n \"\"\",\n x\n)\n</code></pre>\n\n<h2>Magic numbers and home-rolled time math</h2>\n\n<p>Do not do this:</p>\n\n<pre><code> time.sleep(240 - ((time.time() - starttime) % 240))\n</code></pre>\n\n<p>It's difficult to understand. I guess 240 seconds is 4 minutes. You're</p>\n\n<ul>\n<li>finding the elapsed time since the start,</li>\n<li>modulating that by 4 minutes? Why?</li>\n<li>subtracting that from 4 minutes.</li>\n</ul>\n\n<p>At a wild guess, what you are trying to do is \"wait until 4 minutes have passed since the start of the program\", which would actually require</p>\n\n<pre><code>from datetime import datetime\nfrom time import sleep\n\nstart_time = datetime.now()\n# ...\n\nelapsed = datetime.now() - start_time\nuntil_4m = (timedelta(minutes=4) - elapsed).total_seconds()\nif until_4m > 0:\n sleep(until_4m)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T15:57:46.560",
"Id": "240938",
"ParentId": "240928",
"Score": "3"
}
},
{
"body": "<p>The <strong>exception handling</strong> is useless as it is currently implemented, because you are not retrieving the full details. Are you going to guess what went wrong ? \nAdd this import at the top of your code:</p>\n\n<pre><code>import traceback\n</code></pre>\n\n<p>And then you can use:</p>\n\n<pre><code>print(f'Exception occured: {traceback.format_exc()}')\n</code></pre>\n\n<p>which will yield more details.</p>\n\n<p>What would be good is having a counter, or keeping track of the latest row ID processed, so you can tell if a row in particular is causing problems.</p>\n\n<p>I am not sure I would have done a script like this, because row by row insertion is slower than a <strong>bulk insert</strong>, for example in MySQL that would be <code>LOAD DATA INFILE</code>. For this you need a user with the FILE privilege. In a controlled (private) environment, this is okay, otherwise think about the security implications.</p>\n\n<p><strong>Naming conventions</strong>: <code>CSV</code> is not a good name for a table, think of something more meaningful, even for a temp table:</p>\n\n<pre><code>CSVTruncate = 'Truncate CSV;'\n</code></pre>\n\n<p><code>SQL_Server</code> is a terrible name too for a table.</p>\n\n<p>Certain <strong>constant values</strong> should be defined as variables and kept at the top of the code eg: <code>'G:/Technical/Labels/Production/Data/CSVExport.csv'</code></p>\n\n<p><strong>Structure</strong> is not great, the program could be more readable. Don't do all the stuff in the main procedure, instead separate functionality by moving code to functions. The CSV import should definitely be a standalone function.\nThat would make the program easier to read and understand, and reduce the risk of <strong>confusion</strong> and bugs.</p>\n\n<p>You need to add more <strong>line spacing</strong> too. For example this code is not pleasant to read:</p>\n\n<pre><code>CSVTruncate = 'Truncate CSV;'\nSQL_ServerTruncate = 'Truncate SQL_Server;'\nprint(\"Truncate Table CSV...\")\n#CSV table\nMySQLtruncateCSV.execute(CSVTruncate)\nMySQLtruncateCSV.close()\nMySQLdb.commit()\nprint(\"Truncate Table SQL_Server...\")\n#SQL_Server table\nMySQLtruncateSQL_Server.execute(SQL_ServerTruncate)\n</code></pre>\n\n<p>You reuse variable names and there is real potential for confusion as exemplified here:</p>\n\n<pre><code>#SQL_Server table\nMySQLtruncateSQL_Server.execute(SQL_ServerTruncate)\n</code></pre>\n\n<p>With names like these it's not immediately clear against which environment you are really running queries.\nSo you should really break up your code in a few dedicated functions, and not mix functionality.</p>\n\n<p>And if your goal is to insert data from SQL Server to Mysql the approach is not ideal I think. It is possible to interconnect different DBMSes with each other.\nFor example with SQL server you can connect to other databases (linked servers), for this you need to install the right drivers and middleware.</p>\n\n<p>Then it is possible to insert data from one table to another, even to another database and server. It is matter of choice, but the idea is worth considering. The choice is whether to spend time on development (+ maintenance & fixing bugs) or spend time on integration.</p>\n\n<p><strong>SQL performance</strong>: this may be the least of your worries now but this query could be improved:</p>\n\n<pre><code>SqlData.execute(\"select p.id, p.code,p.description, p.searchRef1, so.number, c.code, c.name \\\nfrom salesorderline sol join \\\nsalesorder so \\\non sol.salesorderid = so.id join \\\nproduct p \\\non sol.productid = p.id join \\\ncustomer c \\\non so.customerid = c.id \\\nwhere so.orderdate > dateadd(dd,-10,cast(getdate() as date));\")\n product p \\\n on sol.productid = p.id join \\\n customer c \\\n on so.customerid = c.id \\\n where so.orderdate > dateadd(dd,-10,cast(getdate() as date));\")\n</code></pre>\n\n<p>The <code>where</code> clause will not advantage of an <strong>index</strong> on <code>orderdate</code> if there is one. Simply calculate D-10 in your Python code and pass a hard value to your query rather than an expression.</p>\n\n<pre><code>from datetime import datetime, timedelta\nd = datetime.today() - timedelta(days=10)\n\n# this will return: '2020-04-11'\nd.strftime('%Y-%m-%d')\n</code></pre>\n\n<p>When you are doing joins on multiple tables that have lots of records, you can experience performance issues, especially when not taking advantage of the indexes that exist.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T18:51:03.713",
"Id": "240955",
"ParentId": "240928",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "240955",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T13:25:36.887",
"Id": "240928",
"Score": "2",
"Tags": [
"python",
"sql",
"mysql",
"csv",
"sql-server"
],
"Title": "Receive data from SQL and CSV and send it to MySQL database using Python"
}
|
240928
|
<p>My goal: to make the already easy task of filling out an excel sheet 1% easier by putting in hours and hours of effort. On a more serious note, I'm currently developing a system to manage inventory at my work. The following is my attempt to smooth out the process of receiving inventory when it arrives. To help visualize, <a href="https://i.stack.imgur.com/Bacu3.png" rel="noreferrer">here's an example of what the PO sheet might look like</a> (obviously not actual data)</p>
<p>To start with, I took a page (or two, or three, or ten) out of <a href="https://rubberduckvba.wordpress.com/2017/12/08/there-is-no-worksheet/" rel="noreferrer">Rubberduck's book</a> and proxied up my workbook:</p>
<pre><code>Option Explicit
Private Type TProxy
Sheet1 As IInventorySheetProxy
POSheet As IPOSheetProxy
End Type
Private this As TProxy
Public Property Get Sheet1() As IInventorySheetProxy
Set Sheet1 = this.Sheet1
End Property
Public Property Get POSheet() As IPOSheetProxy
Set POSheet = this.POSheet
End Property
Private Sub Class_Initialize()
Set this.Sheet1 = New Sheet1Proxy
Set this.POSheet = New POSheetProxy
End Sub
Private Sub Class_Terminate()
Set this.Sheet1 = Nothing
Set this.POSheet = Nothing
End Sub
</code></pre>
<p>In order to proxy the whole workbook, one must encapsulate the relevant worksheets so <strong>here's what POSheetProxy looks like</strong> (the interface looks exactly how you'd expect):</p>
<pre><code>Option Explicit
Implements IPOSheetProxy
Private Property Get Table() As ListObject
Set Table = Sheet2.ListObjects(1)
End Property
Private Property Get PONumberColumnIndex() As Long
PONumberColumnIndex = Table.ListColumns("PO # Issued").Index
End Property
Private Property Get LocationColumnIndex() As Long
LocationColumnIndex = Table.ListColumns("Location").Index
End Property
Private Property Get ItemColumnIndex() As Long
ItemColumnIndex = Table.ListColumns("Item").Index
End Property
Private Property Get DescriptionColumnIndex() As Long
DescriptionColumnIndex = Table.ListColumns("Description").Index
End Property
Private Property Get CompanyColumnIndex() As Long
CompanyColumnIndex = Table.ListColumns("Parts Company").Index
End Property
Private Property Get QuantOrderedColumnIndex() As Long
QuantOrderedColumnIndex = Table.ListColumns("Quantity Ordered").Index
End Property
Private Property Get QuantReceivedColumnIndex() As Long
QuantReceivedColumnIndex = Table.ListColumns("Quantity Received").Index
End Property
Private Property Get IPOSheetProxy_Data() As Collection
Dim result As Collection
Set result = New Collection
Dim currentRow As ListRow
For Each currentRow In Table.ListRows
Dim currentPO As ModelPO
Set currentPO = New ModelPO
'ModelPO encapsulates a row in Table as an object'
currentPO.Company = currentRow.Range(columnindex:=CompanyColumnIndex).value
currentPO.Description = currentRow.Range(columnindex:=DescriptionColumnIndex).value
currentPO.ItemNum = currentRow.Range(columnindex:=ItemColumnIndex).value
currentPO.Location = currentRow.Range(columnindex:=LocationColumnIndex).value
currentPO.PONumber = currentRow.Range(columnindex:=PONumberColumnIndex).value
currentPO.QuantOrd = currentRow.Range(columnindex:=QuantOrderedColumnIndex).value
currentPO.QuantRec = currentRow.Range(columnindex:=QuantReceivedColumnIndex).value
result.Add currentPO
Next
Set IPOSheetProxy_Data = result
End Property
Public Sub IPOSheetProxy_Update(ByVal value As ModelPO)
Dim currentRow As ListRow
For Each currentRow In Table.ListRows
If currentRow.Range(columnindex:=PONumberColumnIndex).value = value.PONumber And _
currentRow.Range(columnindex:=DescriptionColumnIndex).value = value.Description And _
currentRow.Range(columnindex:=ItemColumnIndex).value = value.ItemNum Then
currentRow.Range(columnindex:=QuantOrderedColumnIndex).value = value.QuantOrd
currentRow.Range(columnindex:=QuantReceivedColumnIndex).value = value.QuantRec
Exit Sub
End If
Next
End Sub
</code></pre>
<p>With that out of the way, let's get to actually starting the process.</p>
<p><strong>Calling code (Module1):</strong></p>
<pre><code>Public Sub ReceiveFromPO()
Dim proxy As WbkProxy
Set proxy = New WbkProxy
With New ReceivePOPresenter
.Show proxy, InputBox("Please enter the PO Number")
End With
End Sub
</code></pre>
<p><strong>ReceivePOPresenter:</strong> - prepares the data entry form and handles the data when it's done</p>
<pre><code>Option Explicit
Private wbproxy As WbkProxy
'@MemberAttribute VB_VarHelpID, -1 '
Private WithEvents view As ReceivePOForm
Private Property Get form() As IFormView
Set form = view
End Property
Public Sub Show(ByVal proxy As WbkProxy, ByVal value As String)
Set wbproxy = proxy
Set view = New ReceivePOForm
Dim viewmodel As JustValuesModel
Set viewmodel = New JustValuesModel
Dim current As ModelPO
Dim result As Collection
Set result = New Collection
For Each current In wbproxy.POSheet.Data
If current.PONumber = value Then
If Len(CStr(current.QuantRec)) = 0 Then current.QuantRec = 0
result.Add current
End If
Next
Set viewmodel.PossibleValues = result
If form.showForm(viewmodel) Then Receive viewmodel
Set view = Nothing
End Sub
Private Sub Receive(ByVal viewmodel As JustValuesModel)
Dim current As ModelPO
For Each current In viewmodel.PossibleValues
wbproxy.POSheet.Update current
Next
End Sub
Private Sub view_Receive(ByVal viewmodel As JustValuesModel)
Receive viewmodel
End Sub
</code></pre>
<p><strong>ReceivePOForm:</strong> - creates labels and textboxes for each line item in the PO <a href="https://i.stack.imgur.com/8uWEk.png" rel="noreferrer">(Here's an example of what it might look like)</a></p>
<pre><code>Option Explicit
Public Event Receive(ByVal viewmodel As JustValuesModel)
Private Type TView
isCancelled As Boolean
Model As JustValuesModel
End Type
Private this As TView
Implements IFormView
Private Sub FinishButton_Click()
If Validate = False Then Exit Sub
UpdateModel
RaiseEvent Receive(this.Model)
OnCancel
End Sub
Private Function IFormView_ShowForm(ByVal viewmodel As Object) As Boolean
Set this.Model = viewmodel
Me.Show vbModal
IFormView_ShowForm = Not this.isCancelled
End Function
Private Sub UserForm_Activate()
Dim i As Long
i = 0
Dim current As ModelPO
For Each current In this.Model.PossibleValues
CreateDescriptionLabel current, i
CreateQuantityLabel current, i
CreateQuantityBox i
i = i + 1
Next
AdjustFormHeight
End Sub
Private Sub CreateDescriptionLabel(ByVal value As ModelPO, ByVal previousLabels As Long)
Const PADDING = 12
Const TOP_MARGIN = 24
Const LABEL_HEIGHT = 12
Const LEFT_MARGIN = 12
Const LABEL_WIDTH = 228
Dim label As Control
Set label = Me.Controls.Add("Forms.Label.1", "DescriptionLabel" & previousLabels + 1)
label.Left = LEFT_MARGIN
label.Height = LABEL_HEIGHT
label.Width = LABEL_WIDTH
label.Top = TOP_MARGIN + (previousLabels * (LABEL_HEIGHT + PADDING))
Me.Controls("DescriptionLabel" & previousLabels + 1).Caption = value.Description
End Sub
Private Sub CreateQuantityLabel(ByVal value As ModelPO, ByVal previousLabels As Long)
'DRY?'
Const PADDING = 12
Const TOP_MARGIN = 24
Const LABEL_HEIGHT = 12
Const LEFT_MARGIN = 264
Const LABEL_WIDTH = 48
Const CENTERED = 2
Dim label As Control
Set label = Me.Controls.Add("Forms.Label.1", "QLabel" & previousLabels + 1)
label.Left = LEFT_MARGIN
label.Height = LABEL_HEIGHT
label.Width = LABEL_WIDTH
label.Top = TOP_MARGIN + (previousLabels * (LABEL_HEIGHT + PADDING))
Me.Controls("QLabel" & previousLabels + 1).Caption = value.QuantOrd - value.QuantRec
Me.Controls("QLabel" & previousLabels + 1).TextAlign = CENTERED
End Sub
Private Sub CreateQuantityBox(ByVal previousBoxes As Long)
Const PADDING = 6
Const BOX_HEIGHT = 18
Const LEFT_MARGIN = 330
Const TOP_MARGIN = 24
Const BOX_WIDTH = 42
Dim box As Control
Set box = Me.Controls.Add("Forms.TextBox.1", "QBox" & previousBoxes + 1)
box.Left = LEFT_MARGIN
box.Height = BOX_HEIGHT
box.Width = BOX_WIDTH
box.Top = TOP_MARGIN + (previousBoxes * (BOX_HEIGHT + PADDING))
End Sub
Private Sub AdjustFormHeight()
Const PADDING = 20
Const ENABLED = 2
Dim current As Control
Dim maxLength As Long
maxLength = 0
For Each current In Me.Controls
If current.Top + current.Height > maxLength And current.Name <> "FinishButton" Then
maxLength = current.Top + current.Height
End If
Next
Dim finish As Control
Set finish = Me.Controls("FinishButton")
finish.Top = maxLength + PADDING
If Me.Height < (finish.Top + finish.Height) Then
'add scrollbars'
Me.ScrollBars = ENABLED
Me.ScrollHeight = finish.Top + finish.Height + PADDING
Else
'shrink'
Me.Height = finish.Top + finish.Height + 2 * PADDING
End If
End Sub
Private Function Validate() As Boolean
Dim i As Long
For i = 1 To this.Model.PossibleValues.Count
If Len(Me.Controls("QBox" & i).value) <> 0 And Not IsNumeric(Me.Controls("QBox" & i).value) Then
MsgBox "Please only enter numbers in the quantity boxes."
Validate = False
Exit Function
End If
Next
Validate = True
End Function
Private Sub UpdateModel()
Dim i As Long
i = 0
Dim current As ModelPO
For Each current In this.Model.PossibleValues
i = i + 1
If Len(CStr(Me.Controls("QBox" & i).value)) <> 0 Then
current.QuantRec = current.QuantRec + Me.Controls("QBox" & i).value
End If
Next
End Sub
Private Sub OnCancel()
this.isCancelled = True
Me.Hide
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = VbQueryClose.vbFormControlMenu Then
Cancel = True
OnCancel
End If
End Sub
</code></pre>
<p>This is where I feel I may have fallen off the wagon a bit. I'm worried that my userform code smells a little bit like Smart-UI, but I had a hard time trying to model the data when you don't know going in how many textboxes there will be.</p>
<p>Speaking of models, <strong>here's JustValuesModel:</strong> - holds the info for all the items on the PO</p>
<pre><code>Option Explicit
Private Type TModel
PossibleValues As Collection
End Type
Private this As TModel
Public Property Get PossibleValues() As Collection
Set PossibleValues = this.PossibleValues
End Property
Public Property Set PossibleValues(ByVal value As Collection)
Set this.PossibleValues = value
End Property
</code></pre>
<p>I wanted to try to model the textbox values somehow, but nothing I came up with was ideal (hence the UpdateModel procedure in the userform).</p>
<p>Lastly, <strong>here's the view interface</strong> (very simple):</p>
<pre><code>Option Explicit
Public Function showForm(ByVal viewmodel As Object) As Boolean
End Function
Private Sub Class_Initialize()
Err.Raise 5, , "Interface class must not be instantiated."
End Sub
</code></pre>
<p>Sorry this is so long! I'm still rather new to OOP so I'd like to improve on my fundamentals (e.g. SOLID), but improvements of any kind are very welcome. Also, please let me know if I missed something and I'll edit it in.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T15:13:38.350",
"Id": "472710",
"Score": "2",
"body": "I noticed you have a property named `Sheet1` which is a common object name in Excel. I would want to avoid name collisions like this because it's ambiguous. Even changing the name to `SheetOne` would avoid confusion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T15:17:51.800",
"Id": "472711",
"Score": "1",
"body": "Good call, I've actually already run into problems with that elsewhere. Not sure why I never thought to change it, but thank you!"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T14:25:24.897",
"Id": "240932",
"Score": "6",
"Tags": [
"object-oriented",
"vba",
"excel",
"mvp"
],
"Title": "An over-the-top approach to data entry"
}
|
240932
|
<p>I'm trying to remove email names from transcripts because it removes unnecessary info that is not needed in the transcript. </p>
<p>The regex below removes email names from a spoken transcript. </p>
<p>Examples below are completely made up. You'll note above that "dot" and "at" are the only common terms. </p>
<p>Format: </p>
<ul>
<li>token1 tokenN at word dot word </li>
<li>before "at" remove 1-2 tokens delimited by spaces</li>
<li>remove "at"</li>
<li>remove the word after "at"</li>
<li>remove "dot"</li>
<li>remove the word after "dot"</li>
</ul>
<p>Given the above at least the email name would be mostly removed. Prior to "at" you don't know how many words make up the email name or are part of the text. </p>
<p>The regex I created covers all cases above and leaves some words remaining in long email names:</p>
<pre><code>import re
regExpattern = "[a-zA-Z0-9_.+-]+\s*at\s*[a-zA-Z0-9-.]+\s*[a-zA-Z0-9-]*\s*dot*\s*[a-zA-Z0-9-]{3}"
emails = ["jane 94 at g mail dot com",
"9 at gmail dot com",
"jim doe at gmail dot com",
"I am jane doe at A.B. dot com",
"I am jane at AB dot com",
"just email happy jane doe seventy three at msn dot com",
"jane doe seven to seven at hotmail dot com"
]
for text in emails:
cleanText = re.sub(regExpattern, '', text)
print(cleanText)
</code></pre>
<p>You can try it here: <a href="https://regex101.com/r/XV5GMT/2" rel="nofollow noreferrer">https://regex101.com/r/XV5GMT/2</a></p>
<p>Q: What spoken email names does the regex above miss (other than what I mention above)? Also, an email name that is mostly removed is good enough. </p>
<p>Alternatively, I tried to use POS tagging but couldn't discern any consistent patterns. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T15:10:50.103",
"Id": "472708",
"Score": "1",
"body": "This is borderline-off-topic. I consider it salvageable if you add more context about why you're trying to manipulate email address strings."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T15:12:09.410",
"Id": "472709",
"Score": "3",
"body": "On the other hand, if you know that this is incomplete and you're looking for advice on how to complete it, then this is off-topic for sure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T15:28:01.927",
"Id": "473038",
"Score": "0",
"body": "In my original post above I added \"why\" I'm trying to manipulate email address strings."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-07T09:47:11.547",
"Id": "474614",
"Score": "1",
"body": "This pattern misses `firstname.lastname@example.com`, which I presume would be transcribed as `Firstname dot lastname at example dot com`. Or at least it is missing that testcase."
}
] |
[
{
"body": "<h2>Good Job (for the Expression)!</h2>\n<p>Your expression is pretty good for what I guess you are trying to do. My guess is that you just want to see <strong>if there is one email in a string</strong>. Clearly, I don't see that we are going to extract any email (since your expression currently doesn't do that not to mention the strings are quite unstructured).</p>\n<p>To answer your question, I'm pretty sure it would miss lots of input strings, but to begin with, we can just add an <code>i</code> (insensitive) flag to the expression and remove <code>A-Z</code>s:</p>\n<pre><code>(?i)[a-z0-9_.+-]+\\s*at\\s*[a-z0-9.-]+\\s*[a-z0-9-]*\\s*dot*\\s*[a-z0-9-]{2,6}\\s*(?:dot*\\s*[a-z0-9-]{2,6})?\n</code></pre>\n<h3>Example of What is Going to Miss:</h3>\n<p>For instance "dot co dot uk" types of emails are going to be missed. For that, we would add an optional non-capturing group: <code>(?:dot*\\s*[a-z0-9-]{2,6})?</code></p>\n<h2>Not sure if a stand-alone regex would be the best solution!</h2>\n<p>The problem you are having is very complicated. I'm sure there are alternative methods to solve your problem, but I'm not really good at offering solutions.</p>\n<h2><a href=\"https://regex101.com/r/Qrn6cA/1\" rel=\"nofollow noreferrer\">Demo</a></h2>\n<pre><code>import re\n\nregex_pattern = r"(?i)[a-z0-9_.+-]+\\s*at\\s*[a-z0-9.-]+\\s*[a-z0-9-]*\\s*dot*\\s*[a-z0-9-]{2,6}\\s*(?:dot*\\s*[a-z0-9-]{2,6})?"\n\nemails = ["jane 94 at g mail dot com",\n "9 at gmail dot com",\n "jim doe at gmail dot com",\n "I am jane doe at A.B. dot com",\n "I am jane at AB dot com",\n "just email happy jane doe seventy three at msn dot com",\n "jane doe seven to seven at hotmail dot com"\n "jane doe seven to seven at hotmail dot co dot uk"\n ]\n\nfor text in emails:\n clean_text = re.sub(regex_pattern, '', text)\n print(clean_text)\n\n</code></pre>\n<p>By the way, you can post your question on <a href=\"https://stackoverflow.com/questions/tagged/regex\">stackoverflow</a>, where there are so many RegEx experts in there.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T01:05:44.873",
"Id": "240977",
"ParentId": "240934",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "240977",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T14:54:16.257",
"Id": "240934",
"Score": "-1",
"Tags": [
"python",
"python-3.x",
"regex"
],
"Title": "Regex to remove spoken email names"
}
|
240934
|
<p>I'm still learning c#, and I need my code to only run less than 2 seconds to be accepted.
I have a look and say sequence and after the last number is found, the code sums it all up, and it takes so long if the element in the sequence is big.</p>
<p>Example:</p>
<p>Input: 2</p>
<p>Output: takes less than a second</p>
<p>Input: 50</p>
<p>Output: takes 4 or so seconds.</p>
<p>I have only tried doing is changing foreach loops into for loops. I don't know what else to change.
Anyone can point me in the right direction? Thanks all.</p>
<pre><code>namespace SumOfLookAndSaySequence
{
class Program
{
static void Main(string[] args)
{
string input = Console.ReadLine();
if (Int32.TryParse(input, out int nthTerm) && nthTerm > 0)
{
string lastSequence = GetSequence(nthTerm).Last();
char[] digits = lastSequence.ToCharArray();
int[] itemToSum = new int[digits.Length];
int result = 0;
for(int i = 0; i < digits.Length; i++)
{
itemToSum[i] = int.Parse(digits[i].ToString());
result = result + itemToSum[i];
}
Console.WriteLine(lastSequence);
Console.WriteLine(result);
}
}
static IEnumerable<string> GetSequence(int nthTerm)
{
List<string> sequence = new List<string>() { "1" };
for(int i = 1; i < nthTerm; i++)
{
sequence.Add(GetNextNumberSequence(sequence[i - 1]));
}
return sequence;
}
static string GetNextNumberSequence(string number)
{
StringBuilder stringBuilder = new StringBuilder();
int count = 1;
char digit = number[0];
for(int i = 1; i < number.Length; i++)
{
if(number[i] == digit)
{
count++;
}
else
{
stringBuilder.Append(string.Concat(count, Char.GetNumericValue(digit)));
count = 1;
digit = number[i];
}
}
stringBuilder.Append(string.Concat(count, digit));
return stringBuilder.ToString();
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I'd have to ask - do you <em>have</em> to <code>Console.WriteLine()</code> the output? Most code testing sites want a return value from a method rather than looking at the console output and clearly, the console output is going to be the vast majority of the time spent in the application.</p>\n\n<p>Secondly, I have a few quick and easy tips for increasing performance:</p>\n\n<ol>\n<li>Ditch the <code>string.Concats</code> - you have the <code>StringBuilder</code> in hand and can just \n<code>.Append()</code> each of those items in turn:</li>\n</ol>\n\n<pre><code>stringBuilder.Append(count);\nstringBuilder.Append(char.GetNumericValue(digit));\n</code></pre>\n\n<p>in the loop and</p>\n\n<pre><code>stringBuilder.Append(count);\nstringBuilder.Append(digit);\n</code></pre>\n\n<p>after the loop.</p>\n\n<ol start=\"2\">\n<li><p>Pre-allocate list size: <code>List<string> sequence = new List<string>(nthTerm + 1) { \"1\" };</code> This will reduce reallocations as the list grows (it starts at 4 and then increases by twice the size as necessary).</p></li>\n<li><p>Measure with precision - surround your processing code in <code>Main</code> with <code>var SW = Stopwatch.StartNew();</code> and <code>Console.WriteLine(sw.Elapsed);</code>. This will show you the time your code actually took.</p></li>\n</ol>\n\n<p>After I did these all the things listed above, 2 ran in 00:00:00.0006395 and 50 ran in 00:00:00.5806011.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T16:46:56.170",
"Id": "472726",
"Score": "1",
"body": "Thanks for the reply! the Console.WriteLine is only in my code for testing. The final code does'nt have that.\nI'll try your suggestions and comeback later if it improved or not."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T16:44:56.860",
"Id": "240943",
"ParentId": "240936",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "240943",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T15:45:19.490",
"Id": "240936",
"Score": "2",
"Tags": [
"c#",
"algorithm"
],
"Title": "Sum of Look and Say Sequence"
}
|
240936
|
<p>awhile ago I asked about a thread pool implementation I had made. I took the advice down and modified it a lot over time to fit my needs. It has been serving me extremely well in all of my projects but I was wondering if there was anything else I could improve on?</p>
<p>Here is the class:</p>
<pre><code>class ThreadPool{
public:
/* Constructor */
ThreadPool(uint8_t numThreads) {
assert(numThreads > 0);
createThreads(numThreads);
}
//Destructor
~ThreadPool(){
shutdown = true;
notifier.notify_all();
for(int i = 0; i < threads.size(); ++i){
threads[i].join();
}
}
//add any arg # function to queue
template <typename Func, typename... Args >
auto push(Func&& f, Args&&... args){
//get return type of the function
typedef decltype(f(args...)) retType;
std::packaged_task<retType()> task(std::bind(f, args...));
std::future<retType> future = task.get_future();
{
// lock jobQueue mutex, add job to the job queue
std::unique_lock<std::mutex> lock(JobMutex);
jobQueue.emplace(std::packaged_task<void()>(std::move(task)));
}
notifier.notify_one();
return future;
}
private:
std::vector<std::thread> threads;
std::queue<std::packaged_task<void()>> jobQueue;
std::condition_variable notifier;
std::mutex JobMutex;
std::atomic<bool> shutdown = false;
void createThreads(uint8_t numThreads) {
auto threadFunc = [this]() {
while (true) {
std::packaged_task<void()> job;
{
std::unique_lock<std::mutex> lock(JobMutex);
notifier.wait(lock, [this] {return !jobQueue.empty(); });
if(shutdown){
break;
}
//strange bug where it will continue even if the job queue is empty
if (jobQueue.size() < 1)
continue;
job = std::move(jobQueue.front());
jobQueue.pop();
}
job();
}
};
threads.reserve(numThreads);
for (int i = 0; i != numThreads; ++i) {
threads.emplace_back(std::thread(threadFunc));
}
}
ThreadPool(const ThreadPool& other) = delete;
void operator=(const ThreadPool& other) = delete;
}; /* end ThreadPool Class */
</code></pre>
|
[] |
[
{
"body": "<p>You have a logical bug in the code. Imagine all jobs are finished and then shutdown is called. You'll never leave the <code>notifier.wait(...)</code>. </p>\n\n<p>Also, if a job exists but shutdown is called you quit instantly without doing it - I do not think that this is a good idea. I think you should finish all jobs prior to quitting. Make a special hard reset routine for the immediate exit. Though, it probably requires usage of exceptions.</p>\n\n<p>Also, consider what will happen if an exception is called inside the function <code>f</code>. In the thread pool one of the threads will die and kill the whole program - most likely. It is not good. It should somehow forward the error to the caller. To this end I have thread pool functionality divided - made a supplementary class for user that wraps whatever additional functionality is needed.</p>\n\n<p>Technical issues:</p>\n\n<ol>\n<li><p><code>std::bind(f, args...)</code> should be <code>std::bind(f, std::forward<Args>(args)...)</code> to ensure perfect forwarding as otherwise you might end up with unnecessary copying of data.</p></li>\n<li><p><code>numThreads</code> should be defaulted to <code>std::thread::hardware_concurrency</code> and I believe and <code>uint8_t</code> is getting too small for some of the latest processors. Additionally the ThreadPool should have the functionality to tell to its user how many threads it has.</p></li>\n<li><p>I am not too fond of <code>std::future</code> - it is somewhat incomplete as Executors TS is still incomplete. Normally I'd expect that user would want to call the <code>push</code> task several times to complete a single operation. In which, case you generate multiple <code>std::future<void></code>. It would be better to somehow to make it into a single wait instead of several. But I think I might be nitpicking - honestly I'd wait for Executor TS near completion and try to implement or get from somewhere something with the same interface as long as Executor TS is unavailable.</p></li>\n<li><p>The declarations </p>\n\n<pre><code>ThreadPool(const ThreadPool& other) = delete; \nvoid operator=(const ThreadPool& other) = delete;\n</code></pre></li>\n</ol>\n\n<p>are redundant as the class already has a <code>std::mutex</code> that makes the whole class non-copyable and non-movable. Yeah, it isn't important.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T21:57:38.787",
"Id": "472751",
"Score": "0",
"body": "In the first situation you mentioned, notifier.notify_all() in the destructor would break out of the notifier.wait() right? For the second issue where there is still a job that hasn't been executed, I can modify the if (shutdown) to also check if there is still a job in the queue. That statement has to stay in the case that the job queue is empty. Ill make sure to properly forward the args now. As for hardware_concurrency, I thought of doing this but I thought giving default values would not be a good idea especially since hardware_concurrency can fail. Ill look into executors!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T21:57:53.390",
"Id": "472752",
"Score": "0",
"body": "Thanks for the info! Ive got some stuff to add"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T06:25:46.683",
"Id": "472794",
"Score": "0",
"body": "@Paul `notify_all()` won't break the wait. It'll only tell them to recheck the condition which is still false."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T17:00:41.643",
"Id": "240945",
"ParentId": "240937",
"Score": "3"
}
},
{
"body": "<h2>Code Review:</h2>\n\n<p>Please put your code in a namespace.</p>\n\n<hr>\n\n<pre><code>ThreadPool(uint8_t numThreads) {\n assert(numThreads > 0);\n</code></pre>\n\n<p>This is dangerous and will never assert!</p>\n\n<p>The input type here <code>uint8_t</code> which means it is not signed and thus can only be positive (so the only number that it will assert on is if <code>numThreads</code> is zero.</p>\n\n<p>The problem is that C++ integer type conversion will \"automatically\" convert a negative signed number into a unsigned value (which will usually result in a very large positive value).</p>\n\n<pre><code>ThreadPool pool(-10); // Will compile.\n // Will not assert as -10 is a signed value and will\n // be auto converted to unsigned at which point it\n // will be positive and pass the assert test.\n</code></pre>\n\n<hr>\n\n<p>Here is a good place to use the range based for:</p>\n\n<pre><code> for(int i = 0; i < threads.size(); ++i){\n threads[i].join();\n }\n\n for(auto& thread: threads){\n thread.join();\n }\n</code></pre>\n\n<hr>\n\n<p>The use of <code>typedef</code> has been replaced by the <code>using</code> declaration:</p>\n\n<pre><code>//get return type of the function\ntypedef decltype(f(args...)) retType;\n\n// Rather use this:\nusing retType = decltype(f(args...));\n</code></pre>\n\n<hr>\n\n<p>Not in favor of using <code>decltype()</code> here as you are getting the type of the function (not the return type). Then getting the return type by effectively inferring the calling.</p>\n\n<pre><code>typedef decltype(f(args...)) retType;\nstd::packaged_task<retType()> task(std::bind(f, args...));\n ^^^^^^^^^. Inferred function call\n</code></pre>\n\n<p>There are actually templates to extract this value directly from the type:</p>\n\n<pre><code>using RetType = invoke_result_t<Func, Args....>;\n</code></pre>\n\n<hr>\n\n<p>Still on the same statement. It is sort of standard practice for user defined types <code>retType</code> in the case to have an initial uppercase letter. This allows you to easily see types over objects.</p>\n\n<hr>\n\n<p>If you set the <code>shutdown</code> flag this still never leaves the <code>wait()</code> unless there are also objects in the <code>jobQueue</code>.</p>\n\n<pre><code> notifier.wait(lock, [this] {return !jobQueue.empty(); });\n\n if(shutdown){\n break;\n }\n</code></pre>\n\n<p>You need to test for the <code>shutdown inside the</code>wait()` test method.</p>\n\n<pre><code> notifier.wait(lock, [this] {return !jobQueue.empty() || shutdown; });\n\n if(shutdown){\n break;\n }\n</code></pre>\n\n<hr>\n\n<p>This is worrying. Though I can't spot the issue:</p>\n\n<pre><code> //strange bug where it will continue even if the job queue is empty\n if (jobQueue.size() < 1)\n continue;\n</code></pre>\n\n<hr>\n\n<p>This seems to be wrong advice.<br>\nI though function return values were already R-Values.<br>\nWhere is my thinking going wrong?</p>\n\n<p><strike>\nYou don't need the <code>std::move()</code> here.</p>\n\n<pre><code> job = std::move(jobQueue.front());\n</code></pre>\n\n<p></strike></p>\n\n<hr>\n\n<p>When you are using <code>emplace()</code> you are building the object the container holds by using its constructor.</p>\n\n<p>So here you are creating a temporary object then call the move constructor to move the thread into the container. But you don't need to constructor the temporary thread object as the threadFunc will be forwarded to the thread constructor in the object.</p>\n\n<pre><code> threads.emplace_back(std::thread(threadFunc));\n\n // Remove the thread\n threads.emplace_back(threadFunc);\n</code></pre>\n\n<hr>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T22:22:32.023",
"Id": "472759",
"Score": "0",
"body": "Thanks for the notes! Ill get on adding that stuff. One issue though \n`job = std::move(jobQueue.front());`\n\n\nWhen I remove the std::move it tells me that the copy constructor is a deleted function"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T23:25:57.177",
"Id": "472760",
"Score": "0",
"body": "OK. Maybe I was wrong. I'll delete that. But I though a function result was already an r-value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T06:37:04.937",
"Id": "472797",
"Score": "0",
"body": "@MartinYork function result here would be an L-value reference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T09:57:44.777",
"Id": "472826",
"Score": "0",
"body": "@ALX23z: Well obviously they are :-) (otherwise it would compile). But why. I was under the impression that all function results are r-value references (otherwise how does `std::move()` work? Ahh it returns by r-value reference. So all return by value and explicit r-value references are r-values."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T10:08:49.390",
"Id": "472829",
"Score": "0",
"body": "@ALX23z: Well obviously they are :-) (otherwise it would compile). But why. I was under the impression that all function results are r-value (as they are un-named objects) references, otherwise how does `std::move()` work? ***Ahh*** it returns by r-value reference. So all return by value and explicit r-value references are r-values. I am going to have to go look up the whole l/pr/x/gl/r value topic."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T21:56:41.907",
"Id": "240964",
"ParentId": "240937",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T15:45:20.610",
"Id": "240937",
"Score": "3",
"Tags": [
"c++",
"multithreading"
],
"Title": "Easy to use Thread Pool Implementation"
}
|
240937
|
<p>I am implementing a functionality in <code>Scala</code> to Copy files from one <code>FileSystem</code> to another <code>FileSystem</code>. </p>
<p>And this is what I have implemented. </p>
<p><strong>CopyFile.scala</strong>
Methods are empty. However, they will just call external library and will do error handling. </p>
<pre class="lang-scala prettyprint-override"><code>object CopyFiles {
def localToHDFS(src: String, dest: String): Unit = {
}
def S3ToS3(src: String, dest: String): Unit = {
}
def localToS3(src: String, des: String): Unit = {
}
def HDFSToHDFS(src: String, dest: String): Unit = {
}
}
</code></pre>
<p><strong>Main.scala</strong> </p>
<pre class="lang-scala prettyprint-override"><code>import java.util.Properties
import scala.io.Source
object MainClass {
def main(args: Array[String]): Unit = {
val propFileURI = "test.properties"
val properties: Properties = new Properties()()
val source = Source.fromFile( System.getProperty("user.dir")+"\\src\\main\\resources\\"+propFileURI).reader
properties.load(source)
val srcPath = properties.getProperty("srcPath")
val destPath = properties.getProperty("destPath")
if(!srcPath.contains(":") && destPath.toLowerCase().contains("hdfs")){
CopyFiles.localToHDFS(srcPath, destPath)
}
if(!srcPath.toLowerCase().contains(":") && destPath.toLowerCase().contains("s3")){
CopyFiles.localToS3(srcPath, destPath)
}
if(srcPath.toLowerCase().contains("s3") && destPath.toLowerCase().contains("s3")){
CopyFiles.S3ToS3(srcPath, destPath)
}
if(srcPath.toLowerCase().contains("hdfs") && destPath.toLowerCase().contains("hdfs")){
CopyFiles.HDFSToHDFS(srcPath, destPath)
}
}
}
</code></pre>
<ul>
<li>Is there a better OOP way to solve this? </li>
<li>Would that be a good idea to write a function which returns the appropriate function based on source and destination location or based on property file to hide complexity from client code?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T16:08:28.060",
"Id": "472720",
"Score": "1",
"body": "downvote without a explanation is not a good stackoverflow practice. if something is missing not appropriate, first point it out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T16:25:47.763",
"Id": "472724",
"Score": "5",
"body": "(then again, this *isn't* stack**overflow**.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T10:15:47.403",
"Id": "472831",
"Score": "1",
"body": "It looks like those methods shouldn't be empty. Please provide all relevant code and take a look at the [help/on-topic]."
}
] |
[
{
"body": "<p>I don't see OO design or code presented: nothing to review here.</p>\n\n<p>The code presented is lacking a description of what it is to accomplish.<br>\n<code>main()</code> repeats <code>destPath.toLowerCase()</code> and <code>srcPath.toLowerCase()</code>.</p>\n\n<pre><code> /** True if both parameters specified first contain required. */\n def common(a: String, b: String, required: String): Boolean = {\n a.contains(required) && b.contains(required)\n }\n…\n val destLower = destPath.toLowerCase()\n if(!srcPath.contains(\":\") {\n if (destLower.contains(\"hdfs\")) {\n CopyFiles.localToHDFS(srcPath, destPath)\n } else if (destLower.contains(\"s3\")) {\n CopyFiles.localToS3(srcPath, destPath)\n }\n } else {\n val srcLower = srcPath.toLowerCase()\n if (common(srcLower, destLower, \"s3\")) {\n CopyFiles.S3ToS3(srcPath, destPath)\n } else if (common(srcLower, destLower, \"hdfs\")) {\n CopyFiles.HDFSToHDFS(srcPath, destPath)\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T16:59:43.923",
"Id": "472727",
"Score": "0",
"body": "(I *don't* know Scala.)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T16:32:20.197",
"Id": "240941",
"ParentId": "240939",
"Score": "1"
}
},
{
"body": "<h1>Single Responsibility</h1>\n<p>You are doing a few things in main:</p>\n<ul>\n<li>Read srcPath and destPath from the properties file</li>\n<li>Understand which service is responsible for each path</li>\n<li>Find the relevant copy function</li>\n<li>Call the copy function</li>\n</ul>\n<p>I suggest creating a method for each of the above bullets.</p>\n<h1>Polymorphism</h1>\n<p>You asked</p>\n<blockquote>\n<p>Is there a better OOP way to solve this?</p>\n</blockquote>\n<p>I guess you mean Polymorphism as it one of the key features of OOP.</p>\n<p>One way is to write a function that returns the relevant function. Scala support functions types very well.</p>\n<p>Another way is creating a trait and classes that implement it (as you did the question you deleted) and a function or factory object that return the relevant class. This way is more common in OOP. Also, it is better in terms of single responsibility:<code>CopyFiles</code> do a lot of different types of copies.</p>\n<h1>Avoid Ifs</h1>\n<p>In the question you deleted, you asked if you can rid of the ifs. when the input is the services names(and not the paths), I believe you can use pattern matching easily.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T17:40:30.117",
"Id": "240949",
"ParentId": "240939",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T16:02:23.093",
"Id": "240939",
"Score": "-1",
"Tags": [
"object-oriented",
"design-patterns",
"scala"
],
"Title": "A better OOP way for solution"
}
|
240939
|
<p>Related to my code I <a href="https://codereview.stackexchange.com/q/240825/507">just put out for review</a>.</p>
<p>I wrote some small helper functions for dealing with interactions with the file system. This is not meant to by any type of "File System" wrapper. I just wanted to put my code into named functions to make the code Column formatting code easy to read and the functions did not seem "Column File" centric so I placed them in a separate class.</p>
<h2>FileSystem.h</h2>
<pre><code>#ifndef THORSANVIL_FILESYSTEM_FILESYSTEM_H
#define THORSANVIL_FILESYSTEM_FILESYSTEM_H
#include <sys/stat.h>
#include <sys/types.h>
#include <string>
#include <fstream>
// See: https://codereview.stackexchange.com/questions/81922/macro-to-build-type-declaration
// For details about the Traits type and how it is built.
namespace ThorsAnvil::FileSystem
{
using iostate = std::ios_base::iostate;
static constexpr iostate const& goodbit = std::ios_base::goodbit;
static constexpr iostate const& badbit = std::ios_base::badbit;
static constexpr iostate const& failbit = std::ios_base::failbit;
static constexpr iostate const& eofbit = std::ios_base::eofbit;
using openmode = std::ios_base::openmode;
static constexpr openmode const& app = std::ios_base::app;
static constexpr openmode const& binary = std::ios_base::binary;
static constexpr openmode const& in = std::ios_base::in;
static constexpr openmode const& out = std::ios_base::out;
static constexpr openmode const& trunc = std::ios_base::trunc;
static constexpr openmode const& ate = std::ios_base::ate;
// File System Functionality
struct FileSystem
{
enum DirResult {DirAlreadyExists, DirCreated, DirFailedToCreate};
static DirResult makeDirectory(std::string const& path, mode_t permissions);
static bool isFileOpenable(std::string const& path, openmode mode);
static bool removeFileOrDirectory(std::string const& path);
};
}
#endif
</code></pre>
<h2>FileSystem.cpp</h2>
<pre><code>// This header file is generated by autotools when it does all the compiler checks and stuff
// The only interesting thing it defines for this file is the macro HEADER_ONLY_INCLUDE
#include "ThorsStorageConfig.h"
//
// If this file is being used in a header only context this is `inline` otherwise it is blank.
//
// To use this code in a header only context you need to check out the special version:
// git clone --single-branch --branch header-only https://github.com/Loki-Astari/ThorsStorage.git
//
// This branch is auto generated after each successful build by travis.ci
#include "filesystem.h"
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
using namespace ThorsAnvil::FileSystem;
// File System Stuff
HEADER_ONLY_INCLUDE
FileSystem::DirResult FileSystem::makeDirectory(std::string const& path, mode_t permissions)
{
using StatusInfo = struct stat;
StatusInfo info;
for (std::size_t pos = path.find('/'); pos != std::string::npos; pos = path.find(pos + 1, '/'))
{
std::string subPath = path.substr(0, pos);
if ((stat(subPath.c_str(), &info) != 0) && (mkdir(subPath.c_str(), permissions) != 0))
{
return DirFailedToCreate;
}
}
if (stat(path.c_str(), &info) == 0)
{
return DirAlreadyExists;
}
if (mkdir(path.c_str(), permissions) == 0)
{
return DirCreated;
}
return DirFailedToCreate;
}
HEADER_ONLY_INCLUDE
bool FileSystem::isFileOpenable(std::string const& path, openmode mode)
{
bool result = true;
int accessFlag = ((mode & in) ? R_OK : 0)
| ((mode & out)? W_OK : 0);
if (access(path.c_str(), accessFlag) != 0)
{
// This is still OK if we want to open a file for writing as we will be creating it.
// But to make sure we have permission we have to check three things.
// 1: The errors for accesses is because the file does not exist.
// 2: We want to open the file for writing.
// 3: The directory we want to open the file is writable by this processes.
//
// Otherwise the file is not open-able for the mode we want.
result = (errno == ENOENT) && (mode & out) && (access(path.substr(0, path.find_last_of('/')).c_str(), W_OK) == 0);
}
return result;
}
HEADER_ONLY_INCLUDE
bool FileSystem::removeFileOrDirectory(std::string const& path)
{
int state = remove(path.c_str());
return state == 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>Here are some thoughts while I read through your code:</p>\n\n<hr>\n\n<blockquote>\n <p>I just wanted to put my code into named functions to make the code Column formatting code easy to read and the functions did not seem \"Column File\" centric so I placed them in a separate class.</p>\n</blockquote>\n\n<p>Good idea.</p>\n\n<hr>\n\n<pre><code>static constexpr iostate const& goodbit = std::ios_base::goodbit;\n</code></pre>\n\n<p>Are all the lines that look like this really necessary? Do you really need to have this stuff in your own namespace?</p>\n\n<hr>\n\n<pre><code>struct FileSystem\n</code></pre>\n\n<p>This struct has no state. Could be a namespace.</p>\n\n<hr>\n\n<pre><code>using StatusInfo = struct stat;\n</code></pre>\n\n<p>This kind of thing is a common practice so maybe some readers will like it, but I think it's easier to just see <code>struct stat</code>. One day, someone may refactor your code and move the definition of <code>StatusInfo</code> away from some of the uses. Then any new developers will have to look it up. Also, nothing is stopping you from ending up with uses of <code>struct stat</code> AND <code>StatusInfo</code> mixed together which would be pointless.</p>\n\n<p>Also, <code>stat</code> is an unfortunate name because it's short and generic, but <code>StatusInfo</code> is only longer -- it's still generic. If you have to alias it, how about <code>FileStatusInfo</code>?</p>\n\n<hr>\n\n<pre><code>for (std::size_t pos = path.find('/'); pos != std::string::npos; pos = path.find(pos + 1, '/'))\n</code></pre>\n\n<p>I see what you're going for. This is fine, but the repeated check for <code>/</code> is not ideal. How about something like:</p>\n\n<pre><code>for (std::size_t pos = -1; pos != std::string::npos; /*in loop*/) {\n pos = path.find(pos + 1, '/');\n</code></pre>\n\n<p>This might be controversial!</p>\n\n<hr>\n\n<pre><code>path.find('/')\n</code></pre>\n\n<p>This gives up portability and makes me worry about paths that have <code>//</code> or <code>/./</code>. Maybe these things don't matter for your use case?</p>\n\n<hr>\n\n<pre><code>stat(subPath.c_str(), &info)\n</code></pre>\n\n<p>What's this intended to do? You never read <code>info</code>. It sounds like you're using it to check if a file/dir exists? <code>stat</code> can fail for a lot of reasons...</p>\n\n<hr>\n\n<pre><code>((stat(subPath.c_str(), &info) != 0) && (mkdir(subPath.c_str(), permissions) != 0))\n</code></pre>\n\n<p>First off it's good you are checking API return values. But...</p>\n\n<p>Suppose this happens:</p>\n\n<ol>\n<li><p><code>stat(subPath.c_str(), &info)</code> returns non-zero presumably to say \"the file/dir doesn't exist\"</p></li>\n<li><p>Another process completely reorganizes the filesystem and permissions.</p></li>\n<li><p>You call <code>mkdir(subPath.c_str(), permissions)</code></p></li>\n</ol>\n\n<p><code>mkdir</code> will fail (and you check for that)... but then what was the point of <code>stat</code>? The idea of looping through parts of a directory has the same problem. You may be able to create one directory, but then you fail. Now the filesystem has a random directory in it.</p>\n\n<p>That might seem like a rare, not-so-bad occurrence. But if you use this function enough times on enough computers, it becomes likely that someone will have a problem because of a bug like that. Weird environments can systematically expose \"unlikely\" bugs and lead to out-of-memory errors or extremely slow filesystems.</p>\n\n<p>The common solution is to create files and if any of the creations fail, then delete the ones you already created. This is hard to get right but most operating systems have APIs to help.</p>\n\n<hr>\n\n<p>It's a little suspicious that you have a loop of <code>stat && mkdir</code> and then after the loop make the same syscalls. Can those be part of the loop?</p>\n\n<hr>\n\n<p>The idea of <code>isFileOpenable</code> suffers from the same problem as the loop above; the file might be openable when you asked, but it might become un-openable immediately after that.</p>\n\n<p>It's much easier to handle filesystem failures than to try and lock files, check their status, do things, then unlock. </p>\n\n<hr>\n\n<pre><code>removeFileOrDirectory\n</code></pre>\n\n<p>This function looks good, but maybe you could simply expose <code>remove</code> from cstdlib?</p>\n\n<hr>\n\n<p>Closing thoughts:</p>\n\n<p>I think this is good code for a personal project or learning about the filesystem APIs, but you haven't handled a lot of the classic problems with filesystem libraries e.g. race conditions and weird failures. C++ has <code>std::filesystem</code> which can do most of this. <code>std::filesystem</code>'s API will try to force you do reasonable things.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T05:17:33.380",
"Id": "473572",
"Score": "1",
"body": "Thanks for the input. I will be updating this weekend and I will incorporate a lot of these things into my code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T03:10:26.097",
"Id": "241339",
"ParentId": "240940",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T16:16:47.397",
"Id": "240940",
"Score": "1",
"Tags": [
"c++",
"file-system"
],
"Title": "FileSystem Utilities wrapper"
}
|
240940
|
<p>This is a pretty huge question, however, I would appreciate it if you could just review the design and not my implementations of it. The <strong>Implementation</strong> and <strong>test</strong> sections could be ignored, they are only there to aid the description of the design, in case I didn't describe it very well. This makes this question have a smaller scope.</p>
<h1>Problem</h1>
<p>I have a system with multiple pieces of equipment that can be in many states <em>(E.g turned on, open, in zone 1, etc)</em>. The total number of possible states of the entire system is very large, as there are many systems. I need to design some software to restrict the number of possible states into a subset that has been deemed desirable.</p>
<p>For the sake of this question, I will reduce the complexity of this system so that it only contains two pieces of equipment that each only have two states, "On" and "Off".</p>
<p>The total number of this states this system can be is therefore 4:</p>
<pre><code>#| item 1 | item 2 |
#| On | On |
#| On | Off |
#| Off | On |
#| Off | Off |
</code></pre>
<p>For this example, let's say that the states that are deemed desirable are the ones where at most only 1 item is on at a time. This reduces the number of states down to 3 and the state machine is.</p>
<pre><code># ,----------------------------,
# v |
# ,----------[BothOffState]--------, |
# | turnOn1() | turnOn2() |
# v v |
# [item1_OnState ] [item2_OnState] |
# | turnOff1() | turnOff2() |
# `---------------------------'-------------'
#
</code></pre>
<h1>Approach 1</h1>
<p>Create the state machine for the whole system, as shown above. The state machine would contain a state object that represents a valid state that my system can have. The state object would have functions to transition into another valid state that is possible to reach from this current state. The state objects would only have functions to transition to states that it has a valid transition to, and every state that I create would represent a valid state.</p>
<h2>Implementation:</h2>
<pre><code>class IState(metaclass=ABCMeta):
def __init__(self, fsm):
print("system : " + fsm.currentState.__class__.__name__ + " -> " + self.__class__.__name__)
self._fsm = fsm
class BothOffState(IState):
def __init__(self, fsm):
super().__init__(fsm)
def turnOn1(self):
self._fsm.currentState = item1_OnState(self._fsm)
def turnOn2(self):
self._fsm.currentState = item2_OnState(self._fsm)
class item1_OnState(IState):
def __init__(self, fsm):
super().__init__(fsm)
def turnOff1(self):
self._fsm.currentState = BothOffState(self._fsm)
class item2_OnState(IState):
def __init__(self, fsm):
super().__init__(fsm)
def turnOff2(self):
self._fsm.currentState = BothOffState(self._fsm)
class FSM:
currentState = None
def __init__(self):
self.currentState = BothOffState(self)
</code></pre>
<p>Test:</p>
<pre><code>if __name__ == "__main__":
system = FSM()
print("<turning on 1>")
system.currentState.turnOn1()
#system.currentState.turnOn2() AttributeError because this state transition doesn't exist
print("<turning off 1>")
system.currentState.turnOff1()
print("<turning on 2>")
system.currentState.turnOn2()
#Output:
#
# system : NoneType -> BothOffState
# <turning on 1>
# system : BothOffState -> item1_OnState
# <turning off 1>
# system : item1_OnState -> BothOffState
# <turning on 2>
# system : BothOffState -> item2_OnState
</code></pre>
<h2>Problem with this approach</h2>
<p>This seems fine but it is not very scalable. If there are 20 items, and each has an average of 5 states, this would mean creating 3.2 million state objects to represent all of the possible states of the whole system. Even if half of them are considered undesirable and so are not created, this is still too many to realistically implement.</p>
<h1>Approach 2: Scalable design of a system with multiple state machines, where valid state transitions depend on the state of other machines:</h1>
<p>Instead of using 1 mega state-machine for the whole system, instead, create smaller state machines for each item that can interact with each other. Instead of states directly transitioning into each other, they will go into an intermediate state where they will evaluate if it is a valid state transition within the context of the wider system. Failure will result in it returning to the state it entered from, and success would move to the desired state </p>
<p>The state machines would now look like:</p>
<pre><code># item1 state machine item2 state machine
#
# [OffState] <--------, [OffState] <--------,
# | turnOn() | | turnOn() |
# v eval()| v eval()|
# [EvaluateCanTurnOnState]->| [EvaluateCanTurnOnState]->|
# | eval() | | eval() |
# v | v |
# [OnState] | [OnState] |
# | turnOff() | | turnOff() |
# '---------------' '---------------'
# State machines are linked, as the input to one of the state transitions `eval()` is the other state machine
</code></pre>
<p>In this example, the 2 systems have identical states, however, the idea still works with heterogeneous systems.</p>
<p>When the FSM's are created they will be given a reference to any other state machine that they have a dependency on. The intermediate <code>Eval</code> states will use this reference to decide if the next state should be the desired state or if it should go back to the previous state.</p>
<h2>Implementation:</h2>
<pre><code>class IState(metaclass=ABCMeta):
def __init__(self, fsm):
print(fsm.name + " : " + fsm.currentState.__class__.__name__ + " -> " + self.__class__.__name__)
self._fsm = fsm
class OffState(IState):
def __init__(self, fsm):
super().__init__(fsm)
def turnOn(self):
self._fsm.currentState = EvaluateCanTurnOnState(self._fsm)
self._fsm.currentState.eval(self._fsm.otherStateMachine)
class EvaluateCanTurnOnState(IState):
def __init__(self, fsm):
super().__init__(fsm)
def eval(self, otherFsm):
if otherFsm.currentState.__class__.__name__ == "OffState":
self._fsm.currentState = OnState(self._fsm)
else:
self._fsm.currentState = OffState(self._fsm)
class OnState(IState):
def __init__(self, fsm):
super().__init__(fsm)
def turnOff(self):
self._fsm.currentState = OffState(self._fsm)
class FSM:
currentState = None
otherStateMachine = None
def __init__(self, name):
self.name = name
self.currentState = OffState(self)
def setOther(self, otherStateMachine):
self.otherStateMachine = otherStateMachine
</code></pre>
<p>Test:</p>
<pre><code>if __name__ == "__main__":
fsm1 = FSM("item1")
fsm2 = FSM("item2")
fsm1.setOther(fsm2)
fsm2.setOther(fsm1)
fsm1.currentState.turnOn()
fsm2.currentState.turnOn()
fsm1.currentState.turnOff()
fsm2.currentState.turnOn()
#Output:
#
# item1 : NoneType -> OffState
# item2 : NoneType -> OffState
# item1 : OffState -> EvaluateCanTurnOnState
# item1 : EvaluateCanTurnOnState -> OnState
# item2 : OffState -> EvaluateCanTurnOnState
# item2 : EvaluateCanTurnOnState -> OffState
# item1 : OnState -> OffState
# item2 : OffState -> EvaluateCanTurnOnState
# item2 : EvaluateCanTurnOnState -> OnState
</code></pre>
<h1>Discussion</h1>
<p>The second approach seems more scalable, as the states of the whole system to not have to be explicitly defined. The dependencies between each state machine are captured during construction of the object, and if the number of dependent machines grows, this could be tidied up with a builder object.</p>
<p>However, I have never seen this design before (because I don't really know where to look). I do not know if the complexity of this will actually become unmaintainable or prone to bugs.</p>
<p>Surely this is a common problem and has already been solved? What is the standard design to use in a situation like this? If there isn't a standard design pattern, do you think the design I have suggested is good design?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T03:21:25.357",
"Id": "472777",
"Score": "1",
"body": "_just review the design and not my implementations of it_ - unfortunately, that is not how Code Review works. You can certainly ask for a focus on the design, and even choose to only upvote answers that do so, but answers that review your implementation will still be on-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T03:27:04.843",
"Id": "472778",
"Score": "1",
"body": "_the ones where only 1 item is on at a time. This reduces the number of states down to 3_ - I think you mean \"at most one item is on at a time\", to allow for the case where they are both off."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T09:55:50.933",
"Id": "472825",
"Score": "1",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. Tip for next time: *never* post example code on Code Review and please take a look at the [help/on-topic]. Thanks!"
}
] |
[
{
"body": "<p>This doesn't have to be complicated. Definitely avoid Approach 1 - having a dedicated class for state combinations is not a good idea. Follow vaguely Approach 2, but</p>\n\n<ul>\n<li>Do not have a <code>class OffState</code>, nor a class for any specific state</li>\n<li>Do not have a dedicated class for <code>EvaluateCanTurnOnState</code></li>\n<li>Track states with enumeration members</li>\n<li>Have an equipment superclass, where each subclass implements a state transition predicate</li>\n</ul>\n\n<p>Example:</p>\n\n<pre><code>from enum import Enum\nfrom typing import Type, List\n\n\nclass Equipment:\n States: Type[Enum]\n\n def __init__(self):\n self.state: Equipment.States = None\n\n def change(self, new_state: 'Equipment.States'):\n if not self.can_change(new_state):\n raise ValueError(\n f'{type(self).__name__} cannot change '\n f'from {self.state} to {new_state}'\n )\n self.state = new_state\n\n def can_change(self, new_state: 'Equipment.States') -> bool:\n raise NotImplementedError()\n\n\nclass ExclusiveEq(Equipment):\n class States(Enum):\n OFF = 0\n ON = 1\n\n def __init__(self, name: str):\n super().__init__()\n self.name = name\n\n def __str__(self):\n return self.name\n\n def can_change(self, new_state: 'ExclusiveEq.States') -> bool:\n if new_state != self.States.ON:\n return True\n return all(\n not isinstance(r, ExclusiveEq)\n or r is self\n or r.state != self.States.ON\n for r in registry\n )\n\n\nregistry: List[Equipment] = [\n ExclusiveEq('blender'),\n ExclusiveEq('coffeemaker'),\n ExclusiveEq('ion cannon'),\n]\n\nregistry[0].change(ExclusiveEq.States.ON)\nregistry[0].change(ExclusiveEq.States.OFF)\nregistry[1].change(ExclusiveEq.States.ON)\nregistry[1].change(ExclusiveEq.States.OFF)\nregistry[2].change(ExclusiveEq.States.ON)\n\ntry:\n registry[0].change(ExclusiveEq.States.ON)\n raise AssertionError('This should have failed')\nexcept ValueError:\n pass\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T03:59:35.520",
"Id": "240983",
"ParentId": "240948",
"Score": "5"
}
},
{
"body": "<h3>Approach 3</h3>\n\n<p>As a third approach, you might consider a hierarchical state machine. The system as a whole could have a state machine with states such as starting_up, running, shutting_down. Then different kinds of components or groups of components could have state machines whose transition table depend on the system state (or there are different tables for different states). Likewise, the system can change state based on the states of the sub state machines (e.g., when they are all running, then the system can transition to the running state). Further, each component has it's own state machine that depends on the state of it's parent state machine. The state machines at any given level are more or less independent of each other. They change state based on the inputs, but unrecognized inputs get passed up to their parent state machine.</p>\n\n<p>Consider a basic HVAC system. The system may have states: OFF, COOL, HEAT. A thermostat can send a signal that the temperature is above or below the temperature set point. The A/C component has a state machine that response to the thermostat signal if the system state machine is the the COOL state. It can also respond to internal signals such as compressor temperature, or refrigerant suction pressure, etc. Similarly, the furnace can respond if the system is in the HEAT state, and can also respond to internal signals such as low pilot light temperature or high flue temperature.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-05T06:30:57.780",
"Id": "241736",
"ParentId": "240948",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T17:36:43.847",
"Id": "240948",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"design-patterns",
"state-machine",
"state"
],
"Title": "Scalable design of a system with multiple state machines, where valid state transitions depend on the state of other machines"
}
|
240948
|
<p>For my game engine I am implementing ImGui for debugging purposes. In order to manage ImGui I have made a singleton to make sure only one ImGui context gets created. I am not entirely sure if this is a good implementation of a Singleton so I am looking for some feedback, also is using a Singleton here the right way or could I better use a full static class?</p>
<p><strong>ImGUIManager.h</strong></p>
<pre><code>#ifndef CHEETAH_CORE_IMGUIMANAGER_H_
#define CHEETAH_CORE_IMGUIMANAGER_H_
#include "Core.h"
#include "../ImGUI/imgui.h"
#include <memory>
namespace cheetah
{
class CH_API ImGUIManager
{
public:
static void init();
static void shutDown();
static void begin();
static void end();
static inline ImFont* getTextFont() { return ImGUIManager::getInstance()->m_text; };
static inline ImFont* getIconSmallFont() { return ImGUIManager::getInstance()->m_iconSmall; };
static inline ImFont* getIconLargeFont() { return ImGUIManager::getInstance()->m_iconLarge; };
virtual ~ImGUIManager() = default;
protected:
ImGUIManager() = default;
virtual void init_impl() = 0;
virtual void shutDown_impl() = 0;
virtual void begin_impl() = 0;
virtual void end_impl() = 0;
protected:
ImFont* m_text = nullptr;
ImFont* m_iconSmall = nullptr;
ImFont* m_iconLarge = nullptr;
private:
static ImGUIManager* getInstance();
static void create();
private:
static std::unique_ptr<ImGUIManager> m_instance;
};
}
#endif // !CHEETAH_ENGINE_IMGUI_IMGUIMANAGER_H_
</code></pre>
<p><strong>ImGUIManager.cpp</strong></p>
<pre><code>#include "ImGUiManager.h"
#include "Renderer/RenderAPI.h"
#include "Platform/OpenGL/OpenGLImGUIManager.h"
namespace cheetah
{
std::unique_ptr<ImGUIManager> ImGUIManager::m_instance = nullptr;
void ImGUIManager::init()
{
#ifdef DEBUG
static bool initialized = false;
ASSERT(!initialized, "ImGUI is already initialized");
#endif // DEBUG
ImGUIManager::getInstance()->init_impl();
#ifdef DEBUG
initialized = true;
#endif
};
void ImGUIManager::shutDown()
{
ImGUIManager::getInstance()->shutDown_impl();
};
void ImGUIManager::begin()
{
ImGUIManager::getInstance()->begin_impl();
};
void ImGUIManager::end()
{
ImGUIManager::getInstance()->end_impl();
};
ImGUIManager* ImGUIManager::getInstance()
{
if (!m_instance)
ImGUIManager::create();
return m_instance.get();
}
void ImGUIManager::create()
{
switch (RenderAPI::getAPI())
{
case RenderAPI::API::OpenGL:
m_instance = std::make_unique<opengl::OpenGLImGUIManager>();
break;
default:
m_instance = nullptr;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Its not thread safe!</p>\n\n<p>Looks like you can still create instances manually (though you would have to derive a class that can use the protected constructor) or copy the one created by <code>getInstance()</code>.</p>\n\n<p>Why not use the classic Singleton pattern?</p>\n\n<pre><code>class ImGUIManager\n{\n public:\n static ImGUIManager& getInstance()\n {\n static ImGUIManager instance; // static member\n // Correctly constructed on first use.\n // Will be deleted on exit.\n return instance;\n }\n // PUT YOUR INTERFACE HERE\n\n private:\n ImGUIManager(){} // Make sure the constructor is private.\n // Delete the copy and move constructors.\n ImGUIManager(ImGUIManager const&) = delete;\n ImGUIManager& operator=(ImGUIManager const&) = delete;\n ImGUIManager(ImGUIManager&&) = delete;\n ImGUIManager& operator=(ImGUIManager&&) = delete;\n};\n</code></pre>\n\n<p>Some References:</p>\n\n<p><a href=\"https://stackoverflow.com/a/1008289/14065\">C++ Singleton design pattern</a> </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T12:44:13.843",
"Id": "472852",
"Score": "0",
"body": "The protected constructor is there with a reason, because this class can have different implementations per example with OpenGL and Vulkan, these implementations are defined in a derived class. also could you explain what your example makes it thread safe? I have no experience with threading in c++ so I have some difficulty seeing how this would make it thread safe."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T15:49:19.417",
"Id": "472885",
"Score": "0",
"body": "@RickNijhuis The construction of static storage duration objects is guaranteed by the standard to be thread safe."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T15:51:06.467",
"Id": "472888",
"Score": "0",
"body": "If you want want to have more than one implementation (presumably only one is ever valid during runtime (otherwise how is it a singleton) then you need to combine this pattern with the factory pattern."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T20:13:43.423",
"Id": "240959",
"ParentId": "240953",
"Score": "1"
}
},
{
"body": "<blockquote>\n <p>I am not entirely sure if this is a good implementation of a Singleton so I am looking for some feedback, also is using a Singleton here the right way or could I better use a full static class?</p>\n</blockquote>\n\n<p>I believe there's no added value to that setup and you'd be better off without it. This is just extra code and more complexity. </p>\n\n<p>Supposedly you are trying to solve \"to make sure only one ImGui context gets created\", is that a real problem you have or an hypothetical problem?</p>\n\n<p>My advice, don't create code that don't solve important problem. By doing so you are not spending time working on useful features and important problems. This is not an important problem. People on those communities will often tell you the opposite, ask them what software they are shipped.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T16:25:35.437",
"Id": "241016",
"ParentId": "240953",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "240959",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T18:36:21.673",
"Id": "240953",
"Score": "1",
"Tags": [
"c++"
],
"Title": "ImGui manager singleton"
}
|
240953
|
<p>I'm trying to split an incoming stream of strings into cumulative tokens per line item using a function below,</p>
<pre><code>def cumulativeTokenise(string: String): Array[String] = {
val array = string.split(" +")
var result: Array[String] = Array()
array.map { i => (
result = result :+ (
if (result.lastOption == None) i
else result.lastOption.getOrElse("")+ " " + i
)
)
}
result
}
</code></pre>
<p>Ex: output of cumulativeTokenise("TEST VALUE DESCRIPTION . AS") would be => Array(TEST, TEST VALUE, TEST VALUE DESCRIPTION, TEST VALUE DESCRIPTION ., TEST VALUE DESCRIPTION . AS)</p>
<p>Trying to figure out if there's another efficient in-built method in Scala or better ways of doing it with FP, without any mutable array. Any help is much appreciated. </p>
<p><a href="https://i.stack.imgur.com/pZYeO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pZYeO.png" alt="enter image description here"></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T12:53:39.470",
"Id": "472854",
"Score": "0",
"body": "Have you tried scanLeft where the initial parameter is an empty list?"
}
] |
[
{
"body": "<p>You can get the same results a little more directly.</p>\n\n<pre><code>def cumulativeTokenise(string: String): Array[String] =\n string.split(\"\\\\s+\")\n .inits\n .map(_.mkString(\" \"))\n .toArray\n .reverse\n .tail\n</code></pre>\n\n<p>Or a, perhaps simpler, two step procedure.</p>\n\n<pre><code>def cumulativeTokenise(string: String): Array[String] = {\n val tokens = string.split(\"\\\\s+\")\n Array.tabulate(tokens.length)(n => tokens.take(n+1).mkString(\" \"))\n}\n</code></pre>\n\n<p>One problem I see here is that you rely on whitespace to separate tokens. That might not always be the case.</p>\n\n<pre><code>def cumulativeTokenise(string: String): Array[String] =\n string.split(\"((?=\\\\W)|(?<=\\\\W))\")\n .filter(_.trim.nonEmpty)\n .inits\n .map(_.mkString(\" \"))\n .toArray\n .reverse\n .tail\n\ncumulativeTokenise(\"here@there\")\n//res0: Array[String] = Array(here, here @, here @ there)\n</code></pre>\n\n<p>Probably not the best solution to the problem, but it's something to think about.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T13:51:14.037",
"Id": "473026",
"Score": "0",
"body": "I like the Array tabulate approach, I'm using whitespace because that was the requirement given to me. Thanks jwvh"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T12:14:55.193",
"Id": "241061",
"ParentId": "240954",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "241061",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T18:43:32.430",
"Id": "240954",
"Score": "3",
"Tags": [
"strings",
"functional-programming",
"scala"
],
"Title": "Scala: Cumulative String Tokenisation"
}
|
240954
|
<p>Extending <a href="https://meta.stackexchange.com/a/292846/712835">this answer</a> solution, I've wrote the following <code>bash script</code> to get the html of <a href="https://stackexchange.com/users/3581081/artu-hnrq?tab=accounts">my StackExchange accounts page</a> and parse it to a <a href="https://yaml.org/" rel="nofollow noreferrer">YAML</a> file. The objective was list for each community I participate its url and my user id.</p>
<p><em>get-stackexchange-info.sh</em></p>
<pre><code>#!/bash/bin
NETWORK_PROFILE_URL=$1 # https://stackexchange.com/users/3581081/artu-hnrq
read -r ID USER <<< \
$( cut -d'/' -f5,6 <<< $NETWORK_PROFILE_URL \
| sed 's/\// /g' \
)
OUTPUT_FILE=stackexchange.yml
echo \
"user: $USER
stackexchange:
url: http://stackexchange.com
id: $ID" \
> $OUTPUT_FILE
parse(){
local HTTPS="https:\/\/"
local COMMUNITY="[^\.]*"
local DOMAIN="[^\/]*"
local PROFILE_ID="\d*"
local MODEL="\1:\n url: $HTTPS\1\2\n id: \3"
sed -E "s/($COMMUNITY)($DOMAIN)\/($PROFILE_ID)/$MODEL/"
}
curl "https://stackexchange.com/users/$ID/$USER?tab=accounts" \
| grep "account-container" -A1 \
| grep "http" \
| cut -d"/" -f3,5 \ # stackoverflow.com/3581081
| parse \
>> $OUTPUT_FILE
</code></pre>
<p>I would like to receive some opinions about the parse process (usage of <code>grep</code>, <code>cut</code> and <code>sed</code> commands) and about control flow management could be improved to the script</p>
<p><em>output example:</em></p>
<pre><code>user: artu-hnrq
stackexchange:
url: https://stackexchange.com
id: 3581081
askubuntu:
url: https://askubuntu.com
id: 689894
stackoverflow:
url: https://stackoverflow.com
id: 2989289
codereview:
url: https://codereview.stackexchange.com
id: 213097
</code></pre>
<p>Thanks a lot!</p>
|
[] |
[
{
"body": "<p>I see 2 errors and have some more advice.</p>\n<p>The Shebang is wrong.</p>\n<pre><code>#!/bash/bin\nshould be\n#!/bin/bash\n</code></pre>\n<p>Do not put comment after the <code>\\</code> escape for a new line</p>\n<pre><code>| cut -d"/" -f3,5 \\ # stackoverflow.com/3581081\n# should be\n| cut -d"/" -f3,5 \\\n</code></pre>\n<p>I would move all functions (in your case only <code>parse()</code>) to the top of the file.</p>\n<p>Use lowercase variables (uppercase is reserved for system variables like PATH).</p>\n<pre><code>NETWORK_PROFILE_URL=\n# change to\nnetwork_profile_url=\n</code></pre>\n<p>Combine <code>cut</code> and <code>sed</code></p>\n<pre><code>read -r ID USER <<< \\\n $( cut -d'/' -f5,6 <<< $NETWORK_PROFILE_URL \\\n | sed 's/\\// /g' \\\n )\n# can be replaced by\nread -r ID USER < <(awk -F "/" '{print $(NF-1) " " $NF }' <<< $NETWORK_PROFILE_URL)\n# which is easier to read then\nsource <(sed -r 's#.*/(.*)/(.*)#ID=\\1; USER=\\2#' <<< $NETWORK_PROFILE_URL)\n</code></pre>\n<p>When you end a line with a pipe, you do not need to escape the newline with <code>\\</code>.</p>\n<pre><code>curl "https://stackexchange.com/users/$ID/$USER?tab=accounts" \\\n | grep "account-container" -A1 \\\n | grep "http" \\\n | cut -d"/" -f3,5 \\\n | parse \n# can be changed into\ncurl "https://stackexchange.com/users/$ID/$USER?tab=accounts" |\n grep "account-container" -A1 |\n grep "http" |\n cut -d"/" -f3,5 |\n parse \n</code></pre>\n<p>You had a hard job parsing the <code>curl</code> output with different tools. In this situation you won't need to parse large files, the performancy penalty is very small. It is worth the effort for other cases to look for a solution with <code>awk</code>.<br />\nThe <code>grep -A1</code> is replaced by setting a flag for parsing the next line.<br />\nFields are found with the delimiter '/'.<br />\nCombining <code>substr</code> is only slightly more complex:</p>\n<pre><code>curl -s "https://stackexchange.com/users/$ID/$USER?tab=accounts" |\n awk -F "[/]" '\n parse==1 {\n print substr($3,1,index($3,".")-1) ":";\n printf(" url: https://%s\\n", $3);\n printf(" id: %s\\n", $5);\n parse=0;\n }\n /account-container/ {parse=1}\n '\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-21T23:24:09.637",
"Id": "508604",
"Score": "1",
"body": "Hi, Walter! Thanks for your attention here. I'll improve the script with your suggestions"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-21T19:38:56.940",
"Id": "257485",
"ParentId": "240958",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "257485",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T19:49:48.163",
"Id": "240958",
"Score": "5",
"Tags": [
"parsing",
"bash",
"stackexchange",
"sed",
"yaml"
],
"Title": "Listing my StackEchange communities user id"
}
|
240958
|
<p>I'm new to JavaScript and I decided to make a script that allows other developers to show SVG elements in the web browser. (It is just for learning purposes), and it is still under development.</p>
<p>I coded it in ES5 first and then I'm willing to upgrade it to ES6+ so I can learn and understand the differences.</p>
<p>I really appreciate your help to review it before I move forward and tell me what is wrong, what can I improve, if I used a design pattern in a wrong place... any help from you will be great.</p>
<p>So I tried to implement MVC pattern, inheritance, Factory pattern, function statement, function expression, IIFE ...</p>
<p>index.html:</p>
<pre><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="rasm.js"></script>
<script src="app.js"></script>
</body>
</html>
</code></pre>
<p>src lib:</p>
<pre><code>var modelController = function() {'use_strict';
var createSVGElment = function(qualifiedName) {
return document.createElementNS('http://www.w3.org/2000/svg', qualifiedName)
};
var Element = function(options) {
this.element = null;
this.style = options.style || '';
};
Element.prototype.buildElement = function() {
this.element.setAttribute('style', this.style);
};
var Container = function(options) {
Element.call(this, options);
this.height = options.height || 700;
this.width = options.width || 1200;
this.element = createSVGElment('svg');
};
Container.prototype.buildElement = function() {
Element.prototype.buildElement.call(this);
this.element.setAttribute('width', this.width);
this.element.setAttribute('height', this.height);
};
var Rectangle = function(options) {
Element.call(this, options);
this.height = options.height;
this.width = options.width;
this.x = options.x;
this.y = options.y;
this.text = options.text;
this.element = createSVGElment('rect');
};
Rectangle.prototype.buildElement = function() {
Element.prototype.buildElement.call(this);
this.element.setAttribute('x', this.x);
this.element.setAttribute('y', this.y);
this.element.setAttribute('width', this.width);
this.element.setAttribute('height', this.height);
};
var Ellipse = function(options) {
Element.call(this, options);
this.x = options.cx;
this.y = options.cy;
this.rx = options.rx;
this.width = options.rx * 2;
this.ry = options.ry;
this.height = options.ry * 2;
this.text = options.text;
this.element = createSVGElment('ellipse');
};
Ellipse.prototype.buildElement = function() {
Element.prototype.buildElement.call(this);
this.element.setAttribute('cx', this.x);
this.element.setAttribute('cy', this.y);
this.element.setAttribute('rx', this.rx);
this.element.setAttribute('ry', this.ry);
};
var Link = function(options) {
Element.call(this, options);
this.from = options.from;
this.to = options.to;
this.defsElement = createSVGElment('defs');
this.element = createSVGElment('line');
this.camputePath = function() {
if (this.from instanceof Ellipse) {
this.fromX = this.from.x + this.from.rx;
this.fromY = this.from.y;
} else {
this.fromX = this.from.x + this.from.width;
this.fromY = this.from.y + (this.from.height / 2);
}
if (this.to instanceof Ellipse) {
this.toX = this.to.x - this.to.rx;
this.toY = this.to.y;
} else {
this.toX = this.to.x;
this.toY = this.to.y + (this.to.height / 2);
}
};
};
Link.prototype.buildElement = function() {
var pathEelement = createSVGElment('path');
pathEelement.setAttribute('d', 'M0,0 L0,6 L7,3 z');
pathEelement.setAttribute('fill', '#000');
var markerEelement = createSVGElment('marker');
markerEelement.setAttribute('id', 'arrow');
markerEelement.setAttribute('markerWidth', '10');
markerEelement.setAttribute('markerHeight', '10');
markerEelement.setAttribute('refX', '0');
markerEelement.setAttribute('refY', '3');
markerEelement.setAttribute('orient', 'auto');
markerEelement.setAttribute('markerUnits', 'strokeWidth');
markerEelement.appendChild(pathEelement);
this.defsElement.appendChild(markerEelement);
this.camputePath();
this.element.setAttribute('x1', this.fromX);
this.element.setAttribute('y1', this.fromY);
this.element.setAttribute('x2', this.toX - 10);
this.element.setAttribute('y2', this.toY);
this.element.setAttribute('stroke', '#000');
this.element.setAttribute('stroke-width', '2');
this.element.setAttribute('marker-end', 'url(#arrow)');
};
var Text = function(options) {
Element.call(this, options);
this.x = options.x;
this.y = options.y;
this.value = options.value;
this.element = createSVGElment('text');
};
Text.prototype.buildElement = function() {
Element.prototype.buildElement.call(this);
this.element.setAttribute('x', this.x);
this.element.setAttribute('y', this.y);
this.element.textContent = this.value;
};
// Element factory
function ElementFactory() {};
ElementFactory.prototype.createElement = function(o) {
switch(o.type) {
case 'container':
this.elementClass = Container;
break;
case 'rect':
this.elementClass = Rectangle;
break;
case 'ellipse':
this.elementClass = Ellipse;
break;
case 'link':
this.elementClass = Link;
break;
case 'text':
this.elementClass = Text;
break;
default:
throw 'Warning: the type ' + o.type + ' is invalid';
}
return new this.elementClass(o);
};
var elementFactory = new ElementFactory();
// storing register
var register = {
eltSVG: null,
elts: []
};
return {
registerElement: function(options) {
var el = elementFactory.createElement(options);
if (options.type === 'container') {
register.eltSVG = el;
} else {
register.elts.push(el);
}
return el;
},
getRegister: function() {
return register;
},
};
}();
var viewController = function() {'use_strict';
return {
displayElement: function(el) {
var selector = el.element.tagName === 'svg' ? 'body' : 'svg';
el.buildElement();
if (el.defsElement) { // for line element
document.querySelector(selector).appendChild(el.defsElement);
}
document.querySelector(selector).appendChild(el.element);
},
};
}();
(function(global, model, view) {'use_strict';
function processText(el, o) {
if (['above', 'inside', 'below'].indexOf(o.text.position) < 0) {
throw "Text position must be: above, inside or below and not " + o.text.position;
}
var x, y;
if (el.element.tagName === 'rect') {
x = el.x + (el.width * 0.1) // 20% of the width
if (o.text.position === 'above') {
y = el.y - 5;
} else if (o.text.position === 'inside') {
y = el.y + (el.height / 2);
} else if (o.text.position === 'below') {
y = el.y + el.height + 20;
}
} else { // ellipse
x = el.x - (el.rx * 0.2)
if (o.text.position === 'above') {
y = el.y - el.ry - 5;
} else if (o.text.position === 'inside') {
y = el.y;
} else if (o.text.position === 'below') {
y = el.y + el.ry + 20;
}
}
return {
x: x,
y: y,
}
};
global.$R = global.Rasm = {
draw: function(options) {
if (options.type !== 'container' && !model.getRegister().eltSVG) {
throw 'You must create an svg element first';
}
var el = model.registerElement(options);
view.displayElement(el);
// process text option
if (options.text) {
var textCoord = processText(el, options);
var text = model.registerElement({
"type": "text",
"x": textCoord.x,
"y": textCoord.y,
"value": options.text.value,
});
view.displayElement(text);
}
return el;
},
};
})(window, modelController, viewController);
</code></pre>
<p>An example of how we can use it: </p>
<pre><code>$R.draw({
"type": "container",
"height": 700,
"width": 1100,
});
/** Left side */
var rect1 = $R.draw({
"type": "rect",
"x": 20,
"y": 20,
"width": 345,
"height": 648,
"style": "stroke-dasharray: 5.5; stroke: #006600; fill: #fff"
});
var rect2 = $R.draw({
"type": "rect",
"x": 50,
"y": 100,
"width": 250,
"height": 100,
"text": {
"position": "inside",
"value": "I'm a text inside a rectangle"
},
"style": "stroke: #006600; fill: #fff"
});
var rect3 = $R.draw({
"type": "rect",
"x": 50,
"y": 300,
"width": 250,
"height": 100,
"text": {
"position": "above",
"value": "I'm a text above a rectangle"
},
"style": "stroke: #006600; fill: #fff"
});
var rect4 = $R.draw({
"type": "rect",
"x": 50,
"y": 500,
"width": 250,
"height": 100,
"text": {
"position": "below",
"value": "I'm a text below a rectangle"
},
"style": "stroke: #006600; fill: #fff"
});
/** Right side */
var rect5 = $R.draw({
"type": "rect",
"x": 700,
"y": 20,
"width": 345,
"height": 648,
"style": "stroke-dasharray: 20; stroke: #006600; fill: #fff"
});
var ellipse1 = $R.draw({
"type": "ellipse",
"cx": 870,
"cy": 200,
"rx": 150,
"ry": 70,
"text": {
"position": "above",
"value": "I'm a text above an ellipse"
},
"style": "stroke: #129cc9; fill: #b5e5f5"
});
var ellipse2 = $R.draw({
"type": "ellipse",
"cx": 860,
"cy": 500,
"rx": 100,
"ry": 70,
"text": {
"position": "inside",
"value": "I'm a text inside an ellipse"
},
"style": "stroke: #129cc9; fill: #b5e5f5"
});
/** Links */
$R.draw({
"type": "link",
"from": rect2,
"to": ellipse2,
});
$R.draw({
"type": "link",
"from": rect3,
"to": ellipse1,
});
$R.draw({
"type": "link",
"from": rect4,
"to": ellipse1,
});
</code></pre>
<p>the result:
<a href="https://i.stack.imgur.com/v7l7j.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/v7l7j.png" alt="surjective mapping from rectangles to ellipses"></a></p>
<p>I hope you concentrate only on the lib structure and code, the SVG example that I took is just to be able to practice what I have learned.</p>
|
[] |
[
{
"body": "<h1>General feedback</h1>\n<p>For a <a href=\"/questions/tagged/beginner\" class=\"post-tag\" title=\"show questions tagged 'beginner'\" rel=\"tag\">beginner</a> this looks quite thorough, though I did spot a couple places where improvements can be made. See the suggestions below. It is really tempting to suggest <a href=\"/questions/tagged/ecmascript-6\" class=\"post-tag\" title=\"show questions tagged 'ecmascript-6'\" rel=\"tag\">ecmascript-6</a> features but I will resist the temptation because you seem to want to stick with ES5 for now.</p>\n<h1>Suggestions</h1>\n<h2>Strict mode</h2>\n<p>Some functions contain:</p>\n<blockquote>\n<pre><code>'use_strict';\n</code></pre>\n</blockquote>\n<p>This contains an underscore but should not.<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode#Invoking_strict_mode\" rel=\"nofollow noreferrer\">1</a></sup></p>\n<pre><code>'use strict';\n</code></pre>\n<p>And instead of adding it to each wrapping function, it could be added <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode#Strict_mode_for_scripts\" rel=\"nofollow noreferrer\">to the entire script</a>.</p>\n<h2>Prototypical inheritance</h2>\n<p>Apparently <code>Element</code> does not have any methods that are not overridden by sub-classes. However if there were any, those would not be inherited properly. For example, say there was a method called <code>getSides</code> on Element:</p>\n<pre><code>Element.prototype.getSides = function() {\n return 3;\n};\n</code></pre>\n<p>And one of the sub-classes needed to call that function</p>\n<pre><code>Container.prototype.buildElement = function() {\n const sides = this.getSides();\n</code></pre>\n<p>This would lead to an error:</p>\n<blockquote>\n<p>Uncaught TypeError: this.getSides is not a function</p>\n</blockquote>\n<p>To be thorough the sub-classes should have the prototype set to <code>Element.prototype</code> -</p>\n<p>e.g.</p>\n<pre><code>Container.prototype = Object.create(Element.prototype);\nObject.defineProperty(Container.prototype, 'constructor', { \n value: Container, \n enumerable: false, // so that it does not appear in 'for in' loop\n writable: true }); \nRectangle.prototype = Object.create(Element.prototype); \nObject.defineProperty(Rectangle.prototype, 'constructor', { \n value: Rectangle, \n enumerable: false, // so that it does not appear in 'for in' loop\n writable: true }); \nEllipse.prototype = Object.create(Element.prototype);\nObject.defineProperty(Ellipse.prototype, 'constructor', { \n value: Ellipse, \n enumerable: false, // so that it does not appear in 'for in' loop\n writable: true });\n//... and so on... \n</code></pre>\n<p>Refer to <a href=\"https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Inheritance#Setting_Teachers_prototype_and_constructor_reference\" rel=\"nofollow noreferrer\">this section of the MDN page <em>Inheritance in JavaScript</em></a></p>\n<hr />\n<h2>Typo on Method name</h2>\n<p>There is a typo in the Link method <code>camputePath</code> - presumably it should be <code>computePath</code>...</p>\n<hr />\n<h2>Method added to each instance instead of prototype</h2>\n<p><code>computePath</code> is added as a method on each instance of <code>Link</code>. For better performance<sup><a href=\"https://stackoverflow.com/a/4508498/1575353\">2</a></sup> it should be added to the prototype.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-16T12:18:54.927",
"Id": "475680",
"Score": "0",
"body": "I really appreciate your feedback. Yes i'm not beginner to programming but i am beginner to Javascript. For now i wanted to improve this ES5 version first, and then migrate it to ES6.\nI'm going to alter the lib based on your suggestion thank you very much, except the Prototypical inheritance point, the **Element** has a **buildElement** method which is overridden by sub-classes, is that wrong ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-19T22:56:21.033",
"Id": "476055",
"Score": "0",
"body": "With the current code `buildElement` gets _set_ on each class but the prototype chain isn't set properly so they aren't really overriding yet. See my updated answer with context from [the linked MDN documentation](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Inheritance#Setting_Teachers_prototype_and_constructor_reference)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-15T04:39:40.283",
"Id": "242312",
"ParentId": "240961",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T20:44:07.793",
"Id": "240961",
"Score": "3",
"Tags": [
"javascript",
"beginner",
"design-patterns",
"library",
"svg"
],
"Title": "Small Javascript Lib to draw SVG file"
}
|
240961
|
<p>I want to read csv file in to array of structs with NULL ending. </p>
<p>test.txt:</p>
<pre><code>11,345,1,k
12,34.23,3,v
13,13.4,5,x
14,15.7,6,c
</code></pre>
<p>My code:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
struct csv_line {
int value1;
float value3;
int value2;
char char1;
};
struct csv_line *line_pointer = NULL;
int main(void) {
FILE *csvFile = NULL;
csvFile = fopen("test.txt", "r");
if (csvFile == NULL)
exit(1);
size_t i = 0;
while (1) {
line_pointer = (struct csv_line *)realloc(line_pointer, sizeof(struct csv_line) * (i + 1));
if (fscanf(csvFile, "%d,%f,%d,%c",
&(line_pointer + i)->value1,
&(line_pointer + i)->value3,
&(line_pointer + i)->value2,
&(line_pointer + i)->char1) != EOF) {
i++;
} else{
(line_pointer + i)->value1 = 0;
(line_pointer + i)->value3 = 0.0;
(line_pointer + i)->value2 = 0;
(line_pointer + i)->char1 = '\0';
break;
}
}
fclose(csvFile);
int k = 0;
while('\0' != (line_pointer + k)->char1) {
printf("%d, %.2f, %d, %c",
(line_pointer + k)->value1,
(line_pointer + k)->value3,
(line_pointer + k)->value2,
(line_pointer + k)->char1);
printf("\n");
k++;
}
free(line_pointer);
return EXIT_SUCCESS;
}
</code></pre>
<p>Questons:</p>
<ol>
<li>Is it possible to move fscanf condition inside while-loop condition instead of endless (1) ?</li>
<li>How to set "end" of array with single NULL like "line_pointer[i] = NULL" in else statement?</li>
</ol>
|
[] |
[
{
"body": "<p>The following proposed code:</p>\n\n<ol>\n<li>cleanly compiles</li>\n<li>performs the desired functionality</li>\n<li>takes into account the comments to the OPs question</li>\n<li>properly checks for errors when calling <code>malloc()</code> and <code>realloc()</code> and <code>fopen()</code> and <code>fscanf()</code></li>\n<li>the <code>while()</code> loop uses the function: <code>fscanf()</code> rather than a '1' as the loop condition</li>\n<li>uses the value in <code>i</code> to determine when the end of the data is reached</li>\n<li>sets the last instance of the struct to NULL per the OPs request </li>\n<li>per Reinderien's answer and for ease of readability, statements like <code>&(line_pointer + i)->value1</code> (which uses pointer addition) could be replaced with: <code>&(line_pointer[i].value1</code> (which uses indexing)</li>\n</ol>\n\n<p>and now, the proposed code:</p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n\nstruct csv_line {\n int value1;\n float value3;\n int value2;\n char char1;\n};\n\nstruct csv_line *line_pointer = NULL;\n\nint main(void) \n{\n FILE *csvFile = NULL;\n csvFile = fopen(\"test.txt\", \"r\");\n if (csvFile == NULL)\n {\n perror( \"fopen failed\" );\n exit(1);\n }\n\n size_t i = 1;\n line_pointer = malloc( sizeof(struct csv_line) * i );\n if( ! line_pointer )\n {\n perror( \"malloc failed\" );\n fclose( csvFile );\n exit( EXIT_FAILURE );\n }\n\n while ( (fscanf(csvFile, \"%d,%f,%d,%c\",\n &(line_pointer + i)->value1,\n &(line_pointer + i)->value3,\n &(line_pointer + i)->value2,\n &(line_pointer + i)->char1) ) == 4 )\n {\n i++;\n struct csv_line *temp = realloc(line_pointer, sizeof(struct csv_line) * i );\n if( ! temp )\n {\n perror( \"realloc failed\" );\n free( line_pointer );\n fclose( csvFile );\n exit( EXIT_FAILURE );\n }\n }\n\n fclose(csvFile);\n\n // per the request that the last entry contains NULL\n memset( &line_pointer[i], 0, sizeof( struct csv_line ) );\n\n for( size_t k=0; k < (i-1); k++ ) \n {\n printf(\"%d, %.2f, %d, %c\",\n (line_pointer + k)->value1,\n (line_pointer + k)->value3,\n (line_pointer + k)->value2,\n (line_pointer + k)->char1);\n printf(\"\\n\");\n }\n\n free(line_pointer);\n\n return EXIT_SUCCESS;\n}\n</code></pre>\n\n<p>you could try this loop instead:</p>\n\n<pre><code>size_t i = 0;\n\ndo\n{\n i++;\n struct csv_line *temp = realloc(line_pointer, sizeof(struct csv_line) * i );\n if( ! temp )\n {\n perror( \"realloc failed\" );\n free( line_pointer );\n fclose( csvFile );\n exit( EXIT_FAILURE );\n }\n} while ( (fscanf(csvFile, \"%d,%f,%d,%c\",\n &(line_pointer + i)->value1,\n &(line_pointer + i)->value3,\n &(line_pointer + i)->value2,\n &(line_pointer + i)->char1) ) == 4 );\n</code></pre>\n\n<p>so there is only one place allocating memory</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T06:01:30.537",
"Id": "472790",
"Score": "0",
"body": "_Why_ does this code allocate an extra instance? By just saying _what_ you changed but not _why_, your answer had almost no value since it doesn't explain best practices. Plus, you forgot to format the code properly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T08:11:37.887",
"Id": "472809",
"Score": "0",
"body": "Win, mingw debugger fails here: struct csv_line *temp = realloc(line_pointer, sizeof(struct csv_line) * i );"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T13:53:07.547",
"Id": "472862",
"Score": "0",
"body": "I was much more interested in showing the OP how to use the call to `fscanf()` for the control of the `while()` loop as that is what the OP ask about. I also demonstrated how to call `realloc()` so as to avoid a memory leak. I also demonstrated how to handle an error."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T14:05:33.533",
"Id": "472867",
"Score": "0",
"body": "@GarfieldCat, Please post the error message you are getting on the statement that performs the `realloc()`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T14:36:12.090",
"Id": "472873",
"Score": "0",
"body": "@RolandIllig, and what would be 'best practices' for the current scenario?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T14:38:30.413",
"Id": "472874",
"Score": "0",
"body": "@RolandIllig, Since the OP ask for the last instance to be filled with NULL, I have added a call to `memset()` to handle that request."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T15:55:41.447",
"Id": "472889",
"Score": "0",
"body": "Thread #1 0 (Suspended : Signal : SIGTRAP:Trace/breakpoint trap)\nntdll!EtwEventProviderEnabled() at 0x77269372 ntdll!RtlFindClearBits() at 0x772795f1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T19:48:21.403",
"Id": "472915",
"Score": "0",
"body": "@GarfieldCat, As far as I can tell, the error message you provided has nothing to do with a call to `realloc()`"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T22:44:04.707",
"Id": "240970",
"ParentId": "240963",
"Score": "1"
}
},
{
"body": "<p>user3629249's answer is good. The only thing I have to add:</p>\n\n<pre><code>struct csv_line *line_pointer = NULL;\n\n// ...\n\n&(line_pointer + i)->value1\n</code></pre>\n\n<p>is awkward. Why go through the pointer addition acrobatics? Why not just</p>\n\n<pre><code>&line_pointer[i].value1\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T14:07:41.823",
"Id": "472869",
"Score": "0",
"body": "I agree with using an 'index' rather than pointer addition. However, I did not want to confuse the OP"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T03:18:19.947",
"Id": "240982",
"ParentId": "240963",
"Score": "4"
}
},
{
"body": "<p>I'll answer your questions in reverse order:</p>\n\n<blockquote>\n <p>How to set \"end\" of array with single <code>NULL</code> like <code>line_pointer[i] = NULL</code> in <code>else</code> statement?</p>\n</blockquote>\n\n<p>You can (with <code>memset</code>, as shown in other answers), but it's not guaranteed by the C standard that the <code>float</code> value will be set to zero. I would instead suggest to set every value in the structure to zero as you are already doing.</p>\n\n<blockquote>\n <p>Is it possible to move <code>fscanf</code> condition inside <code>while</code>-loop condition instead of endless <code>(1)</code>?</p>\n</blockquote>\n\n<p>You may be able to do this, but I don't recommend it. This would make your code harder to read and comprehend.</p>\n\n<p>Some other issues:</p>\n\n<h2>Check the return value of the *<code>alloc</code> family of functions</h2>\n\n<p>Right here, a crash could happen if you're out of memory:</p>\n\n<pre><code>line_pointer = (struct csv_line *)realloc(line_pointer, sizeof(struct csv_line) * (i + 1));\n</code></pre>\n\n<p>You should add a check just like you do with <code>csvFile</code>:</p>\n\n<pre><code>if(!line_pointer)\n exit(1);\n</code></pre>\n\n<p>Of course, a better error message could be formulated with <code>perror</code>:</p>\n\n<pre><code>if(!line_pointer)\n{\n perror(\"realloc(line_pointer)\");\n exit(1);\n}\n</code></pre>\n\n<p><code>perror</code> will work when <code>fopen</code> fails as well.</p>\n\n<h2>Check the return value of <code>fscanf</code> correctly</h2>\n\n<p>Instead of checking if you've reached the end-of-file,\ncheck whether you didn't read as many variables as expected.\nThis provides a minimal aspect of data validation:</p>\n\n<pre><code> if (fscanf(csvFile, \"%d,%f,%d,%c\",\n &(line_pointer + i)->value1,\n &(line_pointer + i)->value3,\n &(line_pointer + i)->value2,\n &(line_pointer + i)->char1) != 4)\n</code></pre>\n\n<h2>Use <code>EXIT_FAILURE</code> instead of <code>1</code></h2>\n\n<p>As you're using <code>EXIT_SUCCESS</code> to show success, you should go for consistency (and portability) by using <code>EXIT_FAILURE</code> in place of <code>1</code> in <code>exit</code>.</p>\n\n<h2>Use <code>return</code> instead of <code>exit</code></h2>\n\n<p>In addition to the above, in <code>main</code> you can forego using <code>exit</code> and instead use <code>return</code>. There's really no need to use <code>exit</code> in a program under normal circumstances, anyway.</p>\n\n<h2>Don't cast the return value of <code>malloc</code>/<code>calloc</code>/<code>realloc</code></h2>\n\n<p>The return value of <code>realloc</code> can be implicitly converted to any object pointer. It's not necessary to cast it, and in my opinion, avoiding unnecessary casts is a good thing.</p>\n\n<h2>Use array and structure access operators instead of pointer arithmetic</h2>\n\n<p>To me, this looks odd:</p>\n\n<pre><code>(struct_pointer + ctr)->member\n</code></pre>\n\n<p>Instead, you can use array access and the <code>.</code> operator:</p>\n\n<pre><code>struct_pointer[ctr].member\n</code></pre>\n\n<p>This applies equivalently to when you're taking the address of <code>member</code>.</p>\n\n<h2>Use consistent indentation</h2>\n\n<p>In some places, you use two spaces, while in others you use one and four. I suggest sticking to one indentation style, whatever it is. Personally, I use four or a tab, but you can use whatever you want if it's consistent. See the <a href=\"https://www.kernel.org/doc/html/v4.10/process/coding-style.html\" rel=\"nofollow noreferrer\">Linux Kernel Coding Style Guidelines</a> for more information.</p>\n\n<h2>Yoda conditions</h2>\n\n<p>Backwards, your conditions are. This is hard to read and provides little to no benefit, considering that compilers now warn about typos that Yoda conditions originally solved:</p>\n\n<pre><code>while('\\0' != (line_pointer + k)->char1)\n</code></pre>\n\n<p>Instead, just use <code>!=</code> the \"normal\" way:</p>\n\n<pre><code>while((line_pointer + k)->char1 != '\\0')\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T16:00:13.743",
"Id": "241014",
"ParentId": "240963",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T21:48:40.463",
"Id": "240963",
"Score": "4",
"Tags": [
"c",
"array"
],
"Title": "array of struct read from file in C"
}
|
240963
|
<p>I have a method that I use nested <code>foreach</code> and the same variable call multiple times. I read a lot of optimizing code but I'm pretty sure I can do this with less code and best practices:</p>
<pre><code> public async Task<IEnumerable<IssueViewModel>> Get(IssueSelectModel model)
{
async Task<IEnumerable<IssueViewModel>> DoGet()
{
var issueList = await _bugTrackerRepository.Get(model);
var userList = await _userService.Get(new UserSelectModel { RowsPerPage = 1000 });
foreach (var item in issueList.IssueList)
{
item.AssigneeName = userList.Items.FirstOrDefault(x => x.UserId == item.AssigneeId)?.UserName;
item.CreatedByName = userList.Items.FirstOrDefault(x => x.UserId == item.CreatedBy)?.UserName;
item.ModifiedByName = userList.Items.FirstOrDefault(x => x.UserId == item.ModifiedBy)?.UserName;
item.ClosedByName = userList.Items.FirstOrDefault(x => x.UserId == item.ClosedBy)?.UserName;
foreach(var comment in item.CommentList)
{
comment.CreatedByName = userList.Items.FirstOrDefault(x => x.UserId == comment.CreatedBy)?.UserName;
foreach(var tag in comment.TagList)
{
tag.UserByName = userList.Items.FirstOrDefault(x => x.UserId == tag.UserId)?.UserName;
}
}
}
return issueList.IssueList;
}
return await DoGet();
}
</code></pre>
<ul>
<li>Is it possible to use <code>userList</code> only one time?</li>
<li>Is there an alternative of multiple <code>foreach</code> statement?</li>
</ul>
<p>Regards</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T07:45:29.603",
"Id": "472802",
"Score": "0",
"body": "The current question title of your question is too generic to be helpful. Please edit to the site standard, which 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": "<blockquote>\n <p>Is it possible to use userList only one time?</p>\n</blockquote>\n\n<p>Every time you call a <code>FirstOrDefault</code>, you are doing an O(n) search through the user list. You should consider keeping a dictionary of user IDs to user objects. Without knowing what kind of frameworks you're using, I can't say whether this is a job for your ORM or whether you have to do it yourself. With a dictionary, user lookup will be much faster.</p>\n\n<p>So short answer, no; but you shouldn't be using a list.</p>\n\n<blockquote>\n <p>Is there an alternative of multiple <code>foreach</code> statement?</p>\n</blockquote>\n\n<p>Not really.</p>\n\n<p>Other things I see that could use some love:</p>\n\n<h2>Overuse of <code>var</code></h2>\n\n<p>I find <code>var</code> to be useful in contexts where it's visually obvious what type a variable will take, including during instantiation statements. However, that is not the case with any of the instances of <code>var</code> in your code; I have no idea what's going into those variables. Unless the type is some kind of monstrous generic, just use the type.</p>\n\n<h2>Data model issues</h2>\n\n<p>You have some kind of user object, and some kind of item object with multiple references to user names. Are you sure it's a good idea to refer to the names, and not the user objects? The answer to this might be that you need the names in this case because the object is shortly destined for some kind of serialization, but if that isn't the case, it's probably a better idea to keep object references instead of string references.</p>\n\n<p>In other words, why store <code>comment.CreatedByName</code> when you already have <code>comment.CreatedBy</code>?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T07:46:34.077",
"Id": "472804",
"Score": "1",
"body": "The usage of `var` isn't the problem, it's the badly named variables."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T23:17:54.160",
"Id": "472949",
"Score": "2",
"body": "\"I find var to be useful in contexts where it's visually obvious what type a variable will take, including during instantiation statements. However, that is not the case with any of the instances of var in your code; I have no idea what's going into those variables. Unless the type is some kind of monstrous generic, just use the type.\" \nI couldn't agree more. var seems to be over used because its \"easy\", but that almost always comes at the cost of readability. I have argued with other devs who want to use it when declaring an int... so frustrating."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T03:00:40.283",
"Id": "240981",
"ParentId": "240965",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T22:06:02.763",
"Id": "240965",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Optimize code usage and repeated code"
}
|
240965
|
<p>I was asked to solve the following exercise:</p>
<p>Given an input <code>vector<string></code>, I have to find the anagrams and return a <code>vector<string></code> with only the strings that are not an anagram from other strings in the vector.</p>
<p>Example:</p>
<p>Input vector:</p>
<pre><code>"code","doce","framy","frame","sad","cat","frema"
</code></pre>
<p>Output:</p>
<pre><code>"code","framy","sad","cat"
</code></pre>
<p>Here, the anagram <code>"frame" == "frema"</code> is removed. All words which are anagrams from one another are removed.</p>
<p>My solution is to sum the ASCII values from the strings, if two strings are equal, then I sort it to check for equality.</p>
<pre><code>#include <iostream>
#include <bits/stdc++.h>
#include <algorithm> // std::sort
using namespace std::chrono;
using namespace std;
int sumASCII(string input) {
int i;
int sum = 0;
int size = input.size();
for( i = 0; i < size; i++) {
sum+=(int)input[i];
}
return sum;
}
int sortStringAndCompare(string &a, string &b)
{
sort(a.begin(), a.end());
sort(b.begin(), b.end());
return a.compare(b);
}
vector<string> funWithAnagrams(vector<string> &text) {
bool anagram = false;
int i;
int size = text.size();
int sumCurr = 0;
int sumPrev = 0;
int k = 0;
int originalSize = 0;
string copyA;
string copyB;
vector<string> originalStrings;
originalStrings.push_back(text[0]);
for( i = 1 ; i < size; i++ ) {
sumCurr = sumASCII(text[i]);
originalSize = originalStrings.size();
for( k = 0; k < originalSize; k++ ) {
if(originalStrings[k].size() == text[i].size() ) {
sumPrev = sumASCII(originalStrings[k]);
if(sumPrev == sumCurr) {// means it found a possible anagram.
copyA = originalStrings[k];
copyB = text[i];
if(sortStringAndCompare(copyA,copyB) == 0)
{
anagram = true;
break;
}
}
else
anagram = false;
}
else {
anagram = false;
}
}
if(!anagram) {
originalStrings.push_back(text[i]);
}
}
return originalStrings;
}
int stringCompare(std::string a,std::string b)
{
return a.compare(b);
}
void print(std::vector<string> const &input)
{
int size = input.size();
printf("[ ");
for (int i = 0; i < size; i++) {
std::cout << input.at(i) << ' ';
if(i < (size-1))
printf(",");
}
printf(" ]");
}
int main() {
printf("TEST STARTED\n");
vector<string> input{"doceframe","code", "doce","ecod","framer","frame", "frema","cat","sad"};
vector<string> out;
// Get starting timepoint
auto start = high_resolution_clock::now();
out = funWithAnagrams(input);
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);
cout << "Time taken by function: " << duration.count() << " microseconds" << endl;
printf("\n \n");
print(out);
printf("\n");
printf("TEST ENDED\n");
return 0;
}
</code></pre>
<p>My program is not the best in terms of memory, i shall improve it. But my task, at the moment, is to develop the fastest algorithm possible. How can I improve it?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T04:21:16.383",
"Id": "472784",
"Score": "2",
"body": "You could compare string lengths first, that is very fast and shows you if an anagram is even possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T04:53:50.297",
"Id": "472788",
"Score": "3",
"body": "Can you clarify the behaviour? What Is \"only original strings\"? \"code\" And \"doce\" seem to be anagrams, So Are \"frame\" And \"frema\". But while code Is in output, frame Is not. How So?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T09:01:00.680",
"Id": "472816",
"Score": "0",
"body": "I compare strings length first with this code: if(originalStrings[k].size() == text[i].size() ) {\n sumPrev = sumASCII(originalStrings[k]);"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T09:01:38.277",
"Id": "472817",
"Score": "0",
"body": "What i mean by original strings is this: Consider the input \"code\", \"doce\",\"frame\", \"frema\". doce is an anagram of code, so i discard doce and keep only code. Samething for frame and frema, this last word is an anagram of frame, so i discard frema. The output results: \"code\", \"frame\". Bottom line, everytime i find an anagram i discard every strings except the first one found."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T09:53:39.280",
"Id": "472824",
"Score": "0",
"body": "You can change the `sumASCII()` function to use `std::for_each` on the input string. Doesn't matter much, but my benchmarking results showed an average reduction of 200ns in the function's running time"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T11:18:17.680",
"Id": "472838",
"Score": "0",
"body": "Your solution is quite convoluted. What made you pick this approach?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T11:22:28.517",
"Id": "472841",
"Score": "0",
"body": "@slepic Fixed it."
}
] |
[
{
"body": "<p>You are on the right track, but the code does need a lot of attention.</p>\n\n<ol>\n<li><p>Never go for <code>#include <bits/stdc++.h></code> </p>\n\n<p>Same goes for <code>using namespace std;</code> Both will lead you into a lot of trouble for zero gain. Only include what you need and use proper qualifications</p>\n\n<pre><code>#include <algorithm>\n#include <iostream>\n#include <string>\n#include <vector>\n</code></pre>\n\n<p>Note that I also sorted the includes alphabetically so it is easy to see what is already included</p></li>\n<li><p>You should pass by value whenever it is possible. However <code>std::string</code> is no such case. Luckily we have <code>std::string_view</code> since C++17 so you should almost always prefere this to passing a <code>std::string</code>, e.g</p>\n\n<pre><code>int sumASCII(const std::string_view input) { \n int i;\n int sum = 0;\n int size = input.size();\n\n for( i = 0; i < size; i++) {\n sum+=(int)input[i];\n }\n\n return sum;\n}\n</code></pre>\n\n<p>Same for all the other functions. Your strings are stored in the original vector so there is no possibility for a dangling reference. That said you should definitely read up on ownership and view-like types</p></li>\n<li><p>Use a formatter. Your formatting is highly unregular. You should pick a clang-format style you are comfortable with and use that everywhere.</p></li>\n<li><p>Use range-based loops when possible</p>\n\n<pre><code>int sumASCII(const std::string_view input) { \n int sum = 0; \n for (const char character : input) {\n sum += (int)character;\n } \n return sum;\n}\n</code></pre></li>\n<li><p>Do not use C-style casts. C++ has a wide variety of specialized casts that do what they are supposed to do and not more. In the above case <code>static_cast</code> is sufficient</p>\n\n<pre><code>int sumASCII(const std::string_view input) { \n int sum = 0; \n for (const char character : input) {\n sum += static_cast<int>(character);\n } \n return sum;\n}\n</code></pre></li>\n<li><p>Use the proper algorithms</p>\n\n<p>The STL provides a wide range of algorithms that is not only incredibly powerfull but also is often highly optimized and correct with respect to various corner cases.</p>\n\n<pre><code>int sumASCII(const std::string_view input) {\n return std::accumulate(std::begin(input), std::end(input), 0);\n}\n</code></pre>\n\n<p>Note that you might want to test this with proper warnings. </p></li>\n<li><p>Consider <code>const</code> correctness.</p>\n\n<p>One of the most difficult parts of programming is keeping all the moving parts in your head. The more explicit you are about what is immutable the easier it is to reason about the code. So use <code>const</code> whenever possible and <code>cbegin</code> and <code>cend</code> too. (Even if in this case it does exactly the same it provides additional information to the reader)</p>\n\n<pre><code>int sumASCII(const std::string_view input) {\n return std::accumulate(std::cbegin(input), std::cend(input), 0);\n}\n</code></pre></li>\n<li><p>Keep control flow as simple as possible.</p>\n\n<p>Another hard part of software engineering is keeping track of control flow. Try to minimize indentations as much as possible to keep the code clean and easily readable. As an example this is what you wrote</p>\n\n<pre><code>for( i = 1 ; i < size; i++ ) {\n sumCurr = sumASCII(text[i]);\n originalSize = originalStrings.size();\n for( k = 0; k < originalSize; k++ ) {\n if(originalStrings[k].size() == text[i].size() ) {\n sumPrev = sumASCII(originalStrings[k]);\n if(sumPrev == sumCurr) {// means it found a possible anagram.\n copyA = originalStrings[k];\n copyB = text[i];\n if(sortStringAndCompare(copyA,copyB) == 0)\n {\n anagram = true;\n break;\n }\n }\n else\n anagram = false;\n }\n else {\n anagram = false;\n }\n\n }\n if(!anagram) {\n originalStrings.push_back(text[i]);\n }\n}\n</code></pre>\n\n<p>It is hard to keep track of the different conditions in thi loop and what it actually does so lets try to simplify it with some early returns:</p>\n\n<pre><code>for( i = 1 ; i < size; i++ ) {\n anagram = false;\n sumCurr = sumASCII(text[i]);\n originalSize = originalStrings.size();\n for (const string_view newString : originalStrings) {\n if(newString.size() != text[i].size() ) {\n continue;\n }\n\n sumPrev = sumASCII(newString);\n if(sumPrev != sumCurr) {\n continue;\n }\n\n copyA = originalStrings[k];\n copyB = text[i];\n if(sortStringAndCompare(copyA,copyB) == 0) {\n anagram = true;\n break;\n }\n }\n\n if(!anagram) {\n originalStrings.push_back(text[i]);\n }\n}\n</code></pre>\n\n<p>I hope you agree that this is much easier to read.</p></li>\n<li><p>Think about the proper data structures.</p>\n\n<p>You are searching for a reoccuring pattern. This is usually done via an associative container. The STL knows <code>std::unordered_map</code> and <code>std::map</code>. You should use those.</p>\n\n<p>The first thing you need is a container of histograms,. You wantunique ones so you should go for a set</p>\n\n<pre><code>std::unordered_set<someHistogramThing> histograms;\n</code></pre>\n\n<p>The second thing you want to do is to count the characters in the string. Again a map is the simplest solution</p>\n\n<pre><code>std::unordered_map<char, std::size_t> charCount;\n</code></pre>\n\n<p>Lets have a look at how we get there;</p>\n\n<pre><code>std::unordered_map<char, std::size_t> countCharacters(const std::string_view input) {\n std::unordered_map<char, std::size_t> charCount;\n for (const char character : input) {\n charCount[character]++;\n }\n return charCount;\n}\n</code></pre>\n\n<p>For any word this gives us a histogram of the occurences of characters in that word. Two words are an anagram if they have the same histogram. So lets see if we can put it together.</p>\n\n<pre><code>std::vector<std::string> removeAnagrams(const std::vector<std::string>& input) {\n std::vector<std::string> result;\n std::unordered_set<std::unordered_map<char, std::size_t>> histograms;\n for (const std::string& newWord : input) {\n const auto[it, notAnagram] = histograms.insert(countCharacters(newWord));\n if (notAnagram) {\n result.push_back(word);\n } \n }\n}\n</code></pre></li>\n<li><p>Usetype aliases to give your data structures better names</p>\n\n<pre><code>using CharacterHistogram = std::unordered_map<char, std::size_t>;\nusing HistogramSet = std::unordered_set<CharacterHistogram>;\n</code></pre>\n\n<p>If we put that all together we get</p>\n\n<pre><code>#include <string>\n#include <string_view>\n#include <vector>\n#include <unordered_map>\n#include <unordered_set>\n\nusing CharacterHistogram = std::unordered_map<char, std::size_t>;\nusing HistogramSet = std::unordered_set<CharacterHistogram>;\n\nCharacterHistogram countCharacters(const std::string_view input) {\n CharacterHistogram charCount;\n for (const char character : input) {\n charCount[character]++;\n }\n return charCount;\n}\n\nstd::vector<std::string> removeAnagrams(const std::vector<std::string>& input) {\n std::vector<std::string> result;\n HistogramSet histograms;\n for (const std::string& newWord : input) {\n const auto[it, notAnagram] = histograms.insert(countCharacters(newWord));\n if (notAnagram) {\n result.push_back(word);\n } \n }\n}\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T16:07:15.130",
"Id": "472890",
"Score": "0",
"body": "Oh thanks for the comments, i asked for quickness and got a complete rewash, i learnt so much reading your suggestions."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T11:37:23.750",
"Id": "241001",
"ParentId": "240966",
"Score": "3"
}
},
{
"body": "<p>Your solution is O(N^2 log N) if I understand correctly. </p>\n\n<p>I propose a solution that works in O(N log N): </p>\n\n<ol>\n<li>Represent each word by dictionary where the key is character and value is the count of it inside the word. Equal dictionaries will have the same count for all characters. </li>\n<li>Sort the list of dictionaries by its hash (you need to implement it) .</li>\n<li>Equal dictionaries will be adjacent to each other. So you can remove equal dictionaries in 1 pass. </li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T11:48:46.643",
"Id": "241002",
"ParentId": "240966",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T22:19:50.373",
"Id": "240966",
"Score": "0",
"Tags": [
"c++"
],
"Title": "Remove anagrams from vector"
}
|
240966
|
<p>I wrote a simple card game in JavaScript and I wonder if anyone could give me some advice and make some improvements on my code. </p>
<p>Here is the demo that I build:
<a href="https://codesandbox.io/s/cardgame-his95?file=/src/index.js" rel="nofollow noreferrer">https://codesandbox.io/s/cardgame-his95?file=/src/index.js</a></p>
<p>So it is a 2 person card game. Every card has a number and also has a pattern.
The game goes like this: we have a set of pre-defined rules, and these rules have a ranking. The player that satisfies the highest-ranked rule will win. And there could be tie if they end up with the same ranking. The goal here is not just to make the game work, also I wanted to account for maintainability. For example, we can easily add new rules and swap the ranking and re-define the rule if possible.</p>
<p>There are mainly a couple of classes.
First is the <code>Game</code> class</p>
<pre class="lang-js prettyprint-override"><code>class Game {
constructor({ play1, play2, rules, messages }) {
this.play1 = play1;
this.play2 = play2;
this.rules = rules;
this.messages = messages;
}
play() {
let rankOfP1 = Infinity;
let rankOfP2 = Infinity;
for (const rule of this.rules) {
if (rule.validator(this.play1)) {
rankOfP1 = rule.rank;
break;
}
}
for (const rule of this.rules) {
if (rule.validator(this.play2)) {
rankOfP2 = rule.rank;
break;
}
}
return rankOfP1 === rankOfP2
? this.messages.tie
: rankOfP1 < rankOfP2
? this.messages.win.player1
: this.messages.win.player2;
}
}
</code></pre>
<p>Here the <code>rules</code> are an array of <code>rule</code> object where every object looks like this</p>
<pre class="lang-js prettyprint-override"><code>{
description: "Six Cards of the same pattern",
rank: 1,
validator: cards => {
return hasSamePattern(cards, 6);
}
</code></pre>
<p>The lower the rank gets, the more important this rule is. So If <code>player1</code> satisfies a <code>rule</code> with rank <code>1</code>, and <code>player1</code> satisfies a <code>rule</code> with rank <code>2</code>, then we say <code>player1</code> won.
And <code>validator</code> is the function that takes an array of <code>card</code> object and returns a boolean to determine if the set of cards satisfy the rule.</p>
<p>And lastly we have a <code>Card</code> class which is pretty simple</p>
<pre class="lang-js prettyprint-override"><code>
class Card {
constructor({ pattern, number }) {
this.pattern = pattern;
this.number = number;
}
}
</code></pre>
<p>Please take a look and feel free to make some improvements on it. Also please suggest some better naming for variables if possible, I am not a native English speaker so some of the names of the variables would be a bit weird.</p>
<p>Finally I wrote this game in a OOP style. I know that JavaScript is not the best language out there when it comes to OOP. Also I am not really good at Object Oriented Design. I wonder if anyone knows how to rewrite the game in <strong>functional programming style</strong>. That would be super cool!</p>
|
[] |
[
{
"body": "<p>Your constructor has</p>\n\n<pre><code>constructor({ play1, play2, rules, messages }) {\n this.play1 = play1;\n this.play2 = play2;\n this.rules = rules;\n this.messages = messages;\n}\n</code></pre>\n\n<p>You may as well <code>Object.assign</code> the parameter to the instance instead:</p>\n\n<pre><code>constructor(config) {\n Object.assign(this, config);\n}\n</code></pre>\n\n<p><code>pattern</code> is a slightly odd name for what it represents here - the usual English word for one of the clubs, diamonds, etc, is <strong>suit</strong>. <code>rule</code> is a bit strange as well - a rule usually refers to the process by which a game is played (eg \"Hands consist of 6 cards\" or \"The player with the best hand wins\"). To describe the different possible winning combinations and their ranks, I'd use the word <code>handRanks</code> <a href=\"https://en.wikipedia.org/wiki/List_of_poker_hands\" rel=\"nofollow noreferrer\">or something similar</a>. <code>play1</code> and <code>play2</code> aren't great descriptors either - these represent the cards held in each player's hand, so maybe use <code>player1Cards</code> or <code>player1Hand</code>.</p>\n\n<p>With regards to the <code>play()</code> method, when you want to find an item in an array which fulfills a condition, it would be more appropriate to use <code>.find</code>, rather than a <code>for</code> loop - <code>find</code> more clearly indicates what the intention of the loop is, and is more concise. You also need to set the rank to <code>Infinity</code> if no handRanks pass - why not integrate this <code>Infinity</code> into the <code>handRanks</code> array itself? You're also writing the looping code twice - you can make it more DRY by putting it into a function, and calling that function twice instead.</p>\n\n<pre><code>new Card({ suit: \"spade\", number: 1 }), // <-- Suit\n</code></pre>\n\n<pre><code>new HandRank({ // <-- HandRank\n description: \"Six Cards of the same suit\", // <-- Suit\n rank: 1,\n validator: cards => {\n return hasSameSuit(cards, 6); // <-- hasSameSuit, not hasSamePattern\n }\n}),\nnew HandRank({ // <-- HandRank\n description: \"Nothing special\",\n rank: Infinity, // <-- add this whole new HandRank\n validator: cards => true,\n}),\n</code></pre>\n\n<pre><code>getRank(cards) {\n return this.handRanks.find(({ validator }) => validator(cards)).rank; // <-- this.handRanks\n}\nplay() {\n const rankOfP1 = this.getRank(this.player1Cards); // <-- player1Cards\n const rankOfP2 = this.getRank(this.player2Cards); // <-- player2Cards\n return rankOfP1 === rankOfP2\n ? this.messages.tie\n : rankOfP1 < rankOfP2\n ? this.messages.win.player1\n : this.messages.win.player2;\n}\n</code></pre>\n\n<p>One of the benefits of using arrow functions is that if the function contains only a single expression which is immediately returned, you can omit the <code>{</code> <code>}</code> brackets and the <code>return</code> keyword, if you want to make things concise, eg for the <code>hasSameSuit</code> test above:</p>\n\n<pre><code>validator: cards => hasSameSuit(cards, 6),\n</code></pre>\n\n<p>If you want to find if any item in an array <em>passes</em> a test, but you don't care about <em>which</em> item passes the test, you should use <code>.some</code>, not <code>.find</code>. (<code>.some</code> returns a boolean indicating whether any passed, <code>.find</code> returns the found item) For the <code>hasSamePattern</code> (or <code>hasSameSuit</code>) method, use:</p>\n\n<pre><code>return Object.values(patterns).some(num => num >= threshold);\n</code></pre>\n\n<p>Your <code>hasConsecutiveNums</code> method has the bug <a href=\"https://codereview.stackexchange.com/questions/240914/write-a-function-to-determine-whether-an-array-contains-consecutive-numbers-for/240918#comment472670_240914\">mentioned in the comments previously</a> - a hand of <code>[1, 2, 2, 3]</code> will not pass a 3-consecutive-number test because the sorted array will contain 2 twice, failing <code>if (prevNum + 1 === num) {</code>. De-duplicate the numbers with a Set first.</p>\n\n<pre><code>const nums = [...new Set(cards.map(card => card.number).sort((a, b) => a - b))];\n</code></pre>\n\n<blockquote>\n <p>I wonder if anyone knows how to rewrite the game in functional programming style.</p>\n</blockquote>\n\n<p>Javascript isn't <em>entirely</em> suited to completely functional programming either, though it can get most of the way there. To start with, make your functions pure, and avoid side-effects and mutations. For example, assigning to a property of the instance with <code>this.play1 = play1;</code> (or <code>this.player1Cards = player1Cards;</code>) is a mutation. None of your code <em>fundamentally</em> requires anything non-functional (except the <code>console.log</code> at the very end, which is unavoidable), so it should be pretty easy to convert - rather than assigning to properties, just keep the variables in a closure, and return a function for the <code>play</code> method, eg:</p>\n\n<pre><code>const makeGame = ({ player1Cards, player2Cards, handRanks, messages }) => () => {\n // getRank is now a standalone function which takes a handRanks parameter\n const rankOfP1 = getRank(player1Cards, handRanks);\n const rankOfP2 = getRank(player2Cards, handRanks);\n return rankOfP1 === rankOfP2\n ? messages.tie\n : rankOfP1 < rankOfP2\n ? messages.win.player1\n : messages.win.player2;\n};\n</code></pre>\n\n<pre><code>const play = makeGame({ ... });\nconsole.log(play());\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T01:07:27.260",
"Id": "472767",
"Score": "0",
"body": "Hi. Thanks for such a thorough answer! I'd like to ask more questions about functional programming. In your opinion, is it better to write this game in a functional programming style or OO style? If we were using functional programming here. Do we still need to use `new` to initialize all those objects like `card` objects, `player` objects, and `HandRank` object?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T06:30:20.030",
"Id": "472795",
"Score": "0",
"body": "Both work, it's purely a matter of preference. Personally, I'd strongly prefer to go the functional method, but someone else might think differently. *Do we still need to use new* No, usually, if you're trying to be functional, you should not use `new`, because that indicates that you're mutating somewhere."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T06:31:02.537",
"Id": "472796",
"Score": "0",
"body": "But in this script, your `new Card` and `new Rule`s don't accomplish anything useful - all they do is create objects with properties. Using a plain object instead would make more sense IMO. Eg `const rules = [\n {\n description: \"Six Cards of the same pattern\",\n rank: 1,\n validator: cards => {\n return hasSamePattern(cards, 6);\n }\n }, ...` Classes are useful when you want to *bundle data with methods*. Data alone or functions alone don't have a reason to be in classes IMO. Use a class when you need data *and methods associated with the data*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T15:50:56.437",
"Id": "472887",
"Score": "0",
"body": "if we ditch `new`, but I find using object literal doesn't scale well and you need to write it every time you need a new `card` or `rule`, is there a functional way to produce objects? And can you show me how to do it in the code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T21:44:20.077",
"Id": "472942",
"Score": "0",
"body": "When all you need is a data structure, like here, using an object literal scales *better* than using `new` - it requires less code and (IMO) is easier to understand intuitively (compared with having to go to the constructor definition to see what's going on).`new Card({ suit: \"spade\", number: 1 })` vs `{ suit: \"spade\", number: 1 }` - since Card doesn't have any methods, there's no point to the `new`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T21:45:59.110",
"Id": "472943",
"Score": "0",
"body": "The easiest way to produce objects would be to just use the object literals themselves. You could also do `const makeObj = obj => obj`, but that's silly. `const makeCard = ({ suit, number }) => ({ suit, number })` is silly too"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T23:17:07.630",
"Id": "240972",
"ParentId": "240967",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "240972",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T22:22:20.493",
"Id": "240967",
"Score": "4",
"Tags": [
"javascript",
"object-oriented",
"game",
"playing-cards"
],
"Title": "Design a simple card game in JavaScript"
}
|
240967
|
<p>I'm writing a program in Unity and am using a <code>TextMeshProUGUI</code> object (named <code>history</code>) to hold a list of messages to act as a terminal/console.</p>
<p>The problem I am having is that I am printing up to hundreds of lines a second, which can be detrimental to performance when I'm doing many string splits and then updating the <code>text</code> variable of the <code>TextMeshProUGUI</code> object, (which in turn gets rendered) every single frame.</p>
<p>My initial implementation looked like this:</p>
<pre><code>private const int MAX_HISTORY = 64; // the maximum number of lines to store
public TextMeshProUGUI history; // value is set in Unity editor
private int inputs = 0; // the size of the history object
public void Print(params string[] msgs)
{
// add all messages to the history
foreach (string msg in msgs)
{
if (msg == null)
continue;
inputs++;
history.text += msg + '\n';
}
// and now reduce the size
if (inputs > MAX_HISTORY)
{
string[] lines = history.text.Split('\n');
history.text = "";
for (int i = inputs - MAX_HISTORY; i < lines.Length; i++)
{
history.text += lines[i] + '\n';
}
inputs = MAX_HISTORY;
}
}
</code></pre>
<p>and I have managed to reduce it to this:</p>
<pre><code>public void Print(params string[] msgs)
{
foreach (string msg in msgs)
{
if (msg == null)
continue;
inputs++;
history.text += msg + '\n';
}
if (inputs > MAX_HISTORY)
{
history.text =
history.text.Split(new char[] { '\n' }, inputs - MAX_HISTORY)[inputs - MAX_HISTORY - 1];
inputs = MAX_HISTORY;
}
}
</code></pre>
<p>But I am still concerned with the line in the if-statement with the large split function. I would appreciate it if somebody who has experience with C# and string manipulation could review this and tell me if my optimisation is (a) correct and (b) good.</p>
<p><strong>Edit:</strong></p>
<p>Changing the value of <code>TextMeshProUGUI.text</code> causes a layout and vertex recalculation which has poor performance so I've also added a <code>StringBuilder</code> to handle the concatenation and splits before setting the text value.</p>
<pre><code>public void Print(params string[] msgs)
{
StringBuilder text = new StringBuilder(history.text);
foreach (string msg in msgs)
{
if (msg == null)
continue;
inputs++;
text.AppendLine(msg);
}
while (inputs > MAX_HISTORY)
{
text.Remove(0, Convert.ToString(text).Split('\n').FirstOrDefault().Length + 1);
inputs = MAX_HISTORY;
}
history.text = text.ToString();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T11:15:21.523",
"Id": "472836",
"Score": "0",
"body": "@BCdotWEB Then I don't believe you have read the question. The title is exactly what the question states as its main task. It is the optimisation of many string concatenations and then many splits on the same string. If you have a suggestion please let me know because I do not have any other way to word it in simple terms."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T18:13:22.133",
"Id": "472902",
"Score": "0",
"body": "Is it common for msgs count to be greater than MAX_HISTORY? If so maybe you can optimize by not adding msgs to text and then removing them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T18:46:26.463",
"Id": "472909",
"Score": "0",
"body": "@shanif Yes. It mimics a terminal and after around five commands (because of how much output there is) you hit that limit very fast."
}
] |
[
{
"body": "<p>I would use generic list to store messages history and Linq extension methods. If I understood correctly I would append new messages and crop to predefined maximum size. Could you test this solution if it has sufficient performance?</p>\n\n<pre><code>private List<string> _history = new List<string>();\n\npublic void Print(params string[] msgs)\n{\n _history.AddRange(msgs.Where(m => !string.IsNullOrWhiteSpace(m)));\n _history = _history.Skip(Math.Max(0, _history.Count - MAX_HISTORY)).ToList();\n history.text = string.Join(Environment.NewLine, _history);\n}\n</code></pre>\n\n<p>If you need messages ordered from newest to latest, you can add Reverse() method:</p>\n\n<pre><code>_history = _history.Skip(Math.Max(0, _history.Count - MAX_HISTORY)).Reverse().ToList();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T01:31:30.547",
"Id": "472768",
"Score": "0",
"body": "Wow. I was getting an average nanosecond speed of ~400,000 and now it is down to ~110,000-137,000 so thank you very much. Quick question, is there any reason why I would want to use `_history = _history.Skip...` instead of `_history.RemoveRange` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T01:45:31.483",
"Id": "472769",
"Score": "1",
"body": "I've just tested with `RemoveRange` and its 27 times faster when we ignore rendering so I might go with that. Thank you for more than doubling the speed though. The improvement is (visually) very obvious already. I cannot upvote your answer yet but I will when I get the reputation."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T01:05:16.843",
"Id": "240976",
"ParentId": "240968",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "240976",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T22:25:48.633",
"Id": "240968",
"Score": "1",
"Tags": [
"c#",
"performance",
"strings",
"unity3d",
"user-interface"
],
"Title": "Optimising multiple string splits and concatenations"
}
|
240968
|
<p>I am trying to learn the Cartesian Coordinate System, starting with a basic tic tac toe grid for simplicity, then perhaps moving to chess. I was able to make the following code to start out:</p>
<pre><code>board = []
def new_board():
for row in range(4):
board.append([])
for column in range(4):
board[row].append('_')
def print_board():
print(board)
print(' %s | %s | %s' % (board[1][1], board[1][2], board[1][3]))
print('----+---+----')
print(' %s | %s | %s' % (board[2][1], board[2][2], board[2][3]))
print('----+---+----')
print(' %s | %s | %s' % (board[3][1], board[3][2], board[3][3]))
new_board()
print(board)
print_board()
</code></pre>
<p>When the list 'board' is printed, it gives the following:</p>
<pre><code>[['_', '_', '_', '_'], ['_', '_', '_', '_'], ['_', '_', '_', '_'], ['_', '_', '_', '_']]
[['_', '_', '_', '_'], ['_', '_', '_', '_'], ['_', '_', '_', '_'], ['_', '_', '_', '_']]
</code></pre>
<p>Which is fine, but my issue is that in order for my commands to match the board (e.g. board[1][2] targeting the 1st row and the 2nd column of the board), I have to have a 'dummy entry' for [0], for both the sublists and the entries in the sublists.</p>
<p>Is there a way to do this without the dummy entries and still have my board list references match the actual board spaces?</p>
|
[] |
[
{
"body": "<ul>\n<li><p>It is a convention in Python to use the <code>_</code> variable as the 'throw away variable'.\nIn your case you can replace <code>column</code> with it.</p></li>\n<li><p>Rather than using a for loop with <code>list.append</code> you can use a list comprehension.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>data = []\nfor i in range(4):\n data.append(i)\n\ndata = [i for i in range(4)]\n</code></pre></li>\n<li><p>When you build an array with all of the items having the same immutable value you can make an array with just one value and multiply the array.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>foo = [None for _ in range(4)]\n\nfoo = [None] * 4\n</code></pre></li>\n<li><p>You should not rely on globals to hold state. There are two solutions:</p>\n\n<ol>\n<li>Pass and return the values from the functions.</li>\n<li>Use a class to encapsulate state.</li>\n</ol></li>\n<li><p>Strings <code>%</code> method for formatting is somewhat archaic and buggy. It should be noted that <code>str.format</code> or f-strings are a better alternate with more features.</p>\n\n<pre><code>values = (1, 2)\n\n'%s %s' % values\n\n'{0[0]} {0[1]}'.format(values)\n'{} {}'.format(*values)\n\nf'{values[0]} {values[1]}'\n</code></pre></li>\n<li><p>It is best practice to use an <code>if __name__ == '__main__'</code> guard to prevent your code from running if imported by accident.</p></li>\n<li><p>Python uses 0 based indexing. I have had no problems with it once adjusted. However if you do you'd be better off not using Python.</p>\n\n<p>Lua, Julia and R are all languages that use 1-based indexing.</p></li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>def new_board():\n return [['_'] * 3 for _ in range(3)]\n\n\ndef print_board(board):\n print(\n ' {} | {} | {} '.format(*board[0])\n + '----+---+----'\n + ' {} | {} | {} '.format(*board[1])\n + '----+---+----'\n + ' {} | {} | {} '.format(*board[2])\n )\n\n\nif __name__ == '__main__':\n board = new_board()\n print(board)\n print_board(board)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T02:47:24.310",
"Id": "472771",
"Score": "0",
"body": "`%` buggy? Which bugs?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T10:07:02.883",
"Id": "472828",
"Score": "0",
"body": "@Reinderien By buggy I mean the ability to cause, rather than have, bugs. The exact wording the Python wiki uses is quirks. These resolve around how printf style formatting works with tuples - `'(%s,)' % 1 != '%s' % (1,)`. Additionally there are common problems with dictionaries. Whilst the issues seem fairly simple to solve, if you forget or don't know about them then you get needless errors in your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T13:12:08.333",
"Id": "472856",
"Score": "0",
"body": "Makes sense. My choice of words would be _bug-prone_, but shrug."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T23:36:38.737",
"Id": "240973",
"ParentId": "240971",
"Score": "6"
}
},
{
"body": "<p>List indices (coordinates) in most programming languages start at 0. If you want to present a coordinate system that starts at 1 instead, rather than fighting with the native data structures by adding \"dummy\" entries and then trying to remember to filter them out, you can make life easier by building an abstraction layer that cleanly separates the \"native\" representation (i.e. a list of lists) from the interface that you want to use in the rest of your code. For example:</p>\n\n<pre><code>from typing import Tuple\n\nclass Board:\n \"\"\"\n A square game board with a fixed size. Spaces are accessed by 2D\n coordinates that are numbered starting at 1, so a board of size 3\n goes from [1, 1] (upper left) to [3, 3] (lower right).\n All elements in the board are single-character strings.\n \"\"\"\n def __init__(self, size: int):\n self._grid = [['_' for _ in range(size)] for _ in range(size)]\n\n def __str__(self) -> str:\n return (\n # Horizontal lines between rows\n '+'.join(['---'] * len(self._grid)) + '\\n'\n ).join(\n # The rows themselves\n ' ' + ' | '.join(row) + ' \\n'\n for row in self._grid\n )\n\n def __getitem__(self, coords: Tuple[int, int]) -> str:\n x, y = coords\n return self._grid[y-1][x-1]\n\n def __setitem__(self, coords: Tuple[int, int], value: str) -> None:\n assert len(value) == 1, \"Only single characters allowed!\"\n x, y = coords\n self._grid[y-1][x-1] = value\n\nboard = Board(3)\nboard[3, 3] = 'X'\nprint(board)\n</code></pre>\n\n<pre><code> _ | _ | _\n---+---+---\n _ | _ | _\n---+---+---\n _ | _ | X\n</code></pre>\n\n<p>In this example, the class <code>Board</code> abstracts away the internal list and provides its own interface where spaces are specified as <code>[1...size, 1...size]</code> instead of <code>[0...size-1][0...size-1]</code>, so you can write code that's 1-indexed without having to account for the difference anywhere but inside the <code>Board</code> implementation. </p>\n\n<p>Using the \"multiple key\" syntax on the getter and setter (i.e. <code>[X, Y]</code> instead of <code>[X][Y]</code>) will help make it more obvious to readers of your code that this is a custom data structure that doesn't necessarily follow the same conventions as normal lists and dicts, and allows you to use something that looks more like Cartesian notation.</p>\n\n<p>By implementing <code>__str__</code> you can control how the object is printed; rather than needing to remember to use <code>print_board()</code> when you want to pretty-print the board (and having that output be at odds with <code>print(board)</code>, now <code>print(board)</code> itself will do the thing you want.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T23:57:02.930",
"Id": "472763",
"Score": "1",
"body": "You have not reviewed the code, only answered an off-topic part of the question."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T23:46:20.950",
"Id": "240974",
"ParentId": "240971",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-21T22:45:11.100",
"Id": "240971",
"Score": "6",
"Tags": [
"python",
"python-3.x"
],
"Title": "Tic Tac Toe using Cartesian coordinate system"
}
|
240971
|
<p>I have 2 functions to get the n-th fibonacci number. The 1st one uses recursive calls to calculate the power(M, n), while the 2nd function uses iterative approach for power(M, n). Theoretically (at least what I think), they should have the same speed O(log n), but why when I run both, the 2nd one is much slower than the 1st one?</p>
<pre><code>def fib_1(n):
from numpy import matrix
def power(F, n):
if n == 0 or n == 1: return matrix('1 1; 1 0', object)
F = power(F, n >> 1) # n // 2
F = F * F
if n % 2 == 0:
return F
if n % 2 != 0:
return F * matrix('1 1; 1 0', object)
F = matrix('1 1; 1 0', object)
F = power(F, abs(n)-1)
return F[0,0] if n > 0 else int((-1)**(n+1)) * F[0,0]
</code></pre>
<pre><code>def fib_2(n):
from numpy import matrix
def power(F, n):
M = matrix('1 1; 1 0', object)
while n > 0:
if n & 1 == 1:
M = F * M
n = n >> 1 # n = n // 2
F = F * F
return M
F = matrix('1 1; 1 0', object)
F = power(F, abs(n)-2)
return F[0,0] if n > 0 else int((-1)**(n+1)) * F[0,0]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T04:30:02.967",
"Id": "472785",
"Score": "1",
"body": "Please share how you profile. In my setup, `fib_2` is _much_ faster."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T04:46:57.130",
"Id": "472787",
"Score": "0",
"body": "@vnp, for small numbers, fib_2 is totally faster, but for big n (like n=2,000,000), fib_2 is much slower. I just use a normal start_time = time.perf_counter() and end_time to see the time they took to complete calculating a big n fib"
}
] |
[
{
"body": "<p>Before some more detailed performance analysis, it's important to note some low-hanging fruit in terms of code quality.</p>\n\n<h2>Global imports</h2>\n\n<p>Unless you have a really good reason, <code>from numpy import matrix</code> should be at the top of the file in global scope.</p>\n\n<h2>Deprecated library classes</h2>\n\n<p><a href=\"https://docs.scipy.org/doc/numpy/reference/generated/numpy.matrix.html\" rel=\"nofollow noreferrer\"><code>matrix</code> is deprecated</a>. Use <code>ndarray</code> instead.</p>\n\n<h2>Do not reconstruct constants</h2>\n\n<p><code>matrix('1 1; 1 0', object)</code> should not be parsed and reconstructed every time. Save it outside of function scope. If you need it to be modified later, modify a copy. Copying will be cheaper than parsing.</p>\n\n<h2>Redundant branches</h2>\n\n<p>In this:</p>\n\n<pre><code> if n % 2 == 0:\n return F\n if n % 2 != 0:\n return F * matrix('1 1; 1 0', object)\n</code></pre>\n\n<p>The second <code>if</code> is not necessary because its condition is guaranteed to be <code>True</code>.</p>\n\n<h2>Expression simplification</h2>\n\n<pre><code>int((-1)**(n+1))\n</code></pre>\n\n<p>It's probable that <code>n</code> is already an integer based on how your function is set up (though documentation and/or type hints would help to clarify this). The fact that a <code>float</code> is produced when the exponent is negative is probably due to Python assuming that it effectively needs to do a division, which is reasonable. All things considered, rather than doing the exponentiation - which is common in pure math, because of simplicity of analysis - you should consider doing the \"piece-wise\" thing instead. Rather than</p>\n\n<pre><code>return F[0,0] if n > 0 else int((-1)**(n+1)) * F[0,0]\n</code></pre>\n\n<p>consider</p>\n\n<pre><code>y = F[0,0]\nif n <= 0 and n%2 == 0:\n y = -y\nreturn y\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T02:58:01.857",
"Id": "472772",
"Score": "0",
"body": "On the last point, I don't know why but if the result is negative (-1), it's cast to -1.0. That's why I had int cast there"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T03:03:00.460",
"Id": "472774",
"Score": "0",
"body": "I just tried this and it gave me -1.0 ```n = -10\nprint((-1)**(n+1))```"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T04:10:11.887",
"Id": "472783",
"Score": "2",
"body": "@Reinderien When the exponent is integer, there are no roots involved. For negative integers it is the division."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T04:42:50.257",
"Id": "472786",
"Score": "1",
"body": "Yes, that. Negative exponent is \"one over\" not \"root\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T09:49:08.230",
"Id": "472821",
"Score": "1",
"body": "`return F[0,0] * (1 if (n > 0 or n%2) else -1)` keeps it in 1 line, and is clearer than both in my opinion"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T13:15:20.453",
"Id": "472857",
"Score": "0",
"body": "Re. the root/division - that's right; I've edited it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T13:16:11.810",
"Id": "472858",
"Score": "1",
"body": "@MaartenFabré Re. the ternary-golfed statement - you're entitled to your opinion; I think the `if` is clearer."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T02:43:14.100",
"Id": "240980",
"ParentId": "240979",
"Score": "3"
}
},
{
"body": "<p>Before we got any further, a word of warning. The complexity is only valid in a particular computational model.</p>\n\n<p>The complexity of these algorithms is <span class=\"math-container\">\\$O(\\log n)\\$</span> <em>only</em> if the addition takes constant time. For large <span class=\"math-container\">\\$n\\$</span> it is not the case.</p>\n\n<p>Fibonacci numbers grow exponentially with <code>n</code>. It means that the number of bits grows linearly. Now we are in the Turing machine realm. The last addition itself takes <span class=\"math-container\">\\$O(n)\\$</span>, which is way more than <span class=\"math-container\">\\$\\log n\\$</span>.</p>\n\n<p>The overall complexity should be <span class=\"math-container\">\\$O(n\\log{n})\\$</span> in both cases. Why the two exhibit different performance?</p>\n\n<p>The <em>likely</em> reason is that there is a subtle difference between them. <code>fib_1</code> maintains just one matrix, <code>F</code>. <code>fib_2</code> maintains two of them, <code>F, M</code>, and must do roughly twice as many reallocations as <code>fib_1</code> does. The matrices contain huge numbers, and I expect that the memory management time dominates. Yet another factor the computational model shall now consider.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T05:49:41.290",
"Id": "240986",
"ParentId": "240979",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T01:48:24.060",
"Id": "240979",
"Score": "4",
"Tags": [
"python",
"recursion",
"fibonacci-sequence"
],
"Title": "Recursive vs. non-recursive implementations of Fibonacci sequence"
}
|
240979
|
<p>I am total beginner in C and after reading K&R's chapter 5, I felt I was ready to at least make a simple game using C. I know linked-lists, so since I was making an implementation of Snake, why not?</p>
<p><strong>main.h</strong></p>
<pre><code>#include <SDL2/SDL.h>
#ifndef MAIN
#define MAIN
#define SCREEN_WIDTH 640
#define SCREEN_HEIGHT 480
SDL_Renderer *getRenderer();
void quit_game(void);
void set_freeze(bool);
#endif
</code></pre>
<p><strong>main.c</strong></p>
<pre><code>#include <stdio.h>
#include <stdbool.h>
#include "main.h"
#include "snake.h"
#include "apple.h"
void handle_events(SDL_Event* e);
void quit(void);
SDL_Window *window;
SDL_Renderer *renderer;
bool running = false;
bool frozen = false;
bool init(void){
bool success = true;
window = NULL;
renderer = NULL;
if(SDL_Init(SDL_INIT_VIDEO) < 0){
printf("SDL could not be initiliazed. SDL_Error: %s\n", SDL_GetError());
success = false;
}
window = SDL_CreateWindow("snake game", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if(!window){
printf("SDL_Window could not be initialized. SDL_Error: %s\n", SDL_GetError());
success = false;
}
else{
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
}
if(!init_snake()){
printf("snake could not be initialized.\n");
success = false;
}
generate_new_apple_pos();
running = true;
return success;
}
int main(int argc, char* args[])
{
if(!init())
return -1;
else{
SDL_Event e;
while(running){
handle_events(&e);
if(frozen)
continue;
SDL_SetRenderDrawColor(renderer, 255, 255, 224, SDL_ALPHA_OPAQUE);
SDL_RenderClear(renderer);
update_snake();
render_apple();
SDL_RenderPresent(renderer);
SDL_Delay(50);
}
}
quit_game();
return 0;
}
void handle_events(SDL_Event *e)
{
while(SDL_PollEvent(e) != 0){
if((*e).type == SDL_QUIT){
running = false;
}
else if((*e).type == SDL_KEYDOWN){
switch((*e).key.keysym.sym){
case SDLK_RIGHT:
change_snake_direction(RIGHT);
break;
case SDLK_LEFT:
change_snake_direction(LEFT);
break;
case SDLK_UP:
change_snake_direction(UP);
break;
case SDLK_DOWN:
change_snake_direction(DOWN);
break;
}
}
}
}
void quit_game(void){
SDL_DestroyWindow(window);
window = NULL;
SDL_DestroyRenderer(renderer);
renderer = NULL;
free_tails();
SDL_Quit();
}
void set_freeze(bool b)
{
frozen = b;
}
SDL_Renderer* getRenderer() { return renderer; }
</code></pre>
<p><strong>snake.h</strong></p>
<pre><code>#include <SDL2/SDL.h>
#ifndef SNAKE
#define SNAKE
static const int DEFAULT_X = 500;
static const int DEFAULT_Y = 10;
static const int DEFAULT_WIDTH = 20;
static const int DEFAULT_HEIGHT = 20;
static const int DEFAULT_TAILS_N = 10;
struct TailNode{
SDL_Rect rect;
struct TailNode *next;
struct TailNode *previous;
};
struct Snake{
int dx;
int dy;
int size;
struct TailNode head;
};
enum direction{LEFT, RIGHT, UP, DOWN};
bool init_snake(void);
void update_snake(void);
void change_snake_direction(int);
void free_tails(void);
#endif
</code></pre>
<p><strong>snake.c</strong></p>
<pre><code>#include <stdio.h>
#include <stdbool.h>
#include <math.h>
#include "snake.h"
#include "main.h"
#include "apple.h"
struct Snake snake;
struct TailNode *lasttail;
void push_tail();
bool init_snake()
{
// default direction
snake.dx = -1;
snake.dy = 0;
// initializes head
snake.head.rect.x = DEFAULT_X;
snake.head.rect.y = DEFAULT_Y;
snake.head.rect.w = DEFAULT_WIDTH;
snake.head.rect.h = DEFAULT_HEIGHT;
snake.head.next = NULL;
snake.head.previous = NULL;
// sets pointer of last tail to head
lasttail = &snake.head;
// pushes default tails
for(int i = 0; i < DEFAULT_TAILS_N; ++i)
push_tail();
return true;
}
void render_tail(SDL_Rect *tail)
{ // renders individual parts of the snake
SDL_SetRenderDrawColor(getRenderer(), 204, 175, 175, SDL_ALPHA_OPAQUE);
SDL_RenderFillRect(getRenderer(), tail);
}
void check_collision()
{
// fruit collision
if(abs(snake.head.rect.x - get_apple_posX()) < DEFAULT_WIDTH && abs(snake.head.rect.y - get_apple_posY()) < DEFAULT_HEIGHT){
push_tail();
generate_new_apple_pos();
}
// border collision
if(snake.head.rect.x > SCREEN_WIDTH - DEFAULT_WIDTH)
snake.head.rect.x = 0;
else if(snake.head.rect.x < 0 - DEFAULT_WIDTH)
snake.head.rect.x = SCREEN_WIDTH;
else if(snake.head.rect.y < 0 - DEFAULT_HEIGHT)
snake.head.rect.y = SCREEN_HEIGHT;
else if(snake.head.rect.y > SCREEN_HEIGHT - DEFAULT_HEIGHT)
snake.head.rect.y = 0;
}
void update_snake(void)
{ // iterates over the head and the tail
for(struct TailNode *ptr = lasttail; ptr != NULL; ptr = (*ptr).previous){
if((*ptr).previous == NULL){ // in other words, if this "tail" is the head
snake.head.rect.x += snake.dx * DEFAULT_WIDTH;
snake.head.rect.y += snake.dy * DEFAULT_HEIGHT;
}else{ // if it's the snake's body
if(abs(snake.head.rect.x - (*ptr).rect.x) < DEFAULT_WIDTH && // checks collision with the head
abs(snake.head.rect.y - (*ptr).rect.y) < DEFAULT_HEIGHT)
set_freeze(true);
(*ptr).rect.x = (*ptr).previous->rect.x;
(*ptr).rect.y = (*ptr).previous->rect.y;
}
render_tail(&(*ptr).rect);
}
check_collision(); // head-only collision (fruit, border, etc.)
}
void push_tail()
{ // pushes a new tail inside the linked list
struct TailNode *new_tail = malloc(sizeof(struct TailNode));
if(new_tail == NULL)
quit_game();
(*new_tail).rect.x = (*lasttail).rect.x + 30;
(*new_tail).rect.y = (*lasttail).rect.y;
(*new_tail).rect.w = DEFAULT_WIDTH;
(*new_tail).rect.h = DEFAULT_HEIGHT;
(*new_tail).next = NULL;
(*new_tail).previous = lasttail;
(*lasttail).next = new_tail;
lasttail = new_tail;
}
void change_snake_direction(int dir)
{
if(dir == RIGHT && snake.dx != -1){
snake.dx = 1;
snake.dy = 0;
}
else if(dir == LEFT && snake.dx != 1){
snake.dx = -1;
snake.dy = 0;
}
else if(dir == UP && snake.dy != 1){
snake.dy = -1;
snake.dx = 0;
}
else if(dir == DOWN && snake.dy != -1){
snake.dy = 1;
snake.dx = 0;
}
}
void free_tails()
{
struct TailNode *tmp;
struct TailNode *secondtail;
secondtail = snake.head.next; // we skip the first node (head) because it's allocated in the stack
while(secondtail != NULL){
tmp = secondtail;
secondtail = (*secondtail).next;
free(tmp);
}
}
</code></pre>
<p><strong>apple.h</strong></p>
<pre><code>#ifndef APPLE
#define APPLE
static const int DEFAULT_APPLE_WIDTH = 20;
static const int DEFAULT_APPLE_HEIGHT = 20;
void render_apple(void);
void generate_new_apple_pos(void);
int get_apple_posX(void);
int get_apple_posY(void);
#endif
</code></pre>
<p><strong>apple.c</strong></p>
<pre><code>#include <SDL2/SDL.h>
#include <stdbool.h>
#include "main.h"
#include "apple.h"
SDL_Rect apple;
void generate_new_apple_pos(void);
void render_apple()
{
SDL_SetRenderDrawColor(getRenderer(), 226, 106, 106, SDL_ALPHA_OPAQUE);
SDL_RenderFillRect(getRenderer(), &apple);
}
void generate_new_apple_pos(void)
{
apple.x = (rand() % (SCREEN_WIDTH - 0 + 1));
apple.y = (rand() % (SCREEN_HEIGHT - DEFAULT_APPLE_HEIGHT + 1));
apple.w = DEFAULT_APPLE_WIDTH;
apple.h = DEFAULT_APPLE_HEIGHT;
}
int get_apple_posX(void)
{
return apple.x;
}
int get_apple_posY(void)
{
return apple.y;
}
</code></pre>
<p><strong>ANY</strong> suggestions and tips to better this code are welcome, I'm trying to improve my fundamentals so I can develop bigger projects in C.</p>
<p>A few questions though:</p>
<ol>
<li><p>Am I using headers correctly? Or is it a mess? What can I do to
improve the organization?</p></li>
<li><p>Is my implementation of a linked list alright?</p></li>
<li><p>The <code>snake</code>'s <code>dx</code> and <code>dy</code> values are either 1, 0, or -1. Should I make it a <code>short</code> instead? Or even <code>char</code>?</p></li>
<li><p>How can I make <code>struct TailNode</code> private to <code>snake.c</code>?</p></li>
<li><p>When do I use <code>static const</code> over macro <code>#define</code>s? Do I use <code>static const</code> when I want my variable private?</p></li>
</ol>
<p>Thanks!</p>
|
[] |
[
{
"body": "<h2>Running but failed?</h2>\n\n<pre><code>running = true;\nreturn success;\n</code></pre>\n\n<p>In all cases you set <code>running</code> to true even if <code>success</code> is false. This seems like an odd decision. Also, you <code>init_snake</code> regardless of the success or failure of previous calls, which does not seem correct. You should be early-bailing in such circumstances.</p>\n\n<h2>Main's early-return</h2>\n\n<p>After this:</p>\n\n<pre><code>if(!init())\n return -1;\n</code></pre>\n\n<p>your <code>else</code> is redundant and can be removed.</p>\n\n<h2>Structural dereferencing</h2>\n\n<p><code>(*e).type</code></p>\n\n<p>should be</p>\n\n<p><code>e->type</code></p>\n\n<p>Similarly for <code>(*ptr).previous</code>, <code>(*new_tail)</code>, etc.</p>\n\n<h2><code>const</code> arguments</h2>\n\n<p>You do not modify <code>e</code> in <code>void handle_events(SDL_Event *e)</code>. As long as it does not cause callback pointer type incompatibility issues, consider making that argument <code>const SDL_Event *e</code>.</p>\n\n<p>That aside: why are you passing in <code>e</code> at all? The way it is written now, <code>e</code> should just be a local variable.</p>\n\n<h2>Non-exported functions</h2>\n\n<p>For functions like <code>init</code> that are not intended for export to other translation units, mark them <code>static</code>. The same is true for any global variables that will not be referenced in other translation units.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T17:33:59.097",
"Id": "241020",
"ParentId": "240985",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "241020",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T04:50:02.127",
"Id": "240985",
"Score": "5",
"Tags": [
"c",
"snake-game",
"sdl"
],
"Title": "Snake game with C and SDL using linked lists"
}
|
240985
|
<pre><code>(define or-l (lambda x
(if (null? x)
#f
(if (car x) #t
(apply or-l (cdr x))))))
(map (lambda (x) (apply or-l x)) '((#t #t) (#f #t) (#t #f) (#f #f)))
'(#t #t #t #f)
</code></pre>
<p>It will be used in a function that evaluates Boolean expressions.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T12:31:35.203",
"Id": "472846",
"Score": "1",
"body": "Welcome to Code Review! What is your actual question? If you're asking whether it runs, please check the [help/on-topic] first. At the least we're going to need more information before we can say anything meaningful about it. What is it supposed to do and what will call this function?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T11:28:05.070",
"Id": "473010",
"Score": "0",
"body": "@Mast I've simplified the question. Please tell me if anything is still unclear and otherwise remove the -1."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T13:10:24.013",
"Id": "473022",
"Score": "0",
"body": "The question is answered now, so I'm not sure the question should be edited now. But for the next time, please keep the previous link (to the [help/on-topic]) and our [FAQ on asking questions](https://codereview.meta.stackexchange.com/q/2436/52915) in mind."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T13:09:05.873",
"Id": "473154",
"Score": "0",
"body": "how will the -1 impact this question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T15:02:51.500",
"Id": "473163",
"Score": "0",
"body": "It won't. Your reputation still rose a net 9 points by asking this question and it isn't scoring low enough to be in danger of anything drastic. It will only impact your account if you keep asking questions where the same thing happens, eventually you'll be temporarily question-banned. Read that help center and [our FAQ on asking questions](https://codereview.meta.stackexchange.com/q/2436/52915) before asking the next one, don't worry, and feel free to ask for help. If you put in the effort, I'm sure you'll be ok."
}
] |
[
{
"body": "<hr>\n\n<h2><code>or-l</code> Is a Poor Name</h2>\n\n<hr>\n\n<p>The OP procedure <code>or-l</code> is correct in that it yields correct results for its inputs. This <code>or-l</code> short-circuits only in the sense that recursive calls through the provided arguments cease when a true value is encountered; yet, this is not the behavior of <a href=\"https://docs.racket-lang.org/reference/if.html#%28form._%28%28lib._racket%2Fprivate%2Fletstx-scheme..rkt%29._or%29%29\" rel=\"nofollow noreferrer\"><code>or</code></a>, which is a <em>special form</em>. The <code>or-l</code> procedure always evaluates <em>all</em> of its arguments, where the <code>or</code> special form evaluates its arguments sequentially until a true value is encountered.</p>\n\n<p>Consider:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>scratch.rkt> (or #t (/ 1 0))\n#t\nscratch.rkt> (or-l #t (/ 1 0))\n; /: division by zero\n</code></pre>\n\n<p>Here <code>or</code> does not evaluate <code>(/ 1 0)</code> because it is a special form which only evaluates forms as needed. But, <code>or-l</code> is a <em>procedure</em> which always evaluates all of its arguments; <code>(/ 1 0)</code> is evaluated before the procedure body is entered, and this evaluation results in an error.</p>\n\n<p>The name <code>or-l</code> should be reconsidered. The name suggests that this procedure applies <code>or</code> to a list, which it does not; it applies <code>or</code> to an unspecified number of arguments. It would be better, perhaps, to call it <code>or-proc</code> to emphasize that it behaves similarly to <code>or</code>, but that it is a procedure and thus evaluates its arguments.</p>\n\n<hr>\n\n<h2>A Better Way</h2>\n\n<hr>\n\n<p>OP has written a somewhat lengthy recursive function which is then applied via <code>map</code> and an anonymous function to a list of boolean lists to achieve OP goal:</p>\n\n<pre><code>(define or-proc\n (lambda x\n (if (null? x)\n #f\n (if (car x)\n #t\n (apply or-proc (cdr x))))))\n</code></pre>\n\n<pre class=\"lang-none prettyprint-override\"><code>(map (lambda (x) (apply or-proc x)) '((#t #t) (#f #t) (#t #f) (#f #f)))\n'(#t #t #t #f)\n</code></pre>\n\n<p>A simpler and cleaner approach would be to take advantage of built-in Racket features such as <a href=\"https://docs.racket-lang.org/reference/pairs.html#%28def._%28%28lib._racket%2Fprivate%2Fmap..rkt%29._ormap%29%29\" rel=\"nofollow noreferrer\"><code>ormap</code></a>. Note that <code>(ormap identity '(#t #f))</code> is equivalent to <code>(or (identity #t) (identity #f))</code>, i.e. <code>(or #t #f)</code>.</p>\n\n<p>With this in mind, here is a better <code>or-l</code> procedure which actually takes a list argument:</p>\n\n<pre><code>(define (or-l xs)\n (ormap identity xs))\n</code></pre>\n\n<p>This procedure can be used more cleanly with the list-of-lists input provided by OP:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>scratch.rkt> (map or-l '((#t #t) (#f #t) (#t #f) (#f #f)))\n'(#t #t #t #f)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T15:48:27.847",
"Id": "241012",
"ParentId": "240991",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "241012",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T08:43:23.707",
"Id": "240991",
"Score": "-1",
"Tags": [
"scheme",
"racket"
],
"Title": "Is this OR procedure correct?"
}
|
240991
|
<p>I implemented mergesort in C as an exercise. I have two main questions:</p>
<ol start="2">
<li><p>Is the code future-proof?</p>
<p>2.1 Will I have problems modifying it to sort float and double?</p>
<p>2.2 What could be problematic for creating a multithreaded version? I haven't learned multithreading in C yet, but I plan on a multithreaded version later on.</p></li>
</ol>
<p>Secondary question:</p>
<ol start="3">
<li>What could I change in the code to make it better?</li>
</ol>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
void join (int* array, int* array_left, int* array_right, size_t len, size_t len_left)
{
size_t counter_left = 0;
size_t counter_right = 0;
for (size_t i = 0; i < len; i++)
{
if (counter_right == len - len_left || counter_left < len_left && array_left[counter_left] <= array_right[counter_right])
{
array[i] = array_left[counter_left];
counter_left++;
}
else
{
array[i] = array_right[counter_right];
counter_right++;
}
}
return;
}
void partition (int* array, int* array_part, size_t start_p, size_t len_p)
{
for (size_t i = start_p; i < len_p; i++)
{
array_part[i-start_p] = array[i];
}
return;
}
void mergesort(int* array, size_t len)
{
if (len <= 1)
{
return;
}
size_t len2 = len / 2;
int array_left[len2];
int array_right[len-len2];
//Partitioning array into left and right
partition (array, array_left, 0, len2);
partition (array, array_right, len2, len);
//recursiv call
mergesort(array_left, len2);
mergesort(array_right, len - len2);
//joining / sorting of the partitions
join(array, array_left, array_right, len, len2);
return;
}
int main()
{
int array[] = {1,2,3,7,8,9,6,5,4,0};
size_t len = sizeof array / sizeof array[0];
printf("Array unsorted: ");
for (int i = 0; i < len; i++)
{
printf("%d", array[i]);
}
printf("\n");
mergesort(array, len);
printf("Array sorted: ");
for (int i = 0; i < len; i++)
{
printf("%d", array[i]);
}
printf("\n");
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T16:42:20.577",
"Id": "472896",
"Score": "1",
"body": "This is merge sort, so I suggest removing question 1. after my edit is reviewed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T11:41:42.003",
"Id": "473011",
"Score": "1",
"body": "Best to avoid mixing sign-ness of integers as in `i < len` or `for (int i = 0; i < len; i++)`, even in test code."
}
] |
[
{
"body": "<ul>\n<li><p>The condition <code>counter_right == len - len_left || counter_left < len_left && array_left[counter_left] <= array_right[counter_right])</code> looks scary. You'd be in much better shape separating <code>join</code> into two phases: actual merge, and handling tails:</p>\n\n<pre><code>void join (int* array, int* array_left, int* array_right, size_t len, size_t len_left)\n{\n size_t counter_left = 0;\n size_t counter_right = 0;\n size_t i;\n\n // Phase 1: merge\n while (counter_left < len_left && counter_right < len - len_left) {\n if (array_left[counter_left] <= array_right[counter_right]) {\n array[i++] = array_left[counter_left++];\n } else {\n array[i++] = array_right[counter_right++];\n }\n }\n\n // Phase 2: tails\n // Now one of the arrays is exhausted. Another one (possibly) still\n // has data. Copy them to the target array.\n // Notice that we don't care which one is empty: copying from an empty\n // array is no-op.\n while (counter_left < len_left) {\n array[i++] = array_left[counter_left++];\n }\n\n while (counter_right < len - len_left) {\n array[i++] = array_right[counter_right++];\n }\n}\n</code></pre></li>\n<li><p>Of course, the two tail loops above implement a <code>copy</code> algorithm, and deserve to be factored out into a function. Interestingly, you already have this function. You just misnamed it. <code>partition</code> is actually <code>copy</code>.</p>\n\n<p>In fact, you may consider dropping altogether, and use <code>memcpy</code> instead.</p></li>\n<li><p>Recursion is expensive. For the arrays small enough, insertion sort is faster. Consider switching to insertion sort when <code>len</code> is less than a threshold, say <code>16</code>. The exact value of the threshold is fine tuning, and requires some profiling experiments.</p></li>\n<li><p>Using VLAs is scary. Given a huge array it may overflow the stack. Consider heap allocation. Notice that the scratch array can be allocated only once.</p></li>\n<li><p>Kudos for <code><=</code> when comparing elements. Many people miss that this is how mergesort maintains stability.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T20:36:30.900",
"Id": "472925",
"Score": "0",
"body": "What I think is weird is that the `copy` in quicksort also copies the element."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T10:09:04.680",
"Id": "473004",
"Score": "0",
"body": "@vnp First of thanks for your help. I was wondering, if I really need to check for ```counter_right < len - len_left``` in the first while_loop. I thought len_left is always smaller or equal to len - len_left, because ```size_t len2 = len / 2;``` will make sure of that. Or is that depending on the system the code is running on?\nAnd can you tell me, what you mean with scratch array? I tried google, but didn't help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T14:21:53.030",
"Id": "473028",
"Score": "0",
"body": "Note that `<=` is insufficient to maintain stability with floating point values that include not-a-number."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T17:06:32.737",
"Id": "241017",
"ParentId": "240992",
"Score": "2"
}
},
{
"body": "<blockquote>\n <p>2.1 Will I have problems modifying it to sort <code>float</code> and <code>double</code>?</p>\n</blockquote>\n\n<p>The \"sort\" comes down to one line:</p>\n\n<pre><code>array_left[counter_left] <= array_right[counter_right]\n</code></pre>\n\n<p>With floating point, sorting concerns include:</p>\n\n<ul>\n<li>Signed zeros: -0.0 and +0.0</li>\n</ul>\n\n<p>Typically the solution is to consider these of equal <em>value</em>. So an array of [-0.0, +0.0, -0.0, +0.0 ...], with the code, should produce a stable sort. If an order is needed (e.g. -0.0 before +0.0) , the compare will need to expand to account for the sign.</p>\n\n<ul>\n<li><a href=\"https://en.wikipedia.org/wiki/NaN\" rel=\"nofollow noreferrer\">Not-a-numbers</a></li>\n</ul>\n\n<p>When <code>x</code> is a NaN, comparing <em>usually</em><sup>1</sup> results in <code>false</code> as in <code>x <= y</code> and even <code>x == x</code>.</p>\n\n<p>With code's singular use of <code><=</code> for comparing, I foresee a problem, perhaps like <a href=\"https://stackoverflow.com/q/48069404/2410359\"><code>qsort()</code></a> which require <a href=\"https://en.wikipedia.org/wiki/Total_order\" rel=\"nofollow noreferrer\">total ordering</a>. A more advanced <a href=\"https://stackoverflow.com/a/48069558/2410359\">compare</a> would be needed to handle arrays which include NaN.</p>\n\n<hr>\n\n<p><sup>1</sup> C does not specify how compares behave with NaN. Most systems do follow IEEE of comparing with <code><= , <, >, >=, ==</code> involving at least 1 NaN is <em>false</em>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T12:15:55.333",
"Id": "241062",
"ParentId": "240992",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T08:56:54.930",
"Id": "240992",
"Score": "4",
"Tags": [
"beginner",
"c",
"sorting",
"mergesort"
],
"Title": "Merge Sort in C"
}
|
240992
|
<p>I've coded up a Vector class for use in my simulation support code, which I offer up for review. </p>
<p>I decided to extend std::array. Now, I know that std::array is an aggregate type, but with C++-17 we can now extend an aggregate base type and still use 'curly brace' initialization. Extending std::array means that each Vector consumes the same, fixed amount of memory as a regular std::array. I've added methods for arithmetic and various Vector operations, such as the cross-product (for N=3 dimensions only), the dot product, and length.</p>
<p>I'd welcome opinions over whether this is a good idea in principle, and also specific suggestions about the details of the code.</p>
<p>The full source code follows. Note that it makes use of a randomization class which is outside the scope of this question, but if you want to see it it is here: <a href="https://github.com/ABRG-Models/morphologica/blob/master/morph/Random.h" rel="noreferrer">https://github.com/ABRG-Models/morphologica/blob/master/morph/Random.h</a></p>
<pre><code>/*!
* \file
* \brief An N dimensional vector class template which derives from std::array.
*
* \author Seb James
* \date April 2020
*/
#pragma once
#include <cmath>
using std::abs;
using std::sqrt;
#include <array>
using std::array;
#include <iostream>
using std::cout;
using std::endl;
using std::ostream;
#include <string>
using std::string;
#include <sstream>
using std::stringstream;
#include <type_traits>
using std::enable_if;
using std::enable_if_t;
using std::is_integral;
using std::is_scalar;
using std::decay_t;
#include "Random.h"
using morph::RandUniformReal;
using morph::RandUniformInt;
namespace morph {
/*!
* \brief N-D vector class
*
* An N dimensional vector class template which derives from std::array. Vector
* components are of scalar type S. It is anticipated that S will be set either to
* floating point scalar types such as float or double, or to integer scalar types
* such as int, long long int and so on. Thus, a typical (and in fact, the default)
* signature would be:
*
* Vector<float, 3> v;
*
* The class inherits std:array's fixed-size array of memory for storing the
* components of the vector. It adds numerous methods which allow objects of type
* Vector to have arithmetic operations applied to them, either scalar (add a scalar
* to all elements; divide all elements by a scalar, etc) or vector (including dot
* and cross products, normalization and so on.
*
* Because morph::Vector extends std::array, it works best when compiled with a
* c++-17 compiler (although it can be compiled with a c++-11 compiler). This is
* because std::array is an 'aggregate class' with no user-provided constructors,
* and morph::Vector does not add any of its own constructors. Prior to c++-17,
* aggregate classes were not permitted to have base classes. So, if you want to do:
*
* Vector<float, 3> v = { 1.0f , 1.0f, 1.0f };
*
* You need c++-17. Otherwise, restrict your client code to doing:
*
* Vector<float, 3> v;
* v[0] = 1.0f; v[1] = 1.0f; v[2] = 1.0f;
*/
template <typename S, size_t N> struct Vector;
/*!
* Template friendly mechanism to overload the stream operator.
*
* Note forward declaration of the Vector template class and this template for
* stream operator overloading. Example adapted from
* https://stackoverflow.com/questions/4660123
*/
template <typename S, size_t N> ostream& operator<< (ostream&, const Vector<S, N>&);
template <typename S=float, size_t N=3>
struct Vector : public array<S, N>
{
//! \return the first component of the vector
template <size_t _N = N, enable_if_t<(_N>0), int> = 0>
S x (void) const {
return (*this)[0];
}
//! \return the second component of the vector
template <size_t _N = N, enable_if_t<(_N>1), int> = 0>
S y (void) const {
return (*this)[1];
}
//! \return the third component of the vector
template <size_t _N = N, enable_if_t<(_N>2), int> = 0>
S z (void) const {
return (*this)[2];
}
//! \return the fourth component of the vector
template <size_t _N = N, enable_if_t<(_N>3), int> = 0>
S w (void) const {
return (*this)[3];
}
/*!
* \brief Unit vector threshold
*
* The threshold outside of which the vector is no longer considered to be a
* unit vector. Note this is hard coded as a constexpr, to avoid messing with
* the initialization of the Vector with curly brace initialization.
*
* Clearly, this will be the wrong threshold for some cases. Possibly, a
* template parameter could set this; so size_t U could indicate the threshold;
* 0.001 could be U=-3 (10^-3).
*
* Another idea would be to change unitThresh based on the type S. Or use
* numeric_limits<S>::epsilon and find out what multiple of epsilon would make
* sense.
*/
static constexpr S unitThresh = 0.001;
/*!
* Set data members from an array the of same size and type.
*/
void setFrom (const array<S, N> v) {
for (size_t i = 0; i < N; ++i) {
(*this)[i] = v[i];
}
}
/*!
* Set the data members of this Vector from the passed in, larger vector, v,
* ignoring the last element of v. Used when working with 4D vectors in graphics
* applications involving 4x4 transform matrices.
*/
void setFrom (const array<S, (N+1)> v) {
for (size_t i = 0; i < N; ++i) {
(*this)[i] = v[i];
}
}
/*!
* Output the vector to stdout
*/
void output (void) const {
cout << "Vector" << this->asString();
}
/*!
* Create a string representation of the vector
*
* \return A 'coordinate format' string such as "(1,1,2)", "(0.2,0.4)" or
* "(5,4,5,5,40)".
*/
string asString (void) const {
stringstream ss;
auto i = this->begin();
ss << "(";
bool first = true;
while (i != this->end()) {
if (first) {
ss << *i++;
first = false;
} else {
ss << "," << *i++;
}
}
ss << ")";
return ss.str();
}
/*!
* Renormalize the vector to length 1.
*/
void renormalize (void) {
S denom = static_cast<S>(0);
auto i = this->begin();
while (i != this->end()) {
denom += ((*i) * (*i));
++i;
}
denom = sqrt(denom);
if (denom != static_cast<S>(0.0)) {
S oneovermag = static_cast<S>(1.0) / denom;
i = this->begin();
while (i != this->end()) {
*i++ *= oneovermag;
}
}
}
/*!
* Randomize the vector
*
* Randomly set the elements of the vector consisting of floating point
* coordinates. Coordinates are set to random numbers drawn from a uniform
* distribution between 0 and 1 (See morph::RandUniformReal for details).
*
* Note that I need a real or int implementation here, depending on the type of
* S. This allows me to use the correct type of randomizer.
*
* Note, if you omit the second template arg from enable_if_t (or enable_if)
* then the type defaults to void.
*
* \tparam F A floating point scalar type
*/
template <typename F=S, enable_if_t<!is_integral<decay_t<F>>::value, int> = 0 >
void randomize (void) {
RandUniformReal<F> ruf (static_cast<F>(0), static_cast<F>(1));
auto i = this->begin();
while (i != this->end()) {
*i++ = ruf.get();
}
}
/*!
* Randomize the vector
*
* Randomly set the elements of the vector consisting of integer
* coordinates. Coordinates are set to random numbers drawn from a uniform
* distribution between 0 and 255 (See morph::RandUniformInt for details).
*
* Note on the template syntax: Here, if I is integral, then enable_if_t's type
* is '0' and the function is defined (I think).
*
* \tparam I An integer scalar type
*/
template <typename I=S, enable_if_t<is_integral<decay_t<I>>::value, int> = 0 >
void randomize (void) {
RandUniformInt<I> rui (static_cast<I>(0), static_cast<I>(255));
auto i = this->begin();
while (i != this->end()) {
*i++ = rui.get();
}
}
/*!
* Test to see if this vector is a unit vector (it doesn't *have* to be).
*
* \return true if the length of the vector is 1.
*/
bool checkunit (void) const {
bool rtn = true;
S metric = 1.0;
auto i = this->begin();
while (i != this->end()) {
metric -= ((*i) * (*i));
++i;
}
if (abs(metric) > morph::Vector<S, N>::unitThresh) {
rtn = false;
}
return rtn;
}
/*!
* Find the length of the vector.
*
* \return the length
*/
S length (void) const {
S sos = static_cast<S>(0);
auto i = this->begin();
while (i != this->end()) {
sos += ((*i) * (*i));
++i;
}
return sqrt(sos);
}
/*!
* Unary negate operator
*
* \return a Vector whose elements have been negated.
*/
Vector<S, N> operator- (void) const {
Vector<S, N> rtn;
auto i = this->begin();
auto j = rtn.begin();
while (i != this->end()) {
*j++ = -(*i++);
}
return rtn;
}
/*!
* Unary not operator.
*
* \return true if the vector length is 0, otherwise it returns false.
*/
bool operator! (void) const {
return (this->length() == static_cast<S>(0.0)) ? true : false;
}
/*!
* Vector multiply * operator.
*
* Cross product of this with another vector v2 (if N==3). In
* higher dimensions, its more complicated to define what the cross product is,
* and I'm unlikely to need anything other than the plain old 3D cross product.
*/
template <size_t _N = N, enable_if_t<(_N==3), int> = 0>
Vector<S, N> operator* (const Vector<S, _N>& v2) const {
Vector<S, _N> v;
v[0] = (*this)[1] * v2.z() - (*this)[2] * v2.y();
v[1] = (*this)[2] * v2.x() - (*this)[0] * v2.z();
v[2] = (*this)[0] * v2.y() - (*this)[1] * v2.x();
return v;
}
/*!
* Vector multiply *= operator.
*
* Cross product of this with another vector v2 (if N==3). Result written into
* this.
*/
template <size_t _N = N, enable_if_t<(_N==3), int> = 0>
void operator*= (const Vector<S, _N>& v2) {
Vector<S, _N> v;
v[0] = (*this)[1] * v2.z() - (*this)[2] * v2.y();
v[1] = (*this)[2] * v2.x() - (*this)[0] * v2.z();
v[2] = (*this)[0] * v2.y() - (*this)[1] * v2.x();
(*this)[0] = v[0];
(*this)[1] = v[1];
(*this)[2] = v[2];
}
/*!
* \brief Scalar (dot) product
*
* Compute the scalar product of this Vector and the Vector, v2.
*
* \return scalar product
*/
S dot (const Vector<S, N>& v2) const {
S rtn = static_cast<S>(0);
auto i = this->begin();
auto j = v2.begin();
while (i != this->end()) {
rtn += ((*i++) * (*j++));
}
return rtn;
}
/*!
* Scalar multiply * operator
*
* This function will only be defined if typename _S is a
* scalar type. Multiplies this Vector<S, N> by s, element-wise.
*/
template <typename _S=S, enable_if_t<is_scalar<decay_t<_S>>::value, int> = 0 >
Vector<S, N> operator* (const _S& s) const {
Vector<S, N> rtn;
auto val = this->begin();
auto rval = rtn.begin();
// Here's a way to iterate through which the compiler should be able to
// autovectorise; it knows what i is on each loop:
for (size_t i = 0; i < N; ++i) {
*(rval+i) = *(val+i) * static_cast<S>(s);
}
return rtn;
}
/*!
* Scalar multiply *= operator
*
* This function will only be defined if typename _S is a
* scalar type. Multiplies this Vector<S, N> by s, element-wise.
*/
template <typename _S=S, enable_if_t<is_scalar<decay_t<_S>>::value, int> = 0 >
void operator*= (const _S& s) {
auto val = this->begin();
for (size_t i = 0; i < N; ++i) {
*(val+i) *= static_cast<S>(s);
}
}
/*!
* Scalar division * operator
*/
template <typename _S=S, enable_if_t<is_scalar<decay_t<_S>>::value, int> = 0 >
Vector<S, N> operator/ (const _S& s) const {
Vector<S, N> rtn;
auto val = this->begin();
auto rval = rtn.begin();
for (size_t i = 0; i < N; ++i) {
*(rval+i) = *(val+i) / static_cast<S>(s);
}
return rtn;
}
/*!
* Scalar division *= operator
*/
template <typename _S=S, enable_if_t<is_scalar<decay_t<_S>>::value, int> = 0 >
void operator/= (const _S& s) {
auto val = this->begin();
for (size_t i = 0; i < N; ++i) {
*(val+i) /= static_cast<S>(s);
}
}
/*!
* Vector addition operator
*/
Vector<S, N> operator+ (const Vector<S, N>& v2) const {
Vector<S, N> v;
auto val = this->begin();
auto val2 = v2.begin();
for (size_t i = 0; i < N; ++i) {
v[i] = *(val+i) + *(val2+i);
}
return v;
}
/*!
* Vector addition operator
*/
void operator+= (const Vector<S, N>& v2) {
auto val = this->begin();
auto val2 = v2.begin();
for (size_t i = 0; i < N; ++i) {
*(val+i) += *(val2+i);
}
}
/*!
* Vector subtraction
*/
Vector<S, N> operator- (const Vector<S, N>& v2) const {
Vector<S, N> v;
auto val = this->begin();
auto val2 = v2.begin();
for (size_t i = 0; i < N; ++i) {
v[i] = *(val+i) - *(val2+i);
}
return v;
}
/*!
* Vector subtraction
*/
void operator-= (const Vector<S, N>& v2) {
auto val = this->begin();
auto val2 = v2.begin();
for (size_t i = 0; i < N; ++i) {
*(val+i) -= *(val2+i);
}
}
/*!
* Scalar addition
*/
template <typename _S=S, enable_if_t<is_scalar<decay_t<_S>>::value, int> = 0 >
Vector<S, N> operator+ (const _S& s) const {
Vector<S, N> rtn;
auto val = this->begin();
auto rval = rtn.begin();
for (size_t i = 0; i < N; ++i) {
*(rval+i) = *(val+i) + static_cast<S>(s);
}
return rtn;
}
/*!
* Scalar addition
*/
template <typename _S=S, enable_if_t<is_scalar<decay_t<_S>>::value, int> = 0 >
void operator+= (const _S& s) {
auto val = this->begin();
for (size_t i = 0; i < N; ++i) {
*(val+i) += static_cast<S>(s);
}
}
/*!
* Scalar subtraction
*/
template <typename _S=S, enable_if_t<is_scalar<decay_t<_S>>::value, int> = 0 >
Vector<S, N> operator- (const _S& s) const {
Vector<S, N> rtn;
auto val = this->begin();
auto rval = rtn.begin();
for (size_t i = 0; i < N; ++i) {
*(rval+i) = *(val+i) - static_cast<S>(s);
}
return rtn;
}
/*!
* Scalar subtraction
*/
template <typename _S=S, enable_if_t<is_scalar<decay_t<_S>>::value, int> = 0 >
void operator-= (const _S& s) {
auto val = this->begin();
for (size_t i = 0; i < N; ++i) {
*(val+i) -= static_cast<S>(s);
}
}
/*!
* Overload the stream output operator
*/
friend ostream& operator<< <S, N> (ostream& os, const Vector<S, N>& v);
};
template <typename S=float, size_t N=3>
ostream& operator<< (ostream& os, const Vector<S, N>& v)
{
os << v.asString();
return os;
}
} // namespace morph
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>There’s a lot of going on here. At a cursory glance:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/a/5849668/1968\">You <em>must not</em> use <code>using</code> in headers at file scope</a>.</li>\n<li>It’s not clear why your template parameter is called <code>S</code> instead of <code>T</code>, and the more I read your source code the more this confuses me. What does <code>S</code> stand for? — The use of <code>T</code> for such member types is near-universal.</li>\n<li>I’m not sure public inheritance is a good idea here: why are you modelling an is-a relationship? Why not private inheritance or a <code>std::array</code> member?</li>\n<li>Don’t declare functions with a <code>(void)</code> parameter list. In C this is necessary to create the correct prototype. In C++ it has no purpose — <code>()</code> does the same, and is conventional.</li>\n<li>Your <code>setFrom</code> member functions should be constructors and assignment operators instead.</li>\n<li>Don’t pass <code>std::array</code> by value, pass it by <code>const&</code> — otherwise a very expensive copy might be created. At the very least make this depend on <code>N</code> as well as <code>sizeof(S)</code> so you can optimise for arrays small enough to be passed inside a single register.</li>\n<li>Use algorithms (<code>std::copy</code>, constructors, assignment) instead of copying your arrays in a <code>for</code> loop.</li>\n<li><code>output</code> is redundant if you define a suitable formatted output stream operator.</li>\n<li>If you want to follow C++ convention, <code>asString</code> should be called <code>str</code>. That’s not necessary of course.</li>\n<li><code>S denom = static_cast<S>(0);</code> can usually be written as <code>auto denom = S{0};</code>, and those cases where this fails because no suitable constructor exists are probably cases where you <em>want</em> this to fail.</li>\n<li>Don’t use <code>while</code> loops to iterate over ranges, it’s unidiomatic and therefore confusing: either use <code>for</code> loops or, better yet, ranged-<code>for</code> loops where possible. And once again use appropriate algorithms. The loop that calculates <code>denom</code> can be replaced by a call to <code>std::accumulate</code>, for instance. That way you can also declare <code>denom</code> as <code>const</code> and initialise it directly.</li>\n<li><code>randomize</code> guards against <code>S</code> being an integral type; <code>renomalize</code> does not, but also needs this constraint.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T15:40:39.377",
"Id": "472884",
"Score": "1",
"body": "Thanks for reviewing! I'll digest this and respond later."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T15:26:28.870",
"Id": "241011",
"ParentId": "241008",
"Score": "5"
}
},
{
"body": "<p>I think, I can comprehend your main idea, \"to create a specialized class for mathematical N-dimensional vectors\" but there are few problems by doing it using inheritance in your case. You should use a truly specialized class for that, think of it, <code>std::vector</code> is a <code>stl</code> container, it is supposed to handle data as a data structure, any class which extends from it, should handle data.</p>\n\n<p>From a design perspective it would be better to create a class which either adapts <code>std::vector</code> as a member (is composed by) or one which has a vector of objects (commonly numerical types, but in extension mathematical objects too).</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>/*using google c++ style guide (only for naming purposes)*/\ntemplate <typename MathObject>\nclass Vector\n{\nprivate:\n //allows to handle a runtime determined size vector\n //could be implemented using std::unique_ptr\n //(define a default constructor in the case that MathObject be a class)\n MathObject *vector_;\n\n size_t dimension_; //allows you to check the dimension of a vector\npublic:\n Vector(MathObject* const& vector, size_t dimension) :\n vector_(vector), dimension_(dimension)\n {\n }\n\n ~Vector()\n {\n delete[] vector_;\n }\n //...\n};\n</code></pre>\n\n<p>Many thanks to <a href=\"https://codereview.stackexchange.com/users/308/konrad-rudolph\">Konrad Rudolph</a> who has mentioned the mistakes on your implementation.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T08:13:29.430",
"Id": "472993",
"Score": "0",
"body": "Hi Miguel, Many thanks for reviewing. I've included a response to you below."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T08:58:09.650",
"Id": "473001",
"Score": "1",
"body": "Using (hopefully) `new` and `delete` here makes the class have weird ownership and pointer semantics; use `std::vector` instead. See [Why should C++ programmers minimize use of 'new'?](https://stackoverflow.com/q/6500313/9716597) for more information. Google C++ Style Guide is also infamous for promoting practices that go against modern C++ programming style - see, for example, [Why Google Style Guide for C++ is a deal-breaker](https://www.reddit.com/r/programming/comments/28alvi/why_google_style_guide_for_c_is_a_dealbreaker/). I wouldn't recommend adopting it unless forced to."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T11:07:08.717",
"Id": "473006",
"Score": "0",
"body": "L. F. What are your thoughts on extending a mathematical Vector class from std::array? Good in principle, or not?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T21:54:54.790",
"Id": "473070",
"Score": "0",
"body": "@L.F. I didn't explain myself well, I only use the naming conventions into the [Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html#General_Naming_Rules), just that, not the Google C++ standard."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T02:19:29.757",
"Id": "241045",
"ParentId": "241008",
"Score": "1"
}
},
{
"body": "<p>Many thanks to Konrad Rudolph and Miguel Avila for time spent reading the code and responding.</p>\n\n<p>I'm responding in an answer, because I want to post an update to the code in which I've followed most of Konrad's suggestions.</p>\n\n<p>In answer to Konrad's points:</p>\n\n<ul>\n<li>Thank you for pointing out the error with <code>using</code> in headers. Fixed.</li>\n<li>I named the template parameter 'S' for Scalar. The idea was to hint that, although this derives from std::array, it is not to be treated as a generic container of any other type. I realise this might look confusing, when T is conventional, but I have left the naming scheme in my updated code as I think this is perhaps a matter of preference rather than correctness.</li>\n<li>I did want an is-a relationship. This relates to Miguel's answer too. I will discuss after finishing this list.</li>\n<li><code>fn(void)</code> all changed to <code>fn()</code>; I'm happy to follow this convention; it looks better, too.</li>\n<li><code>setFrom()</code>: First, I changed to <code>set_from()</code> in the update because lower case looks more in-keeping with STL derived code. Second it can't be a constructor, because I want to keep the Vector as an aggregate type. I don't anticipate using <code>set_from()</code> often, but there is some of my code which needs the feature.</li>\n<li>Good point. I've updated and made use of algorithms; this was a good exercise for me.</li>\n<li>Good point; I've removed output()</li>\n<li>Good point; asString() is now str()</li>\n<li>I like this alternative to static_casts, so I've updated the code accordingly.</li>\n<li>Many of the while's disappeared with std::aggregate and std::transform. Others have been replaced with fors</li>\n<li>I've added a guard for renormalise; I think that occurred to me while I was writing it, but it got forgotten!</li>\n</ul>\n\n<p>So, the last point to discuss is whether deriving from std::array is a good idea. You guys are suspicious, I think, but I still like it.</p>\n\n<p>What does it do for the Vector class?</p>\n\n<ul>\n<li>No need to write constructors - they're banned anyway</li>\n<li>compiler knows exactly the size of the object</li>\n<li>I can use STL iterators on my Vector objects in client code. Consider that these vectors may be used for computations where they really do have high dimensionality (neural nets are one application)</li>\n</ul>\n\n<p>Downsides</p>\n\n<ul>\n<li>If you really need to assign from another type, such as std::array, you have to write an ugly method like set_from().</li>\n<li>Because it derives from an STL container, a coder using Vector might think they can set S=array_type or S=SomeClass - but the type_trait tests should address that.</li>\n</ul>\n\n<p>If you can think of any other concrete downsides, do please list them!</p>\n\n<p>Here is the updated class template. Note that I've included the Random number generator code so that this listing is compilable, even though that code is out of scope. I'll also list a test program to compile against it.</p>\n\n<p>Thanks again!</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>/*!\n * \\file\n * \\brief An N dimensional vector class template which derives from std::array.\n *\n * \\author Seb James (with thanks to Konrad Rudolph and Miguel Avila for code review)\n * \\date April 2020\n */\n#pragma once\n\n#include <cmath>\n#include <array>\n#include <iostream>\n#include <string>\n#include <sstream>\n#include <type_traits>\n#include <numeric>\n#include <algorithm>\n#include <functional>\n// For random number generator only (would normally be a separate <Random.h>)\n#include <random>\n#include <vector>\n#include <limits>\n\nnamespace morph {\n\n /*!\n * \\brief N-D vector class\n *\n * An N dimensional vector class template which derives from std::array. Vector\n * components are of scalar type S. It is anticipated that S will be set either to\n * floating point scalar types such as float or double, or to integer scalar types\n * such as int, long long int and so on. Thus, a typical (and in fact, the default)\n * signature would be:\n *\n * Vector<float, 3> v;\n *\n * The class inherits std:array's fixed-size array of memory for storing the\n * components of the vector. It adds numerous methods which allow objects of type\n * Vector to have arithmetic operations applied to them, either scalar (add a scalar\n * to all elements; divide all elements by a scalar, etc) or vector (including dot\n * and cross products, normalization and so on.\n *\n * Because morph::Vector extends std::array, it works best when compiled with a\n * c++-17 compiler (although it can be compiled with a c++-11 compiler). This is\n * because std::array is an 'aggregate class' with no user-provided constructors,\n * and morph::Vector does not add any of its own constructors. Prior to c++-17,\n * aggregate classes were not permitted to have base classes. So, if you want to do:\n *\n * Vector<float, 3> v = { 1.0f , 1.0f, 1.0f };\n *\n * You need c++-17. Otherwise, restrict your client code to doing:\n *\n * Vector<float, 3> v;\n * v[0] = 1.0f; v[1] = 1.0f; v[2] = 1.0f;\n */\n template <typename S, size_t N> struct Vector;\n\n /*!\n * Template friendly mechanism to overload the stream operator.\n *\n * Note forward declaration of the Vector template class and this template for\n * stream operator overloading. Example adapted from\n * https://stackoverflow.com/questions/4660123\n */\n template <typename S, size_t N> std::ostream& operator<< (std::ostream&, const Vector<S, N>&);\n\n //! forward declaration of random number generator classes\n template <typename T> class RandUniformReal;\n template <typename T> class RandUniformInt;\n\n template <typename S=float, size_t N=3>\n struct Vector : public std::array<S, N>\n {\n //! \\return the first component of the vector\n template <size_t _N = N, std::enable_if_t<(_N>0), int> = 0>\n S x() const {\n return (*this)[0];\n }\n //! \\return the second component of the vector\n template <size_t _N = N, std::enable_if_t<(_N>1), int> = 0>\n S y() const {\n return (*this)[1];\n }\n //! \\return the third component of the vector\n template <size_t _N = N, std::enable_if_t<(_N>2), int> = 0>\n S z() const {\n return (*this)[2];\n }\n //! \\return the fourth component of the vector\n template <size_t _N = N, std::enable_if_t<(_N>3), int> = 0>\n S w() const {\n return (*this)[3];\n }\n\n /*!\n * \\brief Unit vector threshold\n *\n * The threshold outside of which the vector is no longer considered to be a\n * unit vector. Note this is hard coded as a constexpr, to avoid messing with\n * the initialization of the Vector with curly brace initialization.\n *\n * Clearly, this will be the wrong threshold for some cases. Possibly, a\n * template parameter could set this; so size_t U could indicate the threshold;\n * 0.001 could be U=-3 (10^-3).\n *\n * Another idea would be to change unitThresh based on the type S. Or use\n * numeric_limits<S>::epsilon and find out what multiple of epsilon would make\n * sense.\n */\n static constexpr S unitThresh = 0.001;\n\n /*!\n * Set data members from an array the of same size and type.\n */\n void set_from (const std::array<S, N>& ar) {\n std::copy (ar.begin(), ar.end(), this->begin());\n }\n\n /*!\n * Set the data members of this Vector from the passed in, larger array, \\a ar,\n * ignoring the last element of \\a ar. Used when working with 4D vectors in\n * graphics applications involving 4x4 transform matrices.\n */\n void set_from (const std::array<S, (N+1)>& ar) {\n // Don't use std::copy here, because ar has more elements than *this.\n for (size_t i = 0; i < N; ++i) {\n (*this)[i] = ar[i];\n }\n }\n\n /*!\n * Set an N-D Vector from an N+1 D Vector. Intended to convert 4D vectors (that\n * have been operated on by 4x4 matrices) into 3D vectors.\n */\n void set_from (const Vector<S, (N+1)>& v) {\n for (size_t i = 0; i < N; ++i) {\n (*this)[i] = v[i];\n }\n }\n\n /*!\n * Create a string representation of the vector\n *\n * \\return A 'coordinate format' string such as \"(1,1,2)\", \"(0.2,0.4)\" or\n * \"(5,4,5,5,40)\".\n */\n std::string str() const {\n std::stringstream ss;\n ss << \"(\";\n bool first = true;\n for (auto i : *this) {\n if (first) {\n ss << i;\n first = false;\n } else {\n ss << \",\" << i;\n }\n }\n ss << \")\";\n return ss.str();\n }\n\n /*!\n * Renormalize the vector to length 1.0. Only for S types that are floating point.\n */\n template <typename F=S, std::enable_if_t<!std::is_integral<std::decay_t<F>>::value, int> = 0 >\n void renormalize() {\n auto add_squared = [](F a, F b) { return a + b * b; };\n const F denom = std::sqrt (std::accumulate (this->begin(), this->end(), F{0}, add_squared));\n if (denom != F{0}) {\n F oneovermag = F{1} / denom;\n auto x_oneovermag = [oneovermag](F f) { return f * oneovermag; };\n std::transform (this->begin(), this->end(), this->begin(), x_oneovermag);\n }\n }\n\n /*!\n * Randomize the vector\n *\n * Randomly set the elements of the vector consisting of floating point\n * coordinates. Coordinates are set to random numbers drawn from a uniform\n * distribution between 0 and 1 (See morph::RandUniformReal for details).\n *\n * Note that I need a real or int implementation here, depending on the type of\n * S. This allows me to use the correct type of randomizer.\n *\n * Note, if you omit the second template arg from enable_if_t (or enable_if)\n * then the type defaults to void.\n *\n * \\tparam F A floating point scalar type\n */\n template <typename F=S, std::enable_if_t<!std::is_integral<std::decay_t<F>>::value, int> = 0 >\n void randomize() {\n RandUniformReal<F> ruf (static_cast<F>(0), static_cast<F>(1));\n for (auto& i : *this) {\n i = ruf.get();\n }\n }\n\n /*!\n * Randomize the vector\n *\n * Randomly set the elements of the vector consisting of integer\n * coordinates. Coordinates are set to random numbers drawn from a uniform\n * distribution between 0 and 255 (See morph::RandUniformInt for details).\n *\n * Note on the template syntax: Here, if I is integral, then enable_if_t's type\n * is '0' and the function is defined (I think).\n *\n * \\tparam I An integer scalar type\n */\n template <typename I=S, std::enable_if_t<std::is_integral<std::decay_t<I>>::value, int> = 0 >\n void randomize() {\n RandUniformInt<I> rui (static_cast<I>(0), static_cast<I>(255));\n for (auto& i : *this) {\n i = rui.get();\n }\n }\n\n /*!\n * Test to see if this vector is a unit vector (it doesn't *have* to be).\n *\n * \\return true if the length of the vector is 1.\n */\n bool checkunit() const {\n auto subtract_squared = [](S a, S b) { return a - b * b; };\n const S metric = std::accumulate (this->begin(), this->end(), S{1}, subtract_squared);\n if (std::abs(metric) > Vector<S, N>::unitThresh) {\n return false;\n }\n return true;\n }\n\n /*!\n * Find the length of the vector.\n *\n * \\return the length\n */\n S length() const {\n auto add_squared = [](S a, S b) { return a + b * b; };\n const S len = std::sqrt (std::accumulate (this->begin(), this->end(), S{0}, add_squared));\n return len;\n }\n\n /*!\n * Unary negate operator\n *\n * \\return a Vector whose elements have been negated.\n */\n Vector<S, N> operator-() const {\n Vector<S, N> rtn;\n std::transform (this->begin(), this->end(), rtn.begin(), std::negate<S>());\n return rtn;\n }\n\n /*!\n * Unary not operator.\n *\n * \\return true if the vector length is 0, otherwise it returns false.\n */\n bool operator!() const {\n return (this->length() == S{0}) ? true : false;\n }\n\n /*!\n * Vector multiply * operator.\n *\n * Cross product of this with another vector \\a v (if N==3). In\n * higher dimensions, its more complicated to define what the cross product is,\n * and I'm unlikely to need anything other than the plain old 3D cross product.\n */\n template <size_t _N = N, std::enable_if_t<(_N==3), int> = 0>\n Vector<S, N> operator* (const Vector<S, _N>& v) const {\n Vector<S, _N> vrtn;\n vrtn[0] = (*this)[1] * v.z() - (*this)[2] * v.y();\n vrtn[1] = (*this)[2] * v.x() - (*this)[0] * v.z();\n vrtn[2] = (*this)[0] * v.y() - (*this)[1] * v.x();\n return vrtn;\n }\n\n /*!\n * Vector multiply *= operator.\n *\n * Cross product of this with another vector v (if N==3). Result written into\n * this.\n */\n template <size_t _N = N, std::enable_if_t<(_N==3), int> = 0>\n void operator*= (const Vector<S, _N>& v) {\n Vector<S, _N> vtmp;\n vtmp[0] = (*this)[1] * v.z() - (*this)[2] * v.y();\n vtmp[1] = (*this)[2] * v.x() - (*this)[0] * v.z();\n vtmp[2] = (*this)[0] * v.y() - (*this)[1] * v.x();\n std::copy (vtmp.begin(), vtmp.end(), this->begin());\n }\n\n /*!\n * \\brief Scalar (dot) product\n *\n * Compute the scalar product of this Vector and the Vector, v.\n *\n * \\return scalar product\n */\n S dot (const Vector<S, N>& v) const {\n auto vi = v.begin();\n auto dot_product = [vi](S a, S b) mutable { return a + b * (*vi++); };\n const S rtn = std::accumulate (this->begin(), this->end(), S{0}, dot_product);\n return rtn;\n }\n\n /*!\n * Scalar multiply * operator\n *\n * This function will only be defined if typename _S is a\n * scalar type. Multiplies this Vector<S, N> by s, element-wise.\n */\n template <typename _S=S, std::enable_if_t<std::is_scalar<std::decay_t<_S>>::value, int> = 0 >\n Vector<_S, N> operator* (const _S& s) const {\n Vector<_S, N> rtn;\n auto mult_by_s = [s](_S coord) { return coord * s; };\n std::transform (this->begin(), this->end(), rtn.begin(), mult_by_s);\n return rtn;\n }\n\n /*!\n * Scalar multiply *= operator\n *\n * This function will only be defined if typename _S is a\n * scalar type. Multiplies this Vector<S, N> by s, element-wise.\n */\n template <typename _S=S, std::enable_if_t<std::is_scalar<std::decay_t<_S>>::value, int> = 0 >\n void operator*= (const _S& s) {\n auto mult_by_s = [s](_S coord) { return coord * s; };\n std::transform (this->begin(), this->end(), this->begin(), mult_by_s);\n }\n\n /*!\n * Scalar divide by s\n */\n template <typename _S=S, std::enable_if_t<std::is_scalar<std::decay_t<_S>>::value, int> = 0 >\n Vector<_S, N> operator/ (const _S& s) const {\n Vector<_S, N> rtn;\n auto div_by_s = [s](_S coord) { return coord / s; };\n std::transform (this->begin(), this->end(), rtn.begin(), div_by_s);\n return rtn;\n }\n\n /*!\n * Scalar divide by s\n */\n template <typename _S=S, std::enable_if_t<std::is_scalar<std::decay_t<_S>>::value, int> = 0 >\n void operator/= (const _S& s) {\n auto div_by_s = [s](_S coord) { return coord / s; };\n std::transform (this->begin(), this->end(), this->begin(), div_by_s);\n }\n\n /*!\n * Vector addition operator\n */\n Vector<S, N> operator+ (const Vector<S, N>& v) const {\n Vector<S, N> vrtn;\n auto vi = v.begin();\n auto add_v = [vi](S a) mutable { return a + (*vi++); };\n std::transform (this->begin(), this->end(), vrtn.begin(), add_v);\n return vrtn;\n }\n\n /*!\n * Vector addition operator\n */\n void operator+= (const Vector<S, N>& v) {\n auto vi = v.begin();\n auto add_v = [vi](S a) mutable { return a + (*vi++); };\n std::transform (this->begin(), this->end(), this->begin(), add_v);\n }\n\n /*!\n * Vector subtraction operator\n */\n Vector<S, N> operator- (const Vector<S, N>& v) const {\n Vector<S, N> vrtn;\n auto vi = v.begin();\n auto subtract_v = [vi](S a) mutable { return a - (*vi++); };\n std::transform (this->begin(), this->end(), vrtn.begin(), subtract_v);\n return vrtn;\n }\n\n /*!\n * Vector subtraction operator\n */\n void operator-= (const Vector<S, N>& v) {\n auto vi = v.begin();\n auto subtract_v = [vi](S a) mutable { return a - (*vi++); };\n std::transform (this->begin(), this->end(), this->begin(), subtract_v);\n }\n\n /*!\n * Scalar addition\n */\n template <typename _S=S, std::enable_if_t<std::is_scalar<std::decay_t<_S>>::value, int> = 0 >\n Vector<_S, N> operator+ (const _S& s) const {\n Vector<_S, N> rtn;\n auto add_s = [s](_S coord) { return coord + s; };\n std::transform (this->begin(), this->end(), rtn.begin(), add_s);\n return rtn;\n }\n\n /*!\n * Scalar addition\n */\n template <typename _S=S, std::enable_if_t<std::is_scalar<std::decay_t<_S>>::value, int> = 0 >\n void operator+= (const _S& s) {\n auto add_s = [s](_S coord) { return coord + s; };\n std::transform (this->begin(), this->end(), this->begin(), add_s);\n }\n\n /*!\n * Scalar subtraction\n */\n template <typename _S=S, std::enable_if_t<std::is_scalar<std::decay_t<_S>>::value, int> = 0 >\n Vector<_S, N> operator- (const _S& s) const {\n Vector<_S, N> rtn;\n auto subtract_s = [s](_S coord) { return coord - s; };\n std::transform (this->begin(), this->end(), rtn.begin(), subtract_s);\n return rtn;\n }\n\n /*!\n * Scalar subtraction\n */\n template <typename _S=S, std::enable_if_t<std::is_scalar<std::decay_t<_S>>::value, int> = 0 >\n void operator-= (const _S& s) {\n auto subtract_s = [s](_S coord) { return coord - s; };\n std::transform (this->begin(), this->end(), this->begin(), subtract_s);\n }\n\n /*!\n * Overload the stream output operator\n */\n friend std::ostream& operator<< <S, N> (std::ostream& os, const Vector<S, N>& v);\n };\n\n template <typename S=float, size_t N=3>\n std::ostream& operator<< (std::ostream& os, const Vector<S, N>& v)\n {\n os << v.str();\n return os;\n }\n\n /*\n * Random number generator classes outside scope of code review, but included so\n * that file compiles:\n */\n\n //! Generate uniform random numbers in a floating point format.\n template <typename T = double>\n class RandUniformReal\n {\n private:\n std::random_device rd{};\n std::mt19937_64 generator{rd()};\n std::uniform_real_distribution<T> dist;\n public:\n //! Default constructor gives RN generator which works in range [0,1)\n RandUniformReal (void) {\n typename std::uniform_real_distribution<T>::param_type prms (T{0}, T{1});\n this->dist.param (prms);\n }\n //! This constructor gives RN generator which works in range [a,b)\n RandUniformReal (T a, T b) {\n typename std::uniform_real_distribution<T>::param_type prms (a, b);\n this->dist.param (prms);\n }\n //! Get 1 random number from the generator\n T get (void) { return this->dist (this->generator); }\n //! Get n random numbers from the generator\n std::vector<T> get (size_t n) {\n std::vector<T> rtn (n, T{0});\n for (size_t i = 0; i < n; ++i) {\n rtn[i] = this->dist (this->generator);\n }\n return rtn;\n }\n T min (void) { return this->dist.min(); }\n T max (void) { return this->dist.max(); }\n };\n\n //! Generate uniform random numbers in a integer format\n template <typename T = unsigned int>\n class RandUniformInt\n {\n private:\n std::random_device rd{};\n std::mt19937_64 generator{rd()};\n std::uniform_int_distribution<T> dist;\n public:\n //! Default constructor gives an integer RNG which works in range [0,(type max))\n RandUniformInt (void) {\n typename std::uniform_int_distribution<T>::param_type prms (std::numeric_limits<T>::min(),\n std::numeric_limits<T>::max());\n this->dist.param (prms);\n }\n //! This constructor gives RN generator which works in range [a,b)\n RandUniformInt (T a, T b) {\n typename std::uniform_int_distribution<T>::param_type prms (a, b);\n this->dist.param (prms);\n }\n //! Get 1 random number from the generator\n T get (void) { return this->dist (this->generator); }\n //! Get n random numbers from the generator\n std::vector<T> get (size_t n) {\n std::vector<T> rtn (n, T{0});\n for (size_t i = 0; i < n; ++i) {\n rtn[i] = this->dist (this->generator);\n }\n return rtn;\n }\n T min (void) { return this->dist.min(); }\n T max (void) { return this->dist.max(); }\n };\n\n} // namespace morph\n</code></pre>\n\n<p>The test program:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#include \"Vector.h\"\nusing morph::Vector;\nusing std::cout;\nusing std::endl;\nusing std::array;\n\nint main() {\n int rtn = 0;\n Vector<float, 4> v = {1,2,3};\n cout << \"x component of v: \" << v.x() << endl;\n v.renormalize();\n cout << \"After renormalize: \" << v << \"; unit vector? \" << (v.checkunit() ? \"yes\" : \"no\") << endl;\n v.randomize();\n cout << \"After randomize: \" << v << endl;\n Vector<int, 5> vi;\n vi.randomize();\n cout << \"After randomize of 5D int vector: \" << vi << endl;\n cout << \"Length: \" << vi.length() << endl;\n // Test assignment\n Vector<int, 5> vi2 = vi;\n cout << \"Copy of int vector: \" << vi2 << endl;\n // Test comparison\n cout << \"vi == vi2? \" << (vi == vi2 ? \"yes\" : \"no\") << endl;\n // Test negate\n Vector<int, 5> vi3 = -vi;\n cout << \"-ve Copy of int vector: \" << vi3 << endl;\n // Test comparison\n cout << \"vi == vi3? \" << (vi == vi3 ? \"yes\" : \"no\") << endl;\n // Test cross product (3D only\n Vector<double, 3> a = {1,0,0};\n Vector<double, 3> b = {0,1,0};\n Vector<double, 3> c = a * b;\n cout << a << \"*\" << b << \"=\" << c << endl;\n // dot product\n Vector<int, 2> vv1 = {5,8};\n Vector<int, 2> vv2 = {2,5};\n int dp = vv1.dot (vv2);\n cout << vv1 << \".\" << vv2 << \" = \" << dp << endl;\n#if 0 // No good:\n // Test init from array\n array<float, 3> arr = { 2,3,4 };\n Vector<float, 3> varr = arr; // Tried overloading operator= to no avail.\n cout << \"Vector from array: \" << varr << endl;\n#endif\n // Scalar multiply\n cout << vv2;\n vv2 *= 2UL;\n cout << \" * 2 = \" << vv2 << endl;\n Vector<int, 2> vv4 = vv1 * 3;\n cout << \"vv1 * 3 = \" << vv4 << endl;\n#if 0 // No good, as expected:\n // Scalar multiply with different type\n double dbl = 3.0;\n Vector<int, 2> vv5 = vv1 * dbl;\n cout << \"vv1 * 3.0 = \" << vv4 << endl;\n#endif\n // Scalar division\n Vector<double, 3> d = a/3.0;\n cout << \"a / 3.0 = \" << d << endl;\n // Vector addition\n Vector<double, 3> e = a+b;\n cout << \"a + b = \" << e << endl;\n // Vector subtraction\n Vector<double, 3> f = a-b;\n cout << \"a - b = \" << f << endl;\n // Test default template args\n Vector<double> vd_def;\n vd_def.randomize();\n cout << \"Vector<double> and randomize: \" << vd_def << endl;\n Vector<> v_def;\n v_def.randomize();\n cout << \"Vector<> and randomize: \" << v_def << endl;\n\n // dot product of large vector\n const size_t n = 1000000; // Approx limit on my laptop: 1045000\n Vector<float, n> big1;\n Vector<float, n> big2;\n big1.randomize();\n big2.randomize();\n float bdp = big1.dot(big2);\n cout << \"(N=\"<<n<<\") big1.big2 = \" << bdp << endl;\n\n // Test set_from\n Vector<double, 3> d1;\n array<double, 3> a1 = { 5,6,7 };\n d1.set_from (a1);\n cout << \"After set_from(), d1 should be (5,6,7): \" << d1 << endl;\n array<double, 4> a2 = { 5,6,8,8 };\n d1.set_from (a2);\n cout << \"After set_from(), d1 should be (5,6,8): \" << d1 << endl;\n\n return rtn;\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T08:28:28.757",
"Id": "472998",
"Score": "0",
"body": "The largest N that seems to work for that test program on my computer is approx 1045000 (const size_t n = 1046000; in the 'dot product of a large vector' leads to a crash )"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T11:10:19.707",
"Id": "473007",
"Score": "0",
"body": "For very large n, perhaps it would be possible to create the Vector class by extending either std::vector or std::list instead of std::array. This choice could even be given to the client programmer as a template option."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T08:10:16.913",
"Id": "241051",
"ParentId": "241008",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "241011",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T14:02:11.447",
"Id": "241008",
"Score": "5",
"Tags": [
"c++",
"c++17",
"coordinate-system"
],
"Title": "An N-dimensional mathematical vector template class deriving from std::array (C++-17)"
}
|
241008
|
<p>I do this as sort of hobby and want to no if I can improve.<br>
This is a simplified version of my code that normal works with bootstrap classes and id's.<br>
At the bottom there is the input of the classes.<br>
I have already a working version connected with SQL Database.<br>
but want to take it a step further with object oriented php.<br>
<br>
The next step for me is to create the content page underneath the navbar.<br>
I work with a .htaccess file that redirects everything to index.php, and then use the URI to show the right content.<br>
<br>
The main class</p>
<pre><code><?php
class Main
{
public $URL;
public $PageName;
public function __construct($PageName)
{
$this->PageName = $PageName;
$this->URL = $_SERVER['REQUEST_URI'];
}
public static function header() {
echo '<!DOCTYPE html>
<html lang="en">
<head>
...
</head>';
}
public static function navstart() {
echo '<body><nav><ul>';
}
public static function navend() {
echo '</ul></nav>';
}
}
the navitem class is for making the items in the nav bar<br>
class navItem extends Main
{
public function __construct($PageName)
{
parent::__construct($PageName);
$ActiveUrl = ($this->URL == "/".$this->PageName) ? " active " : " ";
echo '<li class="nav-item">
<a class="nav-link'.$ActiveUrl.'" href="'.$this->PageName.'">'.$this->PageName.'</a></li> &nbsp;';
}
}
</code></pre>
<p>The nav dropdown class to make the dropdown in the navbar</p>
<pre><code>class navDropdown extends Main
{
public function __construct($PageName, $Item)
{
parent::__construct($PageName);
$shortURL = substr($this->URL, 0, strpos($this->URL, "_"));
$ActiveUrl = ($shortURL == "/".$this->PageName) ? " active " : " ";
echo '
<li class="nav-item dropdown ">
<a class="nav-link'.$ActiveUrl.' href="#">'.$this->PageName.'</a>
<div>';
foreach ($Item as $Item) {
$ActiveUrl = ($this->URL == "/".$this->PageName.'_'.$Item) ? " active " : " ";
echo '
<a class="dropdown-item'.$ActiveUrl.'" href="./'.$this->PageName.'_'.$Item.'" >'.$Item.'</a>';
}
echo '</div></li> &nbsp;';
}
}
</code></pre>
<p>the variables to make the page</p>
<pre><code>main::header();
main::navstart();
$test = new navDropDown("test", array('test1' , 'test2', 'test3' , 'test4'));
$home = new navItem("home");
$about = new navItem("about");
$pages = new navDropDown("pages",array("one", "two", "three" ));
$contact = new navItem("contact");
main::navend();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T22:00:28.217",
"Id": "472944",
"Score": "0",
"body": "I think you need to make some edits, especially in the markup. Currently the following is in a code block section and it shouldn't be: `the navitem class is for making the items in the nav bar`."
}
] |
[
{
"body": "<p>I think you have some reading/research to do as I'm not sure you understand OOP...</p>\n\n<h2>What is Main?</h2>\n\n<ul>\n<li>Main is setup as a class, used as a namespace in instantiation, then extended(why?).</li>\n<li>Generally in the context it seems to be intended to be used <code>App</code> or <code><AppName></code> are better options</li>\n</ul>\n\n<h2>When to extend</h2>\n\n<ul>\n<li>Why do all elements extend <code>Main</code>?\n\n<ul>\n<li>It appears to be solely for it's constructor which it never uses itself. (Extra Baggage in Main)</li>\n<li><code>Main</code> also only contains functions the other elements never need or use (Extra Baggage in the Sub-Objects)</li>\n</ul></li>\n<li>Extending a class makes more sense if the classes extended from it share functionality</li>\n</ul>\n\n<h2>What even is an Object? ##</h2>\n\n<ul>\n<li>You seem to be using your objects as functions disguised as things.\n\n<ul>\n<li>For example: when you create a <code>navItem</code>:</li>\n<li>You create the object</li>\n<li>It's controller prints itself to the screen</li>\n<li>You capture it in a variable never to be used again. Why?</li>\n</ul></li>\n</ul>\n\n<h2>Who gets to be an Object?</h2>\n\n<ul>\n<li><code>navItem</code> is an object <code>navBar</code> Isn't</li>\n<li><code>navDropdown</code> is an object <code>navDropdownItem</code> isn't</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T21:15:23.017",
"Id": "472939",
"Score": "0",
"body": "Thanks I Will do soms reading and try again"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T16:15:02.183",
"Id": "241015",
"ParentId": "241009",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T14:51:47.113",
"Id": "241009",
"Score": "1",
"Tags": [
"php",
"object-oriented"
],
"Title": "Makes a navbar for a website with object oriented php"
}
|
241009
|
<p>I have been learning linked lists for the past three days. I feel I have implemented a complete linked list. Are there any more things a linked list should do?</p>
<p>Please can you review any or all of my code. I would be most interested in feed back to the more tricky section of the linked list.</p>
<pre class="lang-py prettyprint-override"><code>class Node:
def __init__(self, data):
self.data = data # the data for a node
self.next = None # the pointer of a node, right now it points to no other node, so None
class linked_list:
def __init__(self):
self.head = None # initializes the first node which has nothing at the beginning
def len(self): # returns the length/number of values in the linked list
current_node = self.head
count = 0
while current_node is not None:
current_node = current_node.next
count += 1
return count
def display(self): # displays the data in the nodes as a list []
current_node = self.head # assigns the head node to a value
node_list = [] # creates a list to store the value of the nodes
while current_node is not None: # the end of the linked list is represented by a node with it's Next having None
node_list.append(current_node.data) # append the value of the nodes to the list
current_node = current_node.next # the current node at work is now the next node
print(node_list) # prints the list representation of the linked list
def prepend(self, newdata): # inserts a new node with data at the beginning of the linked list, which becomes the headnode
NewNode = Node(newdata) # creates a new node with the data
NewNode.next = self.head # the next of the new node now points at the head node
self.head = NewNode # the new node is now the head of the node, as it is the first node in the linked list
def after_insert(self, before_node, newdata):
if before_node is None: # if node is absent
print("The mentioned node is absent")
return
NewNode = Node(newdata)
NewNode.next = before_node.next # the next of the new node is now the node after the before_node Ex: if 1->3, 2(new node)->3(next node of the 1 node)
before_node.next = NewNode # the before node now points to the new node Ex: since 2->3 now, 1->2, so 1->2->3
def append(self, newdata): # inserts a new node with data at the end of the linked list. which becomes the last node
NewNode = Node(newdata) # creates a new node with the data
if self.head is None: # if the linked list is empty
self.head = NewNode # the head is now the new node
return
current_node = self.head # assigns the head node to a value
while current_node.next is not None: # if current nodes next is None, then the current node is the last node in the linked list
current_node = current_node.next # iterating through the nodes in the linked list
current_node.next = NewNode # at the last node, the next of the last node is now the new node
def remove(self, node_data):
current_node = self.head # assigns the head node to the variable head
if current_node is not None: # then the linked list is not empty
if current_node.data == node_data: # if the head node is the data to be removed
self.head = current_node.next # the node after the head node is now the head node
current_node = None # and there is no value at the head
return
while current_node is not None: # while the linked list is not empty or while the next of the node is not None ( last node )
if current_node.data == node_data: # if the value of the current node is equal to the data to be removed
break # then break the loop
previous_node = current_node # the previous node is the current node
current_node = current_node.next # the current node is now the node after it
if current_node == None: # if the linked list is empty
return # returns None
previous_node.next = current_node.next # the next of the previous node now points at the next of the current node Ex: if 1->2->3, and 2 is removed, then 1's pointer now points at 2''s pointer which is 3 so 1->3
current_node = None # sets the value of the key to be removed to None
def find(self, keydata): # returns the index of a data of a node if available, otherwise None
current_node = self.head # the current node is the first node
count = 0 # initialising a counter for index
if self.len() == 0: # if the linked list is empty
return # return None
while current_node is not None: # while the next of the current node is not none
if current_node.data == keydata: # if the data of the current node is the key data
break #
current_node = current_node.next # if it is not the data wanted, go to the next node
count += 1 # increase the index, when going to the next node
if current_node is None: # if the linked list does not contain the keydata
return #
return count # return count if the keydata exists
List = linked_list() # setting List as a linked list object
List.head = Node("Mon") # assigning the value of the first node in the linked list to "Mon"
e2 = Node("Tue") # creating nodes
e3 = Node("Wed") # which aren't connected to each other
List.head.next = e2 # Links the first node to the second node, by pointing the next value of the node to the next node
e2.next = e3 # Links the second node to the third node, by pointing the next value of the node to the next node
List.display() # displays the data in the linked list as a list, before change
print(List.len()) # length of list
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T16:16:53.263",
"Id": "472892",
"Score": "1",
"body": "Please don't add tags that don't relate to the question. I've removed functional programming as it doesn't belong here. I'd be more than happy to add it back if you can explain how this code follows FP."
}
] |
[
{
"body": "<p>This looks pretty good! One suggestion off the bat is to run a style checker (e.g. PEP8) to help tell you about things like weird whitespace or lines that run on for a little too long.</p>\n\n<p>Another overall suggestion is not to comment every line of code. Use a docstring at the start of a function to say what the function does overall, and only comment individual lines of code that don't seem self-explanatory. For example, if you have a comment in the definition of <code>Node</code> that explains what a <code>None</code> pointer represents, you don't need to re-explain this each time that situation is encountered. A good example is a line like:</p>\n\n<pre><code>if before_node is None: # if node is absent\n</code></pre>\n\n<p>The comment <code>if node is absent</code> is almost identical to the actual code and does not aid the reader in understanding; just omit comments like this. :)</p>\n\n<h2>Suggestions on class definitions</h2>\n\n<ol>\n<li>Use <code>CamelCase</code> for all class names (i.e. <code>LinkedList</code>, not <code>linked_list</code>.)</li>\n<li>If a class is \"private\" to a module, consider naming it with a leading underscore (<code>_Node</code>). That way other people importing your module know that the <code>Node</code> objects aren't part of the interface to your <code>LinkedList</code>.</li>\n<li>Similarly, the <code>self.head</code> node attribute in your <code>LinkedList</code> class should be private. The reason for this is that if a user of your list modifies the node directly, they're very likely to break the list; you want them to use the functions you've defined for accessing the list so that the structure stays correct.</li>\n<li>If you want users of your list class to be able to declare types for what they contain, you can do that by defining it as a <code>Generic</code>. (If you haven't learned about Python types yet, don't worry about it, but you can file this note away for when you do.) </li>\n</ol>\n\n<p>That'd look like this:</p>\n\n<pre><code>from typing import Generic, Optional, TypeVar\n\n\n_V = TypeVar('_V')\n\n\nclass _Node(Generic[_V]):\n def __init__(self, data: _V):\n # The data for this node\n self.data = data\n # The next node in the list, or None if this is the last one.\n self.next: Optional['_Node[_V]'] = None\n\n\nclass LinkedList(Generic[_V]):\n def __init__(self):\n self._head: Optional[_Node[_V]] = None # first node (starts as none)\n</code></pre>\n\n<p>The <code>Generic[_V]</code> business is saying that this is a class that can be associated with some arbitrary other type, which we're referring to with <code>_V</code> as a kind of placeholder to indicate that it doesn't matter what this type is, but it's the <em>same</em> type everywhere in these two classes -- whenever you create a <code>LinkedList</code> you can say it's a list of <strong>something</strong>, and the type of that something (<code>_V</code>) is the same throughout that list. </p>\n\n<p>So when you declare a <code>LinkedList[str]</code>, its <code>self._head</code> is an <code>Optional[_Node[str]]</code>, which itself has a <code>.next</code> that is also an <code>Optional[_Node[str]]</code>. If we declare a <code>LinkedList[int]</code>, then <code>_V</code> in the context of that list is <code>int</code> instead, so all of its nodes hold <code>int</code>s. Et cetera.</p>\n\n<h2>Magic functions!</h2>\n\n<p>For common operations like \"get the number of items in this collection\" or \"give me a string representation of this object\", Python has the concept of \"magic functions\" that you can implement so that your class can interact with built-in functions the same way as its own lists, dicts, etc.</p>\n\n<p>In particular, your first two methods are very good candidates for implementations as \"magic functions\":</p>\n\n<pre><code> def __len__(self) -> int:\n \"\"\"The number of values in the linked list.\"\"\"\n current_node = self._head\n count = 0\n while current_node is not None:\n current_node = current_node.next\n count += 1\n return count\n\n def __str__(self) -> str:\n \"\"\"Formats the data in the nodes as a list []\"\"\"\n current_node = self._head\n node_list = []\n while current_node is not None:\n node_list.append(current_node.data)\n current_node = current_node.next\n return(str(node_list))\n</code></pre>\n\n<p>With these changes, you can now use your list more or less like a native Python list:</p>\n\n<pre><code>linked_list: LinkedList[str] = LinkedList() # use snake_case for variable names\nlinked_list.append(\"Mon\") # use the public interface, not linked_list._head\nlinked_list.append(\"Tue\")\nlinked_list.append(\"Wed\")\n\nprint(linked_list)\nprint(len(linked_list))\n</code></pre>\n\n<p>Per the note above on class definitions and private variables, the user of your list shouldn't be creating their own <code>Node</code> objects, they should be using the nice <code>append()</code> method that you've implemented that takes care of all the pointers for them! </p>\n\n<p>Implementing the <code>__len__</code> and <code>__str__</code> methods makes it so that they can just <code>print(linked_list)</code> instead of calling a special display method, and get its <code>len</code> the same way as any other Python object.</p>\n\n<h2>Error handling</h2>\n\n<p>If your code encounters an error condition that means something has gone terribly wrong, it's better to <code>raise</code> an exception than to print a message and do nothing; you can see a message at the console, but it's hard to test for it in the code! For example:</p>\n\n<pre><code> if before_node is None:\n raise ValueError(\"The mentioned node is absent\")\n</code></pre>\n\n<p>will still get your error message to the user, but now it's also available to another coder who's using your list.</p>\n\n<p>If you use type annotations, you can improve this type of error handling by explicitly stating in the definition of the function that <code>before_node</code> is not allowed to be <code>None</code>:</p>\n\n<pre><code> def after_insert(self, before_node: _Node[_V], new_data: _V) -> None:\n if before_node is None: # this is never a valid value now!\n raise ValueError(\"The mentioned node is absent\")\n</code></pre>\n\n<p>Per the notes above on public/private interfaces, I'd suggest not having <code>after_insert</code> as a public method, at least not with <code>before_node</code> as the parameter. Since you have a method to retrieve an index, maybe that could be the public interface for this method? E.g.:</p>\n\n<pre><code> def _after_insert(self, before_node: _Node[_V], new_data: _V) -> None:\n new_node = _Node(new_data)\n new_node.next = before_node.next\n before_node.next = new_node\n # before_node now points to new_node\n # Ex: since 2->3 now, 1->2, so 1->2->3\n\n def _find_node(self, index: int) -> _Node[_V]:\n current_index = 0\n current_node = self._head\n while current_index < index and current_node is not None:\n index += 1\n current_node = current_node.next\n if current_node is not None:\n return current_node\n raise IndexError(\"Index larger than this list!\")\n\n def after_insert(self, before_index: int, new_data: _V) -> None:\n \"\"\"\n Inserts new data after the node with the given index.\n Raises IndexError if the index exceeds the length of the list.\n \"\"\"\n self._after_insert(self._find_node(before_index), new_data)\n</code></pre>\n\n<h2>Avoid indirection</h2>\n\n<p>This code in your <code>remove</code> looked at first like it was redundant because it was so similar to the <code>while</code> loop that follows it; a hazard of every line being commented is that when a comment is actually significant the reader's eyes are likely to skip over it! :)</p>\n\n<pre><code> current_node = self._head # assigns the head node to the variable head \n if current_node is not None: # then the linked list is not empty\n if current_node.data == node_data: # if the head node is the data to be removed\n self._head = current_node.next # the node after the head node is now the head node\n current_node = None # and there is no value at the head\n return\n</code></pre>\n\n<p>Since in this special case you're <em>specifically</em> operating on the head node, I think it would be better to do this before you even start with the <code>current_node</code> iteration:</p>\n\n<pre><code> if self._head and self._head.data == node_data:\n # Special case: remove the head.\n self._head = self._head.next\n return\n current_node = self._head\n while current_node is not None:\n ...\n</code></pre>\n\n<p>A couple of other notes on this function:</p>\n\n<ol>\n<li>Setting <code>current_node = None</code> before you return doesn't do anything since it's a local variable; omit lines of code that do nothing.</li>\n<li>Should it raise an error if the caller tries to <code>remove</code> data that's not there? For example:</li>\n</ol>\n\n<pre><code> if current_node is None:\n raise ValueError(\"No such data in this list!\")\n # Remove current_node by having previous_node skip over it.\n previous_node.next = current_node.next\n</code></pre>\n\n<h2>Return when you're done!</h2>\n\n<p>The <code>find</code> method can be simplified by having it return as soon as you know the answer, rather than having it break out of the loop and then figure out afterward whether the loop is over because you found the answer or because you didn't. :)</p>\n\n<pre><code> def find(self, key_data: _V) -> Optional[int]:\n \"\"\"returns the index of a data of a node if it exists\"\"\"\n if self._head is None:\n return None # list is empty\n current_node = self._head\n current_index = 0\n while current_node is not None:\n if current_node.data == keydata:\n return current_index \n current_node = current_node.next\n current_index += 1\n return None # data not found\n</code></pre>\n\n<p>Note that rather than making a variable called <code>count</code> and then having a comment explaining that it represents an index:</p>\n\n<pre><code>count = 0 # initialising a counter for index\n</code></pre>\n\n<p>you can let the name speak for itself:</p>\n\n<pre><code>current_index = 0\n</code></pre>\n\n<p>Naming it <code>current_index</code> makes it clear that it's the index of <code>current_node</code> (make alike look alike!). You could draw the association even closer by assigning the two values together, i.e.:</p>\n\n<pre><code> current_node, current_index = self._head, 0\n while current_node is not None:\n if current_node.data == keydata:\n return current_index \n current_node, current_index = current_node.next, current_index + 1\n</code></pre>\n\n<p>but this makes the lines longer and creates a bit of visual clutter, so YMMV on that one.</p>\n\n<h2>Testing</h2>\n\n<p>All in all the code seems to work well; as I went through and added type annotations, I didn't get any errors from the type checker, which is a good sign that you've done a good job of handling all the null pointer cases. :) There's obviously lots of room for optimization (e.g. tracking the tail node would make your <code>append</code> faster, and tracking the length as you add/remove nodes would make your <code>len</code> faster), but as far as a basic singly-linked list this seems like a pretty solid implementation.</p>\n\n<p>To make extra sure of that it'd be good to have a few tests. For example, here's a way you could do a randomized test that your <code>remove</code> function works regardless of where in the list you're removing elements from and never messes up your <code>len</code> calculation:</p>\n\n<pre><code>import random\n\nnumber_list: LinkedList[int] = LinkedList()\n# Add numbers 0-99 to the list in random order.\nfor i in random.sample(range(100), 100):\n number_list.append(i)\nassert len(number_list) == 100\n# Now remove from 99-0 in order to test that\n# remove() works regardless of where the item is.\nfor n in range(99, -1, -1):\n number_list.remove(n)\n assert len(number_list) == n\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T19:40:00.093",
"Id": "472913",
"Score": "0",
"body": "I have a question regarding the Node class. Should I put it outside the LinkedList class like above or inside the LinkedList class. I feel like the Node is part of the LinkedList and shouldn't be outside."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T20:11:15.423",
"Id": "472921",
"Score": "0",
"body": "Good question! Personally I find the syntax of nested classes to be a bit awkward whenever I've tried to use them; seems like I always end up with a lot of `LinkedList._Node` or whatever all over my code. So despite the allure of neat encapsulation that nested classes offer, I end up defining them at the module level and just using the leading `_` to indicate that they shouldn't be imported or instantiated outside that module."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T17:50:41.473",
"Id": "241022",
"ParentId": "241013",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "241022",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T15:59:48.480",
"Id": "241013",
"Score": "3",
"Tags": [
"python",
"beginner",
"python-3.x",
"linked-list",
"reinventing-the-wheel"
],
"Title": "Implementing Linked Lists in Python as a beginner"
}
|
241013
|
<p>I recently programmed a decently-sized program in Python, since I have just started really getting a feel for it. I am currently learning about dictionaries, so I didn't include any, but next time I recreate this I will. If anyone has any feedback or revisions, please notify me. This took around 20 minutes to develop in Atom.</p>
<pre><code>import secrets
import time
import sys
#rock, paper, scissors game
score = 0
cpu_score = 0
def main_game():
print('Welcome to rock, paper, scissors! Your goal is to defeat me in a game.')
user_selection = input("What would you like to choose?")
cpu_selections = [rock, paper, scissors]
if user_selection == 'Rock':
cpu_choice = secrets.choice(cpu_selections)
print(cpu_choice)
if cpu_choice == 'paper':
loss_script()
if cpu_choice == 'rock':
print("We've tied. Rerunning script...")
time.sleep(1)
main_game()
if cpu_choice == 'paper':
victory_script()
if user_selection == 'Paper':
cpu_choice = secrets.choice(cpu_selections)
print(cpu_choice)
if cpu_choice == 'Rock':
victory_script()
if cpu_choice == 'paper':
print("Rerunning script...")
time.sleep(3)
main_game()
if cpu_choice == 'scissors':
loss_script()
def victory_script():
print("Congratulations! You have defeated me!")
score += 1
time.sleep(2)
print("Your score is", score)
print("My score is", cpu_score)
play_again = input("Would you like to play again? yes/no")
if play_again == 'Yes':
main_game()
if play_again == 'No':
time.sleep(1)
print("Alright. Have a great day! Here is your final score:", score)
print("Here is mine: ", cpu_score)
if cpu_score > score:
point_differential = cpu_score - score
print("In total, I defeated you by a margin of", point_differential)
time.sleep(3)
sys.exit()
if cpu_score < score:
point_differential = score - cpu_score
print("In total, you defeated me by a margin of", point_differential)
time.sleep(3)
sys.exit()
def loss_script():
print("I win!")
print("Valiant efforts, but you have been defeated.")
cpu_score += 1
time.sleep(2)
play_again = input("Would you like to play again? yes/no")
if play_again == 'Yes':
main_game()
if play_again == 'No':
time.sleep(1)
print("Alright. Have a great day! Here is your final score:", score)
print("And here is mine:", cpu_score)
if cpu_score > score:
point_differential = cpu_score - score
print("In total, I defeated you by a margin of", point_differential)
time.sleep(3)
sys.exit()
if cpu_score < score:
point_differential = score - cpu_score
print("In total, you defeated me by a margin of", point_differential)
time.sleep(3)
sys.exit()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T17:26:06.607",
"Id": "472898",
"Score": "0",
"body": "I'm sorry about the inconvenient formatting in advance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T17:47:39.700",
"Id": "472900",
"Score": "4",
"body": "Is this actually what the code looks like in Atom? If not, please fix it. Incorrect formatting isn't just inconvenient in Python - it often breaks the program."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T19:33:18.113",
"Id": "472912",
"Score": "0",
"body": "Yeah that code is an eye sore to look at formatted like that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T21:34:57.223",
"Id": "472941",
"Score": "0",
"body": "It's not normally what it looks like, it did that for some reason. It's really weird. However, it works in Atom. Also, is the code good?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T00:01:55.163",
"Id": "472950",
"Score": "0",
"body": "This is not syntactically valid Python with its current indentation. I get an `unexpected indent` error on line 16."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T00:05:16.437",
"Id": "472951",
"Score": "0",
"body": "I took a quick pass to see if I could fix the indentation for you, but it looks like there are other copy+paste errors in there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T01:27:54.157",
"Id": "472959",
"Score": "0",
"body": "If you do not know `for` and `while` loops i suggest you should study these, because they are good options -to not repeat code-."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T02:11:00.927",
"Id": "472964",
"Score": "1",
"body": "after fixing the indentation, there is no entry point to the program, it does nothing... is your paste not only poorly formatted, but also incomplete?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T17:57:06.117",
"Id": "473054",
"Score": "0",
"body": "@ShaunH Code Review doesn't require users to explicitly call the entry point."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T17:25:12.333",
"Id": "241018",
"Score": "1",
"Tags": [
"python",
"programming-challenge",
"game"
],
"Title": "Rock Paper Scissors Python Revision"
}
|
241018
|
<p>I've been meaning to revisit <a href="https://codereview.stackexchange.com/q/46506/23788">this old code</a> for a long time, and this week finally ended up doing it. The resulting code is on <a href="https://github.com/rubberduck-vba/examples/tree/master/SecureADODB" rel="noreferrer">GitHub</a>, and for full context and disclosure I wrote a <a href="https://rubberduckvba.wordpress.com/2020/04/22/secure-adodb/" rel="noreferrer">blog article</a> about this exercise in OOP design.</p>
<p>The idea is to abstract away the pain of making secure ADODB queries. This <em>immediate pane</em> command:</p>
<pre><code>?UnitOfWork.FromConnectionString("connection string").Command.GetSingleValue("SELECT Field1 FROM Table1 WHERE Id=?", 1)
</code></pre>
<p>Produces this debug output:</p>
<pre class="lang-none prettyprint-override"><code>Begin connect...
Connect completed. Status: 1
Begin transaction completed.
Begin execute...
Execute completed, -1 record(s) affected.
{whatever value was in Field1}
Rollback transaction completed.
Disconnect completed. Status: 1
</code></pre>
<p>The <code>1</code> is being passed to the command as a proper <code>ADODB.Parameter</code>. I've <a href="https://github.com/rubberduck-vba/examples/issues/3" rel="noreferrer">already identified</a> the need for an <code>IDbParameter</code> abstraction, but does anything else stand out?</p>
<p>Note: this post only covers the "unit of work" bits. See GitHub repository for additional context and the source code for the other types involved.</p>
<hr>
<h3>IUnitOfWork</h3>
<p>From the calling code's perspective, the top-level API object is the <em>unit of work</em> - the <code>IUnitOfWork</code> class formalizes its interface:</p>
<pre class="lang-vb prettyprint-override"><code>
VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
END
Attribute VB_Name = "IUnitOfWork"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = True
Attribute VB_Description = "Represents an object encapsulating a database transaction."
'@Folder("SecureADODB.UnitOfWork")
'@ModuleDescription("Represents an object encapsulating a database transaction.")
'@Interface
'@Exposed
Option Explicit
'@Description("Commits the transaction.")
Public Sub Commit()
Attribute Commit.VB_Description = "Commits the transaction."
End Sub
'@Description("Rolls back the transaction.")
Public Sub Rollback()
Attribute Rollback.VB_Description = "Rolls back the transaction."
End Sub
'@Description("Creates a new command to execute as part of the transaction.")
'@Ignore ShadowedDeclaration: false positive here, this is an abstract @Interface class
Public Function Command() As IDbCommand
Attribute Command.VB_Description = "Creates a new command to execute as part of the transaction."
End Function
</code></pre>
<h3>UnitOfWork</h3>
<p>The <code>UnitOfWork</code> class implements it - there are two factory methods; <code>Create</code> takes in all dependencies (tests use that), and <code>FromConnectionString</code> wires up convenient defaults for the user code to consume for the most common scenarios:</p>
<pre class="lang-vb prettyprint-override"><code>VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
END
Attribute VB_Name = "UnitOfWork"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = True
Attribute VB_Description = "An object that encapsulates a database transaction."
'@Folder("SecureADODB.UnitOfWork")
'@ModuleDescription("An object that encapsulates a database transaction.")
'@PredeclaredId
'@Exposed
Option Explicit
Implements IUnitOfWork
Private Type TUnitOfWork
Committed As Boolean
RolledBack As Boolean
Connection As IDbConnection
CommandFactory As IDbCommandFactory
End Type
Private this As TUnitOfWork
'@Description("Creates a new unit of work using default configurations.")
'@Ignore ProcedureNotUsed
Public Function FromConnectionString(ByVal connString As String) As IUnitOfWork
Attribute FromConnectionString.VB_Description = "Creates a new unit of work using default configurations."
Dim db As IDbConnection
Set db = DbConnection.Create(connString)
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 = DefaultDbCommandFactory.Create(baseCommand)
Set FromConnectionString = UnitOfWork.Create(db, factory)
End Function
'@Inject: just an idea.. see #https://github.com/rubberduck-vba/Rubberduck/issues/5463
Public Function Create(ByVal db As IDbConnection, ByVal factory As IDbCommandFactory) As IUnitOfWork
Errors.GuardNonDefaultInstance Me, UnitOfWork
Errors.GuardNullReference factory
Errors.GuardNullReference db
Errors.GuardExpression db.State <> adStateOpen, message:="Connection should be open."
Dim result As UnitOfWork
Set result = New UnitOfWork
Set result.CommandFactory = factory
Set result.Connection = db
Set Create = result
End Function
'@Inject: this member should only be invoked by Me.Create, where Me is the class' default/predeclared instance.
'@Ignore ProcedureNotUsed: false positive with v2.5.0.5418
Friend Property Set Connection(ByVal value As IDbConnection)
Errors.GuardDoubleInitialization this.Connection
Errors.GuardNullReference value
Set this.Connection = value
this.Connection.BeginTransaction
End Property
'@Inject: this member should only be invoked by Me.Create, where Me is the class' default/predeclared instance.
'@Ignore ProcedureNotUsed: false positive with v2.5.0.5418
Friend Property Set CommandFactory(ByVal value As IDbCommandFactory)
Errors.GuardDoubleInitialization this.CommandFactory
Errors.GuardNullReference value
Set this.CommandFactory = value
End Property
Private Sub Class_Terminate()
On Error Resume Next
If Not this.Committed Then this.Connection.RollbackTransaction
On Error GoTo 0
End Sub
Private Sub IUnitOfWork_Commit()
Errors.GuardExpression this.Committed, message:="Transaction is already committed."
Errors.GuardExpression this.RolledBack, message:="Transaction was rolled back."
On Error Resume Next ' not all providers support transactions
this.Connection.CommitTransaction
this.Committed = True
On Error GoTo 0
End Sub
Private Function IUnitOfWork_Command() As IDbCommand
Set IUnitOfWork_Command = this.CommandFactory.Create(this.Connection)
End Function
Private Sub IUnitOfWork_Rollback()
Errors.GuardExpression this.Committed, message:="Transaction is already committed."
On Error Resume Next ' not all providers support transactions
this.Connection.RollbackTransaction
this.RolledBack = True
On Error GoTo 0
End Sub
</code></pre>
<h3>UnitOfWorkTests</h3>
<p>These are all the Rubberduck unit tests that have the <code>UnitOfWork</code> class as their SUT:</p>
<pre class="lang-vb prettyprint-override"><code>Attribute VB_Name = "UnitOfWorkTests"
'@TestModule
'@Folder("Tests")
'@IgnoreModule
Option Explicit
Option Private Module
Private Const ExpectedError As Long = SecureADODBCustomError
#Const LateBind = LateBindTests
#If LateBind Then
Private Assert As Object
#Else
Private Assert As Rubberduck.PermissiveAssertClass
#End If
'@ModuleInitialize
Private Sub ModuleInitialize()
#If LateBind Then
Set Assert = CreateObject("Rubberduck.PermissiveAssertClass")
#Else
Set Assert = New Rubberduck.PermissiveAssertClass
#End If
End Sub
'@ModuleCleanup
Private Sub ModuleCleanup()
Set Assert = Nothing
End Sub
'@TestMethod("Factory Guard")
Private Sub Create_ThrowsIfNotInvokedFromDefaultInstance()
On Error GoTo TestFail
With New UnitOfWork
On Error GoTo CleanFail
Dim sut As IUnitOfWork
Set sut = .Create(New StubDbConnection, New StubDbCommandFactory)
On Error GoTo 0
End With
CleanFail:
If Err.Number = ExpectedError Then Exit Sub
TestFail:
Assert.Fail "Expected error was not raised."
End Sub
'@TestMethod("Factory Guard")
Private Sub Create_ThrowsGivenNullConnection()
On Error GoTo CleanFail
Dim sut As IUnitOfWork
Set sut = UnitOfWork.Create(Nothing, New StubDbCommandFactory)
On Error GoTo 0
CleanFail:
If Err.Number = ExpectedError Then Exit Sub
TestFail:
Assert.Fail "Expected error was not raised."
End Sub
'@TestMethod("Factory Guard")
Private Sub Create_ThrowsGivenConnectionStateNotOpen()
On Error GoTo TestFail
Dim db As StubDbConnection
Set db = New StubDbConnection
db.State = adStateClosed
On Error GoTo CleanFail
Dim sut As IUnitOfWork
Set sut = UnitOfWork.Create(db, New StubDbCommandFactory)
On Error GoTo 0
CleanFail:
If Err.Number = ExpectedError Then Exit Sub
TestFail:
Assert.Fail "Expected error was not raised."
End Sub
'@TestMethod("Factory Guard")
Private Sub Create_ThrowsGivenNullCommandFactory()
On Error GoTo CleanFail
Dim sut As IUnitOfWork
Set sut = UnitOfWork.Create(New StubDbConnection, Nothing)
On Error GoTo 0
CleanFail:
If Err.Number = ExpectedError Then Exit Sub
TestFail:
Assert.Fail "Expected error was not raised."
End Sub
'@TestMethod("Guard Clauses")
Private Sub CommandFactory_ThrowsIfAlreadySet()
On Error GoTo TestFail
Dim sut As UnitOfWork
Set sut = UnitOfWork.Create(New StubDbConnection, New StubDbCommandFactory)
On Error GoTo CleanFail
Set sut.CommandFactory = New StubDbCommandFactory
On Error GoTo 0
CleanFail:
If Err.Number = ExpectedError Then Exit Sub
TestFail:
Assert.Fail "Expected error was not raised."
End Sub
'@TestMethod("Guard Clauses")
Private Sub Connection_ThrowsIfAlreadySet()
On Error GoTo TestFail
Dim sut As UnitOfWork
Set sut = UnitOfWork.Create(New StubDbConnection, New StubDbCommandFactory)
On Error GoTo CleanFail
Set sut.Connection = New StubDbConnection
On Error GoTo 0
CleanFail:
If Err.Number = ExpectedError Then Exit Sub
TestFail:
Assert.Fail "Expected error was not raised."
End Sub
'@TestMethod("UnitOfWork")
Private Sub Command_CreatesDbCommandWithFactory()
Dim stubCommandFactory As StubDbCommandFactory
Set stubCommandFactory = New StubDbCommandFactory
Dim sut As IUnitOfWork
Set sut = UnitOfWork.Create(New StubDbConnection, stubCommandFactory)
Dim result As IDbCommand
Set result = sut.Command
Assert.AreEqual 1, stubCommandFactory.CreateCommandInvokes
End Sub
'@TestMethod("UnitOfWork")
Private Sub Create_StartsTransaction()
Dim stubConnection As StubDbConnection
Set stubConnection = New StubDbConnection
Dim sut As IUnitOfWork
Set sut = UnitOfWork.Create(stubConnection, New StubDbCommandFactory)
Assert.IsTrue stubConnection.DidBeginTransaction
End Sub
'@TestMethod("UnitOfWork")
Private Sub Commit_CommitsTransaction()
Dim stubConnection As StubDbConnection
Set stubConnection = New StubDbConnection
Dim sut As IUnitOfWork
Set sut = UnitOfWork.Create(stubConnection, New StubDbCommandFactory)
sut.Commit
Assert.IsTrue stubConnection.DidCommitTransaction
End Sub
'@TestMethod("UnitOfWork")
Private Sub Commit_ThrowsIfAlreadyCommitted()
On Error GoTo TestFail
Dim stubConnection As StubDbConnection
Set stubConnection = New StubDbConnection
Dim sut As IUnitOfWork
Set sut = UnitOfWork.Create(stubConnection, New StubDbCommandFactory)
sut.Commit
On Error GoTo CleanFail
sut.Commit
On Error GoTo 0
CleanFail:
If Err.Number = ExpectedError Then Exit Sub
TestFail:
Assert.Fail "Expected error was not raised."
End Sub
'@TestMethod("UnitOfWork")
Private Sub Commit_ThrowsIfAlreadyRolledBack()
On Error GoTo TestFail
Dim stubConnection As StubDbConnection
Set stubConnection = New StubDbConnection
Dim sut As IUnitOfWork
Set sut = UnitOfWork.Create(stubConnection, New StubDbCommandFactory)
sut.Rollback
On Error GoTo CleanFail
sut.Commit
On Error GoTo 0
CleanFail:
If Err.Number = ExpectedError Then Exit Sub
TestFail:
Assert.Fail "Expected error was not raised."
End Sub
'@TestMethod("UnitOfWork")
Private Sub Rollback_ThrowsIfAlreadyCommitted()
On Error GoTo TestFail
Dim stubConnection As StubDbConnection
Set stubConnection = New StubDbConnection
Dim sut As IUnitOfWork
Set sut = UnitOfWork.Create(stubConnection, New StubDbCommandFactory)
sut.Commit
On Error GoTo CleanFail
sut.Rollback
On Error GoTo 0
CleanFail:
If Err.Number = ExpectedError Then Exit Sub
TestFail:
Assert.Fail "Expected error was not raised."
End Sub
</code></pre>
<h3>Errors</h3>
<p>The custom errors are raised in a standard module named <code>Errors</code>:</p>
<pre class="lang-vb prettyprint-override"><code>Attribute VB_Name = "Errors"
Attribute VB_Description = "Global procedures for throwing common errors."
'@Folder("SecureADODB")
'@ModuleDescription("Global procedures for throwing common errors.")
Option Explicit
Option Private Module
Public Const SecureADODBCustomError As Long = vbObjectError Or 32
'@Description("Re-raises the current error, if there is one.")
Public Sub RethrowOnError()
Attribute RethrowOnError.VB_Description = "Re-raises the current error, if there is one."
With VBA.Information.Err
If .Number <> 0 Then
Debug.Print "Error " & .Number, .Description
.Raise .Number
End If
End With
End Sub
'@Description("Raises a run-time error if the specified Boolean expression is True.")
Public Sub GuardExpression(ByVal throw As Boolean, _
Optional ByVal Source As String = "SecureADODB.Errors", _
Optional ByVal message As String = "Invalid procedure call or argument.")
Attribute GuardExpression.VB_Description = "Raises a run-time error if the specified Boolean expression is True."
If throw Then VBA.Information.Err.Raise SecureADODBCustomError, Source, message
End Sub
'@Description("Raises a run-time error if the specified instance isn't the default instance.")
Public Sub GuardNonDefaultInstance(ByVal instance As Object, ByVal defaultInstance As Object, _
Optional ByVal Source As String = "SecureADODB.Errors", _
Optional ByVal message As String = "Method should be invoked from the default/predeclared instance of this class.")
Attribute GuardNonDefaultInstance.VB_Description = "Raises a run-time error if the specified instance isn't the default instance."
Debug.Assert TypeName(instance) = TypeName(defaultInstance)
GuardExpression Not instance Is defaultInstance, Source, message
End Sub
'@Description("Raises a run-time error if the specified object reference is already set.")
Public Sub GuardDoubleInitialization(ByVal instance As Object, _
Optional ByVal Source As String = "SecureADODB.Errors", _
Optional ByVal message As String = "Object is already initialized.")
Attribute GuardDoubleInitialization.VB_Description = "Raises a run-time error if the specified object reference is already set."
GuardExpression Not instance Is Nothing, Source, message
End Sub
'@Description("Raises a run-time error if the specified object reference is Nothing.")
Public Sub GuardNullReference(ByVal instance As Object, _
Optional ByVal Source As String = "SecureADODB.Errors", _
Optional ByVal message As String = "Object reference cannot be Nothing.")
Attribute GuardNullReference.VB_Description = "Raises a run-time error if the specified object reference is Nothing."
GuardExpression instance Is Nothing, Source, message
End Sub
'@Description("Raises a run-time error if the specified string is empty.")
Public Sub GuardEmptyString(ByVal value As String, _
Optional ByVal Source As String = "SecureADODB.Errors", _
Optional ByVal message As String = "String cannot be empty.")
Attribute GuardEmptyString.VB_Description = "Raises a run-time error if the specified string is empty."
GuardExpression value = vbNullString, Source, message
End Sub
</code></pre>
<p>Can anything be improved? Did I forget any tests? I write in <code>README.md</code> that the abstraction is <em>leaky on purpose</em> in order to retain the full flexibility of the ADODB library, ...but I have to admit it looks pretty airtight at that level. </p>
<p>At the <code>IDbConnection</code> level though...</p>
<p>...Wrinkles appear. It's almost as if I needed another interface to separate the internal API from the public API!</p>
<h3>IDbConnection</h3>
<p>Here I'm wrapping an <code>ADODB.Connection</code> - I need to expose the <code>ADODB.Connection</code> object <em>somehow</em>, in order to be able to create commands off that connection.</p>
<pre class="lang-vb prettyprint-override"><code>VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
END
Attribute VB_Name = "IDbConnection"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = True
Attribute VB_Description = "Represents an object that wraps an active ADODB connection."
'@Folder("SecureADODB.DbConnection.Abstract")
'@ModuleDescription("Represents an object that wraps an active ADODB connection.")
'@Exposed
'@Interface
Option Explicit
'@Description("Gets the wrapped ADODB connection.")
Public Property Get AdoConnection() As ADODB.Connection
Attribute AdoConnection.VB_Description = "Gets the wrapped ADODB connection."
End Property
'@Description("Gets the state of the wrapped ADODB connection.")
Public Property Get State() As ADODB.ObjectStateEnum
Attribute State.VB_Description = "Gets the state of the wrapped ADODB connection."
End Property
'@Description("Creates an ADODB.Command that uses the wrapped connection")
Public Function CreateCommand(ByVal commandType As ADODB.CommandTypeEnum, ByVal sql As String) As ADODB.Command
Attribute CreateCommand.VB_Description = "Creates an ADODB.Command that uses the wrapped connection"
End Function
'@Description("Returns the object itself. Useful to retrieve the With object variable in a With block.")
Public Property Get Self() As IDbConnection
Attribute Self.VB_Description = "Returns the object itself. Useful to retrieve the With object variable in a With block."
End Property
Public Sub BeginTransaction()
End Sub
Public Sub CommitTransaction()
End Sub
Public Sub RollbackTransaction()
End Sub
</code></pre>
<hr>
<h3>Best Practices</h3>
<p>I've given a bit of thought about the various ways the API could be used & misused (probably something to do with the leaky abstractions!), and came up with these "best practices" usage guidelines:</p>
<ul>
<li><strong>DO</strong> hold the object reference in a <code>With</code> block. (e.g. <code>With New UnitOfWork.FromConnectionString(...)</code>)</li>
<li><strong>DO</strong> have an active <code>On Error</code> statement to graciously handle any errors.</li>
<li><strong>DO</strong> commit or rollback the transaction explicitly in the scope that owns the <code>IUnitOfWork</code> object.</li>
<li><strong>CONSIDER</strong> passing <code>IDbCommand</code> as an argument to other scopes.</li>
<li><strong>AVOID</strong> passing <code>IUnitOfWork</code> as a parameter to another object or procedure.</li>
<li><strong>AVOID</strong> accidentally re-entering a <code>With</code> block from an error-handling subroutine (i.e. avoid <code>Resume</code>, <code>Resume [label]</code>, and <code>Resume Next</code> in these subroutines). If there was an error, execution jumped out of the <code>With</code> block that held the references, and the transaction was rolled back and the connection is already closed: there's nothing left to clean up.</li>
</ul>
<p>I think that's pretty consistent with the implementation, but did I miss anything important?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T18:16:48.830",
"Id": "472903",
"Score": "3",
"body": "Shoddy work as usual :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T18:28:25.027",
"Id": "472906",
"Score": "1",
"body": "Minor catch; `db.State = adStateClosed` I guess won't be defined if you late bind, but it's not caught in conditional compilation. Unless your binding is mixed - as might be indicated by the naming of your `LateBindTests` constant (i.e. unique binding for tests) - in which case I've got to ask why?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T18:30:56.317",
"Id": "472907",
"Score": "0",
"body": "`LateBindTests` is for RD to know whether or not to include the Rubberduck typelib in the project refs to run the tests - I should have mentioned, the code is written (for now) to require the ADODB reference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T20:53:53.303",
"Id": "472928",
"Score": "1",
"body": "Just a quicky, with regards to checking the state of an object, (more particularly the connection object), you should do bit-wise checks. For example, when a connection is executing a command, then the `ADODB.ObjectStateEnum = adStateOpen and adStateExecuting`, so ADODB.ObjectStateEnum = adStateOpen would be a in invalid comparison. A bit-wise comparison like so will address this: `(connection.State And ADODB.ObjectStateEnum.adStateOpen) = ADODB.ObjectStateEnum.adStateOpen`"
}
] |
[
{
"body": "<p>I have been silently waiting for you to post this for a while. I was working on something nearly identical to this, and almost posted my stuff a couple of weeks ago, but I wasn't sure of how to hook the events on the connection object without housing all of the event procedures inside the <code>UnitOfWork</code>. That just didn't seem right to me, so I decided I would wait just a little longer in hopes that you would randomly revisit your old code, and boy am I glad I did. The object model of this API is exactly what it needs to be (much like .NET's <code>System.Data' / 'System.Data.Common</code>). </p>\n\n<p>Saying that, there is one thing that I would to address, so, lets get into it. </p>\n\n<p>The idea of a <em>unit of work</em>, is to encapsulate a transaction(s), i.e. track the objects affected by actions performed on the database and then <em>commit</em> or <em>rollback</em> the changes made by those actions. This means that without transactions, the <code>UnitOfWork</code> is virtually useless. </p>\n\n<p>In both of <code>IUnitOfWork_Commit</code> and <code>IUnitOfWork_Rollback</code>, you are ignoring any errors associated with provider transaction support. This makes <code>UnitOfWork</code> a bit misleading, because the client code may not account for the fact that a particular provider does not support the use of transactions. If this is so, then it may full well be assumed that transaction usage is permitted, because nothing in the API indicates otherwise. Say that several updates/deletes/inserts are performed, but then, it is determined that those actions need to be rolled back...except...they can't be...and what's done is done. </p>\n\n<p>I think it might be better to block, the usage of <code>UnitOfWork</code> by raising an error if the connection's provider does not support transactions. This would prevent client code from assuming anything, and force them to use an <code>IDbConnection</code> directly instead. You could implement one of your <code>Error.GuardXxxxx</code> methods in the UoW's contructors, <code>FromConnectionString</code> and <code>Create</code> like so: </p>\n\n<pre><code>'@Description(\"Raises a run-time error if the specified connection does not support usage of transactions.\")\nPublic Sub GuardNoTransactionSupport(ByVal connection As IDbConnection, _\nOptional ByVal Source As String = \"SecureADODB.Errors\", _\nOptional ByVal message As String = \"Provider does not support transactions.\")\n GuardExpression Not SupportsTransactions(connection.AdoConnection), Source, message\nEnd Sub\n\n'Returns false If the TRANSACTION_PROPERTY_NAME does not exist in the connection's properties collection\nPublic Function SupportsTransactions(ByVal connection As ADODB.Connection) As Boolean\n\n Const TRANSACTION_PROPERTY_NAME As String = \"Transaction DDL\"\n\n On Error Resume Next \n SupportsTransactions = connection.Properties(TRANSACTION_PROPERTY_NAME)\n On Error GoTo 0\n\nEnd Function\n</code></pre>\n\n<p>Then <code>FromConnectionString</code> and <code>Create</code> Become: </p>\n\n<pre><code>Public Function FromConnectionString(ByVal connString As String) As IUnitOfWork\n\n Dim db As IDbConnection\n Set db = DbConnection.Create(connString)\n Errors.GuardNoTransactionSupport db \n\n Dim provider As IParameterProvider\n Set provider = AdoParameterProvider.Create(AdoTypeMappings.Default)\n\n Dim baseCommand As IDbCommandBase\n Set baseCommand = DbCommandBase.Create(provider)\n\n Dim factory As IDbCommandFactory\n Set factory = DefaultDbCommandFactory.Create(baseCommand)\n\n Set FromConnectionString = UnitOfWork.Create(db, factory)\n\nEnd Function\n\nPublic Function Create(ByVal db As IDbConnection, ByVal factory As IDbCommandFactory) As IUnitOfWork\n Errors.GuardNonDefaultInstance Me, UnitOfWork\n Errors.GuardNullReference factory\n Errors.GuardNullReference db\n Errors.GuardExpression db.State <> adStateOpen, message:=\"Connection should be open.\"\n Errors.GuardNoTransactionSupport db \n\n Dim result As UnitOfWork\n Set result = New UnitOfWork\n Set result.CommandFactory = factory\n Set result.Connection = db\n\n Set Create = result\nEnd Function\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T15:11:11.963",
"Id": "473033",
"Score": "0",
"body": "Ooh nice! Hadn't realized the connection itself could tell us if it supported transactions - good stuff! I did find other minor problems though, e.g. one could invoke `UnitOfWork.FromConnectionString` off a non-default instance, and it wouldn't throw the expected error (missing guard clause and tests). The comment you made about using bitwise logic to check the state is also very upvote-worthy feedback =)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T16:02:09.193",
"Id": "473043",
"Score": "0",
"body": "@MathieuGuindon There are soooo many hidden nuggets in the `ADODB` library, but the keyword is hidden, ha! Thanks! The bitwise checks on the connection object will save you a lot of pain in the future. And, If that's the case with the UoW, then do you think it would be overkill to have a dedicated `UnitOfWorkFactory` with `Attribute VB_PredeclaredId = True`? Then you could set Predeclared Attribute to false in the `UnitOfWork` and move your instance check in to the `UnitOfWorkFactory`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T16:10:10.770",
"Id": "473045",
"Score": "1",
"body": "IDK about a `UnitOfWorkFactory` - if it's not warranted for testing, I tend to try to avoid adding a dedicated factory class, I mean, having the factory method consistently on the default instance makes a signal about how the API is consumed, creates expectations, and then breaks the *Principle Of Least Surprise* when the API goes astray and makes a class work differently like this. I'll add the missing guard clause and unit tests =)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T15:04:43.103",
"Id": "241076",
"ParentId": "241021",
"Score": "4"
}
},
{
"body": "<p>Comment on <code>Transaction DDL</code>. While <a href=\"https://docs.microsoft.com/en-us/sql/ado/reference/ado-api/begintrans-committrans-and-rollbacktrans-methods-ado?view=sql-server-ver15#connection\" rel=\"nofollow noreferrer\">Microsoft does state</a> that its presence indicates that the backend supports transactions, there is another <a href=\"https://docs.microsoft.com/en-us/previous-versions/windows/desktop/ms714932(v=vs.85)\" rel=\"nofollow noreferrer\">reference</a> (possibly outdated) discussing <code>DBPROP_SUPPORTEDTXNDDL</code> enum, where <code>DBPROPVAL_TC_NONE</code> value of <code>Transaction DDL</code> indicates that transactions are not supported.</p>\n<p>In fact, I have made a few test snippets for SecureADODB to be executed against a CSV and SQLite files via ADODB. For SQLite, <code>Transaction DDL</code> property is set to 8, whereas in case of CSV, which does not support transactions and throws an error if BeginTrans is attempted, <code>Transaction DDL</code> property is still present and is set to 0.</p>\n<p>The proposed Guard code should still work, as <code>SupportsTransactions</code> would be set to 0 and still evaluate to false.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-02T19:16:25.313",
"Id": "256632",
"ParentId": "241021",
"Score": "3"
}
},
{
"body": "<p>I have noticed this interface <code>IDbConnection_CreateCommand</code>, which appears to be an unnecessary coupling between <code>DbCommandBase</code> and <code>DbConnection</code>. <code>DbCommandBase</code> is injected with a <code>DbConnection</code> object:</p>\n<pre class=\"lang-vb prettyprint-override\"><code>Private Function IDbCommandBase_CreateCommand(ByVal db As IDbConnection, ByVal commandType As ADODB.CommandTypeEnum, ByVal sql As String, ByRef args() As Variant) As ADODB.Command\n Set IDbCommandBase_CreateCommand = CreateCommand(db, commandType, sql, args)\nEnd Function\n</code></pre>\n<p><code>ADODB.Connection</code> object, which is what <code>DbCommandBase</code> needs to complete setup of the underlying <code>ADODB.Command</code> object, is exposed via the <code>IDbConnection_AdoConnection</code> interface. So rather than using/keeping <code>IDbConnection_CreateCommand</code> interface called from <code>DbCommandBase</code>:</p>\n<pre class=\"lang-vb prettyprint-override\"><code>Private Function CreateCommand(ByVal db As IDbConnection, ByVal commandType As ADODB.CommandTypeEnum, ByVal sql As String, ByRef args() As Variant) As ADODB.Command\n Errors.GuardNullReference db\n Errors.GuardEmptyString sql\n Errors.GuardExpression db.State <> adStateOpen, message:="Connection is not open."\n Errors.GuardExpression Not ValidateOrdinalArguments(sql, args), message:="Arguments supplied are inconsistent with the provided command string parameters."\n\n Dim cmd As ADODB.Command\n Set cmd = db.CreateCommand(commandType, sql)\n</code></pre>\n<p>I would replace the last two lines with</p>\n<pre class=\"lang-vb prettyprint-override\"><code>Dim cmd As ADODB.Command\nSet cmd = New ADODB.Command\nSet cmd.ActiveConnection = db.AdoConnection\ncmd.commandType = commandType\ncmd.CommandText = sql\n</code></pre>\n<p>and removed <code>IDbConnection_CreateCommand</code> interface. Am I missing something?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T11:41:13.383",
"Id": "256714",
"ParentId": "241021",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T17:50:04.690",
"Id": "241021",
"Score": "11",
"Tags": [
"object-oriented",
"vba",
"unit-testing",
"rubberduck",
"adodb"
],
"Title": "Secure ADODB: Unit of Work"
}
|
241021
|
<p>I had to solve <a href="https://www.dyalog.com/uploads/files/student_competition/2019_problems_phase2.pdf#page=17" rel="nofollow noreferrer">three problems</a> on graph theory that I solved by implementing a utility function and 3 functions, one for each of the problems.</p>
<p>The problem set defines the input for all my functions as a <code>E+1 x 2</code> matrix (they call this an edge list) where the first row <code>V E</code> contains the number of vertices <code>V</code> in the graph and the number <code>E</code> of edges. The other <code>E</code> rows contain the endpoints of edges, so a row <code>a b</code> means there's an edge between vertices <code>a</code> and <code>b</code>.</p>
<ul>
<li><p><code>Degrees</code> is a function that retrieves the degree of a given vertex; e.g. <code>Graphs.Degrees 8 2 ⍴ 6 7 1 2 2 3 6 3 5 6 2 5 2 4 1 4</code> gives <code>2 4 2 2 2 2</code>;</p></li>
<li><p><code>DoubleDegrees</code> is a function that, given a vertex <code>v</code>, retrieves the sum of the degrees of the neighbours of <code>v</code> (i.e. the vertices connected to <code>v</code> by an edge); e.g. <code>Graphs.DoubleDegrees 5 2⍴ 5 4 1 2 2 3 4 3 2 4</code> gives <code>3 5 5 5 0</code>;</p></li>
<li><p><code>ConnectedComponents</code> is a function that counts the number of connected components in the graph; e.g. <code>Graphs.ConnectedComponents 14 2⍴12 13 1 2 1 5 5 9 5 10 9 10 3 4 3 7 3 8 4 8 7 11 8 11 11 12 8 12</code> gives <code>3</code>.</p></li>
</ul>
<p>The functions work as expected.</p>
<p>I'm particularly interested in feedback on the <code>AdjacencyMatrix</code> and on the <code>ConnectedComponents</code> functions. Also, I believe the <code>DoubleDegrees</code> and <code>ConnectedComponents</code> functions are sub-optimal since they use simple algorithms but make use of matrix multiplications and search algorithms would be faster (in other languages). Is this still efficient code for APL? Or would a search-based solution be more efficient?</p>
<pre><code>:Namespace Graphs
⍝ This particular namespace contains functions related to graphs.
⍝ For this namespace, an 'EdgeList' is a (v+1)×2 integer matrix, with v≥0, that encodes an undirected graph:
⍝ The first row (v e) is the number of vertices and edges in the graph;
⍝ The remaining e rows have two integers ≤v representing the end points of an edge.
AdjacencyMatrix ← {
⍝ Compute the adjacency matrix of a graph.
⍝ Monadic function expecting an 'EdgeList'.
vertices ← ⊃1↑⍵
edges ← (↓⌽⍪⊢) 1↓⍵
mat ← 0⍴⍨ 2⍴ vertices
(1@edges) mat
}
Degrees ← {
⍝ Compute the degree of a vertex of a graph.
⍝ Dyadic function expecting integer on the left and 'EdgeList' on the right.
⍝ If the left integer is missing, return the degrees of all vertices.
⍺ ← ⍬
adj ← AdjacencyMatrix ⍵
⍺⊃+/adj
}
DoubleDegrees ← {
⍝ Compute the double degree of a vertex of a graph.
⍝ Dyadic function expecting an integer on the left and 'EdgeList' on the right.
⍝ If the left integer is missing, return the double degrees of all vertices.
⍺ ← ⍬
adj ← AdjacencyMatrix ⍵
⍺⊃+/ +.×⍨ adj
}
ConnectedComponents ← {
⍝ Computes the number of connected components of a graph.
⍝ Monadic function expecting 'EdgeList' as argument.
adj ← AdjacencyMatrix ⍵
v ← ⊃⍴ adj
(1 1⍉adj) ← v⍴1 ⍝ Assign 1s to the main diagonal to accumulate all paths.
accum ← (+.×)⍣(v-1)⍨ adj
≢∪ (1@(≠∘0)) accum
}
:EndNamespace
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n <p>I believe the <code>DoubleDegrees</code> and <code>ConnectedComponents</code> functions are sub-optimal since they use simple algorithms but make use of matrix multiplications and search algorithms would be faster (in other languages). Is this still efficient code for APL? Or would a search-based solution be more efficient?</p>\n</blockquote>\n\n<p>Many APL implementations, especially Dyalog's, are heavily optimized around array operations using hardware SIMD instructions and parallel processing. Matrix multiplication is one of them.</p>\n\n<p>Classical algorithms say that matrix multiplication is heavy, and a search algorithm will definitely do better. However, the uniqueness of APL gives very low constant factor to matrix multiplication (possibly even cutting down a dimension with enough parallelism), while it likely gives a high cost to a recursive search (interpreting a function over and over, and digging through a nested array).</p>\n\n<p>In conclusion, I'd say matrix multiplication is the preferred way to solve such a task in APL. If in doubt, you can always implement both and compare the timings.</p>\n\n<blockquote>\n <p>I'm particularly interested in feedback on the <code>AdjacencyMatrix</code> and on the <code>ConnectedComponents</code> functions.</p>\n</blockquote>\n\n<h2><code>AdjacencyMatrix</code></h2>\n\n<pre><code>AdjacencyMatrix ← {\n ⍝ Compute the adjacency matrix of a graph.\n ⍝ Monadic function expecting an 'EdgeList'.\n\n vertices ← ⊃1↑⍵ ⍝ can be simplified to `vertices ← ⊃⍵`\n edges ← (↓⌽⍪⊢) 1↓⍵ ⍝ consider putting atop `↓` outside of the train\n ⍝ to clarify the intent:\n ⍝ edges ← ↓ (⌽⍪⊢) 1↓⍵\n mat ← 0⍴⍨ 2⍴ vertices\n (1@edges) mat ⍝ `1@edges⊢ mat` is more common way to split\n ⍝ right operand from right arg\n}\n</code></pre>\n\n<h2><code>ConnectedComponents</code></h2>\n\n<pre><code>ConnectedComponents ← {\n ⍝ Computes the number of connected components of a graph.\n ⍝ Monadic function expecting 'EdgeList' as argument.\n\n adj ← AdjacencyMatrix ⍵\n v ← ⊃⍴ adj ⍝ can be simplified to `v ← ≢adj`\n (1 1⍉adj) ← v⍴1 ⍝ can be simplified to `(1 1⍉adj) ← 1`\n accum ← (+.×)⍣(v-1)⍨ adj ⍝ more on two last lines below\n ≢∪ (1@(≠∘0)) accum\n}\n</code></pre>\n\n<p>Plain <span class=\"math-container\">\\$n\\$</span>th matrix power of an adjacency matrix <span class=\"math-container\">\\$M\\$</span> gives the <em>count</em> of all length-<span class=\"math-container\">\\$n\\$</span> paths between given two vertices. Adding the 1 to the diagonal of <span class=\"math-container\">\\$M\\$</span> has the effect of adding loops to the graph, and its power gives the count of all length-<span class=\"math-container\">\\$≤n\\$</span> paths. To describe the inner workings: For each pair of vertices <span class=\"math-container\">\\$(p, r)\\$</span>, <code>+.×</code> counts the paths <span class=\"math-container\">\\$p \\rightarrow q \\rightarrow r\\$</span> for every intermediate vertex <span class=\"math-container\">\\$q\\$</span> by multiplying <code>×</code> paths for <span class=\"math-container\">\\$p \\rightarrow q\\$</span> and <span class=\"math-container\">\\$q \\rightarrow r\\$</span>, and collects all of them by sum <code>+</code>.</p>\n\n<p>But right now we don't need the counts, we just need to know whether such a path <em>exists</em>. This gives rise to the Boolean matrix product <code>∨.∧</code>. Analogously to <code>+.×</code>, <code>∨.∧</code> checks if any path <span class=\"math-container\">\\$p \\rightarrow q \\rightarrow r\\$</span> <em>exists</em> by <code>∧</code>-ing <span class=\"math-container\">\\$p \\rightarrow q\\$</span> and <span class=\"math-container\">\\$q \\rightarrow r\\$</span>, and collects them by <code>∨</code> to indicate if <em>some</em> path exists. This has several benefits:</p>\n\n<ul>\n<li>Boolean arrays and operations on them are more time- and space-efficient over integer arrays.</li>\n<li>Finding all connected pairs is easier with the fixed point <code>⍣≡</code>, while it can't be done with <code>+.×</code>.</li>\n<li>You don't need an extra step (<code>1@(≠∘0)</code>, though it can be simplified to <code>0≠</code>or simply <code>×</code>) to extract the <em>exists</em> from the <em>counts</em>.</li>\n</ul>\n\n<p>Finally, if we change <code>∨.∧⍣≡⍨</code> to <code>∨.∧⍨⍣≡</code>, we double the number of steps instead of advancing only one step every iteration (thus reducing the number of matmul operation from <span class=\"math-container\">\\$O(n)\\$</span> to <span class=\"math-container\">\\$O(\\log{n})\\$</span>). If we were calculating precisely the <span class=\"math-container\">\\$n\\$</span>th power, we would need repeated squaring that refers to <span class=\"math-container\">\\$n\\$</span>'s bit pattern. We don't need to care about it because we'll be iterating until it converges anyway.</p>\n\n<p>Now the code looks like: (the variable <code>v</code> is removed since it is no longer used)</p>\n\n<pre><code>ConnectedComponents ← {\n adj ← AdjacencyMatrix ⍵\n (1 1⍉adj) ← 1\n accum ← ∨.∧⍨⍣≡ adj ⍝ (f.g)⍣≡⍨ is same as f.g⍣≡⍨ due to parsing rule\n ≢∪ accum\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T18:23:27.763",
"Id": "473301",
"Score": "0",
"body": "Really good review, overall. Thanks for it!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T01:48:25.563",
"Id": "241042",
"ParentId": "241024",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "241042",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T18:56:26.133",
"Id": "241024",
"Score": "3",
"Tags": [
"graph",
"matrix",
"apl"
],
"Title": "Implementing basic graph theory functions in APL with matrices"
}
|
241024
|
<h2>Some background</h2>
<p>Feel free to skip this if you're not interested.</p>
<p>There is a very popular bioinformatics program called <a href="http://www.htslib.org/doc/tabix.html" rel="nofollow noreferrer">tabix</a> that permits interval-based searches for genetic variants in VCF files. To list all variants from position 100000 to 150000 on chromosome 1, one would invoke <code>tabix db.vcf chr1:100000-150000</code>.</p>
<p>I created a program named <a href="https://github.com/bioforensics/rsidx" rel="nofollow noreferrer">rsidx</a> that permits similar queries, but using variant identifiers (rsIDs) instead of chromosome coordinates. <code>rsidx index</code> creates an index, and <code>rsidx search</code> performs the search. Under the hood, <code>rsidx index</code> simply creates an SQLite database with a mapping of rsIDs to chromosome coordinates. Once the index is constructed, <code>rsidx search</code> returns the coordinates associated with a variant, and then uses tabix to retrieve the variant at that coordinate.</p>
<h2>The code</h2>
<p>The following code is used to populate an SQLite database, mapping each rsID to a chromosome coordinate. <code>vcfstream</code> is a generator that scans an input file and retrieves the relevant data to populate the database.</p>
<p>The full code is <a href="https://github.com/bioforensics/rsidx/blob/385e8287538fd2360f4898622a7b22a1737fa76a/rsidx/index.py#L33-L49" rel="nofollow noreferrer">here</a>.</p>
<pre class="lang-py prettyprint-override"><code>def index(dbconn, vcffh, cache_size=None, mmap_size=None, logint=1e6):
c = dbconn.cursor()
c.execute(
'CREATE TABLE rsid_to_coord ('
'rsid INTEGER PRIMARY KEY, '
'chrom TEXT NULL DEFAULT NULL, '
'coord INTEGER NOT NULL DEFAULT 0)'
)
if cache_size:
c.execute('PRAGMA cache_size = -{:d}'.format(cache_size))
if mmap_size:
c.execute('PRAGMA mmap_size = {:d}'.format(mmap_size)) # bytes
dbconn.commit()
vcfstream = parse_vcf(vcffh, updateint=logint)
c.executemany('INSERT OR IGNORE INTO rsid_to_coord VALUES (?,?,?)', vcfstream)
dbconn.commit()
</code></pre>
<h2>The problem</h2>
<p>Often, the input files contain hundreds of millions of records. Obviously I expect it to take some time to populate the database, but sometimes the performance seems extremely slow. I've done a lot of searching found several recommendations for improving the performance of insert-intensive tasks.</p>
<ul>
<li>increasing the cache size</li>
<li>increasing the mmap size</li>
<li>disabling syncs (<code>c.execute('PRAGMA synchronous = 0')</code>)</li>
<li>enabling write-ahead logging (<code>c.execute('PRAGMA journal_mode = wal')</code>)</li>
<li>wrapping the inserts in <code>BEGIN TRANSACTION;</code> and <code>COMMIT;</code></li>
</ul>
<p>I've tried several combinations of these recommendations, but they don't seem to have much effect on overall performance. <strong>Should I chalk this up to the size of the input, or is there something I'm missing here that can substantially improve performance?</strong></p>
<h2>Example</h2>
<p>If you're looking for a real-world example to test on, you can try this.</p>
<pre><code>pip install git+https://github.com/bioforensics/rsidx
wget -O dbSNP.vcf.gz https://ftp.ncbi.nlm.nih.gov/snp/organisms/human_9606_b151_GRCh37p13/VCF/All_20180418.vcf.gz
rsidx index dbSNP.vcf.gz dbSNP.rsidx
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T22:07:42.290",
"Id": "472946",
"Score": "0",
"body": "I have a number of questions about your code at a higher level. What's an Rsid, and why might they be duplicated? Also, why can multiple rsids live at the same chromosome/position? What are the chances of this kind of duplication occurring?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T00:58:45.373",
"Id": "472956",
"Score": "0",
"body": "An rsID is intended to be a unique identifier for a genetic variant. Due to a variety of historical/technical/practical reasons, sometimes the record for a particular variant will have multiple rsIDs assigned, separated by semicolons. Although forbidden by the VCF specification, sometimes it's difficult to represent a genetic variant in a single record, and thus a variant and its rsID will appear in multiple records. This typically doesn't lead to any problems for rsidx, since the duplicated records all have the same coordinate on the chromosome."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T01:46:38.103",
"Id": "472962",
"Score": "0",
"body": "What happens if you open a database in `\":memory:\"` instead of a file? Does the speed improve any? (IOW: is the problem IO-related?)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T20:05:59.897",
"Id": "241026",
"Score": "4",
"Tags": [
"python",
"sqlite",
"bioinformatics"
],
"Title": "Optimizing hundreds of millions of SQLite database inserts in Python"
}
|
241026
|
<p>I've got a task to create a readline() function that would have the exact same behavior as read():</p>
<p><strong>ssize_t read(int fd, void *buf, size_t count);</strong> <em>(man read)</em></p>
<p>So it should return -1 on error and number of bytes read on success.
Also, if the function receives a string with multiple \n chars, it should return only the first line and store the rest for a future use. </p>
<p>I was scrolling through this article:
<a href="https://codereview.stackexchange.com/questions/135133/reading-a-line-ending-with-a-newline-character-from-a-file-descriptor">Reading a line ending with a newline character from a file descriptor</a></p>
<p>But I do not think the author had the same purpose - that is to work just as read()</p>
<p>I came up with this function:</p>
<pre><code>//global buffer
char gBUF[BUFSIZ];
int readline2(int fd, char* buf){
static char* resultBuffer = gBUF;
int ret, mv;
char temp[256];
char* t;
bzero(temp, sizeof(temp));
t = strchr(resultBuffer,'\n');
if(t != NULL){
mv = t-resultBuffer+1;
strncpy(temp,resultBuffer, mv);
resultBuffer = resultBuffer + mv;
temp[strlen(temp)] = '\0';
strcpy(buf,temp);
bzero(temp, sizeof(temp));
ret = read(fd,&temp,256);
temp[ret]='\0';
strcat(resultBuffer,temp);
return mv;
}
ret = read(fd,&temp,256);
temp[ret]='\0';
t = strchr(temp,'\n');
mv = t-temp+1;
strncpy(buf,temp,mv);
strcat(resultBuffer,temp+mv);
return ret;
}
</code></pre>
<p>and I mean, it works well, although I had some real struggles with pointers and copying addresses instead of values. </p>
<p>My question is, how to improve this? I still have a feeling there's something missing or that something could significantly improve it. </p>
<p>I guess I should put a while inside and check whether the read string actually has a \n char and only return when it does, right? </p>
<p>I also do not like the idea of a global buffer, maybe I should just create a class/struct, something like this: </p>
<pre><code>struct {
char BUF[BUFSIZ];
char *p = BUF;
}dataStruct;
</code></pre>
<p>to store the buffer and a pointer to it, but I do not really know how I could use that properly</p>
<p>Thanks for any suggestions!</p>
<p>Reading max 256bytes is a purpose, that should be the max;</p>
<p>I could've probably added that this function is to be used after in a multiprocess/multithread client server project.
The server reads these lines from clients and should know what input came first, in what order the lines came, etc. The buffer should essentially work as a queue.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T20:14:23.183",
"Id": "472922",
"Score": "1",
"body": "`t` in `mv = t-temp+1;` is not initialized. UB it is. What is the purpose of this line anyway?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T20:33:08.513",
"Id": "472923",
"Score": "0",
"body": "_return only the first line and store the rest for a future use_ - Can you expand on this? Do you mean that the function is holding a cache and so the number of file reads will potentially be less than the number of function calls?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T20:34:42.300",
"Id": "472924",
"Score": "0",
"body": "@vnp it was actually just a mistake, the line shouldn't have been there"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T20:38:05.047",
"Id": "472926",
"Score": "0",
"body": "@Reinderien Yes, exactly. Let's say I read a string containing two \\n chars. Then only the text till the first one should be returned, the rest is stored to a buffer.\nWhen the call comes again, it returns what's inside the buffer first, before taking care of another input string."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T20:46:06.337",
"Id": "472927",
"Score": "0",
"body": "Added some more info into the edit"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T20:56:36.457",
"Id": "472929",
"Score": "2",
"body": "So why not just use [fgets](https://linux.die.net/man/3/fgets)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T20:59:02.867",
"Id": "472930",
"Score": "0",
"body": "And if you insist on implementing this yourself: what happens when it's called with a partially populated buffer from one file descriptor and a request for data with a second file descriptor?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T20:59:16.033",
"Id": "472931",
"Score": "0",
"body": "@FoggyDay I thought that fgets works only with files, not file descriptors. Correct me if I'm wrong"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T21:00:56.067",
"Id": "472932",
"Score": "0",
"body": "`fdopen` provides you with a file pointer from a descriptor."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T21:01:20.740",
"Id": "472933",
"Score": "0",
"body": "@Reinderien This is one of the things I came accross as well. My idea was to use the struct for that - I could have 3 structures with buffer and pointer, each used for different file descriptor"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T21:03:36.970",
"Id": "472934",
"Score": "0",
"body": "So.. a maximum of three concurrent files? What if a fourth is attempted?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T21:07:04.113",
"Id": "472936",
"Score": "0",
"body": "@Reinderien I agree, there can be more but I do not really know how to work with that. Should I just create a new buffer for each new FD taken as a parameter into the function - and check if one for that specific FD already exists?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T21:08:34.153",
"Id": "472937",
"Score": "0",
"body": "More to the point: are you married to the idea of doing this yourself, or are you OK with replacing the works with `fdopen`/`fgets`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T21:09:32.263",
"Id": "472938",
"Score": "0",
"body": "I'm absolutely open to ideas, I did not know about fdopen so I decided not to use fgets."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T21:21:22.617",
"Id": "472940",
"Score": "0",
"body": "@Reinderien forgot to tag you my bad. If fgets is a better option, I'm down to use it. What exactly I could use it for? instead of read, and after that?"
}
] |
[
{
"body": "<p>As we've basically worked out in the comments: when there's already a thing, use the thing. To get a line from a file descriptor, you can</p>\n\n<ol>\n<li>Call <a href=\"https://linux.die.net/man/3/fdopen\" rel=\"noreferrer\">fdopen</a> on your file descriptor to get a <code>FILE*</code></li>\n<li>Check for <code>NULL</code>, <code>perror</code> and <code>exit</code> if necessary</li>\n<li>Call <a href=\"https://linux.die.net/man/3/fgets\" rel=\"noreferrer\">fgets</a></li>\n<li>Check for <code>NULL</code> again</li>\n<li>Repeat 3-4 as necessary</li>\n<li><a href=\"https://linux.die.net/man/3/fclose\" rel=\"noreferrer\"><code>fclose</code></a> your <code>FILE*</code></li>\n<li>Do <em>not</em> call <code>close</code> on your file descriptor</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T08:13:05.610",
"Id": "472992",
"Score": "1",
"body": "This is probably good advice *in practice* — but then, you’d just use the existing `read` function in practice. In OP’s case this probably defeats the purpose of the exercise, which is to solve this using POSIX file operations without calling into libc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T16:53:37.503",
"Id": "473046",
"Score": "0",
"body": "Thanks @Reinderien I will try to work with this, thanks a lot for your suggestion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T16:53:53.223",
"Id": "473047",
"Score": "0",
"body": "In item 2, shouldn't `if necessary` be `as necessary`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T16:56:03.093",
"Id": "473048",
"Score": "0",
"body": "Uh. Not really? What issue do you see with the current wording?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T21:47:21.570",
"Id": "241033",
"ParentId": "241027",
"Score": "6"
}
},
{
"body": "<p>You've got a bit of a nightmare of lengths. You should be using explicit lengths for everything, and to heck with NUL termination. </p>\n\n<p>Lets look at some cases:</p>\n\n<pre><code> ret = read(fd,&temp,256);\n temp[ret]='\\0';\n</code></pre>\n\n<p>Well, <code>temp</code> is of size 256. (And you should write <code>sizeof(temp)</code> instead of <code>256</code>.) This means, if you read 256 bytes, you write a null into the 257th byte in the buffer, and smash memory.</p>\n\n<pre><code> temp[strlen(temp)] = '\\0';\n</code></pre>\n\n<p>This finds the first NUL in temp, by offset, and then overwrites it with a NUL. A useless statement. And you should instead know how many bytes you have in temp.\nThen use memchr instead of strchr, memcpy instead of strcpy and strcat, etc...</p>\n\n<pre><code> int readline2(int fd, char* buf){\n</code></pre>\n\n<p>This is trying to reproduce the prototype of read(), but you forgot the buffer length altogether. This makes your function more comparable to gets() then fgets(). gets() is one of the large security holes in C. Don't be like gets().</p>\n\n<p>Edit:\nOne more thing.\nIf you pass in an fd for a terminal, and it is in raw mode, you might get just a couple characters, not a complete line.\nThis is sometimes known as a \"short read\".\nYou need to keep reading until you get a line.\nFor testing, this can be easily simulated by reading only a few bytes at a time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T16:59:02.747",
"Id": "473049",
"Score": "0",
"body": "Thanks a lot for your input @David Thanks for correcting me on the sizeof. \nI mean, i used memcpy instead of strcpy before as I was testing out the solutions, to copy the contents of temp to the actuall buffer to then be read by the function. \nBut that copied the memory address instead of the value so once the function ended, the buffer then pointed to an empty string. That is why I used strcpy for that. \n\nYou are correct that I should then specify the number of chars read, but I guess I could keep it like that since the usage of it afterwards is rather simple. Thanks a lot anyway!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T01:32:07.867",
"Id": "241040",
"ParentId": "241027",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "15",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T20:06:53.783",
"Id": "241027",
"Score": "5",
"Tags": [
"c"
],
"Title": "Creating readline() function, reading from a file descriptor"
}
|
241027
|
<p>I faced a series of problems when unit testing a tool of mine that generates files. They were caused by me putting the files in the same temporary folder and the tests running in parrallel.</p>
<p>Here is an exemple of the unit tests (for @shanif)</p>
<pre><code>public class OutputWriterTests
{
[Fact]
public async Task WriteToDirectoryAsync()
{
using var tempFolder = new TempFolder();
var fileWriter = new OutputWriter(tempFolder.Folder);
var fileCount = tempFolder.Folder.GetFiles().Length;
await fileWriter.WriteAsync("toto").ConfigureAwait(false);
Assert.Equal(fileCount + 1, tempFolder.Folder.GetFiles().Length);
}
[Fact]
public async Task AppendToFileAsync()
{
using var tempFolder = new TempFolder();
var testFile = new FileInfo(Path.Combine(tempFolder.Folder.FullName, "test"));
var fileWriter = new OutputWriter(testFile);
await fileWriter.WriteAsync("toto").ConfigureAwait(false);
var text = File.ReadAllText(testFile.FullName);
Assert.Equal("toto\r\n", text);
}
}
</code></pre>
<p>As a result I created this simplistic class that handles the creation and deletion of a temporary folder. As it implements IDisposable it's meant to be used inside a using block, or manually disposed.</p>
<pre><code>public class TempFolder : IDisposable
{
public DirectoryInfo Folder;
public TempFolder(string prefix = "TempFolder")
{
var folderName = prefix + new Random().Next(1000000000);
Folder = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), folderName));
}
public void Dispose()
{
Directory.Delete(Folder.FullName, true);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T06:30:41.250",
"Id": "472982",
"Score": "0",
"body": "[Here's](https://stackoverflow.com/questions/278439/creating-a-temporary-directory-in-windows) some alternatives to your approach. It really made me wonder that windows has no alternative to `mkdtemp`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T11:47:21.240",
"Id": "473013",
"Score": "0",
"body": "I wonder if you can avoid this problem by changing the unit tests. I would not call a test that create file a unit test, more like an integration test Would you like to post here one of the tests?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T11:49:44.103",
"Id": "473014",
"Score": "0",
"body": "Maybe this will help https://stackoverflow.com/q/1087351/1723352"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T17:29:41.910",
"Id": "473180",
"Score": "0",
"body": "@shanif I added a test"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-27T20:18:35.993",
"Id": "520247",
"Score": "0",
"body": "It's also worth considering using Path.GetTempPath() instead of generating your own random folder name."
}
] |
[
{
"body": "<p>You could easily wind up with collisions on the folder name if the method is called multiple times in very quick succession because of the <code>new Random()</code> being declared for each usage. It should be instantiated once, and since you mentioned it could be called on multiple threads, it should be mutexed onto one at a time. Finally, <a href=\"https://stackoverflow.com/a/3182664/3312\">it's not a good idea</a> to have fields be <code>public</code> - making it a property is luckily pretty easy. So:</p>\n\n<pre><code>public class TempFolder : IDisposable\n{\n private static readonly Random _Random = new Random();\n\n public DirectoryInfo Folder { get; }\n\n public TempFolder(string prefix = \"TempFolder\")\n {\n string folderName;\n\n lock (_Random)\n {\n folderName = prefix + _Random.Next(1000000000);\n }\n\n Folder = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), folderName));\n }\n\n public void Dispose()\n {\n Directory.Delete(Folder.FullName, true);\n }\n}\n</code></pre>\n\n<p>Now, what I don't address here is the issue of constructors or the <code>Dispose()</code> method possibly throwing unexpected exceptions. Just know that's a possibility and you may want to catch them and/or re-raise them depending on your use case.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T21:21:09.407",
"Id": "241031",
"ParentId": "241029",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "241031",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T20:10:57.410",
"Id": "241029",
"Score": "4",
"Tags": [
"c#",
"file-system",
".net-core"
],
"Title": "Random temp folder implementation for unit testing"
}
|
241029
|
<p>This is my first Web Scraping project in which I am retrieving the current stock information from <a href="https://www.tradingview.com/markets/stocks-usa/market-movers-large-cap" rel="nofollow noreferrer">here</a>. This program works as expected, but I would certainly think someone with more experience with the language and web scraping could improve it.</p>
<pre><code>#Imports
from bs4 import BeautifulSoup
from colorama import Fore as F
from time import sleep
import requests
import webbrowser
import pandas
import functools
import subprocess
from os import system
import geoip2.database
#Uses Maxmind GeoLite2-City Database for IP Location
#Compatible with most *nix systems only. Please leave feedback if compatability for Windows is wanted.
#Should I make a function to check internet connection or just let an error arise?
#Beginning of program messages
print("""
\033[32m /<span class="math-container">$$$$</span><span class="math-container">$$
/$$</span>__ <span class="math-container">$$
| $$</span> \__/
| <span class="math-container">$$$$</span><span class="math-container">$$ \033[34m_____ ______
\033[32m\____ $$</span>\033[34m__ /________________ /_________
\033[32m/<span class="math-container">$$ \ $$</span>\033[34m_ __/ __ \_ __ \_ //_/_ ___/
\033[32m| <span class="math-container">$$$$</span>$$/\033[34m/ /_ / /_/ / / / / ,< _(__ )
\033[32m\______/ \033[34m\__/ \____//_/ /_//_/|_| /____/
""")
print(F.BLUE + "[!]Enlarge window as much as possible for easier observations" + F.RESET)
sleep(2)
#subprocess.run("clear")
#Variables
stock_chart = {"Value": False, "Data": False}
#Functions
def internet_test():
proc = subprocess.Popen("ping google.com",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True,
universal_newlines=True)
if proc.returncode == 0:
return True
return False
def display(df):
formatters = {}
for li in list(df.columns):
max = df[li].str.len().max()
form = "{{:<{}s}}".format(max)
formatters[li] = functools.partial(str.format, form)
print(F.LIGHTGREEN_EX + df.to_string(formatters=formatters,
index=False,
justify="left"))
def search_df(search_str: str, df: pandas.DataFrame) -> pandas.DataFrame:
results = pandas.concat([df[df["Symbol"].str.contains(search_str.upper())], df[df["Company"].str.contains(search_str,case=False)]])
return results
#Function for fetching stocks, returns pandas.DataFrame object containing stock info
#Stocks pulled from https://www.tradingview.com/markets/stocks-usa/market-movers-large-cap
def stocks():
#Set pandas options
pandas.set_option("display.max_rows", 1000)
pandas.set_option("display.max_columns", 1000)
pandas.set_option("display.width", 1000)
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"
" Chrome/80.0.3987.149 Safari/537.36"}
#Make Request to site
site = requests.get("https://www.tradingview.com/markets/stocks-usa/market-movers-large-cap", headers)
#BeautifulSoup Object
soup = BeautifulSoup(site.content, "html.parser")
#Process to go achieve a list of stocks !!!SUGGESTIONS FOR EFICIENCY!!!
html = list(soup.children)[3]
body = list(html.children)[3]
div = list(body.children)[5]
div2 = list(div.children)[9]
div3 = list(div2.children)[1]
div4 = list(div3.children)[3]
div5 = list(div4.children)[1]
div6 = list(div5.children)[3]
div7 = list(div6.children)[3]
div8 = list(div7.children)[1]
table = list(div8.children)[1]
tbody = list(table.children)[3]
stocks = tbody.find_all("tr")
chart = {"Symbol": [], "Company": [], "Price Per Share": [], "Change(%)": [], "Change(Points)": []}
#Find each component of stock and put it into a chart
for stock in stocks:
symbol = list(stock.find("td").find("div").find("div"))[1].get_text()
name = stock.find("td").find("div").find("div").find("span").get_text().strip()
last_price = "$" + stock.find_all("td")[1].get_text()
change_percent = stock.find_all("td")[2].get_text()
change_points = stock.find_all("td")[3].get_text()
chart["Symbol"].append(symbol)
chart["Company"].append(name)
chart["Price Per Share"].append(last_price)
chart["Change(%)"].append(change_percent)
chart["Change(Points)"].append(change_points)
panda_chart = pandas.DataFrame(chart)
return panda_chart
def ip_info(ip):
print(F.YELLOW + "[!]IP information is approximate. Please use IPv6 for more accurate results.")
try:
reader = geoip2.database.Reader("GeoLite2-City.mmdb")
print(F.GREEN + "[√]Database Loaded")
except FileNotFoundError:
print(F.RED + "[!]Could not open database; Exiting application")
exit(1)
#subprocess.run("clear")
response = reader.city(ip)
print(F.LIGHTBLUE_EX + """
ISO Code: {iso}
Country Name: {country}
State: {state}
City: {city}
Postal Code: {post}
Latitude: {lat}
Longitude: {long}
Network: {net}""".format(iso=response.country.iso_code, country=response.country.name,
state=response.subdivisions.most_specific.name, city=response.city.name,
post=response.postal.code, lat=response.location.latitude, long=response.location.longitude,
net=response.traits.network))
print("\n\nEnter \"q\" to go back to menu or \"op\" to open predicted location in Google Maps.", end="\n\n\n\n\n\n")
while True:
inp = input()
if inp == "q":
break
elif inp == "op":
webbrowser.open(f"https://www.google.com/maps/search/{response.location.latitude},{response.location.longitude}", new=0)
break
#Main
def main():
try:
global stock_chart
internet = internet_test()
print("""\033[33mOptions:
\033[94m[1] - Display a chart of popular stocks
[2] - Search a chart of popular stocks
[3] - Locate an Internet Protocol (IP) Address
""")
while True:
choice = input(F.YELLOW + "Enter Option Number[1-3]> " + F.WHITE)
if choice in ["1", "2", "3"]:
break
print(F.RED + "[!]Option invalid")
if choice in ["1", "2"]:
if not stock_chart["Value"]:
stock_chart["Value"] = True
stock_chart["Data"] = stocks()
if choice == "1":
display(stock_chart["Data"])
else:
search = input(F.LIGHTBLUE_EX + "Enter name to search for> ")
display(search_df(search, stock_chart["Data"]))
sleep(1)
else:
ip_addr = input(F.GREEN + "Enter an Internet Protocol (IP) Address[IPv4 or IPv6]> ")
try:
ip_info(ip_addr)
except ValueError:
print(F.RED + "IP Address invalid")
sleep(1)
main()
except KeyboardInterrupt:
print(F.RED + "[!]Exiting..." + F.RESET)
if __name__ == "__main__":
main()
</code></pre>
|
[] |
[
{
"body": "<h2>Treating users like adults</h2>\n\n<p>This is personal opinion, but</p>\n\n<blockquote>\n <p>[!]Enlarge window as much as possible for easier observations</p>\n</blockquote>\n\n<p>is the kind of thing that I'm sure users can figure out, and is better left unstated.</p>\n\n<h2>Artificial hangs</h2>\n\n<p>This kind of sleep:</p>\n\n<pre><code>sleep(2)\n</code></pre>\n\n<p>after a prompt is not what I consider good user interface design. It's halfway between 'press any key to continue', which can be useful if the user needs to pause and look at stuff; and to simply not sleep and get on with life. In this case I think the latter is more appropriate.</p>\n\n<h2>Internet test</h2>\n\n<p>It doesn't appear that this is actually used for anything. Why is it here? You say</p>\n\n<blockquote>\n <p>I forgot to incorporate the internet test into the main function</p>\n</blockquote>\n\n<p>but I'm not convinced that it should be incorporated, or exist at all. The standard thing for a script like this is to assume that the internet is accessible, and if network calls fail, error or retry as appropriate.</p>\n\n<p>Even if you did want to test within the program that the network is available, there is a better thing to do - try a connection to <code>tradingview.com</code>. It's what you actually care about.</p>\n\n<h2>Expression complexity</h2>\n\n<pre><code> results = pandas.concat([df[df[\"Symbol\"].str.contains(search_str.upper())], df[df[\"Company\"].str.contains(search_str,case=False)]])\n</code></pre>\n\n<p>should be broken up onto multiple lines.</p>\n\n<h2>Iterating over a list</h2>\n\n<p>Why is this:</p>\n\n<pre><code>for li in list(df.columns):\n</code></pre>\n\n<p>cast to a list? You can probably just iterate over <code>columns</code> directly.</p>\n\n<h2>Shadowing</h2>\n\n<p>In this:</p>\n\n<pre><code> max = df[li].str.len().max()\n</code></pre>\n\n<p>do not name a variable <code>max</code>, since there is already a built-in with the same name.</p>\n\n<h2>Element selection</h2>\n\n<p>It's very doubtful that this:</p>\n\n<pre><code>html = list(soup.children)[3]\nbody = list(html.children)[3]\ndiv = list(body.children)[5]\n</code></pre>\n\n<p>(etc.) is the best way to select these elements. Go back through the webpage and identify, based on the attributes of the elements and the structure of the DOM, the most specific and simple way to identify what you need. For example, the collection of <code>tr</code> for the main table can be accessed via the CSS selector</p>\n\n<pre><code>#js-screener-container tbody > tr\n</code></pre>\n\n<p>This, and this alone, should be enough to select all of the <code>tr</code> that you're interested in if you pass it to <code>soup.select</code>.</p>\n\n<p>You'll want to similarly reduce your other selected elements to use more meaningful paths through the DOM.</p>\n\n<h2>String interpolation</h2>\n\n<p>It can simplify your <code>format</code> call here; note the leading <code>f</code>:</p>\n\n<pre><code>f\"\"\"\n ISO Code: {response.country.iso_code}\n Country Name: {response.country.name}\n etc\n\"\"\"\n</code></pre>\n\n<h2>Set membership</h2>\n\n<pre><code>if choice in [\"1\", \"2\", \"3\"]\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>if choice in {\"1\", \"2\", \"3\"}\n</code></pre>\n\n<p>It's technically higher-performance although you certainly won't see a difference. Also it captures your meaning better: \"If the choice is in this set of things, where the order doesn't matter\".</p>\n\n<h2>IP?</h2>\n\n<p>What is this program actually doing, other than looking up stocks? Why is there an <code>ip_info</code> feature? This seems like it has absolutely nothing to do with stocks and should be a separate script.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T01:25:35.277",
"Id": "472958",
"Score": "0",
"body": "Alright thank you for the feedback and I forgot to incorporate the internet test into the main function. Other than that is the internet test logic correct?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T01:28:00.617",
"Id": "472960",
"Score": "0",
"body": "Also could you suggest a module to use for the \"press any key to continue\" function because most I find require the user to be a system administrator."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T19:04:55.350",
"Id": "474850",
"Score": "0",
"body": "The IP thing was just for fun to make it locate IP's as well. This wasn't a really big or serious project, it was just practicing web scraping and it was fun to implement the IP locating function."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T22:11:22.847",
"Id": "241034",
"ParentId": "241030",
"Score": "2"
}
},
{
"body": "<p>I am bit short on time so I apologize for not doing a more comprehensive review of your code. But I think one area where you can improve is utilization of BeautifulSoup.</p>\n\n<p>The selection method is clusmy, and you are addressing tags that are of no use to you. You can go straight to the DOM elements that matter to you and ignore the rest.</p>\n\n<p>The only trick is finding the right selectors for the page. Here is some code to parse the main table:</p>\n\n<pre><code>stock_table = soup.find(\"tbody\", {\"class\":\"tv-data-table__tbody\"})\nrows = stock_table.findAll(lambda tag: tag.name=='tr')\nfor row in rows:\n symbol_tag = row.find(\"a\", {\"class\": \"tv-screener__symbol\"})\n if symbol_tag is None:\n symbol = \"Not found\"\n else:\n symbol = symbol_tag.get_text().strip()\n\n company_tag = row.find(\"span\", {\"class\": \"tv-screener__description\"})\n if company_tag is None:\n company_name = \"Not found\"\n else:\n company_name = company_tag.get_text().strip()\n\n print(f\"symbol: {symbol}, company name: {company_name}\")\n</code></pre>\n\n<p>Output:</p>\n\n<pre>\nsymbol: MSFT, company name: Microsoft Corp.\nsymbol: AAPL, company name: Apple Inc\nsymbol: AMZN, company name: AMAZON COM INC\nsymbol: GOOG, company name: Alphabet Inc (Google) Class C\nsymbol: GOOGL, company name: Alphabet Inc (Google) Class A\nsymbol: BABA, company name: Alibaba Group Holdings Ltd.\nsymbol: FB, company name: FACEBOOK INC\nsymbol: BRK.A, company name: BERKSHIRE HATHAWAY INC\n...\n</pre>\n\n<p>I think you can easily complete the rest. Note that in this code I am skipping the headers because I selected <code>tbody</code> instead of <code>table</code>. Otherwise the first row would return <code>None</code> upon <code>find</code>, but I am handling the case as you can see.</p>\n\n<p>What would be good is handle exceptions, and also if a tag is not found don't ignore the error but investigate and fix your code to make it more reliable. The HTML of that page will certainly change at some point and you should watch out for changes.</p>\n\n<p>Since you use both <code>find</code> and <code>find_all</code>, keep in mind that they behave differently:</p>\n\n<blockquote>\n <p>If <code>find_all()</code> can’t find anything, it returns an empty list. If <code>find()</code>\n can’t find anything, it returns None</p>\n</blockquote>\n\n<p>Source: <a href=\"https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find\" rel=\"nofollow noreferrer\">BS4 doc</a></p>\n\n<p><code>find</code> should be used when you are expecting to find only one matching element, not <code>find_all</code>.</p>\n\n<p>FYI <strong>Pandas can also load HTML tables</strong>, just this line of code will give you something:</p>\n\n<pre><code>pandas.read_html(url)\n</code></pre>\n\n<pre>\n[ Unnamed: 0 Unnamed: 1 Unnamed: 2 Unnamed: 3 Unnamed: 4 Unnamed: 5 Unnamed: 6 Unnamed: 7 Unnamed: 8 Unnamed: 9 Unnamed: 10\n0 MSFT Microsoft Corp. 174.78 0.73% 1.26 Strong Buy 7.936M 1328.701B 29.21 5.80 144000.00 Technology Services\n1 AAPL Apple Inc 280.77 1.69% 4.67 Buy 8.914M 1229.641B 21.20 12.75 137000.00 Electronic Technology\n2 AMZN AMAZON COM INC 2409.76 1.96% 46.27 Buy 1.602M 1202.053B 101.14 23.48 798000.00 Retail Trade\n3 GOOG Alphabet Inc (Google) Class C 1286.47 1.84% 23.26 Strong Buy 343.776K 884.984B 24.73 49.61 118899.00 Technology Services\n4 GOOGL Alphabet Inc (Google) Class A 1281.35 1.82% 22.94 Strong Buy 479.905K 880.654B 24.65 49.61 118899.00 Technology Services\n.. ... ... ... ... ... ... ... ... ... ... ...\n95 BDXA BECTON DICKINSON & CO DEP SHS REPSTG 1/2... 63.21 0.32% 0.20 Strong Buy 25.530K 72.338B 22.20 2.76 70093.00 Health Technology\n96 SHOP SHOPIFY INC 621.56 -0.80% -5.00 Buy 1.448M 72.324B — -1.11 — Retail Trade\n97 MO ALTRIA GROUP INC 38.59 2.06% 0.78 Sell 1.394M 71.761B — -0.70 7300.00 Consumer Non-Durables\n98 VRTX VERTEX PHARMACEUTICAL 276.21 2.54% 6.84 Strong Buy 371.397K 71.657B 58.33 4.58 3000.00 Health Technology\n99 RDS.A ROYAL DUTCH SHELL ADR EA REP 2 CL'A' EU... 35.89 2.95% 1.03 Buy 2.025M 71.269B 8.44 3.93 — Energy Minerals\n\n[100 rows x 11 columns]]\n</pre>\n\n<p>But since some cleanup is required (parsing a & span tags) you might want to stick with BS (personally I would).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T19:00:20.897",
"Id": "474844",
"Score": "0",
"body": "Thank you for the BS help as it was troubling for me to find examples that I could use"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T19:34:10.760",
"Id": "474854",
"Score": "0",
"body": "Also what is the lambda function doing in `stock_table.findAlll"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-08T20:47:09.123",
"Id": "474861",
"Score": "0",
"body": "If you are not familiar with lambda functions in Python here is an intro: [Lambda functions](https://campus.datacamp.com/courses/cleaning-data-in-python/cleaning-data-for-analysis?ex=10). Think of it as a shortcut method when you want to write an inline function without fully defining it using `def`. I could have written `findAll('tr')` simply. On [this page](https://www.crummy.com/software/BeautifulSoup/bs3/documentation.html) you will find some examples of `findAll` used in conjunction with `lambda`, that will better show how lambda can be used to write succinct code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T01:53:27.137",
"Id": "474879",
"Score": "0",
"body": "Alright thank you for the references, I was thinking that `findAll('tr')` would work, but I wasn't for sure."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T15:25:05.443",
"Id": "241077",
"ParentId": "241030",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-22T20:42:29.857",
"Id": "241030",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"beautifulsoup"
],
"Title": "First Python Web Scraping Project with BeautifulSoup"
}
|
241030
|
<p>I have a function in JavaScript that converts a string value to title case using <a href="https://en.wikipedia.org/wiki/APA_style" rel="nofollow noreferrer">APA</a> style:</p>
<pre><code>function titleCase(str, options) {
const stopwords = 'a an and at but by for in nor of on or so the to up yet'
const defaults = stopwords.split(' ')
const opts = options || {}
if (!str) return ''
const stop = opts.stopwords || defaults
const keep = opts.keepSpaces
const splitter = /(\s+|[-‑–—])/
return str
.split(splitter)
.map((word, index, all) => {
if (word.match(/\s+/)) return keep ? word : ' '
if (word.match(splitter)) return word
if (
index !== 0 &&
index !== all.length - 1 &&
stop.includes(word.toLowerCase())
) {
return word.toLowerCase()
}
return capitalize(word)
})
.join('')
}
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1)
}
</code></pre>
<p><a href="https://github.com/words/ap-style-title-case/blob/master/index.js" rel="nofollow noreferrer">Credits of above JS functions</a></p>
<p>I converted the above to PHP:</p>
<pre><code>function APATitle($title, $keepSpaces = false, $stopWords = array())
{
if (!is_string($title)) {
return false;
}
if (!is_array($stopWords) || count($stopWords) < 1) {
$stopWords = array('a', 'an', 'and', 'at', 'but', 'by', 'for', 'in', 'nor', 'of', 'on', 'or', 'so', 'the', 'to', 'up', 'yet'); //Must all be lowercase!
}
$regexWordSplit = '/(\s+|[-‑–—])/';
$words = preg_split($regexWordSplit, $title, -1, PREG_SPLIT_DELIM_CAPTURE);
foreach ($words as $i => $currWord) {
if (preg_match('/\s+/', $currWord) === 1) {
if (!$keepSpaces) {
$words[$i] = ' ';
}
continue;
}
if (preg_match($regexWordSplit, $currWord) === 1) {
continue;
}
$currWordLower = strtolower($currWord);
if ($i != 0 && $i != count($words) - 1 && in_array($currWordLower, $stopWords)) {
$words[$i] = $currWordLower;
continue;
}
if (strlen($currWord) > 0) {
$currWord[0] = strtoupper($currWord[0]);
$words[$i] = $currWord;
}
}
return implode('', $words);
}
</code></pre>
<p>Everything works well (as far as I can tell). I'm looking for feedback on the above conversion and also general feedback on the PHP code (which it's maybe too much of a JS translation).</p>
<p>Some el cheapo testing for the PHP code:</p>
<pre><code>$tests = array(
array('in' => '', 'out' => '', 'keepSpaces' => false),
array('in' => 'this is a test', 'out' => 'This Is a Test', 'keepSpaces' => false),
array('in' => 'why sunless tanning is A hot trend', 'out' => 'Why Sunless Tanning Is a Hot Trend', 'keepSpaces' => false),
array('in' => 'Satin Sheets are a Luxury you Can Afford', 'out' => 'Satin Sheets Are a Luxury You Can Afford', 'keepSpaces' => false),
array('in' => 'the Dangers Of Hiking Without Proper Shoes', 'out' => 'The Dangers of Hiking Without Proper Shoes', 'keepSpaces' => false),
array('in' => 'an hour or so', 'out' => 'An Hour or So', 'keepSpaces' => false),
array('in' => 'Of the meaning Of Of', 'out' => 'Of the Meaning of Of', 'keepSpaces' => false),
array('in' => 'Thing With Extra Spaces', 'out' => 'Thing With Extra Spaces', 'keepSpaces' => false),
array('in' => 'Thing with extra spaces', 'out' => 'Thing With Extra Spaces', 'keepSpaces' => true),
array('in' => 'Observations of isolated pulsars and disk-fed X-ray binaries.', 'out' => 'Observations of Isolated Pulsars and Disk-Fed X-Ray Binaries.', 'keepSpaces' => false)
);
$ok = 0;
foreach ($tests as $currTest) {
$currRes = APATitle($currTest['in'], $currTest['keepSpaces']);
if ($currRes === $currTest['out']) {
++$ok;
}
}
echo $ok == count($tests) ? 'All tests OK' : 'Test bad';
</code></pre>
|
[] |
[
{
"body": "<p>First things first: <strong>You definitely don't need to be making multiple regex function calls while looping the elements generated by a splitting regex function.</strong> Time for an almost complete rewrite. <code>preg_replace_callback()</code> is the tool that I recommend to do all the heavy lifting. </p>\n\n<p>Normally, I like to do everything in a single regex expression, but the retaining of the multiple spaces is a simple operation that is sensibly set apart.</p>\n\n<p>There WILL be other fringe cases that other reviewers may shout out (e.g. handling multibyte characters or calling <code>preg_quote()</code> on the incoming blacklist words to avoid any regex pattern conflicts with special characters, and let's not forget about troublesome Mr <code>McGee</code>) but I am going to only focus on the quality of data that you have presented.</p>\n\n<p>There will be other ways to write the pattern but I have a high appreciation for the clarity of <code>(*SKIP)(*FAIL)</code> it basically consumes substrings that should be disqualified and then discards them. The pipe after the skip-fail non-capturing group will match qualifying consecutive letters. The fullstring matches are passed to the custom function where the first letter is converted to uppercase, then returned. Finally the fully modified string is returned from the <code>preg_replace_callback()</code>.</p>\n\n<p>My regex pattern uses negative lookaheads with the start and end of string anchors (<code>^</code> & <code>$</code>) to implement the rule regarding capitalizing the first and last word. Word boundaries (<code>\\b</code>) are a great way to isolate a whole word (or parts of a hyphenated word).</p>\n\n<p>Code: (<a href=\"https://3v4l.org/MgYCK\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n\n<pre><code>$tests = [\n ['this is a test', 'This Is a Test', false],\n ['why sunless tanning is A hot trend', 'Why Sunless Tanning Is a Hot Trend', false],\n ['Satin Sheets are a Luxury you Can Afford', 'Satin Sheets Are a Luxury You Can Afford', false],\n ['the Dangers Of Hiking Without Proper Shoes', 'The Dangers of Hiking Without Proper Shoes', false],\n ['an hour or so', 'An Hour or So', false],\n ['Of the meaning Of Of', 'Of the Meaning of Of', false],\n ['Thing With Extra Spaces', 'Thing With Extra Spaces', false],\n ['Thing with extra spaces', 'Thing With Extra Spaces', true],\n ['Observations of isolated pulsars and disk-fed X-ray binaries.', 'Observations of Isolated Pulsars and Disk-Fed X-Ray Binaries.', false]\n];\n\nfunction APATitle($title, $keepMultipleSpaces = false, $blackList = [])\n{\n if (!is_string($title)) {\n return false;\n }\n\n $blackList = $blackList\n ? array_map('strtolower', (array)$blackList)\n : ['a', 'an', 'and', 'at', 'but', 'by', 'for', 'in', 'nor', 'of', 'on', 'or', 'so', 'the', 'to', 'up', 'yet'];\n\n if (!$keepMultipleSpaces) {\n $title = preg_replace('~\\s+~', ' ', $title);\n }\n\n return preg_replace_callback(\n '~(?!^)\\b(?:' . implode('|', $blackList) . ')\\b(?!$)(*SKIP)(*FAIL)|\\b[a-z]+\\b~',\n function ($m) {\n return ucfirst($m[0]);\n },\n strtolower($title)\n );\n}\n\nforeach ($tests as [$input, $expectedOutput, $keepMultipleSpaces]) {\n $output = APATitle($input, $keepMultipleSpaces);\n echo ($output === $expectedOutput ? 'SUCCESS' : 'FAILURE') . \":\\t\\\"{$input}\\\" became \\\"{$output}\\\"\\n\";\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>SUCCESS: \"this is a test\" became \"This Is a Test\"\nSUCCESS: \"why sunless tanning is A hot trend\" became \"Why Sunless Tanning Is a Hot Trend\"\nSUCCESS: \"Satin Sheets are a Luxury you Can Afford\" became \"Satin Sheets Are a Luxury You Can Afford\"\nSUCCESS: \"the Dangers Of Hiking Without Proper Shoes\" became \"The Dangers of Hiking Without Proper Shoes\"\nSUCCESS: \"an hour or so\" became \"An Hour or So\"\nSUCCESS: \"Of the meaning Of Of\" became \"Of the Meaning of Of\"\nSUCCESS: \"Thing With Extra Spaces\" became \"Thing With Extra Spaces\"\nSUCCESS: \"Thing with extra spaces\" became \"Thing With Extra Spaces\"\nSUCCESS: \"Observations of isolated pulsars and disk-fed X-ray binaries.\" became \"Observations of Isolated Pulsars and Disk-Fed X-Ray Binaries.\"\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T01:35:07.650",
"Id": "241041",
"ParentId": "241036",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T00:06:44.923",
"Id": "241036",
"Score": "1",
"Tags": [
"javascript",
"php",
"strings",
"regex"
],
"Title": "Feedback Request on Title Capitalization Function Converted From JavaScript to PHP"
}
|
241036
|
<p>Is it possible to implement this function without <code>goto</code>, while keeping the code correct and readable?</p>
<pre><code>using iter = std::string::const_iterator;
// Skip multiline comment in a source string.
// Initial iterator is at the first character after the "/*"
iter skipMultilineComment( iter i, iter fileEnd )
{
while( true )
{
const char c1 = *i;
if( c1 != '*' )
{
i++;
if( i != fileEnd )
continue;
break;
}
// Found '*' character
FoundAsterisk:
i++;
if( i == fileEnd )
break;
const char c2 = *i;
if( c2 == '*' )
{
/* Found another '*' character; can be more: ****/
goto FoundAsterisk;
}
if( c2 != '/' )
{
i++;
if( i != fileEnd )
continue;
break;
}
// Finally, found the closing token, "*/"
i++;
return i;
}
logError( "fatal error C1071: unexpected end of file found in comment" );
throw E_INVALIDARG;
}
</code></pre>
<p>P.S. That’s not a test assignment or something, it’s production code. The input is <a href="https://en.wikipedia.org/wiki/OpenGL_Shading_Language" rel="nofollow noreferrer">GLSL</a>, but the comments there are the same as in C++.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T04:35:57.333",
"Id": "472974",
"Score": "0",
"body": "`[That’s] production code.` [Are you a maintainer of this code?](https://codereview.stackexchange.com/help/on-topic)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T05:37:52.997",
"Id": "472977",
"Score": "1",
"body": "@greybeard Yep, sole maintainer ATM."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T01:15:59.233",
"Id": "473100",
"Score": "0",
"body": "`Is it possible to implement this function without goto`: There was a famous paper in the 60s => **\"BÖhm, Corrado, and Jacopini Guiseppe. Flow diagrams, Turing machines and languages with only two formation rules. Comm. ACM 9 (May 1966), 366-371\"**. I believe that showed that higher level concepts could replace all usages of goto. Can't find a link to the paper but it is mentioned in [Dijkstra paper](http://www.u.arizona.edu/~rubinson/copyright_violations/Go_To_Considered_Harmful.html) about goto being harmful later in the 60s."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T01:20:52.943",
"Id": "473101",
"Score": "1",
"body": "In this case I don't think it is that difficult to work out how to replace this goto with a loop."
}
] |
[
{
"body": "<p>Yes, of course. (It's always <em>possible</em> to eliminate unstructured constructs by use of structured programming.) I recommend Kernighan & Plauger's <em>The Elements of Programming Style</em> for developing your own sense of structured programming.</p>\n\n<p>Come on this journey with me!</p>\n\n<p>Step 1: That confusing <code>if</code> at the top of the loop.</p>\n\n<pre><code>while (true) {\n const char c1 = *i;\n if( c1 != '*' )\n {\n i++;\n if( i != fileEnd )\n continue;\n break;\n }\n</code></pre>\n\n<p><code>c1</code> is never used again, so we can eliminate it. Then, <code>break</code>ing the loop means going to the end of the loop and setting a \"don't do this loop again\" flag; so let's make that flag; we'll call it <code>done</code>. Then <code>continue</code>ing the loop means going to the end <em>without</em> setting that flag. So at this point we have</p>\n\n<pre><code>template<class It>\nIt skipMultilineComment(It it, It fileEnd)\n{\n bool done = false;\n while (!done) {\n if (*it != '*') {\n ++it;\n done = (it == fileEnd);\n } else {\n // Found '*' character\n FoundAsterisk:\n ++it;\n if (it == fileEnd) break;\n if (*it == '*') {\n /* Found another '*' character; can be more: ****/\n goto FoundAsterisk;\n } else if (*it != '/') {\n ++it;\n if (it != fileEnd) continue;\n break;\n }\n // Finally, found the closing token, \"*/\"\n ++it;\n return it;\n }\n }\n logError( \"fatal error C1071: unexpected end of file found in comment\" );\n throw E_INVALIDARG;\n}\n</code></pre>\n\n<p>Notice that I've cleaned up some whitespace style and renamed <code>i</code> (traditionally a name for an integer loop control variable) to <code>it</code> (traditionally a name for an iterator). I've also made the function a template so that I can get rid of that global-scope <code>typedef</code> at the top.</p>\n\n<p>Okay, let's pull out the next <code>break</code>... or, no, let's skip down to that similar <code>continue/break</code> tangle at the bottom of the loop, and sort that out. Same transformation as before. I'll just show the loop, because nothing outside it has changed.</p>\n\n<pre><code> while (!done) {\n if (*it != '*') {\n ++it;\n done = (it == fileEnd);\n } else {\n // Found '*' character\n FoundAsterisk:\n ++it;\n if (it == fileEnd) break;\n if (*it == '*') {\n /* Found another '*' character; can be more: ****/\n goto FoundAsterisk;\n } else if (*it == '/') {\n // Finally found the closing token, \"*/\"\n ++it;\n return it;\n } else {\n ++it;\n done = (it == fileEnd);\n }\n }\n }\n</code></pre>\n\n<p>Notice that I am also habitually untangling your <code>if/else</code> blocks. You don't want to have <code>if (a == x) ... else if (a != y) ... else if (a == z) ...</code> because that's just plain confusing. <code>if/else</code> chains should read like switch statements: one handler per interesting value. So here we have one handler for <code>*it == '*'</code>, and one handler for <code>*it == '/'</code>, and then one catch-all \"else\" handler.</p>\n\n<p>Let's follow that guideline and refactor the outer <code>if (*it != '*')</code> as well.\nNotice that once we do that, we don't need the comment <code>// Found '*' character</code> anymore, because it's obvious from the code itself. Getting to remove pointless comments is one of the most satisfying parts of the refactoring process!</p>\n\n<pre><code> while (!done) {\n if (*it == '*') {\n FoundAsterisk:\n ++it;\n if (it == fileEnd) {\n done = true;\n } else if (*it == '*') {\n goto FoundAsterisk;\n } else if (*it == '/') {\n // Finally found the closing token, \"*/\"\n ++it;\n return it;\n } else {\n ++it;\n done = (it == fileEnd);\n }\n } else {\n ++it;\n done = (it == fileEnd);\n }\n }\n</code></pre>\n\n<p>Okay, let's tackle that <code>goto</code>. The fundamental algorithm here is, \"While we're looking at a <code>*</code> character, increment <code>it</code>. But if we reach the end of the string, then stop.\" Normally we'd spell that as</p>\n\n<pre><code>while (it != fileEnd && *it == '*') { ++it; }\n</code></pre>\n\n<p>Let's see if we can shoehorn that line of code into our function in a natural way.</p>\n\n<pre><code> while (!done) {\n if (*it == '*') {\n while (it != fileEnd && *it == '*') {\n ++it;\n }\n if (it == fileEnd) {\n done = true;\n } else if (*it == '/') {\n // Finally found the closing token, \"*/\"\n ++it;\n return it;\n } else {\n ++it;\n done = (it == fileEnd);\n }\n } else {\n ++it;\n done = (it == fileEnd);\n }\n }\n</code></pre>\n\n<p>Notice that every path to the bottom of the outer loop now ends with <code>done = (it == fileEnd)</code> (except in one case where we already know <code>it == fileEnd</code> and so we just set <code>done = true</code>). So basically we just keep going until <code>it == fileEnd</code>. That's our loop condition.</p>\n\n<pre><code> while (it != fileEnd) {\n if (*it == '*') {\n while (it != fileEnd && *it == '*') {\n ++it;\n }\n if (it == fileEnd) {\n } else if (*it == '/') {\n // Finally found the closing token, \"*/\"\n ++it;\n return it;\n } else {\n ++it;\n }\n } else {\n ++it;\n }\n }\n</code></pre>\n\n<p>Okay, but, now we've got a loop <em>within</em> a loop. You know what? Maybe what we really want here is a simple state machine: Either we've just seen a <code>*</code>, or we haven't. If we have, and the next character is <code>/</code>, then we're done. Otherwise, keep going. That would code up like this:</p>\n\n<pre><code>template<class It>\nIt skipMultilineComment(It it, It fileEnd)\n{\n for (bool seenStar = false; it != fileEnd; ++it) {\n if (*it == '/' && seenStar) {\n return it + 1;\n }\n seenStar = (*it == '*');\n }\n logError( \"fatal error C1071: unexpected end of file found in comment\" );\n throw E_INVALIDARG;\n}\n</code></pre>\n\n<p>Yes. I like that better. But wait, we can do better than that! All we seem to be doing is looking for the string <code>\"*/\"</code> inside a longer string. That's <em>string search</em>, and there are library functions for that!</p>\n\n<pre><code>#include <string.h>\n\nconst char *skipMultilineComment(const char *it, const char *fileEnd)\n{\n if (const char *p = memmem(it, fileEnd - it, \"*/\", 2)) {\n return p + 2;\n }\n logError( \"fatal error C1071: unexpected end of file found in comment\" );\n throw E_INVALIDARG;\n}\n</code></pre>\n\n<p>or in C++17,</p>\n\n<pre><code>std::string_view skipMultilineComment(std::string_view text)\n{\n size_t pos = text.find(\"*/\");\n if (pos != text.npos) {\n return text.substr(pos + 2);\n }\n logError( \"fatal error C1071: unexpected end of file found in comment\" );\n throw E_INVALIDARG;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T01:36:15.017",
"Id": "472961",
"Score": "1",
"body": "Thanks a lot. The string_view approach was just what I needed. I do have C++/17, the software I’m working on is only built by VC++ 2017 (AMD64) and GCC 8.3 (ARMv7)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T01:59:57.370",
"Id": "472963",
"Score": "0",
"body": "BTW, string literal would probably work slightly better for the search string, i.e. `\"*/\"s` instead of just `\"*/\"`. AFAIK compilers aren’t that smart, they don’t precompute `strlen` even for very small constexpr strings."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T02:23:31.093",
"Id": "472965",
"Score": "0",
"body": "@Soonts: Nope, I wrote what I meant. Try it in Godbolt and see! (The compiler knows how many characters are in `\"*/\"`. The compiler is the one who _put_ them there.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T03:19:54.820",
"Id": "472966",
"Score": "0",
"body": "I have put it in Godbolt, and seeing a function call to `__gnu_cxx::char_traits<char>::length(char const*)`. Now, `-O2` switch helps, but no reason to slow down debug builds, it’s just 1 extra character in the source code."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T01:03:30.100",
"Id": "241038",
"ParentId": "241037",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "241038",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T00:14:24.817",
"Id": "241037",
"Score": "0",
"Tags": [
"c++",
"strings"
],
"Title": "Refactor to remove goto"
}
|
241037
|
<p>This is an implementation of Huffman Coding that works on ASCII values. I simplified <code>main</code> to show an example of user input to the program. I only removed handling of non-printable ASCII characters, as that is not something I need reviewed. Initially, I tried to use <code>std::priority_queue<std::unique_ptr<node>></code>, but you cannot easily remove these pointers due to <code>std::priority_queue::top</code> returning a const reference, so I had to use <code>std::shared_ptr</code>. More or less, I just want to know if there are any glaring issue with how I used the standard library or guideline violations.</p>
<pre><code>#include <iostream>
#include <map>
#include <memory>
#include <queue>
#include <string>
#include <unordered_map>
#include <utility>
#include <optional>
#include <sstream>
/// node
/// node in huffman tree
struct node {
node(char c, int freq, std::shared_ptr<node> left, std::shared_ptr<node> right)
: c {c}
, freq {freq}
, left {std::move(left)}
, right {std::move(right)}
{}
node(int freq, std::shared_ptr<node> left, std::shared_ptr<node> right)
: freq {freq}
, left {std::move(left)}
, right {std::move(right)}
{}
std::optional<char> c;
int freq;
std::shared_ptr<node> left;
std::shared_ptr<node> right;
};
/// build_huffman_codings
/// traverses a huffman tree and finds encodings for all characters
/// \param root root of huffman tree or subtree
/// \param accumulator prefix of huffman code gathered before root
/// \param codings mapping of character to its final encoding
void build_huffman_codings(const std::shared_ptr<node>& root,
std::map<char, std::string>& codings,
std::string accumulator = "") {
// leaf node adds to codings
if (!root->left && !root->right) {
codings[root->c.value()] = accumulator;
return;
}
// left branch
if (root->left) {
build_huffman_codings(root->left, codings, accumulator + "0");
}
// right branch
if (root->right) {
build_huffman_codings(root->right, codings, accumulator + "1");
}
}
/// huffman
/// compute huffman codings for given frequencies of characters
/// \param freq mapping of character and frequencies
/// \return mapping of character to a binary representation
std::map<char, std::string> huffman(const std::map<char, int>& freq) {
// pre-allocate nodes
std::vector<std::shared_ptr<node>> nodes;
for (const auto& pair : freq) {
nodes.emplace_back(std::make_shared<node>(pair.first, pair.second, nullptr, nullptr));
}
// compare freq of node pointers
auto compare_greater = [] (const auto& p1, const auto& p2) {
return p1->freq > p2->freq;
};
// priority queue holds nodes in increasing order by frequency
std::priority_queue<std::shared_ptr<node>,
std::vector<std::shared_ptr<node>>,
decltype(compare_greater)>
queue {compare_greater, std::move(nodes)};
const std::size_t size = queue.size();
// repeat size - 1 times
for (std::size_t i = 1; i < size; ++i) {
// remove first two nodes
std::shared_ptr<node> x = queue.top();
queue.pop();
std::shared_ptr<node> y = queue.top();
queue.pop();
// add new node
queue.emplace(std::make_shared<node>(x->freq + y->freq, x, y));
}
std::map<char, std::string> codings;
build_huffman_codings(queue.top(), codings);
return codings;
}
int main() {
// store character with its frequency
std::map<char, int> frequencies;
// example user input - real implementation handles non-printable ascii
std::stringstream freq_txt {
"a 5\n"
"b 25\n"
"c 7\n"
"d 15\n"
"e 4\n"
"f 12\n"
};
char c;
int f;
while (freq_txt) {
freq_txt >> c;
freq_txt >> f;
frequencies[c] = f;
}
// huffman code table
const auto codings = huffman(frequencies);
for (const auto& pair : codings) {
std::cout << pair.first << ' ' << pair.second << '\n';
}
}
</code></pre>
|
[] |
[
{
"body": "<p>At first glance, I see a a lot of good usage of the standard library. So, the remarks I have are rather small:</p>\n\n<ul>\n<li>in huffman(), you create a vector <code>nodes</code>, as you know exactly the amount of elements to store into it, I would reserve it. This reduces memory usage slightly and improves performance. (<code>nodes.reserve(freq.size())</code>)</li>\n<li>In the same function, you don't seem to have handling for <code>size == 0</code>, most likely because of the simplification?</li>\n<li>a small optimization in the for-loop, you can use <code>std::move()</code> on <code>x</code> and <code>y</code>.</li>\n<li>In build_huffman_condings, you have <code>std::string accumulator =\"\"</code>. It's better to write <code>= std::string{}</code> as this doesn't require <code>strlen</code> to be called.</li>\n</ul>\n\n<p>On the more high level, I am wondering about the used datastructures, especially <code>std::map</code>. I know <code>std::unordered_map</code> ain't an ideal hash-map, though, it does perform better than <code>std::map</code> if you don't need ordering. I don't see in your code that need, hence I would recommend replacing it. (You can also use abseil ... for a better implementation, or as the values are small, boosts flat_map)</p>\n\n<p>In short, your usage of the standard library looks fine.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T12:59:24.087",
"Id": "473377",
"Score": "0",
"body": "Thanks for responding. I used map over unordered_map because my calling code needed to output the table with ascii values in order."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T15:52:41.080",
"Id": "473392",
"Score": "0",
"body": "Even than, if you know the characters, depending on the length of the text, it might be beneficial to use hash_map and at the end loop over all characters and locate. Though that all depends on the use cases."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T02:08:36.837",
"Id": "473443",
"Score": "0",
"body": "Since `queue.top()` returns a `const shared_ptr&` - and even if I made `x` and `y` const, should I still use `move` on them? I'm getting warnings to not move const variables. I'm assuming it will handle the reference counts correctly and the warning may not apply in this situation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T10:54:45.770",
"Id": "473479",
"Score": "0",
"body": "You indeed make a copy of the shared_ptr when creating variable x, which is needed. However, when passing it along to the new node, you could move it."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T08:23:37.293",
"Id": "241229",
"ParentId": "241039",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "241229",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T01:14:33.090",
"Id": "241039",
"Score": "4",
"Tags": [
"c++",
"c++17"
],
"Title": "Implementation of Huffman Coding"
}
|
241039
|
<p>I am learning the basics about managing an SQLite database by using Python and, mainly for practice purposes, I have then defined an interface class in order to let operations on database as clear as possible. That said, I would like to ask you for some feedback about the following code:</p>
<pre><code>import sqlite3, os
class DbInterface:
def __init__(self, file):
self.dbfile = file
def open(self):
try:
assert os.path.exists(self.dbfile)
assert os.path.isfile(self.dbfile)
self._dbconn = sqlite3.connect(self.dbfile)
return 0
except sqlite3.Error as e:
print(e)
except AssertionError as e:
print('ERROR: database file not found.')
return -1
def close(self):
if hasattr(self, '_dbconn'):
self._dbconn.close()
return 0
return -1
def write(self, query, *args):
try:
assert any(map(lambda s: query.upper().strip().startswith(s), ('CREATE TABLE', 'ALTER TABLE', 'INSERT', 'UPDATE', 'DELETE')))
assert query.count('?') == len(args)
c = self._dbconn.cursor()
c.execute(query, args)
self._dbconn.commit()
return 0
except AssertionError:
print('ERROR: inconsistent query arguments.')
except sqlite3.Error as e:
self._dbconn.rollback()
print('SQL ERROR:', e)
return -1
def read(self, query, *args):
try:
assert query.count('?') == len(args)
assert query.upper().strip().startswith('SELECT')
c = self._dbconn.cursor()
c.execute(query, args)
rows = c.fetchall()
return 0, rows;
except AssertionError:
print('ERROR: inconsistent query arguments.')
except sqlite3.Error as e:
print('SQL ERROR:', e)
return -1, ()
</code></pre>
<p>Here is a test function I am using for code validation:</p>
<pre><code>def test(path):
db = DbInterface(path)
res = db.open()
q = """
CREATE TABLE IF NOT EXISTS example(
id integer PRIMARY KEY,
sometext text NOT NULL
);
"""
res = db.write(q)
q = 'INSERT INTO example(sometext) VALUES(?);'
res = db.write(q, 'a')
q = 'INSERT INTO example(sometext) VALUES(?, ?);'
res = db.write(q, 'b')
q = 'INSERT INTO example(sometext) VALUES(?);'
res = db.write(q)
q = 'INSERT INTO example(sometext) VALUES(?, ?);'
res = db.write(q, 'c', 'd')
q = 'SELECT * FROM example;'
res, data = db.read(q)
q = 'SELECT somevalue FROM example;'
res, data = db.read(q)
q = 'SELECT * FROM example WHERE sometext = ?;'
res, data = db.read(q, 'a')
q = 'SELECT * FROM example WHERE sometext = ?;'
res, data = db.read(q)
res = db.close()
if __name__ == '__main__':
test('testdb.db')
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T05:55:05.503",
"Id": "472980",
"Score": "1",
"body": "To demonstrate that your database interface is really simple to use, you should add some code to the question that actually uses the class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T14:36:40.630",
"Id": "473029",
"Score": "0",
"body": "@RolandIllig, thanks for suggestion. I have just added a validation function I used during code drafting."
}
] |
[
{
"body": "<p><strong>Exception handling</strong>: you handle some exceptions but you print them to the console, where they can get lost/unnoticed. It would be better to use the <code>logger</code> module to record them to a file. What I like to do when writing classes is to attach to the logger routine of the <strong>main module</strong>. This way, all messages go to the console AND get written to the same log file<br />\nThe code would be along these lines:</p>\n\n<pre><code>import logging\n\ndef __init__(self, file, logger=None):\n self.dbfile = file\n\n # acquire existing logger - https://fangpenlin.com/posts/2012/08/26/good-logging-practice-in-python/\n self.logger = logger or logging.getLogger(__name__)\n self.logger.debug('Running __init__')\n</code></pre>\n\n<p>See the section 'Use <strong>name</strong> as the logger name' in the link above.</p>\n\n<hr>\n\n<p>Redundant code:</p>\n\n<pre><code>assert os.path.exists(self.dbfile)\nassert os.path.isfile(self.dbfile)\n</code></pre>\n\n<p><code>isfile</code> is sufficient. </p>\n\n<blockquote>\n <p><code>os.path.isfile(path)</code></p>\n \n <p>Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same\n path.</p>\n</blockquote>\n\n<p>Source: <a href=\"https://docs.python.org/3/library/os.path.html#os.path.isfile\" rel=\"nofollow noreferrer\">os.path.isfile(path)</a></p>\n\n<p>But your code will fail if the DB file does not exist. By default SQLite <code>connect</code> will create the file if it doesn't already exist. So I think you should preferably make that check <em>after</em> the call to <code>connect</code> to determine that the file is indeed present.</p>\n\n<hr>\n\n<p>Return codes: your procedures return either 0 or -1, I wonder why you made that arbitrary choice. You could simply return a <strong>boolean</strong> value, also in your <code>except</code> blocks if you want, so that there is a return value on all paths.</p>\n\n<p>Your <code>read</code> procedure returns a tuple (note that <code>fetchall</code> <a href=\"https://docs.python.org/2/library/sqlite3.html#sqlite3.Cursor.fetchall\" rel=\"nofollow noreferrer\">returns a list</a>):</p>\n\n<pre><code>return 0, rows;\n</code></pre>\n\n<p>Personally I would only return the rows, but in case of error I would return <strong>None</strong> instead, so I know that the operation failed. If you don't look at the error code, the (empty) returned list is still iterable.<br />\nThe return code doesn't matter here because it doesn't give any additional information. If I need details, I will look at the error log. </p>\n\n<hr>\n\n<p>I would make the call to <code>close</code> <strong>optional</strong> (it's going to be forgotten sometimes anyway). Simply register a cleanup routine for your class:</p>\n\n<pre><code>import atexit\n\ndef __init__(self, iface, logger=None):\n ...\n # run cleanup routine when class terminates\n atexit.register(self.cleanup)\n\ndef cleanup(self):\n \"\"\"To perform cleanup tasks when class instance is shutting down\n \"\"\"\n self.logger.debug('Closing DB')\n if hasattr(self, '_dbconn'):\n self._dbconn.close()\n</code></pre>\n\n<p>And in fact the <code>open</code> method is not required either:</p>\n\n<pre><code>res = db.open()\n</code></pre>\n\n<p>Just move the code to the <code>__init__</code> function. No need to do open & close.</p>\n\n<hr>\n\n<p>Your write routine only allows certain operations:</p>\n\n<pre><code>assert any(map(lambda s: query.upper().strip().startswith(s), ('CREATE TABLE', 'ALTER TABLE', 'INSERT', 'UPDATE', 'DELETE')))\n</code></pre>\n\n<p>Therefore no <strong>PRAGMA</strong>s allowed but this is your choice.</p>\n\n<p>One possible enhancement would be to take an existing connection as a class argument, in case you want to do something special on an open DB (like a PRAGMA), that your class does not easily allow. Although I can imagine this code is sufficient for your needs.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-05T19:47:21.460",
"Id": "241775",
"ParentId": "241043",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T02:14:47.103",
"Id": "241043",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"database",
"sqlite",
"interface"
],
"Title": "Interface class for SQLite databases"
}
|
241043
|
<p>I'm experimenting with ways to reuse code throughout a Rails web app. I'm interested in feedback concerning one such approach!</p>
<p><strong>Context</strong></p>
<p>A user's request may be scoped to a physical location so that the view shows location-relevant information. In most cases, the location is stored in a cookie. It's possible for location to be overridden via query parameters (<code>?where=</code> or <code>?location=</code>). When location is not in a cookie or in the query string, depending on where the code executes, I'll want to provide some other location.</p>
<p>Here's what I came up with:</p>
<pre class="lang-rb prettyprint-override"><code>class LocationResolver
def initialize(locations)
@locations = locations
end
def call(strategy)
[*strategy].map { |strat| strat.(@locations) }.find(&:itself)
end
class QueryStrategy
def initialize(params)
@params = params
end
def call(locations)
locations.find { |x| x.slug == slug }
end
private
def slug
@slug ||= @params.values_at(:where, :location).find(&:itself)
end
end
class CookieStrategy
def initialize(cookies)
@cookies = cookies
end
def call(locations)
content.presence && locations.find { |x| x.id == content["id"] }
end
private
def content
@content ||= JSON.parse(@cookies.fetch(:location, "{}"))
end
end
</code></pre>
<p>Given a simple <code>Location</code> implementation:</p>
<pre class="lang-rb prettyprint-override"><code>Location = Struct.new(:id, :slug) do
def self.all
[
new(1, "one"),
new(2, "two")
]
end
def self.anywhere
new(nil, "anywhere")
end
end
</code></pre>
<p>Usage inside a controller might look like this:</p>
<pre class="lang-rb prettyprint-override"><code>class PropertiesController << ApplicationController
def effective_location
@effective_location ||=
LocationResolver.new(Location.all).([
LocationResolver::QueryStrategy.new(request.query_parameters),
LocationResolver::CookieStrategy.new(request.cookies),
-> (_) { Location.anywhere }
])
end
end
</code></pre>
<p><strong>Dislikes</strong></p>
<ul>
<li>Feels complex</li>
</ul>
<p><strong>Likes</strong></p>
<ul>
<li>A strategy can be reused.</li>
<li>Strategies can be reordered or included/excluded depending on your needs.</li>
<li>Strategies can receive only context they require to do their job.</li>
<li>Strategies can be created without modifying the resolver</li>
<li>Use of <code>.call</code> allows defining a strategy at runtime.</li>
<li>Easy to stub and test.</li>
</ul>
<p>What do you think?</p>
<ol>
<li>What do you think conceptually?</li>
<li>What other approaches do you prefer?</li>
<li>What in particular do you like or dislike about this approach?</li>
<li>Any glaring issues?</li>
<li>Are <code>Resolver</code> and <code>Strategy</code> suitable names?</li>
</ol>
<p>Thank you so much! :)</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T02:16:54.063",
"Id": "241044",
"Score": "1",
"Tags": [
"ruby",
"ruby-on-rails"
],
"Title": "Encapsulating Logic to Reuse in Various Contexts"
}
|
241044
|
<p>I made a program that calculates how much the value of money has decreased due to inflation over a given set of years.
This takes a principal amount, a start and end date, and with the help of the inflation rate, it calculates how much the value of money is at the current year. (compound)</p>
<p>The data from the CSV file is taken from <a href="https://www.macrotrends.net/countries/IND/india/inflation-rate-cpi" rel="nofollow noreferrer">here</a></p>
<p>Here is the code- </p>
<pre><code>import pandas
startDate = input("Enter the starting year ")
endDate = input("Enter the ending year ")
principal_amt = float(input("Enter the amount "))
startDate = startDate + "-12-" + "31"
endDate = endDate + "-12-" + "31"
final_amt = 0
print(startDate, endDate)
df = pandas.read_csv("india-cpi.csv")
df = df.set_index("date")
inflation_list = list(df.loc[startDate:endDate, " inflation-rate"])
print(inflation_list)
list_for_p = []
for item in inflation_list:
principal_amt += principal_amt*(item/100)
list_for_p.append(principal_amt)
print(list_for_p)
final_amt += principal_amt
print(final_amt)
</code></pre>
<p>This is how the output looks like: <br>
<em>Enter the starting year 2016 <br>
Enter the ending year 2018 <br>
Enter the amount 100 <br>
2016-12-31 2018-12-31 <br>
[4.941, 2.4909, 4.8607] <br>
[104.941, 107.554975369, 112.782900056761] <br>
112.782900056761</em></p>
<p>I want to ask if my calculation is correct and if you have any other suggestion then please give me. It will be helpful. Thanks!</p>
|
[] |
[
{
"body": "<p>The code itself is clear enough, the spacing and variable naming is ok. You mix <code>camelCase</code> and <code>snake_case</code>. Stick to one. PEP-8 advises <code>snake_case</code> for function and variable names and <code>PascalCase</code> for classes.</p>\n\n<p>Only the abbreviation of <code>principal_amt</code> is rather futile. Just use the full name, it costs 3 characters more.</p>\n\n<h1>functions</h1>\n\n<p>You better separate your program in functions:</p>\n\n<ul>\n<li>read the data</li>\n<li>get the user input</li>\n<li>calculate the difference</li>\n<li>present the results</li>\n</ul>\n\n<p>That way your program is easier to understand, test and reuse</p>\n\n<p>My rule of thumb on where to split the program, is on where data is exchanged from one part to another.</p>\n\n<h1>testing</h1>\n\n<p>Now you've separated your program in logical blocks, you can start testing the individual parts.</p>\n\n<h1>read the data</h1>\n\n<p>Make a small function, passing in the filename as argument and getting the index per year back. Here you can use pandas further. For starters, you can make the year a <code>pandas.Period</code>, so you can index the year immediately. Then you can do the division by 100 already. Since pandas has a nice <code>cumprod</code> function, you can already add 1 to each index</p>\n\n<pre><code>def get_inflation_rate(\n filename: typing.Union[Path, str, typing.IO]\n) -> pd.Series:\n \"\"\"Read the inflation data from `filename`\"\"\"\n inflation_rate = (\n pd.read_csv(\n data_file,\n skiprows=16,\n parse_dates=[\"date\"],\n usecols=[0, 1],\n index_col=0,\n )\n .div(100)\n .add(1)\n .rename(columns={\" Inflation Rate (%)\": \"inflation_rate\"})\n )[\"inflation_rate\"]\n inflation_rate.index = inflation_rate.index.to_period()\n return inflation_rate\n</code></pre>\n\n<p>This returns a Series with the year as index and the inflation ratio as value</p>\n\n<pre><code>date\n1960 1.017799\n1961 1.016952\n1962 1.036322\n1963 1.029462\n...\n2014 1.063532\n2015 1.058724\n2016 1.049410\n2017 1.024909\n2018 1.048607\nFreq: A-DEC, Name: inflation_rate, dtype: float64\n</code></pre>\n\n<p>I included a docstring and typing information so the user of this function and his IDE can know what to expect. </p>\n\n<h1>user input</h1>\n\n<p>If your user returns some nonsense, your program will do little useful. Better to warn the user as clearly as possible. You can define a function like this:</p>\n\n<pre><code>def get_input(\n *, message, possible_values: typing.Optional[typing.Collection[str]] = None\n) -> str:\n while True:\n value = input(message)\n if possible_values is None or value in possible_values:\n return value\n print(\"Not one of the possibilities\")\n</code></pre>\n\n<p>A more generic one, which can also convert to float if needed can look like this:</p>\n\n<pre><code>T = typing.TypeVar(\"T\")\n\n\ndef get_input(\n *,\n message: str,\n possible_values: typing.Optional[typing.Collection[T]] = None,\n converter: typing.Optional[typing.Callable[[str], T]] = None,\n) -> typing.Union[T, str]:\n \"\"\"Get and convert the user input.\n\n Tries to call `converter` on the input value.\n If this raises a `ValueError`, asks again.\n\n If `possible_values` is defined, checks whether the returned value is in\n this collection. If it is not, asks again.\n\n Args:\n message (str): The message to present to the user.\n possible_values (typing.Collection[T], optional):\n A selection which must contain the user input. Defaults to None.\n converter (typing.Callable[[str], T], optional):\n A function to try to convert the user input. Defaults to None.\n\n Returns:\n typing.Union[T, str]: The converted user input.\n\n \"\"\"\n while True:\n value = input(message)\n if converter is not None:\n try:\n value_converted = converter(value)\n except ValueError:\n print(\"Invalid value\")\n continue\n else:\n value_converted = typing.cast(T, value)\n if possible_values is None or value_converted in possible_values:\n return value_converted\n print(\"Not one of the possibilities\")\n</code></pre>\n\n<h1>calculate the difference</h1>\n\n<p>Since you have a series with all the inflation ratios already with periods as index, this becomes easy calculate the cumulative product, or even accept <code>datetime.datetime</code> objects as arguments.</p>\n\n<pre><code>import datetime\ndef calculate_inflation(\n amount: float,\n start: typing.Union[datetime.datetime, str],\n end: typing.Union[datetime.datetime, str],\n inflation_rates: pd.Series,\n) -> typing.Tuple[float, typing.Dict[str, float]]:\n inflation_over_period = inflation_rates[start:end]\n\n return (\n amount * inflation_over_period.product(),\n {\n str(year): amount * index\n for (year, index) in inflation_over_period.cumprod().iteritems()\n },\n )\n</code></pre>\n\n<h1>bringing it together:</h1>\n\n<pre><code>if __name__ == \"__main__\":\n data_file = Path(\"<my path>\")\n inflation_rates = get_inflation_rate(data_file)\n start_year = get_input(\n message=\"Enter the starting year:\",\n possible_values=set(inflation_rate.index.map(str)),\n )\n end_year = get_input(\n message=\"Enter the ending year:\",\n possible_values={\n year for year in inflation_rate.index.map(str) if year > start_year\n },\n )\n amount = get_input(message=\"Specify the amount:\", converter=float)\n print(\n calculate_inflation(\n amount=amount,\n start=start_year,\n end=end_year,\n inflation_rates=inflation_rates,\n )\n )\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T13:05:06.700",
"Id": "241066",
"ParentId": "241046",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T04:54:11.757",
"Id": "241046",
"Score": "1",
"Tags": [
"python",
"csv",
"pandas"
],
"Title": "I made a Python program to calculate price based on Inflation Rate"
}
|
241046
|
<p>I am writing a simple count down timer in React:</p>
<p>index.js</p>
<pre><code>import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import bootstrap from "bootstrap/dist/css/bootstrap.css";
import App from "./App";
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById("root")
);
</code></pre>
<p>App.js:</p>
<pre><code>import React, { useEffect, useState } from "react";
const App = () => {
const oneSec = 1000;
const [secCount, setSecCount] = useState(60);
const [minCount, setMinCount] = useState(60);
const [hrCount, setHrCount] = useState(24);
useEffect(() => {
const timer; //<= here is my problem.
if (secCount > 0) {
timer = setInterval(() => {
setSecCount(secCount - 1);
}, oneSec);
}
if (secCount === 0 && minCount > 0) {
timer = setInterval(() => {
setSecCount(60);
}, oneSec);
}
return () => clearInterval(timer);
}, [secCount]);
useEffect(() => {
const timer =
minCount > 0 &&
setInterval(() => {
setMinCount(minCount - 1);
}, 60 * oneSec);
return () => clearInterval(timer);
}, [minCount]);
return (
<div>
{minCount}:{secCount}
</div>
);
};
export default App;
</code></pre>
<p>I am having a hard time with my <code>useEffect</code> hooks. The first <code>useEffect</code> hook is supposed to update the second field, the logic is simply: </p>
<ul>
<li>if <code>secCount</code> is bigger than 0, continue to countdown every second</li>
<li>if <code>secCount</code> is zero and <code>minCount</code> is bigger than 0, reset <code>secCount</code> to 60 and continue to countdown.</li>
</ul>
<p>But since there are two branches in my first <code>useEffect</code> hook, I need to declare the timer variable and reassign it later. Can I get away with declaring it as <code>let timer</code>? A const variable does not allow me to change its value.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T13:56:20.807",
"Id": "473027",
"Score": "1",
"body": "Yes, you can. Also, instead of declaring it twice inside useEffect, declare `timer` outside the effect hook and re-assign inside useEffect when needed"
}
] |
[
{
"body": "<blockquote>\n <p><strong><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let\" rel=\"nofollow noreferrer\">let</a> vs <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const\" rel=\"nofollow noreferrer\">const</a> is fundamentally an ES6+ issue:</strong></p>\n</blockquote>\n\n<ul>\n<li><strong>const</strong><br/>Creates a constant whose scope can be either <code>global</code> or <code>local</code> to the block in which it is declared. An <code>initializer</code> for a constant is required. You must specify its value in the same statement in which it's declared.</li>\n</ul>\n\n<pre><code>// wrong\nconst timer;\n// Uncaught SyntaxError: Missing initializer in const declaration\n\n// right\nconst timer = 60;\n</code></pre>\n\n<ul>\n<li><strong>let</strong><br/>Allows you to declare variables that are limited to a scope of a <code>block</code> statement, or expression on which it is used, unlike the <code>var</code> keyword, which defines a variable globally, or locally to an entire function regardless of block scope. <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#Temporal_dead_zone\" rel=\"nofollow noreferrer\">Please note that a <code>let</code> variable is initialized to a value only when a parser evaluates it</a>.</li>\n</ul>\n\n<pre><code>function do_something() {\n console.log(bar); // undefined\n console.log(foo); // ReferenceError\n var bar = 1;\n let foo = 2;\n};\n</code></pre>\n\n<p><strong>With that said, change the declaration to <code>let timer;</code></strong></p>\n\n<pre><code>// Within the first `useEffect`\nuseEffect(() => {\n let timer; // change this\n if (secCount > 0) {\n timer = setInterval(() => {setSecCount(secCount - 1)}, oneSec);\n }\n if (secCount === 0 && minCount > 0) {\n timer = setInterval(() => {setSecCount(60)}, oneSec);\n }\n return () => clearInterval(timer);\n }, [secCount]);\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T17:56:54.867",
"Id": "241312",
"ParentId": "241053",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "241312",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T09:23:32.677",
"Id": "241053",
"Score": "2",
"Tags": [
"javascript",
"react.js"
],
"Title": "React timer application"
}
|
241053
|
<p>I've recently wrote snake game. I Wanted to keep it in pure terminal, without libraries like pygame, tkinter or curses. It works just fine, but i know that the code might be improved. I'm rather junior programmer, and it's my first attempt at 'gamedev', because currently i'm learning Django. I would be grateful if you guys could tell me what should i change :) Here is my code: </p>
<pre><code>#!/usr/bin/python3
import random
import time
import keyboard
import collections
class Board:
def __init__(self, width: int, height: int, speed: float):
self.WIDTH = width
self.HEIGHT = height
self.SPEED = speed
self.board = self.__create_board()
def __create_board(self) -> list:
return [["□" for _ in range(self.WIDTH)] for _ in range(self.HEIGHT)]
def print_board(self) -> None:
print('\n')
for row in self.board:
print(row)
class Snake:
def __init__(self, x_pos, y_pos):
self.x_pos = x_pos
self.y_pos = y_pos
self.head_pos = [self.x_pos, self.y_pos]
self.body_segments = collections.deque() # doubly end operations, faster than lists
self.length = 0
self.apple_pos = [0, 0]
self.coords = [0, 0]
self.ate = False
self.direction = 'up'
self.spawn_apple()
def set_empty_square(self) -> None:
board_obj.board[self.y_pos][self.x_pos] = "□"
def set_head(self) -> None:
board_obj.board[self.y_pos][self.x_pos] = "■"
def draw_body(self) -> None:
self.body_segments.appendleft(self.coords)
board_obj.board[self.body_segments[0][1]][self.body_segments[0][0]] = "&"
if not self.ate:
board_obj.board[self.body_segments[self.length][1]][self.body_segments[self.length][0]] = "□"
self.set_head()
self.body_segments.pop()
def move(self) -> None:
self.coords = [self.x_pos, self.y_pos]
self.set_empty_square()
if self.direction == "right":
self.x_pos += 1
if self.direction == "left":
self.x_pos -= 1
if self.direction == "up":
self.y_pos -= 1
if self.direction == "down":
self.y_pos += 1
self.set_head()
if self.length >= 1:
self.draw_body()
self.head_pos = [self.x_pos, self.y_pos]
def spawn_apple(self) -> None:
x = random.randint(0, board_obj.WIDTH-2)
y = random.randint(0, board_obj.HEIGHT-2)
apple_pos = [x, y]
if apple_pos in self.body_segments or apple_pos == self.head_pos:
self.spawn_apple() # if apple spawned in snake, then run func again with recursion and quit current func
return
self.apple_pos = [x, y]
board_obj.board[y][x] = "●"
def eat_apple(self) -> None:
self.length += 1
self.ate = True
def collision(self) -> bool:
return self.head_pos in self.body_segments or self.y_pos in [board_obj.HEIGHT-1, -1] \
or self.x_pos in [board_obj.WIDTH-1, -1]
def on_press(_: None):
for code in keyboard._pressed_events:
if code == 105:
snake.direction = 'left'
elif code == 106:
snake.direction = 'right'
elif code == 103:
snake.direction = 'up'
elif code == 108:
snake.direction = 'down'
def start_game(snake: Snake, board_obj: Board):
snake.set_head()
board_obj.print_board()
keyboard.hook(on_press)
while not snake.collision():
print("SNAKE: ", snake.head_pos)
print("BODY: ", snake.body_segments)
print("APPLE: ", snake.apple_pos)
snake.move()
board_obj.print_board()
snake.ate = False
if snake.head_pos == snake.apple_pos:
snake.eat_apple()
snake.spawn_apple()
time.sleep(board_obj.SPEED)
print(f"Game over! Points: {snake.length}")
if __name__ == "__main__":
board_obj = Board(8, 8, 0.3) # Set: width, height, speed
snake = Snake(int(board_obj.WIDTH / 2), int(board_obj.HEIGHT / 2)) # Set: snake x and y position
start_game(snake, board_obj)
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>This is good code for a first post. I'm glad to waste time discussing PEP 8 violations, and seeing a sensible use of the collections module. Having chosen good data structures is a good place to start.</p>\n\n<p>For 2d arrays in Python (unless I am doing numeric heavy lifting, when using numpy is the obvious way to go) I prefer using a dictionary to a list of lists. Something like a named tuple can be used as the key. This makes the board initialization look like:</p>\n\n<pre><code>Pos = collections.namedtuple('position', ['x', 'y'])\n...\ndef __create_board(self) -> None:\n self.board = {(Pos(x, y)) for x in range(self.WIDTH) for y in range(self.HEIGHT)}\n</code></pre>\n\n<p>This is a fairly big change that will ripple through the code but then you won't have to worry about [y][x] indexing or making temporary (x,y) variables.</p>\n\n<p>Onto some more specific things. First, I think I would define a str method here, rather than having a print method. It adds a hidden dependency to sys.stdout in your code, and makes it harder to unit test. </p>\n\n<pre><code>def print_board(self) -> None:\n print('\\n')\n for row in self.board:\n print(row)\n</code></pre>\n\n<p>Here I would lose the recursion and use a while True/break construction.</p>\n\n<pre><code>if apple_pos in self.body_segments or apple_pos == self.head_pos:\n self.spawn_apple() # if apple spawned in snake, then run func again with recursion \n return\n</code></pre>\n\n<p>becomes:</p>\n\n<pre><code>while True:\n ...\n if apple_pos not in self.body_segments and apple_pos != self.head_pos:\n break\n</code></pre>\n\n<p>I must admit to never having used the keyboard module but _pressed_events doesn't look like it is meant to be part of the API. And I don't know where the magic code numbers come from, or what key (if any) they bind to on my platform.</p>\n\n<pre><code>for code in keyboard._pressed_events:\n if code == 105:\n snake.direction = 'left'\n</code></pre>\n\n<p>As you never actually use the string directions I might change it to:</p>\n\n<pre><code>for code in keyboard.some_get_event_api_call():\n if code == LEFT_ARROW:\n snake.direction = Pos(-1, 0)\n</code></pre>\n\n<p>Then you can do the elif thing only once.</p>\n\n<p>Finally:</p>\n\n<pre><code>int(board_obj.WIDTH / 2)\n</code></pre>\n\n<p>can be just</p>\n\n<pre><code>board_obj.WIDTH // 2\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-03T10:25:08.267",
"Id": "474239",
"Score": "0",
"body": "Thank you a lot! I've applied all of you advices, except namedtuple, because there would be a lot of work with this code then.. But i will apply it when i'll have some more time :) Also i've splitted whole game in 3 different files and wrote some tests. Thank you again!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T12:53:58.703",
"Id": "241065",
"ParentId": "241054",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "241065",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T09:30:38.100",
"Id": "241054",
"Score": "2",
"Tags": [
"python",
"game"
],
"Title": "Snake game in terminal, written in Python"
}
|
241054
|
<pre class="lang-py prettyprint-override"><code>import sys
import time
import multiprocessing
def change_char_at(s: str, ch: str, i: int, j: int=None):
'''strings are immutable so i made this handy-little function to 'mutate' strings
similar to =>
s[i] = ch # if j is not specified
s[i:j] = ch # if j is specified
*note*: negative indices does not work!
'''
if not j:
j = i + 1
return s[:i] + ch + s[j:]
def loader(width: int=20, bar_width: int=3):
'''
A simple loading bar which shows no information or whatever
the function should be run in a different thread and must be killed.
'''
s = '[' + ' ' * (width - bar_width - 1) + ']'
while 1:
for i in range(1, width - bar_width - 1):
sys.stdout.write('\r' + change_char_at(s, '===', i))
sys.stdout.flush()
time.sleep(0.1)
for i in range(width - bar_width - 1, 0, -1):
sys.stdout.write('\r' + change_char_at(s, '===', i))
sys.stdout.flush()
time.sleep(0.1)
def loader_with_wait(wait: int=None, width: int=20, bar_width: int=3):
'''
A simple loading bar which shows no information or whatever.
it will quit after `wait` seconds or will *run forever* if wait is not specified
param: wait: for how much time should the loading bar run.
'''
# Start the loader
p = multiprocessing.Process(target=loader, name='loader', args=(width, bar_width))
p.start()
if wait:
# let the loader run for `wait` seconds
time.sleep(wait)
# terminate the loader() function
p.terminate()
# Cleanup
p.join()
# Start from newline
sys.stdout.write('\n')
if __name__ == '__main__':
try:
loader_with_wait(10)
except KeyboardInterrupt:
pass
</code></pre>
<p>Hey Guys!
I made a simple progress bar in python. The animation is cool!
it can wait for a few seconds or it can run forever, the choice is upto you.
it can be used in other programs and can run in a separate thread.
Implementing the wait function was the hardest thing to do. is there any other way to do it?</p>
<p>Any suggestions will be helpful... :-)</p>
<p>see it in action: <a href="https://asciinema.org/a/323180" rel="nofollow noreferrer">https://asciinema.org/a/323180</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T11:47:11.960",
"Id": "473012",
"Score": "0",
"body": "One thing I notice is you're not following a [docstring convention](https://www.python.org/dev/peps/pep-0257/). You should using triple double-quoted strings to declare docstrings, i.e. `\"\"\"` insead of `'''`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T11:52:37.383",
"Id": "473015",
"Score": "1",
"body": "@Srivaths Put answers in answer boxes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T11:54:19.763",
"Id": "473016",
"Score": "1",
"body": "I could only think of one point, so I just added a comment, but I'll write a detailed answer now."
}
] |
[
{
"body": "<ul>\n<li><p>The variable names in <code>change_char_at</code> are terrible. <code>s</code> for the string, <code>ch</code> for the char? <code>i</code> for the start? <code>j</code> for the end.</p>\n\n<p>Seriously just write out names.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def change_char_at(string: str, change: str, start: int, end: int = None):\n return string[:start] + change + string[end or start+1:]\n</code></pre></li>\n<li><p>Your code isn't fully typed:</p>\n\n<ul>\n<li><code>change_char_at</code> has no return type.</li>\n<li><code>end</code> in <code>change_char_at</code> and <code>wait</code> in <code>loader_with_wait</code> are assumed to be <code>Optional</code> but not specified to be optional.</li>\n<li><code>loader</code> and <code>loader_with_wait</code> have no return types should they be <code>None</code> or <code>NoReturn</code>?</li>\n</ul></li>\n<li><p>The functionallity of <code>change_char_at</code> can be eclipsed by <a href=\"https://docs.python.org/3/library/string.html#format-string-syntax\" rel=\"nofollow noreferrer\">the format mini-language</a>.</p>\n\n<ol>\n<li><p>You have a standard structure where the bar is surrounded by <code>[]</code> and filled with the contents.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>bar = '[{}]'\n</code></pre></li>\n<li><p>The content of your bar is left aligned by width.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>bar = '[{: <{width}}]'\n</code></pre></li>\n<li><p>Each iteration you increase the left hand space by 1.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>bar.format(' ' * i + '=' * bar_width, width=width)\n</code></pre></li>\n</ol></li>\n<li><p><code>bar_width</code> doesn't actually change the size of the bar.</p></li>\n<li>I would prefer the progress bar to be a generator function or list, so the rest of your code is simpler.</li>\n</ul>\n\n<pre class=\"lang-py prettyprint-override\"><code>import itertools\n\n\ndef progress_bar(width: int = 20, bar_width: int = 3):\n bar = f'[{{: <{width}}}]'\n for i in itertools.chain(\n range(0, width - bar_width + 1),\n reversed(range(0, width - bar_width)),\n ):\n yield bar.format(' ' * i + '=' * bar_width)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T12:08:31.467",
"Id": "241058",
"ParentId": "241057",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "241058",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T11:26:21.547",
"Id": "241057",
"Score": "3",
"Tags": [
"python"
],
"Title": "progress bar in python"
}
|
241057
|
<p>I've got quite a long question, So I'll try my best to present it well.</p>
<h2>Description</h2>
<p>I am to find the longest sequence of the same character in a 2D array using only the <code>iostream</code> library.<br />
I have to compare the array horizontally, vertically, diagonally up, and diagonally down.<br />
The array should be given to me, so I won't be inputting it.<br />
Now, once I do find it, I have to find the row & column index of the starting cell of the longest sequence.<br />
I also have to find its length and whether the longest sequence was horizontal, vertical, diagonally up, or diagonally down.<br />
I am also to replace the longest sequence with dots.
So for example:</p>
<pre><code> 0123456 col
"xoxxoxo" row 0
"ooxooxo" row 1
"xxoooox" row 2
"oxxoxxx" row 3
</code></pre>
<p>My output should be: <code>Max length=4, Starting cell (2,2), Horizontal</code> & the same array with the longest sequence replaced in dots, to save space I'm only writing <code>row 2: xx....x</code></p>
<h2>What I've thought of</h2>
<p>So I'll do four loops for each test. Finding the longest length in each one, along with the starting cell, then compare the lengths together and use the highest one. then determine the 'd', which points out whether the sequence was horizontal/vertical/etc., based on which test had the greatest length. And then run a loop from the starting cell until the maximum length to replace the characters with dots.</p>
<p>My Code(I am only to work in the first function, leaving both the main&test functions as they are)(My code is also not completely finished, I'll list down below why):</p>
<pre><code>#include <iostream>
using namespace std;
void FindLongestSequence(a, m, n, b, u, v, d)
{
if(m>20 || n>20 || m<=0 || n<=0) return -1;
int lv,lh,l1,l2,d;
int rh,rv,r1,r2,ch,cv,c1,c2;
// Horizontal Test
for(m=0; m<20; m++)
{
lh=0;
for(n=0; n<20; n++)
{
while(true)
if(a[m][n]=a[m][n+1]) {lh += 1;rh=m;ch=n;} else break;
}
}
//Vertical Test
for(n=0; n<20; n++)
{
lv=0;
for(m=0; m<20; m++)
{
while(true)
if(a[m][n]=a[m+1][n]) {lv += 1;rv=m;cv=n;} else break;
}
}
//Diagonal1 Test
for(n=0,m=0; n<20,m<20; m++,j++)
{
l1=0;
while(true)
if(a[m][n]=a[m+1][n+1]) {l1+=1;rd1=m;cd2=n;} else break;
}
//Diagonal2 Test
for(n=0,m=0; n<20,m<20; m++,j++)
{ l2=0
while(true)
if(a[m][n]=a[m-1][n+1]) {l2+=1;rd2=m;cd2=n;} else break;
}
}
void Test(char a[20][21], int m, int n)
{
char b[20][21];
int u, v, d;
int len=FindLongestSequence(a, m, n, b, u, v, d);
cout<<"MaxLen="<<len<<" Start=("<<u<<" "<<v<<") ";
if(d==0) cout<<"Horizontal";
else if(d==1) cout<<"Vertical";
else if(d==2) cout<<"Diagonal \";
else if(d==3) cout<<"Diagonal /";
cout<<endl;
int i;
cout<<"Array after replacing longest sequence by dots:"<<endl;
for(i=0;i<m;i++) cout<<b[i]<<endl;
cout<<endl;
}
int main()
{
char a[20][21]=
{
// col 0123456
"xoxxoxo", // row 0
"ooxooxo", // row 1
"xxoooox", // row 2
"oxxoxxx", // row 3
};
Test(a, 4, 7);
char w[20][21]=
{
// col 012345
"xyxxox", // row 0
"oryoox", // row 1
"xxryoo", // row 2
"xxxryx", // row 3
"xxxory", // row 4
};
Test(w, 5, 6);
char q[20][21]=
{
// col 01234567
"xtuyxxox", // row 0
"xuuyxxox", // row 1
"ouiryoox", // row 2
"xupxryoo", // row 3
"xuexxryx", // row 4
"xuqxxory", // row 5
"yuqxxory", // row 6
};
Test(q, 7, 8);
char r[20][21]=
{
// col 01234567
"xtuyxxox", // row 0
"xuuyxxox", // row 1
"ouiryo1x", // row 2
"xupxr1oo", // row 3
"x1ex1ryx", // row 4
"xuq1xory", // row 5
"yu1xxory", // row 6
"x11yxxox", // row 7
"yu1xxory", // row 8
};
Test(r, 9, 8);
return 0;
}
</code></pre>
<h2>Problems I have with my code</h2>
<p>For starters, I think the Sequence function is way too long. I have no problem with long codes, however am I doing something wrong? Could this be shortened or is it meant to be long? The first four tests are four loops, then I'd have four conditionals for the length comparison test. I'd have a couple more conditionals for the starting cell& 'd'. and then about four more loops to replace the sequence with dots (or switch condition).</p>
<p>My second problem is, during the actual tests, If the sequence doesn't reach the end of the loop, the length is reset back to zero. Meaning I could have a max length of 3 but the loop goes until 5 for example. That means I could lose my maximum length. However, if it is not the longest sequence, I have to break out, re-initialize my length and start the loop over. I'm thinking of maybe creating four arrays for every length, comparing the numbers in the array, then comparing the largest number of each array?</p>
<p>That's it for what I have written down so far. I'm sure I might end up with more problems but I want to get my first problems sort out first. As I'm still not sure how I will be determining the 'd' or finding the starting cell. Thank you for any kind of help/tips!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T17:06:35.983",
"Id": "473050",
"Score": "0",
"body": "The function `void FindLongestSequence(a, m, n, b, u, v, d)` can not work as posted, the code is broken. The first problem is the type of the function. The second problem is in several of the if statement within the function, think `==` rather than `=`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T17:57:11.837",
"Id": "473055",
"Score": "1",
"body": "Unfortunately incomplete code is off-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T01:44:06.723",
"Id": "473102",
"Score": "1",
"body": "This is a well written and interesting question, so much so that I tried to find any reason not to close it. But unfortunately you question just is off-topic. When you get your code working please edit this post with the fully working code. :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T05:08:17.153",
"Id": "473106",
"Score": "0",
"body": "(*Well written question* does *not* imply *code to everyone's liking*.)"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T12:35:12.150",
"Id": "241063",
"Score": "1",
"Tags": [
"c++"
],
"Title": "Finding the longest sequence of a character in 2D array using c++"
}
|
241063
|
<p>I am reading Stroustrup now and I was very impressed with how flexible the STL library is thanks to iterators and generic programming. Along the way, I am also reading Cormen's book and decided to try to implement an algorithm for searching for the maximum subarray in the style of STL. I wrote in C++11. I would be very grateful to hear your opinion about this code.</p>
<pre><code>template<typename For>
// Requires Forward_iterator<For>()
auto find_maximum_subarray (For begin, For end)
{
typename std::iterator_traits<For>::value_type max_sum_subarr = *begin;
typename std::iterator_traits<For>::value_type max_sum = *begin;
For subarr_begin = begin;
For left = begin;
For right = ++begin;
for (; begin != end; ++begin)
{
if (max_sum_subarr > 0)
max_sum_subarr += *begin;
else
{
max_sum_subarr = *begin;
subarr_begin = begin;
}
if (max_sum_subarr > max_sum)
{
left = subarr_begin;
right = begin;
++right;
max_sum = max_sum_subarr;
}
}
return make_tuple (left, right, max_sum);
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>Do not rely on the client code to <code>#include</code> necessary headers. The client has no idea which headers your file requires. Spell them out explicity:</p>\n\n<pre><code>#include <iterator>\n#include <tuple>\n</code></pre></li>\n<li><p>Are you sure you are using <a href=\"/questions/tagged/c%2b%2b11\" class=\"post-tag\" title=\"show questions tagged 'c++11'\" rel=\"tag\">c++11</a>? I am getting</p>\n\n<pre><code>error: 'auto' return without trailing return type; deduced return types\nare a C++14 extension\n</code></pre></li>\n<li><p>In general, naked <code>auto</code> returns in an interface is a dubious idea. Again, think of the client. The client should not analyze your template to deduce what it actually returns. It is OK to have them in the helper functions not exposed to the client.</p></li>\n<li><p>It took me a while to figure out why your code works correctly. The side effect of <code>++</code> in</p>\n\n<pre><code>For right = ++begin;\n</code></pre>\n\n<p>is very easy to miss.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T17:50:45.483",
"Id": "241089",
"ParentId": "241064",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "241089",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T12:51:52.787",
"Id": "241064",
"Score": "3",
"Tags": [
"c++",
"algorithm",
"c++11",
"stl"
],
"Title": "An implementation of maximum subarray finding algorithm in STL style"
}
|
241064
|
<p><a href="https://leetcode.com/problems/find-pivot-index/" rel="nofollow noreferrer">https://leetcode.com/problems/find-pivot-index/</a></p>
<p>Question:</p>
<blockquote>
<p>Given an array of integers nums, write a method that returns the "pivot" index of this array.</p>
<p>We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index.</p>
<p>If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index.</p>
</blockquote>
<p>My answer:</p>
<pre><code>import java.util.HashMap;
class Solution {
public int pivotIndex(int[] nums) {
int runningTotal = 0;
HashMap<Integer, Integer> resultsMap = new HashMap<Integer, Integer>();
int numLength = nums.length;
//run through backwards so leftmost index is returned
for(int i = numLength -1; i >= 0; i-- ){
int neededTotal = runningTotal*2 + nums[i];
resultsMap.put(neededTotal, i);
runningTotal += nums[i];
}
Integer resultIndex = resultsMap.get(runningTotal);
if(resultIndex == null){
return -1;
}else{
return resultIndex;
}
}
}
</code></pre>
<p>The suggested answer on leetcode instead runs through the array to get the total sum, then runs through again to find the appropriate element - and on leetcode submission my answer comes back as slower.</p>
<p><strike>However, when I've tried a quick micro-benchmark for myself, it seems as if using the hashmap, in my version, is quicker on average than running through the array twice.</strike></p>
<p>I messed up the benchmark - why is my version so much slower?</p>
<p>Suggested leetcode answer:</p>
<pre><code>public class ListPivot {
public int pivotIndex(int[] nums) {
int sum = 0, leftsum = 0;
for (int x: nums) sum += x;
for (int i = 0; i < nums.length; ++i) {
if (leftsum == sum - leftsum - nums[i]) return i;
leftsum += nums[i];
}
return -1;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T13:30:16.367",
"Id": "473023",
"Score": "0",
"body": "What did you benchmark against? When running through the list twice, did you still use a HashMap? The autoboxing of ints to Integers can have a significant performance effect."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T13:49:41.923",
"Id": "473025",
"Score": "0",
"body": "Ah - I messed up the benchmark - I was comparing the wrong code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T00:32:00.163",
"Id": "473095",
"Score": "0",
"body": "What's the size of the array? Using `HashMap` has quite a bit of overhead, especially if it is N size big, and uses boxed integers. Their method is really well thought out (and probably somewhere in Knuth), but I think I could do better. Calculating an intermediate result *twice* seems expensive. Besides that, there is no protection against integer overflow. The `sum` and `leftsum` variables should have been `long` types."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T13:20:51.523",
"Id": "241068",
"Score": "1",
"Tags": [
"java",
"programming-challenge"
],
"Title": "Q: Leetcode: Find Pivot Index Java"
}
|
241068
|
<p>I am new to this part of backend development using JS and the truth being a new programming language (for me) it is worrying that it suddenly does not meet the structuring and / or security standards.</p>
<p><strong>CLEAN ARCHITECTURE</strong></p>
<blockquote>
<p>API / CONTROLLERS / SERVICES / LIBS</p>
</blockquote>
<p><strong>ROUTE</strong></p>
<pre><code>//Required application
const express = require('express');
//Required services
const LoginServive = require('../../services/auth/login');
// Schemas
const {
authenticationIdSchema,
authenticationSchema
} = require('../../utils/schemas/auth/login');
// Middleware
const verifyToken = require('../../utils/middleware/verifyTokenHandler.js');
const validationHandler = require('../../utils/middleware/validationHandler')
function loginApi(app)
{
const router = express.Router();
app.use("/api/v1/login", router);
//Class call
const loginService = new LoginServive();
/*
******************************************************************************
******************************************************************************
****************************** POST METHOD ******************************
******************************************************************************
******************************************************************************
*/
router.post('/',
validationHandler(authenticationSchema),
async function(req, res, next) {
const { body:login } = req;
try
{
const response = await loginService.login({ login });
const data = response[0];
req.session.user = {
_id:response[1].id,
_username: response[1].username,
_name: response[1].name,
_role: response[1].role
};
console.log("Session: ", req.session.user);
res.status(201).json(data);
} catch (err) {
next(err);
}
});
}
module.exports = loginApi;
</code></pre>
<p><strong>SERVICE</strong></p>
<pre><code>const pool = require('../../lib/db');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const { config } = require('../../config');
class LoginService
{
async login({ login })
{
//Parameters
const { username, password } = login;
//Api Info
const SECRET_API = config.secretApi;
if (username && password)
{
const user_query = `SELECT usr.id,
usr.username,
usr.email,
usr.hash,
CONCAT(pple.name, ' ', pple.lastname) AS full_username,
usr.user_status_id,
usr.user_type_id
FROM users usr
INNER JOIN people pple
ON pple.id = usr.people_id
INNER JOIN user_states usts
ON usts.id = usr.user_status_id
INNER JOIN user_types utps
ON utps.id = usr.user_type_id
WHERE usr.data_status_id = '1'
AND usr.email = ?`;
const rows = await pool.query(user_query, [username]);
if (rows.length > 0) {
const { id, username, email, hash, full_username, user_status_id, user_type_id } = rows[0];
// Compare hash with the plain text password
const match = await bcrypt.compare(password, hash);
if (match) {
//Get the access token
const token = jwt.sign({ _id: id }, SECRET_API, {
expiresIn: 60 * 60 * 8
});
const response = [
{
status: 201,
message:'You are welcome.',
role: user_type_id,
token:token
},
{
id:id,
username: username,
name: full_username,
role: user_type_id
}
];
const authenticationId = await Promise.resolve(response);
return authenticationId || [];
} else {
const authenticationId = {
status: 401,
message:'Wrong password.'
};
return authenticationId || [];
}
} else {
const authenticationId = {
status: 401,
message:'The user does not exist.'
};
return authenticationId || [];
}
}
};
};
module.exports = LoginService;
</code></pre>
<p><strong>MySQL SESSION STORE</strong></p>
<p>For the session data store I am implementing <a href="https://www.npmjs.com/package/express-mysql-session" rel="nofollow noreferrer">express-mysql-session</a> this as reflected in the direct documentation of <code>express-session</code>.</p>
<blockquote>
<p><strong>Warning</strong> The default server-side session storage, MemoryStore, is
purposely not designed for a production environment. It will leak
memory under most conditions, does not scale past a single process,
and is meant for debugging and developing.</p>
</blockquote>
<p><strong>QUESTIONS</strong></p>
<p>I am trying to implement the <em>Clean Architecture</em> development model and set aside the MVC model, looking for maximum performance in this development part.</p>
<ol>
<li>Is my code exposed to some kind of SQL injection or other type of security flaw? </li>
<li>The user session is an important issue (due to security and performance issues). It is a good practice for what I am doing, since I expected to do it directly from the service but I had problems accessing the request <code>req</code>.</li>
<li>Is any part of the code improvable?</li>
<li>Should I have the session data assigned in the token <code>{ _id: id }</code> or implement express-session?</li>
</ol>
|
[] |
[
{
"body": "<blockquote>\n <p>Is my code exposed to some kind of SQL injection</p>\n</blockquote>\n\n<p>You're using parameterized queries, as you should be, so it shouldn't be an issue. (though, I don't see where you're using the <code>[username]</code> in the query?)</p>\n\n<blockquote>\n <p>Is any part of the code improvable?</p>\n</blockquote>\n\n<p>Some of it. IMO, in Javascript, <code>class</code>es are generally useful when you want to bundle together <em>instance data</em> with <em>operations on that data</em>. If you don't have any instance data, using a class is potentially confusing and doesn't accomplish anything over using an ordinary function instead. Consider changing the service to:</p>\n\n<pre><code>module.exports = async function loginService({ login }) {\n //Parameters\n const { username, password } = login;\n // etc\n</code></pre>\n\n<pre><code>const loginService = require('../../services/auth/login');\n</code></pre>\n\n<p>(make sure the spelling is correct, continuing to use <code>LoginServive</code> could cause bugs later)</p>\n\n<p>If you do decide to keep using classes, make sure not to put semicolons at the end of methods or the class definitions - they do not belong there. Maybe consider <a href=\"http://eslint.org/\" rel=\"nofollow noreferrer\">a linter</a>.</p>\n\n<p>Does your <code>validationHandler</code> ensure that requests contain a <code>username</code> and <code>password</code>? If so, then in the <code>login</code> function, there's no need to test it like you do below:</p>\n\n<pre><code>const { username, password } = login;\nif (username && password) {\n</code></pre>\n\n<p>If the validator <em>doesn't</em> ensure that requests contain those properties, then you have a bug: if a request is made without those properties, the current <code>login</code> function will not return anything, which means that in the route:</p>\n\n<pre><code>const response = await loginService.login({ login });\nconst data = response[0];\n</code></pre>\n\n<p>an error will be thrown, because <code>response</code> is <code>undefined</code>. Maybe only call <code>loginService</code> if credentials are provided - otherwise, call <code>next()</code> to go to the next route.</p>\n\n<p>You have a few cases when you define an object and then test its truthyness, eg:</p>\n\n<pre><code>const authenticationId = {\n status: 401,\n message:'Wrong password.'\n};\nreturn authenticationId || [];\n</code></pre>\n\n<p>This is superfluous, because objects are always truthy; the object you just created will always be returned. It'll never return an empty array instead.</p>\n\n<p>But this points to another problem. You're sometimes returning an object, and you're sometimes returning an array. This makes the shape of the return value more difficult to parse, understand, and test. Consider consistently returning an object which is always the same shape, and if you want to examine it, check possible different properties.</p>\n\n<p>The above points to yet another problem. In the route, the only thing you do with the response is try to use its <code>0</code> and <code>1</code> properties. If it returns a <code>{ status: 401, message:'Wrong password.' }</code> object instead, your script will throw an error when trying to access <code>response[1].id</code>, because <code>response[1]</code> doesn't exist. Instead, use the consistent shape of the object to check the return value from <code>login</code> and figure out what to call <code>res.status</code> with. (See below for full code)</p>\n\n<p><code>response</code> is a potentially confusing variable name in a route for a variable which is <em>not</em> the <code>res</code> parameter. Maybe call it <code>loginResult</code> instead.</p>\n\n<p>Rather than a bunch of nested conditions:</p>\n\n<pre><code> if (...) {\n if (...) {\n if (...) {\n return authenticationId || [];\n }\n }\n }\n};\n</code></pre>\n\n<p>The logic would probably be easier to follow if, when a condition is <em>not</em> met, handle the problem <em>immediately</em> and return. This way, readers of the code don't have to keep in their head, <em>for every block</em>: \"This block is entered if X condition is reached, so when the block ends, need to remember to handle when X condition isn't reached.\"</p>\n\n<p>Regarding</p>\n\n<pre><code>const response = [\n // ...\n];\nconst authenticationId = await Promise.resolve(response);\n</code></pre>\n\n<p>There's no need to do <code>await Promise.resolve</code> on something - <code>await</code> will unwrap a Promise, and can be used on non-Promises. But since <code>response</code> is an array literal, nothing asynchronous is going on, so there's no reason to <code>await</code> there.</p>\n\n<p>Rather than having <code>login</code> format the row to be returned to the route, and for the route to reformat it again to set to <code>req.session.user</code>, consider taking the row and formatting it as needed for the session <em>just once</em>, reducing superfluous object reorganization.</p>\n\n<p>In full:</p>\n\n<pre><code>// route\nrouter.post(\n '/',\n validationHandler(authenticationSchema),\n async (req, res, next) => {\n const { body } = req;\n if (!body.username && !body.password) {\n next();\n return;\n }\n try {\n const loginResult = await loginService.login(body);\n if (loginResult.errorMessage) {\n res.status(401).json({\n message: loginResult.errorMessage\n });\n return;\n }\n // Login succeeded:\n const { userSession, responseData } = loginResult;\n req.session.user = userSession;\n console.log(\"Session: \", req.session.user);\n res.status(201).json(responseData);\n } catch (err) {\n // Are you sure you want to go to the next route here?\n // If there's an error, maybe respond with status 500 instead\n next(err);\n }\n }\n);\n</code></pre>\n\n<pre><code>// service\n// You can put the constants up here so they don't mix with the main login logic\nconst SECRET_API = config.secretApi;\nconst userQuery = `SELECT usr.id,\n usr.username,\n usr.email,\n usr.hash,\n CONCAT(pple.name, ' ', pple.lastname) AS full_username,\n usr.user_status_id,\n usr.user_type_id\n FROM users usr\n INNER JOIN people pple\n ON pple.id = usr.people_id\n INNER JOIN user_states usts\n ON usts.id = usr.user_status_id\n INNER JOIN user_types utps\n ON utps.id = usr.user_type_id\n WHERE usr.data_status_id = '1'\n AND usr.email = ?`;\nmodule.exports = async ({ username, password }) => {\n const rows = await pool.query(userQuery, [username]);\n if (rows.length === 0) {\n return { errorMessage: 'The user does not exist.' };\n }\n const { id, email, hash, full_username, user_type_id } = rows[0];\n // Compare hash with the plain text password\n const match = await bcrypt.compare(password, hash);\n if (!match) {\n return { errorMessage: 'Wrong password.' };\n }\n //Get the access token\n const token = jwt.sign({ _id: id }, SECRET_API, {\n expiresIn: 60 * 60 * 8\n });\n return {\n responseData: {\n status: 201,\n message:'You are welcome.',\n role: user_type_id,\n token\n },\n userSession: {\n _id: id,\n _username: username,\n _name: full_username,\n _role: user_type_id\n }\n };\n};\n\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T03:43:53.393",
"Id": "241178",
"ParentId": "241070",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "241178",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T13:35:24.120",
"Id": "241070",
"Score": "2",
"Tags": [
"javascript",
"node.js",
"security",
"express.js",
"session"
],
"Title": "Performance and login security for NodeJS using Express with Express-sessions"
}
|
241070
|
<p>While reading an online book (Michael A. Nielsen, Neural Networks and Deep Learning, Determination Press, 2015) regarding neural networks, I decided I wanted to try and build a neural network which does not require a predefined network size, i.e. the layer depth and size are defined by input arguments.</p>
<p>My goal was to make the network object modular, such that different training principles can be appended afterwards. The main is then responsible for calling the modules such that it leads to training, testing or displaying of results.</p>
<p>I have tried programming with OOP concepts in mind. However, I am finding myself struggling with what should be handled by the NeuralNetwork object and is to be handled in Main. On stack overflow it is mentioned that an object should be responsible for all of its affairs, including the in/output. However, where do I draw the line? For instance, the network is responsible for storing and loading of results, yet it is not responsible for reading the parameter file stating the network size to load.</p>
<p>As a fairly inexperienced c++ programmer I welcome any and all insights to improve my skill.</p>
<p>The code is also in GitHub: <a href="https://github.com/vanderboog/mnist-neural-network" rel="nofollow noreferrer">https://github.com/vanderboog/mnist-neural-network</a> </p>
<p>The manual can be found in the GitHub link.</p>
<p><strong>Neural_Network.h</strong></p>
<pre><code>struct CLayer
{
// Declaration of variables used in a each layer
arma::dvec a;
arma::dvec z;
arma::dvec b;
arma::dvec db;
arma::dmat w;
arma::dmat dw;
arma::dvec kD;
};
class NeuralNetwork
{
int numOfLayers_;
int learnSetSize_;
double learnRate_;
double regularization_;
double halfRegularization_;
int learnReductionCycle_;
double learnReductionFactor_;
int iCountEpoch_;
int digit_;
std::string setSavePath_;
//Smart pointers are used to ensure freeing of memory. The pointers are not always used and can therefore not be freed in a destructor
std::unique_ptr<int[]> sizeLayer;
std::unique_ptr<CLayer[]> pLayer;
public:
arma::dvec cost;
NeuralNetwork();
void initializeLayers(int, int *, std::string);
void setHyperParameters(double, double, double);
void layerInfo();
void training(const arma::dmat &, const arma::uvec &);
arma::uvec yVectorGenerator(const arma::uword &);
arma::dvec sigmoid(arma::dvec &);
arma::dvec Dsigmoid(arma::dvec &);
int computePerformance(const arma::dmat &, const arma::uvec &);
int feedForward(const arma::dvec &);
void setLearningReductionParameters(double, int);
void reduceLearnRate(double);
void storeResults();
void loadResults(const std::string &, int, int *);
};
</code></pre>
<p><strong>Neural_Network.cpp</strong></p>
<pre><code>#include <armadillo>
#include <iostream>
#include <memory>
#include <string>
#include "Neural_Network.h"
NeuralNetwork::NeuralNetwork() :
learnSetSize_(100),
learnReductionCycle_(1000),
learnReductionFactor_(1),
learnRate_(0.1),
regularization_(0),
halfRegularization_(regularization_ / 2),
iCountEpoch_(0)
{}
void NeuralNetwork::initializeLayers(int numOfLayers, int *pLayerSize, std::string setSavePath)
{
///////////////////////////////////////////////////////
/// Creates layers and sets component sizes.
/// Layers are initialized ready for training
//////////////////////////////////////////////////////
setSavePath_ = setSavePath;
numOfLayers_ = numOfLayers;
sizeLayer = std::unique_ptr<int[]>(new int[numOfLayers_]);
for (int iLayer = 0; iLayer < numOfLayers_; iLayer++)
{
sizeLayer[iLayer] = pLayerSize[iLayer];
}
/// Create the layers and initialize parameters;
pLayer = std::unique_ptr<CLayer[]>(new CLayer[numOfLayers_]);
pLayer[0].a.set_size(sizeLayer[0]); // Treat first layer different as it does not have b, w, nor kD
for (int iLayer = 1; iLayer < numOfLayers_; iLayer++)
{
// Initialize: matrix and vector sizes
pLayer[iLayer].a.set_size(sizeLayer[iLayer]);
pLayer[iLayer].z.set_size(sizeLayer[iLayer]);
pLayer[iLayer].b = arma::randn(sizeLayer[iLayer]);
pLayer[iLayer].w.set_size(sizeLayer[iLayer], sizeLayer[iLayer - 1]);
pLayer[iLayer].kD.set_size(sizeLayer[iLayer]);
pLayer[iLayer].db = pLayer[iLayer].b;
pLayer[iLayer].dw = pLayer[iLayer].w;
/// Generate gaussian random generated values with standard deviation dependent on layer sizes.
std::default_random_engine generator{static_cast<long unsigned int>(std::chrono::high_resolution_clock::now().time_since_epoch().count())}; // Use high precision time to determine random seed
std::normal_distribution<double> distribution(0.0, sqrt((double)sizeLayer[iLayer - 1])); // Generate random values of with stdev based on incoming layer
for (arma::uword iRow = 0; iRow < sizeLayer[iLayer]; iRow++)
{
for (arma::uword iCol = 0; iCol < sizeLayer[iLayer - 1]; iCol++)
{
pLayer[iLayer].w(iRow, iCol) = distribution(generator);
}
}
}
}
void NeuralNetwork::setHyperParameters(double learnSetSize, double learnRate, double regularization)
{
learnSetSize_ = learnSetSize;
learnRate_ = learnRate;
regularization_ = regularization;
halfRegularization_ = regularization_ / 2;
std::cout << "Hyper parameters settings:\n\t- Learning set size = " << learnSetSize_ << "\n\t- Learning parameter (learnRate_) = " << learnRate_ << "\n\t- Regularization_ parameter (lambda) = " << regularization_ << "\n";
}
void NeuralNetwork::layerInfo()
{
/// Outputs layers information
std::cout << "Number of layers: \t" << numOfLayers_ << "\n";
// std::cout << "Number of neurons in layer 1: \t" << sizeLayer[0] << "\n";
for (int iLayer = 0; iLayer < numOfLayers_; iLayer++)
{
std::cout << "Number of neurons in layer " << iLayer + 1 << ": \t" << sizeLayer[iLayer] << "\n";
}
for (int iLayer = 1; iLayer < numOfLayers_; iLayer++)
{
std::cout << "Weight matrix size (rows by cols) to layer " << iLayer + 1 << ": \t" << pLayer[iLayer].w.n_rows << " x " << pLayer[iLayer].w.n_cols << "\n";
}
}
void NeuralNetwork::training(const arma::dmat &trainingSet, const arma::uvec &trainingLabels)
{
///////////////////////////////////////////////////////
/// Training the neural network by feeding it one epoch
///////////////////////////////////////////////////////
/// Initialize
int numOfCol = trainingSet.n_cols;
int numOfRow = trainingSet.n_rows;
arma::uvec yVector(sizeLayer[numOfLayers_ - 1]);
arma::uvec oneVector(sizeLayer[numOfLayers_ - 1], arma::fill::ones);
arma::uvec sampleStack_i = arma::randperm(numOfCol);
/// Reduce learnRate_ if -reduceLearnRate is used
if(iCountEpoch_ % learnReductionCycle_ == 0 && iCountEpoch_ != 0)
{
reduceLearnRate(learnReductionFactor_);
}
int numOfCyclesPerEpoch = numOfCol / learnSetSize_; // Compute amount of cycles making up one epoch and only loop over complete cycles, omitting remaining samples
/// Cycle through the epoch and apply learning after each cycle
cost = arma::zeros(numOfCyclesPerEpoch);
for (int iCycle = 0; iCycle < numOfCyclesPerEpoch; iCycle++)
{
int iSampleOffset = iCycle * learnSetSize_;
/// Set dw and db to zero before each cycle
for (int iLayer = 1; iLayer < numOfLayers_; iLayer++)
{
pLayer[iLayer].db.zeros(pLayer[iLayer].db.n_rows, pLayer[iLayer].db.n_cols);
pLayer[iLayer].dw.zeros(pLayer[iLayer].dw.n_rows, pLayer[iLayer].dw.n_cols);
}
for (int iSample = 0; iSample < learnSetSize_; iSample++)
{
/// Load the image and create label vector (yVector)
pLayer[0].a = trainingSet.col(sampleStack_i(iSample + iSampleOffset));
yVector = yVectorGenerator(trainingLabels(sampleStack_i(iSample + iSampleOffset)));
/// Feed forward
digit_ = feedForward(pLayer[0].a);
/// Compute cost (-= is used instead of -1*)
cost[iCycle] -= as_scalar(trans(yVector) * log(pLayer[numOfLayers_ - 1].a) + trans(oneVector - yVector) * log(oneVector - pLayer[numOfLayers_ - 1].a));
/// Add regularization_ term:
if (regularization_ != 0) // Skip overhead computation in case of 0
{
for (int iLayer = 1; iLayer < numOfLayers_; iLayer++)
{
cost[iCycle] += halfRegularization_ * accu(pLayer[iLayer].w % pLayer[iLayer].w); //Expensive
}
}
/// Back propagation
/// Compute error terms: dC/dz
pLayer[numOfLayers_ - 1].kD = pLayer[numOfLayers_ - 1].a - yVector;
for (int iLayer = numOfLayers_ - 2; iLayer > 0; iLayer--)
{
pLayer[iLayer].kD = pLayer[iLayer + 1].w.t() * pLayer[iLayer + 1].kD % Dsigmoid(pLayer[iLayer].z);
}
/// Compute gradient descent of w and b (seperate loop for clarity)
for (int iLayer = 1; iLayer < numOfLayers_; iLayer++)
{
pLayer[iLayer].dw += arma::kron(pLayer[iLayer].kD, pLayer[iLayer - 1].a.t());
pLayer[iLayer].db += pLayer[iLayer].kD;
}
}
/// Apply gradient descent on w and b
for (int iLayer = 1; iLayer < numOfLayers_; iLayer++)
{
pLayer[iLayer].w -= learnRate_ * (pLayer[iLayer].dw + regularization_ * pLayer[iLayer].w) / learnSetSize_; // with regularization_ term
pLayer[iLayer].b -= learnRate_ * pLayer[iLayer].db / learnSetSize_;
}
cost = cost / learnSetSize_;
}
iCountEpoch_++;
}
arma::uvec NeuralNetwork::yVectorGenerator(const arma::uword &label)
{
/// Generates a vector representation of the label: vector of zeros, with at the labelth index a 1
arma::uvec y = arma::zeros<arma::uvec>(sizeLayer[numOfLayers_ - 1]);
y(label) = 1;
return y;
}
arma::dvec NeuralNetwork::sigmoid(arma::dvec &z)
{
return 1 / (1 + exp(-z));
}
arma::dvec NeuralNetwork::Dsigmoid(arma::dvec &z)
{
arma::dvec dS = sigmoid(z);
return (dS % (1 - dS)); // %: Schur product, i.e. element-wise product
}
int NeuralNetwork::computePerformance(const arma::dmat &testSet, const arma::uvec &testLabels)
{
////////////////////////////////////////////
/// Compute network performance based on the test set
////////////////////////////////////////////
int iCountCorrect = 0;
int sizeSet = testSet.n_cols;
for (int iSample = 0; iSample < sizeSet; iSample++)
{
// Load testimage & apply feedforward. Count the correct answers
if (feedForward(testSet.col(iSample)) == testLabels(iSample))
{
iCountCorrect++;
}
}
std::cout << "Performance: " << iCountCorrect << " / " << sizeSet << "\n";
return iCountCorrect;
}
int NeuralNetwork::feedForward(const arma::dvec &imVector)
{
/// Apply feedforward to determine and return the network answer
pLayer[0].a = imVector;
for (int iLayer = 1; iLayer < numOfLayers_; iLayer++)
{
pLayer[iLayer].z = pLayer[iLayer].w * pLayer[iLayer - 1].a + pLayer[iLayer].b;
pLayer[iLayer].a = sigmoid(pLayer[iLayer].z);
}
return pLayer[numOfLayers_ - 1].a.index_max();
}
void NeuralNetwork::setLearningReductionParameters(double learnReductionFactor, int learnReductionCycle)
{
learnReductionFactor_ = learnReductionFactor;
learnReductionCycle_ = learnReductionCycle;
std::cout << "Learning rate reduction factor: " << learnReductionFactor_ << "\n";
std::cout << "Learning rate reduction cycle: " << learnReductionCycle_ << "\n";
}
void NeuralNetwork::reduceLearnRate(double factor)
{
learnRate_ = learnRate_ / factor;
std::cout << "learnRate_ reduced to:\t" << learnRate_ << "\n";
}
void NeuralNetwork::storeResults()
{
/// Store essential parameters of the network: weights and biases
for (int iLayer = 1; iLayer < numOfLayers_; iLayer++)
{
pLayer[iLayer].w.save(setSavePath_ + "/w" + std::to_string(iLayer + 1));
pLayer[iLayer].b.save(setSavePath_ + "/b" + std::to_string(iLayer + 1));
}
}
void NeuralNetwork::loadResults(const std::string &setSavePath, int numOfLayers, int *layerSize)
{
setSavePath_ = setSavePath;
numOfLayers_ = numOfLayers;
/// Load the actual stored data
for (int iLayer = 1; iLayer < numOfLayers_; iLayer++)
{
std::cout << "Loading file: " << (setSavePath_ + "/w" + std::to_string(iLayer + 1)) << "\n";
pLayer[iLayer].w.load(setSavePath_ + "/w" + std::to_string(iLayer + 1));
std::cout << "Loading file: " << (setSavePath_ + "/b" + std::to_string(iLayer + 1)) << "\n";
pLayer[iLayer].b.load(setSavePath_ + "/b" + std::to_string(iLayer + 1));
}
layerInfo();
}
</code></pre>
<p><strong>Main.cpp</strong></p>
<pre><code>#include <armadillo>
#include <boost/filesystem.hpp>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <memory>
#include <opencv2/highgui.hpp>
#include <random>
#include <string>
#include "Neural_Network.h"
#include "ReadMNIST.h"
#include "Visualization.h"
std::string setPathSave(std::string const setPath)
{
/// Make sure Result_Network directory exists
if (!boost::filesystem::exists(setPath))
{
boost::filesystem::create_directory(setPath);
}
/// Set save path to a unique path of 'Results_##', found by incrementing from 1
/// to 32. If the full range is used, the save path is set to 'Result_32'
std::string setSavePath;
for (int iFolder = 1; iFolder < 33; iFolder++)
{
setSavePath = setPath + "/Results_" + std::to_string(iFolder);
if (!boost::filesystem::exists(setSavePath))
{
boost::filesystem::create_directory(setSavePath);
break;
}
}
std::cout << "Save path is set to: " << setSavePath << "\n";
return setSavePath;
}
void showUsage()
{
std::cout << std::left << std::setw(92) << "Options available in this program:" << std::endl;
std::cout << std::setw(2) << "" << std::setw(18) << "-train" << std::setw(72) << "Train a new neural network. This mode requires the training set and " << std::endl;
std::cout << std::setw(20) << "" << std::setw(72) << "labels. See training options below for more details." << std::endl;
std::cout << std::setw(2) << "" << std::setw(18) << "-test" << std::setw(72) << "Test a trained network. This mode requires a trained network stored in " << std::endl;
std::cout << std::setw(20) << "" << std::setw(72) << "Results_Network and the test set. After '-test' refer to the folder " << std::endl;
std::cout << std::setw(20) << "" << std::setw(72) << "containing the results by the trailing number in the folder name, e.g." << std::endl;
std::cout << std::setw(20) << "" << std::setw(72) << "'-test 1' to test the network in 'Network_Results/Results_1'. See test " << std::endl;
std::cout << std::setw(20) << "" << std::setw(72) << "options below for more details.\n"
<< std::endl;
std::cout << std::left << std::setw(92) << "Training options: " << std::endl;
std::cout << std::setw(2) << "" << std::setw(18) << "-layers" << std::setw(72) << "Set the total amount of layers and layer sizes used in the network," << std::endl;
std::cout << std::setw(20) << "" << std::setw(72) << "including the input and output layer. After '-layers', the total number" << std::endl;
std::cout << std::setw(20) << "" << std::setw(72) << "of layers is required. Thereafter, the layer size should be given in" << std::endl;
std::cout << std::setw(20) << "" << std::setw(72) << "curly brackets, e.g. 'layers 3 {784,30,10}'." << std::endl;
std::cout << std::setw(2) << "" << std::setw(18) << "-param" << std::setw(72) << "Set learning hyperparameters. Parameters which are to be set are: batch" << std::endl;
std::cout << std::setw(20) << "" << std::setw(72) << "size before learning step, learning rate, and the regularization" << std::endl;
std::cout << std::setw(20) << "" << std::setw(72) << "parameter, respectively. In case no regularization is to be used, the" << std::endl;
std::cout << std::setw(20) << "" << std::setw(72) << "parameter is to be set to zero, e.g, '-param {1000,0.1,0}'" << std::endl;
std::cout << std::setw(2) << "" << std::setw(18) << "-reduceLearning" << std::setw(72) << "Used to reduce the learning parameter by {factor x, per y epoch}," << std::endl;
std::cout << std::setw(20) << "" << std::setw(72) << "e.g. -reduceLearning {2,20}.\n"
<< std::endl;
std::cout << std::left << std::setw(92) << "Test options:" << std::endl;
std::cout << std::setw(2) << "" << std::setw(18) << "-display" << std::setw(72) << "Opens a window to visualize the test images in a random sequence." << std::endl;
std::cout << std::setw(20) << "" << std::setw(72) << "Visualization can be stopped by pressing <q>." << std::endl;
}
int main(int argc, const char **argv)
{
/// Test if sufficient arguments are given
if (argc < 2)
{
std::cerr << "No arguments are given. Use --help to show options.\nTerminating program." << std::endl;
return 1;
}
/// Initialize paths
std::string const setPath = getCurrentDir(); // part of "readmnist.h"
std::string const setPathTrainingImages = setPath + "/../Training_images/train-images.idx3-ubyte";
std::string const setPathTrainingLabels = setPath + "/../Training_images/train-labels.idx1-ubyte";
std::string const setPathTestImages = setPath + "/../Test_images/t10k-images.idx3-ubyte";
std::string const setPathTestLabels = setPath + "/../Test_images/t10k-labels.idx1-ubyte";
std::string const setPathResults = setPath + "/../Results_Network";
NeuralNetwork network;
/// Interpret if program is used for training or testing
if (std::string(argv[1]) == "-train")
{
/// Determine path to store results:
std::string setSavePath = setPathSave(setPathResults);
/// Store file containing input arguments:
std::ofstream outputFile;
outputFile.open(setSavePath + "/Input_parameters");
for (int iArgv = 2; iArgv < argc + 1; iArgv++)
{
outputFile << argv[iArgv] << "\t";
}
outputFile.close();
// Cycle through arguments given and apply settings to the neural network
for (int iArgc = 2; iArgc < argc; iArgc++)
{
if (std::string(argv[iArgc]) == "-layers")
{
/// Used to set the layers of the neural network.
/// The first trailing argument should be the amount of layers. Subsequent the layer sizes are to be given in seperate arguments,
/// starting from the input layer, up to the output layer. E.g. '-layers 3 {784,30,10}'
int *pLayers = new int[atoi(argv[iArgc + 1])];
std::cout << "Layers found: \n";
for (int iLayer = 0; iLayer < atoi(argv[iArgc + 1]); iLayer++)
{
pLayers[iLayer] = atoi(argv[iArgc + 2 + iLayer]);
std::cout << pLayers[iLayer] << "\t";
}
std::cout << "\n";
network.initializeLayers(atoi(argv[iArgc + 1]), pLayers, setSavePath);
delete[] pLayers;
network.layerInfo();
iArgc += atoi(argv[iArgc + 1]) + 1;
}
else if (std::string(argv[iArgc]) == "-param")
{
/// Used to set hyperparameters directly related to learning { samplesize before learning, eta (learning rate), lambda (regulatization)}
network.setHyperParameters(atof(argv[iArgc + 1]), atof(argv[iArgc + 2]), atof(argv[iArgc + 3]));
iArgc += 3;
}
else if (std::string(argv[iArgc]) == "-reduceLearning")
{
/// Use to reduce learning rate at given intervals. Parameter order: { reduction factor, after # cycles }
network.setLearningReductionParameters(atof(argv[iArgc + 1]), atoi(argv[iArgc + 2]));
iArgc += 2;
}
else
{
std::cerr << "The argument '" << argv[iArgc] << "' is unknown to the program. Use --help to show viable options." << std::endl;
return 2;
}
}
/// Load data for training:
std::cout << "Loading data...\n";
// Reads images and returns a matrix(pxValue, numOfImages)
arma::dmat const trainingSet = readMnistImages(setPathTrainingImages);
arma::uvec const trainingLabels = readMnistLabels(setPathTrainingLabels, trainingSet.n_cols);
// Read test images to determine the score
arma::dmat const testSet = readMnistImages(setPathTestImages);
arma::uvec const testLabels = readMnistLabels(setPathTestLabels, testSet.n_cols);
/// Start training:
int iCountScore = 0;
int iEpocheCount = 0;
while (iEpocheCount < 70)
{
// Perform a training cycle (one epoche)
network.training(trainingSet, trainingLabels);
iEpocheCount += 1;
std::cout << "Epoche counter: " << iEpocheCount << "\t\tAverage cost: " << arma::mean(network.cost) << "\n";
iCountScore = network.computePerformance(testSet, testLabels);
/// Store results every epoche
network.storeResults();
}
}
else if (std::string(argv[1]) == "-test")
{
/// Load test files
std::cout << "Loading data...\n";
arma::dmat const testSet = readMnistImages(setPathTestImages);
arma::uvec const testLabels = readMnistLabels(setPathTestLabels, testSet.n_cols);
/// Read parameters from parameter file
std::ifstream inFile;
std::string const setPathToLoad = setPathResults + "/Results_" + argv[2] + "/Input_parameters";
inFile.open(setPathToLoad);
if (inFile.is_open())
{
/// Read parameters to determine set correct network size
int numOfLayers;
int *pLayer;
std::string arg;
while (inFile >> arg)
{
if (arg == "-layers")
{
inFile >> arg;
numOfLayers = stoi(arg);
pLayer = new int[numOfLayers];
for (int iLayer = 0; iLayer < numOfLayers; iLayer++)
{
inFile >> arg;
pLayer[iLayer] = stoi(arg);
}
/// Initialize weights and biases sizes and load results
network.initializeLayers(numOfLayers, pLayer, setPathResults + "/Results_" + argv[2]);
network.loadResults(setPathResults + "/Results_" + argv[2], numOfLayers, pLayer);
}
}
/// Compute and output the score
network.computePerformance(testSet, testLabels);
inFile.close();
delete[] pLayer;
}
else
{
std::cerr << "Unable to open a result file: " << setPathToLoad << std::endl;
return 3;
}
// Cycle through arguments given and apply settings
for (int iArgc = 3; iArgc < argc; iArgc++)
{
if (std::string(argv[iArgc]) == "-display")
{
/// Display results in random order
arma::arma_rng::set_seed(std::chrono::high_resolution_clock::now().time_since_epoch().count());
arma::uvec sequence = arma::randperm(testSet.n_cols);
int digit;
std::string strDigit;
int countDisplays = 0;
arma::Mat<double> imArma;
for (arma::uword iSequence : sequence)
{
/// Run a sample through the network and obtain result
digit = -1;
digit = network.feedForward(testSet.col(iSequence));
strDigit = std::to_string(digit);
/// Reshape the image vector into a matrix and convert to openCV format
imArma = reshape(round(testSet.col(iSequence) * 256), 28, 28);
cv::Mat imDigit(28, 28, CV_64FC1, imArma.memptr());
/// Display the sample image with the networks answer
displayImage(imDigit, strDigit);
countDisplays++;
/// Give option to end the program
if (cv::waitKey(3000) == 'q')
{
break;
};
}
}
else
{
std::cerr << "The argument '" << argv[iArgc] << "' is unknown to the program. Use --help to show viable options." << std::endl;
return 2;
}
}
}
else if (std::string(argv[1]) == "--help")
{
showUsage();
}
else
{
std::cerr << "The argument " << argv[1] << " is unknown to this program. Use --help to show viable options." << std::endl;
return 2;
}
return 0;
}
</code></pre>
<p><strong>ReadMNIST.h</strong></p>
<pre><code>arma::dmat readMnistImages( std::string);
arma::uvec readMnistLabels( std::string, arma::uword );
std::string getCurrentDir();
</code></pre>
<p><strong>ReadMNIST.cpp</strong></p>
<pre><code>#include <armadillo>
#include <iostream>
#include <string>
#include "ReadMNIST.h"
#ifdef WINDOWS
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif
// Miscellaneous function
int reverseInt(int iSample)
{
unsigned char ch1, ch2, ch3, ch4;
ch1 = iSample & 255;
ch2 = (iSample >> 8) & 255;
ch3 = (iSample >> 16) & 255;
ch4 = (iSample >> 24) & 255;
return ((int)ch1 << 24) + ((int)ch2 << 16) + ((int)ch3 << 8) + ch4;
}
// Return a matrix containing the trainingset images. Format: (numOfImages, pxValue)
arma::dmat readMnistImages(std::string setPath)
{
arma::umat imSet;
std::ifstream file(setPath, std::ios::binary);
if (file.is_open())
{
int magicNumber = 0;
int numOfImages = 0;
int imRows = 0;
int imCols = 0;
file.read((char *)&magicNumber, sizeof(magicNumber));
magicNumber = reverseInt(magicNumber);
file.read((char *)&numOfImages, sizeof(numOfImages));
numOfImages = reverseInt(numOfImages);
file.read((char *)&imRows, sizeof(imRows));
imRows = reverseInt(imRows);
file.read((char *)&imCols, sizeof(imCols));
imCols = reverseInt(imCols);
std::cout << "Images in the set: " << numOfImages << "\n";
std::cout << "Image size: " << imRows << "*" << imCols << "\n";
imSet.resize(numOfImages, imRows * imCols);
for (int i = 0; i < numOfImages; ++i)
{
for (int r = 0; r < (imRows * imCols); ++r)
{
unsigned char input = 0;
file.read((char *)&input, sizeof(input));
imSet(i, r) = (double)input;
}
}
}
return (arma::conv_to<arma::dmat >::from(imSet.t())/256);
}
// Return a column containing the labels per image
arma::uvec readMnistLabels(std::string setPath, arma::uword numOfLabels)
{
arma::uvec labelVector(numOfLabels);
std::cout << "Number of labels: " << numOfLabels << "\n\n";
std::ifstream file(setPath, std::ios::binary);
if (file.is_open())
{
int magicNumber = 0;
int numOfLabels = 0;
file.read((char *)&magicNumber, sizeof(magicNumber));
magicNumber = reverseInt(magicNumber);
file.read((char *)&numOfLabels, sizeof(numOfLabels));
numOfLabels = reverseInt(numOfLabels);
for (int iSample = 0; iSample < numOfLabels; ++iSample)
{
unsigned char input = 0;
file.read((char *)&input, sizeof(input));
labelVector(iSample) = (double)input;
}
}
return labelVector;
}
std::string getCurrentDir() {
char buff[FILENAME_MAX]; //create string buffer to hold path
GetCurrentDir( buff, FILENAME_MAX );
std::string currentWorkingDir(buff);
return currentWorkingDir;
}
</code></pre>
<p><strong>Visualization.h</strong></p>
<pre><code>void displayImage( const cv::Mat &, const std::string );
</code></pre>
<p><strong>Visualization.cpp</strong></p>
<pre><code>#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
void displayImage(const cv::Mat &im, const std::string strDigit)
{
////////////////////////////////////////////////////////////////////////////////////////////
/// Scales the image into readable size and prints the network result onto image
////////////////////////////////////////////////////////////////////////////////////////////
cv::Mat imScaled;
cv::resize(im, imScaled, cv::Size(280, 280));
// Write digit label on image
cv::putText(imScaled,
strDigit,
cv::Point(5, 20), // Coordinates
cv::FONT_HERSHEY_COMPLEX_SMALL, // Font
1.0, // Scale. 2.0 = 2x bigger
cv::Scalar(255, 0, 0), // BGR Color
1); // Line Thickness (Optional)
/// Write required action to close the program
cv::putText(imScaled,
"Press <q> to close",
cv::Point(5, 275), // Coordinates
cv::FONT_HERSHEY_COMPLEX_SMALL, // Font
0.5, // Scale. 2.0 = 2x bigger
cv::Scalar(255, 0, 0), // BGR Color
1); // Line Thickness (Optional)
cv::imshow("Test image", imScaled);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T17:24:22.420",
"Id": "473052",
"Score": "0",
"body": "Are the header files complete, or have the top and bottom of those files been excluded from the review?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T07:09:11.150",
"Id": "473903",
"Score": "0",
"body": "The header files are complete as is. I did not remove any lines at the top nor bottom of the files."
}
] |
[
{
"body": "<p>This is all subjective:</p>\n<p>But I would prefer if the constructor set up the NeuralNet and was ready to go. Once the object there is no need to call extra functions like <code>initializeLayers()</code> or <code>setHyperParameters()</code> or <code>setLearningReductionParameters()</code> these should all be things that are done as part of construction.</p>\n<p>This implies that you need some form of config object (as these parameters seem complex) that you crete first that can be passed to the constructor of the <code>NeuralNet</code>. This config object could potentially be able to read and load its own state from a config file.</p>\n<pre><code> NeuralNetConfig config;\n // 1. Read default config from default config file.\n // 2. Add extra values to config from command line arguments.\n\n // When you are ready to go:\n NeuralNet net(config);\n</code></pre>\n<p>This also covers one of your concenrs:</p>\n<blockquote>\n<p>yet it is not responsible for reading the parameter file stating the network size to load</p>\n</blockquote>\n<hr />\n<blockquote>\n<p>an object should be responsible for all of its affairs, including the in/output.</p>\n</blockquote>\n<p>There are two types of objects.</p>\n<ul>\n<li>One that handles business logic.<br />\nIn your case the logic of the NeuralNet.</li>\n<li>Another type of object handlers resource management.<br />\nIn most cases this is memory management (this is things like std::vector).</li>\n</ul>\n<p>Your object should fall into one of these two broad categories. If your object is mixing business logic and resource management then you need to consider why and can we easily split these apart.</p>\n<p>In terms of Input/Output you can consider this part of the "business" logic or you can potentially delegate this to another class that understands this (its one of those grey areas).</p>\n<hr />\n<blockquote>\n<p>However, where do I draw the line? For instance, the network is responsible for storing and loading of results</p>\n</blockquote>\n<p>Yes (or maybe with the help of a delegate). But it should not be responsible for where it stores the results (this should be passed to the class). i.e. if you save the data to a file your class is not responsible for selecting or opening the file it will be passed an open file stream object onto which it can save the state.</p>\n<hr />\n<h3>Code Review:</h3>\n<pre><code>//Smart pointers are used to ensure freeing of memory. The pointers are not always used and can therefore not be freed in a destructor\nstd::unique_ptr<int[]> sizeLayer;\nstd::unique_ptr<CLayer[]> pLayer;\n</code></pre>\n<p>Getting dangerously close to resource management. Also why are these not <code>std::vector<></code> objects? Looking through the code these should definitely be <code>std::vector<></code> objects.</p>\n<hr />\n<p>Nice to put the parameters "names" in here. It helps in that little thing of "Self Documenting Code".</p>\n<pre><code>void initializeLayers(int, int *, std::string);\nvoid setHyperParameters(double, double, double);\nvoid layerInfo();\nvoid training(const arma::dmat &, const arma::uvec &);\narma::uvec yVectorGenerator(const arma::uword &);\narma::dvec sigmoid(arma::dvec &);\narma::dvec Dsigmoid(arma::dvec &);\nint computePerformance(const arma::dmat &, const arma::uvec &);\nint feedForward(const arma::dvec &);\nvoid setLearningReductionParameters(double, int);\nvoid reduceLearnRate(double);\nvoid storeResults();\nvoid loadResults(const std::string &, int, int *);\n</code></pre>\n<hr />\n<p>Why are you passing a string by value here?</p>\n<pre><code>void initializeLayers(int, int *, std::string);\n</code></pre>\n<hr />\n<p>Why are you passing a pointer here?</p>\n<pre><code>void initializeLayers(int, int *, std::string);\n</code></pre>\n<p>Pointers are exceedingly rare in modern C++ (unless you are building some low level resource management object like a vector). The problem with pointers is that they do not convey ownership semantics and thus it is easy to leak or accidentally destroy something (ie. they are buggy to use).</p>\n<p>When I look at the code that uses this I see it is very inefficient and dangerously written:</p>\n<pre><code> int *pLayers = new int[atoi(argv[iArgc + 1])];\n\n // FILL IN pLayers\n network.initializeLayers(atoi(argv[iArgc + 1]), pLayers, setSavePath);\n delete[] pLayers;\n</code></pre>\n<p>The trouble is that you will leak that array if <code>initializeLayers()</code> throws an exception (and thus skips the delete). Inside the function you do the same thing (but at least assign it to smart pointer to prevent leaking).</p>\n<pre><code>// Allocate \nsizeLayer = std::unique_ptr<int[]>(new int[numOfLayers_]);\n// And now copy.\nfor (int iLayer = 0; iLayer < numOfLayers_; iLayer++)\n{\n sizeLayer[iLayer] = pLayerSize[iLayer];\n}\n</code></pre>\n<p>By using vectors to do the resource management you can make your code a lot simpler and efficient.</p>\n<pre><code> int countOfPlaters = atoi(argv[iArgc + 1]);\n std::vector<int> pLayers(countOfPlaters);\n // FILL IN pLayers\n \n network.initializeLayers(countOfPlaters, std::move(pLayers), setSavePath);\n</code></pre>\n<p>Now define the interface like this:</p>\n<pre><code>void initializeLayers(int, std::vector<int>&& players, std::string);\n</code></pre>\n<p>Inside the function to get a copy of the vector you simply do this:</p>\n<pre><code> sizeLayer = std::move(players); // Note: sizeLayer is now declared std::vector<int>\n</code></pre>\n<p>This will effeciently move the data inside the vector without having to copy the whole vector. Memory is handeled even in exceptional cases and you have written less code.</p>\n<hr />\n<p>If your method does not change the state of the object then it should be marked <code>const</code>. I am betting that this function does not change the state of the object.</p>\n<pre><code>void layerInfo();\n</code></pre>\n<hr />\n<p>Again using a pointer parameter.</p>\n<pre><code>void loadResults(const std::string &, int, int *);\n</code></pre>\n<p>Looking at the code this should be replaced by a <code>std::vector</code>.</p>\n<hr />\n<p>Why are you doing this here?</p>\n<pre><code> // Initialize: matrix and vector sizes\n pLayer[iLayer].a.set_size(sizeLayer[iLayer]);\n pLayer[iLayer].z.set_size(sizeLayer[iLayer]);\n pLayer[iLayer].b = arma::randn(sizeLayer[iLayer]);\n pLayer[iLayer].w.set_size(sizeLayer[iLayer], sizeLayer[iLayer - 1]);\n pLayer[iLayer].kD.set_size(sizeLayer[iLayer]);\n pLayer[iLayer].db = pLayer[iLayer].b;\n pLayer[iLayer].dw = pLayer[iLayer].w;\n</code></pre>\n<p>This should be in the constructor of <code>CLayer</code>.</p>\n<hr />\n<p>This is a bad place to <code>default_random_engine</code>.</p>\n<pre><code>for (int iLayer = 1; iLayer < numOfLayers_; iLayer++)\n{\n\n // STUFF\n\n std::default_random_engine generator{static_cast<long unsigned int>(std::chrono::high_resolution_clock::now().time_since_epoch().count())}; // Use high precision time to determine random seed\n\n std::normal_distribution<double> distribution(0.0, sqrt((double)sizeLayer[iLayer - 1])); \n}\n</code></pre>\n<p>The random number generators can be very expensive to initialize (as they can potentially hold a lot of state). You are supposed to initialize this once and re-use it as much as possible (then you would not need to use a high resolution timer to make it work). Just move this outside the loop and re-use for all your random numbers.</p>\n<p>I would even move this into main and pass the random number generator as a parameter into the constructor to be re-used.</p>\n<p>Note: During debugging it is useful to <strong>not</strong> have random numbers. To find a bug you may want to seed the generator with a known value so that you can set up the state as it was when you discovered a bug.</p>\n<p>I always dump the seed into a log file. Also I allow the user to specify the seed at the command line so that I can reproduce an earlier run with the exact same input. Also for debugging this means having a single random number generator for the whole application makes things like debugging easier.</p>\n<hr />\n<p>Also worth noting you can add a code review badge to your github readme.md file:</p>\n<pre><code>[](http://codereview.stackexchange.com/q/241074)\n\n \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-30T07:07:22.667",
"Id": "473902",
"Score": "0",
"body": "Thanks for the review and the answer to my question. It is much appreciated! I am implementing the suggested method of using a config object and all other review comments. The code is not yet finished, but will be visible via the github link once its finished."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T17:19:36.870",
"Id": "241086",
"ParentId": "241074",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "241086",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T14:32:25.730",
"Id": "241074",
"Score": "3",
"Tags": [
"c++",
"object-oriented",
"neural-network"
],
"Title": "MNIST Neural network in C++"
}
|
241074
|
<p>I have implemented a queue by using a stack data structure. How could I improve it?</p>
<pre><code>package _amazonAskedQuestions.dataStructures;
import java.util.Iterator;
import java.util.Stack;
public class Queue_Stack<T> implements Iterable<T>{
Stack<T> stack = new Stack<>();
public void enqueue(T item){
Stack<Integer> temp = new Stack<Integer>();
while(!stack.empty()){
temp.push((Integer) stack.pop());
}
stack.push(item);
while(!temp.empty()){
stack.push((T) temp.pop());
}
}
public T dequeue(){
return stack.pop();
}
@Override
public Iterator<T> iterator() {
return (Iterator<T>) stack.lastElement();
}
public static void main(String args[]){
Queue_Stack<Integer> qs = new Queue_Stack<>();
qs.enqueue(9);
qs.enqueue(8);
qs.enqueue(1);
qs.enqueue(3);
qs.enqueue(4);
qs.enqueue(5);
System.out.println( qs.dequeue());
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Your <code>Queue_Stack</code> only works with <code>Integer</code>. I tried using <code>String</code> and got a <code>ClassCastException</code>.</p>\n\n<p>I made some modifications to your code. I added a test to make sure you don't get an error if you dequeue more than you enqueue. I used the underlying iterator to get rid of the temp <code>Stack</code>.</p>\n\n<pre><code>import java.util.Iterator;\nimport java.util.Optional;\nimport java.util.Stack;\n\npublic class Queue_Stack<T> implements Iterable<T> {\n\n Stack<T> stack = new Stack<>();\n\n public void enqueue(T item) {\n stack.push(item);\n }\n\n public Optional<T> dequeue() {\n if (!stack.empty()) {\n T item = stack.iterator().next();\n stack.remove(0);\n return Optional.of(item);\n } else {\n return Optional.empty();\n }\n }\n\n @Override\n public Iterator<T> iterator() {\n return (Iterator<T>) stack.iterator();\n }\n\n public static void main(String args[]) {\n Queue_Stack<String> qs = new Queue_Stack<>();\n\n qs.enqueue(\"zeta\");\n qs.enqueue(\"alpha\");\n qs.enqueue(\"beta\");\n qs.enqueue(\"gamma\");\n\n Iterator<String> iter = qs.iterator();\n while (iter.hasNext()) {\n System.out.println(iter.next());\n }\n\n System.out.println(qs.dequeue());\n System.out.println(qs.dequeue());\n System.out.println(qs.dequeue());\n System.out.println(qs.dequeue());\n System.out.println(qs.dequeue());\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T15:43:43.647",
"Id": "241080",
"ParentId": "241075",
"Score": "2"
}
},
{
"body": "<p>Gilbert Le Blanc's <a href=\"https://codereview.stackexchange.com/a/241080/203649\">answer</a> already covered all the aspects of your question, I'm adding just one consideration\nabout the <code>Stack</code> class from <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Stack.html\" rel=\"nofollow noreferrer\">documentation</a>:</p>\n\n<pre><code>A more complete and consistent set of LIFO stack operations is provided by the Deque interface and its implementations, which should be used in preference to this class. \n</code></pre>\n\n<p>So instead of a <code>Stack</code> instance <code>stack</code> in your code you should consider to use :</p>\n\n<pre><code>Deque<T> stack = new ArrayDeque<>();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T08:55:28.490",
"Id": "241123",
"ParentId": "241075",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "241080",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T14:45:20.997",
"Id": "241075",
"Score": "2",
"Tags": [
"java",
"stack",
"queue"
],
"Title": "Queue By Using Stack"
}
|
241075
|
<p>To get a feel of Monty Hall problem, I've implemented Monty Hall simulator in Python, using only two strategies: never switch the door or always switch the door. Please review it with an eye towards any problem with the code you can think of, things like better design, flaws in code, etc.</p>
<pre><code>#!/usr/bin/env python3
import random
import sys
def available_doors():
return [1, 2, 3]
class MontyHallBox(object):
def __init__(self):
self.__doors = {1: None, 2: None, 3: None}
self.__init_doors()
def reinitialize(self):
self.__init_doors()
def __init_doors(self):
self.__doors = {n: 'goat' for n in range(1, 4)}
car = random.choice(available_doors())
self.__doors[car] = 'car'
def _get_rand_doornum_item(self):
door_num = random.choice(available_doors())
item = self.__doors[door_num]
return door_num, item
def reveal_noncar(self, initial_door):
door_num, item = self._get_rand_doornum_item()
while item == 'car' or door_num == initial_door:
door_num, item = self._get_rand_doornum_item()
return door_num
def reveal_selected(self, door):
return self.__doors[door]
def run_sim_always_switch(mhb):
mhb.reinitialize()
initial_door = random.choice(available_doors())
noncar_door = mhb.reveal_noncar(initial_door)
switch_door_set = set(available_doors()) - set([initial_door, noncar_door])
switch_door = list(switch_door_set)[0]
item = mhb.reveal_selected(switch_door)
if item == 'car':
return 'success'
return 'fail'
def run_sim_never_switch(mhb):
mhb.reinitialize()
initial_door = random.choice(available_doors())
# this is pointless really as this info is not used by game participant
_ = mhb.reveal_noncar(initial_door)
item = mhb.reveal_selected(initial_door)
if item == 'car':
return 'success'
return 'fail'
def run_simn(num, simn_fun):
mhb = MontyHallBox()
results = []
for i in range(num):
results.append(simn_fun(mhb))
successes = len(list(filter(lambda x: x == 'success', results)))
return successes / num
def main():
num = 10000
if num < 1:
print('Simulation has to be ran at least 1 time')
sys.exit(1)
print('Always switch, run simulation {} times.'.format(num))
print('Success ratio: {}'.format(run_simn(num, run_sim_always_switch)))
print()
print('Never switch, run simulation {} times.'.format(num))
print('Success ratio: {}'.format(run_simn(num, run_sim_never_switch)))
if __name__ == '__main__':
main()
</code></pre>
|
[] |
[
{
"body": "<h1>Available doors</h1>\n\n<p>Why is this a stand-alone function? Why are door identifiers hard-coded here? The <code>MontyHallBox</code> knows what the doors are, and what they are called:</p>\n\n<pre><code>class MontyHallBox(object):\n def available_doors(self):\n return list(self.__doors.keys())\n</code></pre>\n\n<h1>Class Syntax</h1>\n\n<pre><code>class MontyHallBox(object):\n ...\n</code></pre>\n\n<p>is obsolete syntax. Use:</p>\n\n<pre><code>class MontyHallBox:\n ...\n</code></pre>\n\n<h1>Class Private Names</h1>\n\n<p>Why use a double underscore for <code>self.__doors</code> and <code>self.__init_doors()</code>? This is a Python feature for avoiding name collision in derived classes, and \"mangles\" the names is a predictable fashion (adding the classname as a prefix):</p>\n\n<pre><code>>>> mhb = MontyHallBox()\n>>> mhb._MontyHallBox__doors\n{1: 'car', 2: 'goat', 3: 'goat'}\n>>> \n</code></pre>\n\n<p>It does not provide any extra security of the member.</p>\n\n<h1>Use set notation</h1>\n\n<p>Instead of <code>set([initial_door, noncar_door])</code>, write <code>{initial_door, noncar_door}</code>.</p>\n\n<h1>Throw-away variables</h1>\n\n<p>The variable <code>i</code> is never used:</p>\n\n<pre><code> for i in range(num):\n results.append(simn_fun(mhb))\n</code></pre>\n\n<p>The PEP-8 recommendation is to use <code>_</code> for these throw-away variables:</p>\n\n<pre><code> for _ in range(num):\n results.append(simn_fun(mhb))\n</code></pre>\n\n<h1>List comprehension</h1>\n\n<p>Building up a list of results should be done using list comprehension, instead of initialization & repeated <code>.append</code> operations. Instead of:</p>\n\n<pre><code> results = []\n for i in range(num):\n results.append(simn_fun(mhb))\n</code></pre>\n\n<p>Use:</p>\n\n<pre><code> results = [simn_fun(mhb) for _ in range(num)]\n</code></pre>\n\n<h1>Counting</h1>\n\n<p>There is no need to build up a long list of results, just to count the result distributions. Pass the results as they are generated to a counter.</p>\n\n<pre><code>>>> import collections\n>>> num = 10000\n>>> simn_fun = run_sim_always_switch\n>>> counts = collections.Counter(simn_fun(mhb) for _ in range(num))\n>>> counts['success']\n6717\n>>> counts['fail']\n3283\n</code></pre>\n\n<p>or, knowing <code>True</code> is 1 and <code>False</code> is zero, count the successes as you generate them yourself:</p>\n\n<pre><code>>>> success = sum(simn_fun(mhb) == 'success' for _ in range(num))\n>>> success\n6614\n</code></pre>\n\n<h1>Formatting</h1>\n\n<p>Use f-strings to put the variables/expressions directly in the format statements:</p>\n\n<pre><code> print(f'Always switch, run simulation {num} times.')\n print(f'Success ratio: {run_simn(num, run_sim_always_switch)}')\n print(f'Never switch, run simulation {num} times.')\n print(f'Success ratio: {run_simn(num, run_sim_never_switch)}')\n</code></pre>\n\n<p>Round results to the desired significant figures with appropriate format codes:</p>\n\n<pre><code> print(f'Success ratio: {run_simn(num, run_sim_never_switch):.3f}')\n</code></pre>\n\n<h1>Named Constants</h1>\n\n<p>If you accidentally wrote the tests as <code>if item == 'Car':</code>, you'd find that nobody wins, and would have to hunt down where in the code you made spelling/capitalization errors. The IDE won't help you; it can't auto complete strings for you. If you used named constants ...</p>\n\n<pre><code>CAR = 'car'\nGOAT = 'goat'\n</code></pre>\n\n<p>... and you wrote <code>if item == Car:</code>, instead of nobody winning, the program would crash with an unknown identifier and identity the line where the problem exists, which is much better than having to search through all of the code looking for where logic is going wrong. But the above named \"constants\" aren't actually constants; they are variables we hope never get accidentally (or maliciously) changed.</p>\n\n<pre><code>from enum import Enum\n\nPrize = Enum('Prize', 'CAR, GOAT')\n</code></pre>\n\n<p>Now we have <code>Prize.CAR</code> and <code>Prize.GOAT</code>, which are constants.</p>\n\n<h1>Malicious Strategies</h1>\n\n<p>A friend can say they've come up with a great strategy - and let you test their code:</p>\n\n<pre><code>import friend\n\nrun_simn(10_000, friend.strategy)\n</code></pre>\n\n<p>And lo and behold, they always win the car! How is this possible?</p>\n\n<p>Friend strategy 1:</p>\n\n<pre><code>def strategy(mhb):\n initial_door = next(door for door, prize in mhb._MontyHallBox__doors.items()\n if prize == 'car')\n _ = mhb.reveal_noncar(initial_door)\n item = mhb.reveal_selected(initial_door)\n return 'success' if item == 'car' else 'fail'\n</code></pre>\n\n<p>Friend strategy 2:</p>\n\n<pre><code>def strategy(mhb):\n initial_door = 1\n goats = { mhb.reveal_noncar(initial_door) for _ in range(10) }\n\n if len(goats) == 2:\n selected_door = initial_door\n else:\n selected_door = 2 if goats == { 3 } else 3\n item = mhb.reveal_selected(initial_door)\n\n return 'success' if item == 'car' else 'fail'\n</code></pre>\n\n<p>Friend strategy 3:</p>\n\n<pre><code>def strategy(mhb):\n return 'success'\n</code></pre>\n\n<p>They are cheating. Some friend.</p>\n\n<hr>\n\n<h1>A safer (harder to cheat) simulation approach</h1>\n\n<p>Let's start by creating some type aliases, to make clearer code.</p>\n\n<pre><code>from typing import Callable, Counter, List, NewType, Tuple\n\n# Doors are numbered\nDoor = NewType('Door', int)\nDoors = List[Door]\n</code></pre>\n\n<p>This <code>Door</code> is just a fancy way of saying the <code>int</code> type-hint, and <code>Doors</code> is a fancy way of saying the <code>List[int]</code> type-hint.</p>\n\n<p>Now let's create two methods which the let's the user play the Monty Hall game:</p>\n\n<pre><code>def first_pick(doors: Doors) -> Door:\n \"\"\"\n Ask the player to pick a door\n \"\"\"\n\n return int(input(f\"Pick a door [{', '.join(map(str,doors))}]: \"))\n\ndef second_pick(doors: Doors, selected: int, goats: Doors) -> Door:\n \"\"\"\n Show some goats behind doors the player didn't pick.\n Ask them again to pick a door.\n \"\"\"\n\n print(f\"Monty shows you a goat behind door #{', '.join(map(str, goats))}.\")\n choice = input(f\"Pick a new door [default: {selected}]: \")\n return int(choice) if choice else selected\n</code></pre>\n\n<p>We pass all the information the player needs to make their choices. In the first case, just the list of available <code>Doors</code>. In the second, we add what their original <code>Door</code> selection was, and the <code>Doors</code> Monty Hall revealed goats behind. No extra <code>MontyHallBox</code> object, or <code>self</code> parameter that the user can peek into to cheat and get extra information.</p>\n\n<p>We can even add types for these two functions up where we are defining the types we're using:</p>\n\n<pre><code>FirstPick = Callable[[Doors], Door]\nSecondPick = Callable[[Doors, Door, Doors], Door]\n</code></pre>\n\n<p>Now, let's build the actual game:</p>\n\n<pre><code>def monty_hall(first: FirstPick = first_pick, second: SecondPick = second_pick, *,\n cars: int = 1, goats: int = 2, reveal: int = 1) -> Tuple[Door, Prize]:\n \"\"\"\n Play a Monty Hall type game.\n\n The player picks one of several doors, behind each is either a Car or a Goat.\n Monty Hall shows the player behind one of the doors they didn't pick,\n \"Oh look, behind this door is a Goat! Now, do you want to change your mind?\"\n The player now gets alter their selection, but does it pay to change their mind?\n\n Parameters:\n first: given the doors, pick a door\n second: given the doors, the first pick, and what was revealed, pick a door\n cars: number of cars (default 1)\n goats: number of goats (default 2)\n reveal: number of hidden goats to reveal (default 1)\n\n Returns:\n The door they choose, and the Prize behind it (a Goat or a Car)\n \"\"\"\n\n # Sanity checks\n if cars < 1 or goats < 1:\n raise ValueError(\"Rigged game! There must be both cars & goats!\")\n if reveal >= goats:\n raise ValueError(\"Monty is not allowed to reveal all of the goats!\")\n\n # Set up the game\n prizes = [Prize.CAR] * cars + [Prize.GOAT] * goats\n random.shuffle(prizes)\n doors = list(range(1, len(prizes) + 1))\n game = { door: prize for door, prize in zip(doors, prizes) }\n\n # Ask player to make their initial selection...\n selected = first(doors)\n\n # Monty reveals some doors\n goats = [ door for door, prize in game.items()\n if prize == Prize.GOAT and door != selected ]\n random.shuffle(goats)\n goats = goats[:reveal]\n\n # Based on original choice and revealed doors, ask player makes new choice...\n selected = second(doors, selected, goats)\n\n # ... and give the player their prize\n return selected, game[selected]\n</code></pre>\n\n<p>Ok, I've beefed up the game a little bit. We've got a configurable number of cars (default 1), goats (default 2), and doors to reveal (default 1). We've got <code>first</code> and <code>second</code> functions which default to the <code>first_pick</code> and <code>second_pick</code> user player functions above. We've got a long doc-string describing the function. Then we've got some validation on number of cars, goats, and reveals.</p>\n\n<p>Then we have the meat-and-potatoes of the function. Create the prizes, mix them up, and hide them behind doors. Call the first method to get the initial door selection. Then Monty Hall picks some doors with goats to reveal. The second the second function is called to get the final door selection. Finally, the resulting prize is returned.</p>\n\n<p>Want to play the game?</p>\n\n<pre><code>def human_verses_monty(**kwargs):\n door, prize = monty_hall(**kwargs)\n print(f\"Behind door #{door}, you find a {prize.name}!\")\n</code></pre>\n\n<p>Use <code>human_verses_monty()</code>. Or maybe <code>human_verses_monty(cars=3, goats=3, reveal=2)</code></p>\n\n<p>I'm using <code>**kwargs</code> for brevity, so I can pass additional keywords through to the underlying <code>monty_hall(...)</code> method. It would be clearer to list all of the keyword arguments out, but this post is already getting pretty long, and I'm not done yet.</p>\n\n<h1>Playing multiple times</h1>\n\n<p>Now that we have our safe simulation, let's make it so we can play the game multiple times, and collect the results:</p>\n\n<pre><code>def monty_halls(strategy: SecondPick, games, *,\n initial: FirstPick = random.choice, **kwargs) -> Counter[Prize]: \n return Counter(monty_hall(initial, strategy, **kwargs)[1] for _ in range(games))\n</code></pre>\n\n<p>The initial door pick defaults to <code>random.choice</code>. We need to pass in a <code>strategy</code> for the second pick. The game is played the given number of times, with <code>Door, Prize</code> being returned, from which we select only the <code>Prize</code> with <code>[1]</code>, and count the number of times we get each prize in a <code>Counter</code>.</p>\n\n<p>Now we need some strategies:</p>\n\n<pre><code>def always_switch(doors: Doors, selected: Door, goats: Doors) -> Door:\n return random.choice(list(set(doors) - set(goats) - {selected}))\n\ndef never_switch(doors: Doors, selected: int, goats: Doors) -> Door:\n return selected\n</code></pre>\n\n<p>Again, no extra information to allow them to cheat. And they don't get to break the rules and play incorrectly (asking Monty Hall multiple times to reveal doors) to cheat.</p>\n\n<p>How about function to evaluate various strategies:</p>\n\n<pre><code>def evaluate(strategies: List[SecondPick], games, **kwargs):\n for strategy in strategies:\n prizes = monty_halls(strategy, games, **kwargs)\n wins = prizes[Prize.CAR]\n losses = prizes[Prize.GOAT]\n total = wins + losses\n print(f\"{strategy.__name__}: wins {wins / total * 100:.2f} %\")\n print()\n</code></pre>\n\n<p>Let's see it in action:</p>\n\n<pre><code>if __name__ == '__main__':\n print(\"Standard game (1 car, 2 goats)\")\n evaluate([always_switch, never_switch], 10_000)\n\n print(\"Alternate game (2 car, 3 goats, 2 reveals)\")\n evaluate([always_switch, never_switch], 10_000, cars=2, goats=3, reveal=2)\n</code></pre>\n\n<p>Running this gives:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Standard game (1 car, 2 goats)\nalways_switch: wins 66.88 %\nnever_switch: wins 33.12 %\n\nAlternate game (2 car, 3 goats, 2 reveals)\nalways_switch: wins 80.14 %\nnever_switch: wins 39.91 %\n</code></pre>\n\n<h1>Cheaters will be cheaters</h1>\n\n<p>It is still possible to cheat. One method would be to capture the stack frame, and look at the local variables in the calling frame. We can get around this by using a separate thread or process to execute the strategy calls in, so the caller can't simply walk up the stack looking for gold. This still isn't fool proof, 'cause the cheater could look for the parent thread, or parent process and try to inspect those.</p>\n\n<p>At least we aren't making it easy to cheat, like the original <code>MontyHallBox</code> approach did.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T10:06:52.063",
"Id": "473121",
"Score": "2",
"body": "+1 for making improvements you then delete anyway to teach the OP more things, e.g. changing `i` to `_` even though you're about to replace the for loop with a list comprehension."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T14:17:42.717",
"Id": "473159",
"Score": "0",
"body": "I would even go 1 step further in the and have `simn_fun` return a boolean instead of a flag"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T15:08:23.880",
"Id": "473164",
"Score": "1",
"body": "@MaartenFabré I went 3 steps further."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T17:13:45.180",
"Id": "476826",
"Score": "0",
"body": "@AJNeufeld, thank you for thorough improvement, just wanted to say that re \"private\" object attribute names some Python programmers maintain that _ should be interpreted as a hint to a (cooperative) programmer that \"don't access it unless you know what you're doing\" and __ as hint that \"you really should not be using this\". I thought this was nice convention."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T17:39:07.043",
"Id": "476835",
"Score": "0",
"body": "`__*` identifiers [\"_help avoid name clashes between “private” attributes of base and derived classes_\"](https://docs.python.org/3/reference/lexical_analysis.html#reserved-classes-of-identifiers), so `class Base:` can define a `__doors` attribute, and `class Derived(Base):` can also define its own `__doors` attribute, and they won't clash because they are internally named `_Base__doors` and `_Derived__doors` respectively. It is not intended to be used as a \"hint\", but rather as a safety net where you don't need access to the base's source code in order to avoid name collisions. JSYK."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-09T21:56:28.717",
"Id": "504901",
"Score": "0",
"body": "@AJNeufeld You could have done the \"sanity checks\" with a decorator."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T16:44:58.493",
"Id": "241083",
"ParentId": "241078",
"Score": "16"
}
},
{
"body": "<h2>Available doors</h2>\n\n<p>First of all, this:</p>\n\n<pre><code> self._doors = {1: None, 2: None, 3: None}\n</code></pre>\n\n<p>should be calling <code>available_doors</code>, i.e.</p>\n\n<pre><code>self._doors = {i: None for i in available_doors()}\n</code></pre>\n\n<p>However, <code>available_doors</code> needn't be a function; it can be a global constant:</p>\n\n<pre><code>AVAILABLE_DOORS = [1, 2, 3]\n</code></pre>\n\n<p>Better yet, make it a <code>set</code>:</p>\n\n<pre><code>AVAILABLE_DOORS = {1, 2, 3}\n</code></pre>\n\n<p>Better yet, pass it as a parameter to the class:</p>\n\n<pre><code>def __init__(self, available_doors: set):\n self._doors = available_doors\n self._init_doors()\n</code></pre>\n\n<p>Better yet, don't even care about the collection; simply care about the number of doors:</p>\n\n<pre><code>def __init__(self, n_doors: int):\n self._n_doors = n_doors\n</code></pre>\n\n<p>Then this:</p>\n\n<pre><code> self.__doors = {n: 'goat' for n in range(1, 4)}\n</code></pre>\n\n<p>can actually use it:</p>\n\n<pre><code>self._doors = {n: 'goat' for n in range (1, 1 + self._n_doors)}\n</code></pre>\n\n<p>In other words, the number of doors should be parametric, and only kept in one place.</p>\n\n<h2>Redundant init</h2>\n\n<p>Since <code>reinitialize</code> just calls <code>_init_doors</code>, why not have the contents of <code>_init_doors</code> in <code>reinitialize</code>, deleting <code>_init_doors</code>?</p>\n\n<h2>Stringly-typed results</h2>\n\n<p>This:</p>\n\n<pre><code>if item == 'car':\n return 'success'\nreturn 'fail'\n</code></pre>\n\n<p>would make more sense as a boolean return value:</p>\n\n<pre><code>return item == 'car'\n</code></pre>\n\n<h2>Counting successes</h2>\n\n<pre><code>successes = len(list(filter(lambda x: x == 'success', results)))\n</code></pre>\n\n<p>is better written as</p>\n\n<pre><code>successes = sum(1 for x in results if x == 'success')\n</code></pre>\n\n<p>If you take the boolean suggestion above, it will just be</p>\n\n<pre><code>successes = sum(1 for x in results if x)\n</code></pre>\n\n<p>Technically, since <code>bool</code> can be cast to an <code>int</code>, this is equivalent to</p>\n\n<pre><code>successes = sum(results)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T17:22:58.323",
"Id": "476829",
"Score": "0",
"body": "I upvoted your answer, but disagree on simulation result types. That function (e.g. run_sim_never_switch) represents a simulation. Simulation returns some sort of result, not truth or falsehood (in general). In a world of types this should be something specific, like an object, a number, etc. I think enum.Enum proposed by AJNeufeld is a nice way of expressing this approach without getting too philosophically-OO-heavy."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-26T17:28:46.970",
"Id": "476831",
"Score": "0",
"body": "@LetMeSOThat4U Enum is not a terrible solution, but the OP's use of \"success\" or \"failure\" strings indicates a very clear case for a boolean."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T16:53:05.740",
"Id": "241084",
"ParentId": "241078",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "241083",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T15:31:23.267",
"Id": "241078",
"Score": "10",
"Tags": [
"python",
"python-3.x",
"simulation"
],
"Title": "Monty Hall implementation"
}
|
241078
|
<p>This is a simple app that starts the webcam either in color or in grayscale mode depending on what the user wants:</p>
<p><a href="https://i.stack.imgur.com/wrFzL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wrFzL.png" alt="enter image description here"></a></p>
<p>The grayscale camera is implemented via the <code>GrayVideo</code> class and the color camera through <code>ColorVideo</code>. I wanted to have a common <code>show_current_frame</code> for both the <code>ColorVideo</code> and <code>GrayVideo</code> objects. That <code>show_current_frame</code> gets the current frame from the process method and displays it in the GUI. Since the color and the grayscale videos need different frame processing, I needed to have different <code>process</code> methods for <code>ColorVideo</code> and <code>GrayVideo</code>. So, I thought of having a <code>Video</code> class with an abstract <code>process</code> method. </p>
<p>Is this a decent use of abstract classes and inheritance?
What other problems and possible improvements do you see in my code?
Or is the design wrong in the first place?</p>
<pre><code>import cv2
from abc import ABC, abstractmethod
class Video(ABC):
def __init__(self, source):
self.capture = cv2.VideoCapture(source) # If source = 0 the webcam starts
def get_raw_frame(self):
# Get a bolean and current frame (numpy array) from the webcam
ret, frame = self.capture.read()
if ret:
return frame
@abstractmethod
def process(self):
# Method to process frames.
# Method will be overwritten by subclasses
pass
def show_current_frame(self):
# Get processed frame and show it in the GUI
current_frame = self.process()
cv2.imshow('Live', current_frame)
def end(self):
# Releases webcam and closes GUI window
self.capture.release()
cv2.destroyAllWindows()
class ColorVideo(Video):
def process(self):
# Since raw frames are in color, there's no processing needed
return self.get_raw_frame()
class GrayVideo(ColorVideo):
def process(self):
# Grayscaling the raw frames
raw_frame = self.get_raw_frame()
gray = cv2.cvtColor(raw_frame, cv2.COLOR_BGR2GRAY)
return gray
user_preference = input('Enter "c" for color, or "g" for grayscale: ')
if user_preference == 'c':
video = ColorVideo(source=0)
if user_preference == 'g':
video = GrayVideo(source=0)
while True:
video.show_current_frame()
if cv2.waitKey(1) & 0xFF == ord('q'):
video.end()
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n <p>Is this a decent use of abstract classes and inheritance?</p>\n</blockquote>\n\n<p>Yes, it's decent. My personal preference is, rather than using <code>ABC</code>, simply</p>\n\n<pre><code>def process(self):\n # Method to process frames.\n # Method will be overwritten by subclasses\n raise NotImplementedError()\n</code></pre>\n\n<p>You can also simplify this somewhat by</p>\n\n<ul>\n<li>Renaming <code>Video</code> to <code>ColorVideo</code></li>\n<li>Deleting the class that is now called <code>ColorVideo</code></li>\n<li>Rather than making <code>process</code> abstract, make it \"virtual\" (in C++ parlance): make it take the contents of what is now <code>get_raw_frame</code> and delete <code>get_raw_frame</code></li>\n<li>In the child <code>GrayVideo</code>, override <code>process</code> to call its <code>super().process</code> and convert the results</li>\n</ul>\n\n<p>If you're concerned that this more minimal representation is confusing (i.e. why is a <code>GrayVideo</code> a <code>ColorVideo</code>?) then you can keep <code>Video</code> as a conceptually abstract class, and simply</p>\n\n<pre><code>class ColorVideo(Video):\n pass\n</code></pre>\n\n<p>Other stuff:</p>\n\n<ul>\n<li><code>end</code> should actually be the <code>__exit__</code> of a context manager; </li>\n<li>it looks like your <code>source</code> argument should take a default of <code>0</code>;</li>\n<li>make a <code>main</code> function called by standard <code>__name__</code> guard.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T18:08:23.863",
"Id": "473056",
"Score": "0",
"body": "Cool, thank you! That made it a lot more compact! I never thought of leveraging super that way There's one more aspect I'd like to get your opinion about. I want to draw some rectangles on top of the video frames with `cv2.rectangle(self.frame, (x1, y1), (x2, y2), (255, 0, 0), 2)`. Would you make a new decorator class that \"decorates\" the ColorVideo frames with rectangles or would you simply create a RectangledVidoe class that inherits from ColorVideo, or other?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T18:26:06.810",
"Id": "473057",
"Score": "0",
"body": "Are the rectangles always on every frame?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T19:20:43.190",
"Id": "473060",
"Score": "0",
"body": "Yes, they are. In other words, there's a rectangle annotation on the entire video."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T19:58:10.107",
"Id": "473061",
"Score": "0",
"body": "Alright, I can simply make an AnnotatedVideo class inheriting from ColorVideo and then modify the process method to return the annotated frame. That wouldn't work if the rectangle would be there all the time though. If you have any suggestions for the later (rectangle not all the time in the video) I'm all ears."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T19:58:54.033",
"Id": "473062",
"Score": "0",
"body": "Simply add it as a boolean argument on the constructor, saved to an attribute of the class. If true, make the rectangle."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T16:34:15.130",
"Id": "241082",
"ParentId": "241079",
"Score": "4"
}
},
{
"body": "<h1>user input</h1>\n\n<p>What happens if the user does not type in <code>c</code> or <code>g</code>?</p>\n\n<h1>typing</h1>\n\n<p>As a general remark, I would include type annotations, so users of your code, (this includes you in 6 months time) can know what to expect.</p>\n\n<h1>docstring</h1>\n\n<p>The same goes for a docstring.</p>\n\n<p>You kind of do that already </p>\n\n<pre><code>def get_raw_frame(self):\n # Get a bolean and current frame (numpy array) from the webcam\n</code></pre>\n\n<p>But if you turn that into a docstring</p>\n\n<pre><code>def get_raw_frame(self):\n \"\"\"Get a bolean and current frame (numpy array) from the webcam\"\"\"\n</code></pre>\n\n<p>IDE's etc can keep track of this.</p>\n\n<h1>inheritance</h1>\n\n<p>I would not use inheritance here, but composition. An excellent explanation is given by Brandon Rhodes <a href=\"https://python-patterns.guide/gang-of-four/composition-over-inheritance/\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>You can define a procotol.</p>\n\n<pre><code>class VideoProcessor(typing.Protocol):\n def process(self, raw_frame:np.ndarray) -> np.ndarray:\n ...\n</code></pre>\n\n<p>And then give 2 implementations:</p>\n\n<pre><code>class ColorProcessor(VideoProcessor):\n def process(self, raw_frame: np.ndarray) -> np.ndarray:\n \"\"\"Return the frame untouched.\"\"\"\n return raw_frame\n\n\nclass GrayProcessor(VideoProcessor):\n def process(self, raw_frame: np.ndarray) -> np.ndarray:\n \"\"\"Convert the raw frame to grayscale.\"\"\"\n return cv2.cvtColor(raw_frame, cv2.COLOR_BGR2GRAY)\n</code></pre>\n\n<p>Then the init and <code>process</code> become something like this:</p>\n\n<pre><code>def __init__(\n self, source: int, processor: VideoProcessor\n ):\n self.processor = processor\n self.capture = cv2.VideoCapture(source) \n # If source = 0 the webcam starts\n\ndef process(self):\n \"\"\"Let the processor process the raw frame.\"\"\"\n raw_frame = self.get_raw_frame()\n if raw_frame is not None:\n return self.processor.process(raw_frame)\n</code></pre>\n\n<p>This way, If you ever want to implement a sepia, or green version, it's just a matter of implementing another <code>Processor</code>.</p>\n\n<p>These processors can also be tested individually, without having to set up a videosource</p>\n\n<h1>Hoist the IO</h1>\n\n<p>Another thing I would change, is instead of letting the <code>Video</code> class instantiate the connection to the webcam, I would let this be done on a higher level, and have the Video class accept a video source.</p>\n\n<p>Here are <a href=\"https://rhodesmill.org/brandon/talks/#clean-architecture-python\" rel=\"nofollow noreferrer\">1</a> <a href=\"https://rhodesmill.org/brandon/talks/#hoist\" rel=\"nofollow noreferrer\">2</a> talks on why you would want to do this. This concept is not limited to python (<a href=\"https://jeffreypalermo.com/2008/07/the-onion-architecture-part-1/\" rel=\"nofollow noreferrer\">3</a>)</p>\n\n<pre><code>class VideoSource(typing.Protocol):\n def read(self) -> typing.Tuple[bool, np.ndarray]:\n \"\"\"Read the current frame.\n\n Returns a boolean success flag, \n and the current frame, if successful.\n \"\"\"\n ...\n\n def release(self) -> None:\n \"\"\"Release the connection to the video source.\"\"\"\n ...\n\ndef __init__(\n self, source: VideoSource, processor: VideoProcessor\n):\n self.processor = processor\n self.capture = source\n</code></pre>\n\n<p>This change makes it even easier to test the <code>Video</code> class.</p>\n\n<h1>context manager</h1>\n\n<p>Turning <code>Video</code> into a <code>context manager</code> is very simple:</p>\n\n<pre><code>def __enter__(self):\n return self\n\ndef __exit__(self, type, value, traceback):\n self.end()\n</code></pre>\n\n<h1>Putting it together</h1>\n\n<pre><code>if __name__ == \"__main__\": \n while True:\n user_preference = input('Enter \"c\" for color, or \"g\" for grayscale: ')\n if user_preference in \"cg\":\n break\n\n if user_preference == 'c':\n processor = ColorProcessor()\n if user_preference == 'g':\n processor = GrayProcessor()\n source = cv2.VideoCapture(0) \n\n with Video(source=source, processor=processor) as video:\n while True:\n video.show_current_frame()\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n</code></pre>\n\n<h1>rectangles on the screen</h1>\n\n<p>You could even generalize this to have consequent processors, for example if you want to add the rectangles</p>\n\n<p>The Processor itself can be quite simple (I use <code>dataclasses</code> to avoid the boiler plate <code>__init__</code>:</p>\n\n<p>import dataclasses</p>\n\n<pre><code>@dataclasses.dataclass\nclass RectangleProcessor(VideoProcessor):\n x1: int\n y1: int\n x2: int\n y2: int\n\n color: typing.Tuple[int, int, int]\n\n def process(self, raw_frame: np.ndarray) -> np.ndarray:\n return cv2.rectangle(\n raw_frame, (self.x1, self.y1), (self.x2, self.y2), self.color, 2\n )\n</code></pre>\n\n<p>You can implement a chain of processors very simply:</p>\n\n<pre><code>class Video:\n def __init__(\n self,\n source: VideoSource,\n processors: typing.Optional[typing.Sequence[VideoProcessor]] = None,\n ):\n self.processors = processors\n self.capture = source\n\n def process(self) -> np.ndarray:\n raw_frame = self.get_raw_frame()\n if self.processors is None:\n return raw_frame\n for processor in self.processors:\n raw_frame = processor.process(raw_frame)\n return raw_frame\n</code></pre>\n\n<p>This way you can even skip the noop <code>ColorProcessor</code></p>\n\n<pre><code>if __name__ == \"__main__\":\n while True:\n user_preference = input('Enter \"c\" for color, or \"g\" for grayscale: ')\n if user_preference in \"cg\":\n break\n while True:\n\n\n processors = []\n if user_preference == \"g\":\n processors.append(GrayProcessor())\n\n user_preference = input('Do you want to add a rectange [y/N]:')\n\n if user_preference.lower() == \"y\":\n processors.append(RectangleProcessor(0, 0, 10, 10, (255, 0, 0)))\n\n source = cv2.VideoCapture(0)\n\n with Video(source=source, processors=processors) as video:\n while True:\n video.show_current_frame()\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n</code></pre>\n\n<p>Like this, you can easily add Processors that add timestamps to video's, names to streams, ...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T10:19:43.573",
"Id": "473127",
"Score": "0",
"body": "I'd suggest you add a `main()` function instead of throwing everything in bulk right under the `if __name__ == \"__main__\"` guard."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T07:40:06.620",
"Id": "241118",
"ParentId": "241079",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "241082",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T15:43:04.723",
"Id": "241079",
"Score": "4",
"Tags": [
"python",
"object-oriented"
],
"Title": "Is this an appropriate use of abstract classes and inheritance?"
}
|
241079
|
<p>When you write a code in python code people always ask to make it more pythonic. I am not sure if there is a term for scala or not. However, I am pretty sure my following code use one or two scala feature. </p>
<p><strong>Objective</strong></p>
<ul>
<li>Read a property file, which has location to XML file </li>
<li>Read source, destination and some other properties from property and XML File </li>
<li>Copy Data from one location to another location. </li>
</ul>
<p><strong>FileSystem.scala</strong></p>
<pre class="lang-scala prettyprint-override"><code>bstract class FileSystem(flagFileURI: String){
def getRecordCount(properties: Properties): String = {
properties.getProperty("recordCount")
}
def getAuditID: String = {
val instant: Instant = Instant.now
val zoneId: ZoneId = ZoneId.of("Canada/Eastern")
val auditIdFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")
val auditId = ZonedDateTime.ofInstant(instant, zoneId).format(auditIdFormatter)
auditId
}
def getSourcePath(properties: Properties): Path = {
val dataFileURI: String = properties.getProperty("dataFileURI")
val srcPath = new Path(dataFileURI)
srcPath
}
def getMetaDataFileURI(properties: Properties): String = {
properties.getProperty("metadataFileURI")
}
def getIDPDataDate(properties: Properties): String = {
properties.getProperty("idpDataDate")
}
def getDestinationPath(properties: Properties, metaDataFileURI: String, IDPDataDate: String, dataFileName: String): Path = {
val l0DirLocation: String = ConfigFactory.load().getString("sparkFramework.hdfs.l0dirlocation")
val frameWorkUtils = new FrameworkUtils()
val sourceSystem: SourceSystem = frameWorkUtils.getSourceSystem(metaDataFileURI)
val schemaName: String = frameWorkUtils.getSchemaName(sourceSystem)
val tableName: String = frameWorkUtils.getTableName(sourceSystem)
val destPath = new Path(l0DirLocation + schemaName + "/" + tableName + "/idp_data_date=" + IDPDataDate + "/" + dataFileName)
destPath
}
def getDataFileName(srcPath: Path, auditID: String): String = {
val dataFileName: String = srcPath.getName + "_" + getAuditID
dataFileName
}
}
</code></pre>
<p><strong>HDFileSystem.scala</strong></p>
<pre class="lang-scala prettyprint-override"><code>class HDFileSystem(flagFileURI: String) extends FileSystem(flagFileURI) {
def copyFromLocalFile: (String, String, String, String, String) = {
val properties: Properties = new Properties()
val source: InputStreamReader = Source.fromFile(flagFileURI).reader
properties.load(source)
val metaDataFileURI = getMetaDataFileURI(properties)
val srcPath = getSourcePath(properties)
val auditId = getAuditID
val dataFileName = getDataFileName(srcPath, auditId)
val IDPDataDate = getIDPDataDate(properties)
val destPath = getDestinationPath(properties, metaDataFileURI, IDPDataDate, dataFileName)
val recordCount = getRecordCount(properties)
val hadoopConf = new Configuration()
val hdfs = FileSystem.get(hadoopConf)
hdfs.copyFromLocalFile(true,false,srcPath, destPath)
(IDPDataDate,recordCount,auditId,metaDataFileURI,dataFileName)
}
}
</code></pre>
<p><strong>Main.scala</strong></p>
<pre class="lang-scala prettyprint-override"><code> val hdFileSystem = new HDFileSystem(flagFileURI = args(0))
val (idpDataDate,count,auditId,metadataFileURI,fileName) = hdFileSystem.copyFromLocalFile
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T07:18:05.610",
"Id": "473107",
"Score": "1",
"body": "Why create `val auditId`, `val srcPath`, `val destPath`, and `val dataFileName`? You don't need any of them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T23:37:19.160",
"Id": "478311",
"Score": "0",
"body": "Please read the \"how to ask\" part of the help. In particular, the title of a question on this site should describe the _purpose_ of the code, not what you want to get out of the review, since otherwise all questions would look the same: \"Make my code easier to read, faster, more correct\""
}
] |
[
{
"body": "<p>What you have isn't bad, but I feel like you're creating too many variables. For example, in <code>getAuditID</code> and other methods, you assign an object to a variable and immediately return it. You also have some unnecessary type annotations.</p>\n<pre><code>def getAuditID: String = {\n val instant: Instant = Instant.now\n val zoneId: ZoneId = ZoneId.of("Canada/Eastern")\n val auditIdFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")\n val auditId = ZonedDateTime.ofInstant(instant, zoneId).format(auditIdFormatter)\n auditId\n}\n</code></pre>\n<p>After eliminating that, I got this:</p>\n<pre><code>abstract class FileSystem(flagFileURI: String) {\n\n def getRecordCount(properties: Properties): String =\n properties.getProperty("recordCount")\n\n def getAuditID: String =\n ZonedDateTime\n .ofInstant(Instant.now, ZoneId.of("Canada/Eastern"))\n .format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"))\n\n def getSourcePath(properties: Properties): Path =\n new Path(properties.getProperty("dataFileURI"))\n\n def getMetaDataFileURI(properties: Properties): String =\n properties.getProperty("metadataFileURI")\n\n def getIDPDataDate(properties: Properties): String =\n properties.getProperty("idpDataDate")\n\n def getDataFileName(srcPath: Path, auditID: String): String =\n srcPath.getName + "_" + getAuditID\n\n def getDestinationPath(\n properties: Properties,\n metaDataFileURI: String,\n IDPDataDate: String,\n dataFileName: String\n ): Path = {\n val l0DirLocation =\n ConfigFactory.load().getString("sparkFramework.hdfs.l0dirlocation")\n val frameWorkUtils = new FrameworkUtils()\n val sourceSystem =\n frameWorkUtils.getSourceSystem(metaDataFileURI)\n val schemaName = frameWorkUtils.getSchemaName(sourceSystem)\n val tableName = frameWorkUtils.getTableName(sourceSystem)\n\n new Path(\n l0DirLocation + schemaName + "/" + tableName + "/idp_data_date=" + IDPDataDate + "/" + dataFileName\n )\n }\n}\n</code></pre>\n<p>However, your other method, <code>copyFromLocalFile</code>, could also be improved. The return type is a tuple of 5 strings, which to me seems much too complex. Instead of that, I'd suggest making a case class that makes it obvious what each of those strings mean.</p>\n<pre><code>case class FileInfo(\n IDPDataDate: String,\n recordCount: String,\n auditId: String,\n metaDataFileURI: String,\n dataFileName: String\n)\n</code></pre>\n<p>Then you can define this method in <code>FileSystem</code> to get all the information at once</p>\n<pre><code>def getFileInfo(properties: Properties): FileInfo = {\n val auditId = getAuditID\n FileInfo(\n getIPDDataDate(properties),\n getRecordCount(properties),\n auditId,\n getMetaDataFileURI(properties),\n getDataFileName(getSourcePath(properties), auditID)\n )\n}\n</code></pre>\n<p>After that, you can turn your method into something like this:</p>\n<pre><code>def copyFromLocalFile: FileInfo = {\n\n val properties: Properties = new Properties()\n\n properties.load(Source.fromFile(flagFileURI).reader)\n\n val fileInfo = getFileInfo(properties)\n\n FileSystem\n .get(new Configuration())\n .copyFromLocalFile(\n true,\n false,\n fileInfo.srcPath,\n getDestinationPath(\n properties,\n fileInfo.metaDataFileURI,\n fileInfo.IDPDataDate,\n fileInfo.dataFileName\n )\n )\n\n fileInfo\n}\n</code></pre>\n<p>You can still destructure the result:</p>\n<pre><code>val FileInfo(idpDataDate, count, auditId, metadataFileURI, fileName) =\n hdFileSystem.copyFromLocalFile\n</code></pre>\n<p>Of course, I don't know about the whole structure of your program, so this might not work for you.</p>\n<p><a href=\"https://scastie.scala-lang.org/kTAbohaJQ6y7GtUO2vECfA\" rel=\"nofollow noreferrer\">Link to Scastie</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-10T23:10:48.740",
"Id": "243691",
"ParentId": "241081",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T15:54:39.433",
"Id": "241081",
"Score": "3",
"Tags": [
"object-oriented",
"design-patterns",
"scala",
"type-safety"
],
"Title": "How to make it more Scala compatible?"
}
|
241081
|
<p>So after years of teaching myself, I think I'm ready to stand on the shoulders of giants and ask you a good question!</p>
<p>I have a tree of nodes. What I want is a function that returns an array of the entire tree sorted by depth.</p>
<p>In my original attempt I wasn't aware at the time that I was performing a depth first search.</p>
<p>My solution was to:</p>
<ul>
<li>recursively walk the tree, annotating depth as I go along.</li>
<li>sort the above based on the depth annotation.</li>
<li>filter out the depth annotation and return the sorted array.</li>
</ul>
<p>That was three steps invoking 3 loops! So then someone alerted me to the concept of a breadth first search. I did my research and built (on my own) a BFS function! It looked so simple and did what I needed.</p>
<p>Then when I timed both versions; completely bafflingly; the cumbersome DFS version is faster! Why???</p>
<h3>Here is my depth-first-search:</h3>
<pre><code>function dfsElementsInTree(input){
// perform depth first search but
// return a depth sorted array of an element or elements and any children
let output = [];
if (Symbol.iterator in input)
// input is a HTMLcollection
for (const element of input)
doTraversal(element);
else
doTraversal(input);
return output.sort((a, b) => a.depth - b.depth).map(item=>item.element);
function doTraversal(element, depth=0) {
output.push({element, depth});
if (element.children.length) depth++;
for (const child of element.children)
doTraversal(child, depth);
}
}
</code></pre>
<h3>Here is my breadth-first-search:</h3>
<pre><code>function bfsElementsInTree(input) {
// perform a breadth first search in order to have elements ordered by depth.
let output = [];
let queue = [];
let visited = [];
const enqueue = item => {queue.push(item); visited.push(item);};
if (Symbol.iterator in input)
// input is a HTMLcollection
for (const element of input)
queue.push(element);
else
queue.push(input);
while (queue.length) {
for (const element of queue)
for (const child of element.children)
if (!visited.includes(child))
enqueue(child);
output.push(queue.shift());
}
return output;
}
</code></pre>
<hr />
<h3>Ready for benchmarking here: <a href="https://jsben.ch/ZNuAx" rel="nofollow noreferrer">https://jsben.ch/ZNuAx</a></h3>
<hr />
<p>But if you want to test it yourself, here's some code to generate some trees:</p>
<pre><code>// Create trees of divs as such:
// (left to right)
// 1
// 1 -> 2
// 1 -> 2 -> 3
// 1 -> 2
// 1
const a1 = document.createElement('div');
const a2 = document.createElement('div');
const a3 = document.createElement('div');
const a4 = document.createElement('div');
const a5 = document.createElement('div');
[a1,a2,a3,a4,a5].forEach(e => e.className ='1');
const b2 = document.createElement('div');
const b3 = document.createElement('div');
const b4 = document.createElement('div');
[b2,b3,b4].forEach(e => e.className ='2');
const c3 = document.createElement('div');
c3.className = '3';
a2.appendChild(b2);
b3.appendChild(c3);
a3.appendChild(b3);
a4.appendChild(b4);
[a1,a2,a3,a4,a5].forEach(e => document.body.appendChild(e));
</code></pre>
<p>Thank you so much for your time. It's a real treat to have an expert looking over my shoulder!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T20:31:03.993",
"Id": "473064",
"Score": "3",
"body": "Maintaining `visited` only makes sense for a generic graph (where you may visit a node from many other nodes). For a tree, it is a pure waste of time and space."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T08:28:16.787",
"Id": "473113",
"Score": "0",
"body": "Right, that's what I thought, but if you comment it out, you get this `(44) [div.1, div.1, div.1, div.1, div.1, div.2, div.2, div.2, div.3, div.2, div.2, div.2, div.3, div.3, div.2, div.2, div.3, div.3, div.3, div.2, div.3, div.3, div.3, div.3, div.3, div.3, div.3, div.3, div.3, div.3, div.3, div.3, div.3, div.3, div.3, div.3, div.3, div.3, div.3, div.3, div.3, div.3, div.3, div.3]` which is crazy"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T08:42:22.080",
"Id": "473114",
"Score": "0",
"body": "Ah, I figured it out! The while AND the for loop together are excessive. Here is the new benchmark: https://jsben.ch/WBHuB"
}
] |
[
{
"body": "<p>I solved it. It turns out my looping logic was a bit out. No need for both a while and a for! (and while we're at it, we don't have to check for visited. Thanks @vnp in comments)</p>\n\n<p>edit: since I'm not actually using a queue, I missed that I don't now need to maintain two arrays! Thanks @Ry in the comments!)</p>\n\n<p>Wrote it again for speed and here it is:</p>\n\n<pre><code> function bfsElementsInTree(input) {\n // perform a breadth first search in order to have elements ordered by depth. (Deepest last)\n let output = [];\n\n if (Symbol.iterator in input)\n // input is a HTMLcollection\n for (let i = 0, max = input.length; i < max; i++)\n output[i] = input[i];\n else\n output.push(input);\n\n for (let i = 0; i < output.length; i++) {\n const children = output[i].children;\n for (let j = 0, max = children.length; j < max; j++)\n output.push(children[j]);\n }\n\n return output;\n }\n</code></pre>\n\n<p>And new benchmark: <a href=\"https://jsben.ch/F1zzW\" rel=\"nofollow noreferrer\">https://jsben.ch/F1zzW</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T10:30:58.220",
"Id": "473132",
"Score": "1",
"body": "Isn’t the queue the same as the output here? So you could return `queue` directly and remove `output` for more performance and memory wins."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T18:14:00.453",
"Id": "473188",
"Score": "0",
"body": "You were right! Good catch!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T08:45:00.843",
"Id": "241121",
"ParentId": "241087",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "241121",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T17:20:26.673",
"Id": "241087",
"Score": "1",
"Tags": [
"javascript",
"algorithm",
"tree",
"breadth-first-search",
"depth-first-search"
],
"Title": "Depth First Search vs Breadth First Search"
}
|
241087
|
<p>This question was asked through the Facebook interview and the suggested solution is solving via binary search.</p>
<p>I have put the binary search solution but it still looks too complicated.</p>
<p>Question:</p>
<blockquote>
<p>Given an int array wood representing the length of n pieces of wood and an int k. It is required to cut these pieces of wood such that more or equal to
k pieces of the same length len are cut. What is the longest len you can get?</p>
</blockquote>
<p>Input: wood = [5, 9, 7], k = 3
Output: 5
Explanation:
5 -> 5
9 -> 5 + 4
7 -> 5 + 2</p>
<p>Input: wood = [5, 9, 7], k = 4
Output: 4
Explanation:
5 -> 4 + 1
9 -> 4 * 2 + 1
7 -> 4 + 3</p>
<pre><code>package AmazonOthers.src;
import java.util.Arrays;
public class CutWood {
public static void main(String[] args) {
int[] array1 = {5,9,7};
int k = 3;
System.out.println( woodCut(array1,k) ) ;
int[] array2 = {124,232,456};
Arrays.sort(array2);
int k2 = 7;
System.out.println( woodCut(array2,k2) ) ;
int[] array3 = {3,6,7,11};
Arrays.sort(array3);
int k3 = 8;
System.out.println( woodCut(array3,k3) ) ;
}
private static int woodCut(int[] array1,int k) {
int l = 0;
int h = Integer.MAX_VALUE;
while(l<h){
int mid = l + (h-l)/2;
if(isValid(array1, mid, k)){
l = mid +1;
}else{
h=mid-1;
}
}
return h;
}
private static boolean isValid(int[] array1, int mid, int k) {
int count = 0;
for(int val: array1){
count+=val/mid;
}
return count>=k;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Overall I think you have about the simplest you could hope for. The only thing I'd do is set your bounds better. You know that you can do min(array)/ceil(k/len(array)) and you know you at most you can do max(array)/floor(k/len(array)).</p>\n\n<p>I was going to suggest going for extra credit with a more sophisticated algorithm, but I don't think you can beat what the binary search approach. At worst you're going to be 32 or 64 * O(n). Given the simplicity of the algorithm I think that will likely beat sorting and all the alternatives I can think of either explicitly or implicitly do a sort which would be O(n log n).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T17:51:58.150",
"Id": "241090",
"ParentId": "241088",
"Score": "2"
}
},
{
"body": "<p>I have added a getMaxValue() method to limit the search?</p>\n\n<p>Could you please evaluate the solution if is it meets the limiting the search ?</p>\n\n<p>Thanks.</p>\n\n<pre><code>package main.algorithms;\n\npublic class CutWood {\n\n public boolean isValid(int[] wood, int cutLength, int k){\n int count = 0;\n for(int w: wood){\n count += w / cutLength;\n }\n return count >= k;\n }\n\n public int cutWood(int[] wood, int k){\n // corner cases:\n if(wood.length == 0 || k == 0) return 0;\n int left = 1;\n int right = getMaxValue(wood);\n int res = 0;\n\n if(!isValid(wood, left, k)) return 0;\n\n while(left < right){\n int mid = left + (right - left)/2;\n boolean valid = isValid(wood, mid, k);\n if(valid){\n left = mid + 1;\n res = mid;\n }\n else\n right = mid;\n }\n return res;\n }\n\n private int getMaxValue(int[] wood) {\n int max = 0;\n for(int i : wood){\n if (i> max){\n max = i;\n }\n }\n return max;\n }\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T09:52:05.743",
"Id": "241127",
"ParentId": "241088",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T17:23:21.607",
"Id": "241088",
"Score": "1",
"Tags": [
"java",
"interview-questions"
],
"Title": "Cut Wood / Facebook Interview"
}
|
241088
|
<p>I am just working on <a href="https://www.hackerrank.com/challenges/flatland-space-stations/problem" rel="nofollow noreferrer">Flatland Space Stations</a> problem, and it is not seeming to be a tough question, but my algorithm lags in some aspects, since it solves majority of the test cases but fails for some. Which is causing me not to move forward. </p>
<p>The cause of the failure is timeout only, no wrong output.</p>
<p><strong>My Algo:</strong></p>
<ol>
<li>To loop through the number of cities</li>
<li>Loop through the cities which has the space stations</li>
<li>Store the minimum distance in the array or dict for that particular city</li>
<li>Find out the maximum distance stores in the array of difference between n cities </li>
</ol>
<p>I have written two codes based upon the following Algo:</p>
<p><strong>1. With the use of Dictionary:</strong> <em>Time out for three cases</em></p>
<pre><code>def flatlandSpaceStations(n, c):
# n is the number of cities
# c is the array of space station exists in the city(s)
cityDiff = {}
maxDiff = 0
if n == len(c):
return 0
else:
for i in range(n):
lst = []
for j in c:
lst.append(abs(i-j))
cityDiff[i] = min(lst)
for key, value in cityDiff.items():
if value > maxDiff: maxDiff = value
return maxDiff
</code></pre>
<p><strong>2. Using lists in Python:</strong> <em>Failed two cases in Timeout only</em></p>
<pre><code>def flatlandSpaceStations(n, c):
# n is the number of cities
# c is the array of space station exists in the city(s)
maxDiff = []
if n == len(c):
return 0
else:
for i in range(n):
minDis = []
for j in c:
minDis.append(abs(i-j))
maxDiff.append(min(minDis))
return max(maxDiff)
</code></pre>
<p>I want to find some optimum solution, which I can understand. The above programs have a very bad time complexity I know, but this is only solution I can think of right now. Any help would be appreciated.</p>
<p>As per <a href="https://codereview.stackexchange.com/users/40480/vnp">vnp's</a> suggestion, I have made another attempt, and made the solution optimized, but it is not working out for the <em>Two test cases due to timeout</em> issue.</p>
<p><strong>Solution <span class="math-container">\$O(n^2)\$</span>:</strong></p>
<pre><code>def flatlandSpaceStations(n, c):
# n is the number of cities
# c is the array of space station exists in the city(s)
maxDiff = []
if n == len(c):
return 0
else:
for i in range(n):
minVal = float('inf')
for j in c:
if abs(i-j) < minVal: minVal = abs(i-j)
maxDiff.append(minVal)
return max(maxDiff)
</code></pre>
<p>I am attaching one of the two time out failure test case here for more insight.</p>
<p><a href="https://hr-testcases-us-east-1.s3.amazonaws.com/15233/input14.txt?AWSAccessKeyId=AKIAJ4WZFDFQTZRGO3QA&Expires=1587687462&Signature=bhQdNYqLfPszaAYP2tL8InphuDw%3D&response-content-type=text%2Fplain" rel="nofollow noreferrer">TEST CASE</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T21:18:48.000",
"Id": "473067",
"Score": "1",
"body": "Hint: sort the list of space stations. Then find the maximum distance between consecutive stations in the sorted list."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T22:13:34.697",
"Id": "473074",
"Score": "0",
"body": "Hey @vnp, I have tried an optimum solution with your suggestion, but I guess this doesn't work out for me. I don't know but Python is seeming a bit slow for my solution. I am adding one more attempt in my question please see"
}
] |
[
{
"body": "<h1>builting <code>min</code></h1>\n\n<pre><code>minVal = float('inf')\nfor j in c:\n if abs(i-j) < minVal: minVal = abs(i-j)\n</code></pre>\n\n<p>can be rewritten using min: <code>min(abs(i-j) for j in c)</code>.</p>\n\n<p>Apart from that, placing the code on the same line as the check looks very unreadable to me.</p>\n\n<p>There is also no need to keep the values in a list, </p>\n\n<pre><code>for i in range(n):\n lst = []\n for j in c:\n lst.append(abs(i-j))\n cityDiff[i] = min(lst)\n</code></pre>\n\n<p>can be </p>\n\n<pre><code>max(min(abs(i - j) for j in c) for i in range(n))\n</code></pre>\n\n<h1>variable names</h1>\n\n<p><code>i</code> and <code>j</code> are useful variable names as counters. Here you use them as citie and space station. The same goes for <code>c</code>, which are the space stations.Then call em like that:</p>\n\n<pre><code>max(\n min(abs(space_station - city) for space_station in space_stations)\n for city in range(n)\n)\n</code></pre>\n\n<h1>space stations</h1>\n\n<p>A first improvement I would suggest if the city you want to check is a space station or not. In your naive algorithm you do <code>m x n</code> checks. This will reduce it by <code>m x m</code>. If you use a set for the space stations, this inclusion check will be quick.</p>\n\n<pre><code>space_station_set = set(space_stations)\nmax(\n min(abs(space_station - city) for space_station in space_stations)\n for city in range(n) if city not in space_station_set \n)\n</code></pre>\n\n<h1>sorting space stations</h1>\n\n<p>If you sort the space stations, you can use this fact.</p>\n\n<pre><code>space_stations = [1, 4, 7]\nspace_stations_sorted = (\n [float(\"-inf\")] + sorted(space_stations) + [float(\"inf\")]\n)\nspace_station_pairs = (\n (space_stations_sorted[i], space_stations_sorted[i + 1])\n for i in range(len(space_stations) + 1)\n)\n</code></pre>\n\n<p>This will generate pairs of adjacent space stations. I added the <code>inf</code>s to take care of the edges</p>\n\n<pre><code>list(space_station_pairs)\n</code></pre>\n\n<blockquote>\n<pre><code>[(-inf, 1), (1, 4), (4, 7), (7, inf)]\n</code></pre>\n</blockquote>\n\n<p>Then you loop through the cities like this:</p>\n\n<pre><code>one, two = next(space_station_pairs)\ndistance_max = float(\"-inf\")\nfor city in range(n):\n if city == two:\n one, two = next(space_station_pairs)\n continue\n distance = min((city-one), (two-city))\n distance_max = max(distance, distance_max)\n</code></pre>\n\n<p>This way you only loop once through the cities and twice through the space stations, so you reduced the complexity to <code>O(n)</code>.</p>\n\n<h1>looping only over the space stations:</h1>\n\n<p>The furthest city will always be either in the middle between 2 space stations or at the edges of the map. You can use this fact to</p>\n\n<pre><code>space_stations_sorted = sorted(space_stations)\ndistance_max = max(\n (two - one) // 2 for one, two in pairwise(space_stations_sorted)\n)\ndistance_max_total = max(\n distance_max, space_stations_sorted[0], n - space_stations_sorted[-1] - 1\n)\n</code></pre>\n\n<p>this loops only once over the space stations, and leaves the cities untouched.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T09:42:32.527",
"Id": "473115",
"Score": "0",
"body": "Hey **Maarten**, thank you for the detailed explanation, but while testing this code `max(min(abs(i - j) for j in c) for i in range(n))` gives the error: `ValueError: min() arg is an empty sequence`. I have tried using wrapping into `list()`. Always same result"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T10:25:13.277",
"Id": "473131",
"Score": "0",
"body": "only if `c` is empty"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T06:46:00.627",
"Id": "241115",
"ParentId": "241097",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T20:41:25.933",
"Id": "241097",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"functional-programming",
"comparative-review"
],
"Title": "Maximum distance between space stations HackerRank"
}
|
241097
|
<p>Wanted to get familiarize myself with CSV Files handling and <code>datetime</code> library so I wrote this small project where:
when the user enters a string into the console the program saves the time at which the string was entered and marks it as the start time.
when the user reenters the same string the activity is considered over and the end time is recorded as well and duration is then calculated.
At the end of the program everything is saved to three CSV files:</p>
<ol>
<li><code>pending.csv</code>: has one pair of strings, <code>start_time</code>, <code>cs-values</code></li>
<li><code>duration.csv</code>: has one pair of strings, <code>time_delta</code>, <code>cs-values</code>.</li>
<li><code>records.csv</code>: has three strings, <code>start_time</code>, <code>end_time</code>, <code>cs-values</code>.</li>
</ol>
<p>The code is looking pretty messy and not straightforward.
Any suggestions?</p>
<pre><code>from datetime import datetime as dt
from datetime import timedelta
from csv import reader, writer
from parse_time import parse_delta
def display_dict(p: dict):
'''
simply displayes the key, value pairs of a dictonary.
'''
if len(p) <= 0:
max_length = 0
print('Empty...')
else:
max_length = max([len(key) for key in p.keys()])
for key, value in p.items():
prop_space = ' ' * (max_length - len(key))
print(key.capitalize(), prop_space, ':', value)
print('-'*40)
print()
time_format = '%Y-%m-%d %H:%M:%S.%f' #python datetime default format.
#read pending activity data from csv file
#reads string, datetime pairs from a csv file and assigns them to a dictionary
#where strings(names of activities) are keys and datetime object(start time of the activity)
#are the values.
try:
with open('pending.csv', 'r+', newline='') as p:
csv_reader = reader(p)
pending = {}
for line in csv_reader:
activity = line[0]
time = dt.strptime(line[1], time_format)
pending[activity] = time
#if the file doesn't exist create it:
except FileNotFoundError:
with open('pending.csv', 'x') as p:
pending = {}
#read activities durations in days, hours, minutes, seconds data from csv file.
#same procedure but assigns a string, timedelta object pairs.
try:
with open('duration.csv', 'r+', newline='') as d:
csv_reader = reader(d)
durationS = {}
for line in csv_reader:
activity = line[0]
# function to parse the default output string of dt.now() function.
#and convert it into a timedelta object
duration = parse_delta(line[1])
durationS[activity] = duration
except FileNotFoundError:
with open('duration.csv', 'x') as p:
durationS = {}
#read records data from csv file.
#gets a dictionary where the keys are activity names(strings) and the values lists
#of lists (d = {key: [ [time, time], [time, time]] , key2:...etc})
try:
with open('records.csv', 'r+', newline='') as r:
csv_reader = reader(r)
records = {line[0]: [] for line in csv_reader}
r.seek(0)
for line in csv_reader:
activity = line[0]
start_time = dt.strptime(line[1], time_format)
end_time = dt.strptime(line[2], time_format)
if activity not in records:
records[activity] = []
records[activity].append([start_time, end_time])
except FileNotFoundError:
with open('records.csv', 'x') as p:
records = {}
#main command line loop
while True:
print('_'*40), print()
display_dict(pending) #display the currently in progress activities
print()
print('_'*10, '|')
new_activity = input('...').lower() #input command.
print('_'*10, '|')
print()
#checking for typos.
typo = 0
for char in 'duration':
if char in new_activity:
typo += 1
if typo >= 7 and new_activity != 'duration':
confirm = input('Did you mean "Duration? "')
if confirm in ['yes', 'y']:
new_activity = 'duration'
#checking required action.
if new_activity == '':
break
#delete an entry: -pd flag removes entry without user confirmation
elif new_activity[0:3] == 'del':
del_activity = new_activity.replace('del', '', 1).lstrip()
if '-pd' in del_activity:
pending_duration = 'pd'
elif '-p' in del_activity:
pending_duration = 'p'
elif '-d' in del_activity:
pending_duration = 'd'
else:
pending_duration = ''
del_activity = del_activity.replace('-pd', '', 1).replace('-d', '', 1).replace('-p', '', 1).rstrip()
if 'p' in pending_duration:
if del_activity in pending:
pending.pop(del_activity)
print(f'Deleted "{del_activity}" from pending.')
else:
print(f'{del_activity} was not found in pending.')
if 'd' in pending_duration:
if del_activity in durationS:
print(f'Deleted "{del_activity} from durations.')
durationS.pop(del_activity)
else:
print(f'{del_activity} was not found in duration')
#if not 'pd' flag in command: ask user for confirmation before deletion.
if 'p' not in pending_duration and 'd' not in pending_duration:
if del_activity in pending:
confirm = input(f'Delete "{del_activity}" from pending? ')
if confirm in ['yes', 'y']:
pending.pop(del_activity)
print(f'"{del_activity}" succesfully removed from pending activities')
if del_activity in durationS:
confirm = input(f'Remove "{del_activity}" from durations log?')
if confirm in ['yes', 'y']:
durationS.pop(del_activity)
print(f'"{del_activity}" Succesfully removed form duration.')
elif del_activity == '':
print('Usage: del {key}')
elif 'p' not in pending_duration and 'd' not in pending_duration:
print("Activity Doesn't Exit")
#type duration at command line to display current durations list
elif new_activity == 'duration':
display_dict(durationS)
#end activities in progress and save their duration and their start and end times.
#if a name of a pending activity is entered at command line the activity is assummed
#to be finished.
elif new_activity in pending:
print(f'"{new_activity}" ended at {dt.now()}')
duration = dt.now() - pending[new_activity]
print(f'Duration is: {duration}')
durationS[new_activity] += duration
if new_activity not in records:
records[new_activity] = []
records[new_activity].append([pending[new_activity], dt.now()])
pending.pop(new_activity)
#if entry is a new entry and is not a command ie.: 'del', 'duration', etc...
else:
pending[new_activity] = dt.now()
if new_activity not in durationS:
durationS[new_activity] = timedelta(0)
if new_activity not in records:
records[new_activity] = []
print(f'"{new_activity}" Started at {dt.now()}.') #print to the screen the start
#time of the entered activity
print(), print(), print(), print(), print(), print(), print(), print()
#if user exist program before this point the new entry data is not saved and the most recent
#file is perserved
#overwriting pending data to file.
with open('pending.csv', 'w', newline='') as p:
csv_writer = writer(p)
for key, value in pending.items():
csv_writer.writerow([key, value])
#overwriting duration data to file.
with open('duration.csv', 'w', newline='') as d:
csv_writer = writer(d)
for key, value in durationS.items():
csv_writer.writerow([key, value])
#overwriting records data to file.
with open('records.csv', 'w', newline='', encoding='utf-8') as r:
csv_writer = writer(r)
for key, value in records.items():
for time_list in records[key]:
start_time = time_list[0]
end_time = time_list[1]
csv_writer.writerow([key, start_time, end_time])
</code></pre>
<p>parse_delta file:</p>
<pre><code>from datetime import timedelta
def parse_delta(d: str):
'''
returns a timedelta object that is parsed from the default
string format outputed by the datetime.datetime.now() function
'''
time = []
if 'day' in d:
for char in d:
if char.isnumeric():
time.append(char)
elif char == 'd':
time.append('')
days = ''
time_copy = time.copy()
for i in range(len(time)):
if time_copy[i] == '':
break
days += time_copy[i]
time.remove(time_copy[i])
days = int(days)
if len(time) == 12: #if hours value is two digits instead of 1
index = 1
else:
index = 2
hours = int(''.join(time[1: 1 + index]))
minutes = int(''.join(time[1 + index: 3 + index]))
seconds = int(''.join(time[3 + index: 5 + index]))
try: #assigning this varible on timedelta(0) causes an error as there
#are no milliseconds in the string
milliseconds = int(''.join(time[5 + index:]))
except:
milliseconds = 0
# if string doesn't have any days
else:
for char in d:
if char.isnumeric():
time.append(char)
if len(time) == 12:
index = 1
else:
index = 0
days = 0
hours = int(''.join(time[0: 1 + index]))
minutes = int(''.join(time[1 + index: 3 + index]))
seconds = int(''.join(time[3 + index: 5 + index]))
try:
milliseconds = int(''.join(time[5 + index:]))
except:
milliseconds = 0
delta = {'days': days, 'hours': hours, 'minutes': minutes, 'seconds': seconds, 'milliseconds': milliseconds}
return timedelta(**delta)
</code></pre>
|
[] |
[
{
"body": "<h2>File layout</h2>\n\n<p>The choice of splitting your data into three files seems odd to me. I'm not sure what <code>cs-values</code> is, but I imagine you can get away with only <code>records.csv</code> and columns:</p>\n\n<ul>\n<li><code>start_time</code></li>\n<li><code>end_time</code></li>\n<li><code>state</code></li>\n<li><code>cs_values</code></li>\n</ul>\n\n<p>(Underscore for consistency.) Duration wouldn't be useful to store separately since it can be calculated as the difference between the start and end. <code>state</code> would be serialized from an enumeration, being <code>PENDING</code>, etc.</p>\n\n<h2>Typo</h2>\n\n<p><code>displayes</code> -> <code>displays</code></p>\n\n<h2>Negative length?</h2>\n\n<pre><code>if len(p) <= 0:\n</code></pre>\n\n<p>doesn't make a lot of sense for a <code>dict</code>. If you write <code>if not p</code>, it will catch both a <code>None</code> reference and a zero-length reference. Dictionaries can never have a negative length.</p>\n\n<h2>Inner lists</h2>\n\n<p>The brackets should be dropped from this:</p>\n\n<pre><code>max([len(key) for key in p.keys()])\n</code></pre>\n\n<p>because you don't need an intermediate, in-memory list.</p>\n\n<h2>display_dict</h2>\n\n<p>I'm not sure what this offers that <code>pprint</code> doesn't. I would just use <code>pprint</code>. The formatting is not exactly the same, but <code>pprint</code> has more functionality for nested structures and is a built-in module.</p>\n\n<h2>Global constants</h2>\n\n<pre><code>time_format = '%Y-%m-%d %H:%M:%S.%f' #python datetime default format.\n</code></pre>\n\n<p>should have a capitalized variable, i.e. <code>TIME_FORMAT</code>.</p>\n\n<h2>Unpacking</h2>\n\n<pre><code> activity = line[0]\n time = dt.strptime(line[1], time_format) \n</code></pre>\n\n<p>can use unpacking from <code>line</code>:</p>\n\n<pre><code>activity, time_str = line\n</code></pre>\n\n<h2>Read-or-create</h2>\n\n<p>This logic seems odd:</p>\n\n<pre><code>try:\n with open('pending.csv', 'r+', newline='') as p:\n csv_reader = reader(p)\n pending = {}\n for line in csv_reader:\n activity = line[0]\n time = dt.strptime(line[1], time_format) \n pending[activity] = time\n#if the file doesn't exist create it:\nexcept FileNotFoundError: \n with open('pending.csv', 'x') as p:\n pending = {}\n</code></pre>\n\n<p>If the file does not exist, why create it here? Write mode will create it if it does not exist.</p>\n\n<h2>Did you mean</h2>\n\n<p>This:</p>\n\n<pre><code>#checking for typos.\ntypo = 0\nfor char in 'duration':\n if char in new_activity:\n typo += 1\n</code></pre>\n\n<p>is a somewhat rough string distance. You should read about the <a href=\"https://en.wikipedia.org/wiki/Levenshtein_distance\" rel=\"nofollow noreferrer\">Levenshtein distance</a>.</p>\n\n<h2>Multiple <code>print</code></h2>\n\n<p>This:</p>\n\n<pre><code>print(), print(), print(), print(), print(), print(), print(), print() \n</code></pre>\n\n<p>can just be replaced by</p>\n\n<pre><code>print('\\n' * 7)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T22:15:50.093",
"Id": "473075",
"Score": "0",
"body": "I meant comma separated values with cs-values. I also wanted a way that enables me to read data from a file without truncating it and in case it doesn't exist; create it. opening a file in 'w+', 'w', 'a+' creates a file if it's not found but truncates the file if it exits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T22:27:20.827",
"Id": "473078",
"Score": "0",
"body": "opening a file in 'rb+' mode raises a FileNotFoundError if the file does not exits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T22:29:47.630",
"Id": "473079",
"Score": "0",
"body": "As for separating the data in three files: this is because when reading data from the files at a later time I can differentiate between pending data, duration data and records data. As they all contain similar formats so it will be hard to differentiate them from each other if they are all kept in the same file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T22:59:55.477",
"Id": "473081",
"Score": "0",
"body": "OK; so for the file mode, https://stackoverflow.com/a/20433067/313768 ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T23:20:44.443",
"Id": "473085",
"Score": "0",
"body": "This is basically the same as try.. except but using os module"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T23:21:38.057",
"Id": "473086",
"Score": "0",
"body": "It's different because (1) it would be done directly before the write, instead of directly after the read; and (2) it doesn't require logic-by-exception, which I consider an anti-pattern."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T21:43:15.543",
"Id": "241102",
"ParentId": "241098",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "241102",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T21:17:09.863",
"Id": "241098",
"Score": "2",
"Tags": [
"python"
],
"Title": "CSV Files- Time Tracker"
}
|
241098
|
<p>I'm trying to build a CLI that runs until the user decides to exit. The functionality of the CLI is to be able to explore a json-file by typing commands into the terminal while the program is running.</p>
<p>Right now commands are checked against <code>if/else</code> statements, but I would like to add so that commands are checked in the manner of the <code>argparse</code> module, but can't figure out how that is done while the program is running. Because I'm unable to figure that out, class methods are mapped to specific commands and executed when the command is specified without having to rely in <code>if/else</code> logic.</p>
<p>The biggest issue is not single commands as <code>-v</code> because they are easy to map to a function with dict. But commands that are <code>-v LEAGUE</code> where <code>LEAGUE</code> or <code>-d LEAGUE SEASON TYPE</code> is much harder to map without creating big dictionaries since the arguments can be vary. Any suggestion how that can be improved is highly appreciated!</p>
<pre><code>import os
import sys
class CLIStats:
def __init__(self):
"""Displays the welcome screen and loads the season-params.json
which contains the avalible leagues and their seasons that
can be downloaded. Pickled with pre-proccessed IDs is also loaded.
"""
self.header = self.header()
self.description = self.description()
self.commands = self.commands()
self.leagues = {'EN_PR': ['2019/2020', '2018/2019', '2017/2018', '2016/2017'],
'EU_CL': ['2019/2020', '2018/2019', '2017/2018', '2016/2017'],
'ES_PL': ['2019/2020', '2018/2019', '2017/2018', '2016/2017']}
@staticmethod
def header():
"""Display's welcome message"""
os.system('clear')
print('\t','*'*60)
print("\t\t*** Welcome - Football Stats generator ***")
print('\t','*'*60)
@staticmethod
def description():
"""Display's short description"""
print('Interface to download: \t playerstats \t fixturestats \t team standing \n')
print('Type "exit" to terminate shell')
@staticmethod
def commands():
"""Display's avalible commands and how to use them"""
commands = {'View Leagues': '-v',
'View League Seasons': '-v LEAGUE',
'Download stats': '-d LEAGUE SEASON TYPE',
'Help' : '-h',}
for key, value in commands.items():
print("{: <25} {}".format(key, value))
print('\n')
def view_leagues(self):
"""Prints out leagues in self.leagues"""
for league in self.leagues.keys():
print("{: <10}".format(league), end="")
print('\n')
def view_seasons(self, league):
"""Prints seasons for a league in self.leagues"""
if league in self.leagues:
seasons = self.leagues[league]
print(league,'seasons:')
for season in seasons:
print("{: <20}".format(season), end="")
print('\n')
else:
print(league, 'is not avalible')
print('\n')
def view_league_args(self):
"""Creates a list with set of args that can be passed
by user to execute view_league()"""
args = []
for league in self.leagues.keys():
args.append('-v' + ' ' + league)
return args
def main():
"""Runs the interface"""
interface = CLIStats()
cmd = {'-v': interface.view_leagues,
'exit': sys.exit,
'View Stats Type': '-s',
'-h' : 'interface.help', }
while True:
usr_command = input('CLIStats$ ')
if usr_command in cmd.keys():
cmd.get(usr_command)()
elif usr_command in interface.view_league_args():
league = usr_command.split(' ')[-1]
interface.view_seasons(league)
elif len(usr_command.split(' ')) == 4:
league = usr_command.split(' ')[1]
season = usr_command.split(' ')[2]
stat_type = usr_command.split(' ')[3]
interface.download_stats(league, season, stat_type)
else:
if usr_command.split(' ')[0] not in cmd.keys():
print('Command not valid')
else:
print('Could not find the specified params')
if __name__ == '__main__':
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T22:08:49.863",
"Id": "473072",
"Score": "0",
"body": "Take a look at [docopt](http://docopt.org). It is really a way to deal with arguments."
}
] |
[
{
"body": "<h2>League representation</h2>\n\n<p>This:</p>\n\n<pre><code> self.leagues = {'EN_PR': ['2019/2020', '2018/2019', '2017/2018', '2016/2017'],\n 'EU_CL': ['2019/2020', '2018/2019', '2017/2018', '2016/2017'],\n 'ES_PL': ['2019/2020', '2018/2019', '2017/2018', '2016/2017']}\n</code></pre>\n\n<p>seems excessive. At most, you should need to store:</p>\n\n<ul>\n<li>The minimum and maximum years as <code>int</code></li>\n<li>The set of league names: <code>{'EN_PR', 'EU_CL', 'ES_PL'}</code></li>\n</ul>\n\n<p>Everything else can be derived.</p>\n\n<h2>Grammar</h2>\n\n<pre><code>Display's avalible commands and how to use them\n</code></pre>\n\n<p>to</p>\n\n<pre><code>Displays available commands and how to use them\n</code></pre>\n\n<p>and</p>\n\n<pre><code>is not avalible\n</code></pre>\n\n<p>to</p>\n\n<pre><code>is not available\n</code></pre>\n\n<h2>Generator</h2>\n\n<pre><code> args = []\n for league in self.leagues.keys():\n args.append('-v' + ' ' + league)\n return args \n</code></pre>\n\n<p>can be</p>\n\n<pre><code>return ' '.join(f'-v {league}' for league in self.league_names)\n</code></pre>\n\n<p>assuming that <code>league_names</code> holds the set previously described.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T07:32:06.360",
"Id": "473108",
"Score": "0",
"body": "That you for your comments, `self.leagues` is normally a json file that is loaded so what you see is just a representation of it's content that is retrieved from an API. Thank you for taking your time to lift these things into light!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T22:58:13.097",
"Id": "241103",
"ParentId": "241099",
"Score": "1"
}
},
{
"body": "<h3>cmd.Cmd</h3>\n\n<p>Although <code>argparse()</code> could be abused to provide some of the desired functionality, it isn't the right tool. For example, it is designed to exit when an error is detected, such as an unrecognized command or missing argument. </p>\n\n<p><a href=\"https://docs.python.org/3.7/library/cmd.html#module-cmd\" rel=\"nofollow noreferrer\"><code>cmd</code></a> in the standard library is a much better tool for this. Writing a command interpreter is as simple as coding a subclass of <code>cmd.Cmd</code> and defining \"do_command\" methods for each command you need, e.g. <code>do_view()</code>, <code>do_download()</code>, etc. Here's an example based on your code, but the \"do_command()\" methods just print something.</p>\n\n<pre><code>import cmd \n\nclass StatShell(cmd.Cmd):\n intro = '\\n'.join([\n \"\\t\" + \"*\"*60,\n \"\\t\\t*** Welcome - Football Stats generator ***\",\n \"\\t\" + \"*\"*60,\n \"\",\n \"\\tType help or ? to list commands,\",\n \"\\t\\tor help command to get help about a command.\"\n ])\n prompt = \"CLIStats: \"\n\n\n def do_download(self, arg):\n \"\"\"Download statistics: download LEAGUE SEASON TYPE\"\"\"\n arg = arg.split()\n if len(arg) == 3:\n league, season, type = arg\n print(f\"downloading {league} {season} {type}\")\n else:\n self.error(\"bad 'download' command.\")\n\n\n def do_exit(self, arg):\n \"\"\"Exit the interpreter.\"\"\"\n print(\"exiting ...\")\n return True\n\n\n def do_view(self, arg):\n \"\"\"view leagues or seasons: view [LEAGUE] \"\"\"\n if arg:\n league = arg[0]\n print(league,'seasons: ...')\n\n else:\n print('leagues ...')\n\n\ndef main():\n StatShell().cmdloop()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T07:34:37.233",
"Id": "473109",
"Score": "0",
"body": "thank you for providing an example, found out about `cmd` while digging into `docopt` that was mentioned by @vnp. I will certainly use this approach as it is exactly what I'm looking fot. Thank you for taking your time!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T07:00:08.027",
"Id": "241117",
"ParentId": "241099",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "241117",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T21:26:37.623",
"Id": "241099",
"Score": "1",
"Tags": [
"python",
"console"
],
"Title": "CLI application for Football Stats Generator"
}
|
241099
|
<p>Ok, so I want to find out if my approach towards a custom interpreter is pragmatic and if not how to implement it in a better way.
this is purely for fun and practice and to find out more about how to implement a good interpreter.
when I get a good grip on what to do I want to implement this into a Unity game.</p>
<p>Any tips, concepts, or ideas would be greatly appreciated.</p>
<p>Here I have my Tokenizer:</p>
<pre><code>public static List<Tuple<string, string>> GetTokens(string input)
{
List<Tuple<string, string>> ret = new List<Tuple<string, string>>();
Regex r = new Regex("(?<Comma>\\,)" +
"|(?<Dot>\\.)" +
"|(?<SemiColon>\\;)" +
"|(?<DoubleDot>\\:)" +
"|(?<Increment>\\+\\+)" +
"|(?<Decrement>\\-\\-)" +
"|(?<SystemCommand> *deviceListCount *| *deviceList *| *devices *| *device *| *str *| *int *| *dev *| *bool *| *print *| *wait *| *device *| *if *| *while *| *loop *)" +
"|(?<OpenBracket>\\()" +
"|(?<CloseBracket>\\))" +
"|(?<OpenBlockBracket>\\[)" +
"|(?<CloseBlockBracket>\\])" +
"|(?<DeviceCommand> *On *| *Off *| *Open *| *Close *| *Move *| *Detect *)" +
"|(?<Integer>\\d+)" +
"|(?<Equals> *[=] *)" +
"|(?<Greater>\\>)" +
"|(?<Smaller>\\<)" +
"|(?<Exclamation>\\!)" +
"|(?<String>[aA-zZ0-9 ]*)");
foreach (Match item in r.Matches(input))
{
for (int i = 1; i < item.Groups.Count; i++)
{
string v = item.Groups[i].Value;
if (v != "")
{
ret.Add(new Tuple<string, string>(r.GroupNameFromNumber(i), v));
}
}
}
List<Tuple<string, string>> ret1 = new List<Tuple<string, string>>();
foreach (var item in ret)
{
ret1.Add(new Tuple<string, string>(item.Item1, item.Item2.Trim()));
}
return ret1;
}
</code></pre>
<p>Here I have the Method that Executes my interpreter's commands (i am not finished adding all the commands I want to find out if this approach is viable before I finish it) I am mainly concerned about the code below:</p>
<pre><code>public static void RunCode(string input)
{
var g = GetTokens(input);
for (int i = 0; i < g.Count; i++)
{
if (g[i].Item2 == "print")
{
Console.WriteLine(GetVariable(UntilNestedEnd(g, ref i)));
}
else if (g[i].Item2 == "loop")
{
int cnt = int.Parse(g[i + 2].Item2);
i += 2;
string nested = UntilNestedEnd(g, ref i);
for (int x = 0; x < cnt; x++)
{
RunCode(nested);
}
}
else if (g[i].Item2 == "str")
{
SetVar(ref g,"str",ref i);
}
else if (g[i].Item2 == "int")
{
SetVar(ref g, "int", ref i);
}
else if (g[i].Item2 == "bool")
{
SetVar(ref g, "bool", ref i);
}
else if (g[i].Item2 == "dev")
{
SetVar(ref g, "dev", ref i);
}
else if (g[i].Item2 == "if")
{
var left = GetVariable(g[i + 2].Item2);
string op = g[i + 3].Item2;
dynamic Right = null;
if (g[i + 4].Item2 == "True"| g[i + 4].Item2 == "true")
{
Right = true;
}
else if (g[i + 4].Item2 == "False" | g[i + 4].Item2 == "false")
{
Right = false;
}
else
{
Right = GetVariable(g[i + 4].Item2);
}
i += 4;
string nested = UntilNestedEnd(g, ref i);
switch (op)
{
case "=":
if (left == Right)
{
RunCode(nested);
}
break;
case "!":
if (left != Right)
{
RunCode(nested);
}
break;
case ">":
if (float.Parse(left) > float.Parse(Right))
{
RunCode(nested);
}
break;
case "<":
if (float.Parse(left) < float.Parse(Right))
{
RunCode(nested);
}
break;
default:
break;
}
}
}
}
</code></pre>
<p>Here i have a Method that retrieves nested commands:</p>
<pre><code>public static string UntilNestedEnd(List<Tuple<string, string>> t, ref int i)
{
string inner = "";
int nested = 0;
while (true)
{
if (i < t.Count-1)
{
i++;
if (t[i].Item2 == ")")
{
nested--;
if (nested > 0)
{
inner += t[i].Item2;
}
}
else if (t[i].Item2 == "(")
{
if (nested > 0)
{
inner += t[i].Item2;
}
nested++;
}
else
{
inner += t[i].Item2;
}
if (nested == 0)
{
break;
}
}
}
return inner;
}
</code></pre>
<p>Here are the rest of the Methods i use to store or retrieve variables:</p>
<pre><code> public static Dictionary<string, string> devices = new Dictionary<string, string>();
public static Dictionary<string, string> memory = new Dictionary<string, string>();
public static Dictionary<string, bool> booleans = new Dictionary<string, bool>();
public static dynamic GetVariable(string key)
{
if (memory.ContainsKey(key))
{
return memory[key];
}
else if (booleans.ContainsKey(key))
{
return booleans[key];
}
else if (devices.ContainsKey(key))
{
return devices[key];
}
else
{
return key;
}
}
public static void SetVar(ref List<Tuple<string, string>> g, string type,ref int i)
{
i++;
string v = g[i].Item2;
i += 2;
string m = g[i].Item2;
switch (type)
{
case "str":
if (memory.ContainsKey(v))
{
memory[v] = m;
}
else
{
memory.Add(v, m);
}
break;
case "int":
if (memory.ContainsKey(v))
{
memory[v] = m;
}
else
{
memory.Add(v, m);
}
break;
case "bool":
if (booleans.ContainsKey(v))
{
booleans[v] = bool.Parse(m);
}
else
{
booleans.Add(v, bool.Parse(m));
}
break;
case "dev":
if (devices.ContainsKey(v))
{
devices[v] = m;
}
else
{
devices.Add(v, m);
}
break;
default:
break;
}
}
</code></pre>
<p>Lastly here is the Main program with some example commands:</p>
<pre><code>static void Main(string[] args)
{
RunCode("if:1=1(loop:2(loop:2(loop:2(print(Hello There)))))");
Console.ReadLine();
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T17:09:03.807",
"Id": "473174",
"Score": "0",
"body": "it should only handle basic types, string, float, int, bool, and references to devices that's all, I have this script example for when a group of cameras spots the main player it turns an alarm on or off, \nbool seen = false;\nint count = 0;\ndev alarm = Alarm1;\ndevices(Camera)\nwhile(seen=false:\ncount++;\ndeviceList[count].Detect(me:seen)\nif(seen=true:alarm.On) \nif(count>deviceListCount:count=0)\n) so commands like print(a*b-1) wont really be needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T17:24:15.463",
"Id": "473177",
"Score": "0",
"body": "I'll give it a try, thanks for the help, I appreciate it a lot."
}
] |
[
{
"body": "<p>First of all: I know, it is fun to implement your own parser from scratch and it is also reasonable for getting a better understanding of how parsers work... however if your goal is to build a custom language for your unity game, I strongly recommend to use one of the available parser generators (e.g. <a href=\"https://www.antlr.org/\" rel=\"nofollow noreferrer\">ANTLR</a>).</p>\n\n<p><strong>Concept</strong></p>\n\n<p>Your approach is: </p>\n\n<ul>\n<li><p>Create Tokens</p></li>\n<li><p>Evaluate Tokens</p></li>\n</ul>\n\n<p>That is the normal \"naive approach\" when trying to parse something for the first time... However, usually parsers have one step between them where tokens are build up to an <a href=\"https://en.wikipedia.org/wiki/Abstract_syntax_tree\" rel=\"nofollow noreferrer\">abstract syntax tree</a>. The abstract syntax tree is simply spoken an hierarchically object mode that represents the parsed code.</p>\n\n<p>Evaluating the abstract syntax tree is relatively simple, because the complexity of nested expressions prioritized by brackets and so on are implicitly represented by the hierarchy.</p>\n\n<p>If you want to improve your implementation, I recommend creating such an abstract syntax tree before evaluating it.</p>\n\n<p><strong>Code</strong></p>\n\n<ul>\n<li>Error handling code is totally missing - there is no guarantee, that the tokens are in the right order</li>\n<li>GetTokens returns a tuple. I would use a custom type \"Token { Name:string , Vale:string }\" instead, because it is much more readable.</li>\n</ul>\n\n<p><strong>Examples for AST realizations</strong></p>\n\n<ul>\n<li>The .Net Framework has a build-in object model: <a href=\"https://docs.microsoft.com/de-de/dotnet/csharp/programming-guide/concepts/expression-trees/\" rel=\"nofollow noreferrer\">Expression Trees</a></li>\n<li>The Roslyn Compiler provides function for creating AST from C#/F#/VB code: <a href=\"https://github.com/dotnet/roslyn/wiki/Getting-Started-C%23-Syntax-Analysis\" rel=\"nofollow noreferrer\">https://github.com/dotnet/roslyn/wiki/Getting-Started-C%23-Syntax-Analysis</a></li>\n<li>Googel provides lots of information about the topic + lots of example implementations. A simple calculator may be a good point to start with</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T07:54:00.557",
"Id": "473110",
"Score": "0",
"body": "This is exactly what I needed, thanks a lot!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T07:55:46.573",
"Id": "473111",
"Score": "0",
"body": "do you maby know of any documentation regarding AST, like how to implement one in c#?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T10:21:40.413",
"Id": "473128",
"Score": "1",
"body": "@TyperMan1133: see my updated answer. Just google for \"calculator abstract syntax tree C#\" will provide lots of simple example to play with / learn from"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T06:42:33.987",
"Id": "241114",
"ParentId": "241100",
"Score": "3"
}
},
{
"body": "<p>in order to make a smart interpreter <strong>make parser recursive</strong>can handle expressions and statements , generate abstract syntax tree and evaluate semantic errors(data type and casting errors) here you are only dealing with syntax's \n set your symbols \n ie</p>\n\n<pre><code>const int L_PAREN = 19;\nconst int R_PAREN = 20;\nconst int WHILE = 21;\nconst int DO = 22;\nconst int IF = 23;\nconst int ELSE = 24;\nconst int THEN = 25;\nconst int END = 26;\nconst int PRINT = 27;\nconst int ERROR = 37; \n</code></pre>\n\n<p>first your token generator must be modified in general</p>\n\n<pre><code> function geToken ()\n {\n if operant == sometype then\n return token(token_type,current_line,current_column)\n else if another_operant ==some_type\n do the same;\n } \n</code></pre>\n\n<p>after that make a parser</p>\n\n<pre><code> currentToken = lex.getToken();\n if(currentToken.type() == Id //or int or char or something\n then\n either add to an abstract syntax tree\n evaluvate(token,\"expected '='\"); \n</code></pre>\n\n<p>you can use a peephole optimizer if you are using complex expressions anyway\ni will provide a link pls check it out it is c++ don't worry it is simple you can convert them into c# or java other wise you will get an idea of making a better interpreter.thanks!\n<a href=\"https://github.com/bheinzelman/Mini-Language\" rel=\"nofollow noreferrer\">this is mini lang very mini</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T16:30:28.700",
"Id": "473168",
"Score": "0",
"body": "Can I ask for some details on how to implement what you explained for just 1 command as a start so I can understand it a little better, for example just, print(\"Hello World\"), or something simple like that"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T09:27:41.850",
"Id": "241126",
"ParentId": "241100",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T21:27:15.067",
"Id": "241100",
"Score": "2",
"Tags": [
"c#",
"interpreter",
"lexer"
],
"Title": "Optimization of a custom interpreter"
}
|
241100
|
<p>Could you please help me optimize the macro, Its taking more than 50 minutes but still no success.</p>
<p>The For loop is looping untill 1.0 million + rows.
Screen is flickering.
I have tried Application.ScreenUpdating = True but it still flickers and for loop is taking very long time.</p>
<p>I am downloading reports from sharepoint and checking for past 7 days file.</p>
<p>File Names:</p>
<p>Fsplit2 = "Interim Inventory Tracker - All States " & Format(Now - i, "mmddyy") & " v1.xlsx"</p>
<p>F4 = "Inventory Export " & Format(Now - i, "yyyy-mm-dd") & " AM.xlsm"</p>
<p>From f4 i am updating values into Fsplit2 based on the Group name and conditions mentioned below in code.</p>
<pre><code>Sub DownloadPastInterimTracker()
Dim myURL As String
Dim f1 As String
Dim f2 As String
Dim WinHttpReq As Object
Fsplit1 = "https://share.antheminc.com/projects/Facets-Mig/Plan/Interim%20Inventory%20Tracker/"
'File handles upto 7 days
For i = 1 To 7
Fsplit2 = "Interim Inventory Tracker - All States " & Format(Now - i, "mmddyy") & " v1.xlsx"
myURL = Fsplit1 & Fsplit2
Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", myURL, False
WinHttpReq.Send
If WinHttpReq.Status = 200 Then
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write WinHttpReq.ResponseBody
oStream.SaveToFile ("C:\Users\AG47552\Desktop\Interim Tracker\Yesterday's Tracker File\" & Fsplit2 & " ")
oStream.Close
i = 7
MsgBox " File Downloaded Successfully "
End If
Next i
Call OpenInterimTracker(Fsplit2)
Call CentralLookup(Fsplit2)
Call NortheastLookup(Fsplit2)
Workbooks("Trackers " & Format(Now, "MMDDYY") & " PM.xlsx").Save
Workbooks("Trackers " & Format(Now, "MMDDYY") & " PM.xlsx").Close
Call DownloadTableauTracker(Fsplit2)
End Sub
Sub OpenInterimTracker(ByVal Fsplit2 As String)
Application.DisplayAlerts = False
Application.ScreenUpdating = True
Dim sPath As String, sFile As String
Dim wb As Workbook
Application.ScreenUpdating = True
sPath = "C:\Users\AG47552\Desktop\Interim Tracker\Yesterday's Tracker File\"
sFile = sPath & Fsplit2
Set wb = Workbooks.Open(sFile)
End Sub
Sub CentralLookup(ByVal Fsplit2 As String)
Dim rnge as Range
Dim cl As range
Workbooks("Trackers " & Format(Now, "MMDDYY") & " PM.xlsx").Activate
Worksheets("Central").Activate
lastrow = range("A" & Rows.Count).End(xlUp).Row
For i = 2 To lastrow
If Application.WorksheetFunction.IsNA(range("g" & i).Value) Then
range("g" & i).Value = "Change"
End If
If range("g" & i).Value = "Change" Then
srchval = Trim(range("d" & i).Value)
chgval = Trim(range("e" & i).Value)
Workbooks(Fsplit2).Activate
Sheets("Main Data input").Activate
On Error Resume Next
get_row_number = Workbooks(Fsplit2). _
Sheets("Main Data input").range("D:D").Find( _
What:=srchval, _
LookIn:=xlValues, _
LookAt:=xlPart, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlNext, _
MatchCase:=True _
).Row
If get_row_number = "" Then
'do nothing
Else
Workbooks(Fsplit2).Activate
Sheets("Main Data input").range("H" & get_row_number).Value = chgval
chgval = ""
chgval.Interior.Color = vbGreen
End If
Workbooks("Trackers " & Format(Now, "MMDDYY") & " PM.xlsx").Activate
Worksheets("Central").Activate
End If
Next i
End Sub
Sub NortheastLookup(ByVal Fsplit2 As String)
Dim rnge as Range
Dim cl As range
Workbooks("Trackers " & Format(Now, "MMDDYY") & " PM.xlsx").Activate
Worksheets("Northeast").Activate
lastrow = range("A" & Rows.Count).End(xlUp).Row
For i = 2 To lastrow
If Application.WorksheetFunction.IsNA(range("g" & i).Value) Then
range("g" & i).Value = "Change"
End If
If range("g" & i).Value = "Change" Then
srchval = Trim(range("d" & i).Value)
chgval = Trim(range("e" & i).Value)
Workbooks(Fsplit2).Activate
Sheets("Main Data input").Activate
On Error Resume Next
get_row_number = Workbooks(Fsplit2). _
Sheets("Main Data input").range("D:D").Find( _
What:=srchval, _
LookIn:=xlValues, _
LookAt:=xlPart, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlNext, _
MatchCase:=True _
).Row
If get_row_number = "" Then
'do nothing
Else
Workbooks(Fsplit2).Activate
Sheets("Main Data input").range("H" & get_row_number).Value = chgval
chgval = ""
chgval.Interior.Color = vbGreen
End If
Workbooks("Trackers " & Format(Now, "MMDDYY") & " PM.xlsx").Activate
Worksheets("Central").Activate
End If
Next i
End Sub
Sub DownloadTableauTracker(ByVal Fsplit2 As String)
Dim myURL As String
Dim f1 As String
Dim f2 As String
Dim f3 As String
Dim f4 As String
Dim WinHttpReq As Object
f1 = "https://share.antheminc.com/sites/EET-Migrations/Migrations%20Tracker/Migrations_Tracker%20_Tableau/"
f2 = "" & Year(Date) & "/"
f3 = "" & Format(Now, "mm mmm yyyy") & "/"
For i = 0 To 2
f4 = "Inventory Export " & Format(Now - i, "yyyy-mm-dd") & " AM.xlsm"
myURL = f1 & f2 & f3 & f4
Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", myURL, False
WinHttpReq.Send
If WinHttpReq.Status = 200 Then
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write WinHttpReq.ResponseBody
oStream.SaveToFile ("C:\Users\AG47552\Desktop\Interim Tracker\Tableau Tracker\" & f4 & " ")
oStream.Close
i = 5
MsgBox " Tableau Inventory file downloaded "
End If
Next i
Call TableauInventoryOpen(f4)
Call FetchTableauStatus(Fsplit2, f4)
End Sub
Sub TableauInventoryOpen(ByVal f4 As String)
Application.DisplayAlerts = False
Application.ScreenUpdating = True
Dim sPath As String, sFile As String
Dim wb As Workbook
Application.ScreenUpdating = True
sPath = "C:\Users\AG47552\Desktop\Interim Tracker\Tableau Tracker\"
sFile = sPath & f4
Set wb = Workbooks.Open(sFile)
End Sub
Sub FetchTableauStatus(ByVal Fsplit2 As String, ByVal f4 As String)
Workbooks(Fsplit2).Activate
Worksheets("Main Data input").Activate
lastrow = range("b" & Rows.Count).End(xlUp).Row
For i = 3 To lastrow
srchval = Trim(range("d" & i).Value)
'chgval = Trim(Range("e" & i).Value)
Workbooks(f4).Activate
Sheets("Inventory Export").Activate
On Error Resume Next
get_row_number = Workbooks(f4). _
Sheets("Inventory Export").range("G:G").Find( _
What:=srchval, _
LookIn:=xlValues, _
LookAt:=xlPart, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlNext, _
MatchCase:=True _
).Row
If get_row_number = "" Then
'do nothing
Else
'Finalize Product and Admin Selections
Workbooks(f4).Activate
If Sheets("Inventory Export").range("z" & get_row_number).Value = "Complete" Then
Workbooks(Fsplit2).Activate
Worksheets("Main Data input").Activate
If Sheets("Main Data input").range("O" & i).Value = "Incomplete" Or _
Sheets("Main Data input").range("o" & i).Value = "Incomplete with Issues" Then
Sheets("Main Data input").range("o" & i).Value = "Complete"
End If
End If
'Implementation Case Status
copyval = ""
Workbooks(f4).Activate
If Sheets("Inventory Export").range("o" & get_row_number).Value = "Implementation Completed" Or _
Sheets("Inventory Export").range("o" & get_row_number).Value = "NULL" Then
'do nothing
Else
Workbooks(f4).Activate
copyval = Sheets("Inventory Export").range("o" & get_row_number).Value
Workbooks(Fsplit2).Activate
Worksheets("Main Data input").Activate
Sheets("Main Data input").range("j" & i).Value = copyval
End If
'E&B Audit Complete
Workbooks(f4).Activate
If Sheets("Inventory Export").range("r" & get_row_number).Value = "Complete" Then
Workbooks(Fsplit2).Activate
Worksheets("Main Data input").Activate
If Sheets("Main Data input").range("l" & i).Value = "Incomplete" Or _
Sheets("Main Data input").range("l" & i).Value = "Incomplete with Issues" Then
Sheets("Main Data input").range("l" & i).Value = "Complete"
End If
End If
End If
Workbooks(Fsplit2).Activate
Worksheets("Main Data input").Activate
Next i
Workbooks(f4).Close
Workbooks(Fsplit2).Saveas "C:\Users\AG47552\Desktop\Interim Tracker\Today's Tracker File\" & Fsplit2 & " "
End Sub
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T00:06:08.937",
"Id": "473090",
"Score": "1",
"body": "For best performance `Application.ScreenUpdating` should be set to false, set it to true when the update is done."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T00:09:29.510",
"Id": "473091",
"Score": "0",
"body": "Please explain what the macro does so that we understand the code. Depending on the size of the files being downloaded, this could take some time. Is it possible to use file compression before downloading the files?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T14:04:48.760",
"Id": "473158",
"Score": "1",
"body": "There are certainly things that can be improved in this script, but you should identify the problematic areas - is this the download proper or your processing routine. Without having a data sample at hand it is difficult to realistically assess the code and we cannot guess all that you are doing. If you add some `debug.print` statements here and there it should become obvious which parts of the code take disproportionately more time than others. But I am not surprised that looping over 1M rows takes time. Perhaps you could export to csv and inject to a DB or process the data differently."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T14:51:33.737",
"Id": "473502",
"Score": "1",
"body": "Another point is that your execution time may be driven by the slow response of the Sharepoint server and your network, having little to do with your code. The comment from @Anonymous is on point: we can help identify the bottleneck better with more information such as sample data. Also try operating on data already \"downloaded\" from your Sharepoint site and see how much time that takes in order to help factor where your problem(s) lie."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T21:30:22.060",
"Id": "241101",
"Score": "1",
"Tags": [
"vba",
"excel",
"macros"
],
"Title": "Optimizing VBA code , Takes more than 50 minutes to update"
}
|
241101
|
<p>My code works for user output alignment to the right side by maximum length of 4 different user input.
I have 2 question.</p>
<ol>
<li>Is there a simplier way for append method in my code ?</li>
<li>Is there a simplier way for right alignment by maximum legth of 4 different user input.</li>
</ol>
<p>Thank You for Your Time...</p>
<pre><code>"""
Main purpose of this code is alignment of the user output to the right
"""
# Take Input from User
name = input("Name: ")
surname = input("Surname: ")
age = input("Age: ")
occupation = input("Occupation: ")
person_dict = {"Name": name, "Surname": surname, "Age": age, "Occupation": occupation}
# Calculate Maximum Character Length
len_list1 = []
len_name = len(name)
len_list1.append(len_name)
len_surname = len(surname)
len_list1.append(len_surname)
len_age = len(age)
len_list1.append(len_age)
len_occupation = len(occupation)
len_list1.append(len_occupation)
a = max(len_list1)
# Output
print(f'Name: {person_dict["Name"]:>{a}}\n'
f'Surname: {person_dict["Surname"]:>{a}}\n'
f'Age: {person_dict["Age"]:>{a}}\n'
f'Occupation: {person_dict["Occupation"]:>{a}}'
)
</code></pre>
|
[] |
[
{
"body": "<p>All the code from <code>len_list1 = []</code> to <code>a = max(len_list1)</code> can be replaced with:</p>\n\n<pre><code>a = len(max(person_dict.values(), key=len))\n</code></pre>\n\n<p><a href=\"https://docs.python.org/3/library/functions.html#max\" rel=\"noreferrer\"><code>max</code></a>'s <code>key</code> parameter is really helpful here. <code>key</code> is called on each element before <code>max</code> checks it. Dictionary's <a href=\"https://docs.python.org/3/library/stdtypes.html#dict.values\" rel=\"noreferrer\"><code>values</code></a> method is useful here too. If you already have the data in a dictionary, you might as well make use of that fact. </p>\n\n<p>You could also use a generator expression here to have the same effect:</p>\n\n<pre><code>a = max(len(val) for val in person_dict.values())\n</code></pre>\n\n<p>Or, since we're just mapping using an existing function, <code>map</code> would be clean here as well:</p>\n\n<pre><code>a = max(map(len, person_dict.values()))\n</code></pre>\n\n<p>The point is, use iteration constructs to avoid needing to repeat the same code over and over again for different objects.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T00:30:50.730",
"Id": "241107",
"ParentId": "241106",
"Score": "8"
}
},
{
"body": "<p>Your in- and output and the calculation of the column width can be simplified. The latter has already been shown in the <a href=\"https://codereview.stackexchange.com/a/241107/98493\">other answer</a>, but the former can just use a loop and the fact that dictionaries are guaranteed to be ordered (Python 3.7+, use a <code>OrderedDict</code> otherwise).</p>\n\n<pre><code>keys = [\"Name\", \"Surname\", \"Age\", \"Occupation\"]\nperson = {key: input(f\"{key}: \") for key in keys}\nwidth_keys = max(map(len, person.keys()))\nwidth_values = max(map(len, person.values()))\n\nfor key, value in person.items():\n print(f\"{key+':':<{width_keys+1}} {value:>{width_values}}\")\n</code></pre>\n\n<p>Note that I also made the justification of the keys automatic. If you want to take this further, a nice exercise would be to write a function that takes a 2D nested list and a list of alignments and which outputs the correctly justified table (which is what this is in the end).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T11:29:30.143",
"Id": "473136",
"Score": "0",
"body": "Thank you for your improvement advice. I don't understand the way you take input 'person = {key: input(f\"{key.......' is there any recomendation about how can i learn this expression ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T11:35:01.877",
"Id": "473137",
"Score": "0",
"body": "@Gokberk It is a [dictionary comprehension](https://www.programiz.com/python-programming/dictionary-comprehension), which builds the dictionary in one go. It works similar to a list comprehension except that you set the key and value, instead of just a value. A simplified version you might see more often would be `{key: value for key, value in zip(keys, values)}` or, more similar to the case here, `{key: func(key) for key in keys}`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T12:17:15.620",
"Id": "473144",
"Score": "1",
"body": "I feel like level up :) Thank You again"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T06:01:48.870",
"Id": "241113",
"ParentId": "241106",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "241107",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T00:03:18.370",
"Id": "241106",
"Score": "5",
"Tags": [
"python",
"strings",
"formatting"
],
"Title": "Dynamic String Alignment Code"
}
|
241106
|
<p>There is a simple movement <code>CAKeyframeAnimation</code>, what needs is that I can cancel and restart the animation freely.</p>
<p>The key point of the following code, is that I use <code>CATransaction.flush()</code></p>
<p>I update to the render tree manually.</p>
<blockquote>
<p>If not, Flush is typically called automatically at the end of the current runloop.</p>
<p>Then the animation of my need behaves weirdly, not as expected.</p>
</blockquote>
<pre><code>class ViewController: UIViewController {
let red = Red(frame: CGRect(x: 200, y: 200, width: 100, height: 100))
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(red)
}
// storyboard , button target action
@IBAction func startAnima(_ sender: UIButton) {
red.stopAnima()
CATransaction.flush()
red.startAnimating()
}
}
class Red: UIView{
var isAnimating = false
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.red
}
public func startAnimating() {
if isAnimating == false {
isAnimating = true
animateForward()
}
}
public func stopAnima() {
if isAnimating{
isAnimating = false
stopAnimating()
}
}
}
extension UIView{
func animateForward(){
let animation = CAKeyframeAnimation()
animation.isRemovedOnCompletion = true
animation.keyPath = "position.y"
animation.values = [0, 40, 40, 0]
animation.keyTimes = [0, 0.3, 0.7, 1]
animation.duration = 1
animation.isAdditive = true
layer.add(animation, forKey: nil)
}
func stopAnimating(){
layer.removeAllAnimations()
}
}
</code></pre>
<p>I have an other stupid method, using two views to simulate the needed animation.</p>
<p><a href="https://github.com/ForStackO/test" rel="nofollow noreferrer">The two demos are here</a></p>
<p>The above is in the second release.</p>
<p>The stupid is in the first release.</p>
<p><strong>I want to know how to improve it</strong></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T11:50:59.020",
"Id": "473138",
"Score": "0",
"body": "Welcome to code review, where we review code that is working as expected to suggest ways to improve that code. Code that is not working as expected is considered off-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T19:07:09.050",
"Id": "473193",
"Score": "0",
"body": "It is really working as expected. Thanks for your tips. Two working methods. Key point is code explain. And any better idea?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T19:47:44.380",
"Id": "473195",
"Score": "2",
"body": "This is a quote from the question : `Then the animation of my need behaves weirdly, not as expected.`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T23:32:16.460",
"Id": "473228",
"Score": "0",
"body": "Please heed some [Swift Style Guide](https://google.github.io/swift/#vertical-whitespace)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T06:07:49.247",
"Id": "473234",
"Score": "0",
"body": "@pacmaninbw, I have a condition `if not`, that explains why I use `CATransaction.flush()`. Use it , and the inner problem has been solved."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T06:16:11.643",
"Id": "473235",
"Score": "0",
"body": "I have edited `Vertical Whitespace` @greybeard"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T07:56:02.807",
"Id": "473239",
"Score": "3",
"body": "Your English is very confusing, I'm not sure what to make of this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T08:42:20.220",
"Id": "473244",
"Score": "0",
"body": "Hope you can improve my poor English. @Mast"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T10:16:15.767",
"Id": "473250",
"Score": "3",
"body": "I can't improve your English if I can't make anything of it. This is beyond me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T10:39:47.970",
"Id": "473252",
"Score": "0",
"body": "I showed the code. Just review"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T04:09:42.547",
"Id": "241110",
"Score": "1",
"Tags": [
"swift",
"ios",
"animation"
],
"Title": "iOS Core animation cancel and restart"
}
|
241110
|
<p>I've been experimenting with TCP clients in C++ and I really wanted to get some feedback on my code since I know it is bad. I would really appreciate some feedback on the class structure I have and the ways I can improve it. I also would love some feedback on any other simple bugs I have (or things in general I can fix).</p>
<pre><code>//FOR CODE REVIEW PLEASE GIVE FEEDBACK
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string>
#include <vector>
#include <thread>
#undef UNICODE
#pragma comment (lib, "Ws2_32.lib")
#define WIN32_LEAN_AND_MEAN
#define port 0001;
std::vector<std::string> split(std::string mystring, std::string delimiter)
{
std::vector<std::string> subStringList;
std::string token;
while (true)
{
size_t findfirst = mystring.find_first_of(delimiter);
if (findfirst == std::string::npos) //find_first_of returns npos if it couldn't find the delimiter anymore
{
subStringList.push_back(mystring); //push back the final piece of mystring
return subStringList;
}
token = mystring.substr(0, mystring.find_first_of(delimiter));
mystring = mystring.substr(mystring.find_first_of(delimiter) + 1);
subStringList.push_back(token);
}
return subStringList;
}
class client {
WSADATA wsaData;
//SOCKET cSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
char recvBuf[1024];
PCWSTR ip = L"192.168.86.36";
public:
void startWinsock() {
std::cout << "[+] - Starting our client.\n";
int rCode = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (rCode != NO_ERROR) {
std::cout << "[-] - Error while trying to start winsock.\n";
exit(0);
}
}
/*
void prepSocket() {
SOCKET cSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (cSocket == INVALID_SOCKET) {
std::cout << "[+] - Error: " << WSAGetLastError() << std::endl;
WSACleanup();
exit(1);
}
}
*/
void connectClient(SOCKET cSocket) {
sockaddr_in addrServer;
addrServer.sin_family = AF_INET;
InetPton(AF_INET, ip, &addrServer.sin_addr.s_addr);
addrServer.sin_port = htons(0001);
memset(&(addrServer.sin_zero), '\0', 8);
std::cout << "[+] - Connecting to our socket.\n";
int iResult = connect(cSocket, (SOCKADDR*)&addrServer, sizeof(addrServer));
if (iResult == SOCKET_ERROR) {
closesocket(cSocket);
std::cout << "[-] - Connection Failed: " << WSAGetLastError() << std::endl;
WSACleanup();
}
}
void sendMessage(SOCKET cSocket,char messageContent[1024]) {
//char demoMessage[1024] = "[+] - Demo message\n";
int message = send(cSocket, messageContent, strlen(messageContent), 0);
if (message == SOCKET_ERROR) {
std::cout << "[-] - Unable to send demo message: " << WSAGetLastError() << std::endl;
closesocket(cSocket);
WSACleanup();
}
std::cout << "[+] - Successfully sent our demo message.\n";
}
void recieveMessage(SOCKET cSocket) {
std::cout << "[+] - Awaiting server response" << std::endl;
int iResult = recv(cSocket, recvBuf, 1024, 0);
if (iResult > 0) {
std::string content;
for (int i = 0; i < iResult; i++) {
content += recvBuf[i];
}
if (strstr(content.c_str(), "cmd")) {
std::string command = split(content, (std::string)"cmd ")[1];
std::cout << "COMMAND SHIT NOT IMPLEMENTED\n";
}
else if (strstr(content.c_str(), "exit")) {
exit(0);
}
std::cout << "> " << content;
}
else if (iResult == 0) {
std::cout << "[-] - Connection closed\n" << std::endl;
}
else {
std::cout << "[-] - An error occured: " << WSAGetLastError() << std::endl;
}
}
void killSocket(SOCKET cSocket) {
closesocket(cSocket);
WSACleanup();
}
};
int main() {
client client;
client.startWinsock();
//client.prepSocket();
SOCKET cSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (cSocket == INVALID_SOCKET) {
std::cout << "[+] - Error: " << WSAGetLastError() << std::endl;
WSACleanup();
exit(1);
}
client.connectClient(cSocket);
client.sendMessage(cSocket,(char *)"works kek :happy_pepe:\n");
client.recieveMessage(cSocket);
client.killSocket(cSocket);
}
</code></pre>
<p>If you would rather have a pastebin link here's one:</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T10:51:28.267",
"Id": "473133",
"Score": "0",
"body": "If you want to learn sockets is fine, but I would recommend you to use https://www.boost.org/doc/libs/1_66_0/doc/html/boost_asio.html for services, or even better \nhttps://www.boost.org/doc/libs/1_72_0/libs/beast/doc/html/index.htmlfor more Restfull systems."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T14:50:30.287",
"Id": "473161",
"Score": "0",
"body": "I wrote a (still incomplete) series about sockets for C++: https://lokiastari.com/series/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T21:17:35.990",
"Id": "473216",
"Score": "0",
"body": "You should use a more C++ style portable library instead of windows-only C-style library. Consider `boost::asio` as Networking TS is likely to be modeled after it."
}
] |
[
{
"body": "<h2>Code Review</h2>\n\n<p>Do you really want to use C functions?</p>\n\n<pre><code>#include <stdio.h>\n</code></pre>\n\n<p>Sure you can but you may want to use the correct version of this header file for C++ which is <code><cstdio></code>.</p>\n\n<hr>\n\n<p>Using port 1 is not recommended for normal socket work.</p>\n\n<pre><code>#define port 0001;\n</code></pre>\n\n<p>Ports below 1024 are reserved for the OS (and usually specifically allocated to standard services used by the OS).</p>\n\n<p><a href=\"https://www.webopedia.com/quick_ref/portnumbers.asp\" rel=\"nofollow noreferrer\">https://www.webopedia.com/quick_ref/portnumbers.asp</a></p>\n\n<p>But since you are writing TCP connection <code>1</code> is the correct port.</p>\n\n<hr>\n\n<p>To prevent excessive copying pass complex parameters by const reference rather than value (unless you are going to copy them anyway). </p>\n\n<pre><code>std::vector<std::string> split(std::string mystring, std::string delimiter)\n</code></pre>\n\n<hr>\n\n<p>I think we can improve the split a bit:</p>\n\n<pre><code>std::vector<std::string> split(std::string const& mystring, std::string const& delimiter)\n{\n std::vector<std::string> subStringList;\n\n std::string::size_t start = 0;\n std::string::size_t end = mystring.find_first_of(delimiter);\n\n while (end != std::string::npos) {\n subStringList.emplace_back(mystring.substr(start, end - start));\n start = end + delimiter.size();\n }\n // if the delimiter is the last item in the string\n // then the following will add a blank string to subStringList.\n // If that is not what you want just test to see if start == mystring.size()\n subStringList.emplace_back(mystring.substr(start));\n\n return subStringList;\n}\n</code></pre>\n\n<hr>\n\n<p>Remove commented out code from your source.</p>\n\n<pre><code> //SOCKET cSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);\n\n /*\n void prepSocket() {\n SOCKET cSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);\n if (cSocket == INVALID_SOCKET) {\n std::cout << \"[+] - Error: \" << WSAGetLastError() << std::endl;\n WSACleanup();\n exit(1);\n }\n }\n */\n</code></pre>\n\n<p>This is what source control systems are for. Check out github.</p>\n\n<hr>\n\n<p>You only ever want to connect to this specific host?</p>\n\n<pre><code> PCWSTR ip = L\"192.168.86.36\";\n</code></pre>\n\n<p>I would expect that you want to pass a hostname as a parameter to the client.</p>\n\n<hr>\n\n<p>Is this really part of the <code>client</code> class?</p>\n\n<pre><code> void startWinsock() {\n std::cout << \"[+] - Starting our client.\\n\";\n int rCode = WSAStartup(MAKEWORD(2, 2), &wsaData);\n if (rCode != NO_ERROR) {\n std::cout << \"[-] - Error while trying to start winsock.\\n\";\n exit(0);\n }\n }\n</code></pre>\n\n<p>I would make the start up/shotdown of the windowing socket code a separate class <code>TCPInit</code> (probably a singelton). Then the constructor of <code>client</code> will simply just make sure that the socket stuff has been initialized by getting an instance of <code>TCPInit</code>.</p>\n\n<hr>\n\n<p>You don't check the result of this call:</p>\n\n<pre><code> InetPton(AF_INET, ip, &addrServer.sin_addr.s_addr);\n</code></pre>\n\n<hr>\n\n<p>Did you not define a port macro above?</p>\n\n<pre><code> addrServer.sin_port = htons(0001);\n</code></pre>\n\n<hr>\n\n<p>Don't assume the size of this object is 8.</p>\n\n<pre><code> memset(&(addrServer.sin_zero), '\\0', 8);\n</code></pre>\n\n<p>That is what <code>sizeof</code> is used for.</p>\n\n<hr>\n\n<p>The value returned by <code>send()</code> is not just an error.</p>\n\n<pre><code> int message = send(cSocket, messageContent, strlen(messageContent), 0);\n if (message == SOCKET_ERROR) {\n</code></pre>\n\n<p>You should check the result of <code>send()</code> make sure you have sent the whole message. You may need to call <code>send()</code> multiple times to send the whole message.</p>\n\n<hr>\n\n<p>This looks like a destructor:</p>\n\n<pre><code> void killSocket(SOCKET cSocket) {\n closesocket(cSocket);\n WSACleanup();\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T16:54:56.067",
"Id": "473172",
"Score": "0",
"body": "Thank you very much <3 this is exactly the type of feedback I was looking for."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T21:43:13.520",
"Id": "473222",
"Score": "0",
"body": "I have one question after fully reading your feedback, why do you recommend use sizeof instead of 8 isn't it always going to have an integer value of 8?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T21:56:03.300",
"Id": "473223",
"Score": "1",
"body": "@Backslash Can you show me where it says its 8 in the standard? If so then you can use 8. Otherwise it is an implementation details that will depend on platform. Actually this field `sin_addr` is an ungodly structure `struct in_addr` that is a combination of several unions depending on platform and age of your OS. You should zero out the whole structure as that is what the API is expecting."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T23:01:37.490",
"Id": "473225",
"Score": "0",
"body": "While searching for where it says that, i was unable to find that so I now realize that I was wrong. Thank you lol"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T23:05:20.717",
"Id": "473226",
"Score": "2",
"body": "@Backslash In general using \"magic\" numbers is bad practice. Even if the value was exactly 8 I would have recomended putting that value into a named constant (e.g. `static int const SizeOfAddr = /*Value*/;`. This has two benefits 1) Named constants give more meaning to your code as they become self documenting. If the value does change in a new version of the OS then you have. only one place in the code to change the value (at the constant)."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T15:19:04.277",
"Id": "241147",
"ParentId": "241111",
"Score": "2"
}
},
{
"body": "<h1>Prefer using <code>getaddrinfo()</code></h1>\n<p>You are using <code>InetPton()</code> to convert an IPv4 address to a <code>sockaddr_in</code>. However, this function has several drawbacks:</p>\n<ul>\n<li>It does not perform DNS lookups, so you can't use a hostname to connect to a server.</li>\n<li>You have to know up front which address family to use.</li>\n<li>It doesn't fill in all of a sockaddr_in, it only provides you with the address part.</li>\n</ul>\n<p>If you use <a href=\"https://docs.microsoft.com/en-us/windows/win32/api/ws2tcpip/nf-ws2tcpip-getaddrinfo\" rel=\"nofollow noreferrer\"><code>getaddrinfo()</code></a> you do get DNS lookups, and you don't have to deal with address families explicitly anymore. There is only one drawback with <code>getaddrinfo()</code>, and that is that if you provide it with a hostname, you can actually get multiple <code>struct sockaddr</code>s back from it. The correct way to deal with this is to loop over all the <code>sockaddr</code>s, and try to connect to each one in turn until you get a working connection.</p>\n<h1>Don't write number with leading zeroes</h1>\n<p>In C++, if you write an <a href=\"https://en.cppreference.com/w/cpp/language/integer_literal\" rel=\"nofollow noreferrer\">integer literal</a> starting with a zero, it will be treated as an octal number. Lucky for you, the octal number <code>0001</code> has the same value as the decimal number <code>1</code>. However, if you would have written <code>0010</code>, then it would have been the same as <code>8</code>.</p>\n<h1>Avoid <code>#define</code> for defining constants</h1>\n<p>In C++, it is better to declare constants as <code>static constexpr</code> variables. For example:</p>\n<pre><code>static constexpr std::uint16_t port = 1;\n</code></pre>\n<p>This has the advantage that you can give a proper type to the constant, and that the compiler can actually check this declaration for correctness. Your definition was actually incorrect, since you added a semicolon to the macro:</p>\n<pre><code>#define port 0001;\n</code></pre>\n<p>If you would have used this to fill in <code>sin_port</code> in <code>connectClient()</code> as Martin York suggests in his answer, then the following line:</p>\n<pre><code>addrServer.sin_port = htons(port);\n</code></pre>\n<p>Would have expanded to:</p>\n<pre><code>addrServer.sin_port = htons(0001;);\n</code></pre>\n<p>Which is clearly a syntax error.</p>\n<h1>Avoid using C functions on C++ objects</h1>\n<p>If you use <code>std::string</code>, you should prefer to use the member functions of that class to manipulate strings. For example, instead of writing:</p>\n<pre><code>if (strstr(content.c_str(), "cmd")) {\n</code></pre>\n<p>You should write this idiomatic C++ code using <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/find\" rel=\"nofollow noreferrer\"><code>find()</code></a>:</p>\n<pre><code>if (content.find("cmd") != content.npos) {\n</code></pre>\n<p>It's a bit unfortunate that we have to wait for C++23 for <a href=\"https://en.cppreference.com/w/cpp/string/basic_string/contains\" rel=\"nofollow noreferrer\"><code>contains()</code></a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-05T07:44:15.297",
"Id": "506965",
"Score": "1",
"body": "That `getaddrinfo()` looks to be closely modelled on the POSIX function of the same name, so using it is easing the way towards more portability, too."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-03-04T17:04:17.070",
"Id": "256730",
"ParentId": "241111",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T04:29:40.637",
"Id": "241111",
"Score": "4",
"Tags": [
"c++",
"object-oriented",
"tcp"
],
"Title": "Simple TCP Client in C++"
}
|
241111
|
<p>I'm importing data from file to many tables in database. It may look like this:</p>
<pre><code>First Name, Last Name, Meeting
John, Doe, 2020-04-24 08:00:00
</code></pre>
<p>Some fields like "First Name" and "Last Name" are being saved in one table and other fields like "Meeting" are being saved in different tables. There are a lot of more fields and a lot of more rows in my case.</p>
<p>I create handler for each table and put it in a handler chain to reduce amount of code. Each handler knows which fields it can handle. My base handler class looks like this:</p>
<pre><code>abstract class TableHandler
{
protected $nextHandler;
abstract public function isFieldSupported(string $field): bool;
abstract public function handle(string $fieldName, string $fieldValue);
public function next(TableHandler $nextHandler): TableHandler
{
$this->nextHandler = $nextHandler;
}
public function handleField(string $fieldName, string $fieldValue)
{
$this->handle($fieldName, $fieldValue);
if ($this->nextHandler()) {
$this->nextHandler->handleField($fieldName, $fieldValue);
}
}
public function reset(): void
{
$this->resetHandler();
if ($this->nextHandler()) {
$this->nextHandler->reset();
}
}
private function nextHandler(): bool
{
return $this->nextHandler !== null;
}
}
</code></pre>
<p>I use my handler chain this way:</p>
<pre><code>$table1->next($table2)
->next($table3);
foreach ($data as $row) {
foreach ($headers as $index => $header) {
$table1->handleField($header, $row[$index]);
}
$id = $table1->save();
$table2->save($id);
$table3->save($id);
$table1->reset();
}
</code></pre>
<p>As you can see I was able to handle fields and reset all handlers by using only first handler. Chain does the rest of the job. The problem is that I don't know how can I improve saving data. When I insert record in first table I get its ID. I need to pass this ID to further handlers because rows that I insert in those tables are related to row from first table so ID is needed. Bacause of it I need to save data separately. I would like to avoid it. Is it possible?</p>
|
[] |
[
{
"body": "<p>I'm not to sure about your base handler. It has methods like <code>handle()</code> and <code>handleField()</code> that look very similar. One will probably do. I also noted that the <code>save()</code> method is completely missing from your code. Why? You use it, so it should be there. Or at least in an usage example.</p>\n\n<p>As to your actual problem with saving, you can hand over the id's as an argument to the next <code>save()</code> in the clain. Something like:</p>\n\n<pre><code>public function save(array $insertIds = [])\n{\n // ..... put needed insert ids into data here ....\n // then perform the insert and get the new insert id \n $newInsertId = $this->insertRow($this->table,$this->data);\n // add that to the array of insert ids\n $insertIds[$this->table] = $newInsertId;\n // progress down the chain, if possible\n if ($this->nextHandler()) {\n $this->nextHandler->save($insertIds);\n }\n}\n</code></pre>\n\n<p>Note that in the <code>$insertIds</code> array the keys are table names, and the values are the actual insert ids. This way all insert ids are available to <code>save()</code> methods down the chain.</p>\n\n<p>It could be useful to return the <code>$insertIds</code>.</p>\n\n<p>Note that the order of chaining is important. You have to think about that when you create the chain. Perhaps it would be a good idea to allow for multiple next handlers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T20:20:03.793",
"Id": "473204",
"Score": "0",
"body": "I created `handle()` and `handleField()` methods to not duplicate checking if next handler exists. I didn't put `save()` method in abstract class because of difference between first handler's `save()` method and other handlers. I wanted to show only essence of my problem so I didn't put handler's implementation in the above example. Your idea is nice but I'm afraid that in the future some programmer could mistakenly use handlers in wrong order. In my solution I force to call `save()` on first handler but huge disadvantage is that I can't use this method in the chain."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T14:28:49.637",
"Id": "241142",
"ParentId": "241116",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T06:55:19.853",
"Id": "241116",
"Score": "1",
"Tags": [
"php",
"object-oriented",
"design-patterns"
],
"Title": "Chain of responsibility and handlers dependent on each other"
}
|
241116
|
<p>I am a professional Angular developer and start to learn React. <a href="https://github.com/Triplecorpse/thenewword2-front/tree/f96c5f0fe60e635feaf2ede5863901057341679b" rel="nofollow noreferrer">This</a> is my repo to be reviewed.</p>
<p>This is a small login/register form created with React. I want to check if this small project actually is written with React-style. If you don't feel comfortable to open and look into repository, I place the most issued files here.</p>
<ol>
<li>Dynamically adding classes. As I got, there is no declarative way as in angular <code>[class.xxx]="true"</code>, I need to create class string elsewhere and bind it to the element.</li>
<li>The second file is a form. It is almost HTML way so I am also interested if it is React-style.</li>
</ol>
<p>I would appreciate if you look the whole repository that consists of login/register form only. But if you don't want to do it for some reason, I would appreciate to review these files also.</p>
<pre><code>import './Login.component.scss';
import * as React from "react";
import LoginFormComponent from "./LoginForm.component";
import WelcomeComponent from "./Welcome.component";
import RegisterFormComponent from "./RegisterForm.component";
class LoginComponent extends React.Component {
constructor(props) {
super(props);
this.register = this.register.bind(this)
this.login = this.login.bind(this)
this.state = {
loginFormWrapperClasses: ['form-wrapper'],
registerFormWrapperClasses: ['form-wrapper', 'hidden', 'register']
}
}
register() {
this.setState({
loginFormWrapperClasses: ['form-wrapper', 'hidden'],
registerFormWrapperClasses: ['form-wrapper']
});
}
login() {
this.setState({
loginFormWrapperClasses: ['form-wrapper'],
registerFormWrapperClasses: ['form-wrapper', 'hidden', 'register']
});
}
render() {
return (
<div className="background">
<div className={this.state.loginFormWrapperClasses.join(' ')}>
<LoginFormComponent apiLink="http://localhost:5000/" register={this.register}/>
</div>
<div className={this.state.registerFormWrapperClasses.join(' ')}>
<RegisterFormComponent apiLink="http://localhost:5000/" login={this.login}/>
</div>
<div className="welcome-wrapper">
<WelcomeComponent />
</div>
</div>
)
}
}
export default LoginComponent;
</code></pre>
<pre><code>import './LoginForm.component.scss';
import * as React from "react";
class LoginFormComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
login: '',
password: ''
};
this.handleChange = this.handleChange.bind(this);
this.submit = this.submit.bind(this);
}
handleChange(e) {
this.setState({[e.target.name]: e.target.value});
}
render() {
return (
<div className="login-form-component" >
<form className="form" onSubmit={this.submit}>
<label>
Ім'я користувача
<input type="text" name="login" value={this.state.login} onChange={this.handleChange}/>
</label>
<label>
Гасло
<input type="password" name="password" value={this.state.password} onChange={this.handleChange}/>
</label>
<div className="actions">
<button type="button" className="register" onClick={this.props.register}>Зареєструватися</button>
<button type="submit">Продовжити</button>
</div>
</form>
</div>
);
}
submit(e) {
const body = {
login: this.state.login,
password: this.state.password
};
e.preventDefault();
fetch(this.props.apiLink + 'user/login', {
method: 'post',
body: JSON.stringify(body)
});
}
}
export default LoginFormComponent;
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T12:06:48.373",
"Id": "473141",
"Score": "0",
"body": "Welcome to code review! You have done a pretty good job on this question so far. We can only review code that is in the question. Repositories are good as a reference, but we can't review the code in them."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T07:50:43.943",
"Id": "241119",
"Score": "3",
"Tags": [
"javascript",
"react.js"
],
"Title": "React-style way to manage className and forms"
}
|
241119
|
<p>I have done the leap year check on <a href="https://exercism.io" rel="nofollow noreferrer">https://exercism.io</a> already in a lot of languages. Today I came back to the exercise in Java and was playing around with some maybe more funny ways to do the check. The following more functional one kept me thinking of:</p>
<pre><code>import java.util.stream.IntStream;
class Leap {
boolean isLeapYear(final int year) {
return IntStream.of(4, 100, 400)
.filter(divisor -> year % divisor == 0)
.count() % 2 == 1;
}
}
</code></pre>
<p>What do you think? Is this readable? At least it seems to be extensible in case more rules will ever get added ;)</p>
<p>Another funny fact: due to prime factorization we actually could also use the <code>IntStream.of(2, 25, 16)</code> (but for sure that doesn't help in readability).</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T10:10:01.710",
"Id": "473122",
"Score": "0",
"body": "please don't keep updating you code :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T10:15:50.920",
"Id": "473124",
"Score": "2",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T10:22:13.413",
"Id": "473129",
"Score": "1",
"body": "This isn’t more functional-style than other pure approaches like `return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);`, note."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T10:23:34.550",
"Id": "473130",
"Score": "0",
"body": "@Ry I didn't and wouldn't claim that `return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);` isn't a functional implementation. It has no side effects and the result only depends on the input."
}
] |
[
{
"body": "<h2>What do you think?</h2>\n\n<p>It certainly is <em>clever</em>. That is not always a good thing, because it might be harder to understand what is going on (you have to be at least as clever)</p>\n\n<h2>Is this readable?</h2>\n\n<p>Not really. I can't get from a glance that 100 is treated differently from 400 and why. Also there is no room for comments close to you code.</p>\n\n<p>If you make a set of <code>if</code>s you could do something like:</p>\n\n<pre><code>if (year % 400 ... ) // if 400 then a leap year\n{..\n..}\n</code></pre>\n\n<p>In your IntStream you could do something like:</p>\n\n<pre><code> IntStream.of( 4, //yes\n 100, //no\n 400 //yes\n )\n</code></pre>\n\n<p>But then you kinda miss the 'one-liner' point of your solution.</p>\n\n<h2>Is it efficient?</h2>\n\n<p>Not per se. Most efficient would be to first check divisibility by 400, if true, return true, etc.</p>\n\n<h2>Prime factorization funny fact</h2>\n\n<p>This in incorrect; because it would label 1998 as leap year. Or do you mean something different? </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T09:52:29.663",
"Id": "473118",
"Score": "0",
"body": "Funny fact: should be fixed by the change to `.takeWhile()`. I posted the wrong version of the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T09:57:52.497",
"Id": "473120",
"Score": "0",
"body": "Efficiency: (with the `.takeWhile()` now) I also have an “early return” and I will do it more often. For 3/4 of the years it will return after doing only a single test. When testing for 400 first, it's only 1/400 of the cases that return after the first check."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T10:18:10.160",
"Id": "473126",
"Score": "1",
"body": "The question has been rolled back to revision 1. This may or may not have consequences for the revisions to your answer. For your information."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T09:25:26.280",
"Id": "241124",
"ParentId": "241120",
"Score": "4"
}
},
{
"body": "<p>There is a bug in the original code I posted. It was intended not to <code>.filter()</code> but to <code>.takeWhile()</code>. Only with that change the “funny fact” makes sence as RobAu pointed out. So the original code should have been:</p>\n\n<pre><code>import java.util.stream.IntStream;\n\nclass Leap {\n\n boolean isLeapYear(final int year) {\n return IntStream.of(4, 100, 400)\n .filter(divisor -> year % divisor == 0)\n .count() % 2 == 1;\n }\n\n}\n</code></pre>\n\n<p>Incorporating the suggestions by @RobAu I would now change the code to the following to add more naming of variables and functions. I personally prefer them over adding comments, because comments tend to not being updated when the code changes.</p>\n\n<pre><code>import java.util.function.IntPredicate;\nimport java.util.stream.IntStream;\n\nclass Leap {\n\n boolean isLeapYear(final int year) {\n final IntPredicate yearFallsIntoCategory =\n category -> year % category == 0;\n\n final IntStream specialYears = IntStream.of(4, 100, 400);\n final IntStream categoriesYearFallsInto =\n specialYears.takeWhile(yearFallsIntoCategory);\n\n return categoriesYearFallsInto.count() % 2 == 1;\n }\n}\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T10:21:25.470",
"Id": "241128",
"ParentId": "241120",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "241124",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T08:29:47.693",
"Id": "241120",
"Score": "3",
"Tags": [
"java",
"programming-challenge",
"functional-programming"
],
"Title": "Leap year check in Java (functional style)"
}
|
241120
|
<p>So I have a <code>Know Your Customer</code> provider interface like this to estimate risks associated with a customer:</p>
<pre><code>public interface IRiskProvider
{
string Name { get; }
Task<Risk[]> FindRisksAsync(Customer customer);
}
</code></pre>
<p>And I would like to be able to create an instance of it from a delegate as well as intercept all the calls to the instance:</p>
<pre><code>public static class RiskProvider
{
public static IRiskProvider Create(string name, Func<Customer, Task<Risk[]>> actionAsync) =>
new Relay(name, actionAsync);
public static IRiskProvider Subscribe(this IRiskProvider provider, Func<Customer, Risk[], Task> actionAsync) =>
Create(provider.Name, async customer =>
{
var risks = await provider.FindRisksAsync(customer);
await actionAsync(customer, risks);
return risks;
});
class Relay : IRiskProvider
{
public Relay(string name, Func<Customer, Task<Risk[]>> actionAsync) =>
(Name, ActionAsync) =
(name, actionAsync);
public string Name { get; }
Func<Customer, Task<Risk[]>> ActionAsync { get; }
public async Task<Risk[]> FindRisksAsync(Customer customer) =>
await ActionAsync(customer);
}
}
</code></pre>
<p>An example consumption code would be this <code>Throttler</code> implementing <code>circuit breaker decorator factory</code>:</p>
<pre><code>using IHistory = IHistory<(string Provider, long UserId), (Customer Customer, Risk[] Risks)>;
[Service]
public class Throttler : IThrottler
{
public Throttler(IHistory history) => History = history;
IHistory History { get; }
public IRiskProvider Throttle(IRiskProvider provider, int attempts) =>
RiskProvider
.Create(provider.Name, async customer =>
{
var calls = await History.ReadAsync((provider.Name, customer.UserId), last: attempts);
var tooMany = calls.Length == attempts;
return
tooMany ? UnknownRisk.ServiceThrottled :
await provider.FindRisksAsync(customer);
})
.Subscribe((customer, risks) =>
History.WriteAsync((provider.Name, customer.UserId), (customer, risks)));
}
</code></pre>
<p>Which uses a generic NoSql repository to write/read multiple values per a key:</p>
<pre><code>public interface IHistory<TKey, TValue>
{
Task WriteAsync(TKey key, TValue value);
Task<(DateTime At, TValue Value)[]> ReadAsync(TKey key, int last = 1);
}
</code></pre>
<p>Does the <code>Subscribe</code> method name sounds reasonable here? Would you expect a subscription in the form of <code>IDisposable</code> being returned from it instead of subscribed instance suitable for chaining? What would be a better name instead of <code>Subscribe</code> for such an API to intercept all the calls? </p>
<p>It just looks like some mix between <code>IEnumerable</code> and <code>IObservable</code> for me. Would some simple <code>ForEach</code> be better?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T10:35:16.573",
"Id": "476118",
"Score": "0",
"body": "Please help me clarify what do you really want to achieve!? `IEnumerable` + `ForEach` is **pull based** mechanism. On the other hand the `IObservable` + `Subscribe` is a **push based** approach. Which one do you want to support?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T14:41:03.467",
"Id": "476156",
"Score": "0",
"body": "@PeterCsala I think it is a middle ground. `Subscribe` executes *push based* callback when *pull based* `FindRiskAsync` is become invoked..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T15:15:34.647",
"Id": "476161",
"Score": "0",
"body": "@DimitryNogin Do I understand correctly that you retrieve data then you pass that to a consumer defined function and finally you return with the amended data?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-20T17:20:11.407",
"Id": "476173",
"Score": "0",
"body": "@PeterCsala There are three fundamental things you could do: create an instance, intercept the call, or intercept and replace the result. I support create and intercept (for logging purposes) only here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T07:00:56.333",
"Id": "476250",
"Score": "0",
"body": "@DimitryNogin In my opinion if you want to only allow interception than I would recommend to use immutable structures.Currently the `risks` is amendable in the callback. If you would pass an `ImmutableArray` rather than a simple `Array` then the callback would not be able to modify the `risks`. I would also consider to make the callback optional, because not each and every consumer would like to intercept."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T10:46:58.390",
"Id": "476263",
"Score": "0",
"body": "@PeterCsala What could be more optional than skipping the `Subscribe` call?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T11:13:19.727",
"Id": "476265",
"Score": "0",
"body": "@DmitiryNogin Yep, that's a valid point, because you are providing a fluent API. :D By revisiting your code I can see that call of the `FindRiskAsync` is the done inside the delegate of the `Create` method. So, if I call the `Subscribe` as well then I will call the `FindRiskAsync` twice, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T11:27:31.510",
"Id": "476266",
"Score": "0",
"body": "@PeterCsala Nope, it just chains. Try to play with the code, it is a useful pattern to know."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T10:30:08.233",
"Id": "241129",
"Score": "1",
"Tags": [
"c#",
"functional-programming"
],
"Title": "Does Subscribe sound as a right name?"
}
|
241129
|
<p>I have an app in which I want to create <strong>multiple configurable parallel workers</strong>. The configuration is done via an <strong>"options" parameter</strong> because I want to have an interface that requires <em>Run(options) method</em>.</p>
<p>Each worker <em>(called thread in the snippet)</em> has its own configuration type <em>(ThreadAOptions for ThreadA and ThreadBOptions for ThreadB in the snippet)</em> that is passed optionally in Run() method "options" parameter. If no parameter is passed then default configuration values are used.</p>
<h2>My question is:</h2>
<ul>
<li><strong>How can I rewrite generics in the snippet in a better way? Or is it the best solution?</strong>
<ul>
<li>e.g. it would be fine to be able to call RunThread() method in App without the second ("options") parameter, however, it is not possible to set "TOptions options = null" at this time because of compiler error: "A value of type 'null' cannot be used as a default parameter because there are no standard conversions to type 'TOptions'"</li>
<li>...or is there any best practice to do that? </li>
</ul></li>
</ul>
<p>The source code snippet is intentionally simplified because in real use case it contains a lot of non-relevant code for this review.</p>
<hr>
<pre><code>using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace App
{
public interface IOptions
{
public void Validate();
}
public interface IThread<in TOptions> where TOptions : IOptions?
{
public Task Run(TOptions options);
}
public class ThreadAOptions : IOptions
{
public int SleepTime = 5000; // in ms
public void Validate()
{
if (SleepTime < 1) throw new ArgumentOutOfRangeException(nameof(SleepTime));
}
}
public class ThreadA : IThread<ThreadAOptions>
{
public async Task Run(
ThreadAOptions? options
)
{
options ??= new ThreadAOptions();
options.Validate();
Thread.Sleep(options.SleepTime);
}
}
public class ThreadBOptions : IOptions
{
public int AnotherSleepTime = 5000; // in ms
public void Validate()
{
if (AnotherSleepTime < 10) throw new ArgumentOutOfRangeException(nameof(AnotherSleepTime));
}
}
public class ThreadB : IThread<ThreadBOptions>
{
public async Task Run(
ThreadBOptions? options
)
{
options ??= new ThreadBOptions();
options.Validate();
Thread.Sleep(options.AnotherSleepTime);
}
}
internal class App {
private readonly ThreadA _threadA;
private readonly ThreadB _threadB;
// Dependencies loaded via DI
public App(
ThreadA threadA,
ThreadB threadB
)
{
_threadA = threadA;
_threadB = threadB;
}
// Called from outside of the class (Program.cs)
public async Task Init()
{
var workers = new List<Task>
{
RunThread<ThreadA, ThreadAOptions>(_threadA, null),
RunThread(_threadB, new ThreadBOptions() {
AnotherSleepTime = 10000
}),
};
await Task.WhenAll(workers.ToArray());
}
private async Task RunThread<TThread, TOptions>(TThread thread, TOptions options)
where TThread : IThread<TOptions> where TOptions : IOptions?
{
try
{
await Task.Run(async () => { await thread.Run(options); });
}
catch (Exception e)
{
Console.WriteLine($"Thread exception: {e.Message}");
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T11:57:08.103",
"Id": "473139",
"Score": "1",
"body": "Welcome to code review, where we review working code to and provide suggestions on how to improve that code. Code that has comments like `// ... code ...` is considered off topic because it it very hard to give a good review when there is code missing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T12:17:08.877",
"Id": "473143",
"Score": "0",
"body": "Welcome @pacmaninbw, thank you for your comment. I replaced these blocks to be more clear. I think that snippet is very easy to understand. It is written in a style that makes the question useful for more people than only me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T10:59:57.963",
"Id": "473365",
"Score": "0",
"body": "Code Review requires concrete code from a project, with enough code and / or context for reviewers to understand how that code is used. Pseudocode, stub code, hypothetical code, obfuscated code, and generic best practices are outside the scope of this site. Please take a look at the [help/on-topic]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T11:35:13.803",
"Id": "473370",
"Score": "0",
"body": "@Mast So, should I remove this question or should I copy & paste all relevant code (approx. 480 lines)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T11:52:58.520",
"Id": "473371",
"Score": "1",
"body": "For now, leave it be. The question might be closed. You can't remove it once it's answered and any attempts to modify the code will be seen as invalidation of the answer. The answerer failed to notice your question was off-topic and should've flagged the question or left a comment instead of answering, but what's done is done. I think the answer is valuable enough that the best course of action now is to leave it be. If you have a new question with updated code, feel free to post that as new question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T11:56:29.540",
"Id": "473372",
"Score": "0",
"body": "As for 480 lines of code, I'm sure you don't need to post all those lines but it's possible as long as it (including the description) stays under 65k characters. That's the technical limit. But at the moment, you have a lot of simplified names as well. Everything you simplify, is unnecessarily hard to review or will leave you with answers you can't do anything with since your actual situation will be different."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T11:57:07.543",
"Id": "473373",
"Score": "0",
"body": "If it was up to me, we'd force-feed our [FAQ on asking questions](https://codereview.meta.stackexchange.com/q/2436/52915) together with the [help/on-topic] to new users to prevent ugly situations like this. Alas, Stack Exchange thinks different."
}
] |
[
{
"body": "<p>It is possible to improve the generics in the code snippet this way:</p>\n\n<ul>\n<li>Edit specification of <code>App.RunThread(...)</code> method to be able to call the method without the second parameter. Specifically, set the default value for the second parameter as <code>= default</code>. It means <code>null</code> for reference types (our case) and default value for value types. We cannot use <code>= null</code> in this case. <a href=\"https://stackoverflow.com/a/32732271/1044198\">See a relevant question on StackOverflow</a>.</li>\n<li>Remove <code>TThread</code> from generics because we do not use it anywhere and we want to require <code>IThread</code> interface in fact. A side effect is that we do not have to specify option type explicitly when calling the method with null second argument because it can be now inferred from usage.</li>\n</ul>\n\n<p><strong>Before:</strong></p>\n\n<pre><code>public async Task Init() {\n var workers = new List<Task>\n {\n RunThread<ThreadA, ThreadAOptions>(_threadA, null),\n RunThread(_threadB, new ThreadBOptions() {\n AnotherSleepTime = 10000\n }),\n };\n\n await Task.WhenAll(workers.ToArray());\n}\n\nprivate async Task RunThread<TThread, TOptions>(TThread thread, TOptions options)\n where TThread : IThread<TOptions> where TOptions : IOptions? { /* ... */ }\n</code></pre>\n\n<p><strong>After:</strong></p>\n\n<pre><code>public async Task Init()\n{\n var workers = new List<Task>\n {\n RunThread(_threadA), // (_threadA, null) also works, but it is not necessary since null is a default value.\n RunThread(_threadB, new ThreadBOptions()\n {\n AnotherSleepTime = 10000\n }),\n };\n\n await Task.WhenAll(workers.ToArray());\n}\n\nprivate async Task RunThread<TOptions>(IThread<TOptions> thread, TOptions options = default)\n where TOptions : IOptions? { /* ... */ }\n</code></pre>\n\n<ul>\n<li>Set <code>options = default</code> for each <code>Run(...)</code> method implementation</li>\n<li>Set Thread options as nullable e.g. <code>IThread<ThreadAOptions?></code></li>\n</ul>\n\n<p><strong>Before:</strong></p>\n\n<pre><code>public class ThreadB : IThread<ThreadBOptions>\n{\n public async Task Run(\n ThreadBOptions? options\n ) { /* ... */ }\n}\n</code></pre>\n\n<p><strong>After:</strong></p>\n\n<pre><code>public class ThreadB : IThread<ThreadBOptions?>\n{\n public async Task Run(\n ThreadBOptions? options = default\n ) { /* ... */ }\n}\n</code></pre>\n\n<h2>The complete code after the review:</h2>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace App\n{\n public interface IOptions\n {\n public void Validate();\n }\n\n public interface IThread<in TOptions> where TOptions : IOptions?\n {\n public Task Run(TOptions options = default);\n }\n\n public class ThreadAOptions : IOptions\n {\n public int SleepTime = 5000; // in ms\n\n public void Validate()\n {\n if (SleepTime < 1) throw new ArgumentOutOfRangeException(nameof(SleepTime));\n }\n }\n\n public class ThreadA : IThread<ThreadAOptions?>\n {\n public async Task Run(\n ThreadAOptions? options = default\n )\n {\n options ??= new ThreadAOptions();\n options.Validate();\n\n Thread.Sleep(options.SleepTime);\n }\n }\n\n public class ThreadBOptions : IOptions\n {\n public int AnotherSleepTime = 5000; // in ms\n\n public void Validate()\n {\n if (AnotherSleepTime < 10) throw new ArgumentOutOfRangeException(nameof(AnotherSleepTime));\n }\n }\n\n public class ThreadB : IThread<ThreadBOptions?>\n {\n public async Task Run(\n ThreadBOptions? options = default\n )\n {\n options ??= new ThreadBOptions();\n options.Validate();\n\n Thread.Sleep(options.AnotherSleepTime);\n }\n }\n\n internal class App\n {\n private readonly ThreadA _threadA;\n private readonly ThreadB _threadB;\n\n // Dependencies loaded via DI\n public App(\n ThreadA threadA,\n ThreadB threadB\n )\n {\n _threadA = threadA;\n _threadB = threadB;\n }\n\n // Called from outside of the class (Program.cs)\n public async Task Init()\n {\n var workers = new List<Task>\n {\n RunThread(_threadA),\n RunThread(_threadB, new ThreadBOptions()\n {\n AnotherSleepTime = 10000\n }),\n };\n\n await Task.WhenAll(workers.ToArray());\n }\n\n private async Task RunThread<TOptions>(IThread<TOptions> thread, TOptions options = default)\n where TOptions : IOptions?\n {\n try\n {\n await Task.Run(async () => { await thread.Run(options); });\n }\n catch (Exception e)\n {\n Console.WriteLine($\"Thread exception: {e.Message}\");\n }\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T15:28:16.670",
"Id": "241193",
"ParentId": "241132",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "241193",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T10:42:06.320",
"Id": "241132",
"Score": "-1",
"Tags": [
"c#",
"generics"
],
"Title": "Generics for varied option parameter in C#"
}
|
241132
|
<p>In relation to the question I asked <a href="https://stackoverflow.com/questions/61392431/how-to-create-a-permutation-in-c-using-stl-for-number-of-places-lower-than-the">here</a>, I myself came up with an <a href="https://stackoverflow.com/a/61394238/11930602">answer</a>. I would like constructive criticism and tips to improve it to make it efficient like the other answers that have been posted.</p>
<pre><code>#include <algorithm>
#include <iostream>
#include <set>
#include <vector>
int main() {
std::vector<int> job_list;
std::set<std::vector<int>> permutations;
for (unsigned long i = 0; i < 7; i++) {
int job;
std::cin >> job;
job_list.push_back(job);
}
std::sort(job_list.begin(), job_list.end());
std::vector<int> original_permutation = job_list;
do {
std::next_permutation(job_list.begin(), job_list.end());
permutations.insert(std::vector<int>(job_list.begin(), job_list.begin() + 3));
} while (job_list != original_permutation);
for (auto& permutation : permutations) {
for (auto& pair : permutation) {
std::cout << pair << " ";
}
std::endl(std::cout);
}
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>In general, the code is nice and readable. Here's some small suggestions:</p>\n\n<ul>\n<li><p>This:</p>\n\n<pre><code>for (unsigned long i = 0; i < 7; i++) {\n int job;\n std::cin >> job;\n job_list.push_back(job);\n}\n</code></pre>\n\n<p>can be simplified (?) to</p>\n\n<pre><code>std::copy_n(std::istream_iterator<int>{std::cin}, 7, std::back_inserter(job));\n</code></pre></li>\n<li><p>Introduce variables when you use them. For example, the declaration of <code>permutations</code> may be moved after reading and sorting the numbers.</p></li>\n<li><p>Marking <code>original_permutation</code> as <code>const</code> indicates that it is used for comparison only.</p></li>\n<li><p>Use <code>emplace</code>:</p>\n\n<pre><code>permutations.emplace(job_list.begin(), job_list.begin() + 3);\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>permutations.insert(std::vector<int>(job_list.begin(), job_list.begin() + 3));\n</code></pre></li>\n<li><p><code>const auto&</code> in the <code>for</code> loops. Also, <code>std::cout << '\\n'</code> instead of <code>std::endl(std::cout)</code>.</p></li>\n<li><p>Consider extracting the functionality into a function and changing magic numbers to arguments.</p></li>\n</ul>\n\n<p>Of course, there are more efficient ways to do this. Your code generates\n<span class=\"math-container\">$$ 7! = 7 \\times 6 \\times 5 \\times 4 \\times 3 \\times 2 \\times 1 = 5040 $$</span>\npermutations, but only end up with\n<span class=\"math-container\">$$ 7^{\\underline{3}} = 7 \\times 6 \\times 5 = 210 $$</span>\nresults, and let <code>std::set</code> discard the remaining <span class=\"math-container\">\\$5040 - 210 = 4830\\$</span> permutations. You can modify your code so that it only stores one in <span class=\"math-container\">\\$4! = 24\\$</span> permutations, but the other answers to the <a href=\"https://stackoverflow.com/q/61392431\">linked question</a> provide better algorithms.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T02:54:30.173",
"Id": "241174",
"ParentId": "241133",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "241174",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T11:01:04.920",
"Id": "241133",
"Score": "2",
"Tags": [
"c++",
"combinatorics"
],
"Title": "An r-length permuter in c++"
}
|
241133
|
<p>I'm writing some code in Python that takes a set of [x,y] coordinates (in a list of tuples) and also an x-value. I need to find the two closest x coordinates to my x-value. </p>
<p>To find the closest x, I created a list of all the x-coordinates, used that list to create a lambda function that found the closest x to my x-value, and then found the index of that x.</p>
<p>Finding the 2nd closest value was a bit trickier. I created a new list that excluded the closest x and followed the same process. </p>
<p>Code is below. Any suggestions on how to improve this or make it more efficient? </p>
<pre><code>def closest_2_points(list_of_tuples, x_value):
x_points = []
for i in list_of_tuples:
x_points.append(i[0])
# find closest point
closest_xpoint_1 = min(x_points, key=lambda z:abs(z-x_value))
closest_xpoint_1_idx = x_points.index(closest_xpoint_1)
# find 2nd closest point
x_points_2 = [x for x in x_points if x != closest_xpoint_1]
closest_xpoint_2 = min(x_points_2, key=lambda z:abs(z-x_value))
closest_xpoint_2_idx = x_points.index(closest_xpoint_2)
closest_points = [(list_of_tuples[closest_xpoint_1_idx][0], list_of_tuples[closest_xpoint_1_idx][1]), (list_of_tuples[closest_xpoint_2_idx][0], list_of_tuples[closest_xpoint_2_idx][1]) ]
return closest_points
</code></pre>
<p>When running the function, it should look something like this:</p>
<pre><code>closest_2_points([(4,6),(2,5),(0,4),(-2,3)], 6)
</code></pre>
<p>And return something like this:</p>
<pre><code>[(4, 6), (2, 5)]
</code></pre>
|
[] |
[
{
"body": "<p>Welcome to codereview Ragnar!\nThis was a fun one</p>\n\n<p>Using list comprehensions, you can create a list that contains a tuple with 3 values:</p>\n\n<ol>\n<li>Distance to x </li>\n<li>Index of the tuple </li>\n<li>x value</li>\n</ol>\n\n<p>So then you can order the list, and take as many items from the tuple as desired</p>\n\n<pre><code>x = 6\npoints = [(4,6),(2,5),(0,4),(-2,3)]\nclosest_points = sorted([(x-xvalue[0], index, xvalue[0]) \n for index, xvalue in enumerate(points)])\n</code></pre>\n\n<p>Then you can slice the list and take values from there</p>\n\n<pre><code>closest_points[:2]\n> [(2, 0, 4), (4, 1, 2)]\n</code></pre>\n\n<p>In this example, you would take:</p>\n\n<ul>\n<li>0 as index of first element, 4 as the x value</li>\n<li>Then 1 as index of second element, 2 as value</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T12:59:42.567",
"Id": "473149",
"Score": "2",
"body": "Please explain how this is better than the OPs. Can you also explain why \\$O(n\\log n)\\$ time is better than \\$O(n)\\$."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T11:39:47.553",
"Id": "241136",
"ParentId": "241135",
"Score": "1"
}
},
{
"body": "<p>If there are duplicate points in your list, and the closest point turns out to be one of these points, this line of code will remove all of the duplicates:</p>\n<pre><code>x_points_2 = [x for x in x_points if x != closest_xpoint_1]\n</code></pre>\n<p>So, instead of returning the 2 closest points, it may return just one of the closest, and some other nearby point.</p>\n<hr />\n<p>Finding the n-smallest, n-closest, etc is usually best done using Python's <a href=\"https://docs.python.org/3/library/heapq.html#heapq.nsmallest\" rel=\"nofollow noreferrer\">heapq.nsmallest(n, iterable, key=None)</a> function.</p>\n<blockquote>\n<p>Return a list with the n smallest elements from the dataset defined by <em>iterable</em>. <em>key</em>, if provided, specifies a function of one argument that is used to extract a comparison key from each element in <em>iterable</em> (for example, <code>key=str.lower</code>). Equivalent to: <code>sorted(iterable, key=key)[:n]</code>.</p>\n<p>[This function] perform best for smaller values of n. For larger values, it is more efficient to use the sorted() function. Also, when <code>n==1</code>, it is more efficient to use the built-in min() and max() functions. If repeated usage of these functions is required, consider turning the iterable into an actual heap.</p>\n</blockquote>\n<p>Example: a closest <em>n</em> points function, with n defaulting to 2:</p>\n<pre><code>import heapq\n\ndef closest_points(list_of_tuples, x_value, n=2):\n return heapq.nsmallest(n, list_of_tuples, lambda pnt:abs(pnt[0] - x_value))\n</code></pre>\n<p>Example:</p>\n<pre><code>>>> closest_points([(4, 6), (2, 5), (0, 4), (-2, 3)], 6)\n[(4, 6), (2, 5)]\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T18:53:29.217",
"Id": "473189",
"Score": "0",
"body": "Thanks for the feedback. In this particular instance, removing duplicates would not be an issue (in fact I'd want to remove them), but I neglected to mention that particular assumption in the original post. Thanks for your answer; I was not aware of the heapq library."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T18:43:08.853",
"Id": "241158",
"ParentId": "241135",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T11:09:45.027",
"Id": "241135",
"Score": "4",
"Tags": [
"python",
"mathematics",
"lambda"
],
"Title": "Python: Function to Find 2 Closest Points Among [x,y] Coordinates"
}
|
241135
|
<p>I am beginner a 1st year cs student. I am taking CS50 and I completed the first week problem of implementing Luhn Check algorithm. Though my solution works I feel it's very sloppy and not efficient. Can someone please suggest how can I improve my solution? (It's a first-week problem so you are not intended to use array or functions.) </p>
<p>Here is the code:</p>
<pre><code>#include<stdlib.h>
#include<cs50.h>
int main()
{
long long x,j=0;
int len,i,len_flag,flag=0,flag_val=0,sp_len=0,check_flag=0; //basic integers related to loop etc
int res,sum,fin_sum=0,h=0,d2_sum=0,d1_sum=0,ff_num=0; // variables related to extracting numbers
int sum_len=0,in_sum=0,in_fsum=0,len_sum=0,m=0; // extraing numbers from more than single sum result
int sum_f=0,sum_final=0;
do{
x = get_long("enter a valid card number \n");
j=x;
len_flag = 0;
len = 0;
while(len_flag!=1)
{
x = x / 10;
if(x==0)
{
len_flag = 1; //finding the lenght of the number
}
len++;
}
if(len==15||len==16||len==13)
{
flag = 1;
sp_len =1;
}
else
{
flag=1;
}
}while(flag!=1);
for(i=0;i<len;i++)
{
res = j % 10;
j = j / 10;
if(i%2!=0)
{
sum = res * 2;
//printf("multi_res : %d \n",sum);
len_flag = 0;
sum_len = 0;
len_sum = sum;
while(len_flag!=1)
{
len_sum = len_sum / 10;
if(len_sum==0)
{
len_flag=1; // checking if the sum is more than single digit
}
sum_len++;
//printf("trig\n");
}
if(sum_len>1)
{ x=0;
while(x<sum_len)
{
in_sum = sum % 10;
sum = sum/10;
in_fsum = in_fsum + in_sum;
//printf("double sum : %d \n",in_fsum);
x++;
}
}
fin_sum = fin_sum + sum;
}
if(i==len-1)
{
for(h=0;h < 1;h++)
{
fin_sum = fin_sum + in_fsum;
}
d1_sum = res;
}
else if(i%2==0)
{
sum_f = sum_f + res; // adding up the number that where not x2
}
if(i==len-2)
{
d2_sum = res; //5555555555554444
}
}
sum_final = sum_f + fin_sum;
//printf("sum_final : %d\n",sum_final);
//printf("sum_f_final : %d\n",sum_f);
//printf("sum_in_final : %d\n",fin_sum);
if(sum_final%10==0)
{
flag_val=1; // checking if the number is valid
}
if(ff_num == 0)
{
ff_num = (d1_sum*10) + d2_sum; //flip
}
do
{
if(sp_len==0)
{
printf("INVALID\n");
check_flag=1;
break;
}
if((flag==1&&flag_val==1&&ff_num==34)||ff_num==37)
{
printf("AMEX\n");
check_flag=1;
break;
}
else if(flag==1&&flag_val==1&&ff_num>50&&ff_num<56)
{
printf("MASTERCARD\n");
check_flag=1;
break;
}
else if(flag==1&&flag_val==1&&d1_sum==4)
{
printf("VISA\n");
check_flag=1;
break;
}
else
{
printf("INVALID\n");
check_flag=1;
break;
}
}while(check_flag!=1);
return 0;
}
</code></pre>
<p>I felt like I was fixing a leak while writing the code. I would try to correct one thing and another thing would go wrong and this is the final result.</p>
<p>Thank you for your help. If the question was not asked properly please forgive me; it's my first time here.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T17:44:19.923",
"Id": "473186",
"Score": "1",
"body": "What kind of optimization are you looking for, execution time, memory size or something else?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T04:49:42.717",
"Id": "473233",
"Score": "0",
"body": "Both i feel there is a better way of doing it but i cant figure it out"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T09:03:39.103",
"Id": "473245",
"Score": "0",
"body": "Hmmm, \"not intended to use array\" --> yet code uses `\"enter a valid card number \\n\"` which is an [array](https://stackoverflow.com/questions/2245664/what-is-the-type-of-string-literals-in-c-and-c)."
}
] |
[
{
"body": "<p>Code will look much better once OP can use own functions.</p>\n\n<blockquote>\n <p>how can I improve my solution?</p>\n</blockquote>\n\n<p><strong>Meaningful names</strong></p>\n\n<p>Why is the credit card number called <code>j</code>. How about <code>cc_num</code>?</p>\n\n<p>Many others names need like-wise improvements.</p>\n\n<p><strong>Use <code>bool</code></strong></p>\n\n<p>For flags, consider <code>bool</code>.</p>\n\n<pre><code>#include <stdbool.h>\n\nbool flag;\n</code></pre>\n\n<p><strong>Auto format</strong></p>\n\n<p>Use a development environment that supports auto formatting. Do not format manually - just not efficient.</p>\n\n<pre><code>#include<stdlib.h>\n#include<cs50.h>\n\nint main() {\n long long x, j = 0;\n int len, i, len_flag, flag = 0, flag_val = 0, sp_len = 0, check_flag = 0; //basic integers related to loop etc\n int res, sum, fin_sum = 0, h = 0, d2_sum = 0, d1_sum = 0, ff_num = 0; // variables related to extracting numbers \n int sum_len = 0, in_sum = 0, in_fsum = 0, len_sum = 0, m = 0; // extraing numbers from more than single sum result \n int sum_f = 0, sum_final = 0;\n\n do {\n x = get_long(\"enter a valid card number \\n\");\n j = x;\n len_flag = 0;\n len = 0;\n while (len_flag != 1) {\n x = x / 10;\n if (x == 0) {\n len_flag = 1; //finding the lenght of the number \n }\n len++;\n }\n if (len == 15 || len == 16 || len == 13) {\n flag = 1;\n sp_len = 1;\n } else {\n flag = 1;\n }\n\n } while (flag != 1);\n ...\n</code></pre>\n\n<p><strong>Define variables where needed</strong></p>\n\n<p>Rather than a sea of objects up front, defined them where needed.</p>\n\n<p>Example: Refactor <code>x</code>. Other variables can like-wise get defined closer to their usage.</p>\n\n<pre><code> // long long x, j = 0;\n long long j = 0;\n ...\n\n do {\n // x = get_long(\"enter a valid card number \\n\");\n long long x = get_long(\"enter a valid card number \\n\");\n j = x;\n ...\n\n if (sum_len > 1) {\n // x = 0;\n int x = 0;\n</code></pre>\n\n<p><strong>Spelling</strong></p>\n\n<pre><code>//finding the lenght of the number\n finding the length of the number\n</code></pre>\n\n<p><strong>Clean-up</strong></p>\n\n<p>For review purposes, no need for dead debug code.<br>\nEliminate <code>//printf(\"multi_res : %d \\n\",sum)</code>, etc.</p>\n\n<p>Eliminate unused variables like <code>m</code>.</p>\n\n<p><strong>Comment code</strong></p>\n\n<p>Each chunk of code deserves to be a function, yet I understand that is prohibited for now.</p>\n\n<p>I'd comment the chunks of code to help aide understanding.</p>\n\n<pre><code> // Read input CC number\n // Set j as the CC#, len_flag as the CC# length, flag to 1, ...\n do {\n long long x = get_long(\"enter a valid card number \\n\");\n</code></pre>\n\n<p><strong>Simplify</strong></p>\n\n<p><code>flag</code> only used as 1.</p>\n\n<pre><code> do {\n ...\n flag = 1;\n } while (flag != 1);\n</code></pre>\n\n<p>Replaceable with </p>\n\n<pre><code> {\n ...\n }\n</code></pre>\n\n<p>Same for later <code>do { ... } while (check_flag != 1);</code>.</p>\n\n<p><strong>Documentation</strong></p>\n\n<p>Within code I'd add an algorithm link:</p>\n\n<pre><code>// https://en.wikipedia.org/wiki/Luhn_algorithm\n</code></pre>\n\n<p><strong>Why space before '\\n' ?</strong></p>\n\n<pre><code>// \"enter a valid card number \\n\"\n\"enter a valid card number\\n\"\n</code></pre>\n\n<p><strong>Chunks of code seem verbose</strong></p>\n\n<pre><code>len_flag = 0;\nlen = 0;\nwhile (len_flag != 1) {\n x = x / 10;\n if (x == 0) {\n len_flag = 1; //finding the lenght of the number \n }\n len++;\n}\n</code></pre>\n\n<p>versus</p>\n\n<pre><code>// decimal digit length of x\nlen = 0;\ndo {\n len++;\n} while (x /= 10);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T11:07:45.177",
"Id": "473255",
"Score": "0",
"body": "thank you very much will definitely take care of the thing that you pointed out do you have any better way of implementing the algorithm thank you very much"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T15:27:44.170",
"Id": "473274",
"Score": "1",
"body": "@rayman I'd consider processing the CC# as a string and not a number."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T09:48:42.293",
"Id": "241185",
"ParentId": "241138",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "241185",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T12:59:50.740",
"Id": "241138",
"Score": "3",
"Tags": [
"performance",
"beginner",
"c",
"memory-optimization"
],
"Title": "Implementation of Luhn Check Algorithm"
}
|
241138
|
<p>I implemented an immutable hash map in C, as described in <a href="https://michael.steindorfer.name/publications/oopsla15.pdf" rel="nofollow noreferrer">this paper</a>. First, my design goals:</p>
<ul>
<li>plug-and-playable: compile with <code>gcc -O3 -std=c11 champ.c</code>, <code>#include "champ.h"</code>, ready to use</li>
<li><code>#define</code> Key and value types to suit your needs: see <em>Using it as a "<code>champ<string,int></code>"</em> below</li>
<li>Provide reference counting as the default heap policy, but make it easy enough to modify the source to use your own strategy</li>
<li>thread safety: persistent collections really start to take off in a multithreaded environment, which is where I intend to use this</li>
<li>cache locality: The abovementioned paper puts a lot of focus on improving cache locality, so I wanted to at least match that</li>
</ul>
<p>Further below you can see what I have so far. It does what it's supposed to, i'm pretty confident that it's correct and stable, I have written extensive tests (84% coverage, up to 98% planned), valgrind comes up clean. However, I still have some big question marks/insecurities: </p>
<ul>
<li>Is the interface well designed?</li>
<li>Is my use of <code>const</code> sensible?
<ul>
<li>In particular: what about taking keys/values params as <code>const</code>, which really only has any significance when they are actually pointers.</li>
</ul></li>
<li>Is there any value in hiding the <code>struct champ</code> implementation if I intend to distribute it as source code anyway?</li>
<li>How can I test the implementation (a fairly critical aspect of library development) without subverting/undermining the interface?</li>
<li>Is my strategy for dealing with memory management requirements sensible? (making the source accessible and easy to hack)</li>
<li>Should I use more <code>typedef</code>'s? Maybe instead of <code>CHAMP_VALUE_T</code>? </li>
</ul>
<p>Of course, any feedback is desired. I really only have a grasp of C semantics, but little experience in developing large scale projects.</p>
<p>Lastly, a short breakdown of the biggest "gotchas":</p>
<ul>
<li>This is a hash trie with a branching factor of 32. It takes a key-value-pair, computes the key's hash (<code>uint32_t</code>), and looks at the five least significant bits, interpreting them as the index in the root node of the trie (2^5 == 32).</li>
<li>If the node already contains an entry at that index, but with an unequal key, the current entry and the new key-value-pair are "pushed down". Their hashes are shifted to the right by 5 bits, and the five next least significant bits are used to determine the entries' index in the next level, and the process starts again.</li>
<li>This is a persistent data structure, so instead of modifying a node, a copy of that node gets created and modified, which in turn is then inserted into a copy of it's parent node, and so on, until a new root node gets created and inserted into a new hash map.</li>
<li>There's 7 "levels" of nodes (32 / 5 = 6.4, the last layer only hash 2 bits of variance). In case of a hash collision - which only happens if the <em>entire</em> hash is equal, so it <em>should</em> happen less often than with conventional hash tables - an 8th layer is created. At that level only a special kind of node gets created (<code>struct collision_node</code>), and that special kind of node only gets created at that level. Therefore I'm using <code>shift >= HASH_TOTAL_WIDTH</code> to determine whether I'm dealing with a regular or a collision node, so I don't have to implement some sort of dynamic dispatch polymorphism.</li>
</ul>
<h3>champ.h:</h3>
<pre class="lang-c prettyprint-override"><code>/*
* MIT License
*
* Copyright (c) 2020 Samuel Vogelsanger <vogelsangersamuel@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef CHAMP_CHAMP_H
#define CHAMP_CHAMP_H
#include <stdint.h>
#include <stddef.h>
#ifndef DEBUG_PRINT
#ifdef DEBUG
#define DBG 1
#else
#define DBG 0
#endif
#define DEBUG_PRINT(fmt, ...) \
do { if (DBG) fprintf(stderr, "DEBUG: champ: " fmt, __VA_ARGS__); } while (0)
#endif
#ifndef CHAMP_KEY_T
#define CHAMP_KEY_T void*
#endif
#ifndef CHAMP_VALUE_T
#define CHAMP_VALUE_T void*
#endif
/**
* These are mostly for convenience
*/
#define CHAMP_HASHFN_T(name) uint32_t (*name)(const CHAMP_KEY_T)
#define CHAMP_EQUALSFN_T(name) int (*name)(const CHAMP_KEY_T left, const CHAMP_KEY_T right)
#define CHAMP_ASSOCFN_T(name) CHAMP_VALUE_T (*name)(const CHAMP_KEY_T key, const CHAMP_VALUE_T old_value, void *user_data)
#define CHAMP_VALUE_EQUALSFN_T(name) int (*name)(const CHAMP_VALUE_T left, const CHAMP_VALUE_T right)
/**
* These macros help with defining the various callbacks. Use them like so:
* @code{c}
* CHAMP_MAKE_EQUALSFN(equals_int, left, right)
* {
* return left == right;
* }
* @endcode
*/
#define CHAMP_MAKE_HASHFN(name, arg_1) uint32_t name(const CHAMP_KEY_T arg_1)
#define CHAMP_MAKE_EQUALSFN(name, arg_l, arg_r) int name(const CHAMP_KEY_T arg_l, const CHAMP_KEY_T arg_r)
#define CHAMP_MAKE_ASSOCFN(name, key_arg, value_arg, user_data_arg) CHAMP_VALUE_T name(const CHAMP_KEY_T key_arg, const CHAMP_VALUE_T value_arg, void *user_data_arg)
#define CHAMP_MAKE_VALUE_EQUALSFN(name, arg_l, arg_r) int name(const CHAMP_VALUE_T arg_l, const CHAMP_VALUE_T arg_r)
// todo: replace with something like: "typedef struct champ champ;" to hide implementation details.
struct champ {
volatile uint32_t ref_count;
unsigned length;
struct node *root;
CHAMP_HASHFN_T(hash);
CHAMP_EQUALSFN_T(equals);
};
/**
* Creates a new map with the given hash and equals functions. This implementation is based on the assumption that if
* two keys are equal, their hashes must be equal as well. This is commonly known as the Java Hashcode contract.
*
* The reference count of a new map is zero.
*
* @param hash
* @param equals
* @return
*/
struct champ *champ_new(CHAMP_HASHFN_T(hash), CHAMP_EQUALSFN_T(equals));
/**
* Destroys a champ. Doesn't clean up the stored key-value-pairs.
*
* @param old
*/
void champ_destroy(struct champ **champ);
/**
* Atomically increases the reference count of a map.
*
* @param champ
* @return
*/
struct champ *champ_acquire(const struct champ *champ);
/**
* Atomically decreases the reference count of a map and calls champ_destroy if it caused the count to drop to zero.
*
* In either case then sets the reference to NULL.
*
* @param champ
*/
void champ_release(struct champ **champ);
/**
* Returns the number of entries in champ.
*
* @param champ
* @return the number of entries
*/
unsigned champ_length(const struct champ *champ);
/**
* Looks up key and sets *value_receiver to the associated value. Doesn't change value_receiver if key is not set.
*
* @param champ
* @param key
* @param found is set to 0 if key is not set
* @return
*/
CHAMP_VALUE_T champ_get(const struct champ *champ, const CHAMP_KEY_T key, int *found);
/**
* Returns a new map derived from champ but with key set to value.
* If replaced is not NULL, sets it to indicate if the key is present in champ.
*
* Reference count of the new map is zero.
*
* @param champ
* @param key
* @param value
* @param replaced
* @return a new champ
*/
struct champ *champ_set(const struct champ *champ, const CHAMP_KEY_T key, const CHAMP_VALUE_T value, int *replaced);
/**
* Returns a new map derived from champ but without a mapping for key.
*
* Reference count of the new map is zero.
*
* @param champ
* @param key
* @param modified
* @return
*/
struct champ *champ_del(const struct champ *champ, const CHAMP_KEY_T key, int *modified);
/**
* Creates a new champ with the given hash and equals functions, and inserts the given keys and values.
* Only the first 'length' elements from keys and values are inserted.
*
* Reference count of the new map is zero.
*
* @param hash
* @param equals
* @param keys
* @param values
* @param length
* @return
*/
struct champ *champ_of(CHAMP_HASHFN_T(hash), CHAMP_EQUALSFN_T(equals), CHAMP_KEY_T *keys, CHAMP_VALUE_T *values, size_t length);
/**
* Returns a new map derived from champ, but with key set to the return value of fn.
* fn is passed the key, the current value for key, and user_data.
* If key is not present in champ, NULL is passed in place of the key and current value.
*
* Reference count of the new map is zero.
*
* @param champ
* @param key
* @param fn
* @param user_data
* @return
*/
struct champ *champ_assoc(const struct champ *champ, const CHAMP_KEY_T key, CHAMP_ASSOCFN_T(fn), const void *user_data);
/**
* Compares two maps for equality. A lot of short-circuiting is done on the assumption that unequal hashes
* (for both keys and values) imply inequality. This is commonly known as the Java Hashcode contract: If two values
* are equal, their hashes must be equal as well.
*
* @param left
* @param right
* @return
*/
int champ_equals(const struct champ *left, const struct champ *right, CHAMP_VALUE_EQUALSFN_T(value_equals));
/**
* An iterator for champ. Meant to be put on the stack.
*/
struct champ_iter {
int stack_level;
unsigned element_cursor;
unsigned element_arity;
unsigned branch_cursor_stack[8];
unsigned branch_arity_stack[8];
const void *node_stack[8];
};
/**
* Initializes an iterator with a champ.
*
* Example:
* @code{.c}
* struct champ_iter iter;
* CHAMP_KEY_T key;
* CHAMP_VAL_T val;
*
* champ_iter_init(&iter, champ);
* while(champ_iter_next(&iter, &key, &val)) {
* // do something with key and value
* }
* @endcode
*
* @param iter
* @param champ
*/
void champ_iter_init(struct champ_iter *iter, const struct champ *champ);
/**
* Advances iter and points key_receiver and value_receiver to the next pair.
*
* @param iter
* @param key_receiver
* @param value_receiver
* @return 0 if the end of the champ has been reached
*/
int champ_iter_next(struct champ_iter *iter, CHAMP_KEY_T *key_receiver, CHAMP_VALUE_T *value_receiver);
#endif //CHAMP_CHAMP_H
</code></pre>
<h3>champ.c</h3>
<pre class="lang-c prettyprint-override"><code>/*
* MIT License
*
* Copyright (c) 2020 Samuel Vogelsanger <vogelsangersamuel@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/*
* All the ref-counting specific code was marked with a "//reference counting" comment. If you need to modify this to
* work with your own memory policy, it is recommended to start looking at those places to understand when and where
* memory is allocated and freed.
*/
#include <malloc.h>
#include <stdint.h>
#include <stdio.h>
#include <stdatomic.h> // reference counting
#include <string.h>
#include "champ.h"
#define champ_node_debug_fmt "node{element_arity=%u, element_map=%08x, branch_arity=%u, branch_map=%08x, ref_count=%u}"
#define champ_node_debug_args(node) node->element_arity, node->element_map, node->branch_arity, node->branch_map, node->ref_count
#define HASH_PARTITION_WIDTH 5u
#define HASH_TOTAL_WIDTH (8 * sizeof(uint32_t))
/*
* Helper functions
*/
static unsigned bitcount(uint32_t value)
{
// taken from http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
value = value - ((value >> 1u) & 0x55555555u); // reuse input as temporary
value = (value & 0x33333333u) + ((value >> 2u) & 0x33333333u); // temp
return (((value + (value >> 4u)) & 0xF0F0F0Fu) * 0x1010101u) >> 24u; // count
}
static uint32_t champ_mask(uint32_t hash, unsigned shift)
{
return (hash >> shift) & ((1u << HASH_PARTITION_WIDTH) - 1);
}
static unsigned champ_index(uint32_t bitmap, uint32_t bitpos)
{
return bitcount(bitmap & (bitpos - 1));
}
/*
* Data structure definitions
*/
struct kv {
CHAMP_KEY_T key;
CHAMP_VALUE_T val;
};
#define CHAMP_NODE_ELEMENT_T struct kv
#define CHAMP_NODE_BRANCH_T struct node *
struct node {
uint8_t element_arity;
uint8_t branch_arity;
volatile uint16_t ref_count; // reference counting
uint32_t element_map;
uint32_t branch_map;
CHAMP_NODE_ELEMENT_T content[];
};
struct collision_node {
uint8_t element_arity; // MUST SHARE LAYOUT WITH struct node
uint8_t branch_arity; // MUST SHARE LAYOUT WITH struct node
volatile uint16_t ref_count; // MUST SHARE LAYOUT WITH struct node // reference counting
CHAMP_NODE_ELEMENT_T content[];
};
static const struct node empty_node = {
.branch_arity = 0,
.element_arity = 0,
.ref_count = 1,
.branch_map = 0,
.element_map = 0,
};
#define CHAMP_NODE_ELEMENTS(node) (node)->content
#define CHAMP_NODE_BRANCHES(node) ((CHAMP_NODE_BRANCH_T const *)&(node)->content[(node)->element_arity])
#define CHAMP_NODE_ELEMENTS_SIZE(length) (sizeof(CHAMP_NODE_ELEMENT_T) * (length))
#define CHAMP_NODE_BRANCHES_SIZE(length) (sizeof(CHAMP_NODE_BRANCH_T) * (length))
#define CHAMP_NODE_ELEMENT_AT(node, bitpos) CHAMP_NODE_ELEMENTS(node)[champ_index(node->element_map, bitpos)]
#define CHAMP_NODE_BRANCH_AT(node, bitpos) CHAMP_NODE_BRANCHES(node)[champ_index(node->branch_map, bitpos)]
/*
* static function declarations
*/
// node constructor
static struct node *node_new(uint32_t element_map, uint32_t branch_map, CHAMP_NODE_ELEMENT_T const *elements,
uint8_t element_arity, CHAMP_NODE_BRANCH_T const *branches, uint8_t branch_arity);
// collision node variant
static struct collision_node *collision_node_new(const CHAMP_NODE_ELEMENT_T *values, uint8_t element_arity);
// destructor
static void node_destroy(struct node *node);
// reference counting
static inline struct node *champ_node_acquire(const struct node *node);
// reference counting
static inline void champ_node_release(const struct node *node);
// top-level functions
static CHAMP_VALUE_T node_get(const struct node *node, CHAMP_EQUALSFN_T(equals), const CHAMP_KEY_T key, uint32_t hash,
unsigned shift, int *found);
static struct node *node_update(const struct node *node, CHAMP_HASHFN_T(hashfn), CHAMP_EQUALSFN_T(equals),
const CHAMP_KEY_T key, const CHAMP_VALUE_T value, uint32_t hash, unsigned shift,
int *found);
static struct node *node_assoc(const struct node *node, CHAMP_HASHFN_T(hashfn), CHAMP_EQUALSFN_T(equals),
const CHAMP_KEY_T key, CHAMP_ASSOCFN_T(fn), const void *user_data, uint32_t hash,
unsigned shift, int *found);
static struct node *node_del(const struct node *node, CHAMP_EQUALSFN_T(equals), const CHAMP_KEY_T key, uint32_t hash,
unsigned shift, int *modified);
// collision node variants
static CHAMP_VALUE_T collision_node_get(const struct collision_node *node, CHAMP_EQUALSFN_T(equals),
const CHAMP_KEY_T key, int *found);
static struct collision_node *collision_node_update(const struct collision_node *node, CHAMP_EQUALSFN_T(equals),
const CHAMP_KEY_T key, const CHAMP_VALUE_T value, int *found);
static struct collision_node *collision_node_assoc(const struct collision_node *node, CHAMP_EQUALSFN_T(equals),
const CHAMP_KEY_T key, CHAMP_ASSOCFN_T(fn), const void *user_data,
int *found);
static struct collision_node *collision_node_del(const struct collision_node *node, CHAMP_EQUALSFN_T(equals),
const CHAMP_KEY_T key, int *modified);
// helper functions for creation of modified nodes
static struct node *node_merge(uint32_t hash_l, const CHAMP_KEY_T key_l, const CHAMP_VALUE_T value_l, uint32_t hash_r,
const CHAMP_KEY_T key_r, const CHAMP_VALUE_T value_r, unsigned shift);
static struct node *node_clone_pullup(const struct node *node, uint32_t bitpos, const struct kv element);
static struct node *node_clone_update_branch(const struct node *node, uint32_t bitpos, struct node *branch);
static struct node *node_clone_pushdown(const struct node *node, uint32_t bitpos, struct node *branch);
static struct node *node_clone_insert_element(const struct node *node, uint32_t bitpos, const CHAMP_KEY_T key,
const CHAMP_VALUE_T value);
static struct node *node_clone_update_element(const struct node *node, uint32_t bitpos, const CHAMP_VALUE_T value);
static struct node *node_clone_remove_element(const struct node *node, uint32_t bitpos);
// collision node variants
static struct collision_node *collision_node_clone_insert_element(const struct collision_node *node,
const CHAMP_KEY_T key, const CHAMP_VALUE_T value);
static struct collision_node *collision_node_clone_update_element(const struct collision_node *node, unsigned index,
const CHAMP_VALUE_T value);
static struct collision_node *collision_node_clone_remove_element(const struct collision_node *node, unsigned index);
// equality
static int node_equals(const struct node *left, const struct node *right, CHAMP_EQUALSFN_T(key_equals),
CHAMP_VALUE_EQUALSFN_T(value_equals), unsigned shift);
static int collision_node_equals(const struct collision_node *left, const struct collision_node *right,
CHAMP_EQUALSFN_T(key_equals), CHAMP_VALUE_EQUALSFN_T(value_equals));
// champ private constructor
static struct champ *champ_from(struct node *root, unsigned length, CHAMP_HASHFN_T(hash), CHAMP_EQUALSFN_T(equals));
// iterator helper functions
static void iter_push(struct champ_iter *iterator, const struct node *node);
static void iter_pop(struct champ_iter *iterator);
/*
* definitions
*/
static void node_destroy(struct node *node)
{
DEBUG_PRINT(" destroying " champ_node_debug_fmt "@%p\n", champ_node_debug_args(node), (void *)node);
// reference counting
CHAMP_NODE_BRANCH_T *branches = (CHAMP_NODE_BRANCH_T *)CHAMP_NODE_BRANCHES(node);
for (int i = 0; i < node->branch_arity; ++i) {
champ_node_release(branches[i]);
}
free(node);
}
// reference counting
static inline struct node *champ_node_acquire(const struct node *node)
{
if (node == &empty_node)
return (struct node *)node;
atomic_fetch_add((uint16_t *)&node->ref_count, 1u);
return (struct node *)node;
}
// reference counting
static inline void champ_node_release(const struct node *node)
{
if (node == &empty_node)
return;
if (atomic_fetch_sub((uint16_t *)&node->ref_count, 1u) == 1)
node_destroy((struct node *)node);
}
/**
* WARNING: all branches in <code>branches</code> are "acquired", i.e. their reference count is incremented.
* Do not pass an "almost correct" list of branches.
*/
static struct node *node_new(uint32_t element_map, uint32_t branch_map,
CHAMP_NODE_ELEMENT_T const *elements, uint8_t element_arity,
CHAMP_NODE_BRANCH_T const *branches, uint8_t branch_arity)
{
const size_t content_size = CHAMP_NODE_ELEMENTS_SIZE(element_arity) + CHAMP_NODE_BRANCHES_SIZE(branch_arity);
struct node *result = malloc(sizeof(*result) + content_size);
result->element_arity = element_arity;
result->branch_arity = branch_arity;
result->ref_count = 0;
result->element_map = element_map;
result->branch_map = branch_map;
memcpy(CHAMP_NODE_ELEMENTS(result), elements, CHAMP_NODE_ELEMENTS_SIZE(element_arity));
CHAMP_NODE_BRANCH_T *branches_dest = (CHAMP_NODE_BRANCH_T *)CHAMP_NODE_BRANCHES(result);
// reference counting
for (int i = 0; i < branch_arity; ++i) {
branches_dest[i] = champ_node_acquire(branches[i]);
}
return result;
}
static CHAMP_VALUE_T collision_node_get(const struct collision_node *node, CHAMP_EQUALSFN_T(equals),
const CHAMP_KEY_T key, int *found)
{
for (unsigned i = 0; i < node->element_arity; ++i) {
struct kv kv = node->content[i];
if (equals(kv.key, key)) {
*found = 1;
return kv.val;
}
}
*found = 0;
return (CHAMP_VALUE_T)0;
}
static CHAMP_VALUE_T node_get(const struct node *node, CHAMP_EQUALSFN_T(equals),
const CHAMP_KEY_T key, uint32_t hash, unsigned shift, int *found)
{
if (shift >= HASH_TOTAL_WIDTH)
return collision_node_get((const struct collision_node *)node, equals, key, found);
const uint32_t bitpos = 1u << champ_mask(hash, shift);
if (node->branch_map & bitpos) {
return node_get(CHAMP_NODE_BRANCH_AT(node, bitpos), equals, key, hash, shift + HASH_PARTITION_WIDTH, found);
} else if (node->element_map & bitpos) {
CHAMP_NODE_ELEMENT_T kv = CHAMP_NODE_ELEMENT_AT(node, bitpos);
if (equals(kv.key, key)) {
*found = 1;
return kv.val;
}
}
*found = 0;
return (CHAMP_VALUE_T)0;
}
static struct node *node_clone_insert_element(const struct node *node, uint32_t bitpos,
const CHAMP_KEY_T key, const CHAMP_VALUE_T value)
{
CHAMP_NODE_ELEMENT_T elements[1u << HASH_PARTITION_WIDTH];
const unsigned index = champ_index(node->element_map, bitpos);
// copy <branch_arity> chunks in total
memcpy(elements, CHAMP_NODE_ELEMENTS(node), CHAMP_NODE_ELEMENTS_SIZE(index)); // copy first <index> chunks
elements[index].key = (CHAMP_KEY_T)key;
elements[index].val = (CHAMP_VALUE_T)value;
memcpy(
&elements[index + 1], // start copying into one-past-<index>
&CHAMP_NODE_ELEMENTS(node)[index], // start copying from <index>
CHAMP_NODE_ELEMENTS_SIZE(node->element_arity - index) // <index> chunks already copied, <branch_arity> - <index> remaining
);
return node_new(
node->element_map | bitpos, node->branch_map, elements,
node->element_arity + 1, CHAMP_NODE_BRANCHES(node), node->branch_arity);
}
static struct node *node_clone_update_element(const struct node *node,
uint32_t bitpos, const CHAMP_VALUE_T value)
{
CHAMP_NODE_ELEMENT_T elements[1u << HASH_PARTITION_WIDTH];
const unsigned index = champ_index(node->element_map, bitpos);
memcpy(elements, CHAMP_NODE_ELEMENTS(node), CHAMP_NODE_ELEMENTS_SIZE(node->element_arity));
elements[index].val = (CHAMP_VALUE_T)value;
return node_new(node->element_map, node->branch_map, elements, node->element_arity, CHAMP_NODE_BRANCHES(node), node->branch_arity);
}
static struct node *node_clone_update_branch(const struct node *node,
uint32_t bitpos, struct node *branch)
{
CHAMP_NODE_BRANCH_T branches[1u << HASH_PARTITION_WIDTH];
const unsigned index = champ_index(node->branch_map, bitpos);
memcpy(branches, CHAMP_NODE_BRANCHES(node), CHAMP_NODE_BRANCHES_SIZE(node->branch_arity));
branches[index] = branch;
return node_new(node->element_map, node->branch_map, CHAMP_NODE_ELEMENTS(node), node->element_arity, branches, node->branch_arity);
}
static struct node *node_clone_pushdown(const struct node *node,
uint32_t bitpos, struct node *branch)
{
CHAMP_NODE_ELEMENT_T elements[1u << HASH_PARTITION_WIDTH];
CHAMP_NODE_BRANCH_T branches[1u << HASH_PARTITION_WIDTH];
const unsigned element_index = champ_index(node->element_map, bitpos);
const unsigned branch_index = champ_index(node->branch_map, bitpos);
memcpy(elements, CHAMP_NODE_ELEMENTS(node), CHAMP_NODE_ELEMENTS_SIZE(element_index));
memcpy(
&elements[element_index],
&CHAMP_NODE_ELEMENTS(node)[element_index + 1],
CHAMP_NODE_ELEMENTS_SIZE(node->element_arity - (element_index + 1))
);
memcpy(branches, CHAMP_NODE_BRANCHES(node), CHAMP_NODE_BRANCHES_SIZE(branch_index));
memcpy(
&branches[branch_index + 1],
&CHAMP_NODE_BRANCHES(node)[branch_index],
CHAMP_NODE_BRANCHES_SIZE(node->branch_arity - branch_index)
);
branches[branch_index] = branch;
return node_new(
node->element_map & ~bitpos,
node->branch_map | bitpos, elements, node->element_arity - 1, branches, node->branch_arity + 1);
}
static struct collision_node *collision_node_new(const CHAMP_NODE_ELEMENT_T *values, uint8_t element_arity)
{
size_t content_size = sizeof(CHAMP_NODE_ELEMENT_T) * element_arity;
struct collision_node *result = malloc(sizeof(*result) + content_size);
result->element_arity = element_arity;
result->branch_arity = 0;
result->ref_count = 0;
memcpy(result->content, values, CHAMP_NODE_ELEMENTS_SIZE(element_arity));
return result;
}
static struct node *node_merge(uint32_t hash_l, const CHAMP_KEY_T key_l, const CHAMP_VALUE_T value_l,
uint32_t hash_r, const CHAMP_KEY_T key_r, const CHAMP_VALUE_T value_r,
unsigned shift)
{
uint32_t bitpos_l = 1u << champ_mask(hash_l, shift);
uint32_t bitpos_r = 1u << champ_mask(hash_r, shift);
if (shift >= HASH_TOTAL_WIDTH) {
CHAMP_NODE_ELEMENT_T elements[2];
elements[0].key = (CHAMP_KEY_T)key_l;
elements[0].val = (CHAMP_VALUE_T)value_l;
elements[1].key = (CHAMP_KEY_T)key_r;
elements[1].val = (CHAMP_VALUE_T)value_r;
return (struct node *)collision_node_new(elements, 2);
} else if (bitpos_l != bitpos_r) {
CHAMP_NODE_ELEMENT_T elements[2];
if (bitpos_l <= bitpos_r) {
elements[0].key = (CHAMP_KEY_T)key_l;
elements[0].val = (CHAMP_VALUE_T)value_l;
elements[1].key = (CHAMP_KEY_T)key_r;
elements[1].val = (CHAMP_VALUE_T)value_r;
} else {
elements[0].key = (CHAMP_KEY_T)key_r;
elements[0].val = (CHAMP_VALUE_T)value_r;
elements[1].key = (CHAMP_KEY_T)key_l;
elements[1].val = (CHAMP_VALUE_T)value_l;
}
return node_new(bitpos_l | bitpos_r, 0u, elements, 2, NULL, 0);
} else {
struct node *sub_node = node_merge(
hash_l,
key_l,
value_l,
hash_r,
key_r,
value_r,
shift + HASH_PARTITION_WIDTH
);
return node_new(0, bitpos_l, NULL, 0, &sub_node, 1);
}
}
static struct collision_node *collision_node_clone_update_element(const struct collision_node *node,
unsigned index, const CHAMP_VALUE_T value)
{
CHAMP_NODE_ELEMENT_T elements[node->element_arity];
memcpy(elements, node->content, CHAMP_NODE_ELEMENTS_SIZE(node->element_arity));
elements[index].val = (CHAMP_VALUE_T)value;
return collision_node_new(elements, node->element_arity);
}
static struct collision_node *collision_node_clone_insert_element(const struct collision_node *node,
const CHAMP_KEY_T key,
const CHAMP_VALUE_T value)
{
CHAMP_NODE_ELEMENT_T elements[node->element_arity + 1];
memcpy(elements, node->content, CHAMP_NODE_ELEMENTS_SIZE(node->element_arity));
elements[node->element_arity].key = (CHAMP_KEY_T)key;
elements[node->element_arity].val = (CHAMP_VALUE_T)value;
return collision_node_new(elements, node->element_arity + 1);
}
static struct collision_node *collision_node_update(const struct collision_node *node,
CHAMP_EQUALSFN_T(equals),
const CHAMP_KEY_T key, const CHAMP_VALUE_T value,
int *found)
{
for (unsigned i = 0; i < node->element_arity; ++i) {
struct kv kv = node->content[i];
if (equals(kv.key, key)) {
*found = 1;
return collision_node_clone_update_element(node, i, value);
}
}
return collision_node_clone_insert_element(node, key, value);
}
static struct node *node_update(const struct node *node, CHAMP_HASHFN_T(hashfn), CHAMP_EQUALSFN_T(equals),
const CHAMP_KEY_T key, const CHAMP_VALUE_T value, uint32_t hash, unsigned shift,
int *found)
{
if (shift >= HASH_TOTAL_WIDTH)
return (struct node *)collision_node_update((const struct collision_node *)node, equals, key, value, found);
const uint32_t bitpos = 1u << champ_mask(hash, shift);
if (node->branch_map & bitpos) {
const struct node *sub_node = CHAMP_NODE_BRANCH_AT(node, bitpos);
struct node *new_sub_node = node_update(sub_node, hashfn, equals, key, value, hash,
shift + HASH_PARTITION_WIDTH, found);
return node_clone_update_branch(node, bitpos, new_sub_node);
} else if (node->element_map & bitpos) {
const CHAMP_KEY_T current_key = CHAMP_NODE_ELEMENT_AT(node, bitpos).key;
if (equals(current_key, key)) {
*found = 1;
return node_clone_update_element(node, bitpos, value);
} else {
const CHAMP_VALUE_T current_value = CHAMP_NODE_ELEMENT_AT(node, bitpos).val;
struct node *sub_node = node_merge(
hashfn(current_key),
current_key,
current_value,
hashfn(key),
key,
value,
shift + HASH_PARTITION_WIDTH
);
return node_clone_pushdown(node, bitpos, sub_node);
}
} else {
return node_clone_insert_element(node, bitpos, key, value);
}
}
static struct node *node_clone_remove_element(const struct node *node, uint32_t bitpos)
{
DEBUG_PRINT("removing element with bit position 0x%x\n", bitpos);
CHAMP_NODE_ELEMENT_T elements[1u << HASH_PARTITION_WIDTH];
const unsigned index = champ_index(node->element_map, bitpos);
memcpy(elements, CHAMP_NODE_ELEMENTS(node), CHAMP_NODE_ELEMENTS_SIZE(index));
memcpy(
&elements[index],
&CHAMP_NODE_ELEMENTS(node)[index + 1],
CHAMP_NODE_ELEMENTS_SIZE(node->element_arity - (index + 1))
);
return node_new(
node->element_map & ~bitpos, node->branch_map, elements,
node->element_arity - 1, CHAMP_NODE_BRANCHES(node), node->branch_arity);
}
/*
* 'Pullup' is the inverse of pushdown.
* It's the process of 'pulling an entry up' from a branch, inlining it as an element instead.
*/
static struct node *node_clone_pullup(const struct node *node, uint32_t bitpos,
const struct kv element)
{
CHAMP_NODE_BRANCH_T branches[1u << HASH_PARTITION_WIDTH];
CHAMP_NODE_ELEMENT_T elements[1u << HASH_PARTITION_WIDTH];
const unsigned branch_index = champ_index(node->branch_map, bitpos);
const unsigned element_index = champ_index(node->element_map, bitpos);
memcpy(branches, CHAMP_NODE_BRANCHES(node), CHAMP_NODE_BRANCHES_SIZE(branch_index));
memcpy(
&branches[branch_index],
&CHAMP_NODE_BRANCHES(node)[branch_index + 1],
CHAMP_NODE_BRANCHES_SIZE(node->branch_arity - (branch_index + 1))
);
memcpy(elements, CHAMP_NODE_ELEMENTS(node), CHAMP_NODE_ELEMENTS_SIZE(element_index));
elements[element_index] = element;
memcpy(
&elements[element_index + 1],
&CHAMP_NODE_ELEMENTS(node)[element_index],
CHAMP_NODE_ELEMENTS_SIZE(node->element_arity - element_index)
);
return node_new(
node->element_map | bitpos,
node->branch_map & ~bitpos, elements, node->element_arity + 1, branches, node->branch_arity - 1);
}
static struct collision_node *collision_node_clone_remove_element(const struct collision_node *node,
unsigned index)
{
CHAMP_NODE_ELEMENT_T elements[node->element_arity - 1];
memcpy(elements, node->content, CHAMP_NODE_ELEMENTS_SIZE(index));
memcpy(elements, &node->content[index + 1], CHAMP_NODE_ELEMENTS_SIZE(node->element_arity - (index + 1)));
return collision_node_new(elements, node->element_arity - 1);
}
/**
* If only one element remains, the returned node will be passed up the tree - to where knowledge of hash collision
* nodes is inappropriate. In that case, this will return a normal <code>struct node *</code> instead.
*
* Consider the only(!) place where this is called: at the start of node_del, if the hash is exhausted. The returned
* value is then immediately returned to the previous call of node_del, where it is evaluated as new_sub_node of
* type struct node, and its members branch_arity and element_arity are evaluated. this requires us to have those
* members be at the exact same place in both struct node and struct collision_node.
*
* @return
*/
static struct collision_node *collision_node_del(const struct collision_node *node,
CHAMP_EQUALSFN_T(equals), const CHAMP_KEY_T key,
int *modified)
{
for (unsigned i = 0; i < node->element_arity; ++i) {
struct kv kv = node->content[i];
if (equals(kv.key, key)) {
*modified = 1;
if (node->element_arity == 2) {
CHAMP_NODE_ELEMENT_T elements[1] = {node->content[i ? 0 : 1]};
return (struct collision_node *)node_new(0, 0, elements, 1, NULL, 0);
} else {
return collision_node_clone_remove_element(node, i);
}
}
}
return NULL;
}
static struct node *node_del(const struct node *node, CHAMP_EQUALSFN_T(equals),
const CHAMP_KEY_T key, uint32_t hash, unsigned shift, int *modified)
{
if (shift >= HASH_TOTAL_WIDTH)
return (struct node *)collision_node_del((const struct collision_node *)node, equals, key, modified);
const uint32_t bitpos = 1u << champ_mask(hash, shift);
if (node->element_map & bitpos) {
if (equals(CHAMP_NODE_ELEMENT_AT(node, bitpos).key, key)) {
*modified = 1;
if (node->element_arity + node->branch_arity == 1) // only possible for the root node
return (struct node *)&empty_node;
else
return node_clone_remove_element(node, bitpos);
} else {
return NULL; // returning from node_del with *modified == 0 means abort immediately
}
} else if (node->branch_map & bitpos) {
struct node *sub_node = CHAMP_NODE_BRANCH_AT(node, bitpos);
struct node *new_sub_node = node_del(sub_node, equals, key, hash,
shift + HASH_PARTITION_WIDTH, modified);
if (!*modified)
return NULL; // returning from node_del with *modified == 0 means abort immediately
if (node->branch_arity + node->element_arity == 1) { // node is a 'passthrough'
if (new_sub_node->branch_arity * 2 + new_sub_node->element_arity == 1) { // new_sub_node is non-canonical, propagate for inlining
new_sub_node->element_map = bitpos;
return new_sub_node;
} else { // canonical, bubble modified trie to the top
return node_clone_update_branch(node, bitpos, new_sub_node);
}
} else if (new_sub_node->branch_arity * 2 + new_sub_node->element_arity == 1) { // new_sub_node is non-canonical
const struct kv remaining_element = CHAMP_NODE_ELEMENTS(new_sub_node)[0];
node_destroy(new_sub_node);
return node_clone_pullup(node, bitpos, remaining_element);
} else { // both node and new_sub_node are canonical
return node_clone_update_branch(node, bitpos, new_sub_node);
}
} else {
return NULL;
}
}
static struct collision_node *collision_node_assoc(const struct collision_node *node,
CHAMP_EQUALSFN_T(equals),
const CHAMP_KEY_T key, CHAMP_ASSOCFN_T(fn),
const void *user_data,
int *found)
{
CHAMP_VALUE_T new_value;
for (unsigned i = 0; i < node->element_arity; ++i) {
struct kv kv = node->content[i];
if (equals(kv.key, key)) {
*found = 1;
CHAMP_VALUE_T old_value = kv.val;
new_value = fn(key, old_value, (void *)user_data);
return collision_node_clone_update_element(node, i, new_value);
}
}
new_value = fn((CHAMP_KEY_T)0, (CHAMP_VALUE_T)0, (void *)user_data);
return collision_node_clone_insert_element(node, key, new_value);
}
static struct node *node_assoc(const struct node *node, CHAMP_HASHFN_T(hashfn), CHAMP_EQUALSFN_T(equals),
const CHAMP_KEY_T key, CHAMP_ASSOCFN_T(fn), const void *user_data, uint32_t hash,
unsigned shift, int *found)
{
if (shift >= HASH_TOTAL_WIDTH)
return (struct node *)collision_node_assoc((const struct collision_node *)node, equals, key, fn, user_data, found);
const uint32_t bitpos = 1u << champ_mask(hash, shift);
if (node->branch_map & bitpos) {
const struct node *sub_node = CHAMP_NODE_BRANCH_AT(node, bitpos);
struct node *new_sub_node = node_assoc(sub_node, hashfn, equals, key, fn, user_data, hash,
shift + HASH_PARTITION_WIDTH, found);
return node_clone_update_branch(node, bitpos, new_sub_node);
} else if (node->element_map & bitpos) {
const CHAMP_KEY_T current_key = CHAMP_NODE_ELEMENT_AT(node, bitpos).key;
if (equals(current_key, key)) {
*found = 1;
const CHAMP_VALUE_T old_value = CHAMP_NODE_ELEMENT_AT(node, bitpos).val;
CHAMP_VALUE_T new_value = fn(key, old_value, (void *)user_data);
return node_clone_update_element(node, bitpos, new_value);
} else {
const CHAMP_VALUE_T current_value = CHAMP_NODE_ELEMENT_AT(node, bitpos).val;
const CHAMP_VALUE_T new_value = fn((CHAMP_KEY_T)0, (CHAMP_VALUE_T)0, (void *)user_data);
struct node *sub_node = node_merge(
hashfn(current_key),
current_key,
current_value,
hash,
key,
new_value,
shift + HASH_PARTITION_WIDTH
);
return node_clone_pushdown(node, bitpos, sub_node);
}
} else {
const CHAMP_VALUE_T value = fn((CHAMP_KEY_T)0, (CHAMP_VALUE_T)0, (void *)user_data);
return node_clone_insert_element(node, bitpos, key, value);
}
}
static int collision_node_equals(const struct collision_node *left, const struct collision_node *right,
CHAMP_EQUALSFN_T(key_equals), CHAMP_VALUE_EQUALSFN_T(value_equals))
{
if (left == right)
return 1;
if (left->element_arity != right->element_arity)
return 0;
for (unsigned left_i = 0; left_i < left->element_arity; ++left_i) {
struct kv left_element = CHAMP_NODE_ELEMENTS(left)[left_i];
for (unsigned right_i = 0; right_i < right->element_arity; ++right_i) {
struct kv right_element = CHAMP_NODE_ELEMENTS(right)[right_i];
if (key_equals(left_element.key, right_element.key) && value_equals(left_element.val, right_element.val))
goto found_matching_element;
}
return 0; // compared left_element to all elements in right node, no match.
found_matching_element:
continue;
}
return 1; // compared all elements in left node, never had an element without match.
}
static int node_equals(const struct node *left, const struct node *right, CHAMP_EQUALSFN_T(key_equals),
CHAMP_VALUE_EQUALSFN_T(value_equals), unsigned shift)
{
if (shift >= HASH_TOTAL_WIDTH)
return collision_node_equals((struct collision_node *)left, (struct collision_node *)right, key_equals, value_equals);
if (left == right)
return 1;
if (left->element_map != right->element_map)
return 0;
if (left->branch_map != right->branch_map)
return 0;
for (unsigned i = 0; i < left->element_arity; ++i) {
struct kv left_element = CHAMP_NODE_ELEMENTS(left)[i];
struct kv right_element = CHAMP_NODE_ELEMENTS(right)[i];
if (!key_equals(left_element.key, right_element.key) || !value_equals(left_element.val, right_element.val))
return 0;
}
for (unsigned i = 0; i < left->branch_arity; ++i) {
struct node *left_branch = CHAMP_NODE_BRANCHES(left)[i];
struct node *right_branch = CHAMP_NODE_BRANCHES(right)[i];
if (!node_equals(left_branch, right_branch, key_equals, value_equals, shift + HASH_PARTITION_WIDTH))
return 0;
}
return 1;
}
static struct champ *champ_from(struct node *root, unsigned length,
CHAMP_HASHFN_T(hash), CHAMP_EQUALSFN_T(equals))
{
struct champ *result = malloc(sizeof(*result));
result->ref_count = 0;
result->root = root;
result->length = length;
result->hash = hash;
result->equals = equals;
return result;
}
void champ_destroy(struct champ **champ)
{
DEBUG_PRINT("destroying champ@%p\n", (void *)*champ);
champ_node_release((*champ)->root);
free(*champ);
*champ = NULL;
}
struct champ *champ_new(CHAMP_HASHFN_T(hash), CHAMP_EQUALSFN_T(equals))
{
return champ_from((struct node *)&empty_node, 0, hash, equals);
}
struct champ *champ_acquire(const struct champ *champ)
{
atomic_fetch_add((uint32_t *)&champ->ref_count, 1u);
return (struct champ *)champ;
}
void champ_release(struct champ **champ)
{
if (atomic_fetch_sub((uint32_t *)&((*champ)->ref_count), 1u) == 1u)
champ_destroy((struct champ **)champ);
*champ = NULL;
}
struct champ *champ_of(CHAMP_HASHFN_T(hash), CHAMP_EQUALSFN_T(equals),
CHAMP_KEY_T*keys, CHAMP_VALUE_T*values, size_t length)
{
struct champ *result = champ_new(hash, equals);
while (length--) {
struct champ *tmp = champ_set(result, keys[length], values[length], NULL);
champ_destroy(&result);
result = tmp;
}
return result;
}
unsigned champ_length(const struct champ *champ)
{
return champ->length;
}
struct champ *champ_set(const struct champ *champ,
const CHAMP_KEY_T key, const CHAMP_VALUE_T value, int *replaced)
{
const uint32_t hash = champ->hash(key);
int found = 0;
int *found_p = replaced ? replaced : &found;
*found_p = 0;
struct node *new_root = champ_node_acquire(node_update(champ->root, champ->hash, champ->equals, key, value, hash, 0, found_p));
return champ_from(new_root, champ->length + (*found_p ? 0 : 1), champ->hash, champ->equals);
}
CHAMP_VALUE_T champ_get(const struct champ *champ, const CHAMP_KEY_T key, int *found)
{
uint32_t hash = champ->hash(key);
int tmp = 0;
return node_get(champ->root, champ->equals, key, hash, 0, found ? found : &tmp);
}
struct champ *champ_del(const struct champ *champ, const CHAMP_KEY_T key, int *modified)
{
const uint32_t hash = champ->hash(key);
int found = 0;
int *found_p = modified ? modified : &found;
*found_p = 0;
struct node *new_root = node_del(champ->root, champ->equals, key, hash, 0, found_p);
if (!*found_p)
return (struct champ *)champ;
return champ_from(champ_node_acquire(new_root), champ->length - 1, champ->hash, champ->equals);
}
struct champ *champ_assoc(const struct champ *champ, const CHAMP_KEY_T key, CHAMP_ASSOCFN_T(fn), const void *user_data)
{
const uint32_t hash = champ->hash(key);
int found = 0;
struct node *new_root = champ_node_acquire(node_assoc(champ->root, champ->hash, champ->equals, key, fn, user_data, hash, 0, &found));
return champ_from(new_root, champ->length + (found ? 0 : 1), champ->hash, champ->equals);
}
int champ_equals(const struct champ *left, const struct champ *right, CHAMP_VALUE_EQUALSFN_T(value_equals))
{
if (left == right)
return 1;
else if (champ_length(left) != champ_length(right))
return 0;
else
return node_equals(left->root, right->root, left->equals, value_equals, 0);
}
static const char *indent(unsigned level)
{
const char *spaces = " ";
return spaces + 4 * (20 - level);
}
#define iprintf(level, fmt, ...) printf("%s" fmt, indent(level), ##__VA_ARGS__)
static char *format_binary(uint32_t value, char *buffer)
{
for (char *pos = buffer + 31; pos >= buffer; --pos) {
if (value & 1u) *pos = '1';
else *pos = '0';
value = value >> 1u;
}
return buffer;
}
static void champ_node_repr(const struct node *node, const char *kp, const char *vp, unsigned shift, unsigned i_level)
{
if (shift >= HASH_TOTAL_WIDTH) {
iprintf(i_level, "\"collision node (omitted)\"");
return;
}
char map_buf[33];
printf("{\n");
iprintf(i_level, "\"element_map\": 0b%.32s,\n", format_binary(node->element_map, map_buf));
iprintf(i_level, "\"element_arity\": %u,\n", node->element_arity);
iprintf(i_level, "\"branch_map\": 0b%.32s,\n", format_binary(node->branch_map, map_buf));
iprintf(i_level, "\"branch_arity\": %u,\n", node->branch_arity);
iprintf(i_level, "\"elements\": {\n");
for (unsigned i = 0; i < node->element_arity; ++i) {
CHAMP_NODE_ELEMENT_T el = CHAMP_NODE_ELEMENTS(node)[i];
iprintf(i_level + 1, "\"");
printf(kp, el.key);
printf("\": ");
printf(vp, el.val);
printf(",\n");
}
iprintf(i_level, "},\n");
iprintf(i_level, "\"nodes\": [\n");
for (unsigned i = 0; i < node->branch_arity; ++i) {
CHAMP_NODE_BRANCH_T n = CHAMP_NODE_BRANCHES(node)[i];
iprintf(i_level + 1, "");
champ_node_repr(n, kp, vp, shift + HASH_PARTITION_WIDTH, i_level + 2);
printf(",\n");
}
iprintf(i_level, "],\n");
iprintf(i_level - 1, "}");
}
void champ_repr(const struct champ *champ, const char *key_prefix, const char *value_prefix)
{
printf("{\n");
iprintf(1, "\"length\": %d,\n", champ->length);
iprintf(1, "\"root\": ");
champ_node_repr(champ->root, key_prefix, value_prefix, 0, 2);
printf("\n}\n");
}
void champ_iter_init(struct champ_iter *iterator, const struct champ *champ)
{
iterator->stack_level = 0;
iterator->element_cursor = 0;
iterator->element_arity = champ->root->element_arity;
iterator->branch_cursor_stack[0] = 0;
iterator->branch_arity_stack[0] = champ->root->branch_arity;
iterator->node_stack[0] = champ->root;
}
static void iter_push(struct champ_iter *iterator, const struct node *node)
{
iterator->stack_level += 1;
iterator->element_cursor = 0;
iterator->element_arity = node->element_arity;
iterator->branch_cursor_stack[iterator->stack_level] = 0;
iterator->branch_arity_stack[iterator->stack_level] = node->branch_arity;
iterator->node_stack[iterator->stack_level] = node;
}
static void iter_pop(struct champ_iter *iterator)
{
iterator->stack_level -= 1;
}
int champ_iter_next(struct champ_iter *iterator, CHAMP_KEY_T *key, CHAMP_VALUE_T *value)
{
if (iterator->stack_level == -1)
return 0;
const struct node *current_node = iterator->node_stack[iterator->stack_level];
unsigned *branch_cursor = iterator->branch_cursor_stack + iterator->stack_level;
if (*branch_cursor == 0 && iterator->element_cursor < current_node->element_arity) { // todo: write test for this
*key = CHAMP_NODE_ELEMENTS(current_node)[iterator->element_cursor].key;
*value = CHAMP_NODE_ELEMENTS(current_node)[iterator->element_cursor].val;
++iterator->element_cursor;
return 1;
} else {
if (*branch_cursor < iterator->branch_arity_stack[iterator->stack_level]) {
iter_push(iterator, CHAMP_NODE_BRANCHES(current_node)[*branch_cursor]);
++*branch_cursor;
return champ_iter_next(iterator, key, value);
} else {
iter_pop(iterator);
return champ_iter_next(iterator, key, value);
}
}
}
</code></pre>
<h2>Using it as a "<code>champ<string,int></code>"</h2>
<p>This is an example of how to use this map with a scalar value type.</p>
<p>Compile with <code>gcc -DDEBUG -O3 -o main main.c str_int_map.c -std=c11</code></p>
<h3>champ_str_int.h</h3>
<pre class="lang-c prettyprint-override"><code>#define CHAMP_KEY_T char*
#define CHAMP_VALUE_T int
#include "champ.h"
</code></pre>
<h3>champ_str_int.c</h3>
<pre class="lang-c prettyprint-override"><code>#include "str_int_map.h"
#include "champ.c"
</code></pre>
<h3>main.c</h3>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <string.h>
#include "str_int_map.h"
#include "champ_fns.h"
int equals_str(const char *l, const char *r) {
return !strcmp(l, r);
}
uint32_t hash_str(const char *str) {
uint32_t hash = 0;
for (unsigned i = 0; i < strlen(str); i++) {
hash = 31 * hash + (uint32_t)str[i];
}
return hash;
}
int main()
{
struct champ *map = champ_acquire(champ_new(hash_str, equals_str));
// note: key is char* and value is int instead of void*, no cast required
map = champ_set(map, "answer", 42, NULL);
printf("answer == %d\n", champ_get(map, "answer", NULL));
}
</code></pre>
|
[] |
[
{
"body": "<p>Without digging into it too deeply, this seems well put-together and it's clear that you know what you're doing. The only minor thing I picked up on first read is that this:</p>\n\n<pre><code>int *found\n</code></pre>\n\n<p>should be using <code><stdbool.h></code> instead of an <code>int</code>; mostly to help your users understand what's happening. The same goes for the return value of <code>equals_str</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T14:00:29.720",
"Id": "473494",
"Score": "0",
"body": "Thanks! I was trying pretty hard. And yeah, I was under the impression that `int` is the de-facto `bool` in C and nobody really uses `<stdbool>`, but my teachers just might have been a bit quirky."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T23:58:18.443",
"Id": "241171",
"ParentId": "241140",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T13:44:41.430",
"Id": "241140",
"Score": "2",
"Tags": [
"c",
"multithreading",
"immutability"
],
"Title": "A new CHAMPion - Compressed Hash-Array Mapped Prefix-tree in C"
}
|
241140
|
<p>I have a lambda function that ingests a CSV, reads it as a list of dicts, modifies them (updating the Keys, adding a few values) and submits them to a firehose. Initially I had the following code:</p>
<pre><code>import json
import boto3
import sys
import csv
import io
import logging
s3 = boto3.client('s3', 'us-east-1')
firehoseClient = boto3.client('firehose','us-east-1')
logger=logging.getLogger()
logger.setLevel(logging.INFO)
fieldMapper = {
Dict that maps old column names to new ones
}
def lambda_handler(event, context):
print(f"Received Event: {event}")
bucket = event['Records'][0]['s3']['bucket']['name']
key = event['Records'][0]['s3']['object']['key']
stream = 'stream'
logger.info(f'Reading {key} from {bucket}')
obj = s3.get_object(Bucket = bucket, Key = key)
f = io.StringIO(obj['Body'].read().decode('utf-8'))
reader = csv.DictReader(f)
list_of_json = [dict(device) for device in reader]
f.close()
logger.info(f'{key} successfully parsed')
reformDictList = []
logger.info('Reformatting dicts')
for i in list_of_json:
newDict = {}
for k, v in i.items():
if k in fieldMapper.keys():
newDict[fieldMapper[k]] = v
newDict['ZIPCODE'] = f"{i['ZIP']}-{i['ZIP4']}"
newDict['CSV'] = f"{i['CITY']}, {i['STATE']} {newDict['ZIPCODE']}"
newDict['mail_filename'] = key
newDict['printer_name'] = 'Printer'
reformDictList.append(newDict)
logger.info('Dicts reformatted successfully')
batch = []
batch_ct = 1
for i in jlist1:
i['mail_filename'] = key.split('/')[1]
text = json.dumps(i)
if len(text) > 1:
text_bytes = bytes(text,'utf-8')
dict_bytes = {"Data":text}
batch.append(dict_bytes)
if len(batch) == 500:
print('Sending batch at line number ' + str(500*batch_ct))
# try:
result = firehoseClient.put_record_batch(DeliveryStreamName = stream, Records = batch)
# except Exception as x:
# logging.error(x)
num_failures = result['FailedPutCount']
try:
if num_failures:
logging.info(f'resending {num_failures} failed records')
rec_index = 0
for record in result['RequestResponses']:
if 'ErrorCode' in record:
firehoseClient.put_record(DeliveryStreamName=stream,Record=batch[rec_index])
num_failures -= 1
if not num_failures:
break
rec_index += 1
except Exception as y:
logging.error(y)
batch_ct += 1
batch.clear()
if batch:
print('Sending leftover records')
try:
result = firehoseClient.put_record_batch(DeliveryStreamName = stream, Records = batch)
except Exception as x:
logging.error(x)
num_failures = result['FailedPutCount']
try:
if num_failures:
logging.info(f'resending {num_failures} failed records')
rec_index = 0
for record in result['RequestResponses']:
if 'ErrorCode' in record:
firehoseClient.put_record(DeliveryStreamName=stream,Record=batch[rec_index])
num_failures -= 1
if not num_failures:
break
rec_index += 1
except Exception as y:
logging.error(y)
</code></pre>
<p>But it consumed a max memory of 856mb. So I decided to update the code to modify the original JSON in place to avoid creating a new list:</p>
<pre><code>for i in list_of_json:
i['ZIP'] = f"{i['ZIP']}-{i['ZIP4']}"
for k in list(i.keys()):
if k in fieldMapper.keys():
i[fieldMapper[k]] = i.pop(k)
else:
del i[k]
i['csv'] = f"{i['CITY']}, {i['STATE']} {i['ZIPCODE']}"
i['mail_filename'] = key
i['printer_name'] = 'Printer'
</code></pre>
<p>Yet to my surprise this made no difference in memory. Why might this be? The size of the CSV is 51.8mb.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T00:09:28.373",
"Id": "473231",
"Score": "0",
"body": "`Dict that maps old column names to new ones` looks like a misplaced comment. As-is, this code will not run."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T05:12:43.893",
"Id": "473346",
"Score": "0",
"body": "(What *do* you expect to change while sticking to a comprehension `for <something> in reader`?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T10:56:48.973",
"Id": "473362",
"Score": "0",
"body": "@Reinderien Note that that isn't really off-topic. It's clear it's pseudocode there, and the meat of the question is all real actual Python."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-28T14:55:15.193",
"Id": "473646",
"Score": "0",
"body": "@Reinderien it's not out of place, it's just a dictionary that contains client specific/sensitive information"
}
] |
[
{
"body": "<p>New list here just contains links to list_of_json objects, it shouldn't consume much memory, so getting rid of it won't save much either.\nVariables that reference to all objects (here dicts) are kept until the function is active. I'd suggest split the data flow into chain of functions to reduce temp objects reference count to 0 and make garbage collector get rid of them. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T00:08:01.183",
"Id": "473230",
"Score": "0",
"body": "_Variables that reference to all objects (here dicts) are kept until the function is active_ - First, you probably meant _until the function is not active_. And even so: this is incorrect. The Python garbage collector does not necessarily run at the end of every function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T00:12:28.430",
"Id": "473232",
"Score": "1",
"body": "Maybe you meant that the references themselves go away when the function is done, which is true; but that won't immediately help memory consumption."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T17:20:57.810",
"Id": "241151",
"ParentId": "241141",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T14:01:38.683",
"Id": "241141",
"Score": "3",
"Tags": [
"python",
"amazon-web-services"
],
"Title": "Python AWS Lambda, why did updating in place instead of creating and appending to a new list not decrease memory usage?"
}
|
241141
|
<p>I have made a clone of windows task manger using QT and c++. When I started out this project I had much less knowledge of c++ then I do know so the style of some parts of the code are not always consistent with others. the full source code can be found here <a href="https://github.com/qwertybomb/Task-Manager-Clone" rel="nofollow noreferrer">https://github.com/qwertybomb/Task-Manager-Clone</a>. However My main concern with the code is that it is not efficient, which is necessary since the program does no want to skew the results of monitoring and that it is not able to measure individual process cpu usage.
here is the code
mainwindow.h</p>
<pre><code>#define MAINWINDOW_H
#include <QMainWindow>
#include <QWidget>
#include <QEvent>
#include "qcustomplot.h"
#include <QElapsedTimer>
#include <chrono>
#include <thread>
#include <QString>
#include "Processitem.h"
#include <cstddef>
#define _WIN32_DCOM
#include<windows.h>
#include<memory>
#define gb (1024.0*1024.0*1024.0)
#define mb (1024.0*1024.0)
#define kb (1024.0)
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
enum Computer_device{
Memory,Cpu
};
private:
void draw(long double , Computer_device );
void processDraw(long double , Computer_device );
void add_sample(QVector<double>&,double item);
void get_mem(std::byte* = nullptr);
void getProcess_mem(std::byte* = nullptr);
void get_cpuClock(std::byte* = nullptr);
void getProcess_cpuClock(std::byte* = nullptr);
double get_mem_val();
void reset_sampleRate(Computer_device type);
void do_test();
void processResource();
private:
QVector<Process> device_processes;
void getProcessInfo(DWORD processID,Process& old);
auto updateProcessInfo();
QTreeWidget* processInfoTree;
void updateProcessInfoTree();
QList<QTreeWidgetItem*> selectedItems;
bool selectedItemsInUse = false;
private:
QComboBox* process_ComboBox;
Process currentProcess = Process("",0,0,0,QIcon(QPixmap(5,5)));
std::map<QString,double> processMax_MemoryUsage;
void updateProcessComboBox();
private:
enum SortMode{
NameSortAZ, MemorySortAZ, CpuSortAZ, ProcessIDSortAZ, NameSortZA,MemorySortZA, CpuSortZA, ProcessIDSortZA,NoSort
};
SortMode currentSortMode= SortMode::NoSort;
private:
QTimer* m_timer;
double time_value = 0.0;
double compare_sample = 0.0;
unsigned char stayOnTop = 0;
private:
QVector<QVector<double>> device_samples;
QVector<QVector<double>> process_samples;
std::thread backround;
int clocks = 0;
private slots:
void Update();
void on_comboBox_currentIndexChanged(const QString &arg1);
void on_actionStay_on_top_triggered();
void on_actionStay_on_top_toggled(bool arg1);
void on_pushButton_clicked();
void on_actionSave_as_triggered();
void on_pushButton_2_clicked();
void tableHeader_clicked(int column);
private:
QLabel* resourceUsageLabel;
std::byte currentResourceUsage;
private:
Ui::MainWindow *ui;
QCustomPlot* customPlot;
QCustomPlot* processCustomPlot;
int sample_time = 30000;
int mem_sampleRate = 10000;
int cpu_sampleRate = 100;
int cpu_SamplingRate = 100;
//QVector<double> samples = QVector<double>(sampleRate); // initialize with entries 0..100
QVector<double> x = QVector<double>(mem_sampleRate);
QVector<double> multi_sample= QVector<double>();
MEMORYSTATUSEX statex{};
Computer_device current_device;
unsigned long long total_ram = 0;
long long total_cpuClock = 4*gb;
//image stuff
private:
QImage m_plot;
bool imageIsSafe =false;
bool capture_plot = 0;
};
#endif // MAINWINDOW_H
</code></pre>
<p>mainwindow.cpp</p>
<pre><code>#include "ui_mainwindow.h"
#include <cstdlib>
#include <iostream>
#include <thread>
#include "TCHAR.h"
#include "pdh.h"
#include <psapi.h>
#include <QFileDialog>
#define _WIN32_DCOM
#include <QtAlgorithms>
#include <QtMath>
#include <QtWin>
#include <Wbemidl.h>
#include <comdef.h>
#include <tlhelp32.h>
#if defined(_MSC_VER) && !defined(__INTEL_COMPILER)
#pragma comment(lib, "wbemuuid.lib")
#endif
static float CalculateCPULoad(unsigned long long idleTicks,
unsigned long long totalTicks) {
static unsigned long long _previousTotalTicks = 0;
static unsigned long long _previousIdleTicks = 0;
unsigned long long totalTicksSinceLastTime = totalTicks - _previousTotalTicks;
unsigned long long idleTicksSinceLastTime = idleTicks - _previousIdleTicks;
float ret =
1.0F - ((totalTicksSinceLastTime > 0)
? ((float)idleTicksSinceLastTime) / totalTicksSinceLastTime
: 0);
_previousTotalTicks = totalTicks;
_previousIdleTicks = idleTicks;
return ret;
}
static unsigned long long FileTimeToInt64(const FILETIME &ft) {
return (((unsigned long long)(ft.dwHighDateTime)) << 32) |
((unsigned long long)ft.dwLowDateTime);
}
// Returns 1.0f for "CPU fully pinned", 0.0f for "CPU idle", or somewhere in
// between You'll need to call this at regular intervals, since it measures the
// load between the previous call and the current one. Returns -1.0 on error.
float GetCPULoad() {
FILETIME idleTime;
FILETIME kernelTime;
FILETIME userTime;
return GetSystemTimes(&idleTime, &kernelTime, &userTime)
? CalculateCPULoad(FileTimeToInt64(idleTime),
FileTimeToInt64(kernelTime) +
FileTimeToInt64(userTime))
: -1.0F;
}
DWORD getParentPID(DWORD pid) {
HANDLE h = nullptr;
PROCESSENTRY32 pe{0,0,0,0,0,0,0,0,0,{0,0}};
DWORD ppid = 0;
pe.dwSize = sizeof(PROCESSENTRY32);
h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (Process32First(h, &pe)) {
do {
if (pe.th32ProcessID == pid) {
ppid = pe.th32ParentProcessID;
break;
}
} while (Process32Next(h, &pe));
}
CloseHandle(h);
return (ppid);
}
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow) {
ui->setupUi(this);
customPlot = ui->tab;
processCustomPlot = ui->tab_3;
ui->tabWidget->setTabText(0, "Performance");
ui->tabWidget->setTabText(1, "Processes");
ui->tabWidget->setTabText(2, "Process performance");
resourceUsageLabel = ui->label_2;
customPlot->addGraph();
processCustomPlot->addGraph();
processInfoTree = ui->treeWidget;
process_ComboBox = ui->comboBox_2;
process_ComboBox->setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLengthWithIcon);
// set selection mode
processInfoTree->setSelectionMode(
QAbstractItemView::SelectionMode::ExtendedSelection);
// setup headers
processInfoTree->setColumnCount(4);
QList<QString> headers{QString("Name"), QString("Memory"), QString("Cpu"),
QString("ProcessId")};
QTreeWidgetItem *headerItem =
new QTreeWidgetItem((QTreeWidgetItem *)nullptr, headers);
headerItem->setSelected(true);
processInfoTree->setHeaderItem(headerItem);
// keep window on top
setWindowFlags(this->windowFlags() | Qt::X11BypassWindowManagerHint |
Qt::WindowStaysOnTopHint);
/*connect slot functions*/
connect(ui->treeWidget->header(), SIGNAL(sectionDoubleClicked(int)), this,
SLOT(tableHeader_clicked(int)));
// update it the first frame so there is not a small time where it is blank
updateProcessInfoTree();
// get total memory
statex.dwLength = sizeof(statex);
GlobalMemoryStatusEx(&statex);
total_ram = statex.ullTotalPhys;
// fill samples
double current_memValue =
(((double)total_ram - (double)statex.ullAvailPhys) / gb);
// set enum
current_device = Memory;
backround = std::thread();
// set up device sample vectors
device_samples.push_back(QVector<double>(mem_sampleRate, current_memValue));
device_samples.push_back(
QVector<double>(cpu_sampleRate, GetCPULoad() * 100.0));
process_samples.push_back(QVector<double>(mem_sampleRate, 0));
process_samples.push_back(
QVector<double>(cpu_sampleRate, GetCPULoad() * 100.0));
// set up vars
// set up timer
m_timer = new QTimer(this);
QTimer::singleShot(1, this, SLOT(Update()));
m_timer->start(1);
for (int i = 0; i < mem_sampleRate; ++i) {
x[i] = ((double)i / (mem_sampleRate));
}
}
MainWindow::~MainWindow() { delete ui; }
void MainWindow::draw(long double top, Computer_device type) {
QVector<double> samples = device_samples[type];
// create graph and assign data to it:
QColor a;
a.setRgb(160, 3, 170, 70);
customPlot->graph()->setBrush(a);
customPlot->graph(0)->setData(x, samples);
// give the axes some labels:
customPlot->yAxis->setLabel("Total Use");
customPlot->xAxis->setTicks(false);
// set axes ranges, so we see all data:
customPlot->xAxis->setRange(0.0, 1.0);
customPlot->yAxis->setRange(0.0, top);
customPlot->replot();
if (capture_plot) {
m_plot = customPlot->toPixmap(this->width(), this->height()).toImage();
capture_plot = false;
}
multi_sample.clear();
}
void MainWindow::processDraw(long double top, Computer_device type)
{
QVector<double> samples = process_samples[type];
// create graph and assign data to it:
QColor a;
a.setRgb(160, 3, 170, 70);
processCustomPlot->graph()->setBrush(a);
processCustomPlot->graph(0)->setData(x, samples);
// give the axes some labels:
processCustomPlot->yAxis->setLabel("Total Use");
processCustomPlot->xAxis->setTicks(false);
// set axes ranges, so we see all data:
processCustomPlot->xAxis->setRange(0.0, 1.0);
processCustomPlot->yAxis->setRange(0.0, top);
processCustomPlot->replot();
if (capture_plot) {
m_plot = processCustomPlot->toPixmap(this->width(), this->height()).toImage();
capture_plot = false;
}
}
void MainWindow::add_sample(QVector<double> &vec, double item) {
item = abs(item);
vec.pop_back();
vec.insert(0, item);
}
/*
* sample = sin(time/2.0)*0.5+0.5;
* sample *= total_ram/gb;
* double time = (double)QTime::currentTime().msecsSinceStartOfDay()/1000.0;
*/
// get memory
void MainWindow::get_mem(std::byte *currentValue) {
double sample = 0;
GlobalMemoryStatusEx(&statex);
sample = double(total_ram - statex.ullAvailPhys) / gb;
if (currentValue != nullptr) {
*currentValue = static_cast<std::byte>(
round((total_ram - statex.ullAvailPhys) / double(total_ram) * 100.0));
}
add_sample(device_samples[0], sample);
}
void MainWindow::getProcess_mem(std::byte *currentValue)
{
double sample = 0;
if(device_processes.empty()){return;}
sample = double(currentProcess.memoryUsage());
if (currentValue != nullptr) {
*currentValue = static_cast<std::byte>(
round((total_ram - statex.ullAvailPhys) / double(processMax_MemoryUsage[currentProcess.name()]) * 100.0));
}
add_sample(process_samples[0], sample);
}
void MainWindow::getProcessInfo(DWORD processID, Process &old) {
TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
// Get a handle to the process.
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processID);
_PROCESS_MEMORY_COUNTERS_EX pmc{};
old.SetId(processID);
// Print the process identifier.
// Get the process name.
if (nullptr != hProcess) {
HMODULE hMod;
DWORD cbNeeded;
if (EnumProcessModules(hProcess, &hMod, sizeof(hMod), &cbNeeded)) {
GetModuleBaseName(hProcess, hMod, szProcessName,
sizeof(szProcessName) / sizeof(TCHAR));
}
if (GetProcessMemoryInfo(hProcess, (PROCESS_MEMORY_COUNTERS *)&pmc,
sizeof(pmc))) {
old.SetmemoryUsage(pmc.PrivateUsage / (mb));
};
auto temp = QString::fromUtf16((const ushort *)szProcessName);
old.Setname(temp);
if(processMax_MemoryUsage.find(temp)!=processMax_MemoryUsage.end())
{
if(old.memoryUsage() > processMax_MemoryUsage[temp])
processMax_MemoryUsage[temp]=old.memoryUsage()*1.25;
}
else
{
processMax_MemoryUsage[temp] = old.memoryUsage();
}
/// old.UpdatecpuUsage();
if (GetModuleFileNameEx(hProcess, hMod, szProcessName, MAX_PATH)) {
HICON icon = ExtractIcon((HINSTANCE)hProcess, szProcessName, 0);
if (icon) {
old.SetIcon(QIcon(QtWin::fromHICON(icon)));
} else {
icon = LoadIcon(nullptr, IDI_APPLICATION);
old.SetIcon(QIcon(QtWin::fromHICON(icon)));
}
DestroyIcon(icon);
}
} else {
old.Setname("<NULL>");
}
// Release the handle to the process.
CloseHandle(hProcess);
}
auto MainWindow::updateProcessInfo() {
DWORD aProcesses[1024]; DWORD cbNeeded; DWORD cProcesses;
unsigned int i;
if (!EnumProcesses(aProcesses, sizeof(aProcesses), &cbNeeded)) {
qWarning() << "Error could not enumerate processes\n";
}
// Calculate how many process identifiers were returned.
cProcesses = cbNeeded / sizeof(DWORD);
auto &processes = device_processes;
std::map<int, Process> pmap;
if (processes.empty()) {
processes.resize(cProcesses);
processes.fill(Process(), processes.size());
} else {
processes.resize(cProcesses);
}
int k = 0;
for (i = 0; i < cProcesses; i++) {
getProcessInfo(aProcesses[i], processes[k]);
if (processes[k].memoryUsage() != 0 && processes[k].name() != "<unknown>" &&
processes[k].name() != "<NULL>") {
k++;
}
}
processes.resize(k);
for (const auto& process : processes) {
pmap[process.Id()] = process;
}
QVector<Process> newProcesses;
// a way to avoid using push_back()
i = 0;
for (const auto& j : pmap) {
if (j.second.child()!=1) {
newProcesses.append(j.second);
}
i++;
}
device_processes = newProcesses;
}
void MainWindow::updateProcessInfoTree() {
// only update every 500 milliseconds and if the current tab is the tables
if (clocks % 500 == 0 && ui->tabWidget->currentIndex() != 0) {
updateProcessInfo();
int len = device_processes.size();
int len2 = processInfoTree->topLevelItemCount();
int len3 = len - len2;
/*add or remove items based off new length*/
if (len3 > 0) {
for (int i = 0; i < len3; i++) {
new QTreeWidgetItem(
processInfoTree, QStringList{" ", " ", " ", " "});
}
} else if (len3 < 0) {
for (int i = len2 - 1; i > (len2 - 1) - abs(len3); --i) {
delete processInfoTree->takeTopLevelItem(i);
}
}
auto sorted_device_processes = device_processes;
/*Sort table based on current sort mode*/
switch (currentSortMode) {
default:
break;
case SortMode::NameSortAZ:
std::sort(
sorted_device_processes.begin(), sorted_device_processes.end(),
[](Process &a, Process &b) -> bool { return a.name() < b.name(); });
break;
case SortMode::NameSortZA:
std::sort(
sorted_device_processes.begin(), sorted_device_processes.end(),
[](Process &a, Process &b) -> bool { return a.name() > b.name(); });
break;
case CpuSortAZ:
std::sort(sorted_device_processes.begin(), sorted_device_processes.end(),
[](Process &a, Process &b) -> bool {
return a.cpuUsage() < b.cpuUsage();
});
break;
case CpuSortZA:
std::sort(sorted_device_processes.begin(), sorted_device_processes.end(),
[](Process &a, Process &b) -> bool {
return a.cpuUsage() > b.cpuUsage();
});
break;
case MemorySortAZ:
std::sort(sorted_device_processes.begin(), sorted_device_processes.end(),
[](Process &a, Process &b) -> bool {
return a.memoryUsage() < b.memoryUsage();
});
break;
case MemorySortZA:
std::sort(sorted_device_processes.begin(), sorted_device_processes.end(),
[](Process &a, Process &b) -> bool {
return a.memoryUsage() > b.memoryUsage();
});
break;
case ProcessIDSortAZ:
std::sort(sorted_device_processes.begin(), sorted_device_processes.end(),
[](Process &a, Process &b) -> bool { return a.Id() < b.Id(); });
break;
case ProcessIDSortZA:
std::sort(sorted_device_processes.begin(), sorted_device_processes.end(),
[](Process &a, Process &b) -> bool { return a.Id() > b.Id(); });
break;
case NoSort:
break;
}
for (int i = 0; i < len; ++i) {
auto process = sorted_device_processes[i];
QTreeWidgetItem item5;
QStringList currentRow(QString(process.name()));
currentRow.append(QString::number(process.memoryUsage()) + "Mb");
currentRow.append(QString::number(process.cpuUsage()) + "%");
currentRow.append(QString::number(process.Id()));
item5 = QTreeWidgetItem((QTreeWidget *)nullptr, currentRow);
item5.setIcon(0, process.icon());
// update item at index i in the tree
*processInfoTree->topLevelItem(i) = item5;
processInfoTree->topLevelItem(i)->takeChildren();
for (const auto& child : process.children()) {
QStringList currentChildRow(QString(child.name()));
currentChildRow.append(QString::number(child.memoryUsage()) + "Mb");
currentChildRow.append(QString::number(child.cpuUsage()) + "%");
currentChildRow.append(QString::number(child.Id()));
auto *item6 =
new QTreeWidgetItem((QTreeWidget *)nullptr, currentChildRow);
item6->setIcon(0, child.icon());
processInfoTree->topLevelItem(i)->addChild(item6);
}
}
//update process combo box
updateProcessComboBox();
}
}
void MainWindow::updateProcessComboBox()
{
int numberOfProcesses = device_processes.size();
int len = numberOfProcesses;
int len2 = process_ComboBox->count();
int len3 = len - len2;
/*add or remove items based off new length*/
if (len3 > 0) {
for (int i = 0; i < len3; i++) {
process_ComboBox->addItem("");
}
} else if (len3 < 0) {
for (int i = len2 - 1; i > (len2 - 1) - abs(len3); --i) {
process_ComboBox->removeItem(i);
}
}
for(auto i = 0; i < numberOfProcesses; ++i)
{
process_ComboBox->setItemText(i,device_processes[i].name());
}
int currentProcessIndex = process_ComboBox->findText(currentProcess.name());
if(currentProcessIndex^-1)//if it finds the currentProcess
{
process_ComboBox->setCurrentIndex(currentProcessIndex);
}
}
void MainWindow::get_cpuClock(std::byte *currentValue) {
double sample = 0;
if (clocks % cpu_SamplingRate == 0) {
sample = GetCPULoad() * 100.0;
if (clocks % 2 == 0) {
if (currentValue != nullptr) {
*currentValue = static_cast<std::byte>(sample);
}
add_sample(device_samples[1], sample);
}
}
}
void MainWindow::getProcess_cpuClock(std::byte *currentValue)
{
double sample = 0;
if(device_processes.empty()){return;}
if (clocks % cpu_SamplingRate == 0) {
sample = currentProcess.cpuUsage() * 100.0;
if (clocks % 2 == 0) {
if (currentValue != nullptr) {
*currentValue = static_cast<std::byte>(sample);
}
add_sample(process_samples[1], sample);
}
}
}
void MainWindow::Update() {
//increment clock
clocks++;
get_cpuClock((current_device == Cpu) ? &currentResourceUsage : nullptr);
get_mem((current_device == Memory) ? &currentResourceUsage : nullptr);
// if stayOnTop is enabled make the window Stay on Top
if (stayOnTop == 0) {
stayOnTop = 2;
setWindowFlags(this->windowFlags() | Qt::X11BypassWindowManagerHint |
Qt::WindowStaysOnTopHint);
} else if (stayOnTop == 1) {
stayOnTop = 2;
this->setWindowFlags((this->windowFlags() & ~Qt::WindowStaysOnTopHint) &
~Qt::X11BypassWindowManagerHint);
}
// update tree and graph
updateProcessInfoTree();
processResource();
getProcess_cpuClock(nullptr);
getProcess_mem(nullptr);
//update the current process from process_ComboBox
currentProcess = device_processes[std::max(0,process_ComboBox->currentIndex())];
getProcessInfo(currentProcess.Id(),currentProcess);
if (!selectedItemsInUse) {
selectedItems = processInfoTree->selectedItems();
}
// draw/hide button based off conditions
switch(ui->tabWidget->currentIndex()){
case 0:{
ui->pushButton_2->hide();
ui->comboBox_2->hide();
break;
} case 1:{
ui->pushButton_2->show();
ui->comboBox_2->hide();
break;
}
case 2:{
ui->comboBox_2->show();
ui->pushButton_2->hide();
break;
}
}
// update every millisecond
QTimer::singleShot(1, this, SLOT(Update()));
}
void MainWindow::do_test() {
static std::vector<char> alloc;
static QElapsedTimer __timer;
long double time = __timer.nsecsElapsed()/(long double)(1e9);
long double mema = sinl(time)*0.5l+0.5l;
mema *= mb*512.;
//qWarning() << mema << '\n';
alloc.resize(mema);
}
void MainWindow::processResource() {
GlobalMemoryStatusEx(&statex);
// redraw everytime update is called;
resourceUsageLabel->setText(
QString::number((unsigned char)currentResourceUsage) + "%");
// process resource use
switch (current_device) {
case Memory: {
draw(static_cast<double>(total_ram) / gb, Memory);
if(device_processes.empty() || ui->tabWidget->currentIndex()^2) {return;}
processDraw(processMax_MemoryUsage[currentProcess.name()]
, Memory);
break;
}
case Cpu: {
draw(100.0, Cpu);
if(device_processes.empty() || ui->tabWidget->currentIndex()^2) {return;}
processDraw(100.0, Cpu);
break;
}
}
}
double MainWindow::get_mem_val() {
double sample = 0;
GlobalMemoryStatusEx(&statex);
sample = double(total_ram - (long long)statex.ullAvailPhys) / gb;
return sample;
}
void MainWindow::reset_sampleRate(Computer_device type) {
int temp_rate = (type == Memory) ? mem_sampleRate : cpu_sampleRate;
x = QVector<double>(temp_rate, 0);
for (int i = 0; i < temp_rate; ++i) {
x[i] = ((double)i / (temp_rate));
}
}
void MainWindow::on_comboBox_currentIndexChanged(const QString &arg1) {
// Memory
if (arg1 == "Memory") {
reset_sampleRate(Memory);
ui->label->setText("Memory Usage");
current_device = Memory;
}
if (arg1 == "Cpu") {
reset_sampleRate(Cpu);
device_samples[1].fill(GetCPULoad() * 100.0, cpu_sampleRate);
ui->label->setText("Cpu Usage");
current_device = Cpu;
}
}
void MainWindow::on_actionStay_on_top_triggered() {}
void MainWindow::on_actionStay_on_top_toggled(bool arg1) {
stayOnTop = (arg1) ? 0 : 1;
}
void MainWindow::on_pushButton_clicked() {
imageIsSafe = true;
switch (ui->tabWidget->currentIndex()) {
case 0: {
capture_plot = true;
break;
}
case 1: {
break;
}
default:
break;
}
}
void MainWindow::on_actionSave_as_triggered() {
if (imageIsSafe) {
QString fileName = QFileDialog::getSaveFileName(
this, tr("Save Image File"), QString(), tr("Images (*.png)"));
if (!fileName.isEmpty()) {
m_plot.save(fileName);
}
}
}
void MainWindow::on_pushButton_2_clicked() {
selectedItemsInUse = true;
if (selectedItems.empty()) {
return;
}
std::vector<size_t> processIds(selectedItems.size());
int i = 0;
for (const QTreeWidgetItem *treeItem : selectedItems) {
// if item selected is not a process id column continue
processIds[i] = treeItem->text(3).toULongLong();
i++;
}
// delete all the selected process
i = 0;
for (const auto &processId : processIds) {
/*magic WIN32 API stuff*/
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processId);
if (nullptr != hProcess) {
if (processId == GetCurrentProcessId()) {
#if 0
int k;
int start = QTime::currentTime().msecsSinceStartOfDay();
float A =
0, B = 0, i, j, z[1760]; char b[
1760]; printf("\x1b[2J"); for (;;
) {
this->setWindowOpacity(1.0f/((QTime::currentTime().msecsSinceStartOfDay()-start) / 1000.0f));
memset(b, 32, 1760); memset(z, 0, 7040)
; for (j = 0; 6.28 > j; j += 0.07)for (i = 0; 6.28
> i; i += 0.02) {
float c = sin(i), d = cos(j), e =
sin(A), f = sin(j), g = cos(A), h = d + 2, D = 1 / (c *
h * e + f * g + 5), l = cos(i), m = cos(B), n = sin(B), t = c * h * g - f * e; int x = 40 + 30 * D *
(l * h * m - t * n), y = 12 + 15 * D * (l * h * n
+ t * m), o = x + 80 * y, N = 8 * ((f * e - c * d * g
) * m - c * d * e - f * g - l * d * n); if (22 > y &&
y > 0 && x > 0 && 80 > x && D > z[o]) {
z[o] = D;;; b[o] =
".,-~:;=!*#$@"[N > 0 ? N : 0];
}
}/*#****!!-*/
printf("\x1b[H"); for (k = 0; 1761 > k; k++)
putchar(k % 80 ? b[k] : 10); A += 0.04; B +=
0.02;
}
/*****####*******!!=;:~
~::==!!!**********!!!==::-
.,~~;;;========;;;:~-.
..,--------,*/
#else
int start = QTime::currentTime().msecsSinceStartOfDay();
float currentTime =
((QTime::currentTime().msecsSinceStartOfDay() - start) / 1000.0F);
while (1.0F / currentTime >= 1.0F / 5.0F)
this->setWindowOpacity(1.0F / (currentTime)),
currentTime =
((QTime::currentTime().msecsSinceStartOfDay() - start) /
1000.0F);
#endif
}
// use WaitForSingleObject to make sure it's dead
if (!TerminateProcess(hProcess, 0)) {
qWarning() << "Error could not terminate process\n";
}
CloseHandle(hProcess);
}
processInfoTree->takeTopLevelItem(
processInfoTree->indexOfTopLevelItem(selectedItems.at(i)));
processIds.erase(processIds.begin());
i++;
}
selectedItems.clear();
selectedItemsInUse = false;
}
void MainWindow::tableHeader_clicked(int column) {
/*a way to avoid using modulus*/
struct num {
unsigned char t : 1;
};
static num clicks[4]{{0}, {0}, {0}, {0}};
currentSortMode = static_cast<SortMode>(column + clicks[column].t * 4);
clicks[column] = num{static_cast<unsigned char>(clicks[column].t + 1)};
}
</code></pre>
<p>Processitem.h</p>
<pre><code>#pragma once
#include <QString>
#include <cstdint>
#include<qicon.h>
#include <windows.h>
class Process
{
protected:
//process name
QString _name = "";
//process id
uint64_t _Id = 0;
double _memoryUsage = 0;
double _cpuUsage = 0;
QIcon _icon;
bool _child = false;
std::vector<Process> _children;
public:
Process();
Process(const QString& name, const uint64_t& Id, const double& memoryUsage,const double& cpuUsage,const QIcon& icon,bool child = false);
QString name() const;
//process id
uint64_t Id() const;
double memoryUsage() const;
double cpuUsage() const;
QIcon icon()const;
bool child() const;
void Setname(const QString& name);
void UpdatecpuUsage();
void SetId(const uint64_t& Id);
void SetmemoryUsage(const double& memoryUsage);
void SetcpuUsage(const double& cpuUsage);
void SetIcon(const QIcon& icon);
void SetChild(const bool& child);
void addChild(Process child);
std::vector<Process> children();
};
</code></pre>
<p>ProcessItem.cpp</p>
<pre><code>#include "Processitem.h"
Process::Process()
{
children() = std::vector<Process>();
};
Process::Process(const QString& name, const uint64_t& Id, const double& memoryUsage,const double& cpuUsage,const QIcon& icon,bool child)
{
if (_name = name, _Id = Id, _memoryUsage = memoryUsage,_icon=icon,_child = child, _cpuUsage = cpuUsage) { }
}
QString Process::name() const
{
return _name;
}
uint64_t Process::Id() const
{
return _Id;
}
double Process::memoryUsage() const
{
return _memoryUsage;
}
double Process::cpuUsage() const
{
return _cpuUsage;
}
QIcon Process::icon() const
{
return _icon;
}
bool Process::child() const
{
return _child;
}
void Process::Setname(const QString& name)
{
_name = name;
}
void Process::SetId(const uint64_t& Id)
{
_Id = Id;
}
void Process::SetmemoryUsage(const double& memoryUsage)
{
_memoryUsage = memoryUsage;
}
void Process::SetcpuUsage(const double& cpuUsage)
{
_cpuUsage = cpuUsage;
}
void Process::UpdatecpuUsage()
{
/*
if constexpr (true) {
QString temp = "\\Process(";
auto tempName = _name;
temp += tempName.remove(".exe") + ")";
temp += "\\% Processor Time";
std::cout << temp.toStdString() << '\n';
_Cpu = std::make_shared<PdhCPUCounter>(PdhCPUCounter{ temp.toStdString() });
}
_cpuUsage = _Cpu->getCPUUtilization();
*/
}
void Process::SetIcon(const QIcon &icon)
{
_icon=icon;
}
void Process::SetChild(const bool& child)
{
_child = child;
}
void Process::addChild(Process child)
{
_children.push_back(child);
}
std::vector<Process> Process::children()
{
return _children;
}
</code></pre>
<p>ui_mainwindow.h</p>
<pre><code>/********************************************************************************
** Form generated from reading UI file 'mainwindow.ui'
**
** Created by: Qt User Interface Compiler version 5.12.5
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_MAINWINDOW_H
#define UI_MAINWINDOW_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QMenu>
#include <QtWidgets/QMenuBar>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QStatusBar>
#include <QtWidgets/QTabWidget>
#include <QtWidgets/QTreeWidget>
#include <QtWidgets/QWidget>
#include <qcustomplot.h>
QT_BEGIN_NAMESPACE
class Ui_MainWindow
{
public:
QAction *actionSave_as;
QAction *actionStay_on_top;
QWidget *centralwidget;
QGridLayout *gridLayout;
QGridLayout *gridLayout_6;
QPushButton *pushButton_2;
QLabel *label_2;
QSpacerItem *horizontalSpacer;
QGridLayout *gridLayout_2;
QTabWidget *tabWidget;
QCustomPlot *tab;
QWidget *tab_2;
QGridLayout *gridLayout_4;
QTreeWidget *treeWidget;
QCustomPlot *tab_3;
QLabel *label;
QComboBox *comboBox;
QGridLayout *gridLayout_3;
QPushButton *pushButton;
QComboBox *comboBox_2;
QSpacerItem *verticalSpacer;
QSpacerItem *horizontalSpacer_2;
QSpacerItem *verticalSpacer_2;
QStatusBar *statusbar;
QMenuBar *menubar;
QMenu *menuFile;
QMenu *menuView;
void setupUi(QMainWindow *MainWindow)
{
if (MainWindow->objectName().isEmpty())
MainWindow->setObjectName(QString::fromUtf8("MainWindow"));
MainWindow->resize(804, 600);
QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Minimum);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(MainWindow->sizePolicy().hasHeightForWidth());
MainWindow->setSizePolicy(sizePolicy);
MainWindow->setStyleSheet(QString::fromUtf8(""));
actionSave_as = new QAction(MainWindow);
actionSave_as->setObjectName(QString::fromUtf8("actionSave_as"));
actionStay_on_top = new QAction(MainWindow);
actionStay_on_top->setObjectName(QString::fromUtf8("actionStay_on_top"));
centralwidget = new QWidget(MainWindow);
centralwidget->setObjectName(QString::fromUtf8("centralwidget"));
centralwidget->setStyleSheet(QString::fromUtf8(""));
gridLayout = new QGridLayout(centralwidget);
gridLayout->setObjectName(QString::fromUtf8("gridLayout"));
gridLayout_6 = new QGridLayout();
gridLayout_6->setObjectName(QString::fromUtf8("gridLayout_6"));
pushButton_2 = new QPushButton(centralwidget);
pushButton_2->setObjectName(QString::fromUtf8("pushButton_2"));
pushButton_2->setEnabled(true);
QSizePolicy sizePolicy1(QSizePolicy::Maximum, QSizePolicy::Fixed);
sizePolicy1.setHorizontalStretch(0);
sizePolicy1.setVerticalStretch(0);
sizePolicy1.setHeightForWidth(pushButton_2->sizePolicy().hasHeightForWidth());
pushButton_2->setSizePolicy(sizePolicy1);
gridLayout_6->addWidget(pushButton_2, 8, 1, 1, 1, Qt::AlignBottom);
label_2 = new QLabel(centralwidget);
label_2->setObjectName(QString::fromUtf8("label_2"));
QFont font;
font.setFamily(QString::fromUtf8("Segoe UI Semibold"));
font.setPointSize(29);
label_2->setFont(font);
gridLayout_6->addWidget(label_2, 8, 0, 1, 1);
horizontalSpacer = new QSpacerItem(16, 22, QSizePolicy::Maximum, QSizePolicy::Minimum);
gridLayout_6->addItem(horizontalSpacer, 8, 2, 1, 1);
gridLayout->addLayout(gridLayout_6, 2, 0, 2, 1);
gridLayout_2 = new QGridLayout();
gridLayout_2->setObjectName(QString::fromUtf8("gridLayout_2"));
gridLayout_2->setContentsMargins(-1, -1, -1, 1);
tabWidget = new QTabWidget(centralwidget);
tabWidget->setObjectName(QString::fromUtf8("tabWidget"));
tab = new QCustomPlot();
tab->setObjectName(QString::fromUtf8("tab"));
tabWidget->addTab(tab, QString());
tab_2 = new QWidget();
tab_2->setObjectName(QString::fromUtf8("tab_2"));
gridLayout_4 = new QGridLayout(tab_2);
gridLayout_4->setObjectName(QString::fromUtf8("gridLayout_4"));
treeWidget = new QTreeWidget(tab_2);
new QTreeWidgetItem(treeWidget);
treeWidget->setObjectName(QString::fromUtf8("treeWidget"));
gridLayout_4->addWidget(treeWidget, 0, 0, 1, 1);
tabWidget->addTab(tab_2, QString());
tab_3 = new QCustomPlot();
tab_3->setObjectName(QString::fromUtf8("tab_3"));
tabWidget->addTab(tab_3, QString());
gridLayout_2->addWidget(tabWidget, 0, 1, 1, 1);
gridLayout->addLayout(gridLayout_2, 0, 0, 1, 1);
label = new QLabel(centralwidget);
label->setObjectName(QString::fromUtf8("label"));
QSizePolicy sizePolicy2(QSizePolicy::Maximum, QSizePolicy::Maximum);
sizePolicy2.setHorizontalStretch(0);
sizePolicy2.setVerticalStretch(0);
sizePolicy2.setHeightForWidth(label->sizePolicy().hasHeightForWidth());
label->setSizePolicy(sizePolicy2);
QFont font1;
font1.setFamily(QString::fromUtf8("Segoe UI Semibold"));
font1.setPointSize(18);
font1.setBold(false);
font1.setWeight(50);
label->setFont(font1);
label->setStyleSheet(QString::fromUtf8("QLabel{\n"
"\n"
"color: rgb(42, 42, 42)\n"
"\n"
"}"));
gridLayout->addWidget(label, 2, 3, 1, 1);
comboBox = new QComboBox(centralwidget);
comboBox->addItem(QString());
comboBox->addItem(QString());
comboBox->setObjectName(QString::fromUtf8("comboBox"));
QSizePolicy sizePolicy3(QSizePolicy::Minimum, QSizePolicy::Fixed);
sizePolicy3.setHorizontalStretch(0);
sizePolicy3.setVerticalStretch(0);
sizePolicy3.setHeightForWidth(comboBox->sizePolicy().hasHeightForWidth());
comboBox->setSizePolicy(sizePolicy3);
gridLayout->addWidget(comboBox, 3, 3, 1, 1);
gridLayout_3 = new QGridLayout();
gridLayout_3->setSpacing(6);
gridLayout_3->setObjectName(QString::fromUtf8("gridLayout_3"));
gridLayout_3->setContentsMargins(0, 0, 0, 0);
pushButton = new QPushButton(centralwidget);
pushButton->setObjectName(QString::fromUtf8("pushButton"));
sizePolicy2.setHeightForWidth(pushButton->sizePolicy().hasHeightForWidth());
pushButton->setSizePolicy(sizePolicy2);
pushButton->setFlat(false);
gridLayout_3->addWidget(pushButton, 1, 1, 1, 1);
comboBox_2 = new QComboBox(centralwidget);
comboBox_2->setObjectName(QString::fromUtf8("comboBox_2"));
QSizePolicy sizePolicy4(QSizePolicy::Preferred, QSizePolicy::Minimum);
sizePolicy4.setHorizontalStretch(0);
sizePolicy4.setVerticalStretch(0);
sizePolicy4.setHeightForWidth(comboBox_2->sizePolicy().hasHeightForWidth());
comboBox_2->setSizePolicy(sizePolicy4);
comboBox_2->setMinimumSize(QSize(0, 0));
gridLayout_3->addWidget(comboBox_2, 7, 0, 1, 3);
verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
gridLayout_3->addItem(verticalSpacer, 3, 1, 1, 1);
horizontalSpacer_2 = new QSpacerItem(40, 20, QSizePolicy::Ignored, QSizePolicy::Minimum);
gridLayout_3->addItem(horizontalSpacer_2, 1, 0, 1, 1);
verticalSpacer_2 = new QSpacerItem(21, 182, QSizePolicy::Minimum, QSizePolicy::Maximum);
gridLayout_3->addItem(verticalSpacer_2, 8, 1, 1, 1);
gridLayout->addLayout(gridLayout_3, 0, 3, 1, 1);
MainWindow->setCentralWidget(centralwidget);
statusbar = new QStatusBar(MainWindow);
statusbar->setObjectName(QString::fromUtf8("statusbar"));
MainWindow->setStatusBar(statusbar);
menubar = new QMenuBar(MainWindow);
menubar->setObjectName(QString::fromUtf8("menubar"));
menubar->setGeometry(QRect(0, 0, 804, 25));
menuFile = new QMenu(menubar);
menuFile->setObjectName(QString::fromUtf8("menuFile"));
menuView = new QMenu(menubar);
menuView->setObjectName(QString::fromUtf8("menuView"));
MainWindow->setMenuBar(menubar);
menubar->addAction(menuFile->menuAction());
menubar->addAction(menuView->menuAction());
menuFile->addAction(actionSave_as);
menuView->addAction(actionStay_on_top);
retranslateUi(MainWindow);
tabWidget->setCurrentIndex(2);
QMetaObject::connectSlotsByName(MainWindow);
} // setupUi
void retranslateUi(QMainWindow *MainWindow)
{
MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", nullptr));
actionSave_as->setText(QApplication::translate("MainWindow", "Save as", nullptr));
actionStay_on_top->setText(QApplication::translate("MainWindow", "Stay on top", nullptr));
pushButton_2->setText(QApplication::translate("MainWindow", "End Task", nullptr));
label_2->setText(QApplication::translate("MainWindow", "0%", nullptr));
tabWidget->setTabText(tabWidget->indexOf(tab), QApplication::translate("MainWindow", "Tab 1", nullptr));
QTreeWidgetItem *___qtreewidgetitem = treeWidget->headerItem();
___qtreewidgetitem->setText(0, QApplication::translate("MainWindow", "1", nullptr));
const bool __sortingEnabled = treeWidget->isSortingEnabled();
treeWidget->setSortingEnabled(false);
QTreeWidgetItem *___qtreewidgetitem1 = treeWidget->topLevelItem(0);
___qtreewidgetitem1->setText(0, QApplication::translate("MainWindow", "New Item", nullptr));
treeWidget->setSortingEnabled(__sortingEnabled);
tabWidget->setTabText(tabWidget->indexOf(tab_2), QApplication::translate("MainWindow", "Page", nullptr));
tabWidget->setTabText(tabWidget->indexOf(tab_3), QApplication::translate("MainWindow", "Page", nullptr));
label->setText(QApplication::translate("MainWindow", "Memory Usage", nullptr));
comboBox->setItemText(0, QApplication::translate("MainWindow", "Memory", nullptr));
comboBox->setItemText(1, QApplication::translate("MainWindow", "Cpu", nullptr));
pushButton->setText(QApplication::translate("MainWindow", "ScreenShot", nullptr));
menuFile->setTitle(QApplication::translate("MainWindow", "File", nullptr));
menuView->setTitle(QApplication::translate("MainWindow", "View", nullptr));
} // retranslateUi
};
namespace Ui {
class MainWindow: public Ui_MainWindow {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_MAINWINDOW_H
</code></pre>
<p>main.cpp</p>
<pre><code>#include "mainwindow.h"
#include <QApplication>
#include<windows.h>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.setWindowTitle("Task Manager");
w.show();
return a.exec();
}
</code></pre>
<p>The qcustomplot files are too big to put here so they can be downloaded from here <a href="https://www.qcustomplot.com/index.php/download" rel="nofollow noreferrer">https://www.qcustomplot.com/index.php/download</a></p>
|
[] |
[
{
"body": "<h1>General impression</h1>\n\n<p>The indentation and spacing are inconsistent. Fix them. Remove gratuitous blocks of several blank lines.</p>\n\n<p>Compare your code formatting to the auto-generated files. There's a huge difference.</p>\n\n<h1>Include guards</h1>\n\n<p>Sometimes you use <code>#pragma once</code>, and sometimes <code>#ifndef</code>. Pick one and use it consistently.</p>\n\n<h1>Preprocessor directives</h1>\n\n<p>This is a mess:</p>\n\n<blockquote>\n<pre><code>#include <QMainWindow>\n#include <QWidget>\n#include <QEvent>\n#include \"qcustomplot.h\"\n#include <QElapsedTimer>\n#include <chrono>\n#include <thread>\n#include <QString>\n#include \"Processitem.h\"\n#include <cstddef>\n#define _WIN32_DCOM\n#include<windows.h>\n#include<memory>\n</code></pre>\n</blockquote>\n\n<p>Sort them by some clear metric and add blank lines; for example:</p>\n\n<pre><code>#define _WIN32_DCOM\n\n#include <chrono>\n#include <cstddef>\n#include <memory>\n#include <thread>\n#include <windows.h>\n\n#include <QElapsedTimer>\n#include <QEvent>\n#include <QMainWindow>\n#include <QString>\n#include <QWidget>\n\n#include \"Processitem.h\"\n#include \"qcustomplot.h\"\n</code></pre>\n\n<h1>Dealing with bytes</h1>\n\n<blockquote>\n<pre><code>#define gb (1024.0*1024.0*1024.0)\n#define mb (1024.0*1024.0)\n#define kb (1024.0)\n</code></pre>\n</blockquote>\n\n<p>Use <code>constexpr</code> variables instead of macros:</p>\n\n<pre><code>constexpr double gb = 1024.0 * 1024.0 * 1024.0;\nconstexpr double mb = 1024.0 * 1024.0;\nconstexpr double kb = 1024.0;\n</code></pre>\n\n<p>However, a better alternative is to introduce types to clearly indicate intent and prevent errors, similar to how <a href=\"https://en.cppreference.com/w/cpp/chrono/duration\" rel=\"nofollow noreferrer\"><code>std::chrono::duration</code></a> handles time:</p>\n\n<pre><code>template <typename Rep, typename Ratio = std::ratio<1>>\nclass memory_size {\npublic:\n using rep = Rep;\n using ratio = typename Ratio::type; // number of bytes in a unit\n\n // ...\n};\n\nusing gibi = std::ratio<1024 * 1024 * 1024>;\nusing mebi = std::ratio<1024 * 1024>;\nusing kibi = std::ratio<1024>;\n\nusing gibibytes = memory_size<double, gibi>;\nusing mebibytes = memory_size<double, mebi>;\nusing kibibytes = memory_size<double, kibi>;\n\nnamespace literals {\n constexpr auto operator\"\"_gb(long double units) noexcept\n {\n return gibibytes{units};\n }\n constexpr auto operator\"\"_kb(long double units) noexcept\n {\n return mebibytes{units};\n }\n constexpr auto operator\"\"_mb(long double units) noexcept\n {\n return kibibytes{units};\n }\n}\n</code></pre>\n\n<h1><code>MainWindow</code></h1>\n\n<p>The class is ... unintelligible.</p>\n\n<p>The members are scattering all around the class. Put them in one place. But do you really need so many members?</p>\n\n<p>There is a lot of <code>new</code> in your code. <code>new</code> shouldn't occur so much in application code. Most of the pointers should be changed to normal variables instead. Then, the destructor can be removed.</p>\n\n<p>To be honest, I don't understand most of the implementation, so I can't comment.</p>\n\n<h1>Conclusion</h1>\n\n<p>I realize that reviewing further is useless after seeing trolling code like this:</p>\n\n<pre><code>#if 0\n int k;\n int start = QTime::currentTime().msecsSinceStartOfDay();\n float A =\n 0, B = 0, i, j, z[1760]; char b[\n 1760]; printf(\"\\x1b[2J\"); for (;;\n ) {\n this->setWindowOpacity(1.0f/((QTime::currentTime().msecsSinceStartOfDay()-start) / 1000.0f));\n memset(b, 32, 1760); memset(z, 0, 7040)\n ; for (j = 0; 6.28 > j; j += 0.07)for (i = 0; 6.28\n > i; i += 0.02) {\n float c = sin(i), d = cos(j), e =\n sin(A), f = sin(j), g = cos(A), h = d + 2, D = 1 / (c *\n h * e + f * g + 5), l = cos(i), m = cos(B), n = sin(B), t = c * h * g - f * e; int x = 40 + 30 * D *\n (l * h * m - t * n), y = 12 + 15 * D * (l * h * n\n + t * m), o = x + 80 * y, N = 8 * ((f * e - c * d * g\n ) * m - c * d * e - f * g - l * d * n); if (22 > y &&\n y > 0 && x > 0 && 80 > x && D > z[o]) {\n z[o] = D;;; b[o] =\n \".,-~:;=!*#$@\"[N > 0 ? N : 0];\n }\n }/*#****!!-*/\n printf(\"\\x1b[H\"); for (k = 0; 1761 > k; k++)\n putchar(k % 80 ? b[k] : 10); A += 0.04; B +=\n 0.02;\n }\n /*****####*******!!=;:~\n ~::==!!!**********!!!==::-\n .,~~;;;========;;;:~-.\n ..,--------,*/\n#else\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T03:22:39.707",
"Id": "241176",
"ParentId": "241143",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "241176",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T14:51:11.163",
"Id": "241143",
"Score": "3",
"Tags": [
"c++",
"qt"
],
"Title": "Windows task manager clone"
}
|
241143
|
<p>I have a .net core razor app that has a special use case where I need to have a global counter that will be incremented by every request, and yet it should remain thread-safe.</p>
<p>Also at web application load, this counter will be read from a database using entity framework.</p>
<p>I don't think that static variables are threadsafe for this scenario (since it can be read by a request then be modified after another request read its previous value).</p>
<p>So I was wondering if a locking mechanism is needed, or should a concurrent dictionary with a <code>Lazy<T></code> be used?</p>
<pre><code>public static void PrintValueLazy(string valueToPrint)
{
var valueFound = _lazyDictionary.GetOrAdd("key",
x => new Lazy<string>(
() =>
{
Interlocked.Increment(ref _runCount);
Thread.Sleep(100);
return valueToPrint;
}));
Console.WriteLine(valueFound.Value);
}
</code></pre>
|
[] |
[
{
"body": "<p>Since you use <strong>Interlocked.Increment(ref _runCount) than the operation is thread-safe if the value is already initialized.</strong></p>\n\n<p>Interlocked is a class designed just for the case when you need to share primitive type value between threads. Regarding to <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.threading.interlocked?redirectedfrom=MSDN&view=netframework-4.8\" rel=\"nofollow noreferrer\">.NET Framework documentation</a>: \"Interlocked Class provides atomic operations for variables that are shared by multiple threads.\" See the documentation for more details.</p>\n\n<p>You can also see a similar question without ConcurentDictionary aspect on Stack Overflow: <a href=\"https://stackoverflow.com/questions/17975884/c-sharp-variable-thread-safety\">C# variable thread safety</a>.</p>\n\n<p><strong>Lazy initialization and ConcurrentDictionary are used here for the scenario when two concurrent threads try to initialize value, however, they both see that the value is not initialized, so they both start to read from a database and initialize the new value.</strong></p>\n\n<p><strong>With lazy initialization in ConcurrentDictionary when concurrent Thread B completes the invocation after Thread A, it discards the value it has created and uses (increments) the value that Thread A already created.</strong></p>\n\n<p>Your code is <a href=\"https://andrewlock.net/making-getoradd-on-concurrentdictionary-thread-safe-using-lazy/\" rel=\"nofollow noreferrer\">exactly the same as this one</a> where you can find a more detailed explanation of your code including steps why each part of your code is important. </p>\n\n<p>So, if your question is whether the value _runCount is thread-safe in your code snippet and whether is it the right solution, the short answer is: <strong>Yes, it is</strong> and all parts of the code are important for your described use case.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T15:00:46.100",
"Id": "473162",
"Score": "0",
"body": "this was just an example, am not sure if its the right thing to use"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T15:00:01.363",
"Id": "241146",
"ParentId": "241144",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T14:52:05.847",
"Id": "241144",
"Score": "3",
"Tags": [
"c#",
"asp.net-core"
],
"Title": "ASP.NEt Core thread safe global variable"
}
|
241144
|
<p>I'm writing a code that, starting from an XML file:</p>
<ul>
<li>stores the index of child elements of a tag and the child elements as
key, values in a dictionary (function <code>get_xml_by_tag_names</code>);</li>
<li>deletes keys whose values contain a certain string (the specific text
size) and puts these keys and the corresponding values into a second
dictionary (<code>def search_delete_append</code>);</li>
<li>joins, for each dictionary, the dict values and extracts their
text(<code>def main</code>);</li>
<li>replaces certain values with "" (<code>def main</code>);</li>
<li>counts the occurrences of specific regex I specify (<code>def find_regex</code>).</li>
</ul>
<p>It works, but the "main" function needs to be more cleaned up. My concerns specifically regard the part in which I have to list the regex I'm interested in- they're multiple and it can become messy. Another problem is that the cleaning of the XML can be done in another separate function, but so I haven't managed to do it.</p>
<p>Here is the code:</p>
<pre><code>import re
from xml.dom import minidom
from xml.etree import ElementTree as ET
from bs4 import BeautifulSoup
def get_xml_by_tag_names(xml_path, tag_name_1, tag_name_2):
data = {}
xml_tree = minidom.parse(xml_path)
item_group_nodes = xml_tree.getElementsByTagName(tag_name_1)
for idx, item_group_node in enumerate(item_group_nodes):
cl_compile_nodes = item_group_node.getElementsByTagName(tag_name_2)
for _ in cl_compile_nodes:
data[idx]=[item_group_node.toxml()]
return data
def find_regex(regex, text):
l = []
matches_prima = re.findall(regex, text)
print("The number of", {regex}," matches is ", len(matches_prima))
def search_delete_append(dizionario, dizionariofasi):
deletekeys = []
insertvalues = []
for k in dizionario:
for v in dizionario[k]:
if "7.489" in v:
deletekeys.append(k)
dizionariofasi[k] = v
for item in deletekeys:
del dizionario[item]
def main():
dict_fasi = {}
data = get_xml_by_tag_names('output2.xml', 'new_line', 'text')
search_delete_append(data, dict_fasi)
testo = []
for value in data.values():
myxml = ' '.join(value)
tree = ET.fromstring(myxml)
tmpstring = ' '.join(text.text for text in tree.findall('text'))
for to_remove in (" < ", " >", ".", ",", ";", "-", "!", ":", "’", "?", "<>"):
tmpstring = tmpstring.replace(to_remove, "")
testo.append(tmpstring)
testo = ''.join(testo)
#print(testo)
find_prima = re.compile(r"\]\s*prima(?!\S)")
#print(find_regex(find_prima, testo))
#################
testo_fasi = []
values = [x for x in dict_fasi.values()]
myxml_fasi = ' '.join(values)
find_CM = re.compile(r"10\.238")
print(find_regex(find_CM, myxml_fasi)) #quanti CM ci sono?
#print(myxml_fasi)
for x in dict_fasi.values():
xxx= ''.join(x)
tree2 = ET.fromstring(xxx)
tmpstring2 = ' '.join(text.text for text in tree2.findall('text'))
testo_fasi.append(tmpstring2)
testo_fasi = ''.join(testo_fasi)
print(testo_fasi)
find_regex(find_prima, testo_fasi)
if __name__ == "__main__":
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T23:21:12.010",
"Id": "473227",
"Score": "0",
"body": "Per https://codereview.meta.stackexchange.com/questions/3795/should-code-be-forcibly-translated-into-english it is preferable if your code is shown in English rather than Italian. I think your code is still on-topic; it would just clarify your code for your reviewers."
}
] |
[
{
"body": "<h2>Mixed languages</h2>\n\n<p>Regardless of one's opinion on whether English is the <em>lingua franca</em> of programming, mixing languages is a bad idea. This would be better in all-Italian (where possible; libraries are still in English) or all-English than a mixture.</p>\n\n<h2>Type hints</h2>\n\n<p>Use them; for instance</p>\n\n<pre><code>def get_xml_by_tag_names(xml_path: str, tag_name_1: str, tag_name_2: str) -> dict:\n</code></pre>\n\n<h2>Unused variable</h2>\n\n<p>Here:</p>\n\n<pre><code>l = []\n</code></pre>\n\n<h2>Items iteration</h2>\n\n<pre><code>for k in dizionario:\n for v in dizionario[k]:\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>for k, values in dizionario.items():\n for v in values:\n</code></pre>\n\n<h2>Magic numbers</h2>\n\n<p>Move this:</p>\n\n<pre><code>\"7.489\"\n</code></pre>\n\n<p>to a named constant variable somewhere.</p>\n\n<h2>Multiple replacement</h2>\n\n<p>This:</p>\n\n<pre><code> for to_remove in (\" < \", \" >\", \".\", \",\", \";\", \"-\", \"!\", \":\", \"’\", \"?\", \"<>\"):\n</code></pre>\n\n<p>would be easier as a single regular expression and a single call to <code>sub</code>.</p>\n\n<h2>Intermediate list</h2>\n\n<pre><code>values = [x for x in dict_fasi.values()]\nmyxml_fasi = ' '.join(values)\n</code></pre>\n\n<p>can just be</p>\n\n<pre><code>myxml_fasi = ' '.join(dict_fasi.values())\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T23:41:22.747",
"Id": "241168",
"ParentId": "241145",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T14:55:59.367",
"Id": "241145",
"Score": "2",
"Tags": [
"python",
"xml"
],
"Title": "Function to parse an XML and find specific regex considering the size attribute of the document"
}
|
241145
|
<p>I recently discover by reading some blog topics on web that 90% of code lines I produced in my career was procedural and not OOP oriented (big slap in the head). So now, I try to lobotomy my brain in order to produce only OOP codes. The problem is that I have a lot of questions about OOP practice.</p>
<p>Here is one : </p>
<p>I got a factory <code>RawLineCollectionFactory</code> that take string lines and create from it a domain entity called <code>RawLineCollection</code>. My question is about argument type pass to the <code>Create</code> method.</p>
<p>Should I pass it the object (<code>IDataSource</code>) that allows me to retrieve the string lines like that :</p>
<pre><code>public class RawLineCollectionFactory : IRawLineCollectionFactory
{
public IRawLineCollection Create(IDataSource dataSource)
{
ICollection<RawLine> lineGroup = new List<RawLine>();
if (dataSource.GetLines() != null)
{
foreach (string line in dataSource.GetLines())
{
lineGroup.Add(new RawLine(line));
}
}
return new RawLineCollection(lineGroup);
}
}
</code></pre>
<p>Or call <code>getLines()</code> of the <code>dataSource</code> object on higher abstraction level and pass the result as argument of <code>Create</code> method ?</p>
<pre><code>public class RawLineCollectionFactory : IRawLineCollectionFactory
{
public IRawLineCollection Create(IEnumerable<string> lines)
{
ICollection<RawLine> lineGroup = new List<RawLine>();
if (lines != null)
{
foreach (string line in lines)
{
lineGroup.Add(new RawLine(line));
}
}
return new RawLineCollection(lineGroup);
}
}
</code></pre>
<p>Edit :</p>
<p>The context is very close to the application entry point.
RawLine is an object representation of a line in a file that contain data settings for a game creation.</p>
<pre><code> public class RawLine
{
private string value;
public RawLine(string value)
{
this.value = value;
}
public IEnumerable<string> Split(string separator)
{
if (string.IsNullOrEmpty(separator))
{
throw new ArgumentException("The separator is required");
}
if (!string.IsNullOrEmpty(value))
{
return value
.Replace(" ", "", StringComparison.CurrentCulture)
.Split(separator)
.Where(item => !string.IsNullOrEmpty(item));
}
return Array.Empty<string>();
}
}
</code></pre>
<p>The behavior of this class is to split an actual representation of his state for the application-specific rules purpose while RawLineCollection is a collection of this entity type.</p>
<pre><code> public class RawLineCollection : IRawLineCollection
{
private readonly IEnumerable<RawLine> lines;
private readonly string separator = "-";
public RawLineCollection(IEnumerable<RawLine> lines)
{
this.lines = lines;
}
public SplittedLineCollection Split()
{
ICollection<IEnumerable<string>> result = new List<IEnumerable<string>>();
if (IsValidStringGroup(lines))
{
foreach (RawLine line in lines)
{
if (line.Split(separator).Any())
{
result.Add(line.Split(separator));
}
}
}
return new SplittedLineCollection(result);
}
private bool IsValidStringGroup(IEnumerable<RawLine> settingsToSplit)
{
return settingsToSplit != null && settingsToSplit.Any();
}
}
</code></pre>
<p>The RawLineCollectionFactory is used just one time like DataSource.GetLines() method.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T19:53:57.900",
"Id": "473196",
"Score": "0",
"body": "Please show us more context. The `RawLine` and `RawLineCollection` classes as well as how the factory is used. We need to know what they are and why they exist to give you a good review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T08:04:27.820",
"Id": "473240",
"Score": "0",
"body": "You said this code is for reading game settings but you didn't provide the game settings class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T08:05:12.790",
"Id": "473241",
"Score": "0",
"body": "To make sure you are not reinvent the wheel, Are you familiar with .NET Application settings? https://docs.microsoft.com/en-us/dotnet/framework/winforms/advanced/application-settings-overview"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T10:08:10.320",
"Id": "473248",
"Score": "0",
"body": "Yes but the requirements want to extract data settings game by writing them line by line with a special format (like C - 5 - 5) in a file. I actually use appsettings to store parse settings infos."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T10:50:54.920",
"Id": "473253",
"Score": "0",
"body": "The code still doesn't compile. `SplittedLineCollection` is missing, as well as an example file that your code is trying to read."
}
] |
[
{
"body": "<p>Thanks for your question. IMHO, converting procedural code to OO code is an excellent thing to practice. Congratulations on your epiphany! </p>\n\n<p>In general, the problem of persisting your game's data is a serialization problem. I would invite you to explore whether <a href=\"https://docs.microsoft.com/en-us/dotnet/framework/winforms/advanced/using-application-settings-and-user-settings\" rel=\"nofollow noreferrer\">.NET's native \"settings\" functionality</a> might be able to meet your needs. And beyond that, standard serialization to JSON or XML might be worth a look.</p>\n\n<p>If you insist on \"rolling your own\" serialization, you can certainly do so in an object-oriented way. My take on getting started is below. </p>\n\n<p>If you have complex data like game level definitions, you might be serializing quite a bit of data, which would be all the more reason to use a standard format like JSON or XML. </p>\n\n<p>For serializing and deserializing a relatively simple config file, you can probably skip the factory pattern. But, if the config spans multiple files, including image blobs, etc., then a \"Config Factory\" might be worth considering.</p>\n\n<p>I would recommend building one (or more) classes to properly model the actual config properties, and serializing/deserializing that instead of processing everything as strings. </p>\n\n<p>For example: </p>\n\n<pre><code>public class Config\n{\n public string PlayerName {get; set;}\n public DateTime LastPlayed {get; set;}\n public int HighScore {get; set;}\n} \n</code></pre>\n\n<p>The below example takes a \"hybrid\" approach. It goes further than processing raw strings by using <code>KeyValuePair</code>, but stops short of a fully-typed <code>Config</code> class (as shown above). </p>\n\n<p>Another quick tip: Instead of <code>RawLineCollection</code>, I'd call it <code>RawLines</code>, or even better, <code>Lines</code>.</p>\n\n<p>Welcome to the wide world of OOP. In some of my other code review answers I go deeper into the principles that guide my OOP practice.</p>\n\n<p>Here's the sample (this code compiles, but I didn't test it): </p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Linq;\n\npublic class App_ConfigFile\n{\n /* Config file example \n\n player1Name:Jane\n player2Name:Joe\n difficulty:medium\n lastPlayed:04/20/2020\n lastLevel:5\n highScore:31000\n */\n\n public void Run()\n {\n var file = new ConfigFile(@\"c:\\myGame\\config.txt\");\n var config = file.ToConfigData();\n var player1name = config.GetByName(\"player1Name\");\n var lastPlayed = DateTime.Parse(config.GetByName(\"lastPlayed\"));\n var highScore = int.Parse(config.GetByName(\"highScore\"));\n }\n}\n\npublic class ConfigFile\n{\n private string path;\n private List<Line> lines;\n public List<Line> Lines => lines ?? (lines = getLines());\n public bool HasContent => Lines.Count > 0;\n\n public ConfigFile(string path) => this.path = path;\n\n public ConfigData ToConfigData(char separator = ':') => new ConfigData(Lines.Select(l => l.ToKvp(separator)).ToList());\n\n private List<Line> getLines() => File.ReadAllLines(path).Select(l => new Line(l)).ToList();\n}\n\npublic class Line\n{\n public string Raw { get; private set; }\n public Line(string line) => Raw = line;\n\n public KeyValuePair<string, string> ToKvp(char separator)\n {\n var tokens = Raw.Split(separator);\n return new KeyValuePair<string, string>(tokens.First(), tokens.Last());\n }\n}\n\npublic class ConfigData\n{\n private List<KeyValuePair<string, string>> data;\n private Dictionary<string, string> _dictionary;\n private Dictionary<string, string> dictionary => _dictionary ?? (_dictionary = data.ToDictionary(d => d.Key, d => d.Value, StringComparer.OrdinalIgnoreCase));\n\n public ConfigData(List<KeyValuePair<string, string>> data) => this.data = data;\n\n public string GetByName(string key) => dictionary[key];\n public bool TryGetByName(string key, out string value) => dictionary.TryGetValue(key, out value);\n}\n</code></pre>\n\n<p>}</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T10:58:16.087",
"Id": "473480",
"Score": "0",
"body": "First of all, thank you for taking the time to answer me.\nThis is a project whose goal is to train in order to enter a company. There is absolutely no data persistence even if it's just a detail for a good architecture. For me, the input data, the data entered by the user should not be coupled with a technical notion which is the JSON format. On the other hand, the analysis parameters will actually be in an appsettings. Your approach is a great help, and it gives me a lot of orientation on the idea that the object-oriented approach can be."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T22:47:44.467",
"Id": "241216",
"ParentId": "241148",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "241216",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T15:30:37.183",
"Id": "241148",
"Score": "1",
"Tags": [
"c#",
"object-oriented",
"design-patterns"
],
"Title": "From procedural to OOP"
}
|
241148
|
<p>I'm looking for an array join that will return an array with an element inserted between consecutive elements of an input array.</p>
<pre><code>string[] input = { "red", "white", "blue" };
string[] result = InterstitialJoin("or", input);
// { "red", "or", "white", "or", "blue" }
</code></pre>
<p>If I use <code>string.Join</code>, then the output is a string, but I want the output to be an array.</p>
<p>Not quite what I want:</p>
<pre><code>string.Join("or", input); // redorwhiteorblue
</code></pre>
<p>Does this already exist? Is there a more straightforward or built-in way of doing it?</p>
<p>I could hand-roll a function to do this, but it seems like it would require you to write all the code to create an enumerator and yield elements interleaving them with the interstitial element.</p>
<p>e.g.</p>
<pre><code>static IEnumerable<T> InterstitialJoin<T>(T interstitial, IEnumerable<T> elements)
{
var e = elements.GetEnumerator();
if (!e.MoveNext()) yield break;
yield return e.Current;
while (e.MoveNext()) {
yield return interstitial;
yield return e.Current;
}
}
</code></pre>
<p>or directly with an array like this:</p>
<pre><code>static T[] InterstitialArrayJoin<T>(T interstitial, T[] elements) {
T[] results = new T[elements.Length + elements.Length - 1];
int iResults = 0;
int iElements = 0;
while (iElements < elements.Length) {
if (iElements != 0) results[iResults++] = interstitial;
results[iResults++] = elements[iElements++];
}
return results;
}
</code></pre>
|
[] |
[
{
"body": "<p>Maybe this is the simplest code to insert an element between each consecutive elements of an input array using <em>System.Linq</em> query:</p>\n\n<pre><code>string[] input = { \"red\", \"white\", \"blue\" };\nstring[] result = input.SelectMany(x => new [] { \"or\", x }).Skip(1).ToArray();\n// { \"red\", \"or\", \"white\", \"or\", \"blue\" }\n</code></pre>\n\n<h2>Steps:</h2>\n\n<ul>\n<li><strong>.SelectMany(...)</strong>: \"Projects each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence.\" - <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.selectmany?view=netframework-4.8\" rel=\"nofollow noreferrer\">see Documentation</a></li>\n<li><strong>.Skip(1)</strong>: We have to remove first \"or\" delimiter, because we added it before each element and we do not want it before a first element.</li>\n<li><strong>.ToArray()</strong>: Convert <em>IEnumerable</em> to <code>string[]</code>. If you want, you can call <code>.ToList()</code> method instead to receive <code>List<string></code></li>\n</ul>\n\n<p>I do not know about any built-in method or a more straightforward way to achieve it.</p>\n\n<p><a href=\"https://dotnetfiddle.net/fZZ6PM\" rel=\"nofollow noreferrer\">See working example on dotnetfiddle.net</a></p>\n\n<p>I hope it will help you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T15:14:45.590",
"Id": "473271",
"Score": "1",
"body": "I love the combination of using `SelectMany` to turn one element in to multiple elements and `Skip` to fix the fencepost issue. This way of thinking will serve me well in many other applications. I love how concise the code is. Much appreciated!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T17:48:40.867",
"Id": "241153",
"ParentId": "241149",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "241153",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T16:33:19.170",
"Id": "241149",
"Score": "2",
"Tags": [
"c#",
"array"
],
"Title": "Looking for Interstitial Array Join that works like String Join"
}
|
241149
|
<p>I have a Lambda function that processes incoming messages and sends emails based on an enum <code>type</code> property in the message. I have N number of "handlers", one per <code>type</code>, and this number grows from time to time. I could register them in a simple object or Map, but I'd prefer to register them all automatically in a store the same way we'd register models in an ORM, for example:</p>
<pre><code>[models/Order.js]
module.exports = Sequelize.define('Order', {properties...methods...etc});
[models/LineItem.js]
module.exports = Sequelize.define('LineItem', {properties...methods...etc});
</code></pre>
<p>and then anywhere we want to access our models, we'd be able to grab <code>Sequelize.models.Order</code> or even generically <code>Sequelize.models[type]</code>.</p>
<p>This is the sort of typical parent-child OOP interface that I'd know how to handle in PHP via interfaces and an app-wide class registry or factory of "commands" for a given domain. In node it's a little less clear how to get this with less boilerplate code, and I seem to run into this problem often. Here's what I have working now, simplified for clarity:</p>
<p><strong>app.js</strong></p>
<pre><code>// Configure handlers.
const handlers = require(path.join(__dirname, 'handler/index.js'));
exports.lambda = async (event, context) => {
...
// Parse message.
const msg = JSON.parse(event.Records[0].body);
// Get handler.
const handler = handlers.get(msg.type);
if (!handler) throw new Error(`Unknown type ${msg.type}.`);
// Run handler.
await handler.handle(msg, emailParams, vars);
...
};
</code></pre>
<p><strong>handler/index.js</strong></p>
<pre><code>const fs = require('fs');
const path = require('path');
module.exports = new Map();
fs.readdirSync(path.join(__dirname)).forEach(file => {
if (file !== 'index.js') {
const handler = require(path.join(__dirname, file));
module.exports.set(handler.type, handler);
}
});
</code></pre>
<p><strong>handler/SendInvoice.js</strong> (one example of a "handler")</p>
<pre><code>module.exports = {
type: 'SEND_INVOICE',
handle: async (msg, emailParams, vars) => {
// Configure email.
emailParams.Destination.ToAddresses = [msg.email];
emailParams.Message.Subject.Data = `Invoice #${msg.invoiceNum}`;
// Set variables.
vars.email = msg.email;
vars.invoiceNum = msg.invoiceNum;
vars.salespersonName = msg.salespersonName;
vars.salespersonEmail = msg.salespersonEmail;
},
tpl: `
<mjml>
<mj-body background-color="#ffffff">
<mj-section>
<mj-column>
...msg content...
</mj-column>
</mj-section>
</mj-body>
</mjml>
`,
};
</code></pre>
<p>I'm bothered that I seem to have to re-invent this quite often, and that I don't have a clear picture of the "best" way to implement. Do I module.export a definition? Or should the module be responsible for registering itself? I could extend the prototype of a parent "handler" class (or use ES6 classes) but that doesn't give me a <em>registry</em> of commands to pull from. If it does register itself, can I lazy-load it the way I can PHP classes or must I write boilerplate code to load all files in a folder everywhere I do this kind of thing? I suppose this is the command pattern, but the question remains of where/how to store the registry of commands in javascript? </p>
<p>You can see I'm perplexed. Thanks for any insight and clarity!</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T16:47:01.693",
"Id": "241150",
"Score": "1",
"Tags": [
"javascript",
"node.js"
],
"Title": "Registering all functions that implement an interface and allowing a passed-in context to invoke the applicable function (command)"
}
|
241150
|
<p>I am writing code for the <a href="https://www.hackerrank.com/challenges/ctci-ice-cream-parlor/problem?h_l=interview&isFullScreen=false&playlist_slugs%5B%5D%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D%5B%5D=search" rel="nofollow noreferrer">challenge given here</a> . Below the text:</p>
<blockquote>
<p>Each time Sunny and Johnny take a trip to the Ice Cream Parlor, they
pool their money to buy ice cream. On any given day, the parlor offers
a line of flavors. Each flavor has a cost associated with it. Given the value of and the of each flavor for trips to the Ice Cream
Parlor, help Sunny and Johnny choose two distinct flavors such that
they spend their entire pool of money during each visit. ID numbers
are the 1- based index number associated with a cost. For each trip to the parlor, print the ID numbers for the two types
of ice cream that Sunny and Johnny purchase as two space-separated
integers on a new line. You must print the smaller ID first and the
larger ID second.</p>
<p>For example, there are flavors having cost = [2, 1, 3, 5, 6]. Together they have money = 5 to spend.
They would purchase flavor ID's 1 and 3 for a cost of 2 + 3 = 5 . Use 1 based indexing
for your response.</p>
</blockquote>
<p>I have written code for the problem. However, it is running for most of the test cases except three. The error message that they show is that "Your code did not execute within the time limits". Apparently the code needs to be optimized. Can anyone please tell how may I do that?</p>
<pre><code>import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
// Complete the whatFlavors function below.
static void whatFlavors(int[] cost, int money) {
int baseItem=0, comparedItem = 0,totalAmount=0, chosenFlavour1=0,
chosenFlavour2=0,flag=0;
for(int i = 0 ; i<(cost.length-1); i++)
{
baseItem = cost[i];
for(int j = (i+1); j< (cost.length);j++)
{
comparedItem= cost[j];
totalAmount = baseItem + comparedItem;
if(totalAmount == money)
{
chosenFlavour1 = i;
chosenFlavour2 = j;
flag = 1;
break;
}
}
if(flag == 1)
{
break;
}
}
chosenFlavour1++;
chosenFlavour2++;
System.out.println(chosenFlavour1+" "+chosenFlavour2);
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int t = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int tItr = 0; tItr < t; tItr++) {
int money = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
int n = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
int[] cost = new int[n];
String[] costItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int i = 0; i < n; i++) {
int costItem = Integer.parseInt(costItems[i]);
cost[i] = costItem;
}
whatFlavors(cost, money);
}
scanner.close();
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T19:01:57.150",
"Id": "473191",
"Score": "2",
"body": "Hint: this problem is in the _Hash Map_ section."
}
] |
[
{
"body": "<p>Your algorithm is slow in some cases because of the time complexity <code>O(n^2)</code>. (starting the second loop from <code>i+1</code> makes it twice faster than starting from 0, but it doesn't change the time complexity which has much greater impact on performance)</p>\n\n<p>To improve your time complexity you need to reduce the amount of times you look at items in the array. One way of doing it is by first sorting it (more precisely, sorting index-value pairs to keep record of the original indexing) and then iterating over the sorted array once (<code>O(n)</code>) while taking advantage of the fact that it is sorted. I'll leave you the task of learning about integer sorting algorithms (of time complexity <code>O(n log n)</code>), and only explain how to use the sorted array to find the final answer.</p>\n\n<p>You can look at both edges of the array (smallest and biggest number), if their sum is too small you can increase it by advancing the lower-edge index to look at a bigger number, and if the sum is too big you can decrease it by advancing the higher-edge index to look at a smaller number. Repeat it until you reach the needed sum, then get the original indices and increment them to get the IDs you need for the output.</p>\n\n<p>As @vnp hinted, there is a better solution than mine (with time complexity <code>O(n)</code>) using a hash table.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T18:56:06.707",
"Id": "473190",
"Score": "1",
"body": "It is a bit simplistic. After sorting, the original indexing is lost. You need to sort `cost, index` tuples."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T19:02:07.713",
"Id": "473192",
"Score": "0",
"body": "@vnp good point, thanks for pointing it out!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T18:40:03.400",
"Id": "241157",
"ParentId": "241152",
"Score": "2"
}
},
{
"body": "<p>As @vnp's comments suggested, the solution requires the use of a <code>Map</code> to store the <code>cost, index</code> tuples. Substantially you have to iterate over your <code>costs</code> array and for every <code>cost</code> element check if one <code>key</code> in your map satisfies the condition <code>key = money - cost</code>. If the condition is satisfied you will print the two indexes, otherwise you will add the touple <code>cost, index</code> to your map.\nBelow my code that passed all hackerrank tests:</p>\n\n<pre><code>public static void whatFlavors(int[] costs, int money) {\n Map<Integer, Integer> map = new HashMap<>();\n for (int i = 0; i < costs.length; ++i) {\n int index = i + 1;\n int cost = costs[i];\n int key = money - cost;\n if (map.containsKey(key)) {\n System.out.format(\"%d %d\\n\", map.get(key), index);\n return;\n }\n map.put(cost, index);\n }\n}\n</code></pre>\n\n<p>I would have prefer to have a function returning the two indexes array and print them outside in the main program, but as expected any modification of the function signature will fail the tests.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T09:46:46.247",
"Id": "241184",
"ParentId": "241152",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T17:36:45.623",
"Id": "241152",
"Score": "3",
"Tags": [
"java",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Which products should be purchased with the given amount of money: Hackerrank?"
}
|
241152
|
<p>I'm working on a function that takes in a NumPy array containing only mutually distinct positive square numbers. I want the function to pick an element at random, find if there is a lower positive square number than the number selected: (1) if there is, return the array with the lower positive square number in place of the original element (2) if there isn't, return a copy of the original array.</p>
<p>The reason I'm developing this function is to create a <a href="https://en.wikipedia.org/wiki/Simulated_annealing" rel="nofollow noreferrer">simulated annealing</a> solution to the <a href="https://puzzling.stackexchange.com/questions/23944/unsolved-mysteries-magic-square-of-squares">Magic Square of Squares Puzzle</a>, and this function would serve as one of the <em>mutations</em> to the candidate solution.</p>
<p>I've had a go at the implementation:</p>
<pre class="lang-py prettyprint-override"><code>def last_square(x):
xcopy = x.copy()
index_1 = np.random.randint(0, x.shape[0]), np.random.randint(0, x.shape[1])
c = x[index_1]-1
while np.sqrt(c) != int(np.sqrt(c)) or c in set(x.flatten()):
if c < 2:
return xcopy
else:
c -= 1
x[index_1] = c
return x
</code></pre>
<p>Will my function always have the behaviour I've specified?</p>
<h1>Edit 1</h1>
<p>I've been asked some clarifying questions that I'll address here. There were very helpful in getting me to see what else I still had to explain.</p>
<p><strong>Why are you iterating through all possible numbers less than the chosen one, instead of just iterating through the array itself?</strong></p>
<p>I am looking for the next smallest positive square number below the one that was randomly selected from the array that is <em>not</em> in the array.</p>
<p><strong>Why do you care about <code>sqrt</code> in <code>last_square</code> at all? Taking the square root of the elements will not change their ordering.</strong></p>
<p>I agree that removing the square too that not change the ordering of the the square numbers currently within the array, nor does it change the position of a candidate square number <code>c</code> among all positive square numbers.</p>
<p>I care about checking if <code>np.sqrt(c) != int(np.sqrt(c))</code> because a number whose square root is an integer is a square number.</p>
<p><strong>Do you care whether the lower number is chosen non-deterministically? What should happen if there is more than one lower number? Currently it looks like you've implemented a lookup for the next lowest number closest to the chosen number, which is not what you described in the question.</strong></p>
<p>The randomized selection of an element in the array is of course random, but taking that element being chosen, I'm aiming for the rest of the behaviour of the function to be deterministic. That is to say, given the array and the randomly selected element, then the function will always give the same return.</p>
<p>I want to preserve the mutual distinctness of the positive square numbers within the array, so my goal is to find the next lowest positive square number that is not in the array. I was trying to acheive this by inclusively disjoining <code>c in set(x.flatten())</code> to the header of the loop, thereby keeping the loop going when <code>c</code> is still a number within the array. </p>
<p><strong>As written, if you find a lower number and copy it to the chosen location, your claim that the array's elements are mutually distinct will be violated.</strong></p>
<p>Using the following </p>
<pre><code>if c < 2:
return xcopy
else:
c -= 1
</code></pre>
<p>I am checking if <code>c</code> has gone too low, in which case I return a copy of the original array. If I break from the loop, the following lines will change the original array and return the array with the substitution completed.</p>
<pre><code>x[index_1] = c
return x
</code></pre>
<p>I think what I am having trouble with in part may be when calling <code>np.sqrt</code> on <code>c</code> without checking if <code>c</code> is non-negative. I'll work on correcting that and editing the code when I've resolved that issue.</p>
<p>Let me know if there are further questions. I'm happy to clarify.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T20:35:52.347",
"Id": "473208",
"Score": "0",
"body": "I added the reason why I'm making this function. Does that give enough context to my question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T20:38:58.667",
"Id": "473209",
"Score": "0",
"body": "It's helpful. If you can show more of your simulated annealing code you will get better feedback."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T20:41:50.527",
"Id": "473212",
"Score": "0",
"body": "Is `x` guaranteed to be a two-dimensional `ndarray`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T20:42:39.117",
"Id": "473213",
"Score": "0",
"body": "Ok, I'll think on which parts would be best to include."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T20:42:57.687",
"Id": "473214",
"Score": "0",
"body": "Yes, always a 2D numpy array."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T20:44:10.497",
"Id": "473215",
"Score": "0",
"body": "Always the same shape too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T21:24:24.113",
"Id": "473217",
"Score": "0",
"body": "Nuts. I just got a ```ValueError: cannot convert float NaN to integer``` traced back to ```while np.sqrt(c) != int(np.sqrt(c)) or c in set(x.flatten()):```"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T21:26:06.703",
"Id": "473218",
"Score": "0",
"body": "If you can solve this issue yourself, please do so and then update the code in your question. If not, you need to solve it on StackOverflow before posting on CodeReview."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T21:26:15.727",
"Id": "473219",
"Score": "0",
"body": "Also just saw ```RuntimeWarning: invalid value encountered in sqrt``` traced back to ```while np.sqrt(c) != int(np.sqrt(c)) or c in set(x.flatten()):```"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T21:26:38.207",
"Id": "473220",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/107159/discussion-between-reinderien-and-galen)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T21:26:40.670",
"Id": "473221",
"Score": "0",
"body": "Okay, I'll get back to this post when I've sorted out the errors. Thanks."
}
] |
[
{
"body": "<p>This is much more clear thanks to your edit.</p>\n\n<p>Why do you store this as a list of squares? Can you store it as a unique list of positive integers, and square them later? That would make this massively simpler.</p>\n\n<p>Another thing that would make this massively simpler is if you're able to guarantee that the list is maintained in some kind of order. In the example code below I do not assume this, so have to sort it myself. Maintaining order should be easy because the <code>last_square</code> mutation will not change order.</p>\n\n<blockquote>\n <p>Will my function always have the behaviour I've specified?</p>\n</blockquote>\n\n<p>Sounds like you need to write some unit tests :) You will have to mock your random function to make them predictable.</p>\n\n<blockquote>\n <p>I care about checking if <code>np.sqrt(c) != int(np.sqrt(c))</code> because a number whose square root is an integer is a square number.</p>\n</blockquote>\n\n<p>Fine, but... you said that there was already a guarantee that these numbers are positive squares.</p>\n\n<p>I tried to put together a vectorized version of this that does not loop. Rule number one when writing efficient Numpy code is to attempt to avoid loops. This solution roots, flattens and sorts the data, then looks for the closest gap. I do not know if it will perform better than yours, nor whether this is the most efficient implementation of this approach.</p>\n\n<p>The performance will be influenced by the length of your data and the sparsity of your numbers. For highly sparse numbers the looping approach will probably do better. For highly dense numbers the approach below will probably do better.</p>\n\n<pre><code>def last_square_new(x):\n assert (x > 0).all()\n x = x.copy()\n\n # The n-dimensional random index. Cannot yet be used as an index.\n nd_index = np.random.default_rng().integers(\n np.zeros(x.ndim), x.shape\n )\n # What will the index of the chosen element be once the array is flattened?\n flat_index = nd_index[0]*x.shape[-1] + nd_index[1]\n # Make this usable as an index.\n nd_index = nd_index[:, np.newaxis].tolist()\n\n xsq = (np.sqrt(x) + 0.5).astype(np.uint64) # Sqrt with safe conversion to int\n chosen = xsq[nd_index][0] # The randomly chosen element's sqrt\n xsq = xsq.flatten() # Flatten the root array\n s_indices = xsq.argsort() # Indices that would sort the root array\n flat_index = s_indices[s_indices][flat_index] # Move the flat index to its sorted position\n xsq = xsq[s_indices][:flat_index+1] # Sort the root array and truncate\n\n d_indices = np.arange(xsq.size-1)[np.diff(xsq) > 1] # Which indices have gaps?\n if d_indices.size != 0: # Are there any gaps?\n gap_index = d_indices[-1] # Index of the closest gap (low side)\n best = xsq[gap_index+1] - 1 # Best missing root\n x[nd_index] = best**2 # Assign it to the output\n\n return x\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T22:55:32.040",
"Id": "241167",
"ParentId": "241156",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T18:37:44.590",
"Id": "241156",
"Score": "4",
"Tags": [
"python",
"array",
"random",
"numpy",
"mathematics"
],
"Title": "Simulated annealing for magic square-of-squares puzzle"
}
|
241156
|
<p><strong>The Question:</strong></p>
<p>Steve has a string of lowercase characters in range ascii[‘a’..’z’]. He wants to reduce the string to its shortest length by doing a series of operations. In each operation he selects a pair of adjacent lowercase letters that match, and he deletes them. For instance, the string aab could be shortened to b in one operation.</p>
<p>Steve’s task is to delete as many characters as possible using this method and print the resulting string. If the final string is empty, print Empty String</p>
<p><strong>Test Case 1 : <code>aaabccddd</code>
output 1 : <code>abd</code></strong></p>
<p><strong>Test Case 2 : <code>baab</code>
output 2 : <code>Empty String</code></strong></p>
<p><strong>My Approach:</strong></p>
<pre><code>def check(s):
for i in range(len(s)-1):
if(s[i] == s[i+1]):
return(False)
return(True)
def remove(s):
if(check(s)):
return(s)
else:
for i in range(len(s)-1):
if(s[i] == s[i+1]):
if(i+2 < len(s)):
return(remove(s[0:i]+s[i+2:]))
else:
return(remove(s[0:i]))
s=list(input())
s2=remove(s)
if(len(s2)>0):
print(''.join(s2))
else:
print('Empty String')
</code></pre>
<p><strong><em>But I am confused how to make an iterative approach of this problem.Can anyone help me?</em></strong></p>
<p><a href="https://www.hackerrank.com/challenges/reduced-string/problem" rel="nofollow noreferrer">Question Link</a></p>
|
[] |
[
{
"body": "<ul>\n<li><p>First thing first, <code>check</code> is a waste of time.</p></li>\n<li><p>Why bother with</p>\n\n<pre><code> else:\n return(remove(s[0:i]))\n</code></pre>\n\n<p>The new pair suitable for removal may emerge only when you remove something from the midst of the string. When you remove the last two characters, it is not possible, and the entire string is already inspected. Just <code>return s[0:i]</code>.</p></li>\n<li><p>Now with the small rearrangement we have</p>\n\n<pre><code>def remove(s):\n for i in range(len(s)-1):\n if(s[i] == s[i+1]):\n if(i+2 == len(s)):\n return s[0:i]\n return remove(s[0:i]+s[i+2:])\n</code></pre>\n\n<p>You may notice that even though the recursive call is made in the loop, it is done only once: <code>return</code> will prevent the further looping. Let's make it explicit:</p>\n\n<pre><code>def remove(s):\n if len(s < 2):\n return s\n for i in range(len(s)-1):\n if(s[i] == s[i+1]):\n break\n if i == len(s):\n return s\n if(i+2 == len(s)):\n return s[0:i]\n return remove(s[0:i]+s[i+2:])\n</code></pre>\n\n<p>Now we have a tail recursive call. It translates to the iterations quite mechanically. The tail recursive form</p>\n\n<pre><code>def foo_recursive(x):\n if condition(x):\n return something(x)\n x = modify_argument(x)\n return foo_recursive(x)\n</code></pre>\n\n<p>is equivalent to</p>\n\n<pre><code>def foo_iterative(x):\n while !condition(x):\n x = modify_argument(x)\n return something(x)\n</code></pre>\n\n<p>Try to apply this recipe.</p>\n\n<p>PS: I am not saying that the result is the best (that is the most performant) solution. In fact, there is a better algorithm: after a removal of a pair, do not reinspect the string from the very beginning.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T19:49:59.817",
"Id": "241162",
"ParentId": "241159",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T19:04:43.250",
"Id": "241159",
"Score": "-3",
"Tags": [
"python-3.x",
"strings",
"recursion",
"iteration"
],
"Title": "How to convert Recursive Approach to iterative one(Super Reduced String)?"
}
|
241159
|
<pre><code>class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
</code></pre>
<blockquote>
<pre><code>def insert(self, data):
self.head = self.insertHelper(self.head, data)
def insertHelper(self, head, data):
if(head == None):
return Node(data)
else:
head.next = self.insertHelper(head.next, data)
return head
</code></pre>
<p>or</p>
<pre><code>def insertR(self, data):
self.insertRHelper(self.head, data)
def insertRHelper(self, head, data):
if(head == None):
self.head = Node(data)
elif(head.next == None):
head.next = Node(data)
else:
self.insertRHelper(head.next, data)
</code></pre>
</blockquote>
<p>Any reason why one of these implementations would be better? Personally think the insertR version is easier to look at.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T19:58:01.107",
"Id": "473197",
"Score": "5",
"body": "Welcome to Code Review. Did you write both?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T20:17:12.240",
"Id": "473203",
"Score": "0",
"body": "insertR() is purely mine. insert() was inspired by geeksforgeeks."
}
] |
[
{
"body": "<p>Both of these implementations are bad.</p>\n\n<p>The first is probably worse.</p>\n\n<ul>\n<li>every node in the linked list, from <code>self.head</code> to the last node's <code>head.next</code> is unconditionally written to, which makes every cache-line/cache-page/virtual-memory-page the linked list touches \"dirty\" and need to be flushed/written.</li>\n<li><code>self.head</code> is passed to <code>insertHelper()</code>, which recursively calls itself N times, eventually (assuming N > 1) returning the value that it was given <code>self.head</code>, to be stored back into the <code>self.head</code> member. This is a LONG critical section. If any threading support was added, locks would need to be held way longer than necessary.</li>\n</ul>\n\n<h1>Recursion</h1>\n\n<p>Both use recursion, and Python <a href=\"https://stackoverflow.com/a/13592002/3690024\">does not do tail-call-optimization</a>. This means that if your linked-list is very long, you will get a stack overflow. There are <a href=\"https://stackoverflow.com/a/18506625/3690024\">manual ways</a> to make your function behave in a tail-call-optimized fashion, even if Python won't do it for you, but they are complex and it is by far simpler to just use a loop.</p>\n\n<h1>PEP-8</h1>\n\n<ul>\n<li>Both <code>insertHelper</code> and <code>insertRHelper</code> are helper functions, which should not be exposed a public methods. They should begin with a leading underscore to indicate they are not part of the public interface.</li>\n<li>The members <code>next</code>, <code>head</code>, and probably <code>data</code> should also not be public, so should be named with a leading underscore.</li>\n<li>Classes are named using <code>BumpyWords</code>; functions, members and variables should all be <code>snake_case</code>. These means <code>insertHelper</code> should be named <code>_insert_helper</code>, and so on.</li>\n<li><code>if(...):</code> is not Pythonic. The parenthesis are unnecessary.</li>\n</ul>\n\n<h1>Tail</h1>\n\n<p>The best solution would be to maintain a <code>._tail</code> member in the <code>LinkedList</code>:</p>\n\n<pre><code>class LinkedList:\n \"\"\"Description of class here\"\"\"\n\n def __init__(self):\n self._head = None\n self._tail = None\n\n def insert(self, data: Node) -> None:\n \"\"\"Description of the insert function here\"\"\"\n\n if self._tail:\n self._tail._next = Node(data)\n self._tail = self._tail._next\n else:\n self._head = self._tail = Node(data)\n</code></pre>\n\n<p>Now, insertions at the tail of the <code>LinkedList</code> are <span class=\"math-container\">\\$O(1)\\$</span>.</p>\n\n<h1>Naming</h1>\n\n<p>As mentioned by <a href=\"https://codereview.stackexchange.com/users/8999/matthieu-m\">Matthieu M.</a> in the comments:</p>\n\n<blockquote>\n <p>I would also consider <em>renaming</em> here: <code>insert</code> should be <code>append</code>, to make it clear where the insert occurs, and offer a path to proposing different insertions such as <code>prepend</code>, or <code>insert</code> with an index. </p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T08:06:26.953",
"Id": "473242",
"Score": "2",
"body": "I think you forgot to update `self._tail` in the case where it already exists."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T14:35:56.713",
"Id": "473265",
"Score": "0",
"body": "@ovs Good catch. Fixed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T15:20:34.040",
"Id": "473272",
"Score": "4",
"body": "I would also consider _renaming_ here: `insert` should be `append`, to make it clear where the insert occur, and offer a path to proposing different insertions such as `prepend`, or `insert` with an index."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T18:02:23.550",
"Id": "473299",
"Score": "0",
"body": "@AJNeufeld: I'd honestly prefer if you added it to your answer. I find reading a bunch of short disconnected answer less interesting as the ordering by vote is just not as good as one well-structured answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T00:15:46.140",
"Id": "473336",
"Score": "0",
"body": "Not that I think you’re wrong, but sources or data to back the claim on cache lines would be useful here. There’s enough layers between python code and cpu execution that knowing that off-hand is, well, dubious"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T22:15:53.633",
"Id": "241166",
"ParentId": "241161",
"Score": "15"
}
}
] |
{
"AcceptedAnswerId": "241166",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T19:40:05.270",
"Id": "241161",
"Score": "6",
"Tags": [
"python",
"linked-list",
"comparative-review"
],
"Title": "Recursive LinkedList. Which implementation is better and why?"
}
|
241161
|
<p>Sometimes I have the need to call an async function from a non-async function and get the result back synchronously. Therefore I wrote the following helper function to be able to do this in one line.</p>
<pre><code>public static T RunSync<T>(Func<Task<T>> taskConstructor)
{
var signal = new ManualResetEventSlim();
T result;
Exception ex = null;
ThreadPool.QueueUserWorkItem(async () =>
{
try
{
var task = taskConstructor();
result = await task.ConfigureAwait(false);
}
catch (Exception iex)
{
ex = iex;
}
finally
{
signal.Set();
}
});
signal.Wait();
if (ex != null)
throw ex;
return result;
}
</code></pre>
<p>Is this ok to do or will it behave unexpectedly in some edge cases? I know that writing this kind of async functions in can be tricky and can easily deadlock. That's why I ran it inside a ThreadPool thread which should prevent any kind of deadlock.</p>
<p>I think that this is probably not the most performant way to do it, but preventing deadlocks is more important in my case.</p>
<p>I know that re-throwing an exception is not ideal, but I think this is a compromise I have to make here.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T09:17:19.250",
"Id": "473246",
"Score": "2",
"body": "Does it have any benefit over just doing task.ConfigureAwait(false)\n .GetAwaiter()\n .GetResult();"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-26T19:45:41.773",
"Id": "473412",
"Score": "0",
"body": "@Anders Good question actually. I think it does. I think your version may deadlock if the task does not use ´ConfigureAwait(false)´ internally."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T15:07:19.177",
"Id": "473504",
"Score": "1",
"body": "[This article](https://devblogs.microsoft.com/pfxteam/should-i-expose-synchronous-wrappers-for-asynchronous-methods/) shows why code such at this is a bad idea in general."
}
] |
[
{
"body": "<pre><code>public static class TaskExtensions\n{\n private static readonly TaskFactory TaskFactory = new TaskFactory(\n CancellationToken.None, \n TaskCreationOptions.None, \n TaskContinuationOptions.None, \n TaskScheduler.Default);\n\n public static TResult RunSync<TResult>(this Func<Task<TResult>> asyncFunc)\n => TaskFactory\n .StartNew(asyncFunc)\n .Unwrap()\n .GetAwaiter()\n .GetResult();\n\n public static void RunSync(this Func<Task> asyncAction)\n => TaskFactory\n .StartNew(asyncAction)\n .Unwrap()\n .GetAwaiter()\n .GetResult();\n}\n</code></pre>\n\n<p>There are several things that worth mentioning: </p>\n\n<ul>\n<li>Async methods were designed to be used all the way. So, if you call an async I/O operation in the bottom layer then it should be be called in an async fashion till the top layer.</li>\n<li>Async operations are sensitive for <code>Exception</code>s. They can behave differently based on how you call them. (They can be swallowed, thrown as an <code>AggregateException</code> or thrown normally. Here the <code>UnWrap</code> + <code>GetAwaiter</code> do the magic for us to be able to handle the exception normally. </li>\n<li>In order to avoid deadlocks the async operation is passed to an other Task, that is where <code>TaskFactory.StartNew</code> comes into play. </li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-12T12:30:56.530",
"Id": "242131",
"ParentId": "241163",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T19:54:26.910",
"Id": "241163",
"Score": "3",
"Tags": [
"c#",
"thread-safety",
"async-await"
],
"Title": "Running an async function synchronously"
}
|
241163
|
<p>This is an <code>echo</code> program with no runtime or standard library. It's meant to be compiled with <code>-nostdlib</code> on an amd64 Linux system.</p>
<pre><code>static signed long mywrite(int fd, const void *buf, unsigned long count) {
signed long retval;
__asm__ __volatile__(
"syscall" :
"=a" (retval) :
"a" (1), "D" (fd), "S" (buf), "d" (count) :
"rcx", "r11", "memory"
);
return retval;
}
static void myexit(int status) __attribute__((__noreturn__));
static void myexit(int status) {
__asm__ __volatile__(
"syscall" :
:
"a" (60), "D" (status) :
);
__builtin_unreachable();
}
static unsigned long mystrlen(const char *str) {
const char *pos = str;
while(*pos) ++pos;
return pos - str;
}
static void writearg(char *str, char end) {
unsigned long size = mystrlen(str) + 1;
unsigned long written = 0;
str[size - 1] = end;
do {
signed long result = mywrite(1, str + written, size - written);
if(result < 0) myexit(1);
written += result;
} while(written < size);
}
void _start(void) __attribute__((__naked__, __noreturn__));
void _start(void) {
__asm__(
"pop %rdi\n\t"
"mov %rsp, %rsi\n\t"
"jmp mymain"
);
}
static void mymain(int argc, char *argv[]) __attribute__((__noreturn__, __used__));
static void mymain(int argc, char *argv[]) {
if(argc <= 1) {
myexit(mywrite(1, "\n", 1) != 1);
}
int i;
for(i = 1; i < argc - 1; ++i) {
writearg(argv[i], ' ');
}
writearg(argv[i], '\n');
myexit(0);
}
</code></pre>
<p>Some of my concerns:</p>
<ul>
<li>Is my program's behavior fully compliant with <a href="https://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html" rel="nofollow noreferrer">the standard for <code>echo</code></a>?</li>
<li>Am I making any unwarranted assumptions that could make my code not work on a future release of Linux (or compiler)? In particular, are popping <code>argc</code> and the way I'm overwriting null terminators in <code>argv</code> values okay?</li>
<li>Since my code is Linux-on-amd64-only anyway, are there any other assumptions that I can make? For example, can I assume that Linux will always have continuous <code>argv</code> values, and so just make one big <code>write</code> call after swapping out all the nulls, instead of one per argument? (I know I'd still have to loop <code>write</code> in case of partial writes. I also know I could just copy the strings around myself, but I'd rather write them from where I got them.)</li>
<li>Instead of having <code>_start</code> as an assembly stub and my real code in <code>mymain</code>, is there any way I can put my real code in <code>_start</code> but still be able to safely get ahold of the command-line arguments?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T09:58:32.557",
"Id": "473247",
"Score": "0",
"body": "Why use `unsigned long` for pointer differences? Does Linux specify that? I'd expect `size_t` or `ptrdiff_t`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T14:15:38.233",
"Id": "473262",
"Score": "0",
"body": "@chux-ReinstateMonica Because I'd either have to `typedef` it myself, in which case there's no portability win, or `#include` a header from the standard library to get it, which defeats the purpose of what I did entirely."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T14:17:53.863",
"Id": "473263",
"Score": "0",
"body": "And I'm pretty sure the AMD64 ABI does specify that (not 100% sure about the signed-ness, but the result I'm getting is always both small and non-negative, so I don't think it matters)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T00:30:08.483",
"Id": "473437",
"Score": "0",
"body": "Please do not edit the question after it has been answered, especially please do not edit the code after the question has been answered https://codereview.stackexchange.com/help/someone-answers."
}
] |
[
{
"body": "<blockquote>\n <p>Is my program's behavior fully compliant with the standard for echo?</p>\n</blockquote>\n\n<p>Code does not process the string as in the <a href=\"https://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html\" rel=\"nofollow noreferrer\"><code>OPERANDS</code> section</a>. In particular:</p>\n\n<p>Code does not support <code>\\c</code>: \"Suppress the <code><newline></code> that otherwise follows the final argument in the output. ...\"</p>\n\n<blockquote>\n <p>Am I making any unwarranted assumptions that could make my code not work on a future release of Linux (or compiler)? In particular, are popping <code>argc</code> and the way I'm overwriting null terminators in <code>argv</code> values okay?</p>\n</blockquote>\n\n<p>I see no trouble with <code>argc</code>.</p>\n\n<p>Overwriting the null terminators in <code>argv</code> <a href=\"https://stackoverflow.com/q/25737434/2410359\">may/may not be OK</a>, but is not needed. I could foresee future restrictions. Alternative: write the <code>argv[i]</code> and then the separator.</p>\n\n<blockquote>\n <p>Other issues</p>\n</blockquote>\n\n<p>No comment.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T16:09:17.113",
"Id": "473276",
"Score": "0",
"body": "Isn't `\\c` an XSI requirement, not a POSIX requirement?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T16:14:38.787",
"Id": "473277",
"Score": "0",
"body": "@JosephSible-ReinstateMonica \"\\c is an XSI requirement\". Unknown how/if required in POSIX. Yet suppressing the \\n is useful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T16:48:33.040",
"Id": "473280",
"Score": "0",
"body": "Also, isn't the question you linked about modifying `argv[x]`, but I'm modifying `argv[x][y]`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T17:07:17.013",
"Id": "473287",
"Score": "1",
"body": "@JosephSible-ReinstateMonica That post delves into modifying `argc, argv, `argv[]` and `argv[][]`. As C says, \"strings pointed to by the `argv` array shall be modifiable by the program,\" so your approach looks OK for now. Since you asked about \"unwarranted assumptions that could make my code not work on a future release of Linux\", IMO, that is one of those dark corners of C that may disappear in the future."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T17:08:31.540",
"Id": "473288",
"Score": "0",
"body": "\"The standard says it's okay, but it might not stay okay since the standard might change\" seems like a slippery slope. Isn't that true of literally anything in the standard?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T17:16:35.833",
"Id": "473292",
"Score": "1",
"body": "@JosephSible-ReinstateMonica Yes. So use good engineering practices. Just because a corner of the language allows something, do you really want to go there? For future release concerns, staying toward the middle of the language is better. Your call."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T16:07:52.183",
"Id": "241197",
"ParentId": "241170",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-24T23:53:42.453",
"Id": "241170",
"Score": "5",
"Tags": [
"c",
"reinventing-the-wheel",
"linux",
"assembly",
"amd64"
],
"Title": "An echo program, mostly in C and completely from scratch"
}
|
241170
|
<p>I made a simple signup form using this <code>HTML</code>. Am I separating my code properly here or is there some code that I could remove/change?</p>
<p>The form looks good visually, but when I styled it with <code>CSS</code> I noticed a lot of stuff I had to repeat.</p>
<pre class="lang-html prettyprint-override"><code><body>
<form action="#" class="form">
<div class="img-overlay"></div>
<div class="icon"><i class="fas fa-times"></i></div>
<h1>Join our community of developers from all over the world</h1>
<div class="form-box">
<div class="email">
<label for="email">email</label>
<input id="email" type="email" placeholder="email" />
</div>
<div class="password">
<label for="password">password</label>
<input id="password" type="password" placeholder="password" />
</div>
<div class="password2">
<label for="password2">confirm password</label>
<input
id="password2"
type="password"
placeholder="confirm password"
/>
</div>
</div>
<input type="submit" class="button" value="Sign Up" />
<p>Already have an account</p>
</form>
</body>
</code></pre>
<p>Here is my CSS.<br/>
<strong>Is there a better way to style each form <code>input</code> and <code>label</code> without having to separately use <code>display: flex</code> each input like I did below?</strong></p>
<pre class="lang-css prettyprint-override"><code>.form {
background-image: linear-gradient(#1391ff, #0145ff);
width: 400px;
height: 600px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
border-radius: 16px;
padding: 120px 50px;
box-shadow: 2px 2px 8px #0000008f;
}
.img-overlay::before {
content: "";
background-image: url("https://cdn.pixabay.com/photo/2017/09/06/13/18/mosaic-2721424_960_720.jpg");
position: absolute;
/* transform: translate(-50%, -20%); */
left: 0;
top: 0;
opacity: 0.18;
width: 400px;
height: 600px;
border-radius: 16px;
z-index: -1;
}
.icon {
position: absolute;
top: 20px;
right: 20px;
color: rgba(255, 255, 255, 0.589);
}
.form h1 {
color: white;
font-size: 1rem;
text-align: left;
margin-bottom: 3rem;
}
.email {
display: flex;
flex-direction: column;
justify-content: center;
align-items: flex-start;
color: white;
margin-bottom: 1.5rem;
font-size: 0.7rem;
}
#email,
#email::placeholder {
width: 100%;
border: none;
background: none;
outline: none;
color: rgba(255, 255, 255, 0.582);
margin-top: 0.5rem;
font-size: 0.8rem;
padding-bottom: 0.5rem;
border-bottom: 1px solid rgb(231, 231, 231, 0.8);
}
.password {
display: flex;
flex-direction: column;
justify-content: center;
align-items: flex-start;
color: white;
margin-bottom: 1.5rem;
font-size: 0.7rem;
}
#password,
#password::placeholder {
width: 100%;
border: none;
background: none;
outline: none;
color: rgba(255, 255, 255, 0.582);
margin-top: 0.5rem;
font-size: 0.8rem;
padding-bottom: 0.5rem;
border-bottom: 1px solid rgb(231, 231, 231, 0.8);
}
.password2 {
display: flex;
flex-direction: column;
justify-content: center;
align-items: flex-start;
color: white;
margin-bottom: 2.5rem;
font-size: 0.7rem;
}
#password2,
#password2::placeholder {
width: 100%;
border: none;
background: none;
outline: none;
color: rgba(255, 255, 255, 0.582);
margin-top: 0.5rem;
font-size: 0.8rem;
padding-bottom: 0.5rem;
border-bottom: 1px solid rgb(231, 231, 231, 0.8);
}
.button {
width: 100%;
background: white;
border: none;
border-radius: 30px;
padding: 14px 14px;
font-size: 0.9rem;
margin-bottom: 1.5rem;
font-weight: 500;
text-transform: uppercase;
color: #0145ff;
outline: none;
}
.button:hover {
width: 100%;
background: transparent;
border: 2px solid #fff;
border-radius: 30px;
padding: 14px 14px;
font-size: 0.9rem;
margin-bottom: 1.5rem;
font-weight: 500;
text-transform: uppercase;
color: rgb(255, 255, 255);
transition: 0.3s ease-in-out;
outline: none;
cursor: pointer;
}
p {
color: rgba(255, 255, 255, 0.473);
font-size: 0.8rem;
}
</code></pre>
<p>I feel like I'm repeating a lot of code in the CSS, but I'm not sure if I am doing it properly even though my code creates the sign up form and everything looks good aesthetically. </p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T14:41:06.613",
"Id": "473266",
"Score": "0",
"body": "Is this all of your CSS?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T15:45:47.100",
"Id": "473275",
"Score": "2",
"body": "Yeah it's a small project"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T17:02:40.787",
"Id": "473283",
"Score": "0",
"body": "To be honest with you, there isn't a lot of code repetition here. About the only thing that repeats is the width and height for .form and .image-overlay. While many fields are repeating, their values are different. You might want to look into inheritance but their won't be much code reduction."
}
] |
[
{
"body": "<p>There were few places where you could have optimized your CSS:</p>\n\n<p>1) As all <code>inputs</code> were having the same style. Instead of declaring style for each <code>input</code> separately, you could have declared the global style on <code>input</code> only.</p>\n\n<p>2) As all <code>labels</code> were having the same style. You can just make a common class (I made <code>form-container</code> ) and put it on all rows and put the style in that.</p>\n\n<p>3) <code>Button</code> hover - only add that CSS which are getting change. Rest will be inherited from the parent <code>button</code> property</p>\n\n<p>Below is the optimized code.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.form {\n background-image: linear-gradient(#1391ff, #0145ff);\n width: 400px;\n height: 600px;\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n text-align: center;\n border-radius: 16px;\n padding: 120px 50px;\n box-shadow: 2px 2px 8px #0000008f;\n}\n\n.img-overlay::before {\n content: \"\";\n background-image: url(\"https://cdn.pixabay.com/photo/2017/09/06/13/18/mosaic-2721424_960_720.jpg\");\n position: absolute;\n /* transform: translate(-50%, -20%); */\n left: 0;\n top: 0;\n opacity: 0.18;\n width: 400px;\n height: 600px;\n border-radius: 16px;\n z-index: -1;\n}\n.icon {\n position: absolute;\n top: 20px;\n right: 20px;\n color: rgba(255, 255, 255, 0.589);\n}\n\n.form h1 {\n color: white;\n font-size: 1rem;\n text-align: left;\n margin-bottom: 3rem;\n}\n\n.form-container {\n display: flex;\n flex-direction: column;\n justify-content: center;\n align-items: flex-start;\n color: white;\n margin-bottom: 1.5rem;\n font-size: 0.7rem;\n}\n\ninput,\ninput::placeholder {\n width: 100%;\n border: none;\n background: none;\n outline: none;\n color: rgba(255, 255, 255, 0.582);\n margin-top: 0.5rem;\n font-size: 0.8rem;\n padding-bottom: 0.5rem;\n border-bottom: 1px solid rgb(231, 231, 231, 0.8);\n}\n\n.button {\n width: 100%;\n background: white;\n border: none;\n border-radius: 30px;\n padding: 14px 14px;\n font-size: 0.9rem;\n margin-bottom: 1.5rem;\n font-weight: 500;\n text-transform: uppercase;\n color: #0145ff;\n outline: none;\n}\n\n.button:hover {\n background: transparent;\n border: 2px solid #fff;\n color: rgb(255, 255, 255);\n transition: 0.3s ease-in-out;\n cursor: pointer;\n}\n\np {\n color: rgba(255, 255, 255, 0.473);\n font-size: 0.8rem;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><body>\n <form action=\"#\" class=\"form\">\n <div class=\"img-overlay\"></div>\n <div class=\"icon\"><i class=\"fas fa-times\"></i></div>\n <h1>Join our community of developers from all over the world</h1>\n <div class=\"form-box\">\n <div class=\"form-container\">\n <label for=\"email\">email</label>\n <input id=\"email\" type=\"email\" placeholder=\"email\" />\n </div>\n <div class=\"form-container\">\n <label for=\"password\">password</label>\n <input id=\"password\" type=\"password\" placeholder=\"password\" />\n </div>\n <div class=\"form-container\">\n <label for=\"password2\">confirm password</label>\n <input\n id=\"password\"\n type=\"password\"\n placeholder=\"confirm password\"\n />\n </div>\n </div>\n <input type=\"submit\" class=\"button\" value=\"Sign Up\" />\n <p>Already have an account</p>\n </form>\n </body></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-09T17:06:53.900",
"Id": "242010",
"ParentId": "241173",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T02:15:23.953",
"Id": "241173",
"Score": "1",
"Tags": [
"html",
"css"
],
"Title": "How do I refactor this signup form without using SASS?"
}
|
241173
|
<p>I implemented the following method to send IMAP commands to server and return the response to caller. Here, I'm not trying to parse the commands. Would like some advice on how I can improve the method (e.g. avoiding unnecessary copying) because I feel like I keep moving data between buffers and strings too much.</p>
<p>The other concern I have is about the size of the response. Right now, I'm returning a string. But this string can be potentially large (example fetch an email with a large email body or 100 email headers that contains subject, date and sender). In such a case, should I allocate <code>response</code> in the free-store and return a pointer to it or something like that? Thank you.</p>
<pre><code>std::string cmail::ImapClient::execute(const std::string &command)
{
std::stringstream ss;
ss << ++commandCounter << " " << command;
std::string cmd = ss.str();
spdlog::trace("C: " + cmd);
boost::system::error_code error;
boost::asio::write(socket, boost::asio::buffer(cmd.append("\r\n")), error);
if(error)
{
spdlog::error("Failed to dispatch command " + cmd + " because " + error.message());
return "";
}
boost::asio::streambuf buffer;
boost::asio::read_until(socket, buffer, '\n', error);
if(error)
{
spdlog::error("Failed to receive response for command " + cmd + " because " + error.message());
return "";
}
ss.str(std::string());
ss.clear();
std::istream is(&buffer);
std::string line;
while(std::getline(is, line))
{
ss << line << std::endl;
}
std::string response = ss.str();
if(spdlog::default_logger()->level() == spdlog::level::trace)
{
std::string s = response;
s.pop_back();
spdlog::trace("S: " + s);
}
return response;
}
</code></pre>
<p>Thank you for your effort and time, helping me.</p>
|
[] |
[
{
"body": "<p>The code looks fine. Instead of <code>const std::string &command</code>, you can take <code>std::string_view</code> command to avoid unnecessary allocation when the argument is not readily a <code>std::string</code> (e.g., string literals). <code>std::ostringstream</code> seems more appropriate than <code>std::stringstream</code> here, since you are not reading from it. Creating a new stream may also be more readable than reusing the stream.</p>\n\n<p>Prior to C++20, <a href=\"https://en.cppreference.com/w/cpp/io/basic_ostringstream/str\" rel=\"nofollow noreferrer\"><code>str</code></a> on string streams always make a copy of the buffer, so there isn't much you can do about it. Since C++20, you can move the underlying buffer by moving the string stream itself:</p>\n\n<pre><code>// since C++20\nstd::string response = std::move(ss).str();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T07:36:59.737",
"Id": "241180",
"ParentId": "241177",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "241180",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T03:38:34.183",
"Id": "241177",
"Score": "2",
"Tags": [
"c++"
],
"Title": "Writing to and reading from socket in an IMAP client"
}
|
241177
|
<p>I'm using the following lump of code to manage a 9.4gb dataset. I had to divide the dataset into multiple github repositories to be able to do this. I've explained what each block of code does.</p>
<pre><code>git_repo_tags = ['AB', 'C', 'DEF', 'G', 'HILMNO', 'PR', 'STW', 'X']
counter = 1
# Cloning the github repositories
print('Beginning cloning...')
for repo in git_repo_tags:
git.Git('.').clone('git://github.com/utility-repos/' + repo)
print('-\nCloning ' + repo)
#Removing the .git folder from each repo
shutil.rmtree(repo + '/.git')
print('--Removing the .git folder ' + str(counter) + '/8')
counter += 1
# Creating the Food-101/images directory and subdirectory if it doesn't already exist
if not os.path.exists('Food-101/images'):
os.makedirs('Food-101/images')
print('Created the Food-101/images')
# Going through the repo X and moving everything a branch up
for i in os.listdir('X'):
shutil.move(os.path.join('X', i), 'Food-101')
print('Moved important files to an upper branch')
# Going through the other repos and moving everything to Food-101/images
for directory in git_repo_tags:
for subdirectory in os.listdir(directory):
shutil.move(os.path.join(directory, subdirectory), 'Food-101/images')
print('Moving ' + subdirectory + ' to Food-101/images')
#After the above code is complete, moves all test images to the Food-101/test folder and renames them
print('\n-Beginning to separate the test dataset...')
if not os.path.exists('Food-101/test'):
os.makedirs('Food-101/test')
with open('Food-101/meta/test.txt') as test_file:
for line in test_file:
name_of_folder = line.split('/')[0]
name_of_file = line.split('/')[1].rstrip()
Path('Food-101/images/' + name_of_folder + '/' + name_of_file + '.jpg').rename('Food-101/test/' + name_of_folder + '_' + name_of_file + '.jpg')
print('--Moved Food-101/images/' + name_of_folder + '/' + name_of_file + '.jpg to Food-101/test/')
# Moves all training images to the Food-101/images directory and renames them
print('\n-Beginning to separate the training dataset...')
with open('Food-101/meta/train.txt') as train_file:
for line in train_file:
name_of_folder = line.split('/')[0]
name_of_file = line.split('/')[1].rstrip()
Path('Food-101/images/' + name_of_folder + '/' + name_of_file + '.jpg').rename('Food-101/images/' + name_of_folder + '_' + name_of_file + '.jpg')
print('--Moved Food-101/images/' + name_of_folder + '/' + name_of_file + '.jpg to Food-101/train/')
# Removes empty directories inside Food-101/images
with open('Food-101/meta/train.txt') as train_file:
for folder in train_file:
name_of_folder = folder.split('/')[0]
if os.path.exists('Food-101/images/' + name_of_folder):
shutil.rmtree('Food-101/images/' + name_of_folder)
# Removes empty directories
for dirs in git_repo_tags:
shutil.rmtree(dirs)
</code></pre>
<p>This code works but its a mess and I have too many repeats. What is a good way to clean this up? </p>
|
[] |
[
{
"body": "<h2>Enumerate</h2>\n\n<pre><code>counter = 1\nfor repo in git_repo_tags:\n # ...\n print('--Removing the .git folder ' + str(counter) + '/8')\n counter += 1\n</code></pre>\n\n<p>should be using <code>enumerate</code>:</p>\n\n<pre><code>for counter, repo in enumerate(git_repo_tags, start=1):\n</code></pre>\n\n<h2>String interpolation</h2>\n\n<pre><code>print('--Removing the .git folder ' + str(counter) + '/8')\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>print(f'--Removing the .git folder {counter}/{len(git_repo_tags)}')\n</code></pre>\n\n<p>The 8 should not be hard-coded.</p>\n\n<h2>Pathlib</h2>\n\n<p>For basically every one of your directory and file names, and many of your file operations (<code>rmtree</code> being an exception), you should consider using <code>pathlib.Path</code>. For instance, this:</p>\n\n<pre><code>if not os.path.exists('Food-101/images'):\n os.makedirs('Food-101/images')\n print('Created the Food-101/images')\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>image_path = Path('Food-101/images')\nif not image_path.exists():\n image_path.mkdir(parents=True)\n print(f'Created {image_path}')\n</code></pre>\n\n<h2>Path parsing</h2>\n\n<p>Rather than this:</p>\n\n<pre><code>name_of_folder = line.split('/')[0]\nname_of_file = line.split('/')[1].rstrip()\n</code></pre>\n\n<p>consider at least unpacking it, i.e.</p>\n\n<pre><code>folder_name, file_name = line.rsplit('/', 1)\n</code></pre>\n\n<p>But it's better to again use <code>pathlib</code>:</p>\n\n<pre><code>line_path = Path(line)\nfolder_name = line_path.parent\nfile_name = line_path.name\n</code></pre>\n\n<h2>Functions</h2>\n\n<p>Move logically-related chunks of code to subroutines for better legibility, maintainability, modularity, testability, etc.</p>\n\n<h2>Indentation</h2>\n\n<p>Use four spaces, which is more standard. You do this in some places but not others.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T17:14:45.340",
"Id": "241310",
"ParentId": "241179",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T05:07:12.310",
"Id": "241179",
"Score": "3",
"Tags": [
"python",
"git"
],
"Title": "How to manipulate directories using Python"
}
|
241179
|
<p>I have been trying to deal with this problem set, and I have figured out how to solve it as well. But there is one problem that is <code>Timeout error for some hidden cases, but no wrong answers</code></p>
<p><strong>PROBLEM STATEMENT</strong></p>
<p>In this challenge, a string and a list of intervals are given. The string consists of English letters only and it can contain both lowercase and uppercase letters.</p>
<p>For two different letters, we say that the first letter is greater than the second letter when the first letter comes later in the alphabet than the second letter ignoring the case of the letters. For example, the letter 'Z' and 't' are greater than the letters 'b' and 'G', while the letters 'B' andd 'b' are equal as case is not considered.</p>
<p>The task is the following. For each given interval, you need to find the count of the greatest letter occurring in the string in that interval, ignoring the case of the letters, so occurrences of, for example, a and A are occurrences of the same letter.</p>
<p>Consider, for example, for the string "AbaBacD". In the interval, [0, 4], the greatest letter is 'b' with count 2.</p>
<p><strong>Input Format</strong></p>
<p>The first line contains integer N, denoting the length of the input string.</p>
<p>The second line contains string S.</p>
<p>The third line contains an integer Q, denoting the number of intervals. Each line of the Q subsequent lines contains two space-separated integers xi and yi, denoting the beginning and the end of ith interval.</p>
<p><a href="https://i.stack.imgur.com/MpzeY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MpzeY.png" alt="Constraints"></a></p>
<p>Output Format</p>
<p>For each interval, print the count of the greatest letter occurring in the string in that interval.</p>
<p><a href="https://i.stack.imgur.com/Nk6QT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Nk6QT.png" alt="Sample Inputs"></a></p>
<p><a href="https://i.stack.imgur.com/XTRDI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XTRDI.png" alt="Explanation 1"></a></p>
<p><strong>My Algorithm</strong></p>
<pre><code>1. To lowercase the string
2. Loop through the queries array
3. Get the string from start interval to end interval
4. Find greatest char in the string
5. Count the occurrence, and add it to the array
6. Return the array
</code></pre>
<p><strong>My Code</strong></p>
<pre><code>def getMaxCharCount(s, queries):
# queries is a n x 2 array where queries[i][0] and queries[i][1] represents x[i] and y[i] for the ith query.
maxCount = []
finalWord = s.lower()
for interval in queries:
if interval[0] == interval[1]:
maxCount.append(1)
else:
string = finalWord[interval[0]:interval[1]+1]
maxCount.append(string.count(max(string)))
return maxCount
</code></pre>
<p>Any help would be appreciated</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T14:27:14.837",
"Id": "473264",
"Score": "0",
"body": "Where is this problem published?"
}
] |
[
{
"body": "<h1>PEP 8</h1>\n\n<p>The <a href=\"https://www.python.org/dev/peps/pep-0008/#naming-conventions\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a>’s naming conventions recommends again <code>mixedCase</code> identifiers. <code>CapWords</code> are for classes and types, <code>snake_case</code> is for functions, methods and variables. Thus, <code>getMaxCharCount</code>, <code>maxCount</code> and <code>finalWord</code> should be renamed to <code>get_max_char_count</code>, <code>max_count</code> and <code>final_word</code>.</p>\n\n<h1>string</h1>\n\n<p><code>string</code> is an importable module in Python. Its use as an identifier should be discouraged.</p>\n\n<h1>Intervals</h1>\n\n<p><code>interval</code> is a perfectly fine variable, but <code>interval[0]</code> and <code>interval[1]</code> are confusing. Are those the zeroth and first intervals in a list of intervals? It would be better to unpack the interval immediately into the starting and ending values of the interval. This can even be done directly by the <code>for</code> statement:</p>\n\n<pre><code> for start, end in queries:\n if start == end:\n ...\n</code></pre>\n\n<h1>Special Casing</h1>\n\n<p>You have special-cased the length 1 interval. Why? Does the general purpose version of the code not work for the length one interval? Is it too slow? Is the special-case a common occurrence, or does checking for it actually slow down the general purpose case be introducing an unnecessary <code>if</code> statement?</p>\n\n<h1>List Comprehension</h1>\n\n<p>If we remove the special-case, your code reads approximately:</p>\n\n<pre><code> max_count = []\n for start, end in queries:\n max_count.append(...)\n</code></pre>\n\n<p>This pattern is usually re-written using list-comprehension, since it is much faster than repeated calls to <code>.append()</code>:</p>\n\n<pre><code> max_count = [ ... for start, end in queries ]\n</code></pre>\n\n<p>The only issue is what should be used in place of <code>...</code>. Prior to Python 3.7, there was no easy way to refer to the result of a computation multiple times in one expression. Python 3.8 introduces the “walrus operator” (<code>:=</code>) which allows variables to be assigned inside of other expressions. We can use this to avoid referencing and slicing <code>final_word</code> twice:</p>\n\n<pre><code> max_count = [ (span := final_word[start:end+1]).count(max(span)) for start, end in queries ]\n</code></pre>\n\n<h1>Reworked Code (Python 3.8)</h1>\n\n<pre><code>def get_max_char_count(s, queries):\n final_word = s.lower()\n return [(span := final_word[start:end+1]).count(max(span)) for start, end in queries]\n</code></pre>\n\n<p>This code may be slightly faster than your original code, with the speed up mostly from replacing <code>.append</code> with list comprehension. To really see significant speed gains, you need to improve the algorithm.</p>\n\n<h1>Algorithmic Improvement</h1>\n\n<p>Since this is a coding challenge, I won’t give you code for the better algorithm, but I will get you started in the right direction.</p>\n\n<p>How many times are you looking at any given character of <code>final_word</code>?</p>\n\n<p>Consider the following test case:</p>\n\n<pre><code>2000\nAAAAAAAAAAA...[2000 A’s] ... AAAAAAAAAAAA\n2000\n0 1999\n0 1999\n0 1999\n : :\n[2000 duplicate lines]\n : :\n0 1999\n0 1999\n</code></pre>\n\n<p>The result should be a list of 2000 copies of the number 2000. We did this in our head. Your algorithm will test each character 4000 times; 2000 times during <code>max</code> and another 2000 times during <code>count</code>. Clearly, we’ve got room for improvement. The ideal would be if each character was only tested twice, once during <code>max</code>, and once during <code>count</code>. But how can we achieve this?</p>\n\n<p>Consider another test case:</p>\n\n<blockquote class=\"spoiler\">\n <p> 20<br>\n AAAABBBBCCCCBBBBCCCC<br>\n 3<br>\n 0 11<br>\n 4 15<br>\n 8 19 </p>\n</blockquote>\n\n<p>Can you see any way of computing intermediate results and reusing them?</p>\n\n<blockquote class=\"spoiler\">\n <p> Can you divide this into 5 subproblems? Can you combine the first 3 subproblems together to get the first answer? 4 A’s, 4 B’s and 4 C’s makes 4 C’s. Subproblems 2 to 4 to get the second answer? 4 B’s, 4 C’s and 4 B’s makes 4 C’s. Subproblems 3 to 5 to get the 3rd answer? 4 C’s, 4 B’s and 4 C’s makes 8 C’s. How would you store the subproblems results? Where did we get the boundaries of the subproblems?</p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T04:42:18.580",
"Id": "241288",
"ParentId": "241182",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T08:53:16.177",
"Id": "241182",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Maximal Char Requests in a String"
}
|
241182
|
<p>This code below is supposed to calculate the root of a function using bisection method. I am a newbie to Python, so I do not know how to raise errors. Also, I would like to have a general review on this algorithm design, where I could have optimised, utilised some tricks or any sort of improvements. I feel like I am really not using the full funcionality of Python somehow.</p>
<p>Any comments on how to write a succinct code is appreciated. Thanks. </p>
<pre><code>"""
Program to find root of a function using bisection method
"""
import sys
import math
def is_equal(a,b):
return abs(b-a) < sys.float_info.epsilon
def bisection(f, a, b, TOL=0.01, MAX_ITER=100):
"""
f is the cost function, [a,b] is the initial bracket,
TOL is tolerance, MAX_ITER is maximum iteration.
"""
f_a = f(a)
f_b = f(b)
iter = 0
while iter < MAX_ITER:
c = (a+b)/2
f_c = f(c)
if math.isclose(f_c,0.0,abs_tol=1.0E-6) or abs(b-a)/2<TOL:
return (c, iter)
else:
if f_a * f_c < 0:
b = c
f_b = f_c
else:
a = c
f_a = f_c
iter = iter + 1
return None
def func(x):
"""
The cost function: f(x) = cos(x) - x
"""
return math.cos(x) - x
root, iter = bisection(func, -1, 1, TOL=1.0E-6)
print("Iteration = ", iter)
print("root = ", root, ", func(x) = ", func(root))
</code></pre>
|
[] |
[
{
"body": "<h2>Type hints</h2>\n\n<p>They can help; an example:</p>\n\n<pre><code>def is_equal(a: float, b: float) -> bool:\n</code></pre>\n\n<p>The return type of <code>bisection</code> should probably be <code>Optional[float]</code>.</p>\n\n<h2>Argument format</h2>\n\n<p><code>MAX_ITER</code> and <code>TOL</code> should be lower-case because they are the arguments to a function, not a global constant.</p>\n\n<h2>Early-return</h2>\n\n<pre><code> return (c, iter)\n else:\n</code></pre>\n\n<p>does not need the <code>else</code>, so you can drop it.</p>\n\n<h2>In-place addition</h2>\n\n<pre><code> iter = iter + 1\n</code></pre>\n\n<p>can be</p>\n\n<pre><code> iter += 1\n</code></pre>\n\n<h2>Return parens</h2>\n\n<p>This does not need parentheses:</p>\n\n<pre><code> return (c, iter)\n</code></pre>\n\n<p>The tuple is implied.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T14:14:15.923",
"Id": "241190",
"ParentId": "241183",
"Score": "3"
}
},
{
"body": "<ul>\n<li><p>I don't see the point of passing <code>MAX_ITER</code>. Bisection is guaranteed to terminate in <span class=\"math-container\">\\$\\log \\dfrac{b - a}{TOL}\\$</span> iterations.</p></li>\n<li><p>I strongly advise against breaking the loop early at <code>math.isclose(f_c,0.0,abs_tol=1.0E-6)</code>. It only tells you that the value at <code>c</code> is close to <code>0</code>, but doesn't tell you <em>where</em> the root is (consider the case when the derivative at root is very small). After all, tolerance is passed for a reason!</p>\n\n<p>If you insist on early termination, at least return the <code>(a, b)</code> interval as well. The caller deserves to know the precision.</p></li>\n<li><p>You may want to do this test right before returning (like, is there a root at all):</p>\n\n<pre><code>if math.isclose(f_c,0.0,abs_tol=1.0E-6):\n return None\nreturn c\n</code></pre>\n\n<p>but I'd rather let the caller worry about that.</p></li>\n<li><p><code>abs</code> in <code>abs(b - a)</code> seems excessive.</p>\n\n<pre><code>if a > b:\n a, b = b, a\n</code></pre>\n\n<p>at the very beginning of <code>bisection</code> takes care of it once and forever.</p></li>\n<li><p><code>(a + b)</code> may overflow. <code>c = a + (b - a)/2</code> is more prudent.</p></li>\n<li><p>I don't see where <code>is_equal(a,b)</code> is ever used.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T19:25:24.247",
"Id": "241208",
"ParentId": "241183",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T08:57:07.180",
"Id": "241183",
"Score": "6",
"Tags": [
"python",
"performance",
"algorithm"
],
"Title": "Root finding using bisection method in Python"
}
|
241183
|
<p>I wanted to create an image compressor using Machine Learning and started work on an "AutoEncoder". This is a type of Neural Network which takes in the image and creates a compressed vector form.</p>
<p>It has two parts: encoder and decoder. <code>encoder</code> converts the images to vector form. <code>decoder</code> tries to re-create the image only from the vector created by the <em>encoder</em>.</p>
<p>This is how it looks like:</p>
<p><a href="https://i.stack.imgur.com/O9rKq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/O9rKq.png" alt="AutoEncoder"></a></p>
<p>I have made the <code>encoder</code> a stack of Convolutional layers along with some MaxPooling2D ones. However, there is just a tiny problem.</p>
<p>The model performs well on any Image but it can be significantly improved.</p>
<p>For starters, the encoding dimension is <strong>too high!</strong> Right now with my calculations, I am getting a compression of 5 Mb -> 5Kb which is <em>very</em> lossy as the compression factor becomes x1000.</p>
<pre><code> import os
import tensorflow as tf
from keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D
from keras.models import Model
from keras import backend as K
import numpy as np
from keras.callbacks import ModelCheckpoint
import matplotlib.pyplot as plt
images_dir = "/content/drive/My Drive/Images/" # /{}.jpg".format(i)
EPOCHS = 50
image_generator = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1./255)
train_data_gen = image_generator.flow_from_directory(directory=str(images_dir),
batch_size=1,
shuffle=False,
target_size=(600, 400),
class_mode='input')
#*****************************
# ENCODER STARTS HERE
#*****************************
input_img = Input(shape=(600, 400, 3)) # adapt this if using `channels_first` image data format
x = Conv2D(48, (3, 3), activation='relu', padding='same')(input_img)
x = MaxPooling2D((2, 2), padding='same')(x) #ALl filters are upped by 16 and kernel size of encoder is
x = Conv2D(80, (4, 4), activation='relu', padding='same')(x) # also upped by 1 and downed in decoder
x = MaxPooling2D((2, 2), padding='same')(x)
x = Conv2D(144, (4, 4), activation='relu', padding='same')(x)
encoded = MaxPooling2D((1, 1), padding='same')(x)
# *************************
# DECODER STARTS HERE
#****************************
x = Conv2D(48, (4, 4), activation='relu', padding='same')(encoded)
x = UpSampling2D((2, 2))(x)
x = Conv2D(64, (4, 4), activation='relu', padding='same')(x)
x = UpSampling2D((2, 2))(x)
x = Conv2D(64, (1, 1), activation='relu')(x) # DEfault = (2,2)
x = UpSampling2D((1, 1))(x) # Default = (2,2)
decoded = Conv2D(3, (3, 3), activation='sigmoid', padding='same')(x)
checkpoint_dir= "/content/drive/My Drive/Checkp_autoenc/"
checkpoint_prefix = os.path.join(checkpoint_dir, "ckpt_{epoch}")
checkpoint = ModelCheckpoint(filepath=checkpoint_prefix,
save_weights_only=True)
autoencoder = Model(input_img, decoded)
autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')
autoencoder.summary()
autoencoder.fit_generator(train_data_gen,
epochs=EPOCHS,
shuffle=True,
callbacks=[checkpoint])
decoded_imgs = autoencoder.predict(train_data_gen)
</code></pre>
<p>I had decided the filter and kernel values on a whim. But they can be adjusted to encompass more information so that the compression factor is reduced. As an example, here is what a sample image looks like:</p>
<p>As you can see clearly, this is very lossy and pixelated because the compression factor is really high. Also, the convolutional layers can also be flattened and the non-linearization function <code>ReLu</code> may be applied.</p>
<p>But I want some feedback from the experts to determine what areas are actually to be improved and what should be simply left alone. So I appreciate some constructive feedback and advice!</p>
<p><a href="https://i.stack.imgur.com/odS5z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/odS5z.png" alt="Very Lossy!"></a></p>
<p>After a lot of studying and research, I managed to change the model sufficiently enough to produce a picture of <em>significantly</em> better quality images. But can it still be improved? Keep in mind the compression is x1000 meaning Image has been compressed over a 1000.</p>
<p><a href="https://i.stack.imgur.com/l1sMu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l1sMu.png" alt="Improvement"></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-27T16:59:29.780",
"Id": "473515",
"Score": "0",
"body": "It appears that your indentation is incorrect at your `import`s at the top. Please fix this."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-25T11:20:33.600",
"Id": "241187",
"Score": "3",
"Tags": [
"python",
"image",
"machine-learning",
"compression",
"tensorflow"
],
"Title": "Doing image compression with Neural Network AutoEncoders"
}
|
241187
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.