body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>The task:</p>
<blockquote>
<p>Given a string which we can delete at most k, return whether you can
make a palindrome.</p>
<p>For example, given 'waterrfetawx' and a k of 2, you could delete f and
x to get 'waterretaw'.</p>
</blockquote>
<p>The following solution is partially inspired by <a href="https://codereview.stackexchange.com/a/216828/54442">@Oh My Goodness's answer</a>.</p>
<pre><code>const s = "waterrfetawx";
const del = 2;
function palindromePossible(str, deleteAtMost) {
const set = new Set();
for (let i = 0, len = str.length; i < len; i++) {
const char = str[i];
void(set.delete(char) || set.add(char)); // <--is this good code?
}
let iStart = 0, iEnd = str.length - 1, possibleDeletion = 0;
function isSame() {
do {
if (str[iStart] === str[iEnd]) {
iStart++;
iEnd--;
return true;
}
if (++possibleDeletion > deleteAtMost) { return false; }
if (set.has(str[iStart])) { iStart++; }
if (set.has(str[iEnd])) { iEnd--; }
if (iStart > iEnd) { return false; }
} while(str[iStart] !== str[iEnd]);
return true;
}
if (set.size <= deleteAtMost + 1) {
for (let i = 0, len = Math.floor(str.length/2); i < len && iStart <= iEnd; i++) {
if (!isSame()) { return false; }
}
return true;
}
return false;
}
console.log(palindromePossible(s, del));
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T19:22:56.043",
"Id": "419906",
"Score": "0",
"body": "I think you might have an off-by-1 error? `palindromePossible(\"waterrfetawx\", 1)` returns `true`. AKA shouldn't `deleteAtMost + 1` just be `deleteAtMost`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T19:26:53.050",
"Id": "419908",
"Score": "1",
"body": "You can re-order it like this `waterfretawx` and then delete the `x`. `waterfretaw` can the be read forward and backwards @Shelby115"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T19:27:50.280",
"Id": "419909",
"Score": "0",
"body": "Ah, wasn't aware that re-ordering it was an option."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T19:30:15.423",
"Id": "419910",
"Score": "0",
"body": "but good point. I will think of an algorithm that doesn't take re-ordering into consideration. @Shelby115"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T19:35:48.843",
"Id": "419912",
"Score": "1",
"body": "I think that allowing reordering is a bit of a cheat, especially if it is not mentioned in the task and the example lets you believe it isn't allowed. The given solutions don't work if it is not allowed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T13:56:49.523",
"Id": "420009",
"Score": "0",
"body": "@KIKOSoftware I think you are right on this. I updated the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T14:21:15.947",
"Id": "420013",
"Score": "0",
"body": "Ah, yes, that was more difficult, wasn't it? Now let's see if someone can improve on that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-05-21T03:35:04.897",
"Id": "476236",
"Score": "0",
"body": "Do we have this question in any of the OJ platforms like SPOJ, LeetCode, HackerRank, CodeForces etc ?"
}
] | [
{
"body": "<p>You have a question embedded in the code:</p>\n\n<blockquote>\n<pre><code>void(set.delete(char) || set.add(char)); // <--is this good code?\n</code></pre>\n</blockquote>\n\n<p>The <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void\" rel=\"nofollow noreferrer\">void operator</a> \"evaluates the given <em>expression</em> and then returns <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined\" rel=\"nofollow noreferrer\"><code>undefined</code></a>\"<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void\" rel=\"nofollow noreferrer\">1</a></sup>. It doesn't appear that there is a need to have <code>undefined</code> be the final value of that expression because that expression doesn't get assigned or returned. The <code>void()</code> can be removed without changing the functionality of the code. I wouldn't say it is bad code, but unnecessary. </p>\n\n<hr>\n\n<p>That <code>for</code> loop could be simplified:</p>\n\n<blockquote>\n<pre><code>for (let i = 0, len = str.length; i < len; i++) {\n const char = str[i];\n void(set.delete(char) || set.add(char)); // <--is this good code?\n}\n</code></pre>\n</blockquote>\n\n<p>using a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\"><code>for...of</code></a> loop:</p>\n\n<pre><code>for (const char of str) {\n set.delete(char) || set.add(char);\n}\n</code></pre>\n\n<p><sup>1</sup><sub><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void</a></sub></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-14T19:44:26.727",
"Id": "222319",
"ParentId": "217081",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "222319",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T15:08:10.787",
"Id": "217081",
"Score": "4",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"functional-programming",
"palindrome"
],
"Title": "Return whether a string is a palindrome if you can delete at most k elements"
} | 217081 |
<p>I wrote two versions of vector class for my ray tracer. Non-SIMD version and SIMD version. You can find the code below. I want to ask what things should I keep in mind to get max performance with SIMD. I am not getting any performance gain with this. I turned off compiler optimizations and still no results.</p>
<pre><code>#ifndef INC_VEC4_H
#define INC_VEC4_H
#define USE_SSE
#ifndef USE_SSE
#include<iostream>
#include<cassert>
class vec4
{
public:
union {
struct { float x, y, z,w; };
struct { float r, g, b,a; };
};
//normalised directions
static vec4 UP;
static vec4 DOWN;
static vec4 ZERO;
static vec4 LEFT;
static vec4 RIGHT;
static vec4 FORWARD;
static vec4 BACKWARD;
//construction
vec4();
explicit vec4(float x , float y, float z ,float w = 1.0f) ;
explicit vec4(float n);
vec4(const vec4& other);
vec4& operator = (const vec4& other);
//destruction
~vec4();
//vec4-vec4 arithmetic operations
inline vec4 operator + (const vec4& other) const{
return vec4( x+other.x,
y + other.y,
z + other.z);
}
inline vec4 operator - (const vec4& other) const {
return vec4(x - other.x,
y - other.y,
z - other.z);
}
//vec4-vec4 arithmetic operations
inline void operator += (const vec4& other) {
x += other.x;
y += other.y;
z += other.z;
}
inline vec4 operator * (const vec4& other) const {
return vec4(x*other.x,
y*other.y,
z*other.z);
}
inline vec4 operator / (const vec4& other) const {
assert((int)other.x!=0 && (int)other.y!=0 && (int)other.z!=0);
return vec4(x / other.x,
y / other.y,
z / other.z);
}
inline void operator *= (const vec4& other) {
x *= other.x;
y *= other.y;
z *= other.z;
}
inline void operator /= (const vec4& other) {
x /= other.x;
y /= other.y;
z /= other.z;
}
//vec4-scalar * & /
inline vec4 operator / (float scalar) const {
assert(scalar>0.00000f);
return vec4(x / scalar, y / scalar, z/scalar);
}
inline void operator *= (float scalar) {
x *= scalar;
y *= scalar;
z *= scalar;
}
inline void operator /= (float scalar) {
assert(scalar>0.00000000f);
x /= scalar;
y /= scalar;
z /= scalar;
}
inline vec4 normalize() const {
vec4 v;
v.x = x / length();
v.y = y / length();
v.z = z / length();
return v;
}
inline float length() const{
return (sqrt((x*x)+(y*y)+(z*z)));
}
inline float squared_length() const {
return x * x + y * y + z * z;
}
inline void make_it_unit() {
x /= length();
y /= length();
z /= length();
}
inline vec4& make_itzero() {
x = y = z = 0;
return *this;
}
inline float dot(const vec4& other) const {
return ((x*other.x)+(y*other.y)+(z*other.z));
}
inline vec4 cross(const vec4& other) const {
return vec4(
y*other.z+z*other.y,
z*other.x+x*other.z,
x*other.y+y*other.x
);
}
//checks
bool check_ifzero() const{
//typecasting the floats to int since its hard to compare two floats against each other
bool result = (((int)x) == 0 && ((int)y) == 0 && ((int)z) == 0);
return result;
}
//IO
friend std::ostream& operator << (std::ostream& cout, const vec4& other);
};
//non-member inline operators
inline vec4 operator * (const vec4& v,float scalar) {
return vec4(v.x * scalar, v.y * scalar, v.z * scalar);
}
inline vec4 operator * (float scalar, const vec4& v) {
return vec4(v.x * scalar, v.y * scalar, v.z * scalar);
}
inline float dot(const vec4& v1, const vec4& v2) {
return (v1.x*v2.x + v1.y*v2.y+v1.z*v2.z);
}
#else
#include<nmmintrin.h>
_declspec(align(16))
struct vec4
{
union {
__m128 vec;
struct { float x, y, z, w; };
struct { float r, g, b, a; };
};
//normalised directions
static vec4 UP;
static vec4 DOWN;
static vec4 ZERO;
static vec4 LEFT;
static vec4 RIGHT;
static vec4 FORWARD;
static vec4 BACKWARD;
//construction
vec4();
vec4(float x, float y, float z, float w = 1.0f);
explicit vec4(float n);
vec4(const vec4& other);
vec4& operator = (const vec4& other);
//destruction
~vec4();
inline float dot(const vec4& other)
{
__m128 dotResult = _mm_dp_ps(vec, other.vec, 0x7F);
float result;
_mm_store_ss(&result, dotResult);
return result;
}
inline void make_it_unit()
{
__m128 selfDot = _mm_dp_ps(vec, vec, 0x7F);
__m128 sqrtResult = _mm_rsqrt_ps(selfDot);
vec = _mm_mul_ps(vec, sqrtResult);
}
inline vec4 normalize()
{
vec4 result;
__m128 selfDot = _mm_dp_ps(vec, vec, 0x7F);
__m128 sqrtResult = _mm_rsqrt_ps(selfDot);
result.vec = _mm_mul_ps(vec, sqrtResult);
return result;
}
inline float length()
{
__m128 selfDot = _mm_dp_ps(vec, vec, 0x7F);
__m128 sqrtResult = _mm_sqrt_ps(selfDot);
float result;
_mm_store_ss(&result, sqrtResult);
return result;
}
//vec4-vec4 arithmetic operations
inline vec4 operator + (const vec4& other) const {
vec4 result;
result.vec = _mm_add_ps(vec, other.vec);
return result;
}
inline vec4 operator - (const vec4& other) const {
vec4 result;
result.vec = _mm_sub_ps(vec, other.vec);
return result;
}
//vec4-vec4 arithmetic operations
inline void operator += (const vec4& other) {
vec = _mm_add_ps(vec, other.vec);
}
inline vec4 operator * (const vec4& other) const {
vec4 result;
result.vec = _mm_mul_ps(vec, other.vec);
return result;
}
inline vec4 operator / (const vec4& other) const {
vec4 result;
result.vec = _mm_div_ps(vec, other.vec);
return result;
}
inline void operator *= (const vec4& other) {
vec = _mm_mul_ps(vec, other.vec);
}
inline void operator /= (const vec4& other) {
vec = _mm_div_ps(vec, other.vec);
}
//vec4-scalar * & /
inline vec4 operator / (float scalar) const {
vec4 result;
__m128 _scalar = _mm_set_ps(scalar, scalar, scalar, scalar);
result.vec = _mm_div_ps(vec, _scalar);
return result;
}
inline void operator *= (float scalar) {
__m128 _scalar = _mm_set_ps(scalar, scalar, scalar, scalar);
vec = _mm_mul_ps(vec, _scalar);
}
inline void operator /= (float scalar) {
__m128 _scalar = _mm_set_ps(scalar, scalar, scalar, scalar);
vec = _mm_div_ps(vec, _scalar);
}
inline float squared_length() const {
float result;
__m128 dotResult = _mm_dp_ps(vec, vec, 0x7F);
_mm_store_ss(&result, dotResult);
return result;
}
inline vec4& make_itzero() {
vec = _mm_set_ps(0.0f, 0.0f, 0.0f, 0.0f);
}
inline vec4 cross(const vec4& other) const {
vec4 result;
result.vec = _mm_sub_ps(
_mm_mul_ps(_mm_shuffle_ps(vec, vec, _MM_SHUFFLE(3, 0, 2, 1)), _mm_shuffle_ps(other.vec, other.vec, _MM_SHUFFLE(3, 1, 0, 2))),
_mm_mul_ps(_mm_shuffle_ps(vec, vec, _MM_SHUFFLE(3, 1, 0, 2)), _mm_shuffle_ps(other.vec, other.vec, _MM_SHUFFLE(3, 0, 2, 1)))
);
return result;
}
//checks
bool check_ifzero() const {
}
};
//non-member inline operators
inline vec4 operator * (const vec4& v, float scalar) {
vec4 result;
__m128 _scalar = _mm_set_ps(scalar, scalar, scalar, scalar);
result.vec = _mm_mul_ps(v.vec, _scalar);
return result;
}
inline vec4 operator * (float scalar, const vec4& v) {
vec4 result;
__m128 _scalar = _mm_set_ps(scalar, scalar, scalar, scalar);
result.vec = _mm_mul_ps(v.vec, _scalar);
return result;
}
inline float dot(const vec4& v1, const vec4& v2) {
__m128 dotResult = _mm_dp_ps(v1.vec, v2.vec, 0x7F);
float result;
_mm_store_ss(&result, dotResult);
return result;
}
#endif
#endif
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T15:36:45.557",
"Id": "419889",
"Score": "2",
"body": "What task does this code accomplish? Please tell us, and also make that the title of the question via [edit]. Maybe you missed the placeholder on the title element: \"_State the task that your code accomplishes. Make your title distinctive._\". Also from [How to Ask](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T17:54:23.623",
"Id": "419899",
"Score": "0",
"body": "I see a class with lots of operators, but no main program. What did you actually measure to conclude that you are *“not getting any performance gain with this”?*"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T18:56:14.313",
"Id": "419901",
"Score": "0",
"body": "Is your `#define USE_SSE` order swapped?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T00:08:35.590",
"Id": "419933",
"Score": "0",
"body": "\"1 SIMD vector == 1 math vector\" implementations have inherent performance issues (dot product is forced to be inefficient). Fixing that is very non-local and basically restructures the whole program. It's not so much an issue with the code shown here, but an issue with the entire approach implied by it."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T15:14:04.063",
"Id": "217082",
"Score": "1",
"Tags": [
"c++",
"comparative-review",
"x86",
"simd",
"raytracing"
],
"Title": "No performance gain with SIMD 3D vector for ray tracer"
} | 217082 |
<p>This is a simplified version of my app. It has a bunch of scraper classes, and a Job class, which controls the collection of data, and the saving to the db. During scraping it could happen many unforeseen problem due to irregular html structure, date format, missing information etc.
I want to have my app to run without stopping, and if there is an unprocessable item, it should log it, and somehow flag it in the database, that there was a problem with the site. After the irregularity is handled in the code, the next time we know that the page has to be scanned again, but this time it will be work fine, and the flag is switched to <code>scanned</code>.</p>
<p>In this example there is some problem with item nr. 4. It is logged (in my app to a file) and an error is thrown. Should I rethrow it in every function call till it reaches the <code>Job</code> class' <code>flush</code> method?</p>
<p>There was a second idea to handle this problem. Instead of throwing errors around the result of <code>Scraper</code> class' scrape method should contain if something went wrong. <code>[1, 2, 3, false, 5, 6 ...]</code> and during the flush handle the falsy item. The problem: this items are obviously not just simple numbers, but complex objects with a lot of links (to media, sub pages etc.) and those links are also scraped with different scrape classes, so I should handle in every for loop and scraper the falsy entries. Maybe there is a better solution.</p>
<p>jsbin: <a href="https://jsbin.com/jojiwuyugi/1/edit?js,console" rel="nofollow noreferrer">https://jsbin.com/jojiwuyugi/1/edit?js,console</a></p>
<pre><code>class Scraper {
check(item) {
if (item === 4) {
throw 42
console.log('There is a problem with ' + item)
return false
} else {
return true
}
}
scrape() {
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
const res = []
for (const item of arr) {
try {
if (this.check(item))
res.push(item)
} catch(e) {
}
}
return res
}
}
class SiteScraper {
scrape() {
return {
site: 'Foo'
}
}
}
class Job {
flush(data) {
try {
console.log(data.site)
for (const item of data.items)
console.log(item)
} catch(e) {
console.log('Error while flushing ' + e)
}
// here I should switch the flag if everything is fine / wrong
}
collectData() {
const siteScraper = new SiteScraper()
const scraper = new Scraper()
const site = siteScraper.scrape()
site.items = scraper.scrape()
return site
}
run() {
const data = this.collectData()
this.flush(data)
}
}
const j = new Job()
j.run()
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T16:23:00.823",
"Id": "217086",
"Score": "1",
"Tags": [
"javascript",
"node.js",
"error-handling"
],
"Title": "Rethrowing Error through several classes"
} | 217086 |
<p>Review for optimization, code standards, missed validation.</p>
<p>What's in this version:</p>
<ul>
<li>Rewritten, instead of large complex script - few tools with each own
task.</li>
<li>Solid CLI tool and GUI script on top of it.</li>
<li>Apply all previous code reviews on new code.</li>
<li>Some improvements from myself</li>
<li>Input arguments as usual and pass users/passwords to mysql script as
environment vars for improved security.</li>
<li>Man page written(not for review)</li>
</ul>
<p><a href="https://github.com/LeonidMew/CreateVirtualHost/tree/59a5566a605680d20fc0876076def57b86914a49" rel="nofollow noreferrer">Github</a></p>
<p>virtualhost-cli.sh - main cli tool, the only one script what need root</p>
<pre><code>#!/usr/bin/env bash
set -e
cd "${0%/*}"
source virtualhost.inc.sh
parseargs "$@"
validate
parse
#connect
hostfile="${config[a2ensite]}${config[subdomain]}.conf"
siteconf="${config[apachesites]}${hostfile}"
(cat >"$siteconf" <<EOF
<VirtualHost ${config[virtualhost]}:${config[virtualport]}>
ServerAdmin ${config[serveradmin]}
DocumentRoot ${config[webroot]}
ServerName ${config[domain]}
ServerAlias ${config[domain]}
<Directory "${config[webroot]}">
AllowOverride All
Require local
</Directory>
# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
LogLevel error
</VirtualHost>
# vim: syntax=apache ts=4 sw=4 sts=4 sr noet
EOF
) || die "May run as root or give $siteconf writable permissions to current user"
(
mkdir -p "${config[webroot]}"
chown ${config[webmaster]}:${config[webgroup]} "${config[webroot]}"
chmod u=rwX,g=rXs,o= "${config[webroot]}"
chown root:root "$siteconf"
chmod u=rw,g=r,o=r "$siteconf"
a2ensite "${hostfile}"
systemctl reload apache2
) || die "Run as root"
die "Config file saved and enabled at ${siteconf}" "Notice" 0
</code></pre>
<p>virtualhost.inc.sh - lib used by all other scripts</p>
<pre><code>#check if function exists
if ! type die &>/dev/null;then
die() {
echo "${2:-Error}: $1" >&2
exit ${3:-1}
}
fi
[[ "${BASH_VERSINFO:-0}" -ge 4 ]] || die "Bash version 4 or above required"
# defaults
declare -A config=()
config[webmaster]="$(id -un)" # user who access web files. group is www-data
config[webgroup]="www-data" # apache2 web group, does't need to be webmaster group. SGID set for folder.
config[webroot]='${homedir}/Web/${subdomain}'
config[domain]="localhost" # domain for creating subdomains
config[virtualhost]="*" # ip of virtualhost in case server listen on many interfaces or "*" for all
config[virtualport]="80" # port of virtualhost. apache2 must listen on that ip:port
config[serveradmin]="webmaster@localhost" # admin email
config[a2ensite]="050-" # short prefix for virtualhost config file
config[apachesites]="/etc/apache2/sites-available/" # virtualhosts config folder
declare -A mysql=() # mysql script read values from env
have_command() {
type -p "$1" >/dev/null
}
try() {
have_command "$1" && "$@"
}
if_match() {
[[ "$1" =~ $2 ]]
}
validate() {
[[ -z $1 && -z "${config[subdomain]}" ]] && die "--subdomain required"
[[ "${config[webmaster]}" == "root" ]] && die "--webmaster should not be root"
id "${config[webmaster]}" >& /dev/null || die "--webmaster user '${config[webmaster]}' not found"
getent group "${config[webgroup]}" >& /dev/null
[[ $? -ne 0 ]] && die "Group ${config[webgroup]} not exists"
have_command apache2 || die "apache2 not found"
[[ -d ${config[apachesites]} ]] || die "apache2 config folder not found"
(LANG=C; if_match "${config[domain]}" "^[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9\.])*$") || \
die "Bad domain"
[[ -z "$1" ]] && ((LANG=C; if_match "${config[subdomain]}" "^[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$") || \
die "Bad subdomain")
(LANG=C; if_match "${config[serveradmin]}" \
"^[a-z0-9!#<span class="math-container">\$%&'*+/=?^_\`{|}~-]+(\.[a-z0-9!#$%&'*+/=?^_\`{|}~-]+)*@([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)*[a-z0-9]([a-z0-9-]*[a-z0-9])?\$</span>" \
) || die "Bad admin email"
octet="(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])"
(if_match "${config[virtualhost]}" "^$octet\\.$octet\\.$octet\\.$octet$") || \
(if_match "${config[virtualhost]}" "^[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9\.])*$") || \
(if_match "${config[virtualhost]}" "^\*$") || \
die "Bad virtualhost"
(if_match "${config[virtualport]}" "^[1-9][0-9]+$") || die "Bad virtualport"
}
tolowercase() {
echo "${1}" | tr '[:upper:]' '[:lower:]'
}
parse() {
config[webroot]=$(echo "${config[webroot]}" | \
homedir=$( getent passwd "${config[webmaster]}" | cut -d: -f6 ) \
webmaster="${config[webmaster]}" \
subdomain="${config[subdomain]}" \
domain="${config[subdomain]}.${config[domain]}" \
envsubst '${homedir},${webmaster},${subdomain},${domain}')
config[domain]="${config[subdomain]}.${config[domain]}"
config[domain]=$(tolowercase "${config[domain]}")
config[subdomain]=$(tolowercase "${config[subdomain]}")
config[virtualhost]=$(tolowercase "${config[virtualhost]}")
}
# check if apache listening on defined host:port
connect() {
(systemctl status apache2) &>/dev/null || return
local host="${config[virtualhost]}"
[[ "$host" == "*" ]] && host="localhost"
ret=0
msg=$(netcat -vz "$host" "${config[virtualport]}" 2>&1) || ret=$? && true
[[ $ret -ne 0 ]] && die "$msg"
}
# load all allowed arguments into $config array
parseargs() {
(getopt --test > /dev/null) || true
[[ "$?" -gt 4 ]] && die 'I’m sorry, `getopt --test` failed in this environment.'
OPTIONS=""
LONGOPTS="help,webmaster:,webgroup:,webroot:,domain:,subdomain:,virtualhost:,virtualport:,serveradmin:"
! PARSED=$(getopt --options=$OPTIONS --longoptions=$LONGOPTS --name "$0" -- "$@")
if [[ ${PIPESTATUS[0]} -ne 0 ]]; then
# e.g. return value is 1
# then getopt has complained about wrong arguments to stdout
exit 2
fi
# read getopt’s output this way to handle the quoting right:
eval set -- "$PARSED"
while true; do
case "$1" in
--help)
man -P cat ./virtualhost.1
exit 0
;;
--)
shift
break
;;
*)
index=${1#--} # limited to LONGOPTS
config[$index]=$2
shift 2
;;
esac
done
}
validate_mysql() {
for key in adminuser database user;do
(LANG=C; if_match "${mysql[$key]}" "^[a-zA-Z][a-zA-Z0-9_-]*$") || die "bad mysql $key"
done
}
escape_mysql() {
for key in adminpasswd passwd;do
printf -v var "%q" "${mysql[$key]}"
mysql[$key]=$var
done
}
</code></pre>
<p>virtualhost-yad.sh - GUI tool for CLI scripts</p>
<pre><code>#!/usr/bin/env bash
set -e
cd "${0%/*}"
die() {
echo "${2:-Error}: $1" >&2
xmessage -buttons Ok:0 -nearmouse "${2:-Error}: $1" -timeout 10
exit ${3:-1}
}
source virtualhost.inc.sh
in_terminal() {
[ -t 0 ]
}
die() {
local msg="${2:-Error}: $1"
echo "$msg" >&2
in_terminal && exit ${3:-1}
try notify-send "$msg" && exit ${3:-1}
try yad --info --text="$msg" && exit ${3:-1}
try xmessage -buttons Ok:0 -nearmouse "$msg" -timeout 10 && exit ${3:-1}
exit ${3:-1}
}
have_command yad || die "yad package required. 'sudo apt install yad'"
user_info() {
yad --title="Virtualhost" --window-icon="${2:-error}" --info --text="$1" --timeout="${3:-15}" --button="Ok:0" --center
}
parseargs "$@"
while true; do
formbutton=0
formoutput=$(yad --form --field="Subdomain" --field="Domain" --field="Web master username" \
--field="Apache group" --field='Webroot' \
--field='Webroot variables - ${homedir}(of webmaster) ${subdomain} ${webmaster} ${domain}:LBL' \
--field="Virtualhost ip or domain" \
--field="Virtualhost port" --field="Server admin email" \
--field="Create mysql user&db:CHK" \
--field="Mysql admin user" --field="Mysql admin password" \
--field="Create database" \
--field="Create mysql user" --field="Create mysql password" \
--button="Cancel:5" --button="Save defaults:2" --button="Create:0" \
--title="Create apache virtualhost" \
--text='Subdomain are case sensetive for Webroot folder ${subdomain} variable' \
--focus-field=1 --center --window-icon="preferences-system" --width=600 \
"${config[subdomain]}" "${config[domain]}" "${config[webmaster]}" "${config[webgroup]}" \
"${config[webroot]}" "test" "${config[virtualhost]}" "${config[virtualport]}" \
"${config[serveradmin]}" true \
"${mysql[adminuser]}" "${mysql[adminpasswd]}" \
"${mysql[database]}" "${mysql[user]}" "${mysql[passwd]}" \
) || formbutton="$?" && true
# Cancel(5) or close window(other code)
[[ "$formbutton" -ne 0 && "$formbutton" -ne 2 && "$formbutton" -ne 1 ]] && die "Cancel"
IFS='|' read -r -a form <<< "$formoutput"
pos=0
for key in subdomain domain webmaster webgroup webroot nothing virtualhost virtualport serveradmin;do
config[$key]="${form[$pos]}"
let pos=pos+1
done
usemysql=
[[ "${form[9]}" -eq "TRUE" ]] && usemysql=1
pos=10
for key in adminuser adminpasswd database user passwd;do
mysql[$key]="${form[$pos]}"
let pos=pos+1
done
vres=0
# subdomain can't be default option, skip it
[[ "$formbutton" -eq 2 ]] && skipsubdomain=1 || skipsubdomain=
# validate input, continue or show error and return to form
valoutput=$(validate $skipsubdomain 2>&1) || vres=$? && true
[[ "$vres" -ne 0 ]] && user_info "$valoutput" && continue
clires=0
if [[ "$formbutton" -ne 2 ]]; then
cmd="pkexec `pwd`/virtualhost-cli.sh"
[[ "$formbutton" -eq 2 ]] && cmd="./virtualhost-install.sh"
clioutput=$($cmd --subdomain "${config[subdomain]}" \
--domain "${config[domain]}" --webmaster "${config[webmaster]}" \
--webgroup "${config[webgroup]}" --webroot "${config[webroot]}" \
--virtualhost "${config[virtualhost]}" --virtualport "${config[virtualport]}" \
--serveradmin "${config[serveradmin]}" 2>&1) || clires=$? && true
[[ "$clioutput" ]] && user_info "$clioutput" || true
[[ "$clires" -ne 0 ]] && continue
# mysql
if [[ "$usemysql" ]]; then
mysqlres=0
mysqloutput=$(adminuser="${mysql[adminuser]}" adminpwd="${mysql[adminpasswd]}" \
database="${mysql[database]}" mysqluser="${mysql[user]}" \
mysqlpasswd="${mysql[passwd]}" ./virtualhost-mysql.sh \
--subdomain "${config[subdomain]}" 2>&1) || mysqlres=$? && true
[[ "$mysqloutput" ]] && user_info "$mysqloutput" || true
[[ "$mysqlres" -ne 0 ]] && continue
break
fi
break
fi
done
</code></pre>
<p>virtualhost-mysql.sh - create db and user, values passed by environment variables to not appear in ps output - for security.</p>
<pre><code>#!/usr/bin/env bash
set -e
cd "${0%/*}"
source virtualhost.inc.sh
parseargs "$@" # only --subdomain used
# read values from env
subdomain=$(tolowercase "${config[subdomain]}")
mysql[adminuser]="${adminuser:-root}"
mysql[adminpasswd]="${adminpwd}"
mysql[database]="${mysqldatabase:-${subdomain}}"
mysql[user]="${mysqluser:-${subdomain:-$(id -un)}}"
mysql[passwd]="${mysqlpasswd}"
validate_mysql
escape_mysql
mysqlcreate=$(cat <<EOF
CREATE USER '${mysql[user]}'@'localhost' IDENTIFIED BY '${mysql[passwd]}';
GRANT USAGE ON *.* TO '${mysql[user]}'@'localhost';
CREATE DATABASE IF NOT EXISTS \`${mysql[database]}\` CHARACTER SET utf8 COLLATE utf8_general_ci;
GRANT ALL PRIVILEGES ON \`${mysql[database]}\`.* TO '${mysql[user]}'@'localhost';
FLUSH PRIVILEGES;
EOF
)
mysql --user="${mysql[adminuser]}" --password="${mysql[adminpasswd]}" <<<$mysqlcreate
</code></pre>
<p>virtualhost-install.sh - install desktop shortcut with arguments defined as defaults for GUI tool. Can be executed from "virtualhost-yad.sh" with values from form. Not for review as simple and similar.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T17:13:46.057",
"Id": "420047",
"Score": "0",
"body": "@200_success How to make link to a state of repository? I want to update link, as readme and file executable permissions changed, not the code. Google for it, but no relevant results."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T18:10:43.527",
"Id": "420053",
"Score": "1",
"body": "Click on the [\"19 commits\" link](https://github.com/LeonidMew/CreateVirtualHost/commits/d0d8589ac7621f271816bf77faedb37fbb051f1e), then on one of the \"<>\" buttons corresponding to the commit you want to link to."
}
] | [
{
"body": "<h3>Naming</h3>\n\n<p>In larger scripts like this, naming is even more important than usual,\nto help the reader understand the elements of the program easily.</p>\n\n<p>Looking at this at the beginning and I'm already puzzled:</p>\n\n<blockquote>\n<pre><code>parseargs \"$@\"\nvalidate\nparse\n#connect\n</code></pre>\n</blockquote>\n\n<p>Although it's pretty obvious what <code>parseargs</code> will do, it's not so obvious how <code>parse</code> is different. And what is <code>validate</code> going to do that <code>parseargs</code> doesn't already do? Why doesn't it do everything needed?</p>\n\n<p>And what is <code>#connect</code>?\nLooking at the implementation I see it checks if a virtual host + port is up.\nA more verbose, descriptive name would be better for this function.</p>\n\n<p>The other functions are not so easy to fix, we need to look at an organizational issue first.</p>\n\n<hr>\n\n<p><code>parseargs</code> populates a <code>config</code> array.\nThis may be subjective,\nthe name \"config\" makes me thing of some sort of configuration file,\nbut in this case it's about command line arguments.\nI would rename it to <code>args</code>.</p>\n\n<p>In fact in this program <code>config</code> is used for multiple purposes:\nstore defaults, and then parsed arguments.\nI would find it easier to understand to separate these two (define <code>defaults</code>),\nand have an additional step that combines them into <code>params</code>.</p>\n\n<h3>Program organization</h3>\n\n<p>As hinted earlier, I would have expected <code>parseargs</code> to encapsulate everything needed before the program is ready to execute its main job.</p>\n\n<p>I see that the different scripts have slightly different needs:</p>\n\n<ul>\n<li><code>virtualhost-cli.sh</code> calls <code>parseargs</code>, <code>validate</code> and <code>parse</code></li>\n<li><code>virtualhost-yad.sh</code> calls just <code>parseargs</code></li>\n<li><code>virtualhost-mysql.sh</code> calls <code>parseargs</code> and <code>validate_mysql</code></li>\n</ul>\n\n<p>I see that <code>parseargs</code> is a common element,\nbut it's hard to see what is included in it and what is not,\nand how much of what it does is shared.\nIn fact <code>virtualhost-mysql.sh</code> only needs it to parse <code>--subdomain</code>.</p>\n\n<p>Consider this alternative usage:</p>\n\n<p>In <code>virtualhost-cli.sh</code>:</p>\n\n<pre><code>parseargs_opts=\"help,webmaster:,webgroup:,webroot:,domain:,subdomain:,virtualhost:,virtualport:,serveradmin:\"\nparseargs \"$@\"\n</code></pre>\n\n<p>In <code>virtualhost-yad.sh</code>:</p>\n\n<pre><code>parseargs_opts=\"help,webmaster:,webgroup:,webroot:,domain:,subdomain:,virtualhost:,virtualport:,serveradmin:\"\nparseargs \"$@\"\n</code></pre>\n\n<p>In <code>virtualhost-mysql.sh</code>:</p>\n\n<pre><code>parseargs_opts=\"help,subdomain:\"\nparseargs \"$@\"\n</code></pre>\n\n<p>This way it would be much more clear what <code>parseargs</code> does, where its responsibilities begin and end.\nYes there is some duplication for two of the scripts,\nbut I think the clarity this alternative organization brings makes it well worth it.</p>\n\n<hr>\n\n<p>Another program organization <em>smell</em> is that <code>validate_mysql</code> and <code>escape_mysql</code> are defined in a shared script, but only used by <code>virtualhost-mysql.sh</code>.\nIt would be better to define these functions in the same script where they are used.</p>\n\n<h3>Sloppy error messages</h3>\n\n<p>Early in the script there's this:</p>\n\n<blockquote>\n<pre><code>(cat >\"$siteconf\" <<EOF\n<VirtualHost ${config[virtualhost]}:${config[virtualport]}>\n ServerAdmin ${config[serveradmin]}\n ...\n</VirtualHost>\nEOF\n) || die \"May run as root or give $siteconf writable permissions to current user\"\n</code></pre>\n</blockquote>\n\n<p>And then this:</p>\n\n<blockquote>\n<pre><code>(\n mkdir -p \"${config[webroot]}\"\n chown ${config[webmaster]}:${config[webgroup]} \"${config[webroot]}\"\n chmod u=rwX,g=rXs,o= \"${config[webroot]}\"\n ...\n) || die \"Run as root\"\n</code></pre>\n</blockquote>\n\n<p>I don't like the error messages in <code>die \"...\"</code> because I don't think you can know for sure that they are always appropriate. In compound operations like this, I would phrase the error message after the big-picture task it was trying to perform and failed, and not speculate about what the solution might be.</p>\n\n<p>Btw, if the second snippet requires <code>root</code>, then it would be better to check the user's identity at the very beginning of the script and fail fast.</p>\n\n<h3>Don't reference undefined variables</h3>\n\n<p>It seems to me that <code>virtualhost-yad.sh</code> references <code>${mysql[...]}</code> before those values are set, in the long <code>while true; do</code> loop body.\nIf this is not a bug, well it's hard to read and confusing.</p>\n\n<h3>Safety</h3>\n\n<p>It's a good practice to declare variables used within functions as <code>local</code>,\nto avoid unintended side effects.</p>\n\n<hr>\n\n<p>I'm a bit puzzled by this statement:</p>\n\n<blockquote>\n <p>virtualhost-mysql.sh - create db and user, values passed by environment variables to not appear in ps output - for security.</p>\n</blockquote>\n\n<p>And then in the script there's this line:</p>\n\n<blockquote>\n<pre><code>mysql --user=\"${mysql[adminuser]}\" --password=\"${mysql[adminpasswd]}\" <<<$mysqlcreate\n</code></pre>\n</blockquote>\n\n<p>The admin user and password are exposed!</p>\n\n<h3>Effective Bash</h3>\n\n<p>I see <code>(...)</code> a lot of sub-shells in the script, far more than really necessary.\nAlthough the performance penalty is likely negligible in this script,\nit's better to not get used to bad habits.</p>\n\n<p>In many places in <code>(if_match ...) || ...</code> you could simply drop the parentheses.</p>\n\n<p>Or where you write <code>(LANG=C; if_match ...) || die \"...\"</code> I think you could write <code>LANG=C if_match ... || die \"...\"</code>.</p>\n\n<p>For a more complex example, instead of:</p>\n\n<blockquote>\n<pre><code>(cat >\"$siteconf\" <<EOF\n...\nEOF\n) || die \"...\"\n</code></pre>\n</blockquote>\n\n<p>You could write:</p>\n\n<pre><code>cat >\"$siteconf\" <<EOF || die \"...\"\n...\nEOF\n</code></pre>\n\n<p>Here, you could replace the <code>(...)</code> with <code>{ ... }</code> and lose nothing, but avoid the creation of a sub-shell:</p>\n\n<blockquote>\n<pre><code>(\n mkdir -p \"${config[webroot]}\"\n chown ${config[webmaster]}:${config[webgroup]} \"${config[webroot]}\"\n chmod u=rwX,g=rXs,o= \"${config[webroot]}\"\n chown root:root \"$siteconf\"\n chmod u=rw,g=r,o=r \"$siteconf\"\n a2ensite \"${hostfile}\"\n systemctl reload apache2\n) || die \"Run as root\"\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>Instead of <code>echo ... | tr ...</code>, use <code>tr ... <<< \"...\"</code>.</p>\n\n<p>Instead of <code>cmd <<< $var</code>, write <code>cmd <<< \"$var\"</code>.</p>\n\n<p>Instead of <code>let pos=pos+1</code>, I prefer the simpler <code>((pos++))</code>.</p>\n\n<p>Since the script requires Bash 4,\nyou could take advantage of native lowercasing with <code>${1,,}</code> instead of <code>tr '[:upper:]' '[:lower:]' <<< \"$1\"</code>.</p>\n\n<p>The repeated definitions of the <code>die</code> function are confusing, especially in <code>virtualhost-yad.sh</code>.</p>\n\n<p>The implementations of the <code>die</code> functions look unnecessary complex.\nMost of the time it's only used with a single message argument.\nIt would be better to keep it simple,\nand for the rare cases where you need slightly different behavior,\neither just write out the different behavior, or define another function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T11:31:40.023",
"Id": "420235",
"Score": "0",
"body": "Thanks for review. Bounty is yours, but I will assign it later. Is it fine to use envsubst with limited set of validated variables on var like this config[webroot]='${homedir}/Web/${subdomain}' ? I'm planning to use same on some other config and mysql variables. All review suggestions is good, however I`ll not apply one for config array."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T12:33:23.777",
"Id": "420249",
"Score": "0",
"body": "I don't really get the purpose of `envsubst`. Why not simply embed variables in a double quoted string?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T12:51:59.887",
"Id": "420257",
"Score": "0",
"body": "Because they defined later then that string. And are subject to change, while string for envsubst remains the same. For example {subdomain} every time new, can be changed in yad dialog, so this envsubst needed to get new path"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T13:05:02.527",
"Id": "420262",
"Score": "0",
"body": "About mysql password, I just read in mysql documentation what some versions of `ps` can show environment of a command, but this script quickly do the job and disappear from `ps` list. `mysql` command also accept passwd from env. Other way to send admin password is to use options file, is it more secure? With 0600 permissions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T17:17:42.820",
"Id": "420301",
"Score": "0",
"body": "((pos++)) not working in set -e script, it breaks. I have to do `((pos++)) || true` instead, looks not better then pos=$pos+1"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T05:29:38.287",
"Id": "420350",
"Score": "0",
"body": "Indeed, use `((++pos))` instead!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T21:57:28.920",
"Id": "217225",
"ParentId": "217089",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "217225",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T17:05:35.033",
"Id": "217089",
"Score": "2",
"Tags": [
"mysql",
"bash",
"configuration"
],
"Title": "Create Apache2 virtualhost, Mysql db & user. CLI tool and GUI on top of it"
} | 217089 |
<p>I created a universal OpenGL object RAII wrapper class, that only takes care of object creation and destruction. Here's my code and reasoning behind it:</p>
<p>I first wrote a class that would take <code>glCreate/Delete*()</code> function pointers as constructor arguments, but I quickly realized that's not the right way to go. I'd have to store the <code>glDelete*()</code> function pointer in each object (waste of memory + dereference overhead). Additionally, OpenGL functions have three different forms (see specializations section, further in my code), so that would require 3 different pointer types - ugly. I decided to change my approach.</p>
<p>So, here I am with this template code. As far as I'm concerned, there should be no unnecessary OpenGL call overhead. The class is standard layout, only contains the object ID and there's no virtual stuff involved, so that seems pretty nice. Also, classes wrapping different OpenGL object types cannot be assigned to each other, because template arguments differ.</p>
<p>I'd like to hear your remarks according my code, the class design and the reasoning behind it. Improvement ideas are also welcome.</p>
<p>This is the main code:</p>
<pre><code>/**
\brief Serves as a RAII wrapper for OpenGL objects
\note This class provides no OpenGL error checking - this is up to derived classes.
\template T is object type as in glObjectLabel
*/
template <GLenum T>
class gl_object
{
public:
//! Object type used for labeling
const static GLenum object_type = T;
inline gl_object( );
inline explicit gl_object( GLenum target );
inline ~gl_object( );
// Deleted copy constructor and copy assignment operator
gl_object( const gl_object &src ) = delete;
gl_object &operator=( const gl_object &rhs ) = delete;
// Move semantics with source invalidation
gl_object( gl_object &&src );
gl_object &operator=( gl_object &&rhs );
//! Allows casting to object's ID (GLuint)
inline operator GLuint( ) const noexcept;
//! Returns object's ID
inline GLuint id( ) const noexcept;
protected:
//! The object ID
GLuint m_id;
};
//! Move constructor with source invalidation
template <GLenum T>
gl_object<T>::gl_object( gl_object<T> &&src ) :
m_id( src.m_id )
{
src.m_id = 0;
}
//! Move assignment operator with source invalidation
template <GLenum T>
gl_object<T> &gl_object<T>::operator=( gl_object<T> &&rhs )
{
// Prevent self-move
if ( this != &rhs )
{
m_id = rhs.m_id;
rhs.m_id = 0;
}
return *this;
}
// Allows cast to GLuint
template <GLenum T>
gl_object<T>::operator GLuint( ) const noexcept
{
return m_id;
}
// Used for acquiring object's ID
template <GLenum T>
GLuint gl_object<T>::id( ) const noexcept
{
return m_id;
}
</code></pre>
<p>Then, there are many very similar template specializations. Here are the most interesting ones:</p>
<pre><code>// Specializations for GL_BUFFER
template <>
gl_object<GL_BUFFER>::gl_object( )
{
glCreateBuffers( 1, &m_id );
}
template <>
gl_object<GL_BUFFER>::~gl_object( )
{
glDeleteBuffers( 1, &m_id );
}
// Specializations for GL_TEXTURE
template <>
gl_object<GL_TEXTURE>::gl_object( GLenum target )
{
glCreateTextures( target, 1, &m_id );
}
template <>
gl_object<GL_TEXTURE>::~gl_object( )
{
glDeleteTextures( 1, &m_id );
}
// Specializations for GL_SHADER
template <>
gl_object<GL_SHADER>::gl_object( GLenum type )
{
m_id = glCreateShader( type );
}
template <>
gl_object<GL_SHADER>::~gl_object( )
{
glDeleteShader( m_id );
}
// Specializations for GL_PROGRAM
template <>
gl_object<GL_PROGRAM>::gl_object( )
{
m_id = glCreateProgram( );
}
template <>
gl_object<GL_PROGRAM>::~gl_object( )
{
glDeleteProgram( m_id );
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T13:48:16.717",
"Id": "484384",
"Score": "2",
"body": "Is the intention that application writers directly use this code, or is it used internally by other classes that wrap OpenGL functionality? An example of how your code is to be used would be helpful. Also, why are templates necessary? Wouldn't a base class for `m_id` and derived classes that implement the constructors and destructors work?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T15:47:28.253",
"Id": "484391",
"Score": "0",
"body": "This class was supposed to be a general purpose OpenGL wrapper meant for internal use in a game engine I was making at the time. Base class for `m_id` would of course work (I think I've even used this approach for a while), but I thought that use of templates instead of a common base class would better emphasize that these objects shouldn't be mixed together (now they are completely distinct types)."
}
] | [
{
"body": "<h1>Ensuring you have distinct types</h1>\n<p>You said this in the comments:</p>\n<blockquote>\n<p>I thought that use of templates instead of a common base class would better emphasize that these objects shouldn't be mixed together (now they are completely distinct types).</p>\n</blockquote>\n<p>Two classes that derive from the same base class are also two distinct types. Furthermore, you can make the constructor of the base class protected, so you cannot instantiate a bare base class, and you can use protected or private inheritance to ensure you cannot get a pointer to the base class from a derived class. For example:</p>\n<pre><code>class base {\nprotected:\n base() = default;\n};\n\nclass derived: base {\n ...\n};\n\nderived foo; // OK\nbase bar; // Error: constructor is protected\nbase *baz = &foo; // Error: base is inaccessible\n</code></pre>\n<h1>The problem with template specialization</h1>\n<p>Your construction using template specialization has a flaw. The problem is that all member functions you might ever want to use in specializations need to be present in the default template. This is why you have:</p>\n<pre><code>template <GLenum T>\nclass gl_object\n{\n ...\n inline gl_object( );\n inline explicit gl_object( GLenum target );\n ...\n};\n</code></pre>\n<p>The second constructor that takes the <code>target</code> parameter is only used for <code>gl_object<GL_TEXTURE></code>, and in fact you <em>must</em> have a target for the texture in order to call <code>glCreateTextures()</code>. The problem is now that I can do the following:</p>\n<pre><code>gl_object<GL_BUFFER> buffer(GL_TEXTURE_2D);\ngl_object<GL_TEXTURE> texture;\n</code></pre>\n<p>The above statements will compile without errors (but perhaps with a warning), because you promised both constructors would exist. Only the linker will give an error, because there is no implementation of those constructors. But in a large project it might be hard to track down this issue.</p>\n<p>You won't have this problem with derived classes, since you have full control over which public member functions (including constructors) each derived class has.</p>\n<h1>Alternatives without templates</h1>\n<p>There are two ways to implement this without templates. Either you say that, for example, a <code>gl_texture</code> "is a" <code>gl_object</code>, and use class inheritance, or you say that a <code>gl_texture</code> "has a" <code>gl_name</code> (the OpenGL term for the GLuint identifier given to objects), and use composition. In the first case, you'd structure your code as:</p>\n<pre><code>class gl_object {\nprotected:\n GLuint m_id;\n\n gl_object() = default;\n\n // delete copy constructors\n // add move semantics\n // access the ID\n};\n\nclass gl_buffer: gl_object {\npublic:\n gl_buffer() {\n glCreateBuffers(1, &m_id);\n }\n ...\n\n // Enable the default constructor and assignment operator:\n gl_buffer(gl_buffer &&other) = default;\n gl_buffer &operator=(gl_buffer &&other) = default;\n};\n</code></pre>\n<p>In the second case, you would write:</p>\n<pre><code>class gl_name {\nprivate:\n GLuint m_id;\n\npublic:\n // delete copy constructors\n // add move semantics\n // access the ID\n\n GLuint &get() {\n return m_id;\n }\n};\n\nclass gl_buffer {\nprivate:\n gl_name m_id;\n\npublic:\n gl_buffer() {\n glCreateBuffers(1, &m_id.get());\n }\n ...\n\n // Enable the default constructor and assignment operator:\n gl_buffer(gl_buffer &&other) = default;\n gl_buffer &operator=(gl_buffer &&other) = default;\n};\n</code></pre>\n<p>In the second case, since you deleted the copy constructors for <code>gl_name</code>, classes that use that as a member variable will also no longer be default copy constructable.</p>\n<p>The main drawback of either two cases is that you need to implement the move constructors and move assignment operators in each derived class. In this case the default move constructor and move assignment operator would have worked just fine, but they have been implicitly deleted. To re-enable them, just explicitly add the default move constructor and move assignemnt operator.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T08:24:56.860",
"Id": "484465",
"Score": "1",
"body": "The move constructor and move assignment operator for `gl_buffer` could use `= default` to simplify things (assuming that worked with any other class members)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T09:24:10.960",
"Id": "484478",
"Score": "0",
"body": "@user673679 Good point, in this case no other state is in the derived classes that needs different treatment when moving, so enabling the defaults works."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T20:20:10.903",
"Id": "484547",
"Score": "0",
"body": "For some reason, I haven't thought of using private inheritance, which really helps here. Thank you for your remarks - it's been over a year since I wrote that, but it's better to learn late than never :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T20:42:00.513",
"Id": "484549",
"Score": "1",
"body": "Thanks to @Mask for editting your question and bringing it back to the front page :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-04T22:04:04.417",
"Id": "247491",
"ParentId": "217090",
"Score": "3"
}
},
{
"body": "<p>G.Sliepen points out this problem:</p>\n<pre><code>gl_object<GL_BUFFER> buffer(GL_TEXTURE_2D);\ngl_object<GL_TEXTURE> texture;\n</code></pre>\n<p>Another possible way to avoid this issue is to define the <code>gl_object</code> constructor using variadic template arguments. These arguments are forwarded to a class template specialization for the specific object type:</p>\n<pre><code> template<class... ArgsT>\n gl_object(ArgsT&&... args):\n m_id(gl_object_impl<T>::create(std::forward<ArgsT>(args)...)) { }\n\n ~object_id()\n {\n if (m_id != GLuint{ 0 })\n gl_object_impl<T>::destroy(m_id);\n }\n</code></pre>\n<p>So we forward declare <code>gl_object_impl</code> in the header with <code>gl_object</code>:</p>\n<pre><code> template<class T>\n struct gl_object_impl;\n</code></pre>\n<p>And each object type provides a specialization along with the rest of the operations for that object:</p>\n<pre><code> template<>\n struct gl_object_impl<GL_FRAMEBUFFER>\n {\n static GLuint create()\n {\n auto id = GLuint{ 0 };\n glGenFramebuffers(1, &id);\n return id;\n }\n\n static void destroy(GLuint id)\n {\n glDeleteFramebuffers(1, &id);\n }\n };\n\n\n class gl_framebuffer : public gl_object<GL_FRAMEBUFFER> { ... };\n</code></pre>\n<hr />\n<p>A few more things:</p>\n<ul>\n<li><p>Note that the use of <code>inline</code> on those functions isn't necessary. (Standard compiler settings allow the compiler to decide what to inline, because they're better at that than programmers).</p>\n</li>\n<li><p>The <code>GLuint</code> cast operator should be marked <code>explicit</code> to prevent accidents. (Personally I'd just delete it entirely, since we can do the same thing neatly and obviously with <code>.id()</code>.)</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T20:27:26.830",
"Id": "484548",
"Score": "1",
"body": "I added implicit `GLuint` cast operator only to be able to call OpenGL functions just like I normally would with `GLuint` 'objects'. Looking back, it seems to be excessive laziness... Thank you for your remarks and showing another approach :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-08-05T08:54:00.460",
"Id": "247514",
"ParentId": "217090",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "247491",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T17:58:55.873",
"Id": "217090",
"Score": "7",
"Tags": [
"c++",
"wrapper",
"opengl",
"raii"
],
"Title": "Universal OpenGL object RAII wrapper class"
} | 217090 |
<p>How do I simplify else if statements? I want the code to be able to run a bunch of code based on the users input, such as bring to link for some of them, so I am not looking for </p>
<pre><code>alert (prompt)
</code></pre>
<p>BELOW IS AN EXAMPLE</p>
<pre><code>var prompt = prompt ("Test");
if (prompt == "test1"){
alert ("test1")
}
else if (prompt == "Test2"){
alert ("test2")
}
else if (prompt == "Test3"){
alert ("Test3")
}
</code></pre>
<p>Is there a way to stop copy pasting the else if statements and shorten the code? Sorry. Im a bit newbie.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T18:19:31.770",
"Id": "419900",
"Score": "3",
"body": "Give a bit more context about what you're actually trying to achieve with that code please."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T19:19:13.647",
"Id": "419905",
"Score": "0",
"body": "If you're example is exact to the scenario you have, then `if (prompt) { alert(prompt); }` should simplify it quite a bit. I assume that's not actually the case though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T08:54:05.087",
"Id": "419962",
"Score": "0",
"body": "Welcome to Code Review! This question lacks any indication of what the code is intended to achieve. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](//meta.codereview.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](//meta.codereview.stackexchange.com/q/2436)."
}
] | [
{
"body": "<p>Have you looked into switch statements? It may provide cleaner code and possibly better speed if you have a lot of possibilities (more than 5) for the prompt var.</p>\n\n<pre><code>var prompt = \"Test1\"\nswitch(prompt) {\n case \"Test1\":\n alert(prompt)\n break;\n case \"Test2\":\n alert(prompt)\n break;\n default:\n alert(prompt)\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T18:31:09.453",
"Id": "217093",
"ParentId": "217091",
"Score": "1"
}
},
{
"body": "<p>Probably need more context here, depending on the number of cases you could possibly make this cleaner by </p>\n\n<pre><code>const availablePrompts = [“Test1”, “Test2”...]\n\nif(availablePrompts.includes(prompt)) { \n alert(prompt)\n} else {\n \\\\ action when the prompt is not valid \n}\n</code></pre>\n\n<p>Of course this assumes you are actually trying to run the same function for each prompt. If there are only a few cases it probably isn’t worth trying to shorten/optimize, if there are 5-10, probably a switch statement, and if there are more than 10ish there could potentially just be a better way to structure your logic so that it is more generalizable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T19:00:00.780",
"Id": "419902",
"Score": "0",
"body": "@Jonathan Harvey if you recently registered and [Jonathan](https://codereview.stackexchange.com/users/197127/jonathan) is your unregistered account, you can request a merge via the [contact](https://codereview.stackexchange.com/contact) link at the bottom left corner of the page."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T18:40:04.017",
"Id": "217094",
"ParentId": "217091",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T18:15:46.750",
"Id": "217091",
"Score": "-3",
"Tags": [
"javascript"
],
"Title": "Simplify else if statements in JS for a prompt to code?"
} | 217091 |
<p>This method takes a comment object and displays it correctly depending on what columns are available. <code>EVENT_TEXT</code> and <code>REASON_TEXT</code> are hashes that map properties to more human readable strings, like so</p>
<pre><code>EVENT_TEXT = { edit_item: 'edited an item' }
REASON_TEXT = { pickup_date: 'a pickup date change' }
</code></pre>
<p>The method that calls this one prepends this text with a username, so the text output expected is something along the lines of <em>edited an item due to a pickup date change: the supplier is not ready yet</em>.</p>
<pre><code> def comment_text(comment)
text = ''
if comment.event.present?
text += EVENT_TEXT[comment.event.to_sym]
if comment.reason.present?
text += ' due to ' + REASON_TEXT[comment.reason.to_sym]
end
end
text + ': ' + comment.text if comment.text.present?
end
</code></pre>
<p>Which has a an Assignement Branch Condition size of 17, higher than Rubocop's default of 15. Is there a better way to concatenate strings conditionally in Ruby? I really don't feel like this method is doing too much.</p>
<p>Should I just increase Rubocop's threshhold? But even if I did, how would I handle a scenario like this with 10 conditions?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T19:59:05.003",
"Id": "419914",
"Score": "0",
"body": "Please provide some more context by showing the code for the `Comment` class. It seems that in some circumstances, your `comment_text()` function might return an empty string, or just \"due to…\" or just \": _some text_\" — is that really so? Note that the second implementation does not have the same behaviour as the first."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T19:59:51.577",
"Id": "419915",
"Score": "0",
"body": "Take care not to say [\"refactoring\"](https://refactoring.com), which has a specific meaning, when you just mean \"rewriting\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T20:41:56.360",
"Id": "419922",
"Score": "0",
"body": "@200_success I've made some updates to the question. You made me realize that I expect a reason whenever there's an event. `event`, `reason`, and `text` are all strings. There is nothing in the comment class. Do you still need more context? It could theoretically return an empty string, but given that different fields are required in different circumstances, it never does in practice."
}
] | [
{
"body": "<p>Perhaps just extracting the hash lookups would help:</p>\n\n<pre><code>def comment_event_string(comment)\n EVENT_TEXT[comment.event.to_sym]\nend\n\ndef comment_reason_string(comment)\n \" due to #{REASON_TEXT[comment.reason.to_sym]}\"\nend\n\ndef comment_text_string(comment)\n \": #{comment.text}\"\nend\n\ndef comment_text(comment)\n text = ''\n if comment.event.present?\n text += comment_event_string(comment)\n text += comment_reason_string(comment) if comment.reason.present?\n end\n text + comment_text_string(comment) if comment.text.present?\nend\n</code></pre>\n\n<p>Passing <code>comment</code> around seems to be to be something of a code smell though, and I wonder if this code would be better placed inside the <code>Comment</code> class.</p>\n\n<pre><code>private def event_string\n EVENT_TEXT[event.to_sym]\nend\n\nprivate def reason_string\n \" due to #{REASON_TEXTreason.to_sym]}\"\nend\n\nprivate def text_string\n \": #{text}\"\nend\n\ndef nice_text(comment)\n nice_text = ''\n if event.present?\n nice_text += event_string\n nice_text += reason_string if reason.present?\n end\n nice_text + text_string if text.present?\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T13:22:23.260",
"Id": "217198",
"ParentId": "217096",
"Score": "1"
}
},
{
"body": "<p>I think extracting methods would help to make the method more readable and easier to understand. This also reduces the ABC size.</p>\n\n<pre><code># frozen_string_literal: true\n\nrequire \"ostruct\"\nrequire \"active_support\"\nrequire \"active_support/core_ext\"\nrequire \"minitest/autorun\"\n\nEVENT_TEXT = { edit_item: 'edited an item' }.freeze\nREASON_TEXT = { pickup_date: 'a pickup date change' }.freeze\n\ndef comment_text(comment)\n text = append_event('', comment)\n text = append_reason(text, comment)\n append_comment_text(text, comment)\nend\n\ndef append_event(text, comment)\n return text if comment.event.blank?\n\n text + EVENT_TEXT[comment.event.to_sym]\nend\n\ndef append_reason(text, comment)\n return text if comment.reason.blank?\n\n text + ' due to ' + REASON_TEXT[comment.reason.to_sym]\nend\n\ndef append_comment_text(text, comment)\n text + ': ' + comment.text if comment.text.present?\nend\n\nalias context describe\n\ndescribe \"comment_text\" do\n context \"when there is no text\" do\n it \"returns nil\" do\n assert_nil comment_text(OpenStruct.new)\n end\n end\n\n context \"when there is text but no event\" do\n it \"returns text\" do\n assert_equal \": foo\", comment_text(OpenStruct.new(text: \"foo\"))\n end\n end\n\n context \"when the event is unknown\" do\n it \"blows up\" do\n assert_raises do\n comment_text(OpenStruct.new(event: \"foo\"))\n end\n end\n end\n\n context \"when there is no text and event is known\" do\n it \"returns nil\" do\n assert_nil comment_text(OpenStruct.new(event: \"edit_item\"))\n end\n end\n\n context \"when there is no text and event and reason is known\" do\n it \"returns nil\" do\n assert_nil comment_text(OpenStruct.new(event: \"edit_item\", reason: \"pickup_date\"))\n end\n end\n\n context \"when there is no text and event is known and reason is unknown\" do\n it \"blows up\" do\n assert_raises do\n comment_text(OpenStruct.new(event: \"edit_item\", reason: \"foo\"))\n end\n end\n end\n\n context \"when there is text and event is valid\" do\n it \"displays text\" do\n assert_equal \"edited an item: foo\", comment_text(OpenStruct.new(event: \"edit_item\", text: \"foo\"))\n end\n end\n\n context \"when there is text and event and reason are valid\" do\n it \"displays text with reason\" do\n assert_equal \"edited an item due to a pickup date change: foo\", comment_text(OpenStruct.new(event: \"edit_item\", reason: \"pickup_date\", text: \"foo\"))\n end\n end\nend\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T15:11:18.557",
"Id": "425208",
"Score": "0",
"body": "Why would extracting methods help? Please add more explanation. This site is primarily about making observations about user code which you do, but you don't provide enough context. Good answers may contain no code at all or a single example."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-10T14:55:03.640",
"Id": "220053",
"ParentId": "217096",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T19:06:23.690",
"Id": "217096",
"Score": "3",
"Tags": [
"strings",
"ruby",
"ruby-on-rails",
"cyclomatic-complexity"
],
"Title": "Keep ABC size down for conditional string concatenation in Ruby"
} | 217096 |
<p>I'm working on my implementaion of the linux wc command. I finally have something that is working properly (with no options yet) but i think it needs a lot of "cleaning". I mean, i highly disrespect the "do not repeat yourself rule" and i want to hear some ideas on how can i polish this up a bit.</p>
<p>Here 's the code:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <getopt.h>
#define BUF_SIZE 1024
typedef struct Total{ //stores the Total count of lines words and bytes
int lines;
int words;
int bytes;
} Total;
Total* new_Total(int lines, int words, int bytes){ //constructor function for Total
Total* t = (Total*)malloc(sizeof(Total));
t->lines = lines;
t->words = words;
t->bytes = bytes;
return t;
}
void updateTotal(Total *t, int lines, int words, int bytes){ //updates Total counters
t->lines += lines;
t->words += words;
t->bytes += bytes;
}
void readStdin(Total* t, char c){ //reads from stdin, counts and prints
int lines = 0, words = 0, bytes = 0, startWord = 0;
char ch;
while((ch=fgetc(stdin)) != EOF){//count the bytes, lines and words
bytes++;
if (ch == '\n'){
lines++;
}
if (ch != ' ' && ch != '\n' && ch != '\r' && ch != '\t'){ //if there's a visible char, there's a word
startWord = 1;
}
if ((ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t') && startWord == 1){ //when the word ends
words++; //increment the word coutner
startWord = 0; //reset word finder
}
}
updateTotal(t, lines, words, bytes);
if (c == '\0'){ //if the command was called with no arguments
printf ("%d %d %d\n", lines, words, bytes);
}
else{
printf ("%d %d %d %c\n", lines, words, bytes, c);
}
}
void readFile(Total *t, char* filename, FILE* fp){
int lines = 0, words = 0, bytes = 0, startWord = 0;
char ch;
if (fp == NULL){
printf("%s: No such file or drectory\n", filename);
exit(1);
}
while ((ch=fgetc(fp)) != EOF){ //count the bytes, lines and words
bytes++;
if (ch == '\n'){
lines++;
}
if (ch != ' ' && ch != '\n' && ch != '\r' && ch != '\t'){
startWord = 1;
}
if ((ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t') && startWord == 1){
words++;
startWord = 0;
}
}
updateTotal(t, lines, words, bytes);
printf("%d %d %d %s\n", lines, words, bytes, filename);
}
void readArgs(Total* t, int argc, char* argv[]){
FILE* fp;
for (int i=1; i<argc; i++){
if (*argv[i] == '-'){//if a '-' is found, read from stdin
readStdin(t, '-');
clearerr(stdin);
}
else { //tries to read the file in argv[i]
fp = fopen(argv[i], "r");
readFile(t, argv[i], fp);
fclose(fp);
}
}
if (argc > 2){ //if there's more than one file, print the total in the end
printf("%d %d %d total\n", t->lines, t->words, t->bytes);
}
else {
exit(0);
}
}
int main(int argc, char* argv[]){
Total* t = new_Total(0,0,0);
if (argc<2){ //no arguments
readStdin(t,'\0'); //pass /0 to readstin because as it is the only time it is called, there's no need to append the name of the argument
return 0;
}
readArgs(t, argc, argv);
free(t);
return 0;
}
</code></pre>
<p>As you can see, both in readStdin() and in readFile() i have the same piece of code that handles the counting. I've tried to make a function out of this using pointers but i gave up. Any suggestion would be much appreciated. Also, if you have any hint that has nothing to do with the problem that i mentioned, shoot it up!</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T15:49:37.400",
"Id": "420030",
"Score": "0",
"body": "Why describe it as *Linux* `wc` command? `wc` has been around much longer than Linux has!"
}
] | [
{
"body": "<p>Well, i actually did it on my own so, if anyone's interested, here's the code: </p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include <getopt.h>\n#define BUF_SIZE 1024\n\ntypedef struct Counter{ //stores the count of lines, words, bytes and the value of starword\n int lines;\n int words;\n int bytes;\n int wordFlag; //when counting words, if one is found, set to 1. when digested, reset.\n} Counter;\n\nCounter* new_Counter(int lines, int words, int bytes, int wordFlag){ //constructor function for Counter\n Counter* t = (Counter*)malloc(sizeof(Counter));\n t->lines = lines;\n t->words = words;\n t->bytes = bytes;\n t->wordFlag = wordFlag;\n return t;\n}\n\nvoid updateTotal(Counter *t, int lines, int words, int bytes){ //updates the total counter\n t->lines += lines;\n t->words += words;\n t->bytes += bytes;\n}\n\nvoid count(char ch, Counter* cnt){//counts the bytes, lines and words\n cnt->bytes++; //if a char is passed, count it\n if (ch == '\\n'){ //count each line\n cnt->lines++;\n }\n if (ch != ' ' && ch != '\\n' && ch != '\\r' && ch != '\\t'){ //if there's a visible char, there's a word\n cnt->wordFlag = 1;\n }\n if ((ch == ' ' || ch == '\\n' || ch == '\\r' || ch == '\\t') && cnt->wordFlag == 1){ //when the word ends\n cnt->words++; //increment the word counter\n cnt->wordFlag = 0; //reset the flag\n }\n}\n\nvoid readStdin(Counter* t, char c){ //reads from stdin and prints\n Counter* cnt = new_Counter(0,0,0,0);\n char ch;\n while((ch=fgetc(stdin)) != EOF){\n count(ch, cnt);\n }\n updateTotal(t, cnt->lines, cnt->words, cnt->bytes);\n\n if (c == '\\0'){ //if the command was called with no arguments\n printf (\"%d %d %d\\n\", cnt->lines, cnt->words, cnt->bytes);\n }\n else{\n printf (\"%d %d %d %c\\n\", cnt->lines, cnt->words, cnt->bytes, c);\n }\n free(cnt);\n}\n\nvoid readFile(Counter *t, char* filename, FILE* fp){\n Counter* cnt = new_Counter(0,0,0,0);\n char ch;\n if (fp == NULL){\n fprintf(stderr, \"./my_wc: %s: No such file or directory\\n\", filename);\n exit(1);\n }\n while ((ch=fgetc(fp)) != EOF){ //count the bytes, lines and words\n count(ch, cnt);\n }\n updateTotal(t, cnt->lines, cnt->words, cnt->bytes);\n printf(\"%d %d %d %s\\n\", cnt->lines, cnt->words, cnt->bytes, filename);\n}\n\nvoid readArgs(Counter* t, int argc, char* argv[]){\n FILE* fp;\n for (int i=1; i<argc; i++){\n if (*argv[i] == '-'){//if a '-' is found, read from stdin\n readStdin(t, '-');\n clearerr(stdin);\n }\n else { //tries to read the file in argv[i]\n fp = fopen(argv[i], \"r\");\n readFile(t, argv[i], fp);\n fclose(fp);\n }\n }\n if (argc > 2){ //if there's more than one file, print the Counter in the end\n printf(\"%d %d %d total\\n\", t->lines, t->words, t->bytes);\n }\n else {\n exit(0);\n }\n}\n\nint main(int argc, char* argv[]){\n Counter* t = new_Counter(0,0,0,0); //pointer to the total counter\n if (argc<2){ //no arguments\n readStdin(t,'\\0'); //pass /0 to readstin because as it is the only time it is called, there's no need to append the name of the argument\n return 0;\n }\n readArgs(t, argc, argv);\n free(t);\n return 0;\n}\n</code></pre>\n\n<p>As you can see, i renamed the struct to Counter and i used it to store, not only the total counter, but also every temporary counter, then i implemented the function count() that does with the temporary counter values what those if statements in readStdin and readFile do.\nIf you still have any suggestions, please do not hesitate.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T21:57:47.690",
"Id": "217103",
"ParentId": "217099",
"Score": "0"
}
},
{
"body": "<p>A standard way to do this is to break the function up into smaller 'private' (<code>static</code>) functions, each with one thing to do. One can pass the default to the counting function in case we are not provided the argument. This allows separation of the code which counts and the UI.</p>\n\n<p><code>Total</code> is always going to be called with <code>(0, 0, 0)</code>, it's unnecessary to provide these arguments. In fact, the storage of <code>Total</code> in dynamic memory is probably unnecessary. No need to <code>updateTotal</code>, use of the counters directly is fine. In fact, there is going to be 1 <code>total</code>, might as well make it <a href=\"https://stackoverflow.com/questions/13251083/the-initialization-of-static-variables-in-c\">static</a>.</p>\n\n<p><code>fgetc</code> returns an <code>int</code>, <code>char ch</code> is not enough to tell <code>EOF</code>, which is -1. You've defined <code>BUF_SIZE</code>, an excellent optimization, but never use it. I'd go from <code>fgetc</code> to <code>fgets</code>. Note that this assumes that the file is text and doesn't contain a <code>'\\0'</code> inside, (eg, modified UTF-8.)</p>\n\n<p>You've included <code>getopt</code> and <code>unistd</code>, making your code <code>POSIX C99</code>, but you're not using those. Removing them makes your code more general <code>C99</code> (now your code will compile on more compilers.)</p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <errno.h>\n\n//stores the Total count of lines words and bytes\nstruct Total {\n size_t lines, words, bytes;\n} total;\n\n//count the bytes, lines and words\n//gives incorrect results on binary files with embedded 0\n//a word is delimited by everything that {isgraph}\n//using the unix definition of a text file, {lines = count('\\n')}\nstatic int readFile(FILE *fp) {\n char buffer[1024], b;\n int startWord = 1;\n size_t i;\n while(fgets(buffer, (int)sizeof buffer, fp)) {\n i = 0;\n do {\n b = buffer[i++];\n if(b == '\\n') {\n /* This will not recognize '\\l' in old Mac text files opened\n with \"wb\"? Hmm. */\n total.lines++;\n startWord = 1;\n } else if(b == '\\0') {\n break;\n } else if(isgraph(b)) {\n //if there's a visible char, there's a word\n if(startWord) total.words++, startWord = 0;\n } else {\n startWord = 1;\n }\n } while(1);\n total.bytes += i;\n }\n return ferror(fp) ? 0 : 1;\n}\n\nint main(int argc, char *argv[]) {\n FILE *fp = 0;\n char *fn = \"<no file>\";\n for(int i = 1; i < argc; i++) {\n fn = argv[i];\n fp = fopen(fn, \"r\");\n if(!fp || !readFile(fp)) break;\n fclose(fp), fp = 0;\n }\n if(argc <= 1) readFile(stdin);\n if(fp) fclose(fp);\n if(errno) return perror(fn), EXIT_FAILURE;\n /* https://stackoverflow.com/a/2524675/2472827 */\n printf(\"%zu lines; %zu words; %zu bytes total.\\n\",\n total.lines, total.words, total.bytes);\n return EXIT_SUCCESS;\n}\n</code></pre>\n\n<p>Some see <code>typedef struct</code> as problematic, and, in my opinion, it's not needed here; see <a href=\"https://www.kernel.org/doc/html/v4.10/process/coding-style.html#typedefs\" rel=\"nofollow noreferrer\">Linux kernel coding style</a>. <code>INT_MAX</code> could be as little as <a href=\"https://en.wikibooks.org/wiki/C_Programming/limits.h\" rel=\"nofollow noreferrer\">32,767</a>; it's never going to be less than zero, so I'd prefer <code>unsigned</code>, or <code>size_t</code> in this context. What if there are other chars besides <code>'\\n', ' ', '\\r', '\\t'</code>? I've included <code><ctype.h></code> to get rid of the ambiguity. There was a bug counting the word at the end of the line. Now, a line is defined as the number of <code>'\\n'</code> (UNIX style.) A word is delimited by <code>isgraph</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T23:28:19.093",
"Id": "217105",
"ParentId": "217099",
"Score": "4"
}
},
{
"body": "<p>Don't cast the result of <code>malloc()</code>; it's unnecessary clutter and it makes it harder to make changes. For the same reason, it's better to use the pointed-to value rather than the type as argument to <code>sizeof</code>:</p>\n\n<pre><code>Total *t = malloc(sizeof *t);\n</code></pre>\n\n<p>We need to test the result of <code>malloc()</code> is not null before using it, else we run into Undefined Behaviour.</p>\n\n<p>However, it's unnecessary to use dynamic allocation at all. Instead of <code>new_Total()</code> we could provide <code>init_Total()</code> to initialise an existing (e.g. stack-allocated) value:</p>\n\n<pre><code>void init_Total(Total *t, int lines, int words, int bytes)\n{\n assert(t);\n //constructor function for Total\n t->lines = lines;\n t->words = words;\n t->bytes = bytes;\n}\n</code></pre>\n\n<p>Then, <code>main()</code> can begin like this:</p>\n\n<pre><code>int main(int argc, char* argv[])\n{\n Total t;\n init_Total(&t, 0, 0, 0);\n</code></pre>\n\n<hr>\n\n<p>We can use a single function for files and <code>stdin</code>:</p>\n\n<pre><code>static bool readStream(Total *t, FILE* fp)\n{\n // common code here\n}\n\nbool readFile(Total *t, char* filename)\n{\n FILE *const f = fopen(filename, \"r\");\n if (!f) {\n perror(filename);\n return false;\n }\n return readStream(t, f) & fclose(f);\n}\n\nbool readStdin(Total *t)\n{\n return readStream(t, stdin);\n}\n</code></pre>\n\n<p>You might even feel that naming <code>readStdin()</code> is overkill, and simply call <code>readStream(t, stdin);</code> directly from <code>main()</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T10:53:17.423",
"Id": "217124",
"ParentId": "217099",
"Score": "2"
}
},
{
"body": "<p>I see a number of things that may help you improve your program.</p>\n\n<h2>Use only the required <code>#include</code>s</h2>\n\n<p>As far as I can tell, nothing from <code><getopt.h></code> is actually used, so that could be omitted.</p>\n\n<h2>Eliminate unused definitions</h2>\n\n<p>The <code>BUF_SIZE</code> definition is not used and should be eliminated.</p>\n\n<h2>Avoid allocating memory if possible</h2>\n\n<p>There's not really much need here for <code>malloc</code> and <code>free</code>. The <code>Total</code> structure is small and easily fits on the stack frame. Avoiding <code>malloc</code> means you'll never have to worry about <code>free</code>ing the memory later.</p>\n\n<h2>Prefer a <code>switch</code> to a long <code>if...else</code></h2>\n\n<p>The <code>while</code> loop only examines <code>ch</code> but it does so inefficiently because potentially, it examines the same character multiple times. A <code>switch</code> would be more efficient, shorter and more easily understood here.</p>\n\n<h2>Use <code>bool</code> where appropriate</h2>\n\n<p>The <code>startWord</code> variable is apparently being used as a boolean variable. For that reason, I'd suggest using <code>#include <stdbool.h></code> and declaring it as <code>bool</code>. </p>\n\n<h2>Use <code>const</code> where practical</h2>\n\n<p>The <code>filename</code> argument is not and should not be altered by the <code>readFile</code> function. For that reason, it would be better to declare that argument <code>const</code>.</p>\n\n<h2>Consolidate code by combining cases</h2>\n\n<p>Instead of having completely separate <code>readStdin</code> and <code>readFile</code> functions, it would be sensible to simply retain only <code>readFile</code> and initialize the <code>FILE</code> structure like this:</p>\n\n<pre><code>FILE *file = (filename && filename[0] == '-') ? stdin : fopen(filename, \"r\");\n</code></pre>\n\n<h2>Use the appropriate <code>printf</code> format string</h2>\n\n<p>The code uses <code>%d</code> for the format string, but would it ever make sense for the passed arguments to be negative? I would say not, and would suggest instead that these variables would more appropriately be <code>size_t</code> and that the format string should be <code>%lu</code> or <code>%u</code> depending on your compiler's implementation.</p>\n\n<h2>Simplify code by using functions</h2>\n\n<p>There are four places in the code that use <code>printf</code> to show totals. These could instead be reduced to a single place by creating a simple function:</p>\n\n<pre><code>static void report(const char *filename, size_t lines, size_t words, size_t letters) {\n printf(\"%5lu %5lu %5lu %s\\n\", lines, words, letters, filename);\n}\n</code></pre>\n\n<h2>Don't quit after a single error</h2>\n\n<p>The way that <code>wc</code> works is that it will keep going to process other files if one happens not to exist. To mimic that behavior, you'd have to alter your code to not <code>exit</code> if the file does not exist.</p>\n\n<h2>Carefully consider whether a <code>struct</code> is worthwhile</h2>\n\n<p>I'm all for consolidating variables into meaningfully named <code>struct</code>s as you have done, but I think the code is simpler using the three plain variables. Here's my complete version which incorporates all of these suggestions so that you can compare for yourself:</p>\n\n<pre><code>#include <stdio.h>\n#include <stdbool.h>\n\nstatic void count(const char *filename, size_t *lines, size_t *words, size_t *letters) {\n FILE *file = (filename && filename[0] == '-') ? stdin : fopen(filename, \"r\");\n if (file == NULL) {\n printf(\"%s: No such file or drectory\\n\", filename);\n return;\n }\n bool inword = false;\n for (int ch = fgetc(file); ch != EOF; ch = fgetc(file)) {\n switch (ch) {\n case '\\n':\n ++*lines;\n // fall through\n case ' ': \n case '\\r':\n case '\\t':\n if (inword) {\n ++*words;\n }\n inword = false;\n break;\n default:\n inword = true; \n }\n ++*letters;\n }\n fclose(file);\n}\n\nstatic void report(const char *filename, size_t lines, size_t words, size_t letters) {\n printf(\"%5lu %5lu %5lu %s\\n\", lines, words, letters, filename);\n}\n\nint main(int argc, char* argv[]) {\n size_t totallines = 0;\n size_t totalwords = 0;\n size_t totalletters = 0;\n if (argc < 2) {\n puts(\"Usage: wc filename [filename ...]\");\n return 0;\n }\n for (int i=1; i < argc; ++i) {\n size_t lines = 0;\n size_t words = 0;\n size_t letters = 0;\n count(argv[i], &lines, &words, &letters);\n report(argv[i], lines, words, letters);\n totallines += lines;\n totalwords += words;\n totalletters += letters;\n }\n if (argc > 2) {\n report(\"total\", totallines, totalwords, totalletters);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T22:07:39.243",
"Id": "420069",
"Score": "0",
"body": "That's good advice. I would say that a `struct` is probably worthwhile, since the data are strongly linked together."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T23:27:25.107",
"Id": "420071",
"Score": "1",
"body": "@NeilEdelman: Yes, I could definitely argue it either way. In C++ I would definitely use a `class` (primarily for the `operator+=` and `ostream<<` functions) but I don't see as much benefit in this particular C code. Grouping can be handy, but it's also pretty easy to remember three or four well-named variables."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T20:37:49.923",
"Id": "420166",
"Score": "0",
"body": "I don't know C++ as well as C, but isn't a `struct` and a `class` the same wrt `operator`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T00:44:41.377",
"Id": "420338",
"Score": "1",
"body": "@NeilEdelman: The difference is that one can overload operators for custom `struct` or `class` types in C++, but one cannot overload operators at all in C."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T14:03:54.547",
"Id": "217135",
"ParentId": "217099",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T20:20:43.087",
"Id": "217099",
"Score": "3",
"Tags": [
"c",
"strings",
"reinventing-the-wheel",
"io"
],
"Title": "Linux wc command in C"
} | 217099 |
<p>I have a list of objects each with a unique <code>Key</code> and a display name (<code>Label</code>). The list needs to remain sorted by the keys of each object but unfortunately the keys need to be strings rather than numerical and as such 'sorted' here refers to the keys being sorted alphabetically rather than numerically. (Although the keys can be string of numbers - their actual string values don't matter so long as they're alphabetically ordered).</p>
<p>The list should be re-order-able but then the keys need to re-shuffle so that they're once more in alphabetical order.</p>
<p>Currently my implementation allows for the re-ordering of the list and then iterates over all of the objects re-assigning them fresh keys in alphabetical order - something which I feel is a bad idea as it's a lot of effort for a single swap of values.</p>
<p>My object looks like the following</p>
<pre><code>class Item
{
public string Key { get; set; }
public string Label { get; set; }
public Item(string key, string label)
{
Key = key;
Label = label;
}
public override string ToString() => Key + ", " + Label;
}
</code></pre>
<p>I have added an extension method to handle the re-ordering process</p>
<pre><code>static class Utils
{
public static List<Item> MoveIndex(this List<Item> myItems, int from, int to)
{
Item temp = myItems[from];
myItems.RemoveAt(from);
myItems.Insert(to, temp);
for (int i = 0; i < myItems.Count; i++)
{
myItems[i].Key = i.ToString("D2");
}
return myItems;
}
}
</code></pre>
<p>And finally I have an example usage of the extension method</p>
<pre><code>static void Main(string[] args)
{
List<Item> myItems = new List<Item>()
{
new Item("0", "Zero"),
new Item("1", "One"),
new Item("2", "Two"),
new Item("3", "Three"),
new Item("4", "Four"),
new Item("5", "Five"),
new Item("6", "Six"),
new Item("7", "Seven"),
new Item("8", "Eight"),
new Item("9", "Nine"),
new Item("10", "Ten"),
new Item("11", "Eleven"),
new Item("12", "Twelve"),
};
myItems.MoveIndex(3, 5);
Console.ReadKey();
}
</code></pre>
<p>As the code currently sits, placing a breakpoint on the <code>Console.ReadKey()</code> shows that the Labels are not in their original order but the Keys are - proving that it currently works.</p>
<hr>
<p>Are there any better ways to manage the Keys when the list is being re-ordered? Perhaps ways which don't require iterating over everything in the list?</p>
<p>Are there any better strings which I could be using for the keys?</p>
<hr>
<p>I know that as it sits this system has a capacity for only 100 Items before it breaks and that is OK - There will be checking in place to ensure that there are never more than this.</p>
| [] | [
{
"body": "<blockquote>\n<pre><code> public static List<Item> MoveIndex(this List<Item> myItems, int from, int to)\n</code></pre>\n</blockquote>\n\n<p>Code to the interface, not the implementation: you <em>might</em> be able to rewrite this as</p>\n\n<pre><code> public static IList<Item> MoveIndex(this IList<Item> myItems, int from, int to)\n</code></pre>\n\n<p>and if not you can almost certainly rewrite it as</p>\n\n<pre><code> public static TList MoveIndex<TList>(this TList myItems, int from, int to)\n where TList : IList<Item>\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code> for (int i = 0; i < myItems.Count; i++)\n {\n myItems[i].Key = i.ToString(\"D2\");\n }\n</code></pre>\n</blockquote>\n\n<p>For a start, this looks too tightly bound to me. From the description given I would expect <code>MoveIndex</code> to work with the existing keys, whatever they are.</p>\n\n<p>But given the strong assumptions made here, I wonder whether there's a better solution based on eliminating the <code>List<Item></code> entirely. Can you maintain an <code>IList<string></code> which contains the labels and then generate the items lazily with <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.select?view=netframework-4.7.2#System_Linq_Enumerable_Select__2_System_Collections_Generic_IEnumerable___0__System_Func___0_System_Int32___1__\" rel=\"nofollow noreferrer\"><code>IEnumerable<string>.Select(Func<string, int, Item>)</code></a>?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T10:14:47.270",
"Id": "217121",
"ParentId": "217100",
"Score": "3"
}
},
{
"body": "<p>If your need is max 100 items in the list, I think your implementation is OK.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>public static List<Item> MoveIndex(this List<Item> myItems, int from, int to)\n{\n Item temp = myItems[from];\n myItems.RemoveAt(from);\n myItems.Insert(to, temp);\n for (int i = 0; i < myItems.Count; i++)\n {\n myItems[i].Key = i.ToString(\"D2\");\n }\n return myItems;\n}\n</code></pre>\n</blockquote>\n\n<p>Some minor considerations:</p>\n\n<p>If <code>from < to</code> then by removing <code>from</code>, you left shift from <code>from</code> and upwards and \nmaybe invalidate the <code>to</code> index?</p>\n\n<p>To me it's counter intuitive that the list is returned from this method, because you manipulate the input list itself. If returning a list here, I would expect the input list to be untouched and the returned list to be a new instance holding the change. </p>\n\n<p>You can make a minor optimization in that it is only necessary to renumber the entries from <code>Math.Min(from, to)</code> to <code>Math.Max(from, to)</code> (both inclusive) because everything before and after these indices are untouched.</p>\n\n<hr>\n\n<p>As Peter Taylor writes, it's common good practice to code for interfaces rather than implementations, but be aware that not all <code>IList<s></code> implementations support <code>RemoveAt(int index)</code> and <code>Insert(int index, T value)</code>. For instance arrays don't. So in this special case it's maybe a good idea to stick with the <code>List<Item></code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T12:49:53.000",
"Id": "217133",
"ParentId": "217100",
"Score": "2"
}
},
{
"body": "<p>You're doing a lot of work for no gain. If you really can guarantee that there will never be more than 100 items in the list, why not go ahead and create 100 strings, store them, and assigned them the the items during your ordering phase. </p>\n\n<p>You can just reuse the same set of strings each time, never do any work formatting, and get some efficiency because the ordering step would just be running through a loop assigning values from one array (in order) to the objects in the other array (in order):</p>\n\n<pre><code>for (int i = 0; i < myItems.Count; i++)\n{\n myItems[i].Key = listOf100Strings[i];\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T14:36:46.123",
"Id": "217136",
"ParentId": "217100",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "217121",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T20:37:21.233",
"Id": "217100",
"Score": "3",
"Tags": [
"c#"
],
"Title": "Reordering items which must have alphabetically ordered keys"
} | 217100 |
<p>I want to pass time interval as a string (to program args) and then I want to parse it to <code>TimeSpan</code>. I created simple class:</p>
<pre><code>public static class TimeSpanConverter
{
public static TimeSpan Convert(string input)
{
var units = new Dictionary<string, int>()
{
{@"(\d+)(ms|mili[|s]|milisecon[|s])", 1 },
{@"(\d+)(s|sec|second[|s])", 1000 },
{@"(\d+)(m|min[|s])", 60000 },
{@"(\d+)(h|hour[|s])", 3600000 },
{@"(\d+)(d|day[|s])", 86400000 },
{@"(\d+)(w|week[|s])", 604800000 },
};
var timespan = new TimeSpan();
foreach(var x in units)
{
var matches = Regex.Matches(input, x.Key);
foreach(Match match in matches)
{
var amount = System.Convert.ToInt32(match.Groups[1].Value);
timespan = timespan.Add(TimeSpan.FromMilliseconds(x.Value * amount));
}
}
return timespan;
}
}
</code></pre>
<p>Which is working, and I can easly parse like this:</p>
<pre><code>var interval = TimeSpanConverter.Convert("1day13hour2min12s52ms");
</code></pre>
<p>What do you think about that? How can I improve that? I have a feeling, that it is not well coded.</p>
| [] | [
{
"body": "<blockquote>\n<pre><code>public static class TimeSpanConverter\n {\n public static TimeSpan Convert(string input)\n</code></pre>\n</blockquote>\n\n<p>To people who use WPF a lot, the name hints at this class being a <code>TypeConverter</code> or an <code>IValueConverter</code>. I would say that it's really a parser. Similarly, I think that the method should be called <code>Parse</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> var units = new Dictionary<string, int>()\n {\n {@\"(\\d+)(ms|mili[|s]|milisecon[|s])\", 1 },\n {@\"(\\d+)(s|sec|second[|s])\", 1000 },\n {@\"(\\d+)(m|min[|s])\", 60000 },\n {@\"(\\d+)(h|hour[|s])\", 3600000 },\n {@\"(\\d+)(d|day[|s])\", 86400000 },\n {@\"(\\d+)(w|week[|s])\", 604800000 },\n };\n</code></pre>\n</blockquote>\n\n<p>The prefix <em>milli</em> has two <em>l</em>s. <em>millisecond</em> ends in a <em>d</em>.</p>\n\n<p><code>[|s]</code> is more idiomatically written as <code>s?</code>.</p>\n\n<p>Given the way the regexes are used (searching for matches without anchoring), most of them could be simplified. E.g. any match for <code>min</code> would also match <code>m</code>, so <code>@\"(\\d+)m\"</code> will find exactly the same multiples of a minute.</p>\n\n<p>The numbers on the right are <em>magic numbers</em>, and at a glance I can't be completely certain that they're correct. I would prefer to use <code>TimeSpan</code> instances and take advantage of <code>TimeSpan.FromMilliseconds(1)</code>, <code>TimeSpan.FromSeconds(1)</code>, etc.</p>\n\n<p>I think that a real world example of a human-readable string would be <code>\"1 day, 13 hours, 2 minutes, 12 seconds, and 52 ms\"</code>. At the very least, I would add <code>\\s*</code> between the digits and the units.</p>\n\n<p>Another quite realistic example would be <code>\"2 minutes and 13.5 seconds\"</code>.</p>\n\n<p>It's also plausible that people will use <code>:</code> as a separator: <code>\"2 days, 11:04:20\"</code></p>\n\n<p>Then you get ugly stuff like months and years, which don't have fixed lengths.</p>\n\n<p>If you want to refuse to parse some of these, that's fine. But in that case, I think the method still needs to handle them by throwing an exception. At present they would all return <code>TimeSpan.Zero</code>, which is misleading.</p>\n\n<p>Have you given any thought to localisation? If you only want to use this in an English-language context, wouldn't <code>[0-9]</code> make more sense than <code>\\d</code>? If you're matching all digits, you should have test cases for things like <code>\"¹day١hourminute①second\"</code>.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> var timespan = new TimeSpan();\n</code></pre>\n</blockquote>\n\n<p>Can you think of a more descriptive name for this variable?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> var matches = Regex.Matches(input, x.Key);\n foreach(Match match in matches)\n</code></pre>\n</blockquote>\n\n<p>If the string has more than one match for a given regex, isn't that rather worrying? I wouldn't consider <code>\"4hours2minutes1hour\"</code> to be a very realistic input.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> var amount = System.Convert.ToInt32(match.Groups[1].Value);\n timespan = timespan.Add(TimeSpan.FromMilliseconds(x.Value * amount));\n</code></pre>\n</blockquote>\n\n<p>Again, <code>amount</code> isn't a very descriptive name.</p>\n\n<p><code>TimeSpan</code> supports the operator <code>+</code>, and IMO <code>total += addend;</code> is more readable than <code>total = total.Add(addend);</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T08:02:57.687",
"Id": "420093",
"Score": "0",
"body": "_I would add \\s* between the digits and the units._ - In such cases I usually _normalize_ a string first by replacing all multiple-whitespaces by a single one to avoid using the `*`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T10:44:40.677",
"Id": "217122",
"ParentId": "217101",
"Score": "11"
}
},
{
"body": "<p>Adding to Peter Taylors answer:</p>\n\n<blockquote>\n <p><code>@\"(\\d+)(ms|mili[|s]|milisecon[|s])\"</code></p>\n \n <p><code>@\"(\\d+)(m|min[|s])\"</code></p>\n</blockquote>\n\n<p><code>\"5ms\"</code> will be caught by both patterns above.</p>\n\n<hr>\n\n<blockquote>\n <p><code>var amount = System.Convert.ToInt32(match.Groups[1].Value);</code></p>\n</blockquote>\n\n<p>For <code>weeks > 3</code> this will make an overflow when multiplied with <code>604800000</code>.</p>\n\n<p>You should use <code>double.Parse()</code>, because <code>TimeSpan.FromMilliseconds()</code> takes a double as argument.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T11:35:19.587",
"Id": "217126",
"ParentId": "217101",
"Score": "5"
}
},
{
"body": "<p>I don't have experience in programming in C#, but I do have some regex advice to share.</p>\n\n<p>You can DRY your pattern by </p>\n\n<pre><code>(\\d+)(?:ms|mili(?:secon)?s?)\n(\\d+)(?:s(?:ec)?|seconds?)\n(\\d+)(?:m|mins?)\n(\\d+)(?:h|hours?)\n(\\d+)(?:d|days?)\n(\\d+)(?:w|weeks?)\n</code></pre>\n\n<p>I am encouraging:</p>\n\n<ul>\n<li>non-capturing groups when there is no use for the matched substrings.</li>\n<li>I am using the zero or more quantifier (<code>?</code>) to reduce repetition and alternation (pipes).</li>\n<li>the omission of pipes in your character classes because they are useless in your expected input.</li>\n<li><code>s?</code> to make pluralization optional.</li>\n</ul>\n\n<p>If you need to ensure that <code>m</code> is not followed by <code>s</code> when executing the minutes pattern, you will need to extend the pattern. Perhap <code>m(?!s)|mins?</code>.</p>\n\n<p>If you are in control of the incoming strings, please correct the spelling of <code>milliseconds</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-23T12:43:56.510",
"Id": "217954",
"ParentId": "217101",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "217122",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T20:38:13.570",
"Id": "217101",
"Score": "8",
"Tags": [
"c#",
"regex"
],
"Title": "Convert human readable string to TimeSpan"
} | 217101 |
<blockquote>
<p><strong><a href="https://www.hackerrank.com/challenges/beautiful-string/problem" rel="nofollow noreferrer">Problem Statement</a></strong></p>
<p>You are given a string, <em>S</em> , consisting of lowercase English letters.</p>
<p>A string is beautiful with respect <em>S</em> to if it can be derived from <em>S</em> by removing exactly 2 characters.</p>
<p>Find and print the number of different strings that are beautiful with respect to <em>S</em>.</p>
<p><strong>Input Format</strong></p>
<p>A single string of lowercase English letters denoting <em>S</em>.</p>
<p><strong>Output Format</strong></p>
<p>Print the number of different strings that are beautiful with respect
to <em>S</em>.</p>
<p><strong>Sample Input</strong></p>
<p>abba </p>
<p><strong>Sample Output</strong></p>
<p>4 </p>
<p><strong>Explanation</strong></p>
<p>The following strings can be derived by removing characters from <em>S</em>:
<code>ab, bb, ba, ab, ba, aa and bb</code>.</p>
<p>This gives us our set of unique beautiful strings, <code>B = {ab, ba, aa,
bb}</code> as <code>|B| = 4</code>, we print 4</p>
</blockquote>
<p>Here is my solution but it's not using dynamic programming. I am not getting any hints about how it can be solved via a DP approach.</p>
<pre><code>function beautifulStrings(str) {
const res = new Set()
for (let i = 0; i < str.length - 1; i++) {
for (let j = i + 1; j < str.length; j++) {
let s = str.split('')
s[i] = undefined
s[j] = undefined
res.add(s.join(''))
}
}
return res.size
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-08T21:00:19.887",
"Id": "217102",
"Score": "1",
"Tags": [
"javascript",
"programming-challenge",
"dynamic-programming"
],
"Title": "Hackerrank Beautiful Strings"
} | 217102 |
<p>I've been trying to learn Groovy lately and I tried to solve a problem which involves designing a routine that will calculate the average Product price per Group.</p>
<p>I have the following data:</p>
<pre><code>// contains information about [Product, Group, Cost]
products = [
["A", "G1", 20.1],
["B", "G2", 98.4],
["C", "G1", 49.7],
["D", "G3", 35.8],
["E", "G3", 105.5],
["F", "G1", 55.2],
["G", "G1", 12.7],
["H", "G3", 88.6],
["I", "G1", 5.2],
["J", "G2", 72.4]
]
// contains information about Category classification based on product Cost
// [Category, Cost range from (inclusive), Cost range to (exclusive)]
// i.e. if a Product has Cost between 0 and 25, it belongs to category C1
category = [
["C3", 50, 75],
["C4", 75, 100],
["C2", 25, 50],
["C5", 100, null],
["C1", 0, 25]
]
// contains information about margins for each product Category
// [Category, Margin (either percentage or absolute value)]
margins = [
"C1" : "20%",
"C2" : "30%",
"C3" : "0.4",
"C4" : "50%",
"C5" : "0.6"]
</code></pre>
<p>What I tried so far is the following (I mixed some Java here):</p>
<pre><code>def calculateResult() {
def group1 = []
def group2 = []
def group3 = []
def pricePerGroupMap = [:]
category.each { cat ->
String catDesc = cat[0]
BigDecimal min = cat[1]
BigDecimal max = cat[2]
if (max == null) {
max = 9999.9;
}
products.each { product ->
BigDecimal currProductPrice = BigDecimal.valueOf(product[2])
if (currProductPrice.compareTo(min) >= 0 && currProductPrice.compareTo(max) <= 0) {
String selectedMarginAsString = margins.getAt(catDesc);
BigDecimal selMargin = 0.0;
if (selectedMarginAsString.endsWith("%")) {
selMargin = new BigDecimal(selectedMarginAsString.trim().replace("%", "")).divide(BigDecimal.valueOf(100));
} else {
selMargin = new BigDecimal(selectedMarginAsString);
}
if (product[1].equals("G1")) {
group1.add(product[2] * (1 + selMargin))
} else if (product[1].equals("G2")) {
group2.add(product[2] * (1 + selMargin))
} else if (product[1].equals("G3")) {
group3.add(product[2] * (1 + selMargin))
}
}
}
}
pricePerGroupMap["G1"] = group1.sum() / group1.size()
pricePerGroupMap["G2"] = group2.sum()/ group2.size()
pricePerGroupMap["G3"] = group3.sum()/ group3.size()
print pricePerGroupMap
}
</code></pre>
<p>I am sure there are better ways to optimize this algorithm taking advantage of closures.</p>
| [] | [
{
"body": "<p>After being investigating a little bit more about usage of closures and some other facilities that Groovy provides, I managed to reduce a little bit the algorithm, after looking for benchmarking posts, I believe this is probably not the most optimal solution, but it looks a lot better than the first proposal (the one in my question).</p>\n\n<p>One of the things I considered to improve the solution is to use Groovy \"maps\" instead of multiple arrays to hold the data.</p>\n\n<p>I also considered using one additional variable to hold the value of a group being evaluated. </p>\n\n<p>And finally, I decided to avoid using more conditionals to add the results to the arrays and use a more simple instruction taking advantage of the map definition.</p>\n\n<pre><code>MAX_DEFAULT_VALUE_WHEN_NULL = 99999.9\n\ndef calculateResult() {\n def pricesPerGroupMap = [G1:[], G2:[], G3:[]]\n def avgPricePerGroupMap = [:]\n\n category.each { cat ->\n String categoryId = cat[0]\n BigDecimal min = cat[1]\n BigDecimal max = cat[2]\n\n if (max == null) {\n max = MAX_DEFAULT_VALUE_WHEN_NULL\n }\n\n products.each { product ->\n BigDecimal currProductPrice = BigDecimal.valueOf(product[2])\n String group = product[1]\n if (currProductPrice.compareTo(min) >= 0 && currProductPrice.compareTo(max) == -1) {\n String selectedMarginAsString = margins.getAt(categoryId);\n BigDecimal selMargin = 0.0;\n\n if (selectedMarginAsString.endsWith(\"%\")) {\n selMargin = new BigDecimal(selectedMarginAsString.trim().replace(\"%\", \"\")).divide(BigDecimal.valueOf(100))\n } else {\n selMargin = new BigDecimal(selectedMarginAsString)\n }\n pricesPerGroupMap[group].add(currProductPrice * (1 + selMargin))\n }\n }\n }\n pricesPerGroupMap.each { k, v -> \n avgPricePerGroupMap.put(k, new BigDecimal(v.sum()).divide(v.size(), 1, RoundingMode.UP))\n }\n return avgPricePerGroupMap\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T17:05:55.503",
"Id": "425091",
"Score": "1",
"body": "Hi Marcelo! Can you edit your post to provide some more detail about what makes this answer better than the original code posted in the question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-09T20:41:54.237",
"Id": "425128",
"Score": "1",
"body": "Sure @cariehl, thanks for the heads up. I added more detail on the changes I made and how I implemented them. Please, let me know if more details are needed for this post. Thanks in advance."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T16:16:46.937",
"Id": "217144",
"ParentId": "217108",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T01:48:06.470",
"Id": "217108",
"Score": "4",
"Tags": [
"beginner",
"array",
"statistics",
"groovy",
"closure"
],
"Title": "Groovy script to get average price per group from different data arrays"
} | 217108 |
<p>I implemented a card game using pygame, the game is a game of war and using png files that I made in Microsoft paint. I tried to keep the object classes as separated from the pygame module as possible. The idea of this is so I can use the CardClasses module with other graphical interfaces, and to reuse it on different games whose displays will be different. When I go to rewrite this, or something similar the idea is to plan on using a Game class as opposed to the more function paradigm I wrote here. I learned that I cant upload the card image files here so I will upload the code in hopes that some brave soul will comb through the lines and give me some feedback. Looking at how to rewrite the doc strings, I feel as though they are weak and only give the idea of the functions or classes they represent.</p>
<p>CardClasses.py</p>
<pre><code>"""Created: 3/30/2019
Objects to represent a playing Card, playing Deck, and Player
"""
from enum import Enum
from itertools import product
from random import shuffle
class ranks(Enum):
TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE = range(2, 15)
class suits(Enum):
CLUBS,DIAMONDS,HEARTS,SPADES = range(1, 5)
class Card(object):
"""Card object represents a standard playing card.
The object attributes, suit and rank, are implemented as enums whose values determine the weight of the card
"""
def __init__(self, suit, rank, in_deck = False, image = None):
if rank in ranks and suit in suits:
self.rank = rank
self.suit = suit
else:
self.rank = None
self.suit = None
self.in_deck = in_deck
self.image = image
self.position_x, self.position_y = 0,0
self.horizontal_demension = None
self.vertical_demension = None
def __str__(self):
return str(self.rank.name) + " " + str(self.suit.name)
def __eq__(self, other):
return True if self.rank == other.rank and self.suit == other.suit else False
def __gt__(self, other):
"""Tests suit precedence, if suits are equal then checks ranks precedence"""
if self.suit == other.suit:
if self.rank.value > other.rank.value:
return True
if self.suit.value > other.suit.value:
return True
return False
class Deck(object):
"""A deck is a collection of 52 Card objects
Object attributes: cards, removed
methods: draw(range = 1), deck_shuffle()
"""
def __init__(self):
self.cards = [Card(suit, rank, in_deck = True) for suit, rank in product(suits, ranks)]
self.removed = []
def __str__(self):
return str([str(card) for card in self.cards])
def draw(self, range = 1):
"""Draw card(s) by removing them from deck"""
drawn_cards = self.cards[:range]
for card in drawn_cards:
card.in_deck = False
del self.cards[:range]
self.removed.append(drawn_cards)
return drawn_cards
def deck_shuffle(self):
"""Shuffles deck object in place"""
shuffle(self.cards)
class Player(object):
"""Implementation of a player object
Object attributes: name, hand, score, turn, card_selected
methods: remove_from_hand(card)
"""
def __init__(self, name, hand = None, score = 0, turn = False):
self.name = name
self.hand = hand
self.score = score
self.turn = turn
self.selected_card = None
def __str__(self):
return str(self.name)
def remove_from_hand(self, card):
"""Removes a card object from the players hand"""
if card and card in self.hand:
position = self.hand.index(card)
del self.hand[position]
return card
return None
</code></pre>
<p>Game.py</p>
<pre><code>"""3/31/2019
Implementation of game of war using pygame and CardClasses
"""
from CardClasses import *
import pygame
green = (0, 200, 50)
def show_hand(screen, player):
"""Displays all cards in hand of player on pygame display object"""
x, y, space_between_cards = 5, 462, 5
for card in player.hand:
card.position_x, card.position_y = x, y
screen.blit(card.image, (x, y))
x += card.horizontal_demension + space_between_cards
def select_card(player, mouse_x, mouse_y):
"""Player selects a card to play"""
if mouse_x:
for card in player.hand:
lower_x, upper_x = (card.position_x, card.position_x + card.horizontal_demension)
lower_y, upper_y = (card.position_y, card.position_y + card.vertical_demension)
if mouse_x > lower_x and mouse_x < upper_x:
if mouse_y > lower_y and mouse_y < upper_y:
player.selected_card = card
def load_card_images(player):
"Loads image, and demensions to card objects"
for card in player.hand:
card.image = pygame.image.load("Cards/" + str(card) + ".png")
width, hieght = card.image.get_size()
card.horizontal_demension = width
card.vertical_demension = hieght
def play_selected_card(screen, player):
"""Display card that is selected on pygame display object"""
x = player.selected_card.position_x = 220
y = player.selected_card.position_y
screen.blit(player.selected_card.image, (x,y))
def show_winner(screen, player1, player2, my_font):
"""Display text stating game winner at end of game"""
screen.fill(green)
winner = str(player1) if player1.score > player2.score else str(player2)
textsurface = my_font.render("The winner is: " + winner, False, (0, 0, 0))
screen.blit(textsurface, (100, 270))
def update_selected_card_position(player, new_y_position):
"""Change the Y position of selected card to move card to played position"""
if player.selected_card:
player.selected_card.position_y = new_y_position
def evaluate(player1, player2):
"""determines who won round and updates their score"""
round_winner = None
if player1.selected_card and player2.selected_card:
pygame.time.delay(1000)
round_winner = player1 if player1.selected_card > player2.selected_card else player2
round_winner.score += 1
player1.selected_card, player2.selected_card = None, None
return round_winner
def show_player_scores(screen, player1, player2):
"""Left corner is player 1 score, right corner is player 2 score"""
font_size = 12
my_font = pygame.font.SysFont('Times New Roman', font_size)
textsurface1 = my_font.render("Player 1 score: " + str(player1.score), False, (0, 0, 0))
textsurface2 = my_font.render("Player 2 score: " + str(player2.score), False, (0, 0, 0))
screen.blit(textsurface1, (0,0))
screen.blit(textsurface2, (470,0))
def flip_turns(player1, player2):
"""Negates Turn attributes of player1 and player2"""
player1.turn = not player1.turn
player2.turn = not player2.turn
def turn(player, mouse_x, mouse_y, new_y_position):
"""Player will select card using mouse_x, and mouse_y, card will be removed from hand and played"""
select_card(player, mouse_x, mouse_y)
player.remove_from_hand(player.selected_card)
update_selected_card_position(player, new_y_position)
def winner_goes_first(winner, loser):
"""Sets the winner to the starter of the next round"""
winner.turn = True
loser.turn = False
def main():
"""GAME of war, each player is given a hand of 10 cards, on each turn a player will select a card to play,
players cards will be compared and the player with the greater in value card will be assigned a point for round victory.
When all cards in hand have been played game ends and winner is displayed
"""
sc_width, sc_height = 555, 555
selected_card_y_pos_player_1 = 330
selected_card_y_pos_player_2 = 230
font_size = 30
delay_time_ms = 1000
number_of_cards = 10
turn_count = 1
deck = Deck()
deck.deck_shuffle()
player1 = Player(input("Player 1 name: "), hand = deck.draw(number_of_cards), turn = True)
player2 = Player(input("Player 2 name: "), hand = deck.draw(number_of_cards))
pygame.init()
screen = pygame.display.set_mode((sc_width, sc_height))
load_card_images(player1)
load_card_images(player2)
pygame.font.init()
my_font = pygame.font.SysFont('Times New Roman', font_size)
"""Main Game Loop"""
game_is_running = True
while game_is_running:
screen.fill(green)
mouse_x, mouse_y = None, None
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
game_is_running = False
quit()
if event.type == pygame.MOUSEBUTTONUP:
mouse_x, mouse_y = pygame.mouse.get_pos()
if player1.turn:
show_hand(screen, player1)
turn(player1, mouse_x, mouse_y, selected_card_y_pos_player_1)
if player1.selected_card:
flip_turns(player1, player2)
else:
show_hand(screen, player2)
turn(player2, mouse_x, mouse_y, selected_card_y_pos_player_2)
if player2.selected_card:
flip_turns(player1, player2)
if player1.selected_card:
play_selected_card(screen, player1)
if player2.selected_card:
play_selected_card(screen, player2)
show_player_scores(screen, player1, player2)
pygame.display.update()
winner = evaluate(player1,player2)
if winner:
if winner == player1:
winner_goes_first(player1, player2)
else:
winner_goes_first(player2, player1)
if not player1.hand and not player2.hand:
show_winner(screen, player1, player2, my_font)
pygame.display.update()
pygame.time.delay(delay_time_ms)
game_is_running = False
if __name__ == '__main__':
main()
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T01:54:41.197",
"Id": "217109",
"Score": "1",
"Tags": [
"python",
"object-oriented",
"game",
"pygame"
],
"Title": "Card Game using pygame module"
} | 217109 |
<p>I'm in the process of creating a n-puzzle solver in Clojurescript. I have the basic model up and running and can move tiles on the screen. I plan to implement A* or such an algorithm to solve a given puzzle. Before I do that, I welcome any general comments for improving the quality of the code right now.</p>
<p>I am just pasting the most important files only here. The entire repo is <a href="https://github.com/nakiya/npuzzle-gen" rel="nofollow noreferrer">here</a></p>
<p><strong>puzzle.cljs</strong></p>
<pre><code> (ns npuzzle.puzzle
(:require [cljs.test :refer-macros [deftest testing is run-tests]]
[clojure.zip :as zip]))
(defn get-tiles [puzzle] (nth puzzle 0))
(defn get-size [puzzle] (nth puzzle 1))
(defn set-tiles [puzzle tiles] (assoc puzzle 0 tiles))
(defn make-puzzle
([size]
[(conj (vec (range 1 (* size size))) :space) size])
([tiles size]
[tiles size]))
(defn index->row-col [puzzle index]
(let [size (get-size puzzle)]
[(quot index size) (mod index size)]))
(defn row-col->index [puzzle [row col]]
(let [size (get-size puzzle)]
(+ (* row size) col)))
(defn get-tile [puzzle [row col]]
((get-tiles puzzle) (+ (* row (get-size puzzle)) col)))
(defn get-index-of-space [puzzle]
(.indexOf (get-tiles puzzle) :space))
(defn get-space-coords [puzzle]
(index->row-col puzzle (get-index-of-space puzzle)))
(defn is-space? [puzzle coords]
(= :space (get-tile puzzle coords)))
(defn valid-coords? [puzzle [row col]]
(let [size (get-size puzzle)]
(and (>= row 0) (>= col 0)
(< row size) (< col size))))
(defn get-adjacent-coords [puzzle [row col]]
(->> '([0 1] [-1 0] [0 -1] [1 0]) ;;'
(map (fn [[dr dc]]
[(+ row dr) (+ col dc)]))
(filter #(valid-coords? puzzle %))))
(defn inversions [puzzle]
(let [size (get-size puzzle)
tiles (get-tiles puzzle)
inversions-fn
(fn [remaining-tiles found-tiles inversions]
(if-let [i (first remaining-tiles)]
(recur (rest remaining-tiles)
(conj found-tiles i)
(+ inversions (- (dec i) (count (filter found-tiles (range i))))))
inversions))]
(inversions-fn (remove #{:space} tiles) #{} 0)))
(defn is-solvable? [puzzle]
(let [inv-cnt (inversions puzzle)
size (get-size puzzle)
[row col] (get-space-coords puzzle)]
(if (odd? size)
(even? inv-cnt)
(if (even? (- size row))
(odd? inv-cnt)
(even? inv-cnt)))))
(defn can-move? [puzzle coords]
;;Check if any one of the adjacent tiles is the space.
(->> (get-adjacent-coords puzzle coords)
(filter #(is-space? puzzle %))
(first)))
(defn swap-tiles [puzzle coord1 coord2]
(let [index1 (row-col->index puzzle coord1)
index2 (row-col->index puzzle coord2)
tile1 (get-tile puzzle coord1)
tile2 (get-tile puzzle coord2)
tiles (get-tiles puzzle)]
(set-tiles puzzle
(-> tiles
(assoc index1 tile2)
(assoc index2 tile1)))))
(defn move [puzzle coords]
(if (can-move? puzzle coords)
(swap-tiles puzzle coords (get-space-coords puzzle))
puzzle))
(defn random-move [puzzle]
(let [space-coords (get-space-coords puzzle)
movable-tiles (get-adjacent-coords puzzle space-coords)
random-movable-tile (nth movable-tiles (rand-int (count movable-tiles)))]
(move puzzle random-movable-tile)))
(defn shuffle-puzzle
"Shuffles by moving a random steps"
([puzzle]
(let [num-moves (+ 100 (rand 200))]
(shuffle-puzzle puzzle num-moves)))
([puzzle num-moves]
(if (> num-moves 0)
(recur (random-move puzzle) (dec num-moves))
puzzle)))
</code></pre>
<p><strong>puzzle_test.cljs</strong></p>
<pre><code>(ns npuzzle.puzzle-test
(:require [cljs.test :refer-macros [deftest testing is run-tests]]
[npuzzle.puzzle :as pzl]))
(deftest puzzle-tests
(let [p1 (pzl/make-puzzle 3)]
(testing "make-puzzle"
(is (= [1 2 3 4 5 6 7 8 :space] (pzl/get-tiles p1)))
(is (= 3 (pzl/get-size p1))))
(testing "get-tile"
(is (= 1 (pzl/get-tile p1 [0 0])))
(is (= 2 (pzl/get-tile p1 [0 1])))
(is (= 5 (pzl/get-tile p1 [1 1]))))
(testing "get-index-of-space"
(is (= 8 (pzl/get-index-of-space p1))))
(testing "get-space-coords"
(is (= [2 2] (pzl/get-space-coords p1))))
(testing "is-space?"
(is (pzl/is-space? p1 [2 2]))
(is (not (pzl/is-space? p1 [2 1]))))
(testing "index->row-col"
(is (= [1 1] (pzl/index->row-col p1 4)))
(is (= [2 3] (pzl/index->row-col (pzl/make-puzzle 5) 13))))
(testing "row-col->index"
(is (= 4 (pzl/row-col->index p1 [1 1])))
(is (= 13 (pzl/row-col->index (pzl/make-puzzle 5) [2 3]))))
(testing "valid-coords?"
(is (pzl/valid-coords? p1 [1 1]))
(is (not (pzl/valid-coords? p1 [2 3]))))
(testing "get-adjacent-coords"
(is (= #{[0 1] [1 0] [1 2] [2 1]} (into #{} (pzl/get-adjacent-coords p1 [1 1]))))
(is (= #{[0 1] [1 0]} (into #{} (pzl/get-adjacent-coords p1 [0 0])))))
(testing "can-move?"
(is (pzl/can-move? p1 [1 2]))
(is (pzl/can-move? p1 [2 1]))
(is (not (pzl/can-move? p1 [1 1]))))
(testing "move"
(is (= [1 2 3 4 5 :space 7 8 6] (pzl/get-tiles (pzl/move p1 [1 2]))))
(is (= [1 2 3 4 :space 5 7 8 6] (pzl/get-tiles (pzl/move (pzl/move p1 [1 2]) [1 1]))))
(is (= [1 2 3 4 5 6 7 8 :space] (pzl/get-tiles (pzl/move p1 [0 1])))))
(testing "inversions"
(is (= 10 (pzl/inversions (pzl/make-puzzle [1 8 2 :space 4 3 7 6 5] 3))))
(is (= 41 (pzl/inversions (pzl/make-puzzle [13 2 10 3 1 12 8 4 5 :space 9 6 15 14 11 7] 4))))
(is (= 62 (pzl/inversions (pzl/make-puzzle [6 13 7 10 8 9 11 :space 15 2 12 5 14 3 1 4] 4))))
(is (= 56 (pzl/inversions (pzl/make-puzzle [3 9 1 15 14 11 4 6 13 :space 10 12 2 7 8 5] 4)))))
(testing "is-solvable?"
(is (pzl/is-solvable? (pzl/make-puzzle [1 8 2 :space 4 3 7 6 5] 3)))
(is (pzl/is-solvable? (pzl/make-puzzle [13 2 10 3 1 12 8 4 5 :space 9 6 15 14 11 7] 4)))
(is (pzl/is-solvable? (pzl/make-puzzle [6 13 7 10 8 9 11 :space 15 2 12 5 14 3 1 4] 4)))
(is (not (pzl/is-solvable? (pzl/make-puzzle [3 9 1 15 14 11 4 6 13 :space 10 12 2 7 8 5] 4)))))
(testing "shuffle-puzzle"
(is (pzl/is-solvable? (pzl/shuffle-puzzle (pzl/make-puzzle 4))))
(is (pzl/is-solvable? (pzl/shuffle-puzzle (pzl/make-puzzle 6))))
(is (pzl/is-solvable? (pzl/shuffle-puzzle (pzl/make-puzzle 9))))
(is (not= (pzl/shuffle-puzzle (pzl/make-puzzle 3)) (pzl/make-puzzle 3)))
(is (not= (pzl/shuffle-puzzle (pzl/make-puzzle 8)) (pzl/make-puzzle 8))))))
(run-tests)
</code></pre>
<p><strong>views.cljs</strong></p>
<pre><code>(ns npuzzle.views
(:require
[re-frame.core :as re-frame]
[npuzzle.subs :as subs]
[npuzzle.events :as ev]))
(defn- on-puzzle-size-changed [e]
(re-frame/dispatch [::ev/change-puzzle-size (int (-> e .-target .-value))]))
(defn- on-tile-mouse-down [e]
(let [idx (.getAttribute (-> e .-target) "data-tileindex")]
(re-frame/dispatch [::ev/move-tile (int idx)])))
(defn- tile-div [idx tile]
[:div {:style {:text-align :center
:padding "15px"
:font-size "20px"
:border (if (not= :space tile) "1px solid black" :none)
:background (if (not= :space tile) :lightblue nil)
:height "25px"
:width "25px"
;;cursor = default for disabling caret on hover over text
:cursor :default}
:onMouseDown on-tile-mouse-down
:data-tileindex idx}
(if (= :space tile)
" "
tile)])
(defn- tiles-container [puzzle size tile-fn]
(into [:div {:style {:display :inline-grid
:grid-template-columns (apply str (repeat size "auto "))
:grid-gap "2px"
:border "2px solid black"}}]
(map-indexed
(fn [idx tile]
(tile-fn idx tile)) puzzle)))
(defn main-panel []
(let [name (re-frame/subscribe [::subs/name])
sizes (re-frame/subscribe [::subs/size-choices])
current-size (re-frame/subscribe [::subs/puzzle-size])
puzzle (re-frame/subscribe [::subs/puzzle])]
[:div
[:h1 "Hello to " @name]
[:div
{:style {:padding "10px"}}
(into [:select {:name "puzzle-size"
:on-change on-puzzle-size-changed
:defaultValue @current-size}]
(for [size @sizes]
(into [:option {:value size} size])))]
(tiles-container @puzzle @current-size tile-div)]))
</code></pre>
| [] | [
{
"body": "<p>I don't really see anything major. I also don't know Cljs (only Clj), so I apologize if a suggestion of mine doesn't apply to Cljs.</p>\n\n<p>Just a few small things:</p>\n\n<p>Personally, I don't like having function definitions all on one line. Increasingly, I'm even splitting <code>def</code> definitions over two lines. I find it generally helps readability. I'd change your definitions at the top to:</p>\n\n<pre><code>(defn get-tiles [puzzle]\n (nth puzzle 0))\n\n(defn get-size [puzzle]\n (nth puzzle 1))\n\n(defn set-tiles [puzzle tiles]\n (assoc puzzle 0 tiles))\n</code></pre>\n\n<hr>\n\n<p>And I don't see any sample data, but judging by the first two functions, you seem to be storing the puzzle as a vector \"tuple\" of <code>[tiles size]</code>. You may find that it's neater to store that as a map instead. Something like <code>{:tiles [...], :size ...}</code>. That gives you getters for free (as keywords), and makes the structure itself more self explanatory.</p>\n\n<hr>\n\n<p>You're using <code>:space</code> as a sentinel value. You may find using a namespaced-qualified version (<code>::space</code> internally) is beneficial. I like using <code>::</code> keywords when possible because IntelliJ gives better autocomplete suggestions when using namespaced keywords, so it's harder to cause typos.</p>\n\n<hr>\n\n<p><code>valid-coords?</code> can be simplified a bit by taking advantage of \"comparison chaining\":</p>\n\n<pre><code>(defn valid-coords? [puzzle [row col]]\n (let [size (get-size puzzle)]\n (and (< -1 row size)\n (< -1 col size))))\n</code></pre>\n\n<p>You could also use <code><=</code> and <code>dec</code> <code>size</code> before comparing:</p>\n\n<pre><code>(defn valid-coords? [puzzle [row col]]\n (let [size (dec (get-size puzzle))]\n (and (<= 0 row size)\n (<= 0 col size))))\n</code></pre>\n\n<hr>\n\n<p><code>is-solvable?</code> can have some of its nesting reduced using <code>cond</code>:</p>\n\n<pre><code>(defn is-solvable? [puzzle]\n (let [inv-cnt (inversions puzzle)\n size (get-size puzzle)\n [row col] (get-space-coords puzzle)]\n (cond\n (odd? size) (even? inv-cnt)\n (even? (- size row)) (odd? inv-cnt)\n :else (even? inv-cnt))))\n</code></pre>\n\n<p>I go back and forth between putting the conditions and bodies on the same and separate lines. In this case though, everything is short enough that readability is fine. If I spaced this out like I normally would:</p>\n\n<pre><code>(defn is-solvable? [puzzle]\n (let [inv-cnt (inversions puzzle)\n size (get-size puzzle)\n [row col] (get-space-coords puzzle)]\n (cond\n (odd? size)\n (even? inv-cnt)\n\n (even? (- size row))\n (odd? inv-cnt)\n\n :else\n (even? inv-cnt))))\n</code></pre>\n\n<p>It becomes huge, although I do think the readability is better in the second version.</p>\n\n<hr>\n\n<p><code>(if (> num-moves 0)</code> can alternatively be written as <code>(if (pos? num-moves)</code>.</p>\n\n<hr>\n\n<p>A lot of your tests have a series of <code>is</code> checks that are all basically checking the same thing, just with different data:</p>\n\n<pre><code>(testing \"get-tile\"\n (is (= 1 (pzl/get-tile p1 [0 0])))\n (is (= 2 (pzl/get-tile p1 [0 1])))\n (is (= 5 (pzl/get-tile p1 [1 1]))))\n</code></pre>\n\n<p>This can be simplified using <a href=\"https://clojuredocs.org/clojure.test/are\" rel=\"nofollow noreferrer\"><code>are</code></a>:</p>\n\n<pre><code>(testing \"get-tile\"\n (are [result coord] (= result (pzl/get-tile p1 coord))\n 1 [0 0]\n 2 [0 1]\n 5 [1 1]))\n</code></pre>\n\n<p>That gets rid of a <em>lot</em> of explicit duplicate calls and noise.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T08:30:02.887",
"Id": "420096",
"Score": "0",
"body": "Thanks for all the suggestions. I will incorporate these in..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T15:20:58.677",
"Id": "217140",
"ParentId": "217110",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "217140",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T02:52:38.880",
"Id": "217110",
"Score": "3",
"Tags": [
"clojure",
"sliding-tile-puzzle",
"clojurescript"
],
"Title": "n-puzzle in Clojurescript"
} | 217110 |
<p>I have a working script that will batch add users to an instance of nextcloud running on top of docker. This version is the result of changes made after asking this <a href="https://codereview.stackexchange.com/questions/216335/batch-upload-users-to-nextcloud-on-docker-with-bash-csv/216345?noredirect=1#comment418813_216345">question</a>.</p>
<p>I guess I'm looking for a re-review to ensure that I haven't missed anything. I'm also interested if there are areas where I could make things better in terms of readability, performance, security, etc. You're the reviewer. My code is your oyster.</p>
<pre><code>#!/bin/sh
set -eu
# Handle printing errors
die () {
printf '%s\n' "$1" >&2
exit 1
}
message () {
printf '%s\n' "$1" >&2
}
usage () {
cat <<'EOF'
NAME
batch_up - batch upload users
SYNOPSIS
batch_up -?
batch_up -h
batch_up --help
batch_up -v
batch_up -vv
batch_up -vvv
batch_up --verbose
batch_up -d
batch_up --delimiter
batch_up --delimiter=
DESCRIPTION
Batch_up is a program that adds a batch of users to an instance of NextCloud
running inside of a docker container by reading a comma separated list from
stdin or a csv file. Stdin is the default and will be used if no file is
supplied. The delimiter does not have to be a comma, and can be set via the
-d flag.
CSV file should be formatted in one of the following configurations:
username,Display Name,group,email@address.domain
username,Display Name,group
username,Display Name
username
CSV files should not include the header.
OPTIONS
-? or -h or --help
This option displays a summary of the commands accepted by batch_up.
-v or -vv or -vvv or --verbose
This option sets the verbosity. Each v adds to the verbosity.
See the occ command for OwnCloud/NextCloud for more details as this
option is passed on to the occ command.
If this option is not passed, the default behavior is to pass the
-q option to occ (the quiet option), making occ non-verbose.
-d or --delimiter or --delimiter=
This option allows you to choose which delimiter you would like to use.
The following are acceptable characters for this option. ,.;:|
ENVIRONMENT VARIABLES
OC_PASS
Sets the password for users added. The OC_PASS environment variable
is required.
EXAMPLES
The command:
batch_up.sh foobar.csv
Will add the users from foobar.csv. Users will be given the password
in the OC_PASS environment variable.
The command:
batch_up.sh <<< "jack,Jack Frost,users,jack.frost@gmail.com"
Will add the user jack, set his display name to Jack Frost, add him
to the group users, and set his email to jack.frost@gmail.com.
The command:
echo "jack,Jack Frost,users,jack.frost@gmail.com" | batch_up.sh
Will add the user jack, set his display name to Jack Frost, add him
to the group users, and set his email to jack.frost@gmail.com.
The command:
batch_up.sh -d : foobar.csv
Will set the delimiter to : and add the users from foobar.csv.
EOF
}
# Set verbosity. Default is silent.
verbose=-q
# flags
while [ $# -gt 0 ]
do
case $1 in
-h|-\?|--help)
usage # Display a usage synopsis.
exit
;;
-v|-vv|-vvv|--verbose)
verbose=$1
;;
-d|--delimiter)
if [ $# -gt 1 ]
then
case $2 in
,|.|\;|:|\|)
delimiter=$2
shift
;;
*)
die 'Error: delimiter should be one of ,.;:| characters.'
esac
else
die 'Error: "--delimiter requires a non-empty option argument.'
fi
;;
--delimiter=?*)
case ${1#*=} in # Delete everything up to the = and assign the remainder.
,|.|\;|:|\|)
delimiter=${1#*=}
shift
;;
*)
die 'Error: delimiter should be one of ,.;:| characters.'
esac
;;
--delimiter=) # Handle the case of empty --delimiter=
die 'Error: "--delimiter=" requires a non-empty option argument.'
;;
--)
shift
break
;;
-?*)
printf 'WARN: Unknown option (ignored): %s\n' "$1" >&2
;;
*) # Default case. No more options, so break out of the loop
break
esac
shift
done
# Is the file readable?
if [ $# -gt 0 ]
then
[ -r "$1" ] || die "$1: Couldn't read file."
fi
# Is the OC_PASS environment variable set?
[ ${OC_PASS:-} ] || die "$0: No password specified. Run with --help for more info."
status=true # until a command fails
message 'Adding users'
while IFS=${delimiter:-,} read -r f1 f2 f3 f4
do
if [ "$f1" ]
then
docker-compose exec -T -e OC_PASS --user www-data app php occ \
user:add --password-from-env \
${verbose:+"$verbose"} \
${f2:+"--display-name=$f2"} \
${f3:+"--group=$f3"} \
"$f1" </dev/null \
|| status=false
# If there is a fourth value in the csv, use it to set the user email.
if [ "$f4" ]
then
docker-compose exec -T \
--user www-data app php occ \
user:setting "$f1" settings email "$f4" \
</dev/null \
|| status=false
fi
else
echo "Expected at least one field, but none were supplied." >&2
status=false
continue
fi
message '...'
done <"${1:-/dev/stdin}"
message 'Done'
exec $status
</code></pre>
| [] | [
{
"body": "<h3>Don't repeat yourself</h3>\n\n<p>There is redundant logic in the processing of the <code>-d</code> and <code>--delimiter=...</code> options. I would eliminate that, to be something more like this:</p>\n\n<pre><code>-d|--delimiter)\n [ $# -gt 1 ] && arg=$1 || arg=\n parseDelimiter \"$arg\"\n ;;\n--delimiter=*)\n parseDelimiter \"${1#*=}\"\n ;;\n</code></pre>\n\n<p>Where <code>parseDelimiter</code> is a function that will parse the passed argument and set <code>delimiter</code> appropriately, or exit with an error.</p>\n\n<h3>A simpler pattern in <code>case</code> (maybe)</h3>\n\n<p>Instead of <code>,|.|\\;|:|\\|)</code>, perhaps <code>[,.\\;:\\|])</code> is slightly simpler and easier to type (less likely you mistype something, for example less likely to forget a <code>|</code> between the different allowed values).</p>\n\n<h3>Assign positional arguments to descriptive variables early on</h3>\n\n<p>Near the end of the script I see <code>done <\"${1:-/dev/stdin}\"</code>, and wonder:\n<em>what was <code>$1</code> again?</em>\nI think it's easier to understand when positional arguments are assigned to variables with descriptive names early on in a script.</p>\n\n<h3>Prefer comments on their own lines</h3>\n\n<p>I read code from top to bottom,\nand this line makes my eyes make an unnecessary detour to the right:</p>\n\n<blockquote>\n<pre><code>status=true # until a command fails\n</code></pre>\n</blockquote>\n\n<p>I would have preferred that comment on its own line just before the code it's referring to.</p>\n\n<p>Incidentally, I don't understand what this comment is trying to say.\nThe <code>status</code> variable is used to determine the exit status of the program.\nIn this script, it will be \"failure\" if some failure happened in the loop body, otherwise \"success\".</p>\n\n<p>I would have named this <code>exit_status</code>, and then at the end of the script do <code>exit \"$exit_status\"</code>, rather than the current <code>exec $status</code>, which I find a bit odd.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-11T05:45:30.173",
"Id": "220078",
"ParentId": "217111",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T03:35:29.610",
"Id": "217111",
"Score": "3",
"Tags": [
"csv",
"posix",
"sh",
"docker"
],
"Title": "batch add users to nextcloud on docker with csv"
} | 217111 |
<p>I have below code which will fetch the text from json & onclick text , display pop up box in page.... Now i need to give options to change font-family, font color....</p>
<p>But Adding the code in the place of <strong>Content</strong> is going to be extremely difficult....</p>
<p>Is there any way so that i can improve code structure or write same code in another way ?</p>
<p><a href="https://i.stack.imgur.com/S1Aky.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/S1Aky.png" alt="enter image description here"></a></p>
<p><strong>JSON</strong> :</p>
<pre><code>{
"font" : "Arian",
"x" : 201,
"y" : 461,
"src" : "180ef82d1.otf",
"width" : 679,
"type" : "text",
"text" : "Good Food",
"name" : "edit_good_1"
}
</code></pre>
<p><strong>script</strong></p>
<pre><code>const lightId = 'light' + layer.name
const lightIdString = '#' + lightId
$('.container').append(
'<a id ="' + layer.name + '" onclick="openPopUp(' + lightId + ')"' +
'<div class="txtContainer" contenteditable="true" ' +
'style="' +
'left: ' + layer.x + 'px; ' +
'top: ' + layer.y + 'px; ' +
'">' + layer.text + '</div></a>' +
'<div id="light' + layer.name + '" class="white_content" style="' +
'top: ' + layer.y + 'px; ' + '"> content <a href="javascript:void(0)" ' +
'onclick="closePopUp(' + lightId + ')">Close</a></div> <div>'
);
document.getElementById(lightId).style.left = layer.x + document.getElementById(layer.name).offsetWidth + 'px'
</code></pre>
<p>codepen : <a href="https://codepen.io/kidsdial/pen/OGbGwN" rel="nofollow noreferrer">https://codepen.io/kidsdial/pen/OGbGwN</a></p>
<p>fiddle : <a href="https://jsfiddle.net/kidsdial1/z6eyq4j3/" rel="nofollow noreferrer">https://jsfiddle.net/kidsdial1/z6eyq4j3/</a></p>
| [] | [
{
"body": "<p>Your code is very prone to errors, since you write all your html tags and content as a single string. Containing html and javascript in that way is extremely unsafe. </p>\n\n<p>I would suggest creating your elements with <code>document.createElement()</code> and then using the JSON to set all the attributes. In the function you could just pass the id, and then find the correct json data for that id.</p>\n\n<p>Concept code</p>\n\n<pre><code>function buildPopup(id) {\n let layer = findJsonData(id)\n\n let popup = document.createElement(\"div\")\n popup.classList.add(\"txtContainer\")\n popup.id = layer.name\n popup.style.left = layer.x + \"px\"\n popup.style.top = layer.y + \"px\"\n popup.style.fontFamily = layer.font\n popup.innerHTML = layer.text\n\n // adding a close button\n let btn = document.createElement(\"button\")\n popup.appendChild(btn)\n btn.addEventListener(\"click\", ()=>{\n closePopup(layer.name)\n })\n\n document.body.appendChild(popup)\n}\n</code></pre>\n\n<p>Example for calling this function</p>\n\n<pre><code> <a onclick=\"openPopUp('edit_good_1')\">Open popup</a>\n</code></pre>\n\n<p>Example for getting the json by id</p>\n\n<pre><code> // this function will find the right json data for this id \n function findJsonData(id){\n return { \n \"font\" : \"Arian\",\n \"x\" : 201,\n \"y\" : 461,\n \"src\" : \"180ef82d1.otf\",\n \"width\" : 679,\n \"type\" : \"text\", \n \"text\" : \"Good Food\", \n \"name\" : \"edit_good_1\"\n }\n }\n</code></pre>\n\n<p>I realise this is a bit conceptual but hopefully it will point you in the right direction!</p>\n\n<p><a href=\"https://jsfiddle.net/hjvbp9qc/4/\" rel=\"nofollow noreferrer\">JSFiddle</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T11:45:08.653",
"Id": "419981",
"Score": "0",
"body": "Thanks a lot, is it possible for you to update your code in codepen i posted in question ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T11:58:08.783",
"Id": "419982",
"Score": "1",
"body": "My intention was to give you some pointers on how to improve your code , I have added a JSFiddle to show that it works!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T12:52:25.907",
"Id": "419997",
"Score": "0",
"body": "Thanks again, in json i posted in question, there are multiple layers , some layers have images & some have text..... i will try your code in the codepen i posted in question....."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T15:09:28.560",
"Id": "420024",
"Score": "1",
"body": "Bear in mind that if your code becomes too complicated, you can probably simplify it at a higher level. For example, you could define your popups in `template` tags to save yourself a lot of `createElement` lines. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T11:41:25.227",
"Id": "217128",
"ParentId": "217116",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "217128",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T07:48:08.597",
"Id": "217116",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"html"
],
"Title": "Fetch text values from JSON and Display pop onclick text"
} | 217116 |
<p>I am new to spark. I have two dataframes df1 and df2. df1 has three rows. df2 has more than few million rows. I want to check whether all items in df2 are in transaction of df1, if so sum up the costs. Example as follows:</p>
<pre><code> df1 = spark.createDataFrame(
[(1, [(1), (4), (2) ,(3)])],
("id", "transaction")
)
df2 = spark.createDataFrame(
[([ (1),(2),(3)], 2.0), ([(5),(2),(3)], 1.0) ],
("items", "cost")
)
</code></pre>
<p>Desired Result is:</p>
<pre><code> id transaction score
1 [1,4,2,3] 2.0
</code></pre>
<p>My Current code is:</p>
<pre><code>out=df1.crossJoin(df2)
@udf('boolean')
def check(trans,itm):
itertrans = iter(trans)
return all(i in itertrans for i in itm)
out.groupby('id','transaction')\
.agg(sum_(when(check('transaction','items'),col('cost'))).alias('score'))\
.show()
</code></pre>
<p>The other solution which i have:</p>
<pre><code> costs = (df1
# Explode transaction
.select("id", explode("transactions").alias("item"))
.join(
df2
# Add id so we can later use it to identify source
.withColumn("_id", monotonically_increasing_id().alias("_id"))
# Explode items
.select(
"_id", explode("items").alias("item"),
# We'll need size of the original items later
size("items").alias("size"), "cost"),
["item"])
# Count matches in groups id, items
.groupBy("_id", "id", "size", "cost")
.count()
# Compute cost
.groupBy("id")
.agg(sum_(when(col("size") == col("count"), col("cost"))).alias("score")))
costs.show()
</code></pre>
<p>with 500,000 rows of df2, crossJoin method produced results quicker (in 6 min) when compared to the explode and join soution (which took 15 mins).</p>
<p>with 900,000 rows of df2, both solution run for hours without results.
I run the program in standalone mode. </p>
<p>Questions:</p>
<p>How can i improve the speed? Any other solution?
if i convert to rdd and run in clutser, will the process speeds up?
How to convert to rdd?(i tried but don't know how to convert the group by and aggreagta part)</p>
<p>Any help would be great.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T09:04:44.067",
"Id": "217117",
"Score": "3",
"Tags": [
"python",
"performance",
"python-3.x",
"sql",
"apache-spark"
],
"Title": "spark takes long time for checking an array of items present in another array"
} | 217117 |
<p>I am trying to apply a function to each group in a pandas dataframe where the function requires access to the entire group (as opposed to just one row). For this I am iterating over each group in the groupby object. Is this the best way to achieve this?</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'id': [1,1,1,1,2,2,2],
'value': [70,10,20,100,50,5,33],
'other_value': [2.3, 3.3, 7.4, 1.1, 5, 10.3, 12]})
def clean_df(df, v_col, other_col):
'''This function is just a made up example and might
get more complex in real life. ;)
'''
prev_points = df[v_col].shift(1)
next_points = df[v_col].shift(-1)
return df[(prev_points > 50) | (next_points < 20)]
grouped = df.groupby('id')
pd.concat([clean_df(group, 'value', 'other_value') for _, group in grouped])
</code></pre>
<p>The original dataframe is</p>
<pre><code> id other_value value
0 1 2.3 70
1 1 3.3 10
2 1 7.4 20
3 1 1.1 100
4 2 5.0 50
5 2 10.3 5
6 2 12.0 33
</code></pre>
<p>The code will reduce it to </p>
<pre><code> id other_value value
0 1 2.3 70
1 1 3.3 10
4 2 5.0 50
</code></pre>
| [] | [
{
"body": "<p>You can directly use <code>apply</code> on the grouped dataframe and it will be passed the whole group:</p>\n\n<pre><code>def clean_df(df, v_col='value', other_col='other_value'):\n '''This function is just a made up example and might \n get more complex in real life. ;)\n '''\n prev_points = df[v_col].shift(1)\n next_points = df[v_col].shift(-1)\n return df[(prev_points > 50) | (next_points < 20)] \n\ndf.groupby('id').apply(clean_df).reset_index(level=0, drop=True)\n# id other_value value\n# 0 1 2.3 70\n# 1 1 3.3 10\n# 4 2 5.0 50\n</code></pre>\n\n<p>Note that I had to give the other arguments default values, since the function that is applied needs to have only one argument. Another way around this is to make a function that returns the function:</p>\n\n<pre><code>def clean_df(v_col, other_col):\n '''This function is just a made up example and might \n get more complex in real life. ;)\n '''\n def wrapper(df):\n prev_points = df[v_col].shift(1)\n next_points = df[v_col].shift(-1)\n return df[(prev_points > 50) | (next_points < 20)] \n return wrapper\n</code></pre>\n\n<p>Which you can use like this:</p>\n\n<pre><code>df.groupby('id').apply(clean_df('value', 'other_value')).reset_index(level=0, drop=True)\n</code></pre>\n\n<p>Or you can use <a href=\"https://docs.python.org/3/library/functools.html#functools.partial\" rel=\"nofollow noreferrer\"><code>functools.partial</code></a> with your <code>clean_df</code>:</p>\n\n<pre><code>from functools import partial\n\ndf.groupby('id') \\\n .apply(partial(clean_df, v_col='value', other_col='other_value')) \\\n .reset_index(level=0, drop=True)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T11:54:36.007",
"Id": "217130",
"ParentId": "217118",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "217130",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T09:44:05.080",
"Id": "217118",
"Score": "1",
"Tags": [
"python",
"pandas"
],
"Title": "Applying a dataframe function to a pandas groupby object"
} | 217118 |
<p>I was presented with an interview question described as follows:</p>
<p>Receiving an <code>int[] A</code> of cities, where each <code>A[i]</code> has an appeal value. We want to plan our trip based on the highest appeal possible, taking in mind that is calculated as follows <code>A[i] + A[j] + (i - j)</code>. This means the appeal values of 2 cities summed, plus their distance.</p>
<p>Function signature:</p>
<p><code>public static int solution(int[] A);</code></p>
<p>The constraints were the following:</p>
<ul>
<li>N is an integer within [1, 100,000]</li>
<li>A[i] is an integer within [-1,000,000,000, 1,000,000,000]</li>
</ul>
<p>Using the <strong>same value</strong> is a possible valid solution, so for example, if we have <code>A = {1, 3, -3};</code> this should return <code>6</code> as visiting city <code>A[0]</code> twice gives the max appeal value <code>A[0] + A[0] + (0 - 0) = 6</code>.</p>
<p>So given that, a possible solution is the same value twice, I did not found other solution than:</p>
<pre><code>int highestAppeal = 0;
for (int i = 0; i < A.length; i++) {
for (int j = 0; j < A.length; j++) {
int currentAppeal = A[i] + A[j] + (i - j);
highestAppeal = currentAppeal > highestAppeal ? currentAppeal : highestAppeal;
}
}
return highestAppeal;
</code></pre>
<p>This solution was marked as pretty bad. I realize that a <span class="math-container">\$O(n^2)\$</span> solution is far from efficient, but in this case, I did not see how to improve it. Later on, I thought about sorting <code>A</code> values in descending order and, for repeated values, using indexes in ascending order. But I don't see that going forward.</p>
<p>What would be a better and more efficient solution for this?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T12:13:46.947",
"Id": "419987",
"Score": "0",
"body": "Well, I've added the expected function signature, so it is clear that an ```int``` is expected as result."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T12:16:28.743",
"Id": "419989",
"Score": "0",
"body": "Ah, sorry, missed that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T12:24:18.090",
"Id": "419990",
"Score": "1",
"body": "I deleted my answer. I've come to the conclusion that this was a trick question with a purpose of finding out if you notice bad requirements and are able to ask clarifications."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T12:25:45.633",
"Id": "419991",
"Score": "0",
"body": "I had lots of things to ask clarification for, but they sent me as an assignment through a site. I had 2 tasks which I had to do in 1 hour. This was one of them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T12:26:35.237",
"Id": "419992",
"Score": "0",
"body": "So, had no contact or any way of asking anything."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T12:26:35.657",
"Id": "419993",
"Score": "0",
"body": "You dodged a bullet. The task was incredibly badly set up. Good luck with the next application."
}
] | [
{
"body": "<p>Thinking this more, there are three things affecting the appeal.</p>\n\n<ul>\n<li>A[i]</li>\n<li>A[j]</li>\n<li>i - j</li>\n</ul>\n\n<p>Since <code>A[i] + A[j]</code> is the same as <code>A[j] + A[i]</code>, you don't need to traverse the whole array in the inner loop.</p>\n\n<p>Since the third component increases the appeal only when <code>j < i</code>, you can restrict the inner loop to run from 0 to i.</p>\n\n<p>You also need to take into account the fact that all cities may have negative appeal. Integer.MIN_VALUE is safe initial value, as the lowest valid value (2 * -1000000000 - 100000) is still greater than that.</p>\n\n<p>Using Math.max would have been more readable.</p>\n\n<pre><code> int highestAppeal = Integer.MIN_VALUE;\n\n for (int i = 0; i < A.length; i++) {\n for (int j = 0; j <= i; j++) {\n final int currentAppeal = A[i] + A[j] + (i - j);\n highestAppeal = Math.max(highestAppeal, currentAppeal);\n }\n }\n\n return highestAppeal; \n</code></pre>\n\n<p>And you can't overestimate the value of commented code in an interview answer.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T12:15:40.067",
"Id": "217131",
"ParentId": "217120",
"Score": "1"
}
},
{
"body": "<p>Yesterday, I asked the interviewers themselves for an efficient solution to this problem, and I finally got one:</p>\n\n<pre><code>int maxStart = A[0];\nint maxEnd = A[0];\n\nfor (int i = 0; i < A.length; i++) {\n if ((A[i] - i) > maxStart) {\n maxStart = A[i] - i;\n }\n\n if ((A[i] + i) > maxEnd) {\n maxEnd = A[i] + i;\n }\n}\n\nreturn maxEnd + maxStart;\n</code></pre>\n\n<p>So this is the O(n) solution they gave me, which I found pretty beautiful to be honest.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T10:22:01.970",
"Id": "217192",
"ParentId": "217120",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "217192",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T10:10:58.277",
"Id": "217120",
"Score": "4",
"Tags": [
"java",
"performance",
"algorithm",
"interview-questions"
],
"Title": "Trip planning algorithm"
} | 217120 |
<p>I have come up with the following method to remove sensitive information with the help of the garbage collector:</p>
<pre><code>def wipe_sensitive_info(d, keys):
"""
In Python we are not able to overwrite memory areas. What we do is:
- remove references to the specified objects, in this case keys in a dictionary
- immediately call garbage collection
"""
# TODO: the following points are pending
# - this relies on the gc to remove the objects from memory (de-allocate memory).
# - the memory itself is not guaranteed to be overwritten.
# - this will only deallocate objects which are not being referred somewhere else (ref count 0 after del)
for key in keys:
del d[key]
logger.info('Garbage collected {} objects'.format(gc.collect()))
</code></pre>
<p>This would be called from a django app as follows:</p>
<pre><code>wipe_sensitive_info(request.data, ['password'])
</code></pre>
<p>Any ideas or comments on how to improve this implementation?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T14:00:26.570",
"Id": "420011",
"Score": "0",
"body": "Please provide more details about this \"sensitive information\". Are they strings? Where and how do you use them?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T14:02:53.943",
"Id": "420012",
"Score": "0",
"body": "What is your motivation for doing this (i.e. what is your threat model)? Do you want to prevent accidental logging? Access from a hostile plugin? A hacker who might somehow examine a memory dump?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T16:00:29.503",
"Id": "420034",
"Score": "0",
"body": "@200_success The attack vector is a memory dump"
}
] | [
{
"body": "<p>One advantage of the <code>logger</code> module is that you can pass it strings and objects to log at some level, and the string formatting is only performed if it is actually needed (i.e. the logging level is low enough). Also, having the <code>gc.collect()</code> actually hides it a lot, I was looking for it for some time. So I would do this instead:</p>\n\n<pre><code>def wipe_sensitive_info(d, keys):\n \"\"\"\n In Python we are not able to overwrite memory areas. What we do is:\n - remove references to the specified objects, in this case keys in a dictionary\n - immediately call garbage collection\n \"\"\"\n # TODO: the following points are pending\n # - this relies on the gc to remove the objects from memory (de-allocate memory).\n # - the memory itself is not guaranteed to be overwritten.\n # - this will only deallocate objects which are not being referred somewhere else (ref count 0 after del)\n for key in keys:\n del d[key]\n n_garbage_collected = gc.collect()\n logger.info(\"Garbage collected %s objects\", n_garbage_collected)\n</code></pre>\n\n<p>You could add a check for objects which have reference counts left:</p>\n\n<pre><code>import sys\n\n...\n\nfor key in keys:\n if sys.getrefcount(d[key]) > 2:\n # The count returned is generally one higher than you might expect,\n # because it includes the (temporary) reference as an argument to\n # getrefcount().\n logger.debug(\"Object potentially has references left: %s\", key)\n del d[key]\n</code></pre>\n\n<p>Note that this might give you some false positives for interned objects, like small integers or strings. Case in point, in an interactive session, <code>sys.getrefcount(\"s\")</code> just gave me <code>1071</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T17:17:37.983",
"Id": "217151",
"ParentId": "217125",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T10:58:05.523",
"Id": "217125",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"security",
"memory-management",
"django"
],
"Title": "Wipe sensitive information from memory in Python"
} | 217125 |
<p>So, I am new to VS and C#, I am self-teaching to get a better understanding of the back-end of the product I work with. I have created a small database with some information and a Login form. Everything appears to compile correctly but is that the security way to do that or there is another way, any help is appreciated. Thanks.</p>
<pre><code> private void button2_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("select * from tbladmin where username=@username and password=@password", sqlcon);
cmd.Parameters.AddWithValue("@username", txtusername.Text);
cmd.Parameters.AddWithValue("@password", txtpassword.Text);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dtbl = new DataTable();
sda.Fill(dtbl);
try
{
if (dtbl.Rows.Count > 0)
{
if (dtbl.Rows[0]["role"].ToString() == "Admin")
{
SqlCommand cmd2 = new SqlCommand("select date from tbladmin where username=@username and password=@password", sqlcon);
cmd2.Parameters.AddWithValue("@username", txtusername.Text);
cmd2.Parameters.AddWithValue("@password", txtpassword.Text);
SqlDataAdapter sda2 = new SqlDataAdapter(cmd2);
DataTable dss = new DataTable();
sda2.Fill(dss);
String value2 = dss.Rows[0][0].ToString();
DateTime date = DateTime.Parse(dss.Rows[0][0].ToString());
Class1.Txtusername = txtusername.Text;
Debug.WriteLine("value is : " + value2);
if (date.AddDays(90) < DateTime.Now)
{
Changpassad obj2 = new Changpassad();
this.Hide();
obj2.Show();
}
else
{
calladmin obj = new calladmin(dss.Rows[0][0].ToString());
this.Hide();
obj.Show();
}
}
}
else if (dtbl.Rows.Count == 0)
{
SqlCommand cmd3 = new SqlCommand("select date from tblcallcenter where username=@username and password=@password", sqlcon);
cmd3.Parameters.AddWithValue("@username", txtusername.Text);
cmd3.Parameters.AddWithValue("@password", txtpassword.Text);
SqlDataAdapter sda2 = new SqlDataAdapter(cmd3);
DataTable dss = new DataTable();
sda2.Fill(dss);
String value2 = dss.Rows[0][0].ToString();
DateTime date = DateTime.Parse(dss.Rows[0][0].ToString());
Debug.WriteLine("value is : " + value2);
if (date.AddDays(90) < DateTime.Now)
{
Changpass obj2 = new Changpass()/;
this.Hide();
obj2.Show();
}
else
{
SqlCommand cmd4 = new SqlCommand("select user_id , username from tblcallcenter where username=@username and password=@password", sqlcon);
cmd4.Parameters.AddWithValue("@username", txtusername.Text);
cmd4.Parameters.AddWithValue("@password", txtpassword.Text);
SqlDataAdapter From_sda = new SqlDataAdapter(cmd4);
DataTable From_ds = new DataTable();
From_sda.Fill(From_ds);
String value1 = From_ds.Rows[0][1].ToString();
int id = int.Parse(From_ds.Rows[0][0].ToString());
Debug.WriteLine("value is : " + value1);
Class1.Txtusername = txtusername.Text;
this.Hide();
SqlCommand cmd5 = new SqlCommand("select [from], Take from tblcallcenter where username=@username and password=@password", sqlcon);
cmd5.Parameters.AddWithValue("@username", txtusername.Text);
cmd5.Parameters.AddWithValue("@password", txtpassword.Text);
SqlDataAdapter sda1 = new SqlDataAdapter(cmd5);
DataTable ds = new DataTable();
sda1.Fill(ds);
Callcenter1 obj = new Callcenter1(ds.Rows[0][0].ToString(), ds.Rows[0][1].ToString());
this.Hide();
obj.Show();
}
}
else
{
MessageBox.Show("Invalid Login try checking Useraname Or Password !", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception)
{
MessageBox.Show("Invalid Login try checking Useraname Or Password !", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T12:05:46.970",
"Id": "419983",
"Score": "0",
"body": "Welcome to Code Review. Code needs to be working before we review it. In the question you say it compiles, does this code execute properly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T12:06:30.263",
"Id": "419984",
"Score": "0",
"body": "@pacmaninbw yes it working"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T13:30:06.923",
"Id": "420003",
"Score": "2",
"body": "Aside from the code, which is addressed below, it seems as if you're storing passwords as plaintext in the database. This is a big no-no in security circles. Search for salting/hashing passwords for any number of good implementations of securing stored passwords."
}
] | [
{
"body": "<p>The code looks like it is coming from Windows Forms, I can't be certain, it could be WPF.</p>\n\n<p>The code does not seem to be in a <code>MVVM</code> or <code>MVC</code> design pattern. Either of these design patterns would allow data abstraction from the user interface.</p>\n\n<p>The code might be less complex and easier to maintain if there was some separation between the UI (view) and the data (Model). The code might also be less complex and easier to maintain if it was broken up into smaller functions that did only one thing (<a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a>).</p>\n\n<p><strong>All SQL Queries can throw errors</strong></p>\n\n<p>The first SQL query in the file is not in a try/catch block, if the SQL query fails the program will fail.</p>\n\n<p>The error message in the catch block \"Invalid Login try checking Username Or Password !\" doesn't represent what actually happened. If this catch block executes it means that the database that is being queried threw the exception and that there is an error either in the SQL code or the table doesn't exist in the database.</p>\n\n<p><strong>Use Using Blocks</strong> </p>\n\n<p>A using statement provides additional error checking as well as cleaning up after the SQL call. There are some examples of using statements in this <a href=\"https://stackoverflow.com/questions/3079098/the-c-sharp-using-statement-sql-and-sqlconnection\">stackoverflow question</a>.</p>\n\n<p>You can wrap connections and SQL commands in using statements. For an SQL connection wrapped in a using statement the database the connection will be closed automatically. An SQL command will be properly disposed of it is wrapped in a using statement.</p>\n\n<pre><code> private DataRow GetRawSeriesData(uint seriesId)\n {\n DataRow rawData = null;\n\n if (seriesId > 0)\n {\n try\n {\n using (MySqlConnection conn = new MySqlConnection(_dbConnectionString))\n {\n string queryString = \"SELECT * FROM series WHERE idSeries = '\" + seriesId.ToString() + \"';\";\n int ResultCount = 0;\n DataTable Dt = new DataTable();\n conn.Open();\n using (MySqlCommand cmd = new MySqlCommand())\n {\n cmd.Connection = conn;\n cmd.CommandType = CommandType.Text;\n cmd.CommandText = queryString;\n\n MySqlDataAdapter sda = new MySqlDataAdapter(cmd);\n ResultCount = sda.Fill(Dt);\n if (ResultCount > 0)\n {\n rawData = Dt.Rows[0];\n }\n }\n }\n }\n catch (Exception ex)\n {\n string errorMsg = \"Database Error: \" + ex.Message;\n MessageBox.Show(errorMsg);\n }\n }\n\n return rawData;\n }\n</code></pre>\n\n<p><strong>User Input Error Checking</strong> </p>\n\n<p>There doesn't seem to be any error checking on the username or password, in some cases this can allow SQL Injection attacks.</p>\n\n<p>On more secure websites the password might be checked against a set of rules to make it more secure, such as a requirement for 2 lowercase characters, 2 uppercase characters, 2 integers, and special characters, as well as a minimum length.</p>\n\n<p>There might also be a count of the number of times the button was pushed to prevent a bot attack.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T13:52:11.193",
"Id": "420007",
"Score": "4",
"body": "Why do you use string concatenation in your query? *that* is primo territory for an injection attack. The OP uses a standard parameter injection mechanism that lets the SQL/DB code take care of escaping/sanitizing input precisely to avoid this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T14:37:06.517",
"Id": "420018",
"Score": "0",
"body": "@D.BenKnoble I agree with your analysis based on what you see of the code. If this was user input I wouldn't do it this way. seriesId is a uint value that has been assigned as a primary key by SQL. This code is buried in about 4 layers of code that performs error checking."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T14:41:14.160",
"Id": "420020",
"Score": "0",
"body": "@D.BenKnoble updated the code example to show the full function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T14:45:19.690",
"Id": "420022",
"Score": "1",
"body": "thanks—didnt want to give the wrong impression to future readers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T17:18:52.850",
"Id": "420049",
"Score": "0",
"body": "@D.BenKnoble Thanks for the prompt to fix my code, you'll find a new and hopefully improved version here https://codereview.stackexchange.com/questions/217150/database-model-security-for-book-inventory"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T13:14:12.583",
"Id": "217134",
"ParentId": "217129",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "217134",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T11:50:33.817",
"Id": "217129",
"Score": "2",
"Tags": [
"c#",
"security"
],
"Title": "C# Login Form, Login Button , security"
} | 217129 |
<h2>Description</h2>
<ul>
<li>Given a class, return all its subclasses (recursively).</li>
<li>As you can see I've eliminated recursion using a stack.</li>
</ul>
<h2>What I want reviewed</h2>
<ul>
<li>Is there a better way to do this?</li>
<li>How can I make this code more generic and easier to use?</li>
<li>Is it pythonic?</li>
<li>Better way to eliminate recursion?</li>
</ul>
<h2>Code</h2>
<pre><code>def all_subclasses(cls):
if cls == type:
raise ValueError("Invalid class - 'type' is not a class")
subclasses = set()
stack = []
try:
immediate_subclasses = cls.__subclasses__()
except (TypeError, AttributeError) as ex:
raise ValueError("Invalid class" + repr(cls)) from ex
for subclass in immediate_subclasses:
stack.append(subclass)
while stack:
sub = stack.pop()
subclasses.add(sub)
try:
sub_subclasses = sub.__subclasses__()
except (TypeError, AttributeError) as _:
continue
if sub_subclasses:
stack.extend(sub_subclasses)
return list(subclasses)
</code></pre>
<h2>Tests</h2>
<pre><code>import unittest
from class_util import all_subclasses
def names(classes):
return sorted([cls.__name__ for cls in classes])
class A:
@classmethod
def all_subclasses(cls):
return all_subclasses(cls)
class B(A):
pass
class C(B):
pass
class D(C):
pass
class E(C):
pass
class F(E, C):
pass
class AllSublassesTestCase(unittest.TestCase):
def test_nested_classes(self):
self.assertEqual(names(A.all_subclasses()), ["B", "C", "D", "E", "F"])
def test_work_with_buitins(self):
self.assertTrue(names(all_subclasses(dict)))
self.assertTrue(names(all_subclasses(tuple)))
self.assertTrue(names(all_subclasses(list)))
def test_value_error_is_raised_on_invalid_classes(self):
self.assertRaises(ValueError, all_subclasses, type)
self.assertRaises(ValueError, all_subclasses, "")
self.assertRaises(ValueError, all_subclasses, None)
self.assertRaises(ValueError, all_subclasses, [])
if __name__ == "__main__":
unittest.main()
</code></pre>
| [] | [
{
"body": "<ul>\n<li>While working on the stack you are using <code>stack.extend</code>. You can also use this in the part where you add the immediate subclasses.</li>\n<li>There is no need to check if a list is empty before using <code>extend</code>, if it is empty it will just do nothing.</li>\n<li>If you don't need the exception, just don't catch it with <code>as _</code>.</li>\n<li>Not sure if you should be doing <code>if cls is type</code> instead of <code>if cls == type</code>.</li>\n</ul>\n\n\n\n<pre><code>def all_subclasses(cls):\n\n if cls == type:\n raise ValueError(\"Invalid class - 'type' is not a class\")\n\n subclasses = set()\n\n stack = []\n try:\n stack.extend(cls.__subclasses__())\n except (TypeError, AttributeError) as ex:\n raise ValueError(\"Invalid class\" + repr(cls)) from ex \n\n while stack:\n sub = stack.pop()\n subclasses.add(sub)\n try:\n stack.extend(sub.__subclasses__())\n except (TypeError, AttributeError):\n continue\n\n return list(subclasses)\n</code></pre>\n\n<p>One way to optimize this further is to make sure you don't visit a class multiple times:</p>\n\n<pre><code> while stack:\n sub = stack.pop()\n subclasses.add(sub)\n try:\n stack.extend(s for s in sub.__subclasses__() if s not in subclasses)\n except (TypeError, AttributeError):\n continue\n</code></pre>\n\n<p>This should prevent having to visit (almost) every class twice with convoluted hierarchies like this:</p>\n\n<pre><code> A\n / \\\n B C\n \\ /\n D\n / | | \\\nE F G ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T18:28:09.733",
"Id": "420057",
"Score": "1",
"body": "Nice. Thanks for this. I'll post more questions when I can."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T16:42:21.883",
"Id": "217148",
"ParentId": "217137",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "217148",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T14:39:10.457",
"Id": "217137",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"inheritance"
],
"Title": "List subclasses of a class"
} | 217137 |
<pre><code>#!/bin/bash
reset
echo "Creating output folder to Desktop/CombinedText and final passwordlist will show up as Final0Duplicates.txt"
##Functions##
##output file detection and creation##
function Dependency_Check
{
file2='~/Desktop/backupwordlist'
if [ ! -f "$file2" ]
touch "$file2"
file2='~/Desktop/CombinedText'
if [ ! -f "$file3" ]
touch "$file3"
}
## sort and merge .txt files and list files##
function Combined_Sort
{
##checks if file1 is not in directory##
file1='Final.list'
if [ ! -f "$file1" ]
then
echo "$file1 is not present"
echo -e "\e[41m\e[5m[+]-------------------creating $file1 and adding all .txt files to it-----------[+]\e[0m"
cat *.txt > Final.txt
reset
##text_Troll
sleep 2s
echo -e "\e[42m\e[5m[+]-------------------Working on Final List-------------------------------------[+]\e[0m"
cat Final.txt > Final.list
reset
echo -e "\e[42m\e[5m[+]--------final list finished removing 1.list-------[+]\e[0m"
echo -e "\e[41m\e[5mremoving Duplicates from Final list\e[0m"
sleep 10s
reset
sort -u Final.list > Final0Duplicates.txt
find . -name Final0Duplicates.txt -exec cp {} ~/Desktop/backupwordlist \;
sleep 10s
else
echo "$file1 is present"
echo "combining list files to 2.txt"
cat *.list > 2.txt
sleep 30s
reset
sleep 20s
echo "Working on Final List"
cat *.txt > Final.list
echo "final list finished removing 1.list"
echo "removing Duplicates from Final list"
sort -u Final.list > Final0Duplicates.txt
find . -name Final0Duplicates.txt -exec cp {} ~/Desktop/backupwordlist \;
sleep 10s
fi
}
##Crawls all subdirectories and extracts txt documents to desktop folder##
function crawl
{
find . -name \*.txt -exec cp {} ~/Desktop/CombinedText \;
}
reset
crawl
reset
echo "crawling"
Dependency_Check
echo "Creating Dependency Folder on desktop "
Combined_Sort
echo "All Text Documents have been Combined and sorted."
sleep 6
</code></pre>
<blockquote>
<p>Okay so a break down of this project started as a pseudo code project out of boredom. but I was looking to see how this can be preformed in python. There are several functions in this code as a break down.</p>
</blockquote>
<p><strong>Functions</strong></p>
<blockquote>
<p><strong>Dependency_Check</strong>
checks to see if the output folders are on the Desktop if not it creates it to be honest this is probably an unnecessary function</p>
<p><strong>Combined_Sort</strong>
This takes all of the text documents and merges them into one text document than removes duplicate entries and outputs a file <code>Final0Duplicates.txt</code> to <code>~/Desktop/backupwordlist</code></p>
<p><strong>Crawler</strong>
This function crawls all subdirectories of the working folder and grabs all files with .txt extension copies them to <code>~/Desktop/CombinedText</code></p>
<p><strong>GOAL</strong></p>
<p><em>My Goal with this program is to possibly create this as a powershell script to work with windows or a batch file using system variables instead of importing a ton of libraries with python. any help would be greatly appriciated, Later this will be released on github as a tool for pentesters to build a master dictionary attack file. Feel free to use this code it is fully fuctional as of 4/9/2019 on 64 bit kali linux latest build and patch.</em></p>
</blockquote>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T16:15:56.260",
"Id": "420036",
"Score": "2",
"body": "Hey, welcome to Code Review! Here we review working code and try to make it better. This is not the right place to ask for help in rewriting your code in another language. Have a look at our [help/on-topic] for more information on what is on-topic here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T16:20:13.860",
"Id": "420037",
"Score": "0",
"body": "Also, there seems to be a lot of pointless `sleep`ing, running of needlessly expensive commands (`cat Final.txt > Final.list` instead of `cp Final.txt Final.list`) and weird comments (`##text_Troll`). Is this code meant as a joke?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T10:49:45.657",
"Id": "420111",
"Score": "2",
"body": "so you're telling me you reimplemented `cat ./**/*.txt | sort | uniq >> CombinedText` badly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T13:54:51.213",
"Id": "420124",
"Score": "0",
"body": "The Text troll was a joke that brought up a command window and told a sory about harambe the Guerrilla"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T13:57:39.400",
"Id": "420125",
"Score": "2",
"body": "Vogel612 Your a wizard and apparently I could have done this with that magic one liner of yours.....face palm with a pan"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T14:29:23.960",
"Id": "420271",
"Score": "1",
"body": "@Vogel612: `cat ./**/*.txt | sort -u >> CombinedText` would be [even faster](https://unix.stackexchange.com/a/76050/162318)."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T16:04:07.050",
"Id": "217143",
"Score": "2",
"Tags": [
"python",
"bash",
"linux",
"shell",
"powershell"
],
"Title": "Word list scrapper Merger and parse for duplicate entries trying too optimize and convert to python"
} | 217143 |
<p>I'm a python dev by day trying to learn C. </p>
<p>This is a simple implementation of a singly linked list. As a noob I would like comments on style and C conventions as well as functional remarks on memory management etc. </p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
/*
--------linkedList---------
| |
| |
| |
| |
*head --> nodes --> *end
*/
struct linkedList {
struct node * head;
struct node * end;
int len;
};
struct node {
int id;
int val;
struct node * next;
};
struct linkedList * createList() {
struct linkedList * l_list = (struct linkedList * ) malloc(sizeof(struct linkedList));
l_list->head = NULL;
l_list->end = NULL;
l_list->len = 0;
printf("created list\n");
return l_list;
}
struct node * createNode(int id, int val) {
struct node * n_node = (struct node * ) malloc(sizeof(struct node));
n_node->id = id;
n_node->val = val;
n_node->next = NULL;
printf("created node\n");
return n_node;
}
void addNode(struct linkedList * ptr, int id, int val) {
struct node * new_node = createNode(id, val);
if (ptr->len == 0) {
ptr->head = new_node;
ptr->end = new_node;
ptr->len += 1;
printf("created a list and added a new value\n");
} else {
// update next of previous end
// make new end this node
struct node * temp;
temp = ptr->end;
temp->next = new_node;
ptr->end = new_node;
ptr->len += 1;
// printf("updated a preexisting list\n");
}
}
void printListWithFor(struct linkedList * someList) {
struct node currentNode = * someList->head;
printf("current length of list is %d\n", someList->len);
printf("first item is %d, last item is %d\n", someList->head->val, someList->end->val);
if (currentNode.next == NULL) {
printf("current node id is %d, with a value of %d\n", currentNode.id, currentNode.val);
}
for (int i = 0; i < ( * someList).len; i++) {
printf("current node id is %d, with a value of %d\n", currentNode.id, currentNode.val);
currentNode = * currentNode.next;
}
}
void printListWithWhile(struct linkedList * someList) {
struct node currentNode = * someList->head;
struct node endNode = * someList->end;
printf("current length of list is %d\n", someList->len);
printf("first item is %d, last item is %d\n", someList->head->val, someList->end->val);
if (currentNode.next == NULL) {
printf("current node id is %d, with a value of %d\n", currentNode.id, currentNode.val);
}
while (currentNode.id != endNode.id) {
printf("current node id is %d, with a value of %d\n", currentNode.id, currentNode.val);
currentNode = * currentNode.next;
}
printf("current node id is %d, with a value of %d\n", currentNode.id, currentNode.val);
}
struct node * findNode(struct linkedList * someList, int id) {
struct node headNode = * someList->head;
struct node endNode = * someList->end;
struct node * nullNode = createNode(-1, -1);
if (headNode.id == id) {
free(nullNode);
return someList->head;
}
if (endNode.id == id) {
free(nullNode);
return someList->end;
}
struct node * currentNode = headNode.next;
while (currentNode-> id != endNode.id) {
if (currentNode->id == id) {
free(nullNode);
return currentNode;
}
currentNode = currentNode->next;
}
return nullNode;
}
int delNode(struct linkedList * someList, int id) {
struct node * headNode = someList->head;
struct node * endNode = someList->end;
if (headNode->id == id) {
// remove node, replace it with next node, free memory
struct node * temp = headNode->next;
someList->head = temp;
printf("removed a node with id of %d and value of %d\n", headNode->id, headNode->val);
free(headNode);
someList->len -= 1;
return 0;
}
if (endNode->id == id) {
printf("removed a node with id of %d and value of %d\n", endNode->id, endNode->val);
free(endNode);
someList->len -= 1;
return 0;
}
struct node * currentNode = headNode->next;
struct node * prevNode = headNode;
while (prevNode->id != endNode->id) {
if (currentNode->id == id) {
struct node * temp = currentNode->next;
prevNode->next = temp;
printf("removed a node with id %d and value of %d\n", currentNode->id, currentNode->val);
free(currentNode);
someList->len -= 1;
return 0;
}
prevNode = currentNode;
currentNode = currentNode->next;
}
return -1;
}
int main() {
struct linkedList * list = createList();
addNode(list, 1, 7);
addNode(list, 2, 6);
addNode(list, 3, 11);
addNode(list, 5, 92);
addNode(list, 18, 6);
addNode(list, 10, 3);
addNode(list, 50, 9);
// printListWithWhile(list);
// printListWithFor(list);
printf("\n");
struct node * foundNode = findNode(list, 1);
printf("Node id : %d\n", foundNode->id);
printf("Node val : %d\n", foundNode->val);
printf("\n");
// printListWithWhile(list);
delNode(list, 2);
printListWithWhile(list);
delNode(list, 18);
printf("\n");
printListWithWhile(list);
return 0;
}
</code></pre>
| [] | [
{
"body": "<p>In C, it's not necessary or desirable to cast the return value from <code>malloc()</code>. It is however <em>essential</em> to check the result isn't null before dereferencing it:</p>\n\n<pre><code>struct linkedList *createList() {\n struct linkedList *list = malloc(sizeof *list);\n if (list) {\n list->head = NULL;\n list->end = NULL;\n list->len = 0;\n }\n return list;\n}\n</code></pre>\n\n<p>Note that the caller of <code>createList</code> <em>also</em> needs to check whether the returned list pointer is null before attempting to use it.</p>\n\n<p>There doesn't seem to be a corresponding function to release a list; this is likely what makes the test program leak memory. See this Valgrind output:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>==868== HEAP SUMMARY:\n==868== in use at exit: 104 bytes in 6 blocks\n==868== total heap usage: 10 allocs, 4 frees, 1,176 bytes allocated\n==868== \n==868== 104 (24 direct, 80 indirect) bytes in 1 blocks are definitely lost in loss record 6 of 6\n==868== at 0x483577F: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)\n==868== by 0x109186: createList (217145.c:24)\n==868== by 0x1096D7: main (217145.c:151)\n</code></pre>\n\n<p>We can't rely on the node <code>id</code> values being unique:</p>\n\n<blockquote>\n<pre><code>if (currentNode.next == NULL) {\n printf(\"current node id is %d, with a value of %d\\n\", currentNode.id, currentNode.val);\n}\nwhile (currentNode.id != endNode.id) {\n printf(\"current node id is %d, with a value of %d\\n\", currentNode.id, currentNode.val);\n currentNode = * currentNode.next;\n}\n</code></pre>\n</blockquote>\n\n<p>This looks very weird, because it is copying the entire value of each node into <code>currentNode</code>. A more efficient and more idiomatic approach is to define <code>currentNode</code> as a pointer; since we don't want to modify the list through it, make it a pointer to <code>const</code>.</p>\n\n<pre><code>void printListWithWhile(const struct linkedList * someList)\n{\n const struct node *currentNode = someList->head;\n printf(\"current length of list is %d\\n\", someList->len);\n if (someList->head) {\n printf(\"first item is %d, last item is %d\\n\",\n someList->head->val, someList->end->val);\n }\n\n while (currentNode) {\n printf(\"current node id is %d, with a value of %d\\n\",\n currentNode->id, currentNode->val);\n currentNode = currentNode->next;\n }\n}\n</code></pre>\n\n<p>Or more idiomatically (though now belying the name) as a <code>for</code> loop:</p>\n\n<pre><code>void printListWithWhile(const struct linkedList * someList)\n{\n printf(\"current length of list is %d\\n\", someList->len);\n if (someList->head) {\n printf(\"first item is %d, last item is %d\\n\",\n someList->head->val, someList->end->val);\n }\n\n for (const struct node *currentNode = someList->head; currentNode; currentNode = currentNode->next) {\n printf(\"current node id is %d, with a value of %d\\n\", currentNode->id, currentNode->val);\n }\n}\n</code></pre>\n\n<p>These observations apply to most of the functions.</p>\n\n<p>Other odd things:</p>\n\n<ul>\n<li>Why does <code>findNode()</code> create a dummy object to return on failure, rather than just returning <code>NULL</code>?</li>\n<li>And why waste resources creating it in the cases where it's simply deleted again?</li>\n<li>What does the return value of <code>delNode()</code> signify? A common convention is true (i.e. non-zero) for success and false (zero) if not found; is there a reason for a different convention here?</li>\n<li><code>printListWithFor()</code> never seems to be called.</li>\n<li>Lots of commented-out code and unnecessary <code>printf()</code>s seem to have been left in when debugging. These should be removed before the code is ready to use.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T19:07:58.900",
"Id": "420155",
"Score": "0",
"body": "You wouldn't recommend using typedef for the node and list type?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T20:17:30.160",
"Id": "420165",
"Score": "0",
"body": "I don't have a strong opinion, though it can make code easier to read. You're welcome to post an answer of your own, of course..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T21:04:38.843",
"Id": "420172",
"Score": "0",
"body": "I think `typedef` is overused by beginners; I would not use it if you have a choice. See https://www.kernel.org/doc/html/v4.10/process/coding-style.html#typedefs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T20:12:06.907",
"Id": "420324",
"Score": "0",
"body": "You may also want to mention that the argument to `printListWithWhile` should be `const` and that generally, one would just name that `printList`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T07:12:44.540",
"Id": "420356",
"Score": "0",
"body": "Thanks @Edward; I've updated the argument to that function. The naming is unconventional, but OTOH, I can see that it's done for (auto?)didactic purposes, to compare two ways of terminating the loop, so I think that wasn't a mistake."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T09:09:27.340",
"Id": "420382",
"Score": "0",
"body": "@Edward they are named that way on purpose for the exact reason Toby mentioned."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T09:14:11.957",
"Id": "420385",
"Score": "0",
"body": "@TobySpeight The reason I returned a dummy object was because I didn't realise I could simply return Null. But in hindsight I realise I'm returning a pointer not a struct allowing for the Null return."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T09:15:39.750",
"Id": "420386",
"Score": "0",
"body": "@TobySpeight also in regards to the return statement of `delNode`, I was copying bash where success is zero and I just assumed it was the same in C but now I know."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T16:12:22.880",
"Id": "217209",
"ParentId": "217145",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "217209",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T16:16:53.967",
"Id": "217145",
"Score": "6",
"Tags": [
"beginner",
"c",
"linked-list"
],
"Title": "Single-Linked List in C - beginner"
} | 217145 |
<p>This code is one of the models developed for the Book Inventory application that <a href="https://codereview.stackexchange.com/questions/215431/non-entity-framework-database-interaction-model">is open for review</a>. It is also based on a comment on <a href="https://codereview.stackexchange.com/questions/217129/c-login-form-login-button-security/217134#217134">this answer</a> to a C# question. Based on the comment I did some research and found this <a href="https://stackoverflow.com/questions/14376473/what-are-good-ways-to-prevent-sql-injection">stackoverflow question</a>.</p>
<p>The code presented for review is the database model for a series of books in the Book Inventory. A series of books has an author and a title. The author is represented by a key into the author table. To add a series to the database the user has to select the author from a list of authors already in the database. They then have to add the title or name of the series.</p>
<p>Below I present a before and after, the before is one function that was used in the answer above, the after is the entire code to be reviewed including the refactored function.</p>
<p>Questions:</p>
<p>Is there anything else I can do to prevent SQL Injection attacks?</p>
<p>What else can I do to improve the code, keep in mind I've been on this site for a while, I'm not asking "Does my code suck?", all code sucks, I'm asking <strong>how</strong> does my code suck. </p>
<p><strong>Before</strong></p>
<p>From my <a href="https://codereview.stackexchange.com/questions/217129/c-login-form-login-button-security/217134#217134">answer</a></p>
<blockquote>
<pre><code> private DataRow GetRawSeriesData(uint seriesId)
{
DataRow rawData = null;
if (seriesId > 0)
{
try
{
using (MySqlConnection conn = new MySqlConnection(_dbConnectionString))
{
string queryString = "SELECT * FROM series WHERE idSeries = '" + seriesId.ToString() + "';";
int ResultCount = 0;
DataTable Dt = new DataTable();
conn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = queryString;
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
ResultCount = sda.Fill(Dt);
if (ResultCount > 0)
{
rawData = Dt.Rows[0];
}
}
}
}
catch (Exception ex)
{
string errorMsg = "Database Error: " + ex.Message;
MessageBox.Show(errorMsg);
}
}
return rawData;
}
</code></pre>
</blockquote>
<p><strong>After: Code to be Reviewed: SeriesTableModel.cs</strong> </p>
<pre><code>using System;
using System.Collections.Generic;
using System.Data;
using System.Windows;
using MySql.Data.MySqlClient;
namespace pacsw.BookInventory.Models
{
public class SeriesTableModel : CDataTableModel
{
private int seriesTitleIndex;
private int seriesKeyIndex;
private int seriesAuthorKeyIndex;
public SeriesTableModel() : base("series", "getAllSeriesData", "addAuthorSeries")
{
seriesTitleIndex = GetDBColumnData("SeriesName").IndexBasedOnOrdinal;
seriesKeyIndex = GetDBColumnData("idSeries").IndexBasedOnOrdinal;
seriesAuthorKeyIndex = GetDBColumnData("AuthorOfSeries").IndexBasedOnOrdinal;
}
public DataTable Series { get { return DataTable; } }
public bool AddSeries(ISeriesModel iSeriesData)
{
SeriesModel seriesModel = (SeriesModel)iSeriesData;
return addItem(seriesModel);
}
public bool AddSeries(SeriesModel seriesModel)
{
return addItem(seriesModel);
}
public List<string> SeriesSelectionListCreator(AuthorModel author)
{
List<string> seriesSelectionList = new List<string>();
if (author != null && author.IsValid)
{
DataTable currentSeriesList = Series;
string filterString = "LastName = '" + author.LastName + "' AND FirstName = '" + author.FirstName + "'";
DataRow[] seriesTitleList = currentSeriesList.Select(filterString);
foreach (DataRow row in seriesTitleList)
{
seriesSelectionList.Add(row[seriesTitleIndex].ToString());
}
}
return seriesSelectionList;
}
public uint GetSeriesKey(AuthorModel author, string seriesTitle)
{
uint key = 0;
if (author != null && author.IsValid)
{
string SqlQuery = "SELECT series.idSeries FROM series WHERE series.SeriesName = @title AND series.AuthorOfSeries = @authorid;";
using (MySqlConnection conn = new MySqlConnection(_dbConnectionString))
{
int ResultCount = 0;
DataTable Dt = new DataTable();
try
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = SqlQuery;
cmd.Parameters.Add("@title", MySqlDbType.String);
cmd.Parameters["@title"].Value = seriesTitle;
cmd.Parameters.Add("@authorid", MySqlDbType.UInt32);
cmd.Parameters["@authorid"].Value = author.AuthorId;
cmd.ExecuteNonQuery();
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
ResultCount = sda.Fill(Dt);
if (ResultCount > 0)
{
key = Dt.Rows[0].Field<uint>(0);
}
}
}
catch (Exception ex)
{
string errorMsg = "Database Error: " + ex.Message;
MessageBox.Show(errorMsg);
key = 0;
}
}
}
return key;
}
public string GetSeriesTitle(uint seriesId)
{
string title = string.Empty;
if (seriesId > 0)
{
string SqlQuery = "SELECT series.SeriesName FROM series WHERE series.idSeries = @seriesid;";
using (MySqlConnection conn = new MySqlConnection(_dbConnectionString))
{
int ResultCount = 0;
DataTable Dt = new DataTable();
try
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = SqlQuery;
cmd.Parameters.Add("@seriesid", MySqlDbType.UInt32);
cmd.Parameters["@seriesid"].Value = seriesId;
cmd.ExecuteNonQuery();
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
ResultCount = sda.Fill(Dt);
if (ResultCount > 0)
{
title = Dt.Rows[0].Field<string>(0);
}
}
}
catch (Exception ex)
{
string errorMsg = "Database Error: " + ex.Message;
MessageBox.Show(errorMsg);
}
}
}
return title;
}
public SeriesModel GetSeriesModel(uint seriesId)
{
SeriesModel seriesData = null;
DataRow rawSeriesData = GetRawSeriesData(seriesId);
if (rawSeriesData != null)
{
seriesData = ConvertDataRowToSeriesModel(rawSeriesData);
}
return seriesData;
}
protected override void InitializeSqlCommandParameters()
{
AuthorTableModel authorTable = ((App)Application.Current).Model.AuthorTable;
MySqlParameterCollection parameters = AddItemParameters;
_addSqlCommandParameter("First Name", authorTable.GetDBColumnData("FirstName"), parameters["@authorFirst"]);
_addSqlCommandParameter("Last Name", authorTable.GetDBColumnData("LastName"), parameters["@authorLast"]);
_addSqlCommandParameter("Series Title", GetDBColumnData("SeriesName"), parameters["@seriesTitle"]);
}
private SeriesModel ConvertDataRowToSeriesModel(DataRow rawSeriesData)
{
uint authorId;
uint.TryParse(rawSeriesData[seriesAuthorKeyIndex].ToString(), out authorId);
string title = rawSeriesData[seriesTitleIndex].ToString();
AuthorModel author = ((App)Application.Current).Model.AuthorTable.GetAuthorFromId(authorId);
SeriesModel seriesModel = new SeriesModel(author, title);
return seriesModel;
}
private DataRow GetRawSeriesData(uint seriesId)
{
DataRow rawData = null;
if (seriesId > 0)
{
try
{
using (MySqlConnection conn = new MySqlConnection(_dbConnectionString))
{
string queryString = "SELECT * FROM series WHERE idSeries = @seriesid;";
int ResultCount = 0;
DataTable Dt = new DataTable();
conn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = queryString;
cmd.Parameters.Add("@seriesid", MySqlDbType.UInt32);
cmd.Parameters["@seriesid"].Value = seriesId;
MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
ResultCount = sda.Fill(Dt);
if (ResultCount > 0)
{
rawData = Dt.Rows[0];
}
}
}
}
catch (Exception ex)
{
string errorMsg = "Database Error: " + ex.Message;
MessageBox.Show(errorMsg);
}
}
return rawData;
}
}
}
</code></pre>
| [] | [
{
"body": "<p>Anytime I see something like these I wonder "is there a better way we can do this?":</p>\n<blockquote>\n<pre><code>cmd.Parameters.Add("@title", MySqlDbType.String);\ncmd.Parameters["@title"].Value = seriesTitle;\ncmd.Parameters.Add("@authorid", MySqlDbType.UInt32);\ncmd.Parameters["@authorid"].Value = author.AuthorId;\n</code></pre>\n</blockquote>\n<p>Well, in this case, I'm going to suggest a slightly-functional approach to this process.</p>\n<p>C# has a (mostly) handy feature called "Extension Methods". In general, I try to avoid them unless there's a <em>good</em> application for them, such as here.</p>\n<p>I would define an extension method here quick:</p>\n<pre><code>public static MySqlCommand AddParameter<T>(this MySqlCommand command, string name, MySqlDbType type, T value) {\n command.Parameters.Add(name, type);\n command.Parameters[name].Value = value;\n return command;\n}\n</code></pre>\n<p>Now, here, I returned the <code>MySqlCommand</code> on purpose, because I want to chain this:</p>\n<pre><code>command.AddParameter("@title", MySqlDbType.String, seriesTitle)\n .AddParameter("@authorid", MySqlDbType.UInt32, author.AuthorId);\n</code></pre>\n<p>Since you aren't using an ORM (and I suspect you have reasons for that, I definitely won't try to persuade you to use one) I would do a couple of these small things to make life a little easier on myself. It's pretty cheap, and it allows us to work our code more easily.</p>\n<hr />\n<p>I would take some of these shorter functions and apply some expression-bodied members:</p>\n<blockquote>\n<pre><code>public DataTable Series { get { return DataTable; } }\n\npublic bool AddSeries(ISeriesModel iSeriesData)\n{\n SeriesModel seriesModel = (SeriesModel)iSeriesData;\n return addItem(seriesModel);\n}\n\npublic bool AddSeries(SeriesModel seriesModel)\n{\n return addItem(seriesModel);\n}\n</code></pre>\n</blockquote>\n<p>To:</p>\n<pre><code>public DataTable Series => DataTable;\npublic bool AddSeries(ISeriesModel iSeriesData) => addItem((SeriesModel)iSeriesData);\npublic bool AddSeries(SeriesModel seriesModel) => addItem(seriesModel);\n</code></pre>\n<p>For simple functions like those, it's trivial to do and saves you some vertical space.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T18:34:25.590",
"Id": "420059",
"Score": "0",
"body": "If I implement the first suggestion in the abstract class CDataTableModel in my original question will it work in all the inherited DataTable models classes?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T18:37:06.587",
"Id": "420060",
"Score": "1",
"body": "No, you will need to make a new `public static class` for the extension methods, but then _as long as the namespace containing that `public static class` is available, it will work in any class._"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T10:35:54.373",
"Id": "420107",
"Score": "0",
"body": "Usually it's a better idea to cast a `class` into an `interface` rather the the other way around as in your last two lines but I guess this is just a _blind_ copy/paste of OP's code and turning the methods into expression-bodied ones but in this case the overload taking a `SeriesModel` is no longer necessary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T11:37:05.063",
"Id": "420116",
"Score": "0",
"body": "@t3chb0t Yeah I didn't look at any of the dependency trees, just went off what was in the question."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T18:10:41.260",
"Id": "217154",
"ParentId": "217150",
"Score": "4"
}
},
{
"body": "<blockquote>\n<pre><code>public bool AddSeries(ISeriesModel iSeriesData)\n{\n SeriesModel seriesModel = (SeriesModel)iSeriesData;\n return addItem(seriesModel);\n}\n\npublic bool AddSeries(SeriesModel seriesModel)\n{\n return addItem(seriesModel);\n}\n</code></pre>\n</blockquote>\n\n<p>If <code>SeriesModel</code> implements <code>ISeriesModel</code> interface (which I suppose it does) then you need only the overload taking the interface.</p>\n\n<p>Also casting an <code>interface</code> into a <code>class</code> is rarely a good idea because we then loose the advantages of having the interface in the first place like using a mock type.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T12:57:22.660",
"Id": "420119",
"Score": "0",
"body": "Is there a good source for when to use and interface and when not to use an interface? I was using it to hide data."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T13:03:27.880",
"Id": "420121",
"Score": "1",
"body": "@pacmaninbw I would look on software engineering but in general you use it when you need a level of abstraction to decouple the interface you're working with from the type implementing it. This allows us to easily exchange the implementation without breaking anything. Another usage can be when several types should share some common api like CalculateArea if it was a shape. In python it would work with duck typing."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T10:40:02.670",
"Id": "217193",
"ParentId": "217150",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "217154",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T17:09:43.923",
"Id": "217150",
"Score": "3",
"Tags": [
"c#",
"sql",
"security",
"sql-injection"
],
"Title": "Database Model Security For Book Inventory"
} | 217150 |
<p>I made my first Python project with the help of Tkinter. I was trying to make it works like iPhone calculator. I am a beginner and I am looking for ways to improve my code.</p>
<p><a href="https://i.stack.imgur.com/nIuYP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/nIuYP.png" alt="How it looks"></a></p>
<p>I use PyCharm and got rid of all warnings, but I still think that code isn't clear enough. I know that I must comment my code, but I am going to do that later, when I will be sure that everything is ok.</p>
<p>GitHub project page: <a href="https://github.com/Unknown-reader/Python-Calculator/tree/2b97a74dddc4aff35b2ebc1d667cf3dc4d03f885" rel="noreferrer">https://github.com/Unknown-reader/Python-Calculator</a></p>
<pre><code>from tkinter import *
from math import *
root = Tk()
root.title("Calculator")
root.resizable(width=False, height=False)
screen = StringVar()
screen.set("0")
current = ""
power = ""
firstnum = str()
secondnum = str()
mathsign = str()
defxworking = False
percentt = False
def math_button_pressed():
if mathsign == '+':
button_plus.config(relief=SUNKEN)
if mathsign == '-':
button_minus.config(relief=SUNKEN)
if mathsign == '*':
button_multiply.config(relief=SUNKEN)
if mathsign == '/':
button_division.config(relief=SUNKEN)
def math_button_raised():
button_plus.config(relief=RAISED)
button_minus.config(relief=RAISED)
button_multiply.config(relief=RAISED)
button_division.config(relief=RAISED)
def is_int(num):
if int(num) == float(num):
return int(num)
else:
return float(num)
def number_pressed(butt):
global current, power, firstnum, secondnum
if mathsign == str() and defxworking == False:
current = current + str(butt)
screen.set(current)
firstnum = float(current)
elif mathsign != str() and defxworking == False:
math_button_raised()
current = current + str(butt)
screen.set(current)
secondnum = float(current)
elif mathsign == str() and defxworking == True:
power = power + str(butt)
current = current + str(butt)
screen.set(current)
elif mathsign != str and defxworking == True:
power = power + str(butt)
current = current + str(butt)
screen.set(current)
print(power)
def math_pressed(math):
global current, power, mathsign, firstnum, secondnum, defxworking, percentt
if mathsign == str() and defxworking == False and percentt == False and firstnum != str():
mathsign = str(math)
math_button_pressed()
current = ""
elif mathsign != str() and defxworking == False and percentt == False:
print(2)
if mathsign == '+':
firstnum = round(float(firstnum + secondnum),6)
if mathsign == '-':
firstnum = round(float(firstnum - secondnum),6)
if mathsign == '*':
firstnum = round(float(firstnum * secondnum),6)
if mathsign == '/':
firstnum = round(float(firstnum / secondnum),6)
screen.set(is_int(firstnum))
mathsign = str(math)
math_button_pressed()
current = ""
elif mathsign != str() and defxworking == True and percentt == False:
if mathsign == '+':
firstnum = round(firstnum + secondnum ** int(power),6)
if mathsign == '-':
firstnum = round(firstnum - secondnum ** int(power),6)
if mathsign == '*':
firstnum = round(firstnum * (secondnum ** int(power)),6)
if mathsign == '/':
firstnum = round(firstnum / (secondnum ** int(power)),6)
defxworking = False
screen.set(is_int(firstnum))
defxworking = False
mathsign = str(math)
math_button_pressed()
power = ""
current = ""
elif defxworking and percentt == False:
firstnum = round(firstnum ** int(power), 6)
defxworking = False
screen.set(is_int(firstnum))
mathsign = str(math)
math_button_pressed()
power = ""
current = ""
elif percentt:
if mathsign == '+':
firstnum = round(float(firstnum + firstnum/100*secondnum),6)
if mathsign == '-':
firstnum = round(float(firstnum - firstnum/100*secondnum),6)
screen.set(is_int(firstnum))
percentt = False
mathsign = str(math)
math_button_pressed()
current = ""
def squareroot():
global firstnum, secondnum, mathsign, current
if mathsign == str():
firstnum = round(sqrt(firstnum),6)
screen.set(is_int(firstnum))
if mathsign != str():
if mathsign == '+':
firstnum = round(sqrt(firstnum + float(secondnum)),6)
if mathsign == '-':
firstnum = round(sqrt(firstnum - float(secondnum)),6)
if mathsign == '*':
firstnum = round(sqrt(firstnum * float(secondnum)),6)
if mathsign == '/':
firstnum = round(sqrt(firstnum / float(secondnum)),6)
screen.set(is_int(firstnum))
secondnum = str()
mathsign = str()
current = ""
def x():
global firstnum, secondnum, mathsign, current, defxworking
if mathsign == str():
current = str(is_int(firstnum)) + '^'
screen.set(current)
defxworking = True
elif mathsign != str():
current = str(is_int(secondnum)) + '^'
screen.set(current)
defxworking = True
def result():
global firstnum, secondnum, mathsign, current, power, defxworking, percentt
if defxworking == False and percentt == False:
if mathsign == '+':
firstnum = round(float(firstnum + secondnum),6)
if mathsign == '-':
firstnum = round(float(firstnum - secondnum),6)
if mathsign == '*':
firstnum = round(float(firstnum * secondnum),6)
if mathsign == '/':
firstnum = round(float(firstnum / secondnum),6)
screen.set(is_int(firstnum))
if mathsign == str() and defxworking == True and percentt == False:
firstnum = round(firstnum ** int(power),6)
defxworking = False
screen.set(is_int(firstnum))
if mathsign != str() and defxworking == True and percentt == False:
if mathsign == '+':
firstnum = round(firstnum + secondnum ** int(power),6)
defxworking = False
if mathsign == '-':
firstnum = round(firstnum - secondnum ** int(power),6)
defxworking = False
if mathsign == '*':
firstnum = round(firstnum * (secondnum ** int(power)),6)
defxworking = False
if mathsign == '/':
firstnum = round(firstnum / (secondnum ** int(power)),6)
defxworking = False
screen.set(is_int(firstnum))
if defxworking == False and percentt == True:
if mathsign == '+':
firstnum = round(float(firstnum + firstnum/100*secondnum),6)
screen.set(is_int(firstnum))
percentt = False
if mathsign == '-':
firstnum = round(float(firstnum - firstnum/100*secondnum),6)
screen.set(is_int(firstnum))
percentt = False
mathsign = str()
current = ""
power = ""
if defxworking == False and mathsign == '*' or '/' and percentt == True:
clear()
def clear():
global current, firstnum, secondnum, mathsign, power, defxworking, percentt
screen.set(0)
current = ""
power = ""
firstnum = str()
secondnum = str()
mathsign = str()
defxworking = False
math_button_raised()
percentt = False
def percent():
global firstnum, secondnum, current, percentt
current = str(is_int(secondnum)) + '%'
screen.set(current)
percentt = True
# Widgets
calculation = Entry(root, textvariable = screen, font=("Verdana", 15, ), bd = 12,
insertwidth=4, width=14, justify=RIGHT)
calculation.grid(columnspan=4)
# Numbers
button1 = Button(root, text='1', command=lambda: number_pressed(1), bg="gainsboro",
bd=3, padx=12, pady=5, font=("Helvetica", 14, "bold"))
button1.grid(row=2, column=0, sticky=W)
button2 = Button(root, text='2', command=lambda: number_pressed(2), bg="gainsboro",
bd=3, padx=12, pady=5, font=("Helvetica", 14, "bold"))
button2.grid(row=2, column=1, sticky=W)
button3 = Button(root, text='3', command=lambda: number_pressed(3), bg="gainsboro",
bd=3, padx=12, pady=5, font=("Helvetica", 14, "bold"))
button3.grid(row=2, column=2, sticky=W)
button4 = Button(root, text='4', command=lambda: number_pressed(4), bg="gainsboro",
bd=3, padx=12, pady=5, font=("Helvetica", 14, "bold"))
button4.grid(row=3, column=0, sticky=W)
button5 = Button(root, text='5', command=lambda: number_pressed(5), bg="gainsboro",
bd=3, padx=12, pady=5, font=("Helvetica", 14, "bold"))
button5.grid(row=3, column=1, sticky=W)
button6 = Button(root, text='6', command=lambda: number_pressed(6), bg="gainsboro",
bd=3, padx=12, pady=5, font=("Helvetica", 14, "bold"))
button6.grid(row=3, column=2, sticky=W)
button7 = Button(root, text='7', command=lambda: number_pressed(7), bg="gainsboro",
bd=3, padx=12, pady=5, font=("Helvetica", 14, "bold"))
button7.grid(row=4, column=0, sticky=W)
button8 = Button(root, text='8', command=lambda: number_pressed(8), bg="gainsboro",
bd=3, padx=12, pady=5, font=("Helvetica", 14, "bold"))
button8.grid(row=4, column=1, sticky=W)
button9 = Button(root, text='9', command=lambda: number_pressed(9), bg="gainsboro",
bd=3, padx=12, pady=5, font=("Helvetica", 14, "bold"))
button9.grid(row=4, column=2, sticky=W)
button0 = Button(root, text='0', command=lambda: number_pressed(0), bg="gainsboro",
bd=3, padx=12, pady=5, font=("Helvetica", 14, "bold"))
button0.grid(row=5, column=0, sticky=W)
button_float = Button(root, text='.', command=lambda: number_pressed('.'), bg="gainsboro",
bd=3, padx=15, pady=5, font=("Helvetica", 14, "bold"))
button_float.grid(row=5, column=1)
# Math signs
button_plus = Button(root, text='+', command=lambda: math_pressed('+'), bg="gray70",
bd=3, padx=11, pady=5, font=("Helvetica", 14, "bold"))
button_plus.grid(row=2, column=3, sticky=W)
button_minus = Button(root, text='-', command=lambda: math_pressed('-'), bg="gray70",
bd=3, padx=11, pady=4, font=("Verdana", 14, "bold"))
button_minus.grid(row=3, column=3, sticky=W)
button_multiply = Button(root, text='*', command=lambda: math_pressed('*'), bg="gray70",
bd=3, padx=13, pady=5, font=("Helvetica", 14, "bold"))
button_multiply.grid(row=4, column=3, )
button_division = Button(root, text='/', command=lambda: math_pressed('/'), bg="gray70",
bd=3, padx=14, pady=5, font=("Helvetica", 14, "bold"))
button_division.grid(row=5, column=3, )
button_equal = Button(root, text='=', command=lambda: result(), bg='orange',
bd=3, padx=12, pady=5, font=("Arial", 14))
button_equal.grid(row=5, column=2, )
button_percent = Button(root, text='%', command=lambda: percent(), bg="gray70",
bd=3, padx=8, pady=5, font=("Helvetica", 14, "bold"))
button_percent.grid(row=1, column=3, )
button_clear = Button(root, text='C', command=lambda: clear(), bg='gray70',
bd=3, padx=11, pady=5, font=("Helvetica", 14))
button_clear.grid(row=1, column=0)
button_sqrt = Button(root, text='√', command=lambda: squareroot(), bg="gray70",
bd=3, padx=12, pady=5, font=("Helvetica", 14, "bold"))
button_sqrt.grid(row=1, column=1, sticky=W)
button_x = Button(root, text='x^y', command=lambda: x(), bg="gray70",
bd=3, padx=6, pady=5, font=("Helvetica", 14))
button_x.grid(row=1, column=2, sticky=W)
root.mainloop()
</code></pre>
| [] | [
{
"body": "<p>Your code is organized oddly.</p>\n\n<ul>\n<li>Imports</li>\n<li>Variable declarations & code</li>\n<li>Function definitions</li>\n<li>More Variable declarations & code</li>\n</ul>\n\n<p>You should keep the variable declarations and code together.</p>\n\n<hr>\n\n<p><code>str()</code> - why are you using this everywhere? It returns an empty string: <code>\"\"</code>, which is 3 characters shorter to type and is much easier to understand.</p>\n\n<hr>\n\n<p><code>elif mathsign != str and defxworking == True:</code> does not do what you intended. It compares <code>mathsign</code> with the function <code>str</code>, not an empty string. You are missing the brackets ... <code>mathsign != str()</code>, but again, use <code>mathsign != \"\"</code> instead.</p>\n\n<hr>\n\n<p>In several places you have code that reads ...</p>\n\n<pre><code>if mathsign == '+':\n # code\nif mathsign == '-':\n # code\nif mathsign == '*':\n # code\nif mathsign == '/':\n # code\n</code></pre>\n\n<p>These last three should <code>elif</code> statements, not <code>if</code> statements.</p>\n\n<p>Similarly, code like:</p>\n\n<pre><code>if mathsign == str():\n # code\nif mathsign != str():\n # code\n</code></pre>\n\n<p>should be replaced with:</p>\n\n<pre><code>if mathsign == \"\":\n # code\nelse:\n # code\n</code></pre>\n\n<hr>\n\n<p>Don't Repeat Yourself (DRY). For example, in <code>def math_pressed(math):</code> you have every branch of your <code>if ... elif</code> ending in:</p>\n\n<pre><code>mathsign = str(math)\nmath_button_pressed()\ncurrent = \"\"\n</code></pre>\n\n<p>This can be moved out of every branch, and added as common code at the end.</p>\n\n<p>Along a similar vein, I see the following over and over in the code:</p>\n\n<pre><code>if condition:\n firstnum = round( (... some operation ...), 6)\nif other_condition:\n firstnum = round( (... some operation ...), 6)\nif third_condition:\n firstnum = round( (... some operation ...), 6)\nif fourth_condition:\n firstnum = round( (... some operation ...), 6)\n</code></pre>\n\n<p>How about:</p>\n\n<pre><code>if condition:\n result = ... some operation ...\nelif other_condition:\n result = ... some operation ...\nelif third_condition:\n result = ... some operation ...\nelif fourth_condition:\n result = ... some operation ...\n\nfirstnum = round(result, 6)\n</code></pre>\n\n<p>Maybe you want a <code>def precision(value)</code> function that rounds <code>value</code> to the desired precision. If you want to increase the precision later, you could change this in one spot.</p>\n\n<p>Again, <code>screen.set(is_int(firstnum))</code> is repeated over and over, occasionally with <code>secondnum</code> as the argument. How about a <code>set_screen(value)</code> function which sets the <code>screen</code> variable to the <code>int</code> or <code>float</code> representation of the value?</p>\n\n<p>Or a <code>def set_firstnum(value)</code> function which rounds the value to the desired precision, sets the <code>firstnum</code> variable, and updates the <code>screen</code>.</p>\n\n<hr>\n\n<p>You have <code>lambda</code> functions that call functions based on which button is pressed. But you are inconsistent about what you pass to the function. Does <code>number_pressed(butt)</code> take an integer, such as <code>0</code> through <code>9</code>, or a string such as (<code>'.'</code>)? You pass in both types, which forces you to use <code>str(butt)</code> in the function itself to convert the input into a string. Instead, just always pass in a string value.</p>\n\n<p>Creation of the GUI. You have written a lot of code for something that can be done in a loop.</p>\n\n<pre><code>for idx, digit in enumerate(\"1234567890\"):\n cmd = lambda arg=digit: number_pressed(arg)\n btn = Button(root, text=digit, command=cmd, bg=\"gainsboro\",\n bd=3, padx=12, pady=5, font=('Helvetica', 14, bold))\n btn.grid(row = 2 + idx // 3, column = idx % 3, sticky=W)\n</code></pre>\n\n<p>With 5 lines, instead of 30, we create all 10 digit buttons.</p>\n\n<p><strong>Note</strong>: We needed a little bit of magic (<code>arg=digit</code>) to generate the lambda functions without binding the <code>digit</code> variable itself to the lambda function body. Without that magic, the lambda functions for all buttons would use the last value assigned to the <code>digit</code> variable when the lambda function gets invoked ... which would mean every button would call <code>number_pressed('0')</code>.</p>\n\n<p>You can generate the remaining buttons in a similar manner. The main difficulty is ensuring the right <code>padx</code>, <code>bg</code>, and <code>font</code> values, which are different for some buttons.</p>\n\n<p>Also, you'll want to store the buttons for the math operators, so you can implement <code>math_button_raised()</code>. I'd recommend adding them to a list, so you can still generate them in a loop.</p>\n\n<hr>\n\n<p>Global variables are horrible. Don't use them. A class object would make a nice container for you calculator GUI:</p>\n\n<pre><code>from tkinter import *\n\nclass Calculator:\n\n def __init__(self, root):\n self.current = \"\"\n self.firstnum = 0\n self.screen = StringVar()\n\n display = Entry(root, textvariable=self.screen, justify=RIGHT)\n display.grid(columnspan=4)\n\n for idx, digit in enumerate('1234567890.'):\n cmd = lambda arg=digit: self.number_pressed(arg)\n btn = Button(root, text=digit, command=cmd)\n btn.grid(row=2+idx//3, column=idx%3)\n\n # ... etc ...\n\n def number_pressed(self, digit):\n self.current += digit\n self.screen.set(self.current)\n self.firstnum = float(self.current)\n\n # ... etc ...\n\nroot = Tk()\nCalculator(root)\nroot.mainloop()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T04:23:22.827",
"Id": "217177",
"ParentId": "217153",
"Score": "5"
}
},
{
"body": "<p>The <a href=\"https://codereview.stackexchange.com/a/217177/92478\">answer of AJNeufeld</a> already has a lot of absolutely great advice you should definitely follow.</p>\n\n<p>Another thing that I previously commented on under his answer is that you should not use <code>if bool_value == True:</code> or <code>if bool_value == False:</code>. Instead use <code>if bool_value:</code> and <code>if not bool_value:</code>.</p>\n\n<p>If you follow this advice, and your <code>if</code> statements don't \"read\" well, maybe think about how a <strong>better names for your variables can improve clarity and readability</strong>. I would say a prime example for this would be <code>defxworking</code>. Even after staring at your code for some time I'm still not sure why the variable is named like this. Another instance would be <code>percentt</code>. At first glance I thought about a typo, but later realized that it's probably because of <code>def percent():</code>. I think both, the function (soon to be method if you follow the other review) and the variable could have more telling names.</p>\n\n<p>Since you have already mentioned that you plan to document your code, I invite you to have a read into the \"official\" <a href=\"https://www.python.org/dev/peps/pep-0008\" rel=\"nofollow noreferrer\">Style Guide for Python Code</a> - section <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\">\"Documentation Strings\"</a> (or <a href=\"https://www.python.org/dev/peps/pep-0257/#specification\" rel=\"nofollow noreferrer\">this</a> for further reading).<br/>\nTo sum it up shortly: you're encouraged to document every function with a short docstring, wrapped in <code>\"\"\"...\"\"\"</code>, immediately following the <code>def method_name(your, args)</code>. For example:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def math_pressed(math):\n \"\"\"Handle presses of math operator buttons\"\"\"\n</code></pre>\n\n<p>Following this convention will help Python's built-in <code>help(...)</code> function and also Python IDEs like PyCharm to pick-up your documentation. Future-you will also be greatful, especially if code gets more complex and spread out over multiple files.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T16:34:03.143",
"Id": "217210",
"ParentId": "217153",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "217177",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T18:04:26.507",
"Id": "217153",
"Score": "8",
"Tags": [
"python",
"beginner",
"python-3.x",
"calculator",
"tkinter"
],
"Title": "First Python GUI Calculator with exponentiation function and percents"
} | 217153 |
<p>I wrote a program for a problem in Harvard's CS50 course, Vigenere (week 2).</p>
<p>Here is a <a href="https://docs.cs50.net/2018/x/psets/2/vigenere/vigenere.html" rel="nofollow noreferrer">description of what the program needs to do</a>:</p>
<blockquote>
<p>Design and implement a program that encrypts messages using Vigenère’s cipher.</p>
<ul>
<li><p>Implement your program in a file called <code>vigenere.c</code> in a directory
called <code>vigenere</code>.</p></li>
<li><p>Your program must accept a single command-line argument: a keyword, <em>k</em>, composed entirely of alphabetical characters.</p></li>
<li><p>If your program is executed without any command-line arguments, with more than one command-line argument, or with one command-line argument that contains any non-alphabetical character, your program should print an error (of your choice) and exit immediately, with <code>main</code> returning <code>1</code> (thereby signifying an error).</p></li>
<li><p>Otherwise, your program must proceed to prompt the user for a string of plaintext, <em>p</em>, (as by a prompt for <code>plaintext:</code>) which it must then encrypt according to Vigenère’s cipher with <em>k</em>, ultimately printing the result (prepended with <code>ciphertext:</code> and ending with a newline) and exiting, with <code>main</code> returning <code>0</code>.</p></li>
<li><p>With respect to the characters in <em>k</em>, you must treat <code>A</code> and <code>a</code> as 0, <code>B</code> and <code>b</code> as 1, …, and <code>Z</code> and <code>z</code> as 25.</p></li>
<li><p>Your program must only apply Vigenère’s cipher to a character in <em>p</em> if that character is a letter. All other characters (numbers, symbols, spaces, punctuation marks, etc.) must be outputted unchanged. Moreover, if your code is about to apply the <em>j<sup>th</sup></em> character of <em>k</em> to the <em>i<sup>th</sup></em> character of <em>p</em>, but the latter proves to be a non-alphabetical character, you must wait to apply that <em>j<sup>th</sup></em> character of <em>k</em> to the next alphabetical character in <em>p</em>; you must not yet advance to the next character in <em>k</em>.</p></li>
<li><p>Your program must preserve the case of each letter in <em>p</em>.</p></li>
</ul>
</blockquote>
<p>I received full credit for my answer, but I still want to clean up the code if possible. I am new to programming, so I enjoy seeing what changes more experienced programmers would make.</p>
<pre><code>#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int check(string argv);
int shift(char c);
int main(int argc, string argv[])
{
//check for valid key and save
int valid = 0;
if (argc == 2)
{
valid = check(argv[1]);
}
else
{
printf("Usage: ./vigenere keyword\n");
return 1;
}
//begin encryption
int key;
int index = -1;
int new_code;
if (valid == 1)
{
//get plaintext to encrypt
string plaintext = get_string("plaintext: ");
printf("ciphertext: ");
//iterate through each char of plaintext
for (int j = 0, l = strlen(plaintext); j < l; j++)
{
if (isalpha(plaintext[j]))
{
//iterate through the keyword only when there is an alpha in the plaintext
index++;
key = shift(tolower(argv[1][index % strlen(argv[1])]));
new_code = (int) plaintext[j] + key;
if ((int) tolower(plaintext[j]) + key > 122)
{
new_code = new_code - 26;
printf("%c", (char) new_code);
}
else
{
printf("%c", (char) new_code);
}
}
else
{
printf("%c", (char) plaintext[j]);
}
}
printf("\n");
}
else
{
printf("Usage: ./vigenere keyword\n");
return 1;
}
}
//create key
int shift(char c)
{
int key = (int) c - 97;
return key;
}
//decide if key is valid
int check (string argv)
{
int val = 0;
for (int i = 0, n = strlen(argv); i < n; i++)
{
if (isalpha(argv[i]))
{
val = 1;
}
else
{
val = 0;
break;
}
}
return val;
}
</code></pre>
| [] | [
{
"body": "<p>It's usually best to return as early as possible for invalid cases. This avoids unnecessary nesting and complexity.</p>\n\n<p>e.g. the <code>main()</code> function has a lot of redundant code:</p>\n\n<pre><code>int main(int argc, string argv[])\n{\n //check for valid key and save\n int valid = 0;\n if (argc == 2)\n {\n valid = check(argv[1]); \n }\n else \n {\n printf(\"Usage: ./vigenere keyword\\n\");\n return 1;\n }\n\n ...\n if (valid == 1)\n {\n ...\n }\n else\n {\n printf(\"Usage: ./vigenere keyword\\n\"); \n return 1;\n }\n}\n</code></pre>\n\n<p>and could be shortened to:</p>\n\n<pre><code>int main(int argc, string argv[])\n{\n if (argc != 2 || check(argv[1]) != 0)\n {\n printf(\"Usage: ./vigenere keyword\\n\");\n return 1;\n }\n\n ...\n}\n</code></pre>\n\n<p>The main loop of the program could be abstracted to a separate function (after checking for a valid key / printing usage on error).</p>\n\n<hr>\n\n<p>Similarly <code>check()</code> could be written as:</p>\n\n<pre><code>int check (string argv)\n{\n for (int i = 0, n = strlen(argv); i < n; i++)\n {\n if (!isalpha(argv[i]))\n {\n return 1;\n }\n }\n\n return 0;\n}\n</code></pre>\n\n<hr>\n\n<p><code>check()</code> is not an informative name for a function. It should at least be <code>check_key</code>, or <code>is_all_alpha</code> or something. <code>shift()</code> is a similarly cryptic name.</p>\n\n<hr>\n\n<p>By using <code>strlen</code>, we are unnecessarily iterating the string twice (once to find the null at the end, then again to process it). We can simply run until we find a null character:</p>\n\n<pre><code>for (int j = 0; plaintext[j]; ++j)\n</code></pre>\n\n<hr>\n\n<p>Don't use magic numbers. What are <code>122</code>, <code>26</code>, or <code>97</code>?</p>\n\n<hr>\n\n<p>Variables should be declared as close to their point of usage as possible, and initialized with real values. (<code>key</code>, <code>index</code>, <code>new_code</code>).</p>\n\n<hr>\n\n<p>It would be better to use another variable (e.g. <code>keyword</code>) as an alias, rather than using <code>argv[1]</code> throughout the code.</p>\n\n<p>There is no need to <code>strlen()</code> the keyword for every character.</p>\n\n<hr>\n\n<p>The main loop always ends up printing a char. The rest of the code just decides what the char will be. So perhaps it could be abstracted into a function. Also, since we are expected to treat both 'a' and 'A' the same, we can simplify things by only outputting letters in lowercase.</p>\n\n<p>I'd be inclined to do something like this (not tested):</p>\n\n<pre><code>string key = argv[1];\nint key_len = strlen(key);\nint key_i = 0;\nfor (int j = 0; plaintext[j]; ++j)\n{\n char p = plaintext[j];\n char c = !isalpha(p) ? p : encode_char(p, key[key_i++ % key_len]);\n printf(\"%c\", c);\n}\n\nprintf(\"\\n\");\n...\n\nchar encode_char(char plaintext, char key)\n{\n assert(isalpha(plaintext)); // #include <assert.h>\n\n int k = shift(tolower(key));\n int p = shift(tolower(plaintext));\n\n return unshift((p + k) % 26);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T14:09:29.467",
"Id": "420127",
"Score": "0",
"body": "The instructions say that the program must be case-preserving, therefore outputting only lowercase letters won't work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T18:17:46.600",
"Id": "420149",
"Score": "0",
"body": "Good catch. I missed that last point. I guess I'd do much the same thing, but check the case before hand and re-apply it with `toupper()` afterwards if necessary."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T21:38:51.967",
"Id": "217161",
"ParentId": "217155",
"Score": "6"
}
},
{
"body": "<p>It appears that you built and tested this code on a system using ASCII or similar encoding. Codings other than ASCII will cause you problems:</p>\n\n<ul>\n<li>Encodings that are supersets of ASCII have more characters that match <code>isalpha()</code> (e.g. in Latin-1, <code>à</code> is an alphabetic character).</li>\n<li>Other encodings have different numeric values for <code>a</code>, <code>A</code> and the other values you've written as integer literals.</li>\n<li>Some encodings (notably EBCDIC) don't have contiguous alphabetic runs, so performing arithmetic on characters won't give the results you want.</li>\n<li><code>isalpha()</code> and related functions have undefined behaviour when passed negative values (in this code, that can happen on systems where <code>char</code> is a signed type).</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T10:03:43.790",
"Id": "217191",
"ParentId": "217155",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "217161",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T18:30:12.537",
"Id": "217155",
"Score": "4",
"Tags": [
"c",
"vigenere-cipher"
],
"Title": "CS50 Vigenere program"
} | 217155 |
<p>I'm currently a 3rd year computer science student and lecturers have never checked the readability and maintainability of code. We were only marked on our outputs and as such I've written some truly horrible looking code in the past. I'm trying to work on that and one thing I've learned is that it's a good idea to put things in functions to make testing and maintaining code easier. </p>
<p>I completed <a href="https://www.codewars.com/kata/catching-car-mileage-numbers/train/python" rel="nofollow noreferrer">the following question</a>:</p>
<blockquote>
<p>Write the function that parses the mileage number input, and returns a <code>2</code> if the number is "interesting" (see below), a <code>1</code> if an interesting number occurs within the next two miles, or a <code>0</code> if the number is not interesting.</p>
<h3>"Interesting" Numbers</h3>
<p>Interesting numbers are 3-or-more digit numbers that meet one or more of the following criteria:</p>
<ul>
<li>Any digit followed by all zeros: <code>100</code>, <code>90000</code></li>
<li>Every digit is the same number: <code>1111</code></li>
<li>The digits are sequential, incementing<sup>†</sup>: <code>1234</code></li>
<li>The digits are sequential, decrementing<sup>‡</sup>: <code>4321</code></li>
<li>The digits are a palindrome: <code>1221</code> or <code>73837</code></li>
<li>The digits match one of the values in the <code>awesome_phrases</code> array</li>
</ul>
<p><sup>†</sup> For incrementing sequences, <code>0</code> should come after <code>9</code>, and not before <code>1</code>, as in <code>7890</code>.<br>
<sup>‡</sup> For decrementing sequences, <code>0</code> should come after <code>1</code>, and not before <code>9</code>, as in <code>3210</code>.</p>
</blockquote>
<p>My code is:</p>
<pre><code>def number_followed_by_zeroes(number):
#divides a number until there are no more trailing zeroes
while(number%10 == 0):
number = number/10
if(number>10):
return False
return True
def repeating_digit(number):
#stores all digits in a set(duplicates not allowed in sets)
#converts to list of digits then stores in set
unique_digits = set( list( str( number ) ) )
#All digits were the same
if(len(unique_digits) == 1):
return True
return False
def increasing_sequential(number):
#store all digits in a list
digits = list( str( number ) )
#Sorted function doesn't alter original list
sorted_list = sorted(digits)
#While loop ensures all zeros are at the end of sorted list
#As specified by question
zero_edge = sorted_list[0]
while(zero_edge == "0"):
sorted_list.append(sorted_list[0])
del sorted_list[0]
zero_edge = sorted_list[0]
#Make sure it's incrementally increasing
#consec_num stands for consecutive_number
consec_num = int(sorted_list[0])
for i in sorted_list:
if consec_num != int(i):
return False
consec_num += 1
if i == "9":
consec_num = 0
#if sorted and original list are the same then
#number was sorted
if(sorted_list == digits):
return True
return False
def decreasing_sequential(numbers):
#similar to increasing_sequential but in reverse
#No need to alter normal sorting in regards to zero
digits = list( str( numbers ) )
sorted_list = sorted( digits )
#Make sure it's incrementally increasing
#consec_num stands for consecutive_number
consec_num = int(sorted_list[0])
for i in sorted_list:
if consec_num != int(i):
return False
consec_num += 1
sorted_list.reverse()
if(sorted_list == digits):
return True
return False
def palindrome(numbers):
digits = list( str( numbers ) )
#Splits the digits into half storing each in their own list
first_half = digits[0:(int(len(digits) /2))]
second_half = digits[int(len(digits)/2):]
#Runs if there were an odd number of digits, deletes the middle number
if(len(first_half) != len(second_half)):
del second_half[0]
#Since a second half of string would be reverse copy of first in a palindrome
second_half.reverse()
if(second_half == first_half):
return True
return False
def is_interesting(number, awesome_phrases):
if(number<98):
return 0
if number in awesome_phrases:
return 2
#if the original number is awesome
if(number > 99 and (number_followed_by_zeroes(number) or repeating_digit(number) or
increasing_sequential(number) or decreasing_sequential(number) or
palindrome(number)) ):
return 2
#if the next 2 numbers are awesome
for i in range(1,3):
number += 1
if number in awesome_phrases:
return 1
if(number_followed_by_zeroes(number) or repeating_digit(number) or
increasing_sequential(number) or decreasing_sequential(number) or
palindrome(number) ):
return 1
return 0
pass
</code></pre>
<p>Would I be fine if I coded this at a business or have I created too many functions or taken too rudimentary approaches to each function?</p>
<p>One thing I did consider is to add another function to make the number is above 99</p>
<pre><code>def great_enough(number):
if number>99:
return True
</code></pre>
| [] | [
{
"body": "<h2>Confusion</h2>\n\n<p>I think that the challenge is poorly posed, because of an ambiguity in the term \"interesting\". On one hand, it says \"A number is only interesting if it is greater than <code>99</code>!\" On the other hand, the specification calls for the <code>is_interesting()</code> function to return \"<code>1</code> if an interesting number occurs with the next two miles\". So, what should <code>is_interesting(98, [])</code> return? By my interpretation, it should return <code>1</code>, because <code>98</code> itself is not interesting, but it is nearly <code>100</code>, which is <code>1</code> followed by two zeroes. Your code does that, but it's not obvious why it behaves that way, especially since you wrote <code>if(number<98): return 0</code>. (Why is 98 special? Because it's 2 less than a three-digit number. So, you've encoded the within-two rule in two places: <code>if(number<98): return 0</code> and <code>for i in range(1,3)</code> — and it's <strong>bad practice to encode a rule twice</strong>.)</p>\n\n<p>It's unfortunate that the challenge calls for an <code>is_interesting()</code> function to be written, when it would be more accurately described as \"is interesting or <em>approaching</em> interesting\". Given the unfortunate specification, though, I think it would be a good idea to write a function <code>is_intrinsically_interesting()</code>, which returns either <code>True</code> or <code>False</code>, without considering the next two integers. That would <strong>eliminate the redundancy in your implementation of <code>is_interesting()</code></strong>.</p>\n\n<p><strong>Your comments confuse awesomeness (whether a number appears in the <code>awesome_phrases</code> list) with interestingness.</strong></p>\n\n<h2>Functions</h2>\n\n<p>You and the challenge talk about testing, but you haven't included any tests. I suggest writing <a href=\"https://docs.python.org/3/library/doctest.html\" rel=\"noreferrer\"><strong>doctests</strong></a>.</p>\n\n<p>A good <strong>naming convention</strong> to follow is <code>is_…</code> for predicates (functions that return either <code>True</code> or <code>False</code>.</p>\n\n<p>Most of your functions take a <code>number</code> parameter, but for some reason you wrote <code>decreasing_sequential(numbers)</code> and <code>palindrome(numbers)</code>, which is confusing.</p>\n\n<p>Since most of these tests operate on digits, consider accepting a list of digits instead of the integer.</p>\n\n<h2>Expressiveness</h2>\n\n<p>Some of your functions are rather long. <strong>Each test could be written as a one-liner, or nearly so.</strong></p>\n\n<p>Instead of writing</p>\n\n<pre>\nif <i>condition</i>:\n return True\nreturn False\n</pre>\n\n<p>… you should just write <code>return <em>condition</em></code> (or, to explicitly coerce the result to a boolean, <code>return bool(<em>condition</em>)</code>.</p>\n\n<p>The <code>pass</code> on the very last line is dead code.</p>\n\n<p>The <code>palindrome()</code> function should be written such that you don't need separate even- and odd-length cases.</p>\n\n<h2>Suggested solution</h2>\n\n<pre><code>def is_digit_followed_by_all_zeroes(digits):\n \"\"\"\n >>> is_digit_followed_by_all_zeroes([1, 0, 0])\n True\n >>> is_digit_followed_by_all_zeroes([9, 0, 0, 0, 0])\n True\n >>> is_digit_followed_by_all_zeroes([1, 0, 1])\n False\n \"\"\"\n return all(digit == 0 for digit in digits[1:])\n\ndef is_repeated_digit(digits):\n \"\"\"\n >>> is_repeated_digit([1, 1, 1, 1])\n True\n >>> is_repeated_digit([2, 1, 2])\n False\n \"\"\"\n return 1 == len(set(digits))\n\ndef is_increasing_sequential(digits):\n \"\"\"\n >>> is_increasing_sequential([1, 2, 3, 4])\n True\n >>> is_increasing_sequential([7, 8, 9, 0])\n True\n >>> is_increasing_sequential([9, 0, 1])\n False\n \"\"\"\n ORDER = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]\n return all(\n ORDER.index(i) + 1 == ORDER.index(j)\n for i, j in zip(digits, digits[1:])\n )\n\ndef is_decreasing_sequential(digits):\n \"\"\"\n >>> is_decreasing_sequential([4, 3, 2, 1])\n True\n >>> is_decreasing_sequential([3, 2, 1, 0])\n True\n >>> is_decreasing_sequential([2, 1, 0, 9])\n False\n \"\"\"\n return all(\n i - 1 == j\n for i, j in zip(digits, digits[1:])\n )\n\ndef is_palindrome(digits):\n \"\"\"\n >>> is_palindrome([7,3,8,3,7])\n True\n >>> is_palindrome([1,2,2,1])\n True\n >>> is_palindrome([1,2,3,1])\n False\n \"\"\"\n half_len = (len(digits) + 1) // 2 # Half the length, rounding up\n return digits[:half_len] == digits[-1 : -half_len-1 : -1]\n\ndef is_intrinsically_interesting(number, awesome_phrases):\n \"\"\"\n Test whether the number itself is \"interesting\".\n \"\"\"\n digits = [int(d) for d in str(number)]\n return number > 99 and (\n is_digit_followed_by_all_zeroes(digits) or\n is_repeated_digit(digits) or\n is_increasing_sequential(digits) or\n is_decreasing_sequential(digits) or\n is_palindrome(digits)\n ) or number in awesome_phrases\n\ndef is_interesting(number, awesome_phrases):\n return (\n 2 if is_intrinsically_interesting(number, awesome_phrases) else\n 1 if is_intrinsically_interesting(number + 1, awesome_phrases) else\n 1 if is_intrinsically_interesting(number + 2, awesome_phrases) else\n 0\n )\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T20:37:29.057",
"Id": "217158",
"ParentId": "217156",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T18:53:21.610",
"Id": "217156",
"Score": "4",
"Tags": [
"python",
"algorithm",
"programming-challenge"
],
"Title": "Code to find if a number fulfills certain requirements (e.g. sequential increasing, palindrome, repeating, etc)"
} | 217156 |
<p>I created my cross-platform implementations of <code>getline</code> function in C.</p>
<p>It takes different arguments and have different return values than 'original' <code>getline</code> function, but aim is the same. The only argument <code>input_file</code> is file from which the line have to be read. Return value is the line read from file or NULL if nothing read.</p>
<p>Here is one implementation, using <code>fgets()</code>:</p>
<pre><code>static inline char*
getline(FILE* input_file){
const unsigned int chunk_size=256;
char* line=malloc(chunk_size*sizeof*line+1);
if(line==NULL){
fprintf(stderr,"Fatal: failed to allocate %zu bytes.\n",chunk_size*sizeof*line+1);
exit(1);
}
unsigned int i;
for(i=0;;++i){
memset(line+chunk_size*i,0,chunk_size);
if(fgets(line+chunk_size*i,chunk_size+1,input_file)==NULL)
break;
if(line[strlen(line)-1]=='\n')
break;
char* tmp=realloc(line,chunk_size*(i+2)*sizeof*line+1);
if(tmp==NULL){
fprintf(stderr,"Fatal: failed to allocate %zu bytes.\n",chunk_size*(i+2)*sizeof*line+1);
exit(1);
}else
line=tmp;
}
if(strlen(line)==0){
free(line);
return NULL;
}else{
line[strlen(line)-1]=0;
return line;
}
}
</code></pre>
<p>Here is my second implementation, using <code>fgetc()</code>:</p>
<pre><code>static inline char*
getline(FILE* input_file){
const unsigned int chunk_size=3;
char* line=calloc(chunk_size,sizeof*line+1);
if(line==NULL){
fprintf(stderr,"Fatal: failed to allocate %zu bytes.\n",chunk_size*sizeof*line+1);
exit(1);
}
char c;
unsigned int i,j;
for(i=0,j=1;;++i){
c=(char)fgetc(input_file);
if(c==EOF||c=='\n')
break;
line[i]=c;
if(i==chunk_size*j){
++j;
char* tmp=realloc(line,chunk_size*(j+1)*sizeof*line+1);
if(tmp==NULL){
fprintf(stderr,"Fatal: failed to allocate %zu bytes.\n",chunk_size*(j+1)*sizeof*line+1);
exit(1);
}else{
line=tmp;
memset(line+chunk_size*j,0,chunk_size);
}
}
}
if(strlen(line)==0){
free(line);
return NULL;
}else{
line[strlen(line)]=0;
return line;
}
}
</code></pre>
| [] | [
{
"body": "<p><code>exit(1)</code> is probably a bad idea, so is <code>fprintf</code> to <code>stderr</code>. We don't know how big the string can be, therefore running out of memory could be valid, and if <code>stderr</code> is redirected to somewhere a client can see. <code>realloc</code> should already set <code>errno</code> to <code>ENOMEM</code>, so you could probably just return <code>NULL</code>, and modify comment that upon returning <code>NULL</code>, caller should check <code>errno</code>. Or maybe you should return empty string if there's no data, and use <code>NULL</code> to indicate error.</p>\n\n<p>change <code>calloc</code> to <code>malloc</code>, as you anyway <code>NULL</code> terminate the string in your <code>fgetc</code> implementation.</p>\n\n<p>Instead of having this code duplicated for error message (which I vote against), and actual calculation: <code>chunk_size*(j+1)*sizeof*line+1</code>, you could create a variable and use it in both places, therefore you know you print exactly what you did, and there wasn't a mistake if you had to change the calculation slightly.</p>\n\n<p>Try this on windows (as it claims to be a cross platform implementation), but from memory <code>fgetc</code> will return <code>'\\r'</code>, which you'll put right into the line, whereas I'm pretty sure <code>fgets</code> won't return <code>'\\r'</code>, when the line terminator is <code>\"\\r\\n\"</code>; I believe <code>fgets</code> returns <code>\"\\n\"</code>, not <code>\"\\r\\n\"</code> on windows, even if <code>\"\\r\\n\"</code> is in the input stream.</p>\n\n<p>You don't need to assign data to <code>tmp</code> like this: <code>char* tmp=realloc(line,chunk_size*(i+2)*sizeof*line+1);</code> as upon success you always do: <code>line=tmp</code>, and upon failure, line will no longer point to valid memory. So you could just assign to <code>line</code>.</p>\n\n<p>Notice how you're calling <code>malloc/calloc/realloc</code>, I would add a <code>freeline</code> function to your code in order to free any memory allocated by this code. The caller may not be using the same <code>malloc/calloc/realloc</code> you're using, and their <code>free</code> may not be compatible.</p>\n\n<p>Finally I'm not really sure about this: <code>chunk_size*(j+1)*sizeof*line+1</code><br/>\nI think you want: <code>chunk_size*(j+1)*sizeof*char+1</code>, as I think <code>line</code> is of size <code>4</code> or maybe even <code>8</code>?, print it out in the debugger, and see, I think you're allocating a lot more memory then you end up putting into the array.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T13:43:57.123",
"Id": "422998",
"Score": "1",
"body": "Welcome to Code Review! Your answer has a lot of claims in it (\"I'm pretty sure ...\", \"I think ...\") and it would be nice to back these up with some references to documentation resources."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T14:46:42.210",
"Id": "423011",
"Score": "0",
"body": "I'm pretty sure that although many `realloc()` implementations set `errno` as you claim (and POSIX mandates it), that's not in the C Standard, so a conforming implementation may exist which doesn't do that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T15:05:40.673",
"Id": "423015",
"Score": "0",
"body": "Ok, if the errno is not set for some reason, I would recommend setting it explicitly from the method. This might be a good idea in either case, as it makes the intention explicit, vs. relying on underlying code; Also if there is still going to be an fprintf to report on error, it may change the errno to something else, thus setting it right before returning would be good."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T13:15:51.500",
"Id": "219017",
"ParentId": "217157",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T20:06:38.347",
"Id": "217157",
"Score": "5",
"Tags": [
"c",
"comparative-review",
"file",
"portability"
],
"Title": "Two cross-platform implementations of getline in C"
} | 217157 |
<p>I wrote a function that joins a collection of Strings with a delimiter. It's based on <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.Iterable-" rel="nofollow noreferrer">Java's version of the function</a>. I'm assuming C has some similar built-in.</p>
<p>Example:</p>
<pre><code>int main() {
char* coll[] = {"Hello", "World", "This", "Should", "Be", "Joined!"};
char* joined = awfulJoinStr(", ", coll, 6);
printf("%s\n", joined);
// Prints "Hello, World, This, Should, Be, Joined!"
}
</code></pre>
<p>Basically how it works is, it alternates between iterating the collection strings and the delimiter. It writes the current word to the buffer until it hits a null terminator, then it switches to either writing the next word, or to the delimiter.</p>
<p>I'm new to C, so I'd like comments on anything in the code. My main concerns:</p>
<ul>
<li><p>It's super inefficient. All the strings need to be iterated at the start to get a total length so I know how big of a buffer to allocate later. I can't see how else I'd do it though unless I do reallocations while writing, but that seems like it would be even more inefficient.</p></li>
<li><p>It requires <em>three</em> iteration counters (<code>stringI</code>, <code>charI</code>, and <code>bufferI</code>) and a flag. I need to keep track of the current word that I'm writing, my position in it, and need to track where I am in the buffer. I also need a flag to track when I'm currently writing a delimiter or word.</p></li>
<li><p>It requires passing in how many strings I want to join (<code>nStrings</code>). This seems like it's necessary as well since I can't know the length of <code>strArr</code>, but it's unfortunate.</p></li>
<li><p>It's huge. It doesn't fit in one screen at a comfortable zoom. </p></li>
</ul>
<p>I also included my version of <code>strlen</code> for kicks, and because I used it instead of the built-in.</p>
<pre><code>#include <stdlib.h>
#include <stdbool.h>
size_t myStrLen(char* str) {
size_t length = 0;
while (str[length] != '\0') {
length++;
}
return length;
}
char* awfulJoinStr(char* delimiter, char** strArr, size_t nStrings) {
size_t delimiterSize = myStrLen(delimiter);
size_t totalDelimiterSize = (nStrings - 1) * delimiterSize;
size_t totalStringSize = 0;
for (size_t i = 0; i < nStrings; i++) {
totalStringSize += myStrLen(strArr[i]);
}
size_t bufferSize = totalDelimiterSize + totalStringSize + 1;
char* buffer = malloc(sizeof(char) * bufferSize);
buffer[bufferSize - 1] = '\0';
bool inDelim = false;
size_t charI = 0;
size_t stringI = 0;
for (size_t bufferI = 0; bufferI < bufferSize - 1;) {
char current = inDelim ? delimiter[charI] : strArr[stringI][charI];
if (current == '\0') {
// Start at the beginning of the word and toggle what we're writing
charI = 0;
if (!inDelim) {
stringI++;
}
inDelim = !inDelim;
} else {
buffer[bufferI] = current;
charI++;
bufferI++;
}
}
return buffer;
}
</code></pre>
| [] | [
{
"body": "<p>I see a number of things that may help you improve your code.</p>\n\n<h2>Use standard library functions where appropriate</h2>\n\n<p>Except as a learning exercise (which I recognize this probably is), there's little reason to write duplicates of existing, well-tested, well-documented and often highly optimized library functions. For that reason, in real code, I'd expect <code>strlen()</code> to be used rather than <code>myStrLen()</code>.</p>\n\n<h2>Don't leak memory</h2>\n\n<p>Unlike Java, in C it is the responsibility of the programmer to clean up memory allocations. For that reason, I'd expect the sample code to have the line <code>free(joined);</code> before the end of <code>main</code>.</p>\n\n<h2>Use <code>const</code> where appropriate</h2>\n\n<p>The <code>delimiter</code> and <code>strArr</code> arguments to <code>awfulJoinStr</code> are not and should not be modified by that function, so it would be better to indicate that fact and change the parameter list to this:</p>\n\n<pre><code>char* awfulJoinStr(const char* delimiter, const char** strArr, size_t nStrings)\n</code></pre>\n\n<h2>Consider using a sentinel value</h2>\n\n<p>Generally, there are two ways to tell a function the size of a list. Either it can be passed explicitly as you do in the current code, or one can use a <em>sentinel value</em> which is simply a special \"end of list\" marker value. In this case, I think it might be more convenient to use a sentinel value of <code>NULL</code>. So your <code>coll</code> could look like this:</p>\n\n<pre><code>const char* coll[] = {\"Hello\", \"World\", \"This\", \"Should\", \"Be\", \"Joined!\", NULL};\n</code></pre>\n\n<p>And now the code could look for the special <code>NULL</code> value instead of having to pass a count.</p>\n\n<h2>Check for errors</h2>\n\n<p>The call to <code>malloc</code> could fail. The <em>only</em> indication you would have of this would be that it would return <code>NULL</code>, so for that reason, you should check for a <code>NULL</code> return from <code>malloc</code> before using the returned pointer or risk having your code crash.</p>\n\n<p>Also, if <code>nStrings</code> is zero, the calculated <code>totalDelimiterSize</code> is huge and the result will certainly not be what you want, even if it doesn't crash.</p>\n\n<h2>Simplify code by knowing the standard well</h2>\n\n<p>The current code includes this line:</p>\n\n<pre><code>char* buffer = malloc(sizeof(char) * bufferSize);\n</code></pre>\n\n<p>However, the standard <em>defines</em> <code>sizeof(char)</code> as always being equal to <code>1</code> so this could and should be written like this instead:</p>\n\n<pre><code>char* buffer = malloc(bufferSize);\n</code></pre>\n\n<h2>Bail out early on error</h2>\n\n<p>If the parameters to the function are faulty, or if there are no passed strings, it would probably make most sense to bail out early, rather than doing a bunch of work that would ultimately be thrown away. </p>\n\n<h2>Understand the use of pointers</h2>\n\n<p>A fundamental (but not always easy!) concept in C programming is the <em>pointer</em>. Understanding how to use pointers effectively is an important skill to learn when mastering C programming. Examples as applied to this program are shown in the code in the next section.</p>\n\n<h2>Simplify your code by decomposing into functions</h2>\n\n<p>Here's one way to rewrite the function using most of what's suggested above:</p>\n\n<pre><code>char* awfulJoinStr(const char* delimiter, const char** strArr) {\n if (strArr == NULL || delimiter == NULL) {\n return NULL;\n }\n // first calculate the total length of the strings\n size_t bufferSize = 0;\n size_t nStrings = 0;\n for (const char **str = strArr; *str != NULL; ++str) {\n bufferSize += strlen(*str);\n ++nStrings;\n }\n if (nStrings == 0) {\n return NULL;\n }\n size_t delimiterSize = strlen(delimiter);\n bufferSize += (nStrings - 1) * delimiterSize + 1;\n char* buffer = malloc(bufferSize);\n if (buffer == NULL) {\n return NULL;\n }\n buffer[bufferSize - 1] = '\\0';\n for (char *curr = scopy(buffer, *strArr++); *strArr; ++strArr) {\n curr = scopy(curr, delimiter);\n curr = scopy(curr, *strArr);\n }\n return buffer;\n}\n</code></pre>\n\n<p>As you see, the copying is done via a custom string copy function <code>scopy</code>. We use this instead ofthe standard <code>strcpy</code> because <code>strcpy</code> returns the <em>start</em> of the destination string, but this code requires one past the end instead. Here's <code>scopy</code>:</p>\n\n<pre><code>char *scopy(char *dest, const char *src) {\n while (*src) {\n *dest++ = *src++;\n }\n return dest;\n}\n</code></pre>\n\n<p>This short function uses a lot of specialized C knowledge. First, the passed parameters are both pointers. We can alter the pointers without necesarily altering what they're pointing to. Second is the idea of post-increment versus pre-increment. This line is a very common C idiom:</p>\n\n<pre><code>*dest++ = *src++;\n</code></pre>\n\n<p>What it means in English is, in effect, \"get the thing that <code>src</code> is pointing to and copy that to wherever <code>dest</code> is pointing; then increment both pointers.\" (That's not exactly the sequence of events, but it will suffice to understand the intent of this line.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T00:51:34.743",
"Id": "217165",
"ParentId": "217163",
"Score": "4"
}
},
{
"body": "<p>Regarding: </p>\n\n<pre><code>char* buffer = malloc(sizeof(char) * bufferSize);\n</code></pre>\n\n<ol>\n<li><p>Always check (!=NULL) the returned value to assure the operation was successful. If not successful, then call <code>perror( \"my error message\" );</code> to notify the user that a problem occurred and what the system thinks is the cause of the problem. Then, most likely, clean up (close files, etc) then call: <code>exit( EXIT_FAILURE );</code> </p></li>\n<li><p>The expression: <code>sizeof( char )</code> is defined in the C standard as 1. Multiplying anything by 1 has no effect. I suggest removing that expression.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T09:38:51.013",
"Id": "420102",
"Score": "2",
"body": "`perror()` is not appropriate for a `malloc()` failure, as `errno` is not set by that. Use a plain `fprintf(stderr, \"Failed memory allocation\");`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T08:43:18.560",
"Id": "420227",
"Score": "0",
"body": "@TobySpeight, This is an excerpt from the MAN page. Note that it does set `errno`. \"ERRORS\n calloc(), malloc(), realloc(), and reallocarray() can fail with the following error:\n\n ENOMEM Out of memory.\" So, the function: `perror()` is a valid function to call when `malloc()` fails"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T12:54:27.057",
"Id": "420258",
"Score": "0",
"body": "[POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/malloc.html) does indeed specify that `errno` is set. I don't have a C standard handy, but I'm pretty sure that it doesn't mention `errno` with `malloc()` - meaning that non-POSIX platforms may or may not set it. [I'm told](//stackoverflow.com/a/55395293) that Windows and MacOS default libraries *do* set `errno`, so if you only care about those and POSIX, then you may file that recommendation under \"pedantry\"..."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T02:54:50.070",
"Id": "217174",
"ParentId": "217163",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "217165",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T23:03:22.450",
"Id": "217163",
"Score": "4",
"Tags": [
"beginner",
"c",
"strings",
"c99"
],
"Title": "String joining function in C"
} | 217163 |
<p>I need help simplifying this Python code. I'm new, this adventure game is one of my first projects. I have tried simplifying my code already and this was the best result I could get.</p>
<pre><code>import time
import random
r = random.randrange(10)
#r is the weapon being used for gun
#pauses the story
def print_pause(lines):
for line, pause in lines:
print(line)
time.sleep(pause)
def print_sep():
print("You chose " + answer + ".")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
def game_over():
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("""
___
/ __|__ _ _ __ ___ _____ _____ _ _
| (_ / _` | ' \/ -_) / _ \ V / -_) '_|
\___\__,_|_|_|_\___| \___/\_/\___|_|
""")
def win():
print("""
_ _ _
| | | | (_)
| |___| | ___ _ _ _ _ _ _ ____
|_____ |/ _ \| | | | | | | | | _ \
_____| | |_| | |_| | | | | | | | | |
(_______|\___/|____/ \___/|_|_| |_|
""")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("Soviet Union, 1988")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
time.sleep(1)
name = input("Comrade, what is your name?")
print_pause([
("-- KGB Offices, Moscow --", 1),
("Glory to the party and the glorious leader, " + name + ".", 2),
("You were arrested after participating in a democratic protest in\nKazan yesterday. My name is Vladimir; tell me what happened.", 3),
("Do you: \n A: Tell the KGB officer everything \n B: Say nothing", 0) #how many seconds to rest
])
answer = input("A or B?")
print_sep()
if answer == "A":
print_pause([
("You tell Vladimir everything; and he approaches you with a\nlucrative offer.", 3),
("You have a one time opportunity to join the KGB, otherwise you face prison time.", 3),
("Do you: \n A: Accept the offer \n B: Decline the offer", 3)
])
answer = input("A or B?")
print_sep()
if answer == "A":
print_pause([
("Agent " + name + ", welcome to the KGB.", 1),
("Here is your badge and gun; your first task; help us arrest known\ndissident guards at the Inner German border.", 3),
("You are sent to the Inner German border; and soon you are feet away from West Germany. Do you escape?", 3),
("Do you: \n A: Escape \n B: Continue on your mission", 3)
])
answer = input("A or B?")
print_sep()
if answer == "A":
if r > 5:
print_pause([
("Success, you escaped from the Eastern Bloc.", 2),
("Wait another 3 years, and all of communism collapses.", 2)
])
win()
else:
print_pause([
("As you try to climb across the border, you step on an infamous\nSM-70 mine.", 3),
("80 steel cubes rip into your body.", 2)
])
game_over()
elif answer == "B":
print_pause([
("You find the guard dissident, and you shout 'HALT!'", 2),
("He whips around, but before he can shoot you, you tackle him to the ground", 3),
("For the rest of your life, you continue to work for the KGB, and retire comfortably after the collapse of the USSR", 3)
])
win()
elif answer == "B":
print_pause([
("Prison, like Vladimir said, is your new home.", 2),
("But the USSR collapses in 1991; so you are free to go after 3 years!", 3),
("Unfortunately the KGB wants you to keep quiet about what you went\nthrough so a splinter faction kills you to make sure you don't leak\nany info.", 3)
])
game_over()
elif answer == "B":
print_pause([
("You are tortured for days on by Vladimir.", 2),
("Just when you think you lost all hope, you find an opportunity: his pistol left on the table.", 2),
("Do you:\n A: Grab the pistol \n B: Leave it on the table", 2.5)
])
answer = input("A or B?")
print_sep()
if answer == "A":
if r > 5:
print_pause([
("You pick up the pistol. It's a Makarov; standard issue for KGB. You fire!\nThe bullet whizzes through the air... and hits it's mark!", 3),
("Vladimir lies in a pool of blood as you run." , 2),
("Do you: \n A: Run away \n B: Surrender", 2)
])
answer = input("A or B?")
print_sep()
if answer == "A":
print_pause([
("You escape... barely.", 2),
("You spend the rest of your years in hiding until your charges are dropped after the dissolution of the USSR.", 3)
])
win()
elif answer == "B":
print_pause([
("Bad choice... the USSR carries the death penalty for murder cases.", 2)
("I'll leave the rest to your imagination.", 2)
])
game_over()
else:
print_pause([
("You shoot, and the bullet whizzes past Vladimir, hitting the wall.", 3),
("He easily whips around and chokes you to death with the ferocity of a bear." , 2)
])
game_over()
elif answer == "B":
print_pause([
("You tried your best, but eventually you gave up.", 2),
("You told Vladimir everything, and a show trial exiles you to a gulag.", 2),
("The rest of your days you spend working in the Siberian cold.", 2)
])
game_over()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T01:55:50.800",
"Id": "420076",
"Score": "2",
"body": "Welcome to Code Review! I hope you get some great answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T16:49:57.590",
"Id": "420445",
"Score": "0",
"body": "I rolled back your last edit. After getting an answer you are [not allowed to change your code anymore](https://codereview.stackexchange.com/help/someone-answers) (including removing the code...). This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). Refer to [this post](https://codereview.meta.stackexchange.com/a/1765/120114) for more information"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T22:17:12.990",
"Id": "420475",
"Score": "0",
"body": "Thanks that was an accident of mine."
}
] | [
{
"body": "<h2>Standard docstrings</h2>\n\n<p>Rather than</p>\n\n<pre><code>#pauses the story\ndef print_pause(lines):\n</code></pre>\n\n<p>the standard is to do:</p>\n\n<pre><code>def print_pause(lines):\n \"\"\"\n pauses the story\n \"\"\"\n</code></pre>\n\n<p>It'd be a good idea to add similar documentation to your other functions.</p>\n\n<h2>f-strings</h2>\n\n<p>This:</p>\n\n<pre><code>print(\"You chose \" + answer + \".\")\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>print(f'You chose {answer}.')\n</code></pre>\n\n<p>similar instances elsewhere.</p>\n\n<h2>Hard wraps?</h2>\n\n<p>This:</p>\n\n<pre><code>\"Unfortunately the KGB wants you to keep quiet about what you went\\nthrough so a splinter faction kills you to make sure you don't leak\\nany info.\"\n</code></pre>\n\n<p>shouldn't really include newlines. A proper terminal will auto-wrap on character based on the width of the terminal. If you want to be more careful and wrap on the word, do a little reading about the <code>textwrap</code> library:</p>\n\n<p><a href=\"https://docs.python.org/3.7/library/textwrap.html\" rel=\"noreferrer\">https://docs.python.org/3.7/library/textwrap.html</a></p>\n\n<h2>General</h2>\n\n<p>Your game logic is very simple. As such, consider re-representing your game as a very small game engine, and a set of data - perhaps represented in a .json file - that represents outputs and choices.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T13:45:10.183",
"Id": "217201",
"ParentId": "217164",
"Score": "6"
}
},
{
"body": "<h1>Decouple the game engine from the data</h1>\n\n<p>An adventure game is a good example of a <strong>state</strong> machine: at any given point in the game, a small number of parameters determine the user's position, and a small number of actions are available that cause transitions to possible new states.</p>\n\n<p>For this game, we can give a number to each state:</p>\n\n<ol>\n<li>KGB Offices, Moscow</li>\n<li>Vladimir makes an offer</li>\n<li>Welcome to the KGB</li>\n<li>Escape</li>\n<li>Land-mine</li>\n<li>Kill the guard</li>\n<li>Prison</li>\n<li>Torture</li>\n<li>...</li>\n</ol>\n\n<p>We can represent each state as an object. For example, state 1 might look something roughly like:</p>\n\n<pre><code>id = 1\ndescription = \"You were arrested after participating in \" + more_description\nactions = [ (\"Tell the KGB officer everything\", 2), (\"Say nothing\", 8) ]\n</code></pre>\n\n<p>Now, we're able to turn the game into a loop that just prints the description from the current state and presents the available actions. When the user inputs a valid action, then we set the current state from the action's next state.</p>\n\n<p>With the data separated like this, it's easier to re-use the game engine for an entirely different game, just by changing the data.</p>\n\n<p>If the game data are kept in a separate file to the code, the story could be written by a professional author and the text could be translated into many languages by professional translators even if none of them are programmers - this is common in the software industry, and allows each person to contribute what they're best at without needing additional skills.</p>\n\n<hr>\n\n<p>A small problem that needs fixing is that we always assume the user will enter a valid action. If the user enters something other than the options presented, we should re-ask for valid input. With the game engine transformed into a simple loop, there's only one <code>input()</code> that we need to change - another benefit of separating the code from the data.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T16:51:10.160",
"Id": "217211",
"ParentId": "217164",
"Score": "6"
}
},
{
"body": "<p>Your story is basically a directed graph. From each question you can take multiple routes. So I would represent each question as such, with different types of nodes for when the user chooses, the choice is random or the game is over (either winning or loosing).</p>\n\n<pre><code>import random\n\nclass Node:\n def __init__(self, message, choices):\n self.message = message\n self.choices = choices\n\n def __str__(self):\n return self.message\n\n def choose(self):\n pass\n\n\nclass UserChoice(Node):\n def choose(self):\n while True:\n answer = input(\"A or B?\" )\n if answer in self.choices:\n return self.choices[answer]\n\n\nclass RandomChoice(Node):\n def choose(self):\n return random.choice(list(self.choices.values()))\n\n\nclass Win(Node):\n def __str__(self):\n return super().__str__() + r\"\"\"\n _ _ _\n| | | | (_)\n| |___| | ___ _ _ _ _ _ _ ____\n|_____ |/ _ \\| | | | | | | | | _ \\\n _____| | |_| | |_| | | | | | | | | |\n(_______|\\___/|____/ \\___/|_|_| |_|\n\"\"\"\n\n\nclass GameOver(Node):\n def __str__(self):\n return super().__str__() + r\"\"\"\n ___\n / __|__ _ _ __ ___ _____ _____ _ _\n| (_ / _` | ' \\/ -_) / _ \\ V / -_) '_|\n \\___\\__,_|_|_|_\\___| \\___/\\_/\\___|_|\n\"\"\"\n\n\nnodes = {\n \"start\": UserChoice(\"\"\"-- KGB Offices, Moscow --\nGlory to the party and the glorious leader,\nYou were arrested after participating in a democratic protest in\nKazan yesterday. My name is Vladimir; tell me what happened.\nDo you:\n A: Tell the KGB officer everything\n B: Say nothing\"\"\", {\"A\": \"offer\", \"B\": \"torture\"}),\n \"offer\": UserChoice(\"\"\"You tell Vladimir everything; and he approaches you with a\nlucrative offer.\nYou have a one time opportunity to join the KGB, otherwise you face prison time.\nDo you:\n A: Accept the offer\n B: Decline the offer\"\"\", {\"A\": \"kgb\", \"B\": \"game_over_kgb\"}),\n \"kgb\": UserChoice(\"\"\"Welcome to the KGB.\nHere is your badge and gun; your first task; help us arrest known\ndissident guards at the Inner German border.\nYou are sent to the Inner German border; and soon you are feet away from West Germany. Do you escape?\nDo you:\n A: Escape\n B: Continue on your mission\"\"\", {\"A\": \"escape\", \"B\": \"win_kgb\"}),\n \"escape\": RandomChoice(None, {\"A\": \"win_escape1\", \"B\": \"game_over_mine\"}),\n \"torture\": UserChoice(\"\"\"You are tortured for days on by Vladimir.\nJust when you think you lost all hope, you find an opportunity: his pistol left on the table.\nDo you:\n A: Grab the pistol\n B: Leave it on the table\"\"\", {\"A\": \"pistol_random\", \"B\": \"game_over_gulag\"}),\n \"pistol_random\": RandomChoice(None, {\"A\": \"pistol_lucky\", \"B\": \"game_over_choke\"}),\n \"pistol_lucky\": UserChoice(\"\"\"You pick up the pistol. It's a Makarov;\nstandard issue for KGB. You fire!\nThe bullet whizzes through the air... and hits it's mark!\nVladimir lies in a pool of blood as you run.\nDo you:\n A: Run away\n B: Surrender\"\"\", {\"A\": \"win_escape2\", \"B\": \"game_over_surrender\"}),\n \"win_kgb\": Win(\"\"\"You find the guard dissident, and you shout 'HALT!'\nHe whips around, but before he can shoot you, you tackle him to the ground\nFor the rest of your life, you continue to work for the KGB, and retire comfortably after the collapse of the USSR\"\"\", None),\n \"win_escape1\": Win(\"\"\"Success, you escaped from the Eastern Bloc.\nWait another 3 years, and all of communism collapses.\"\"\", None),\n \"win_escape2\": Win(\"\"\"You escape... barely.\nYou spend the rest of your years in hiding until your charges are dropped after the dissolution of the USSR.\"\"\", None),\n \"game_over_mine\": GameOver(\"\"\"As you try to climb across the border, you step on an infamous\nSM-70 mine.\n80 steel cubes rip into your body.\"\"\", None),\n \"game_over_kgb\": GameOver(\"\"\"Prison, like Vladimir said, is your new home.\nBut the USSR collapses in 1991; so you are free to go after 3 years!\nUnfortunately the KGB wants you to keep quiet about what you went\nthrough so a splinter faction kills you to make sure you don't leak\nany info.\"\"\", None),\n \"game_over_surrender\": GameOver(\"\"\"Bad choice... the USSR carries the death penalty for murder cases.\nI'll leave the rest to your imagination.\"\"\", None),\n \"game_over_choke\": GameOver(\"\"\"You shoot, and the bullet whizzes past Vladimir, hitting the wall.\nHe easily whips around and chokes you to death with the ferocity of a bear.\"\"\", None),\n \"game_over_gulag\": GameOver(\"\"\"You tried your best, but eventually you gave up.\nYou told Vladimir everything, and a show trial exiles you to a gulag.\nThe rest of your days you spend working in the Siberian cold.\"\"\", None),\n}\n</code></pre>\n\n<p>With this the actual calling code becomes very easy:</p>\n\n<pre><code>if __name__ == \"__main__\":\n print(\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\n print(\"Soviet Union, 1988\")\n current = nodes[\"start\"]\n while current.choices is not None:\n if current.message is not None:\n print(\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\n print(current)\n current = nodes[current.choose()]\n print(current)\n</code></pre>\n\n<p>Note that I used a <a href=\"http://stackoverflow.com/questions/419163/what-does-if-name-main-do\"><code>if __name__ == \"__main__\":</code> guard</a> to allow importing from this script from another script and made your \"You win\" and \"Game over\" strings raw strings (by prepending an <code>r</code>) so that the backslashes don't potentially escape the character after them.</p>\n\n<p>This structure has the advantage that it is very easy to visualize the story as well. Add the following code:</p>\n\n<pre><code>import sys\n\n...\n\nif __name__ == \"__main__\":\n if len(sys.argv) > 1 and sys.argv[1] == \"--graph\":\n print(\"digraph G {\")\n for name, node in nodes.items():\n if node.choices is not None:\n for label, choice in node.choices.items():\n print(f\"{name} -> {choice} [ label={label} ];\")\n print(\"}\")\n else:\n ...\n</code></pre>\n\n<p>And just run this with <code>python3 story_graph.py --graph | dot | display</code> to get this output:</p>\n\n<p><a href=\"https://i.stack.imgur.com/mzyov.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mzyov.png\" alt=\"enter image description here\"></a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T14:16:01.910",
"Id": "217262",
"ParentId": "217164",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "217211",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T00:15:52.193",
"Id": "217164",
"Score": "9",
"Tags": [
"python",
"beginner",
"adventure-game"
],
"Title": "Python - Text Adventure"
} | 217164 |
<p>I created a class to automate some requests for an API. Can I improve this code in any way?</p>
<p>The code itself is very simple and easy to understand.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using RestSharp;
namespace Dummie
{
public class AutoRequest
{
RestClient client;
public CancellationTokenSource Cancel;
string captchaResult = "";
public AutoRequest(int timeout)
{
client = new RestClient("http://127.0.0.1");
client.Timeout = timeout;
client.CookieContainer = new System.Net.CookieContainer();
Cancel = new CancellationTokenSource();
}
private WebProxy ParseProxy(string proxy)
{
try
{
var p = proxy.Split(':');
if (p.Count() > 2)
{
var webproxy = new WebProxy(p[0], Convert.ToInt32(p[1]));
webproxy.Credentials = new NetworkCredential(p[2], p[3]);
return webproxy;
}
else
{
return new WebProxy(p[0], Convert.ToInt32(p[1]));
}
}
catch (Exception)
{
return null;
}
}
public async Task<bool> TestProxy(string proxy)
{
client.Proxy = ParseProxy(proxy);
var request = new RestRequest("http://127.0.0.1", Method.GET);
var response = await client.ExecuteTaskAsync(request, Cancel.Token);
if (response.StatusCode != System.Net.HttpStatusCode.OK)
{
return false;
}
return true;
}
public async Task<bool> CreatCookies(string apiCaptcha)
{
captchaResult = await SolveCaptchaAsync(apiCaptcha);
var request = new RestRequest("http://127.0.0.1", Method.GET);
var response = await client.ExecuteTaskAsync(request, Cancel.Token);
if(response.StatusCode != System.Net.HttpStatusCode.OK)
{
throw new Exception();
}
return true;
}
private async Task<string> SolveCaptchaAsync(string apiCaptcha)
{
TwoCaptcha.Solve solver = new TwoCaptcha.Solve();
var result = await solver.ReCaptchaV2Async(apiCaptcha, "6LeLvl", "http://127.0.0.1");
return result.Request;
}
public async Task<string> SignUp()
{
var request = new RestRequest("http://127.0.0.1/api_test", Method.POST);
request.AddParameter("g-recaptcha-response", captchaResult);
var response = await client.ExecuteTaskAsync(request, Cancel.Token);
if (response.StatusCode != System.Net.HttpStatusCode.OK)
{
return "[ERROR] Failed during request. Status: " + response.StatusDescription;
}
if (response.ResponseUri.ToString() == "http://127.0.0.1/api_test?result=ok")
{
return "[OK] Account Successfully Created";
}
else
{
return "[ERROR] There was an error creating your account. URI: " + response.ResponseUri.ToString();
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T08:47:53.853",
"Id": "420097",
"Score": "5",
"body": "I don't think this code is easy to understand. Could you summarize what it is exactly that it is automating?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T01:01:38.590",
"Id": "420191",
"Score": "0",
"body": "sign up process"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T01:21:57.440",
"Id": "217167",
"Score": "2",
"Tags": [
"c#",
"asynchronous",
"rest",
"client"
],
"Title": "REST API request automation"
} | 217167 |
<p>New to Java, just finished the Helsinki MOOC course. I programmed a basic mortgage calculator as my first solo project and while it works, I have a few questions about coding style:</p>
<ol>
<li><p>The listener and ui classes are cluttered with variables at the top. Is this acceptable or is there a cleaner way of organizing it?</p></li>
<li><p>Is initializing the variables in the <code>CalcLogic</code> class as strings and then creating new <code>BigDecimal</code> variables in the methods an accepted way of using <code>BigDecimal</code>, or would it better to initialize the variables as BigDecimals?</p></li>
<li><p>Are there any other coding style or logic issues that are noticeable?</p></li>
</ol>
<p><code>CalcLogic</code> class:</p>
<pre><code>package mortgagecalculator.logic;
import java.math.BigDecimal;
import java.math.RoundingMode;
/**
* Logic for mortgage calculator.
* Input variables for home value, loan term, etc. and outputs EMI, total payment, etc.
*
*/
public class CalcLogic {
//Variables for calculating mortgage. propTax, homeIns, etc are not initialized in constructor
private String principal = "0";
private String downPayment = "0";
private String interestRate = "0";
private int loanTerm = 0;
private String propTax = "0";
private String homeIns = "0";
private String hoaFee = "0";
private String pmiRate = "0";
public void setPrincipal(String principal) {
this.principal = principal;
}
public void setDownPayment(String downPayment) {
this.downPayment = downPayment;
}
public void setInterest(String interestRate) {
this.interestRate = interestRate;
}
public void setLoanTerm(int loanTerm) {
this.loanTerm = loanTerm;
}
public void setPropTax(String propTax) {
this.propTax = propTax;
}
public void setHomeIns(String homeIns) {
this.homeIns = homeIns;
}
public void setHOAfee(String hoaFee) {
this.hoaFee = hoaFee;
}
public void setPMIrate(String pmiRate) {
this.pmiRate = pmiRate;
}
//Returns principal minus downpayment
public BigDecimal getInitialAmount() {
return new BigDecimal(this.principal).subtract(new BigDecimal(this.downPayment));
}
//Returns twenty percent of principal
public BigDecimal twentyDown() {
BigDecimal twenty = new BigDecimal("20").divide(new BigDecimal("100"));
return new BigDecimal(this.principal).multiply(twenty);
}
public BigDecimal monthlyInterest() {
return new BigDecimal(this.interestRate).divide(new BigDecimal("100"))
.divide(new BigDecimal("12"), 8, RoundingMode.UP);
}
public BigDecimal monthlyPMI() {
try {
BigDecimal result = getInitialAmount().divide(new BigDecimal(this.pmiRate).divide(new BigDecimal("100"))
.divide(new BigDecimal("12")), 2, RoundingMode.UP);
return result;
} catch (Exception e) {
return BigDecimal.ZERO;
}
}
public BigDecimal additionalTax() {
BigDecimal sum = new BigDecimal(this.propTax);
sum = sum.add(new BigDecimal(this.homeIns)).add(new BigDecimal(this.hoaFee));
return sum;
}
public BigDecimal getEMI() {
BigDecimal value = monthlyInterest().add(BigDecimal.ONE);
value = value.pow(this.loanTerm * 12);
BigDecimal numerator = value.multiply(monthlyInterest()).multiply(getInitialAmount());
BigDecimal denominator = value.subtract(BigDecimal.ONE);
return numerator.divide(denominator, 2, RoundingMode.UP);
}
public BigDecimal monthlyPayment() {
BigDecimal result = getEMI().add(monthlyPMI()).add(additionalTax());
return result;
}
public BigDecimal totalInterest() {
BigDecimal result = getEMI().multiply(new BigDecimal(this.loanTerm * 12));
result = result.subtract(getInitialAmount());
return result;
}
//Returns month where principal payments first exceed interest payments
public int amortMonth() {
BigDecimal remaining = getInitialAmount().setScale(2, RoundingMode.CEILING);
for (int i = 0; i < this.loanTerm * 12; i++) {
BigDecimal interPay = remaining.multiply(monthlyInterest()).setScale(2, RoundingMode.CEILING);
BigDecimal princPay = getEMI().subtract(interPay).setScale(2, RoundingMode.CEILING);
if (princPay.compareTo(interPay) == 1) {
return i + 1;
}
remaining = remaining.subtract(princPay).setScale(2, RoundingMode.CEILING);
}
return 0;
}
}
</code></pre>
<p><code>CalcListener</code> class:</p>
<pre><code>package mortgagecalculator.ui;
import mortgagecalculator.logic.CalcLogic;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.math.BigDecimal;
public class CalcListener implements ActionListener {
private JTextField principal;
private JTextField downPayment;
private JTextField interestRate;
private JTextField loanTerm;
private JTextField propTax;
private JTextField homeIns;
private JTextField hoaFee;
private JTextField pmiRate;
private JButton button;
private JTextField EMI;
private JTextField monthlyFee;
private JTextField totalInt;
private JTextField changeMonth;
private CalcLogic calc;
public CalcListener(JTextField principal, JTextField downPayment, JTextField interestRate,
JTextField loanTerm, JTextField propTax, JTextField homeIns,
JTextField hoaFee, JTextField pmiRate, JTextField EMI,
JTextField monthlyFee, JTextField totalInt, JTextField changeMonth, JButton button) {
this.principal = principal;
this.downPayment = downPayment;
this.interestRate = interestRate;
this.loanTerm = loanTerm;
this.propTax = propTax;
this.homeIns = homeIns;
this.hoaFee = hoaFee;
this.pmiRate = pmiRate;
this.button = button;
this.EMI = EMI;
this.monthlyFee = monthlyFee;
this.totalInt = totalInt;
this.changeMonth = changeMonth;
this.calc = new CalcLogic();
}
@Override
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == this.button) {
this.calc.setPrincipal(this.principal.getText());
this.calc.setDownPayment(this.downPayment.getText());
this.calc.setInterest(this.interestRate.getText());
this.calc.setLoanTerm(Integer.parseInt(this.loanTerm.getText()));
this.calc.setPropTax(this.propTax.getText());
this.calc.setHomeIns(this.homeIns.getText());
this.calc.setPMIrate(this.pmiRate.getText());
this.calc.setHOAfee(this.hoaFee.getText());
this.EMI.setText(this.calc.getEMI().toString());
this.monthlyFee.setText(this.calc.monthlyPayment().toString());
this.totalInt.setText(this.calc.totalInterest().toString());
this.changeMonth.setText(String.valueOf(this.calc.amortMonth()));
}
}
}
</code></pre>
<p><code>UserInterface</code> class:</p>
<pre><code>package mortgagecalculator.ui;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.*;
import mortgagecalculator.ui.CalcListener;
public class UserInterface implements Runnable {
private JFrame frame;
private JTextField principal;
private JTextField downPayment;
private JTextField interestRate;
private JTextField loanTerm;
private JTextField propTax;
private JTextField homeIns;
private JTextField hoaFee;
private JTextField pmiRate;
private JButton button;
private JTextField EMI;
private JTextField monthlyFee;
private JTextField totalInt;
private JTextField changeMonth;
@Override
public void run() {
frame = new JFrame("Mortgage Calculator");
frame.setPreferredSize(new Dimension(1000, 1000));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
createComponents(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
private void createComponents(Container container) {
generateVariables();
container.setLayout(new GridLayout(3, 1));
container.add(createInputPanel());
container.add(this.button);
container.add(createOutputPanel());
}
private void generateVariables() {
this.principal = new JTextField("");
this.downPayment = new JTextField("");
this.interestRate = new JTextField("");
this.loanTerm = new JTextField("");
this.propTax = new JTextField("");
this.homeIns = new JTextField("");
this.hoaFee = new JTextField("");
this.pmiRate = new JTextField("");
this.EMI = new JTextField("");
this.monthlyFee = new JTextField("");
this.totalInt = new JTextField("");
this.changeMonth = new JTextField("");
this.button = new JButton("Calculate!");
CalcListener calc = new CalcListener(this.principal, this.downPayment, this.interestRate,
this.loanTerm, this.propTax, this.homeIns, this.hoaFee,
this.pmiRate, this.EMI, this.monthlyFee, this.totalInt,
this.changeMonth, this.button);
this.button.addActionListener(calc);
}
private JPanel createInputPanel() {
JPanel panel = new JPanel(new GridLayout(4, 4));
panel.add(new JLabel("Principal"));
panel.add(new JLabel("Down Payment"));
panel.add(new JLabel("Interest Rate (in %)"));
panel.add(new JLabel("Loan term (in years)"));
panel.add(this.principal);
panel.add(this.downPayment);
panel.add(this.interestRate);
panel.add(this.loanTerm);
panel.add(new JLabel("Property Tax (Monthly)"));
panel.add(new JLabel("Home Insurance (Monthly)"));
panel.add(new JLabel("HOA Fees (Monthly)"));
panel.add(new JLabel("PMI Rate (in %)"));
panel.add(this.propTax);
panel.add(this.homeIns);
panel.add(this.hoaFee);
panel.add(this.pmiRate);
return panel;
}
private JPanel createOutputPanel() {
JPanel panel = new JPanel(new GridLayout(4, 2));
panel.add(new JLabel("Equated Monthly Installment"));
panel.add(new JLabel("Monthly w/ fees"));
panel.add(this.EMI);
panel.add(this.monthlyFee);
panel.add(new JLabel("Total Interest Payments"));
panel.add(new JLabel("Month where principal payments > interest"));
panel.add(this.totalInt);
panel.add(this.changeMonth);
return panel;
}
public JFrame getFrame() {
return frame;
}
}
</code></pre>
| [] | [
{
"body": "<p><code>CalcLogic</code> should only deal with <code>BigDecimal</code> values; not <code>String</code> values.</p>\n\n<p>Consider the symmetry of input and output:</p>\n\n<pre><code>class CalcLogic {\n public void setPrinciple(String principle) { ... }\n public BigDecimal getInitialAmount() { ... }\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>class CalcLogic {\n public void setPrinciple(BigDecimal principle) { ... }\n public BigDecimal getInitialAmount() { ... }\n}\n</code></pre>\n\n<p>Why would you <code>setXxxx()</code> a <code>String</code> value and <code>getXxxx()</code> a <code>BigDecimal</code>? This class deals with numbers, specifically money. Money values go in; money values come out.</p>\n\n<hr>\n\n<p>Along that vein, you should write the member functions following the Java Bean standard. Instead of <code>monthlyInterest()</code>, you should name the method <code>getMonthlyInterest()</code>.</p>\n\n<hr>\n\n<p>The <code>CalcListener</code> class is breaking encapsulation. It requires exactly the same fields as a the <code>UserInterface</code> class, and all those fields have to be passed in the constructor. If you add a field, you have to add code in many places to ensure the class definitions are kept in sync.</p>\n\n<p>Instead, <code>CalcListener</code> could be an inner class.</p>\n\n<pre><code>public class UserInterface implements Runnable {\n\n private JTextField principal;\n // ... etc ...\n\n class CalcListener implements ActionListener {\n\n private final CalcLogic calc = new CalcLogic();\n\n @Override\n public void actionPerformed(ActionEvent ae) {\n calc.setPrinciple(new BigDecimal(principle.getText()));\n // ... etc ...\n }\n }\n\n private void generateVariables() {\n // ... etc ...\n button.addActionListener(new CalcListener());\n }\n\n // ... etc ...\n}\n</code></pre>\n\n<p>As an inner class, <code>CalcListener</code> has access to all the <code>private</code> members of <code>UserInterface</code>, so there is no need to pass them all in a call to the <code>CalcListener()</code> constructor.</p>\n\n<p>It is still breaking encapsulation, albeit in a different way - one which requires a lot less code.</p>\n\n<hr>\n\n<p>Instead of using <code>JTextField</code>, you probably want to use <a href=\"https://docs.oracle.com/en/java/javase/12/docs/api/java.desktop/javax/swing/JFormattedTextField.html\" rel=\"nofollow noreferrer\"><code>JFormattedTextField</code></a>.</p>\n\n<p>The <code>JFormattedTextField</code> can perform the work of converting between the display format, a <code>String</code>, and the model object, in this case a <code>BigDecimal</code>.</p>\n\n<p>Use a helper function to create the <code>JFormattedTextField</code>, to set it up properly.</p>\n\n<pre><code>private static JFormattedTextField bigDecimalField(String initialValue, String format) {\n BigDecimal value = new BigDecimal(initialValue);\n JFormattedTextField tf = new JFormattedTextField(value);\n DefaultFormatter fmt = new NumberFormatter(new DecimalFormat(format));\n fmt.setValueClass(value.getClass());\n DefaultFormatterFactory factory = new DefaultFormatterFactory(fmt, fmt, fmt);\n tf.setFormatterFactory(factory);\n\n return tf;\n}\n</code></pre>\n\n<p>Create the fields like:</p>\n\n<pre><code>private final JFormattedTextField principle = bigDecimalField(\"0.00\", \"#.00\");\n// ...etc..\n</code></pre>\n\n<p>And reference the values like:</p>\n\n<pre><code> @Override\n public void actionPerformed(ActionEvent ae) {\n calc.setPrinciple((BigDecimal) principle.getValue());\n // ... etc ...\n }\n</code></pre>\n\n<p>Notice, you are no longer retrieving a text string from the field, but the actual model object ... a <code>BigDecimal</code>.</p>\n\n<p>Of course, you can do better by declaring your own <code>BigDecimalField</code> class, which returns the correctly cast return value, so the caller doesn't have to cast all the time.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T05:05:44.167",
"Id": "217178",
"ParentId": "217168",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "217178",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T01:23:29.127",
"Id": "217168",
"Score": "3",
"Tags": [
"java",
"beginner",
"calculator",
"swing",
"finance"
],
"Title": "Mortgage calculator with Swing for Helsinki MOOC"
} | 217168 |
<p>I'm new to C language and never got my self into the details of UTF-8, and after reading <a href="https://www.cprogramming.com/tutorial/unicode.html" rel="noreferrer">some articles</a> about it, I wanted to try and play with UTF-8 with C language for both fun and practicing purposes. This is a little C library that is supposed to validates UTF-8 strings, counts chars, guesses the language of the string based on the Unicode code points blocks. </p>
<ul>
<li><p>What do you think about it ? </p></li>
<li><p>this is my first time to design a C library, what do you think of it as a <em>library</em>?</p></li>
<li>also what do you think about the way I organized the source files/protected the code/exposed the code (the design of the software) ?</li>
</ul>
<p>Thank you very much</p>
<p>The source code consists of 3 files</p>
<h2>libmyutf8.c</h2>
<p>This is the entire code of the library</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include "headerAll.h"
unsigned long buildCodePoint(unsigned char byte1,
unsigned char byte2,
unsigned char byte3,
unsigned char byte4,
int numberOfBytes );
int increseCodeBlock( unsigned long codePoint,
int codeBlocksCount,
struct codePointBlock *codePointBlocks);
//macros
//https://stackoverflow.com/questions/523724/c-c-check-if-one-bit-is-set-in-i-e-int-variable
#define CHECK_BIT(var,pos) ((var) & (1<<(pos)) )
unsigned long scanUTF8(char *str, struct codePointBlock *codePointBlocks)
{
int i = 0;
unsigned long maxLength = 10485760; // 10MB
unsigned char currentByte;
unsigned char byte1 = 0, byte2 = 0, byte3 = 0, byte4 = 0;
int firstByte = 1;
int charBytesRemaining = 0;
unsigned long codePoint = 0;
int numberOfBytes = 0;
int codeBlocksCount = 0;
int charsFound = 0;
while(codePointBlocks[codeBlocksCount].blockName) codeBlocksCount++;
do {
currentByte = *(str + i);
//printf("iiiiiiiiiiiiiii%d\n", i);
//printf("curentByteee%d\n", currentByte);
if(currentByte == 0) break;//end of string
if (firstByte) {
firstByte = 0;
//lastCodePoint is ready
byte1 = currentByte;
if ( !(CHECK_BIT(currentByte, 7)) ){
// if 0XXXXXXX
firstByte = 1;
numberOfBytes = 1;
charBytesRemaining = 0;
codePoint = buildCodePoint(byte1, 0, 0, 0, numberOfBytes);
increseCodeBlock(codePoint, codeBlocksCount, codePointBlocks);
charsFound++;
} else if (CHECK_BIT(currentByte, 7) && CHECK_BIT(currentByte, 6) &&
!CHECK_BIT(currentByte, 5)
){
// if 110XXXXX
charBytesRemaining = 1;
numberOfBytes = 2;
} else if (CHECK_BIT(currentByte, 7) && CHECK_BIT(currentByte, 6) &&
CHECK_BIT(currentByte, 5) && !CHECK_BIT(currentByte, 4)
){
// if 1110XXXX
charBytesRemaining = 2;
numberOfBytes = 3;
} else if (CHECK_BIT(currentByte, 7) && CHECK_BIT(currentByte, 6) &&
CHECK_BIT(currentByte, 5) && CHECK_BIT(currentByte, 4) &&
!CHECK_BIT(currentByte, 3)
){
// if 11110XXX
charBytesRemaining = 3;
numberOfBytes = 4;
} else {
//not utf-8
return -1;
}
} else {
//not first byte in char
if (CHECK_BIT(currentByte, 7) && !CHECK_BIT(currentByte, 6)){
//must be 10XXXXXX
// byte1 byte2 byte3 byte4
if (charBytesRemaining == 3){
byte2 = currentByte;
} else if(charBytesRemaining == 2){
if (numberOfBytes == 4){
byte3 = currentByte;
} else if (numberOfBytes == 3){
byte2 = currentByte;
}
} else if (charBytesRemaining == 1){
if (numberOfBytes == 4){
byte4 = currentByte;
} else if (numberOfBytes == 3){
byte3 = currentByte;
} else if (numberOfBytes == 2){
byte2 = currentByte;
}
}
charBytesRemaining--;
if (charBytesRemaining == 0){
//end of char (last byte)
firstByte = 1;
/*
// uncomment for debugging
printf("codePointCalled\n");
printf("byte1:%d\n", byte1);
printf("byte2:%d\n", byte2);
printf("byte3:%d\n", byte3);
printf("byte4:%d\n", byte4);
printf("numberOfBytes:%d\n", numberOfBytes);
*/
codePoint = buildCodePoint(byte1, byte2, byte3, byte4, numberOfBytes);
increseCodeBlock(codePoint, codeBlocksCount, codePointBlocks);
byte1 = byte2 = byte3 = byte4 = numberOfBytes = 0;
charsFound++;
}
}else{
//not utf-8
return -1;
}
}
i++;
} while (i < maxLength);
return charsFound;
}
int increseCodeBlock( unsigned long codePoint,
int codeBlocksCount,
struct codePointBlock *codePointBlocks)
{
for(int i = 0; i < codeBlocksCount; i++){
if(codePoint >= codePointBlocks[i].start && codePoint <= codePointBlocks[i].end){
codePointBlocks[i].count++;
return 1;
}
}
return 0;
}
unsigned long buildCodePoint(unsigned char byte1,
unsigned char byte2,
unsigned char byte3,
unsigned char byte4,
int numberOfBytes )
{
// codePoint = (Byte1) | (Byte2) | (Byte3) | (Byte4)
if(numberOfBytes == 1){
byte2 = 0;
byte3 = 0;
byte4 = 0;
}else if(numberOfBytes == 2){
byte1 &= 0b00011111;
byte2 &= 0b00111111;
byte3 = 0;
byte4 = 0;
}else if(numberOfBytes == 3){
byte1 &= 0b00001111;
byte2 &= 0b00111111;
byte3 &= 0b00111111;
byte4 = 0;
}else if(numberOfBytes == 4){
byte1 &= 0b00000111;
byte2 &= 0b00111111;
byte3 &= 0b00111111;
byte4 &= 0b00111111;
}else {
perror("buildCodePoint number of bytes is not riht");
return 0;
}
if(numberOfBytes == 1) return (unsigned long) byte1;
unsigned long byte1L = (unsigned long) byte1;
unsigned long byte2L = (unsigned long) byte2;
unsigned long byte3L = (unsigned long) byte3;
unsigned long byte4L = (unsigned long) byte4;
int missedBits = (4 - numberOfBytes) * 8;// 0 4
// 1(8) 3
// 2(16) 2
// codePoint = (Byte1) | (Byte2) | (Byte3) | (Byte4)
//
unsigned long codePoint = byte4L |
(byte3L << (8 - (missedBits + 2 * (numberOfBytes - 3) ) ) )|
(byte2L << (16 - (missedBits + 2 * (numberOfBytes - 2) )) ) |
(byte1L << (24 - (missedBits + 2 * (numberOfBytes - 1) )));
return codePoint;
}
//code blocks extracted from https://www.utf8-chartable.de/unicode-utf8-table.pl
struct codePointBlock codePointBlocks[] = {
//281 blocks
{0x0000, 0x007F, "Basic Latin",0},
{0x0080, 0x00FF, "Latin-1 Supplement",0},
{0x0100, 0x017F, "Latin Extended-A",0},
{0x0180, 0x024F, "Latin Extended-B",0},
{0x0250, 0x02AF, "IPA Extensions",0},
{0x02B0, 0x02FF, "Spacing Modifier Letters",0},
{0x0300, 0x036F, "Combining Diacritical Marks",0},
{0x0370, 0x03FF, "Greek and Coptic",0},
{0x0400, 0x04FF, "Cyrillic",0},
{0x0500, 0x052F, "Cyrillic Supplement",0},
{0x0530, 0x058F, "Armenian",0},
{0x0590, 0x05FF, "Hebrew",0},
{0x0600, 0x06FF, "Arabic",0},
{0x0700, 0x074F, "Syriac",0},
{0x0750, 0x077F, "Arabic Supplement",0},
{0x0780, 0x07BF, "Thaana",0},
{0x07C0, 0x07FF, "NKo",0},
{0x0800, 0x083F, "Samaritan",0},
{0x0840, 0x085F, "Mandaic",0},
{0x0860, 0x086F, "Syriac Supplement",0},
{0x08A0, 0x08FF, "Arabic Extended-A",0},
{0x0900, 0x097F, "Devanagari",0},
{0x0980, 0x09FF, "Bengali",0},
{0x0A00, 0x0A7F, "Gurmukhi",0},
{0x0A80, 0x0AFF, "Gujarati",0},
{0x0B00, 0x0B7F, "Oriya",0},
{0x0B80, 0x0BFF, "Tamil",0},
{0x0C00, 0x0C7F, "Telugu",0},
{0x0C80, 0x0CFF, "Kannada",0},
{0x0D00, 0x0D7F, "Malayalam",0},
{0x0D80, 0x0DFF, "Sinhala",0},
{0x0E00, 0x0E7F, "Thai",0},
{0x0E80, 0x0EFF, "Lao",0},
{0x0F00, 0x0FFF, "Tibetan",0},
{0x1000, 0x109F, "Myanmar",0},
{0x10A0, 0x10FF, "Georgian",0},
{0x1100, 0x11FF, "Hangul Jamo",0},
{0x1200, 0x137F, "Ethiopic",0},
{0x1380, 0x139F, "Ethiopic Supplement",0},
{0x13A0, 0x13FF, "Cherokee",0},
{0x1400, 0x167F, "Unified Canadian Aboriginal Syllabics",0},
{0x1680, 0x169F, "Ogham",0},
{0x16A0, 0x16FF, "Runic",0},
{0x1700, 0x171F, "Tagalog",0},
{0x1720, 0x173F, "Hanunoo",0},
{0x1740, 0x175F, "Buhid",0},
{0x1760, 0x177F, "Tagbanwa",0},
{0x1780, 0x17FF, "Khmer",0},
{0x1800, 0x18AF, "Mongolian",0},
{0x18B0, 0x18FF, "Unified Canadian Aboriginal Syllabics Extended",0},
{0x1900, 0x194F, "Limbu",0},
{0x1950, 0x197F, "Tai Le",0},
{0x1980, 0x19DF, "New Tai Lue",0},
{0x19E0, 0x19FF, "Khmer Symbols",0},
{0x1A00, 0x1A1F, "Buginese",0},
{0x1A20, 0x1AAF, "Tai Tham",0},
{0x1AB0, 0x1AFF, "Combining Diacritical Marks Extended",0},
{0x1B00, 0x1B7F, "Balinese",0},
{0x1B80, 0x1BBF, "Sundanese",0},
{0x1BC0, 0x1BFF, "Batak",0},
{0x1C00, 0x1C4F, "Lepcha",0},
{0x1C50, 0x1C7F, "Ol Chiki",0},
{0x1C80, 0x1C8F, "Cyrillic Extended-C",0},
{0x1CC0, 0x1CCF, "Sundanese Supplement",0},
{0x1CD0, 0x1CFF, "Vedic Extensions",0},
{0x1D00, 0x1D7F, "Phonetic Extensions",0},
{0x1D80, 0x1DBF, "Phonetic Extensions Supplement",0},
{0x1DC0, 0x1DFF, "Combining Diacritical Marks Supplement",0},
{0x1E00, 0x1EFF, "Latin Extended Additional",0},
{0x1F00, 0x1FFF, "Greek Extended",0},
{0x2000, 0x206F, "General Punctuation",0},
{0x2070, 0x209F, "Superscripts and Subscripts",0},
{0x20A0, 0x20CF, "Currency Symbols",0},
{0x20D0, 0x20FF, "Combining Diacritical Marks for Symbols",0},
{0x2100, 0x214F, "Letterlike Symbols",0},
{0x2150, 0x218F, "Number Forms",0},
{0x2190, 0x21FF, "Arrows",0},
{0x2200, 0x22FF, "Mathematical Operators",0},
{0x2300, 0x23FF, "Miscellaneous Technical",0},
{0x2400, 0x243F, "Control Pictures",0},
{0x2440, 0x245F, "Optical Character Recognition",0},
{0x2460, 0x24FF, "Enclosed Alphanumerics",0},
{0x2500, 0x257F, "Box Drawing",0},
{0x2580, 0x259F, "Block Elements",0},
{0x25A0, 0x25FF, "Geometric Shapes",0},
{0x2600, 0x26FF, "Miscellaneous Symbols",0},
{0x2700, 0x27BF, "Dingbats",0},
{0x27C0, 0x27EF, "Miscellaneous Mathematical Symbols-A",0},
{0x27F0, 0x27FF, "Supplemental Arrows-A",0},
{0x2800, 0x28FF, "Braille Patterns",0},
{0x2900, 0x297F, "Supplemental Arrows-B",0},
{0x2980, 0x29FF, "Miscellaneous Mathematical Symbols-B",0},
{0x2A00, 0x2AFF, "Supplemental Mathematical Operators",0},
{0x2B00, 0x2BFF, "Miscellaneous Symbols and Arrows",0},
{0x2C00, 0x2C5F, "Glagolitic",0},
{0x2C60, 0x2C7F, "Latin Extended-C",0},
{0x2C80, 0x2CFF, "Coptic",0},
{0x2D00, 0x2D2F, "Georgian Supplement",0},
{0x2D30, 0x2D7F, "Tifinagh",0},
{0x2D80, 0x2DDF, "Ethiopic Extended",0},
{0x2DE0, 0x2DFF, "Cyrillic Extended-A",0},
{0x2E00, 0x2E7F, "Supplemental Punctuation",0},
{0x2E80, 0x2EFF, "CJK Radicals Supplement",0},
{0x2F00, 0x2FDF, "Kangxi Radicals",0},
{0x2FF0, 0x2FFF, "Ideographic Description Characters",0},
{0x3000, 0x303F, "CJK Symbols and Punctuation",0},
{0x3040, 0x309F, "Hiragana",0},
{0x30A0, 0x30FF, "Katakana",0},
{0x3100, 0x312F, "Bopomofo",0},
{0x3130, 0x318F, "Hangul Compatibility Jamo",0},
{0x3190, 0x319F, "Kanbun",0},
{0x31A0, 0x31BF, "Bopomofo Extended",0},
{0x31C0, 0x31EF, "CJK Strokes",0},
{0x31F0, 0x31FF, "Katakana Phonetic Extensions",0},
{0x3200, 0x32FF, "Enclosed CJK Letters and Months",0},
{0x3300, 0x33FF, "CJK Compatibility",0},
{0x3400, 0x4DBF, "CJK Unified Ideographs Extension A",0},
{0x4DC0, 0x4DFF, "Yijing Hexagram Symbols",0},
{0x4E00, 0x9FFF, "CJK Unified Ideographs",0},
{0xA000, 0xA48F, "Yi Syllables",0},
{0xA490, 0xA4CF, "Yi Radicals",0},
{0xA4D0, 0xA4FF, "Lisu",0},
{0xA500, 0xA63F, "Vai",0},
{0xA640, 0xA69F, "Cyrillic Extended-B",0},
{0xA6A0, 0xA6FF, "Bamum",0},
{0xA700, 0xA71F, "Modifier Tone Letters",0},
{0xA720, 0xA7FF, "Latin Extended-D",0},
{0xA800, 0xA82F, "Syloti Nagri",0},
{0xA830, 0xA83F, "Common Indic Number Forms",0},
{0xA840, 0xA87F, "Phags-pa",0},
{0xA880, 0xA8DF, "Saurashtra",0},
{0xA8E0, 0xA8FF, "Devanagari Extended",0},
{0xA900, 0xA92F, "Kayah Li",0},
{0xA930, 0xA95F, "Rejang",0},
{0xA960, 0xA97F, "Hangul Jamo Extended-A",0},
{0xA980, 0xA9DF, "Javanese",0},
{0xA9E0, 0xA9FF, "Myanmar Extended-B",0},
{0xAA00, 0xAA5F, "Cham",0},
{0xAA60, 0xAA7F, "Myanmar Extended-A",0},
{0xAA80, 0xAADF, "Tai Viet",0},
{0xAAE0, 0xAAFF, "Meetei Mayek Extensions",0},
{0xAB00, 0xAB2F, "Ethiopic Extended-A",0},
{0xAB30, 0xAB6F, "Latin Extended-E",0},
{0xAB70, 0xABBF, "Cherokee Supplement",0},
{0xABC0, 0xABFF, "Meetei Mayek",0},
{0xAC00, 0xD7AF, "Hangul Syllables",0},
{0xD7B0, 0xD7FF, "Hangul Jamo Extended-B",0},
{0xD800, 0xDB7F, "High Surrogates",0},
{0xDB80, 0xDBFF, "High Private Use Surrogates",0},
{0xDC00, 0xDFFF, "Low Surrogates",0},
{0xE000, 0xF8FF, "Private Use Area",0},
{0xF900, 0xFAFF, "CJK Compatibility Ideographs",0},
{0xFB00, 0xFB4F, "Alphabetic Presentation Forms",0},
{0xFB50, 0xFDFF, "Arabic Presentation Forms-A",0},
{0xFE00, 0xFE0F, "Variation Selectors",0},
{0xFE10, 0xFE1F, "Vertical Forms",0},
{0xFE20, 0xFE2F, "Combining Half Marks",0},
{0xFE30, 0xFE4F, "CJK Compatibility Forms",0},
{0xFE50, 0xFE6F, "Small Form Variants",0},
{0xFE70, 0xFEFF, "Arabic Presentation Forms-B",0},
{0xFF00, 0xFFEF, "Halfwidth and Fullwidth Forms",0},
{0xFFF0, 0xFFFF, "Specials",0},
{0x10000, 0x1007F, "Linear B Syllabary",0},
{0x10080, 0x100FF, "Linear B Ideograms",0},
{0x10100, 0x1013F, "Aegean Numbers",0},
{0x10140, 0x1018F, "Ancient Greek Numbers",0},
{0x10190, 0x101CF, "Ancient Symbols",0},
{0x101D0, 0x101FF, "Phaistos Disc",0},
{0x10280, 0x1029F, "Lycian",0},
{0x102A0, 0x102DF, "Carian",0},
{0x102E0, 0x102FF, "Coptic Epact Numbers",0},
{0x10300, 0x1032F, "Old Italic",0},
{0x10330, 0x1034F, "Gothic",0},
{0x10350, 0x1037F, "Old Permic",0},
{0x10380, 0x1039F, "Ugaritic",0},
{0x103A0, 0x103DF, "Old Persian",0},
{0x10400, 0x1044F, "Deseret",0},
{0x10450, 0x1047F, "Shavian",0},
{0x10480, 0x104AF, "Osmanya",0},
{0x104B0, 0x104FF, "Osage",0},
{0x10500, 0x1052F, "Elbasan",0},
{0x10530, 0x1056F, "Caucasian Albanian",0},
{0x10600, 0x1077F, "Linear A",0},
{0x10800, 0x1083F, "Cypriot Syllabary",0},
{0x10840, 0x1085F, "Imperial Aramaic",0},
{0x10860, 0x1087F, "Palmyrene",0},
{0x10880, 0x108AF, "Nabataean",0},
{0x108E0, 0x108FF, "Hatran",0},
{0x10900, 0x1091F, "Phoenician",0},
{0x10920, 0x1093F, "Lydian",0},
{0x10980, 0x1099F, "Meroitic Hieroglyphs",0},
{0x109A0, 0x109FF, "Meroitic Cursive",0},
{0x10A00, 0x10A5F, "Kharoshthi",0},
{0x10A60, 0x10A7F, "Old South Arabian",0},
{0x10A80, 0x10A9F, "Old North Arabian",0},
{0x10AC0, 0x10AFF, "Manichaean",0},
{0x10B00, 0x10B3F, "Avestan",0},
{0x10B40, 0x10B5F, "Inscriptional Parthian",0},
{0x10B60, 0x10B7F, "Inscriptional Pahlavi",0},
{0x10B80, 0x10BAF, "Psalter Pahlavi",0},
{0x10C00, 0x10C4F, "Old Turkic",0},
{0x10C80, 0x10CFF, "Old Hungarian",0},
{0x10E60, 0x10E7F, "Rumi Numeral Symbols",0},
{0x11000, 0x1107F, "Brahmi",0},
{0x11080, 0x110CF, "Kaithi",0},
{0x110D0, 0x110FF, "Sora Sompeng",0},
{0x11100, 0x1114F, "Chakma",0},
{0x11150, 0x1117F, "Mahajani",0},
{0x11180, 0x111DF, "Sharada",0},
{0x111E0, 0x111FF, "Sinhala Archaic Numbers",0},
{0x11200, 0x1124F, "Khojki",0},
{0x11280, 0x112AF, "Multani",0},
{0x112B0, 0x112FF, "Khudawadi",0},
{0x11300, 0x1137F, "Grantha",0},
{0x11400, 0x1147F, "Newa",0},
{0x11480, 0x114DF, "Tirhuta",0},
{0x11580, 0x115FF, "Siddham",0},
{0x11600, 0x1165F, "Modi",0},
{0x11660, 0x1167F, "Mongolian Supplement",0},
{0x11680, 0x116CF, "Takri",0},
{0x11700, 0x1173F, "Ahom",0},
{0x118A0, 0x118FF, "Warang Citi",0},
{0x11A00, 0x11A4F, "Zanabazar Square",0},
{0x11A50, 0x11AAF, "Soyombo",0},
{0x11AC0, 0x11AFF, "Pau Cin Hau",0},
{0x11C00, 0x11C6F, "Bhaiksuki",0},
{0x11C70, 0x11CBF, "Marchen",0},
{0x11D00, 0x11D5F, "Masaram Gondi",0},
{0x12000, 0x123FF, "Cuneiform",0},
{0x12400, 0x1247F, "Cuneiform Numbers and Punctuation",0},
{0x12480, 0x1254F, "Early Dynastic Cuneiform",0},
{0x13000, 0x1342F, "Egyptian Hieroglyphs",0},
{0x14400, 0x1467F, "Anatolian Hieroglyphs",0},
{0x16800, 0x16A3F, "Bamum Supplement",0},
{0x16A40, 0x16A6F, "Mro",0},
{0x16AD0, 0x16AFF, "Bassa Vah",0},
{0x16B00, 0x16B8F, "Pahawh Hmong",0},
{0x16F00, 0x16F9F, "Miao",0},
{0x16FE0, 0x16FFF, "Ideographic Symbols and Punctuation",0},
{0x17000, 0x187FF, "Tangut",0},
{0x18800, 0x18AFF, "Tangut Components",0},
{0x1B000, 0x1B0FF, "Kana Supplement",0},
{0x1B100, 0x1B12F, "Kana Extended-A",0},
{0x1B170, 0x1B2FF, "Nushu",0},
{0x1BC00, 0x1BC9F, "Duployan",0},
{0x1BCA0, 0x1BCAF, "Shorthand Format Controls",0},
{0x1D000, 0x1D0FF, "Byzantine Musical Symbols",0},
{0x1D100, 0x1D1FF, "Musical Symbols",0},
{0x1D200, 0x1D24F, "Ancient Greek Musical Notation",0},
{0x1D300, 0x1D35F, "Tai Xuan Jing Symbols",0},
{0x1D360, 0x1D37F, "Counting Rod Numerals",0},
{0x1D400, 0x1D7FF, "Mathematical Alphanumeric Symbols",0},
{0x1D800, 0x1DAAF, "Sutton SignWriting",0},
{0x1E000, 0x1E02F, "Glagolitic Supplement",0},
{0x1E800, 0x1E8DF, "Mende Kikakui",0},
{0x1E900, 0x1E95F, "Adlam",0},
{0x1EE00, 0x1EEFF, "Arabic Mathematical Alphabetic Symbols",0},
{0x1F000, 0x1F02F, "Mahjong Tiles",0},
{0x1F030, 0x1F09F, "Domino Tiles",0},
{0x1F0A0, 0x1F0FF, "Playing Cards",0},
{0x1F100, 0x1F1FF, "Enclosed Alphanumeric Supplement",0},
{0x1F200, 0x1F2FF, "Enclosed Ideographic Supplement",0},
{0x1F300, 0x1F5FF, "Miscellaneous Symbols and Pictographs",0},
{0x1F600, 0x1F64F, "Emoticons",0},
{0x1F650, 0x1F67F, "Ornamental Dingbats",0},
{0x1F680, 0x1F6FF, "Transport and Map Symbols",0},
{0x1F700, 0x1F77F, "Alchemical Symbols",0},
{0x1F780, 0x1F7FF, "Geometric Shapes Extended",0},
{0x1F800, 0x1F8FF, "Supplemental Arrows-C",0},
{0x1F900, 0x1F9FF, "Supplemental Symbols and Pictographs",0},
{0x20000, 0x2A6DF, "CJK Unified Ideographs Extension B",0},
{0x2A700, 0x2B73F, "CJK Unified Ideographs Extension C",0},
{0x2B740, 0x2B81F, "CJK Unified Ideographs Extension D",0},
{0x2B820, 0x2CEAF, "CJK Unified Ideographs Extension E",0},
{0x2CEB0, 0x2EBEF, "CJK Unified Ideographs Extension F",0},
{0x2F800, 0x2FA1F, "CJK Compatibility Ideographs Supplement",0},
{0xE0000, 0xE007F, "Tags",0},
{0xE0100, 0xE01EF, "Variation Selectors Supplement",0},
{0xF0000, 0xFFFFF, "Supplementary Private Use Area-A",0},
{0x100000, 0x10FFFF, "Supplementary Private Use Area-B",0},
{0, 0xFFFFFF, "Unknown",0},
{0,0,NULL,0}
};
</code></pre>
<h2>libmyutf8.h</h2>
<p>This is only what the library user is going to include (the library interface) . Only one function </p>
<pre><code>#ifndef HEADER_MYLIB
#define HEADER_MYLIB
#include "headerAll.h"
extern unsigned long scanUTF8(char *str, struct codePointBlock *codePointBlocks );
extern struct codePointBlock codePointBlocks;
#endif
</code></pre>
<h2>headerAll.h</h2>
<p>This header file will contain definitions needed for both the library files, and the files of the user</p>
<pre><code>#ifndef HEADER_ALL
#define HEADER_ALL
struct codePointBlock{
int start;
int end;
char *blockName;
int count;
};
#endif
</code></pre>
<h2>Testing</h2>
<p>This is the user files </p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include "libmyutf8.h" // < the library
int main( int argc, char *argv[])
{
FILE* pFile;
char *buffer = 0;
pFile = fopen(argv[1], "rb");
if(pFile == NULL) return 1;
fseek (pFile, 0, SEEK_END);
long length = ftell (pFile);
fseek (pFile, 0, SEEK_SET);
buffer = malloc (length + 1);
if (buffer) fread (buffer, 1, length, pFile);
fclose (pFile);
buffer[length] = '\0';
struct codePointBlock *cpbPointer = &codePointBlocks;
int charsCount = scanUTF8(buffer, cpbPointer);
int i = 0;
while(cpbPointer[i].blockName){
if(cpbPointer[i].count) printf("%s: %d\n", cpbPointer[i].blockName, cpbPointer[i].count);
i++;
}
printf("chars count:%d\n", charsCount);
return 0;
}
</code></pre>
<p>I tested it like this</p>
<pre><code>./libmyutf8 "utf8testingfile.txt"
</code></pre>
<p>And the program output was like this</p>
<pre><code>Basic Latin: 49
Latin-1 Supplement: 18
Latin Extended-B: 9
Armenian: 9
Hebrew: 9
Arabic: 72
Enclosed Alphanumerics: 9
Old Persian: 9
chars count:184
</code></pre>
| [] | [
{
"body": "<p><code>libmyutf8.c</code> should be including <code>\"libmyutf8.h\"</code> rather than <code>\"headerAll.h\"</code> - that ensures that the function definitions are consistent with the header's prototypes. With that change, there's no need for a separate <code>\"headerAll.h\"</code>, so it can be inlined into <code>\"libmyutf8.h\"</code>.</p>\n\n<hr>\n\n<p>The non-public functions ought to be declared with static linkage, so that they don't pollute the namespace of user code. By adding <code>static</code> to the signature, we can prevent the problem where other code can use the same identifier but then find conflicts when linking the object files together.</p>\n\n<hr>\n\n<p>Our functions should accept pointer to const, since we don't intend to modify the input string.</p>\n\n<hr>\n\n<p>I recommend using an unsigned <code>1u</code> rather than <code>1</code> here:</p>\n\n<blockquote>\n<pre><code>#define CHECK_BIT(var,pos) ((var) & (1<<(pos)) )\n</code></pre>\n</blockquote>\n\n<p>That ensures that all the terms of the calculation are unsigned, and there's no unexpected promotion to a signed type (I don't believe that's a problem anywhere this is used, but it makes it easier to reason about; always prefer unsigned types for bit operations where possible).</p>\n\n<hr>\n\n<p>The URI in the comment can be shortened: <code>https://stackoverflow.com/q/523724</code>.</p>\n\n<hr>\n\n<p>Testing a group of bits is simpler when done as a <em>mask</em> operation. So instead of:</p>\n\n<blockquote>\n<pre><code> } else if (CHECK_BIT(currentByte, 7) && CHECK_BIT(currentByte, 6) &&\n CHECK_BIT(currentByte, 5) && CHECK_BIT(currentByte, 4) &&\n !CHECK_BIT(currentByte, 3))\n</code></pre>\n</blockquote>\n\n<p>We can write:</p>\n\n<pre><code> } else if ((currentByte & 0xf8) == 0xf0)\n</code></pre>\n\n<hr>\n\n<p>Instead of a linear search in <code>increseCodeBlock</code> (is that a typo for <code>increase</code>?), we could use a binary search. An alternative would be to have a table of pointers using the high portion of the character to index to the start point in <code>codePointBlocks</code>. I haven't fully thought this through, but it would go something like this:</p>\n\n<pre><code>/* Instead of writing this by hand, we could initialise this using\n code to determine where each xx00 can be found */\nstatic int blockIndex[] = {\n 0, /* 00xx - Basic Latin and Latin-1 */\n 2, /* 01xx - Latin Extended A and B */\n 3, /* 02xx - Latin B, to Spacing Modifiers */\n 6, /* 03xx - Combining Diacriticals, Greek, Coptic */\n ... /* lots more... */\n};\nstatic const size_t blockIndexSize = sizeof blockIndex / sizeof *blockIndex;\n\nunsigned long highPart = codePoint / 0x100;\nif (highPart >= blockIndexSize) {\n highPart = blockIndexSize - 1;\n}\n\nfor (int i = blockIndex[highPart]; i < codeBlocksCount; i++) {\n</code></pre>\n\n<p>The <code>blockIndex</code> table just serves to allow us to start <code>i</code> at a point nearer to the target, so saving us testing so many entries.</p>\n\n<hr>\n\n<p>The big <code>do</code>/<code>while</code> loop in <code>scanUtf8</code> looks like it could be a <code>for</code> loop (we have an initial <code>i = 0</code>, a test of <code>i</code> and an increment <code>++i</code>, so would be clearer expressed that way). It looks like</p>\n\n<blockquote>\n<pre><code>int i = 0;\ndo {\n /* code */\n ++i;\n} while (i < maxLength);\n</code></pre>\n</blockquote>\n\n<p>Most C programmers would expect to see that as</p>\n\n<pre><code>for (int i = 0; i < maxLength; ++i) {\n /* code */\n}\n</code></pre>\n\n<p>(The equivalence does require <code>0 < maxLength</code>, because this change moves the test from the end to the beginning of each loop)</p>\n\n<hr>\n\n<p>Instead of four variables <code>byte1</code>, <code>byte2</code>, <code>byte3</code>, <code>byte4</code>, it may be better to build up the code point incrementally:</p>\n\n<pre><code>/* UNTESTED! */\n\n/* Store next UTF-8 character into ch, and return next start position */\nconst char* scanUTF8(const char *s, wchar_t *ch)\n{\n int remaining = 0;\n\n for (; *s; ++s) {\n unsigned char c = *s;\n if (remaining) {\n /* check that it's a continuation byte */\n if (c & 0xc0 != 0x80) {\n *ch = BAD_UTF8;\n return s;\n }\n *ch = (*ch << 6) + (c & 0x3f);\n if (!--remaining) {\n return s;\n }\n } else if (c & 0x80 == 0) {\n /* single-byte (ASCII) */\n *ch = c;\n return s;\n } else {\n /* should be a start byte */\n for (remaining = 3; remaining > 0; --remaining) {\n if (~c >> (6 - remaining) == 1u) {\n *ch = c & ((1u << (6 - remaining)) - 1);\n break;\n }\n }\n if (!remaining) {\n /* not a valid start byte */\n *ch = BAD_UTF8;\n return ++s;\n }\n }\n }\n\n /* incomplete UTF-8 sequence */\n *ch = BAD_UTF8;\n return s;\n}\n</code></pre>\n\n<hr>\n\n<p>The test program assumes that <code>malloc()</code> will succeed, without checking. Don't do this, not even in test programs. Actually, <em>especially</em> not in test programs - make it fail with a useful message, so we don't confuse runtime errors with code bugs.</p>\n\n<hr>\n\n<p>A utility of this nature really deserves a decent unit-test suite. Whilst it's good that there is a test program included, we can do better. Making a set of minimal inputs and expected outputs has these benefits over the test program:</p>\n\n<ul>\n<li>It's self-contained, rather than needing a separate input file.</li>\n<li>Each test exercises a known subset of the code (making it easier to relate a failed test to its underlying cause).</li>\n<li>Tests can be run automatically every build (and fail the build if they don't all pass).</li>\n</ul>\n\n<p>If we have access to a C++ compiler, that allows us to use one of the excellent test frameworks implemented in that language (it's easy to link our C function into a C++ program, using <code>extern \"C\"</code>).</p>\n\n<p>When writing unit tests, I usually start with the easy error cases first (null string, empty string). That will quickly get us into the testing mindset. After that, we can start adding the success cases and more complex errors (out-of-range characters, extra or missing continuation bytes, surrogate codepoints, overlong encoding, and so on). You might want to read <a href=\"https://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt\" rel=\"nofollow noreferrer\">Markus Kuhn's decoder capability tests</a> for some ideas on what to test.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T20:37:57.747",
"Id": "420167",
"Score": "0",
"body": "wow, thank you very much, would you allow me to ask some questions... **1-** *\"The non-public functions ought to be declared with static linkage, so that they don't pollute the namespace of user code.\"* .... you mean here if I declared non public function like `increaseCodeBlock` in the HEADER file `libmyutf8.h` , right ? like this `static int increseCodeBlock(....` ? shouldn't I never declare non-public functions in the header file at all ? **2-** *\"I recommend using an unsigned 1u rather than 1 here\"* ... why ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T20:39:12.963",
"Id": "420168",
"Score": "0",
"body": "**3-** *\"we could use a binary search. An alternative would be to have a table of pointers using the high portion of the character to index to the start point in codePointBlocks,\"* ... what is a table of pointers ? is it a 2 dimensional array ? can you please show me how I can do it ?...and yes it is a typo I meant \"increase\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T20:40:38.967",
"Id": "420169",
"Score": "0",
"body": "**4-** *\"we have an initial i = 0, a test of i\"*... what is the test for the `i` here ? do you mean I do `strlen()` to know the count of the chars before I start the big `for` loop ?\n\nI like how you write this `currentByte & 0xf8 == 0xf0` instead of 4 lines :D . and the entire new logic looks very smart, I will study it again today. Thank you very very much."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T07:55:21.943",
"Id": "420217",
"Score": "1",
"body": "**1**. No, don't declare the internal functions in the header. But do add `static` in the implementation file, so that others can use the same identifier without running into problems when they *link* with this object file (perhaps as a library member). **2**. Unsigned types have fewer surprises with `>>` and other bitwise operators. **3**, No, just an array - see edit. **4**, The test is `i < maxLength` - also see edit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T10:33:55.903",
"Id": "420233",
"Score": "0",
"body": "`unsigned long highPart = codePoint / 0x100;` you mean here `&` , right ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T12:23:46.717",
"Id": "420240",
"Score": "0",
"body": "Thanks @Deduplicator - I never remember the correct precedence for bitwise operators!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T12:27:12.780",
"Id": "420243",
"Score": "1",
"body": "@Accountantم, no I meant `/`: we want to turn 00xx into 0, 01xx into 1, 02xx into 2, etc, where 'x' is any hex digit. The idea is that we use the high-order bits to decide how much of the `blockIndex` array to skip over before starting the search. But don't get hung up on that too much - the linear search works, and I regard this optimisation as the least important of my recommendations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T12:29:11.347",
"Id": "420246",
"Score": "1",
"body": "Sometimes knowing history helps: The precedence of bitwise-operators is borked because they were split off from the logical operators very late, and without fixing their precedence."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T12:43:06.423",
"Id": "420255",
"Score": "0",
"body": "@TobySpeight hmm, I got it, it's the same effect as `>>2`. Actually I got a paper and pen to remember how division works for binary numbers :D . I liked it so much because when I wrote this function, I thought of better way than the linear search but I couldn't find any, thank you for this and offcurse for the other recommendations. How come this answer didn't get more upvotes :( , it helped me a lot."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T13:00:51.043",
"Id": "420260",
"Score": "0",
"body": "Nearly right; it's the same as `>>8` (shift right 8 bits). Any decent compiler will produce the same object code whether you write it as `/ 0x100` or `>> 16`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T22:06:46.980",
"Id": "420472",
"Score": "0",
"body": "Tests missing: Detection of surrogates and values above `0x10FFFF` - which should error."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T22:18:45.763",
"Id": "420476",
"Score": "0",
"body": "Code also missing other bad input sequences: Consider 0xC0 0x80 should fail. Recommend that `*ch = c & ((1u << (6 - remaining)) - 1);` followed by a setting of a min/max for later use in the `if (!--remaining) {` block."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T14:04:19.413",
"Id": "420556",
"Score": "0",
"body": "If `*s` --> 0, `scanUTF8(s, ch)` sets `*ch = BAD_UTF8;` rather than 0."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T07:44:25.077",
"Id": "420742",
"Score": "0",
"body": "@chux, there was a typo: I wrote `UNTESTED?` when I meant `UNTESTED!`"
}
],
"meta_data": {
"CommentCount": "14",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T09:25:32.440",
"Id": "217189",
"ParentId": "217169",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "217189",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T01:36:50.817",
"Id": "217169",
"Score": "8",
"Tags": [
"beginner",
"c",
"reinventing-the-wheel",
"utf-8"
],
"Title": "myUTF-8 small lib (validate UTF-8, guess language, count chars)"
} | 217169 |
<p>The task:</p>
<blockquote>
<p>You are given an array of length n + 1 whose elements belong to the
set {1, 2, ..., n}. By the pigeonhole principle, there must be a
duplicate. Find it in linear time and space.</p>
</blockquote>
<pre><code>const lst = [1,2,3,4,5,6,7,8,7];
</code></pre>
<p>My functional solution:</p>
<pre><code>const findDuplicate = lst => {
const set = new Set();
let ret;
lst.some(x => set.has(x) ?
!Boolean(ret = x) :
!Boolean(set.add(x))
);
return ret;
};
console.log(findDuplicate(lst));
</code></pre>
<p>My imperative solutions:</p>
<pre><code>function findDuplicate2(lst) {
const set = new Set();
let i = 0;
while(!set.has(lst[i])) { set.add(lst[i++]); }
return lst[i];
}
console.log(findDuplicate2(lst));
function findDuplicate3(lst) {
for (let i = 0, len = lst.length; i < len; i++) {
if (lst[Math.abs(lst[i])] >= 0) {
lst[Math.abs(lst[i])] = -lst[Math.abs(lst[i])];
} else {
return Math.abs(lst[i]);
}
}
}
console.log(findDuplicate3(lst));
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T08:16:09.103",
"Id": "420094",
"Score": "0",
"body": "(How about sketching an O(1) space solution?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T08:22:16.710",
"Id": "420095",
"Score": "0",
"body": "@greybeard isn't `findDuplicate3` O(1) space? I don't use an additional variable - only the running variable `i`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T08:49:20.230",
"Id": "420098",
"Score": "0",
"body": "Announced as `imperative solution`, I didn't expect nor notice more than one - even eye-balling it has to wait till after \"day-time chores\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T08:50:34.813",
"Id": "420099",
"Score": "0",
"body": "@greybeard but I don't know whether it's good practice to mutate the input value."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T10:47:45.130",
"Id": "420110",
"Score": "0",
"body": "sorry for nitpicking, but a set – by definition – is a collection of **distinct** objects."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T12:04:14.753",
"Id": "420117",
"Score": "0",
"body": "@morbusg ok, what’s your point ?"
}
] | [
{
"body": "<p>I'm not a big fan of the functional solution for following reasons:</p>\n\n<ol>\n<li><p>the pointless use of the <code>some()</code> method, because its callback always returns <code>false</code>. This is this possibly an error? The call would short-circuit, if <code>Boolean(ret = x)</code> weren't negated. But even then <code>some()</code> would be the wrong choice, because it's just used for short-circuiting. I believe <code>find()</code> would be a better choice.</p></li>\n<li><p>the conditional expression together with <code>Boolean(...)</code> expressions are a bit if a crutch. The conditional expression seems to be only used to be shorter that an full <code>if</code>, but that requires <code>Boolean()</code>, so that it still returns a boolean value needed for <code>some()</code>.</p></li>\n</ol>\n\n<p>Using <code>find()</code> I've come up with</p>\n\n<pre><code>const findDuplicate = lst => {\n const set = new Set();\n return lst.find(\n x => set.has(x) || !set.add(x)\n );\n};\n</code></pre>\n\n<p>However I do admit it may be a bit cryptic. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T08:06:38.630",
"Id": "217186",
"ParentId": "217171",
"Score": "3"
}
},
{
"body": "<p>You know all the values in the array before you start.</p>\n\n<p>The solution you are looking for is purely is a mathematical one.</p>\n\n<p>The set is 1 to n, thus all items in the set sum to <code>sum = 1 + 2 + 3 + ... + n</code></p>\n\n<p>Thus if there is a duplicate in an array <code>a</code> that contains the set of <code>1</code> to <code>a.length</code> then that duplicate must be the sum of all values subtract the sum of the unique values.</p>\n\n<pre><code>function findDuplicate(arr) {\n var sum = 0, sumArr = 0, i = arr.length;\n while (i--) { \n sum += i;\n sumArr += arr[i];\n }\n return sumArr - sum;\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>function findDuplicate(arr) {\n var res = 0, i = arr.length;\n while (i--) { res += i - arr[i] }\n return -res;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T09:15:22.033",
"Id": "420101",
"Score": "0",
"body": "Hmm.... wait a minute. The task says the elements in the array are members of the set of natural numbers {1..n}. But it doesn't say that the elements consists of consecutive numbers from 1 to n. For example this could also be a valid input: `const lst = [1, 3, 4,7,8,7] `"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T10:41:22.027",
"Id": "420108",
"Score": "0",
"body": "@thadeuszlay the *\"set {1, 2, ..., n}.\"* means all values from 1 to and including n else it would be a subset of the set *\"set {1, 2, ..., n}.\"* which contains some of the values. If array length is n + 1 then the array must contain the set `{1,2,..., n}`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T15:24:57.820",
"Id": "420132",
"Score": "0",
"body": "I see. What is your opinion about this solution:\n`const findDuplicate = arr => arr.reduce((acc, x) => acc + x, 0) - ((arr.length - 1)*(arr.length) / 2 );`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T15:30:30.213",
"Id": "420133",
"Score": "0",
"body": "One downside of your algorithm is that it runs till the end of the array even though it may have come across the duplicate already."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T15:59:33.277",
"Id": "420139",
"Score": "0",
"body": "@thadeuszlay I assume that the items are not in order, that means that worst case will always requires stepping over all items. Your (comment) reduce version is just as valid"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T08:55:13.337",
"Id": "217188",
"ParentId": "217171",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "217188",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T02:02:46.233",
"Id": "217171",
"Score": "6",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"functional-programming"
],
"Title": "Find duplicate in linear time and space"
} | 217171 |
<h3>Brief Preface</h3>
<p>I recognize that there are many nuances and requirements for a standard-compatible allocator. There are a number of questions here covering a range of topics associated with allocators. I realize that the requirements set out by the standard are critical to ensuring that the allocator functions correctly in all cases, doesn't leak memory, doesn't cause <em>undefined-behaviour</em>, etc. This is particularly true where the allocator is meant to be used (or at least, can be used) in a wide range of use cases, with a variety of underlying types and different standard containers, object sizes, etc.</p>
<p>In contrast, I have a very specific use case where I personally strictly control all of the conditions associated with its use, as I describe in detail below. Consequently, I believe that what I've done is perfectly acceptable given the highly-specific nature of what I'm trying to implement. </p>
<p><strong><em>I'm hoping someone with far more experience and understanding than me can either confirm that the description below is acceptable or point out the problems (and, ideally, how to fix them too).</em></strong></p>
<h1>Overview / Specific Requirements</h1>
<p>In a nutshell, I'm trying to write an allocator that is to be used within my own code and for a single, specific purpose:</p>
<ul>
<li>I need "a few" <code>std::vector</code> (probably <code>uint16_t</code>), with a fixed (at runtime) number of elements. I'm benchmarking to determine the best tradeoff of performance/space for the exact integer type[1]</li>
<li>As noted, the number of elements is always the same, but it depends on some runtime configuration data passed to the application</li>
<li>The number of vectors is also either fixed or at least bounded. The exact number is handled by a library providing an implementation of <code>parallel::for(execution::par_unseq, ...)</code></li>
<li>The vectors are constructed by me (i.e. so I know with certainty that they will always be constructed with N elements)</li>
</ul>
<p>[1] The value of the vectors are used to conditionally copy a <code>float</code> from one of 2 vectors to a target: <code>c[i] = rand_vec[i] < threshold ? a[i] : b[i]</code> where <code>a, b, c</code> are contiguous arrays of <code>float</code>, <code>rand_vec</code> is the <code>std::vector</code> I'm trying to figure out here, and <code>threshold</code> is a single variable of type <code>integer_tbd</code>. The code compiles as SSE SIMD operations. I do not remember the details of this, but I believe that this requires additional shifting instructions if the ints are smaller than the floats.</p>
<p>On this basis, I've written a very simple allocator, with a single static <code>boost::lockfree::queue</code> as the free-list. Given that I will construct the vectors myself and they will go out of scope when I'm finished with them, I know with certainty that all calls to <code>alloc::deallocate(T*, size_t)</code> will always return vectors of the same size, so I believe that I can simply push them back onto the queue without worrying about a pointer to a differently-sized allocation being pushed onto the free-list.</p>
<p>As noted in the code below, I've added in runtime tests for both the allocate and deallocate functions for now, while I've been confirming for myself that these situations cannot and will not occur. Again, I believe it is unquestionably safe to delete these runtime tests. Although some advice would be appreciated here too -- considering the surrounding code, I think they should be handled adequately by the branch predictor so they don't have a significant runtime cost (although without instrumenting, hard to say for 100% certain).</p>
<p>In a nutshell - as far as I can tell, everything here is completely within my control, completely deterministic in behaviour, and, thus, completely safe. This is also suggested when running the code under typical conditions -- there are no segfaults, etc. I haven't yet tried running with sanitizers yet -- I was hoping to get some feedback and guidance before doing so.</p>
<p>I should point out that my code runs 2× faster than using <code>std::allocator</code>, which is at least qualitatively to be expected.</p>
<hr>
<h2>CR_Vector_Allocator.hpp</h2>
<pre><code>class CR_Vector_Allocator {
using T = CR_Range_t; // probably uint16_t or uint32_t, set elsewhere.
private:
using free_list_type = boost::lockfree::queue>;
static free_list_type free_list;
public:
T* allocate(size_t);
void deallocate(T* p, size_t) noexcept;
using value_type = T;
using pointer = T*;
using reference = T&;
template struct rebind { using other = CR_Vector_Allocator;};
};
</code></pre>
<h2>CR_Vector_Allocator.cc</h2>
<pre><code>CR_Vector_Allocator::T* CR_Vector_Allocator::allocate(size_t n) {
if (n <= 1)
throw std::runtime_error("Unexpected number of elements to initialize: " +
std::to_string(n));
T* addr_;
if (free_list.pop(addr_)) return addr_;
addr_ = reinterpret_cast<T*>(std::malloc(n * sizeof(T)));
return addr_;
}
void CR_Vector_Allocator::deallocate(T* p, size_t n) noexcept {
if (n <= 1) // should never happen. but just in case, I don't want to leak
free(p);
else
free_list.push(p);
}
CR_Vector_Allocator::free_list_type CR_Vector_Allocator::free_list;
</code></pre>
<hr>
<p>It is used in the following manner:</p>
<pre><code>using CR_Vector_t = std::vector<uint16_t, CR_Vector_Allocator>;
CR_Vector_t Generate_CR_Vector(){
/* total_parameters is a member of the same class
as this member function and is defined elsewhere */
CR_Vector_t cr_vec (total_parameters);
std::uniform_int_distribution<uint16_t> dist_;
/* urng_ is a member variable of type std::mt19937_64 in the class */
std::generate(cr_vec.begin(), cr_vec.end(), [this, &dist_](){
return dist_(this->urng_);});
return cr_vec;
}
void Prepare_Next_Generation(...){
/*
...
*/
using hpx::parallel::execution::par_unseq;
hpx::parallel::for_loop_n(par_unseq, 0l, pop_size, [this](int64_t idx){
auto crossovers = Generate_CR_Vector();
auto new_parameters = Generate_New_Parameters(/* ... */, std::move(crossovers));
}
}
</code></pre>
<p>Any feedback, guidance or rebukes would be greatly appreciated. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T02:53:57.213",
"Id": "420082",
"Score": "0",
"body": "Please fix the typo in your code (Ctrl+F `queue>;`) and make sure that what you've posted is compileable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T06:33:15.307",
"Id": "420087",
"Score": "0",
"body": "> \"`c[i] = rand_vec[i] < threshold ? a[i] : b[i]` where a, b, c are contiguous arrays\". It's not about the allocator, but having only one array where a[i], b[i] and c[i] are neighbors would improve locality and probably performance. It's not much but a lot easier to do than implementing allocators"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T06:51:00.380",
"Id": "420089",
"Score": "0",
"body": "\"The number of vectors is also either fixed or at least bounded\": is the number or the bound known at some point in the program?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-15T21:16:56.487",
"Id": "439489",
"Score": "0",
"body": "@papagaga Thanks for your comments - sorry for the very late response. As to your comment regarding putting the vectors into a single array, this is not practical due to the algorithm, which is an implementation of Differential Evolution - the arrays a and b are the mutated and parent trial vectors, respectively. I recognize that an allocator will only make a limited difference; however, due to the number of calls, the savings will add up. Also, even as-is, I expect that the compiler should generate streaming vector conditional moves for that statement (although I have not yet verified it)"
}
] | [
{
"body": "<p>This only works if <code>n</code> is never changes between calls.</p>\n<pre><code>T* addr_;\nif (free_list.pop(addr_)) return addr_;\n</code></pre>\n<p>IF you can guarantee this then its fine. Otherwise you need a free list for every different value of <code>n</code>. otherwise an allocation for 10 could be done then deallocated (thus you have a block of ten on the list). Now an allocation comes in for 20 (you will give it the block on the free list which has a size of 10).</p>\n<p>If you know that <code>n</code> never changes then:</p>\n<pre><code>if (n <= 1)\n throw std::runtime_error("Unexpected number of elements to initialize: " +\n std::to_string(n));\n</code></pre>\n<p>and</p>\n<pre><code>if (n <= 1) // should never happen. but just in case, I don't want to leak\n free(p);\n</code></pre>\n<p>Are a waste of time. You have already guaranteed that <code>n</code> is consistent.</p>\n<p>This is particularly bad practice for something that needs optimal work.</p>\n<pre><code>if (n <= 1) // should never happen. but just in case, I don't want to leak\n free(p);\n</code></pre>\n<p>Branching is the single most problematic thing in degradation of performance. If the CPU branch prediction is off then you always pay the price. I would put that check in an <code>assert()</code> that way you can validate when testing but in production you don't need to perform the test.</p>\n<h2>Undefined Behavior.</h2>\n<p>This will not work:</p>\n<pre><code>static free_list_type free_list;\n</code></pre>\n<p>If you have any <code>std::vector<></code> that use your allocator that is in the global scope (or any constructors for static storage duration objects that create vectors directly or indirectly with your allocator).</p>\n<p>You will need to convert this to a static function:</p>\n<pre><code> static free_list_type getFreeList() {\n static free_list_type free_list;\n return free_list;\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T23:34:01.590",
"Id": "217234",
"ParentId": "217172",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T02:04:28.440",
"Id": "217172",
"Score": "5",
"Tags": [
"c++",
"memory-management"
],
"Title": "A custom, highly-specialized, special-purpose standard-compliant C++ allocator"
} | 217172 |
<p>I want to get <code>version</code> from <code>Cargo.toml</code> and use the value inside my app. Here is a function I wrote:</p>
<pre><code>use std::fs;
pub fn get_version() -> &'static str {
let text = fs::read_to_string("Cargo.toml").unwrap();
for line in text.split("\n") {
if line.starts_with("version") {
let start = line.find('"').unwrap() + 1;
let end = line.rfind('"').unwrap();
let version = &line[start..end];
return Box::leak(version.to_string().into_boxed_str());
}
}
panic!("failed parsing version from Cagro.toml");
}
</code></pre>
<p>Writting the function, I had some questions. So I'd like to get help from others.</p>
<ul>
<li>How can I replace <code>for</code> and <code>if</code> nested blocks with iterator methods?</li>
<li>To return value as <code>static</code> lifetime, I used <code>Box::leak(version.to_string().into_boxed_str())</code> which is too complicated (<code>&str -> String -> Box<str></code> just for avoiding compile errors). How can I return <code>&'static str</code> or <code>&'a str</code> simply without getting <code>cannot return value referencing local variable ...</code> error in this case?</li>
<li>Can I make the code simpler? (ex: parsing the version value)</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T14:57:31.147",
"Id": "420130",
"Score": "1",
"body": "Do you know about macro [env!](https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T01:15:57.290",
"Id": "420192",
"Score": "0",
"body": "@aSpex Thanks for the information. I can easily get Cargo version via `env!`. Apart from it, I'd like to get my code reviewed."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T03:59:49.773",
"Id": "217176",
"Score": "3",
"Tags": [
"parsing",
"file",
"rust"
],
"Title": "Parsing version from Cargo.toml"
} | 217176 |
<p>I am using the <a href="https://www.npmjs.com/package/music-metadata-browser" rel="nofollow noreferrer">music metadata-browser</a> npm package to retrieve audio metadata from files. This library is being used in an <a href="https://electronjs.org/" rel="nofollow noreferrer">Electron</a> and React desktop app. </p>
<p>To get the metadata of audio files, (and add it to the redux state), I use the following function to get metadata and add the file to redux state. This method works well with small amounts of data, but gets really slow (obviously) as more audio files are given to be processed. Is there a better way I can process these files? Not sure if javascript has any worker/job techniques I could use.</p>
<pre><code>import * as mm from 'music-metadata-browser';
const addFile = (filePath, file, dispatch, ext) => {
if (Buffer.isBuffer(file)) {
mm.parseBuffer(file, ext)
.then(metadata => {
const libraryEntry = createLibraryEntry(filePath, metadata);
dispatch({ type: constants.ADD_FILE, libraryEntry, totalFiles });
});
}
else {
mm.parseBlob(file, ext)
.then((metadata) => {
const libraryEntry = createLibraryEntry(filePath, metadata);
dispatch({ type: constants.ADD_FILE, libraryEntry, totalFiles });
});
}
};
const processFiles = (files, dirPath, dispatch) => {
files.map((file, index) => {
const parsedFile = file.split('.');
const format = parsedFile[parsedFile.length - 1];
const filePath = `${dirPath}/${file}`;
const isDirectory = fs.lstatSync(filePath).isDirectory();
if (isDirectory) {
fs.readdir(filePath, (err, files) => {processFiles(files, filePath, dispatch);});
}
else if (isValidFormat(format)) {
fs.readFile(filePath, (err, file) => {
addFile(filePath, Buffer(file), dispatch, format);
});
}
return;
});
};
</code></pre>
<p>Thanks for the help.</p>
| [] | [
{
"body": "<p>It appears <a href=\"https://www.npmjs.com/package/music-metadata\" rel=\"nofollow noreferrer\">music-metadata</a> is the Node.js/desktop flavor of music-metadata-browser (intended for browsers). The author doesn't explain the differences between the two, but maybe the desktop variant will be faster for you.</p>\n\n<p>Synchronous anything is a mistake for an inherently parallel task like this. Use <code>fs.lstat</code> instead of the <code>fs.lstatSync</code>. If <code>createLibraryEntry</code> or <code>dispatch</code> touch the disk they should be replaced with async versions as well.</p>\n\n<p>Worker threads <a href=\"https://nodejs.org/api/worker_threads.html\" rel=\"nofollow noreferrer\">are a thing</a> but you probably don't need them, because disk access is what's slowing you down and async disk access <a href=\"https://blog.stephencleary.com/2013/11/there-is-no-thread.html\" rel=\"nofollow noreferrer\">doesn't require threads</a>. </p>\n\n<p>If you have disk I/O that can't be asynchronized (if that's a word) by conventional callback functions, or if you've made everything async and it's still too slow, that is the time to consider using workers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T15:40:19.890",
"Id": "420136",
"Score": "0",
"body": "Thanks for the response! Yes, I tried to use `music-metadata` but for some reason I'd receive an error saying `fs is undefined` when I tried to use it within my electron-based app. I'll definitely switch to using the async options and see how that impacts performance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T18:25:49.187",
"Id": "420305",
"Score": "0",
"body": "Update: I ended up sending the files to the main electron process so that I could use `music-metadata` without any fs issues. (Also for speed and performance)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T06:44:16.757",
"Id": "217184",
"ParentId": "217181",
"Score": "2"
}
},
{
"body": "<h1>Caching and Streaming.</h1>\n<h2>Cache data</h2>\n<p>I can not workout if you are doing this each time your app loads. If you are and it is a slow point you should consider storing the processed data in a file or IndexedDB. The index can be the file path or hash derived from the file path.</p>\n<p>Then the app should only retrieve the meta data from the cache as needed.</p>\n<h2>System RAM</h2>\n<p>You are loading the entire music file via the <code>fs.readFile</code> before you extract the meta data, and you read all the files in one go.</p>\n<p>This will be a slow point, not due to the processing speed but rather the paging speed of system memory.</p>\n<p>As example using my music directory. It is 104Gb of disk space. Your <code>processFiles</code> function would thus attempt to load 104Gb of music files. That will keep the paging system very busy and slow the whole system. (Personally if I saw an app abuse my system like that I would shut it down and uninstall)</p>\n<h2>Streaming</h2>\n<p>Looking at the metadata reader it does support streaming. You can then process the files without the need to load a massive RAM buffer of files.</p>\n<p><code>mm.parseNodeStream(readableStream)</code> will use Nodes <a href=\"https://nodejs.org/api/stream.html#stream_readable_streams\" rel=\"nofollow noreferrer\">readable stream</a></p>\n<p>This will reduce the RAM overhead. However that still is a lot of data to process so it is still best to store the extracted meta data in some form of indexedDB</p>\n<p>Then at start up scan the music directory for changes, and read the meta data only from new or updated files, all others will be in the cache.</p>\n<h2>Slow it down.</h2>\n<p>Last point is that you should not try to get the data as fast as possible. The job will take time, people are prepared to wait for full functionality as long as you don't block the interface while you process the data.</p>\n<p>Prioritize if you can the files that need to be process (eg in UI's view, next to play, or whatever your app does).</p>\n<p>Keep an eye on the systems level of activity and process fast when not very busy, and slowly when busy (Note be aware your processing will effect the system activity)</p>\n<p>If it is a must that you process all file before the app can work then make the first processing job as part of the install.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T15:38:33.587",
"Id": "420135",
"Score": "0",
"body": "Thanks for the response! The idea is to only load in the files once, and then save state upon the app closing. I'm new to streams but I'll try to implement what I'm doing using `mm.parseNodeStream(readableStream)`. I'll also look into `indexedDB`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T14:14:27.967",
"Id": "217206",
"ParentId": "217181",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "217184",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T05:34:28.660",
"Id": "217181",
"Score": "4",
"Tags": [
"javascript",
"performance",
"file-system",
"react.js",
"redux"
],
"Title": "Best way to retrieve music metadata from audio files?"
} | 217181 |
<p>I am new to rust and to start learning the language I decided to implement a simple one-time pad encryption program.</p>
<p>The part I am least sure about is the reading and writing from the files. Ideally this would run efficiently on large files.</p>
<pre><code>use clap::{Arg, App};
use std::{
error::Error,
fs::File,
io::{
self,
Read,
Write,
},
};
const CAPACITY: usize = 1024;
fn main() -> Result<(), Box<dyn Error>> {
let matches = App::new("onetime")
.version("0.1")
.author("Carlo Abelli <carlo@abelli.xyz>")
.about("Encrypts/decrypts a file using a one-time pad.")
.arg(Arg::with_name("FILE")
.required(true)
.help("The file to encrypt/decrypt"))
.arg(Arg::with_name("PAD")
.short("p")
.long("pad")
.takes_value(true)
.value_name("PAD")
.required(true)
.help("The pad to use for encryption/decryption"))
.arg(Arg::with_name("OUTPUT")
.short("o")
.long("output")
.value_name("OUT")
.help("The output file (default: stdout)"))
.get_matches();
let mut file = File::open(matches.value_of("FILE").unwrap())?;
let mut pad = File::open(matches.value_of("PAD").unwrap())?;
if file.metadata()?.len() > pad.metadata()?.len() {
panic!("file is larger than pad!");
}
let mut out: Box<dyn Write> = match matches.value_of("OUTPUT") {
Some(name) => Box::new(File::create(name)?),
None => Box::new(io::stdout()),
};
let mut file_buffer = vec![0u8; CAPACITY];
let mut pad_buffer = vec![0u8; CAPACITY];
loop {
let size = file.read(&mut file_buffer)?;
if size == 0 {
break;
}
pad.read_exact(&mut pad_buffer[..size])?;
let out_buffer: Vec<u8> = pad_buffer.iter()
.zip(file_buffer.iter())
.map(|(pad_byte, file_byte)| pad_byte ^ file_byte)
.collect();
out.write_all(&out_buffer)?;
}
Ok(())
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T05:39:19.570",
"Id": "217182",
"Score": "3",
"Tags": [
"beginner",
"file",
"rust"
],
"Title": "Simple one-time pad in Rust"
} | 217182 |
<p>The task:</p>
<blockquote>
<p>Given an array of integers, return a new array where each element in
the new array is the number of smaller elements to the right of that
element in the original input array.</p>
<p>For example, given the array [3, 4, 9, 6, 1], return [1, 1, 2, 1, 0],
since:</p>
<ul>
<li>There is 1 smaller element to the right of 3</li>
<li>There is 1 smaller element to the right of 4</li>
<li>There are 2 smaller elements to the right of 9</li>
<li>There is 1 smaller element to the right of 6</li>
<li>There are no smaller elements to the right of 1</li>
</ul>
</blockquote>
<pre><code>const lst = [3, 4, 9, 6, 1];
</code></pre>
<p>My solutions:</p>
<pre><code>const numberOfSmallerElem = lst => lst.map((x,i) => lst.slice(i + 1).reduce((acc,y) => y < x ? ++acc : acc, 0));
console.log(numberOfSmallerElem(lst));
function numberOfSmallerElem2(lst) {
for (let i in lst) {
lst[i] = lst.slice(i).reduce((acc,y) => y < lst[i] ? ++acc : acc, 0);
}
return lst;
}
console.log(numberOfSmallerElem2(lst));
function numberOfSmallerElem3(lst) {
const ret = [];
for (let i = 0, len = lst.length; i < len - 1; i++) {
const reference = lst[i];
let counter = 0;
for (let j = i + 1; j < len; j++) {
if(lst[j] < reference) { counter++; }
}
ret.push(counter);
}
ret.push(0);
return ret;
}
console.log(numberOfSmallerElem3(lst));
</code></pre>
| [] | [
{
"body": "<h3>Performance</h3>\n\n<p>The posted implementations are quadratic.\nA log-linear solution exists.\nHere's a hint:</p>\n\n<blockquote class=\"spoiler\">\n <p> What if you insert values from right to left into a sorted list?</p>\n</blockquote>\n\n<h3>Avoid mutations in functional implementations</h3>\n\n<p>Can you spot the mutation on this line?</p>\n\n<blockquote>\n<pre><code>const numberOfSmallerElem = lst => lst.map((x,i) => lst.slice(i + 1).reduce((acc,y) => y < x ? acc++ : acc, 0)); \n</code></pre>\n</blockquote>\n\n<p>It's actually not easy to spot it when the line is so long!\nI suggest to break it up, for readability.\nAnd then eliminate the mutation.</p>\n\n<blockquote class=\"spoiler\">\n <p> Replace <code>acc++</code> with <code>acc + 1</code></p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T14:40:54.560",
"Id": "420274",
"Score": "0",
"body": "So in functional programming you don't do increment/decrement, i.e. a++/a--?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T08:05:57.860",
"Id": "217253",
"ParentId": "217187",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "217253",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T08:48:49.847",
"Id": "217187",
"Score": "1",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"functional-programming"
],
"Title": "Return a new array where each element is the number of smaller elements to the right of that element in the original input"
} | 217187 |
<p>I have two different series in pandas that I have created a nested for loop which checks if the values of the first series are in the other series. But this is time consuming in pandas and I cannot work out how to change it to a pandas method. I thought to use the <code>apply</code> function but it did not work with method chaining. My original nested for loops look like so and they work;</p>
<pre class="lang-py prettyprint-override"><code>for x in df_one['ser_one']:
print(x)
for y in df_two['ser_two']:
if 'MBTS' not in y and x in y:
if 'L' in y:
print(y)
</code></pre>
<p>Is there a way to make this less time consuming?</p>
<p>Here is what I attempted using <code>apply</code> methods;</p>
<pre><code>df_two['ser_two'].apply(lambda x: x if 'MBTS' not in df_one['ser_one'].apply(lambda y:y) and x in df_one['ser_one'].apply(lambda y:y))
</code></pre>
<hr>
<p>Example input:</p>
<pre><code>df_one.head()
Out[136]:
type ser_one
0 MBTS VUMX1234
1 MBTS VUMX6436
2 MBTS VUMX5745
3 MBTS VUMX5802
4 MBTS VUMX8091
</code></pre>
<pre><code>df_two.head()
Out[137]:
ser_two
0 VUMX8091
1 VUMX8091L
2 VUMX1234
3 VUMX1234L
4 VUMX5838
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T13:00:59.337",
"Id": "420120",
"Score": "0",
"body": "Can you add some example input?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T13:32:37.617",
"Id": "420122",
"Score": "1",
"body": "@Graipher have added."
}
] | [
{
"body": "<p>Disclaimer, I am not the best at pandas, and I'm absolutely sure there is a far more readable way to accomplish this, but the following will rid you of your for loop and nested if statements, which are slower than vectorized numpy/pandas operations.</p>\n\n<p>Your filter <code>if 'MBTS' not in y</code> won't work the way you think it will, at least, given the limited sample input, as <code>y</code> is a Series made from the column <code>ser_one</code>, not <code>type</code>. Let's assume that's an easy fix so in pseudocode it should be something like:</p>\n\n<pre><code>for x in df_one.ser_one:\n for y in df_two: # iterate through the rows so you get both columns\n if 'MBTS' not in y.type and x in y.ser_two:\n if 'L' not in y.ser_two:\n print(y)\n</code></pre>\n\n<p>This is a bit clunky, and pandas is great for vectorizing these sorts of operations, so let's filter it down to just <code>Series</code> operations. I'm working with a small part of your dataframes, so as a sanity check, they look like </p>\n\n<pre><code>df_one\n ser_one type\n0 VUMX1234 MBTS\n1 VUMX6436 MBTS\n2 VUMX5745 MBTS\n3 VUMX5802 MBTS\n4 VUMX8091 MBTS\n5 VUMX1234 XXXX\n6 VUMX1234L XXXX\n\ndf_two\n ser_two\n0 VUMX8091\n1 VUMX8091L\n2 VUMX1234\n3 VUMX1234L\n4 VUMX5838\n</code></pre>\n\n<p>I added a few entries that were non-MBTS to fit your problem.</p>\n\n<p>The first bit, you want to find where <code>'MBTS'</code> is not in <code>df_one.type</code>, but we want to filter the <em>entire</em> dataframe for that. <code>df.loc</code> will give you the rows that pass a given filter:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>df_one.loc[df_one['type'] == 'MBTS']\n ser_one type\n0 VUMX1234 MBTS\n1 VUMX6436 MBTS\n2 VUMX5745 MBTS\n3 VUMX5802 MBTS\n4 VUMX8091 MBTS\n\n# or\ndf_one.loc[df_one['type'] != 'MBTS']\n ser_one type\n5 VUMX1234 XXXX\n6 VUMX1234L XXXX\n</code></pre>\n\n<p>Now you can check if the results of <code>ser_one</code> are contained within <code>ser_two</code>, since the output of that previous check is a <code>Series</code>, like so:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>df_one.loc[df_one['type'] != 'MBTS']['ser_one'].isin(df_two['ser_two'])\n5 True\n6 True\n</code></pre>\n\n<p>Just get the <code>.loc</code> back from that, and you should be left with two records in this example:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>df_one.loc[df_one.loc[df_one['type'] != 'MBTS']['ser_one'].isin(df_two['ser_two']).index]\n ser_one type\n5 VUMX1234 XXXX\n6 VUMX1234L XXXX\n</code></pre>\n\n<p>It might be a bit easier to do the filtering against any <code>ser_one</code> that contains <code>'L'</code> ahead of time:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>df_one[~df_one['ser_one'].str.contains(\"L\")]\n ser_one type\n0 VUMX1234 MBTS\n1 VUMX6436 MBTS\n2 VUMX5745 MBTS\n3 VUMX5802 MBTS\n4 VUMX8091 MBTS\n5 VUMX1234 XXXX\n</code></pre>\n\n<p>Now, combining all of that into one big gigantic horrible expression</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>df_one.loc[df_one[~df_one['ser_one'].str.contains(\"L\")].loc[df_one['type'] != 'MBTS']['ser_one'].isin(df_two['ser_two']).index]\n\n ser_one type\n5 VUMX1234 XXXX\n</code></pre>\n\n<p>The outer <code>loc</code> will take an array of index values as returned by the <code>.index</code> call near the end of the expression. The rest is just chained filters which are operations in native pandas, implemented in C and fast.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T19:31:38.387",
"Id": "217220",
"ParentId": "217194",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T10:52:09.303",
"Id": "217194",
"Score": "2",
"Tags": [
"python",
"performance",
"pandas"
],
"Title": "Pandas nested loop which checks if values from one series are in another series"
} | 217194 |
<p>I have a web application where my users can upload text documents and emails into what I call Streams. A stream is like a "stack", that holds all emails / documents.</p>
<p>My users can then add <code>fields</code> to the stream, and <code>field_rules</code>. This means, that every time a new document or email is added, the <strong>text content</strong> of the document/email, will be parsed according to the rules, and then the final parsing result is then stored in the database.</p>
<p>My current code works, to some degree, however, it feels a bit "hackish" as well as not very "Laravel like". </p>
<h1>My progress so far</h1>
<p>Whenever a new document (or email) is added, it will be handled by a queue:</p>
<pre><code>public function handle(DocumentHandlingFinished $event)
{
$stream = Stream::find($event->document->stream_id);
$ParsingRules = new ApplyParsingRules($stream, $event->document);
$event->document->storeResults($ParsingRules->parse());
return true;
}
</code></pre>
<p>OK, so in above I start off by getting the "Stream" that the document was uploaded to.</p>
<p>Then I instanciate the <code>ParsingRule</code> class, that will perform the various rules on the content of the document.</p>
<p>Finally, I save the parsed results to the database.</p>
<p>Below you can see my <code>ApplyParsingRule</code> class:</p>
<pre><code>public function __construct(Stream $stream, Document $document)
{
$this->data = $document;
$this->content = $document->content;
$this->stream = $stream;
$this->fields = $this->stream->documentfields()->with('rules')->get();
}
//Iterate through each rule and parse through the content.
public function parse() : object
{
$content = $this->content;
$results = collect([]);
foreach ($this->fields as $field) {
foreach ($field->rules as $fieldrule) {
$content = doSomething($content); //Minified for simplicity.
$results[] = [
'field_rule_id' => $fieldrule->id,
'content' => $content
];
}
}
return $results;
}
</code></pre>
<p>Now as you can see in my handle message, I call the <code>parse()</code> function and then saves the results:</p>
<pre><code>$event->document->storeResults($ParsingRules->parse());
</code></pre>
<p>In my Document model, I have the <code>storeResults()</code> function:</p>
<p><code>Document.php</code></p>
<pre><code>//Persist the parsed content to the database.
public function storeResults(object $results) : object
{
//If the document was already parsed before, delete old records.
if ($this->results->count() > 0) {
$this->results()->delete($this->results);
}
//Use ->last() because we only want to insert the last parsed text result.
return $this->results()->create($results->last());
}
</code></pre>
<p>So above flow works as long as the <code>$results</code> array contains information. </p>
<p>I was wondering if above code can be refactored / improved even further?</p>
<p>Another concern I have is, If the <code>$results</code> array from the <code>ApplyParsingRule</code> class is <strong>empty</strong>, then the <code>create()</code> method will fail.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T10:57:17.300",
"Id": "217195",
"Score": "2",
"Tags": [
"php",
"laravel"
],
"Title": "PHP - Transforming text content according to rules then persisting to database"
} | 217195 |
<p>I have a function to check if a character is a delimiter and I wonder if it is consistent or can be improved:</p>
<pre><code>int chDelimit(int ch)
{
return
(ch == '\n' || ch == '\t') ||
(ch >= ' ' && ch <= '/') ||
(ch >= ':' && ch <= '@') ||
(ch >= '[' && ch <= '`') ||
(ch >= '{' && ch <= '~') ||
(ch == '\0');
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T12:34:59.470",
"Id": "420118",
"Score": "2",
"body": "Can you add a description of what a delimiter is in this case? What one program considers a delimiter, another might not."
}
] | [
{
"body": "<ol>\n<li><p><strong>Function Name</strong> It isn't clear that <code>chDelimit()</code> is a function that tests whether a character is a delimiter character. For functions that return boolean, it's generally accepted to call it <code>Is<Condition>()</code> where <code>condition</code> is phrased in the affirmative. For example, I'd name this function <code>IsDelimiter()</code> and not <code>IsNonDelimiterCharacter()</code></p></li>\n<li><p>Depending on your application, it might be worthwhile to create macros for boolean values (or enums). See <a href=\"https://stackoverflow.com/a/1921557/5972766\">SO: Using Boolean Values in C </a></p></li>\n<li><p>If the list of delimiter characters isn't going to grow too large, create a character array, <code>DelimiterCharacters</code>, and have your function do a one-pass search. </p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T13:48:38.303",
"Id": "217202",
"ParentId": "217197",
"Score": "4"
}
},
{
"body": "<p>There's no particular ordering of characters' code-points in C (other than the digits <code>0</code>..<code>9</code>). This code assumes (for example) that <code>'['</code> is less than <code>'`'</code>, but that's not the case in EBCDIC at least.</p>\n\n<p>I think you might be better off creating a table of boolean values, and indexing into that with the (unsigned value of) <code>ch</code>, in the way that standard <code><ctype.h></code> functions are normally implemented. This will probably improve performance (one lookup, rather than up to 11 comparisons, per call).</p>\n\n<p>Alternatively, and depending on what characters are considered \"delimiters\", you may be able to use standard library functions (e.g. <code>isalnum()</code>) in combination.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T14:00:03.797",
"Id": "217204",
"ParentId": "217197",
"Score": "5"
}
},
{
"body": "<p>Strictly speaking you can't assume that the various characters are in range, portably. The only characters actually guaranteed to be located in a continuous range in the symbol table are <code>'0'</code> to <code>'9'</code>. That's mostly a nitpick though, since 99.9% of all systems are ASCII or UTF.</p>\n\n<p>What's more serious is that this look-up is slow. You have numerous branches which the CPU must execute. If you have to call this function repeatedly from a loop, it will be performance-heavy. Instead, you can replace all of this with a look-up table.</p>\n\n<p>For boolean checks, you should be using <code>bool</code>.</p>\n\n<p>A fixed function might look like this:</p>\n\n<pre><code>#include <stdbool.h>\n\nbool isdelimit (char ch)\n{\n ch &= 0x7F; // ensure 7 bit \n\n const bool DELIMIT[128] = \n {\n ['\\n'] = true,\n ['\\t'] = true,\n [' '] = true,\n ['\\0'] = true,\n // ...\n };\n return DELIMIT[ch];\n}\n</code></pre>\n\n<p>The table <code>DELIMIT</code> will per default initialize all items to <code>false</code> save for those that you explicitly initialize. By using the character value as the search key, the algorithm turns branchless and efficient.</p>\n\n<p>The above trick with using designated initializers means that you only need to type out those delimiters you are interested in, rather than typing out a big table of 127 values.</p>\n\n<p>Also check out the rarely used but 100% standard C functions <code>strpbrk</code> and <code>strcspn</code> (string.h) that can be used for this very purpose too.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T13:46:01.723",
"Id": "420418",
"Score": "0",
"body": "This designated initializer is a very cool idea."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T13:58:38.960",
"Id": "420419",
"Score": "0",
"body": "99+% of systems are Extended ASCII, like UTF-8, Latin-1, ASCII+Don'tCare, and so on, at least leaving out other wider UTFs. Few are vanilla ASCII."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T14:02:05.290",
"Id": "420420",
"Score": "0",
"body": "@Deduplicator With ASCII being a subset of them all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T22:26:30.203",
"Id": "420480",
"Score": "0",
"body": "I'd expect values outside the `0...7F` range to return `false`, not ignore the 8th bit. Simple enough to use `const bool DELIMIT256[UCHAR_MAX + 1]` and `static const bool DELIMIT[(unsigned char) ch];`"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T11:56:04.737",
"Id": "217319",
"ParentId": "217197",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "217204",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T11:48:14.547",
"Id": "217197",
"Score": "0",
"Tags": [
"c"
],
"Title": "To find if a character is a delimiter"
} | 217197 |
<p>I want some JavaScript code to take 3 things as parameters:</p>
<ul>
<li>A function returning a Promise.</li>
<li>The maximum number of attempts.</li>
<li>The delay between each attempt.</li>
</ul>
<p>What I ended up doing is using a <code>for</code> loop. I did not want to use a recursive function : this way, even if there are 50 attempts the call stack isn't 50 lines longer.</p>
<p>Here is the <strong>typescript</strong> version of the code:</p>
<pre class="lang-js prettyprint-override"><code>/**
* @async
* @function tryNTimes<T> Tries to resolve a {@link Promise<T>} N times, with a delay between each attempt.
* @param {Object} options Options for the attempts.
* @param {() => Promise<T>} options.toTry The {@link Promise<T>} to try to resolve.
* @param {number} [options.times=5] The maximum number of attempts (must be greater than 0).
* @param {number} [options.interval=1] The interval of time between each attempt in seconds.
* @returns {Promise<T>} The resolution of the {@link Promise<T>}.
*/
export async function tryNTimes<T>(
{
toTry,
times = 5,
interval = 1,
}:
{
toTry: () => Promise<T>,
times?: number,
interval?: number,
}
): Promise<T> {
if (times < 1) throw new Error(`Bad argument: 'times' must be greater than 0, but ${times} was received.`);
let attemptCount: number;
for (attemptCount = 1; attemptCount <= times; attemptCount++) {
let error: boolean = false;
const result = await toTry().catch((reason) => {
error = true;
return reason;
});
if (error) {
if (attemptCount < times) await delay(interval);
else return Promise.reject(result);
}
else return result;
}
}
</code></pre>
<p>The <code>delay</code> function used above is a promisified timeout:</p>
<pre class="lang-js prettyprint-override"><code>/**
* @function delay Delays the execution of an action.
* @param {number} time The time to wait in seconds.
* @returns {Promise<void>}
*/
export function delay(time: number): Promise<void> {
return new Promise<void>((resolve) => setTimeout(resolve, time * 1000));
}
</code></pre>
<p>Is this a "good" way of doing it? And if not, how could I improve it?</p>
| [] | [
{
"body": "<h2>Call stack / Job queue / Event queue</h2>\n\n<p>Calling an <code>async</code> function does not use the call stack in the way you may be used to.</p>\n\n<p>Rather the async call remains on the call stack only until an await is encountered. Then the call is removed from the call stack and the await (a micro task (I think it is called)) is placed in the job queue (new to ES6). Micro tasks are very similar to the events but have higher priority (micro tasks will be executed before events)</p>\n\n<p>That means that async functions can not overflow the call stack if you call it recursively as <strong>long</strong> as there is an await before the recursion. </p>\n\n<p>Awaiting the recursion call will not work as the code to the right of await is executed before the current context is removed from the call stack.</p>\n\n<p>The following JS example shows a recursive count down from 1billion (it will take some time but will not throw a call stack overflow)</p>\n\n<p>Eg</p>\n\n<pre><code>async function recursive(c = 1e9) { // 1 billion\n if (c > 0) { \n await Promise.resolve(); // removes call recursive from call stack\n // adds this micro task to the job queue\n // Execution is idle and thus the micro task\n // is removed from the queue and next line is\n // executed\n return recursive(c - 1);\n }\n return c;\n}\nrecursive().then(console.log); // will in time display 0\n</code></pre>\n\n<h2>Recursion</h2>\n\n<p>There is no danger in using a recursive and less complex style for your solution. The example below outlines the principle in JS (I am too lazy to type typescript)</p>\n\n<pre><code>const MAX_TRYS = 10; TRY_TIMEOUT = 500;\nfunction toTry() {\n return new Promise((ok, fail) => { \n setTimeout(() => Math.random() < 0.05 ? ok(\"OK!\") : fail(\"Error\"), TRY_TIMEOUT);\n });\n}\nasync function tryNTimes(toTry, count = MAX_TRYS) {\n if (count > 0) {\n const result = await toTry().catch(e => e);\n if (result === \"Error\") { return await tryNTimes(toTry, count - 1) } \n return result\n }\n return `Tried ${MAX_TRYS} times and failed`;\n}\n\ntryNTimes(toTry).then(console.log);\n</code></pre>\n\n<h2>Promise resolve/reject are micro tasks</h2>\n\n<p>I will point out that even if you used just plain old promises rather than a async function the result is the same. A promise adds a micro task to the job queue and will not resolve or reject until the current call stack is empty.</p>\n\n<p>It is therefor safe to recursively call the calling function from the resolved/rejected promise. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T19:51:45.150",
"Id": "217221",
"ParentId": "217199",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "217221",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T13:32:47.093",
"Id": "217199",
"Score": "3",
"Tags": [
"node.js",
"error-handling",
"typescript",
"promise"
],
"Title": "Retry a Promise resolution N times, with a delay between the attempts"
} | 217199 |
<p><strong>UPDATE</strong></p>
<p>New regex - covers escaped slashes and uses lazy qualifiers:</p>
<pre><code>/(?>(')(?>(?>\\\\)|\\'|.)*')|(?>(")(?>(\\\\)|(?>\\")|.)*")|(?>((?>\/\/|#)).*^)|(?>(\/\*).*\*\/)/msU
</code></pre>
<p>Here are the different parts:</p>
<p>Single quotes: <code>(?>(')(?>(?>\\\\)|\\'|.)*')</code></p>
<p>Double quotes: <code>(?>(")(?>(\\\\)|(?>\\")|.)*")</code></p>
<p>Single line comments: <code>(?>((?>\/\/|#)).*^)</code></p>
<p>Multiline comments: <code>(?>(\/\*).*\*\/)</code></p>
<p>I moved the html comments to a different regex because html will be handled differently.</p>
<p><strong>Here's an example of what it does:</strong> (The matched parts are bold)</p>
<hr>
<p><strong>//single line comment</strong></p>
<p>random text ... <strong>#another comment</strong></p>
<p>Multiline comments:</p>
<p><strong>/* this is a multiline comment</strong></p>
<p><strong>matches the whole thing</strong>
<strong>*/</strong></p>
<p>Quotes:</p>
<p><strong>"also matches strings with \" escaped quotes or 'the other kind of quotation marks in it' "</strong></p>
<p><strong>'matches the end quote because it it not escaped \\'</strong></p>
<hr>
<p>This is the original post:</p>
<p>I'm working on making syntax highlighting on my blog, and I created a regex to match strings and comments (I'm going to make a callback function to format each differently)</p>
<p>Here's my regex:</p>
<pre><code>(?>(")(?>[^"]|(?>(?<=\\)"))*")|(?>(')(?>[^']|(?<=\\)')*')|(?>((?>\/\/|#))[^\n\r]*)|(?>(\/\*)(?>.(?!\*\\))*\*\/)|(?>(<!--)(?>.(?!-->))*.-->)
</code></pre>
<p>I tested it and it seemed to work, but is there anything I'm missing or an easier way to do it? It currently matches strings (<code>"..."</code>, <code>'...'</code>) and takes into account escaped chars and strings within other strings. It also matches comments (<code>//...</code>, <code>#...</code>, <code>/*...*/</code>, <code><!--...--></code>).</p>
<p>Here's what I'm using each part of the regex for:</p>
<p>Part 1: <code>(?>(")(?>[^"]|(?>(?<=\\)"))*")</code>: Match strings quoted with <code>"</code></p>
<p>Part 2: <code>(?>(')(?>[^']|(?<=\\)')*')</code>: Match strings quoted with <code>'</code></p>
<p>Part 3: <code>(?>((?>\/\/|#))[^\n\r]*)</code>: Match single line comments <code>#</code> or <code>//</code></p>
<p>Part 4: <code>(?>(\/\*)(?>.(?!\*\\))*\*\/)</code>: Match multiline comments <code>/*...*/</code></p>
<p>Part 5: <code>(?>(<!--)(?>.(?!-->))*.-->)</code>: Match html comments <code><!--...--></code></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T03:06:38.580",
"Id": "420195",
"Score": "0",
"body": "What if there is an escaped backslash before a quote (or any other known ending delimiter)? Are you deliberately avoiding non-greedy (lazy) quantifiers? Do you actually need to separately capture the leading characters for your process? I will assume, yes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T12:24:25.370",
"Id": "420241",
"Score": "0",
"body": "shoot I didn't think of an escaped backslash! I'm don't remember why I didn't use lazy qualifiers but I'll check, and yes I have that capture group so the callback function can easily identify if it's a quote or a comment. thanks for the feedback!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T12:28:38.673",
"Id": "420245",
"Score": "0",
"body": "So theoretically, you'd need to continue matching if a single or double quote is preceded by an odd number of slashes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T12:39:45.223",
"Id": "420253",
"Score": "0",
"body": "Please add context to your question. Specifically add a handful of realistic/tricky input strings and your exact expected output."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T12:40:57.653",
"Id": "420254",
"Score": "0",
"body": "Yeah I'll do that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T02:42:16.050",
"Id": "420341",
"Score": "0",
"body": "you can view a live version of what I'm trying to do on my blog: [maxpelic.com/blog/post/include-files-web/](https://maxpelic.com/blog/post/include-files-web/)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T02:45:27.533",
"Id": "420342",
"Score": "0",
"body": "But, basically, these are just strings of data that are being stored in a database and printed to screen, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T20:40:31.543",
"Id": "420465",
"Score": "0",
"body": "right, there actually stored in json files but same diff"
}
] | [
{
"body": "<p>Instead of using a single regular expression, you should keep a separate expression for each kind of token you want to match.</p>\n\n<p>What about these string literals?</p>\n\n<pre><code>\"\"\n\"\\n\"\n\"\\\\\"\n\"\\\\\\\\\\\\\\\\\"\n\"{$arr['key']->[\"value\"]}\"\n</code></pre>\n\n<p>Some further questions:</p>\n\n<ul>\n<li>Does PHP have literals for regular expressions?</li>\n<li>Are there other tokens that look like strings?</li>\n<li>Are you the first person in the world who wants to split PHP code into separate tokens?</li>\n<li>What about multiline string literals?</li>\n<li>What about <code>?> these <?php</code> string literals?</li>\n</ul>\n\n<p>Since the answer to the third question is a clear No, just use an existing library.</p>\n\n<p>My advice is to keep the regular expressions as small as possible. Otherwise your code will become unreadable in the future.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T14:29:35.647",
"Id": "420128",
"Score": "0",
"body": "I didn't want to use separate expressions because a string in a comment should not be matched, and vice versa"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T14:31:53.233",
"Id": "420129",
"Score": "0",
"body": "Good point. In that case, you should still keep them separate and test them separately, and in the one place where you use the complete regular expression, put it together from the individual parts."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T14:27:13.283",
"Id": "217207",
"ParentId": "217203",
"Score": "1"
}
},
{
"body": "<p>If it is PHP source code you want to highlight, why not use the tokenizer that's build into PHP itself? I use that and it seems to work fine:</p>\n\n<pre><code>$tokens = token_get_all($sourceCode);\n</code></pre>\n\n<p>Then all you have to do is walk through all the tokens and give them a color.</p>\n\n<p>See: <a href=\"https://www.php.net/manual/en/function.token-get-all.php\" rel=\"nofollow noreferrer\">https://www.php.net/manual/en/function.token-get-all.php</a></p>\n\n<p>No extra library, no faffing around with endless regular expressions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T12:26:04.837",
"Id": "420242",
"Score": "0",
"body": "This function is blowing my mind, never saw it before. However, unless I misunderstand its usage and/or the OP's requirements, I don't think it can be relied upon. https://3v4l.org/CffGq correct me if I am wrong."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T12:27:48.807",
"Id": "420244",
"Score": "0",
"body": "@mickmackusa Can you clarify what problem you see? I cannot correct you if you don't tell. ;-) Oh, wait there's a weird link. I'll have a look."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T12:30:09.313",
"Id": "420247",
"Score": "0",
"body": "I kind of expected the double quoted substring to be a single chunk for the OP's requirements, but that wasn't the case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T12:31:40.280",
"Id": "420248",
"Score": "0",
"body": "@mickmackusa I need to have a think about this..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T12:34:29.747",
"Id": "420250",
"Score": "0",
"body": "It is not meant to be valid php code, just content in a blog I guess. There is no sample data with the question, so I don't know what kind of input strings to expect."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T12:39:26.363",
"Id": "420252",
"Score": "0",
"body": "@mickmackusa Just feed it the content of a valid PHP file (with or without HTML) and inspect the result. I've created an example: https://3v4l.org/7Lhf0"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T12:45:36.503",
"Id": "420256",
"Score": "0",
"body": "@mickmackusa as for the misunderstanding in your example: The first bit of the string, before `<?` is HTML, the PHP parser reacts to `<?` even within double quoted HTML strings, it seems. I cannot tell whether that is normal behavior, but I expect it is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T20:42:20.190",
"Id": "420466",
"Score": "0",
"body": "this is a really cool function! I'm actually trying to parse multiple programming languages, but this is definitely an option for the PHP code"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T18:57:36.033",
"Id": "217217",
"ParentId": "217203",
"Score": "3"
}
},
{
"body": "<p>I think I may have thrown you slightly when I mentioned lazy quantifiers. The truth is, using greedy quantifiers improves pattern efficiency.</p>\n\n<p>Regarding your atomic grouping, I don't see any benefit (in my pattern anyhow) because I am actively avoiding the need to backtrack in each \"alternative\" (the expressions between the pipes).</p>\n\n<p>For the single and double quote and multiline comment alternatives, I want the dot to match \"any character AND new lines\". For the inline comment alternative, I want the dot to match \"any non-newline character\". For this reason, I am using \"inline modifiers\", specifically <code>(?s)</code> where needed.</p>\n\n<p>I try to use pattern delimiting characters that do not occur in my pattern. This helps to make the pattern more readable and prevents having to do unnecessary escaping.</p>\n\n<pre><code>~ # pattern delimiter\n(?| # branch reset\n(\")(?:[^\"\\\\]|\\\\(?s).)*\" # capture double quote, match any non-double-quote/non-backslash unless backslash is followed by any character (used as an escaping character)\n| # OR\n(')(?:[^'\\\\]|\\\\(?s).)*' # capture single quote, match any non-single-quote/non-backslash unless backslash is followed by any character (used as an escaping character)\n| # OR\n(#|//).* # capture hash or two-slashes, match the rest of the line # OR\n(/\\*)(?s).*?\\*/ # capture \\*, match zero or more of any character (including newlines), then */ (lazy quantifier)\n| # OR\n(<!--)(?s).*?-->) # capture <!--, match zero or more of any character (including newlines) (lazy quantifier)\n) # end branch reset\n~ # pattern delimiter\n</code></pre>\n\n<p>(<a href=\"https://regex101.com/r/27LzpN/3\" rel=\"nofollow noreferrer\">Pattern Demo</a>)</p>\n\n<p>Implementation: (<a href=\"https://3v4l.org/napru\" rel=\"nofollow noreferrer\">PHP Demo</a>)</p>\n\n<pre><code>const PATTERN = <<<'PATTERN'\n~(?|(\")(?:[^\"\\\\]|\\\\(?s).)*\"|(')(?:[^'\\\\]|\\\\(?s).)*'|(#|//).*|(/\\*)(?s).*?\\*/|(<!--)(?s).*?-->)~\nPATTERN;\n\nconst LOOKUP = [\n '#' => 'gainsboro',\n '//' => 'lightgrey',\n '/*' => 'silver',\n '<!--' => 'darkgrey',\n \"'\" => 'mint',\n '\"' => 'aqua'\n];\n\necho preg_replace_callback(PATTERN, function($m) {\n return \"<span style=\\\"color:\" . LOOKUP[$m[1]] . \";\\\">{$m[0]}</span>\";\n }, $string);\n</code></pre>\n\n<p>By declaring the lookup array as a constant, scoping issues are avoided inside of the <code>preg_replace_callback()</code> callback function. In other words, you don't have to pass in the lookup array with <code>use()</code>.</p>\n\n<p>I am using <a href=\"https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc\" rel=\"nofollow noreferrer\">nowdoc syntax</a> when declaring the pattern constant so that I don't need to escape any quotes. I am declaring a constant for no other reason than the fact that the pattern will not change in the script.</p>\n\n<p>By wrapping the whole expression in a \"<a href=\"https://www.regular-expressions.info/branchreset.html\" rel=\"nofollow noreferrer\">branch reset</a>\" (<code>(?|...)</code>), you can avoid calling <code>end($m)</code> inside the custom function to access the captured group. The branch reset ensures that each capture group is always the second element in the matches output (at <code>[1]</code>). If you removed the branch reset in the Regex101 demo above, you will see that the captured \"marker\" matches will have differing indexes.</p>\n\n<p>Hmm... If your code is relying on the different indexes as part of a lookup-based replacement, then don't use the branch reset -- it's a good chance to break out one of the new weapons: <a href=\"https://stackoverflow.com/a/52098132/2943403\">array_key_last($m)</a>.</p>\n\n<p>Test Input:</p>\n\n<pre><code>$string = <<<'STRING'\n//single line comment\n\nrandom text ... #another comment\n\nMultiline comments:\n\n/* this is a multiline comment\n\nwith 'squote and \"dquote\"\n\nmatches the whole thing */\n\n// single line 'squoted' \"dquoted\" comment w/ extra \" for no reason\n\nMore comments <!-- yatta yatta\nyatta\nyatta -->\n\nQuotes:\n\n\"also matches strings with \\\" escaped quotes or 'the other kind of quotation marks in it' \"\n\na \"nested 'squote with nested \\\"dquote\\\"'\" assuming only outermost quoting matters for formatting\n\n'matches the end quote because it it not escaped \\\\'\nSTRING;\n</code></pre>\n\n<p>Output (unrendered):</p>\n\n<pre><code><span style=\"color:lightgrey;\">//single line comment</span>\n\nrandom text ... <span style=\"color:gainsboro;\">#another comment</span>\n\nMultiline comments:\n\n<span style=\"color:silver;\">/* this is a multiline comment\n\nwith 'squote and \"dquote\"\n\nmatches the whole thing */</span>\n\n<span style=\"color:lightgrey;\">// single line 'squoted' \"dquoted\" comment w/ extra \" for no reason</span>\n\nMore comments <span style=\"color:darkgrey;\"><!-- yatta yatta\nyatta\nyatta --></span>\n\nQuotes:\n\n<span style=\"color:aqua;\">\"also matches strings with \\\" escaped quotes or 'the other kind of quotation marks in it' \"</span>\n\na <span style=\"color:aqua;\">\"nested 'squote with nested \\\"dquote\\\"'\"</span> assuming only outermost quoting matters for formatting\n\n<span style=\"color:mint;\">'matches the end quote because it it not escaped \\\\'</span>\n</code></pre>\n\n<p>Reasons to re-invent the wheel. The wheel that you need is very narrow and employing/loading a complete library may be overkill in terms of performance or memory consumption for your task.</p>\n\n<p>In terms of step count, my pattern is slightly more efficient than yours. Though to be honest, I have been informed (by Stackoverflow regex gurus who I respect) that step count is not a reliable metric to gauge pattern efficiency. I generally use it, though, as a rough indicator of pattern efficiency.</p>\n\n<p>I reckon taking these opportunities to sharpen regular expression knowledge is a healthy exercise for programmers. The more you work with regular expressions, the less scary they become.</p>\n\n<p>I am purposely not bothering to acknowledge any tinfoil-hat fringe cases regarding premature-terminating substrings like:</p>\n\n<ul>\n<li><code>/* arithmetic symbols include: +-*/ */</code> and</li>\n<li><code><!-- This is a long --> arrow --></code></li>\n</ul>\n\n<p>because these deliberate monkeywrenches are not commonly escaped by slashes and they can be sensibly overcome by recrafting the comment. Such as:</p>\n\n<ul>\n<li><code>/* re-ordered arithmetic symbols include: +-/* */</code> and</li>\n<li><code><!-- I only use short -> arrows in comments--></code></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T23:42:38.793",
"Id": "420486",
"Score": "0",
"body": "On second thought, I think I'll recommend simply using lazy matching with the multiline comment blocks. https://regex101.com/r/27LzpN/2 I'll adjust my answer when I get to my computer again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T02:19:47.520",
"Id": "420495",
"Score": "0",
"body": "that's for all the time you spent on this! I'll take a look in detail when I get a chance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T02:21:26.250",
"Id": "420496",
"Score": "0",
"body": "As I spend my Saturday in the garden, my mind keeps playing out refinements. I'll update and let you know."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T22:59:38.977",
"Id": "217356",
"ParentId": "217203",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "217356",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T13:57:16.243",
"Id": "217203",
"Score": "5",
"Tags": [
"php",
"regex",
"formatting"
],
"Title": "Regex match comments and quotes"
} | 217203 |
<p>I am using Python 3 and pandas 0.24.2 to do some data processing and ETL flows. I have followed this pattern a couple of times and it is really bothering me but I am not sure which direction to go to majorly improve it. Any advice for what to do differently is greatly appreciated. This is a toy example but the logic is the same. The main method is below. How can the structure of the class be improved?</p>
<pre><code>import pandas as pd
from collections import deque
from collections import defaultdict
from collections import namedtuple
from src.query_helper import postgres_query_helper as pgqh
class ComputeNetProfitSummary():
def __init__(self, date=None, factory_id=None):
self.date = date
self.factory_id = factory_id
self.pg_query_helper = pgqh.PostgresQueryHelper()
def build_sql_query(self):
sql_query = f"""Select * FROM factory_table
WHERE date='{self.date}'
AND factory_id={self.factory_id}
"""
return sql_query
def create_orders_df(self):
"""Create orders Data Frame"""
if self.date and self.factory_id:
sql_query = self.build_sql_query()
df = self.pg_query_helper.execute_sql_return_df(sql_query)
return df
def compute_complex_metrics_on_df(self):
"""Some complicated logic using FIFO attribution"""
ComplexData = namedtuple('ComplexData', ['ColumnNamesA', ..., 'ColumnNamesZ'])
all_data = []
for row in self.orders_df.iterrows():
"""Do complicated stuff"""
transform_row = # some computations on row
complex_output = ComplexData(transform_row)
all_data.append(complex_output)
complex_df = pd.DataFrame(all_data)
return complex_df
def compute_summary_statistics(self):
"""Compute summary data"""
summary_data = defaultdict(dict)
# Create summary data, I am fine with this
return summary_data
def compute_summary_data(self):
self.orders_df = self.create_orders_df()
self.complex_df = compute_complex_metrics_on_df()
self.summary_statistics = compute_summary_statistics()
if __name__ == '__main__':
cnp = ComputeNetProfitSummary(date='2019-01-01', factory_id='A')
summary_data = cnp.compute_summary_data()
for key, value in summary_data.items():
print(key)
print(value)
</code></pre>
<p>NOTE: I am one of the only Python developers on my team so I do not get a lot of feedback on this type of code very often. Any feedback or constructive criticism is welcome, from design patterns to PEP8.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T14:01:09.107",
"Id": "217205",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"pandas"
],
"Title": "Feedback on Object-Oriented ETL Class Structure for Computing Profit Summary Data"
} | 217205 |
<h1>Context</h1>
<p>I am trying to get some practice with Django and Django REST framework.<br>
As a toy example I want to set up a server to which I can POST results of automated test runs.<br>
In the simplest version, a test result contains the following information:</p>
<ul>
<li>a testcase id, which is unique and will never change</li>
<li>a testcase name, which might change from time to time </li>
<li>a verdict, which may only take one of the predefined values "PASS", "FAIL" or "SKIPPED"</li>
</ul>
<p>I came up with three different possible solutions. Each one is working, but I am not sure which one is the best approach since I am lacking experience.</p>
<h1>Expected behavior</h1>
<p>The implementation should fulfill the following requirements:</p>
<ul>
<li>POST request containing any other verdict than PASS, FAIL or SKIPPED -> HTTP 400</li>
<li>POST request with a new and yet unused testcase id -> create and use new testcase instance</li>
<li>POST request with an existing testcase id but different testcase name-> retrieve existing testcase instance for this id and update the name in the database</li>
<li>GET request -> return list of all test results with testcase id, testcase name and verdict</li>
</ul>
<h1>Django Models</h1>
<p>For the models I have the following code:</p>
<p>models.py:</p>
<pre class="lang-py prettyprint-override"><code>from django.db import models
class Testcase(models.Model):
uid = models.CharField(max_length=10, unique=True)
name = models.CharField(max_length=50)
def __str__(self):
return f"{self.uid:<10} {self.name:<50}"
class Verdict(models.Model):
value = models.CharField(max_length=10, unique=True)
def __str__(self):
return f"{self.value:>10}"
class Testresult(models.Model):
testcase = models.ForeignKey(Testcase, related_name='results', on_delete=models.CASCADE) # many-to-one
verdict = models.ForeignKey(Verdict, on_delete=models.CASCADE) # many-to-one
def __str__(self):
return f"{self.testcase}: {self.verdict}"
</code></pre>
<hr>
<h1>Take One: use base ModelSerializers and let the ViewSet handle create()</h1>
<p>views.py:</p>
<pre class="lang-py prettyprint-override"><code>from rest_framework import viewsets, status
from rest_framework.response import Response
from .models import Testresult, Testcase, Verdict
from .serializers import StandardTestresultSerializer
class CustomTestresultViewSet(viewsets.ModelViewSet):
queryset = Testresult.objects.all()
serializer_class = StandardTestresultSerializer
def create(self, request, *args, **kwargs):
try:
verdict = Verdict.objects.get(value=request.data["verdict.value"])
except (Verdict.DoesNotExist, KeyError):
return Response(status=status.HTTP_400_BAD_REQUEST)
testcase = self._create_or_update_testcase(request)
testresult = Testresult.objects.create(verdict=verdict, testcase=testcase)
return Response(StandardTestresultSerializer(testresult).data)
def _create_or_update_testcase(self, request):
uid = request.data.get("testcase.uid")
name = request.data.get("testcase.name")
try:
testcase = Testcase.objects.get(uid=uid)
if testcase.name != name:
testcase.name = name
testcase.save()
except Testcase.DoesNotExist:
testcase = Testcase.objects.create(**request.data["testcase"])
return testcase
</code></pre>
<p>serializers.py:</p>
<pre class="lang-py prettyprint-override"><code>from rest_framework import serializers
from .models import Testresult, Verdict, Testcase
class StandardVerdictSerializer(serializers.ModelSerializer):
class Meta:
model = Verdict
fields = ('value',)
class StandardTestcaseSerializer(serializers.ModelSerializer):
class Meta:
model = Testcase
fields = ('uid', 'name')
class StandardTestresultSerializer(serializers.ModelSerializer):
testcase = StandardTestcaseSerializer()
verdict = StandardVerdictSerializer()
class Meta:
model = Testresult
fields = ('testcase', 'verdict')
</code></pre>
<h3>What I like about this approach</h3>
<p>The logic for looking up / creating / updating Verdict and Testcase instances and returning error statiuses lives in the View class.
From what I've understood so far, serializers are not really intended to use as a way to retrieve already existing instances.</p>
<h3>What I don't like</h3>
<p>Input validation which for Verdict and Testcase is bypassed, what would normally be done by the serializers. This is currently not too much of a problem, but if (for example) the Verdict model gets a new field <code>date</code> this could become more important.</p>
<hr>
<h1>Take Two: Using a simple View class and more complex Serializers classes</h1>
<p>views.py:</p>
<pre class="lang-py prettyprint-override"><code>class StandardTestresultViewSet(viewsets.ModelViewSet):
queryset = Testresult.objects.all()
serializer_class = UnvalidatedTestresultSerializer
</code></pre>
<p>serializers.py:</p>
<pre class="lang-py prettyprint-override"><code>class UnvalidatedVerdictSerializer(serializers.ModelSerializer):
class Meta:
model = Verdict
fields = ('value',)
extra_kwargs = {
'value': {'validators': []}
}
def create(self, validated_data):
try:
return Verdict.objects.get(**validated_data)
except ObjectDoesNotExist:
raise serializers.ValidationError(detail="Unknown result value", code=status.HTTP_400_BAD_REQUEST)
class UnvalidatedTestcaseSerializer(serializers.ModelSerializer):
class Meta:
model = Testcase
fields = ('uid', 'name')
extra_kwargs = {
'uid': {'validators': []}
}
def create(self, validated_data):
uid = validated_data.get('uid')
name = validated_data.get('name')
try:
testcase = Testcase.objects.get(uid=uid)
if testcase.name != name:
testcase.name = name
testcase.save()
except ObjectDoesNotExist:
testcase = Testcase.objects.create(**validated_data)
return testcase
class UnvalidatedTestresultSerializer(serializers.ModelSerializer):
testcase = UnvalidatedTestcaseSerializer()
verdict = UnvalidatedVerdictSerializer()
class Meta:
model = Testresult
fields = ('testcase', 'verdict')
def create(self, validated_data):
verdict_data = validated_data.pop('verdict')
serialized_verdict = UnvalidatedVerdictSerializer(data=verdict_data)
serialized_verdict.is_valid(raise_exception=True)
verdict_instance = serialized_verdict.save()
testcase_data = validated_data.pop('testcase')
serialized_testcase = UnvalidatedTestcaseSerializer(data=testcase_data)
serialized_testcase.is_valid(raise_exception=True)
testcase_instance = serialized_testcase.save()
return Testresult.objects.create(testcase=testcase_instance, verdict=verdict_instance)
</code></pre>
<h3>What I like</h3>
<p>Validation mechanisms of ModelSerializer can be utilized.</p>
<h3>What I don't like</h3>
<p><code>create</code> methods don't actually create Model instances but merely retrieve and udpate them if necessary.<br>
GET requests will also be using the "Unvalidated" serializers, which I don't see as a problem right now, but maybe that is also not a good practice?</p>
<hr>
<h1>Take Three: combining both approaches and select the serializer class to use depending on the request method</h1>
<p>In this approach the same serializer classes as shown in Take One and Take Two will be used, so I'm only giving the code for the View class.</p>
<p>views.py:</p>
<pre class="lang-py prettyprint-override"><code>class DynamicTestresultViewSet(viewsets.ModelViewSet):
queryset = Testresult.objects.all()
def get_serializer_class(self):
if self.request.method == "POST":
return UnvalidatedTestresultSerializer
else:
return StandardTestresultSerializer
</code></pre>
<h3>What I like</h3>
<p>Serializers are used to parse and validate the input data of the request. GET requests will be served using the "normal" serializer.</p>
<h3>What I don't like</h3>
<p>Requires six serializer classes instead of three.</p>
<hr>
<p>What approach would you suggest, or would you do it entirely different?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T17:46:39.177",
"Id": "217214",
"Score": "2",
"Tags": [
"python",
"django"
],
"Title": "Django Restframework: Writable nested serializer with custom behavior"
} | 217214 |
<p>This is based off the popular Pokemon Turn Based project (<a href="https://www.reddit.com/r/beginnerprojects/comments/1aw0iq/project_turn_based_pokemon_style_game/" rel="nofollow noreferrer">here</a>). </p>
<blockquote>
<h2>GOAL</h2>
<p>Write a simple game that allows the user and the computer to take
turns selecting moves to use against each other. Both the computer and
the player should start out at the same amount of health (such as
100), and should be able to choose between the three moves:</p>
<ul>
<li><p>The first move should do moderate damage and has a small range (such as 18-25).</p></li>
<li><p>The second move should have a large range of damage and can deal high or low damage (such as 10-35).</p></li>
<li><p>The third move should heal whoever casts it a moderate amount, similar to the first move.</p></li>
</ul>
<p>After each move, a message should be printed out that tells the user
what just happened, and how much health the user and computer have.
Once the user or the computer's health reaches 0, the game should end.</p>
<h3>SUBGOALS</h3>
<ul>
<li><p>When someone is defeated, make sure the game prints out that their health has reached 0, and not a negative number.</p></li>
<li><p>When the computer's health reaches a set amount (such as 35%), increase it's chance to cast heal.</p></li>
<li><p>Give each move a name.</p></li>
</ul>
</blockquote>
<p>I am new to Python and I am trying to use OOP. Did I use my classes properly and is there a way to reduce the number of if statements in my code? Since this is my first code review, how is the formatting, number of comments, etc? </p>
<pre><code>import random
class Pokemon:
"""Blueprint for turn based Pokemon battle"""
def __init__(self, attack_choice):
self.__attack_choice = attack_choice
def attack(self):
if self.__attack_choice == 1:
attack_points = random.randint(18,25)
return attack_points
elif self.__attack_choice == 2:
attack_points = random.randint(10,35)
return attack_points
else:
print("That is not a selection. You lost your turn!")
def heal(self):
heal_points = random.randint(18,25)
return heal_points
###########################################################################
user_health = 100
mew_health = 100
battle_continue = True
while battle_continue == True:
print("\nATTACK CHOICES\n1. Close range attack\n2. Far range attack\n3. Heal")
attack_choice = eval(input("\nSelect an attack: "))
# Mew selects an attack, but focuses on attacking if health is full.
if mew_health == 100:
mew_choice = random.randint(1,2)
else:
mew_choice = random.randint(1,3)
mew = Pokemon(mew_choice)
user_pokemon = Pokemon(attack_choice)
# Attacks by user and Mew are done simultaneously.
if attack_choice == 1 or attack_choice == 2:
damage_to_mew = user_pokemon.attack()
heal_self = 0
print("You dealt",damage_to_mew,"damage.")
if mew_choice == 1 or mew_choice ==2:
damage_to_user = mew.attack()
heal_mew = 0
print("Mew dealt", damage_to_user, "damage.")
if attack_choice == 3:
heal_self = user_pokemon.heal()
damage_to_mew = 0
print("You healed",heal_self,"health points.")
if mew_choice == 3:
heal_mew = mew.heal()
damage_to_user = 0
print("Mew healed", heal_mew, "health points.")
user_health = user_health - damage_to_user + heal_self
mew_health = mew_health - damage_to_mew + heal_mew
# Pokemon health points are limited by a min of 0 and a max of 100.
if user_health > 100:
user_health = 100
elif user_health <= 0:
user_health = 0
battle_continue = False
if mew_health > 100:
mew_health = 100
elif mew_health <= 0:
mew_health = 0
battle_continue = False
print("Your current health is", user_health)
print("Mew's current health is", mew_health)
print("Your final health is", user_health)
print("Mew's final health is", mew_health)
if user_health < mew_health:
print("\nYou lost! Better luck next time!")
else:
print("\nYou won against Mew!")
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T20:55:19.317",
"Id": "420170",
"Score": "4",
"body": "Welcome to Code Review! I hope you get some great answers. Please include a (possible shortened) description of the task you want to accomplish in case the external description is somehow no longer available."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T22:48:39.810",
"Id": "420177",
"Score": "0",
"body": "I suspect you have a typo, as the code presented doesn't follow the spec: `heal_points = random.randint(18,35)` does not have the same range as attack option one, topping out at 35 instead of 25"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T23:30:29.253",
"Id": "420179",
"Score": "0",
"body": "OOP, as it is typically practiced in languages like C# and Java, is not strongly encouraged in Python. Python's late binding on all names (include modules, classes, and unattached methods) negates many of the benefits of pervasive object use in other languages. More procedurally or functionally minded approaches are more common and often (or maybe usually) simpler."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T04:53:11.387",
"Id": "420199",
"Score": "0",
"body": "Have you checked [Pokemon Showdown's server code](https://github.com/Zarel/Pokemon-Showdown)? In particular how various things are structured."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T13:44:13.067",
"Id": "420267",
"Score": "0",
"body": "@Voile I will take a look at the server code. I am still new to programming and Github in general so code is fairly foreign to me. Is there something specific that you would like me to look at?"
}
] | [
{
"body": "<p>The <code>heal</code> method and the handling of health points strike me as odd. In the current setup,</p>\n\n<ul>\n<li><p><code>heal</code> does not heal; it simply returns a random number. It also currently has no direct relation to any part of the Pokemon class, so it doesn't really make sense as a method of the class. </p></li>\n<li><p>The health points of each Pokemon are \"loose\" in the script, along with instances of the Pokemon class. You have a Pokemon class representing a Pokemon, and it makes sense that health would be an attribute of a Pokemon itself.</p></li>\n</ul>\n\n<p>The design can be improved by doing something like (stripped down):</p>\n\n<pre><code>class Pokemon:\n def __init__(self, start_health):\n self.hp = start_health\n\n def heal(self, heal_amount):\n self.hp += heal_amount\n\n def hurt(self, damage):\n self.hp -= damage\n</code></pre>\n\n<p>Now, you can do something like:</p>\n\n<pre><code>mew = Pokemon(100)\nmew.hurt(50) # Ow\nmew.heal(49) # Back to almost full\nprint(mew.hp) # Prints 99\n</code></pre>\n\n<p>And you don't need to have loose health values floating around in the code for each Pokemon in use. Using the method like this also lets you check the health after healing to ensure that you didn't exceed the maximum health allowed. As long as you're going to make use of a class, you can benefit by having it encapsulate all the data (like health) that's directly relevant to it.</p>\n\n<p>I also decided to not have <code>heal</code> generate the random amount to heal for the following reasons:</p>\n\n<ul>\n<li><p>Are you <em>sure</em> that every time you want to heal you want it to be a random value, and are you sure you will always want it to be a random value in the range (10, 25]? As you mentioned, what about potions? Are you sure you want potion healing to be random, and always in that range? What about when Pokemon level up and have more health? Are you sure that you'll only want to heal them in that narrow range? The <code>Pokemon</code> class simply does not have enough information to always decide how much Pokemon should be healed by, and that shouldn't be its responsibility in the first place anyways. </p></li>\n<li><p>Using random data complicates testing. Say you want to add tests to ensure the correctness of the <code>hurt</code> and <code>heal</code> methods. You would expect this to always pass:</p>\n\n<pre><code>start_health = 100\npoke = Pokemon(start_health)\npoke.hurt(50)\npoke.heal(50)\n\n# A simplified test\nprint(\"Test Passed?\", poke.hp == start_health)\n</code></pre>\n\n<p>If the methods are correct, you would expect this test to always pass. With random data though, your tests can't be as definitive. You may know that it was hurt by some value, then healed by some value, but that isn't enough information to ensure correct functionality (unless you're only testing that it produces results in a certain range).</p>\n\n<p>For small toy projects like this, testing isn't really necessary (although it's always good to practice). When you start dealing with larger projects split across multiple files, written by multiple people, and changing code that you haven't looked at in potentially months, you need tests to ensure that code stays correct from one change to the next. Making testing easier helps ensure the validity of the tests, and prevents you from wasting your time trying to Jerry-rig some test in place after the fact. </p></li>\n</ul>\n\n<p>If some code wants to hurt the Pokemon by a random amount, they can generate the random data themselves to pass in to <code>hurt</code>.</p>\n\n<hr>\n\n<p><code>while battle_continue == True:</code> has a redundant condition. <code>while</code> (and <code>if</code>) just check if their condition is truthy. You can just write:</p>\n\n<pre><code>while battle_continue:\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T15:20:13.453",
"Id": "420284",
"Score": "0",
"body": "Thanks for your response. Could you help me clarify what you mean by the issues caused by the random values for `heal`? Would there be a constant value for healing? Like how potions work?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T15:25:06.347",
"Id": "420285",
"Score": "3",
"body": "@citruslipbalm What if, in the future, you wanted to add different healing moves or items that healed for different amounts? Or that healed for a constant amount. `Pokemon.heal` shouldn't decide how much to heal for, it should take an argument and add that amount to the health, then moves or items that heal can specify how much they heal by, and you can, for example, use `Pokemon.heal(potion.get_heal_amount)`. `get_heal_amount` can then return a constant number, or generate a random number within a range, or get its data elsewhere."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T16:32:08.353",
"Id": "420292",
"Score": "0",
"body": "@citruslipbalm On top of Skidsdev's points, see my new section at the bottom of the answer that elaborates."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T09:54:01.793",
"Id": "420392",
"Score": "0",
"body": "I would never use ``heal(-damage)``. The method name does not allow for this. I would rather insert ``assert heal_amount >= 0``. The alternative would be to use a ``change_health`` method (possibly called from ``heal`` and ``hurt``)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T14:04:33.170",
"Id": "420422",
"Score": "1",
"body": "@allo Ya, I'm not sure why I added that originally. Removed."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T22:02:46.367",
"Id": "217226",
"ParentId": "217222",
"Score": "14"
}
},
{
"body": "<p>You have chosen a great problem to begin with, however there are a few things you get wrong about OOP. OOP is not simply about using a class for \"everything\", it's a kind of way to think about a problem.</p>\n\n<p>To begin with, it helped me a lot to think about a class as a prototype of a \"thing\". In your case the \"thing\" would be a Pokemon. A Pokemon can do certain things. In your simplified versions that would be 1. attack another Pokemon and 2. heal itself. Often these actions are reflected in the classes's methods. I think you mostly understood that. What else is there about the Pokemon/\"thing\" it has certain properties that describe it. I would say that's an aspect you did not think about. A property could be name, color, ... or it's health status. We also learn that the health can only be between <code>0</code> and <code>100</code>.</p>\n\n<p>So with this on our mind, let's think of a new design for <code>class Pokemon</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class Pokemon:\n \"\"\"Blueprint for a new pokemon\"\"\"\n\n def __init__(self):\n self._health = 100\n # ^--- the leading _ is a convention to mark internal values\n\n @property\n def health(self):\n \"\"\"The health of the Pokemon which is between 0 and 100\"\"\"\n return self._health\n\n @health.setter\n def health(self, new_health):\n \"\"\"Set the new heath value\"\"\"\n # here the health limits are enforced\n self._health = min(100, max(0, new_health))\n\n def attack(self, other, choice):\n \"\"\"Attack another Pokemon with the chosen attack (1 or 2)\n\n This function also returns the raw amount of random damage dealt. The\n amount of damage dealt depends on the attack type.\n \"\"\"\n if choice == 1:\n attack_points = random.randint(18, 25)\n elif choice == 2:\n attack_points = random.randint(10, 35)\n else:\n print(\"That is not a selection. You lost your turn!\")\n attack_points = 0\n other.health -= attack_points\n return attack_points\n\n def heal(self):\n \"\"\"Heal the Pokemon\"\"\"\n heal_points = random.randint(18, 35)\n self.health += heal_points\n return heal_points\n</code></pre>\n\n<p>A lot of this should look familiar to you, since the main work is still done by the code you've written. What is new that the Pokemon now has health. If your unfamiliar with properties in Python just think of them as synthatic sugar on what would normally be done using getter and setter functions in other languages. There is a great <a href=\"https://stackoverflow.com/a/36943813/5682996\">SO post</a> with a nice explanation on properties. In addition to that, <code>attack</code> and <code>heal</code> now handle the update of the health value for the Pokemon, as well as the opponent. This allows us to write up a simple battle in a very concise way:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>mew = Pokemon()\nuser = Pokemon()\nmew.attack(user, 1)\nprint(f\"User health after attack: {user.health}\")\nuser.heal()\nprint(f\"User health after heal: {user.health}\")\nmew.heal() # health should still only be 100\nprint(f\"Mew's health after 'illegal' heal: {user.health}\")\n</code></pre>\n\n<p>which prints for example:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>User health after attack: 75\nUser health after heal: 100\nMew's health after 'illegal' heal: 100\n</code></pre>\n\n<p>No additional variables that need to track health status, no checking on the health limits. Everything is nicely encapsulated into the <code>Pokemon</code> class. As <a href=\"https://codereview.stackexchange.com/users/197357/\">DaveMongoose</a> pointed out in his comment, a drawback of this approach is that the Pokemon can not be defeated as long as it heals after an attack, no matter how much damage it took.</p>\n\n<hr>\n\n<p><strong>Short break on style and other conventions</strong><br/>\nAnother thing that has changed in contrast to your solution is the documentation I added to each function. Python has an \"official\" <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">Style Guide</a> (which is worth a read on its own) with a section on how to write these so called <em>docstrings</em> <a href=\"https://www.python.org/dev/peps/pep-0008/#documentation-strings\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>It also features <a href=\"https://www.python.org/dev/peps/pep-0008/#blank-lines\" rel=\"nofollow noreferrer\">guidelines</a> on where to use blank lines and where not to use them. In my oppinion the excessive use of blank lines in your code hinders readability more than it does help to structure the code.</p>\n\n<p>I also used only a single leading underscore for my internal value instead of two as you did. The Style Guide also has you covered on <a href=\"https://www.python.org/dev/peps/pep-0008/#method-names-and-instance-variables\" rel=\"nofollow noreferrer\">this topic</a>. In general you should always use a single leading underscore to mark functions and variables/members as internal. For more details on what happens if you use two leading underscores, follow the link above.</p>\n\n<hr>\n\n<p>After that short intermezzo, let's look on how the battle simulation looks with the new class:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def battle_simulation():\n \"\"\"Run a simple interactive Pokemon battle simulation\"\"\"\n mew = Pokemon()\n user_pokemon = Pokemon()\n while True:\n print(\"\\nATTACK CHOICES\\n1. Close range attack\\n2. Far range attack\\n3. Heal\")\n attack_choice = int(input(\"\\nSelect an attack: \"))\n # DON'T use eval on user input, this can be dangerous!\n\n # Mew selects an attack, but focuses on attacking if health is full.\n mew_choice = random.randint(1, 2 if mew.health == 100 else 3)\n # this is your original distinction just condensed into a single line\n\n # Attacks by user and Mew are done simultaneously\n # with the changes to Pokemon, there is no need to save all the\n # intermediate damage/heal values -> nice and short code\n if attack_choice != 3:\n print(f\"You dealt {user_pokemon.attack(mew, attack_choice)} damage.\")\n\n if mew_choice != 3:\n print(f\"Mew dealt {mew.attack(user_pokemon, mew_choice)} damage.\")\n\n if attack_choice == 3:\n print(f\"You healed {user_pokemon.heal()} health points.\")\n\n if mew_choice == 3:\n print(f\"Mew healed {mew.heal()} health points.\")\n\n if mew.health == 0 or user_pokemon.health == 0:\n break\n\n print(f\"Your current health is {user_pokemon.health}\")\n print(f\"Mew's current health is {mew.health}\")\n\n print(f\"Your final health is {user_pokemon.health}\")\n print(f\"Mew's final health is {mew.health}\")\n\n if user_pokemon.health < mew.health:\n print(\"\\nYou lost! Better luck next time!\")\n else:\n print(\"\\nYou won against Mew!\")\n\n\nif __name__ == \"__main__\":\n battle_simulation()\n</code></pre>\n\n<p>As you can see, we got rid of all the variables needed to store damage and heal values since everything is no done internally in the <code>Pokemon</code> class. With this, the code becomes quite a bit shorter, clearer and easier to read. Cool, isn't it?</p>\n\n<p>A thing you will see me use quite often are the so called f-strings. They take arbitrary Python expressions (function calls, variables, ...) and allow to incorporate them into a formatted string. If you want to know more about them, I would recommend <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\">this</a> blog post.</p>\n\n<p>Happy Coding!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T16:38:29.660",
"Id": "420294",
"Score": "0",
"body": "An excellent answer, but there's a possibly unwanted side effect of how you're constraining health in the setter and resolving healing after damage - it's impossible for either player to lose on a turn when they heal.\n\nIt might be best to allow health to exceed the limits during a turn and then constrain it at the end - this way healing and damage are effectively resolved at the same time, and it would still be possible for one side to lose because the damage exceeded their healing + remaining health."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T17:42:23.720",
"Id": "420304",
"Score": "0",
"body": "Excellent catch. I will add a note that this is something one would have to consider."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T17:23:25.433",
"Id": "420943",
"Score": "0",
"body": "Thanks for the resources and improvements. Is there a way to avoid a simultaneous attack? Considering that this is more turn based, is there a way that I can the User can go first, see damage on Mew then Mew does its attack? Would I have to consider subclasses for this to work?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T17:55:12.503",
"Id": "420947",
"Score": "1",
"body": "I see no need for subclasses here. You would have to rearrange the `if`s and check if Mew is down to 0 health before allowing it to attack. Then after Mew's attack check if the player is down to 0 before going to the next round."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T22:25:05.963",
"Id": "217227",
"ParentId": "217222",
"Score": "7"
}
},
{
"body": "<p>Hello and welcome to CodeReview. Congratulations on writing code that is well-formatted and compliant with the basics of the generally-agreed-upon Python coding style. </p>\n\n<p>You have made some errors in organization and structure, however. Let's look at those first:</p>\n\n<h2>Organization & Structure</h2>\n\n<h3>Organization</h3>\n\n<p>Your code is \"against the wall.\" This means that if I import your module, the code is going to be run, not just loaded. That's bad because it means you can't import it into the python command line REPL to play around with it, and you can load it into a debugger or a test framework.</p>\n\n<p>The basic solution is to find all your \"left-edge\" statements, like these:</p>\n\n<pre><code>user_health = 100\nmew_health = 100\nbattle_continue = True\n\nwhile battle_continue == True:\n</code></pre>\n\n<p>And move them into a function. Call it <code>main</code> until you have a better name (if you have a lot of code you might break it into more than one function, but <code>main</code> is a good place to start!). Then at the bottom of your module, do:</p>\n\n<pre><code>if __name__ == '__main__:\n main()\n</code></pre>\n\n<p>That \"hook\" means that if you run <code>python myfile.py</code> the code will run and the game will play, but if you start the REPL using just <code>python</code> and then type <code>>>> from myfile import *</code> you will have all the functions available and can call them to see what they do in different circumstances. And it also means you can use one of the many Python unit testing frameworks to check your code.</p>\n\n<h3>Structure</h3>\n\n<p>You have one class, and you don't really use it. The class is syntactically correct, but you aren't treating it as a class because you don't \"trust\" it. You're still treating it as a collection of functions that you can call.</p>\n\n<p>Let's look at the first part of the problem statement. It's nice and small, so let's just play a game of <strong>find the nouns</strong> and see if that gives us any ideas about objects:</p>\n\n<blockquote>\n <p>Write a <strong>simple game</strong> that allows the <strong>user</strong> and the <strong>computer</strong> to take\n <strong>turns</strong> selecting <strong>moves</strong> to use against each other. Both the computer and\n the player should start out at the same amount of <strong>health</strong> (such as\n 100), and should be able to choose between the three moves:</p>\n \n <ul>\n <li><p>The first move should do moderate <strong>damage</strong> and has a small <strong>range</strong> (such as 18-25).</p></li>\n <li><p>The second move should have a large range of damage and can deal high or low damage (such as 10-35).</p></li>\n <li><p>The third move should <strong>heal</strong> whoever casts it a moderate amount, similar to the first move.</p></li>\n </ul>\n \n <p>After each move, a <strong>message</strong> should be printed out that tells the user\n what just happened, and how much health the user and computer have.\n Once the user or the computer's health reaches 0, the game should end.</p>\n</blockquote>\n\n<p>(I flagged \"heal\" as a noun because it's really the opposite of \"damage\".)</p>\n\n<p>The general rule for OOP is that objects are nouns and methods are verbs. So our set of potential objects includes:</p>\n\n<ol>\n<li>Game</li>\n<li>User</li>\n<li>Computer</li>\n<li>Turn</li>\n<li>Move</li>\n<li>Health</li>\n<li>Damage</li>\n<li>Range</li>\n<li>Heal</li>\n<li>Message</li>\n</ol>\n\n<p>With those in mind, it seems like User and Computer are likely to be either different parts (methods or functions) of the Game object, or they will be two different implementations of a Player interface (or subclasses of a Player class). </p>\n\n<p>The Turn might be an object, but it seems more likely that \"take turns\" is a verb on the Game. A Move seems <em>very</em> likely to be an object, since there are so many details and requirements about them. </p>\n\n<p>Health seems like an attribute, since we get a starting number provided, and both Heal and Damage both seem like verbs affecting health more than separate attributes or objects. The Range seems like an attribute of the various Move objects, but an internal attribute - when you invoke a move, it will adjust a player's health by some internally-computed amount.</p>\n\n<p>Message is probably just a string. It's an object, but of a type that comes built-in. There is one key question, though: are turns sequential or simultaneous? If turns are sequential, messages can just be printed as they happen. If turns are simultaneous, messages might have to be computed after the results of both moves are understood. (What happens if both players kill each other during the same turn?)</p>\n\n<h2>Pro-Tips</h2>\n\n<h3>Move class</h3>\n\n<p>Having <code>Move</code> as a class would be an example of the <a href=\"https://en.wikipedia.org/wiki/Command_pattern\" rel=\"noreferrer\"><strong>Command</strong> pattern</a>, and might look something like this:</p>\n\n<pre><code>from abc import ABC, abstractmethod\n\nclass Move(ABC):\n ''' Abstract game move. (Command pattern.) Perform an action when\n invoked.\n '''\n def __init__(self, name):\n self.name = name\n\n @abstractmethod\n def execute(self, us: 'Player', them: 'Player') -> str:\n ''' Perform an operation like damaging them, or healing us. '''\n return f\"{us.name} uses {self.name}! It's super effective!\"\n</code></pre>\n\n<p>(Note: You could also construct the Move objects with the us/them attributes configured during <code>__init__</code>, instead of passed as parameters.)</p>\n\n<h3>Random choices</h3>\n\n<p>You should eliminate all uses of <code>if</code> that involve random choices. You are randomly choosing a move: use a list or tuple of Move objects and compute the index of the object, then pass that object around. You are randomly generating damage or healing: compute the number, then apply that number to the appropriate player health attribute. The only <code>if</code> statement you need is to guard against going above or below the maximum or minimum health values (and those aren't random)!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T22:34:54.530",
"Id": "420175",
"Score": "0",
"body": "Interesting idea. Would have never thought of this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T00:21:49.773",
"Id": "420188",
"Score": "2",
"body": "TIL \"code is against the wall\" = a lot of left-adjusted statements / scripting"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T23:42:45.920",
"Id": "420337",
"Score": "0",
"body": "\"This means that if I import your module, the code is going to be run, not just loaded\" Hard disagree that this is a bad thing. If I write a module that executes some stuff, I would imagine it's not to be imported, or it's doing some necessary set up. If I find that I want to import it for some reason, I refactor the portion that I want to import into its own module, and import that. Adding 4 spaces of indentation to protect people importing something ridiculous is an anti-pattern in my opinion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T17:27:53.087",
"Id": "420945",
"Score": "0",
"body": "Thank you for your response. I wanted to answer your comment re: if the attacks are simultaneous or turn based/random. If I wanted more turn based, are subclasses more appropriate? The way I am currently seeing it is assigning the user or Mew 1 or 2 and have a random number generated which will activate the appropriate subclass. Please let me know if I am totally off with this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T21:34:10.257",
"Id": "420964",
"Score": "0",
"body": "Subclasses are orthogonal to messages. But what subclasses would you assign?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T19:13:17.300",
"Id": "421223",
"Score": "0",
"body": "@AustinHastings I might be confusing myself here. I was trying to make a connection with your comment regarding subclasses. Could you help me clarify?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T21:31:53.010",
"Id": "421232",
"Score": "0",
"body": "@citruslipbalm there are two places I see for subclasses, (1) if you create a Player class and subclass \"human\" and \"computer\" versions; (2) if you create a Move class and subclass the various move types. Note that (2) may not be required, if you can fit damage and healing into the same structure. I also suggest that messages might need to be a *class* rather than just `str`, but see my comment above - I don't think it's really needed."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T22:31:08.377",
"Id": "217229",
"ParentId": "217222",
"Score": "12"
}
}
] | {
"AcceptedAnswerId": "217227",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T20:43:18.723",
"Id": "217222",
"Score": "12",
"Tags": [
"python",
"beginner",
"python-3.x",
"battle-simulation",
"pokemon"
],
"Title": "Pokemon Turn Based battle (Python)"
} | 217222 |
<p>In an Ionic App a user can open a new browser via "inAppBrowser". I'm trying to get the stats of the user before they go into to the inAppBrowser, get the stats again when browser closes, and then run a function to compare the before and after. </p>
<p>What I have right now is working but I feel like I'm not doing it the proper RXJS way and I want to make sure I do this right. Is this a case for using MergeMap or is that making it needlessly complicated? Do I need to worry about possible race conditions?</p>
<p>Code Snippet:</p>
<pre><code>let previousStats = []
this.reloadStats(user)
.pipe(
first(), // getting only the first because I dont want this to update
tap(val => {
previousStats = val //setting the stats before the user leaves
})
)
.subscribe()
const browser = this.inAppBrowser.create(user.url) //user opens a browser
this.subscriptionUserUrl = browser.on('exit') // user closes the browser
.switchMap(() => this.reloadStats(user)) // get the most latest stats
.subscribe(currentStats =>{
this.handleBrowserExit(previousStats, currentStats) // do the comparison
})
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T21:04:59.537",
"Id": "217224",
"Score": "1",
"Tags": [
"typescript",
"observer-pattern",
"rxjs"
],
"Title": "RXJS and Ionic- Sequencial Subscriptions Waiting on User Action"
} | 217224 |
<p>I wrote a generator class which implements Fast Poisson Disk Sampling algorithm in Python. I did some optimizations like, <code>x ** 2 -> x * x</code>, using unpacking instead of indexing, move unpacking outside of loops and precalculating of constants (like <code>2 * pi</code>), but still not very pleased with results. Is it possible to speed up it even more?</p>
<pre><code>import math
import random
class PoissonDiskGenerator(object):
def __init__(self, field, r, k=30):
self.field_x, self.field_y = field
self.cell_size = math.ceil(r / math.sqrt(2))
self.grid_size_x, self.grid_size_y = math.ceil(field[0] / self.cell_size), math.ceil(field[1] / self.cell_size)
self.samples_grid = [
[None for y in range(math.ceil(self.field_x / self.cell_size))]
for x in range(math.ceil(self.field_y / self.cell_size))
]
x = random.uniform(0, field[0]), random.uniform(0, field[1])
self.points = [x]
self.active_indices = [0]
self.active_iter = 1
self.tries = k
self.radius = r
self.radius2 = 2 * r
self.pi2 = 2 * math.pi
def __iter__(self):
return self
def __next__(self):
if self.active_indices:
point = self.try_place_new_point()
while not point and self.active_indices:
point = self.try_place_new_point()
if not point:
raise StopIteration
return point
else:
raise StopIteration
def try_place_new_point(self):
ref_ind = random.choice(self.active_indices)
for i in range(self.tries):
point_x, point_y = self.pick_point(self.points[ref_ind])
grid_x, grid_y = math.floor(point_x / self.cell_size), math.floor(point_y / self.cell_size)
neighbor_list = self.neighbors(grid_x, grid_y)
point_ok = True
if neighbor_list:
for neighbor in neighbor_list:
nb_x, nb_y = neighbor
if (point_x - nb_x) * (point_x - nb_x) + (point_y - nb_y) * (point_y - nb_y) < self.radius * self.radius:
point_ok = False
if point_ok:
self.points.append((point_x, point_y))
self.active_indices.append(self.active_iter)
self.samples_grid[grid_x][grid_y] = self.active_iter
self.active_iter += 1
return point_x, point_y
self.active_indices.remove(ref_ind)
return None
def pick_point(self, ref_point):
ref_x, ref_y = ref_point
while True:
rho, theta = random.uniform(self.radius, self.radius2), random.uniform(0, self.pi2)
pick_x, pick_y = ref_x + rho * math.cos(theta), ref_y + rho * math.sin(theta)
if 0 < pick_x < self.field_x and 0 < pick_y < self.field_y:
return pick_x, pick_y
def grid_to_point(self, grid_x, grid_y):
try:
return self.samples_grid[grid_x][grid_y]
except IndexError:
return None
def neighbors(self, grid_x, grid_y):
neighbors_list = (
self.grid_to_point(grid_x, grid_y),
self.grid_to_point(grid_x, grid_y - 1),
self.grid_to_point(grid_x, grid_y + 1),
self.grid_to_point(grid_x - 1, grid_y),
self.grid_to_point(grid_x - 1, grid_y - 1),
self.grid_to_point(grid_x - 1, grid_y + 1),
self.grid_to_point(grid_x + 1, grid_y),
self.grid_to_point(grid_x + 1, grid_y - 1),
self.grid_to_point(grid_x + 1, grid_y + 1),
self.grid_to_point(grid_x + 2, grid_y + 1),
self.grid_to_point(grid_x + 2, grid_y),
self.grid_to_point(grid_x + 2, grid_y - 1),
self.grid_to_point(grid_x + 1, grid_y + 2),
self.grid_to_point(grid_x, grid_y + 2),
self.grid_to_point(grid_x - 1, grid_y + 2),
self.grid_to_point(grid_x - 2, grid_y + 1),
self.grid_to_point(grid_x - 2, grid_y),
self.grid_to_point(grid_x - 2, grid_y - 1),
self.grid_to_point(grid_x + 1, grid_y - 2),
self.grid_to_point(grid_x, grid_y - 2),
self.grid_to_point(grid_x - 1, grid_y - 2)
)
return (self.points[ngb] for ngb in neighbors_list if ngb is not None)
</code></pre>
<p>Profiling code:</p>
<pre><code>import cProfile
import pstats
def full_gen_run():
size = (15000, 15000)
point_gen = PoissonDiskGenerator(size, 100)
while True:
try:
next(point_gen)
except StopIteration:
break
print(len(point_gen.points))
cProfile.run('full_gen_run()', 'profile_stats')
stats = pstats.Stats('profile_stats')
stats.strip_dirs()
stats.sort_stats('tottime')
stats.print_stats('poissondisk.py:')
</code></pre>
<p>Visualisation code:</p>
<pre><code>import pyglet
import time
from pyglet.window import key
from pyge.poissondisk import PoissonDiskGenerator
class Game(pyglet.window.Window):
SPEED = 10
def __init__(self):
super(Game, self).__init__(1280, 720)
self.size_x = 20000
self.size_y = 20000
self.set_caption(pyglet.version)
self.fps_display = pyglet.window.FPSDisplay(self)
pyglet.clock.schedule_interval(self.update, 1.0 / 60)
self.batch = pyglet.graphics.Batch()
self.viewpos = (self.size_x / 2, self.size_y / 2)
self.zoom = self.size_x / self.height
self.key_state_handler = key.KeyStateHandler()
self.push_handlers(self.key_state_handler)
self.point_gen = PoissonDiskGenerator((self.size_x, self.size_y), 100)
self.start_time = None
self.generation_done = False
def update(self, _):
if not self.generation_done:
if self.start_time is None:
self.start_time = time.perf_counter()
print('Points...')
time_good = True
start_time = time.perf_counter()
while time_good:
time_good = time.perf_counter() - start_time < 0.01
try:
point = next(self.point_gen)
except StopIteration:
self.generation_done = True
end_time = time.perf_counter()
print('OK ({:.2f} ms)'.format((end_time - self.start_time) * 1000))
break
self.batch.add(1, pyglet.gl.GL_POINTS, None, ('v2f', point))
if self.key_state_handler[key.W]:
self.viewpos = (self.viewpos[0], self.viewpos[1] + 10 * self.SPEED)
if self.key_state_handler[key.S]:
self.viewpos = (self.viewpos[0], self.viewpos[1] - 10 * self.SPEED)
if self.key_state_handler[key.A]:
self.viewpos = (self.viewpos[0] - 10 * self.SPEED, self.viewpos[1])
if self.key_state_handler[key.D]:
self.viewpos = (self.viewpos[0] + 10 * self.SPEED, self.viewpos[1])
if self.key_state_handler[key.E]:
self.zoom -= 0.01 * self.SPEED
if self.zoom < 1.0:
self.zoom = 1.0
if self.key_state_handler[key.Q]:
self.zoom += 0.01 * self.SPEED
def on_draw(self):
self.clear()
pyglet.gl.glViewport(0, 0, self.width, self.height)
pyglet.gl.glMatrixMode(pyglet.gl.GL_PROJECTION)
pyglet.gl.glLoadIdentity()
pyglet.gl.glOrtho(self.viewpos[0] - self.width / 2 * self.zoom, self.viewpos[0] + self.width / 2 * self.zoom,
self.viewpos[1] - self.height / 2 * self.zoom, self.viewpos[1] + self.height / 2 * self.zoom,
-1, 1)
pyglet.gl.glMatrixMode(pyglet.gl.GL_MODELVIEW)
self.batch.draw()
self.fps_display.draw()
if __name__ == '__main__':
game = Game()
pyglet.app.run()
</code></pre>
<p><a href="https://i.stack.imgur.com/AhcoC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AhcoC.png" alt="screenshot of visualisation"></a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T23:23:06.377",
"Id": "420178",
"Score": "0",
"body": "What is a typical `r` for testing? Can you post some test code that will exercise this thing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T23:36:55.307",
"Id": "420180",
"Score": "0",
"body": "@Reinderien I test it by calling next() until StopIteration raises, and gather profiling stats using cProfile. This code generate ~14179 points with r=100 and field=(15000, 15000) in about 7 sec. UPD: added code to question"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T23:58:51.997",
"Id": "420183",
"Score": "0",
"body": "OK; but that's profiling, not testing. What kind of tests can you run against the output to ensure that it's correct?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T00:08:03.243",
"Id": "420184",
"Score": "0",
"body": "@Reinderien sorry, I didn't write any tests. I just visualize an output using pyglet."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T00:16:42.223",
"Id": "420186",
"Score": "0",
"body": "Please edit your question to show that code, as well as a screenshot."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T00:39:06.367",
"Id": "420189",
"Score": "1",
"body": "@Reinderien added code and screenshot you requested"
}
] | [
{
"body": "<blockquote>\n <p>Is it possible to speed up it even more?</p>\n</blockquote>\n\n<p>Yes. Use Numpy. It's not really worth thinking about any other micro-optimizations until you've attempted to vectorize this thing with a proper numerical library.</p>\n\n<p>Here's a tutorial on how to start out vectorizing with Numpy:</p>\n\n<p><a href=\"https://www.oreilly.com/library/view/python-for-data/9781449323592/ch04.html\" rel=\"nofollow noreferrer\">https://www.oreilly.com/library/view/python-for-data/9781449323592/ch04.html</a></p>\n\n<p>There are many others.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T23:44:34.780",
"Id": "420181",
"Score": "0",
"body": "Any tips on what I can vectorize in this algorithm?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T23:44:53.130",
"Id": "420182",
"Score": "0",
"body": "Yes; I'm writing up an example"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T04:48:32.110",
"Id": "420198",
"Score": "0",
"body": "As I see after some searching, Fast Poisson Disk algorithm can't be vectorized, because samples cannot be generated independently; each sample depends on the positions of the other samples. I can use sample elimination algorithm, but it's a different problem, that requires research to understand will it be faster or not. Question remains opened."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T11:50:15.783",
"Id": "420236",
"Score": "1",
"body": "@Hadwig: Maybe have a look at [this implementation](https://scipython.com/blog/poisson-disc-sampling-in-python/), it uses at least some `numpy`. Would be interesting to see if it is faster/slower than yours."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T02:00:58.270",
"Id": "420340",
"Score": "1",
"body": "@Graipher This code spend 14.464 sec, while mine 8.158 sec, with same generation parametrs. Problem here - `numpy` `ndarray` work slower than python lists when you simply need to get/set one value many times. They very fast in vector calculations, but here it does not help at all."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T23:11:38.633",
"Id": "217232",
"ParentId": "217231",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T23:06:28.497",
"Id": "217231",
"Score": "2",
"Tags": [
"python",
"performance",
"algorithm",
"random",
"iterator"
],
"Title": "Speed up fast poisson disk sampling generator in Python"
} | 217231 |
<p>Can someone help me to create a generic method that validates common fields/variables comes from multiple objects, if that is possible?</p>
<p>The below code validates some bunch of variables/fields from a schema object, so here the requirement is I have two different schema objects which has common Fields/variables, Is it possible to validate these variables in more generic way. In below code there is two events FI & Profile (Note: Future can be more events like these) these are two different schema objects but has same fields/variables of same Object "Types".</p>
<pre><code>public class RequestValidation {
public void validateRequest(EventRequest eventRequest) {
//FI Event
FIEventProcessorImpl fiEventProcessor = new FIEventProcessorImpl();
FIEventSchema fiEvent = fiEventProcessor.getFiEventSchema(eventRequest);
//Party data Validation
String partyFName = null;
String partyLName = null;
String partyEmail = null;
String partyId = null;
if (null != fiEvent.getParty()) {
partyId = fiEvent.getParty().getPartyId();
if (null != fiEvent.getParty().getPartyName()
&& null != fiEvent.getParty().getPartyName().getName()) {
partyFName = fiEvent.getParty().getPartyName().getName().getGivenName();
partyLName = fiEvent.getParty().getPartyName().getName().getSurname();
if (null == partyFName && null == partyLName) {
Map<String, Object> nameMap = fiEvent.getParty().getPartyName().getName()
.getAdditionalProperties();
if (!nameMap.isEmpty()) {
partyFName = getAdditionalProperty(nameMap, "first_name");
partyLName = getAdditionalProperty(nameMap, "last_name");
}
}
}
if (null != fiEvent.getParty().getPartyEmail()) {
partyEmail = fiEvent.getParty().getPartyEmail().getEmailAddress();
if(null == partyEmail || partyEmail.isEmpty()){
//Logging missing field value logic
}
}
}
if (null == partyFName || partyFName.isEmpty() || null == partyLName || partyLName.isEmpty()
|| null == partyId || partyId.isEmpty()) {
//Logging missing field value logic
}
//Application Context data Validation
String score = null;
String clientId = null;
if(null != fiEvent.getApplicationContext() && null != fiEvent.getApplicationContext().getContextItems()){
List<ContextItem> contextItems = fiEvent.getApplicationContext().getContextItems();
if(null != contextItems && !contextItems.isEmpty()){
socialScore = getContextValue(contextItems, "SCORE");
clientFp = getContextValue(contextItems, "CLIENT_ID");
}
}
if (null == score || score.isEmpty() || null == clientId || clientId.isEmpty()) {
//Logging missing field value logic
}
//ProfileChange Event
ProfileProcessorImpl eventProcessor = new ProfileProcessorImpl();
ProfileEventSchema profileevent = eventProcessor.getProfileEventSchema(eventRequest);
//Party data Validation
if (null != profileevent.getParty()) {
partyId = profileevent.getParty().getPartyId();
if (null != profileevent.getParty().getPartyName()
&& null != profileevent.getParty().getPartyName().getName()) {
partyFName = profileevent.getParty().getPartyName().getName().getGivenName();
partyLName = profileevent.getParty().getPartyName().getName().getSurname();
if (null == partyFName && null == partyLName) {
Map<String, Object> nameMap = profileevent.getParty().getPartyName().getName()
.getAdditionalProperties();
if (!nameMap.isEmpty()) {
partyFName = getAdditionalProperty(nameMap, "first_name");
partyLName = getAdditionalProperty(nameMap, "last_name");
}
}
}
if (null != profileevent.getParty().getPartyEmail()) {
partyEmail = profileevent.getParty().getPartyEmail().getEmailAddress();
if(null == partyEmail || partyEmail.isEmpty()){
//Logging missing field value logic
}
}
}
if (null == partyFName || partyFName.isEmpty() || null == partyLName || partyLName.isEmpty()
|| null == partyId || partyId.isEmpty()) {
//Logging missing field value logic
}
//Application Context data Validation
if(null != profileevent.getApplicationContext() && null != profileevent.getApplicationContext().getContextItems()){
List<ContextItem> contextItems = profileevent.getApplicationContext().getContextItems();
if(null != contextItems && !contextItems.isEmpty()){
socialScore = getContextValue(contextItems, "SCORE");
clientFp = getContextValue(contextItems, "CLIENT_ID");
}
}
if (null == score || score.isEmpty() || null == clientId || clientId.isEmpty()) {
//Logging missing field value logic
}
}
private String getContextValue(List<ContextItem> contextItems, String key) {
String value = null;
for(ContextItem contextItem : contextItems){
if(contextItem.getKey().equalsIgnoreCase(key)){
value = contextItem.getValue();
}
}
return value.toString();
}
private String getAdditionalProperty(Map<String, ?> map, String key) {
Object value = map.get(key);
return value == null ? null : value.toString();
}
}
</code></pre>
| [] | [
{
"body": "<p>It looks like both of the events are validating the same party and context objects. If those are the same type you could make a method to validate the profile, and a method to validate the context object. If the objects are different but you have control over the classes you could make both party objects implement an interface with getters for all of the fields being retrieved. If the objects being retrieved are different you can continue with the same pattern. In my opinion this method would be much easier to read if it was broken up to smaller methods that validate one thing, such as the name of the party.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T16:31:11.077",
"Id": "420441",
"Score": "0",
"body": "Thank you for the suggestion, this helps!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T02:06:14.093",
"Id": "217238",
"ParentId": "217233",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "217238",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T23:26:17.033",
"Id": "217233",
"Score": "1",
"Tags": [
"java"
],
"Title": "Validating variables/fields from a schema object"
} | 217233 |
<p>This is my first program written outside of using books and tutorials. Any help on style and functionality would be helpful.</p>
<pre><code>
import sys
from textwrap import dedent
import os
import random
os.system('CLS')
# board number setup
board = [0,1,2,
3,4,5,
6,7,8]
# Defines the board layout printed to the console
def board_layout():
print(dedent(f'''
*************
* {board[0]} | {board[1]} | {board[2]} *
*-----------*
* {board[3]} | {board[4]} | {board[5]} *
*-----------*
* {board[6]} | {board[7]} | {board[8]} *
*************
'''))
move_count= 0
def main():
while True:
#Prints board layout to console.
board_layout()
#checks for a winner when called at end of each turn
def check_winner():
global move_count
#list of lists with all the winning combinations for from the tic tac toe board
winning_list = [[board[0],board[1],board[2]],[board[3],board[4],board[5],],
[board[6],board[7],board[8]],[board[0],board[4],board[8]],[board[2],board[4],board[6]],
[board[0],board[3],board[6]],[board[1],board[4],board[7]],[board[2],board[5],board[8]]]
#Keeps a reference to winning_list so it is updated at the end of every turn
new_list = winning_list
#iterates over the lists in winning_list
for i,j,k in winning_list:
#looks at the lists in winning_list to determine if a list has all x's for a win
if i == 'x' and j == 'x' and k == 'x' :
print('X wins')
end()
#looks at the lists in winning_list to determine if a list has all o's for a win
elif i == 'o' and j == 'o' and k == 'o' :
print('O wins')
end()
#possible moves is 9 in tic tac toe. If all moves are taken and there is no winner no winner forces a draw.
if move_count == 9:
print('You Tied')
end()
#Takes user input for the move
move =int(input('Please select a spot: '))
print(move)
#Player move, makes sure the spot is not taken and adds 1 to move_count
if board[move] !='x' and board[move] != 'o':
board[move] = 'x'
move_count += 1
check_winner()
#npc move, chooses a random spot that is not taken and adds 1 to move_count
while True:
npc = random.randint(0,8)
if board[npc] != 'o' and board[npc] != 'x':
board[npc] = 'o'
print('Computer chooses spot ', npc)
move_count += 1
check_winner()
break
#If spot is taken prints that the spot is already taken
else:
print('This spot is taken')
#Game ending
def end():
print('Thank you for playing')
sys.exit()
if __name__ == "__main__":
main()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T00:42:05.703",
"Id": "420190",
"Score": "0",
"body": "Welcome to Code Review! I hope you get some great answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T01:17:28.520",
"Id": "420193",
"Score": "0",
"body": "Thank you Phrancis, I'm looking forward to learning from people in the field."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T16:13:12.737",
"Id": "420289",
"Score": "0",
"body": "One possible algorithmic change in `check_winner()` would be checking only those lines where the move has been just made. Not sure, though, if it is an improvement - it would certainly save some effort on checking lines which did not change recently, but it would require additional work on selecting those needing checking. However, in games on bigger boards it will definitely make some gain."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T21:27:45.590",
"Id": "420332",
"Score": "0",
"body": "Welcome to Code Review! I rolled back your last edit. After getting an answer you are [not allowed to change your code anymore](https://codereview.stackexchange.com/help/someone-answers). This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). Refer to [this post](https://codereview.meta.stackexchange.com/a/1765/120114) for more information"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T22:05:46.257",
"Id": "420333",
"Score": "0",
"body": "Thank you for the clarification @Sᴀᴍ Onᴇᴌᴀ. I added it as an answer and explained the changes and mentioned who gave me the suggestions I used."
}
] | [
{
"body": "<p>The function <code>check_winner()</code> does not need <code>global move_count</code>. Using <code>global</code> is code smell, avoid if at all possible, which tends to be always. But in this case it is completely unnecessary, as <code>move_count</code>, like <code>board</code>, is already accessible in <code>check_winner()</code>.</p>\n\n<p><code>winning_list</code> is constructed every time <code>check_winner()</code> is called. It does not persist from one call to the next, so <code>new_list = winning_list</code> and the comment immediately above it should be removed.</p>\n\n<hr>\n\n<p>The statement <code>move = int(input(...))</code> can crash if the user enters invalid input. Even if a valid integer is given, the integer could be outside the valid range, like <code>42</code>, which will cause when <code>board[move]</code> is evaluated. Place user input in a <code>try ... except</code> statement, inside a loop, and don’t let the program continue until valid input has been given.</p>\n\n<hr>\n\n<p>You have a game loop that handles two turns (a move by both players) each pass through the loop. While this does work, it will paint you into a corner in subsequent programs. 3 or more players is going to make writing the game loop much harder.</p>\n\n<p>It is usually simpler to handle one turn (a move by only one player), in each pass through the loop. At the end of the loop, the “current player” is incremented, wrapping around to the first player when necessary. With only 2 players, this alternates between them. More advanced games may require skipping player when a “lose a turn” move is made. Other games may even reverse the direction of play mid game. All of these would be horrible to try to write the game loop for if each pass through the loop tried to handle all player moves in one pass.</p>\n\n<hr>\n\n<p>When the game loop is change to handle only a single move at each pass, it is much easier to handle the “game over” condition. A <code>while game_is_running</code> loop is all that is required. Or, for tic-tac-toe, you could use:</p>\n\n<pre><code>for move_count in range(9):\n # moves made here\n # break if someone wins\nelse:\n print(\"You Tied\")\n</code></pre>\n\n<p>The <code>else:</code> clause of a <code>for</code> loop only executes if the loop finishes without executing <code>break</code>, so after 9 moves with no winner, it is a tie game.</p>\n\n<p>Using <code>sys.exit()</code> to stop the interpreter on a “game over” condition is a bad idea. It works here, but it makes test code impossible to write, because the program can kill the interpreter, and the test code can’t stop that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T07:29:07.587",
"Id": "420214",
"Score": "0",
"body": "@AJNeufed Thank you for the input and i will work on the suggestion made. I will work on the suggestions and post an updated version"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T05:42:09.430",
"Id": "217245",
"ParentId": "217235",
"Score": "2"
}
},
{
"body": "<h2>Function Placement</h2>\n\n<p>You lose a bit of performance and readability by defining <code>check_winner</code> inside your <code>while</code> loop. <code>move_count</code>, <code>board</code> etc are all in global scope, even though they are within that loop:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def check_winner():\n # Rest of function\n\nwhile True:\n</code></pre>\n\n<p>The <code>def end()</code> could also be moved to global scope, because again you are redefining it during every iteration which isn't what you want.</p>\n\n<h2>check_winner</h2>\n\n<p>The <code>new_list = winning_list</code> doesn't do anything, it copies the reference from <code>winning_list</code> and the two variables are tied together unless you did a <code>deep_copy</code>, which creates a new object. Furthermore, I don't really see any use of <code>new_list</code> anywhere, so you can just drop that line entirely.</p>\n\n<p>As @AJNewfeld pointed out, the <code>global move_count</code> can be dropped because, again, <code>move_count</code> is already global and is accessible by all <code>check_winner</code>, as it will look in the <code>locals()</code> mapping first, if <code>move_count</code> isn't in the local mapping (from positional or keyword args taken in by the function), it will search <code>globals()</code>. A <code>NameError</code> is only raised when those don't contain the variable you are looking for.</p>\n\n<h2>Making Moves</h2>\n\n<p>The <code>while</code> loop for <code>npc</code> can be easily refactored so that you aren't possibly iterating over the entire board, and makes the code a bit easier to read. Your <code>board</code> is made up of either two entries: <code>int</code> for open spots and <code>str</code> for taken spots. This means that <code>npc</code>'s move can be a function like so:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>def npc_move():\n # This will give you only the indices for spots that have yet to be taken\n remaining_spots = [i for i, value in enumerate(board) if isinstance(value, int)]\n return random.choice(remaining_spots)\n</code></pre>\n\n<p>Or you could also use a <code>set()</code> globally to represent remaining spots and <code>pop</code> indices out of it:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># Declare globally at the beginning \nmoves_left = set(range(9))\n\n# Your while loop can now be to check if the set is empty or not\nwhile moves_left: # A populated set acts as True\n my_move = moves_left.pop(random.choice(moves_left))\n\n # Now moves_left has one fewer element\n</code></pre>\n\n<p>Taking this idea a little further, you could combine the user's move with the npc's move in one function:</p>\n\n<pre><code># The npc default will allow you to set it to True if it's\n# npc's turn, otherwise, no args need to be supplied\ndef make_move(npc=False):\n\n if npc is False:\n user_move = \"\" # dummy default to kick off while loop\n while user_move not in moves_left:\n try:\n user_move = int(input(f\"Choose a move out of {moves_left}: \"))\n return moves_left.pop(user_move)\n except ValueError, KeyError: # invalid int conversion or not in moves_left\n print(\"Invalid move\")\n continue\n\n else:\n return moves_left.pop(random.choice(moves_left)) \n</code></pre>\n\n<p>You can then call it like:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>moves_left = set(range(9)) # At beginning of game\n\nnpc_move = make_move(npc=True)\n3\nuser_move = make_move()\n\nChoose a move out of {0, 1, 2, 4, 5, ,6 ,7, 8}: a\nInvalid move\nChoose a move out of {0, 1, 2, 4, 5, ,6 ,7, 8}: 3\nInvalid move\nChoose a move out of {0, 1, 2, 4, 5, ,6 ,7, 8}: 4\n\nuser_move\n4\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T13:45:49.613",
"Id": "217261",
"ParentId": "217235",
"Score": "1"
}
},
{
"body": "<p>I made some of the changes suggested by @AJNeufeld. I made the game loop a for i in range(9) and removed all global variables from the code. Put the move by the player in a try/except block to catch IndexError and the loop only handles one turn each go throug and looping back to the beginning when needed(I am not sure if i did this is the best way). End no longer uses the sys.exit() and changed to quit() and now offers am option to play again.</p>\n\n<pre><code>import sys\nfrom textwrap import dedent\nimport os\nimport random\n\nos.system('CLS')\n\n# board number setup\nboard = [0, 1, 2,\n 3, 4, 5,\n 6, 7, 8]\n\n\n# Defines the board layout printed to the console\ndef board_layout():\n print(dedent(f''' \n *************\n * {board[0]} | {board[1]} | {board[2]} *\n *-----------*\n * {board[3]} | {board[4]} | {board[5]} *\n *-----------*\n * {board[6]} | {board[7]} | {board[8]} *\n *************\n '''))\n\n\ndef main():\n players = ('Player','NPC')\n turn = 'Player'\n change_turn = 0\n for moves in range(9):\n if turn == 'Player': \n while True:\n try:\n board_layout()\n player_move = int(input('Please select a spot: '))\n if board[player_move] != 'x' and board[player_move] != 'o':\n board[player_move] = 'x'\n check_winner()\n break\n except IndexError:\n print('please select valid spot')\n if turn == 'NPC':\n # npc move, chooses a random spot that is not taken \n while True:\n npc = random.randint(0, 8)\n if board[npc] != 'o' and board[npc] != 'x':\n board[npc] = 'o'\n print('Computer chooses spot ', npc)\n check_winner()\n break \n try:\n change_turn += 1\n turn = players[change_turn]\n except:\n change_turn = 0\n turn = players[change_turn]\n else:\n print('You Tied')\n end() \n\n\n\n\n\ndef end():\n print('Thank you for playing')\n answer = input('Would you like to play again?: Y/N')\n\n if answer.lower() == 'n':\n quit()\n elif answer.lower() == 'y':\n clear_board()\n main()\n else:\n print('Please choose a valid option')\n end()\n\ndef clear_board():\n for i in range(9):\n board[i] = i\n\n# checks for a winner when called at end of each turn \ndef check_winner():\n\n # list of lists with all the winning combinations for from the tic tac toe board\n winning_list = [[board[0], board[1], board[2]], [board[3], board[4], board[5], ],\n [board[6], board[7], board[8]], [board[0], board[4], board[8]],\n [board[2], board[4], board[6]],\n [board[0], board[3], board[6]], [board[1], board[4], board[7]],\n [board[2], board[5], board[8]]]\n\n # iterates over the lists in winning_list\n for i, j, k in winning_list:\n # looks at the lists in winning_list to determine if a list has all x's for a win\n if i == 'x' and j == 'x' and k == 'x':\n print('X wins')\n end()\n # looks at the lists in winning_list to determine if a list has all o's for a win\n elif i == 'o' and j == 'o' and k == 'o':\n print('O wins')\n end()\n\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T01:55:14.347",
"Id": "420339",
"Score": "0",
"body": "Are you happy with this new code, or are you hoping for additional review feedback? If the latter, you need to ask a new question, say “First Python program: Tic-Tac-Toe (Followup)”, include a link back to this question, and a link from this question to the follow up question. See “[What should I do when someone answers my question](https://codereview.stackexchange.com/help/someone-answers)” in “Help” for more details. All the feedback I can give you in a comment on this answer is “I don’t like what you’ve done”, but don’t have nearly the space to explain why."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T02:48:38.967",
"Id": "420343",
"Score": "0",
"body": "@ AJNeufeld 52 i was hoping for addition feedback. I have posted a follow-up at [link](https://codereview.stackexchange.com/questions/217304/first-python-program-tic-tac-toe-followup)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T21:51:03.580",
"Id": "217290",
"ParentId": "217235",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T23:41:18.717",
"Id": "217235",
"Score": "4",
"Tags": [
"python",
"beginner",
"tic-tac-toe"
],
"Title": "First Python program: Tic-Tac-Toe"
} | 217235 |
<p>I am currently study the basic data structure and trying to implement everything as I go. can anyone give me some feedback about class BinarySearchTree how to make the code more elegant. any review are appreciated.</p>
<pre class="lang-py prettyprint-override"><code>class TreeNode:
def __init__(self, value=None, left=None, right=None):
self.val = value
self.left = left
self.right = right
class BinarySearchTree:
"""
Database strucutre for binary search tree
1:search
2:insert
3:delete
4:get_height
5:get_min_value
6:get_max_value
"""
def __init__(self, root=None):
self.root = root
def __iter(self, cur):
if cur is not None:
yield from self.__iter(cur.left)
yield cur
yield from self.__iter(cur.right)
def __repr__(self):
cur = self.root
return ''.join(str(i.val) for i in self.__iter(cur))
def insert(self, key):
"""insert node into binary tree based on node's value"""
cur = self.root
if cur is None:
self.root = TreeNode(key)
return
while cur is not None:
if key < cur.val:
if cur.left is None:
cur.left = TreeNode(key)
return
else:
cur = cur.left
elif key > cur.val:
if cur.right is None:
cur.right = TreeNode(key)
return
else:
cur = cur.right
def search(self, key):
"""find node from binary tree based on node's value"""
cur = self.root
if cur is None:
raise KeyError(f'{key} is not found')
while cur is not None:
if key < cur.val:
cur = cur.left
elif key > cur.val:
cur = cur.right
else:
return cur
raise KeyError(f'{key} is not found')
def get_min_value(self):
"""return the min value from tree"""
cur = self.root
while cur is not None and cur.left is not None:
cur = cur.left
return cur.val
def get_max_value(self):
"""return the max value from tree"""
cur = self.root
while cur is not None and cur.right is not None:
cur = cur.right
return cur.val
def get_height(self):
"""return tree height of binary search tree"""
h = 0
return self.__get_height(self.root, h) if self.root else h
def __get_height(self, cur, h):
"""recursion the tree with left subtree and right subtree"""
if cur is None: return h
left_height = self.__get_height(cur.left, h + 1)
right_height = self.__get_height(cur.right, h + 1)
return max(left_height, right_height)
def delete(self, key):
"""delete the node from binary tree based on node's key value"""
if self.root is None: raise KeyError('key is not found')
self.__delete(self.root, key)
def __delete(self, cur, key):
"""recursion the tree to find the node and delete from tree"""
if cur is None: return
if key < cur.val:
cur.left = self.__delete(cur.left, key)
elif key > cur.val:
cur.right = self.__delete(cur.right, key)
else:
if cur.left is None:
return cur.right
elif cur.right is None:
return cur.left
else:
def __get_successor(n):
while n is not None and n.left is not None:
n = n.left
return n
successor = __get_successor(cur)
cur.key = successor.key
cur.right = self.__delete(cur.right, successor.key)
return cur
if __name__ == '__main__':
bst = BinarySearchTree()
bst.insert(6)
bst.insert(2)
bst.insert(8)
bst.insert(0)
bst.insert(4)
bst.insert(7)
bst.insert(9)
bst.insert(3)
bst.insert(5)
print(bst.search(5).val == 5)
print(bst.search(0).val == 0)
print(bst.search(9).val == 9)
print(bst.search(6).val == 6)
try:
bst.search(13)
except KeyError as e:
print(e)
print(bst.get_height() == 4)
bst.delete(5)
print(bst.get_height() == 4)
print(bst.get_max_value() == 9)
print(bst.get_min_value() == 0)
bst.delete(3)
bst.delete(7)
bst.delete(9)
print(bst.get_height() == 3)
print(bst)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T05:34:12.057",
"Id": "420201",
"Score": "1",
"body": "I believe that if you try to insert a duplicate value, your code will go into an infinite loop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T15:00:11.460",
"Id": "420278",
"Score": "0",
"body": "yes, for binary search tree. i am not sure how I should handle duplicated value and how to remove the duplicated recursion based on search, insert and delete"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T15:56:43.637",
"Id": "420801",
"Score": "2",
"body": "@A.Lee This depends on a specification, but I would expect that infinite loop is unlikely to be desirable. Throwing an exception or not inserting duplicates seems to be preferable solutions."
}
] | [
{
"body": "<p>The code is clean, but there are some problems: 1. your binary search tree is not a standard binary search tree; 2. your implementation is not consistent; 3. various issues.</p>\n\n<h1>Problems</h1>\n\n<h2>What is a binary search tree?</h2>\n\n<p>There is one bug that was pointed in a comment: what happens if you insert a value that is already present in the tree? In the current code, you fall in an infinite loop since the case is simply ignored:</p>\n\n<pre><code># insert\nwhile cur is not None:\n if key < cur.val:\n ...\n elif key > cur.val:\n ...\n # What if key == cur.val???\n # Nothing: just loop, and loop, and loop...\n</code></pre>\n\n<p>But the question is: what would you like to do if the value to insert is already present? Just let the tree as it is, or insert the value and get it twice in the tree? In the standard binary tree, nodes have a <code>key</code> and a <code>value</code>, and you insert a pair <code>key/value</code>: if the <code>key</code> is already present, the previous <code>value</code> is replaced by the new <code>value</code>. You can create a simplified version where the <code>key</code> is the value <code>value</code> itself, and thus just ignore the duplicate <code>value</code>s, or allow duplicate <code>value</code>s, but I think the best is to create a regular BST with <code>key</code>s and <code>value</code>s since it's as easy as create one with only <code>value</code>s.</p>\n\n<h2>Implementation consistency</h2>\n\n<p>You do not choose between a recursive implementation and an iterative one: <code>insert</code>, <code>search</code>, <code>get_min/max</code> are iterative while <code>get_height</code> and <code>delete</code> are recursive. For a first implementation, I would use only recursion because it's easier to understand. Once the code works, you can improve the speed by removing recursion <strong>if and only if</strong> it is mandatory.</p>\n\n<h2>Misc</h2>\n\n<h3>Double underscores</h3>\n\n<p>Do not use them as a synonym for <code>private</code> in other OOP languages:</p>\n\n<blockquote>\n <p>Generally, double leading underscores should be used only to avoid name conflicts with attributes in classes designed to be subclassed\n <em>~ <a href=\"https://www.python.org/dev/peps/pep-0008/#method-names-and-instance-variables\" rel=\"noreferrer\">PEP8</a></em></p>\n</blockquote>\n\n<h3><code>__repr__</code></h3>\n\n<blockquote>\n <p>For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object.\n <em>~ <a href=\"https://docs.python.org/3/library/functions.html#repr\" rel=\"noreferrer\"><code>repr</code></a></em></p>\n</blockquote>\n\n<p>Your implementation matches more <code>__str__</code> than <code>__repr__</code>.</p>\n\n<h3><code>__iter</code></h3>\n\n<p>This method might be confused with <code>__iter__</code>. You should etiehr implement <code>__iter__</code> or choose another name.</p>\n\n<h1>Tests</h1>\n\n<h2>Testing framework</h2>\n\n<p>You gave us some tests: that's a very good point. But they are non standard. You should use a testing framework. There are two testing tools shipped with Python: <a href=\"https://docs.python.org/3/library/unittest.html\" rel=\"noreferrer\"><code>unittest</code></a> and <a href=\"https://docs.python.org/3/library/doctest.html#module-doctest\" rel=\"noreferrer\"><code>doctest</code></a>. I'm really in love with <code>doctest</code>, because can test your module without writing boilerplate code. But this method has some limits: if you want to thoroughly test a module, you'll have to write separate unit tests.</p>\n\n<h2>Code refactoring</h2>\n\n<p>When you refactor any code, I think <strong>it's very important to</strong> make sure the exisiting tests still pass. Hence, I insert a docstring at the top the file with your tests:</p>\n\n<pre><code>\"\"\"\n >>> bst = BinarySearchTree()\n >>> for v in [6,2,8,0,4,7,9,3,5]:\n ... bst.insert(v)\n >>> [bst.search(v).value for v in [5,0,9,6]]\n [5, 0, 9, 6]\n >>> bst.search(13)\n Traceback (most recent call last):\n ...\n KeyError: '13 is not found'\n >>> bst.get_height()\n 4\n >>> bst.delete(5)\n >>> bst.get_height()\n 4\n >>> bst.get_max_value()\n 9\n >>> bst.get_min_value()\n 0\n >>> for v in [3,7,9]:\n ... bst.delete(v)\n >>> bst.get_height()\n 3\n >>> bst\n 02468\n\"\"\"\n\n# BODY OF THE MODULE\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n</code></pre>\n\n<p>Now we can confidently refactor the code: it will perform at least as good as before.</p>\n\n<p>As you see, the tests mimic a REPL, which is very intuitive and well known by every Python user. Usually, you put comments around the tests to explain whats going on.</p>\n\n<p>I made some little improvements to the tests:\n* bunch insert of values with a <code>for</code> loop\n* a list comprehension to test the <code>search</code> method</p>\n\n<p>We'll use <code>doctest</code> in the docstrings of functions too.</p>\n\n<h1>A recursive implementation</h1>\n\n<p>As I wrote above, a recursive implementation seems a good start, since the trees are inherently recursive structures.</p>\n\n<h2>The <code>TreeNode</code> class</h2>\n\n<p>Your <code>__init__</code> method allows the value to be <code>None</code>.</p>\n\n<pre><code>def __init__(self, value=None, left=None, right=None):\n</code></pre>\n\n<p>But there is no reason to accept nodes with a <code>None</code> value. Sooner or later, you'll get something like:</p>\n\n<pre><code>key > cur.value\n</code></pre>\n\n<p>where <code>cur.value</code> is None! Result:</p>\n\n<pre><code>TypeError: '>' not supported between instances of 'xxx' and 'NoneType'\n</code></pre>\n\n<p>I like the idea that the user of the class is not a child, and won't use <code>None</code> as a value (we should warn him/her). That's the responsibity of the user not to use <code>None</code> -- the user means also: You, when you use your own classes. But <strong>your</strong> responsibility is to ensure that the object state is correct with the default parameters. That's not the case.</p>\n\n<p>As written, to get a regular BST, we need to add a <code>key</code> field. Since the <code>TreeNode</code> has no method and is just a convenient way to store the attributes of a node, we can use the new 3.7 <code>dataclass</code>:</p>\n\n<pre><code>from dataclasses import dataclass\nfrom typing import Any\n\n@dataclass\nclass TreeNode:\n key: Any\n value: Any\n left: 'TreeNode' = None\n right: 'TreeNode' = None\n</code></pre>\n\n<p>Note on <code>Any</code> type: we could enforce the presence of <code>__eq__</code> and <code>__lt__</code> in the <code>key</code>, but that would be overkill I think. It's Python, not Java!</p>\n\n<h2><code>search</code></h2>\n\n<p>This is, in my mind, the best entry point: we want a tree to search key/values pairs. Note that, in your code:</p>\n\n<pre><code>if cur is None:\n raise KeyError(f'{key} is not found')\nwhile cur is not None:\n ...\n\nraise KeyError(f'{key} is not found')\n</code></pre>\n\n<p>you don't need to test if <code>cur is None</code> before the loop since the loop will be skipped immediately and the error raised. But we need this test in the recursive version:</p>\n\n<pre><code>class BinarySearchTree:\n ...\n\n def search(self, key):\n \"\"\"Return the value assiociated with key, or raise a KeyError exception\"\"\"\n return _search(self.root, key).value\n\n# standalone function, out of the BinarySearchTree class\ndef _search(node, key):\n \"\"\"Search a node by key. Raise a KeyError exception if the key is not in the tree\"\"\"\n if node is None: # end of recursion\n raise KeyError(f'{key} is not found')\n if key < node.key:\n return _search(node.left, key)\n elif key > node.key:\n return _search(node.right, key)\n else: # key == node.key\n return node\n</code></pre>\n\n<p>I think we can solve a little puzzle here. It's not an accident you had to create helper methods (<code>__get_height</code> and <code>__delete</code>) for the recursive methods. Actually, the methods <code>get_height</code> and <code>delete</code> are only bootstraps for those methods. Here, <code>BinarySearchTree.search</code> is a bootstrap for the standalone <code>_search</code> function.</p>\n\n<p>That's because, conceptually, <em>every node is also a tree, and a complete tree</em>. That means that, in your code, the tree is represented by the <code>TreeNode</code> class, not the <code>BinarySearchTree</code> class. The <code>BinarySearchTree</code> class is just a wrapper around the root and a method supplier.</p>\n\n<p>It would be possible to attach the <code>_search</code> method to the <code>TreeNode</code> class, but we would have to test for <code>None</code> value at the children level:</p>\n\n<pre><code>class TreeNode:\n ...\n\n def search(self, key):\n \"\"\"Search a node by key. Raise a KeyError exception if the key is not in the tree\"\"\"\n if key < self.key and self.left is not None:\n return node.left.search(key)\n elif key > node.key and self.right is not None:\n return node.right.search(key)\n elif key == node.key:\n return node\n raise KeyError(f'{key} is not found')\n</code></pre>\n\n<p>I would probably write it like that in Java, but its easier to use standalone functions in Python.</p>\n\n<p>Now we have the <code>_search</code> function, we can test it. Just add to the docstring a few lines:</p>\n\n<pre><code>\"\"\"Search a node by key. Raise a KeyError exception if the key is not in the tree\n\n>>> _search(None, 1)\nTraceback (most recent call last):\n...\nKeyError: '1 is not found'\n>>> _search(TreeNode(0, 0), 1)\nTraceback (most recent call last):\n...\nKeyError: '1 is not found'\n>>> _search(TreeNode(1, 0), 1)\nTreeNode(key=1, value=0, left=None, right=None)\n>>> _search(TreeNode(0, 0, None, TreeNode(1, 1)), 1)\nTreeNode(key=1, value=1, left=None, right=None)\n\"\"\"\n</code></pre>\n\n<p>We have to fix the tests in the module docstring too, but I keep it for later.</p>\n\n<h2><code>insert</code></h2>\n\n<p>We know how to search a node by <code>key</code>. Now, we need to <code>insert</code> <code>key/value</code> pairs in the tree:</p>\n\n<pre><code>class BinarySearchTree:\n ...\n\n def insert(self, key, value):\n \"\"\"insert node into binary tree based on node's key\"\"\"\n self.root = _insert(self.root, key, value)\n\ndef _insert(node, key, value):\n \"\"\"Return node extended with a new key/value pair\"\"\"\n if node is None:\n return TreeNode(key, value)\n\n if key < node.key:\n return TreeNode(node.key, node.value, _insert(node.left, key, value), node.right)\n elif key > node.key:\n return TreeNode(node.key, node.value, node.left, _insert(node.right, key, value))\n else: # key == node.key\n return TreeNode(node.key, value, node.left, node.right)\n</code></pre>\n\n<p>There is an interesting pattern here:</p>\n\n<pre><code>return TreeNode(node.key, node.value, _insert(node.left, key, value), node.right)\n</code></pre>\n\n<p>Seems equivalent to:</p>\n\n<pre><code>node.right = _insert(node.left, key, value)\nreturn node\n</code></pre>\n\n<p>But there is a big difference: the former is side effect free, while the latter is not. I prefer to avoid side effects because the code is easier to understand, <em>but there is a performance cost</em>. Again, we add some tests:</p>\n\n<pre><code>\"\"\"Return node extended with a new key/value pair\n\n>>> node = TreeNode(0,0)\n>>> for i in range(2):\n... node = _insert(node, i, 2*i+1)\n>>> node\nTreeNode(key=0, value=1, left=None, right=TreeNode(key=1, value=3, left=None, right=None))\n>>> _insert(node, -1, -2)\nTreeNode(key=0, value=1, left=TreeNode(key=-1, value=-2, left=None, right=None), right=TreeNode(key=1, value=3, left=None, right=None))\n\"\"\"\n</code></pre>\n\n<h2><code>get_min</code>, <code>get_max</code> and <code>get_height</code></h2>\n\n<p>You should known how to proceed: <code>get_min</code> and <code>get_max</code> are easy to write recursively.</p>\n\n<p>Your implementation of <code>get_height</code>, is recursive, but uses a tail call optimization (a mechanism that prevents the stack from growing insanely). I don't know if you did it on purpose, but I will remove this optimization for the sake of clarity:</p>\n\n<pre><code>def _get_height(node):\n \"\"\"return tree height of binary search tree\"\"\"\n if node is None:\n return 0\n return 1 + max(_get_height(node.left), _get_height(node.right))\n</code></pre>\n\n<h2><code>delete</code></h2>\n\n<p>The <code>delete</code> operation needs the two following steps: 1. find the node having the given <code>key</code>; 2. remove the <code>key</code>. The first step is easy, now but the second one is not. Let's look at your code to understand what happens:</p>\n\n<pre><code> else: # key == cur.key\n if cur.left is None:\n return cur.right\n elif cur.right is None:\n return cur.left\n else:\n def __get_successor(n):\n while n is not None and n.left is not None:\n n = n.left\n return n\n\n successor = __get_successor(cur)\n cur.key = successor.key\n cur.right = self.__delete(cur.right, successor.key)\n</code></pre>\n\n<p>If the node lacks one of its chidren, you just return the other child. That's ok.</p>\n\n<p>But if the node has both left and right children, you take the leftmost element of the right child (you could take the rightmost element of the left child) and replace the current node with that node. That's ok because the leftmost element has a value that is: greater than any value in the left child; lower than any <em>other</em> value of the right child (definition of a BST). Hence, you find the successor and delete it from the right child.</p>\n\n<p>Now in recursive idiom:</p>\n\n<pre><code>else: # key == node.key\n if node.left is None:\n return node.right\n else:\n successor, right = _detach_min(node.right)\n return TreeNode(successor.key, successor.value, node.left, right)\n</code></pre>\n\n<p>Wait! what is this <code>_detach_min</code> function? When I write my code, I try to keep the momentum. If I don't know how to write something, I just use a function that does not exist yet. Later, I try to write this function:</p>\n\n<pre><code>def _detach_min(node):\n \"\"\"Return the min value from the tree and the\n rest of the tree\"\"\"\n if node.left is None:\n return node, None\n\n m, r = _detach_min(node.left)\n return m, TreeNode(node.key, node.value, r, node.right)\n</code></pre>\n\n<p>First, we detach the min from the left child, then we return this min and the tree without the min.</p>\n\n<h2><code>__repr__</code> and <code>__str__</code></h2>\n\n<p>With the <code>dataclass</code>, <code>__repr__</code> is almost free:</p>\n\n<pre><code>def __repr__(self):\n return f\"BinarySearchTree(root={self.root})\"\n</code></pre>\n\n<p>We'll see <code>__str__</code> and the iteration on <code>key/value</code>s later.</p>\n\n<h1>Full code</h1>\n\n<p>The code is now complete. I will just adapt the initial tests:</p>\n\n<pre><code>\"\"\"\n >>> bst = BinarySearchTree()\n >>> for v in [6,2,8,0,4,7,9,3,5]:\n ... bst.insert(v, v)\n >>> [bst.search(v) for v in [5,0,9,6]]\n [5, 0, 9, 6]\n >>> bst.search(13)\n Traceback (most recent call last):\n ...\n KeyError: '13 is not found'\n >>> bst.get_height()\n 4\n >>> bst.delete(5)\n >>> bst.get_height()\n 4\n >>> bst.get_max_value()\n 9\n >>> bst.get_min_value()\n 0\n >>> bst.delete(3)\n >>> bst.delete(7)\n >>> bst.delete(9)\n >>> bst.get_height()\n 3\n >>> bst\n BinarySearchTree(root=TreeNode(key=6, value=6, left=TreeNode(key=2, value=2, left=TreeNode(key=0, value=0, left=None, right=None), right=TreeNode(key=4, value=4, left=None, right=None)), right=TreeNode(key=8, value=8, left=None, right=None)))\n\"\"\"\n\nfrom dataclasses import dataclass\nfrom typing import Any\n\n@dataclass\nclass TreeNode:\n key: Any\n value: Any\n left: 'TreeNode' = None\n right: 'TreeNode' = None\n\nclass BinarySearchTree:\n def __init__(self):\n self.root = None\n\n def search(self, key):\n \"\"\"Return the value assiociated with key, or raise a KeyError exception\"\"\"\n return _search(self.root, key).value\n\n def insert(self, key, value):\n \"\"\"insert node into binary tree based on node's key\"\"\"\n self.root = _insert(self.root, key, value)\n\n def get_min_value(self):\n \"\"\"return the min value from tree\"\"\"\n return _get_min(self.root).value\n\n def get_max_value(self):\n \"\"\"return the min value from tree\"\"\"\n return _get_max(self.root).value\n\n def get_max_value(self):\n \"\"\"return the min value from tree\"\"\"\n return _get_max(self.root).value\n\n def get_height(self):\n \"\"\"return the height from tree\"\"\"\n return _get_height(self.root)\n\n def delete(self, key):\n \"\"\"Delete the node having the given key\"\"\"\n self.root = _delete(self.root, key)\n\n def __repr__(self):\n return f\"BinarySearchTree(root={self.root})\"\n\n# standalone function, out of the BinarySearchTree class\ndef _search(node, key):\n \"\"\"Search a node by key. Raise a KeyError exception if the key is not in the tree\n\n >>> _search(None, 1)\n Traceback (most recent call last):\n ...\n KeyError: '1 is not found'\n >>> _search(TreeNode(0, 0), 1)\n Traceback (most recent call last):\n ...\n KeyError: '1 is not found'\n >>> _search(TreeNode(1, 0), 1)\n TreeNode(key=1, value=0, left=None, right=None)\n >>> _search(TreeNode(0, 0, None, TreeNode(1, 1)), 1)\n TreeNode(key=1, value=1, left=None, right=None)\n \"\"\"\n if node is None: # end of recursion\n raise KeyError(f'{key} is not found')\n\n if key < node.key:\n return _search(node.left, key)\n elif key > node.key:\n return _search(node.right, key)\n else:\n return node\n\n\ndef _insert(node, key, value):\n \"\"\"Return node extended with a new key/value pair\n\n >>> node = TreeNode(0,0)\n >>> for i in range(2):\n ... node = _insert(node, i, 2*i+1)\n >>> node\n TreeNode(key=0, value=1, left=None, right=TreeNode(key=1, value=3, left=None, right=None))\n >>> _insert(node, -1, -2)\n TreeNode(key=0, value=1, left=TreeNode(key=-1, value=-2, left=None, right=None), right=TreeNode(key=1, value=3, left=None, right=None))\n \"\"\"\n if node is None:\n return TreeNode(key, value)\n\n if key < node.key:\n return TreeNode(node.key, node.value, _insert(node.left, key, value), node.right)\n elif key > node.key:\n return TreeNode(node.key, node.value, node.left, _insert(node.right, key, value))\n else: # key == node.key\n return TreeNode(node.key, value, node.left, node.right)\n\ndef _get_min(node):\n \"\"\"return the min value from tree\n >>> node = TreeNode(0,0)\n >>> for i in range(3):\n ... node = _insert(node, i, 2*i+1)\n >>> _get_min(node).value\n 1\n \"\"\"\n if node.left is None:\n return node\n\n return _get_min(node.left)\n\ndef _get_max(node):\n \"\"\"return the max value from tree\n >>> node = TreeNode(0,0)\n >>> for i in range(3):\n ... node = _insert(node, i, 2*i+1)\n >>> _get_max(node).value\n 5\n \"\"\"\n if node.right is None:\n return node\n\n return _get_max(node.right)\n\ndef _get_height(node):\n \"\"\"return tree height of binary search tree\n >>> node = TreeNode(0,0)\n >>> for i in range(3):\n ... node = _insert(node, i, 2*i+1)\n >>> _get_height(node)\n 3\n \"\"\"\n if node is None: # end of the recursion\n return 0\n return 1 + max(_get_height(node.left), _get_height(node.right))\n\ndef _delete(node, key):\n \"\"\"Return the tree without the node having the given key\n >>> node = TreeNode(0,0)\n >>> node = _insert(node, 1, 1)\n >>> node = _insert(node, -1, 2)\n >>> _delete(node, 0)\n TreeNode(key=1, value=1, left=TreeNode(key=-1, value=2, left=None, right=None), right=None)\n \"\"\"\n if node is None:\n return None\n if key < node.key:\n return TreeNode(node.key, node.value, _delete(node.left, key), node.right)\n elif key > node.key:\n return TreeNode(node.key, node.value, node.left, _delete(node.right, key))\n else: # key == node.key, end of recursion\n if node.left is None:\n return node.right\n else:\n successor, right = _detach_min(node.right)\n return TreeNode(successor.key, successor.value, node.left, right)\n\ndef _detach_min(node):\n \"\"\"return the min value from tree\n >>> node = TreeNode(0,0)\n >>> node = _insert(node, 1, 1)\n >>> node = _insert(node, -1, 2)\n >>> node = _insert(node, -2, 4)\n >>> node = _insert(node, -0.5, 2.5)\n >>> _detach_min(node)\n (TreeNode(key=-2, value=4, left=None, right=None), TreeNode(key=0, value=0, left=TreeNode(key=-1, value=2, left=None, right=TreeNode(key=-0.5, value=2.5, left=None, right=None)), right=TreeNode(key=1, value=1, left=None, right=None)))\n \"\"\"\n if node.left is None:\n return node, None\n\n m, r = _detach_min(node.left)\n return m, TreeNode(node.key, node.value, r, node.right)\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n</code></pre>\n\n<p>As you can see, the code is not only recursive: it's functional, that means that you don't have any side effect in the functions. Usually, functional code is more readable while imperative code is more efficient. Hence there is no good version: it depends on your needs. What matters is to be consistent.. or not, depending on your needs.</p>\n\n<h1>Conclusion</h1>\n\n<p>Here are the more important points to notice:</p>\n\n<ul>\n<li>A node is a complete tree (all standalone functions deal with nodes as trees).</li>\n<li>The code now decouples the operations on the tree (standalone function) and the operations on the mapping (methods).</li>\n<li><code>doctest</code> was perhaps used where <code>unitest</code> should have been preferred.</li>\n</ul>\n\n<h1>A step further</h1>\n\n<p>I will prove that the second point is important. A binary tree is a mapping. Python provides a frame for mappings: <a href=\"https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping\" rel=\"noreferrer\">https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping</a>. Why not try to fit this frame?</p>\n\n<p>We just make <code>BinarySearchTree</code> inherit from <code>Mapping</code>:</p>\n\n<pre><code>from collections.abc import MutableMapping\n\nclass BinarySearchTree(MutableMapping):\n ...\n</code></pre>\n\n<p>Now, Python requires some methods to be implemented:</p>\n\n<pre><code>TypeError: Can't instantiate abstract class BinarySearchTree with abstract methods __delitem__, __getitem__, __iter__, __len__, __setitem__\n</code></pre>\n\n<ul>\n<li><code>__delitem__</code> is simply our <code>delete</code> method;</li>\n<li><code>__getitem__</code> is our <code>search</code> method;</li>\n<li><code>__setitem__</code> is our <code>insert</code> method;</li>\n<li><code>__iter__</code> must return an iterator over items;</li>\n<li><code>__len__</code> must return the number of nodes of the binary tree;</li>\n</ul>\n\n<h2><code>__iter__</code></h2>\n\n<p>We'll use a generator to implement the iterator:</p>\n\n<pre><code> def __iter__(self):\n return _iter(self.root)\n\ndef _iter(node):\n if node is None:\n return\n\n yield from _iter(node.left)\n yield node.key\n yield from _iter(node.right)\n</code></pre>\n\n<h2><code>__len__</code></h2>\n\n<p>The method is similar to <code>get_height</code>:</p>\n\n<pre><code>def _len(node):\n if node is None:\n return 0\n\n return 1 + _len(node.left) + _len(node.right)\n</code></pre>\n\n<h2><code>__str__</code></h2>\n\n<p>The <code>__str__</code> may be implemented to show the sorted dictionary:</p>\n\n<pre><code>def __str__(self):\n return \"{\"+\", \".join(f\"{k}: {v}\" for k, v in self.items())+\"}\"\n</code></pre>\n\n<h2>A mapping initializer</h2>\n\n<p>We need a convenient way to initialize the binary tree:</p>\n\n<pre><code>def __init__(self, mapping={}):\n self.root = None\n self.update(mapping)\n</code></pre>\n\n<p>We could update the <code>__repr__</code> method to use this initializer.</p>\n\n<h1>Code v2</h1>\n\n<p>I omit the parts that where not modified:</p>\n\n<pre><code>\"\"\"\n >>> bst = BinarySearchTree({v: v for v in [6,2,8,0,4,7,9,3,5]})\n >>> [bst[v] for v in [5,0,9,6]]\n [5, 0, 9, 6]\n >>> bst[13]\n Traceback (most recent call last):\n ...\n KeyError: '13 is not found'\n >>> bst.get_height()\n 4\n >>> del bst[5]\n >>> bst.get_height()\n 4\n >>> bst.get_max_value()\n 9\n >>> bst.get_min_value()\n 0\n >>> del bst[3]\n >>> del bst[7]\n >>> del bst[9]\n >>> bst.get_height()\n 3\n >>> str(bst)\n '{0: 0, 2: 2, 4: 4, 6: 6, 8: 8}'\n\"\"\"\n\n...\n\nclass BinarySearchTree(MutableMapping):\n def __init__(self, mapping={}):\n self.root = None\n self.update(mapping)\n\n def __getitem__(self, key):\n return _search(self.root, key).value\n\n def __iter__(self):\n return _iter(self.root)\n\n def __setitem__(self, key, value):\n self.root = _insert(self.root, key, value)\n\n ...\n\n def __delitem__(self, key):\n self.root = _delete(self.root, key)\n\n def __repr__(self):\n return f\"BinarySearchTree(root={self.root})\"\n\n def __str__(self):\n return \"{\"+\", \".join(f\"{k}: {v}\" for k, v in self.items())+\"}\"\n\n def __len__(self):\n return _len(self.root)\n\n\ndef _iter(node):\n if node is None:\n return\n\n yield from _iter(node.left)\n yield node.key\n yield from _iter(node.right)\n\ndef _len(node):\n if node is None:\n return 0\n\n return 1 + _len(node.left) + _len(node.right)\n\n...\n</code></pre>\n\n<p>Have a look at the tests: the class may be used as any standard Python mapping! The important point is that the interface of the binary tree was adapted to fit with the <code>Mapping</code> interface, but we didn't need to modify the standalone functions. That's a sign that the code was, I hope, correctly decoupled.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T20:48:04.187",
"Id": "217583",
"ParentId": "217239",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "217583",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T03:02:12.127",
"Id": "217239",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"tree"
],
"Title": "Implement BinarySearchTree class in python"
} | 217239 |
<p>I'm starting using hooks, and I have a specific scenario that I'm thinking <code>useEffect</code>is appropriate for. </p>
<p>Essentially what I'm doing is: </p>
<ul>
<li>I have some <code>ssiData</code> in the redux store. </li>
<li>If that data has an invite code, <em>and</em> the invite isn't already accepted, then I want to display a QR code</li>
<li>If the invite is accepted, then this component will not be displayed. </li>
<li>If I am displaying the QR code, then I want to dispatch an action that is going to poll for updates to the <code>ssiData</code></li>
<li>But if the user navigates away - I want to cancel the polling.</li>
<li>If the connection is accepted while the QR is displayed, I want to stop polling, and the QR to disappear. </li>
</ul>
<p>The idea is - the QR is displayed to the user, they use their phone to scan it to accept the invite. </p>
<p>So the way I've done this is: </p>
<pre><code>function SsiQrCodeRender({ ssiData, pollForChanges, cancelPolling }) {
const classes = useStyles();
const image = "data:image/png;base64," + qrImage.imageSync(JSON.stringify(ssiData.invite)).toString('base64');
useEffect(() => {
pollForChanges(ssiData.ssiId)
return () => {
cancelPolling();
}
})
return <Card
component="section"
>
<img src={image} className={classes.root} />
</Card>;
}
const mapStateToProps = (
state,
ownProps
) => {
return {
ssiData: ssiInitConnectionRedux.dataSelector(state)
};
};
const mapDispatchToProps = dispatch => {
return {
pollForChanges: (ssiId) => dispatch(ssiPollForConnectionChangeRedux.actionFn(ssiId)),
cancelPolling: () => dispatch(ssiCancelPolling.actionFn()),
};
};
export const SsiQrCode = connect(
mapStateToProps,
mapDispatchToProps
)(SsiQrCodeRender);
</code></pre>
<p>And the parent component (simplified): </p>
<pre><code>function SsiStudentLinkPanelRender({ ssiData, doDisplayQr }) {
const classes = useStyles();
return <Card
component = "section"
className={classes.root}>
{doDisplayQr && <SsiQrCode />}
</Card>;
}
const doDisplayQrSelector = (ssiData) => {
return ssiData.invite && ssiData.connectionState !==4 ;
}
const mapStateToProps = (
state,
ownProps
) => {
const ssiData = ssiInitConnectionRedux.dataSelector(state);
return {
ssiData,
doDisplayQr: doDisplayQrSelector(ssiData),
};
};
const mapDispatchToProps = dispatch => {
return {
};
export const SsiStudentLinkPanel = connect(
mapStateToProps,
mapDispatchToProps
)(SsiStudentLinkPanelRender);
</code></pre>
<p>Am I going about this the right way? What I've got so far seems to work ok (although I haven't actually implemented the start polling/stop polling actions). </p>
<p>There's something that seems a bit complicated and flakey with this. </p>
<p>Is this code written such that it will necessarily have a one to one mapping of 'start polling' to 'stop polling' actions? </p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T03:04:06.080",
"Id": "217240",
"Score": "1",
"Tags": [
"react.js",
"jsx",
"redux"
],
"Title": "React Hooks conditional in useEffect"
} | 217240 |
<p>The task:</p>
<blockquote>
<p>Given a string of parentheses, write a function to compute the minimum
number of parentheses to be removed to make the string valid (i.e.
each open parenthesis is eventually closed).</p>
<p>For example, given the string "()())()", you should return 1. Given
the string ")(", you should return 2, since we must remove all of
them.</p>
</blockquote>
<pre><code>const brackets = "()())()";
</code></pre>
<p>My functional solution:</p>
<pre><code>const numberOfUnbalanced = brackets => Object.values(brackets
.split("")
.reduce((brackCounter, b) => {
b === "(" ? brackCounter.openBrackets++ :
brackCounter.openBrackets ? brackCounter.openBrackets-- :
brackCounter.closedBrackets++;
return brackCounter;
}, {openBrackets: 0, closedBrackets: 0}))
.reduce((sum, b) => sum + b, 0);
console.log(numberOfUnbalanced(brackets));
</code></pre>
<p>My imperative solution:</p>
<pre><code>function numberOfUnbalanced2(brackets) {
let openBrackets = 0, closedBrackets = 0;
for (let i in brackets) {
brackets[i] === "(" ? openBrackets++ :
openBrackets ? openBrackets-- :
closedBrackets++;
}
return openBrackets + closedBrackets;
}
console.log(numberOfUnbalanced2(brackets));
</code></pre>
<p>Usually the functional approach is shorter and tend to be easier to understand in comparison to imperative approaches. However, in this case it doesn't have any advantage to the imperative approach. I guess it is due to the nested structure in the functional solution.</p>
| [] | [
{
"body": "<p>Nested ternaries tend to be hard to read. The writing style could help a lot though, consider this:</p>\n\n<pre><code>b === \"(\"\n ? brackCounter.openBrackets++\n : brackCounter.openBrackets\n ? brackCounter.openBrackets--\n : brackCounter.closedBrackets++;\n</code></pre>\n\n<p>The term \"bracket\" is redundant within the implementation.\nWhat else would you count, have open or closed, than brackets?\nNothing, so I suggest dropping that from the names:</p>\n\n<ul>\n<li><code>brackCounter</code> -> <code>counter</code></li>\n<li><code>openBrackets</code> -> <code>open</code></li>\n<li><code>closedBrackets</code> -> <code>closed</code></li>\n</ul>\n\n<p>Functional programming tries to avoid mutation.\nThe way the object <code>{openBrackets: 0, closedBrackets: 0}</code> is mutated through the reduce goes against that.\nYou could return new <em>tuples</em> instead:</p>\n\n<pre><code>const numberOfUnbalanced = brackets => brackets\n .split(\"\")\n .reduce(([open, closed], b) => {\n return b === \"(\"\n ? [open + 1, closed]\n : open\n ? [open - 1, closed]\n : [open, closed + 1];\n }, [0, 0])\n .reduce((sum, b) => sum + b);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T05:35:30.157",
"Id": "217244",
"ParentId": "217242",
"Score": "1"
}
},
{
"body": "<h2><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\"><code>for of</code></a> not <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in\" rel=\"nofollow noreferrer\"><code>for in</code></a></h2>\n\n<p>I have noticed that on occasion you use the indexing <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in\" rel=\"nofollow noreferrer\"><code>for in</code></a> Try to avoid using this loop as it can be problematic if the object you iterate has inherited properties not set as <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/propertyIsEnumerable\" rel=\"nofollow noreferrer\"><code>enumerable = false</code></a></p>\n\n<p>Use the values iterator <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\"><code>for of</code></a> as it avoids the problems that come with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in\" rel=\"nofollow noreferrer\"><code>for in</code></a>. It also has the benefit of not needing to index the object for the value</p>\n\n<h2>Use <code>const</code></h2>\n\n<p>When using either <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\"><code>for of</code></a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in\" rel=\"nofollow noreferrer\"><code>for in</code></a> and you don't intend to change the value or key use a <code>const</code> eg <code>for(const i in brackets)</code> or <code>for(const char of brackets)</code></p>\n\n<p><strong>Note</strong> That you can not use a <code>const</code> in <code>for(;;)</code> loops but <code>let</code> is allowed. <code>for(let i=0;i<10;i++)</code>. The reason is that even though a new instance of <code>i</code> is created each iteration and assigned the value of the previous <code>i</code>, the last loop expression <code>i++</code> is applied at the bottom of the loop block and thus does not work for constants.</p>\n\n<h2>Simplify</h2>\n\n<p>Strings are iterable objects so you can avoid the need to use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split\" rel=\"nofollow noreferrer\">String.split</a> and use the more succinct spread <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"nofollow noreferrer\"><code>...</code></a> operator. eg <code>[...string]</code> is the same as <code>string.split(\"\");</code></p>\n\n<h2>Complexity</h2>\n\n<ul>\n<li><p>Your imperative function is <span class=\"math-container\">\\$O(n)\\$</span> time and <span class=\"math-container\">\\$O(1)\\$</span> space.</p></li>\n<li><p>Your declarative (you call functional) function is <span class=\"math-container\">\\$O(n)\\$</span> time and <span class=\"math-container\">\\$O(n)\\$</span> space.</p></li>\n</ul>\n\n<h2>Ambiguity</h2>\n\n<p>The question does not indicate if the string will contain characters other than <code>\"()\"</code>, yet the example shows only <code>\"()\"</code> and your solutions count characters other than <code>\"()\"</code> as <code>\")\"</code> so will assume that the input string contains only <code>\"()\"</code></p>\n\n<h2>Solutions</h2>\n\n<h3>Imperative</h3>\n\n<pre><code>function balanced(str) {\n var open = 0, closed = 0;\n for (const char of str) { char === \"(\" ? open++ : (open ? open-- : closed++) } \n return open + closed ;\n}\n</code></pre>\n\n<h3>Declarative</h3>\n\n<pre><code>function balanced(str) {\n const open = counts => (counts[0]++, counts);\n const close = counts => (counts[0] ? counts[0]-- : counts[1]++, counts);\n const counter = (counts, char) => char === \"(\" ? open(counts) : close(counts);\n const sum = arr => arr[0] + arr[1];\n const chars = str => [...str];\n return sum(chars(str).reduce(counter, [0, 0]));\n} \n</code></pre>\n\n<h3>Functional</h3>\n\n<pre><code>function balanced(str) {\n const counter = ([open, closed], char) => {\n char === \"(\" ? open++ : (open ? open-- : closed++);\n return [open, closed];\n }\n const sum = (sum, val) => sum += val;\n return [...str]\n .reduce(counter, [0, 0])\n .reduce(sum, 0);\n} \n</code></pre>\n\n<p>or</p>\n\n<pre><code>function balanced(str) {\n const counter = ([open, closed], char) =>\n (char === \"(\" ? open++ : (open ? open-- : closed++), [open, closed]);\n const res = [...str].reduce(counter, [0, 0])\n return res[0] + res[1];\n} \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T14:57:36.923",
"Id": "420276",
"Score": "0",
"body": "Thanks! You are always offering very insightful and helpful answers with useful background information."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T14:58:40.537",
"Id": "420277",
"Score": "0",
"body": "How do you differentiate between `declarative` vs. `functional`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T15:09:50.917",
"Id": "420281",
"Score": "0",
"body": "Is there a good use case for a `for..in` statement?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T15:17:59.097",
"Id": "420282",
"Score": "0",
"body": "@thadeuszlay In this case declarative has side effects, the array of counts, while functional must not have side effects. `for...in` maybe there are some use cases of merit, but its more of a legacy syntax than practical, IMHO"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T14:54:24.770",
"Id": "217266",
"ParentId": "217242",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "217266",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T03:42:21.053",
"Id": "217242",
"Score": "1",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"functional-programming",
"balanced-delimiters"
],
"Title": "Minimum number of parentheses to be removed to make a string of parentheses balanced"
} | 217242 |
<p>This is my first program with C# and VS and was originally a VBA Add-In I wrote. I have embarked on this as a learning exercise. The code does work and provides the desired output in a new workbook.</p>
<p>The code below is called from a button on a custom ribbon created in Excel. It collects data from other workbooks w/o opening them and compiles the data into a new workbook so it can be easily reviewed.</p>
<p>Some of the things I am looking for in the review are but not limited to:</p>
<ul>
<li>Proper class design</li>
<li>Proper use of static vs non-static</li>
<li>Have best practices been followed regarding connections</li>
</ul>
<p>I am aware that the exception handling needs improvement. Part of me thinks that warrants a question unto itself but making it more explicit is on my todo list. </p>
<p>Below is the only part of the code that is in the VSTO project and has been truncated.</p>
<pre class="lang-cs prettyprint-override"><code>// Ribbon Callbacks
try
{
switch (control.Id)
{
case "fullReport":
FullReport.FullReportMain(Globals.ThisAddIn.Application);
break;
}
}
catch (Exception ex)
{
DialogResult dialogResult = MessageBox.Show(ex.Message, "System Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
</code></pre>
<p>The separate project in the same solution to be reviewed.</p>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Data;
using System.Data.OleDb;
using System.Globalization;
using System.Linq;
using Excel = Microsoft.Office.Interop.Excel;
namespace BfMetricsAddIn
{
/// <summary>
/// Static Class for FullReport button.
/// </summary>
public static class FullReport
{
private const string MNewbornsWS = "Newborns_3";
#if DEBUG
/// <summary>
/// Main for the FullReport.
/// </summary>
/// <param name="xlApp">Excel application</param>
public static void FullReportMain(Excel.Application xlApp)
#else
/// <summary>
/// Main for the FullReport.
/// </summary>
/// <param name="xlApp">Excel Application</param>
public static void FullReportMain(Excel.Application xlApp)
#endif
{
#if DEBUG
string[] pathArray = XlFileDialog.SelectFiles();
#else
string[] pathArray = XlFileDialog.SelectFiles(xlApp);
#endif
BreastFeedingData[] breastFeedingDataArr = new BreastFeedingData[pathArray.Length];
for (int i = 0; i < pathArray.Length; i++)
{
DataTable dataTable = CreateDataTable(pathArray[i]);
breastFeedingDataArr[i] = new BreastFeedingData(dataTable);
}
// Sort Array by date.
BreastFeedingData[] sorted = breastFeedingDataArr.OrderBy(c => c.FileDate).ToArray();
// Create a new workbook
ReportWorkbook repWorkbook = new ReportWorkbook(xlApp, sorted);
try
{
// Add data to newly created workbook
repWorkbook.AddData();
}
catch (Exception)
{
repWorkbook.Workbook.Close(false);
throw;
}
// Save new workbook
string savePath = string.Format(
CultureInfo.CurrentCulture, @"C:\Users\{0}\Documents\BFMetrics\ReportFiles", Environment.UserName);
// Save in default location
const string fileName = @"\" + "BFMetricsReport";
repWorkbook.Workbook.SaveAs(savePath + fileName);
}
/// <summary>
/// Create a DataTable from Excel workbook
/// </summary>
/// <param name="fileName">full path of Excel worksheet.</param>
/// <returns>DataTable from Excel workbook.</returns>
private static DataTable CreateDataTable(string fileName)
{
DataTable dt = null;
OleDbConnection myConnection = null;
try
{
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + fileName +
";Extended Properties='Excel 12.0 xml;HDR=Yes;IMEX=1'";
myConnection = new OleDbConnection(connectionString);
myConnection.Open();
const string sheetName = MNewbornsWS + "$";
OleDbDataAdapter myCommand = new OleDbDataAdapter("select * from [" + sheetName + "]", myConnection);
dt = new DataTable();
myCommand.Fill(dt);
}
catch (Exception)
{
throw;
}
finally
{
myConnection.Close();
}
return dt;
}
}
}
</code></pre>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Globalization;
using Excel = Microsoft.Office.Interop.Excel;
using FileDialog = Microsoft.Office.Core.FileDialog;
using Office = Microsoft.Office.Core;
namespace BfMetricsAddIn
{
/// <summary>
/// The file dialog box selector in Excel.
/// </summary>
public static class XlFileDialog
{
/// <summary>
/// Debugging preselected files.
/// </summary>
/// <returns>Predefined Array for testing.</returns>
public static string[] SelectFiles()
{
string folderPath = string.Format(
CultureInfo.CurrentCulture, @"C:\Users\{0}\Documents\BFMetrics\OriginalMonthFiles\", Environment.UserName);
// Debugging file paths
string[] pathArray = new string[3];
pathArray[0] = folderPath + "BreastfeedingMetrics(Nov18).xlsx";
pathArray[1] = folderPath + "BreastfeedingMetrics(Dec18).xlsx";
pathArray[2] = folderPath + "BreastfeedingMetrics(Aug18).xlsx";
return pathArray;
}
/// <summary>
/// User selects files to collect data from.
/// </summary>
/// <param name="xlApp">Excel Application</param>
/// <returns>Array of full file path strings.</returns>
public static string[] SelectFiles(Excel.Application xlApp)
{
FileDialog dialog = xlApp.FileDialog[Office.MsoFileDialogType.msoFileDialogOpen];
dialog.AllowMultiSelect = true;
dialog.Filters.Add("Excel Files", "*.xlsx", 1);
dialog.InitialFileName = string.Format(
CultureInfo.CurrentCulture, @"C:\Users\{0}\Documents\BFMetrics\OriginalMonthFiles", Environment.UserName);
if (dialog.Show() > 0)
{
string[] pathArray = new string[dialog.SelectedItems.Count];
for (int i = 1; i < dialog.SelectedItems.Count; i++)
{
pathArray[i - 1] = dialog.SelectedItems.Item(i);
}
if (pathArray.Length > 0)
{
return pathArray;
}
throw new ArgumentException($"{pathArray} has a length of zero.");
}
else
{
throw new ArgumentException("File selection canceled by user.");
}
}
}
}
</code></pre>
<pre class="lang-cs prettyprint-override"><code>namespace BfMetricsAddIn
{
/// <summary>
/// Excel workbook that will hold monthly stats report.
/// </summary>
public class ReportWorkbook
{
private readonly Excel.Application xlApp;
private readonly BreastFeedingData[] sorted;
private Excel.Worksheet worksheet;
/// <summary>
/// Initializes a new instance of the <see cref="ReportWorkbook"/> class.
/// </summary>
/// <param name="xlApp">An current instance of the Excel Application.</param>
/// <param name="sorted">Array of BreastFeedingData objects sorted by date.</param>
public ReportWorkbook(Excel.Application xlApp, BreastFeedingData[] sorted)
{
this.xlApp = xlApp;
this.sorted = sorted;
this.Workbook = this.xlApp.Workbooks.Add(Type.Missing);
}
/// <summary>
/// Gets created workbook.
/// </summary>
public Excel.Workbook Workbook { get; }
/// <summary>
/// Adds the data to the workbook
/// </summary>
public void AddData()
{
this.worksheet = this.Workbook.ActiveSheet;
this.worksheet.Name = "StatReport";
string[] rowNames = new string[]
{ "Date", "One Hour Feeding", "Skin to Skin", "Initiation Rate", "Exclusivity Rate", "Number of Babies" };
for (int r = 0; r < rowNames.Length; r++)
{
this.worksheet.Cells[r + 1, 1].Value = rowNames[r];
}
for (int c = 0; c < this.sorted.Length; c++)
{
int r = 1;
this.worksheet.Cells[r++, c + 2].Value = "'" + this.sorted[c].FileDate.ToString("MMMyy", CultureInfo.CurrentCulture);
this.worksheet.Cells[r++, c + 2].Value = this.sorted[c].OneHourFeeding;
this.worksheet.Cells[r++, c + 2].Value = this.sorted[c].SkinToSkin;
this.worksheet.Cells[r++, c + 2].Value = this.sorted[c].InitiationRate;
this.worksheet.Cells[r++, c + 2].Value = this.sorted[c].ExclusivityRate;
this.worksheet.Cells[r++, c + 2].Value = this.sorted[c].NumberOfNewborns;
r = 1;
}
// Formatting
Excel.Range xlDataRange = this.worksheet.Range[
this.worksheet.Cells[1, 2], this.worksheet.Cells[6, this.sorted.Length + 2]];
// Format doubles to percentage
Excel.Range xlDoublesRange = this.worksheet.Range[
this.worksheet.Cells[2, 2], this.worksheet.Cells[5, this.sorted.Length + 2]];
xlDoublesRange.NumberFormat = "##%";
// Set Alignment to center
xlDataRange.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
// AutoFit first column
Excel.Range rowNameColumn = this.worksheet.Columns[1];
rowNameColumn.EntireColumn.AutoFit();
}
}
}
</code></pre>
<pre class="lang-cs prettyprint-override"><code>using System;
using System.Data;
namespace BfMetricsAddIn
{
/// <summary>
/// One month of breast feeding data.
/// </summary>
public class BreastFeedingData
{
// Column names
private const string MFullName = "Full Name";
private const string MMRN = "MRN";
private const string MOHFColumnName = "Time to First Feeding (min)";
private const string MSTSColumnNameC = "Skin to Skin within 1 hour - Cesarean (1=Yes, 0=No)";
private const string MSTSColumnNameV = "Skin to Skin within 1 hour - Vaginal (1=Yes, 0=No)";
private const string MIRColumnName = "Ever Breastfed? (1=Yes, 0=No)";
private const string MERColumnName = "Exclusive? (1=Yes, 0=No)";
private const string MDDColumName = "Discharge Date/Time";
// Constants for String to search for in row
private const string MNBCountRowName = "Mother/Infant - Count distinct";
private const string MNBStatRowName = "Mother/Infant - Total";
private DateTime fileDate;
private double oneHourFeeding;
private double skinToSkin;
private double initiationRate;
private double exclusivityRate;
private int numberOfNewborns;
/// <summary>
/// Initializes a new instance of the <see cref="BreastFeedingData"/> class.
/// </summary>
/// <param name="dt">DataTable created from Excel workbook</param>
public BreastFeedingData(DataTable dt)
{
this.ReadFromDataTable(dt);
}
/// <summary>
/// Gets the number of newborns for the month.
/// </summary>
public int NumberOfNewborns
{
get => this.numberOfNewborns;
internal set
{
if (value == 0)
{
throw new ArgumentOutOfRangeException($"_numberOfNewborns = {value}");
}
else
{
this.numberOfNewborns = value;
}
}
}
/// <summary>
/// Gets the number of newborns fed within the first hour.
/// </summary>
public double OneHourFeeding
{
get => (double)this.oneHourFeeding / this.NumberOfNewborns;
internal set
{
if (value == 0)
{
throw new ArgumentOutOfRangeException($"_oneHourFeeding = {value}");
}
else
{
this.oneHourFeeding = value;
}
}
}
/// <summary>
/// Gets the number of newborns with skin to skin within the first hour.
/// </summary>
public double SkinToSkin
{
get => (double)this.skinToSkin / this.NumberOfNewborns;
internal set
{
if (value == 0)
{
throw new ArgumentOutOfRangeException($"_skinToSkin = {value}");
}
else
{
this.skinToSkin = value;
}
}
}
/// <summary>
/// Gets the number of newborns that have breast fed this month.
/// </summary>
public double InitiationRate
{
get => (double)this.initiationRate / this.NumberOfNewborns;
internal set
{
if (value == 0)
{
throw new ArgumentOutOfRangeException($"_initiationRate = {value}");
}
else
{
this.initiationRate = value;
}
}
}
/// <summary>
/// Gets the number of newborns that have only breast fed this month.
/// </summary>
public double ExclusivityRate
{
get => (double)this.exclusivityRate / this.NumberOfNewborns;
internal set
{
if (value == 0)
{
throw new ArgumentOutOfRangeException($"_exclusivityRate = {value}");
}
else
{
this.exclusivityRate = value;
}
}
}
/// <summary>
/// Gets the month and year associated with the data.
/// </summary>
public DateTime FileDate
{
get => this.fileDate;
internal set
{
if (value == DateTime.MinValue)
{
throw new ArgumentOutOfRangeException($"_fileDate = {value}");
}
else
{
this.fileDate = value;
}
}
}
private void ReadFromDataTable(DataTable dt)
{
int oHFCounter = 0;
bool firstRowFlag = false;
bool keyValueFlagA = false;
bool keyValueFlagB = false;
try
{
foreach (DataRow row in dt.Rows)
{
bool isSuccess;
if (!firstRowFlag)
{
string strDateTime = row[MDDColumName].ToString();
isSuccess = DateTime.TryParse(strDateTime, out DateTime dateTime);
if (isSuccess)
{
this.FileDate = dateTime;
}
firstRowFlag = true;
}
// keyValue is the first column value.
string keyValue = row[MFullName].ToString();
string oneHourFeeding = row[MOHFColumnName].ToString();
isSuccess = int.TryParse(oneHourFeeding, out int oHFItem);
if (isSuccess && oHFItem <= 60 && oHFItem > 0)
{
oHFCounter++;
}
if (keyValue.Equals(MNBCountRowName, StringComparison.Ordinal))
{
keyValueFlagA = true;
string numberOfNewborns = row[MMRN].ToString();
isSuccess = int.TryParse(numberOfNewborns, out int intNumberOfNewborns);
if (isSuccess)
{
this.NumberOfNewborns = intNumberOfNewborns;
}
}
if (keyValue.Equals(MNBStatRowName, StringComparison.Ordinal))
{
keyValueFlagB = true;
string s2sV = row[MSTSColumnNameV].ToString();
isSuccess = int.TryParse(s2sV, out int ints2sV);
string s2sC = row[MSTSColumnNameC].ToString();
isSuccess = int.TryParse(s2sV, out int ints2sC);
if (isSuccess)
{
this.SkinToSkin = ints2sC + ints2sV;
}
string initiationRate = row[MIRColumnName].ToString();
isSuccess = int.TryParse(initiationRate, out int intInitiationRate);
if (isSuccess)
{
this.InitiationRate = intInitiationRate;
}
string exclusivityRate = row[MERColumnName].ToString();
isSuccess = int.TryParse(exclusivityRate, out int intExclusivityRate);
if (isSuccess)
{
this.ExclusivityRate = intExclusivityRate;
}
}
}
if (!keyValueFlagA || !keyValueFlagB)
{
throw new ArgumentException($"Both values must be true. keyValueFlagA: {keyValueFlagA} keyValueFlagB: {keyValueFlagB}.");
}
this.OneHourFeeding = oHFCounter;
}
catch (Exception)
{
throw;
}
}
}
}
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T06:54:44.957",
"Id": "420203",
"Score": "0",
"body": "This is a nice first question! ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T06:56:54.887",
"Id": "420204",
"Score": "0",
"body": "The signature of the `FullReportMain` method in the `FullReport` class is the same in both `DEBUG` and `else` parts - is this intended?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T07:02:15.860",
"Id": "420206",
"Score": "0",
"body": "It is not intended. I just failed to remove it XD. Good catch!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T12:08:55.333",
"Id": "421043",
"Score": "1",
"body": "I posted a question about an error class for VSTO and got a really good response. Hope it helps. :) https://codereview.stackexchange.com/q/205724/158032"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T12:14:43.567",
"Id": "421045",
"Score": "0",
"body": "Also, here's my GitHub site for Excel VSTO projects https://github.com/Excel-projects"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T14:08:30.617",
"Id": "421054",
"Score": "0",
"body": "I agree, those are some great pointers you were given. My favorite take-away from that was the use of var for readability. It really does clean up the code."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T05:01:04.700",
"Id": "217243",
"Score": "3",
"Tags": [
"c#",
"excel"
],
"Title": "Converting VBA Add-In to C# VSTO. Code following button click event"
} | 217243 |
<ul>
<li><p>Requirements</p>
<ul>
<li>Display movie datas inside all tags that have the class movie_list</li>
<li>Make an ajax call for fetching movie datas</li>
<li>Fill loading text before fetch data</li>
<li>If any error occurs during loading, the content should be empty</li>
</ul></li>
<li><p>What I did</p>
<ul>
<li>Cached all elements which have the class movie_list</li>
<li>Made functions which have only one responsibility </li>
<li>Functions take movieList elements for making easy to unit test</li>
</ul></li>
<li><p>What I want to know</p>
<ul>
<li>More readable/reusable code</li>
<li>Any performance improvement point</li>
<li>Any good design pattern on here</li>
</ul></li>
</ul>
<pre><code>function loadMovies() {
const url = 'http://moviedatas.com/movies';
const movieList = $('.movie_list');
setOnLoading(movieList);
$.ajax({
method: 'GET',
url: url,
data: {
count: 10
},
success: function(response) {
movieList.each(function() {
const wrapper = $(this);
render(wrapper, items);
});
},
error: function(error) {
onError(movieList);
}
})
}
function setOnLoading(movieList) {
movieList.each(function() {
$(this).html('Loading...');
});
}
function render(wrapper, items) {
const template = `<div class="movie_item">
<div class="title">{title}</div>
<div class="desc">{description}</div>
</div>`;
let movies = '';
for (let i = 0; i < items.length; i++) {
movies += template
.replace('{title}', items[i].title)
.replace('{description}', items[i].description);
}
wrapper.html(movies);
}
function onError(movieList) {
movieList.each(function() {
$(this).html('');
});
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T11:36:08.360",
"Id": "420405",
"Score": "1",
"body": "Your code is incomplete, you are iterating a movie list (array of elements) passing what is presumably a list of movie titles/descriptions to each, yet there is no reference to `items` in `render(wrapper, items);`? Nor does the code make semantic sense, it reads as creating a movie list of movie lists?? You will have to clarify and fix the code to get a good review."
}
] | [
{
"body": "<p>As pointed out by <strong>Blindman67</strong>: in <code>render(wrapper, items);</code>, <code>items</code> is not defined.</p>\n\n<ol>\n<li><blockquote>\n<pre><code>const url = 'http://moviedatas.com/movies';\n</code></pre>\n</blockquote>\n\n<p>Const variable used only one time, you can remove it and write <code>url: http://moviedatas.com/movies</code></p>\n\n<p>Same for</p>\n\n<pre><code>const wrapper = $(this);\n</code></pre></li>\n<li><p>Use ES6 arrow function shortcut syntax <code>() =></code></p>\n\n<blockquote>\n<pre><code> success: function(response) {\n movieList.each(function() {\n const wrapper = $(this);\n\n render(wrapper, items);\n });\n },\n</code></pre>\n</blockquote>\n\n<p>7 lines in one, shorter is cleaner.</p>\n\n<pre><code>success: (response) => movieList.each(() => render($(this), response.items)),\n</code></pre></li>\n<li><blockquote>\n<pre><code>error: function(error) {\n onError(movieList);\n}\n</code></pre>\n</blockquote>\n\n<p>If you don't use <code>error</code> XHR response, just write</p>\n\n<pre><code>error: () => onError(movieList)\n</code></pre></li>\n<li><p>Write <a href=\"http://usejsdoc.org/about-getting-started.html\" rel=\"nofollow noreferrer\">jsDoc</a> docstring above functions to help developers and IDE understanding what is happening.</p></li>\n<li><p>If functions are becoming inline, you may write them directly in caller function.</p></li>\n</ol>\n\n<h2>Full review (without docstring)</h2>\n\n<pre class=\"lang-js prettyprint-override\"><code>function loadMovies() {\n const movieList = $('.movie_list');\n\n // setOnLoading\n movieList.each(() => $(this).html('Loading...'));\n\n $.ajax({\n method: 'GET',\n url : 'http://moviedatas.com/movies',\n data : { count: 10 },\n success: (response) => movieList.each(() => render($(this), response.items))\n error : () => movieList.each(() => $(this).html(''));\n });\n}\n\nfunction render(wrapper, items) {\n const template = `<div class=\"movie_item\">\n <div class=\"title\">{title}</div>\n <div class=\"desc\">{description}</div>\n </div>`;\n\n let movies = '';\n\n for (let i = 0; i < items.length; i++) {\n movies += template\n .replace('{title}', items[i].title)\n .replace('{description}', items[i].description);\n }\n\n wrapper.html(movies);\n}\n</code></pre>\n\n<p>Also, I don't understand the logic of getting a movie list data and then iterating over a movie list HTML to put movies in. It becomes a list of list of movies...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T08:18:10.080",
"Id": "217471",
"ParentId": "217246",
"Score": "2"
}
},
{
"body": "<p>The code already uses some <a href=\"/questions/tagged/ecmascript-6\" class=\"post-tag\" title=\"show questions tagged 'ecmascript-6'\" rel=\"tag\">ecmascript-6</a> features like the <code>const</code> and <code>let</code> keywords and template literals. </p>\n\n<p>Another ES-6 feature that could be used is the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"nofollow noreferrer\">for...of loop</a> to simplify blocks like this:</p>\n\n<blockquote>\n<pre><code>for (let i = 0; i < items.length; i++) {\n movies += template\n .replace('{title}', items[i].title)\n .replace('{description}', items[i].description);\n}\n</code></pre>\n</blockquote>\n\n<p>To this:</p>\n\n<pre><code>for (const item of items) {\n movies += template\n .replace('{title}', item.title)\n .replace('{description}', item.description);\n}\n</code></pre>\n\n<hr>\n\n<p>The error handler could be simplified using a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Partially_applied_functions\" rel=\"nofollow noreferrer\">partially applied function</a>, to avoid an extra function call - i.e.</p>\n\n<blockquote>\n<pre><code>error: function(error) {\n onError(movieList);\n}\n</code></pre>\n</blockquote>\n\n<p>Can be simplified to: </p>\n\n<pre><code>error: onError.bind(null, movieList)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-09T19:04:39.980",
"Id": "223826",
"ParentId": "217246",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T05:52:01.010",
"Id": "217246",
"Score": "9",
"Tags": [
"javascript",
"jquery",
"ecmascript-6",
"ajax"
],
"Title": "Fetching movie data using jQuery"
} | 217246 |
<p>I am trying to clear my localstorage when I am logging out of the application. I want to write a unit test case in Jasmine to check if this task is performed when logout function is run. I am writing test cases for the first time so got stuck in the approach.</p>
<p>In my compoment.ts file I have a logout function:</p>
<pre><code>logout() {
location.href = "/";
localstorage.clear();
}
</code></pre>
<p>spec.ts file</p>
<pre><code>beforeEach(function () {
var store = {};
spyOn(localStorage, 'getItem').andCallFake(function (key) {
return null;
});
});
</code></pre>
<p>I don't know if this is a correct approach to write the test case for this particular requirement or which one among unit or integration test cases is actually valid for this situation.</p>
| [] | [
{
"body": "<p>If you are using any I/O (in this case, local storage), you must have fallen into an integration test. </p>\n\n<ol>\n<li><strong>A unit test</strong> could be that when <em>logout</em> is executed, the call to\nclearing the local storage is made (using an spy on <em>localStorage</em>). </li>\n<li><strong>An integration test</strong> could be that you have data in the local storage and after you have logged out, you don't. </li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-21T21:09:06.953",
"Id": "220675",
"ParentId": "217247",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T05:52:30.010",
"Id": "217247",
"Score": "1",
"Tags": [
"unit-testing",
"typescript",
"angular-2+",
"jasmine",
"browser-storage"
],
"Title": "Unit Test case to check if localstorage is empty once I logout of the Web app"
} | 217247 |
<p>In this post, I attempted to compare the performance of two concurrency constructs:</p>
<ol>
<li><a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Semaphore.html" rel="nofollow noreferrer"><code>java.util.concurrent.Semaphore</code></a>,</li>
<li><a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/ReentrantReadWriteLock.html" rel="nofollow noreferrer"><code>ReentrantReadWriteLock</code></a>.</li>
</ol>
<p>The idea is to increment/read an <code>int</code> in a thread-safe manner. </p>
<p><strong><code>net.coderodde.concurrent.fun.ConcurrentInt</code></strong>:</p>
<pre><code>package net.coderodde.concurrent.fun;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* This interface defines the API for concurrent access to an {@code int} field.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Apr 10, 2019)
*/
public interface ConcurrentInt {
/**
* This interface method increments the integer.
*/
public void increment();
/**
* This interface method reads the current value of the integer.
* @return
*/
public int read();
static void rethrowInterruptedException(InterruptedException ex,
Logger logger) {
String exceptionMessage =
getExceptionMessage(
Thread.currentThread().getName());
logger.log(Level.SEVERE, exceptionMessage, ex);
throw new RuntimeException(exceptionMessage, ex);
}
static String getExceptionMessage(String threadName) {
return String.format("The thread '%s'"
+ " was interrupted.", threadName);
}
}
</code></pre>
<p><strong><code>net.coderodde.concurrent.fun.SemaphoreConcurrentInt</code></strong>:</p>
<pre><code>package net.coderodde.concurrent.fun.impl;
import net.coderodde.concurrent.fun.ConcurrentInt;
import java.util.concurrent.Semaphore;
import java.util.logging.Logger;
/**
* This class implements a {@link net.coderodde.concurrent.fun.ConcurrentInt} -
* interface via (binary) semaphores.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Apr 10, 2019)
*/
public final class SemaphoreConcurrentInt implements ConcurrentInt {
/**
* This static field the object for neat printing of messages to a console.
*/
private static final Logger LOGGER =
Logger.getLogger(SemaphoreConcurrentInt.class.getName());
/**
* The actual integer field.
*/
private volatile int integer;
/**
* A semaphore for concurrent access to the {@code integer}.
*/
private final Semaphore mutex = new Semaphore(1, true);
@Override
public void increment() {
try {
mutex.acquire();
integer++;
mutex.release();
} catch (InterruptedException ex) {
ConcurrentInt.rethrowInterruptedException(ex, LOGGER);
}
}
@Override
public int read() {
int value = 0;
try {
mutex.acquire();
value = integer;
mutex.release();
} catch (InterruptedException ex) {
ConcurrentInt.rethrowInterruptedException(ex, LOGGER);
}
return value;
}
}
</code></pre>
<p><strong><code>net.coderodde.concurrent.fun.ReentrantLockConcurrentInt</code></strong>:</p>
<pre><code>package net.coderodde.concurrent.fun.impl;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import net.coderodde.concurrent.fun.ConcurrentInt;
/**
* This class implements a {@link net.coderodde.concurrent.fun.ConcurrentInt} -
* interface via a re-entrant lock.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Apr 10, 2019)
*/
public final class ReentrantLockConcurrentInt implements ConcurrentInt {
/**
* The actual integer field.
*/
private volatile int integer;
/**
* A semaphore for concurrent access to the {@code integer}.
*/
private final ReentrantReadWriteLock lock =
new ReentrantReadWriteLock(true);
@Override
public void increment() {
lock.writeLock().lock();
integer++;
lock.writeLock().unlock();
}
@Override
public int read() {
lock.readLock().lock();
int value = integer;
lock.readLock().unlock();
return value;
}
}
</code></pre>
<p><strong><code>Main.java</code></strong>:</p>
<pre><code>package net.coderodde.concurrent.fun;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.coderodde.concurrent.fun.impl.ReentrantLockConcurrentInt;
import net.coderodde.concurrent.fun.impl.SemaphoreConcurrentInt;
/**
* This class implements a demo program for benchmarking the concurrency
* facilities for incrementing an integer.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Apr 10, 2019)
* @see net.coderodde.concurrent.fun.ConcurrentInt
* @see net.coderodde.concurrent.fun.impl.SemaphoreConcurrentInt
* @see net.coderodde.concurrent.fun.impl.
*/
public class Main {
/**
* This static inner class groups all the default values.
*/
private static final class DefaultValues {
/**
* The default number oF read operations per thread.
*/
private static final int DEFAULT_NUMBER_OF_READ_OPERATIONS = 1_000;
/**
* The default number of increment operations per thread.
*/
private static final int DEFAULT_NUMBER_OF_INCREMENT_OPERATIONS = 1_000;
/**
* The default number of increment threads.
*/
private static final int DEFAULT_NUMBER_OF_INCREMENT_THREADS = 10;
/**
* The default number of read threads.
*/
private static final int DEFAULT_NUMBER_OF_READ_THREADS = 10;
}
/**
* This static inner class groups all the minimum values.
*/
private static final class MinimumValues {
/**
* The minimum number of read operations per thread.
*/
private static final int MINIMUM_NUMBER_OF_READ_OPERATIONS = 1;
/**
* The minimum number of increment operations per thread.
*/
private static final int MINIMUM_NUMBER_OF_INCREMENT_OEPRATIONS = 1;
/**
* The minimum number of increment threads.
*/
private static final int MINIMUM_NUMBER_OF_INCREMENT_THREADS = 1;
/**
* The minimum number of read threads.
*/
private static final int MINIMUM_NUMBER_OF_READ_THREADS = 1;
}
/**
* This inner static class contains all the return values of this program.
*/
private static final class ReturnValues {
/**
* Returned whenever we cannot parse the number of read threads.
*/
private static final int ERROR_NUMBER_OF_READ_THREADS = 3;
/**
* Returned whenever we cannot parse the number of increment threads.
*/
private static final int ERROR_NUMBER_OF_INCREMENT_THREADS = 2;
/**
* Returned whenever we cannot parse the number of read operations.
*/
private static final int ERROR_NUMBER_OF_READ_OPERATIONS = 3;
/**
* Returned whenever we cannot parse the number of increment operations.
*/
private static final int ERROR_NUMBER_OF_INCREMENT_OPERATIONS = 4;
}
/**
* This static inner class contains all the command line flags.
*/
private static final class CommandLineFlags {
/**
* Print verbose operations.
*/
private static final String VERBOSE_SHORT = "-v";
/**
* Print verbose operation. Longer flag.
*/
private static final String VERBOSE_LONG = "--verbose";
/**
* Print program version.
*/
private static final String VERSION = "--version";
/**
* Print help message.
*/
private static final String HELP_SHORT = "-h";
/**
* Print help message. Longer flag.
*/
private static final String HELP_LONG = "--help";
}
private static final String HELP_MESSAGE =
"Usage:\n" +
" java -jar This.jar [" + CommandLineFlags.VERSION + "] " +
" [" + CommandLineFlags.HELP_SHORT + " | " +
CommandLineFlags.HELP_LONG + "] [" +
CommandLineFlags.VERBOSE_SHORT + " | " +
CommandLineFlags.VERBOSE_LONG + "} [RT [IT [NR [NI]]]] where\n" +
" RT number of read threads,\n" +
" IT number of increment threads,\n" +
" NR number of read operations,\n" +
" NI number of increment threads.";
private static final String VERSION_MESSAGE =
"ReadAccessTrial, v1.6 by Rodion \"rodde\" Efremov, Apr. 11, 2019";
/**
* The logger of this class.
*/
private static final Logger LOGGER = Logger.getLogger(Main.class.getName());
/**
* This static inner class implements a thread type operating on a given
* {@link net.coderodde.concurrent.fun.ConcurrentInt}.
*/
private static final class ConcurrentIntIncrementerThread extends Thread {
/**
* The operation this thread performs.
*/
enum Operation {
/**
* Denotes that this thread runs
* {@link net.coderodde.concurrent.fun.ConcurrentInt#increment()}.
*/
INCREMENT,
/**
* Denotes that this thread runs
* {@link net.coderodde.concurrent.fun.ConcurrentInt#read()}.
*/
READ,
}
/**
* The instance of {@link net.coderodde.concurrent.fun.ConcurrentInt} to
* work on.
*/
private final ConcurrentInt concurrentInt;
/**
* The number of operations to perform.
*/
private final int numberOfOperations;
/**
* The operation to perform.
*/
private final Operation operation;
ConcurrentIntIncrementerThread(ConcurrentInt concurrentInt,
int numberOfOperations,
Operation operation) {
this.concurrentInt = concurrentInt;
this.numberOfOperations = numberOfOperations;
this.operation = operation;
}
@Override
public void run() {
switch (operation) {
case INCREMENT:
runIncrements();
break;
case READ:
runReads();
break;
default:
throw new IllegalStateException(
"Unknowon operation: " + operation);
}
}
private void runIncrements() {
for (int i = 0; i < numberOfOperations; i++) {
concurrentInt.increment();
}
}
private void runReads() {
for (int i = 0; i < numberOfOperations; i++) {
concurrentInt.increment();
}
}
}
private static int parseCommandLineArgument(String argument,
String numberFormatMessage,
int exitValue) {
try {
return Integer.parseInt(argument);
} catch (NumberFormatException ex) {
LOGGER.log(Level.SEVERE,
String.format(numberFormatMessage, argument));
System.exit(exitValue);
return Integer.MIN_VALUE;
}
}
private static final boolean argumentsContainFlag(String[] arguments,
String flag) {
for (int i = 0; i < arguments.length; i++) {
if (flag.equals(arguments[i])) {
return true;
}
}
return false;
}
private static String[] removeArgument(String[] arguments, String flag) {
int count = 0;
for (String srgument : arguments) {
if (srgument.equals(flag)) {
count++;
}
}
String[] newArguments = new String[arguments.length - count];
for (int sourceIndex = 0, targetIndex = 0;
sourceIndex < arguments.length;
sourceIndex++) {
String argument = arguments[sourceIndex];
if (!argument.equals(flag)) {
newArguments[targetIndex++] = argument;
}
}
return newArguments;
}
public static void main(String[] args) {
boolean verbose = false;
if (argumentsContainFlag(args, CommandLineFlags.VERBOSE_SHORT)) {
verbose = true;
args = removeArgument(args, CommandLineFlags.VERBOSE_SHORT);
}
if (argumentsContainFlag(args, CommandLineFlags.VERBOSE_LONG)) {
verbose = true;
args = removeArgument(args, CommandLineFlags.VERBOSE_LONG);
}
if (argumentsContainFlag(args, CommandLineFlags.VERSION)) {
args = removeArgument(args,CommandLineFlags.VERSION);
System.out.println(VERSION_MESSAGE);
System.exit(0);
}
if (argumentsContainFlag(args, CommandLineFlags.HELP_SHORT) ||
argumentsContainFlag(args, CommandLineFlags.HELP_LONG)) {
System.out.println(HELP_MESSAGE);
System.exit(0);
}
int numberOfReadThreads =
DefaultValues.DEFAULT_NUMBER_OF_READ_THREADS;
int numberOfIncrementThreads =
DefaultValues.DEFAULT_NUMBER_OF_INCREMENT_THREADS;
int numberOfReadOperations =
DefaultValues.DEFAULT_NUMBER_OF_READ_OPERATIONS;
int numberOfIncrementOperations =
DefaultValues.DEFAULT_NUMBER_OF_INCREMENT_OPERATIONS;
switch (args.length) {
case 4:
// Fall through!
numberOfIncrementOperations =
parseCommandLineArgument(
args[3],
"Could not parse '%s' as the number of increment " +
"operations.",
ReturnValues.ERROR_NUMBER_OF_INCREMENT_OPERATIONS);
// Fall through!
case 3:
numberOfReadOperations =
parseCommandLineArgument(
args[2],
"Could not parse'%s' as the number of read " +
"operations.",
ReturnValues.ERROR_NUMBER_OF_READ_OPERATIONS);
// Fall through!
case 2:
numberOfIncrementThreads =
parseCommandLineArgument(
args[1],
"Could not parse '%s' as the number of increment " +
"threads.",
ReturnValues.ERROR_NUMBER_OF_INCREMENT_THREADS);
// Fall through!
case 1:
numberOfReadThreads =
parseCommandLineArgument(
args[0],
"Coudl not parse '%s' as the number of read " +
"threads.",
ReturnValues.ERROR_NUMBER_OF_READ_THREADS);
}
int effectiveNumberOfReadThreads =
Math.max(numberOfReadThreads,
MinimumValues.MINIMUM_NUMBER_OF_READ_THREADS);
int effecitveNumberOfIncrementThreads =
Math.max(numberOfIncrementThreads,
MinimumValues.MINIMUM_NUMBER_OF_INCREMENT_THREADS);
int effectiveNumberOfReadOperations =
Math.max(numberOfReadOperations,
MinimumValues.MINIMUM_NUMBER_OF_READ_OPERATIONS);
int effectiveNumberOfIncrementOperations =
Math.max(numberOfIncrementOperations,
MinimumValues.MINIMUM_NUMBER_OF_INCREMENT_OEPRATIONS);
if (verbose) {
printEffectiveArguments(numberOfReadThreads,
numberOfIncrementThreads,
numberOfReadOperations,
numberOfIncrementOperations,
effectiveNumberOfReadThreads,
effecitveNumberOfIncrementThreads,
effectiveNumberOfReadOperations,
effectiveNumberOfIncrementOperations);
}
ConcurrentInt concurrentInt1 = new SemaphoreConcurrentInt();
ConcurrentInt concurrentInt2 = new ReentrantLockConcurrentInt();
long duration;
duration = benchmark(concurrentInt1,
numberOfReadOperations,
numberOfIncrementOperations,
numberOfReadThreads,
numberOfIncrementThreads);
System.out.println(String.format("%d in %d milliseconds.",
concurrentInt1.read(),
duration));
duration = benchmark(concurrentInt2,
numberOfReadThreads,
numberOfIncrementThreads,
numberOfReadOperations,
numberOfIncrementOperations);
System.out.println(String.format("%d in %d milliseconds.",
concurrentInt2.read(),
duration));
}
private static void printEffectiveArguments(
int numberOfReadThreads,
int numberOfIncrementThreads,
int numberOfReadOperations,
int numberOfIncrementOperations,
int effectiveNumberOfReadThreads,
int effectiveNumberOfIncrementThreads,
int effectiveNumberOfReadOperations,
int effectiveNumberOfIncrementOperations) {
System.out.println("Requested parameters >>>");
System.out.println("Number of read threads: " + numberOfReadThreads);
System.out.println("Number of increment threads: " +
numberOfIncrementThreads);
System.out.println("Number of read operations: " +
numberOfReadOperations);
System.out.println("Number of increment operations: " +
numberOfIncrementOperations);
System.out.println("Effective parameters >>>");
System.out.println("Effective number of read threads: " +
effectiveNumberOfReadThreads);
System.out.println("Effective number of increment threads: " +
effectiveNumberOfIncrementThreads);
System.out.println("Effective number of read operations: " +
effectiveNumberOfReadOperations);
System.out.println("Effective number of increment operations: " +
effectiveNumberOfIncrementOperations);
}
/**
* This static method performs the actual benchmaark.
* @param concurrentInt the {@link net.coderodde.concurrent.fun.ConcurrentInt}
* to operate on.
* @param numberOfReadThreads the number of read threads.
* @param numberOfIncrementThreads the number of increment threads.
* @param numberOfReadOperations the number of read operations per
* thread.
* @param numberOfIncrementOperations the number of increment operations per
* thread.
* @return the number of milliseconds that took to operate on the
* {@link net.coderodde.concurrent.fun.ConcurrentInt}.
*/
private static final long benchmark(ConcurrentInt concurrentInt,
int numberOfReadThreads,
int numberOfIncrementThreads,
int numberOfReadOperations,
int numberOfIncrementOperations) {
List<ConcurrentIntIncrementerThread>
concurrenetIntIncrementerThreadList =
new ArrayList<>(numberOfReadThreads +
numberOfIncrementThreads);
for (int i = 0; i < numberOfReadThreads; i++) {
concurrenetIntIncrementerThreadList.add(
new ConcurrentIntIncrementerThread(
concurrentInt,
numberOfReadOperations,
Main.ConcurrentIntIncrementerThread
.Operation
.READ));
}
for (int i = 0; i < numberOfIncrementThreads; i++) {
concurrenetIntIncrementerThreadList.add(
new ConcurrentIntIncrementerThread(
concurrentInt,
numberOfIncrementOperations,
Main.ConcurrentIntIncrementerThread
.Operation
.INCREMENT));
}
Collections.shuffle(concurrenetIntIncrementerThreadList);
long startMoment = System.currentTimeMillis();
for (ConcurrentIntIncrementerThread thread : concurrenetIntIncrementerThreadList) {
thread.start();
}
for (ConcurrentIntIncrementerThread thread : concurrenetIntIncrementerThreadList) {
try {
thread.join();
} catch (InterruptedException ex) {
LOGGER.log(Level.SEVERE,
String.format(
"The thread '{0}' threw " +
"InterruptedException: {1}",
thread.getName(),
ex.getMessage()));
throw new RuntimeException(ex);
}
}
long endMoment = System.currentTimeMillis();
return endMoment - startMoment;
}
}
</code></pre>
<p><strong>Sample output</strong></p>
<pre><code>java -jar ReadAccessTrial.jar 2 2 2000 2000
8000 in 803 milliseconds.
8000 in 157 milliseconds.
</code></pre>
<p><strong>Critique request</strong></p>
<p>I would like to hear comments on coding conventions, readability and maintainability, to name a few.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T16:31:23.193",
"Id": "420291",
"Score": "1",
"body": "Request for Clarification:\n\nYou're question lacks, well, **a question**. What type of feedback are you interested in? Coding format? Performance? Readability/Maintainability? Better ways to do the same process/ tasks?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T05:13:26.867",
"Id": "420348",
"Score": "0",
"body": "@DapperDan Addes a `Critique request` section to my post."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T08:00:45.023",
"Id": "217252",
"Score": "2",
"Tags": [
"java",
"multithreading",
"thread-safety",
"concurrency",
"locking"
],
"Title": "Comparing Java Semaphore versus ReentrantReadWriteLock"
} | 217252 |
<h1>Problem</h1>
<p>I have written code to solve this <a href="https://pandaoj.com/problem/JC7E" rel="nofollow noreferrer">challenge</a>:</p>
<blockquote>
<p>Given a formula:</p>
<p><a href="https://i.stack.imgur.com/beC0x.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/beC0x.gif" alt="Formula" /></a></p>
<p>GCD(x,y) means the GCD (Greatest Common Divisor) of x and y.</p>
<p>For example: if N=2, then:</p>
<ul>
<li>f(2) = 1/GCD(1, 4) + 2/GCD(2, 4) + 3/GCD(3, 4) + 4/GCD(4,4)</li>
<li>f(2) = 1/1 + 2/2 + 3/1 + 4/4</li>
<li>f(2) = 1 + 1 + 3 + 1</li>
<li>f(2) = 6</li>
</ul>
<p>Given <strong>N</strong>, find <strong>f(N)</strong>.</p>
<p>Output:</p>
<p>Value of f(N) modulo 1.000.000.007 (109 + 7)</p>
<p>Edit: Output should be in modulo <strong>10^9 + 7</strong></p>
</blockquote>
<p>I found a simplified formula using Wolframalpha, by finding the first 10 elements: <strong><a href="https://www.wolframalpha.com/input/?i=1,%202,%206,%2022,%2086,%20342,%201366,%205462,%2021846,%2087382,%20349526&fbclid=IwAR3utjx7Qh0bKYRR0DCGNbP0yvaa7zgNFcqYdjaWPaHfju0LJFHRrL0G2RI" rel="nofollow noreferrer">(4^(n + 1) + 8) / 12</a></strong></p>
<h1>Code</h1>
<pre><code>#include <bits/stdc++.h>
#define MOD 1000000007
using namespace std;
typedef short i16;
typedef unsigned short u16;
typedef int i32;
typedef unsigned int u32;
typedef long int i64;
typedef unsigned long int u64;
typedef float f32;
typedef double f64;
u64 pawa(u64 a, u64 b){
u64 tot = 1;
for (u64 i = 0; i < b; i++) {
tot *= a;
tot = tot % MOD;
}
return tot;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
u64 n;
cin>>n;
cout<<(pawa(4, n + 1) + 8) / 12<<'\n';
return 0;
}
</code></pre>
<p>This code scales poorly - time limit exceeded. The upper corner constraint is <strong>10^9</strong>. How do I improve my algorithm?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T09:54:46.530",
"Id": "420229",
"Score": "2",
"body": "Think about it a bit, or google it, but exponentiation should only use log(Exponent) multiplications, not Exponent ones."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T12:20:05.447",
"Id": "420239",
"Score": "0",
"body": "What's that `MOD` constant there for? Is there a part of the challenge that requires that (if so, it should be in the description)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T12:35:30.777",
"Id": "420251",
"Score": "0",
"body": "@TobySpeight Sorry, I forgot to write it, it's part of the challenge. Its included in the output description."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T13:03:52.073",
"Id": "420261",
"Score": "0",
"body": "@Deduplicator, this particular case (a fixed base of 4) gets a nice easy head start by bit shifting before we even need to think about multiplication..."
}
] | [
{
"body": "<p>It's great that you found a closed form to generate the results. Shame that it was by search rather than by reasoning. (<em>i/GCD(i, 2^n)</em> is simply <em>i</em> shifted right until it's odd, so we get the sequence (in binary) 1**,** 1<s>0</s><strong>,</strong> 11, 1<s>00</s><strong>,</strong> 101, 11<s>0</s><strong>,</strong> 111, 11<s>00</s><strong>,</strong> ... You can see that every other value is divided by 2, every fourth value divided by 4 and so on; that allows you to arrive at the closed form fairly quickly.</p>\n\n<p>I'll note that the numerator and denominator have a common factor of 4, so could be reduced to <span class=\"math-container\">\\$\\frac{4^n+2}3\\$</span>.</p>\n\n<p>Now to the code:</p>\n\n<p><code><bits/stdc++.h></code> is non-portable, and extremely wasteful. Include only the headers that are needed; in this case just <code><iostream></code>.</p>\n\n<p>Instead of using a preprocessor <code>#define</code> for a constant integer, always prefer to use a C++ constant. Macros don't respect context.</p>\n\n<p>Avoid <code>using namespace std;</code>. It doesn't even save you typing, once the unnecessary <code>stdio</code> operations are removed.</p>\n\n<p>The typedefs are misleading: the name <code>u64</code> suggests that <code>unsigned long</code> happens to be 64 bits on your particular target, but it also suggests that you've written brittle code that depends on that assumption (and all the other typedefs appear to be unused). For this code, I think we really should be using <code>std::uint_fast64_t</code> from <code><cstdint></code>.</p>\n\n<p>Moving on to <code>main()</code>: as hinted earlier, <code>std::ios_base::sync_with_stdio()</code> and <code>std::cin::tie()</code> are pointless, given that we're not using the C standard streams, so should be omitted. Also, there's no checking that streaming from <code>std::cin</code> was successful; that's easily fixed.</p>\n\n<p>Now we need to look at <code>pawa()</code>. Given that we only ever call it with <code>a</code> equal to 4, then we can make a special-purpose function rather than a general <code>modpow()</code> - let's call it <code>exp4mod()</code> (meaning exponentiation base 4, modulo 1000000007).</p>\n\n<p>For values of <code>b</code> less than 15, the result is less than 1000000007, so that is easily computed as <code>1u << (2*b)</code>. Values of 15 or more can be reduced using the identity <span class=\"math-container\">\\$4^{14a+b} = (4^{14})^a4^b\\$</span>, and then we can use a standard binary exponentiation for the first part and a shift for the second.</p>\n\n<p>All that said, it's unclear why the exponentiation must be done modulo 1000000007 - the description says that the <em>result</em> be reduced modulo such a number. So perhaps there's a logic error there, and we really need to be reducing modulo 3000000021 (having reduced the fraction so we divide by 3)?</p>\n\n<p>Here's the version I ended up with, having made the recommended changes (and modifying <code>main()</code> not to require input):</p>\n\n<pre><code>#include <cstdint>\n#include <iostream>\n\nusing u64 = std::uint_fast64_t;\n\n\nstatic u64 modpow(u64 x, u64 y, u64 mod)\n{\n u64 result = 1;\n while (y) {\n if (y%2) {\n result = result * x % mod;\n }\n x = x * x % mod;\n y /= 2;\n }\n\n return result;\n}\n\nstatic u64 exp4mod(u64 x)\n{\n static auto const mod = 3000000021;\n static auto const chunk_size = 16;\n\n static const u64 one = 1;\n static auto const residue = (one << 2*chunk_size) % mod; // 4^15%mod = 73741817\n\n const auto a = x / chunk_size;\n const auto b = x % chunk_size;\n return (modpow(residue, a, mod) << (2 * b)) % mod;\n}\n\nint main()\n{\n for (u64 n = 0; n < 35; ++n)\n std::cout << n << \": \" << (exp4mod(n) + 2) / 3 << '\\n';\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T12:45:08.720",
"Id": "420914",
"Score": "0",
"body": "Thanks for the answer. I just have read the modular exponentiation and solve it before, but I really appreciate the review!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T14:24:06.193",
"Id": "217263",
"ParentId": "217254",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "217263",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T08:36:36.973",
"Id": "217254",
"Score": "1",
"Tags": [
"c++",
"performance",
"algorithm",
"time-limit-exceeded",
"mathematics"
],
"Title": "Sum of number's quotients when divided by exact powers of 2"
} | 217254 |
<p>I'm pretty new to Qt but already have a little experience with C++ so the first "project" I wanted to try out was a <strong><em>GUI random number generator</em></strong>.
I am looking for some advices either in naming conventions or OOP architecture, what should I do better and what I'm already doing good. The code is really short so there is not so much to review but I hope you will find something.</p>
<p>1) I know that you should NOT use <code>_</code> prefix, but I really like it and <code>m_</code> looks ugly to me. </p>
<p>2) I could not decide whether it's good to write code like this ( I find this better ):</p>
<pre><code>_maxSpinBox->setMinimum ( Config::SpinBox::minimum );
_maxSpinBox->setMaximum ( Config::SpinBox::maximum );
_maxSpinBox->setSingleStep ( Config::SpinBox::single_step );
_maxSpinBox->setValue ( Config::SpinBox::default_value );
</code></pre>
<p>Or like this</p>
<pre><code>_maxSpinBox->setMinimum ( Config::SpinBox::minimum );
_maxSpinBox->setMaximum ( Config::SpinBox::maximum );
_maxSpinBox->setSingleStep ( Config::SpinBox::single_step );
_maxSpinBox->setValue ( Config::SpinBox::default_value );
</code></pre>
<p>3) I also thought about adding <code>using namespace Config;</code> into <code>generator.cpp</code> because writing <code>Config::</code> everywhere is really annoying.</p>
<p>Thanks for tips</p>
<p><a href="https://i.stack.imgur.com/oyDsY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/oyDsY.png" alt="enter image description here"></a></p>
<p><strong><em>main.cpp</em></strong></p>
<hr>
<pre><code>#include <QApplication>
#include <iostream>
#include "generator.h"
int main(int argc, char **argv)
{
QApplication qapp( argc, argv );
Generator generator{};
generator.show ();
try {
qapp.exec();
}
catch(const std::exception& e) {
std::cerr << e.what () << std::endl;
}
return 0;
}
</code></pre>
<p><strong><em>config.h</em></strong></p>
<pre><code>#ifndef CONFIG_H
#define CONFIG_H
#include <QFont>
#include <QString>
namespace Config
{
namespace Window
{
constexpr static int height = 150;
constexpr static int width = 300;
} // Window
namespace Button
{
const static QString title = "Generate";
constexpr static int height = 30;
constexpr static int width = 80;
constexpr static int pos_x = Window::width / 2 - width / 2;
constexpr static int pos_y = Window::height - height - 10;
} // Button
namespace Display
{
constexpr static int height = 45;
constexpr static int width = 90;
constexpr static int pos_x = Window::width / 2 - width / 2;
constexpr static int pos_y = 20;
constexpr static int default_value = 0;
} // Display
namespace Fonts
{
const static QFont serifFont( "Times", 10, QFont::Bold );
const static QFont sansFont( "Helvetica [Cronyx]", 12 );
} // Fonts
namespace SpinBox
{
constexpr static int minimum = -30000;
constexpr static int maximum = 30000;
constexpr static int single_step = 1;
constexpr static int default_value = 0;
} // SpinBox
} // Config
#endif // CONFIG_H
</code></pre>
<p><strong><em>generator.h</em></strong></p>
<pre><code>#ifndef GENERATOR_H
#define GENERATOR_H
#include <QWidget>
#include <exception>
class QPushButton;
class QLabel;
class QSpinBox;
class QGroupBox;
class QVBoxLayout;
struct BadParameters : std::logic_error
{
using std::logic_error::logic_error;
};
class Generator : public QWidget
{
Q_OBJECT
public:
explicit Generator( QWidget* parent = nullptr );
public slots:
void showNumber();
signals:
private:
QPushButton* _button;
QLabel* _display;
QSpinBox* _minSpinBox;
QSpinBox* _maxSpinBox;
QGroupBox* _groupBox;
QVBoxLayout* _layout;
int _generateNumber( int low, int high );
void _createSpinBoxes();
void _createMinSpinBox();
void _createMaxSpinBox();
void _createSpinBoxLayout();
void _createButton();
void _createDisplay();
void _init();
};
#endif // GENERATOR_H
</code></pre>
<p><strong><em>generator.cpp</em></strong></p>
<pre><code>#include <QGroupBox>
#include <QLabel>
#include <QPushButton>
#include <QSpinBox>
#include <QTime>
#include <QVBoxLayout>
#include <random>
#include <qglobal.h>
#include "config.h"
#include "generator.h"
Generator::Generator( QWidget* parent )
: QWidget( parent )
{
_init();
_createDisplay ();
_createButton ();
_createSpinBoxes ();
connect ( _button, SIGNAL(clicked()), this, SLOT(showNumber()) );
}
void Generator::_init() {
QTime time = QTime::currentTime ();
qsrand( static_cast< uint >( time.msec ()) );
setFixedSize( Config::Window::width, Config::Window::height );
setWindowTitle( "Random Number Generator" );
}
void Generator::_createButton() {
_button = new QPushButton( Config::Button::title, this );
_button->setGeometry ( Config::Button::pos_x,
Config::Button::pos_y,
Config::Button::width,
Config::Button::height );
}
void Generator::_createDisplay() {
_display = new QLabel( this );
_display->setFont ( Config::Fonts::sansFont );
_display->setAlignment ( Qt::AlignCenter);
_display->setGeometry ( Config::Display::pos_x,
Config::Display::pos_y,
Config::Display::width,
Config::Display::height );
_display->setNum ( Config::Display::default_value );
}
void Generator::_createSpinBoxes() {
_createMinSpinBox();
_createMaxSpinBox();
_createSpinBoxLayout();
}
void Generator::_createSpinBoxLayout(){
_groupBox = new QGroupBox( this );
_layout = new QVBoxLayout;
QLabel* labelMin = new QLabel( tr("Minimum: ") );
QLabel* labelMax = new QLabel( tr("Maximum: ") );
_layout->addWidget ( labelMin );
_layout->addWidget ( _minSpinBox );
_layout->addWidget ( labelMax );
_layout->addWidget ( _maxSpinBox );
_groupBox->setLayout ( _layout );
}
void Generator::_createMaxSpinBox() {
_maxSpinBox = new QSpinBox ( this );
_maxSpinBox->setMinimum ( Config::SpinBox::minimum );
_maxSpinBox->setMaximum ( Config::SpinBox::maximum );
_maxSpinBox->setSingleStep ( Config::SpinBox::single_step );
_maxSpinBox->setValue ( Config::SpinBox::default_value );
}
void Generator::_createMinSpinBox() {
_minSpinBox = new QSpinBox ( this );
_minSpinBox->setMinimum ( Config::SpinBox::minimum );
_minSpinBox->setMaximum ( Config::SpinBox::maximum );
_minSpinBox->setSingleStep ( Config::SpinBox::single_step );
_minSpinBox->setValue ( Config::SpinBox::default_value );
}
int Generator::_generateNumber( int low, int high ) {
if ( low > high ) {
throw BadParameters( "Upper bound is NOT higher \n" );
}
return qrand() % (( high + 1) - low) + low;
}
void Generator::showNumber() {
_display->setNum( _generateNumber( _minSpinBox->value(),
_maxSpinBox->value () ));
}
</code></pre>
<p>This</p>
| [] | [
{
"body": "<p>your first statement is that you want advice in naming conventions and in your second line you state</p>\n\n<blockquote>\n <p>I know that you should NOT use _ prefix, but I really like it and m_ looks ugly to me.</p>\n</blockquote>\n\n<p>Some conventions are just form and it is up to you to decide what you like better. The reason not to use names in c++ that are prefixed with an underscore is that you are just one keystroke away from writing identifiers that are considered invalid. The standard reserves <code>_<UpperCaseLetter></code> and <code>__</code> for internal identifiers. So the advice is stay away from leading underscores. </p>\n\n<p>Where you put your parenthesis is totally up to you, don't get too attached to your style as each project, or each company will have their own style that you should adhere to. My personal advice here, use <code>clang-format</code> or a similar tool and never manually shift things around. </p>\n\n<p>With regard to QT there are differing opinions, my advice is <em>use the designer</em>! Laying UIs out by hand is not a good use of your time. It becomes more and more tedious, these tools are made for a reason and a lot of layout tasks can be done using the QT Designer. This would alleviate your namespace problem for example. And remove most of the code that you wrote dealing with the construction of the UI. It will let you focus on crafting a well thought out and convenient UI rather than writing rote and repetitive code to create the widgets that make up the UI. Some of the following comments are more on the quality of the UI than the code, but I see that as part of the project that you created.</p>\n\n<p>Albeit doing it once is a decent exercise and it looks ok. Although it really doesn't handle ok, If you have the requirement that <code>Minimum</code> is smaller than <code>Maximum</code> your UI should enforce that and not let the user set a minimum that is larger than maximum. Right now your UI will just crash, that is not good. At least an error message would be better, but i'd really expect the UI to enforce any give constraints.</p>\n\n<p>Your question is tagged just <code>c++</code> and not <code>c++11</code>. If you are just learning C++ that you should learn least c++11, and not start with anything prior. Qt is somewhat orthogonal, and sometimes even blocks some of these features. But it is going to be a lot easier to step back to an older version of c++ than to learn new things. In that vein you should look at this writeup about a variation on how to <a href=\"https://wiki.qt.io/New_Signal_Slot_Syntax\" rel=\"nofollow noreferrer\">connect signals and slots</a>.</p>\n\n<p>Keep it up ... </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T09:40:11.220",
"Id": "420388",
"Score": "0",
"body": "Thanks for a tip with QtDesigner, it is really useful tool and it also has shortened my code a lot!\nWhat do you think about getting values from spinboxes? Is it \"better\" to call `value()` every time I need it or to make separate function `extractValues()` which will fill my two attributes with these values. Thanks"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T14:52:50.610",
"Id": "217265",
"ParentId": "217257",
"Score": "3"
}
},
{
"body": "<p>I see a number of things that may help you improve your program.</p>\n\n<h2>Use proper case for file names</h2>\n\n<p>We all know that Windows is not case sensitive with respect to file names, but pretty much every other operating system out there (Apple's OS X, Linux, BSD, etc.) is. For that reason, when you have a class named <code>Generator</code> it should be in a file named <code>Generator.h</code> rather than <code>generator.h</code> or tools such as <code>moc</code> won't recognize them on any OS other than Windows. By using proper case for file names now, you can avoid all future annoyance in having to port the code to any other OS.</p>\n\n<h2>Don't <code>throw</code> from a Qt event handler</h2>\n\n<p>Qt does not support <code>throw</code>ing an exception from within an event handler, so this code:</p>\n\n<pre><code>int Generator::_generateNumber( int low, int high ) {\n if ( low > high ) {\n throw BadParameters( \"Upper bound is NOT higher \\n\" );\n }\n return qrand() % (( high + 1) - low) + low;\n}\n</code></pre>\n\n<p>will generate the following error under Qt5:</p>\n\n<blockquote>\n <p>Qt has caught an exception thrown from an event handler. Throwing exceptions from an event handler is not supported in Qt. You must not let any exception whatsoever propagate through Qt code. If that is not possible, in Qt 5 you must at least re-implement QCoreApplication::notify() and catch all exceptions there.</p>\n</blockquote>\n\n<p>See <a href=\"https://stackoverflow.com/questions/10075792/how-to-catch-exceptions-in-qt\">https://stackoverflow.com/questions/10075792/how-to-catch-exceptions-in-qt</a> for more details. </p>\n\n<p>In this case, I'd suggest linking the two spinboxes together to make it impossible for the condition to occur. That is, don't allow <code>high</code> to be set to a value less than <code>low</code> - it's almost always better to prevent exceptions than to try to catch them.</p>\n\n<h2>Don't use obsolete functions</h2>\n\n<p>The <code>qsrand()</code> and <code>qrand()</code> functions <a href=\"https://doc.qt.io/qt-5/qtglobal-obsolete.html\" rel=\"nofollow noreferrer\">are obsolete</a> and should not be used in new code. I'd suggest using the <a href=\"https://en.cppreference.com/w/cpp/numeric/random\" rel=\"nofollow noreferrer\">standard C++ <code><random></code></a> tools instead.</p>\n\n<h2>Naming and formatting</h2>\n\n<p>The code currently contains these lines:</p>\n\n<pre><code>_minSpinBox->setMinimum ( Config::SpinBox::minimum );\n_minSpinBox->setMaximum ( Config::SpinBox::maximum );\n_minSpinBox->setSingleStep ( Config::SpinBox::single_step );\n</code></pre>\n\n<p>There's a lot that could be improved here. First, aligning parentheses like that creates a maintenance headache. If someone adds one single line that happens to be longer than the <code>setSingleStep</code> line, they'd have to adjust <em>every other line</em> to realign. Over the long term, that's a pointless and frustrating battle. Let it go!</p>\n\n<p>Second, you've already noted that the underscore prefix is technically legal but suspect. Personally, I don't bother usually with any particular identifier prefix or suffix and find it easier to both read and write as a result. </p>\n\n<p>Third, rather than making separate calls to <code>setMinimum</code> and <code>setMaximum</code>, one could instead make a single call to <code>setRange</code> instead.</p>\n\n<p>Fourth, this could would be much easier to read without the <code>Config::SpinBox</code> prefix everywhere. I'd suggest rewriting the function like this (in conjunction with the next suggestion):</p>\n\n<pre><code>QSpinBox *Generator::createSpinBox() {\n using namespace Config::SpinBox;\n auto sb = new QSpinBox(this);\n sb->setRange(minimum, maximum);\n sb->setSingleStep(single_step);\n sb->setValue(default_value);\n return sb;\n}\n</code></pre>\n\n<h2>Don't Repeat Yourself (DRY)</h2>\n\n<p>If you are creating a lot of <em>almost</em> identical code, you should ask yourself if there is a way to avoid it. This is such common advice that programmers often just use the shorthand and say \"DRY up your code\". In this case, here's a rewrite of <code>_createSpinBox()</code> that shows how to use the single function above instead of two separate functions:</p>\n\n<pre><code>void Generator::_createSpinBoxes() {\n _minSpinBox = createSpinBox();\n _maxSpinBox = createSpinBox();\n _createSpinBoxLayout();\n}\n</code></pre>\n\n<h2>Accomodate translations</h2>\n\n<p>The current code correctly uses <code>tr()</code> in a few places, but not all. For example, the window title and button label. It's very beneficial to get into the habit of making sure that all displayable literal values are translatable. See <a href=\"https://doc.qt.io/qt-5/i18n-source-translation.html\" rel=\"nofollow noreferrer\">the Qt translation docs</a> for more details.</p>\n\n<h2>Use the new version of <code>connect</code></h2>\n\n<p>Since Qt5, there is a better syntax for connecting slots and signals. So instead of this:</p>\n\n<pre><code>connect ( _button, SIGNAL(clicked()), this, SLOT(showNumber()) );\n</code></pre>\n\n<p>one could write this:</p>\n\n<pre><code>connect(_button, &QPushButton::clicked, this, &Generator::showNumber);\n</code></pre>\n\n<p>The version above is <strong>thanks to @GrecKo</strong>. I had originally written this, but the use of <code>std::bind</code> is really not needed here. I think it was a leftover from an experiment I did on the code.</p>\n\n<pre><code>connect(_button, &QPushButton::clicked, std::bind(&Generator::showNumber, this));\n</code></pre>\n\n<p>Note that I've used <code>std::bind</code> from <code><functional></code> here to allow the correct passing of <code>this</code>. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T18:33:01.437",
"Id": "420306",
"Score": "2",
"body": "Why use `std::bind` and not just `connect(_button, &QPushButton::clicked, this, &Generator::showNumber);`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T18:35:57.863",
"Id": "420310",
"Score": "0",
"body": "@GrecKo: that would work, too, and should probably be used instead because it's simpler. I don't know why I did it as I did."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T12:41:36.183",
"Id": "420412",
"Score": "1",
"body": "I've never known `moc` to care about the filenames - when building code from Stack Exchange, I normally just name the files using the question number, and that's no problem for it. AFAIK, the filenames are used only when printing error messages, and in the head-of-file comment in the output. Personally, I'd never use upper-case in a filename, except in Java where it is unfortunately required."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T12:46:58.250",
"Id": "420414",
"Score": "0",
"body": "@TobySpeight: it's specifically the use of `moc` and `CMake`, which is the combination I use, that fails unless the filename case is as I indicated. I believe I recall having such problems with other tools (maybe `QMake`?) but don't recall details. In any case, it's a simple and useful thing to do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T13:31:19.670",
"Id": "420416",
"Score": "0",
"body": "Ah, thanks - I use plain Make and `pkg-config`, and at work I use QMake; the latter with filenames that are lower-case versions of the class names, and that works fine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T14:13:30.807",
"Id": "420423",
"Score": "1",
"body": "Something that I've seen recommended, and have quite taken to, is to explicitly show when `auto` results in a pointer: `auto *sb = new QSpinBox(this);` (note the `*`). It seemed strange at first, but I find it has grown on me. Food for thought."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T17:25:35.567",
"Id": "217273",
"ParentId": "217257",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "217265",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T12:06:51.803",
"Id": "217257",
"Score": "5",
"Tags": [
"c++",
"gui",
"qt"
],
"Title": "GUI Number Generator in QT C++"
} | 217257 |
<p>I've created a JavaFX app to the data about Vessels, Employees and Jobs. The current version works but it is quite slow which I need to fix. I understand the root of my problems but I do not know how to avoid it</p>
<p>I have several entities</p>
<pre><code>class Vessel
{
IntegerProperty id;
StringProperty name;
//and some other fields...
}
class Employee
{
IntegerProperty id;
StringProperty name;
//and some other fields...
}
class Job
{
IntegerProperty id;
StringProperty name;
IntegerProperty employee;
//and also a list of vessels assigned to it
//and many more fields...
}
</code></pre>
<p>These entities correspond to the following tables (PostgreSQL)</p>
<pre><code>CREATE TABLE vessels(id SERIAL PRIMARY KEY, "name" VARCHAR);
CREATE TABLE employees(id SERIAL PRIMARY KEY, "name" VARCHAR);
CREATE TABLE jobs(id SERIAL PRIMARY KEY, "name" VARCHAR);
CREATE TABLE jobs_vessels(id SERIAL PRIMARY KEY, job INT REFERENCES jobs(id), vessel INT REFERENCES vessels(id));
</code></pre>
<p>If I am dealing with <code>Vessel</code>s, <code>Employee</code>s or other simple entities (field are simple types), I execute</p>
<pre><code>SELECT * FROM vessels ORDER BY "name";
</code></pre>
<p>followed by the standard JDBC code with <code>Connection</code>, <code>PreparedStatement</code> and <code>ResultSet</code>.
Then I create <code>ObservableList<Vessel></code> and populate it with the data from <code>ResultSet</code>.
Next I create a <code>TableView</code>, initialize it's <code>TableColumn</code>s (which are basically <code>TextFieldTableCell</code>) and finally display the data.</p>
<p>The problem arises when I want to display\modify a list of complex objects (fields are of type "class ...").
The first part would look the same...
I execute</p>
<pre><code>SELECT * FROM jobs ORDER BY "name";
</code></pre>
<p>and then I convert <code>ResultSet resultSet</code> to <code>ObservableList<Job> jobs</code>.</p>
<p>I also need to get vessels assigned to each job, so I do</p>
<pre><code>protected Map<Job, List<int>> jobsVesselsMap;
//...
for (Job job : jobs)
{
//1. get list of vessels (ids) assigned to the job via "SELECT * FROM jobs_vessels WHERE job = ?"
//2. convert ResultSet to List<int>
//3. store List<int> to "jobsVesselsMap".
}
</code></pre>
<p>Because I need to modify assigned vessels and an employee (to allow a user to select these via corresponding <code>ComboBox</code>s), I need 2 more lists: list of vessels and list of employees.
I execute </p>
<pre><code>SELECT * FROM vessels ORDER BY "name";
</code></pre>
<p>and convert <code>ResultSet</code> into <code>ObservableList<Vessel></code>.
Then I execute</p>
<pre><code>SELECT * FROM employees ORDER BY "name";
</code></pre>
<p>and convert <code>ResultSet</code> into <code>ObservableList<Employee></code>.</p>
<p>Now comes the slow part.
Because a complete "job" object should contain actual data about vessels and employees, I need to swap id's with actual objects.
A complete job is represented by the object of type <code>JobEx</code></p>
<pre><code>class JobEx
{
IntegerProperty id;
StringProperty name;
ObjectProperty<Employee> employee;
ListProperty<Vessel> vessels;
//and many more fields...
}
</code></pre>
<p>I convert <code>ObservableList<Job></code> to <code>ObservableList<JobEx></code> by calling <code>toJobEx</code> in a loop.</p>
<pre><code>public static JobEx toJobEx(Job job,
ObservableList<Vessel> vessels,
ObservableList<Employee> employees,
List<int> jobVesselsIds)
{
JobEx jobEx = new JobEx();
jobEx.setId(job.getId());
jobEx.setName(job.getName());
//employee
Optional<Employee> employee = employees.stream().filter(e -> e.getId() == job.getEmployee()).findFirst();
if (employee.isPresent())
{
jobEx.setVessel(employee.get());
}
//vessels
ObservableList<Vessel> jobVessels = FXCollections.observableArrayList();
for (int vesselId : jobVesselsIds)
{
Optional<Vessel> vessel = vessels.stream().filter(v -> v.getId() == vesselId).findFirst();
if (vessel.isPresent())
{
jobEx.setVessel(vessel.get());
}
}
jobEx.setVessels(jobVessels);
return jobEx;
}
//...
ObservableList<JobEx> jobExs = FXCollections.observableArrayList();
for (Job job : jobs)
{
jobExs.add(toJobEx(job));
}
</code></pre>
<p>At this step I have a complete list of jobs and I start to display it.</p>
<p>I create a <code>TableView</code>, create it's <code>TableColumns</code>, set corresponding editors for it's cells (<code>TextFieldTableCell</code> for <code>StringProperty</code>s, <code>ComboBoxTableCell</code> for <code>ObjectProperty<Employees></code>, custom editor (multiple comboboxes + buttons) for `ListProperty'.</p>
<p>When I want save the data, I execute this process in reverse: <code>ObservableList<JobEx></code> --> <code>ObservableList<Job></code> --> save to multiple tables.</p>
<p>Now comboboxes inside the table display selected values correctly because fields of each <code>JobEx</code> instance and members of lists that were used to populate these comboboxes point to the same memory and same addresses which means that comboboxes select values automatically which is exactly what I want to achieve.</p>
<p>The positive side is that I can user JavaFX bindings and easily select\manipulate values via lists, comboboxes and similar UI controls. I don't know how to achieve the same by keeping ids (without "id to object, array of ids to lists of objects" approach).
The drawback is that this <code>Job</code> to <code>JobEx</code> conversion take time (sometimes way to much) and in a real app there are a lot more "...Ex" classes that have objects instead of ids which result in a high amount of code and painful loading times.</p>
<p>Is there any way to avoid this. Ideally, I would like to completely remove this "to ...Ex conversion" part because is is slow and feels very incorrect. </p>
| [] | [
{
"body": "<p>One way to improve the problem section would be to look at it as an algorithm. For your business of I employees and J vessels, you have N jobs. You iterate over all jobs <strong>(N)</strong> and per job, you iterate over employees and vessels <strong>(worst case access time: N * I + N * J = N * (I + J) )</strong>. Since you iterate over the employee and vessel lists for every Job, your access times are going to eat your performance.</p>\n\n<hr>\n\n<h2>Solution </h2>\n\n<p>If you use a HashMap for vessels and employees, <strong>your access times for .contains and get/put reduce to <a href=\"https://stackoverflow.com/questions/1055243/is-a-java-hashmap-really-o1\">most likely O(1)</a></strong> rather than O(J) and O(I) respectively. Lookup is easily mapped by making each employees ID its key within the map. Now you've reduced your algorithm from <strong>O(N * I + J)</strong> to <strong>O(N * 1 + 1) =~ O(N)</strong></p>\n\n<hr>\n\n<pre class=\"lang-java prettyprint-override\"><code>//employee\n Optional<Employee> employee = employees.stream().filter(e -> e.getId() == job.getEmployee()).findFirst();\n\n if (employee.isPresent())\n {\n jobEx.setVessel(employee.get());\n }\n</code></pre>\n\n<p>becomes</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>int employeeID = job.getEmployee();\nif(employeeHashMap.containsKey(employeeID){\n jobEx.setVessel(employeeHashMap.get(employeeID))\n}\n</code></pre>\n\n<p>and likewise,</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>//vessels\n ObservableList<Vessel> jobVessels = FXCollections.observableArrayList();\n\n for (int vesselId : jobVesselsIds)\n {\n Optional<Vessel> vessel = vessels.stream().filter(v -> v.getId() == vesselId).findFirst();\n\n if (vessel.isPresent())\n {\n jobEx.setVessel(vessel.get());\n }\n }\n</code></pre>\n\n<p>becomes</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> ObservableList<Vessel> jobVessels = FXCollections.observableArrayList();\n\n for (int vesselId : jobVesselsIds)\n {\n if(vesselHashMap.containsKey(vesselId)\n {\n jobEx.setVessel(vesselHashMap.get(vesselID));\n }\n }\n</code></pre>\n\n<hr>\n\n<p>Lastly, some small bugs I noticed:\nInside your <strong>employee</strong> loop you have this line</p>\n\n<p><code>jobEx.setVessel(employee.get());</code></p>\n\n<p>Do you mean to set the Vessel to your employee object?</p>\n\n<p>Also, inside your <strong>vessel</strong> loop, you create a list</p>\n\n<p><code>ObservableList<Vessel> jobVessels = FXCollections.observableArrayList();</code></p>\n\n<p>never touch it,</p>\n\n<pre class=\"lang-java prettyprint-override\"><code> if (vessel.isPresent())\n {\n jobEx.setVessel(vessel.get());\n }\n</code></pre>\n\n<p>and then add the empty list</p>\n\n<p><code>jobEx.setVessels(jobVessels);</code></p>\n\n<p>Is this intentional? The internal part of this loop <code>jobEx.setVessel(vessel.get())</code> would overide the JobEx vessel every time its called. If this method instead adds a new overall vessel, I would suggest renaming it <code>addVessel()</code> for accuracy</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T07:04:35.540",
"Id": "420355",
"Score": "0",
"body": "`jobEx.setVessel(employee.get())`\nYes, this is just a mistake I made when I created the question."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T15:03:01.770",
"Id": "217267",
"ParentId": "217259",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T12:54:36.830",
"Id": "217259",
"Score": "1",
"Tags": [
"java",
"performance",
"gui",
"javafx",
"postgresql"
],
"Title": "slow JavaFx PostgreSQL CRUD app with complex object"
} | 217259 |
<p>I've been working on a way to optimize pixel computation in OpenGL with C. If this information helps, my current environtment = Linux (terminal) + GPU (Nvidia 1080Ti). I'm working with old OpenGL (with GLUT) and not Modern OpenGL. Here's what I'm doing, this function will take image input, this is how I call the image</p>
<pre><code>image = SOIL_load_image("Images/image_1.jpg", &width, &height, 0, SOIL_LOAD_RGBA);
if(image == NULL) exit(0);
image1 = NULL;
imgCompute();
</code></pre>
<p>Image computation processes are below :</p>
<ul>
<li>Convert RGB image → XYZ</li>
<li>XYZ → xy chromaticity </li>
<li>Do some computation to alter the pixel value</li>
<li>Convert back xy → XYZ</li>
<li>Convert back XYZ → RGB</li>
<li>Convert RGB result → LMS</li>
<li>Do computation in LMS</li>
<li>Convert back LMS → RGB</li>
</ul>
<pre><code>float fps = 60.0;
/* image */
int xsize = 1600;
int ysize = 1000;
float conv_x = 0.3;
float conv_y = 0.25;
static void imgCompute()
{
unsigned char *p, *p1;
float R, G, B, r, g, b;
float X, Y, Z, X2, Y2, Z2, x ,y, z;
float l, m, s , L, M, S;
float *p2;
if(image1 == NULL) {
image1 = (unsigned char *)malloc(width*height*4);
if(image1 == NULL) exit(0);
image2 = (float *)malloc(sizeof(float)*width*height*5);
if(image2 == NULL) exit(0);
p = image;
p2 = image2;
for(int i = 0; i < height*width; i++) {
//gamma correction
R = pow(*(p+0)/255.0, 2.2);
G = pow(*(p+1)/255.0, 2.2);
B = pow(*(p+2)/255.0, 2.2);
//XYZ colorspace
X = (0.412453 * R) + (0.357580 * G) + (0.180423 * B);
Y = (0.212671 * R) + (0.715160 * G) + (0.072169 * B);
Z = (0.019334 * R) + (0.119193 * G) + (0.950227 * B);
x = X/(X+Y+Z);
y = Y/(X+Y+Z);
z = Z/(X+Y+Z);
p2[0] = x;
p2[1] = y;
p2[2] = Y;
//======================================================
//some functions from header file
struct Line equation = var(conv_x, conv_y, x, y);
struct Intersection i = point(equation);
struct Distance D = dist(i, x, y);
global = shift(conv_x, conv_y, D, x, y);
float x1 = global.x2;
float y1 = global.y2;
float x2 = global.x3;
float y2 = global.y3;
p2[3] = x1-x;
p2[4] = y1-y;
p2 += 5;
//=======================================================
p += 4;
}
}
p1 = image1;
p2 = image2;
for(int i = 0; i < height*width; i++) {
x = p2[0] + p2[3];
y = p2[1] + p2[4];
Y = p2[2];
X2 = (x * Y)/y;
Y2 = Y;
Z2 = (1-x-y)*Y/y;
R = ( 3.240479 * X2) + ( -1.53715 * Y2) + ( -0.498535 * Z2);
G = ( -0.969256 * X2) + ( 1.875991 * Y2) + ( 0.041556 * Z2);
B = ( 0.055648 * X2) + ( -0.204043 * Y2) + ( 1.057311 * Z2);
//============================================================
//lms colorspace
L = (17.8824 * R) + (43.5161 * G) + ( 4.1194 * B) ;
M = ( 3.4557 * R) + (27.1554 * G) + ( 3.8671 * B) ;
S = ( 0.0300 * R) + ( 0.1843 * G) + ( 1.4671 * B) ;
r = ( 0.0209 * L) + ( -0.1005 * M) + ( 0.0067 * S);
g = ( -0.0002 * L) + ( 0.0003 * M) + ( -0.1006 * S);
b = ( -0.0004 * L) + ( -0.0021 * M) + ( 0.3035 * S);
//gamma correction
*(p1+0) = pow(r, (1.0 / 2.2))*255.0;
*(p1+1) = pow(g, (1.0 / 2.2))*255.0;
*(p1+2) = pow(b, (1.0 / 2.2))*255.0;
*(p1+3) = 0;
p1 +=4;
p2 +=5;
}
}
</code></pre>
<p>My desired fps is 60fps and my original image size is 1600 x 1000. What I've been checking :</p>
<ol>
<li>Original image + gamma correction applied = 3 fps.</li>
<li>Original image (no gamma correction) = 20 fps. </li>
</ol>
<p>From tesult no.2 (20 fps), I tried to resize my image into 1/3 original size to see if I could achieve 60fps, </p>
<ol start="3">
<li>Resized image + gamma correction = 30 fps.</li>
<li>Resized image (no gamma correction) = 60 fps.</li>
</ol>
<p>I've also checked each colorspace transformation, they are fine and don't affect the fps. As of now, the problems are image size and per pixel gamma computation. I'd appreciate some suggestions to improve performance of this function.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T17:19:44.877",
"Id": "420302",
"Score": "1",
"body": "Have you profiled your application and checked where the most time is spent ? Are you calling `imgCompute` every frame ? if yes your performance will be increased if you can avoid calling malloc every time but passing preallocated memory into this function. Otherwise I'm not sure if you are going to get much better performance without using any kind of paralelization or vectorization, be that on the CPU, or letting the GPU do the work and implementing your algorithms as shaders using OpenGL or via OpenCL."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T07:22:16.480",
"Id": "420359",
"Score": "2",
"body": "Can you include a suitable `main()` to show how this would be used? It's hard to see how a function of no arguments and no result is intended to operate. We're also missing includes of `<math.h>`, `<stdlib.h>` and whatever defines `struct Line`, `struct Intersection`, `struct Distance` and their related functions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T17:26:49.783",
"Id": "420695",
"Score": "0",
"body": "Hi, @TobySpeight. I've checked my functions (including those inside header file) one by one and the function I put on my question is the one function that takes much time. Just this one function. Also, of course I call of my libraries. I'm trying to make post not as long. I put the link to the gist code on my post."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T03:13:14.587",
"Id": "420732",
"Score": "0",
"body": "[What you may and may not do after receiving answers](https://codereview.meta.stackexchange.com/a/1765)"
}
] | [
{
"body": "<h3>Create lookup table</h3>\n<p>I ran your program on a buffer filled with random bytes and I found that most of the time was being spent doing the <code>pow()</code> operations. You can speed this part up by creating a lookup table, like this:</p>\n<pre><code>float powTable[256];\n\n// Call this from main() \nstatic void computeTable(void)\n{\n int i;\n for (i = 0; i < 256; i++) \n powTable[i] = pow(i/255.0, 2.2);\n} \n\nstatic void imgCompute()\n{\n // ...\n\n //gamma correction\n R = powTable[p[0]];\n G = powTable[p[1]];\n B = powTable[p[2]];\n\n // ...\n}\n</code></pre>\n<p>Adding this one lookup table cut the time of the function by 50%.</p>\n<h3>Inverse gamma correction</h3>\n<p>I tried to do the same thing with the second set of <code>pow()</code> calls. However, that part was a bit tricky since instead of starting with an <code>int</code> in the range <code>0..255</code> and converting to a <code>float</code> in the range <code>0..1</code>, you are starting with a <code>float</code> and converting to an <code>int</code> (i.e. the reverse function).</p>\n<p>I actually implemented something that I thought would work (it was a lookup table that rounded the input float to the nearest 0.0001 and had 10000 entries). However, when I ran the program I discovered that a lot of the <code>float</code> values were either <code>< 0.0</code>, <code>> 1.0</code>, or even <code>Nan</code>. I traced that <code>Nan</code> back to these lines:</p>\n<pre><code> X = (0.412453 * R) + (0.357580 * G) + (0.180423 * B);\n Y = (0.212671 * R) + (0.715160 * G) + (0.072169 * B);\n Z = (0.019334 * R) + (0.119193 * G) + (0.950227 * B);\n\n x = X/(X+Y+Z);\n y = Y/(X+Y+Z);\n z = Z/(X+Y+Z);\n</code></pre>\n<p>Here, if <code>R = G = B = 0</code>, then <code>X = Y = Z = 0</code>. Then when you divide by <code>(X+Y+Z)</code>, you get a division by zero. I'm not sure if that is a problem or not. Also, I'm not sure if the negative or greater than 1 values are problematic because when you apply the inverse gamma correction, you will get a pixel value outside the range <code>0..255</code>. In any case, I decided to clamp the input values to the range <code>0..1</code> before doing the lookup. With the 2nd lookup table, it shaved another 50% of the time off. So with both lookup tables in place, the final program was about 4x faster than the original.</p>\n<h3>No need for intermediate buffer</h3>\n<p>There is no need for the <code>image2</code> intermediate buffer. If you combine your two processing loops, you will only ever need a 5 floating point intermediate buffer instead of allocating and filling a <code>1600 x 1000 x 5 x 4 = 32 MB</code> buffer. Having such a big intermediate buffer could cause your program to run slower because it could cause your cpu cache to fill up. In my testing, it didn't make any difference in speed, but I would still recommend getting rid of that buffer and combining the two loops.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T17:10:25.560",
"Id": "420692",
"Score": "0",
"body": "Hi, thanks a lot ! It took me 2 days to implement the lookup table, I was having another issue with my code. Now my question is also put on hold (?) Now the gamma correction with lookup table works, but as you said the inverse gamma is problematic. I created another variable to store the inverse gamma, I've updated my code, would you please take a look at it ? As for image2, before I added more function, I started with just one image and it was so much slower, so I went with image2 and it's better now."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T23:47:36.997",
"Id": "217292",
"ParentId": "217269",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "217292",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T15:40:28.040",
"Id": "217269",
"Score": "6",
"Tags": [
"performance",
"c",
"image",
"opengl"
],
"Title": "Per pixel Image Computation with Gamma Correction in OpenGL and C"
} | 217269 |
<p>I have a fully working Python server that utilizes Tornado, asyncio, websockets and tweepy(Twitter's Streaming api). The main point of this server is to receive a query from the user, call upon tweepy to track the query, perform sentiment analysis on any message received and send it back to the client.</p>
<p>All messages sent by the client are a json message of the form:</p>
<pre><code>{
track: 'query to track'
}
</code></pre>
<p>All messages sent by the server are a json message of the form:</p>
<pre><code>{
polarityIndex: 'An index where 0 is positive sentiment, 1 is negative sentiment and 2 is neutral',
hashtags: 'A dictionary of all the hashtags that were found and their frequency.'
}
</code></pre>
<p>There are four main modules that make up this entire server. There are also two extra modules but those two don't do anything interesting. One of them simply setup a logger and the other one loads up environment variables.</p>
<p>The first one we are going to look at is the <code>server.py</code> file</p>
<pre><code>import logging
import ssl
from queue import Queue
from setup_logger import ROOT_LOGGER
from tornado import web, ioloop
from tornado.options import define, options, parse_command_line
from websocket_handler import WSHandler
from constants import SETTINGS
from tweet_stream_listener import TweetStreamListener, listen_for_tweets
define("port", default=8000, help="run on the given port.", type=int)
define("debug", default=True, help="run in debug mode.", type=bool)
def main():
parse_command_line()
logger = logging.getLogger(ROOT_LOGGER)
settings = {
"debug": options.debug,
}
app = web.Application(
[
(r"/track", WSHandler),
],
**settings
)
queue = Queue()
app.listener = TweetStreamListener(queue)
context = None
if SETTINGS['CERTFILE'] and SETTINGS['KEYFILE']:
context = ssl.SSLContext()
context.load_cert_chain(SETTINGS['CERTFILE'], SETTINGS['KEYFILE'])
app.listen(port=options.port, ssl_options=context)
logger.info("Server listening on port: {0}".format(options.port))
loop = ioloop.IOLoop.current()
loop.run_in_executor(None, listen_for_tweets, app.listener, queue)
try:
loop.start()
except KeyboardInterrupt:
loop.stop()
# This is a sentinel value to to the consumer queue that we are done.
queue.put(None)
app.listener.stop_tracking()
logger.info('Server shutting down.')
if __name__ == "__main__":
main()
</code></pre>
<p>Nothing too interesting here except for a couple of things. Notice at the end I'm putting none in a queue that is being shared the twitter streamer listener class and a threaded function of some sort. You can think of the queue in the twitter stream listener as my producer queue and the queue that is being passed into to my threaded function as my consumer queue. The second interesting thing that I'm doing is I'm attaching my listener to the main application object <code>app</code> so that I have access to it in my <code>websocket handler</code> class. Now we are going to move on to the <code>websocket handler</code> class.</p>
<pre><code>import logging
import json
from constants import SETTINGS
from urllib.parse import urlparse
from uuid import uuid4
from tornado import ioloop, gen
from tornado.websocket import WebSocketHandler
class WSHandler(WebSocketHandler):
LOGGER = logging.getLogger(__qualname__)
WHITELISTED_DOMAINS = SETTINGS['WHITELISTED_DOMAINS'].split(",")
def check_origin(self, origin):
parsed_origin = urlparse(origin)
if parsed_origin.hostname is 'localhost':
return True
domain = ".".join(parsed_origin.netloc.split(".")[1:])
return domain in WSHandler.WHITELISTED_DOMAINS
def open(self):
self._sess_id = uuid4().hex
WSHandler.LOGGER.debug(
'Websocket with id {0} is now connected.'.format(self._sess_id))
self.application.listener.websockets[self._sess_id] = self
@gen.coroutine
def on_message(self, body):
WSHandler.LOGGER.debug(
'Websocket {0} has received a message: {1}'.format(self._sess_id, body))
message = json.loads(body)
yield self.wait_still_stream_finishes(message['track'])
@gen.coroutine
def wait_still_stream_finishes(self, message):
# Disconnect the stream momentarily.
self.application.listener.stop_tracking()
while self.application.listener.is_stream_running():
yield gen.sleep(1)
ioloop.IOLoop.current().run_in_executor(None,
self.application.listener.start_tracking,
self._sess_id, message)
def on_close(self):
WSHandler.LOGGER.debug(
'Websocket with id {0} has disconnected.'.format(self._sess_id))
self.application.listener.websockets.pop(self._sess_id)
if(len(self.application.listener.websockets) is 0):
WSHandler.LOGGER.debug(
"No more connections to keep track of. Closing stream.")
self.application.listener.stop_tracking()
</code></pre>
<p>There is quite a bit going on in this class so I'm going to try to explain as much as I can. First, because tornado is stateless and I have no way of knowing which websocket made which request, I need to introduce some internal state. Every time there is a new connection, we generate a uuid4 so we can identify any websocket easily in the dictionary via their uuid4. The twitter streamer listener class is the one that is keeping track of all active websockets and anytime one of the websockets close the connection, we remove the websocket from the dictionary and remove the query from the list of queries that we are keeping track of. </p>
<p>Now, there is a limitation with tweepy and maybe some of the maintainers of tweepy can tell me of a better way of doing this but when a user makes query, I need to temporarily stop the stream, recreate the list of query with the new query while keeping all the queries that other users have made intact and then start streaming again. Of course, I can not simply disconnect the stream and start it up again. If I did, there would not be enough time for the previous thread to finish before I could create a new thread and start streaming again. This solution I don't really like at all and would like ideas on how I can do this better. Let us move to the <code>twitter stream listener</code> module.</p>
<pre><code>import logging
import asyncio
from tornado.websocket import WebSocketClosedError
from tweepy import StreamListener, OAuthHandler, Stream, API
from constants import SETTINGS
from tweet_sentiment_analyzer import get_polarity_index_from_tweet, \
get_hashtag_frequencies_from_tweet, preprocess_tweet
auth = OAuthHandler(
SETTINGS["TWITTER_CONSUMER_API_KEY"], SETTINGS["TWITTER_CONSUMER_API_SECRET_KEY"])
auth.set_access_token(
SETTINGS["TWITTER_ACCESS_KEY"], SETTINGS["TWITTER_ACCESS_SECRET_KEY"])
api = API(auth, wait_on_rate_limit=True)
class TweetStreamListener(StreamListener):
def __init__(self, queue):
self.api = api
self.queue = queue
self.websockets = {}
self.logger = logging.getLogger(self.__class__.__name__)
self.stream = Stream(auth=self.api.auth, listener=self,
tweet_mode='extended')
self.current_searches = {}
self.streaming = False
def start_tracking(self, sess_id, track):
self.logger.debug('Stream has started')
self.streaming = True
tracking_list = self.get_updated_tracking_list(sess_id, track)
self.stream.filter(track=tracking_list, languages=['en'])
self.streaming = False
self.logger.debug('Stream has stopped')
def get_updated_tracking_list(self, sess_id, track):
# New tweet to listen to.
self.current_searches[sess_id] = track.lower()
'''
Create a new search term list and put it all in a set to remove
potential duplicate search terms.
'''
return set(self.current_searches.values())
def stop_tracking(self):
self.stream.disconnect()
def is_stream_running(self):
return self.streaming
def on_status(self, status):
# We are not processing retweets. Only new tweets.
if getattr(status, 'retweeted_status', None):
return
self.queue.put(status)
def on_timeout(self, status):
self.logger.error('Stream disconnected. continuing...')
return True # Don't kill the stream
"""
Summary: Callback that executes for any error that may occur. Whenever we get a 420 Error code, we simply
stop streaming tweets as we have reached our rate limit. This is due to making too many requests.
Returns: False if we are sending too many tweets, otherwise return true to keep the stream going.
"""
def on_error(self, status_code):
if status_code == 420:
self.logger.error(
'Encountered error code 420. Disconnecting the stream')
# returning False in on_data disconnects the stream
return False
else:
self.logger.error('Encountered error with status code: {}'.format(
status_code))
return True # Don't kill the stream
def listen_for_tweets(listener, queue):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
while True:
message = queue.get()
if message is None:
break
# We still have websockets to send this message to.
if len(listener.websockets) > 0:
task = asyncio.ensure_future(process_tweet(message, listener.current_searches,
listener.websockets))
loop.run_until_complete(task)
queue.task_done()
loop.close()
async def process_tweet(status, current_searches, websockets):
tweet = status.text.lower()
# If extended_tweet exists, this the means that status.text is truncated.
# We want the entire text.
if getattr(status, 'extended_tweet', None):
tweet = status.extended_tweet['full_text'].lower()
polarity_tweet, filtered_hashtag_list = preprocess_tweet(tweet)
polarityIndex = get_polarity_index_from_tweet(polarity_tweet)
hashtag_freqs = get_hashtag_frequencies_from_tweet(filtered_hashtag_list)
message = {
'polarityIndex': polarityIndex,
'hashtags': dict(hashtag_freqs)
}
sess_ids = []
for sess_id, topic in current_searches.items():
if topic in filtered_hashtag_list:
sess_ids.append(sess_id)
for sess_id in sess_ids:
try:
# We need this check and exception in case a websocket closes abruptly.
if sess_id in websockets:
await websockets[sess_id].write_message(message)
except WebSocketClosedError:
continue
</code></pre>
<p>So this is the module that listens for tweets and figures out which websockets sends which messages. Now let us talk about the two queues that are being used in this module. Depending if the topic that the user searched for is trending or not, it may be the case that we have to analyze alot of incoming messages. To offload this work, any message that we receive from twitter we simply check that it is not a retweet and put it in the queue. Then once a message has been placed in the queue, the queue in the threaded function listen for tweets will get the message off of the queue, process the tweet and figure out which websocket sends which messages.</p>
<p>Notice that there is another dictionary called current_searches. The key for that dictionary is the same key that the websocket dictionary uses. The whole point of the current_searches dictionary is so that we know which query belongs to which socket. When we receive a message from twitter and have finished analyzing it, we then need to figure out who should receive this message. To keep it simple, all we do is look through the tweet and see which query is in this tweet. If we find a match, we store their key in a list. Of course, a tweet may contain multiple queries and so we simply add in all of their keys in the list as well. The last module that we are going to look at is the <code>twitter sentiment analyzer module</code>.</p>
<pre><code>import re
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
from nltk.corpus import stopwords
from nltk import FreqDist
analyser = SentimentIntensityAnalyzer()
default_stopwords = set(stopwords.words('english'))
def get_polarity_index_from_tweet(text):
polarity_scores = analyser.polarity_scores(text)
polarityIndex = 2
# 0 is positive sentiment, 1 is negative sentiment and 2 is neutral sentiment
if polarity_scores['compound'] > 0.05:
polarityIndex = 0
elif polarity_scores['compound'] < -0.05:
polarityIndex = 1
return polarityIndex
def remove_pattern(text, pattern):
matches = re.findall(pattern, text)
for match in matches:
text = re.sub(match, '', text)
return text
def preprocess_tweet(tweet):
# remove twitter handles (@xxx)
tweet = remove_pattern(tweet, r"@[\w]*")
# remove URL links (httpxxx)
tweet = remove_pattern(tweet, r"https?://[A-Za-z0-9./]*")
'''
remove special characters, numbers and punctuations. Exceptions are #, !, ' and ? as vader uses both ! and ?
characters for emphasis and will affect our polarity score, vader also takes into account contractions and we
want to keep hashtags to calculate which hashtags were more frequent. Because of all these exceptions, we are
going to have two tweets. One tweet called polarity tweet that is feed into the vader analyzer and another tweet
that only has letters and the hashtag. The second tweet is what we will use to calculate the frequency of a hashtag
from each tweet that we get and will be fed into a function that ntlk has called FreqDist to calculate the frequency
distribution in a tweet.
'''
polarity_tweet = re.sub(r"[^a-zA-Z#!?']", " ", tweet)
hashtag_tweet = re.sub(r"[^a-zA-Z#]", " ", tweet)
tokenize_hashtag_list = hashtag_tweet.split()
filtered_hashtag_list = [
word for word in tokenize_hashtag_list if not word in default_stopwords]
return (polarity_tweet, filtered_hashtag_list)
def extract_hashtags(tweet_list):
hashtags = []
for word in tweet_list:
ht = re.findall(r"#(\w+)", word)
hashtags.append(ht)
return hashtags
def get_hashtag_frequencies_from_tweet(tweet_list):
hashtags = extract_hashtags(tweet_list)
return FreqDist(sum(hashtags, []))
</code></pre>
<p>To perform sentiment analysis, I use a pre train mode that supposedly does well with social media text. I have a simple threshold that determines whether something is positive, negative or neutral. This is a threshold that the maintainers of vader recommend. Then, I also have a couple of preprocessing functions that strips out @ and https text, extract hashtags and count their frequencies. I also have this big comment which you guys should read so you guys know why I did what I did when it came to preprocessing each tweet. </p>
<p>Here is the link to the repo <a href="https://github.com/LuisAverhoff/Senti-Server/tree/f5d02e1eca7665e9579e1e5bddb2b43abdcd422b" rel="nofollow noreferrer">Senti Server</a> for those that want to take a look at the entire repo. Feel free to respond on how I can make this better and make it more testable.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T15:43:53.070",
"Id": "217270",
"Score": "4",
"Tags": [
"python",
"asynchronous",
"twitter",
"websocket",
"tornado"
],
"Title": "Python server that performs sentiment analysis on Twitter data"
} | 217270 |
<p>I've done some research, reviewed countless SO questions that appeared similar, leading me to endless rabbit holes.</p>
<p>My solution is working, but I don't like it. I want to create a random IV for AES and store it with my cipher. You'll see various approaches based on the comments in my code. This final version is mostly from another source I found with some changes. What I was hoping to do is instead of generating two separate strings and concatenating them together, I could write into the same byte array and break it apart later. <strong>Goal is AES256 with random IV.</strong></p>
<p>This led to errors like:</p>
<ul>
<li>Invalid characters in base64 string</li>
<li>length of data to encrypt is invalid</li>
<li>padding is invalid and cannot be removed</li>
</ul>
<p>So here's my code. And of course, if there's a hole or ten, advice welcome. Feel free to share examples in c#. This project just happens to be in VB.net</p>
<pre><code>Public Function EncryptText(input As String) As String
Dim password As String = "THISISONLYTEMPORARY"
Dim bytesToBeEncrypted As Byte() = Encoding.UTF8.GetBytes(input)
Dim passwordBytes As Byte() = Encoding.UTF8.GetBytes(password)
passwordBytes = SHA256.Create().ComputeHash(passwordBytes)
Dim result As String = AES_Encrypt(bytesToBeEncrypted, passwordBytes)
Return result
End Function
Public Function DecryptText(ByVal input As String) As String
Dim password As String = "THISISONLYTEMPORARY"
'Dim savedSalt As Byte() = Convert.FromBase64String(input.Split("%"c)(0))
'Dim savedValue As String = input.Split("%"c)(1)
Dim savedSalt As Byte() = Convert.FromBase64String(input.Substring(0, 44))
Dim savedValue As String = input.Substring(44, input.Length - 44)
Dim bytesToBeDecrypted As Byte() = Convert.FromBase64String(savedValue)
Dim passwordBytes As Byte() = Encoding.UTF8.GetBytes(password)
passwordBytes = SHA256.Create().ComputeHash(passwordBytes)
Dim result As String = AES_Decrypt(bytesToBeDecrypted, passwordBytes, savedSalt)
Return result
End Function
Public Function AES_Encrypt(ByVal bytesToBeEncrypted As Byte(), ByVal passwordBytes As Byte()) As String
Dim encryptedBytes As Byte() = Nothing
'Dim saltBytes As Byte() = New Byte() {1, 2, 3, 4, 5, 6, 7, 8}
Dim saltBytes = New Byte(31) {}
Using rng As RandomNumberGenerator = New RNGCryptoServiceProvider()
rng.GetBytes(saltBytes)
End Using
Dim saltToSave As String = Convert.ToBase64String(saltBytes)
Using ms As MemoryStream = New MemoryStream()
Using AES = New AesManaged()
AES.KeySize = 256
AES.BlockSize = 128
Dim key = New Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000)
AES.Key = key.GetBytes(CInt(AES.KeySize / 8))
AES.IV = key.GetBytes(CInt(AES.BlockSize / 8))
AES.Mode = CipherMode.CBC
AES.Padding = PaddingMode.PKCS7
Using cs = New CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write)
'cs.Write(saltBytes, 0, saltBytes.Length) ' new
cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length)
cs.Close()
End Using
encryptedBytes = ms.ToArray()
End Using
End Using
Return saltToSave & Convert.ToBase64String(encryptedBytes)
End Function
Public Function AES_Decrypt(ByVal bytesToBeDecrypted As Byte(), ByVal passwordBytes As Byte(), savedSalt As Byte()) As String
Dim decryptedBytes As Byte() = Nothing
'Dim saltBytes As Byte() = New Byte() {1, 2, 3, 4, 5, 6, 7, 8}
Using ms As MemoryStream = New MemoryStream()
Using AES = New AesManaged()
AES.KeySize = 256
AES.BlockSize = 128
Dim key = New Rfc2898DeriveBytes(passwordBytes, savedSalt, 1000)
AES.Key = key.GetBytes(CInt(AES.KeySize / 8))
AES.IV = key.GetBytes(CInt(AES.BlockSize / 8))
AES.Mode = CipherMode.CBC
AES.Padding = PaddingMode.PKCS7
Using cs = New CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write)
cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length)
cs.Close()
End Using
decryptedBytes = ms.ToArray()
End Using
End Using
'Return Encoding.UTF8.GetString(decryptedBytes.Skip(savedSalt.Length).ToArray())
Return Encoding.UTF8.GetString(decryptedBytes.ToArray())
End Function
</code></pre>
<p>I was at one point joining my IV and cipher text with a <code>%</code> character and splitting those, but didn't like the visible clear separation which made the IV obvious. </p>
<p>Again this is working. My question is more about hardening it within the constraints that you see (A single private password and random IV) and ditching this string concatenation.</p>
<p>I posted this on stackoverflow but it was suggested to move to here because my solution is working. It was also suggested to not be concerned about splitting my encrypted string with "%" as you see commented out in my code and was pointed to this link: <a href="https://en.wikipedia.org/wiki/Kerckhoffs%27s_principle" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Kerckhoffs%27s_principle</a></p>
| [] | [
{
"body": "<p>Disclaimer: I'm not an expert in VB.NET / C#, so I can't and won't comment on things like code-style. I will however address the security of this code. My points are in order of decreasing severity.</p>\n\n<h2>Hard-Coded Password</h2>\n\n<p>The password is currently hard-coded into the source. I <em>really hope</em> this is just for demonstration purposes to produce a minimal working example. This is very bad practice that I would strongly recommend against, as it usually leads to the password ending up in some (public) code repository and not exclusively in the hands of your sysadmin or end-user where it belongs. Also putting the password into the source means that you need to re-compile and re-distribute the binary whenever you change the password, which will probably be a hassle...</p>\n\n<p>The usual approach for handling passwords is to either put them into an environment variable or to query the user for them at runtime. If you have tight control over the file system a plain file or a file encrypted using a cloud key management service are also options.</p>\n\n<h2>Use of (plain) CBC-Mode</h2>\n\n<p>Currently this code uses the <em>infamous</em> CBC-mode which time and again has lead to attacks in when it was used in TLS. The problem here is that an attacker may modify the message in a malicious way, e.g. to exploit a parser bug or trigger some other reaction without the receiver having a high chance of noticing it before it's too late. The better solution is to use <a href=\"https://blogs.msdn.microsoft.com/shawnfa/2009/03/17/authenticated-symmetric-encryption-in-net/\" rel=\"nofollow noreferrer\"><em>authenticated encryption</em> (like AES-GCM)</a> which will make sure the message is unmodified before handing out the plaintext.</p>\n\n<h2>Use of PBKDF2</h2>\n\n<p>Right now PKCS#5 PBKDF2 (<a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.rfc2898derivebytes?view=netframework-4.7.2\" rel=\"nofollow noreferrer\"><code>Rfc2898DeriveBytes</code></a>) is used to derive the key and IV from the password and the salt. This is an outdated standard, because it allows for easy parallelization of the password-guessing attacks using GPUs and similar specialized hardware. It is recommended to use <a href=\"https://github.com/kmaragon/Konscious.Security.Cryptography\" rel=\"nofollow noreferrer\">Argon2</a> these days.</p>\n\n<p>On a side note, .NET by default uses HMAC-SHA1 for PBKDF2 which has a 20 byte output width. The code at hand however is asking for 48 bytes of output. This means that (due to the bad design of PBKDF2) the complete 1000 iterations are actually run <em>three times</em> in a parallelizable fashion. An attacker can just run these three instances in parallel to speed up their attack and attackers of password hashing scheme usually have <em>a lot</em> of parallel hardware available, so that is not good. </p>\n\n<h2>The IV / Salt</h2>\n\n<p>The current generation strategy for the salt is fine even though <em>31</em> bytes is a bit of an odd choice for the size. As for the <em>actual</em> IV, as you are altering the key with each encrypted message due to always altering the salt, it can actually be constant. The contract of modern encryption schemes is that you must not use any (key,IV) pair after all and if you always change the key you are not violating that contract.</p>\n\n<p>As for the salt, don't worry about it being public and recognizable. After all a determined attacker will only take a short amount of time to extract the salt from your format and you have no good method available to change that.</p>\n\n<h2>Pre-Hashing the Password</h2>\n\n<p>Currently the provided password is run through SHA256 before being feeded into the password hashing scheme. While this is unusual, this is actually fine, as long as the password hashing step <em>always</em> comes afterwards and this hash is treated with the same care as the actual password. This is because it is just one motivated GPU-cracking-cluster user away from being the case.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T18:47:41.793",
"Id": "420315",
"Score": "0",
"body": "If you have further questions regarding cryptographic topics, please ask them over on [crypto.se] where we also already have quite the collection of Q&As. For more general security (policy) questions (like the point with key management I was making) please refer to [security.se]. But do note that neither site will be willing to look at actual code, abstract pseudo-code however is fine. Also note that [so] usually isn't the _best_ source for answering cryptographic / security questions..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T18:39:37.803",
"Id": "420453",
"Score": "0",
"body": "Thank you. I posted a follow up here: https://crypto.stackexchange.com/questions/68735/i-need-help-determining-the-best-encryption-options-based-on-system-security-cry"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-20T16:18:27.580",
"Id": "421393",
"Score": "0",
"body": "I've continued my adventure: https://codereview.stackexchange.com/questions/217784/encrypts-using-aes-gcm-for-data-with-limited-visibility-and-long-rest"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T18:44:59.227",
"Id": "217283",
"ParentId": "217271",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "217283",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T15:48:09.777",
"Id": "217271",
"Score": "1",
"Tags": [
".net",
"asp.net",
"cryptography",
"vb.net",
"aes"
],
"Title": "Encrypts using AES with random initialization vector meant for data with limited visibility and then long rest"
} | 217271 |
<p>I tried to solve the question at <a href="https://leetcode.com/problems/roman-to-integer/" rel="nofollow noreferrer">https://leetcode.com/problems/roman-to-integer/</a> i.e Converting an Roman Digit to a Integer using C#. It passes all the test cases but any suggestions to reduce run time and memory usage would be appreciated.</p>
<pre><code> public static int RomanToInt(string s)
{
if (s.Length>=2)
{
int currentIndex = s.Length - 1,HighestValue=CharacterValue(s[currentIndex]),number=HighestValue;
currentIndex--;
while (currentIndex>=0)
{
int currentValue = CharacterValue(s[currentIndex]);
if(currentValue >= HighestValue)
{
number = number + currentValue;
HighestValue = currentValue;
}
else
{
number = number - currentValue;
}
currentIndex--;
}
return number;
}
else
{
return CharacterValue(s[0]);
}
}
public static int CharacterValue(char c)
{
switch (c)
{
case 'I': return 1;
break;
case 'V':
return 5;
break;
case 'X':
return 10;
break;
case 'L':
return 50;
break;
case 'C':
return 100;
break;
case 'D':
return 500;
break;
case 'M':
return 1000;
break;
default:
return 0;
break;
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T07:37:40.993",
"Id": "420362",
"Score": "0",
"body": "You want to reduce the runtime but you are not telling us what your current measurements are. Why do you care about it? Do you experience any problems with it? Please also include some example(s) how thi method is supposed to be used."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T14:36:45.870",
"Id": "420426",
"Score": "0",
"body": "Question has been edited"
}
] | [
{
"body": "<p>Run time is linear, and memory usage is constant (and small), so I don't think you're going to see much improvement in either. </p>\n\n<p>You might be able to make some slight improvements by using pointers in unsafe mode (see <a href=\"https://stackoverflow.com/questions/13179554/is-it-faster-to-access-char-in-string-via-operator-or-faster-to-access-char-i\">https://stackoverflow.com/questions/13179554/is-it-faster-to-access-char-in-string-via-operator-or-faster-to-access-char-i</a>), but unless you're processing a very large number of strings this is probably not necessary. As always, profile before and after making any optimizations!</p>\n\n<p>Stylistically, there are a few improvements that could be made:</p>\n\n<ul>\n<li>Declare your variables in separate statements.</li>\n<li>HighestValue should be highestValue.</li>\n<li>In CharacterValue, you don't need to break when you're returning anyway.</li>\n<li>It would be clearer to remove the blank line between the inner if and else.</li>\n<li>You don't need the outer if/else for the length of the string; the code inside the main case would handle a length-1 string fine.</li>\n<li>The way the logic works, the first item doesn't have to be handled as a special case, so this could be rewritten as a for loop, which would make it (for many people) easier to read.</li>\n</ul>\n\n<p>And one functional one - your code doesn't currently handle the string being null or empty; it should either return 0 or throw an appropriate exception in that case, depending on whether you consider that to be valid input.</p>\n\n<p>So for example:</p>\n\n<pre><code> public static int RomanToInt(string s)\n {\n if (string.IsNullOrEmpty(s))\n {\n return 0;\n }\n\n int highestValue = 0;\n int number = 0;\n\n for(int currentIndex = s.Length - 1; currentIndex >= 0; currentIndex--)\n {\n int currentValue = CharacterValue(s[currentIndex]);\n\n if (currentValue >= highestValue)\n {\n number += currentValue;\n highestValue = currentValue;\n }\n else\n {\n number -= currentValue;\n }\n }\n\n return number;\n }\n\n private static int CharacterValue(char c)\n {\n switch (c)\n {\n case 'I': return 1;\n case 'V': return 5;\n case 'X': return 10;\n case 'L': return 50;\n case 'C': return 100;\n case 'D': return 500;\n case 'M': return 1000;\n default: return 0;\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T10:27:32.770",
"Id": "420395",
"Score": "0",
"body": "Thanks for the input.I am curious ,should we declare variables in separate statements in general"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T00:31:18.830",
"Id": "217295",
"ParentId": "217272",
"Score": "3"
}
},
{
"body": "<p>Although your algorithm seems to handle the conversion of the expected chars to numbers and the subtraction and addition rules, it doesn't take care of invalid characters like <code>'K'</code> or <code>'b'</code> or any other <code>char</code>. It's not enough to validate against <code>null</code> or empty strings. <code>CharacterValue(char c)</code> defaults to <code>0</code> for invalid chars. It would be more appropriate to throw an <code>ArgumentOutOfRangeException</code> with a description of the invalid <code>char</code>.</p>\n\n<p>Besides that, there are a couple of other rules for roman numbers, that you could try to handle. Project Euler has an excellent description of the few rules <a href=\"https://projecteuler.net/about=roman_numerals\" rel=\"nofollow noreferrer\">here</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T04:23:38.067",
"Id": "217306",
"ParentId": "217272",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T16:48:19.977",
"Id": "217272",
"Score": "1",
"Tags": [
"c#",
"algorithm",
"programming-challenge",
"roman-numerals"
],
"Title": "Leetcode: Roman digit to integer"
} | 217272 |
<p>I have built a real estate management system with Django. I want to know if my design database was wrong. Please let me know how to improve it.</p>
<p>Should I make the models use more than two tables (classes)?</p>
<pre><code>class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=50)
image = models.ImageField(upload_to='profiles', default='logo.png')
phone = models.CharField(max_length=11, default='')
bio = models.CharField(max_length=100, default='')
city = models.CharField(max_length=20, default='erbil')
location = models.CharField(max_length=40, default='')
date = models.DateTimeField(default=datetime.now)
active = models.BooleanField(default=False)
def __str__(self):
return f'{self.user}'
class Listing(models.Model):
objects = ListingManager()
company = models.ForeignKey(User, on_delete=models.CASCADE )
title = models.CharField(max_length=200)
slug = models.SlugField(unique=True, default='', blank=True)
address = models.CharField(max_length=200)
city = models.CharField(max_length=100, choices=city_choices, default='lodon')
estate_type = models.CharField(max_length=20, choices=estate_choices, default=house)
description = models.TextField(blank=True)
rent_sale = models.CharField(max_length=20, choices=rent_sale_choice, default=sale)
price = models.IntegerField()
bedrooms = models.IntegerField(default=0)
bathrooms = models.DecimalField(max_digits=2, decimal_places=1)
garage = models.IntegerField(default=0)
sqft = models.IntegerField()
sold = models.BooleanField(default=False)
sold_time = models.DateTimeField(default=datetime.now,blank=True)
photo_main = models.ImageField(upload_to='listings_main')
photo_1 = models.ImageField(upload_to='listings_1', blank=True)
photo_2 = models.ImageField(upload_to='listings_1', blank=True)
photo_3 = models.ImageField(upload_to='listings_1', blank=True)
photo_4 = models.ImageField(upload_to='listings_1', blank=True)
photo_5 = models.ImageField(upload_to='listings_1', blank=True)
photo_6 = models.ImageField(upload_to='listings_1', blank=True)
is_published = models.BooleanField(default=True)
list_date = models.DateTimeField(default=datetime.now, blank=True)
unless = models.CharField(default='', max_length=20)
</code></pre>
| [] | [
{
"body": "<p>As a rule of thumb in programming, \"there are only four numbers\": zero, one, two, and \"many\". You have seven photo fields, which means that you should just treat that as \"many\". Not only is that an unfortunate artificial limitation (someday there will be a listing with eight photos, and you won't be able to accommodate it easily), it's also a pain to write code that uses your schema (you either have to copy-and-paste code six times, or use variably-named identifiers).</p>\n\n<p>What you want is a separate table for photos, to support a one-to-many relationship.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T19:46:40.637",
"Id": "420321",
"Score": "0",
"body": "The rule I use is \"a few\" and \"a lot\" instead of two and many. But this is an excellent point!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T21:14:32.900",
"Id": "420331",
"Score": "0",
"body": "class Listing(models.Model):\n .\n .\n .\n .\n images = models.OneTwoManyField(Image)\n\nclass Image(models.Model):\n photo = models.ImageField(upload_to='listings') , how is it? thanks for your suggestions"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T19:17:54.920",
"Id": "217284",
"ParentId": "217274",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T17:41:56.873",
"Id": "217274",
"Score": "4",
"Tags": [
"python",
"database",
"django"
],
"Title": "Django model for real estate"
} | 217274 |
<p><strong>The Task</strong></p>
<p>is taken from <a href="https://www.codewars.com/kata/5277c8a221e209d3f6000b56/train/typescript" rel="nofollow noreferrer">codewars</a>:</p>
<blockquote>
<p>Write a function that takes a string of braces, and determines if the
order of the braces is valid. It should return <code>true</code> if the string is
valid, and <code>false</code> if it's invalid.</p>
<p>All input strings will be nonempty, and will only consist of
parentheses, brackets and curly braces: <code>()[]{}</code>.</p>
<p>What is considered Valid? A string of braces is considered valid if
all braces are matched with the correct brace.</p>
<p>Examples</p>
<ul>
<li><code>(){}[]</code> => <code>True</code></li>
<li><code>([{}])</code> => <code>True</code></li>
<li><code>(}</code> => <code>False</code></li>
<li><code>[(])</code> => <code>False</code></li>
<li><code>[({})](]</code> => <code>False</code></li>
</ul>
</blockquote>
<p><strong>My solution</strong></p>
<pre><code>const areBracesBalanced = brc => {
const brace = Object.freeze({
"(": [],
"[": [],
"{": [],
});
const removeBrace = b => brace[b].splice(-1, 1);
const getLastBraceIndex = b => brace[b][brace[b].length - 1]
const braceExists = b => !brace[b].length;
const isBraceBeforeClosed = (before, current) => braceExists(before) || getLastBraceIndex(before) < getLastBraceIndex(current);
const braceIsBalanced = (b, i) => {
switch (b) {
case "(":
case "[":
case "{":
return brace[b].push(i);
case ")":
return isBraceBeforeClosed("[", "(") &&
isBraceBeforeClosed("{", "(") &&
removeBrace("(");
case "]":
return isBraceBeforeClosed("(", "[") &&
isBraceBeforeClosed("{", "[") &&
removeBrace("[");
case "}":
return isBraceBeforeClosed("(", "{") &&
isBraceBeforeClosed("[", "{") &&
removeBrace("{");
default:
// be a good code...
}
};
return[...brc]
.every(braceIsBalanced) && !Object.values(brace).flat().length;
}
</code></pre>
| [] | [
{
"body": "<p>I'm not very good at Javascript, but I do know how to make an algorithm. </p>\n\n<p>In the code below I use the fact that correct <code>{}</code> or <code>[]</code> or <code>()</code> will always touch and can be removed. Just taken these away until there aren't any left and if you've got an empty string it was balanced, if it is not empty then clearly it must be unbalanced.</p>\n\n<pre><code>function isBalanced(input)\n{\n while (input.length > 0) {\n var output = input.replace(\"{}\", \"\").replace(\"[]\", \"\").replace(\"()\", \"\");\n if (input == output) return false;\n input = output;\n }\n return true;\n}\n\nfunction test(input)\n{\n alert(\"'\"+input+\"' = \"+(isBalanced(input) ? \"Correct\" : \"Incorrect\"));\n}\n\ntest(\"(){}[]\");\ntest(\"([{}])\");\ntest(\"(}\");\ntest(\"[(])\");\ntest(\"[({})](]\");\ntest(\"(){[}]\");\n</code></pre>\n\n<p>Someone with a bit more knowledge of Javascript might be able to further optimize this code.</p>\n\n<p>To make it slightly more efficient there's a version with a regular expression:</p>\n\n<pre><code>function isBalanced(input)\n{\n while (input.length > 0) {\n var output = input.replace(/\\(\\)|\\{\\}|\\[\\]/, \"\");\n if (input == output) return false;\n input = output;\n }\n return true;\n}\n</code></pre>\n\n<p>I think this short code is elegant, but here it is somewhat at the expense of clarity.</p>\n\n<p>Here's why the above code is an improvement:</p>\n\n<ul>\n<li>The code is a lot shorter.</li>\n<li>The code is easier the read.</li>\n<li>There's a simple algorithm that is explained.</li>\n</ul>\n\n<p>Yes, the code might be less efficient, and doesn't build on the code in the question, and for that I apologize.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T18:28:56.660",
"Id": "217279",
"ParentId": "217275",
"Score": "2"
}
},
{
"body": "<p>Your solution is complicated due to the use of three separate stacks:</p>\n\n<ul>\n<li>For each closing character, you have to cross-validate the two other types of delimiters. (If you had to handle a fourth type of matching characters, such as <code><</code> and <code>></code>, it would be even messier.)</li>\n<li>At the end, you need to write <code>!Object.values(brace).flat().length</code> to verify that all of the stacks have been cleared.</li>\n</ul>\n\n<p>I also think that the use of <code>Object.freeze()</code> is overkill.</p>\n\n<p>Your <code>removeBrace()</code> helper can use <code>Array.prototype.pop()</code> instead.</p>\n\n<h2>Suggested solution</h2>\n\n<p>Keep all of the state in one combined stack.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const areBracesBalanced = brs => {\n let expectCloseStack = [];\n return [...brs].every(b => {\n switch (b) {\n case \"(\": return expectCloseStack.push(\")\");\n case \"[\": return expectCloseStack.push(\"]\");\n case \"{\": return expectCloseStack.push(\"}\");\n\n case \")\":\n case \"]\":\n case \"}\":\n return expectCloseStack.pop() === b;\n }\n }) && !expectCloseStack.length;\n};\n\nconsole.log(areBracesBalanced(\"[({})](]\"));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T18:53:09.027",
"Id": "420317",
"Score": "0",
"body": "Really good! I was thinking of something like a `pop()`, but couldn't come an algorithm similar to your's."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T12:16:18.477",
"Id": "420410",
"Score": "0",
"body": "When would you use object.freeze?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T14:02:33.897",
"Id": "420421",
"Score": "0",
"body": "Here, everything is local and easy to understand, so freezing introduces noise, mostly. If you need to pass it to other people's code, or the project grows so large that there is a possibility of interacting with other people's code, then I would see value in freezing. That's my opinion."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T18:32:43.120",
"Id": "217282",
"ParentId": "217275",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "217282",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T17:44:52.000",
"Id": "217275",
"Score": "4",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"functional-programming",
"balanced-delimiters"
],
"Title": "Check whether string of braces, brackets, and parentheses is balanced"
} | 217275 |
<p><em>Application Logic</em></p>
<p>The software take odds data from an internet site and store them inside my own database, this application is basically a scraper.</p>
<p>There are different types of odds, eg:</p>
<ol>
<li>FullTime</li>
<li>Under / Over</li>
<li>Double Chance</li>
</ol>
<p><em>My goal</em></p>
<p>I want avoid code redundancy, for doing so, I created a method called <code>GetOddsRow</code> which returns a type called <code>GenericOdds</code>, this is the code:</p>
<pre><code>private async Task<List<GenericOdds>> GetOddsRows(Uri fixtureLink, string endpoint, string[] filter)
{
HtmlDocument doc = new HtmlDocument();
List<GenericOdds> gos = new List<GenericOdds>();
int i = 0;
foreach (string newEndpoint in filter)
{
//Make a new endpoint to get the odds type.
fixtureLink = new Uri(fixtureLink, endpoint + newEndpoint);
string html = await NetworkHelper.LoadAndWaitForSelector(fixtureLink, _oddsTable);
doc.LoadHtml(html);
//Get only the containers that contains data.
var containers = doc.DocumentNode.SelectNodes("//div[@class='table-container' and not(@style)]");
//The odds are not available for this container.
if (containers.ElementAtOrDefault(i) == null)
break;
GenericOdds go = new GenericOdds();
HtmlNode container = containers[i];
//Get the table which contains the odds.
HtmlNode table = container.SelectSingleNode(".//table[@class='" + _oddsTableClass + "']");
//Get the odds description type.
go.OddsType = container.SelectSingleNode(".//strong[1]//a").InnerText;
//Get all the rows (odds available).
go.Odds = table.SelectNodes(".//tbody//tr[normalize-space()]");
gos.Add(go);
i++;
}
return gos;
}
</code></pre>
<p>This method have three parameters:</p>
<ol>
<li><strong>fixtureLink</strong>: is the link of the event that contains the odds</li>
<li><strong>endpoint</strong>: is the odds type</li>
<li><strong>filter</strong>: specify the category of the odds</li>
</ol>
<p>eg: </p>
<pre><code>[fixtureLink]
https://www.oddsportal.com/soccer/africa/africa-cup-of-nations/libya-south-africa-0QsEg3I8/?r=1#
[endpoint]
over-under;2;
[filter]
0.50;0
</code></pre>
<p>The method logic is really simple, I iterate through all the filters available and then join this filter to the endpoint to create a new url, that url will be used to get the odds data.</p>
<p>I store each list of rows (of a specific category) in a new <code>GenericOdds</code> which have the following implementation:</p>
<pre><code>public class GenericOdds
{
public HtmlNodeCollection Odds { get; set; }
public string OddsType { get; set; }
}
</code></pre>
<p>This allow me to organize the odds rows, so I can easily navigate to that list and see the type of the rows, eg:</p>
<pre><code>GenericOdds[0]
HtmlNodeList => 10 elements
OddsType => Over 0.5
GenericOdds[1]
HtmlNodeList => 5 elements
OddsType => Over 1.5
GenericOdds[2]
HtmlNodeList => 3 elements
OddsType => Over 3.5
</code></pre>
<p>Now I have 10 methods that call <code>GetOddsRows</code>, for example of <code>Over / Under</code>:</p>
<pre><code>public async Task<List<OverUnder>> GetOverUnder(Uri fixtureLink, OddsCategory cat)
{
List<OverUnder> overUnders = new List<OverUnder>();
string endpoint = "?r=1#over-under;2;";
if (cat == OddsCategory.Firsthalf)
endpoint = "?r=1#over-under;3";
else if (cat == OddsCategory.Secondhalf)
endpoint = "?r=1#over-under;4";
//Odds filters.
string[] filter = { "0.50;0", "1.50;0", "2.50;0", "3.50;0", "4.50;0", "5.50;0", "6.50;0" };
List<GenericOdds> gos = await GetOddsRows(fixtureLink, endpoint, filter);
gos.ForEach(od =>
{
foreach(HtmlNode tr in od.Odds)
{
OverUnder overUnder = new OverUnder();
overUnder.Book = tr.SelectSingleNode(".//td//div//a[2]").InnerText;
overUnder.Description = od.OddsType;
//Get event odds
HtmlNode odds = tr.SelectSingleNode(".//td[contains(@class, 'odds')][1]");
overUnder.Over = OddsUtility.ParseOdds(odds);
odds = tr.SelectSingleNode(".//td[contains(@class, 'odds')][2]");
overUnder.Under = OddsUtility.ParseOdds(odds);
overUnder.Payout = OddsUtility.GetPayout(tr);
overUnders.Add(overUnder);
}
});
return overUnders;
}
</code></pre>
<p>as you can see I have an endpoint for the specific type of odds which is <code>Under / Over</code>, this type is defined as below:</p>
<pre><code>public class OverUnder
{
public string Book { get; set; }
public string Description { get; set; }
public KeyValuePair<decimal?, int> Over { get; set; }
public KeyValuePair<decimal?, int> Under { get; set; }
public decimal? Payout { get; set; }
}
</code></pre>
<p>there is also <code>OddsCategory</code> that is an <code>enum</code> that allow me to understand which types of odds need to be downloaded.</p>
<p>as I said before, there are also others odds method eg: GetFullTime, GetDoubleChance, GetHalfTime, etc...</p>
<p>all of these methods vary only by:</p>
<ol>
<li>endpoint</li>
<li>filter</li>
<li>return type</li>
</ol>
<p>So my goal is to avoid code redundancy, honestly I don't like the solution of <code>GenericOdds</code>, I'm looking for a way to return different types from <code>GetOddsRow</code>, something like an interface.</p>
<p>Additional methods:</p>
<p>The site is based on ajax request, for handle that I'm using <a href="https://www.nuget.org/packages/PuppeteerSharp/" rel="nofollow noreferrer">Puppeteer Sharp</a>, and I create the following method:</p>
<pre><code>public static async Task<string> LoadAndWaitForSelector(Uri url, string selector)
{
var browser = await Puppeteer.LaunchAsync(new LaunchOptions
{
Headless = true,
ExecutablePath = Environment.GetEnvironmentVariable("CHROME_PATH"),
});
using (Page page = await browser.NewPageAsync())
{
await page.GoToAsync(url.ToString());
await page.WaitForSelectorAsync(selector);
return await page.GetContentAsync();
}
}
</code></pre>
<p>this method wait for the selector requested by the caller and return the odds table generated by the ajax request.</p>
<p>Also, if you are looking for another odds type:</p>
<pre><code>public async Task<List<HalfTime>> GetHalfTime(Uri fixtureLink)
{
List<HalfTime> hfts = new List<HalfTime>();
string endpoint = "?r=1#ht-ft;2;";
//Odds filters.
string[] filter = { "27", 30", "33" };
List<GenericOdds> gos = await GetOddsRows(fixtureLink, endpoint, filter);
gos.ForEach(od =>
{
foreach(HtmlNode tr in od.Odds)
{
HalfTimeFullTime hf = new HalfTimeFullTime();
hf.Book = tr.SelectSingleNode(".//td//div//a[2]").InnerText;
hf.Description = header.InnerText;
//Get odds.
HtmlNode odds = tr.SelectSingleNode(".//td[contains(@class, 'odds')][1]");
hf.Odds = OddsUtility.ParseOdds(odds);
hfts.Add(hf);
}
});
return hfts;
}
</code></pre>
<p>and type:</p>
<pre><code>public class HalfTime
{
public string Book { get; set; }
public string Description { get; set; }
public KeyValuePair<decimal?, int> Odds { get; set; }
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T18:09:39.140",
"Id": "217276",
"Score": "4",
"Tags": [
"c#",
"web-scraping"
],
"Title": "Return different types from web scraper method"
} | 217276 |
<p>Let's consider you want to clone all items of a vector <code>orig</code> except the item of index <code>i</code> should be taken from alternative value <code>alt</code>.</p>
<p>Lets say the items are of the type</p>
<pre class="lang-rust prettyprint-override"><code>struct Bla{
// Some fields
}
</code></pre>
<h2>Using for loop</h2>
<p>On simple solution would be:</p>
<pre class="lang-rust prettyprint-override"><code>fn clone(orig: &Vec<Bla>, i: usize, alt: Bla) -> Vec<Bla> {
let cloned = Vec::new();
for (j, item) in orig.iter().enumerate() {
let new_item = if i != j {item.clone()} else {alt};
cloned.push(new_item);
}
cloned
}
</code></pre>
<blockquote>
<p>Note: Does not compile, because the compiler does not know that <code>i==j</code> is only valid once.</p>
</blockquote>
<h2>Using functional style</h2>
<p>The functional alternative would be the follow:</p>
<pre class="lang-rust prettyprint-override"><code>fn clone(orig: &Vec<Bla>, i: usize, alt: Bla) -> Vec<Bla> {
orig.iter().enumerate()
.map(|(j, item)| if i != j {item.clone()} else {alt})
.collect::<Vec<Bla>>()
}
</code></pre>
<p>The last one looks nice, but does not compile :( because the rust compiler does not know that alt gets moved (or consumed) only once (<code>i==j</code>).</p>
<h2>Using mem replace</h2>
<p>In order to fix the version above one can use a default value for the index which should be replaced.</p>
<pre class="lang-rust prettyprint-override"><code>fn clone(orig: &Vec<Bla>, i: usize, alt: Bla) -> Vec<Bla> {
let mut result = orig.iter().enumerate()
.map(|(j, item)| if i != j {item.clone()} else {Bla::default()})
.collect::<Vec<Bla>>();
mem::replace(&mut result[i], alt);
result
}
</code></pre>
<p>What is the most concise and fastest implementation to do so?</p>
| [] | [
{
"body": "<p>In my opinion none of your solution is idiomatic and all use an useless comparaison.</p>\n\n<p>Using for loop:</p>\n\n<ul>\n<li>Doesn't pre-allocate the vector</li>\n<li>Use a comparaison that could be avoid</li>\n</ul>\n\n<p>Using functional style:</p>\n\n<ul>\n<li>Use a comparaison that could be avoid</li>\n</ul>\n\n<p>Using mem replace:</p>\n\n<ul>\n<li>Use a comparaison that could be avoid</li>\n<li>Is unnecessary complex to just copy a vector</li>\n</ul>\n\n<p>Also, you should avoid take a <code>&Vec<T></code> as parameter, it's much better to take a <code>&[T]</code>. See: <a href=\"https://stackoverflow.com/q/40006219/7076153\">Why is it discouraged to accept a reference to a String (&String), Vec (&Vec), or Box (&Box) as a function argument?</a></p>\n\n<p>I would use one of the following version:</p>\n\n<pre class=\"lang-rust prettyprint-override\"><code>#[derive(Clone)]\nstruct Pokemon {\n}\n\nfn a(pokemons: &[Pokemon], i: usize, pokemon: Pokemon) -> Vec<Pokemon> {\n let mut digimons = Vec::with_capacity(pokemons.len());\n\n digimons.extend_from_slice(&pokemons[0..i]);\n digimons.push(pokemon);\n digimons.extend_from_slice(&pokemons[i + 1..]);\n\n digimons\n}\n\nfn b(pokemons: &[Pokemon], i: usize, pokemon: Pokemon) -> Vec<Pokemon> {\n let mut digimons = pokemons.to_vec();\n digimons[i] = pokemon;\n\n digimons\n}\n\nfn c(pokemons: &[Pokemon], i: usize, pokemon: Pokemon) -> Vec<Pokemon> {\n pokemons[0..i]\n .iter()\n .cloned()\n .chain(std::iter::once(pokemon))\n .chain(pokemons[i + 1..].iter().cloned())\n .collect()\n}\n</code></pre>\n\n<p>I don't really know witch version is better, <code>a()</code> and <code>c()</code> <strong>should</strong> be the same but sometime <code>chain()</code> is not optimized away. And <code>b()</code> is probably the most straightforward solution. I think I would choice <code>a()</code> in a production code.</p>\n\n<p>However, looking at the <a href=\"https://godbolt.org/z/uLTZwW\" rel=\"nofollow noreferrer\">assembly</a>, we can see that <code>a()</code> and <code>c()</code> doesn't produce the same, and that <code>b()</code> is the simplest.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T14:51:40.617",
"Id": "420428",
"Score": "0",
"body": "But solution `a()` and `c()` avoid copying/cloning `i`th element unnecessary from the incomming slice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T16:19:02.303",
"Id": "420440",
"Score": "0",
"body": "@Matthias depend on the cost of clone, `b()` \"could\" be faster. If you really want to be sure, you must do some bench-marking."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T01:14:43.327",
"Id": "217299",
"ParentId": "217277",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "217299",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T18:24:22.900",
"Id": "217277",
"Score": "2",
"Tags": [
"comparative-review",
"rust",
"vectors"
],
"Title": "Clone Vector in rust except at one index"
} | 217277 |
<p>I am a beginner in programming. To rotate the array to left, I have written the below code. Please point out how to optimize the code and anything I am doing which is not good programming practice.</p>
<pre><code>package arrays;
import java.util.Scanner;
public class ArrayLeftRotation {
public static int[] LeftRotation(int numberOfLeftRotations, int[] a, int[] b) {
int n1 = numberOfLeftRotations, n2 = numberOfLeftRotations;
/*
* First for loop Given array a0=1,a1=2,a3=4,a4=5,a5=6,a6=7; First we
* are shifting the first 3 elements to last 3 slots and the array looks
* like below a0=1,a1=2,a2=3,a3=,a4=1,a5=2,a6=3; The above step we are
* performing through below logic
* a[array.length-numberOfLeftRotations]=b[i]; GIVEN ARRAY LENGTH -
* NUMBER OF LEFT ROTATIONS IS THE STARTING POINT TO MOVE THE FIRST
* ELEMENTS OF THE ARRAY TO LAST
*/
for (int i = 0; i < numberOfLeftRotations; i++) {
a[a.length - n1] = b[i];
n1--;
}
/*
* Second for loop After executing the above loop the array look like
* below a0=1,a1=2,a2=3,a3=,a4=1,a5=2,a6=3; now except the last three
* slots every thing needs to be changed
* a0=4,a1=5,a2=6,a3=7,a4=1,a5=2,a6=3; we achieved the above array
* result through below logic a[i]=b[numberOfLeftRotations]; REPLACED
* THE REMAINING SLOTS WITH THE VALUES STARTING FROM
* NUMBEROFLEFTROTATIONS
*/
for (int i = 0; i < a.length - numberOfLeftRotations; i++) {
a[i] = b[n2];
n2++;
}
return a;
}
public static int[] LeftRotation(int numberOfLeftRotations, int[] a) {
return a;
}
public static int[] printArray(int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
return a;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of Left Rotations need to be done");
int l = sc.nextInt();
System.out.println("Enter number of elements in an array");
int e = sc.nextInt();
int[] a = new int[e];
for (int i = 0; i < a.length; i++) {
a[i] = sc.nextInt();
}
int[] b = a.clone();
LeftRotation(l, a, b);
printArray(a);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T19:22:36.077",
"Id": "420319",
"Score": "1",
"body": "Why do you have second rotation function?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T20:12:24.890",
"Id": "420325",
"Score": "0",
"body": "In second rotation function I am actually replacing the initial elements in an array which are not replaced in first function."
}
] | [
{
"body": "<p>Your class has 4 methods:</p>\n\n<ol>\n<li><code>int[] LeftRotate(int, int[], int[])</code></li>\n<li><code>int[] LeftRotate(int, int[])</code></li>\n<li><code>int[] printArray(int[])</code></li>\n<li><code>void main(String[])</code></li>\n</ol>\n\n<p>The second method is never called, and can be removed.</p>\n\n<p>The first and third methods (and the second) all return an <code>int[]</code>, the <code>a</code> parameter, but the returned values are never assigned to anything. This return value can be removed, and the methods declared to return <code>void</code>.</p>\n\n<p>In the first method, you are looping over increasing <code>i</code> values, decrementing <code>n1</code>, and assigning to <code>a[a.length - n1]</code>. This “double negative” makes the code harder to understand; decrementing <code>n1</code> increases the destination index value. You already have a <code>i</code> index which in incrementing. You could instead:</p>\n\n<pre><code>for(int i = 0; i < numberOfLeftRotations; i++) {\n a[a.length - numberOfLeftRotations + i] = b[i];\n}\n</code></pre>\n\n<p>This is a little easier to understand; you are only changing <code>i</code>, increasing it, and adding it to a starting point for the destination. We can make it a little clearer:</p>\n\n<pre><code>int dest_start = a.length - numberOfLeftRotations;\nfor(int i = 0; i < numberOfLeftRotations; i++) {\n a[dest_start + i] = b[i];\n}\n</code></pre>\n\n<p>That is much more understandable. Do the same for the second loop.</p>\n\n<hr>\n\n<p>The above is just a cleanup of your existing code. We can restructure / refactor the code to make it better and easier to use.</p>\n\n<p>When you want to left-rotate an array, you always need to create a new array for the destination. You can make the left-rotate function create the destination array for the caller.</p>\n\n<pre><code>int[] LeftRotate(int numberOfLeftRotations, int[] source) {\n int[] dest = new int[source.length];\n // ... copy rotated version from dest into source\n return dest;\n}\n</code></pre>\n\n<p>And use it as:</p>\n\n<pre><code>int[] b = LeftRotation(l, a);\n</code></pre>\n\n<p>In fact, this is probably what was intended for your second method. The code to copy the rotated version from dest to source could just be a call of the first “helper” method:</p>\n\n<pre><code>int[] LeftRotate(int numberOfLeftRotations, int[] source) {\n int[] dest = new int[source.length];\n LeftRotate(numberOfLeftRotations, dest, source);\n return dest;\n}\n</code></pre>\n\n<p>Your first method should still be <code>void</code>, as it is not returning anything that wasn’t just passed to it.</p>\n\n<hr>\n\n<p>Copying sequential elements from one array to another is a common operation, and Java provides a method which does just that: <a href=\"https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/lang/System.html#arraycopy(java.lang.Object,int,java.lang.Object,int,int)\" rel=\"noreferrer\"><code>System.arraycopy()</code></a>. Using this, your left rotation can be performed very efficiently in two statements:</p>\n\n<pre><code>System.arraycopy(source, 0, dest, dest.length - numberOfLeftRotations, numberOfLeftRotations);\nSystem.arraycopy(source, numberOfLeftRotations, dest, 0, dest.length - numberOfLeftRotations);\n</code></pre>\n\n<hr>\n\n<p>Use better variable names. <code>a</code> and <code>b</code> are unclear; <code>source</code> and <code>dest</code> give context to the reader. <code>numberOfLeftRotations</code> is a very descriptive, but it is perhaps a little long. <code>numLeftRotations</code> is just as clear and doesn’t result in lines becoming excessively long. <code>numRotations</code> or <code>rotations</code> might be even better; the reader would know they are left rotations, because the variables are contained within a “left rotate” function.</p>\n\n<p>Convention is for only Class names to begin with upper case letters; method names should not. You should name the method <code>leftRotate</code>, not <code>LeftRotate</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T08:28:41.870",
"Id": "420376",
"Score": "0",
"body": "Thanks a lot for the explanation. will keeps this points in mind from here on"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T00:54:05.480",
"Id": "217297",
"ParentId": "217280",
"Score": "6"
}
},
{
"body": "<p><a href=\"https://codereview.stackexchange.com/a/217297/153986\">@AJNeufeld's Answer</a> covers all of the logical review quite effectively, but I would like to add a note on your naming schemes.</p>\n\n<p>As it stands calling your current code would look something like:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>ArrayLeftRotation.LeftRotation(source, /*some number*/a)\n</code></pre>\n\n<p>It would be significanly more succinct to rename the Class from ArrayLeftRotation to RotateArray or even Rotate, and the simply rename your LeftRotation method left() (using lowercase method names as mentioned in above answer)</p>\n\n<p>Your new call looks much cleaner as:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>Rotate.left(source, /*some number*/ a)\n</code></pre>\n\n<p>This also offers a built in symmetry should you extend the code to rotate the opposite direction, as such a call would be similar: <code>Rotate.right()</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T15:05:51.193",
"Id": "217329",
"ParentId": "217280",
"Score": "2"
}
},
{
"body": "<p>A rotation is a <a href=\"https://en.wikipedia.org/wiki/Modular_arithmetic\" rel=\"nofollow noreferrer\">modular arithmic</a> operation. </p>\n\n<p>The <em>congruent</em> value of any number <code>n</code> is <code>(n % size + size) % size</code>.</p>\n\n<blockquote>\n<pre><code>public static int[] LeftRotation(int numberOfLeftRotations, int[] a, int[] b) {\n int n1 = numberOfLeftRotations, n2 = numberOfLeftRotations;\n for (int i = 0; i < numberOfLeftRotations; i++) {\n a[a.length - n1] = b[i];\n n1--;\n }\n for (int i = 0; i < a.length - numberOfLeftRotations; i++) {\n a[i] = b[n2];\n n2++;\n }\n return a;\n }\n</code></pre>\n</blockquote>\n\n<p>So the above code could be rewritten as below to allow for:</p>\n\n<ol>\n<li>both left and right rotations with <code>k</code> number of rotations</li>\n<li>both positive and negative rotations (left and right rotations are complements)</li>\n<li>rotations with <code>k > source.length</code></li>\n</ol>\n\n<p>code</p>\n\n<pre><code> public class Rotate\n {\n public static <T> T[] leftFrom(T[] source, int k)\n {\n if (source == null)\n throw new IllegalArgumentException(\"source\");\n @SuppressWarnings(\"unchecked\")\n T[] target = (T[]) new Object[source.length];\n if (target.length == 0) return target;\n for (int i = 0; i < target.length; i++)\n {\n target[i] = source[mod(i + k, target.length)];\n }\n return target;\n }\n\n public static <T> T[] rightFrom(T[] source, int k)\n {\n if (source == null)\n throw new IllegalArgumentException(\"source\");\n @SuppressWarnings(\"unchecked\")\n T[] target = (T[]) new Object[source.length];\n if (target.length == 0) return target;\n for (int i = 0; i < target.length; i++)\n {\n target[i] = source[mod(i - k, target.length)];\n }\n return target;\n }\n\n public static <T> void left(T[] source, int k)\n {\n T[] target = leftFrom(source, k);\n System.arraycopy(target, 0, source, 0, target.length);\n }\n\n public static <T> void right(T[] source, int k)\n {\n T[] target = rightFrom(source, k);\n System.arraycopy(target, 0, source, 0, target.length);\n }\n\n private static int mod(int a, int n)\n {\n assert n > 0;\n return (a % n + n) % n;\n }\n }\n</code></pre>\n\n<p>Examples</p>\n\n<pre><code> import java.lang.reflect.Array;\n import java.util.Arrays;\n\n public void Examples()\n {\n Integer[] source = new Integer[] { 0, 1, 2 };\n\n // rotate left\n areEqual(new[] { 0, 1, 2 }, Rotate.leftFrom(source, 0));\n areEqual(new[] { 1, 2, 0 }, Rotate.leftFrom(source, 1));\n areEqual(new[] { 2, 0, 1 }, Rotate.leftFrom(source, 2));\n areEqual(new[] { 0, 1, 2 }, Rotate.leftFrom(source, 3));\n // rotate left overflow (k ~ k % source.length)\n areEqual(new[] { 1, 2, 0 }, Rotate.leftFrom(source, 4));\n // rotate left retrograde (rotate left k ~ rotate right (-k))\n areEqual(new[] { 2, 0, 1 }, Rotate.leftFrom(source, -1));\n\n // rotate right\n areEqual(new[] { 0, 1, 2 }, Rotate.rightFrom(source, 0));\n areEqual(new[] { 2, 0, 1 }, Rotate.rightFrom(source, 1));\n areEqual(new[] { 1, 2, 0 }, Rotate.rightFrom(source, 2));\n areEqual(new[] { 0, 1, 2 }, Rotate.rightFrom(source, 3));\n // rotate right overflow (k ~ k % source.length)\n areEqual(new[] { 2, 0, 1 }, Rotate.rightFrom(source, 4));\n // rotate right retrograde (rotate right k ~ rotate left (-k))\n areEqual(new[] { 1, 2, 0 }, Rotate.rightFrom(source, -1));\n\n // rotate and assign\n areEqual(new[] { 0, 1, 2 }, source); // unchanged so far\n Rotate.left(source, 1);\n areEqual(new[] { 1, 2, 0 }, source);\n Rotate.right(source, 1);\n areEqual(new[] { 0, 1, 2 }, source);\n }\n\n static void areEqual(int[] a, int[] b)\n {\n assert Arrays.equals(a, b);\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T09:21:00.560",
"Id": "221100",
"ParentId": "217280",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "217297",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T18:30:27.237",
"Id": "217280",
"Score": "6",
"Tags": [
"java",
"beginner",
"array"
],
"Title": "Rotate array to the left"
} | 217280 |
<h2>Github</h2>
<p><a href="https://github.com/Webbarrr/MyStopwatch" rel="nofollow noreferrer">Github for easy testing</a></p>
<hr>
<p>I'm currently undertaking a training course to try & further develop my skills in </p>
<p>C#. The latest exercise was to create a basic stopwatch class that meets the following criteria -</p>
<blockquote>
<p>Design a class called Stopwatch. The job of this class is to simulate
a stopwatch. It should provide two methods: Start and Stop. We call
the start method first, and the stop method next. Then we ask the
stopwatch about the duration between start and stop. Duration should
be a value in <code>TimeSpan</code>. Display the duration on the console. We should
also be able to use a stopwatch multiple times. So we may start and
stop it and then start and stop it again. Make sure the duration value
each time is calculated properly. We should not be able to start a
stopwatch twice in a row (because that may overwrite the initial start
time). So the class should throw an <code>InvalidOperationException</code> if its
started twice.</p>
<p>Educational tip: The aim of this exercise is to make you understand
that a class should be always in a valid state. We use encapsulation
and information hiding to achieve that. The class should not reveal
its implementation detail. It only reveals a little bit, like a
blackbox. From the outside, you should not be able to misuse a class
because you shouldn’t be able to see the implementation detail.</p>
</blockquote>
<p>I'm sure someone is bound to mention it, but yes I'm aware that there is already a stopwatch class in the .NET framework, but as this was the exercise I wanted to try & accomplish it based on the requirements.</p>
<p>The class is as follows -</p>
<pre><code>public class Stopwatch
{
private TimeSpan _duration;
// private TimeSpan _start;
private DateTime _start;
public Stopwatch()
{
ZeroStart();
}
public void Start()
{
// if (_start != TimeSpan.Zero)
if (_start != DateTime.Min)
throw new InvalidOperationException("The stopwatch has already been started.");
_start = DateTime.Now;
}
public TimeSpan Stop()
{
// if (_start == TimeSpan.Zero)
if (_start == DateTime.Min)
throw new InvalidOperationException("The stopwatch has not been started.");
_duration = DateTime.Now- _start;
ZeroStart();
return _duration;
}
private void ZeroStart()
{
// _start = TimeSpan.Zero;
_start = DateTime.Min;
}
}
</code></pre>
<p>I haven't done an awful lot of OOP or even effective work with classes. Most of the stuff I have done in the past has been more procedural based stuff, just a long list of static methods in static classes etc...</p>
<p>I'm not sure if this is really enough to go on for anyone to actually critique me on so I'm sorry if that's the case.</p>
<p>I've tested the code using the following -</p>
<pre><code>class Program
{
static void Main(string[] args)
{
UsingStopwatch();
}
static void UsingStopwatch()
{
Console.WriteLine("This is a stop watch. Type 'start' to start it & 'stop' to stop it.");
var stopwatch = new Stopwatch();
while (true)
{
var input = Console.ReadLine();
switch (input.ToLower())
{
case "start":
stopwatch.Start();
break;
case "stop":
Console.WriteLine(stopwatch.Stop());
break;
default:
Console.WriteLine("Sorry I don't recognize that.");
break;
}
}
}
}
</code></pre>
<hr>
<h2>Update</h2>
<p><a href="https://codereview.stackexchange.com/users/104803/jandotnet">Thanks to jandotnet</a> I have made some updates to how I store some of the data. <code>_start</code> is now <code>DateTime</code> & I have comparing values with <code>DateTime.MinValue</code>. I have updated the above with the full snippet.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T20:15:03.143",
"Id": "420326",
"Score": "1",
"body": "Using `TimeOfDay` is not is good idea if you want to use the stop watch from one day to the next ;). i.e: `new DateTime(2019, 01, 02, 00, 05, 00).TimeOfDay -\nnew DateTime(2019, 01, 01, 23, 55, 00).TimeOfDay -> -23:50:00`. You can just use DateTime instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T20:35:28.537",
"Id": "420327",
"Score": "0",
"body": "Sorry if this sounds stupid but if I change it to `_start = DateTime;` or `_start = new DateTime;` both throw exceptions. The former being because `DateTime` is a type & the latter being that `DateTime` can't be converted to `TimeSpan`. How exactly do you mean to just use `DateTime`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T04:09:31.580",
"Id": "420346",
"Score": "1",
"body": "My suggestion is: change type of _start to DateTime and use DateTime.Now instead of DateTime.Now.TimeOfDate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T09:13:59.277",
"Id": "420384",
"Score": "0",
"body": "Only way to get your Stopwatch as accurate as the built in stopwatch is to use the OS tick https://docs.microsoft.com/en-us/windows/desktop/api/sysinfoapi/nf-sysinfoapi-gettickcount"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T15:50:42.800",
"Id": "420437",
"Score": "0",
"body": "@JanDotNet Thank you for clarifying, sorry I didn't understand at first."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T15:50:46.837",
"Id": "420438",
"Score": "0",
"body": "@Anders I'm not that worried about the accuracy, it was more the concept from the exercise but I appreciate the feedback. Thank you"
}
] | [
{
"body": "<p>I see no problem with a programming challenge that has a low accuracy stopwatch. I have problems with your particular implementation. Since one aim of exercise is to be fully aware of state, I am surprised in how it maintains state indirectly and privately based on the value in _start. A simple stopwatch has a very simple state: its either running or not. So I would just directly offer a Boolean IsRunning property with public getter and private setter. This removes any mystery as to what the state is, and it exposes that state clearly and publicly to the consumer of the stopwatch.</p>\n\n<p>I personally would prefer _start to be renamed _startTime, but that's no big deal. I would have the Start() method do 2 things: (1) sets IsRunning to true, and (2) sets _startTime to DateTime.UtcNow. Note that UtcNow is not only faster than Now (Now actually calls UtcNow first), but also allows the stopwatch to not have any odd side effects from Daylight Saving Time transitions (really the biggest reason to use UtcNow).</p>\n\n<p>My other big gripe is the Stop() method should just stop the stopwatch. Your implementation has it stopping and also returning the duration. I would change Stop() to be void, and then offer a TimeSpan Duration property. Stop() should set IsRunning to false, and somehow store the duration for later retrieval.</p>\n\n<p>This now gives you flexibility that you did not possess before. What behavior do you want the stopwatch to exhibit if someone asks for the Duration while its running? Do you want to throw an exception because Stop() has not been issued first? Or would you like to return a Duration while running?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-19T11:02:53.310",
"Id": "421278",
"Score": "1",
"body": "Thank you for your feedback! Your answer makes perfect sense. I've updated my GitHub repo with your suggested changes & I'm a lot happier with it. My `Stop()` method was one thing that I wasn't particulary happy with, your comment about the name of `_start` to `_startTime` just makes more sense in my head. I'm a bit annoyed at myself for not thinking about the state of the object itself. Thank you for teaching me about public getters & private setters (I honestly had no clue that was a thing)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-19T12:40:21.513",
"Id": "421290",
"Score": "1",
"body": "@Webbarr I peeked at your updated GitHub. Amazingly how short and simple the new code base is! Much cleaner to read and understand. There is a bug in Stop (line 26) where you set IsRunning to true when it should be set to false."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-19T20:29:39.293",
"Id": "421334",
"Score": "0",
"body": "it is! Quite embarrassing that I missed that. I've fixed it now. Thank you again for your time, I think the main thing I need to take away is to stop rushing it (missing a glaringly obvious bug like that as a prime example)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T20:20:37.127",
"Id": "217696",
"ParentId": "217285",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "217696",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T19:22:24.690",
"Id": "217285",
"Score": "2",
"Tags": [
"c#",
"object-oriented",
"programming-challenge"
],
"Title": "Stopwatch exercise from training course"
} | 217285 |
<p>I have an angular 7 app that is data focused and as a result has dozens of grids. These grids are from the Kendo UI for ANgular component library made by Telerik. These grid components expose hooks for the sort, filter, group functions of the grid. 90% of the grids I have are a very simple CRUD grid with next to no validation or business logic involved.</p>
<p>As a result, I have to write the following code (Typescript) over and over for each grid:</p>
<pre><code> public initData(): void {
this.gridData = process(this.data, this.gridState);
}
public onStateChange(state: DataStateChangeEvent): void {
state.group.map(group => (group.aggregates = this.aggregates));
this.gridState = state;
this.gridData = process(this.data, this.gridState);
}
public groupChange(grp: GroupDescriptor[]): void {
this.groups = grp;
this.gridData = process(this.data, this.gridState);
}
public sortChange(srt: SortDescriptor[]): void {
this.sort = srt;
this.gridData = process(this.data, this.gridState);
}
public filterChange(fltr: CompositeFilterDescriptor): void {
this.filter = fltr;
this.gridData = process(filterBy(this.data, this.filter), {
group: this.groups,
sort: this.sort
});
}
</code></pre>
<p>this is obviously in the component class behind each grid.</p>
<p>What I am wondering is, Can I move the functions to a service so that I don't have to rewrite them for each component? Additionally, should I create them as static so that there is only one or should I instantiate a new "service" for each component? </p>
<p>Just wondering what others think about this</p>
<p>Thanks</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T20:14:19.253",
"Id": "217286",
"Score": "1",
"Tags": [
"typescript",
"angular-2+"
],
"Title": "angular service for centralizing common grid functions"
} | 217286 |
<p>At the end of each billing cycle, Amazon generates a raw transaction file for my store's orders that cycle. I am converting that raw transaction file into a .csv file to be imported into my accounting software. My converter program takes two input files.</p>
<p>The first input, the <a href="https://drive.google.com/file/d/1kMnQWBOL_t15I56etr0Zwq9UR7VZ-h5w/view?usp=sharing" rel="nofollow noreferrer">Amazon data file</a>, contains hundreds of lines, and looks like this:</p>
<pre><code>settlement-id settlement-start-date settlement-end-date deposit-date total-amount currency transaction-type order-id merchant-order-id adjustment-id shipment-id marketplace-name amount-type amount-description amount fulfillment-id posted-date posted-date-time order-item-code merchant-order-item-id merchant-adjustment-item-id sku quantity-purchased promotion-id
11774871501 2019-04-01 13:09:26 UTC 2019-04-07 14:54:57 UTC 2019-04-09 14:54:57 UTC 11591.38 USD
11774871501 Order 111-3282062-5204245 111-3282062-5204245 DW6NY7djJ Amazon.com ItemPrice Principal 29.95 AFN 2019-04-03 2019-04-03 17:13:29 UTC 04346910081818 D0-FMT7-C3G9 1
11774871501 Order 111-3282062-5204245 111-3282062-5204245 DW6NY7djJ Amazon.com ItemPrice Shipping 4.42 AFN 2019-04-03 2019-04-03 17:13:29 UTC 04346910081818 D0-FMT7-C3G9 1
11774871501 Order 111-3282062-5204245 111-3282062-5204245 DW6NY7djJ Amazon.com ItemFees FBAPerUnitFulfillmentFee -3.19 AFN 2019-04-03 2019-04-03 17:13:29 UTC 04346910081818 D0-FMT7-C3G9 1
11774871501 Order 111-3282062-5204245 111-3282062-5204245 DW6NY7djJ Amazon.com ItemFees Commission -4.49 AFN 2019-04-03 2019-04-03 17:13:29 UTC 04346910081818 D0-FMT7-C3G9 1
11774871501 Order 111-3282062-5204245 111-3282062-5204245 DW6NY7djJ Amazon.com ItemFees ShippingChargeback -4.42 AFN 2019-04-03 2019-04-03 17:13:29 UTC 04346910081818 D0-FMT7-C3G9 1
11774871501 Order 114-8130626-1298654 114-8130626-1298654 D7RCVz0SP Amazon.com ItemPrice Principal 173.08 AFN 2019-04-03 2019-04-03 22:32:57 UTC 50221749590266 E6-0OOH-4ASK 1
11774871501 Order 114-8130626-1298654 114-8130626-1298654 D7RCVz0SP Amazon.com ItemFees FBAPerUnitFulfillmentFee -9.02 AFN 2019-04-03 2019-04-03 22:32:57 UTC 50221749590266 E6-0OOH-4ASK 1
11774871501 Order 114-8130626-1298654 114-8130626-1298654 D7RCVz0SP Amazon.com ItemFees Commission -25.96 AFN 2019-04-03 2019-04-03 22:32:57 UTC 50221749590266 E6-0OOH-4ASK 1
…
</code></pre>
<p>The second input is a <a href="https://drive.google.com/file/d/1pqBqXssA3gofyoZyr4duFm-skZsR9BLf/view?usp=sharing" rel="nofollow noreferrer">CSV file that stores the necessary accounting codes</a>, which contains a few dozen lines, and looks like this:</p>
<pre><code>combined-type,AccountCode,Description
Non-AmazonOrderItemFeesFBAPerUnitFulfillmentFee,501,Non-Amazon - Order - ItemFees - FBAPerUnitFulfillmentFee
Amazon.comOrderItemPricePrincipal,400,Amazon.com - Order - ItemPrice - Principal
Amazon.comOrderItemPriceShipping,403,Amazon.com - Order - ItemPrice - Shipping
Amazon.comOrderItemPriceShippingTax,202,Amazon.com - Order - ItemPrice - ShippingTax
…
</code></pre>
<p>I used Python 3 and Pandas. Can you help me make this code bulletproof? My concern is the code does not catch errors and/or does not execute my intent.</p>
<p>Landmark 1:
Read in the settlement file (raw transaction file).
Read in the account codes file to match transactions to accounting codes.</p>
<p>Landmark 2:
Clean up the settlement file by collecting the summary data and converting the four columns into a combined column for comparison and matching to the account codes file.</p>
<p>Landmark 3:
Find the matching account code for each transaction and sum the total. So now we should have a summary amount for each account code.</p>
<p>Landmark 4:
Clean up the new combined dataframe into the proper template format for our accounting software. Export new file as .csv for uploading into accounting software.</p>
<pre><code>#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
#Read in Amazon settlement - can be picked up by Python script later
az_data = pd.read_csv('/Users/XXX/Desktop/az_data.txt', sep='\t', header=0, parse_dates=['settlement-start-date', 'settlement-end-date'])
df = pd.DataFrame(az_data)
#Read in Account codes - this can be SQL storage later
acct_codes = pd.read_csv('/Users/XXX/Desktop/acct_codes.csv', sep=',', header=0)
df_accts = pd.DataFrame(acct_codes)
#Take summary data from first row of Amazon settlement and use as check-data
settlement_id = df.iloc[0,0]
settlement_start_date = df.iloc[0,1]
settlement_end_date = df.iloc[0,2]
deposit_date = df.iloc[0,3]
invoice_total = df.iloc[0,4]
#Drop summary row as it is no longer needed and doesn't match
df.drop(df.index[0], inplace=True)
#Replace blank values in 'marketplace-name' column with 'alt-transaction' so groupby doesn't skip those values. And replace all other blank values with 'NA' value
fillvalues = {'marketplace-name': 'alt-transaction'}
df.fillna(value=fillvalues, inplace=True)
df.fillna('NA', inplace=True)
#Create combined column to use as a key
df['combined-type'] = df['marketplace-name'] + df['transaction-type'] + df['amount-type']+ df['amount-description']
#Groupby combined column and take sum of categories
df_mod = df.groupby(['combined-type'])[['amount']].sum()
#Merge dataframes to get account codes and descriptions
df_results = df_mod.merge(df_accts, on='combined-type', how='left')
#Drop row from un-used account
df_results = df_results[df_results['combined-type'] != 'Non-AmazonOrderItemPricePrincipal']
#Rename columns to match Xero template
df_results.rename(columns={'amount':'UnitAmount'}, inplace=True)
#Drop the now un-needed combined-type column
df_results.drop(columns=['combined-type'], inplace=True)
#Add invoice template columns with data
df_results['ContactName'] = 'Amazon.com'
df_results['InvoiceNumber'] = 'INV_' + str(settlement_id)
df_results['Reference'] = 'AZ_Xero_Py_' + str(settlement_id)
df_results['InvoiceDate'] = settlement_start_date
df_results['DueDate'] = settlement_end_date
df_results['Quantity'] = 1
df_results['Currency'] = 'USD'
df_results['TaxType'] = 'Tax on Sales'
df_results['TaxAmount'] = 0
df_results['TrackingName1'] = 'Channel'
df_results['TrackingOption1'] = 'Amazon'
#Re-order columns to match template
all_column_list = ['ContactName','EmailAddress','POAddressLine1','POAddressLine2','POAddressLine3','POAddressLine4','POCity','PORegion','POPostalCode','POCountry','InvoiceNumber','Reference','InvoiceDate','DueDate','InventoryItemCode','Description','Quantity','UnitAmount','Discount','AccountCode','TaxType','TrackingName1','TrackingOption1','TrackingName2','TrackingOption2','Currency','BrandingTheme']
df_final = df_results.reindex(columns=all_column_list)
print (df_final.dtypes)
#Re-format the datetimes to be dates
df_final['InvoiceDate'] = df_final['InvoiceDate'].dt.date
df_final['DueDate'] = df_final['DueDate'].dt.date
#Export final df to csv
df_final.to_csv('/Users/XXX/Desktop/invoice' + str(settlement_id) + '.csv', index=False)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T20:50:34.217",
"Id": "420328",
"Score": "0",
"body": "Welcome to Code Review! I hope you'll get some great feedback."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T20:56:59.260",
"Id": "420329",
"Score": "0",
"body": "Thanks @Alex , I am looking forward to learning!"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T20:17:28.333",
"Id": "217287",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"csv",
"pandas",
"e-commerce"
],
"Title": "Convert Amazon transaction data for import into accounting system"
} | 217287 |
<p>I asked this question here: <a href="https://stackoverflow.com/q/55640147/5202255">https://stackoverflow.com/q/55640147/5202255</a> and was told to post on this forum. I would like to know whether my solution can be improved or if there is another approach to the problem. Any help is really appreciated!</p>
<p>I have a pandas dataframe in which the column values exist as lists. Each list has several elements and one element can exist in several rows. An example dataframe is: </p>
<pre><code>X = pd.DataFrame([(1,['a','b','c']),(2,['a','b']),(3,['c','d'])],columns=['A','B'])
X =
A B
0 1 [a, b, c]
1 2 [a, b]
2 3 [c, d]
</code></pre>
<p>I want to find all the rows, i.e. dataframe indexes, corresponding to elements in the lists, and create a dictionary out of it. Disregard column A here, as column B is the one of interest! So element 'a' occurs in index 0,1, which gives {'a':[0,1]}. The solution for this example dataframe is:</p>
<pre><code>Y = {'a':[0,1],'b':[0,1],'c':[0,2],'d':[2]}
</code></pre>
<p>I have written a code that works fine, and I can get a result. My problem is more to do with the speed of computation. My actual dataframe has about 350,000 rows and the lists in the column 'B' can contain up to 1,000 elements. But at present the code is running for several hours! I was wondering whether my solution is very inefficient.
Any help with a faster more efficient way will be really appreciated!
Here is my solution code:</p>
<pre><code>import itertools
import pandas as pd
X = pd.DataFrame([(1,['a','b','c']),(2,['a','b']),(3,['c','d'])],columns=['A','B'])
B_dict = []
for idx,val in X.iterrows():
B = val['B']
B_dict.append(dict(zip(B,[[idx]]*len(B))))
B_dict = [{k: list(itertools.chain.from_iterable(list(filter(None.__ne__, [d.get(k) for d in B_dict])))) for k in set().union(*B_dict)}]
print ('Result:',B_dict[0])
</code></pre>
<p>Output</p>
<pre><code>Result: {'d': [2], 'c': [0, 2], 'b': [0, 1], 'a': [0, 1]}
</code></pre>
<p>The code for the final line in the for loop was borrowed from here <a href="https://stackoverflow.com/questions/45649141/combine-values-of-same-keys-in-a-list-of-dicts">https://stackoverflow.com/questions/45649141/combine-values-of-same-keys-in-a-list-of-dicts</a>, and <a href="https://stackoverflow.com/questions/16096754/remove-none-value-from-a-list-without-removing-the-0-value">https://stackoverflow.com/questions/16096754/remove-none-value-from-a-list-without-removing-the-0-value</a></p>
| [] | [
{
"body": "<p>First, I would use <a href=\"https://stackoverflow.com/a/39011596/4042267\">this solution</a> by <a href=\"https://stackoverflow.com/users/2901002/jezrael\">@jezrael</a> to expand your lists into rows of the dataframe, repeating the values of the index where necessary:</p>\n\n<pre><code>df2 = pd.DataFrame(df.B.tolist(), index=df.index) \\ \n .stack() \\ \n .reset_index(level=1, drop=True) \\ \n .reset_index(name=\"B\")\n# index B\n# 0 0 a\n# 1 0 b\n# 2 0 c\n# 3 1 a\n# 4 1 b\n# 5 2 c\n# 6 2 d\n</code></pre>\n\n<p>Then you can simply group by <code>B</code> and get all values of <code>index</code>:</p>\n\n<pre><code>df2.groupby(\"B\")[\"index\"].apply(list).to_dict()\n# {'a': [0, 1], 'b': [0, 1], 'c': [0, 2], 'd': [2]}\n</code></pre>\n\n<p>This should be faster for large dataframes (but you should profile it to make sure it is). However, it will create a largish intermediate dataframe (basically duplicate your current one), so might not be usable for <em>very</em> large dataframes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T14:26:18.617",
"Id": "420558",
"Score": "1",
"body": "Thanks for the response and help Graipher! As pointed out by the user below, this solution becomes slower when the data size becomes larger. The defaultdict approach is much faster, so I have accepted that as the solution. I used the solution given to my problem here: https://stackoverflow.com/questions/55640147/fastest-way-to-find-dataframe-indexes-of-column-elements-that-exist-as-lists/55641757#55641757. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T09:09:20.200",
"Id": "217313",
"ParentId": "217288",
"Score": "2"
}
},
{
"body": "<h1><code>itertuples</code></h1>\n<p>When traversing over the rows of a <code>DataFrame</code>, using itertuples is generally faster than <code>iterrows</code>. The latter makes a new <code>Series</code> for each row, the former a <code>namedtuple</code>, which is generally faster.</p>\n<h1><code>defaultdict</code></h1>\n<p>Appending items to a list on a key is typically done with a <code>defaultdict</code>.</p>\n<pre><code>from collections import defaultdict\nresult = collections.defaultdict(list)\nfor row in X.itertuples():\n idx = row.Index\n for item in row.B:\n result[item].append(idx)\n</code></pre>\n<p>The method you use to combine the values in the dictionary is meant to include empty items as <code>None</code>. Here you add them, and then filter them out, so using a <code>defaultdict</code> will simplify this up a lot.</p>\n<h1>naming</h1>\n<p>Try to follow pep-8.</p>\n<ul>\n<li><code>snake_case</code> for variables, etc.</li>\n<li>spaces around operators</li>\n<li>...</li>\n</ul>\n<hr />\n<h1>timings</h1>\n<h2>dummy data</h2>\n<pre><code>def make_dummydata(rows, max_length, seed=0):\n letters = string.ascii_letters\n np.random.seed(seed)\n random.seed(seed)\n col1 = np.random.randint(0, 10, size=rows)\n items_per_row = np.random.randint(0, max_length, size=rows) + 1\n col2 = [random.choices(letters, k=amount) for amount in items_per_row]\n return pd.DataFrame({"A": col1, "B": col2})\n</code></pre>\n<h2>benchmark method</h2>\n<pre><code>import timeit\n\ndef benchmark(cases, functions):\n for rows, max_length in cases:\n df = make_dummydata(rows, max_length)\n for name, function in functions.items():\n result = timeit.timeit(\n stmt=f"function(df)",\n globals={"df": df, "function": function},\n number=1,\n )\n yield rows, max_length, name, result\n</code></pre>\n<h2>results</h2>\n<pre><code>cases = [(10, 2), (100, 10), (1000, 40), (10000, 200)]\nfunctions = {\n "OP": find_op,\n "maarten": find_maarten,\n "jezrael": find_jezrael,\n}\nlist(benchmark())\n</code></pre>\n<blockquote>\n<pre><code>[(10, 2, 'OP', 0.001344002000003286),\n (10, 2, 'maarten', 0.0003913850000003549),\n (10, 2, 'jezrael', 0.005293956000002709),\n (100, 10, 'OP', 0.027166392000005146),\n (100, 10, 'maarten', 0.0004795910000012782),\n (100, 10, 'jezrael', 0.013824836999994261),\n (1000, 40, 'OP', 0.3434149869999956),\n (1000, 40, 'maarten', 0.0032574399999987236),\n (1000, 40, 'jezrael', 0.018533767000000978),\n (10_000, 200, 'OP', 33.48681208600001),\n (10_000, 200, 'maarten', 0.10972772499999905),\n (10_000, 200, 'jezrael', 0.7631061700000004),\n (350_000, 1000, 'maarten', 22.097186581000003),\n (350_000, 1000, 'jezrael', 516.128048978)]\n</code></pre>\n</blockquote>\n<p>The method using <code>defaultdict</code> is a lot faster. This only says something about the run-time, not the memory usage, where my method does not create a large intermediary <code>DataFrame</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T14:28:59.020",
"Id": "420559",
"Score": "0",
"body": "Thanks a lot Maarten for this insightful response! Plenty to learn from it. The defaultdict approach is indeed the best solution here. I have accepted your solution and also the solution to my problem posted here: https://stackoverflow.com/questions/55640147/fastest-way-to-find-dataframe-indexes-of-column-elements-that-exist-as-lists/55641757#55641757, which are the same."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T10:45:34.267",
"Id": "217316",
"ParentId": "217288",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "217316",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T20:45:29.320",
"Id": "217288",
"Score": "2",
"Tags": [
"python",
"performance",
"pandas",
"hash-map"
],
"Title": "Fastest way to find dataframe indexes of column elements that exist as lists"
} | 217288 |
<p>My code exceeds the time limit on the second test set. A suggestion/hint of a better algorithm would be appreciated. </p>
<blockquote>
<p><strong>Problem</strong></p>
<p>Thanh wants to paint a wonderful mural on a wall that is <strong>N</strong> sections long. Each section of the wall has a <em>beauty score</em>, which indicates how beautiful it will look if it is painted. Unfortunately, the wall is starting to crumble due to a recent flood, so he will need to work fast!</p>
<p>At the beginning of each day, Thanh will paint one of the sections of the wall. On the first day, he is free to paint any section he likes. On each subsequent day, he must paint a new section that is next to a section he has already painted, since he does not want to split up the mural.</p>
<p>At the end of each day, one section of the wall will be destroyed. It is always a section of wall that is adjacent to only one other section and is unpainted (Thanh is using a waterproof paint, so painted sections can't be destroyed).</p>
<p>The <em>total beauty</em> of Thanh's mural will be equal to the sum of the beauty scores of the sections he has painted. Thanh would like to guarantee that, no matter how the wall is destroyed, he can still achieve a total beauty of at least B. What's the maximum value of B for which he can make this guarantee?</p>
<p><strong>Input</strong></p>
<p>The first line of the input gives the number of test cases, <strong>T</strong>. <strong>T</strong> test cases follow. Each test case starts with a line containing an integer <strong>N</strong>. Then, another line follows containing a string of <strong>N</strong> digits from 0 to 9. The i-th digit represents the beauty score of the i-th section of the wall.</p>
<p><strong>Output</strong></p>
<p>For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is the maximum beauty score that Thanh can guarantee that he can achieve, as described above.</p>
<p><strong>Limits</strong></p>
<ul>
<li>1 ≤ <strong>T</strong> ≤ 100.</li>
<li>Time limit: 20 seconds per test set.</li>
<li>Memory limit: 1 GB.</li>
</ul>
<p><strong>Small dataset (Test set 1 - Visible)</strong></p>
<p>2 ≤ <strong>N</strong> ≤ 100.</p>
<p><strong>Large dataset (Test set 2 - Hidden)</strong></p>
<p>For exactly 1 case, <strong>N</strong> = 5 × 10^6; for the other <strong>T</strong> - 1 cases, 2 ≤ <strong>N</strong> ≤ 100.</p>
<p><strong>Sample</strong></p>
<p>Input</p>
<pre><code>4
4
1332
4
9583
3
616
10
1029384756
</code></pre>
<p>Output</p>
<pre><code>Case #1: 6
Case #2: 14
Case #3: 7
Case #4: 31
</code></pre>
<p>In the first sample case, Thanh can get a total beauty of 6, no matter how the wall is destroyed. On the first day, he can paint either section of wall with beauty score 3. At the end of the day, either the 1st section or the 4th section will be destroyed, but it does not matter which one. On the second day, he can paint the other section with beauty score 3.</p>
<p>In the second sample case, Thanh can get a total beauty of 14, by painting the leftmost section of wall (with beauty score 9). The only section of wall that can be destroyed is the rightmost one, since the leftmost one is painted. On the second day, he can paint the second leftmost section with beauty score 5. Then the last unpainted section of wall on the right is destroyed. Note that on the second day, Thanh cannot choose to paint the third section of wall (with beauty score 8), since it is not adjacent to any other painted sections.</p>
<p>In the third sample case, Thanh can get a total beauty of 7. He begins by painting the section in the middle (with beauty score 1). Whichever section is destroyed at the end of the day, he can paint the remaining wall at the start of the second day.</p>
</blockquote>
<p><strong>My solution</strong></p>
<pre><code>T = int(input()) # number of tries in test set
for i in range(1,T+1):
N = int(input()) # number of sections of wall
score_input = input() # string input of beauty scores
beauty_scores = [int(x) for x in score_input]
muralLength = (N+1)//2
bestScore = 0 # to obtain best beauty score
for k in range((N+2)//2): # the no. of possible murals
score = sum(beauty_scores[k:k+muralLength])
if score > bestScore:
bestScore = score
print("Case #{}: {}".format(i, bestScore))
</code></pre>
<p><strong>Further details</strong></p>
<p>My code worked fine for the first test set, but the time limit was exceeded for the second. The most likely outcome is that with the test case <strong>N</strong> = 5 x 10^6, there was far too many mural options for the code to check (2500001 to be exact.)</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T22:28:00.290",
"Id": "420335",
"Score": "1",
"body": "Welcome to Code Review! I hope you will get some great reviews."
}
] | [
{
"body": "<p>A time to compute <code>sum(beauty_scores[k:k+muralLength])</code> is proportional to <code>muralLength</code>, which is <code>N/2</code>, and there are <code>N/2</code> iterations. Total time to execute the loop is <span class=\"math-container\">\\$O(N^2)\\$</span>. TLE.</p>\n\n<p>As a hint, once you've computed the sum for a <code>[0..m]</code> slice, the sum for next slice (<code>[1..m+1]</code>) can be computed much faster. I don't want to say more.</p>\n\n<hr>\n\n<p><code>range(1, T+1)</code> is unconventional, considering that <code>i</code> is never used. Also, Pythonic style recommends to use <code>_</code> for a dummy loop variable:</p>\n\n<pre><code> for _ in range(T):\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T11:54:19.933",
"Id": "420408",
"Score": "1",
"body": "I used `i` as part of the output, which was needed for the question. Will keep `_` in mind in the future!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T23:46:39.080",
"Id": "217291",
"ParentId": "217289",
"Score": "8"
}
}
] | {
"AcceptedAnswerId": "217291",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T21:43:07.990",
"Id": "217289",
"Score": "5",
"Tags": [
"python",
"performance",
"python-3.x",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Google Kick Start Practice Round 2019 - Mural"
} | 217289 |
<p>I am reading an Excel file using Pandas and I feel like there has to be a better way to handle the way I create column names. This is something like the Excel file I'm reading:</p>
<pre><code> 1 2 # '1' is merged in the two cells above 'a'and 'b'
Date a b c d # likewise for '2'. As opposed to 'centered across selection'
1 1-Jan-19 100 200 300 400
2 1-Feb-19 101 201 301 401
3 1-Mar-19 102 202 302 402
</code></pre>
<p>I want my to merge the 'a','b','c',and'd' columns heads with the '1'and '2' above them, so I'm doing the following to get my headers the way that I want:</p>
<pre><code>import pandas as pd
import json
xls = pd.ExcelFile(r'C:\Path_to\Excel_Pandas_Connector_Test.xls')
df = pd.read_excel(xls, 'Sheet1', header=[1]) # uses the abcd row as column names
# I only want the most recent day of data so I do the following
json_str = df[df.Date == df['Date'].max()].to_json(orient='records',date_format='iso')
dat_data = json.loads(json_str)[0]
def clean_json():
global dat_data
dat_data['1a'] = dat_data.pop('a')
dat_data['1b'] = dat_data.pop('b')
dat_data['2c'] = dat_data.pop('c')
dat_data['2d'] = dat_data.pop('d')
clean_json()
print(json.dumps(dat_data,indent=4))
</code></pre>
<p>My desired output is:</p>
<pre><code>{
"Date": "2019-03-01T00:00:00.000Z",
"1a": 102,
"1b": 202,
"2c": 302,
"2d": 402
}
</code></pre>
<p>This works as written, but is there a Pandas built-in that I could have used to do the same thing instead of the clean_json function?</p>
| [] | [
{
"body": "<p>Yes, there is an easier way, using <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Index.get_level_values.html\" rel=\"nofollow noreferrer\"><code>pandas.Index.get_level_values</code></a>.</p>\n\n<p>First, I could only get your example dataframe when calling the read with <code>df = pd.read_excel(\"/tmp/temp.xls\", header=[0, 1])</code>, so I get both headers correctly.</p>\n\n<p>Then you can just do this:</p>\n\n<pre><code>import pandas as pd\nimport json\n\n# read df\ndf = pd.read_excel(\"/tmp/temp.xls\", header=[0, 1])\ndf.index = pd.to_datetime(df.index)\n\n# combine multilevel columns to one level\ndf.columns = (pd.Series(df.columns.get_level_values(0)).apply(str)\n + pd.Series(df.columns.get_level_values(1)).apply(str))\n\n# get Date as a column\ndf = df.reset_index()\ndf.columns = [\"Date\"] + list(df.columns[1:])\n\nprint(df)\n# 1a 1b 2c 2d\n# 2019-01-02 100 200 300 400\n# 2019-01-02 101 201 301 401\n# 2019-01-03 102 202 302 402\n</code></pre>\n\n<p>After which you can just do something similar to what you are doing, but directly getting the index of the maximum instead of comparing all values to the value of the maximum:</p>\n\n<pre><code>json_data = json.loads(df.loc[df.Date.idxmax()].to_json(date_format='iso'))\nprint(json.dumps(json_data, indent=4))\n</code></pre>\n\n<p>Which produces the desired output:</p>\n\n<pre><code>{\n \"Date\": \"2019-01-03T00:00:00.000Z\",\n \"1a\": 102,\n \"1b\": 202,\n \"2c\": 302,\n \"2d\": 402\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T12:24:47.730",
"Id": "420411",
"Score": "1",
"body": "Thanks, that's really concise and works well. I can see that there is a lot to learn in Pandas."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T08:28:37.710",
"Id": "217310",
"ParentId": "217294",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "217310",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T00:10:49.360",
"Id": "217294",
"Score": "3",
"Tags": [
"python",
"excel",
"pandas"
],
"Title": "Python: Combining Two Rows with Pandas read_excel"
} | 217294 |
<p>I'm attempting to parse an SVG file to get all of the colors that are present in the file. SVGs are XML based and their structure can vary a bit. For example:</p>
<pre><code><svg viewBox="-80 -80 160 160">
<g stroke="black" fill="none">
<path d='...' fill='#0FF'/>
<path d='...' fill='#F0F'/>
...
</g>
</svg>
</code></pre>
<p>and</p>
<pre><code><svg viewBox="0 0 100 100">
<a>
<path d="..." stroke="black" fill="red"/>
<ellipse stroke="black" fill="white" cx="50" cy="40" rx="22" ry="35"/>
<circle cx="50" cy="40" r="5" stroke="black" fill="red"/>
</a>
</svg>
</code></pre>
<p>and</p>
<pre><code><svg viewBox="0 0 80 120">
<rect id="background-rect" x="0%" y="0%" width="100%" height="100%" fill="#aaaaaa"/>
</svg>
</code></pre>
<p>Are all examples of valid SVGs. At first I attempted to create the underlying <code>struct</code>s that would allow me to represent all of these structures but then I decided to take a more generic approach that would focus soley on the <code>fill</code> attribute which is all I care about:</p>
<pre><code>type GenericNode struct {
XMLName xml.Name
Fill string `xml:"fill,attr"`
Nodes []GenericNode `xml:",any"`
}
func (s *SVGController) GetColorsFromXML() []string {
xmlFile, _ := os.Open(s.Path)
byteValue, _ := ioutil.ReadAll(xmlFile)
var svg GenericNode
xml.Unmarshal(byteValue, &svg)
// Using a map here to avoid having to worry about having
// duplicate colors in the color slice
colorMap := make(map[string]struct{})
colorMap = getSVGColors(svg, colorMap)
// Once we have a complete color map extract all the keys
// to an array and return it.
colors := make([]string, len(colorMap))
i := 0
for k := range colorMap {
colors[i] = k
i++
}
return colors
}
func getSVGColors(svg GenericNode, colors map[string]struct{}) map[string]struct{} {
if svg.Fill != "" && strings.ToLower(svg.Fill) != "none" {
colors[svg.Fill] = struct{}{}
}
for _, node := range svg.Nodes {
colors = getSVGColors(node, colors)
}
return colors
}
</code></pre>
<p>Is this a reasonable approach to take? Am I doing anything here that should be avoided?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T00:48:16.793",
"Id": "217296",
"Score": "1",
"Tags": [
"xml",
"go"
],
"Title": "Extracting attribute value from multiple XML nodes in golang?"
} | 217296 |
<p>This is meant to present main content in the carousel above with a painless navigation below where the moment you start dragging the content keeps up.</p>
<p>I was trying to avoid having to drag once per slide or press "next" many times. Also the <code>previous</code> and <code>next</code> classes are added for effect. Will look quite different in production, it's the functionality I'm showing off here.</p>
<p>Here's a working codepen: <a href="https://codepen.io/Julix/pen/xexawP" rel="nofollow noreferrer">https://codepen.io/Julix/pen/xexawP</a></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>// Flickity slider from external js: flickity.pkgd.js
// Prev- and next classes from external js: https://codepen.io/desandro/pen/wWQQwN.js
"use strict";
var $carousel = $('.carousel-main').flickity({
"wrapAround": true,
"draggable": true,
"prevNextButtons": false,
"pageDots": false
});
var $nav = $('.carousel-nav').flickity({
"on": {
ready: choseCenterSlide,
scroll: choseCenterSlide
},
"asNavFor": ".carousel-main",
"wrapAround": true,
"percentPosition": false,
"draggable": true,
"pageDots": false,
"prevNextButtons": false
});
;
var navDragging = false;
$nav.on('dragStart.flickity', function () {
return navDragging = true;
});
$nav.on('settle.flickity', function () {
return navDragging = false;
});
$nav.data('flickity').resize();
var isWrapped = true;
var isInstant = true;
function choseCenterSlide() {
// check if this.x is within slideableWidth
var currentX = this.x > 0 ? -this.slideableWidth + this.x : this.x < -this.slideableWidth ? this.slideableWidth + this.x : this.x; // calculate closest slide
var distances = this.slides.map(function (slide) {
return -slide.target;
});
var closestDistance = distances.reduce(function (prev, curr) {
return Math.abs(curr - currentX) < Math.abs(prev - currentX) ? curr : prev;
});
var closestSlideIndex = distances.indexOf(closestDistance); // early return
if (closestSlideIndex == this.scrollSlideIndex) return; // register
if (this.scrollSlideIndex == null) this.scrollSlideIndex = this.selectedIndex; // change scrollSlide
this.slides[this.scrollSlideIndex].cells.forEach(function (cell) {
cell.element.classList.remove('is-closest');
});
this.slides[closestSlideIndex].cells.forEach(function (cell) {
cell.element.classList.add('is-closest');
}); // update state variable
this.scrollSlideIndex = closestSlideIndex; // update selectedSlide
if (navDragging) {
this.select(this.scrollSlideIndex, isWrapped, isInstant);
if (this.navCompanion) {
this.navCompanion.select(this.scrollSlideIndex);
}
}
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* external css: flickity.css */
.carousel-nav .carousel-cell.is-selected {
background: lightblue;
}
.carousel-nav .carousel-cell.is-closest {
background: #ffd466;
}
.carousel-nav .carousel-cell.is-closest {
background: #ffd466;
}
.carousel-nav .carousel-cell.is-selected {
background: lightblue;
}
.carousel-nav .carousel-cell.is-nav-selected {
background: linear-gradient(to left, darkred, #640404, darkred);
}
.carousel-nav .carousel-cell.is-previous {
background: linear-gradient(to left, darkred, lightgreen);
}
.carousel-nav .carousel-cell.is-next {
background: linear-gradient(to right, darkred, lightgreen);
}
* { box-sizing: border-box; }
body { font-family: sans-serif; }
.carousel {
background: transparent;
}
.carousel-main .carousel-cell,
.carousel-nav .carousel-cell {
height: 100px;
margin-right: 10px;
background: #8C8;
border-radius: 5px;
counter-increment: carousel-cell;
}
.carousel-main .carousel-cell {
height: 200px;
line-height: 200px;
width: 66%;
}
.carousel-nav .carousel-cell {
width: 300px;
}
/* cell number */
.carousel-cell:before {
display: block;
text-align: center;
content: counter(carousel-cell);
font-size: 80px;
color: white;
}
.carousel-nav {
}
.carousel-nav .carousel-cell {
width: 200px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://npmcdn.com/flickity@2/dist/flickity.pkgd.js"></script>
<script src="https://codepen.io/desandro/pen/wWQQwN.js"></script>
<h1>Main attraction</h1>
<div class="carousel carousel-main">
<div class="carousel-cell"></div>
<div class="carousel-cell"></div>
<div class="carousel-cell"></div>
<div class="carousel-cell"></div>
<div class="carousel-cell"></div>
<div class="carousel-cell"></div>
<div class="carousel-cell"></div>
<div class="carousel-cell"></div>
<div class="carousel-cell"></div>
<div class="carousel-cell"></div>
<div class="carousel-cell"></div>
<div class="carousel-cell"></div>
</div>
<h2>Navigation</h2>
<div class="carousel carousel-nav">
<div class="carousel-cell"></div>
<div class="carousel-cell"></div>
<div class="carousel-cell"></div>
<div class="carousel-cell"></div>
<div class="carousel-cell"></div>
<div class="carousel-cell"></div>
<div class="carousel-cell"></div>
<div class="carousel-cell"></div>
<div class="carousel-cell"></div>
<div class="carousel-cell"></div>
<div class="carousel-cell"></div>
<div class="carousel-cell"></div>
</div></code></pre>
</div>
</div>
</p>
<p>Feedback welcome! :)</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T01:00:45.537",
"Id": "217298",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "Flickity JS carousel plus nav slider"
} | 217298 |
<p>I wrote this for a class project, the backend for this <a href="https://socialchoice.nuphilosophy.com/" rel="nofollow noreferrer">dog voting website</a>. I noticed duplicate code among multiple functions I was writing to be deployed as a cloud function: they all were wrapped in try/except blocks that returned either 200 and JSON or 500 and a traceback. (I understand that it would be better to return an informative, structured error code, but this helped with debugging and we didn't have extensive error handling on the front-end: this was a loss I was willing to take).</p>
<p>The decorator gives each function a connection pool, uses jsonschema to validate input and output, responds to CORS OPTIONS from anywhere, and uses print statements for logging. This isn't great, but it was far easier to set up than the Google Cloud Function logging library, and everything printed to stdout during function execution is logged to GCP Stackdriver.</p>
<p>Here is the decorator itself:</p>
<pre><code>import functools
import json
import traceback
import jsonschema
from util.get_pool import get_pool
pg_pool = None
def cloudfunction(in_schema=None, out_schema=None):
"""
:param in_schema: the schema for the input, or a falsy value if there is no input
:param out_schema: the schema for the output, or a falsy value if there is no output
:return: the cloudfunction wrapped function
"""
# Both schemas must be valid according to jsonschema draft 7, if they are provided.
if in_schema:
jsonschema.Draft7Validator.check_schema(in_schema)
if out_schema:
jsonschema.Draft7Validator.check_schema(out_schema)
def cloudfunction_decorator(f):
""" Wraps a function with two arguments, the first of which is a json object that it expects to be sent with the
request, and the second is a postgresql pool. It modifies it by:
- setting CORS headers and responding to OPTIONS requests with `Allow-Origin *`
- passing a connection from a global postgres connection pool
- adding logging, of all inputs as well as error tracebacks.
:param f: A function that takes a `request` and a `pgpool` and returns a json-serializable object
:return: a function that accepts one argument, a Flask request, and calls f with the modifications listed
"""
@functools.wraps(f)
def wrapped(request):
global pg_pool
if request.method == 'OPTIONS':
return cors_options()
# If it's not a CORS OPTIONS request, still include the base header.
headers = {'Access-Control-Allow-Origin': '*'}
if not pg_pool:
pg_pool = get_pool()
try:
conn = pg_pool.getconn()
if in_schema:
request_json = request.get_json()
print(repr({"request_json": request_json}))
jsonschema.validate(request_json, in_schema)
function_output = f(request_json, conn)
else:
function_output = f(conn)
if out_schema:
jsonschema.validate(function_output, out_schema)
conn.commit()
print(repr({"response_json": function_output}))
response_json = json.dumps(function_output)
# TODO allow functions to specify return codes in non-exceptional cases
return (response_json, 200, headers)
except:
print("Error: Exception traceback: " + repr(traceback.format_exc()))
return (traceback.format_exc(), 500, headers)
finally:
# Make sure to put the connection back in the pool, even if there has been an exception
try:
pg_pool.putconn(conn)
except NameError: # conn might not be defined, depending on where the error happens above
pass
return wrapped
return cloudfunction_decorator
# If given an OPTIONS request, tell the requester that we allow all CORS requests (pre-flight stage)
def cors_options():
# Allows GET and POST requests from any origin with the Content-Type
# header and caches preflight response for an 3600s
headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Max-Age': '3600'
}
return ('', 204, headers)
</code></pre>
<p>get_pool is here:</p>
<pre><code>from os import getenv
from psycopg2 import OperationalError, connect
from psycopg2.pool import SimpleConnectionPool
INSTANCE_CONNECTION_NAME = getenv('INSTANCE_CONNECTION_NAME', "")
POSTGRES_USER = getenv('POSTGRES_USER', "")
POSTGRES_PASSWORD = getenv('POSTGRES_PASSWORD', "")
POSTGRES_NAME = getenv('POSTGRES_DATABASE', "postgres")
pg_config = {
'user': POSTGRES_USER,
'password': POSTGRES_PASSWORD,
'dbname': POSTGRES_NAME
}
def get_pool():
try:
return __connect(f'/cloudsql/{INSTANCE_CONNECTION_NAME}')
except OperationalError:
# If production settings fail, use local development ones
return __connect('localhost')
def __connect(host):
"""
Helper functions to connect to Postgres
"""
pg_config['host'] = host
return SimpleConnectionPool(1, 1, **pg_config)
def get_connection(host="localhost"):
pg_config["host"] = host
return connect(**pg_config)
</code></pre>
<p>And an example of usage:</p>
<pre><code>
@cloudfunction(
in_schema={"type": "string"},
out_schema={
"anyOf": [{
"type": "object",
"properties": {
"dog1": {"type": "integer"},
"dog2": {"type": "integer"}
},
"additionalProperties": False,
"minProperties": 2,
}, {
"type": "null"
}]
})
def get_dog_pair(request_json, conn):
[function body elided]
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T02:23:12.860",
"Id": "217303",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"web-services",
"google-cloud-platform"
],
"Title": "Decorate a python function to work as a Google Cloud Function"
} | 217303 |
<p>I am unsure if I followed the the suggestions on my <a href="https://codereview.stackexchange.com/questions/217235/first-python-program-tic-tac-toe/217290">previous post</a>.
I have only been working on programming for about 3 weeks so any more suggestions or insight would be more than welcomed.</p>
<pre><code>import sys
from textwrap import dedent
import os
import random
os.system('CLS')
# board number setup
board = [0, 1, 2,
3, 4, 5,
6, 7, 8]
# Defines the board layout printed to the console
def board_layout():
print(dedent(f'''
*************
* {board[0]} | {board[1]} | {board[2]} *
*-----------*
* {board[3]} | {board[4]} | {board[5]} *
*-----------*
* {board[6]} | {board[7]} | {board[8]} *
*************
'''))
def main():
players = ('Player','NPC')
turn = 'Player'
change_turn = 0
for moves in range(9):
if turn == 'Player':
while True:
try:
board_layout()
player_move = int(input('Please select a spot: '))
if board[player_move] != 'x' and board[player_move] != 'o':
board[player_move] = 'x'
check_winner()
break
except IndexError:
print('please select valid spot')
if turn == 'NPC':
# npc move, chooses a random spot that is not taken
while True:
npc = random.randint(0, 8)
if board[npc] != 'o' and board[npc] != 'x':
board[npc] = 'o'
print('Computer chooses spot ', npc)
check_winner()
break
try:
change_turn += 1
turn = players[change_turn]
except:
change_turn = 0
turn = players[change_turn]
else:
print('You Tied')
end()
def end():
print('Thank you for playing')
answer = input('Would you like to play again?: Y/N')
if answer.lower() == 'n':
quit()
elif answer.lower() == 'y':
clear_board()
main()
else:
print('Please choose a valid option')
end()
def clear_board():
for i in range(9):
board[i] = i
# checks for a winner when called at end of each turn
def check_winner():
# list of lists with all the winning combinations for from the tic tac toe board
winning_list = [[board[0], board[1], board[2]], [board[3], board[4], board[5], ],
[board[6], board[7], board[8]], [board[0], board[4], board[8]],
[board[2], board[4], board[6]],
[board[0], board[3], board[6]], [board[1], board[4], board[7]],
[board[2], board[5], board[8]]]
# iterates over the lists in winning_list
for i, j, k in winning_list:
# looks at the lists in winning_list to determine if a list has all x's for a win
if i == 'x' and j == 'x' and k == 'x':
print('X wins')
end()
# looks at the lists in winning_list to determine if a list has all o's for a win
elif i == 'o' and j == 'o' and k == 'o':
print('O wins')
end()
if __name__ == "__main__":
main()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T05:26:12.740",
"Id": "420349",
"Score": "0",
"body": "Many of your code improvements can be taken from this post, please have a look: https://codereview.stackexchange.com/questions/201506/tictactoe-game-in-python-3"
}
] | [
{
"body": "<p>You now have two methods of setting up the board. The first is direct initialization:</p>\n\n<pre><code>board = [0, 1, 2,\n 3, 4, 5,\n 6, 7, 8]\n</code></pre>\n\n<p>and the second is a resetting an already existing board:</p>\n\n<pre><code>def clear_board():\n for i in range(9):\n board[i] = i\n</code></pre>\n\n<p>I hate that there are two. It would be easy to make a mistake and change one (for example, changing to a 4x4 grid) but not the other.</p>\n\n<hr>\n\n<p><code>board_layout()</code> is an odd name for the function that prints the board. It is not laying out the board. I might call it <code>print_board()</code>.</p>\n\n<p>I dislike seeing the same thing over and over. In <code>board_layout()</code>, you have <code>board[ ]</code> appear 9 times in the format string. If you wanted to change the name of the game board, you'd have to edit the code in 9 places in this one function. You can eliminate these duplicates using the <code>.format()</code> command, instead of using a f-string. I know, seems like going backwards; f-strings are supposed to be an improvement!</p>\n\n<pre><code>''' \n*************\n* {} | {} | {} *\n*-----------*\n* {} | {} | {} *\n*-----------*\n* {} | {} | {} *\n*************\n'''.format(*board)\n</code></pre>\n\n<p><code>*board</code> takes the <code>board</code> list, takes the individual elements and \"splats\" them all as the arguments to the <code>.format()</code> call. Each argument, in turn, is substituted into the next <code>{}</code> format code.</p>\n\n<hr>\n\n<p>Jumping ahead.</p>\n\n<pre><code> winning_list = [[board[0], board[1], board[2]], [board[3], board[4], board[5], ],\n [board[6], board[7], board[8]], [board[0], board[4], board[8]],\n [board[2], board[4], board[6]],\n [board[0], board[3], board[6]], [board[1], board[4], board[7]],\n [board[2], board[5], board[8]]]\n</code></pre>\n\n<p>Again, here we have <code>board[ ]</code> repeated 24 times! There has got to be a better way. And there is. First, create as a global constant, a list of list of winning indices. Since these will never be modified, I've used tuples instead of lists.</p>\n\n<pre><code>WINNING_ROWS = ((0, 1, 2), (3, 4, 5), (6, 7, 8), # Rows\n (0, 3, 6), (1, 4, 7), (2, 5, 8), # Columns\n (0, 4, 8), (2, 4, 6)) # Diagonals\n</code></pre>\n\n<p>Now we just need to use these indices to check for a win condition. We can even use chained comparisons to make the test more concise:</p>\n\n<pre><code> for i, j, k in WINNING_ROWS:\n if board[i] == board[j] == board[k] == 'x':\n print('X wins')\n</code></pre>\n\n<p>That tests <code>board[i] == board[j]</code> AND <code>board[j] == board[k]</code> AND <code>board[k] == 'x'</code>, but we haven't repeated any of the terms in the test.</p>\n\n<pre><code> elif board[i] == board[j] == board[k] == 'o':\n print('O wins')\n</code></pre>\n\n<p>And now we have.</p>\n\n<p>Whenever you repeat code, you should think \"maybe a loop\" or \"maybe a function\". A loop doesn't seem right here. Let's use a function:</p>\n\n<pre><code>def has_won(player):\n for i, j, k in WINNING_ROWS:\n if board[i] == board[j] == board[k] == player:\n return True\n return False\n</code></pre>\n\n<p>Now you can use <code>if has_won('x'):</code> to check in the <code>'x'</code> player has won after they have made their move, and <code>if has_won('o'):</code> to check if the <code>'o'</code> player has won after they have made theirs.</p>\n\n<p>We can condense this function. The <code>all()</code> function will test each of its arguments, and return <code>True</code> only if all of the arguments are true. We can use list comprehension to extract each index in turn from the row tuples:</p>\n\n<pre><code>def has_won(player):\n for row in WINNING_ROWS:\n if all(board[idx] == player for idx in row):\n return True\n return False\n</code></pre>\n\n<p>Like the <code>all()</code> function, there is an <code>any()</code> function, which returns <code>True</code> if any of its arguments are true. Again, we'll use list comprehension to loop over each row in <code>WINNING_ROWS</code>:</p>\n\n<pre><code>def has_won(player):\n return any(all(board[idx] == player for idx in row) for row in WINNING_ROWS)\n</code></pre>\n\n<p>For any of the winning rows, if all of the board locations contain the player's symbol, <code>True</code> is returned. Pretty darn concise, if you want to use it.</p>\n\n<hr>\n\n<p>Checking for a valid spot:</p>\n\n<pre><code>if board[player_move] != 'x' and board[player_move] != 'o':\n\nif board[npc] != 'o' and board[npc] != 'x':\n</code></pre>\n\n<p>Effectively the same test, repeated twice. And <code>board[pos]</code> referenced twice in each test. Don't Repeat Yourself. DRY. As opposed to Write Everything Twice, or WET. You want DRY code, not WET code. The <code>in</code> operator will test if the item on the left of <code>in</code> is contained in the container on the right.</p>\n\n<pre><code>def is_valid_move(move):\n return board[move] not in ('x', 'o')\n</code></pre>\n\n<p>Not bad. But is <code>12</code> a valid move? How about <code>-1</code>? Note that <code>-1</code> will not cause an <code>IndexError</code>, it will just return the last element of the list (<code>board[8]</code>).</p>\n\n<pre><code>def is_valid_move(move):\n return move in range(9) and board[move] not in ('x', 'o')\n</code></pre>\n\n<hr>\n\n<p>Elephant in the room.</p>\n\n<p>You play the game, win, play again, loose, play again, tie, play again. What is the stack trace at this point?</p>\n\n<pre><code>main() -> check_winner() -> end() -> main() -> check_winner() -> end() -> main() -> check_winner() -> end() -> main() -> check_winner() -> end() ...\n</code></pre>\n\n<p>If you make a mistake and enter invalid input in the <code>end()</code> method, you could even have <code>end() -> end()</code> repeats in that stack trace.</p>\n\n<p>Do not use recursion as a substitute for looping!</p>\n\n<hr>\n\n<p>Here is a possible implementation, which doesn't use recursion. Note that there are no global variables, other than the constant <code>WINNING_ROWS</code>. Since <code>board</code> is no longer global, it can be created brand new each time a game is started. </p>\n\n<pre><code>import random\n\nWINNING_ROWS = ((0, 1, 2), (3, 4, 5), (6, 7, 8),\n (0, 3, 6), (1, 4, 7), (2, 5, 8),\n (0, 4, 8), (2, 4, 6))\n\ndef print_board(board):\n row = \" {} | {} | {}\\n\"\n line = \" ---+---+---\\n\" \n print(((row + line) * 2 + row).format(*board))\n\ndef has_won(player, board):\n return any(all(board[idx] == player for idx in row) for row in WINNING_ROWS)\n\ndef is_valid_move(move, board):\n return move in range(9) and board[move] not in ('x', 'o')\n\ndef player_move(board):\n print_board(board)\n while True:\n try:\n move = int(input('Please select as spot: '))\n if is_valid_move(move, board):\n return move\n except ValueError:\n pass\n print('Invalid input.', end=' ')\n\ndef npc_move(board):\n while True:\n move = random.randint(0, 8)\n if is_valid_move(move, board):\n return move\n\ndef play_game():\n\n board = list(range(9))\n player = 'x'\n\n for _ in range(9):\n if player == 'x':\n move = player_move(board)\n else:\n move = npc_move(board)\n\n board[move] = player\n\n if has_won(player, board):\n print_board(board)\n print(f\"{player.upper()} wins!\")\n return\n\n player = 'o' if player == 'x' else 'x'\n\n print(\"Tie game\")\n\ndef main():\n answer = 'y'\n\n while answer == 'y':\n play_game()\n\n answer = ''\n while answer not in ('y', 'n'):\n answer = input('Play again? (Y/N): ').lower()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T04:55:20.007",
"Id": "217307",
"ParentId": "217304",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "217307",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T02:47:10.357",
"Id": "217304",
"Score": "3",
"Tags": [
"python",
"beginner",
"python-3.x",
"tic-tac-toe"
],
"Title": "First Python program: Tic-Tac-Toe (Followup)"
} | 217304 |
<p>Simple class to simpify runtime file loading of ressources. The class reads all files from a given directory including all subdirectories and stores the name together with the path in a simple struct. If a file needs to be used by the program just pass the name to GetPath() and the class returns the location of the file. </p>
<p>Any suggestions/improvements about my implementation of this? Im especially not sure if making this static is the right choice.</p>
<pre><code>using System.IO;
using System.Collections.Generic;
namespace Sample
{
struct File
{
public string Name;
public string Path;
}
static class FileManager
{
private static List<File> Files = new List<File>();
public static void AddFiles(string directory)
{
foreach(string file in Directory.GetFiles(directory))
{
Files.Add(new File() { Name = Path.GetFileName(file), Path = directory });
}
foreach(string subdirectory in Directory.GetDirectories(directory))
{
AddFiles(subdirectory);
}
}
public static string GetPath(string filename)
{
var File = Files.Find(x => x.Name == filename);
return File.Path;
}
public static void ClearFiles()
{
Files.Clear();
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T09:11:07.363",
"Id": "420383",
"Score": "1",
"body": "What is `Find` and how does it handle files with same names? Please add its implementation to the question. Oh, or not... I see it's a `List`'s method haha, I've never used it before ;-] and it returns the first match. Interesting. Is this what you want? Why don't you use `FirstOrDefault` which I find much cleaner because you clearly see what you'll get."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T09:49:00.073",
"Id": "420390",
"Score": "1",
"body": "There should not be ressources with identical name and file ending. So Find() returning the first match is fine for the program. That being said, maybe i should consider checking the List for duplicates when filling it to raise an error when somehow two ressources with identical names do actually exist in different subdirectories."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T11:57:38.880",
"Id": "420530",
"Score": "0",
"body": "What if files are added to a folder after the initial read? Is that something you need to support?"
}
] | [
{
"body": "<p>I don't think I would make this class static, unless it's going to be used extensively throughout the program. If not you can build up a large list of files, that may hang around in memory for no use, unless you remember to call <code>ClearFiles()</code>. Instead you could make a static method that could return an initialized object like:</p>\n\n<pre><code>public static FileManager Create(string directoryPath)\n{\n FileManager fm = new FileManager();\n fm.AddFiles(directoryPath);\n return fm;\n}\n</code></pre>\n\n<p>If you have a need for it, then make this instance as static somewhere in the application.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>public static string GetPath(string filename)\n{\n var File = Files.Find(x => x.Name == filename);\n return File.Path;\n}\n</code></pre>\n</blockquote>\n\n<p>It returns only a first match of possible more matches, which will be in a directory high in the hierarchy, but what if you actually seek a path to a file in a subdirectory?</p>\n\n<p>I think I would return a list/array/IEnumerable instead and let the client filter as needed.</p>\n\n<p>Besides that, file names are case insensitive, so you should do:</p>\n\n<pre><code>Files.Find(x => string.Equals(x.Name, filename, StringComparison.CurrentCultureIgnoreCase));\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>public static void AddFiles(string directory)\n{\n foreach (string file in Directory.GetFiles(directory))\n {\n Files.Add(new File() { Name = Path.GetFileName(file), Path = directory });\n }\n foreach (string subdirectory in Directory.GetDirectories(directory))\n {\n AddFiles(subdirectory);\n }\n}\n</code></pre>\n</blockquote>\n\n<p>Nice recursive method. As an alternative you could consider to use <code>DirectoryInfo</code> instead - it can handle the recursive search for you:</p>\n\n<pre><code> DirectoryInfo directory = new DirectoryInfo(directoryPath);\n Files.AddRange(\n directory\n .GetFiles(\"*.*\", SearchOption.AllDirectories)\n .Select(fi => new File { Name = fi.Name, Path = fi.DirectoryName }));\n</code></pre>\n\n<hr>\n\n<p>There is no way to iterate through all the found File objects because the <code>Files</code> static member is private. I would consider to provide a public IEnumerable of some kind.</p>\n\n<hr>\n\n<p>All in all, my implementation would look something like:</p>\n\n<pre><code> public struct File\n {\n public string Name;\n public string Path;\n\n public override string ToString()\n {\n return $\"{Name} => {Path}\";\n }\n }\n\n public class FileManager : IEnumerable<File>\n {\n private List<File> Files = new List<File>();\n\n public void AddFiles(string directoryPath)\n {\n DirectoryInfo directory = new DirectoryInfo(directoryPath);\n Files.AddRange(\n directory\n .GetFiles(\"*.*\", SearchOption.AllDirectories)\n .Select(fi => new File { Name = fi.Name, Path = fi.DirectoryName }));\n }\n\n public IEnumerable<string> GetPaths(string filename)\n {\n return Files\n .Where(x => string.Equals(x.Name, filename, StringComparison.CurrentCultureIgnoreCase))\n .Select(f => f.Path);\n }\n\n public void Clear()\n {\n Files.Clear();\n }\n\n public IEnumerator<File> GetEnumerator()\n {\n return Files.GetEnumerator();\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n\n public static FileManager Create(string directoryPath)\n {\n FileManager fm = new FileManager();\n fm.AddFiles(directoryPath);\n return fm;\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T11:56:41.797",
"Id": "420529",
"Score": "0",
"body": "Windows 10 supports marking directories/entire file systems as case-insensitive. It's not mentioned, but if this were dotnet core, then running on Linux/Mac would also support that. That said, if you're going to ignore case, I *believe* the proper thing to do for windows files (assuming case insensitivity) is to use `OrdinalIgnoreCase`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T13:20:44.433",
"Id": "420547",
"Score": "0",
"body": "Too late to edit my comment, but that first line was supposed to read: Windows10 supports... case *sensitive*"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T15:58:21.557",
"Id": "217330",
"ParentId": "217311",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "217330",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T08:31:51.117",
"Id": "217311",
"Score": "5",
"Tags": [
"c#"
],
"Title": "Simple File Manager with recursion in C#"
} | 217311 |
<p>I have been practicing competitive coding for a while now and am using codeforces.com. I recently encountered a problem called <a href="https://codeforces.com/problemset/problem/721/A" rel="noreferrer">"One Dimensional Japanese Crossword"</a> on that site.
The problem is as follows:</p>
<p>The judge provides an integer (up to 100) and then a string with that many characters being either 'B' or 'W'. We need to output how many groups of 'B' there are and how many 'B's there are in each group. For example:</p>
<p><strong>Input:</strong></p>
<pre><code>6
BBWBWB
</code></pre>
<p><strong>Output:</strong></p>
<pre><code>3
2 1 1
</code></pre>
<hr>
<p>After lots of tries and lots of fails, I was finally able to get the code accepted by the judge. However, for some reason I feel that my code is really inefficient and there might be an easier and better way to solve this problem.</p>
<pre><code>#include<iostream>
#include<vector>
using namespace std;
int main()
{
int n;
cin >> n;
string s;
cin >> s;
int bGroups = 0;
int wGroups = 0;
char initChar = s[0];
for (int i = 1; i < s.length(); i++)
{
if (initChar == 'B')
{
if (s[i] != initChar)
{
bGroups++;
initChar = 'W';
}
}
else if (initChar == 'W')
{
if (s[i] != initChar)
{
wGroups++;
initChar = 'B';
}
}
}
if (s[n - 1] == 'B')
{
bGroups++;
}
else if (s[n - 1] == 'W')
{
wGroups++;
}
char init = s[0];
vector<int>grpSize(bGroups);
int counter = 0;
int i = 0;
while (counter < bGroups)
{
if (init == 'B')
{
while (init == 'B')
{
grpSize[counter]++;
i++;
init = s[i];
}
counter++;
while (init == 'W')
{
i++;
init = s[i];
}
}
else
{
while (init == 'W')
{
i++;
init = s[i];
}
while (init == 'B')
{
grpSize[counter]++;
i++;
init = s[i];
}
counter++;
}
}
cout << bGroups << endl;
for (int i = 0; i < bGroups; i++)
{
cout << grpSize[i] << " ";
}
}
</code></pre>
<p>So basically, in the first pass over the string, I count how many groups of 'B' and 'W' there are. Then I create an int vector to store the size of each 'B' group. Then on the second pass I fill in the values into the vector and then output the results.</p>
| [] | [
{
"body": "<p>Code with iterators and standard algorithms, and you'll see your coding style improve dramatically:</p>\n\n<ul>\n<li><p>finding the beginning of a group of Bs can be done with <code>std::find</code>: <code>auto b = std::find(first, last, 'B');</code></p></li>\n<li><p>finding the end of a group of Bs can also be done with <code>std::find</code>: <code>auto e = std::find(b, last, 'W');</code></p></li>\n<li><p>computing the distance between the two is the job of <code>std::distance</code>: <code>auto nb_bs = std::distance(b, e)</code>.</p></li>\n</ul>\n\n<p>So combining all that we get:</p>\n\n<pre><code>#include <vector>\n#include <algorithm>\n\ntemplate <typename Iterator>\nauto groups_of_bs(Iterator first, Iterator last) {\n std::vector<int> result;\n while (true) {\n first = std::find(first, last, 'B');\n if (first == last) break;\n auto w = std::find(std::next(first), last, 'W');\n result.push_back(std::distance(first, w));\n if (w == last) break;\n first = std::next(w);\n }\n return result;\n}\n</code></pre>\n\n<p>Now the only thing left is to display the size of the vector, and then its elements:</p>\n\n<pre><code>#include <string>\n#include <iostream>\n\nint main() {\n std::string test{\"BBWBWB\"};\n auto res = groups_of_bs(test.begin(), test.end());\n std::cout << res.size() << '\\n';\n for (auto i : res) std::cout << i << ' ';\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T12:59:53.757",
"Id": "217323",
"ParentId": "217318",
"Score": "11"
}
},
{
"body": "<p>Here are a number of things that may help you improve your program.</p>\n\n<h2>Don't abuse <code>using namespace std</code></h2>\n\n<p>Putting <code>using namespace std</code> at the top of every program is <a href=\"http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">a bad habit</a> that you'd do well to avoid. Know when to use it and when not to (as when writing include headers). In this particular case, it's not too terrible because it's a single short program and not a header. Some people seem to think it should never be used under any circumstance, but my view is that it can be used as long as it is done responsibly and with full knowledge of the consequences. </p>\n\n<h2>Make sure you have all required <code>#include</code>s</h2>\n\n<p>The code uses <code>std::string</code> but doesn't <code>#include <string></code>. It's important to make sure you have all required includes to assure that the code compiles and runs portably.</p>\n\n<h2>Simplify your algorithm</h2>\n\n<p>The puzzle can be solved with a single pass through the data. Here's how this might be done:</p>\n\n<pre><code>#include <iostream>\n#include <iterator>\n#include <vector>\n#include <algorithm>\n#include <string>\n\nstd::vector<unsigned> count(const std::string &s, size_t n) {\n std::vector<unsigned> groups;\n bool withinBs{false};\n if (s.size() >= n) {\n for (size_t i{0}; i < n; ++i) {\n switch(s[i]) {\n case 'B':\n if (withinBs) {\n ++groups.back();\n } else {\n groups.push_back(1);\n }\n withinBs = true;\n break;\n default:\n withinBs = false;\n }\n }\n }\n return groups;\n}\n\nint main() {\n int n;\n std::cin >> n;\n std::string s;\n std::cin >> s;\n\n auto groups{count(s, n)};\n std::cout << groups.size() << '\\n';\n std::copy(groups.begin(), groups.end(), std::ostream_iterator<int>(std::cout, \" \"));\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T13:06:40.540",
"Id": "217324",
"ParentId": "217318",
"Score": "9"
}
},
{
"body": "<p>I will try to tell you what is wrong with your algorithm and why.</p>\n\n<h1>You do loop twice over the input string which is most certainly wrong</h1>\n\n<p>Your first loop does provide <code>bGroups</code> and <code>wGroups</code> as a result. We immediatly notice, that <code>wGroups</code> is not used at all and can be removed completely. <code>bGroups</code> is used only as limit in the second loop where you loop over all characters again and have to find all groups anyway. So why bother with finding them firsthand? If the second loop iterates over all characters (like the first one does) it can do the group search on its own and we can delete the first loop completely.</p>\n\n<p>However your second loop contains nested while loops that do not stop at the last character. It needs to know the number of groups in advance. But it does not respect the length of the string anyway as it accesses <code>s[s.size()]</code> if the last character is a <code>'B'</code>. This is guaranteed to be <code>'\\0'</code> in C++14 (and thus different than <code>'B'</code>) but may work on older compilers just by accident. The bottom line is that your algorithm would be broken for a different container or of you were searching <code>'\\0'</code> characters.</p>\n\n<p>As a learning you should avoid parsing where states are represented by a position in a sequential code. Hold state in variables and have a single flat loop that can safely break.</p>\n\n<p>You also can see your nested loop counting is wrong as there is code duplication. There is an <code>if</code> statement to have the very same code in a different order depending on the start character.</p>\n\n<h1>Try to format your code pretty</h1>\n\n<p><code>#include<iostream></code> should read <code>#include <iostream></code></p>\n\n<h1>Use <code>std::string.size()</code></h1>\n\n<p>This is the standard how to determine the length of a container and iterate over it. It is a pretty bad idea to hold the length in a seperate variable that must match the actual length. Instead of</p>\n\n<pre><code>for (int i = 0; i < bGroups; i++)\n{\n cout << grpSize[i] << \" \";\n}\n</code></pre>\n\n<p>The traditional container loop looks like</p>\n\n<pre><code>for (int i = 0; i < grpSize.size(); i++)\n{\n cout << grpSize[i] << \" \";\n}\n</code></pre>\n\n<p>The modern range based loop - stick to that - looks like</p>\n\n<pre><code>for (const auto & n : grpSize) {\n cout << n << \" \";\n}\n</code></pre>\n\n<h1>Do not construct a vector like an array</h1>\n\n<p>Instead of doing so and filling with the <code>operator[]()</code> you should use <code>std::vector.push_back()</code> to grow in size when you need.</p>\n\n<h1>Separate I/O from algorithm</h1>\n\n<p>Make a testable function without I/O that you call from main. The code should be structured somewhat like</p>\n\n<pre><code>std::vector<int> puzzle(std::string s)\n{\n std::vector<int> grpSize;\n // ...\n return grpSize;\n}\n\nstd::string input() {\n // ...\n return s;\n}\n\nvoid output(std::vector<int> v) {\n // ...\n}\n\nint main() {\n std::string s(input());\n output(puzzle(s));\n}\n</code></pre>\n\n<h1><code>using namespace std;</code></h1>\n\n<p>This line is found in many tutorials and even in IDE templates. You should use this very carefully in a limited scope only. Never use this in header files or before include lines as it may introduce name conflicts. When you fully understand this you may decide to use it in *.cpp files e. g. in an output function. </p>\n\n<hr>\n\n<p>finally your algorithm should look somewhat like</p>\n\n<pre><code>std::vector<int> puzzle(std::string s)\n{\n std::vector<int> grpSize;\n\n // as we are interested in 'B' groups only\n // we start in state 'W' to catch the first 'B'\n char state{'W'};\n\n for (const auto & c : s) {\n if (c == 'B') {\n if (state != 'B') {\n grpSize.push_back(0);\n }\n ++grpSize.back();\n }\n state = c;\n }\n return grpSize;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T21:17:05.623",
"Id": "420470",
"Score": "0",
"body": "Good review! One thing about `std::string.size()` is that while what you wrote is definitely generally good advice, the peculiar way this problem is set up is to have a number followed by a string of that length. There is no guidance as to what to do if they fail to match -- my version of the code just silently drops any excess characters and returns no matches if the string is too short."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T22:58:27.047",
"Id": "420485",
"Score": "0",
"body": "@Edward: I had the wrong example on size(), fixed that, thanks. About the coding challenges - the input is used for many programming languages, some may need a size before read. So I do not give too much attention on aasserting input consistency."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T06:16:18.767",
"Id": "420509",
"Score": "0",
"body": "@stephan: Thanks a lot for your input. I won't lie. I am new to coding and though I understood some of what you said, quite a bit of it went over my head. But I am working on improving my knowledge of C++ and I will keep learning and reading this till I understand it completely. But quite a bit of it made perfect sense. Thanks again!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T21:04:55.760",
"Id": "217350",
"ParentId": "217318",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "217323",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T11:47:02.527",
"Id": "217318",
"Score": "7",
"Tags": [
"c++",
"programming-challenge"
],
"Title": "One-dimensional Japanese puzzle"
} | 217318 |
<p>I am working on <a href="https://leetcode.com/problems/valid-perfect-square/" rel="nofollow noreferrer">Valid Perfect Square - LeetCode</a>
and wrote a standard leftmost bisect search to solve the problem:</p>
<pre><code>class Solution:
def isPerfectSquare(self, num: int) -> bool:
#base case 1
if num == 1: return True
lo = 1
hi = num
#recur case
while lo < hi:
mid = (lo + hi) // 2
if num > mid ** 2:
lo = mid + 1
else:
hi = mid
return True if lo ** 2 == num else False
</code></pre>
<p>However, the score is annoying: </p>
<blockquote>
<p>Runtime: 48 ms, faster than 24.22% of Python3 online submissions for Valid Perfect Square.
Memory Usage: 13.2 MB, less than 5.17% of Python3 online submissions for Valid Perfect Square.</p>
</blockquote>
<p>I am not able to improve a standard template a little bit.</p>
<p>Could you please provide any advice? </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T16:37:19.897",
"Id": "420444",
"Score": "0",
"body": "It doesn't justify an answer imo, but python has builtin bisect which would be faster."
}
] | [
{
"body": "<p>Some small points:</p>\n\n<h1>ternary expression</h1>\n\n<p>No need for <code>return True if lo ** 2 == num else False</code>. you can use just <code>return lo ** 2 == num</code></p>\n\n<h1>early return</h1>\n\n<p>If <code>mid**2 == num</code>, you can return early:</p>\n\n<pre><code>sq = mid ** 2\nif num == sq:\n return True\nif num > sq:\n lo = mid + 1\nelse:\n hi = mid -1\n</code></pre>\n\n<p>returns early in this case. This reduced the time for me to 36ms.</p>\n\n<h1>unpacking</h1>\n\n<p>If you want, you can use a ternary expression and tuple unpacking to redefine <code>hi</code> and <code>lo</code></p>\n\n<pre><code>lo, hi = (mid + 1, hi) if num > sq else (lo, mid - 1)\n</code></pre>\n\n<p>but this is a matter of taste, and doesn't seem to save any time or memory.</p>\n\n<h1>memory</h1>\n\n<p>I don't see a lot of ways in which to reduce this method's memory usage. If you look at the distribution of all <a href=\"https://leetcode.com/submissions/detail/221922019/\" rel=\"nofollow noreferrer\">submissions</a>, almost all use this bisect method, so memoty reduction will be based on the wims of the VM.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T13:48:06.737",
"Id": "217326",
"ParentId": "217322",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "217326",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T12:55:54.620",
"Id": "217322",
"Score": "2",
"Tags": [
"python",
"performance"
],
"Title": "Leftmost bisect search to find valid perfect square"
} | 217322 |
<p>I have the following working code, but it is too slow because I have to run the same code for several files inside a folder. Please help me avoid the nested for loop or make it more efficient.</p>
<pre><code>columnNames = {33:"boy", 24: "girl"}
events = [{1:"bo", 2: "irl"}, {1:"oy", 207: "gir"}, {1:"bboy", 2: "girly"}]
def create_game_data():
columns = {}
for column in columnNames.keys():
columnValues = []
for event in events:
columnValues.append(columnNames[column]) if column in columnNames.keys() else columnValues.append("NA")
columns[column] = columnValues
return columns
</code></pre>
<p>Take note of the following.</p>
<ol>
<li>columnNames is a dictionary of with 15 keys and pairs.</li>
<li>events is a list of dictionaries with 2000 items.</li>
<li>Every dictionary in the events list has 13 keys and pairs</li>
</ol>
<h2>My algorithm works in the following steps.</h2>
<ol start="4">
<li><p>Loop through every list item in the events list (list of dictionaries) and append every value associated with the key from the outer for loop to the list called columnValues.</p>
</li>
<li><p>Replace the current key (from the outer for loop) with columnVales.
The desired output should be</p>
<p>{33: ['boy', 'boy', 'boy'], 24: ['girl', 'girl', 'girl']}</p>
</li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T13:41:55.803",
"Id": "420417",
"Score": "2",
"body": "In most cases with Python, the way to better performance does not lie with micro-optimization of a single function, but rather with large-scale algorithmic changes. Please provide as much context as possible, and an explanation of the results you need."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T14:35:07.857",
"Id": "420425",
"Score": "0",
"body": "I have updated the code to make it more reproducible"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T16:31:22.273",
"Id": "420442",
"Score": "0",
"body": "It would appear that you just multiply each value in columnNames, with the length of one item in events and create a dictionary. However, I am reusing the code in a situation where such logic will not solve the same problem."
}
] | [
{
"body": "<p>I'm not sure if you really desire that output. But I'll do some refactoring to show what your code does.</p>\n\n<p>In your code</p>\n\n<pre><code>def create_game_data():\n columns = {}\n for column in columnNames.keys():\n columnValues = []\n for event in events:\n columnValues.append(columnNames[column]) if column in columnNames.keys() else columnValues.append(\"NA\")\n columns[column] = columnValues\n return columns\n</code></pre>\n\n<p>there is an if condition always true. <code>if column in columnNames.keys()</code> is always true for your loop <code>for column in columnNames.keys().</code> So we skip that test</p>\n\n<pre><code>def create_game_data():\n columns = {}\n for column in columnNames.keys():\n columnValues = []\n for event in events:\n columnValues.append(columnNames[column])\n columns[column] = columnValues\n return columns\n</code></pre>\n\n<p>Next we find that you loop over the events without using them. So we could safely write </p>\n\n<pre><code>def create_game_data():\n columns = {}\n for column in columnNames.keys():\n columnValues = []\n for _ in events:\n columnValues.append(columnNames[column])\n columns[column] = columnValues\n return columns\n</code></pre>\n\n<p>This is equivalent to </p>\n\n<pre><code>def create_game_data():\n columns = {}\n for column in columnNames.keys():\n columns[column] = [columnNames[column]] * len(events)\n return columns\n</code></pre>\n\n<p>Now we chose to iterate over the dict in a key-value manner</p>\n\n<pre><code>def create_game_data():\n columns = {}\n for column, name in columnNames.items():\n columns[column] = [name] * len(events)\n return columns\n</code></pre>\n\n<p>Which is easily written as comprehension</p>\n\n<pre><code>def create_game_data():\n return {k:[v] * len(events) for k, v in columnNames.items()}\n</code></pre>\n\n<p>Is that really what you want?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-09-30T12:56:10.423",
"Id": "490399",
"Score": "0",
"body": "I really appreciate the way you did a code optimization, thanks to both!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T17:11:20.600",
"Id": "217332",
"ParentId": "217325",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "217332",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T13:31:27.207",
"Id": "217325",
"Score": "1",
"Tags": [
"python",
"performance",
"python-3.x"
],
"Title": "Remove nested for loops in python"
} | 217325 |
<p>I am calculating parameters for a time series and the data size is very big. How can I make my function faster? The following function, <code>param</code>, calculates parameters for a time series model.</p>
<p>Input:</p>
<pre><code>import pandas as pd
import statsmodels.api as sm
data = [['01-01-2018', 150,661,396,286,786],['01-02-2018',231,341,57,768,941], ['01-03-2018',486,526,442,628,621],
['01-04-2018',279,336,140,705,184],['01-05-2018',304,137,800,94,369],['01-06-2018',919,340,372,494,117],
['01-07-2018',947,920,848,716,719],['01-08-2018',423,20,313,368,909],['01-09-2018',422,678,656,604,674],
['01-10-2018',422,678,656,604,674],['01-11-2018',337,501,743,606,991],['01-12-2018',408,536,669,903,463]]
df = pd.DataFrame(data, columns = ['date', 'A','B','C','D','E'])
df.index = df.date
def param(data_param):
w = []
x = []
y = []
z = []
p = d = q = range(0, 2) # Define the p, d and q parameters to take any value between 0 and 2
pdq = list(itertools.product(p, d, q)) # Generate all different combinations of p, q and q triplets
seasonal_pdq = [(x[0], x[1], x[2], 12) for x in list(itertools.product(p, d, q))] # Generate all different combinations of seasonal p, q and q triplets
for i in data_param:
for param in pdq:
for param_seasonal in seasonal_pdq:
try:
results = sm.tsa.statespace.SARIMAX(data_param[i],
order=param,
seasonal_order=param_seasonal,
enforce_stationarity=False,
enforce_invertibility=False).fit()
#print(i,param, param_seasonal,results.aic)
w.append(i)
x.append(param)
y.append(param_seasonal)
z.append(results.aic)
mod_score_param = pd.DataFrame({
'id': w,
'param': x,
'param_seasonal': y,
'results_aic': z,
})
except:
continue
mod_score_param = mod_score_param.sort_values(by='results_aic')
mod_score_param = mod_score_param.dropna()
mod_score_param = mod_score_param[mod_score_param['results_aic']>3.0]
mod_score_param = mod_score_param.sort_values(['id','results_aic'])
mod_score_param = mod_score_param.drop_duplicates(['id'],keep='first')
return(mod_score_param)
Output= param(df)
</code></pre>
<p>Output:</p>
<pre><code>+-----+----+-----------+----------------+-------------+
| | id | param | param_seasonal | results_aic |
+-----+----+-----------+----------------+-------------+
| 199 | A | (1, 0, 1) | (1, 0, 0, 12) | 4.565 |
| 197 | B | (1, 0, 0) | (1, 0, 0, 12) | 21.752 |
| 30 | C | (0, 1, 1) | (1, 0, 0, 12) | 87.847 |
| 22 | D | (1, 1, 1) | (0, 1, 0, 12) | 91.183 |
| 50 | E | (0, 1, 1) | (0, 1, 0, 12) | 92.87 |
+-----+----+-----------+----------------+-------------+
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T14:52:03.163",
"Id": "420429",
"Score": "0",
"body": "If you add a sample of data, will we be able to run the code and see it working?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T14:57:12.850",
"Id": "420430",
"Score": "0",
"body": "Code is working perfectly fine, but it is very slow. Check, its time series data"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T15:08:06.773",
"Id": "420431",
"Score": "2",
"body": "What is `sm` and what output is produced by that call? Also please add the example input not (only) as a pretty but useless table, but such that it is easy for reviewers to run your code without having to type out your data."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T15:21:03.177",
"Id": "420434",
"Score": "0",
"body": "ok, did necessary changes"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T16:07:31.247",
"Id": "420439",
"Score": "0",
"body": "Just curious: 1. do you actually need `d` and `q`? I would expect you can do `itertools.product(p, p, p)` 2. Do you need to call it twice? I suppose you can iterate over `pdq` to build `seasonal`..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T17:33:41.990",
"Id": "420447",
"Score": "0",
"body": "1. Yes I need d & q also, al three are different parameters. So p, d, q can take anything upto 5. Here i am passing 0,1,2 only. 2. I can. Order & seasonal_order I am passing. So here i am creating 8 order & 8 seasonal_order, because of that each column/ model running for 64 time (A-64,B-64,C-64,D-64E-64)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T01:20:45.580",
"Id": "420491",
"Score": "2",
"body": "If I copy/paste your code, I receive the following message `Traceback (most recent call last):\n File \"20190413a.py\", line 6, in <module>\n ['01-08-2018',423,20,313,368,909],['01-09-2018',422,678,656,604,674],['01-10-2018',422,678,656,604,674]['01-11-2018',337,501,743,606,991]['01-12-2018',408,536,669,903,463]]\nTypeError: list indices must be integers or slices, not tuple\n`. Regardless, I fixed the code but your program doesn't output anything like you post. Please confirm working code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T07:02:12.430",
"Id": "420739",
"Score": "0",
"body": "@C.Harley Please check, now code is working"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T08:40:14.673",
"Id": "420749",
"Score": "0",
"body": "`param()` is called nowhere. how and with what arguments should it be called?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T08:53:52.573",
"Id": "420754",
"Score": "0",
"body": "Output = param(df)"
}
] | [
{
"body": "<p>Without really understanding what you're attempting to do (and sorry, not enough time to dig into the subject matter), I've rewritten you code a little and profiled it.<br>\nThe biggest bottleneck I see have to do with the panda/numpy definitions, there is a lot of code querying what your data structure is to determine how to handle it. Perhaps review all your cells in the data frame and ensure they're defined correctly? </p>\n\n<p><img src=\"https://i.imgur.com/nSiOrqul.png\" alt=\"Profiling Output\"></p>\n\n<p>Full image (but I'm pretty sure it's not helpful): <a href=\"https://i.imgur.com/nSiOrqu.png\" rel=\"nofollow noreferrer\">https://i.imgur.com/nSiOrqu.png</a></p>\n\n<p>A lot of those hints come from the exceptions which are raised - something you could have found easily if you didn't disable them with <code>continue</code>. More on that later.</p>\n\n<p><img src=\"https://i.imgur.com/uF5ae12.png\" alt=\"Exceptions\"></p>\n\n<p>Onto the code. Firstly was the imports, make sure you have them defined - when I loaded up your code I had a missing import, and that could have been either your paste (missing) or settings on your computer.</p>\n\n<pre><code>import pandas as pd\nimport statsmodels.api as sm\nimport itertools\n</code></pre>\n\n<p>Next is you're missing the entry point for your python code, always have this as it performs several things. First, it lets people reading your code understand where it begins and ends, secondly if you use tools like an auto-documentor, they load your code to perform reflection on all the objects.<br>\nCurrently your code would just execute immediately on loading (that's loading, not executing), and that's not good - think of it like your car taking off in gear as soon as you turn the engine on.</p>\n\n<pre><code>if __name__ == \"__main__\":\n</code></pre>\n\n<p>Is your standard entry point for python code. Next, we have data initialisations at the top of the code - again, they should be after the entry point, or better yet, external (like an .ini file) and imported at runtime. The code comes out to:</p>\n\n<pre><code>if __name__ == \"__main__\":\n data = [['01-01-2018', 150, 661, 396, 286, 786], ['01-02-2018', 231, 341, 57, 768, 941],\n ['01-03-2018', 486, 526, 442, 628, 621],\n ['01-04-2018', 279, 336, 140, 705, 184], ['01-05-2018', 304, 137, 800, 94, 369],\n ['01-06-2018', 919, 340, 372, 494, 117],\n ['01-07-2018', 947, 920, 848, 716, 719], ['01-08-2018', 423, 20, 313, 368, 909],\n ['01-09-2018', 422, 678, 656, 604, 674],\n ['01-10-2018', 422, 678, 656, 604, 674], ['01-11-2018', 337, 501, 743, 606, 991],\n ['01-12-2018', 408, 536, 669, 903, 463]]\n df = pd.DataFrame(data, columns=['date', 'A', 'B', 'C', 'D', 'E'])\n result = param(df)\n print(result)\n</code></pre>\n\n<p>When looking at the function <code>def param(data_param):</code>, the first thing that my IDE highlighted was <code>mod_score_param</code> was used inside a loop on a conditional path - but never initialised outside the loop.<br>\nWhen you write code, you need to be aware of what scope your variables have. Usually variables used inside loops are discarded at the end of the loop. This changes the start of <code>def param(data_param):</code> slightly to:</p>\n\n<pre><code> seasonal_pdq = [(x[0], x[1], x[2], 12) for x in list(\n itertools.product(p, d, q))] # Generate all different combinations of seasonal p, q and q triplets\n\n mod_score_param = pd.DataFrame({\n 'id': w,\n 'param': x,\n 'param_seasonal': y,\n 'results_aic': z,\n })\n\n for i in data_param:\n</code></pre>\n\n<p>The next modification I did was to extract the call to the stats package into it's own function, this is because we try to adhere to the Single Responsibility Principle (from S.O.L.I.D) where each function should only perform a single action - it makes it much easier to track down bugs, and we usually only change a single line of code when fixing problems (great when our single change doesn't work - we don't need to debug 10 <strong>new</strong> lines of code to find out what went wrong on top of the original bug).<br>\nMuch easier in the long-run (and the code looks very clean). Here is the function:</p>\n\n<pre><code>def model_params(data_param, i, param, param_seasonal):\n results = sm.tsa.statespace.SARIMAX(data_param[i],\n order=param,\n seasonal_order=param_seasonal,\n enforce_stationarity=False,\n enforce_invertibility=False).fit()\n return results.aic\n</code></pre>\n\n<p>So the caller becomes:</p>\n\n<pre><code> try:\n results = model_params(data_param, i, param, param_seasonal)\n w.append(i)\n x.append(param)\n y.append(param_seasonal)\n z.append(results)\n</code></pre>\n\n<p>The exception was modified slightly too:</p>\n\n<pre><code> except Exception as e:\n print(\"Exception reached: \", e)\n continue\n</code></pre>\n\n<p>So we can see immediately what is broken and needs fixing. It's important with any coding - you should <em>never</em> let your exceptions be silenced, because it will lead to bigger problems in the future.<br>\nIf they are known, catch them with the appropriate exception handler, such as <code>ZeroDivisionError</code> or <code>TypeError</code>, and handle them at the time of the exception.<br>\nIf they don't match any existing error type, create a custom error handler and handle that particular error before continuing on.</p>\n\n<p>That wraps up my code review and attempt to help you find the slow down in your code. Please apply these changes and see if the modifications to your data frame definitions (such as defining the frequency of the date strings - that's one of the warnings I saw) make the intended improvements.<br>\nGood Luck!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-22T13:21:48.273",
"Id": "421625",
"Score": "0",
"body": "Thank you @C. Harley. I changed the code & it seems little speed increased. If I want to use multiprocessing how will I use? For same. Any guidance?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-23T15:15:09.550",
"Id": "421860",
"Score": "0",
"body": "I'd start with threading to work out the engineering challenges of having multiple processes writing back into the dataframe in an out-of-order method and a thread-safe work queue. Multiprocessing is a little heavier as each spawned mp object is a full copy of Python, and you need to work on heavier data sharing techniques (doable, but faster to thread then mp). Firstly, I'd spawn the threads in daemon mode (pointing at the `model_params` function monitoring a queue), then each loop place a copy of the data onto the queue. Results to a second queue, then reintegrate and compare results match."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T05:23:33.913",
"Id": "217601",
"ParentId": "217327",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T14:18:00.180",
"Id": "217327",
"Score": "2",
"Tags": [
"python",
"performance",
"pandas"
],
"Title": "Faster way to 3 nested for loop python"
} | 217327 |
<p>I work in marketing and I am currently trying to <code>aggregate data for 50 facebook pages</code> on the same Business Page.</p>
<p>I have a <code>loop</code> that tries a <code>series of requests</code> to grab all data. I am not sure I am <code>handling exceptions</code> in the best way possible, so I was wondering if somebody had any idea on how to improve the situation.</p>
<p>Main problem is that, for a reason or another, the calls for page n°40 out of my 50 pages break the API Limit 8th fold. Not sure what's causing the issue, but I imagine it has to do with this part of my code. </p>
<p>I can post the whole function if necessary.</p>
<pre><code>counter = 0
while True:
try:
if ('next' in s['paging']):
next_s = s['paging']['next']
s = requests.get(next_s).json()
s_total.extend(s['data'])
counter += 1
print("Getting Page. Current progress: {}".format(counter))
elif ('after' in s['paging']['cursors']):
next_s = s['paging']['cursors']['after']
new_page_url = next_request+next_s
s = requests.get(new_page_url).json()
s_total.extend(s['data'])
print("Getting After. Current progress: {}".format(counter))
elif ('32' in str(s['error']['code'])):
print('Faced error {} in: {} '.format(str(s['error']['code']), username))
print('Sleeping for 1 hour')
sleep(3605)
next_s = s['paging']['next']
s = requests.get(next_s).json()
s_total.extend(s['data'])
counter += 1
print('Continuing...')
continue
elif ('4' in str(s['error']['code'])):
print('Faced error {} in: {} '.format(str(s['error']['code']), username))
print('Sleeping for 1 hour')
sleep(3605)
next_s = s['paging']['next']
s = requests.get(next_s).json()
s_total.extend(s['data'])
counter += 1
print('Continuing...')
continue
else:
print(s['error'])
break
except KeyError:
print('Finished page : {} '.format(username))
break
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T14:42:35.047",
"Id": "217328",
"Score": "1",
"Tags": [
"python",
"error-handling",
"api",
"pandas",
"facebook"
],
"Title": "Requests / Facebook API - Dealing with Errors"
} | 217328 |
<p>The Hashset uses open addressing, linear probing and Robin Hood hashing for handling collisions. It comes with <code>insert</code> and <code>remove</code> operations, iteration (back and forward using a single iterator), <code>min</code> and <code>max</code> keys (this is to interface with a treeset that I've made, but not very useful) and set operations like <code>union</code>, <code>intersection</code>, <code>difference</code> and <code>symmetric_difference</code>.</p>
<p><strong>Concerns</strong></p>
<ul>
<li>This is the first time I've used Robin Hood hashing. It seems way too simple so I'm not sure if it is implemented correctly!</li>
<li>Is it better to have an array of entries (buckets) or an array of pointers to entries (initialized with NULL)?</li>
<li>Are there any improvements that can be done in this hashtable?</li>
</ul>
<p>This data structure is generated using macros. They follow the same idea as two of my previous questions (<a href="https://codereview.stackexchange.com/questions/213553/simple-generic-macro-generated-containers">this one</a> and <a href="https://codereview.stackexchange.com/questions/216737/generic-macro-generated-linked-list-in-c">this one</a>).</p>
<p><strong>How to</strong></p>
<p>You can use <code>HASHSET_GENERATE</code> to generate a hashset of any type you want. It has 4 parameters:</p>
<ul>
<li><strong>PFX</strong> - Functions prefix, or namespace;</li>
<li><strong>SNAME</strong> - Structure name (<code>typedef SNAME##_s SNAME;</code>);</li>
<li><strong>FMOD</strong> - Functions modifier (<code>static</code> or empty, edit: not sure if works with <code>inline</code>);</li>
<li><strong>V</strong> - Your data type to be worked with.</li>
</ul>
<p>Or you can generate each part individually using <code>HASHSET_GENERATE_STRUCT</code>, <code>HASHSET_GENERATE_HEADER</code> and <code>HASHSET_GENERATE_SOURCE</code>.</p>
<p><strong>hashset.h</strong></p>
<pre><code>#ifndef CMC_HASHSET_H
#define CMC_HASHSET_H
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#ifndef CMC_HASH_TABLE_SETUP
#define CMC_HASH_TABLE_SETUP
typedef enum EntryState_e
{
ES_DELETED = -1,
ES_EMPTY = 0,
ES_FILLED = 1
} EntryState;
static const size_t cmc_hashtable_primes[] = {53, 97, 193, 389, 769, 1543, 3079,
6151, 12289, 24593, 49157, 98317,
196613, 393241, 786433, 1572869,
3145739, 6291469, 12582917,
25165843, 50331653, 100663319,
201326611, 402653189, 805306457,
1610612741};
#endif /* CMC_HASH_TABLE_SETUP */
#define HASHSET_GENERATE(PFX, SNAME, FMOD, V) \
HASHSET_GENERATE_STRUCT(PFX, SNAME, FMOD, V) \
HASHSET_GENERATE_HEADER(PFX, SNAME, FMOD, V) \
HASHSET_GENERATE_SOURCE(PFX, SNAME, FMOD, V)
/* PRIVATE *******************************************************************/
#define HASHSET_GENERATE_HEADER_PRIVATE(PFX, SNAME, FMOD, K, V) \
HASHSET_GENERATE_HEADER(PFX, SNAME, FMOD, V)
#define HASHSET_GENERATE_SOURCE_PRIVATE(PFX, SNAME, FMOD, K, V) \
HASHSET_GENERATE_STRUCT(PFX, SNAME, FMOD, V) \
HASHSET_GENERATE_SOURCE(PFX, SNAME, FMOD, V)
/* PUBLIC ********************************************************************/
#define HASHSET_GENERATE_HEADER_PUBLIC(PFX, SNAME, FMOD, K, V) \
HASHSET_GENERATE_STRUCT(PFX, SNAME, FMOD, V) \
HASHSET_GENERATE_HEADER(PFX, SNAME, FMOD, V)
#define HASHSET_GENERATE_SOURCE_PUBLIC(PFX, SNAME, FMOD, K, V) \
HASHSET_GENERATE_SOURCE(PFX, SNAME, FMOD, V)
/* STRUCT ********************************************************************/
#define HASHSET_GENERATE_STRUCT(PFX, SNAME, FMOD, V) \
\
struct SNAME##_s \
{ \
struct SNAME##_entry_s *buffer; \
size_t capacity; \
size_t count; \
double load; \
int (*cmp)(V, V); \
size_t (*hash)(V); \
}; \
\
struct SNAME##_entry_s \
{ \
V value; \
size_t dist; \
enum EntryState_e state; \
}; \
\
struct SNAME##_iter_s \
{ \
struct SNAME##_s *target; \
size_t cursor; \
size_t index; \
size_t first; \
size_t last; \
bool start; \
bool end; \
}; \
\
/* HEADER ********************************************************************/
#define HASHSET_GENERATE_HEADER(PFX, SNAME, FMOD, V) \
\
typedef struct SNAME##_s SNAME; \
typedef struct SNAME##_entry_s SNAME##_entry; \
typedef struct SNAME##_iter_s SNAME##_iter; \
\
FMOD SNAME *PFX##_new(size_t size, double load, int (*compare)(V, V), size_t (*hash)(V)); \
FMOD void PFX##_clear(SNAME *_set_); \
FMOD void PFX##_free(SNAME *_set_); \
FMOD bool PFX##_insert(SNAME *_set_, V element); \
FMOD bool PFX##_remove(SNAME *_set_, V element); \
FMOD bool PFX##_insert_if(SNAME *_set_, V element, bool condition); \
FMOD bool PFX##_remove_if(SNAME *_set_, V element, bool condition); \
FMOD V PFX##_max(SNAME *_set_); \
FMOD V PFX##_min(SNAME *_set_); \
FMOD bool PFX##_empty(SNAME *_set_); \
FMOD size_t PFX##_count(SNAME *_set_); \
\
FMOD SNAME *PFX##_union(SNAME *_set1_, SNAME *_set2_); \
FMOD SNAME *PFX##_intersection(SNAME *_set1_, SNAME *_set2_); \
FMOD SNAME *PFX##_difference(SNAME *_set1_, SNAME *_set2_); \
FMOD SNAME *PFX##_symmetric_difference(SNAME *_set1_, SNAME *_set2_); \
\
FMOD void PFX##_iter_new(SNAME##_iter *iter, SNAME *target); \
FMOD bool PFX##_iter_start(SNAME##_iter *iter); \
FMOD bool PFX##_iter_end(SNAME##_iter *iter); \
FMOD void PFX##_iter_tostart(SNAME##_iter *iter); \
FMOD void PFX##_iter_toend(SNAME##_iter *iter); \
FMOD bool PFX##_iter_next(SNAME##_iter *iter, V *value, size_t *index); \
FMOD bool PFX##_iter_prev(SNAME##_iter *iter, V *value, size_t *index); \
\
/* SOURCE ********************************************************************/
#define HASHSET_GENERATE_SOURCE(PFX, SNAME, FMOD, V) \
\
FMOD bool PFX##_grow(SNAME *_set_); \
FMOD SNAME##_entry *PFX##_get_entry(SNAME *_set_, V element); \
FMOD size_t PFX##_calculate_size(size_t required); \
\
FMOD SNAME *PFX##_new(size_t size, double load, int (*compare)(V, V), size_t (*hash)(V)) \
{ \
if (size == 0 || load <= 0 || load >= 1) \
return NULL; \
\
size_t real_size = PFX##_calculate_size(size); \
\
SNAME *_set_ = malloc(sizeof(SNAME)); \
\
if (!_set_) \
return NULL; \
\
_set_->buffer = malloc(sizeof(SNAME##_entry) * real_size); \
\
if (!_set_->buffer) \
{ \
free(_set_); \
return NULL; \
} \
\
memset(_set_->buffer, 0, sizeof(SNAME##_entry) * real_size); \
\
_set_->count = 0; \
_set_->capacity = real_size; \
_set_->load = load; \
_set_->cmp = compare; \
_set_->hash = hash; \
\
return _set_; \
} \
\
FMOD void PFX##_clear(SNAME *_set_) \
{ \
memset(_set_->buffer, 0, sizeof(SNAME##_entry) * _set_->capacity); \
\
_set_->count = 0; \
} \
\
FMOD void PFX##_free(SNAME *_set_) \
{ \
free(_set_->buffer); \
free(_set_); \
} \
\
FMOD bool PFX##_insert(SNAME *_set_, V element) \
{ \
if ((double)_set_->capacity * _set_->load <= (double)_set_->count) \
{ \
if (!PFX##_grow(_set_)) \
return false; \
} \
\
size_t hash = _set_->hash(element); \
size_t original_pos = hash % _set_->capacity; \
size_t pos = original_pos; \
\
SNAME##_entry *target = &(_set_->buffer[pos]); \
\
if (PFX##_get_entry(_set_, element) != NULL) \
return false; \
\
if (target->state == ES_EMPTY || target->state == ES_DELETED) \
{ \
target->value = element; \
target->dist = pos - original_pos; \
target->state = ES_FILLED; \
} \
else \
{ \
while (true) \
{ \
pos++; \
target = &(_set_->buffer[pos % _set_->capacity]); \
\
if (target->state == ES_EMPTY || target->state == ES_DELETED) \
{ \
target->value = element; \
target->dist = pos - original_pos; \
target->state = ES_FILLED; \
\
break; \
} \
else if (target->dist < pos - original_pos) \
{ \
V tmp = target->value; \
size_t tmp_dist = target->dist; \
\
target->value = element; \
target->dist = pos - original_pos; \
\
element = tmp; \
original_pos = pos - tmp_dist; \
} \
} \
} \
\
_set_->count++; \
\
return true; \
} \
\
FMOD bool PFX##_remove(SNAME *_set_, V element) \
{ \
SNAME##_entry *result = PFX##_get_entry(_set_, element); \
\
if (result == NULL) \
return false; \
\
result->value = 0; \
result->dist = 0; \
result->state = ES_DELETED; \
\
_set_->count--; \
\
return true; \
} \
\
FMOD bool PFX##_insert_if(SNAME *_set_, V element, bool condition) \
{ \
if (condition) \
return PFX##_insert(_set_, element); \
\
return false; \
} \
\
FMOD bool PFX##_remove_if(SNAME *_set_, V element, bool condition) \
{ \
if (condition) \
return PFX##_remove(_set_, element); \
\
return false; \
} \
\
FMOD V PFX##_max(SNAME *_set_) \
{ \
if (PFX##_empty(_set_)) \
return 0; \
\
V result, max; \
size_t index; \
SNAME##_iter iter; \
\
for (PFX##_iter_new(&iter, _set_); !PFX##_iter_end(&iter);) \
{ \
PFX##_iter_next(&iter, &result, &index); \
\
if (index == 0) \
max = result; \
else if (_set_->cmp(result, max) > 0) \
max = result; \
} \
\
return max; \
} \
\
FMOD V PFX##_min(SNAME *_set_) \
{ \
if (PFX##_empty(_set_)) \
return 0; \
\
V result, min; \
size_t index; \
SNAME##_iter iter; \
\
for (PFX##_iter_new(&iter, _set_); !PFX##_iter_end(&iter);) \
{ \
PFX##_iter_next(&iter, &result, &index); \
\
if (index == 0) \
min = result; \
else if (_set_->cmp(result, min) < 0) \
min = result; \
} \
\
return min; \
} \
\
FMOD bool PFX##_empty(SNAME *_set_) \
{ \
return _set_->count == 0; \
} \
\
FMOD size_t PFX##_count(SNAME *_set_) \
{ \
return _set_->count; \
} \
\
FMOD SNAME *PFX##_union(SNAME *_set1_, SNAME *_set2_) \
{ \
V value; \
size_t index; \
SNAME##_iter iter1, iter2; \
\
SNAME *_set_r_ = PFX##_new(_set1_->capacity, _set1_->load, _set1_->cmp, _set1_->hash); \
\
if (!_set_r_) \
return false; \
\
PFX##_iter_new(&iter1, _set1_); \
PFX##_iter_new(&iter2, _set2_); \
\
for (PFX##_iter_tostart(&iter1); !PFX##_iter_end(&iter1);) \
{ \
PFX##_iter_next(&iter1, &value, &index); \
PFX##_insert(_set_r_, value); \
} \
\
for (PFX##_iter_tostart(&iter2); !PFX##_iter_end(&iter2);) \
{ \
PFX##_iter_next(&iter2, &value, &index); \
PFX##_insert(_set_r_, value); \
} \
\
return _set_r_; \
} \
\
FMOD SNAME *PFX##_intersection(SNAME *_set1_, SNAME *_set2_) \
{ \
V value; \
size_t index; \
SNAME##_iter iter; \
\
SNAME *_set_r_ = PFX##_new(_set1_->capacity, _set1_->load, _set1_->cmp, _set1_->hash); \
\
if (!_set_r_) \
return false; \
\
SNAME *_set_A_ = _set1_->count < _set2_->count ? _set1_ : _set2_; \
SNAME *_set_B_ = _set_A_ == _set1_ ? _set2_ : _set1_; \
\
PFX##_iter_new(&iter, _set_A_); \
\
for (PFX##_iter_tostart(&iter); !PFX##_iter_end(&iter);) \
{ \
PFX##_iter_next(&iter, &value, &index); \
\
if (PFX##_get_entry(_set_B_, value) != NULL) \
PFX##_insert(_set_r_, value); \
} \
\
return _set_r_; \
} \
\
FMOD SNAME *PFX##_difference(SNAME *_set1_, SNAME *_set2_) \
{ \
V value; \
size_t index; \
SNAME##_iter iter; \
\
SNAME *_set_r_ = PFX##_new(_set1_->capacity, _set1_->load, _set1_->cmp, _set1_->hash); \
\
if (!_set_r_) \
return false; \
\
PFX##_iter_new(&iter, _set1_); \
\
for (PFX##_iter_tostart(&iter); !PFX##_iter_end(&iter);) \
{ \
PFX##_iter_next(&iter, &value, &index); \
\
if (PFX##_get_entry(_set2_, value) == NULL) \
PFX##_insert(_set_r_, value); \
} \
\
return _set_r_; \
} \
\
FMOD SNAME *PFX##_symmetric_difference(SNAME *_set1_, SNAME *_set2_) \
{ \
V value; \
size_t index; \
SNAME##_iter iter1, iter2; \
\
SNAME *_set_r_ = PFX##_new(_set1_->capacity, _set1_->load, _set1_->cmp, _set1_->hash); \
\
if (!_set_r_) \
return false; \
\
PFX##_iter_new(&iter1, _set1_); \
PFX##_iter_new(&iter2, _set2_); \
\
for (PFX##_iter_tostart(&iter1); !PFX##_iter_end(&iter1);) \
{ \
PFX##_iter_next(&iter1, &value, &index); \
\
if (PFX##_get_entry(_set2_, value) == NULL) \
PFX##_insert(_set_r_, value); \
} \
\
for (PFX##_iter_tostart(&iter2); !PFX##_iter_end(&iter2);) \
{ \
PFX##_iter_next(&iter2, &value, &index); \
\
if (PFX##_get_entry(_set1_, value) == NULL) \
PFX##_insert(_set_r_, value); \
} \
\
return _set_r_; \
} \
\
FMOD void PFX##_iter_new(SNAME##_iter *iter, SNAME *target) \
{ \
iter->target = target; \
iter->cursor = 0; \
iter->index = 0; \
iter->start = true; \
iter->end = PFX##_empty(target); \
\
if (!PFX##_empty(target)) \
{ \
for (size_t i = 0; i < target->capacity; i++) \
{ \
if (target->buffer[i].state == ES_FILLED) \
{ \
iter->first = i; \
break; \
} \
} \
\
iter->cursor = iter->first; \
\
for (size_t i = target->capacity; i > 0; i--) \
{ \
if (target->buffer[i - 1].state == ES_FILLED) \
{ \
iter->last = i - 1; \
break; \
} \
} \
} \
} \
\
FMOD bool PFX##_iter_start(SNAME##_iter *iter) \
{ \
return PFX##_empty(iter->target) || iter->start; \
} \
\
FMOD bool PFX##_iter_end(SNAME##_iter *iter) \
{ \
return PFX##_empty(iter->target) || iter->end; \
} \
\
FMOD void PFX##_iter_tostart(SNAME##_iter *iter) \
{ \
iter->cursor = iter->first; \
iter->index = 0; \
iter->start = true; \
iter->end = PFX##_empty(iter->target); \
} \
\
FMOD void PFX##_iter_toend(SNAME##_iter *iter) \
{ \
iter->cursor = iter->last; \
iter->index = iter->target->count - 1; \
iter->start = PFX##_empty(iter->target); \
iter->end = true; \
} \
\
FMOD bool PFX##_iter_next(SNAME##_iter *iter, V *value, size_t *index) \
{ \
if (iter->end) \
return false; \
\
SNAME##_entry *scan = &(iter->target->buffer[iter->cursor]); \
\
*value = scan->value; \
*index = iter->index; \
\
if (iter->cursor == iter->last) \
iter->end = true; \
else \
{ \
iter->index++; \
\
while (1) \
{ \
iter->cursor++; \
scan = &(iter->target->buffer[iter->cursor]); \
\
if (scan->state == ES_FILLED) \
break; \
} \
} \
\
iter->start = PFX##_empty(iter->target); \
\
return true; \
} \
\
FMOD bool PFX##_iter_prev(SNAME##_iter *iter, V *value, size_t *index) \
{ \
if (iter->start) \
return false; \
\
SNAME##_entry *scan = &(iter->target->buffer[iter->cursor]); \
\
*value = scan->value; \
*index = iter->index; \
\
if (iter->cursor == iter->first) \
iter->start = true; \
else \
{ \
iter->index--; \
\
while (1) \
{ \
iter->cursor--; \
scan = &(iter->target->buffer[iter->cursor]); \
\
if (scan->state == ES_FILLED) \
break; \
} \
} \
\
iter->end = PFX##_empty(iter->target); \
\
return true; \
} \
\
FMOD bool PFX##_grow(SNAME *_set_) \
{ \
size_t new_size = PFX##_calculate_size((size_t)((double)_set_->capacity * 1.5)); \
\
SNAME *_new_set_ = PFX##_new(new_size, _set_->load, _set_->cmp, _set_->hash); \
\
if (!_new_set_) \
return false; \
\
V value; \
size_t index; \
SNAME##_iter iter; \
\
for (PFX##_iter_new(&iter, _set_); !PFX##_iter_end(&iter);) \
{ \
PFX##_iter_next(&iter, &value, &index); \
PFX##_insert(_new_set_, value); \
} \
\
if (_set_->count != _new_set_->count) \
{ \
PFX##_free(_new_set_); \
\
return false; \
} \
\
SNAME##_entry *tmp = _set_->buffer; \
_set_->buffer = _new_set_->buffer; \
_new_set_->buffer = tmp; \
\
_set_->capacity = _new_set_->capacity; \
\
PFX##_free(_new_set_); \
\
return true; \
} \
\
FMOD SNAME##_entry *PFX##_get_entry(SNAME *_set_, V element) \
{ \
size_t hash = _set_->hash(element); \
size_t pos = hash % _set_->capacity; \
\
SNAME##_entry *target = &(_set_->buffer[pos % _set_->capacity]); \
\
while (target->state == ES_FILLED || target->state == ES_DELETED) \
{ \
if (_set_->cmp(target->value, element) == 0) \
return target; \
\
pos++; \
target = &(_set_->buffer[pos % _set_->capacity]); \
} \
\
return NULL; \
} \
\
FMOD size_t PFX##_calculate_size(size_t required) \
{ \
const size_t count = sizeof(cmc_hashtable_primes) / sizeof(cmc_hashtable_primes[0]); \
\
if (cmc_hashtable_primes[count - 1] < required) \
return required; \
\
size_t i = 0; \
while (cmc_hashtable_primes[i] < required) \
i++; \
\
return cmc_hashtable_primes[i]; \
}
#endif /* CMC_HASHSET_H */
</code></pre>
<p><strong>EXAMPLE</strong></p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include "hashset.h"
HASHSET_GENERATE(set, hash_set, /* static */, int)
void print_set(hash_set *s)
{
size_t index;
int result;
hash_set_iter iter;
set_iter_new(&iter, s);
for (set_iter_tostart(&iter); !set_iter_end(&iter);)
{
set_iter_next(&iter, &result, &index);
if (index == 0)
printf("[ %2d, ", result);
else if (index == s->count - 1)
printf("%2d ]\n", result);
else
printf("%2d, ", result);
}
}
int intcmp(int a, int b)
{
return a - b;
}
size_t inthash(int t)
{
size_t a = t;
a += ~(a << 15);
a ^= (a >> 10);
a += (a << 3);
a ^= (a >> 6);
a += ~(a << 11);
a ^= (a >> 16);
return a;
}
int main(int argc, char const *argv[])
{
hash_set *set1 = set_new(50, 0.9, intcmp, inthash);
hash_set *set2 = set_new(50, 0.9, intcmp, inthash);
for (int i = 1; i <= 20; i++)
set_insert(set1, i);
for (int i = 11; i <= 30; i++)
set_insert(set2, i);
hash_set *set3 = set_union(set1, set2);
print_set(set1);
printf("UNION\n");
print_set(set2);
printf("=\n");
print_set(set3);
printf("\n\n");
hash_set *set4 = set_intersection(set1, set2);
print_set(set1);
printf("INTERSECTION\n");
print_set(set2);
printf("=\n");
print_set(set4);
printf("\n\n");
hash_set *set5 = set_difference(set1, set2);
print_set(set1);
printf("DIFFERENCE\n");
print_set(set2);
printf("=\n");
print_set(set5);
printf("\n\n");
hash_set *set6 = set_symmetric_difference(set1, set2);
print_set(set1);
printf("SYMMETRIC DIFFERENCE\n");
print_set(set2);
printf("=\n");
print_set(set6);
set_free(set1);
set_free(set2);
set_free(set3);
set_free(set4);
set_free(set5);
set_free(set6);
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T22:25:53.197",
"Id": "420479",
"Score": "1",
"body": "An array of entries has the advantage of cache coherence, but it's bigger in memory and only supports a fixed size of entry. From Wikipedia, \"If the table is expected to have a high load factor, the records are large, or the data is variable-sized, chained hash tables often perform as well or better.\" So, it depends?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T00:58:41.080",
"Id": "420489",
"Score": "0",
"body": "Is it possible to have an associative array with this? It seems to me that that's not enough parameters."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T01:43:05.343",
"Id": "420492",
"Score": "1",
"body": "@NeilEdelman To make a Hashmap is very very very close to the Hashset. In fact I have it implemented [here](https://github.com/LeoVen/C-Macro-Collections/blob/master/src/hashmap.h)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T19:59:27.500",
"Id": "420594",
"Score": "0",
"body": "I still don't see how this is enough parameters. In your example, how do you link `intcmp` and `inthash` into your header?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T20:51:54.140",
"Id": "420601",
"Score": "0",
"body": "@NeilEdelman Sorry I didn't quite understand your question, but I do hope that I can clarify things here. *Not enough parameters* of what? In the example `intcmp` and `inthash` are associated with the hashtable when you call `set_new()`. Here you can use any comparison function (in case it is a more complex data type like a `struct`) and any hash function you'd like. There is no need to generate the code with a pre-set comparison or hash function. If that was not your question, please feel free to ask again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T22:09:53.220",
"Id": "420719",
"Score": "1",
"body": "Ahh, I see how it's done now. If you coded it in HASHSET_GENERATE instead of the constructor, all the same hashset types would be compatible. And really, how much do you really have two or more equiality relations? I mean, I guess you could, but I would think it's rare."
}
] | [
{
"body": "<blockquote>\n <p>... used <a href=\"https://en.wikipedia.org/wiki/Hash_table#Robin_Hood_hashing\" rel=\"nofollow noreferrer\">Robin Hood hashing</a>. It seems way too simple so I'm not sure if it is implemented correctly!</p>\n</blockquote>\n\n<p>No comment.</p>\n\n<blockquote>\n <p>Is it better to have an array of entries (buckets) or an array of pointers to entries (initialized with NULL)?</p>\n</blockquote>\n\n<p>6.01 or half-dozen of the other. Depends on use case.</p>\n\n<p>I prefer a dynamic array of entries for less (perceived) fragmentation.</p>\n\n<blockquote>\n <p>Are there any improvements that can be done in this hashtable?</p>\n</blockquote>\n\n<p><strong>Lack of comments.</strong></p>\n\n<p>I'd expect <em>something</em> to help indicate usage and limitation of the various generated functions in the <code>.h</code> files. Perhaps even a commented terse example?</p>\n\n<p>Put that <strong>How to</strong> in the .h</p>\n\n<p><strong>Name space impact.</strong></p>\n\n<p><code>hashset.h</code> creates</p>\n\n<pre><code>CMC_HASHSET_...\nCMC_HASH_...\nEntryState...\nES_...\ncmc_hashtable...\nHASHSET_...\n</code></pre>\n\n<p>I'd expect a more uniform name space usage. Example</p>\n\n<pre><code>cmcht.h\ncmcht_...\nCMCHT_...\n</code></pre>\n\n<p><strong>Assumed range</strong></p>\n\n<p><code>size_t cmc_hashtable_primes[] = {53, 97, 193, 389, ... 402653189, 805306457, 1610612741</code> assumes <code>size_t</code> is 32 bit. For wider portability, conditionally handle 16 to 64 bit.</p>\n\n<p>Unclear why table lacked entries near 2,000,000,000 and 4,000,000,000.</p>\n\n<p><strong>Why <code>double</code> math?</strong></p>\n\n<pre><code>(size_t)((double)_set_->capacity * 1.5)\nvs.\n_set_->capacity + _set_->capacity/2\n</code></pre>\n\n<p>If concerned about overflow, a prior test is useful.</p>\n\n<p><strong>Linear search vs binary</strong></p>\n\n<p>With dozens of values to search, instead of a linear search <code>while (cmc_hashtable_primes[i] < required) i++;</code>, perhaps a binary one?</p>\n\n<p><strong>Allocate to sizeof de-referenced pointer</strong></p>\n\n<p>Original code was hard to review for correctnesses.</p>\n\n<pre><code>_set_->buffer = malloc(sizeof(SNAME##_entry) * real_size); \n// vs\n_set_->buffer = malloc(sizeof *_set_->buffer * real_size); \n</code></pre>\n\n<p><strong>Good use of <code>size_t</code>/<code>bool</code></strong></p>\n\n<p><strong>Good use of prime numbers in hashing</strong></p>\n\n<pre><code>size_t hash = _set_->hash(element); \nsize_t original_pos = hash % _set_->capacity; \n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/q/32912894/2410359\">related</a></p>\n\n<p><strong>Main test</strong></p>\n\n<p>I'd re-order <code>includes</code> to insure <code>\"hashset.h\"</code> stands on its own</p>\n\n<pre><code>//#include <stdio.h>\n//#include <stdlib.h>\n#include \"hashset.h\"\n#include <stdio.h>\n#include <stdlib.h>\n</code></pre>\n\n<p>It appears the .h code is designed to handle multiple <code>HASHSET_GENERATE()</code>. If so, good to demo it.</p>\n\n<p>A full range <code>int</code> compare for <code>intcmp(int a, int b)</code> without potential UB is <code>return (a > b) - (a < b)</code></p>\n\n<hr>\n\n<p>Bonus</p>\n\n<p>OP had \"only go to 32 bit integers is because I took them from <a href=\"https://planetmath.org/goodhashtableprimes\" rel=\"nofollow noreferrer\">here</a>.\" so I extended to 64-bit.</p>\n\n<pre><code>0x 3 3\n0x 7 7\n0x D 13\n0x 1D 29\n0x 35 53\n0x 61 97\n0x C1 193\n0x 185 389\n0x 301 769\n0x 607 1543\n0x C07 3079\n0x 1807 6151\n0x 3001 12289\n0x 6011 24593\n0x C005 49157\n0x 1800D 98317\n0x 30005 196613\n0x 60019 393241\n0x C0001 786433\n0x 180005 1572869\n0x 30000B 3145739\n0x 60000D 6291469\n0x C00005 12582917\n0x 1800013 25165843\n0x 3000005 50331653\n0x 6000017 100663319\n0x C000013 201326611\n0x 18000005 402653189\n0x 30000059 805306457\n0x 60000005 1610612741\n0x C0000001 3221225473\n0x 180000017 6442450967\n0x 300000005 12884901893\n0x 600000017 25769803799\n0x C0000002F 51539607599\n0x 1800000007 103079215111\n0x 3000000001 206158430209\n0x 6000000019 412316860441\n0x C000000005 824633720837\n0x 18000000011 1649267441681\n0x 30000000059 3298534883417\n0x 60000000001 6597069766657\n0x C0000000025 13194139533349\n0x 18000000002F 26388279066671\n0x 300000000037 52776558133303\n0x 60000000000D 105553116266509\n0x C00000000037 211106232533047\n0x 1800000000011 422212465066001\n0x 3000000000059 844424930132057\n0x 6000000000011 1688849860263953\n0x C000000000019 3377699720527897\n0x 18000000000053 6755399441055827\n0x 3000000000001F 13510798882111519\n0x 6000000000005F 27021597764223071\n0x C0000000000005 54043195528445957\n0x 180000000000025 108086391056891941\n0x 300000000000023 216172782113783843\n0x 600000000000005 432345564227567621\n0x C00000000000031 864691128455135281\n0x1800000000000011 1729382256910270481\n0x3000000000000005 3458764513820540933\n0x600000000000002F 6917529027641081903\n0xC000000000000011 13835058055282163729\n0xFFFFFFFFFFFFFFC5 18446744073709551557 extra\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T13:34:44.667",
"Id": "420549",
"Score": "0",
"body": "Your implementation of `intcmp` performs two comparisons while only 1.5 of them are actually required."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T13:39:55.657",
"Id": "420551",
"Score": "1",
"body": "@bipll Both `(a > b) - (a < b)` and the \"1.5 compare\" approaches are O(1) complexity. Compilers readily emit efficient code from `(a > b) - (a < b)` so to assess either is a micro-optimization. My goal is first correct functionality over range which `a - b` does not have."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T20:38:02.533",
"Id": "420599",
"Score": "0",
"body": "Hi. First, thanks for the review! About the prime numbers and why they only go to 32 bit integers is because I took them from [here](https://planetmath.org/goodhashtableprimes). I still couldn't find prime numbers that go up to 64 bit values."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T02:55:46.503",
"Id": "420612",
"Score": "0",
"body": "@LeoVen Finding primes (each number is as far as possible from the nearest two powers of two) up to 2^64 looks like a fun programming task.... ;-)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T12:44:53.407",
"Id": "217393",
"ParentId": "217333",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "217393",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T17:13:39.983",
"Id": "217333",
"Score": "3",
"Tags": [
"c",
"generics",
"collections",
"hash-map",
"set"
],
"Title": "Generic Macro Generated Hashset in C"
} | 217333 |
<p>I have a list of article titles, where I wish to count the number of occurrences for each word (and remove some words and characters). The input is in a .csv file where the titles are in column 'Titles'.</p>
<p>Maybe someone could help me do it more elegantly.</p>
<pre><code>import numpy as np
import pandas as pd
#imports Counter, as we will need it later:
from collections import Counter
df = pd.read_csv("Article_titles.csv")
print (df.head(10))
#Selecting the titles into variable
titles = []
titles = df.Title
remove_words_list = ["at","of","a","and","in","for","the","to","with","on","using","an","after","from","by","use","review","upper","new","system"]
remove_characters_list = ".:,-%()[]?'"
huge_title_list = []
#create a list of all article titles:
for i in range(len(titles)):
clean_title = titles[i].lower().translate({ord(i): None for i in remove_characters_list})
huge_title_list.append(clean_title)
total_words_string = " ".join(huge_title_list)
#join all article titles into one huge string
querywords = total_words_string.split()
#split the string into a series of words
resultwords = [word for word in querywords if word not in remove_words_list]
#From stackoverflow
resultwords_as_list = list( Counter(resultwords).items())
#Convert resultwords_list to dataframe, then convert count to numbers and finally sorting.
resultframe = pd.DataFrame(np.array(resultwords_as_list).reshape(-1,2), columns = ("Keyword","Count"))
resultframe.Count = pd.to_numeric(resultframe.Count)
sortedframe = resultframe.sort_values(by='Count',ascending=False).reset_index(drop=True)
print(sortedframe[0:50])
</code></pre>
<p>example of Input:</p>
<pre><code>Titles | other_field | other_field2
"Current status of prognostic factors in patients with metastatic renal cell carcinoma." |"asdf"|12
"Sentinel lymph node biopsy in clinically node-negative Merkel cell carcinoma: the Westmead Hospital experience." |"asdf"|15
</code></pre>
<p>desired output:</p>
<pre><code>Word | Count
carcinoma | 2
cell | 2
biopsy | 1
clinically | 1
....
...
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T17:59:23.223",
"Id": "420448",
"Score": "1",
"body": "Welcome to Code Review! Good job on your first question. I hope you get great answers."
}
] | [
{
"body": "<p>Very good first post! There are a few small things to call out. First, refrain from using pandas and numpy unless it's absolutely necessary. Both are fantastic tools which excel in certain areas, but generally speaking many stock Python scripts can be just as performant, much more portable, and a lot more clear on their own. For example, stock Python is fantastically suited for counting the frequency of hashable items (in fact, you used it with <code>Counter</code>). But if I wanted to do QR decomposition, I would absolutely reach for numpy as it already has an implementation of this and that implementation will likely be much faster than anything I can write. Always be sure to use the right tool for the job. Generally speaking, the more dependencies a piece of code has, the harder it is to compose with other things (harder could be quantifying programmer effort here--as in, the effort to install dependencies/debug version issues/etc.). So for this reason, I'm going to remove numpy and pandas from my answer.</p>\n\n<hr>\n\n<pre class=\"lang-py prettyprint-override\"><code>#imports Counter, as we will need it later:\nfrom collections import Counter\n</code></pre>\n\n<p>This is a useless comment. Of course that's what the following line does. And of course you're importing something because you need it. Don't just comment for the sake of commenting. Comment to explain the \"why\" not the \"what.\"</p>\n\n<hr>\n\n<p>You can do your csv reading with stock python. You should be using <code>with</code> contexts here to handle properly closing files (especially if exceptions are raised). <code>csv.DictReader</code> will be useful here as it is an iterator that yields <code>dict</code>s for each row. This allows us to use a generator comprehension to build the list of titles. If you are unfamiliar with generators, you should [read up on them}(<a href=\"https://stackoverflow.com/q/1756096/568785\">https://stackoverflow.com/q/1756096/568785</a>). The benefit they give you is that they don't build up a big list in memory. They only produce values upon request. In your code you have a lot of list and string manipulation (see the list comprehension of <code>resultwords</code>, the <code>join</code>/<code>split</code> dance of <code>total_words_string</code> and <code>querywords</code>--which is unnecessary--,and <code>huge_title_list</code>). All of these points can be bottlenecks, because they require building up in memory the entire state to that point. Instead, using a generator allows you to lazily defer the work until you need it (in this case, when you use <code>Counter</code>).</p>\n\n<p>A good analogy for this is an assembly line. Imagine you had a factory building computers with 3 stops on the assembly line (we'll call them A, B, and C). At each stop, a worker adds one component to the computer (let's say motherboard, CPU, RAM). If we were to write this out using lists it would look like this:</p>\n\n<pre><code>computers_after_A = [add_motherboard(computer) for computer in bare_computers]\ncomputers_after_B = [add_CPU(computer) for computer in computer_after_A]\ncomputers_after_C = [add_RAM(computer) for computer in computer_after_B]\n</code></pre>\n\n<p>This looks innocent enough, but if you were to run your factory like this you'd have some real problems. Let's say the factory processes 1000 computers per day. The above code would be equivalent to the following:</p>\n\n<ol>\n<li>The worker at A adds motherboards to each incoming computer and then adds the finished computers to a big stack.</li>\n<li>Once worker A is done with all 1000 computers, the stack is pushed to worker B who takes one from each stack, adds the CPU and then makes a new stack of finished computers.</li>\n<li>Once worker B is done with all 1000 computers, the stack of 1000 computers is pushed to worker C, who adds the RAM and then adds the computers to the finally done stack.</li>\n</ol>\n\n<p>The problem with the above is that it is inefficient (worker B has no work until worker A completes all 1000 computers and worker C has no work until <em>both</em> workers A and B finish all 1000 computers) and requires you to have the room to store all 1000 computers at each location A, B, and C.</p>\n\n<p>A much better approach is how factories really work. A constantly moving conveyor belt which moves the computers through one by one. At each location, the worker adds their respective component and then send each computer along individually to the next station. This would be equivalent to the following:</p>\n\n<pre><code>computers_after_A = (add_motherboard(computer) for computer in bare_computers)\ncomputers_after_B = (add_CPU(computer) for computer in computer_after_A)\ncomputers_after_C = (add_RAM(computer) for computer in computer_after_B)\n</code></pre>\n\n<p>With this approach we've replaced lists with generators. Now, computers are immediately available (instead of only available after everything finishes) and we don't need the space to build up 3 piles of 1000 computers.</p>\n\n<p>Hopefully, this motivates why we should use generators. I'll be using them below.</p>\n\n<p>There's no reason to use pandas to sort the counts from <code>Counter</code>. <code>Counter</code> has a <a href=\"https://docs.python.org/3.3/library/collections.html#collections.Counter.most_common\" rel=\"nofollow noreferrer\"><code>most_common()</code></a> method that will do this for you.</p>\n\n<p>You had the right idea with using <code>translate</code> to replace unwanted characters. But you don't need to build the dictionary every time. Instead using <code>string.maketrans</code> and saving this \"translation dictionary\" will avoid doing lots of extra work.</p>\n\n<p><code>remove_words_list</code> should probably be called <code>stop_list</code> as this is the common parlance for words you want to exclude. Also, you should make this a <code>frozenset</code> so that <code>word in stop_list</code> is O(1) instead of an O(n) scan (what you currently do, which is really inefficient).</p>\n\n<p>Typically, we include code that we want to run in a <code>main()</code> function and run it only <code>if __name__ == '__main__'</code>. This allows other code to include this file (and potentially use an utility functions it defines) without having the <code>main()</code> run.</p>\n\n<p>With all that in mind, I'd refactor your code to something like this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import csv\nimport string\n\nSTOP_WORDS = frozenset(('at', 'of', 'a', 'and', 'in')) # ...\nEXCLUDE_CHARS = string.maketrans('', '', '.:,-%()[]?\\'')\n\ndef main():\n with open('Article_titles.csv') as f: # consider accepting the filename as an argument (sys.argv)\n titles = (row['title'] for row in csv.DictReader(f, delimter='|'))\n words = (word.lower().translate(EXCLDUE_CHARS)\n for title in titles for word in title.split())\n interesting_words = (word for word in words if word not in STOP_WORDS)\n frequencies = Counter(interesting_words)\n\n print(frequencies.most_common())\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>Now remember how I mentioned above choosing the right tool for the job? It turns out that what you're trying to do (word extraction) is pretty tricky. Natural language has all sorts of irregularities, odd formatting, and inconsistencies. Luckily, there's a fantastic Python library which has a fairly good (complicated) implementation for handling all this for you: <a href=\"https://www.nltk.org/\" rel=\"nofollow noreferrer\">nltk</a>. This is a very appropriate use of a library, because this task is hard and nltk has put lots of work into building a robust implementation. The home page has an example of what you need:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>>>> from nltk import word_tokenize\n>>> word_tokenize('When this thing hits 88 miles per hour')\n['When', 'this', 'thing', 'hits', '88', 'miles', 'per', 'hour']\n</code></pre>\n\n<p>I'll leave integrating nltk as an exercise for you, but it should only involve changing one line in my above code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T06:31:06.823",
"Id": "420511",
"Score": "0",
"body": "That is a really great answer. Thanks a bunch.\nThis is my first real python project(and my first real coding project since i played around with qbasic and pascal in the 90s)\nI struggled a bit to see the difference in the two 'computer production factory' -code analogy until i noticed the different parentheses. :)\nCan you give ELI5 of the difference between () and [] lists?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-16T07:03:52.570",
"Id": "420879",
"Score": "1",
"body": "`()` is a generator expression and `[]` is a list expression. The former creates a generator and the latter creates the list. If you ignore the code, the analogy of a real assembly line being a generator still holds. A generator doesn't produce all its values at once. You can think of it like a function that can be frozen. When you need the next value from a generator, you unfreeze it, run the code until it produces a value, and then freeze it again. With lists (and list comprehensions), all of the values are available in memory immediately. There is no freezing. There is no one-at-a-time."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T19:56:39.503",
"Id": "217344",
"ParentId": "217334",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "217344",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T17:20:25.287",
"Id": "217334",
"Score": "4",
"Tags": [
"python",
"strings",
"csv",
"pandas"
],
"Title": "Count words in a list of titles, with some cleanup"
} | 217334 |
<p>I have created the code below that compare two spreadsheets . It initially compares the range of value from sheet1 ("Status") to sheet2 ("Interface") . Whenever a range matches with the ranges present in other sheet , it does nothing .When the range does not any matches in the other sheet , then the entire record is copied from sheet2 to sheet1 . I have around 1500 rows of data in both sheets with 15 columns . It takes around 30 minutes .
. I look forward to see If I could get any help.</p>
<pre><code> Option Explicit
Function UpdateNEW() As Long
' This Sub will do the Following Update
' Run through all records in NEW
' if found in Steps ---> Do nothing
' if not found in Steps ----> Add it to Steps
'
Dim WSO As Worksheet
Dim WSN As Worksheet
Dim MaxRowO As Long, MaxRowN As Long, I As Long, J As Long, lAdd As Long
Dim sJob As String, sOps As String, sFirstAddress As String
Dim cCell As Range
Dim bNotFound As Boolean
'---> Disable Events
With Application
.EnableEvents = False
.DisplayAlerts = False
.ScreenUpdating = False
End With
'---> Set Variables
Set WSO = Sheets("Steps")
Set WSN = Sheets("Interface")
MaxRowO = WSO.Range("A" & WSO.Rows.Count).End(xlUp).Row
MaxRowN = WSN.Range("C" & WSN.Rows.Count).End(xlUp).Row
WSN.Range("P6:P" & MaxRowN).ClearContents
'---> Loop thruough all rows in sheet New
For I = 6 To MaxRowN
bNotFound = False
sJob = WSN.Cells(I, "D")
sOps = WSN.Cells(I, "E")
Set cCell = WSO.Range("B2:B" & MaxRowO).Find(what:=sJob, LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False)
If Not cCell Is Nothing Then
bNotFound = True
sFirstAddress = cCell.Address
Do
'---> Check to See if Ops if found for that Job
If WSO.Cells(cCell.Row, "C") = sOps Then
bNotFound = False
Exit Do
End If
Set cCell = WSO.Range("B2:C" & MaxRowO).FindNext(cCell)
Loop While Not cCell Is Nothing And cCell.Address <> sFirstAddress
Else
bNotFound = True
End If
'---> Add Record to OLD if Not Found
If bNotFound Then
WSN.Range("C" & I & ":O" & I).Copy WSO.Range("A" & MaxRowO + 1)
'WSN.Range("P" & I) = "Copied to OLD"
'WSO.Range("N" & MaxRowO + 1) = sJob & " " & sOps & " Copied from New row " & I
MaxRowO = MaxRowO + 1
lAdd = lAdd + 1
End If
Next I
'---> Enable Events
With Application
.EnableEvents = True
.DisplayAlerts = True
.ScreenUpdating = True
End With
UpdateNEW = lAdd
End Function
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T19:06:19.257",
"Id": "420454",
"Score": "1",
"body": "Welcome to [codereview.se]! Your title probably applies to about half the code posted here. Please [edit] it to describe in a few words _what your code does_ not what kind of help you're looking for. The \"halp make it fasterzzz!!!\" part belongs in the text of the question, as you currently have it. :)"
}
] | [
{
"body": "<p>The unique data could be appended, using a Scripting Dictionary and arrays in less than a second. Alternatively, you could use an ADO Query to append records from sheet1, not in sheet2.</p>\n\n<p>The easiest method would be to add all the records to the second worksheet then record a macro that:</p>\n\n<ul>\n<li>Convert the range to a table</li>\n<li>Select a cell in the range then click Ribbon > Table Tools > Remove Duplicates</li>\n</ul>\n\n<p>All that is left to do is refactor the Macro to make the code dynamic.</p>\n\n<p>Watch:\n - <a href=\"https://www.youtube.com//watch?v=h9FTX7TgkpM&index=28&list=PLNIs-AWhQzckr8Dgmgb3akx_gFMnpxTN5\" rel=\"nofollow noreferrer\">Excel VBA Introduction Part 25 - Arrays</a>\n - <a href=\"https://www.youtube.com//watch?v=dND4coLI_B8&index=43&list=PLNIs-AWhQzckr8Dgmgb3akx_gFMnpxTN5\" rel=\"nofollow noreferrer\">Excel VBA Introduction Part 39 - Dictionaries</a>\n - <a href=\"https://www.youtube.com//watch?v=-c2QvyPpkAM&index=36&list=PLNIs-AWhQzckr8Dgmgb3akx_gFMnpxTN5\" rel=\"nofollow noreferrer\">Excel VBA Introduction Part 32 - ADO (ActiveX Data Objects) SQL Statements (INSERT, UPDATE, DELETE)</a></p>\n\n<hr>\n\n<p>Here is how I would rewrite the OP's code using a Scripting Dictionary and arrays.</p>\n\n<pre><code>Function UpdateNEW2() As Long\n Const Delimiter As String = \"|\"\n Dim dic As Object\n Set dic = CreateObject(\"Scripting.Dictionary\")\n Dim newRows As Range\n Dim vSteps, key\n With Sheets(\"Steps\")\n vSteps = .Range(\"A2:O2\", .Cells(.Rows.Count, 2).End(xlUp)).Value\n End With\n\n Dim r As Long, c As Long, n As Long\n For r = 1 To UBound(vSteps)\n key = vSteps(r, 3) & Delimiter & vSteps(r, 4)\n Debug.Print key\n If Not dic.Exists(key) Then dic.Add key, 0\n Next\n\n Dim vInterface, results\n With Sheets(\"Interface\")\n vInterface = .Range(\"A7:O7\", .Cells(.Rows.Count, \"C\").End(xlUp)).Value\n End With\n\n ReDim results(1 To UBound(vInterface), 1 To 15)\n For r = 1 To UBound(vInterface)\n key = vInterface(r, 4) & Delimiter & vInterface(r, 5)\n Debug.Print key\n If Not dic.Exists(key) Then\n n = n + 1\n For c = 3 To 15\n results(n, c - 2) = vInterface(r, c)\n Next\n End If\n Next\n If n > 0 Then\n With Sheets(\"Steps\")\n With .Cells(.Rows.Count, 2).End(xlUp).Offset(1)\n .Resize(n, 15).Value = results\n End With\n End With\n End If\n UpdateNEW2 = n\nEnd Function\n</code></pre>\n\n<p>(<a href=\"https://drive.google.com/open?id=1kVU1NobGBaVO2Jk3vucIcrMcecD-C-QU\" rel=\"nofollow noreferrer\">Sample Data</a>)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T05:43:51.530",
"Id": "420981",
"Score": "0",
"body": "Thanks . I am new to VBA . If possible could you indicate lines where the codes can be modified . It would be of great help ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T06:30:53.807",
"Id": "420987",
"Score": "0",
"body": "@JohnPattrick I added some untested code. Sorry, but I didn't add any comments. Let me know where you get the errors...lol."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T07:53:05.760",
"Id": "421004",
"Score": "0",
"body": "Thanks for your efforts . While I am executing the code , I get Run Time Error 1004 on the code -> .Resize(n, 15).Value = results"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T11:14:43.080",
"Id": "421032",
"Score": "0",
"body": "@JohnPattrick it probably didn't return any results. Can you link me the file?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T12:04:42.063",
"Id": "421042",
"Score": "0",
"body": "I have uploaded a sample worksheet of the original file . When pasted , the highlighted ones should be below the rest of file ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T12:12:55.683",
"Id": "421044",
"Score": "0",
"body": "https://drive.google.com/file/d/1kVU1NobGBaVO2Jk3vucIcrMcecD-C-QU/view?usp=sharing"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-17T13:56:31.983",
"Id": "421053",
"Score": "0",
"body": "@JohnPattrick I updated my answer. I didn't notice that the data starts on row 7 of Interface. Unless you have a compelling reason to do otherwise, it is better to start your data in A1 for consistency. I also didn't bother with: `WSN.Range(\"P6:P\" & MaxRowN).ClearContents`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T08:03:09.930",
"Id": "421161",
"Score": "0",
"body": "Thanks for your time and effort . It worked ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-18T08:27:57.270",
"Id": "421165",
"Score": "0",
"body": "@JohnPattrick Sweet!! How long does it take to run?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-22T18:12:03.873",
"Id": "421675",
"Score": "0",
"body": "It takes now around 1 to 3 min to execute compared to last time when it took more than 15 min to execute."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-22T18:12:52.473",
"Id": "421676",
"Score": "0",
"body": "I have one small doubt . Is there any way ,we can make the function does not work when the sheets are empty . It can indicate that sheet is empty kinda of thing"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-23T04:21:43.690",
"Id": "421741",
"Score": "0",
"body": "1 to 3 min is a ridiculous amount of time for that little amount of data. You should add the \"Disable Events\" and \"Enable Events\" parts of the code to the procedure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T16:24:14.967",
"Id": "423039",
"Score": "0",
"body": "Small Help . Could you explain your code . It works , I just wanted to learn how it executes"
}
],
"meta_data": {
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T01:01:24.007",
"Id": "217420",
"ParentId": "217336",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "217420",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T18:24:39.740",
"Id": "217336",
"Score": "1",
"Tags": [
"vba",
"excel",
"time-limit-exceeded",
"join"
],
"Title": "Merging records from one spreadsheet into another"
} | 217336 |
<h2>GitHub</h2>
<p><a href="https://github.com/Webbarrr/MyDbConnector" rel="nofollow noreferrer">GitHub if it's easier</a></p>
<hr>
<p>I'm in the process of doing a training course in C#. I've just gone over covering Polymorphic OOP / composition over inheritance etc...</p>
<p>The latest exercise I completed in the course was to create two base classes, <code>DBConnector</code> & <code>DBCommand</code> that can be used for any database. The verbatim requirements were as follows -</p>
<blockquote>
<p>To access a database, we need to open a connection to it first and
close it once our job is done. Connecting to a database depends on the
type of the target database and the database management system (DBMS).
For example, connecting to a SQL Server database is different from
connecting to an Oracle database. But both these connections have a
few things in common:<br>
- They have a connection string<br>
- They can be opened<br>
- They can be closed<br>
- They may have a timeout attribute (so if the
connection could not be opened within the timeout, an exception will
be thrown).</p>
<p>Your job is to represent these commonalities in a base
class called <code>DbConnection</code>. This class should have two properties:<br>
- <code>ConnectionString</code> : <code>string</code><br>
- <code>Timeout</code> : <code>TimeSpan</code><br>
<code>DbConnection</code> will not be in a valid state if it doesn’t have a connection string. So you need
to pass a connection string in the constructor of this class. Also,
take into account the scenarios where null or an empty string is sent
as the connection string. Make sure to throw an exception to guarantee
that your class will always be in a valid state. Our DbConnection
should also have two methods for opening and closing a connection. We
don’t know how to open or close a connection in a DbConnection and
this should be left to the classes that derive from DbConnection.
These classes (e.g. SqlConnection or OracleConnection) will provide the
actual implementation. So you need to declare these methods as
abstract. Derive two classes SqlConnection and OracleConnection from
DbConnection and provide a simple implementation of opening and
closing connections using Console.WriteLine(). In the real-world, SQL
Server provides an API for opening or closing a connection to a
database. But for this exercise, we don’t need to worry about it.</p>
</blockquote>
<p>And for the DBCommand -</p>
<blockquote>
<p>Now that we have the concept of a DbConnection, let’s work out how to
represent a DbCommand. Design a class called DbCommand for executing
an instruction against the database. A DbCommand cannot be in a valid
state without having a connection. So in the constructor of this
class, pass a DbConnection. Don’t forget to cater for the null. Each
DbCommand should also have the instruction to be sent to the database.
In case of SQL Server, this instruction is expressed in T-SQL
language. Use a string to represent this instruction. Again, a command
cannot be in a valid state without this instruction. So make sure to
receive it in the constructor and cater for the null reference or an
empty string. Each command should be executable. So we need to create
a method called Execute(). In this method, we need a simple
implementation as follows: Open the connectionRun the instruction
Close the connectionNote that here, inside the DbCommand, we have a
reference to DbConnection. Depending on the type of DbConnection sent
at runtime, opening and closing a connection will be different. For
example, if we initialize this DbCommand with a SqlConnection, we will
open and close a connection to a Sql Server database. This is
polymorphism. Interestingly, DbCommand doesn’t care about how a
connection is opened or closed. It’s not the responsibility of the
DbCommand. All it cares about is to send an instruction to a database.
For running the instruction, simply output it to the Console. In the
real-world, SQL Server (or any other DBMS) provides an API for running
an instruction against the database. We don’t need to worry about it
for this exercise. In the main method, initialize a DbCommand with
some string as the instruction and a SqlConnection. Execute the
command and see the result on the console. Then, swap the SqlConnection
with an OracleConnection and see polymorphism in action.</p>
</blockquote>
<p>This is the first exercise in the course I've struggled with & would appreciate a more learned eye to have a look at it. I don't feel that I've done particularly well in this exercise. As I feel the need to have called <code>base.Open();</code> inside both derived classes is a bit of a bad design, but I'm not 100% sure how else I could go about it.</p>
<p>These are my base classes -</p>
<pre><code>public class DBConnection
{
private readonly string _connectionString;
public TimeSpan Timeout { get; set; }
public DBConnection(string connectionString)
{
if (string.IsNullOrWhiteSpace(connectionString))
throw new InvalidOperationException("Connection String is required.");
this._connectionString = connectionString;
}
public virtual void Open()
{
var startTime = DateTime.Now;
// connection code would go here...
var endTime = DateTime.Now;
CheckTimeout(startTime, endTime);
}
public virtual void Close()
{
}
private void CheckTimeout(DateTime startTime, DateTime endTime)
{
if (endTime - startTime >= this.Timeout)
throw new TimeoutException("The connection timed out...");
}
}
public class DBCommand
{
private readonly DBConnection _dBConnection;
private readonly string _sql;
public DBCommand(DBConnection dBConnection, string sql)
{
_dBConnection = dBConnection ?? throw new InvalidOperationException("DBConnection required.");
this._sql = sql ?? throw new InvalidOperationException("sql required.");
}
public void Execute()
{
_dBConnection.Open();
Console.WriteLine($"Executing: {_sql}");
_dBConnection.Close();
}
}
</code></pre>
<p>And here are my derived classes -</p>
<pre><code>public class SqlConnection : DBConnection
{
public SqlConnection(string connectionString)
: base(connectionString)
{
base.Timeout = TimeSpan.FromSeconds(60);
}
public override void Close()
{
Console.WriteLine("Closing connection to SQL Server...");
}
public override void Open()
{
base.Open();
Console.WriteLine("Opening connection to SQL Server...");
Console.WriteLine($"Timeout is set to {base.Timeout}");
}
}
public class OracleConnection : DBConnection
{
public OracleConnection(string connectionString)
: base(connectionString)
{
}
public override void Close()
{
Console.WriteLine("Closing connection to Oracle...");
}
public override void Open()
{
base.Open();
Console.WriteLine("Opening connection to Oracle...");
Console.WriteLine($"Oracle has no timeout");
}
}
</code></pre>
<p>And finally my test code -</p>
<pre><code> static void UsingDbCommand()
{
var sqlConnection = new SqlConnection("My.SQL.ConnectionString");
var sqlCommand = new DBCommand(sqlConnection, "DROP TABLE tblUsers -- On SQL Server");
sqlCommand.Execute();
var oracleConnection = new OracleConnection("My.Oracle.ConnectionString");
var oracleCommand = new DBCommand(oracleConnection, "DROP TABLE tblUsers -- On Oracle");
oracleCommand.Execute();
try
{
var fakeSQLConnection = new SqlConnection("fasdf");
var fakeSQLCommand = new DBCommand(fakeSQLConnection, null);
fakeSQLCommand.Execute();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
</code></pre>
| [] | [
{
"body": "<p>I can see how this could get a bit confusing. The way the requirements are phrased make it bit more difficult. Maybe it was written in an attempt to not give an obvious solution. But, it did take more effort to follow at least for me.</p>\n\n<p>I'm making the assumption that you're only supposed to use inheritance for this step, and interfaces are not necessary.</p>\n\n<p>Let's start with <strong>DbConnection</strong>, which need:</p>\n\n<ul>\n<li>ConnectionString property</li>\n<li>Timeout property</li>\n<li>Open abstract method</li>\n<li>Close abstract method</li>\n</ul>\n\n<pre><code>public class DBConnection\n{\n[...]\n</code></pre>\n\n<p>The class needs to be abstract if we're going to use abstract methods.</p>\n\n<pre><code>[...]\n private readonly string _connectionString;\n[...]\n</code></pre>\n\n<p>There doesn't seem to be any way to access connection string from classes inheriting <code>DBConnection</code> see <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/accessibility-levels\" rel=\"nofollow noreferrer\">Access Levels</a> </p>\n\n<pre><code>[...]\n public TimeSpan Timeout { get; set; }\n[...]\n</code></pre>\n\n<p>No problem with the above, but I would recommend at least making it virtual so that the classes inheriting from this abstraction can control the accessibility if requirements change. </p>\n\n<pre><code>[...]\n public virtual void Open()\n {\n var startTime = DateTime.Now;\n\n // connection code would go here...\n\n var endTime = DateTime.Now;\n\n CheckTimeout(startTime, endTime);\n }\n\n public virtual void Close()\n {\n }\n\n private void CheckTimeout(DateTime startTime, DateTime endTime)\n {\n if (endTime - startTime >= this.Timeout)\n throw new TimeoutException(\"The connection timed out...\");\n }\n}\n[...]\n</code></pre>\n\n<ol>\n<li>On the above, I notice that neither <strong>Open</strong> or <strong>Close</strong> methods are abstract</li>\n<li>Neither method should have any code in the DBConnection. SqlServer and OracleDatabase will likely use different APIs so the code in the abstraction will likely always get overwritten and not used. Even if you do try and force its use, you would be calling open twice in a way. And, the part that interacts with the API will end up having nothing to do with the start time/endtime variables.</li>\n<li>About this <code>CheckTimeout</code> it's not really in the requirement. So I invoke <a href=\"https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it\" rel=\"nofollow noreferrer\">YAGNI</a>. Problem is that, it will be very difficult to deal with that at the Base Class since we are given a hint that we <strong>may</strong> need to use it during implementation.</li>\n</ol>\n\n<p>Once you take care of the DBConnection class you shouldn't need to call <code>base.Open()</code> in the implementations. And, you shouldn't need to set timeout in the constructor, nor write timeout line in the implementation open method.</p>\n\n<p>The only other issue that I see with the code is in the <strong>DBCommand</strong> constructor:</p>\n\n<pre><code>[...]\n this._sql = sql ?? throw new InvalidOperationException(\"sql required.\");\n[...]\n</code></pre>\n\n<p>The requirement states:</p>\n\n<blockquote>\n <p>[...] So make sure to receive it in the constructor and cater for the null reference or an empty string.</p>\n</blockquote>\n\n<p>This may deal with a null value. But, it will not catch string.Empty or whitespace strings. You should probably use string.IsNullOrWhiteSpace() like you did in SqlConnection. </p>\n\n<p>Actually I think this may be the first time I've seen the <code>??</code> operator to throw. That's not saying, it's good or bad, I just never thought of it. Though, it does make the line longer, which depending on formatting rules can be a problem. Than again, it could be formatted slightly different to help. Maybe someone else has a better opinion on that.</p>\n\n<p>Hope that helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-20T07:34:32.687",
"Id": "421362",
"Score": "0",
"body": "Welcome to Code Review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-20T10:59:59.633",
"Id": "421376",
"Score": "0",
"body": "Welcome to Code Review! Thanks for your answer. Your first paragraph pretty much sums up my experience with this exercise. I was very confused about how I was supposed to go about doing some of the things based on the requirements.\n\nEdit: forgot I had to do shift line break.\n\nI've taken your points on board & made a few extra amendments of my own, for example on your point around `this._sql = sql ?? throw new InvalidOperationException(\"sql required.\");` I did some test cases to check & they seemed to work, although I think I should stick to a consistent approach. I've updated GitHub"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-20T15:23:57.950",
"Id": "421389",
"Score": "0",
"body": "Thanks for the welcome. Yeah, I'm not sure \"cater\" is a good word to use when asking to handle nulls.\nI did do a quick check. Since the new code is not here I added [issue1](https://github.com/Webbarrr/MyDbConnector/issues/1) and [issue2](https://github.com/Webbarrr/MyDbConnector/issues/2) on your github project."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-20T16:07:47.033",
"Id": "421392",
"Score": "1",
"body": "I would also like to suggest getting familiar with unit testing frameworks. I like [xunit](https://xunit.net/) or [nunit](https://nunit.org/). It's a bit difficult at first, but it becomes increasingly simple the more you use it. Visually checking outputs relies on your concentration and effort every time you run the test as well as the assumptions and effort you made when you wrote it. While a unit test relies on the assumptions and writing effort. So you reduce steps, efforts and the chance of visually missing something."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-20T04:48:44.313",
"Id": "217766",
"ParentId": "217337",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "217766",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T18:33:00.903",
"Id": "217337",
"Score": "2",
"Tags": [
"c#",
"object-oriented",
"programming-challenge",
"polymorphism"
],
"Title": "Polymorphic DBConnector class exercise"
} | 217337 |
<p>I have a list of orders and for some order fields I need get the data that is common among the orders. If the data is not in common, I should indicate null. I collect the common data in a <code>CommonData</code> object. In addition, I also store the order codes and order ids associated with the <code>CommonData</code>. </p>
<p>I have two approaches that I'm considering:</p>
<p>Approach 1:</p>
<pre><code>public CommonData getCommonData(List<Order> orders) {
Order firstOrder = order.get(0);
LocalDate commonStartDate = firstOrder.getStartDate();
LocalDate commonEndDate = firstOrder.getEndDate();
List<Item> commonItems = firstOrder.getItems();
CommonData commonData= new CommonData();
for (Order order : orders) {
commonData.addCode(order.getCode());
commonData.addId(order.getId());
if (commonStartDate != null &&
!commonStartDate.equals(order.getStartDate())) {
commonStartDate = null;
}
if (commonEndDate != null &&
!commonEndDate.equals(order.getEndDate())) {
commonEndDate = null;
}
if (!equalLists(commonItems, order.getItems())) {
commonData.setDifferentItems(true);
commonItems = null;
}
}
commonData.setCommonStartDate(commonStartDate);
commonData.setCommonEndDate(commonEndDate);
commonData.setCommonItems(commonItems);
return commonData;
}
</code></pre>
<p>Approach 2:</p>
<pre><code>private boolean haveSameDate(List<Order> orders,
Function<Order,LocalDate> getDate) {
return orders.stream()
.map(getDate)
.distinct()
.limit(2)
.count() == 1;
}
public CommonData getCommonData(List<Order> orders) {
CommonData commonData = new CommonData();
if (haveSameDate(orders,
Order::getStartDate)) {
commonData.setCommonStartDate(orders.get(0).getStartDate());
}
if (haveSameDate(orders,
Order::getEndDate)) {
commonData.setCommonEndDate(orders.get(0).getEndDate());
}
commonData.setCodes(
orders.stream()
.map(order -> order.getCode())
.collect(Collectors.toList()));
commonData.setIds(
orders.stream()
.map(order -> order.getId())
.collect(Collectors.toList()));
List<Item> firstOrderItems = orders.get(0).getItems();
if (orders.stream()
.map(Order::getItems)
.allMatch(x -> equalLists(x,firstOrderItems))) {
commonData.setCommonItems(firstOrderItems);
} else {
commonData.setDifferentItems(true);
}
return commonData;
}
</code></pre>
<p>Even though approach 2 involves multiple iterations over orders, the order and item lists will always be small. </p>
<p>In approach 2, having operations on one piece of data is in one spot within the method but it is scattered in approach 1. Approach 1 also has negative logic. Approach 2 is more complex in finding common order items. </p>
<p>Can approach 1 be redesigned to have the benefits of approach 2 (such as remove negative logic and keep operations on a piece of data in a single spot)? Or should approach 2 be used and perhaps be improved to better handle finding common order items?</p>
| [] | [
{
"body": "<p>Basically, this boils down to the question of how to find out whether a given number of items is always the same. The mathematical tool for this is a set and checking its cardinality.</p>\n\n<p>Putting this into code, you can use a Set implementation in Java:</p>\n\n<pre><code>Set<LocalDate> allStartDates = new HashSet<>();\n\nfor (...) {\n ...\n allStartDates.add(order.getStartDate());\n ...\n}\n\nif (allStartDates.size() == 1)\n commonData.setCommonStartDate(allStartDates.iterator().next());\n</code></pre>\n\n<p>BUT: in a real-world-application, I'd move this logic to the CommonData class.</p>\n\n<p>Basically, redesign the CommonData in a way, that you can simply add an order and then boil the loop down to:</p>\n\n<pre><code>CommonData commonData = new CommonData();\norders.stream().forEach(commonData::add);\n</code></pre>\n\n<p>and inside the common data <code>add</code> method, add the codes and ids, maintain two sets of dates, and do the if-logic in the appropriate getters.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T04:35:28.710",
"Id": "217366",
"ParentId": "217338",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "217366",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T18:45:38.663",
"Id": "217338",
"Score": "1",
"Tags": [
"java",
"lambda"
],
"Title": "Extract Common Data From List of Objects"
} | 217338 |
<p>The point of this project is to be able to create an excel configuration file where the user can input search strings and search files, both potentially having wildcards, and search those files for those strings. </p>
<p>The problem is that while I have working code, it just simply takes the program too long to run. Based on what I've seen from people reading in files on google through C++, my program is incredibly slow even though I use getline and have seen much faster results from people using getline on stackexchange, for example. What am I doing wrong?</p>
<p>Here is my code:</p>
<pre class="lang-c prettyprint-override"><code>int main()
{
// Here you enter in the file path to an excel file that has two columns: Search Strings,
// and Search Files.
// Search Strings are strings that can contain wildcards or escaped special characters
// but not commas because that screws up the file reading too much. (Wildcard can be used
// in place of comma and will return line text w/comma there.
cout << "Please enter in the excel config. path " << "\n";
cout << "Note this must be valid for the program to work correctly. LIMIT 100 CHARS " << "\n";
string excelPath;
char input[100];
cin.getline(input,sizeof(input));
excelPath = input;
// User can input the file path to an excel csv where output results
// will be written.
cout << "Please enter in the file path where you would like an output .csv file written: LIMIT 100 CHARS " << "\n";
string outputExcel;
char oInput[100];
cin.getline(oInput, sizeof(oInput));
outputExcel = oInput;
// Get Search Strings + Search Files with this side function.
bool openedFile;
openedFile = useExcelConfig(excelPath);
size_t found;
// Main body of function is here.
auto start = high_resolution_clock::now();
if (openedFile == true)
{
// Defining required variables here.
smatch matches;
vector<regex> expressions;
for (int i = 0; i < regex_patterns.size(); i++) { expressions.emplace_back(regex_patterns.at(i)); }
for (size_t j = 0; j < searchFiles.size();j++)
{
// Defining some more variables here (that are mainly used in writing the csv data, not in the main file reading code)
vector<int> lineNumber;
vector<string> lineText;
string fileName;
string folderName;
fileName = searchFiles.at(j);
int fileNameSlashIdx = fileName.rfind("\\");
folderName = fileName.substr(0, fileNameSlashIdx);
fileName = fileName.substr(fileNameSlashIdx + 1, string::npos);
vector<string>lineStrings;
string entireFile;
// File ifstream definition/opening
ifstream file;
file.open(searchFiles.at(j), ios::in | ios::ate);
// Fill and close file
if (file)
{
ifstream::streampos filesize = file.tellg();
entireFile.reserve(filesize);
file.seekg(0);
while (!file.eof())
{
entireFile += file.get();
}
}
file.close();
/*
auto regexstart = high_resolution_clock::now();
for (size_t r = 0; r < expressions.size(); r++)
{
ptrdiff_t number_of_matches = distance(sregex_iterator(entireFile.begin(), entireFile.end(), expressions.at(r)), sregex_iterator());
}
auto regexstop = high_resolution_clock::now();
auto duration = duration_cast<seconds>(regexstop - regexstart);
cout << "Time spent on testing this new method: " << duration.count() << "\n"; */
int linecount = 0;
auto regexstart = high_resolution_clock::now();
stringstream stream(entireFile);
while (1)
{
string line;
getline(stream, line);
if (!stream.good())
break;
for (size_t r = 0; r < expressions.size(); r++)
{
//cout << "Current line: " << line << "\n";
//cout << "Current REGEXP: " << regex_patterns.at(r) << "\n";
//ptrdiff_t number_of_matches = distance(sregex_iterator(line.begin(),line.end(), expressions.at(r)),sregex_iterator());
//cout << number_of_matches << "\n";
found = regex_search(line, matches, expressions.at(r));
if (found == 1)
{
lineNumber.push_back(linecount);
lineText.push_back(line);
}
}
}
// Running this section of code on a file of size 1875 KB takes 17 seconds. Using tests to figure out where the time is spent:
// All the time is spent not on the regex search of the line but on the actual file reading.
// How can I speed this up?
auto regexstop = high_resolution_clock::now();
auto duration = duration_cast<seconds>(regexstop - regexstart);
entireFile.clear();
ofstream myOutPut(outputExcel);
myOutPut << "Line Text, Line Number, File Name, Folder Path," << "\n";
{
tuple<vector<string>, vector<int>, string, string>result = make_tuple(lineText, lineNumber, fileName, folderName);
writeResultsToFile(result, outputExcel);
}
lineText.clear();
lineNumber.clear();
cout << "Finished file " << (j + 1) << " of " << searchFiles.size() << "." << "\n";
}
}
auto stop = high_resolution_clock::now();
auto duration = duration_cast<seconds>(stop - start);
cout << "Elapsed Time: " << duration.count() << " seconds." << "\n";
cout << "Full time during file search is: " << duration.count() << "\n";
return 0;
}
</code></pre>
<p>I included some code here that isn't where most of the time is taken so that you can get a good idea of what is going on. The main file reading loop takes forever and I've tried multiple different ways that I've seen people on google try. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T19:21:09.927",
"Id": "420455",
"Score": "1",
"body": "Welcome to Code Review! Please add example input so that reviewers are able to test run your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T19:27:40.650",
"Id": "420457",
"Score": "1",
"body": "Also, please add the definitions for `regex_patterns`, `searchFiles`, and at least the declarations for `useExcelConfig` and `writeResultsToFile`."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T19:00:05.677",
"Id": "217339",
"Score": "2",
"Tags": [
"c++",
"performance",
"beginner"
],
"Title": "Trying to speed up doing a regex_search function with X strings on Y files"
} | 217339 |
<p><strong>The task:</strong></p>
<blockquote>
<p>Implement integer exponentiation. That is, implement the pow(x, y)
function, where x and y are integers and returns x^y.</p>
<p>Do this faster than the naive method of repeated multiplication.</p>
<p>For example, pow(2, 10) should return 1024.</p>
</blockquote>
<p><strong>Solution 1</strong></p>
<pre><code>function pow(x, y) {
if (!y) { return 1; }
let tmp = res = x;
for (let i = 1; i < y; i++) {
for (let j = 1; j < x; j++) {
tmp += res;
}
res = tmp;
}
return res;
}
console.log(pow(2, 10));
</code></pre>
<p>I can't claim the following solution to be originally by me. I read it up and implemented it the way I understood. I'm also not sure whether <code>Solution 1</code> nor <code>Solution 2</code> is "faster than (...) repeated multiplication".</p>
<p><strong>Solution 2</strong> Also known as "<a href="https://en.wikipedia.org/wiki/Exponentiation_by_squaring" rel="nofollow noreferrer">Exponentiation by squaring</a>"</p>
<pre><code>function pow2(x, y) {
if (!y) { return 1; }
if (y % 2) {
return x * pow2(x, y - 1);
}
const p = pow2(x, y/2);
return p * p;
}
console.log(pow2(2,10));
</code></pre>
| [] | [
{
"body": "<p>The solution 1 is still a repeated multiplication. The only difference is that the multiplication is implemented as a repeated addition:</p>\n\n<pre><code> for (let j = 1; j < x; j++) {\n tmp += res;\n }\n</code></pre>\n\n<p>is a very long way to say</p>\n\n<pre><code> tmp = res * x;\n</code></pre>\n\n<p>and obviously it doesn't make the code any faster.</p>\n\n<hr>\n\n<p>The second solution is <em>almost</em> correct. It fails for negative <code>y</code> (negative is still integer!), and the handling of <code>pow2(0, 0)</code> is questionable.</p>\n\n<p>Besides that, try to avoid the recursion; recursive calls are expensive, and the goal of the exercise is to achieve the maximal speed. There does exist a true honest-to-goodness iterative algorithm.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T01:42:27.300",
"Id": "217364",
"ParentId": "217340",
"Score": "4"
}
},
{
"body": "<p>To see for yourself how efficient these algorithms are, you can simply add some counters in the code paths:</p>\n\n<pre><code>let assignments = 0;\nlet additions = 0;\nlet multiplications = 0;\n\nconst add = (a, b) => {\n additions++;\n return a + b;\n};\n</code></pre>\n\n<p>And in your algorithms, just increment these counters in the correct places.</p>\n\n<p>To check whether the exponentiation is efficient, <code>pow(3, 10)</code> should use less than 10 multiplications.</p>\n\n<pre><code>pow(3, 10)\n= pow(3, 5) ** 2\n= (pow(3, 4) * 3) ** 2\n= ((pow(3, 2) ** 2) * 3) ** 2\n= (((pow(3, 1) ** 2) ** 2) * 3) ** 2\n= (((3 ** 2) ** 2) * 3) ** 2\n</code></pre>\n\n<p>That's 4 multiplications instead of 10.</p>\n\n<p>In this example I intentionally use 3 as the base in order to avoid confusion between the 2 from the base and the 2 from the squaring.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T04:36:07.550",
"Id": "217367",
"ParentId": "217340",
"Score": "2"
}
},
{
"body": "<p>This function is very dependent on the inputs, with the function <code>pow</code> being the fastest when the power (second arg) is small, but quickly becomes slower as the power grows.</p>\n\n<h2>Bit-wise and wiser recursing</h2>\n\n<p>You can get a tiny bit more out of the <code>pow2</code> function if you use bit-wise math.\nThe big gain is in avoiding the need to step into the last recursion that returns 1. See (Example B)</p>\n\n<p>The following functions where bench marked. See bottom table.</p>\n\n<h2>Your functions as tested</h2>\n\n<pre><code>function pow(x, y) {\n if (!y) { return 1 }\n let tmp = res = x;\n for (let i = 1; i < y; i++) {\n for (let j = 1; j < x; j++) { tmp += res }\n res = tmp;\n }\n return res;\n}\n\nfunction pow2(x, y) {\n if (!y) { return 1; }\n if (y % 2) {\n return x * pow2(x, y - 1);\n }\n const p = pow2(x, y/2);\n return p * p;\n}\n</code></pre>\n\n<h2>Example B</h2>\n\n<pre><code>// Using bitwise math and skipping last recursion when possible\nfunction pow2B(x, y) {\n if (y < 2) { return y ? x : 1 }\n if (y & 1) { return x * pow2B(x, y & 0x7FFFFFFE)}\n const p = pow2B(x, y >> 1);\n return p * p;\n}\n</code></pre>\n\n<p>The benchmark results </p>\n\n<pre><code>Time per 10,000 calls in µs (1/1,000,000th sec)\n===============================================\nargs >> (21, 11) | (2, 8) | (1, 2)\n===================|==========|================ \npow 0.075µs | 0.014µs | 0.007µs\npow2 0.014µs | 0.010µs | 0.005µs (*1)\npow2B (*2) 0.011µs | 0.007µs | 0.005µs\n</code></pre>\n\n<p><strong>NOTES</strong></p>\n\n<ul>\n<li><p>(*1) The times are right on the precision limits but the <code>pow2</code> function for (1,2) consistently completed 200 Million operations per second compared to the next best at 194 million. The difference to small to show up in the times.</p></li>\n<li><p>(*2) The bit-wise math contributed ~25% of the improvement while the 1 less recursion contributed ~75% of the improvement.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T06:12:31.140",
"Id": "420508",
"Score": "0",
"body": "How did you get the benchmark results ? Ảena the results dependent on the browser engine?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T06:24:36.707",
"Id": "420510",
"Score": "0",
"body": "@thadeuszlay Yes dependent on browser and platform, but you will find that relative performance generally keeps the same order across browsers and platforms. Browser Chrome, Win 10, Laptop i7 1.6Ghz. I use my own benchmarker"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T09:08:54.047",
"Id": "420514",
"Score": "0",
"body": "BTW: isn’t the use of bitwise operator a good practice? (It makes it less declarative and more difficult to understand by other programmers.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T10:10:16.323",
"Id": "420518",
"Score": "0",
"body": "@thadeuszlay It is no more or less declarative than using a + operator. All programmers should know how bitwise operators work and how to use them. If not then they should not be messing with your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T10:17:31.550",
"Id": "420519",
"Score": "0",
"body": "haha.... bad ass answer!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T06:06:57.393",
"Id": "217369",
"ParentId": "217340",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "217369",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T19:02:08.370",
"Id": "217340",
"Score": "3",
"Tags": [
"javascript",
"algorithm",
"programming-challenge"
],
"Title": "Implement integer exponentiation faster than repeated multiplication"
} | 217340 |
<p>The following code is for a vertical menu, where I needed a marker to slide down next to a link upon hovering over said link. Therefore I needed to change CSS properties of a HTML element (the top-margin in this case).</p>
<p>What I've done in jQuery is add a class ('.movedown1' or '.movedown2') to the marker div ('#slide') when the mouse hovers over one of the links ('#menulink2' or '#menulink3'), and remove the class when the mouse stops hovering over the link.</p>
<p>It works!...But is it a clean method to add/change CSS properties of a HTML element? Does it follow best practices for jQuery? I've only used jQuery a few times in the past so I'm not familiar with best practices.</p>
<p><a href="https://codepen.io/AlbertMcTorre/pen/PgjXBy" rel="nofollow noreferrer">Codepen</a></p>
<p>HTML(Pug):</p>
<pre><code>#slide
#menu
a.menulink#menulink1(href="#")
p RED
a.menulink#menulink2(href="#")
p BLUE
a.menulink#menulink3(href="#")
p GREEN
</code></pre>
<p>CSS (Sass)</p>
<pre><code>a
color: white
text-decoration: none
#slide
width: 10px
height: 30px
background-color: red
position: absolute
border-radius: 15px
transition: 0.3s ease-in-out
.movedown1
margin-top: 40px
background-color: blue !important
.movedown2
margin-top: 80px
background-color: green !important
#menu
margin-left: 30px
.menulink
height: 40px
width: 70px
display: block
.menulink p
height: 30px
width: 70px
margin: 0px
border-radius: 15px
display: flex
align-items: center
justify-content: center
#menulink1 p
background: red
#menulink2 p
background: blue
#menulink3 p
background: green
</code></pre>
<p>jQuery</p>
<pre><code>$('#menulink2').hover(
function(){
$('#slide').addClass('movedown1');
},
function(){
$('#slide').removeClass('movedown1')
});
$('#menulink3').hover(
function(){
$('#slide').addClass('movedown2');
},
function(){
$('#slide').removeClass('movedown2')
});
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T20:30:11.007",
"Id": "420464",
"Score": "0",
"body": "Really clean code. great work."
}
] | [
{
"body": "<h2>JavaScript</h2>\n\n<p>This code violates the <a href=\"https://deviq.com/don-t-repeat-yourself/\" rel=\"nofollow noreferrer\"><em><strong>D</strong>on't <strong>R</strong>epeat <strong>Y</strong>ourself</em> principle</a> because there is some redundancy in the code to handle the hover events, but for a beginner it might be challenging to know how to abstract the common code. </p>\n\n<p>One way to reduce the redundancy is to define a mapping of id values to classes to toggle. This can be done with a plain-old JavaScript <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object\" rel=\"nofollow noreferrer\">Object</a>, like below, or with a <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map\" rel=\"nofollow noreferrer\">Map()</a> object. </p>\n\n<pre><code>const targetClassMapping = {\n 'menulink2': 'movedown1',\n 'menulink3': 'movedown2'\n};\n</code></pre>\n\n<p>Then the code can utilize <a href=\"http://api.jquery.com/hover/#hover2\" rel=\"nofollow noreferrer\"><code>.hover()</code></a> on any element with the class name <code>menulink</code> with a single event handler that checks the <code>id</code> attribute (using the jQuery <a href=\"https://api.jquery.com/attr\" rel=\"nofollow noreferrer\"><code>.attr()</code></a> method) of the event target and if the <code>id</code> matches a key in that mapping it then calls <a href=\"http://api.jquery.com/toggleClass\" rel=\"nofollow noreferrer\"><code>.toggleClass()</code></a> on the slider element. Additionally, <code>$('slider')</code> can be stored in a variable and used when needed instead of querying the DOM each time.</p>\n\n<pre><code>const slide = $('#slide');\n$('.menulink').hover(function(){\n const id = $(this).attr('id');\n if (id && id in targetClassMapping) {\n slide.toggleClass(targetClassMapping[id]);\n }\n});\n</code></pre>\n\n<p>This could also be done without jQuery, though the code wouldn't be quite as succinct.</p>\n\n<pre><code>const slider = document.getElementById('slide');\nconst targetClassMapping = {\n 'menulink2': 'movedown1',\n 'menulink3': 'movedown2'\n};\n['mouseover', 'mouseout'].forEach(type => document.addEventListener(type, handleMouseEventOnMenuLink));\nfunction handleMouseEventOnMenuLink(event) {\n if (event.target.parentNode) {\n const id = event.target.parentNode.id;\n if (id in targetClassMapping) {\n const method = event.type === 'mouseover' ? 'add' : 'remove';\n slider.classList[method](targetClassMapping[id]);\n }\n }\n} \n</code></pre>\n\n<h2>CSS / SASS</h2>\n\n<p>I see a couple lines with <code>!important</code>. </p>\n\n<blockquote>\n<pre><code>.movedown1\n margin-top: 40px\n background-color: blue !important\n\n.movedown2\n margin-top: 80px\n background-color: green !important\n</code></pre>\n</blockquote>\n\n<p>It is wise to not depend on <code>!important</code> if possible, <a href=\"https://stackoverflow.com/a/3427813/1575353\">to avoid confusion</a>. You can remove the <code>!important</code> from those background color styles if you make the selectors more specific than just <code>#slide</code> - e.g. <code>#slide.movedown1</code> and <code>#slide.movedown2</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T20:41:07.473",
"Id": "217349",
"ParentId": "217341",
"Score": "1"
}
},
{
"body": "<p>It is possible by changing the location of your <code>#slide</code> element so that it is a sibling of <code>menulink</code>. I would also remove the paragraph tags as they are redundant and reduce the dependence on id tags. Rsather use classes. </p>\n\n<p>Here is how I would implement it (though you could also use a flex layout)</p>\n\n<pre><code>#menu\n a.menulink(href=\"#\") RED\n a.menulink(href=\"#\") BLUE\n a.menulink(href=\"#\") GREEN\n .slide\n</code></pre>\n\n<pre><code>.slide\n width: 10px\n height: 30px\n background-color: red\n position: absolute\n top: 8px\n border-radius: 15px\n transition: 0.3s ease-in-out\n\n.menulink:hover:nth-child(2) ~ .slide\n margin-top: 40px\n background-color: blue\n\n.menulink:hover:nth-child(3) ~ .slide\n margin-top: 80px\n background-color: green\n\n#menu\n margin-left: 30px\n\n.menulink\n display: block\n margin: 5px 16px\n width: 70px\n display: block\n height: 30px\n line-height: 30px\n border-radius: 15px\n color: white\n text-decoration: none\n text-align: center\n\n.menulink:nth-child(1)\n background: red\n.menulink:nth-child(2)\n background: blue\n.menulink:nth-child(3)\n background: green\n<span class=\"math-container\">```</span> \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T00:58:39.693",
"Id": "217362",
"ParentId": "217341",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "217349",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T19:06:25.567",
"Id": "217341",
"Score": "3",
"Tags": [
"javascript",
"beginner",
"jquery",
"html",
"css"
],
"Title": "Sliding marker on link hover with jQuery"
} | 217341 |
<p>I work in the population health industry and get contracts from commercial companies to conduct research on their products. This is the general code to identify target patient groups from a provincial datasets, including DAD (hospital discharge), PC (physician claims), NACRS (emergency room visit), PIN (drug dispensation), and REG (provincial registry). Same patients can have multiple rows in each of the databases. For example, if a patient was hospitalized 3 times, s/he will show up as three separate rows in DAD data. The code does the followings:</p>
<ol>
<li>Import data from csv files into individual Pandas dataframes (df's)</li>
<li>Then it goes through some initial data cleaning and processing (such as random sampling, date formatting, calling additional reference information (such as icd code for study condition)</li>
<li>Under the section <code>1) Identify patients for case defn'n #1</code>, a series of steps have been done to label (as tags) each of the relevant data and filtering based on these tags. Datasets are linked together to see if a particular patient fulfills the diagnostic code requirement.</li>
<li>Information also needs to be aggregated by unique patient level via the <code>pivot_table</code> function to summarize by unique patients</li>
<li>At the end, the final patient dataframe is saved into local directory, and analytic results are printed</li>
<li>I also made my own modules <code>feature_tagger</code> to house some of the more frequently-used functions away from this main code</li>
</ol>
<pre><code># Overall steps:
# 1) Patient defintiion: Had a ICD code and a procedure code within a time period
# 2) Output: A list of PHN_ENC of included patients; corresponding index date
# .. 'CaseDefn1_PatientDict_FINAL.txt'
# .. 'CaseDefn1_PatientDf_FINAL.csv'
# 3) Results: Analytic results
# ----------------------------------------------------------------------------------------------------------
import pandas as pd
import datetime
import random
import feature_tagger.feature_tagger as ft
import data_descriptor.data_descriptor as dd
import data_transformer.data_transformer as dt
import var_creator.var_creator as vc
# Unrestrict pandas' output display
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 120)
# Control panel
save_file_switch = False # WARNING: will overwrite existing when == True
df_subsampling_switch = False # WARNING: make to sure turn off for final results
edge_date_inclusion = True # whether to include the last date in the range of inclusion criteria
testing_printout_switch = False
result_printout_switch = True
done_switch = True
df_subsampling_n = 15000
random_seed = 888
# Instantiate objects
ft_obj = ft.Tagger()
dt_obj = dt.Data_Transformer()
# Import data
loc = 'office'
if loc == 'office':
directory = r'E:\My_Working_Primary\Projects\Data_Analysis\\'
elif loc == 'home':
directory = r'C:\Users\MyStuff\Dropbox\Projects\Data_Analysis\\'
else: pass
refDataDir = r'_Data\RefData\\'
realDataDir = r'_Data\RealData\\'
resultDir = r'_Results\\'
file_dad = 'Prepped_DAD_Data.csv'
file_pc = 'Prepped_PC_Data.csv'
file_nacrs = 'Prepped_NACRS_Data.csv'
file_pin = 'Prepped_PIN_Data.csv'
file_reg = 'Prepped_REG_Data.csv'
df_dad = pd.read_csv(directory+realDataDir+file_dad, dtype={'PHN_ENC': str}, encoding='utf-8', low_memory=False)
df_pc = pd.read_csv(directory+realDataDir+file_pc, dtype={'PHN_ENC': str}, encoding='utf-8', low_memory=False)
df_nacrs = pd.read_csv(directory+realDataDir+file_nacrs, dtype={'PHN_ENC': str}, encoding='utf-8', low_memory=False)
df_pin = pd.read_csv(directory+realDataDir+file_pin, dtype={'PHN_ENC': str}, encoding='utf-8', low_memory=False)
df_reg = pd.read_csv(directory+realDataDir+file_reg, dtype={'PHN_ENC': str}, encoding='utf-8', low_memory=False)
# Create random sampling of df's to run codes faster
if df_subsampling_switch==True:
if (df_subsampling_n>len(df_dad))|(df_subsampling_n>len(df_pc))|(df_subsampling_n>len(df_nacrs))|(df_subsampling_n>len(df_pin)):
print ('Warning: Specified subsample size is larger than the total no. of row of some of the dataset,')
print ('As a result, resampling with replacement will be done to reach specified subsample size.')
df_dad = dt_obj.random_n(df_dad, n=df_subsampling_n, on_switch=df_subsampling_switch, random_state=random_seed)
df_pc = dt_obj.random_n(df_pc, n=df_subsampling_n, on_switch=df_subsampling_switch, random_state=random_seed)
df_nacrs = dt_obj.random_n(df_nacrs, n=df_subsampling_n, on_switch=df_subsampling_switch, random_state=random_seed)
df_pin = dt_obj.random_n(df_pin, n=df_subsampling_n, on_switch=df_subsampling_switch, random_state=random_seed)
# Format variable type
df_dad['ADMIT_DATE'] = pd.to_datetime(df_dad['ADMIT_DATE'], format='%Y-%m-%d')
df_dad['DIS_DATE'] = pd.to_datetime(df_dad['DIS_DATE'], format='%Y-%m-%d')
df_pc['SE_END_DATE'] = pd.to_datetime(df_pc['SE_END_DATE'], format='%Y-%m-%d')
df_pc['SE_START_DATE'] = pd.to_datetime(df_pc['SE_START_DATE'], format='%Y-%m-%d')
df_nacrs['ARRIVE_DATE'] = pd.to_datetime(df_nacrs['ARRIVE_DATE'], format='%Y-%m-%d')
df_pin['DSPN_DATE'] = pd.to_datetime(df_pin['DSPN_DATE'], format='%Y-%m-%d')
df_reg['PERS_REAP_END_RSN_DATE'] = pd.to_datetime(df_reg['PERS_REAP_END_RSN_DATE'], format='%Y-%m-%d')
# Import reference codes
file_rxCode = '_InStudyCodes_ATC&DIN.csv'
file_icdCode = '_InStudyCodes_DxICD.csv'
file_serviceCode = '_InStudyCodes_ServiceCode.csv'
df_rxCode = pd.read_csv(directory+refDataDir+file_rxCode, dtype={'ICD_9': str}, encoding='utf-8', low_memory=False)
df_icdCode = pd.read_csv(directory+refDataDir+file_icdCode, encoding='utf-8', low_memory=False)
df_serviceCode = pd.read_csv(directory+refDataDir+file_serviceCode, encoding='utf-8', low_memory=False)
# Defining study's constant variables
inclusion_start_date = datetime.datetime(2017, 4, 1, 00, 00, 00)
inclusion_end_date = datetime.datetime(2018, 3, 31, 23, 59, 59)
sp_serviceCode_dict = {df_serviceCode['Short_Desc'][0]:df_serviceCode['Health_Service_Code'][0]}
sp_serviceCode_val = sp_serviceCode_dict['ABC injection']
sp_dxCode_dict = {'DIABETES_ICD9': df_icdCode['ICD_9'][0], 'DIABETES_ICD10': df_icdCode['ICD_10'][0]}
sp_dxCode_val_icd9 = sp_dxCode_dict['DIABETES_ICD9']
sp_dxCode_val_icd10 = sp_dxCode_dict['DIABETES_ICD10']
# ----------------------------------------------------------------------------------------------------------
# 1) Identify patients for case def'n #1.
# Step 1 - Aged between 18 and 100 years old on the index date
# Step 2 - Had at least 1 recorded ICD diagnostic code based on physician visit (ICD-9-CA=9999 in PC) or
# hospitalization (ICD-10-CA=G9999 in DAD) during the inclusion period
# Step 3.1 - Had at least 1 specific procedure code (99.999O) during
# the inclusion period (Note: earliest ABC injection code date is the Index date)
# Step 3.2 - Construct index date
# Step 4 - Registered as a valid Alberta resident for 2 years before the index date and 1 year after the
# index date (determined from PR)
# 1.1) Get age at each service, then delete rows with age falling out of 18-100 range
df_dad_ageTrimmed = df_dad.copy()
df_dad_ageTrimmed = df_dad_ageTrimmed[(df_dad_ageTrimmed['AGE']>=18) & (df_dad_ageTrimmed['AGE']<=100)]
df_pc_ageTrimmed = df_pc.copy()
df_pc_ageTrimmed = df_pc_ageTrimmed[(df_pc_ageTrimmed['AGE']>=18) & (df_pc_ageTrimmed['AGE']<=100)]
# 1.2) Tag appropriate date within sp range > tag DIABETES code > combine tags
df_dad_ageTrimmed['DAD_DATE_TAG'] = ft_obj.date_range_tagger(df_dad_ageTrimmed, 'ADMIT_DATE',
start_date_range=inclusion_start_date, end_date_range=inclusion_end_date, edge_date_inclusion=
edge_date_inclusion)
df_dad_ageTrimmed['DAD_ICD_TAG'] = ft_obj.multi_var_cond_tagger(df_dad_ageTrimmed, repeat_var_base_name='DXCODE',
repeat_var_start=1, repeat_var_end=25, cond_list=[sp_dxCode_val_icd10])
df_dad_ageTrimmed['DAD_DATE_ICD_TAG'] = ft_obj.summing_all_tagger(df_dad_ageTrimmed, tag_var_list=['DAD_DATE_TAG',
'DAD_ICD_TAG'])
df_pc_ageTrimmed['PC_DATE_TAG'] = ft_obj.date_range_tagger(df_pc_ageTrimmed, 'SE_END_DATE',
start_date_range=inclusion_start_date, end_date_range=inclusion_end_date, edge_date_inclusion=
edge_date_inclusion)
df_pc_ageTrimmed['PC_ICD_TAG'] = ft_obj.multi_var_cond_tagger(df_pc_ageTrimmed, repeat_var_base_name='HLTH_DX_ICD9X_CODE_',
repeat_var_start=1, repeat_var_end=3, cond_list=[str(sp_dxCode_val_icd9)])
df_pc_ageTrimmed['PC_DATE_ICD_TAG'] = ft_obj.summing_all_tagger(df_pc_ageTrimmed, tag_var_list=['PC_DATE_TAG',
'PC_ICD_TAG'])
# Output a list of all patients PHN_ENC who satisfy the Date and DIABETES code criteria
df_dad_ageDateICDtrimmed = df_dad_ageTrimmed[df_dad_ageTrimmed['DAD_DATE_ICD_TAG']==1]
df_pc_ageDateICDtrimmed = df_pc_ageTrimmed[df_pc_ageTrimmed['PC_DATE_ICD_TAG']==1]
dad_patientList_diabetes_Code = df_dad_ageDateICDtrimmed['PHN_ENC'].unique().tolist()
pc_patientList_diabetes_Code = df_pc_ageDateICDtrimmed['PHN_ENC'].unique().tolist()
dad_pc_patientList_diabetes_Code = list(set(dad_patientList_diabetes_Code)|set(pc_patientList_diabetes_Code))
dad_pc_patientList_diabetes_Code.sort()
# 1.3.1) Tag appropriate date within sp range > tag ABC injection code > combine tags
df_pc_ageTrimmed['PC_PROC_TAG'] = df_pc_ageTrimmed['ABC_INJECT']
df_pc_ageTrimmed['PC_DATE_PROC_TAG'] = ft_obj.summing_all_tagger(df_pc_ageTrimmed, tag_var_list=['PC_DATE_TAG',
'PC_PROC_TAG'])
df_pc_ageDateProcTrimmed = df_pc_ageTrimmed[df_pc_ageTrimmed['PC_DATE_PROC_TAG']==1]
pc_patientList_procCode = df_pc_ageDateProcTrimmed['PHN_ENC'].unique().tolist()
dad_pc_patientList_diabetes_NprocCode = list(set(dad_pc_patientList_diabetes_Code)&set(pc_patientList_procCode))
dad_pc_patientList_diabetes_NprocCode.sort()
# 1.3.2) Find Index date
df_pc_ageDateProcTrimmed_pivot = pd.pivot_table(df_pc_ageDateProcTrimmed, index=['PHN_ENC'],
values=['SE_END_DATE', 'AGE', 'SEX', 'RURAL'], aggfunc={'SE_END_DATE':np.min, 'AGE':np.min,
'SEX':'first', 'RURAL':'first'})
df_pc_ageDateProcTrimmed_pivot = pd.DataFrame(df_pc_ageDateProcTrimmed_pivot.to_records())
df_pc_ageDateProcTrimmed_pivot = df_pc_ageDateProcTrimmed_pivot.rename(columns={'SE_END_DATE':'INDEX_DT'})
# 1.4) Filter by valid registry
# Create a list variable (based on index date) to indicate which fiscal years need to be valid according to
# the required 2 years before index and 1 year after index date, in df_pc_ageDateProcTrimmed_pivot
def extract_needed_fiscal_years(row): # extract 2 years before and 1 year after index date
if int(row['INDEX_DT'].month) >= 4:
index_yr = int(row['INDEX_DT'].year)+1
else:
index_yr = int(row['INDEX_DT'].year)
first_yr = index_yr-2
four_yrs_str = str(first_yr)+','+str(first_yr+1)+','+str(first_yr+2)+','+str(first_yr+3)
return four_yrs_str
df_temp = df_pc_ageDateProcTrimmed_pivot.copy()
df_temp['FYE_NEEDED'] = df_temp.apply(extract_needed_fiscal_years, axis=1)
df_temp['FYE_NEEDED'] = df_temp['FYE_NEEDED'].apply(lambda x: x[0:].split(',')) # from whole string to list of string items
df_temp['FYE_NEEDED'] = df_temp['FYE_NEEDED'].apply(lambda x: [int(i) for i in x]) # from list of string items to list of int items
# Create a list variable to indicate the active fiscal year, in df_reg
df_reg['FYE_ACTIVE'] = np.where(df_reg['ACTIVE_COVERAGE']==1, df_reg['FYE'], np.nan)
df_reg_agg = df_reg.groupby(by='PHN_ENC').agg({'FYE_ACTIVE':lambda x: list(x)})
df_reg_agg = df_reg_agg.reset_index()
df_reg_agg['FYE_ACTIVE'] = df_reg_agg['FYE_ACTIVE'].apply(lambda x: [i for i in x if ~np.isnan(i)]) # remove float nan
df_reg_agg['FYE_ACTIVE'] = df_reg_agg['FYE_ACTIVE'].apply(lambda x: [int(i) for i in x]) # convert float to int
# Merge df's and create tag, if active years do not cover all the required fiscal year, exclude patients
# Create inclusion/exclusion patient list to apply to obtain patient cohort based on case def'n #1
df_temp_v2 = df_temp.merge(df_reg_agg, on='PHN_ENC', how='left')
df_temp_v2_trimmed = df_temp_v2[(df_temp_v2['FYE_NEEDED'].notnull())&(df_temp_v2['FYE_ACTIVE'].notnull())]
# Remove rows with missing on either variables
def compare_list_elements_btw_cols(row):
if set(row['FYE_NEEDED']).issubset(row['FYE_ACTIVE']):
return 1
else:
return 0
df_temp_v2_trimmed['VALID_REG'] = df_temp_v2_trimmed.apply(compare_list_elements_btw_cols, axis=1)
df_temp_v2_trimmed_v2 = df_temp_v2_trimmed[df_temp_v2_trimmed['VALID_REG']==1]
reg_patientList = df_temp_v2_trimmed_v2['PHN_ENC'].unique().tolist()
# Apply inclusion/exclusion patient list (from REG) to find final patients
# Obtain final patient list
df_final_defn1 = df_pc_ageDateProcTrimmed_pivot.merge(df_temp_v2_trimmed_v2, on='PHN_ENC', how='inner')
df_final_defn1 = df_final_defn1[['PHN_ENC', 'AGE_x', 'SEX_x', 'RURAL_x', 'INDEX_DT_x']]
df_final_defn1 = df_final_defn1.rename(columns={'AGE_x':'AGE', 'SEX_x':'SEX', 'RURAL_x':'RURAL', 'INDEX_DT_x':'INDEX_DT',})
df_final_defn1['PREINDEX_1Yr'] = (df_final_defn1['INDEX_DT']-pd.Timedelta(days=364)) # 364 because index date is counted as one pre-index date
df_final_defn1['PREINDEX_2Yr'] = (df_final_defn1['INDEX_DT']-pd.Timedelta(days=729)) # 729 because index date is counted as one pre-index date
df_final_defn1['POSTINDEX_1Yr'] = (df_final_defn1['INDEX_DT']+pd.Timedelta(days=364))
list_final_defn1 = df_final_defn1['PHN_ENC'].unique().tolist()
dict_final_defn1 = {'Final unique patients of case definition #1':list_final_defn1}
# Additional ask (later on)
# How: Create INDEX_DT_FIS_YR (index date fiscal year) by mapping INDEX_DT to fiscal year
def index_date_fiscal_year(row):
if ((row['INDEX_DT'] >= datetime.datetime(2015, 4, 1, 00, 00, 00)) &
(row['INDEX_DT'] < datetime.datetime(2016, 4, 1, 00, 00, 00))):
return '2015/2016'
elif ((row['INDEX_DT'] >= datetime.datetime(2016, 4, 1, 00, 00, 00)) &
(row['INDEX_DT'] < datetime.datetime(2017, 4, 1, 00, 00, 00))):
return '2016/2017'
else:
return 'Potential error'
df_final_defn1['INDEX_DT_FIS_YR'] = df_final_defn1.apply(index_date_fiscal_year, axis=1)
# 2) Output final patient list for future access
# WARNING: will overwrite existing
if save_file_switch == True:
if df_subsampling_switch == True:
f = open(directory+resultDir+'_CaseDefn1_PatientDict_Subsample.txt',"w")
f.write(str(dict_final_defn1)+',')
f.close()
df_final_defn1.to_csv(directory+resultDir+'_CaseDefn1_PatientDf_Subsample.csv', sep=',', encoding='utf-8')
elif df_subsampling_switch == False:
f = open(directory+resultDir+'CaseDefn1_PatientDict_FINAL.txt',"w")
f.write(str(dict_final_defn1)+',')
f.close()
df_final_defn1.to_csv(directory+resultDir+'CaseDefn1_PatientDf_FINAL.csv', sep=',', encoding='utf-8')
# 3) Results: Analytic results
if result_printout_switch == True:
print ('Unique PHN_ENC N, (aged 18 to 100 during inclusion period) from DAD:')
print (df_dad_ageTrimmed['PHN_ENC'].nunique())
print ('Unique PHN_ENC N, (aged 18 to 100 during inclusion period) from PC:')
print (df_pc_ageTrimmed['PHN_ENC'].nunique())
print ('Unique PHN_ENC N, (aged 18 to 100 during inclusion period) from DAD or PC:')
dd_obj = dd.Data_Comparator(df_dad_ageTrimmed, df_pc_ageTrimmed, 'PHN_ENC')
print (dd_obj.unique_n_union())
print ('Unique PHN_ENC N, (aged 18 to 100) and (had DIABETES code during inclusion period) from DAD:')
print (df_dad_ageDateICDtrimmed['PHN_ENC'].nunique())
print ('Unique PHN_ENC N, (aged 18 to 100) and (had DIABETES code during inclusion period) from PC:')
print (df_pc_ageDateICDtrimmed['PHN_ENC'].nunique())
print ('Unique PHN_ENC N, (aged 18 to 100) and (had DIABETES code during inclusion period) from DAD or PC:')
print (len(dad_pc_patientList_diabetes_Code))
print ('Unique PHN_ENC N, (aged 18 to 100) and (had DIABETES code during inclusion period)\
and (had ABC injection code) from DAD and PC:')
print (df_pc_ageDateProcTrimmed_pivot['PHN_ENC'].nunique())
print ('Unique PHN_ENC N, (aged 18 to 1005) and (had DIABETES code during inclusion period)\
and (had ABC injection code) and (had AB resident around index date) from DAD, PC, and REG [Case Def #1]:')
print (df_final_defn1['PHN_ENC'].nunique())
# Additional analytic ask (later on)
print ('Patient N by index date as corresponding fiscal year:')
print (df_final_defn1['INDEX_DT_FIS_YR'].value_counts())
if done_switch == True:
ctypes.windll.user32.MessageBoxA(0, b'Hello there', b'Program done.', 3)
</code></pre>
<p>My questions are:</p>
<ul>
<li>This is a code for a specific project, other projects from other companies while aren't exactly the same, they usually follow similar overall steps including cleaning data, linking data, creating tags, filtering tags, aggregating data, saving files, and producing data. How can I refactor my code to be maintainable within this specific project, as well as reusable across similar projects?</li>
<li>Many times, once I have run the code and produce the results, clients may come back to ask for additional follow-up information (i.e., the ones under <code># Additional ask (later on)</code>). How can I deal with additional asks more effectively with maintainability and expandability in mind?</li>
<li>Any areas I can try using some design patterns?</li>
<li>Any other suggestions on how I can write better python code are more than welcome.</li>
</ul>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T19:45:02.883",
"Id": "420458",
"Score": "0",
"body": "Your original title said \"big data\". That doesn't seem to apply, since you're dealing with hundreds of rows, rather than millions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T19:52:11.743",
"Id": "420460",
"Score": "0",
"body": "Nope, my full datasets normally reached millions of rows. That's why I need the `df_subsampling_switch` to sample data for code development. Another characteristic that deems this problem to be big data is that they are linkable, which created a lot more complexity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T19:54:12.233",
"Id": "420461",
"Score": "0",
"body": "Sorry, I made a wrong assumption based on `pd.set_option('display.max_rows', 500)`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T19:56:27.580",
"Id": "420462",
"Score": "0",
"body": "No worries. that's fine."
}
] | [
{
"body": "<p>If I understand correctly, most or all of your \"projects\" follow the same format, even if they use different files and look for different data in different fields.</p>\n\n<p>That says to me that you should try to squeeze out the repeated parts into various helpers, and try to put the boilerplate parts into some sort of common framework. </p>\n\n<p>(Note: it looks like you are using Dropbox, and I suspect you're using it to move those files from the office to home. I don't know if you're paying for your dropbox or just using the free version, and I suspect that dropbox is probably better at security than most. But please <a href=\"https://blog.acolyer.org/2019/04/08/how-bad-can-it-git-characterizing-secret-leakage-in-public-github-repositories/\" rel=\"nofollow noreferrer\">be careful.</a></p>\n\n<h2>Create a module for configuration data and setup</h2>\n\n<p>Have a look at the help available from the <code>pip install --help</code> command, specifically the <code>-e (--editable)</code> option. This allows you to install from a directory or URL. </p>\n\n<p>This will allow you to create a module that detects your home/office setup (if hostname == 'MY-PC': ... home ... else: ... office ...) and makes whatever configuration is appropriate. Then you can do something like:</p>\n\n<pre><code>from kubik88 import Config\nfrom kubik88.data_analysis import *\n</code></pre>\n\n<p>(Doing the <code>import *</code> allows you to import functions and classes from other modules-- just set your <code>__all__</code> correctly.) </p>\n\n<h2>Use the <em>template method</em> pattern</h2>\n\n<p>Create a class. Then create a <a href=\"https://en.wikipedia.org/wiki/Template_method\" rel=\"nofollow noreferrer\"><strong>template method</strong></a> on that class that summarizes your effort at the highest level. I'm basing mine off the text of your comments, and I stopped after a few steps because I hope you get the idea:</p>\n\n<pre><code>class PatientDataAnalysis:\n\n def analysis(self):\n self.instantiate_objects()\n self.import_data()\n self.random_sample_dataframes()\n self.update_column_formats()\n self.import_reference_codes()\n self.define_constant_variables()\n ...\n</code></pre>\n\n<p>Notice I'm not doing any work, just calling some methods to do \"primitive\" operations.</p>\n\n<p>Next, define methods to do the primitive things:</p>\n\n<pre><code># Waaaay up at the top:\nimport pathlib\n\n def import_data(self):\n ''' Import all the project data into dataframes. '''\n for abbr, filename in self.data_files.items():\n self.import_csv(abbr, filename)\n\n def import_csv(self, abbr, filename, **kwargs):\n ''' Import one CSV file into a dataframe, and store it in \n `self.dataframes` keyed by abbr. \n '''\n options = (self.read_csv_options if not kwargs\n else { **self.read_csv_options, **kwargs })\n filespec = self.base_path / self.real_data / filename\n df = pd.read_csv(str(filespec), **options)\n self.dataframes[abbr] = df\n</code></pre>\n\n<p>With this approach, you can now subclass the parent class and extend the methods that you care about, leaving the default behavior where you don't care (or where it just works):</p>\n\n<pre><code>class DiabetesStudy2019(PatientDataAnalysis):\n def import_data(self):\n # Do the usual stuff\n super().import_data()\n # And also do one more thing:\n ...\n</code></pre>\n\n<h2>Use helper functions/methods to implement repeated operations:</h2>\n\n<p>Pretty much anything you find yourself doing more than one time you should write a function to do. If you're lucky (or good) there will be a way to convert that function into a more \"data-driven\" approach:</p>\n\n<pre><code>def reformat_date_field(self, df, fieldname, format='%Y-%m-%d'):\n df[fieldname] = pd.to_datetime(df[fieldname], format=format)\n\nreformat_date_field(self.dataframes['dad'], 'ADMIT_DATE')\nreformat_date_field(self.dataframes['dad'], 'DIS_DATE')\nreformat_date_field(self.dataframes['pc'], 'SE_END_DATE')\nreformat_date_field(self.dataframes['pc'], 'SE_START_DATE')\nreformat_date_field(self.dataframes['nacrs'], 'ARRIVE_DATE')\nreformat_date_field(self.dataframes['pin'], 'DSPN_DATE')\nreformat_date_field(self.dataframes['reg'], 'PERS_REAP_END_RSN_DATE')\n</code></pre>\n\n<p>Which becomes:</p>\n\n<pre><code>date_fields = (('dad', 'ADMIT_DATE'), ('dad', 'DIS_DATE'), ('pc', 'SE_END_DATE'),\n ('pc', 'SE_START_DATE'), ('nacrs', 'ARRIVE_DATE'), ('pin', 'DISP_DATE'),\n ('reg', 'PERS_REAP_END_RSN_DATE'))\n\nfor df, field in date_fields:\n reformat_date_field(self.dataframes[df], field)\n</code></pre>\n\n<p>(Or possibly some other data format that makes your life easy.)</p>\n\n<p>The idea is to (1) make it clear what is happening by calling a named function; and (2) make it easy to extend or modify the list of fields by storing them as data instead of function calls.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T03:00:21.163",
"Id": "420498",
"Score": "0",
"body": "You don't show what the tag classes do. But it seems like they're very close to creating boolean columns in the dataframes, or maybe taking boolean columns as input. I'd suggest looking in that direction to see if there isn't some low-hanging fruit to be picked."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T03:42:24.880",
"Id": "420499",
"Score": "0",
"body": "For example, I need to make a date_tag which is similar to what you said but in 0 or 1, that is derived from if the record date is or isn't falling in an expected date range, then I have an icd_tag which is by screening 25 different diagnostic variables to see if any contains any element from a set of target icd codes. Then I retain patients if date_tag==icd_tag==1. Should I create separate helper functions, then add the function call in PatientDataAnalysis class?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T03:50:20.177",
"Id": "420500",
"Score": "0",
"body": "It seems like this is the real \"meat\" of your analysis. So no. The PatientDataAnalysis class is the \"skeleton\" of the analysis. The particular details that talk about diabetes between 18 and 100 are not generic, but specific. So they would go in a specific subclass."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T03:54:20.487",
"Id": "420501",
"Score": "0",
"body": "Also, instead of making a 0/1 tag, could you make a true/false tag, and then just do `in_group = df[df.date_tag & df.icd_tag]` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T04:50:55.693",
"Id": "420504",
"Score": "0",
"body": "Using boolean does look a lot cleaner. The only thing is, I am interested to aggregate into unique patients. For example, if a patient has `date_tag==icd_tag==1` on 3 occurrences of hospitalization, summing it (from 0/1) allows me to characterize this patient to have 3 hospitalizations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T23:16:18.467",
"Id": "420610",
"Score": "0",
"body": "I am new to design pattern, and thanks for suggesting the template method pattern, it seems very powerful and relevant to my needs. I wonder for data visualization, say I normally need to present some basic descriptive stats and also statistical testing, but each project is somewhat different in terms of the exact stats, is template method also a good approach for this? So for the entire project, should I create one template method for patient creation, one for analysis, and one for data visualization etc?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T00:40:16.150",
"Id": "217359",
"ParentId": "217343",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "217359",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T19:35:37.063",
"Id": "217343",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"pandas",
"data-mining"
],
"Title": "Analyzing patient treatment data using Pandas"
} | 217343 |
<p>I have this sample data:</p>
<pre><code>let trips = [
{
from: "DEN",
to: "JFK"
},
{
from: "SEA",
to: "DEN"
},
{
from: 'JFK',
to: 'SEA'
},
];
</code></pre>
<p>and my origin is 'JFK', I want to sort the list by how I have traveled. So for instance, this should be the end result:</p>
<pre><code>let trips = [
{
from: 'JFK',
to: 'SEA'
},
{
from: "SEA",
to: "DEN"
},
{
from: "DEN",
to: "JFK"
},
];
</code></pre>
<p>My solution works but it's not very well written, but I tried!</p>
<pre><code>function sortByLinked(trips, origin = 'JFK') {
let sortedArray = [];
let first = trips.filter(trip => trip.from === origin)[0];
sortedArray.push(first);
for(var i = 0; i < trips.length; i++) {
if(sortedArray[0].to === trips[i].from) {
sortedArray.push(trips[i]);
}
}
for(var i = 0; i < trips.length; i++) {
if(sortedArray[1].to === trips[i].from) {
sortedArray.push(trips[i]);
}
}
return sortedArray;
}
sortByLinked(trips)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T21:58:17.907",
"Id": "420473",
"Score": "0",
"body": "is it like the origin and final destination always the same? and how many intermediate trips are going to be present?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T22:00:47.537",
"Id": "420474",
"Score": "0",
"body": "Is `from` unique for all elements?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T22:44:27.763",
"Id": "420482",
"Score": "0",
"body": "@karthick yes the origin and final should be the same."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T22:44:30.990",
"Id": "420483",
"Score": "0",
"body": "@Taplar yes from is unique"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T00:06:58.490",
"Id": "420488",
"Score": "0",
"body": "The task you want to perform is a simple kind of [topological sorting](https://en.wikipedia.org/wiki/Topological_sorting)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T15:18:07.280",
"Id": "420563",
"Score": "0",
"body": "@200_success: I don't think so. The graph has at least one cycle, so you cannot apply topological sorting. You need to find an Eulerian cycle, e.g. with Hierholzer's algorithm. See [here](https://codereview.stackexchange.com/a/217402/139491)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-20T07:34:14.963",
"Id": "421361",
"Score": "0",
"body": "What's up with the complicated title? It's wrong as far as I can tell : the whole graph is a cycle."
}
] | [
{
"body": "<p>Your solution only works if there's exactly 3 trips. After you find the first trip, put it at the front of the array and then find each subsequent one but instead of using a <code>for</code> loop like you're doing there are other ways to find the next trip like using <code>Array.map()</code> or <code>Array.filter()</code>. </p>\n\n<p>Here's one way to sort it in place and can handle any number of trips greater than 1.</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 sortByLinked(trips, origin = 'JFK') {\n\n // this will be useful\n function swap(array, index1, index2){\n let temp = array[index1];\n array[index1] = array[index2];\n array[index2] = temp;\n }\n\n // find first one\n let first = trips.filter(trip => trip.from === origin)[0];\n\n // put him in the front of the list\n swap(trips, trips.map(trip => trip.from).indexOf(first.from), 0);\n\n // sort it in place\n for(let i=1; i<trips.length; i++){\n swap(trips, i, trips.map(trip => trip.from).indexOf(trips[i-1].to));\n }\n}</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T22:38:22.057",
"Id": "420481",
"Score": "0",
"body": "Because [tag:ecmascript-6] is used here: [\"_Two variables values can be swapped in one destructuring expression._\"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Swapping_variables)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T22:21:48.443",
"Id": "217353",
"ParentId": "217351",
"Score": "5"
}
},
{
"body": "<p>It would be good if your function could work for more than 3 trips. </p>\n\n<p>And for larger chains of trips it becomes important to make it efficient. It is not efficient to search for the next trip by scanning the whole array. This will make the solution have <em>O(n²)</em> time complexity. So I would suggest creating a <code>Map</code> first, so that you can access a trip by its <code>from</code> property in constant time:</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 sortByLinked(trips, origin = \"JFK\") {\n const map = new Map(trips.map(trip => [trip.from, trip]));\n const result = [];\n for (let trip; trip = map.get(origin); origin = trip.to) {\n result.push(trip);\n map.delete(origin);\n }\n return result;\n}\n\nconst trips = [{from: \"DEN\",to: \"JFK\"},{from: \"SEA\",to: \"DEN\"},{from: 'JFK', to: 'SEA'}];\nconst sorted = sortByLinked(trips, \"JFK\");\nconsole.log(sorted);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T14:54:44.993",
"Id": "420561",
"Score": "0",
"body": "Interesting. It doesn't work with cycles, though, does it? e.g. `[{from: \"JFK\",to: \"XXX\"},{from: \"XXX\",to: \"YYY\"},{from: \"DEN\",to: \"JFK\"},{from: \"SEA\",to: \"DEN\"},{from: 'JFK', to: 'SEA'}]`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T15:13:42.057",
"Id": "420562",
"Score": "0",
"body": "Indeed, it is not expecting multiple trip objects with the same `from` property. That would need a more comprehensive tree traversal."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T22:42:47.097",
"Id": "217354",
"ParentId": "217351",
"Score": "6"
}
},
{
"body": "<h2>Code style</h2>\n<ul>\n<li><p>Use constants for variables that do not change. Eg <code>const sortedArray = [];</code></p>\n</li>\n<li><p>Don't include the type in the name, Eg <code>const sortedArray = [];</code> can be Eg <code>const sorted = [];</code></p>\n</li>\n<li><p>The default parameter in this case seams inappropriate as it is likely that <code>"JFK"</code> is not an origin in all calls to this function. If no origin is given one could assume that the first item in trips contains the origin. <code>function sortByLinked(trips, origin = trips[0].from) {</code> which will throw an error if trips is empty so the function should not be called with an empty trips array if you don't pass the <code>from</code> parameter.</p>\n<p>However in this example best to leave the default as <code>undefined</code> if not passed as that will return an empty array which is more fitting the input parameters.</p>\n</li>\n<li><p>The name <code>sort</code> is inappropriate as in JS it implies that the array be sorted in place, that all items be sorted (may not be possible).</p>\n</li>\n<li><p>You have declared <code>i</code> two times. As a <code>var</code> you should put the declaration at the top of the function and not in the <code>for</code> loop.</p>\n</li>\n<li><p>Rather than use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\" rel=\"noreferrer\"><code>Array.filter</code></a> you can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find\" rel=\"noreferrer\"><code>Array.find</code></a>. It will find the first instance.</p>\n</li>\n<li><p>Using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of\" rel=\"noreferrer\"><code>for...of</code></a> rather than <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for\" rel=\"noreferrer\"><code>for(;;)</code></a> reduces the code complexity.</p>\n</li>\n<li><p>No point continuing the search inside the for loops when you have found a match. Use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break\" rel=\"noreferrer\"><code>break</code></a> token to stop a loop early</p>\n</li>\n<li><p>Put a space between <code>if</code> and <code>(</code></p>\n</li>\n<li><p>Don't forget to add the <code>;</code> where appropriate. It is missing from the call <code>sortByLinked(trips)</code></p>\n</li>\n<li><p>You call the origin <code>origin</code> and <code>from</code> this can get confusing. Keep the naming unambiguous. As the trip items use <code>from</code> then that would be the better name for the second input argument.</p>\n</li>\n</ul>\n<p>Using the above points to modify your code we get</p>\n<pre><code>function tripFrom(trips, from) {\n const sorted = [];\n const first = trips.find(trip => trip.from === from);\n sorted.push(first);\n\n for (const trip of trips) {\n if (first.to === trip.from) {\n sorted.push(trip);\n break;\n }\n }\n for (const trip of trips) {\n if (sorted[sorted.length - 1].to === trip.from) {\n sorted.push(trips);\n break;\n }\n }\n return sorted;\n}\n\nsortByLinked(trips, "JFK");\n</code></pre>\n<p>This is still not a good solution. Its not at all <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"noreferrer\">DRY (don't repeat yourself)</a> and is hard coded to a single use case.</p>\n<h2>Improving the function.</h2>\n<p>It can all be done within a single loop and work for any length array.</p>\n<p>To create the function we must add some constraints on the array <code>trips</code> and what to do when we encounter any problems.</p>\n<ol>\n<li>That the array <code>trips</code> contains objects that each have the property <code>from</code> and <code>to</code> that are correctly formatted static strings. The resulting array is erroneous or indeterminate if not so.</li>\n<li>That the array does not contain circular trips shorter than the array length.</li>\n<li>That a complete trip length is no longer than the array, or when a matching <code>trip.to</code> can not be found. The returned array can be 0 to <code>trips.length</code> in size.</li>\n<li>Locations are case sensitive.</li>\n<li>If there is more than one matching <code>trip.from</code> it is assumed that the first match in trips is the correct one. (It would be interesting to extract the longest possible trip from? or the shortest trip that returns to the origin?)</li>\n</ol>\n<h2>Example</h2>\n<pre><code>function tripFrom(trips, from) {\n const result = [];\n while (result.length < trips.length) {\n const trip = trips.find(trip => trip.from === from);\n if (!trip) { break }\n from = trip.to;\n result.push(trip);\n }\n return result;\n}\ntripFrom(trips, "JFK");\n</code></pre>\n<p>Or if it is known that the trip is the same length as the input array.</p>\n<pre><code>function tripFrom(trips, from) {\n const res = [];\n while (res.length < trips.length) {\n from = (res[res.length] = trips.find(trip => trip.from === from)).to;\n }\n return res;\n}\ntripFrom(trips, "JFK");\n</code></pre>\n<p>It is unclear if you want the array sorted in place. If that is a requirement then the above version can be modified to do that by simply copying the results array <code>res</code> to the <code>trips</code> array. You can empty an array by setting its length to zero. The <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"noreferrer\">spread <code>...</code> operator</a> in this case spreads the array items over the functions arguments <code>trips.push(...res)</code> thus pushing all the items to the array.</p>\n<pre><code>function tripFrom(trips, from) {\n const res = [];\n while (res.length < trips.length) {\n from = (res[res.length] = trips.find(trip => trip.from === from)).to;\n }\n trips.length = 0; \n trips.push(...res);\n return trips;\n}\ntripFrom(trips, "JFK");\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T17:20:05.977",
"Id": "420573",
"Score": "0",
"body": "It's common practice to avoid using braces in inline if-statements (your first example). Also, you make a comment about a missing semicolon and I'd like to point out, just for the sake of having options, that completely getting rid of semicolons is a growing practice since it generally looks nicer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T18:41:36.810",
"Id": "420586",
"Score": "0",
"body": "@Adam It may be a common practice to not delimit single line statement blocks, but that does not make it a good practice.Consistency is the most important part of good style. If you use semicolon then use them, not just sometimes. Generally I advice that if you are not going to use them then you should know every case where automatic insertion will not happen but is required to mark the end of line. Eg \"(()=>{});\\n()\" is not the same as \"(()=>{})\\n()\" (as string to show new line location)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T19:30:33.260",
"Id": "420590",
"Score": "0",
"body": "Right. I'm not saying he shouldn't use a semicolon in that specific spot. I'm just making it known that completely getting rid of semicolon delimiters is a very common practice nowadays."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T02:28:03.720",
"Id": "217365",
"ParentId": "217351",
"Score": "8"
}
},
{
"body": "<p>You could also solve the problem by introducing an object <code>mo</code> (as a makeshift associative array) like shown in the following example</p>\n\n<pre><code>const trav=[{from:\"bos\",to:\"sfo\"},{from:\"jer\",to:\"jfk\"},{from:\"zur\",to:\"brm\"},{from:\"haj\",to:\"cdg\"},{from:\"pma\",to:\"mlg\"},{from:\"sfo\",to:\"zur\"},\n {from:\"cdg\",to:\"hav\"},{from:\"jfk\",to:\"haj\"},{from:\"man\",to:\"cdg\"},\n {from:\"mlg\",to:\"jer\"},{from:\"brm\",to:\"pma\"},{from:\"hav\",to:\"bos\"}],\n mo={},srt=[];\nvar fr='jfk',v,n=20;\ntrav.forEach(v=>mo[v.from]=v);\nwhile (n--&&(v=mo[fr])){srt.push(v);fr=v.to;}\nconsole.log(JSON.stringify(srt));\n</code></pre>\n\n<p>The <code>n</code> is a \"safety switch<span class=\"math-container\">`</span> that gets you out when the sequence turns out to be circular (as is the case in my example).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T13:47:36.890",
"Id": "420554",
"Score": "2",
"body": "Welcome to Code Reviews, cars10m. Providing an alternative implementation is interesting and handy on some level, but it doesn't constitute a code review. Was there something so wrong with the original that you needed to rewrite it instead of tweaking it in smaller ways?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T18:57:39.283",
"Id": "423072",
"Score": "0",
"body": "I was offline (in Cuba) for the last 10 days, so please excuse my late reply. I answered this question after it had been posted on stackoverflow. At the time I was at the airport and didn't notice, after the answer was already posted, that the thread had been moved to Code review. I apologise if I haven't kept to the rules of this forum. I wrote my code simply to demonstrate how to solve problem without looping through long lists and making comparisons but instead by finding the elements of a chain directly by addressing properties of an object."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-24T20:03:23.027",
"Id": "423085",
"Score": "0",
"body": "Thanks for reminding me of the context. I missed that this was a migrated question during the review queue."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T10:38:52.203",
"Id": "217383",
"ParentId": "217351",
"Score": "1"
}
},
{
"body": "<p>This problem is related to <a href=\"https://en.wikipedia.org/wiki/Graph_theory\" rel=\"nofollow noreferrer\">graph theory</a>, and you're looking for an <a href=\"https://en.wikipedia.org/wiki/Eulerian_path\" rel=\"nofollow noreferrer\"><em>Eulerian cycle</em></a>:</p>\n\n<blockquote>\n <p>In graph theory, an Eulerian trail (or Eulerian path) is a trail in a\n finite graph which visits every edge exactly once. Similarly, an\n Eulerian circuit or Eulerian cycle is an Eulerian trail which starts\n and ends on the same vertex.</p>\n</blockquote>\n\n<p>You can find a Eulerian cycle if and only if every airport is connected to an even number of airports. To find the cycle in linear time, you can use <a href=\"https://en.wikipedia.org/wiki/Eulerian_path#Hierholzer's_algorithm\" rel=\"nofollow noreferrer\">Hierholzer's algorithm</a>.</p>\n\n<p>You could use a graph library for Javascript, e.g. <a href=\"http://js.cytoscape.org/\" rel=\"nofollow noreferrer\">Cytoscape</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T15:14:21.983",
"Id": "217402",
"ParentId": "217351",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "217365",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T21:54:10.990",
"Id": "217351",
"Score": "9",
"Tags": [
"javascript",
"algorithm",
"sorting",
"graph"
],
"Title": "Sort a list of pairs representing an acyclic, partial automorphism"
} | 217351 |
<p>I'm new to Python, for a school project I created a "fishing simulator". Basically, it is a use of random. I know that my code is repetitive towards the end, but I don't know how to simplify it.</p>
<pre><code>import time
import random
fishing = True
a = b = c = d = e = 0 #define multiple variables as same thing
print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print ("Welcome to Lake Tocowaga")
print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
time.sleep(1)
name = input("What is your name fisherman?")
answer = input("Would you like to go fishing, " + name + "?")
if answer.lower() == "no":
fishing == False
while fishing == True:
time.sleep(1)
answer = input("Throw out your line, or go home?")
if answer == "go home":
fishing = False
er = float(e / (a + b + c + d))
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("Thanks for playing " + name + "!")
print("You caught:", str(a), "cod, ", str(b), "salmon, ", str(c), "shark, ", str(d), "wildfish. \nEfficiency Rate: ", str(er), ".")
else:
t = random.randrange(1, 7)
if t == 1:
a += 1
print("You caught a cod!")
elif t == 2:
b += 1
print("You caught a salmon!")
elif t == 3:
c += 1
print("You caught a shark!")
elif t == 4:
d += 1
print("You caught a wildfish!")
elif t >= 5:
e += 1
print("You caught nothing!")
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T00:01:45.767",
"Id": "420487",
"Score": "6",
"body": "Why did you tag this question as [tag:python-2.x]? I'm not convinced that it would work correctly in Python 2."
}
] | [
{
"body": "<p>A few simple things.</p>\n\n<hr>\n\n<pre><code>a = b = c = d = e = 0\n</code></pre>\n\n<p>This is bad for a couple reasons:</p>\n\n<ul>\n<li><p>Those are all nondescript, overly simple names. There's no way to tell what they represent just by looking at them.</p></li>\n<li><p>You're shoving their declarations/definitions all on one line. This is generally regarded as poor practice. Say I'm looking for where <code>c</code> is defined. It's much easier to find it when I can be sure that I'm looking for exactly <code>c = ...</code> somewhere. It's harder to find though when it's declared half way through a line.</p></li>\n</ul>\n\n<p>In both cases, you're sacrificing readability for brevity. Avoid doing this unless you're code golfing. Readability takes precedence over nearly everything else.</p>\n\n<hr>\n\n<p><code>fishing = True</code> is the third line in your file, yet you don't use it until later. Unless it's a constant, it's a good idea to declare variables near where they're first used. When someone's reading your code and wants to see the definition of <code>fishing</code>, it's more efficient if they only have to look up a line or two instead of needing to scroll to the top of the file.</p>\n\n<hr>\n\n<p><code>while fishing == True:</code> can simply be written as <code>while fishing:</code>.</p>\n\n<hr>\n\n<p>You actually have a bug. <code>fishing == False</code> should be <code>fishing = False</code>.</p>\n\n<hr>\n\n<p><code>if answer.lower() == \"no\":</code> could be written to be more \"tolerant\" (but less exact) by only checking the first letter:</p>\n\n<pre><code>if answer.lower().startswith(\"n\"):\n</code></pre>\n\n<p>Now input like \"nope\" will work as well. Whether or not you want this behavior is another story though. If you had other answers that require \"n\" as the first letter, obviously this would break things. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T06:32:19.837",
"Id": "420631",
"Score": "0",
"body": "About `while fishing`: Suppose, say by user input or something, `fishing` is a string, then `while fishing` would always be `True`. Isn't it safer to write `while fishing is True`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T07:20:33.423",
"Id": "420635",
"Score": "0",
"body": "`if answer.lower()[0] == \"n\":` will break if `answer` is an empty string. Better `if answer.lower().startswith('n'):`. :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T13:13:14.513",
"Id": "420655",
"Score": "0",
"body": "@niko `fishing` is never assigned user input. If it was accidentally, any behavior resulting from that would be incorrect, so I don't think using `is True` would help anything."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T13:13:51.257",
"Id": "420656",
"Score": "0",
"body": "@TrebledJ Yes, good call."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T15:57:25.180",
"Id": "420802",
"Score": "0",
"body": "@niko no, don't do this. Defensive coding is a good paradigm, but it has to do with handling unknown inputs, not elements of your own code. `while fishing` is the correct statement here."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T00:47:48.933",
"Id": "217360",
"ParentId": "217357",
"Score": "25"
}
},
{
"body": "<p>Welcome to CodeReview. It's never too early to develop good coding habits, and reviewing your code is about the best way to do so.</p>\n\n<p>First, congratulations on writing a clean, straightforward program. While you do have some issues (below), they're not major, and your program seems appropriate for its level.</p>\n\n<p>Now, for the issues ;-)</p>\n\n<h1>Use whitespace</h1>\n\n<p>Python requires you to use horizontal whitespace. But you should also use vertical whitespace (aka \"blank lines\") to organize the different parts of your code into <em>paragraphs.</em></p>\n\n<p>This huge block:</p>\n\n<pre><code>import time\nimport random\nfishing = True\na = b = c = d = e = 0 #define multiple variables as same thing\nprint (\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\nprint (\"Welcome to Lake Tocowaga\")\nprint (\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\ntime.sleep(1)\nname = input(\"What is your name fisherman?\")\nanswer = input(\"Would you like to go fishing, \" + name + \"?\")\nif answer.lower() == \"no\":\n fishing == False\nwhile fishing == True: \n</code></pre>\n\n<p>would read better if it were broken up like so:</p>\n\n<pre><code>import time\nimport random\n\nfishing = True\na = b = c = d = e = 0 #define multiple variables as same thing\n\nprint (\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\nprint (\"Welcome to Lake Tocowaga\")\nprint (\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\ntime.sleep(1)\n\nname = input(\"What is your name fisherman?\")\nanswer = input(\"Would you like to go fishing, \" + name + \"?\")\n\nif answer.lower() == \"no\":\n fishing == False\n\nwhile fishing == True: \n</code></pre>\n\n<p>All I did was add a few blank lines, but I was trying to show that \"these things go together\" and \"these things are in sequence but not related\".</p>\n\n<h1>Use meaningful names:</h1>\n\n<p>Which one of these is the shark?</p>\n\n<pre><code>a = b = c = d = e = 0\n</code></pre>\n\n<p>I have no idea. But if you named them appropriately:</p>\n\n<pre><code>cod = shark = wildfish = salmon = nothing = 0\n</code></pre>\n\n<p>I would know for sure!</p>\n\n<h1>Use named constants</h1>\n\n<p>This line appears three times:</p>\n\n<pre><code>print (\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\n</code></pre>\n\n<p>It's probably hard to get the right number of tilde characters, unless you are copy/pasting it. And if you're doing that, it's probably a pain. Instead, create a name for the tildes. By convention, constants are spelled in uppercase. (It's not really a constant, but since constants are spelled in upper case, if you name it in upper case you'll know not to modify it.)</p>\n\n<pre><code>H_LINE = \"~\" * 32\n\nprint(H_LINE)\nprint(\"Welcome to Lake Tocowaga\")\nprint(H_LINE)\n</code></pre>\n\n<h1>Put last things last</h1>\n\n<p>There's a place for everything. And everything should be in its place. The place for printing a summary would be at the bottom.</p>\n\n<p>You had a good idea with your <code>while fishing:</code> loop. But instead of immediately printing the summary when you respond to the user input, just change the variable and let the loop fail, then print the summary at the bottom. It's more \"natural\" (and it makes your loops easier to read!).</p>\n\n<pre><code>while fishing == True: \n time.sleep(1)\n answer = input(\"Throw out your line, or go home?\")\n if answer == \"go home\":\n fishing = False\n er = float(e / (a + b + c + d))\n print(\"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\")\n print(\"Thanks for playing \" + name + \"!\")\n print(\"You caught:\", str(a), \"cod, \", str(b), \"salmon, \", str(c), \"shark, \", str(d), \"wildfish. \\nEfficiency Rate: \", str(er), \".\")\n else:\n ...\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>while fishing == True: \n time.sleep(1)\n answer = input(\"Throw out your line, or go home?\")\n if answer == \"go home\":\n fishing = False\n else:\n ...\n\ner = float(e / (a + b + c + d))\nprint(H_LINE)\nprint(\"Thanks for playing \" + name + \"!\")\nprint(\"You caught:\", str(a), \"cod, \", str(b), \"salmon, \", str(c), \"shark, \", str(d), \"wildfish. \\nEfficiency Rate: \", str(er), \".\")\n</code></pre>\n\n<h1>Let the built-in functions do their job</h1>\n\n<p>You are calling functions that you don't need to call. The result of \"true\" division between integers is a float. You don't need to call <code>float(e / (a + b + c + d))</code>. And if you <em>did</em> need to call it, you'd be calling it too late!</p>\n\n<p>Likewise, <code>print</code> knows how to handle integers and floating point numbers. You don't need to <code>print(..., str(a), ...)</code> when you can just do: <code>print(..., a, ...)</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T01:01:17.537",
"Id": "217363",
"ParentId": "217357",
"Score": "36"
}
},
{
"body": "<p>In addition to the other answers, you can also take advantage of python dictionaries:</p>\n\n<pre><code>a = b = c = d = e = 0\n...\nelse:\n t = random.randrange(1, 7)\n if t == 1:\n a += 1\n print(\"You caught a cod!\")\n elif t == 2:\n b += 1\n print(\"You caught a salmon!\")\n elif t == 3:\n c += 1\n print(\"You caught a shark!\")\n elif t == 4:\n d += 1\n print(\"You caught a wildfish!\")\n elif t >= 5:\n e += 1\n print(\"You caught nothing!\")\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>caught_fish = {\n 'cod': 0,\n 'salmon': 0,\n 'shark': 0,\n 'wildfish': 0,\n 'nothing': 0,\n}\n...\nelse:\n t = random.randrange(1,7)\n # clamp 't' to dictionary size\n if t > len(caught_fish):\n t = len(caught_fish)\n # pick a type of fish from the list of keys of 'caught_fish' using index 't'\n type_of_fish = list(caught_fish)[t - 1]\n # update the dictionary\n caught_fish[type_of_fish] += 1\n # print what type of fish was caught, or if no fish was caught\n article = 'a ' if type_of_fish != 'nothing' else ''\n print(\"You caught {}{}!\".format(article, type_of_fish))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T06:31:56.700",
"Id": "217370",
"ParentId": "217357",
"Score": "6"
}
},
{
"body": "<p>First off I think your use case is a nifty way of getting into Python, and it looks like aside from the bugs that others have already pointed out you'll likely soon be unstoppable.</p>\n\n<p>However, instead of <em>simplifying</em> the code I'd suggest modularizing as well as making use of <code>__doc__</code> strings. It'll make adding features much easier in the future, and if you so choose, allow for making a full application with <a href=\"https://kivy.org/\" rel=\"nofollow noreferrer\"><em><code>Kivy</code></em></a>, <a href=\"https://www.blender.org/\" rel=\"nofollow noreferrer\"><em><code>Blender</code></em></a>, or one of the other many GUI frameworks for Python development. Plus modularizing or abstraction allows for simplifying the intentions/usage.</p>\n\n<blockquote>\n <p>Some notes before diving-in...</p>\n \n <ul>\n <li><p>it's probably a good idea to get a snack and drink; I'm a <em>bit verbose</em> and am about to compress <em>some years</em> of knowledge</p></li>\n <li><p><em><code>__bar__</code></em> when spoken is <a href=\"https://www.urbandictionary.com/define.php?term=dunder\" rel=\"nofollow noreferrer\"><em>\"dunder bar\"</em> </a>, and the <em>phylum</em> that they're classified under are <a href=\"https://rszalski.github.io/magicmethods/\" rel=\"nofollow noreferrer\"><em>\"magic methods\"</em></a></p></li>\n <li><p>what I share is <strong>not</strong> <em>gospel</em> as such, but a collection of tricks I wish someone had shown me when I was getting into Python</p></li>\n </ul>\n \n <p>... okay back on track.</p>\n</blockquote>\n\n<p>Here's some example code inspired by yours that shows some of what I was going on about in your question's comments...</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>#!/usr/bin/env python\n\nimport time\nimport random\n\n\nprint_separator = \"\".join(['_' for _ in range(9)])\n__author__ = \"S0AndS0\"\n\n#\n# Functions\n#\n\ndef question(message):\n \"\"\" Returns response to `message` from user \"\"\"\n return input(\"{message}? \".format(message = message))\n\n\n#\n# Classes\n#\n\nclass Gone_Fishing(dict):\n \"\"\"\n Gone_Fishing is a simple simulation inspired by\n [Python - Fishing Simulator](https://codereview.stackexchange.com/q/217357/197446)\n\n ## Arguments\n\n - `fishes`, `dict`ionary such as `{'cod': {'amount': 0, 'chances': [1, 2]}}`\n - `min_chance`, `int`eger of min number that `random.randint` may generate\n - `max_chance`, `int`eger of max number that `random.randint` may generate\n \"\"\"\n\n def __init__(self, fishes, min_chance = 1, max_chance = 10, **kwargs):\n super(Gone_Fishing, self).__init__(**kwargs)\n self.update(fishes = fishes,\n chances = {'min': min_chance, 'max': max_chance})\n\n @staticmethod\n def keep_fishing(message, expected):\n \"\"\" Return `bool`ean of if `response` to `message` matches `expected` \"\"\"\n response = question(message)\n if not response or not isinstance(response, str):\n return False\n\n return response.lower() == expected\n\n @property\n def dump_cooler(self):\n \"\"\"\n Returns `score`, a `dict`ionary similar to `{'cod': 5, 'tire': 2}`,\n after printing and reseting _`amount`s_ caught\n \"\"\"\n score = {}\n for fish, data in self['fishes'].items():\n if data['amount'] > 0:\n score.update({fish: data['amount']})\n if data['amount'] > 1 and data.get('plural'):\n fish = data['plural']\n\n print(\"{amount} {fish}\".format(**{\n 'fish': fish,\n 'amount': data['amount']}))\n\n data['amount'] = 0\n\n return score\n\n def catch(self, chance):\n \"\"\" Returns `None` or name of `fish` caught based on `chance` \"\"\"\n caught = []\n for fish, data in self['fishes'].items():\n if chance in data['chances']:\n caught.append(fish)\n\n return caught\n\n def main_loop(self):\n \"\"\"\n Asks questions, adds to _cooler_ anything caught, and prints score when finished\n \"\"\"\n first = True\n message = 'Go fishing'\n expected = 'yes'\n while self.keep_fishing(message, expected):\n time.sleep(1)\n if first:\n first = False\n message = \"Keep fishing\"\n\n chances = random.randint(self['chances']['min'], self['chances']['max'])\n caught = self.catch(chances)\n if caught:\n for fish in caught:\n self['fishes'][fish]['amount'] += 1\n fancy_fish = ' '.join(fish.split('_')).title()\n print(\"You caught a {fish}\".format(fish = fancy_fish))\n else:\n print(\"Nothing was caught this time.\")\n\n print(\"{0}\\nThanks for playing\".format(print_separator))\n if True in [x['amount'] > 0 for x in self['fishes'].values()]:\n print(\"You caught\")\n self.dump_cooler\n print(print_separator)\n\n\nif __name__ == '__main__':\n \"\"\"\n This block of code is not executed during import\n and instead is usually run when a file is executed,\n eg. `python gone_fishing.py`, making it a good\n place for simple unit tests and example usage.\n \"\"\"\n gone_fishing = Gone_Fishing(\n fishes = {\n 'cod': {'amount': 0, 'chances': [1]},\n 'salmon': {'amount': 0, 'chances': [5]},\n 'shark': {'amount': 0, 'chances': [9, 10], 'plural': 'sharks'},\n 'wild_fish': {'amount': 0, 'chances': [7], 'plural': 'wild_fishes'},\n 'old_shoe': {'amount': 0, 'chances': [10, 15], 'plural': 'old_shoes'},\n 'tire': {'amount': 0, 'chances': [2, 19], 'plural': 'tires'},\n },\n min_chances = 0,\n max_chances = 20,\n )\n\n gone_fishing.main_loop()\n</code></pre>\n\n<p>... okay there's a <em>bit</em> going on up there, so feel free to dissect it's operation by adding <a href=\"https://stackoverflow.com/a/6980836/2632107\"><em><code>breakpoints</code></em></a> or <em><code>print(something)</code></em> lines.</p>\n\n<hr>\n\n<p>Here's what output of running the above script may look like</p>\n\n<pre><code># python gone_fishing.py\nGo fishing? 'yes'\nYou caught a Wild Fish\nKeep fishing? 'yes'\nNothing was caught this time.\nKeep fishing? 'yes'\nYou caught a Shark\nYou caught a Old Shoe\nKeep fishing? 'yes'\nNothing was caught this time.\n# ... trimmed for brevity\nKeep fishing? 'no'\n_________\nThanks for playing\nYou caught\n2 sharks\n1 tire\n2 wild_fishes\n1 cod\n_________\n</code></pre>\n\n<hr>\n\n<p>Taking it from the top <code>print_separator = \"\".join(['_' for _ in range(9)])</code> is what I like to use when generating strings of repeating characters because it's easy to make something that outputs <code>_-_-_</code> via <code>\"-\".join(['_' for _ in range(3)])</code>.</p>\n\n<blockquote>\n <p>Note from the future; check the comments of this answer for some swell suggestions from @Izaak van Dongen.</p>\n</blockquote>\n\n<hr>\n\n<p>By defining a class that inherits from the built in <code>dict</code>ionary <code>class</code> (that's what the <code>class Gone_Fishing(dict):</code> line did), I'm being a bit lazy as this allows for <em>dumping</em> all saved states via...</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(gone_fishing)\n# -> {'cod': {'amount': 2, 'chances': [1]}, ...}\n</code></pre>\n\n<blockquote>\n <p>... and while I'm on the tangent of getting info back out...</p>\n</blockquote>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(gone_fishing.main_loop.__doc__)\n# Or\n# help(gone_fishing.main_loop)\n</code></pre>\n\n<blockquote>\n <p>... will print the previously mentioned <code>__doc__</code> strings.</p>\n</blockquote>\n\n<p>... and figuring out where you too can avoid re-inventing the wheel is just something that'll get picked up over time. Personally I choose to view it as <em>expanding one's vocabulary</em>, when I discover some built-in that's been waiting to solve some edge-case.</p>\n\n<hr>\n\n<p>The <code>__init__</code> <code>method</code> <em>absorbs</em> three arguments and re-assigns'em with <code>self.update()</code> so that other methods that use the <code>self</code> argument are able to get and/or modify <code>class</code> saved states; more on that latter.</p>\n\n<blockquote>\n <p>Side note; the <code>__init__</code> method is one of many that are called implicitly by preforming some action with an object, eg. <code>__add__</code> is called implicitly by using <code>+</code> between two <code>Objects</code> with a <code>__add__</code> method (side-side note, I'll get into why that was an <em><code>a</code></em> and not an <em><code>an</code></em> in a bit), which is why the following works with lists...</p>\n</blockquote>\n\n<pre class=\"lang-py prettyprint-override\"><code>list_one = [3, 2, 1]\nlist_two = [0, -1, -2]\n\nlist_one + list_two\n# -> [3, 2, 1, 0, -1, -2]\n</code></pre>\n\n<p>That bit with <code>**kwargs</code> stands for <em><code>key word arguments</code></em> which passes things as a <em>bare</em> <code>dict</code>ionary, the other syntax you may run across is <code>*args</code>, which passes things as a <em>bare</em> <code>list</code> of arguments; there be some <em>fanciness</em> that can be done with this syntax that I'll not get into at this point other than saying that context matters. However, you'll find some examples of passing an unwrapped dictionary, such as to <code>format</code> via <code>print(\"{amount} {fish}\".format(**{...}))</code>, which hint hint, is a great way of passing variable parameter names.</p>\n\n<blockquote>\n <p>This is one of those idiomatic things that you can pick-up with some experimentation (and grokking-out others' code bases); it's super powerful so use it often but be kind to your future self too.</p>\n</blockquote>\n\n<p>The bit with <code>super(Gone_Fishing, self).__init__(**kwargs)</code> is what allows the <code>Gone_Fishing</code> <code>class</code> to call <code>dict</code>'s <code>__init__</code> from within it's own <code>__init__</code> <code>method</code>... indeed that was a little convoluted so taking a sec to unpack that...</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class SomeThing(dict):\n def __init__(self, an_argument = None, **kwargs):\n super(SomeThing, self).__init__(**kwargs)\n self.update({'an_argument': an_argument})\n</code></pre>\n\n<p>... it's possible to call <code>self.update()</code> from within <code>SomeThing.___init__</code> without causing confusion of intent, where as to have <code>SomeThing</code> still operate as a <code>dict</code>ionary, eg. assigning <code>something = SomeThing(spam = 'Spam')</code> without causing errors, one should use <code>super(SomeThing, self).__init__(**kwargs)</code> to allow Python to preform it's voodoo with figuring out which inheriting <code>class</code>'ll take responsibility for those arguments.</p>\n\n<blockquote>\n <p>That does mean that one could do <code>class SomeThing(dict, Iterator)</code>, and have that mean something but I'll not get into that here; kinda already covered that specifically on <a href=\"https://math.stackexchange.com/users/657433/s0ands0\"><em>math stack</em></a> in regards to graph modeling and prioritization.</p>\n</blockquote>\n\n<hr>\n\n<p>The <code>@staticmethod</code> and other <a href=\"https://www.geeksforgeeks.org/decorators-in-python/\" rel=\"nofollow noreferrer\"><em><code>decorators</code></em></a> are ways of denoting a special use <code>method</code>. In the case of <code>property</code>s they operate <em>similarly</em> to <code>Object</code> properties, eg...</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>class Test_Obj:\n pass\n\no = Test_Obj()\no.foo = 'Foo'\n\nprint(o.foo)\n# -> Foo\n</code></pre>\n\n<p>... but can only be <em>gotten</em> not <em>set</em>, which makes'em a great place to stash dynamic or semiprivate properties about an <code>Object</code>.</p>\n\n<p>In the case of <code>staticmethod</code>s, they're not passed a reference to <code>self</code> so cannot easily access or modify saved states, but they can be more easily used without initializing so operate similarly to regular functions, eg...</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>responses = []\n\nresponses.append(question(\"Where to\"))\nprint(\"I heard -> {response}\".format(response = responses[-1]))\nfor _ in range(7):\n responses.append(question(\"... are you sure\"))\n print(\"I heard -> {response}\".format(response = responses[-1]))\n\nprint(\"Okay... though...\")\n</code></pre>\n\n<blockquote>\n <p>Note also the various <code>.format()</code> usages are to show ways of <em>future prepping</em> (for perhaps using <code>f strings</code> in the future), as well as making strings somewhat more explicit.</p>\n</blockquote>\n\n<p>Generally I use'em to make the intended usage more explicit but that's not to say that you couldn't get lost in the amount of options available just for decorating a <code>method</code>.</p>\n\n<blockquote>\n <p>Note from the future; as pointed out by @Maarten Fabré I indeed slipped in some superfluous use of the <code>staticmethod</code> decorator, good catch there, and this'll now serve as an example of <em>getting carried away</em> when <code>decorat</code>ing.</p>\n \n <p>Generally I use <code>staticmethod</code>s when I've a class that isn't concerned with it's internal state but isn't large enough to warrant it's own file, very edge case kinda thing, and usually it means that I should probably split'em out into a file that organizes similar functions. Hopefully recent edits now look closer to <em>proper</em> for future readers.</p>\n</blockquote>\n\n<hr>\n\n<p>That bit within the <code>main_loop</code> <code>method</code> with <code>while self.keep_fishing(message, expected)</code>, when unwrapped I think you'll really like, it's returning <code>True</code> or <code>False</code> at the <em>top</em> of every iteration based on asking the user a question and comparing their response with what's expected.</p>\n\n<p>And the bit with <code>if True in [x['amount'] > 0 for x in self['fishes'].values()]</code> is something that <em>masks</em> data using <a href=\"https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions\" rel=\"nofollow noreferrer\"><em><code>list comprehensions</code></em></a>, I'll advise against getting too <em>fancy</em> with'em, and instead try to utilize'em whenever it doesn't make code less readable. Also don't get to attached to such cleverness because <a href=\"http://www.numpy.org/\" rel=\"nofollow noreferrer\"><em><code>numpy</code></em></a>, <a href=\"https://pandas.pydata.org/\" rel=\"nofollow noreferrer\"><em><code>pandas</code></em></a>, or one of the many other libraries, will preform similar tasks far faster.</p>\n\n<hr>\n\n<p>The things happening bellow the <code>if __name__ == '__main__':</code>, aside from the <em>doc string</em> ...</p>\n\n<blockquote>\n <p>Side note for those new to Python; sure you could call'em <em>\"dunder docs\"</em> and those <em>in the know</em> would know what you where saying, but they'd also likely <em>smize</em> at ya too, and saying <em>\"dundar doc string\"</em> if timed when a listener is drinking could have messy consequences... so \"pro-tip\", callem <em>\"doc strings\"</em> to be <em><code>super</code> <code>class</code>y</em> when talking about Python code ;-)</p>\n</blockquote>\n\n<pre class=\"lang-py prettyprint-override\"><code>gone_fishing = Gone_Fishing(fishes = {\n 'cod': {'amount': 0, 'chances': [1]},\n 'salmon': {'amount': 0, 'chances': [2]},\n 'shark': {'amount': 0, 'chances': [3], 'plural': 'sharks'},\n 'wild_fish': {'amount': 0, 'chances': [4], 'plural': 'wild_fishes'},\n 'old_shoe': {'amount': 0, 'chances': [5, 6], 'plural': 'old_shoes'},\n 'tire': {'amount': 0, 'chances': [7, 8], 'plural': 'tires'},\n})\n</code></pre>\n\n<p>... and how the above is parsed could take <em>some words</em> to do a full <em>stack trace</em>, but the gist is that <code>chances</code> is a <code>list</code> that you could even have overlapping integers, eg. a <code>shark</code> who had an <code>old_shoe</code> inside could be...</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>gone_fishing['fishes']['shark']['chances'].append(5)\n</code></pre>\n\n<p>... though without adjustments to other values that would make for a very large shoal of soul hungry sharks.</p>\n\n<blockquote>\n <p>Note from the future; I've made adjustments to the code to enable overlapping values and returning of more than one result; there probably be <em>better</em> ways of doing it but this is also an example of iterative development now.</p>\n</blockquote>\n\n<hr>\n\n<p>When you've figured out how <code>plural</code> is an optional key value pair within a nested dictionary you'll start seeing similar things in other code (at least it's one of those things I've not been unable to unsee), try not to get messy with that trick though, otherwise I think it's self-explanatory as to the intentions of it's usage.</p>\n\n<hr>\n\n<p>The arguments that I didn't assign, <code>min_chance</code> and <code>max_chance</code>, much like the <code>chances</code> with <code>sharks</code> could be updated similarly, eg...</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>gone_fishing['chances']['max'] = 20\n</code></pre>\n\n<p>... though initializing a new trip would look like...</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>another_fishing_trip = Gone_Fishing(\n fishes = {\n 'cod': {'amount': 0, 'chances': [1]},\n 'salmon': {'amount': 0, 'chances': [5]},\n 'shark': {'amount': 0, 'chances': [9, 10], 'plural': 'sharks'},\n 'wild_fish': {'amount': 0, 'chances': [7], 'plural': 'wild_fishes'},\n 'old_shoe': {'amount': 0, 'chances': [10, 15], 'plural': 'old_shoes'},\n 'tire': {'amount': 0, 'chances': [2, 19], 'plural': 'tires'},\n },\n min_chances = 0,\n max_chances = 20,\n)\n</code></pre>\n\n<p>... which serves as an example of something you'd be wise to avoid doing to your own code, swapping words especially isn't going to win any points from a <em>future self</em> or other developers.</p>\n\n<hr>\n\n<p>There's certainly more room for improvement, eg. having <em><code>gone_fishing['fishes'][fish_name]['amount']</code></em> subtracted from, while adding to <em><code>gone_fishing['cooler']</code></em> or similar structure; just for a start. But this was all just to expose quick-n-dirty methods of organizing the problem space with Object Oriented Programing.</p>\n\n<p>Hopefully having code with a bit more abstraction shows ya that going with something that looks a bit more complex can allow for simplifying the usage and future <a href=\"https://en.wikipedia.org/wiki/Feature_creep\" rel=\"nofollow noreferrer\"><em><code>feature creep</code></em></a>. Please keep us posted if ya make something more out of your learning project.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T08:01:17.060",
"Id": "420513",
"Score": "5",
"body": "Welcome to Code Review! I think you did a grat job on your first answer here. Keep it going!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T20:33:54.113",
"Id": "420597",
"Score": "0",
"body": "Thank you! I'm self taught so am glad that this seems to be helping others getting into Python development."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T23:06:29.597",
"Id": "420609",
"Score": "2",
"body": "A lot of great advice, but I would like to note that this: \n `print_separator = \"\".join(['_' for _ in range(9)])`\nCan be shortened to this: \n `print_separator = '_' * 9`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T23:40:16.617",
"Id": "420611",
"Score": "0",
"body": "Quite right @shellster, `print_seperator = '_' * 9` is certainly more readable and quicker to write. I mainly use `print_separator = \"\".join(['_' for _ in range(9)])` because it allows for future fanciness like `_--_--_` via `\"--\".join(['_' for _ in range(3)])`, which I think is worth a few more characters in setup. That said I don't think `print_seperator = lambda sep_main, sep_sub, ammount: \"{sep_sub}\".format(sep_sub = sep_sub).join([sep_main for _ in range(ammount)])` would be worth using except in jest."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T03:20:40.660",
"Id": "420614",
"Score": "1",
"body": "`print(\"{amount} {fish}\".format(**{'fish': fish, 'amount': data['amount']}))` -- why not `print(\"{amount} {fish}\".format(fish=fish, amount=data['amount']))`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T04:12:30.807",
"Id": "420615",
"Score": "0",
"body": "Both are perfectly valid @kevinsa5; for one I sometimes get board with picking one, second the code is a compressed form of lots of various ways of doing things. Combined with code read time far exceeds execution time, I wanted to make sure that there where _plenty-o-goodies_ to find on repeat reads. And more specific to your question `print(\"{amount} {fish}\".format(**{'amount': amount, 'fish': fist}))` is more _explicit_ in regards to what's going on _under the hood_; well if I remember correctly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T17:41:59.350",
"Id": "420697",
"Score": "1",
"body": "@S0AndS0 This is obviously a tiny nitpick, but even then it would probably be better to use one of `\"--\".join('_' * 3)` (limitations: underscore must be single character and builds intermediary string), `\"--\".join('_' for _ in range(3))`, `\"--\".join(itertools.repeat('_', 3))`, depending whether or not you like `itertools`. Constructing an intermediary list in memory here is really not necessary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T18:38:10.580",
"Id": "420700",
"Score": "1",
"body": "Indeed an intermediate `list` is _uncalled for_ in the example use case, and I'm glad that you've pointed out a plethora of other options. That first one is sweet @Izaak van Dongen! And has some interesting outputs when more than one character is used, eg. `\"--\".join('_|' * 3)` `->` `_--|--_--|--_--|`. Especially when compared to the output of your other suggestion `\"--\".join('_|' for _ in range(3))` `->` `_|--_|--_|`... definitely something that I'll keep in mind for fancy dividers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T08:59:12.043",
"Id": "420755",
"Score": "2",
"body": "If you really want to use classes (do you?), I would expect a class for a Fish, a Pond, a Fisher and perhaps a Game. Not like this. All these staticmethods are unneeded on the class, but should go in the module namespace. You make a lot of simple things extra complicated. I suggest you post this piece of code as a seperate question, then you can get some tips on how to improve this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T15:32:40.650",
"Id": "420797",
"Score": "0",
"body": "@Maarten Fabré I was really tempted! Like you'd maybe believe. Selection of fishing poles, different bait shops, `import`ing, all sorts of good stuff... And you're absolutely correct that there's little reason for `staticmethod`s within a `class`; was kinda getting worried that no one had called me out on this earlier. It's something to play around with to better expose avenues of improvement; I'll critique my code far harsher than someone else's. Given a little more time I may `git push` something a bit more thought-out and post a question with cross-linking back to here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-15T16:03:38.017",
"Id": "420803",
"Score": "0",
"body": "This is massively overzealous use of OO. Your descriptions are great, your code is _fine_ -- probably even better than fine -- but this isn't a great use case for object-oriented behavior."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T07:53:01.270",
"Id": "217374",
"ParentId": "217357",
"Score": "24"
}
},
{
"body": "<p>This is another inprovement using a dictionary. Currently all of your data is hardcoded and distributed somewhere in the code. If you wanted to add another fish, you would have to add a variable <code>f</code>, extend <code>random.randint</code> (so the chance for nothing does not decrease) and finally add it to the <code>if</code> conditions and the printing.</p>\n\n<p>That is a lot of work just to add one more fish. Instead I would propose to use a dictionary of possible fishing outcomes and their chance of being caught. You can then use this with <a href=\"https://docs.python.org/3/library/random.html#random.choices\" rel=\"nofollow noreferrer\"><code>random.choices</code></a>, which takes a <code>weights</code> argument detailing the probabilities.</p>\n\n<pre><code>pond = {'cod': 1, 'salmon': 1, 'shark': 1, 'wildfish': 1, 'nothing': 2}\n</code></pre>\n\n<p>The probabilities are here just relative to each other, <code>random.choices</code> normalizes them for you. All fish have the same probability and getting nothing has double the probability of any single fish.</p>\n\n<p>Your loop also does not need the <code>fishing</code> variable at all, just <code>break</code> it when the user is done fishing.</p>\n\n<p>Whenever you need to count something, using <a href=\"https://docs.python.org/3/library/collections.html#collections.Counter\" rel=\"nofollow noreferrer\"><code>collections.Counter</code></a> is probably a good idea. It basically works like a dictionary and has the nice feature that it assumes all elements have a count of zero.</p>\n\n<p>In Python 3.6 a new way to format strings was introduced, the <a href=\"https://realpython.com/python-f-strings/\" rel=\"nofollow noreferrer\"><code>f-string</code></a>.</p>\n\n<pre><code>from collections import Counter\nfrom random import choices\nfrom time import sleep\n\nPOND = {'cod': 1, 'salmon': 1, 'shark': 1, 'wildfish': 1, 'nothing': 2}\n\nname = input(\"What is your name fisherman? \")\n\ncaught = Counter()\nwhile True:\n keep_fishing = input(\"Throw out your line, or go home? \")\n if keep_fishing == \"go home\":\n break\n sleep(1)\n result = choices(list(POND), weights=POND.values(), k=1)[0]\n print(f\"You caught: {result}\")\n caught[result] += 1\n\nprint(f\"\\nThanks for playing, {name}!\")\nprint(\"You caught:\")\nfor fish, n in caught.most_common():\n if fish != \"nothing\":\n print(n, fish)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T20:42:14.507",
"Id": "420709",
"Score": "0",
"body": "For the behavior to be the same as the original code, nothing should have chance 3"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T20:45:13.820",
"Id": "420710",
"Score": "0",
"body": "@Vaelus `randrange` is exclusive of the end, so produces vales from 1 to 6 (inclusive), therefore only 5 and 6 produce `nothing`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-14T23:36:50.100",
"Id": "420724",
"Score": "1",
"body": "Whoops, you're right. Yet another reason to use your method."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T08:48:40.680",
"Id": "217375",
"ParentId": "217357",
"Score": "11"
}
}
] | {
"AcceptedAnswerId": "217363",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-12T23:30:33.913",
"Id": "217357",
"Score": "27",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "Fishing simulator"
} | 217357 |
<p>It's an extremely simply HTTP server in Python using the socket library, and a few others to get the MIME type, etc...</p>
<p>I've also avoided the <code>../../</code> vulnerability, although some of the code in the <code>send_file</code> function seems a bit weak.</p>
<p>It should also be PEP8 compliant, aside from maybe some trailing whitespace in comments.</p>
<pre class="lang-py prettyprint-override"><code>import filetype
import socket
import _thread
class ServerSocket():
''' Recieves connections, parses the request and ships it off to a handler
'''
def __init__(self, address, handler=None, *args, **kwargs):
''' Creates a server socket and defines a handler for the server
'''
self.socket = socket.socket()
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind(address)
self.handler_args = args
self.handler_kwargs = kwargs
if handler:
self.handler = handler # The custom handler
else:
self.handler = Handler # The default handler
def initialise(self, open_connections=5):
''' Initilises the server socket and has it listen for connections
'''
self.socket.listen(open_connections)
self.listen()
def parse(self, data):
''' Splits a packet into
the request,
the headers (which includes the request),
and contents
'''
stringed = str(data, 'utf-8')
split = stringed.split('\r\n\r\n')
headers = split[0]
if len(split) > 1:
content = split[1]
else:
content = []
request = headers.split(' ')[0]
return request, headers, content
def handle(self, client, address):
''' Parses the data and handles the request. It then closes the connection
'''
try:
data = client.recv(1024)
except ConnectionResetError:
if self.handler_kwargs["logging"] is True:
print(f'{address[0]} unexpectedly quit')
client.close()
return
parsed = self.parse(data)
handler = self.handler(self.handler_args, self.handler_kwargs)
handler.handle(client, parsed, address)
client.close()
def listen(self):
''' Listens until a keyboard interrupt and handles each connection in a
new thread
'''
try:
while True:
client_data = self.socket.accept()
if self.handler_kwargs['logging'] is True:
print(f'Connection from {client_data[1][0]}')
_thread.start_new_thread(self.handle, client_data)
except KeyboardInterrupt:
self.socket.close()
class Handler():
''' Handles requests from the Server Socket
'''
def __init__(self, args, kwargs):
self.args = args
self.kwargs = kwargs
def set_status(self, code, message):
''' Used to add a status line:
- 'HTTP/1.1 200 OK' or 'HTTP/1.1 404 Not Found', etc...
'''
self.reply_headers = [f'HTTP/1.0 {code} {message}']
def set_header(self, header, content):
''' Defines a custom header and adds it to the response
'''
self.reply_headers += [f'{header}: {content}']
def response(self, content):
''' Adds to the content of the response
'''
if type(content) == str:
self.reply_content += content.split('\n')
else:
self.reply_content += [content]
def calculate_content_length(self):
''' Calculates the content length and adds it to the header
'''
length = len(self.reply_content) * 2
lengths = [len(line) for line in self.reply_content]
length += sum(lengths)
self.set_header('Content-Length', length)
def get_type(self, file_name):
return filetype.guess('./public/'+file_name)
def extract_file_name(self, file_name=None):
if file_name:
f_name = file_name[1:]
else:
f_name = self.request_status.split(' ')[1][1:]
return f_name
def send_file(self, file_name=None):
if file_name is None:
file_name = self.extract_file_name()
if file_name == '':
file_name = 'index.html'
elif file_name[0] in './':
self.set_status(403, "Forbidden")
self.set_header('Content-Type', 'text/html')
self.reply_content = ['<p>Error 403: Forbidden</p>']
return
try:
with open('./public/'+file_name, 'rb') as file:
file_contents = file.read()
except FileNotFoundError:
self.set_status(404, 'Not Found')
self.set_header('Content-Type', 'text/html')
self.reply_content = ['<p>Error 404: File not found</p>']
return
file_type = self.get_type(file_name)
if file_type is not None:
self.set_header('Content-Type', file_type.MIME)
elif file_name.split('.')[-1] == 'html':
self.set_header('Content-Type', 'text/html')
else:
self.set_header('Content-Type', 'text/txt')
self.response(file_contents)
def get_request_address(self):
return self.address
def parse_headers(self, headers):
t = {}
for header in headers[1:]:
t[header.split(': ')[0]] = header.split(': ')[1]
return t
def reply(self):
''' Assembles the response and sends it to the client
'''
if self.reply_headers[0][0:4] != "HTTP":
self.set_status(200, 'OK')
self.set_header('Content-Type', 'text/html')
self.reply_content = ['<p>Response Status unspecified</p>']
self.calculate_content_length()
message = '\r\n'.join(self.reply_headers)
message += '\r\n\r\n'
try:
message += '\r\n'.join(self.reply_content)
message += '\r\n'
except TypeError:
message = bytes(message, 'utf-8')
message += b'\r\n'.join(self.reply_content)
message += b'\r\n'
try:
if type(message) == str:
self.client.send(bytes(message, 'utf-8'))
else:
self.client.send(message)
except:
pass
def handle(self, client, parsed_data, address):
''' Initialises variables and case-switches the request type to
determine the handler function
'''
self.client = client
self.address = address
self.reply_headers = []
self.reply_content = []
self.headers = True
self.request_status = parsed_data[1].split('\r\n')[0]
request = parsed_data[0]
headers = self.parse_headers(parsed_data[1].split('\r\n'))
contents = parsed_data[2]
if request == "GET":
func = self.get
elif request == "POST":
func = self.post
elif request == "HEAD":
func = self.head
elif request == "PUT":
func = self.put
elif request == "DELETE":
func = self.delete
elif request == "CONNECT":
func = self.connect
elif request == "OPTIONS":
func = self.options
elif request == "TRACE":
func = self.trace
elif request == "PATCH":
func = self.patch
else:
func = self.default
func(headers, contents)
self.reply()
def default(self, headers, contents):
''' If the request is not known, defaults to this
'''
self.set_status(200, 'OK')
self.set_header('Content-Type', 'text/html')
self.response('''<p>Unknown Request Type</p>''')
def get(self, headers, contents):
''' Overwrite to customly handle GET requests
'''
self.set_status(200, 'OK')
self.set_header('Content-Type', 'text/html')
self.response('''<p>Successfully got a GET Request</p>''')
def post(self, headers, contents):
''' Overwrite to customly handle POST requests
'''
self.set_status(200, 'OK')
self.set_header('Content-Type', 'text/html')
self.response('''<p>Successfully got a POST Request</p>''')
def head(self, headers, contents):
''' Overwrite to customly handle HEAD requests
'''
self.set_status(200, 'OK')
self.set_header('Content-Type', 'text/html')
self.response('''<p>Successfully got a HEAD Request</p>''')
def put(self, headers, contents):
''' Overwrite to customly handle PUT requests
'''
self.set_status(200, 'OK')
self.set_header('Content-Type', 'text/html')
self.response('''<p>Successfully got a PUT Request</p>''')
def delete(self, headers, contents):
''' Overwrite to customly handle DELETE requests
'''
self.set_status(200, 'OK')
self.set_header('Content-Type', 'text/html')
self.response('''<p>Successfully got a DELETE Request</p>''')
def connect(self, headers, contents):
''' Overwrite to customly handle CONNECT requests
'''
self.set_status(200, 'OK')
self.set_header('Content-Type', 'text/html')
self.response('''<p>Successfully got a CONNECT Request</p>''')
def options(self, headers, contents):
''' Overwrite to customly handle OPTIONS requests
'''
self.set_status(200, 'OK')
self.set_header('Content-Type', 'text/html')
self.response('''<p>Successfully got an OPTIONS Request</p>''')
def trace(self, headers, contents):
''' Overwrite to customly handle TRACE requests
'''
self.set_status(200, 'OK')
self.set_header('Content-Type', 'text/html')
self.response('''<p>Successfully got a TRACE Request</p>''')
def patch(self, headers, contents):
''' Overwrite to customly handle PATCH requests
'''
self.set_status(200, 'OK')
self.set_header('Content-Type', 'text/html')
self.response('''<p>Successfully got a PATCH Request</p>''')
# =======================================================================
if __name__ == "__main__":
import sys
class CustomHandler(Handler):
def get(self, headers, contents):
self.set_status(200, 'OK')
request_address = self.get_request_address()[0]
file_name = self.extract_file_name()
print(f'{request_address} -> {headers["Host"]}/{file_name}')
self.send_file()
def run():
if len(sys.argv) == 2:
port = int(sys.argv[1])
else:
port = 80
try:
print('Initialising...', end='')
http_server = ServerSocket(
('0.0.0.0', port),
CustomHandler,
logging=True
)
print('Done')
http_server.initialise()
except Exception as e:
print(f'{e}')
run()
</code></pre>
| [] | [
{
"body": "<h1>ServerSocket</h1>\n\n<h2>self.handler</h2>\n\n<p>The handler evaluation in <code>__init__</code> can be accomplished with an <code>or</code> ternary operation. It's clearer to the reader as to what's going on. Also, the name could be changed to <code>HandlerClass</code>, since it represents a <code>class</code> rather than an instance:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> self.HandlerClass = handler or Handler\n</code></pre>\n\n<h2><code>self.handler</code> logging</h2>\n\n<p>The check against <code>handler_kwargs</code> makes the code a bit difficult to follow, since the <code>SocketServer</code> is now in charge of something that arguably the <code>handler</code> should be doing. If the <em>server</em> is who should be doing the logging, then I would leave the logging check out of the <code>handler_kwargs</code> entirely. Store <code>self.logging</code> as a boolean setting on the server instance, and just check against that:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># for traceback handling\nimport traceback \n\nclass SocketServer:\n def __init__(self, address, handler=None, *args, **kwargs):\n ~skipping some code~\n\n # this is so you don't unpack logging from kwargs since\n # it looks like you need it in your handler\n self.logging = kwargs.get('logging', False)\n\n ...\n\n def handle(self):\n try:\n data = client.recv(1024)\n except ConnectionResetError as e:\n # use the more pythonic `if bool` check\n # here, rather than comparing against a singleton\n if self.logging:\n print(f'{address[0]} unexpectedly quit: {e}', file=sys.stderr)\n traceback.print_exception(*sys.exc_info(), file=sys.stderr) \n</code></pre>\n\n<p>I've added a <code>sys.stderr</code> stream to your print statement, and added the exception to your print statement. I've also added a traceback print which points to stderr. </p>\n\n<h2><code>handle</code> Refactor</h2>\n\n<p>The <code>client.close(); return</code> statement can also be refactored using <code>try/except</code>'s <code>else</code> feature and a <code>finally</code> block, since you <em>always</em> want the client to close</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> try:\n data = client.recv(1024)\n except ConnectionResetError as e:\n if self.logging:\n print(f'{address[0]} unexpectedly quit: {e}', file=sys.stderr)\n traceback.print_exception(*sys.exc_info(), file=sys.stderr) \n # this is if no exception fired\n else:\n parsed = self.parse(data)\n handler = self.HandlerClass()\n handler.handle(client, parsed, address)\n # this will always execute\n finally:\n client.close()\n</code></pre>\n\n<h2>Convert <code>bytes</code> to <code>str</code></h2>\n\n<h2><code>parse</code></h2>\n\n<p>First, when converting bytes to str, use <code>bytes.decode()</code> rather than <code>str(byte_obj, encoding)</code>. The <code>headers</code> and <code>content</code> evaluation can be handled using argument unpacking, and from there you can use an <code>or</code> expression with <code>any</code> on <code>contents</code> to either take the first result or create an empty list:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> def parse(self, data):\n ''' Splits a packet into\n the request,\n the headers (which includes the request),\n and contents\n '''\n stringed = data.decode().split('\\r\\n\\r\\n')\n\n # The headers and content blocks can be handled also with argument\n # unpacking and a ternary operator on content:\n\n headers, *content = data.decode().split('\\r\\n\\r\\n')\n content = content[0] if content else []\n\n request = headers.split(' ')[0]\n\n return request, headers, content\n</code></pre>\n\n<h1>Handler</h1>\n\n<h2>Adding to lists</h2>\n\n<p>There are lots of cases where you do this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>self.some_list += [some_value]\n</code></pre>\n\n<p>Just use <code>.append(some_value)</code>, it's faster since you don't have to create a list just to add the value to an existing list. For example:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> def set_header(self, header, content):\n ''' Defines a custom header and adds it to the response\n '''\n # this is much quicker, do this instead\n self.reply_headers.append(f'{header}: {content}')\n</code></pre>\n\n<h2>type-checking</h2>\n\n<p>Use <code>isinstance</code> rather than <code>type(object) == some_type</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># This\n def response(self, content):\n ''' Adds to the content of the response\n '''\n if type(content) == str:\n self.reply_content += content.split('\\n')\n else:\n self.reply_content += [content]\n\n# should be this\n def response(self, content):\n if isinstance(content, str):\n self.reply_content.extend(content.split('\\n'))\n else:\n self.reply_content.append(content)\n</code></pre>\n\n<p>Note that I'm also switching the addition of lists to appropriate calls to <code>append</code> and <code>extend</code>. Though, looking through the rest of your code, you only use this against <code>str</code> or <code>bytes</code> types, so I'd refactor to the following:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> def response(self, content):\n # force everything to bytes-type for convenience, that way\n # you never have to worry about TypeErrors later\n content = content if isinstance(content, bytes) else content.encode()\n\n self.reply_content.append(content)\n</code></pre>\n\n<h2>content-length calculation</h2>\n\n<p>Here, you can drop the creation of the <code>lengths</code> list, and just use <code>sum</code> on <code>map</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> def calculate_content_length(self):\n ''' Calculates the content length and adds it to the header\n '''\n length = len(self.reply_content) * 2\n\n # sum will take any iterable, even generators and maps\n # len in map is the function to be applied to each element\n length += sum(map(len, self.reply_content))\n self.set_header('Content-Length', length)\n</code></pre>\n\n<p>It's faster and doesn't build as many objects inside the function</p>\n\n<h1>Magic Numbers</h1>\n\n<p>In your <code>extract_file_name</code> function, you are slicing the file name from the first element, though it's not completely clear why:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> def extract_file_name(self, file_name=None):\n if file_name:\n f_name = file_name[1:]\n else:\n f_name = self.request_status.split(' ')[1][1:]\n return f_name\n</code></pre>\n\n<p>This is usually a code smell and you should include a docstring and/or comments to explain why you slice that way. Otherwise, the index is a \"magic number\" and can be difficult for you or others to maintain later. You also never use the <code>file_name</code> argument at any point when calling this function, so I might just leave it out.</p>\n\n<h2>Sending Files</h2>\n\n<p>Most of the improvements here follow the ones that have been suggested above:</p>\n\n<h3>Ternary Operation or Use <code>or</code> for <code>file_name</code></h3>\n\n<pre class=\"lang-py prettyprint-override\"><code>file_name = file_name or self.extract_file_name()\n\n## or \n\nfile_name = file_name if file_name else self.extract_file_name()\n</code></pre>\n\n<p>The latter mirrors your <code>if</code> statement a bit more</p>\n\n<h3>Checking an empty string</h3>\n\n<p>Use <code>if some_string</code> not <code>if some_string == ''</code>.</p>\n\n<h3>Checking string start and end values</h3>\n\n<p>The <code>str.startswith</code> and <code>str.endswith</code> methods will help here, and they avoid indexing or slicing which can impair readability:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>if file_name.startswith('./'):\n # do something\n\n\nif file_name.endswith('html'):\n # do something\n</code></pre>\n\n<p>The logic in <code>send_file</code> could be cleaned up a bit. First, I think a <code>handle_error</code> method would do nicely to clean up some of the repeated code where you handle exceptions:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> def handle_error(self, code, short_reason, reason):\n \"\"\"\n code: integer error code\n short_reason: string denoting the short error reason\n reason: string denoting the full error reason\n\n example:\n self.handle_error(404, 'Not Found', 'File Not Found')\n \"\"\"\n self.set_status(code, short_reason)\n self.set_header('Content-Type', 'text/html')\n self.reply_content = [f'<p>Error {code}: {reason} </p>'] \n</code></pre>\n\n<p>Next, I think the filename checking can be refactored to make a bit more sense. First, it seems a bit counterintuitive that a path that might start with <code>'.'</code> is forbidden. What about <code>./public/index.html</code>? If you're trying to avoid folder traversal such as paths with <code>.</code> and <code>..</code> in them, it might not be that bad to use a regex. For example, what if I tried to give you a path like `../../root_file.txt'? It would pass your test, even though it will traverse back directories. I would do something like the following:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import re\n~skipping lots of code~\n\n @staticmethod\n def valid_path(path):\n \"\"\"\n Will take any unix-path and check for any '.' and '..' directories\n in it. Example:\n\n import re\n re_path = re.compile('^\\.+$')\n\n some_path = '/root/path/to/../folder/./file.txt'\n public_path = 'public/folder/../../../file.txt'\n\n next(filter(re_path.match, some_path.split('/')))\n # '..'\n\n '/'.join(filter(re_path.match, some_path.split('/')))\n # '..'\n valid_path = '/path/to/file.txt'\n next(filter(re_path.match, valid_path.split('/')))\n StopIteration\n \"\"\"\n path = path.lstrip('.').lstrip('/')\n re_path = re.compile('^\\.+$')\n try:\n match = next(filter(re_path.match, path.split('/')))\n except StopIteration:\n return True\n return False\n</code></pre>\n\n<p>This way you can check if there are backout paths without colliding with something inocuous like <code>./public/file.txt</code>, and you can handle the following <code>FileNotFoundError</code>. Otherwise, you'll get a <code>None</code> on return, and then you can return an <code>AccessDenied</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> def send_file(self, file_name=None):\n ~snip~\n # this is more pythonic than doing\n # if file_name == ''\n file_name = file_name or 'index.html'\n\n # will either be True or False\n if not self.valid_path(file_name):\n # I've added the keywords here for clarity\n self.handle_error(403, short_reason='Forbidden', reason='Forbidden')\n return \n\n try:\n # use and f-string here rather than string\n # concatenation\n with open(f'./public/{file_name}', 'rb') as fh:\n file_contents = file.read()\n except FileNotFoundError:\n self.handle_error(404, short_reason='Not Found', reason='File Not Found')\n return\n\n file_type = self.get_type(file_name)\n if file_type is not None:\n self.set_header('Content-Type', file_type.MIME)\n # use str.endswith here\n elif file_name.endswith('html'):\n self.set_header('Content-Type', 'text/html')\n else:\n self.set_header('Content-Type', 'text/txt')\n\n self.response(file_contents)\n</code></pre>\n\n<h2>Redundant Methods</h2>\n\n<p>The method <code>get_request_address</code> in my opinion doesn't need to be there. Just access <code>self.address</code> wherever you call it.</p>\n\n<h2><code>parse_headers</code></h2>\n\n<p>If it were up to me, I'd make the headers a dictionary from the get-go, but this can be re-factored like so:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> # this can be static since you never access any self attributes\n @staticmethod\n def parse_headers(headers):\n t = {}\n for header in headers[1:]:\n # unpack k and v from one call to split\n k, v = header.split(': ')\n t[k] = v\n return t\n</code></pre>\n\n<p>Or, even more succinctly</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> @staticmethod\n def parse_headers(headers):\n return dict(header.split(': ') for header in headers[1:])\n</code></pre>\n\n<h2><code>reply</code></h2>\n\n<p>Again, I'd force everything to <code>bytes</code>. You try to append to a <code>str</code> (<code>message</code>) with mixed types, which will fail:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> def reply(self):\n ''' Assembles the response and sends it to the client\n '''\n if not self.reply_headers[0].startswith(\"HTTP\"):\n self.set_status(200, 'OK')\n self.set_header('Content-Type', 'text/html')\n self.reply_content = ['<p>Response Status unspecified</p>']\n\n self.calculate_content_length()\n\n # here's how to coerce to bytes on reply_headers\n message = b'\\r\\n'.join(map(str.encode, self.reply_headers))\n message += b'\\r\\n\\r\\n'\n\n\n message += b'\\r\\n'.join(x.encode() if isinstance(x, str) else x for x in self.reply_content))\n message += b'\\r\\n'\n\n # Now you don't have to type-check\n try:\n self.client.send(message)\n except:\n pass\n</code></pre>\n\n<p>Avoiding the type-checking entirely makes your code more streamlined and maintainable. </p>\n\n<p>Last, instead of using <code>pass</code> on an unexpected Exception, I'd raise some sort of <code>500</code>:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> try:\n self.client.send(message)\n except Exception as e:\n traceback.print_exception(*sys.exc_info(), file=sys.stderr)\n self.handle_error(500, 'Server Error', 'Internal Server Error')\n</code></pre>\n\n<p>Then at the very least there's some visibility either by the client or by you that something bad happened.</p>\n\n<h2><code>handle</code></h2>\n\n<p>This is a classic case of don't repeat yourself. Looking at the big block of <code>if</code> statements, your execution times will be slightly worse for a <code>PATCH</code> than a <code>GET</code>. To refactor, I would use a dictionary that binds the names of functions to operations, yielding a constant time lookup:</p>\n\n<pre><code> def __init__(self, ...):\n ~snip~\n self.functions = {\n 'GET': self.get,\n 'POST': self.post,\n 'HEAD': self.head,\n 'PUT': self.put,\n 'DELETE': self.delete,\n 'CONNECT': self.connect,\n 'OPTIONS': self.options,\n 'TRACE': self.trace,\n 'PATCH': self.patch\n }\n\n\n def call_method(self, contents, request_type=None, headers=None):\n headers = headers or {}\n\n headers['Content-Type'] = headers.get('Content-Type', 'text/html')\n\n self.set_status(200, 'OK')\n\n for k, v in headers.items():\n self.set_header(k, v)\n\n func = self.functions.get(request_type.upper() if request_type else '', self.default)\n\n func(headers, contents)\n self.reply()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-07T17:37:54.870",
"Id": "230325",
"ParentId": "217358",
"Score": "9"
}
}
] | {
"AcceptedAnswerId": "230325",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T00:03:19.190",
"Id": "217358",
"Score": "8",
"Tags": [
"python",
"python-3.x",
"http",
"server"
],
"Title": "Basic Python HTTP Server"
} | 217358 |
<h3>Description:</h3>
<ul>
<li>The questions are being showed in the console tap with player's score.</li>
<li>It's questioning by prompt continually until the prompt input gets 'exit'.</li>
<li>If the answer for each question is right then player's scores are counting up.</li>
<li>But, if not then it shows the same question over and over until the answer is right.</li>
</ul>
<pre><code>var Question = function(question,answers,correctAnswer){
this.question = question;
this.answers = answers;
this.correctAnswer = correctAnswer;
}
Question.prototype.score = 0;
Question.prototype.playersAnswer;
Question.prototype.logAll = function(){
console.log(this.question);
for(var i = 0; i < this.answers.length; i++){
console.log(i + " : " + this.answers[i]);
}
}
Question.prototype.askQuestions = function(){
Question.prototype.playersAnswer = prompt(this.question);
}
Question.prototype.checkIfRight = function (){
if(this.correctAnswer === Question.prototype.playersAnswer){
console.log("Correct Answer!");
Question.prototype.score++;
Question.prototype.logScore();
}
else if(Question.prototype.playersAnswer === "exit"){return 0;}
else {
console.log("Wrong! Try again :)");
Question.prototype.logScore();
return 'w';
}
}
Question.prototype.logScore = function(){
console.log("Your Score : " + Question.prototype.score
+ "\n---------------------------------");
}
var q1 = new Question('What is the name of the course\'s teacher?',['John','Baek','Jonas'],'2');
var q2 = new Question('Is JavaScript the coolest language in the world?',['Yes','No'],'0');
var q3 = new Question('What language are you gonna learn about after?',
['C++','C','Java','Python','Node.js'],'4');
var questions = [q1,q2,q3];
function init(){
var n = Math.floor(Math.random() * 3);
questions[n].logAll();
questions[n].askQuestions();
questions[n].checkIfRight();
}
do {
var n = Math.floor(Math.random() * 3);
questions[n].logAll();
questions[n].askQuestions();
while(questions[n].checkIfRight() === 'w'){
questions[n].logAll();
questions[].askQuestions();
};
}
while (q1.playersAnswer !== "exit");
</code></pre>
<p>Can you review it for best coding practices?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T04:40:41.167",
"Id": "420505",
"Score": "0",
"body": "You can instal ESLint in your project, ESLint is a standard used by the biggest companies which use JavaScript. ESLint will throw warnings and errors which will tell you how to format and write your code by the standard, gives you suggestions and links with examples how is wrong and how is right to write your code and format it. You can learn more here: https://eslint.org/\nI hope that helps, my JavaScript improved a lot after I started using the linting feature in all of my projects."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T04:47:32.550",
"Id": "420506",
"Score": "0",
"body": "None of the things you’re changing at runtime on `Question.prototype` belong there. You can just use variables."
}
] | [
{
"body": "<p>In object-oriented design, the key to modelling is to figure out <strong>how your application will respond to <em>messages</em></strong>. Messages can be requests for information, requests to do something, or notifications that something has happened.</p>\n\n<p>In your example, the application could receive a message, \"what is the next question?\" After giving it some thought, you might decide that a <code>Quiz</code> object would be responsible for providing that information, in which case you would need <code>Quiz</code> class with <strong>a method to respond to the message</strong>.</p>\n\n<pre><code>function Quiz() {\n...\n}\n\nQuiz.prototype.nextQuestion = function () {\n...\n};\n</code></pre>\n\n<p>Now, you don't really have any questions yet, so another obvious message that your application will have to handle is, \"add this question with these answer choices and correct answer.\"</p>\n\n<p><strong>DO NOT</strong> simply rush and add a new method to <code>Quiz</code> to handle the new message; instead, you need to repeat the thought process and decide which object is best suited to respond. In this case, again it is a <code>Quiz</code> object because questions are needed to answer the previous message of, \"what is the next question?\" So, you update your <code>Quiz</code> class accordingly. (Along the way you create a <em>structure</em> to represent a question and an index to track the current question, thus enabling you to find the next question.)</p>\n\n<pre><code>function Quiz() {\n this.questions = [];\n this.index = 0;\n}\n\nQuiz.prototype.addQuestion = function (text, choices, answer) {\n this.questions.push(new Question(text, choices, answer)); \n};\n\nQuiz.prototype.nextQuestion = function () {\n if (this.index < this.questions.length)\n return this.questions[this.index++];\n return null;\n};\n\nfunction Question(text, choices, answer) {\n this.text = text;\n this.choices = choices;\n this.answer = answer;\n}\n\n</code></pre>\n\n<p>I will skip messages that your application might have to handle in relation to player management and get to those that will require your objects to collaborate.</p>\n\n<p>Say, your application receives a message, \"the player has answered to this question with this answer.\" Going through the same thought process as before, you decide that the <code>Quiz</code> object will handle that, and you add a new method.</p>\n\n<pre><code>Quiz.prototype.answer = function (player, question, answer) {\n...\n};\n</code></pre>\n\n<p>However, this time, you need to check if the answer is correct as part of responding to that message. But which object can do that? Of course, the <code>Question</code> structure has the knowledge of correct answer, so it becomes its responsibility. <code>Question</code> has just been promoted from a simple structure to a full-blown class that can also respond to messages; in this case, \"is this answer correct?\" Therefore--</p>\n\n<pre><code>Question.prototype.isCorrect = function (answer) {\n return this.answer === answer;\n};\n</code></pre>\n\n<p>And--</p>\n\n<pre><code>Quiz.prototype.answer = function (player, question, answer) {\n if (question.isCorrect(answer)) {\n // score some points for player\n }\n}\n</code></pre>\n\n<p>As you can see, object-oriented design is not just finding classes and adding methods to them. You need to think about the messages and how they are handled; in other words, messages are key--NOT classes, NOT methods.</p>\n\n<p>Good luck!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T10:38:49.717",
"Id": "217382",
"ParentId": "217368",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-13T04:33:59.813",
"Id": "217368",
"Score": "2",
"Tags": [
"javascript",
"object-oriented"
],
"Title": "Player's scoring using JavaScript"
} | 217368 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.