body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>I have a server where shell commands to the supervisor-service must be executed by the specific user <code>lx</code>. I have written a bash function that does exactly that.</p>
<pre><code>function supervisor {
if [ `id -nu` != lx ]; then
sudo su - lx -c "supervisor \"\$@\"" -- supervisor "$@"
else
sh -s "$@" <<EOF
supervisor "$@"
EOF
fi
}
</code></pre>
<p>It works, but it's doesn't look clean and I'm not really comfortable with half the things I'm using here.</p>
<p>How can that function be written in a less convoluted way?</p>
| [] | [
{
"body": "<p>The only simpler way to do this I've come up with is just to <code>sudo</code> every time and not worry about whether you're already the right user or not. But overall it seems pretty straight forward and it should work fine as-is. Some other suggestions:</p>\n\n<ul>\n<li>Indent your code with the function. Leaving the heredoc alone is ok.</li>\n<li>Use <code>[[</code> for conditionals. See <a href=\"https://unix.stackexchange.com/a/306115/79839\">https://unix.stackexchange.com/a/306115/79839</a> for more context.</li>\n<li>It is more modern to use <code>$()</code> for subcommands instead of backticks (<code>``</code>). Parenthesis <code>()</code> are also used for creating subshells so the <code>$()</code> is just substituting the result of a subshell.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T15:10:44.293",
"Id": "413865",
"Score": "0",
"body": "I don't think that [unix.se] answer provides any argument that `[[` should be preferred to `[`. I'd argue against using `[[` if that's the only Bashism (which it can be, if we remove the unnecessary `function` keyword). Then we can make it a plain POSIX shell script and let `/bin/sh` execute it (for portability and efficiency)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T15:52:44.570",
"Id": "413868",
"Score": "0",
"body": "The `[[` syntax came from `ksh` and it is a good habit to get into. Maintainability matters more to me than portability to things that don't have `bash` or `ksh`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T16:30:23.640",
"Id": "413872",
"Score": "1",
"body": "In what way do you consider `[[` better than `[`? Most of the time, I find its unusual parsing rules annoying rather than helpful (e.g. variable names expanded without any `$`)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T17:50:57.600",
"Id": "413881",
"Score": "1",
"body": "I still think avoiding the problem of empty variables causing missing argument errors is a good idea. http://www.tothenew.com/blog/foolproof-your-bash-script-some-best-practices/ and https://github.com/progrium/bashstyle agree with me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T12:53:44.903",
"Id": "413974",
"Score": "1",
"body": "Running all commands with sudo won't let me start `supervisor` as `lx`. But it **must** be `lx` to correctly run `supervisor`. That is the reason why I've written that function to start with."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T15:02:03.997",
"Id": "213966",
"ParentId": "213953",
"Score": "3"
}
},
{
"body": "<p>I think it's better to simply give an error if it's invoked as the wrong user (or even better, not provide the function at all, similar to hiding admin programs away from non-root users in <code>/sbin</code> rather than <code>/bin</code>). That allows a user to then consider whether they are typing into the right terminal (and any other issues), and if appropriate, issue their own <code>sudo</code> or <code>fakeroot</code>.</p>\n\n<p>Consider this version (with the single Bashism removed, to make a portable script, and with shellcheck errors addressed):</p>\n\n<pre><code>supervisor() {\n if [ \"$(id -nu)\" != lx ]\n then\n echo \"supervisor: can only be run by user 'lx'\" >&2\n return 1\n fi\n\n command supervisor \"$@\"\n}\n</code></pre>\n\n<p>I removed the use of the pointless inner shell - that just serves to expand arguments a second time (similar to using <code>$*</code> instead of <code>\"$@\"</code>) which probably isn't what you want. Instead, I use the <code>command</code> builtin to make the shell find a non-function version of <code>supervisor</code>.</p>\n\n<hr>\n\n<p>If you really must invoke <code>sudo</code> from within the script, then we can simplify a bit. If users are allowed to <code>sudo</code> an arbitrary command (which they should be able to, if they can <code>sudo su</code>), then we can make the function invoke it like this:</p>\n\n<pre><code>sudo -u lx -- supervisor \"$@\"\n</code></pre>\n\n<p>That seems cleaner than creating a shell and funnelling arguments through it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T12:49:50.620",
"Id": "413970",
"Score": "1",
"body": "- I need to open a inner shell on **that** system because: I only get all the necessary environement variables to run supervisor when a shell is started."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T12:51:04.783",
"Id": "413971",
"Score": "0",
"body": "- I switch to lx for our users, because I don't want to bother them when it's clearly unnecessary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T12:22:23.597",
"Id": "414268",
"Score": "0",
"body": "If you really, really need an inner shell (because you can't set the environment variables any other way - but why not?), then you'd want to quote the script you're providing - i.e. `<<'EOF'` instead of `<<EOF`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T23:26:58.573",
"Id": "414362",
"Score": "0",
"body": "what difference does it make if I put `<<'EOF'` instead of `<<EOF`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T08:07:23.297",
"Id": "414382",
"Score": "1",
"body": "[If any part of *word* is quoted, ... the here-document lines shall not be expanded. ((Otherwise)), all lines of the here-document shall be expanded for parameter expansion, command substitution, and arithmetic expansion](http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_07_04). We need the here-document to be preserved as we wrote it, for the inner shell to perform expansions."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T15:29:12.840",
"Id": "213969",
"ParentId": "213953",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T12:00:30.313",
"Id": "213953",
"Score": "3",
"Tags": [
"bash"
],
"Title": "Bash - Passing arguments with \"$@\" to either 'sudo su' or 'sh'"
} | 213953 |
<p>I've made a simple website from scratch using HTML and CSS, for practice purposes only. I got the website to look the way I want but I would appreciate some feedback on the code, especially the CSS feels quite hacky to me.</p>
<p>The HTML file index.html</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-115442650-1"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-115442650-1');
</script>
<title>Joos Korstanje Data Science</title>
<meta charset="utf-8">
<link rel="stylesheet" href="main.css">
</head>
<body>
<header class="header">
<nav>
<ul class="header-nav">
<li><a href="/" class="logo">
<img src="jkconsultancy4.png" alt="Joos Korstanje Logo" >
</a></li>
<li><a href="/">Home</a></li>
<li><a href="/projects.html">Projects</a></li>
<li><a href="https://www.linkedin.com/in/jooskorstanje/">About me</a></li>
<li><a href="https://www.linkedin.com/in/jooskorstanje/">Contact</a></li>
<li>
<ul class="socials">
<li><a href="https://www.linkedin.com/in/jooskorstanje/" >Linkedin</a></li>
<li><a href="https://www.malt.fr/profile/jooskorstanje" >Malt</a></li>
<li><a href="https://github.com/jooskorstanje" >Github</a></li>
<li><a href="https://stackoverflow.com/users/8639281/joos-korstanje" >Stackoverflow</a></li>
</ul>
</li>
</ul>
</nav>
</header>
<div class="hero">
<img src="businessmannew6.png" alt="Data Science Businessman" >
<div class="herotext">
<p>JOOS KORSTANJE DATA SCIENCE</p>
<p>Machine Learning Solutions | Data Strategy</p>
<p>Statistical Methods | Training and Education</p>
</div>
<p class="scroll-down-text">Scroll down for more</p>
</div>
<div class= "buttons-wrapper">
<div class="button left">
<a href="/projects.html#machinelearning">
<img src="lightbulb brain.png" alt="Machine Learning Solutions">
</a>
</div>
<div class="button right">
<a href="/projects.html#trainingandeducation">
<img src="lightbulb educate.png" alt="Training and Education">
</a>
</div>
<div class="button middle">
<a class="button" href="/projects.html#datastrategy">
<img src="lightbulb dollar.png" alt="Data Strategy">
</a>
</div>
</div>
<div class= "title-wrapper">
<div class="title left">
<a href="/projects.html#machinelearning">Machine Learning Solutions</a>
</div>
<div class="title right">
<a href="/projects.html#trainingandeducation">Training and Education</a>
</div>
<div class="title middle">
<a href="/projects.html#datastrategy">Data Strategy</a>
</div>
</div>
<div class="footer">
<img src="jkconsultancy4.png" alt="Joos Korstanje Logo" >
<p>Joos Korstanje, Data Scientist</p>
<p><a href="https://www.google.com/maps/place/Île-de-France/">Serris, Ile de France, France</a></p>
<p>Don't hesitate to send me a message or add me on <a href="https://www.linkedin.com/in/jooskorstanje/">LinkedIn</a> !.</p>
<p>Credits: Lightbulb icon made by and adapted from Freepik from www.flaticon.com</p>
</div>
</body>
</html>
</code></pre>
<p>The CSS file :</p>
<pre><code>html, body {
padding: 0;
margin: 0;
background-color: #fff;
}
.header {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
background-color: #000;
color: #000;
height: 50px;
position: fixed;
width: 100%;
z-index: 20;
}
.header-nav {
position: relative;
left: -50px;
}
.header-nav > li {
display: inline-block;
padding-left: 0px;
position: relative;
top: -35px;
}
.logo > img {
height:50px;
margin-top: -2px;
margin-left: 0px;
margin-right: -100px;
}
.header-nav a {
color: #fff;
font-size: 0.8rem;
font-weight: bold;
text-decoration: none;
text-transform: uppercase;
padding-left: 50px;
padding-right: 50px;
border-left: 1px solid rgba(255, 255, 255, 0.3);
}
.header-nav a:hover,
.header-nav a:active {
color: #ed6e2f;
}
.header-nav > li:first-child a {
color: #ed6e2f;
position: relative;
top: 20px;
padding-left: 10px;
border-left: 0px;
}
.header-nav > li:first-child a:hover {
color: #fff;
}
/* SOCIALS STYLES */
.socials {
position: fixed;
right: 1vw;
top: 15px;
}
.socials > li {
display: inline-block;
list-style: none;
padding-left: 0px;
line-height: 0.5;
}
.socials > li > a {
color: #abc;
font-size: 0.5em;
padding: 0px;
margin: 0px;
border-left: 0px;
}
/* HERO STYLES */
.hero > img {
padding-top: 50px;
width: 100%;
}
.herotext {
position: absolute;
top: 150px;
left: 200px;
top: 20%;
left: 15%;
font-family: verdana;
font-size: 15px;
color: #000;
font-weight: bold;
padding: 20px;
border: solid black 1pt;
}
.herotext > p {
margin: 5px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.herotext p:first-child {
font-size: 20px;
}
.scroll-down-text {
margin-top: -100px;
left: 50%;
text-align: center;
font-family: verdana;
font-size: 15px;
}
/* ICON (BUTTON) STYLES */
.buttons-wrapper {
display: inline-block;
height: auto;
padding-top: -15px;
margin-top: -15px;
width: 100%;
}
.button {
height: 180px;
text-align: center;
width: 33.33333%;
margin-top: 150px;
}
.title-wrapper {
display: inline-block;
height: auto;
padding-top: -15px;
margin-top: -15px;
width: 100%;
}
.title {
height: 180px;
text-align: center;
width: 33.33333%;
}
.title a {
color: #000;
font-size: 0.8rem;
font-weight: bold;
text-decoration: none;
text-transform: uppercase;
}
.button img {
height: 150px;
}
.left {
float: left;
display: inline-block;
}
.middle {
display: inline-block;
}
.right {
float: right;
display: inline-block;
}
/* FOOTER STYLES */
.footer {
background-color: #000;
height: 200px;
}
.footer a {
color: #484848;
}
.footer p {
text-align: center;
color: #484848;
font-size: 0.6rem;
}
.footer img {
padding-top: 20px;
margin-left: 47vw;
}
.footer p:first-child {
padding-top: 50px;
}
/* PROJECT STYLES */
.project-block-wrapper {
padding-top: 50px;
width: 100%;
font-family: verdana;
}
.project-block {
padding: 25px 15%;
border-bottom: solid black 1px;
}
.project-block > h2 {
text-align: center;
padding-left: 38px;
padding-top: 50px;
padding-bottom: 25px;
margin-bottom:0;
}
.project-block > ul {
list-style: none;
padding-top: 0px;
margin-top: 0px;
}
.project-block li {
padding-top: 10px;
padding-bottom: 10px;
text-align:justify;
}
.project-block img {
height: 250px;
display: block;
margin-left: auto;
margin-right: auto;
margin-top: 30px;
margin-bottom: 20px;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T05:33:02.907",
"Id": "413934",
"Score": "0",
"body": "Would you mind expanding on what feels ‘hacky’ to you, and why you feel that way. And maybe narrow down what kind of feedback your expecting to get out of this? For example, discussion on accessibility, browser compatibility, SEO etc etc"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T07:56:45.293",
"Id": "413944",
"Score": "0",
"body": "My blocks or divs don’t naturally fall on the right place and I’ve solved that by adding a lot of padding and margin everywhere to make things fit together. I wonder if I missed something in my css that could have avoided all the padding and margin."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T08:03:02.887",
"Id": "413947",
"Score": "0",
"body": "In terms of feedback all points you mention are interesting to me. It’s the first website I made for practice purposes and it would be an interesting lesson to see all points I’ve been missing so far so that I can read more on those topics."
}
] | [
{
"body": "<p>I have looked at your code. I think you got most of the basic concepts of HTML and CSS. But there are a few things you could improve. For example lets look at the button-wrapper. There we have an image with a caption. The first thing you could improve is to represent this in your HTML. Currently the image and the caption are seperated from one another. I would suggest to do something like this in your </p>\n\n<p><strong>HTML</strong></p>\n\n<pre><code><section id=\"services\">\n <div class=\"container\">\n <figure class=\"service-item\">\n <a href=\"\">\n <img src=\"http://placehold.it/200x200\" alt=\"Machine Learing Solutions\">\n <figcaption>\n <h3>Machine Learning Solutions</h3>\n </figcaption>\n </a>\n </figure>\n <figure class=\"service-item\">\n <a href=\"\">\n <img src=\"http://placehold.it/200x200\" alt=\"Training and Education\">\n <figcaption>\n <h3>Training and Education</h3>\n </figcaption>\n </a>\n </figure>\n <figure class=\"service-item\">\n <a href=\"\">\n <img src=\"http://placehold.it/200x200\" alt=\"Data strategy\">\n <figcaption>\n <h3>Data strategy</h3>\n </figcaption>\n </a>\n </figure>\n </div>\n </section>\n</code></pre>\n\n<p><strong>CSS</strong></p>\n\n<pre><code>#services .container{\n display: flex;\n justify-content: space-between;\n}\n\n.service-item{\n text-align: center;\n}\n</code></pre>\n\n<p>To align content in a consistent and responsive way you should make use of a container class. For example like this:</p>\n\n<pre><code>.container{\n max-width: 1440px;\n width: 90%;\n margin: 0 auto;\n}\n</code></pre>\n\n<p>Also you shouldn't use <code>float</code> and instead have a look at the CSS Property <code>display: flex</code>.\nIt helps you to build flexible layouts. For example in your footer you could do something like this:</p>\n\n<p><strong>HTML</strong></p>\n\n<pre><code><footer id=\"footer\">\n <div class=\"container\">\n <img src=\"http://placehold.it/200x50\" alt=\"\">\n </div>\n</footer>\n</code></pre>\n\n<p><strong>CSS</strong></p>\n\n<pre><code>#footer{\n background: #000;\n}\n\n#footer .container{\n display: flex;\n justify-content: flex-end;\n}\n</code></pre>\n\n<p>I would highly recommend that you experiment more with margins. For example you could push the image in the footer completly to the right by declaring <code>margin-left: auto;</code>. You should also have a look at HTML5 Tags like section, figure and figcaption. Keep experimenting and look at other websites and how they do stuff.</p>\n\n<p>I hope this was helpful for you :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-19T12:37:55.120",
"Id": "215746",
"ParentId": "213959",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "215746",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T13:10:07.053",
"Id": "213959",
"Score": "3",
"Tags": [
"html",
"css"
],
"Title": "Simple HTML website with CSS"
} | 213959 |
<p><a href="https://www.codewars.com/kata/total-primes/train/python" rel="noreferrer">Codewars Kata</a>: Given integers <em>a</em> and <em>b</em>, count all primes <em>p</em> where <em>a</em> ≤ <em>p</em> < <em>b</em> and the digits of <em>p</em> are all prime. <em>b</em> may be as large as 10<sup>7</sup>.</p>
<p>To start with, I hardcoded all valid 1903 primes in <span class="math-container">\$[1, 10^7]\$</span> that can be formed from digits <span class="math-container">\$\{2, 3, 5, 7\}\$</span> and stored it in a list. Then I use binary search to locate the indexes corresponding to the given bounds, then return the difference of these indexes + 1, and my code <em>times out</em>. That is frankly baffling to me. Like I can't even coherently theorise why the program would be slow. All the heavy duty computation is handled by the binary search which is logarithmic time, and is called only a few times and on a 1903 element list (Also, the binary search function completes 1000 searches of 200,000 element lists in 228.67s in <a href="https://www.codewars.com/kata/element-equals-its-index/train/python" rel="noreferrer">another kata</a>, so I don't think I implemented it poorly).<br>
<a href="https://i.stack.imgur.com/1USMt.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1USMt.png" alt="enter image description here"></a><a href="https://i.stack.imgur.com/FnUSc.png" rel="noreferrer"><img src="https://i.stack.imgur.com/FnUSc.png" alt="enter image description here"></a></p>
<p><strong>My Code</strong> </p>
<pre><code>def xbinsearch(pred, lst, *extras, type = "min", default = None):
low, hi, best = 0, len(lst)-1, default
while low <= hi:
mid = (low+hi)//2
p = pred(mid, lst, *extras)
if p[0]: #The current element satisfies the given predicate.
if type == "min":
if best == default or lst[mid] < lst[best]: best = mid
hi = mid-1
elif type == "max":
if best == default or lst[mid] > lst[best]: best = mid
low = mid+1
elif p[1] == 1: #For all `x` > `lst[mid]` not `P(x)`.
hi = mid - 1
elif p[1] == -1: #For all `x` < `lst[mid]` not `P(x)`.
low = mid + 1
return best
def pred_a(idx, lst, *extras):
tpl, val = [None, None], lst[idx],
if extras: a, b = extras[0], extras[1]
tpl[0] = a <= val < b
if val > b: tpl[1] = 1
elif val < a: tpl[1] = -1
return tuple(tpl)
def get_total_primes(a, b):
low, hi = xbinsearch(pred_a, primes, a, b), xbinsearch(pred_a, primes, a, b, type="max")
return hi + 1 - low
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T13:52:32.437",
"Id": "413847",
"Score": "0",
"body": "I figured out the problem with this question. It was literally a missing token (well I checked for `>` instead of `>=` in my upper bounds check because I thought it was an inclusive upper bound while it was in reality exclusive. Should I delete my question or answer it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T14:24:40.617",
"Id": "413853",
"Score": "2",
"body": "You can answer it, there are more to improve than a change in comparison operator."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T19:47:18.380",
"Id": "413898",
"Score": "0",
"body": "Note: once you have determined `low`, `high` cannot possibly be before it... therefore only searching `primes[low:]` could be faster!"
}
] | [
{
"body": "<p>Please read <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> and apply its advice; this will make your code look like Python code to others. Mainly, avoid code blocks on the same line as their conditions, and avoid cramming too many assignments on the same line.</p>\n\n<p>You can also make your predicate function return a single value, as the first element of the returned tuple can be computed from the second (mainly <code>p[0]</code> is <code>p[1] is None</code>). You could also use the more common values <code>-1</code>, <code>0</code> and <code>1</code> and add an <code>else</code> clause in your <code>xbinsearch</code> loop to raise an exception. This would have caught the case where <code>val == b</code> in your usage.</p>\n\n<p>Lastly, <a href=\"https://docs.python.org/3/library/bisect.html#module-bisect\" rel=\"nofollow noreferrer\"><code>bisect</code></a> should be the module to reach for when dealing with binary search in Python. In fact, having your list of <code>primes</code> ready, the code should be:</p>\n\n<pre><code>def get_total_primes(a, b):\n low = bisect.bisect_left(primes, a)\n high = bisect.bisect_left(primes, b)\n return high - low\n</code></pre>\n\n<p>And if you ever want to include the upper bound, you can:</p>\n\n<pre><code>def get_total_primes_inclusive(a, b):\n low = bisect.bisect_left(primes, a)\n high = bisect.bisect_right(primes, b)\n return high - low\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T14:39:00.500",
"Id": "213964",
"ParentId": "213960",
"Score": "10"
}
}
] | {
"AcceptedAnswerId": "213964",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T13:27:31.053",
"Id": "213960",
"Score": "6",
"Tags": [
"python",
"beginner",
"programming-challenge",
"time-limit-exceeded",
"primes"
],
"Title": "Counting primes in a range whose digits are all prime"
} | 213960 |
<p>(See the next follow-up <a href="https://codereview.stackexchange.com/questions/262790/a-simple-clusterness-measure-of-data-in-one-dimension-using-java-follow-up">here</a>.)</p>
<p><strong>Problem definition</strong></p>
<p>Given <span class="math-container">\$X = (x_1, \dots, x_n)\$</span> such that <span class="math-container">\$x_1 \leq x_2 \leq \dots \leq x_n \$</span>. Let <span class="math-container">\$x_{\min} = \min X = x_1\$</span>, <span class="math-container">\$x_{\max} = \max X = x_n\$</span> and <span class="math-container">\$r = x_{\max} - x_{\min}\$</span>. Also, let <span class="math-container">\$m = n - 1\$</span>. Finally,
<span class="math-container">$$
\ell = \frac{r}{m}
$$</span>
is the average gap length. The clusterness measure <span class="math-container">\$CM\$</span> of <span class="math-container">\$X\$</span> is given by
<span class="math-container">$$
CM_X = \frac{1}{r} \sum_{i = 1}^m \min(\vert \ell - \Delta_i \vert, \ell),
$$</span>
where <span class="math-container">\$\Delta_i = x_{i + 1} - x_i\$</span> is the length of the <span class="math-container">\$i\$</span>th gap. Assuming <span class="math-container">\$r > 0\$</span>, <span class="math-container">\$CM\$</span> returns a value in range <span class="math-container">\$[0, 1)\$</span> that represents how well the points in <span class="math-container">\$X\$</span> are close to each other, the value of 0 denoting the situation where all the gaps are equal in length. If we define <span class="math-container">\$CM = 1\$</span> in case <span class="math-container">\$r = 0\$</span> (all <span class="math-container">\$x_i\$</span> are equal), the range of <span class="math-container">\$CM\$</span> extends to <span class="math-container">\$[0, 1]\$</span>.</p>
<p><strong>Solution</strong></p>
<pre><code>package net.coderodde.datascience.measures;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* This class implements a method for computing clusterness measure (CM). CM
* asks for a set of points <code>x1, x2, ..., xn</code>, and it returns a
* number within <code>[0, 1]</code>. The
* idea behind CM is that it returns 0 when all the data points are equal and 1
* whenever all adjacent points are equidistant.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Feb 21, 2019)
*/
public class ClusternessMeasure {
public double computeClusternessMeasure(Collection<Double> points) {
List<Double> pointList = new ArrayList<>(points);
Collections.sort(pointList);
double minimumPoint = pointList.get(0);
double maximumPoint = pointList.get(pointList.size() - 1);
double range = maximumPoint - minimumPoint;
if (range == 0.0) {
// Once here, all data points are equal and so CM must be 1.0.
return 1.0;
}
double expectedDifference = range / (points.size() - 1);
double sum = 0.0;
for (int i = 0; i < points.size() - 1; i++) {
double currentDifference = pointList.get(i + 1) - pointList.get(i);
sum += Math.min(Math.abs(expectedDifference - currentDifference),
expectedDifference);
}
return sum / range;
}
public static void main(String[] args) {
ClusternessMeasure cm = new ClusternessMeasure();
// CM = 0.0
System.out.println(
cm.computeClusternessMeasure(
Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0)));
// CM = 1.0
System.out.println(
cm.computeClusternessMeasure(
Arrays.asList(2.0, 2.0, 2.0)));
System.out.println(
cm.computeClusternessMeasure(
Arrays.asList(1.0, 2.0, 3.0, 5.0, 4.0, 6.0, 7.1)));
}
}
</code></pre>
<p><strong>Critique request</strong></p>
<p>Please tell me anything that comes to mind. I am most interested in coding conventions and naming style. Also, would like to hear comments from machine learning perspective.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T14:39:28.787",
"Id": "413857",
"Score": "0",
"body": "Do you have more context: 1. Does the algorithm come from somewhere else, or is this implementation canonical? 2. is the test code only expected usage? if not what is the expected input size? 3. Is it possible that it will be compared to other similar measures?"
}
] | [
{
"body": "<p>In my opinion your code is perfectly fine! I just found some fussy thinks.</p>\n<hr />\n<h1>HTML Comments</h1>\n<p>In Robert C. Martin's book <a href=\"https://www.investigatii.md/uploads/resurse/Clean_Code.pdf#%5B%7B%22num%22%3A1325%2C%22gen%22%3A0%7D%2C%7B%22name%22%3A%22XYZ%22%7D%2C-48%2C671%2C1%5D\" rel=\"nofollow noreferrer\">Clean Code under HTML Comments</a> you can read</p>\n<blockquote>\n<p>HTML in source code comments is an abomination [...]. It makes the comments hard to read in the one place where they should be easy to read — the editor/IDE. If comments are going to be extracted by some tool (like Javadoc) to appear in a Web page, then it should be the responsibility of that tool, and not the programmer, to adorn the comments with appropriate HTML.</p>\n</blockquote>\n<p>In two places you uses the <code><code></code>-tag. Which can be replaced by javadocs <code>{@code}</code></p>\n<p>For example from</p>\n<blockquote>\n<pre class=\"lang-java prettyprint-override\"><code><code>x1, x2, ..., xn</code> \n</code></pre>\n</blockquote>\n<p>to</p>\n<pre class=\"lang-java prettyprint-override\"><code>{@code x1, x2, ..., xn}\n</code></pre>\n<hr />\n<h1>Duplicated Statement</h1>\n<p>The statement <code>points.size() - 1</code> occurs three times inside the method <code>computeClusternessMeasure</code>. Even it is only a <span class=\"math-container\">\\$O(1)\\$</span>-statement it makes it easier to read the variable <code>indexOfLastEntry</code> instead of <code>points.size() - 1</code></p>\n<hr />\n<h1>An Other Argument</h1>\n<p>Currently <code>computeClusternessMeasure</code> takes a <code>Collection</code> but instead you need a <code>List</code>. This "transformation" has nothing to do with the algorithm and a a collection makes additional to that no sense..</p>\n<p>Furthermore you need to <code>sort</code> it..</p>\n<h1>Take a <a href=\"https://www.cs.helsinki.fi/u/luontola/tdd-2009/ext/ObjectCalisthenics.pdf\" rel=\"nofollow noreferrer\">First-Class-Collection</a> as Argument</h1>\n<p>If you want to keep the flexibility you could create a First-Class-Collection.</p>\n<blockquote>\n<p>Any class that contains a collection should contain no other member variables. Each collection gets wrapped in its own class, so now behaviors related to the collection have a home.</p>\n</blockquote>\n<p>The method signature I want to create is <code>double computeClusternessMeasure(SortedMessurementPoints points)</code></p>\n<pre class=\"lang-java prettyprint-override\"><code>public class SortedMessurementPoints {\n\n private List<Double> points;\n \n public SortedMessurementPoints(Collection<Double> points) {\n List<Double> asList = new ArrayList(points);\n Collection.sort(asList )\n this.points = asList;\n }\n\n public double get(int index) {\n return points.get(index);\n }\n\n public int indexOfLastEntry() {\n return points.size() - 1;\n }\n}\n</code></pre>\n<pre class=\"lang-java prettyprint-override\"><code>public double computeClusternessMeasure(SortedMessurementPoints points) {\n double minimumPoint = points.get(0);\n double maximumPoint = points.get(points.indexOfLastEntry());\n double range = maximumPoint - minimumPoint;\n\n if (range == 0.0) {\n // Once here, all data points are equal and so CM must be 1.0.\n return 1.0;\n }\n\n double expectedDifference = range / points.indexOfLastEntry();\n double sum = 0.0;\n\n for (int i = 0; i < points.indexOfLastEntry(); i++) {\n double currentDifference = points.get(i + 1) - points.get(i);\n sum += Math.min(Math.abs(expectedDifference - currentDifference),\n expectedDifference);\n }\n\n return sum / range;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T18:13:37.727",
"Id": "413887",
"Score": "0",
"body": "In my 20+ year career I have never heard the term \"zero based size\". It is quite confusing because the type of indexing doesn't change the size. Might be clearer to use \"indexOfLastEntry\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T18:20:39.337",
"Id": "413891",
"Score": "0",
"body": "@TorbenPutkonen renamed it! Good hint.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T07:56:42.353",
"Id": "479322",
"Score": "0",
"body": "Too bad I can't upvote twice! ^^"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-19T08:12:50.287",
"Id": "479325",
"Score": "0",
"body": "thank you, that motivates me a lot, @coderodde! "
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T15:09:04.490",
"Id": "213967",
"ParentId": "213961",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "213967",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T13:28:52.367",
"Id": "213961",
"Score": "1",
"Tags": [
"java",
"machine-learning",
"numerical-methods"
],
"Title": "A simple clusterness measure of data in one dimension using Java"
} | 213961 |
<p>I need to be able to create an Excel document with multiple tabs for a dataset with multiple results\data tables. I have a stored procedure with 3 selects in them, fairly simple ones pulling data from the sys tables in SQL Server.</p>
<p>Below is my script where I am assuming there will be 5 tables, if there are more then it will be missed and if there are less and then the other tabs will be empty.</p>
<p>What's the best way to loop through the dataset and create the Excel document?</p>
<pre><code>$SQLServer = '.\SQLEXPRESS';
$Database = 'AdventureWorks';
$sqlCommand = "SELECT 'Tables' AS DataSetName, * FROM sys.tables
SELECT 'Columns' AS DataSetName, * FROM sys.columns";
$connectionString = "Server=$SQLServer;Database=$Database;Integrated
Security=true"
$connection = New-Object
System.Data.SqlClient.SqlConnection($connectionString)
$command = New-Object System.Data.Sqlclient.Sqlcommand($sqlCommand,
$connection)
$connection.Open()
$adapter = New-Object System.Data.sqlclient.SqlDataAdapter $command
$dataset = New-Object System.Data.DataSet
$adapter.Fill($dataSet) > null
$connection.Close()
foreach($table in $dataset.Tables)
{
Write-Host $table.TableName
if ($($table.TableName) -eq 'table'){$Table1 = $table}
if ($($table.TableName) -eq 'table1'){$Table2 = $table}
if ($($table.TableName) -eq 'table2'){$Table3 = $table}
if ($($table.TableName) -eq 'table3'){$Table4 = $table}
if ($($table.TableName) -eq 'table4'){$Table5 = $table}
}
$DataToGather = @{
table = {$Table1}
table1 = {$Table2}
table2 = {$Table3}
table3 = {$Table4}
table4 = {$Table5}
}
Export-MultipleExcelSheets -Show -AutoSize 'C:\Temp\Test.xlsx' $DataToGather
$DataToGather.Clear()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T15:08:07.237",
"Id": "413864",
"Score": "1",
"body": "Welcome to Code Review! Can you confirm that the code is complete and that it functions correctly? If so, I recommend that you [edit] to add a summary of the testing (ideally as reproducible unit-test code). If it's not working, it isn't ready for review (see [help/on-topic]) and the question may be deleted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T06:38:48.280",
"Id": "413939",
"Score": "0",
"body": "Thanks a lot @TobySpeight, the code does work but would like a better solution to eliminate the use of fixed tables. Rather want to iterate through the dataset. Ive tried below example by Lot Pings but getting some issues which I will post. Will also update the script so anyone can run it on against their SQL instance."
}
] | [
{
"body": "<p>If the Excel sheet names should retain the original TableNames this could do:<br>\n(can't test myself)<br>\nThe code contains two commented out alternatives.</p>\n\n<pre><code># your code upto $connection.Close() ...\n\n$DataToGather = @{} \nforeach ($table in $dataset.Tables) {\n Write-Host $table.TableName\n Add-Member -InputObject $DataToGather -Name $table.TableName -Value $table \n# Add-Member -InputObject $DataToGather -Name $table.TableName -Value $dataset.Tables['$($table.TableName)']\n# $DataToGather.Add($table.TableName,$table)\n}\n\nExport-MultipleExcelSheets -Path 'C:\\Temp\\Test.xlsx' -InfoMap $DataToGather -Show -AutoSize \n#$DataToGather\n\n$DataToGather.Clear()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T12:56:20.660",
"Id": "413975",
"Score": "0",
"body": "getting the below when running the script with your snippet added. Table\ncmdlet Add-Member at command pipeline position 1\nSupply values for the following parameters:\nMemberType:"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T13:48:35.873",
"Id": "413980",
"Score": "0",
"body": "Try with `-MemberType NoteProperty`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T08:15:26.887",
"Id": "414251",
"Score": "0",
"body": "Getting this now. Invoke-Item : Cannot find path 'C:\\Temp\\Test.xlsx' because it does not exist.\nAt C:\\Program \nFiles\\WindowsPowerShell\\Modules\\ImportExcel\\5.4.4\\ImportExcel.psm1:525 char:17\n+ if ($Show) {Invoke-Item $Path}"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-04T13:55:01.413",
"Id": "415187",
"Score": "0",
"body": "Can't get this to work correctly, still getting the above error."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T10:20:39.473",
"Id": "415287",
"Score": "0",
"body": "Sorry, but without a similar environment I can't test myself."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T14:31:41.713",
"Id": "213963",
"ParentId": "213962",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T13:29:29.277",
"Id": "213962",
"Score": "2",
"Tags": [
"excel",
"powershell"
],
"Title": "ImportExcel for Dataset with Multiple tables"
} | 213962 |
<p>This Python script extracts data from <code>txt</code> files containing raw numerical data, notably the increase average, the relative evolution and the standard deviation of the values, all of these values require a period on which they are calculated, this period is set via the command line.</p>
<pre><code>#! /usr/bin/env python3
import statistics
import sys
if len(sys.argv) != 2:
print("""SYNOPSIS
./%s period
DESCRIPTION
period the number of days defining a period""" % (sys.argv[0]))
exit(1)
increases = []
period = int(sys.argv[1])
values = []
def check_length(array):
if len(array) > period:
array.pop(0)
def mean(data):
"""Return the arithmetic mean of data."""
return round(sum(data) / len(data), 2)
def calculate_g():
increase = 0
try:
increase = (values[-1] * 10000 - values[-2] * 10000) / 10000
except IndexError:
pass
if increase > 0:
increases.append(increase)
else:
increases.append(0)
if len(values) < period + 1:
print("g=nan ", end="")
else:
increases_average = mean(increases[1:])
print("g=%.2f " % (increases_average), end="")
def calculate_r():
if len(values) < period + 1:
print("r=nan% ", end="")
return "nan"
else:
evolution = round((values[period] - values[0]) * 100 / values[0])
print("r=%.0f%% " % (evolution), end="")
return (1, -1)[evolution < 0]
def _ss(data):
"""Return sum of square deviations of sequence data."""
average = mean(data)
ss = sum((x-average)**2 for x in data)
return ss
def stddev():
"""Calculates the population standard deviation by default."""
n = len(values)
if n < period:
print("s=nan", end="")
else:
ss = _ss(values[-(period):])
print("s=%.2f" % (round((ss / period) ** 0.5, 2)), end="")
def main():
line = input()
prev_sign = 0
say = ""
switch = 0
while line != "STOP":
values.append(float(line))
calculate_g()
sign = calculate_r()
stddev()
if sign != "nan":
if sign == prev_sign * -1:
say = " a switch occurs"
switch += 1
else:
say = ""
prev_sign = sign
print("%s" % (say))
check_length(values)
check_length(increases)
line = input()
print("STOP\nGlobal tendency switched %i times" % (switch))
if __name__ == "__main__":
main()
</code></pre>
<p>and here is sample data:</p>
<pre><code>27.7
31.0
32.7
34.7
35.9
37.4
38.2
39.5
40.3
42.2
41.3
40.4
39.8
38.7
36.5
35.7
33.4
29.8
27.5
25.2
24.7
23.1
22.8
22.7
23.6
24.3
24.5
26.7
27.0
27.4
29.8
29.4
31.5
29.6
29.8
28.9
28.7
27.2
25.7
26.0
25.2
21.6
20.3
21.1
20.4
19.8
19.1
19.6
21.2
21.0
21.4
24.0
25.5
25.5
26.4
29.4
32.1
31.4
32.3
35.2
38.3
36.6
38.4
39.9
40.5
39.4
39.0
40.5
42.1
38.7
37.5
38.1
36.5
35.4
STOP
</code></pre>
<p>I'm pretty sure my code isn't that clean since i'm pretty new to Python and I would like to know good practices.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T14:45:11.330",
"Id": "213965",
"Score": "2",
"Tags": [
"python",
"beginner",
"python-3.x",
"statistics"
],
"Title": "Simple data analysis for forecasting"
} | 213965 |
<p>With HTML5 you can add <em>captions</em> to your video using the <code><track /></code> element. However, only <em>vtt</em> files are officialy supported, while the current most populair subtitle format is the well known <em>srt</em> format.</p>
<p>So instead of converting all the <em>srt</em> files to <em>vtt</em> files, I had the idea of writing a script which will do all of this on the fly. Without any manual converting.</p>
<p>Using the script you can add <em>srt</em> files to the <code><track /></code> element like so:</p>
<pre><code><track label="English" kind="subtitles" srclang="en" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/1178475/Fantastic.Beasts.The.Crimes.of.Grindelwald.2018.1080p.WEB-DL.H264.AC3-EVO.srt" default>
</code></pre>
<p>What the script basically does is following</p>
<ul>
<li>Gets the content from the file using a XMLHttpRequest</li>
<li>Converts the srt format to a vtt format</li>
<li>Creates a blob from the vtt string</li>
<li>Creates a file from the blob</li>
<li>Replaces the original <code>src</code> with the generated vtt file</li>
</ul>
<p>The script itself is very simple and small, only 4kb in size. I wonder if I can make the script even smaller and if I wrote the code well.</p>
<pre><code>document.addEventListener("DOMContentLoaded", function () {
/**
* Get all videos
*/
var videoElements = document.getElementsByTagName('video');
/**
* This function converts all srt's to vtt files
*/
function convertSrtToVtt()
{
/**
* Generate an unique identifier
*/
this.id = '_' + Math.random().toString(36).substr(2, 9);
/**
* All tracks assigned to current video element
*/
var tracks = document.querySelectorAll("#" + this.id + " track");
var subtitle = {
data:
{
track: {}
},
/**
* Load the file from url
*
* @param {object} track - DOM <track /> object
*/
load: function(track)
{
subtitle.track = track;
if(subtitle.isSrt(subtitle.track.src))
{
var client = new XMLHttpRequest();
client.open('GET', subtitle.track.src);
client.onreadystatechange = function()
{
subtitle.convert(client.responseText).then(
function (file)
{
/**
* Replace the srt file with the generated vtt file
*/
subtitle.track.src = file
}
);
}
client.send();
}
},
/**
* Converts the SRT string to a VTT formatted string
*
* @param {string} content - SRT string
* @return {object} promise - Returns a promise with the generated file as the return value
*/
convert: function(content)
{
var promise = new Promise(
function (resolve, reject)
{
/**
* Replace all (,) commas with (.) dots. Eg: 00:00:01,144 -> 00:00:01.144
*/
content = content.replace(/(\d+:\d+:\d+)+,(\d+)/g, '$1.$2');
content = "WEBVTT - Generated using SRT2VTT\r\n\r\n" + content;
/**
* Convert content to a file
*/
var blob = new Blob([content], {type: 'text/vtt'});
var file = window.URL.createObjectURL(blob);
resolve(file);
}
);
return promise;
},
isSrt: function(filename)
{
return filename.split('.').pop().toLowerCase() === 'srt' ? true : false;
},
isVTT: function(filename)
{
return filename.split('.').pop().toLowerCase() === 'vtt' ? true : false;
}
}
for(var i = 0;i < tracks.length;i++)
{
subtitle.load(tracks[i]);
}
}
for(var i = 0;i < videoElements.length;i++)
{
videoElements[i].addEventListener('loadstart', convertSrtToVtt);
}
});
</code></pre>
<p><a href="https://codepen.io/richardmauritz/pen/vbPORR?editors=1000" rel="nofollow noreferrer">Working demo on CodePen</a><br>
<a href="https://github.com/redbullzuiper/SRT-Support-for-HTML5-videos/tree/1eebeda797adc83be28e8a7b81810d68780aa91d" rel="nofollow noreferrer">Github repository</a></p>
| [] | [
{
"body": "<h1>Bloated</h1>\n\n<p>You have 104 lines of code, that can easily by made more readable with some simple redunctions. Remove comments, same line open blocks <code>{</code>, and remove empty lines. That reduces the code to 54 lines.</p>\n\n<h2>Review</h2>\n\n<p>I can see you are somewhat new to JS</p>\n\n<h3>Some JS items</h3>\n\n<ul>\n<li>Use <code>const</code> for variables that do not change.</li>\n<li>In JS we put the open block delimiter <code>{</code> on the same line.</li>\n<li>When using vars you should hoist them to the top of the function they are scoped to.</li>\n<li>Use arrow functions for anonymous functions.</li>\n<li><code>window</code> is the default object, you don't need to use it. You don't use it for <code>Blob</code> eg <code>new window.Blob(</code> but next line down you use it for <code>URL</code> Why?</li>\n<li>Use shortest form. eg <code>for(var i = 0;i < tracks.length;i++) {</code> the index is not needed so <code>for(const track of tracks)</code> or <code>tracks.forEach(subtitle.load)</code> would be better;.</li>\n<li>Don't use <code>substr</code> it is on the great list of the depreciated. Use <code>substring</code> or <code>slice</code></li>\n<li>Use function shorthand when declaring object function. Eg <code>load: function(track) {</code> should be <code>load(track) {</code></li>\n</ul>\n\n<h3>Code style and logic</h3>\n\n<ul>\n<li>comment are way over the top and just repeat what is self evident in the code.</li>\n<li>Space between <code>if</code> and <code>(</code></li>\n<li>You don't use the second argument of the promise callback, so why define it?</li>\n<li>Don't use generic names for variables and arguments. <code>new Promise( function (resolve, reject) {</code> has no semantic meaning, something like <code>new Promise(converted => {</code> would be more apt.</li>\n<li>Don't add redundant code <code>return filename.split('.').pop().toLowerCase() === 'srt' ? true : false;</code> is identical to <code>return filename.split('.').pop().toLowerCase() === 'srt';</code></li>\n<li>Why add the two functions <code>isSrt</code> and <code>isVTT</code> to the object. They are generic and can be defined once outside the object (BTW should it be <code>isSrt</code> or <code>isSRT</code> I don't know what it stands for, but if an acronym then it should be uppercase?)</li>\n<li>The random <code>id</code> can produce a string shorter than 7 characters. eg <code>(1/36).toString(36).substr(2, 9)</code> would create <code>\"1\"</code> not <code>\"1000000\"</code></li>\n<li>I do not see the point of creating an random <code>id</code> (There is a definite chance of a clash) when you already have the element you want to query.</li>\n</ul>\n\n<h3>Structure</h3>\n\n<ul>\n<li>Why create an object <code>subtitle</code> when its not needed?</li>\n<li>Why is <code>subtitle: { data: { track: {}}...</code> created. I can find no reference to it.</li>\n<li>You could have used the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch\" rel=\"nofollow noreferrer\"><code>Fetch</code> API</a> rather than <code>XMLHttpRequest</code></li>\n</ul>\n\n<h2>Alternative example.</h2>\n\n<p>A lot of bloat can be removed and the process can thus be viewed in one page, this improves maintainability, readability, and reduces the chance of bugs.</p>\n\n<pre><code>document.addEventListener(\"DOMContentLoaded\", function () {\n const isSrt = name => name.split(\".\").pop().toLowerCase() === \"srt\"; \n const convert = content => new Promise(converted => {\n content = content.replace(/(\\d+:\\d+:\\d+)+,(\\d+)/g, \"$1.$2\");\n content = \"WEBVTT - Generated using SRT2VTT\\r\\n\\r\\n\" + content;\n converted(URL.createObjectURL(new Blob([content], {type: \"text/vtt\"})));\n }); \n for (const vid of document.getElementsByTagName(\"video\")) {\n vid.addEventListener(\"loadstart\", event => {\n const tracks = [...event.target.querySelectorAll(\"track\")];\n tracks.forEach(track => {\n if (isSrt(track.src)) {\n const client = new XMLHttpRequest();\n client.open(\"GET\", track.src);\n client.onreadystatechange = () => {\n convert(client.responseText).then(file => track.src = file);\n };\n client.send();\n }\n });\n }\n }\n});\n</code></pre>\n\n<h2>Update</h2>\n\n<p>To support legacy browsers you should use something like <a href=\"https://babeljs.io/\" rel=\"nofollow noreferrer\">Babel</a>. Please note this will not cover media <code>textTrack</code> support, only javascript</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T22:11:38.717",
"Id": "413913",
"Score": "0",
"body": "Wow, thanks for this realy helpfull review. This review realy helps me understand what I could do better. A few notes to some points you made, but I do understand them. 1) Bloated - I added the comments on purpose so others can see whats going on, I included a minified file which doenst contain all this bloat. 2) In JS we put the open block delimiter { on the same line. - Ah ok, I'm used to it using PHP. So I put them on new lines. Is this realy a bad practice? In production we use minified files anyway?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T22:17:52.620",
"Id": "413914",
"Score": "0",
"body": "I agree with a lot of this advice, but I don't think that it's fair to assume ES6 support, when the original code does not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T22:20:54.200",
"Id": "413915",
"Score": "0",
"body": "@Red The reduction of code size is not for transport (its all zipped anyways) Each line of code increase the chance of a bug, needs additional cognitive effort (we don't read individual characters, but line break force us to do that), can force interruption of thought when you need to scroll. Comments... Others are all coders and do not need comments that reiterate what is self evident in the code, the comment get in the way of readability.. The new line `{` in PHP and C/C++/C# (and like) is something these languages need to get over."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T22:23:41.843",
"Id": "413916",
"Score": "0",
"body": "@200_success he uses Promise in the original. The original code will only run on ES6+"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T22:34:19.787",
"Id": "413920",
"Score": "0",
"body": "Just as an example, [Promises](https://caniuse.com/#feat=promises) are supported in Safari ≥ 7.1 (released Sep 2014), but [arrow functions](https://caniuse.com/#feat=arrow-functions) require Safari ≥ 10 (released Sep 2016). That's a two-year compatibility gap you have introduced."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T22:49:53.290",
"Id": "413924",
"Score": "0",
"body": "@200_success LOL have fixed with update."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T13:27:16.130",
"Id": "413978",
"Score": "0",
"body": "An HTMLCollection has an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator), which means you can use it directly in a for...of loop without converting it to an array. This is also why you can use the spread syntax to convert it in the first place. But it doesn't have forEach, so you can't get around it there, unless you change that to for...of instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T14:40:23.730",
"Id": "413986",
"Score": "0",
"body": "@Kruga Yep, totally agree, I had a forEach on the outer loop then changed my mind in the final edit. forgot to change the array back to an iterator.;"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T21:46:37.343",
"Id": "213990",
"ParentId": "213970",
"Score": "3"
}
},
{
"body": "<p>Clobbering the <code>id</code> attribute of each <code><video></code> element is unexpected and unfair. That could break the page (such as any CSS rules that rely on the original <code>id</code>).</p>\n\n<p>Your huge <code>convertSrtToVtt()</code> definition is placed between the <code>var videoElements</code> definition and the loop that uses those <code>videoElements</code>. That's a huge unnecessary annoyance for readability.</p>\n\n<p>Personally, I find the</p>\n\n<pre><code>/**\n * Multi-line comments\n */\n</code></pre>\n\n<p>to be a hindrance to readability, especially when the comments apply to single statements.</p>\n\n<p>The <code>isVTT</code> function is never used, and should be dropped. (Note that its capitalization is inconsistent with <code>isSrt</code> and <code>convertSrtToVtt</code>.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T22:49:26.610",
"Id": "213995",
"ParentId": "213970",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "213990",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T15:38:09.443",
"Id": "213970",
"Score": "3",
"Tags": [
"javascript",
"html5",
"animation",
"dom",
"video"
],
"Title": "SRT caption support for HTML5's video element"
} | 213970 |
<blockquote>
<p>Given the mapping a = 1, b = 2, ... z = 26, and an encoded message,
count the number of ways it can be decoded.</p>
<p>For example, the message '111' would give 3, since it could be decoded
as 'aaa', 'ka', and 'ak'.</p>
<p>You can assume that the messages are decodable. For example, '001' is
not allowed.</p>
</blockquote>
<pre><code>class DailyCodingProblem7 {
public static void main(String args[]) {
String message = "11111111";
int n=message.length();
Integer[] ways=new Integer[n+1];
int res = solution(message,n,ways);
System.out.println(res);
}
private static int solution(String message,int k,Integer[] ways) {
int n=message.length();
if(k==0)
{
return 1;
}
if((int)message.charAt(n-k)==0)
{
return 0;
}
if(ways[k]!=null)
{
System.out.println(k+" : " +ways[k]);
return ways[k];
}
ways[k]=solution(message,k-1,ways);
if(k>=2 && Integer.valueOf(message.substring(n-k,n-k+2))<26)
ways[k]+=solution(message,k-2,ways);
return ways[k];
}
}
</code></pre>
<p>If you observe the flow, we can notice <code>ways[k]</code> only needs the most recent 2 values this <code>ways[k-1]</code> and <code>ways[k-2]</code>. Should I use a Hashmap or there is a better approach?</p>
<pre><code>1 : 1
2 : 2
3 : 3
4 : 5
5 : 8
6 : 13
34
</code></pre>
| [] | [
{
"body": "<p>You have almost understood the <a href=\"https://en.wikipedia.org/wiki/Divide-and-conquer_algorithm\" rel=\"nofollow noreferrer\">divide and conquer principle</a> of recursion. Your solution is a bit too complex still.</p>\n\n<ol>\n<li>For each mapping that matches the start of the sequence...</li>\n<li>...see how many times the rest of the sequence can be decoded.</li>\n<li>If step 2 returned a number greater than 0, add the value to the sum.</li>\n<li>Return sum.</li>\n</ol>\n\n<p>The only thing you need to pass as parameters in the recursion is the sequence to be decoded and the index from which you start decoding.</p>\n\n<p>As to code style, please read <a href=\"https://www.oracle.com/technetwork/java/codeconvtoc-136057.html\" rel=\"nofollow noreferrer\">Oracles code conventions for Java</a> </p>\n\n<p>Ps. <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#startsWith-java.lang.String-int-\" rel=\"nofollow noreferrer\"><code>String.startsWith(prefix, offset)</code></a> could be your friend right now.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T21:31:12.413",
"Id": "413906",
"Score": "1",
"body": "Note that you do not need a test to add the value to the sum if the value is zero. It's not that expensive that a condition would offset the resulting amount of time used for the add."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T18:01:55.207",
"Id": "213978",
"ParentId": "213972",
"Score": "6"
}
},
{
"body": "<h3>Houston, you have some bugs</h3>\n\n<p>The algorithm counts incorrectly in some cases involving zeros.\nFor example, there's only one way to make \"10\" or \"20\", not 2.</p>\n\n<p>A different problem is the overly strict condition <code><26</code>,\nwhich excludes \"26\" even it can be decoded to <code>z</code>.</p>\n\n<h3>Beware of string slicing</h3>\n\n<p><code>String.substring</code> creates a new string.\nThis could become expensive when repeated often.\nIf you change the logic to work with a <code>char[]</code> instead of a <code>String</code>,\nthen you can check if the first digit is <code>'1'</code>,\nor the first digit is <code>'2'</code> and the second digit is <code><= '6'</code>.</p>\n\n<h3>Unnecessary code</h3>\n\n<p>This condition will never be true:</p>\n\n<blockquote>\n<pre><code>if((int)message.charAt(n-k)==0)\n</code></pre>\n</blockquote>\n\n<p>The characters in the input are in the range of <code>'0'..'9'</code>,\ntherefore their <code>int</code> values are in the range of <code>48..57</code>.</p>\n\n<h3>Unnecessary <code>Integer[]</code></h3>\n\n<p>You could safely replace <code>Integer[]</code> with <code>int[]</code>,\nand use a condition on zero value instead of <code>null</code> value.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T20:56:06.687",
"Id": "213988",
"ParentId": "213972",
"Score": "11"
}
}
] | {
"AcceptedAnswerId": "213988",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T16:13:07.160",
"Id": "213972",
"Score": "12",
"Tags": [
"java",
"algorithm",
"programming-challenge"
],
"Title": "Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded"
} | 213972 |
<h1>Context</h1>
<p>For one of my projects I have to use a library which works similarly to the following code :</p>
<pre><code>enum LibEntry {
Int1, Char1, Float1,
Int2, Char2, Float2
};
union ValueUnion {
int i;
float f;
char c;
};
class Object {};
void getValue(Object*, LibEntry entry, ValueUnion* val) {
//Real code uses the Object pointer of course, this just for the example
switch(entry) {
case LibEntry::Int1:
val->i=1;
break;
case LibEntry::Char1:
val->c='a';
break;
case LibEntry::Float1:
val->f=1.1f;
break;
case LibEntry::Int2:
val->i=2;
break;
case LibEntry::Char2:
val->c='b';
break;
case LibEntry::Float2:
val->f=2.2f;
break;
}
}
</code></pre>
<p>My objective is to wrap it in a class to get rid of the union type, but for that I need to map the <code>LibEntry</code> values to the type returned by <code>getValue()</code>.</p>
<h1>My solution</h1>
<p>I wrote for that two class templates (and copied an implementation of <code>std::type_identity</code> from cppreference since C++20 is not available yet) which gives correct results with my tests. I also encapsulated the <code>LibEntry</code> enum of the library in my own <code>MyEntry</code> enum class (with the same enumerator names for the example)</p>
<pre><code>/********** type_identity **********/
template<typename T>
struct type_identity {
using type = T;
};
/********** TemplateList **********/
// Template declaration, version used for empty lists
template<auto...>
struct TemplateList {
template<auto>
static constexpr bool contains = false;
};
// Specialization for non-empty lists
template<auto head, auto... tail>
struct TemplateList<head, tail...> {
template<auto v>
static constexpr bool contains = (v==head) || TemplateList<tail...>::template contains<v>;
};
/********** ValueToTypeMap **********/
// Template declaration, this version should not be used
template<auto, typename...>
struct ValueToTypeMap {};
// General case : if value is in List (which should be an instance of TemplateList),
// then the member typedef type is ResultType, else discard List and ResultType
template<auto value, typename List, typename ResultType, typename... Else>
struct ValueToTypeMap<value, List, ResultType, Else...> {
using type = typename std::conditional_t<List::template contains<value>,
type_identity<ResultType>,
ValueToTypeMap<value, Else...>
>::type;
};
// Specialization for the last case to check, when no default type is provided
template<auto value, typename List, typename ResultType>
struct ValueToTypeMap<value, List, ResultType> {
static_assert(List::template contains<value>, "Map Error: could not map given value to any type");
using type = ResultType;
};
// Specialization for (optional) default type when value was not found
template<auto value, typename Default>
struct ValueToTypeMap<value, Default> {
using type = Default;
};
/********** The wrapper class **********/
class Foo {
public:
// Encapsulating the library's LibEntry
enum class MyEntry : std::underlying_type_t<LibEntry> {
Int1 = LibEntry::Int1,
Char1 = LibEntry::Char1,
Float1 = LibEntry::Float1,
Int2 = LibEntry::Int2,
Char2 = LibEntry::Char2,
Float2 = LibEntry::Float2
};
private:
Object* obj = nullptr; // Stub member for the library's object type
template<MyEntry entry>
using associatedType =
typename ValueToTypeMap<entry, TemplateList<MyEntry::Int1 , MyEntry::Int2 >, int,
TemplateList<MyEntry::Char1 , MyEntry::Char2 >, char,
TemplateList<MyEntry::Float1, MyEntry::Float2>, float
>::type;
public:
template<MyEntry entry>
associatedType<entry> getEntry() {
using type = associatedType<entry>;
ValueUnion result {0};
getValue(obj, static_cast<LibEntry>(entry), &result);
return reinterpret_cast<const type&>(result);
}
};
/********** My test code **********/
int main()
{
Foo bar;
auto i1 = bar.getEntry<Foo::MyEntry::Int1>();
std::cout << typeid(i1).name() << ' ' << i1 << std::endl; // Output : i 1
auto i2 = bar.getEntry<Foo::MyEntry::Int2>();
std::cout << typeid(i2).name() << ' ' << i2 << std::endl; // Output : i 2
auto c1 = bar.getEntry<Foo::MyEntry::Char1>();
std::cout << typeid(c1).name() << ' ' << c1 << std::endl; // Output : c a
auto c2 = bar.getEntry<Foo::MyEntry::Char2>();
std::cout << typeid(c2).name() << ' ' << c2 << std::endl; // Output : c b
auto f1 = bar.getEntry<Foo::MyEntry::Float1>();
std::cout << typeid(f1).name() << ' ' << f1 << std::endl; // Output : f 1.1
auto f2 = bar.getEntry<Foo::MyEntry::Float2>();
std::cout << typeid(f2).name() << ' ' << f2 << std::endl; // Output : f 2.2
// Outputs are correct for these cases
return 0;
}
</code></pre>
<p>Now I have several question about my solution :</p>
<ul>
<li>Are there any case for which my class templates will not work as intended ?</li>
<li>To avoid checking for which member of <code>ValueUnion</code> I have to return, I instead thought of casting it to the correct <code>type</code> with <code>reinterpret_cast<const type&>(result);</code>, this seems to work with my tests, but I'm not sure whether it will always work or not. Are there any case for which it will fail, or any possible side-effects (assuming the <code>type</code> found is correct) ?</li>
<li>If the value parameter of <code>ValueToTypeMap</code> is not found and no default type is given, I get a compile error from the static_assert, as I intended, though the error message from the compiler is pretty verbose, and the message from the static_assert is buried in many lines of error. Is there any less verbose solution to this ? <strong>Update</strong>: just tested with clang on wandbox, which is a bit less verbose, and also put the static_assert error on the first line. The many lines of error I had originally were with g++ in mingw64. <strong>Update 2</strong>: even with g++ the errors are less verbose now, I'm not sure what I have done which changed that.</li>
<li>Any other suggestion is welcome</li>
</ul>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T16:39:09.770",
"Id": "213973",
"Score": "1",
"Tags": [
"c++",
"template"
],
"Title": "Value-To-Type Map"
} | 213973 |
<ul>
<li><p><strong>Edit:</strong> The goal of this Question was only seeking code review and guidance in learning or tips for improvement. I apologize if that was not clear or aligned properly with the goals of this forum. </p></li>
<li><p><strong>Script Goal:</strong> audit file existence and differences between two red hat Enterprise Linux Servers </p>
<ul>
<li>Place information in sql server tables to use for analysis </li>
<li>Maintain ability to view the diff in a web page
<ul>
<li><strong>Process Steps</strong></li>
<li><em>Set array with Directorys to check</em>
<ul>
<li><em>Set array of file types to look for</em> </li>
<li><em>Build a list of existing files for each Environment</em></li>
</ul></li>
<li><strong>Script will solve the following</strong></li>
<li><em>If the files exist in both servers are they the identical?</em> (md5)*
<ul>
<li><em>If no what is different (Diff)?</em> </li>
<li><em>Does the file contain hard coded values</em> (grep) </li>
</ul></li>
<li><em>View Diff in web page (currently reading text file using into site php)</em> </li>
</ul></li>
</ul></li>
<li><p><strong><em>Code</em></strong></p>
<pre><code>DIR=(/Dir/Durp/DurpaDurp/Scriptdir1 /Dir/Durp/DurpaDurp/Scriptdir2 /Dir/Durp/DurpaDurp/Scriptdir3 )
f_Type=("*.sh" "*.txt" "*.log")
f_Type2=("*.img" "*.rpt" )
for((i=0; i<${#DIR[@]}; i++))
do
echo "CHECKING: ${DIR[$i]}"
cd "${DIR[$i]}"
for((x=0; x<${#f_Type[@]}; x++))
do
echo "FOR FILE TYPE: ${f_Type[$x]}"
find $PWD -type f -name "${f_Type[$x]}" | sed 's/^/ENV1|/'| column -t >> "$filelistENV1"
done
if [[ ${DIR[$i]} == "/Dir/Durp/DurpaDurp/Script3" ]];
then
for((y=0; y<${#f_Type[@]}; y++))
do
echo "FOR FILE TYPE: ${f_Type2[$y]}"
find $PWD -type f -name "${f_Type2[$y]}" | sed 's/^/ENV1|/'| column -t >> "$filelistENV1"
done
fi
done
</code></pre></li>
<li><p>After these files are output to the text files the script will delete the existing data from a staging table in SQL Server 2008 R2 and insert the new data.</p>
<pre><code>for((i=0; i<${#ENV[@]}; i++))
do
sqlcmd -S $_DB_CONN -d $_DB -Q "DELETE FROM ['$_DB']..['$_TABLE'] WHERE ENV = '${ENV[$i]}'";
done
bcp $_DB_CONN.."$_TABLE" in "$filelistENV1" -f "$_SCRIPTDIR/STG.fmt" -e $_ERRDIR/ERROR_STG$(date -d "today" +"%Y%m%d%H%M").txt -S $_DB_CONN -d "$_DB"
</code></pre></li>
<li><p>the format file creates 2 columns </p>
<p><code>AbsoluteFilePath | ENV</code> </p></li>
<li><p>gets a list of files from the database to compare </p></li>
</ul>
<p>` </p>
<pre><code>sqlcmd -S $_DB_CONN -d $_DB -s "|" -h-1 -m -1 -W -i $_SCRIPTDIR/SQL/EXPORT_COMPARE.sql -o $_INPUT/comp_list.txt set NOCOUNT ON;
</code></pre>
<ul>
<li><p>compare the md5sum of the files. </p>
<pre><code>for i in $(cat "$_INPUT/comp_list.txt")
do
export filename=$(basename "$i")
export path=$(dirname "$i")
env1_md5sum=$(md5sum "$i")
env1="${env1_md5sum%% *}"
export tmpdir=("$_TMPDIR$path")
if ssh "$_CONN" stat $path'$filename' \> /dev/null 2\>\&1
then
env2_md5sum=$(ssh $_CONN "cd $path; find -name '$filename' -exec md5sum {} \;")
env2_md5="${env2_md5sum%% *}"
if [[ $env1_md5 == $env2_md5 ]]; then
echo $filename $path >> "$matchingMD5"
else
echo "md5 does not match, getting copy of file"
echo "$i" >> "$no_matchMD5"
mkdir -p $tmpdir
scp $_CONN:$i $tmpdir
fi
fi done
</code></pre></li>
<li><p>run a diff on files that do not match </p>
<pre><code>for x in $(cat "$no_matchMD5")
do
comp_filename=$(basename "$x")
env2file=(/"$ScriptsDir"/tmp"$x")
DIFF=$(diff --ignore-all-space --ignore-blank-lines --brief "$x" "$env2file" &>/dev/null
</code></pre></li>
</ul>
| [] | [
{
"body": "<h3>Performance pitfalls</h3>\n\n<p>Running <code>ssh</code> in a loop tends to be slow. Running it twice for every file in a list is probably extremely slow. There's no easy fix for this. You need to rethink how to solve the problem of matching paths between two systems.</p>\n\n<p>Off the top of my head:</p>\n\n<ol>\n<li>Get the list of paths from both systems, and then try to match those locally. This can be done with one <code>ssh</code> call per system: a major improvement.</li>\n<li>For the list of matched paths, get the md5 sums. Again this can be done with one <code>ssh</code> call per system.</li>\n<li>Compare the hashes, and build a new list of mismatched files.</li>\n<li>For the final comparison of files, you could fetch them one by one to conserve disk space. If the number of remaining files is expected to be small, then one <code>scp</code> call per file might be acceptable. Or if disk space is not an issue, then you could transfer all the files with one call.</li>\n</ol>\n\n<p>A much smaller performance issue is running <code>sed ... | column ...</code> for each file type for each base directory. You could instead make the loop body output only the output of the multiple <code>find</code> calls, and run the <code>sed ...</code> pipeline on the entire loop (writing as <code>done | sed ...</code>).</p>\n\n<h3>Looping over arrays</h3>\n\n<p>Instead of this:</p>\n\n<blockquote>\n<pre><code>for((i=0; i<${#DIR[@]}; i++)) \ndo\n echo \"CHECKING: ${DIR[$i]}\"\n</code></pre>\n</blockquote>\n\n<p>When you don't need the array indexes, just the elements, you can iterate like this:</p>\n\n<pre><code>for dir in \"${DIR[@]}\"\ndo\n echo \"CHECKING: $dir\"\n</code></pre>\n\n<p>Most of the loops in the posted script can be replaced with this simpler, more intuitive style.</p>\n\n<h3>Simple mistakes</h3>\n\n<ul>\n<li>Use <code>.</code> instead of <code>$PWD</code></li>\n<li>Double-quote variables used in command arguments: instead of <code>find $var</code>, write <code>find \"$var\"</code></li>\n<li>Don't <code>export</code> if you don't need to</li>\n<li>Don't create arrays if you need a simple variable: instead of <code>tmpdir=(\"$_TMPDIR$path\")</code> write <code>tmpdir=\"$_TMPDIR$path\"</code></li>\n<li>Strive for simple writing style: instead of <code>env2file=(/\"$ScriptsDir\"/tmp\"$x\")</code>, write <code>env2file=\"$ScriptsDir/tmp$x\"</code></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T19:07:34.043",
"Id": "413895",
"Score": "0",
"body": "Thank you for the feedback, I will clarify and minimize my post."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T12:18:17.617",
"Id": "414056",
"Score": "0",
"body": "I tried to implement all of your suggestions to the best of my ability. It made a huge difference. Thanks again"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T12:37:20.457",
"Id": "414057",
"Score": "0",
"body": "@Maggie You followed the suggestions very well, nicely done! You could post your revised code as a new question, and get more reviews for further tips"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T18:39:15.643",
"Id": "213981",
"ParentId": "213977",
"Score": "2"
}
},
{
"body": "<p>While more work is needed, After implementing some of the suggested improvements the scripts execution time dropped from 13 minutes to about 30 Seconds. That is a massive improvement. (only posting as an answer to show the updated code)</p>\n\n<ul>\n<li>Most Significant Changes\n\n<ul>\n<li>Preforming MD5sum is now done on each server then sent to DB</li>\n<li>fetching files from env2 for comparison is now in one sftp connection using a batchfile. </li>\n</ul></li>\n</ul>\n\n<pre><code>FINDFILES() {\nsqlcmd -S $_DB_CONN -Q \"TRUNCATE TABLE [DASHDB]..[STAGING_TBL]\"\nssh \"$_CONN\" \"$_SHAREDPATH/scripts/findFiles.sh\"\n\nDIR=(\"/durp/durpdurp/scripts/apps\" \"/durp/durpdurp/tests/utilities\" \"/durp/audit/utilities\" \"/work\")\nf_Type=(\"*.sh\" \"*.sql\" \"*.log\" \"*.rpt\" \"*.php\" \"*.html\") \nPatterns=\"patternabc|anotherpattern123|someserver|somepassword\" \n\nfor dir in \"${DIR[@]}\"\ndo\n for x in \"${f_Type[@]}\"\n do \n # using \"$dir to get the Absolute path in the output instead of . printing relative path\n find \"$dir\" -type f -name \"$x\" -exec md5sum {} + | sed 's/^/Q|/'| column -t >> \"$_OUTPUT/md5sum.txt\"\n find \"$dir\" -type f -name \"$x\" | xargs -0 grep --files-with-matches \"$Patterns\" >> \"$_OUTPUT/hardCoded.txt\"\n done\ndone\n\nsed --in-place 's/ /|/g' \"$_OUTPUT/md5sum.txt\"\n# still not sure why quoting $_DB_CONN breaks this line but not sqlcmd\nbcp DASHDB.dbo.STAGING_TBL in \"$_OUTPUT/md5sum.txt\" -S $_DB_CONN -t \"|\" -c -e \"$_ERRDIR/Error$(date -d \"today\" +\"%Y%m%d%H%M\").txt\"\nrm --force \"$_OUTPUT/md5sum.txt\"\n}\n\nFINDFILES\n\nDIFFCHECK(){\n#Gets list of files in both servers with md5 that do not match \nsqlcmd -S \"$_DB_CONN\" -s \"|\" -h-1 -m -1 -W -i \"$_SCRIPTDIR/SQL/EXPORT_NOMD5_MATCH.sql\" -o \"$_OUTPUT/MD5_noMatch_compare.txt\" \n if rm --recursive --force \"${_TMPDIR:?}/\"*; then \n echo \"$_TMPDIR subfolders removed\"\n else\n exit 1\n fi \n\n#Create SFTP file to fetch all files with one connection\nwhile read -r dir; do\n echo \"get $dir $_TMPDIR$dir\" >> \"$_OUTPUT/batchfile.txt\"\n path=$(dirname \"$dir\")\n mkdir --parents \"$_TMPDIR$path\"\ndone < \"$_OUTPUT\"/MD5_noMatch_compare.txt\n\n #Execute Batchfile\n sftp -b \"$_OUTPUT/batchfile.txt\" \"$_CONN\" \n rm --force \"$_OUTPUT/batchfile.txt\"\n\n#narrow the list to compare, ignore white space Diffs \nwhile read -r dir; do\n diff --ignore-all-space --ignore-blank-lines --brief \"$dir\" \"$_TMPDIR$dir\"\n result=$?\n if [[ $result -eq 1 ]]; \n then echo \"$dir\" >> \"$_OUTPUT/diff_files.txt\" \n fi \ndone < \"$_OUTPUT\"/MD5_noMatch_compare.txt\nrm --force \"$_OUTPUT\"/MD5_noMatch_compare.txt\n}\n\nDIFFCHECK\n\nendTime=$(date +%s)\nrunTime=$((endTime - startTime))\necho \"Audit Has Ended: $((runTime / 60)) minutes and $((runTime % 60)) seconds have elapsed.\" >> \"$_OUTPUT/findFilesRun.log\"\n\nexit 0\n<span class=\"math-container\">````</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T12:12:51.777",
"Id": "214111",
"ParentId": "213977",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "213981",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T17:43:30.733",
"Id": "213977",
"Score": "0",
"Tags": [
"performance",
"beginner",
"bash",
"sql-server"
],
"Title": "Bash Script for file auditing, push information to server and be able to view in a web page"
} | 213977 |
<p>Code first, elaboration later:</p>
<pre><code>// Fizzbuzz: 1..100, %3->fizz, %5->buzz, %15->fizzbuzz
// noif: do not use if/switch statements or ternary expressions
// LIMIT must be a power of 10
// WIDTH must be equal to log10(LIMIT)
#include <stdio.h>
#include <string.h>
#define LIMIT 100
#define WIDTH 2
char *
itoa(int n)
{
static char out[WIDTH + 1];
for(char *outp = out + WIDTH - 1; outp >= out; --outp, n /= 10)
*outp = '0' + n % 10;
return out;
}
void
fizzbuzz(int n)
{
static char *FBSTR[4] = {"", "Fizz", "Buzz"};
FBSTR[3] = itoa(n);
fputs(FBSTR[1 * (n%3 == 0)], stdout);
fputs(FBSTR[2 * (n%5 == 0)], stdout);
fputs(FBSTR[3 * (n%3 > 0 && n%5 > 0)], stdout);
putchar('\n');
}
int
main(void)
{
for(int i = 1; i <= LIMIT; ++i)
fizzbuzz(i);
return 0;
}
</code></pre>
<p>I've been reading a little bit about the anti-if campaign, and decided to try my hand at a challenge: Fizzbuzz but without if statements.</p>
<p>Because I'm not trying to be cheap, that also means no switch statements,</p>
<pre><code>switch(n % 3){
case 0: fputs("fizz", stdout); break;
}
</code></pre>
<p>no ternary expressions,</p>
<pre><code>fputs((n % 3 == 0) ? ("fizz") : (""), stdout);
</code></pre>
<p>and no contrived while loops.</p>
<pre><code>int lock = 0;
while(lock++ == 0 && n % 3 == 0)
fputs("fizz", stdout);
</code></pre>
| [] | [
{
"body": "<pre><code>char *\nitoa(int n)\n{\n static char out[WIDTH + 1];\n\n for(char *outp = out + WIDTH - 1; outp >= out; --outp, n /= 10)\n *outp = '0' + n % 10;\n</code></pre>\n\n<p>Nice bounds-check (<code>outp >= out</code>). This ensures that you don't overrun your buffer when given a very large integer. However, since <code>out-1</code> is not a valid pointer value, <code>outp >= out</code> is an <em>incorrect</em> bounds-check for the same reason that</p>\n\n<pre><code>int decr(int x) {\n int y = x - 1;\n if (y > x) return 0; // oops, overflow happened\n return y;\n}\n</code></pre>\n\n<p>is an <em>incorrect</em> overflow-check.</p>\n\n<p>Your bounds-check code also has another similarity to the above overflow-check code: When overflow happens, you return an <em>in-range value</em> that the caller might reasonably confuse for a valid result of the function. When <code>itoa(x)</code> returns <code>\"42\"</code>, does it mean that <code>x</code> was <code>42</code>, or does it mean that <code>x</code> was <code>1042</code> and overflow happened? It would be much better to say, if overflow happens, we return <code>NULL</code>.</p>\n\n<p>Of course you'll have to express that \"if\" without <code>if</code>. ;)</p>\n\n<hr>\n\n<p><code>itoa</code> returns <code>char*</code>, but you don't expect the caller to modify the pointed-to chars, so you should declare it as returning a pointer to non-modifiable chars: <code>const char*</code>. <a href=\"https://quuxplusone.github.io/blog/2019/01/03/const-is-a-contract/\" rel=\"nofollow noreferrer\">Const is a contract.</a></p>\n\n<p>Similarly, <code>static char *FBSTR[4]</code> should be <code>static const char *FBSTR[4]</code>.</p>\n\n<hr>\n\n<pre><code>static const char *FBSTR[4] = {\"\", \"Fizz\", \"Buzz\", NULL};\n</code></pre>\n\n<p>would be much clearer to the human reader; it shows that you didn't miscount the number of array elements. In fact, you might even write</p>\n\n<pre><code>static const char *FBSTR[] = {\"\", \"Fizz\", \"Buzz\", NULL};\n</code></pre>\n\n<p>although the downside of that is that the number of indices is actually <em>really important</em> to your algorithm, so I can see a valid argument for keeping the <code>4</code> in this case.</p>\n\n<hr>\n\n<pre><code>fputs(FBSTR[1 * (n%3 == 0)], stdout);\nfputs(FBSTR[2 * (n%5 == 0)], stdout);\nfputs(FBSTR[3 * (n%3 > 0 && n%5 > 0)], stdout);\nputchar('\\n');\n</code></pre>\n\n<p>I did puzzle this out, but printing all those empty strings feels like a strange way to go about it. Why not simply</p>\n\n<pre><code>int idx = 1*(n%3 == 0)\n + 2*(n%5 == 0)\n + 3*(n%3 != 0 && n%5 != 0);\nfputs(FBSTR[idx], stdout);\nputchar('\\n');\n</code></pre>\n\n<p>In which case you can combine the <code>fputs</code> and <code>putchar</code> into</p>\n\n<pre><code>puts(FBSTR[idx]);\n</code></pre>\n\n<hr>\n\n<p>If you think it would be easier to understand, you could even rewrite the index computation using bitwise operations:</p>\n\n<pre><code>const char *FBSTR[] = {itoa(n), \"Fizz\", \"Buzz\", \"FizzBuzz\"};\nint idx = (n%3 == 0) + 2*(n%5 == 0);\nputs(FBSTR[idx]);\n</code></pre>\n\n<hr>\n\n<p>To avoid reinventing the wheel, you could replace <code>itoa(n)</code> with <code>snprintf(somelocalbuffer, sizeof somelocalbuffer, \"%d\", n)</code>. However, for this toy example, <code>itoa</code> does have a more ergonomic interface; and reinventing the wheel isn't necessarily a bad thing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T01:04:04.267",
"Id": "413929",
"Score": "0",
"body": "Lots of good advice, some I'd even thought about myself before posting (ambiguous itoa `42`/`...42`, FBSTR should explicitly declare its fourth element, use of `char const*` instead of `char*`, `ptr - ... - 1` could backfire if `...` ever happens to be `0`). I haven't been to CR in a while--should I edit my question to integrate your advice, or is that against the spirit of CR?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T01:23:00.580",
"Id": "413931",
"Score": "0",
"body": "I will say that I'm a bit confused by the third-to-last piece of advice, which seems to be telling me to add the three indices together, which, to my understanding, would cause my program to output itoa's buffer rather than \"FizzBuzz\" when `n % 15 == 0` is true."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T20:26:39.257",
"Id": "213987",
"ParentId": "213985",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T19:35:00.943",
"Id": "213985",
"Score": "0",
"Tags": [
"c",
"fizzbuzz"
],
"Title": "Fizzbuzz but without if"
} | 213985 |
<p>I've created a personal API for creating elements for an HTML page. I would like feedback on efficiency, particularly in creating buttons and labels. Any and all feedback is appreciated and considered</p>
<p><strong>tag.js</strong></p>
<pre><code>/*
* Shortcuts for creatings different tags
*/
function createLabel(text) {
let label_tag = document.createElement('label');
let label_tag_text = document.createTextNode(text);
tabel_tag.appendChild(label_tag_text);
return label_tag;
}
function createButton(type) {
/* need to manually add .onclick when creating button */
let button_tag = document.createElement('button');
button_tag.type = type;
return button_tag;
}
function createInput(type, id) {
let input_tag = document.createElement('input');
input_tag.type = type;
input_tag.id = id;
return input_tag;
}
function createDiv(id) {
let div_tag = document.createElement('div');
div_tag.id = id;
return div_tag;
}
function createTag(tag) {
/*
* Used for creating basic tags (<p>, <br>, <hr>, etc)
* Any tag that doesn't often use an ID, TYPE, NAME, CLASS, etc
*/
return document.createElement(tag);
}
</code></pre>
| [] | [
{
"body": "<p>You have a lot of repeated code. If you follow the same design you will end up with a huge list of <code>create???()</code> functions</p>\n\n<p>You could simplify to a single function, and pass tag name and an optional properties containing element and style properties.</p>\n\n<pre><code>const createTag = (tag, props = {}) => {\n const style = props.style;\n if (style) { delete props.style }\n const el = Object.assign(document.createElement,props);\n if (style) { Object.assign(el.style, style) }\n return el;\n}\n</code></pre>\n\n<p>Thus you can create tags</p>\n\n<pre><code>createTag(\"input\", {type : \"button\", id : \"buttonId\"});\ncreateTag(\"button\", {value : \"Click me\"});\ncreateTag(\"div\", {textContent: \"abc\", id: \"abcId\", className: \"abcDiv\", style: {width: \"10px\"}});\n</code></pre>\n\n<p>If you did want to have a function to create each type then it would pay to put them together.</p>\n\n<pre><code>const createDOM = {\n label(...\n button(...\n input(...\n div(...\n // and so on\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T23:00:43.540",
"Id": "213996",
"ParentId": "213989",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "213996",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T21:27:37.403",
"Id": "213989",
"Score": "1",
"Tags": [
"javascript",
"dom"
],
"Title": "JavaScript shortcut to create elements"
} | 213989 |
<p>Imagine you have two string sequences:</p>
<pre><code>val s1 = Seq("c", "a", "b", "z", "a", "b")
val s2 = Seq("a", "b")
</code></pre>
<p>You need to come up with an algorithm that generates a binary membership mask of <code>s2</code> in <code>s1</code>, e.g.:</p>
<pre><code>algorithm(s1, s2) => 011000
</code></pre>
<p>Here are some other examples:</p>
<pre><code>val s1 = Seq("a", "b", "z", "c", "a")
val s2 = Seq("a", "b", "z")
11100
val s1 = Seq("z", "b", "a", "a", "b")
val s2 = Seq("a", "b")
00011
val s1 = Seq("z", "b", "a", "a", "b")
val s2 = Seq("a")
00100
val s1 = Seq("z", "b", "a", "a", "b")
val s2 = Seq("a", "a")
00110
</code></pre>
<p>Notice that we only count first sequence match and discard the rest sequence matches.</p>
<p>Basically, in case of <code>s2 = Seq("z", "b", "a", "a", "b")</code> and <code>s1 = Seq("a", "b")</code> we are trying to solve the following task:</p>
<pre class="lang-none prettyprint-override"><code>"z" "b" "a" "a" "b"
| | | | |
" " " " " " "a" "b"
| | | | |
0 0 0 1 1
</code></pre>
<p>Why? Imagine you have a sequence of auto-generated strings like "This is Google Inc ." but you only need to extract "Google" from it cutting everything else. It is easy when you know what you are searching for but once it is "This is ? Inc ." you have no way but to rely on binary masks that you collected from a big corpus. In order to generate such masks, you first need the algorithm described above.</p>
<p>I have come up with a simple while loop. This looks pretty ugly, so there should be another more Scala-like solution. How would you solve it?</p>
<pre><code>def binmask(a: Seq[String], b: Seq[String]): String = {
val x = a.sliding(b.length, 1)
var continue = true
var mask = ""
while (continue && x.hasNext) {
val g = x.next()
if (g == b) {
mask += "1"*b.length + "0"*x.length
continue = false
} else mask += "0"
}
if (continue) mask += "0"
mask
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T22:37:05.353",
"Id": "413921",
"Score": "0",
"body": "So this is basically a substring search, except that each \"character\" is a string?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T22:49:05.407",
"Id": "413923",
"Score": "0",
"body": "Yes, you can say so. Although I would not call it a substring but rather subsequence search since we shall split each string via whitespace."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T23:26:04.257",
"Id": "413925",
"Score": "0",
"body": "What if `s2` never occurs in `s1`? For example, `binmask(Seq(\"a\", \"b\", \"a\", \"a\", \"b\"), Seq(\"b\", \"b\"))` is `\"0000\"`, which is shorter than `binmask(Seq(\"a\", \"b\", \"a\", \"a\", \"b\"), Seq(\"a\", \"a\"))`, which is `\"00110\"`. Is that intentional?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T06:15:02.273",
"Id": "413936",
"Score": "0",
"body": "This should not happen because you only select `s2` that exist in `s1` beforehand. But this is a valid point. I added another `if` condition."
}
] | [
{
"body": "<p>The \"never occurs\" bug is still there. It stems from the fact that the length of <code>b</code> has an inverse relationship to the length of <code>x</code>. Try varying the length of a non-occurring <code>b</code> and see what you get.</p>\n\n<p>There's also the fact that this is a rather imperative approach, whereas good Scala style tries to be more functional.</p>\n\n<p>When I first saw this I thought, \"Doesn't <code>indexOfSlice()</code> offer most of what's needed?\"</p>\n\n<pre><code>def binmask(seq :Seq[String], slice :Seq[String]) :String = {\n val ios = seq indexOfSlice slice\n if (ios < 0)\n \"0\"*seq.length\n else {\n val slcLen = slice.length\n \"0\"*ios + \"1\"*slcLen + \"0\"*(seq.length-slcLen-ios)\n }\n}\n</code></pre>\n\n<p>The slight drawback here is that <code>indexOfSlice()</code> will traverse the <code>seq</code> input until it finds a match (or completely if not found) and then <code>seq</code> is traversed <em>again</em> for its length.</p>\n\n<p>The standard Scala means to achieve iteration <em>with</em> early termination but <em>without</em> mutable state, is via recursion. Preferably tail recursion, which the compiler turns into a <code>while</code> loop under the hood.</p>\n\n<pre><code>def binmask(seq :Seq[String], slice :Seq[String], acc :String = \"\") :String =\n if (seq startsWith slice) {\n val slcLen = slice.length\n acc + \"1\"*slcLen + \"0\"*(seq.length - slcLen)\n }\n else if (seq.isEmpty) acc\n else binmask(seq.tail, slice, acc + \"0\")\n</code></pre>\n\n<p>Some feel that making the accumulator a passed parameter (even though it is \"hidden\" behind a default value) exposes too much implementation in the public interface. For them, an inner recursion loop is preferable.</p>\n\n<pre><code>def binmask(seq :Seq[String], slice :Seq[String]) :String = {\n def loop(subseq: Seq[String], acc: String): String =\n if (subseq startsWith slice) {\n val slcLen = slice.length\n acc + \"1\" * slcLen + \"0\" * (subseq.length - slcLen)\n }\n else if (subseq.isEmpty) acc\n else loop(subseq.tail, acc + \"0\")\n\n loop(seq, \"\")\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T09:12:44.447",
"Id": "214015",
"ParentId": "213991",
"Score": "2"
}
},
{
"body": "<p>The function should be genericized to accept any two sequences of the same type, so that you can also write <code>binmask(\"abaab\", \"aa\")</code> for convenience.</p>\n\n<p>Recursion is a bit tedious and error-prone, as your correction in Rev 7 shows. I suggest taking advantage of <a href=\"https://www.scala-lang.org/api/current/scala/collection/Iterator.html#indexWhere%28p:A=>Boolean%29:Int\" rel=\"nofollow noreferrer\"><code>Iterator.indexWhere()</code></a> to perform the search.</p>\n\n<pre><code>def binmask[T](a: Seq[T], b: Seq[T]): String = a.sliding(b.length, 1).indexWhere(_ == b) match {\n case -1 => \"0\" * a.length\n case i => \"0\" * i + \"1\" * b.length + \"0\" * (a.length - i - b.length)\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T22:24:17.673",
"Id": "214073",
"ParentId": "213991",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "214015",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T21:50:01.750",
"Id": "213991",
"Score": "3",
"Tags": [
"scala"
],
"Title": "Solve membership binary mask problem in Scala"
} | 213991 |
<p>Fairly new to writing PHP. I want some PHP code to query an API with a post request, set specific headers and message body, and echo out the JSON response. This is the code I have come up with, which validates but I dont know if its optimal:</p>
<pre><code><?php
$url = 'http://api.local/rest/users';
$data = '{"4":"four","8":"eight"}';
$accesstoken = 'abc';
$apikey = 'abc';
$companyid = 'abc';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/json', 'Content-Type: application/json', 'Authorization: Bearer $accesstoken', 'x-api-key: $apikey', 'x-proxy-global-company-id: $companyid']);
$result = curl_exec($ch);
?>
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T22:30:18.477",
"Id": "213993",
"Score": "1",
"Tags": [
"php",
"json",
"curl"
],
"Title": "PHP API Query using CURL and return JSON"
} | 213993 |
<p>I'm trying to develop a program in Python that allows the user to import datasets and perform operations on them using pandas and numpy so she/he can skip writing all the preprocessing code her/himself.</p>
<p>I have two questions. Am I using my functions poorly? For example, can I create cleaner, more efficient code by using more classes and creating objects with <code>def SomeCode(self, etc, etc)</code>? I still struggle with understanding the concept of <code>__init__</code> and <code>self</code> because I mainly use Python to clean and analyze data. I'm worried I'm writing some <em>real</em> spaghetti code.</p>
<p>Second, I need to save the state of the data frame after it's been operated on. For example, at the beginning of the program, the user imports a dataset and it's read into the variable <code>df</code>. The user then has options to perform operations on the dataset, such as drop columns by index, rename columns, etc. After a user operates on the data frame, I need to save the new state of the data frame and have it reflected everywhere else in the program. So the next time the user displays the dataset, he sees the dataset with the changes. For example, if the user re-displays the columns, the columns he dropped earlier are not displayed.</p>
<pre><code>class Clean:
# Imports file, displays some information about the dataset
def Main():
while True:
file_name = input("\nPlease enter the name of the .csv file you want to process (if the .csv file is not in the same directory as this program, please provide relative path): \n")
try:
print("Reading in file...\n")
df = pd.read_csv(file_name) # Reads in file and stores it in df variable
df_types = (df.dtypes) # Reads in data types of dataset
df_columns = (df.columns) # Reads in columns of dataset
df_shape = (df.shape) # Reads in the 'shape' or dimensions of dataset
df_null_values = (df.isnull().sum(axis=0)) # Reads in the counts of null values in columns
# Prints information to screen
print("Here is some information about your dataframe...\n")
time.sleep(.5)
print("Your data types: \n\n{}".format(df_types))
time.sleep(.5)
print("\nYour column names:\n {}".format(df_columns))
time.sleep(.5)
print("\nThe shape of your dataframe is {}\n".format(df_shape))
time.sleep(.5)
print("Here is the count of null values per column:\n{}\n".format(df_null_values))
except (FileNotFoundError):
print("File path does not exist. Please enter valid path.\n")
else:
break
# Ran when user types in "exit" at any point in the program
def ExitProgram():
double_check = input("Are you sure you want to exit the program? (yes/no) (NOTE: Saying 'no' will return you to option menu.)\n")
if double_check in yes_values:
print("\nThanks for cleaning your dirty data!")
exit()
elif double_check in no_values:
DoNext()
def SaveDataframeState(temp_df):
temp_file_name = "temp.csv"
temp_df.to_csv(temp_file_name)
df = pd.read_csv(temp_file_name)
# Hashes columns to an index
def ColumnsToIndex():
column_list = []
index_of_list = []
for col in df_columns:
column_list.append(col)
length_of_list = len(column_list)
for num in range(length_of_list):
index_of_list.append(num)
hash = {k:v for k, v in zip(index_of_list, column_list)}
print("\nHere is the index of columns...\n")
for k,v in hash.items():
print(k, ":", v)
ColumnsToIndex()
# Displays the amount of rows user inputs
def DisplayInputtedRows():
while True:
try:
rows_to_display = input("\nHow many rows would you like to display? (Note: Whole dataset will have a limited display in terminal)\n")
time.sleep(.5)
print(df.head(int(rows_to_display))) # prints inputted rows to screen
except (ValueError):
print("Please pass an integer.")
else:
break
DisplayInputtedRows()
# Displays the amount of rows user inputs when they type 'row' on option menu
def RedisplayRows():
while True:
try:
rows_to_redisplay = input("\nHow many rows would you like to display? (Note: Whole dataset will have a limited display in terminal)\n")
time.sleep(.5)
print(df.head(int(rows_to_redisplay)))
DoNext()
except (ValueError):
print("Please pass an integer.")
else:
break
def RenameColumns():
print("\nHere are your columns by name:\n{}".format(df_columns))
rename_columns = input("\nWhat columns would you like to rename?\n")
print(rename_columns)
if rename_columns == "return":
DoNext()
elif rename_columns == 'exit':
ExitProgram()
def DropOneColByIndex():
drop_one_col_by_index = input("What columns do you want to drop? Please type in the index:\n")
temp_df = df.drop(df.columns[int(drop_one_col_by_index)], axis=1)
print(temp_df.head())
DoNext()
def DropColumnsByIndexPrompt():
print("Here are your columns by name:\n{}".format(df_columns))
ColumnsToIndex()
drop_more_than_one_col = input("\nWould you like to drop ONLY 1 COLUMN? Types 'yes' to ONLY drop 1 COLUMN, type 'no' to drop MORE THAN 1 COLUMN.\n")
if drop_more_than_one_col in yes_values:
DropOneColByIndex()
elif drop_more_than_one_col in no_values:
print()
elif drop_more_than_one_col == "return":
DoNext()
elif drop_more_than_one_col== 'exit':
ExitProgram()
time.sleep(.5)
def DropColumnsByDatatype():
print("Here are your columns by data-type:\n{}".format(df_types))
drop_columns_by_datatype = input("\nWhat columns would you like to drop?\n")
if drop_columns_by_datatype == "return":
DoNext()
elif drop_columns_by_datatype == 'exit':
ExitProgram()
# Main option screen where user can select operations on dataframe
def DoNext():
print("\n(NOTE: If at any point in the program you want to exit back to this option menu, just type 'return'.)\n")
print("(NOTE: At this part of the program you can also redisplay rows by typing 'rows'.)\n")
do_next = input("\nWhat would you like to do next?\n[0] Rename Columns \n[1] Drop Column(s) by Index \n[2] Drop Column(s) by Data-type\n")
if do_next == '0':
RenameColumns()
elif do_next == '1':
DropColumnsByIndexPrompt()
elif do_next == '2':
DropColumnsByDatatype()
elif do_next == 'exit':
ExitProgram()
elif do_next == "rows":
RedisplayRows()
DoNext()
Main()
</code></pre>
| [] | [
{
"body": "<p>First, Python has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>, which programmers are encouraged to follow. It recommends using <code>lower_case</code> for variables and functions and <code>PascalCase</code> only for classes.</p>\n\n<p>Next, currently your code is just a big mess of functions being defined, sometimes only within some inner scope, sometimes being called directly after being defined and sometimes not. I think making this into a proper class would be a good idea.</p>\n\n<p>Ideally this class will hold the dataframe object, have a method to construct the object with a given filename, have all those functions you designed as methods and give access to the underlying dataframe in case you need to do something not implemented (this would be already given by being able to access <code>self.df</code>, but we can do better).</p>\n\n<pre><code>class DataFrameHelper:\n @classmethod\n def from_file(cls, file_name):\n df = pd.read_csv(file_name)\n return cls(df)\n\n def __init__(self, df):\n self.df = df\n\n def __repr__(self):\n return repr(self.df)\n\n def __str__(self):\n return str(self.df)\n\n def __getattribute__(self, name):\n try:\n return super().__getattribute__(name)\n except AttributeError:\n return getattr(self.df, name)\n\n ...\n</code></pre>\n\n<p>This is all that is needed for the setup. When initializing this class you either need to pass in a dataframe (<code>DataFrameHelper(df)</code>), or use the classmethod which returns an instance of the class when given a file name (<code>DataFrameHelper.from_file(file_name)</code>).</p>\n\n<p>The <code>__repr__</code> magic method gets called whenever you just type <code>x</code> in an interactive session (with <code>x</code> being an instance of this class). Similarly <code>__str__</code> gets called when you do <code>print(x)</code>.</p>\n\n<p>The <code>__getattribute__</code> magic method will be called whenever we try to access an attribute of the instance (e.g. <code>x.dtypes</code>). It first tries to find that attribute in the class (so that methods we define there have priority) and if that fails tries to find the attribute in the dataframe. The latter call might still fail, in which case it will just give back that error. This way we don't need your <code>df_dtypes</code>, <code>df_columns</code> and <code>df_shape</code> variables anymore.</p>\n\n<p>Now we just need to add your methods to this class:</p>\n\n<pre><code> ...\n\n @property\n def null_values(self):\n return self.isnull().sum(axis=0)\n\n def save_data(self, file_name=\"temp.csv\"):\n self.df.to_csv(file_name)\n\n def columns_to_index(self):\n print(\"\\nHere is the index of columns...\\n\")\n for k, name in enumerate(self.columns):\n print(k, \":\", name)\n\n def display_n_rows(self):\n n = ask_user(\"\\nHow many rows would you like to display? (Note: Whole dataset will have a limited display in terminal)\\n\", int)\n print(self.head(n))\n\n def rename_columns(self):\n print(\"\\nHere are your columns by name:\")\n print(self.columns)\n rename_columns = input(\"\\nWhat columns would you like to rename?\\n\")\n if rename_columns == \"return\":\n return\n elif rename_columns == 'exit':\n EXIT()\n else:\n raise NotImplementedError\n\n def drop_column_by_index(self):\n i = ask_user(\"What column do you want to drop? Please type in the index:\\n\", int)\n self.df.drop(self.columns[i], axis=1, inplace=True)\n print(self.head())\n\n def drop_columns_by_index(self):\n print(\"Here are your columns by name:\")\n print(self.columns)\n self.columns_to_index()\n\n n_cols = input(\"\\nWould you like to drop ONLY 1 COLUMN? Types 'yes' to ONLY drop 1 COLUMN, type 'no' to drop MORE THAN 1 COLUMN.\\n\")\n\n if n_cols in yes_values:\n self.drop_column_by_index()\n elif n_cols in no_values:\n raise NotImplementedError\n elif n_cols == \"return\":\n return\n elif n_cols== 'exit':\n EXIT()\n\n def drop_columns_by_type(self):\n print(\"Here are your columns by data-type:\\n\")\n print(self.dtypes)\n dtype = input(\"\\nWhat columns would you like to drop?\\n\")\n if dtype == \"return\":\n return\n elif dtype == 'exit':\n EXIT()\n else:\n raise NotImplementedError\n</code></pre>\n\n<p>And finally we just need to add the menu around it and the two functions I added above, <code>ask_user</code>, which asks the user until an answer is given that can be cast to the given type and passes an optional validator, and <code>EXIT</code>:</p>\n\n<pre><code>import os\nimport pandas as pd\nimport sys\n\ndef ask_user(message, type_=str, validator=lambda x: True, invalid=\"Not valid\"):\n while True:\n try:\n x = type_(input(message))\n if validator(x):\n return x\n else:\n print(invalid)\n except ValueError:\n print(\"Please pass a(n)\", type_)\n\ndef EXIT():\n double_check = input(\"Are you sure you want to exit the program? (yes/no) (NOTE: Saying 'no' will return you to option menu.)\\n\")\n if double_check in yes_values:\n print(\"\\nThanks for cleaning your dirty data!\")\n sys.exit()\n\ndef main():\n file_name = ask_user(\"\\nPlease enter the name of the .csv file you want to process (if the .csv file is not in the same directory as this program, please provide relative path): \\n\",\n validator=os.path.isfile,\n invalid=\"File path does not exist. Please enter valid path.\\n\")\n df = DataFrameHelper.from_file(file_name)\n print(\"Here is some information about your dataframe...\\n\")\n print(\"Your data types:\\n\\n\", df.dtypes)\n print(\"\\nYour column names:\\n\", df.columns)\n print(\"\\nThe shape of your dataframe is {}\\n\".format(df.shape))\n print(\"Here is the count of null values per column:\\n{}\\n\".format(df.null_values))\n\n print(\"\\n(NOTE: If at any point in the program you want to exit back to this option menu, just type 'return'.)\\n\")\n\n while True:\n do_next = input(\"\\nWhat would you like to do next?\\n[0] Rename Columns \\n[1] Drop Column(s) by Index \\n[2] Drop Column(s) by Data-type\\n\")\n if do_next == '0':\n df.rename_columns()\n elif do_next == '1':\n df.drop_columns_by_index()\n elif do_next == '2':\n df.drop_columns_by_type()\n elif do_next == 'exit':\n EXIT()\n elif do_next == \"rows\":\n df.display_n_rows()\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n\n<p>NB: I got rid of all of your <code>sleep(0.5)</code> calls. Don't let the user wait just so it seems that your program is doing something.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T18:43:06.407",
"Id": "414019",
"Score": "0",
"body": "Wow, this not only helped me organize my code better but also gave me an understanding of things I was having a hard time grasping. To comment on the \"sleep\" function, it's there so the user is not overwhelmed by all the data getting printed to the screen."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T10:28:28.087",
"Id": "214023",
"ParentId": "213998",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T01:46:52.077",
"Id": "213998",
"Score": "2",
"Tags": [
"python",
"functional-programming",
"machine-learning"
],
"Title": "User-Interactive Data Cleaning Program in Python"
} | 213998 |
<p>The intention is to implement an xmlHttpRequest in plain vanilla js while considering all possible errors and problem situations without crashing in the browser. Result and faults are to be properly communicated back to the caller.</p>
<pre><code>function get() {
return new Promise(function(resolve, reject){
var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open("GET", "http://localhost/products", true);
xmlHttpRequest.onreadystatechange = function() {
if (xmlHttpRequest.readyState === 4) {
try {
var data = JSON.parse(xmlHttpRequest.response);
} catch (error) { // in case parser error
reject(error);
return;
}
if(xmlHttpRequest.status === 200) {
resolve(data);
} else {
reject(data);
}
}
};
xmlHttpRequest.addEventListener("error", function(error){
reject(error);
});
xmlHttpRequest.send();
});
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T04:36:19.630",
"Id": "413933",
"Score": "0",
"body": "I'd also like to mention that there's a status 0 condition, it happens when browser is offline, that means no json response etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T08:58:59.070",
"Id": "414253",
"Score": "0",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see [what you may and may not do after receiving answers](https://codereview.meta.stackexchange.com/a/1765)."
}
] | [
{
"body": "<p>Here are a few issues with your code</p>\n\n<ul>\n<li>If older browsers aren't a concern, you can just use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API\" rel=\"nofollow noreferrer\"><code>fetch</code></a> instead of XHR. It's built-in and uses promises.</li>\n<li>HTTP 200 isn't the only \"successful\" response status. See <a href=\"https://en.wikipedia.org/wiki/List_of_HTTP_status_codes\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/List_of_HTTP_status_codes</a>.</li>\n<li>Status \"0\" is a generic network error, not just being offline. It can also be caused by the browser suppressing the request due to some restriction, an extension blocking the request, an insecure connection/invalid certificate.</li>\n<li>Send an <code>Accept</code> header with <code>application/json</code> as value. This is because, while the server might support JSON, it might not respond with it by default.</li>\n<li>The third argument of <code>xhr.open</code> is by default <code>true</code>. You may omit that third argument.</li>\n<li>You can use <code>readystatechange</code> with <code>addEventListener</code> instead of the <code>onreadystatechange</code> property to assign your callback.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T06:10:09.497",
"Id": "414237",
"Score": "0",
"body": "Thanks Joseph for review, I've edited with version 2 of my code. It'd be very helpful to know the exact error message for your point #3, is there a property that I can read on xhr. REST contract dictates 200 for the success in this case. I've incorporated the rest of the feedback. please review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T09:01:01.203",
"Id": "414254",
"Score": "0",
"body": "Hi Joseph, they didn't let me update the code, can you please let me know how to get specific error details when status is 0 from xhr object?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-01T00:23:13.450",
"Id": "414825",
"Score": "0",
"body": "hi joseoph, reaching out to you again, can you please explain how to read such kind of errors from xhr object, I've tried statusText but it's empty string."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-01T13:25:09.697",
"Id": "414870",
"Score": "0",
"body": "@Developer Status 0, as far as I know, does not provide any textual response. This behavior may be vendor-specific, but I wouldn't count on it to return anything meaningful cross-browser. Hence \"generic network error\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-01T13:29:10.613",
"Id": "414871",
"Score": "0",
"body": "Thanks Joseph. I've searched a lot and I'm totally blocked on this. So there's no description on xhr, that's disappointing that API is designed like this. In other words it's an error with no details at the code level, and I'll be forced to open developer tools and see what went wrong. (it's harder on mobile apps)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-01T13:29:20.187",
"Id": "414872",
"Score": "0",
"body": "the objective was I wanted to be able to catch all errors and display descriptive messages nicely in UI."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T17:40:23.557",
"Id": "214052",
"ParentId": "214002",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "214052",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T04:30:54.090",
"Id": "214002",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "XMLHttpRequest in the browser"
} | 214002 |
<p>I have an older class that I am working on and I'm updating it to remove "Windows" specific code. It had some "Thread Protection Code" that used <code>CRITICAL_SECTION</code>. I'm in the process of changing the use of <code>CRITICAL_SECTION</code> to use <code>std::mutex</code> and <code>std::lock_guard</code>. One thing to take note of is that my class does have static functions and this class is of a singleton type. </p>
<p>This is what my old code would have looked like.</p>
<p><em>-Logger.h-</em></p>
<pre><code>#pragma once
#include "Singleton.h"
class Logger final : public Singleton {
public:
// enum here
private:
// private variables not of concern
CRITICAL_SECTION criticalSection_;
public:
explicit Logger( const std::string& filename );
virtual ~Logger();
static void log( const std::string& text, LoggerType type );
static void log( const std::ostringstream& stream, LoggerType type );
static void log( const char* text, LoggerType type )
};
</code></pre>
<p><em>-Logger.cpp-</em></p>
<pre><code>#include "Logger.h"
#include "BlockThread.h" // old class that would block threads - replacing with mutex lock_guard
#include "TextFileWriter.h" // file handler the Logger uses to write text files
// since this is a singleton type class as I only want a single logger per
// application run; here I use a static pointer to this class, the reason
// the log functions are static to begin with.
static Logger* spLogger_ = nullptr;
Logger::Logger( const std::string& filename ) :
Singleton( LOGGER ) { // Base class takes an enum type of Singleton
// variable initializations
// ...
// ------------------------
InitializeCriticalSection( &criticalSection_ );
BlockThread blockThread( criticalSection ); // Enter Critical Section
// Start the log file
TextFileWriter file( filename_, false, false ); //
spLogger_ = this;
}
Logger::~Logger() {
spLogger_ = nullptr;
DeleteCriticalSection( &criticalSection_ );
}
void Logger::log( const std::string& text, LoggerType type ) {
log( text.c_str(), type );
}
void Logger::log( const std::ostringstream& stream, LoggerType type ) {
log( stream.str().c_str(), type );
}
void Logger::log( const char* text, LoggerType type ) {
if ( nullptr = spLogger_ ) {
// output error message
return;
}
BlockThread blockThread( spLogger->criticalSection_ ); // Enter Critical Section
std::ostringstream stream;
// setup logger's text formatting
// get the date and time
// push the date and time into the stream
// push the text message into the stream
// print stream to console
try {
TextFileWriter file (spLogger_->filename_, true, false );
file.write( stream.str() );
} catch( ... ) {
// output error message failed to write to file.
}
}
</code></pre>
<p>If you need to see the <code>BlockThread</code> class I'll show it here just incase...</p>
<p><em>-BlockThread.h-</em></p>
<pre><code>#pragma once
class BlockThread final {
private:
CRITICAL_SECTION* criticalSection_;
public:
explicit BlockThread( CRITICAL_SECTION& criticalSection );
~BlockThread();
};
</code></pre>
<p><em>-BlockThread.cpp-</em></p>
<pre><code>#include "BlockThread.h"
BlockThread::BlockThread( CRITICAL_SECTION& criticalSection ) {
criticalSection_ = &criticalSection;
EnterCriticalSection( criticalSection_ );
}
BlockThread::~BlockThread() {
LeaveCriticalSection( criticalSection_ );
}
</code></pre>
<p>This was how my old classes were set up.</p>
<hr>
<p>This is my attempt to remove <code>BlockThread</code> class and the <code>CRITICAL_SECTION</code> and its related functions by replacing them with <code>std::mutex</code> and <code>std::lock_guard</code></p>
<p><em>-Logger.h-</em></p>
<pre><code>#pragma once
#include "Singleton.h"
#include <mutex> // added this for mutex
class Logger final : public Singleton {
public:
// public enum
private:
// private members
// CRITICAL_SECTION
static std::mutex critical_;
public:
// constructor, destructor and log function declarations same as above
};
</code></pre>
<p><em>-Logger.cpp-</em></p>
<pre><code>#include "Logger.h"
static Logger* spLogger_ = nullptr;
std::mutex Logger::critical_{};
Logger::Logger( const std::string& filename ) {
// init variables
// InitializeCriticalSection( &criticalSection_ )
// BlockThread blockThread( criticalSection_ );
std::lock_guard<std::mutex> lock(critical_ );
TextFileWriter file( filename, false, false );
spLogger_ = this;
}
Logger::~Logger() {
spLogger_ = nullptr;
// DeleteCriticalSection( &criticalSection_ );
// Left empty don't think I have to do anything since `lock_guard`
// is destroyed once it leaves its scope...
}
// skip the first two log functions no difference here...
void Logger::log( const char* text, LoggerType type ) {
// check if spLogger_ is null if so print error message & return
// BlockThread blockThread( spLogger_->criticalSection_ ); // Enter Critical Section
std::lock_guard<std::mutex> lock( spLogger_->criticalSection_ );
// text formatting, date-time and message
// print stream to console
// try catch block same as above.
}
</code></pre>
<hr>
<p>There's a set of questions that are sort of related; that's why I feel they are all important in this situation...</p>
<p>What I would like to know:</p>
<ul>
<li>Is the replacement of my original <code>CRITICAL_SECTION</code> it's related functions and my original <code>BlockThread</code> class with <code>std::mutex</code> and <code>std::lock_guard</code> correct?</li>
<li>Will this behave in the same manner or fashion?</li>
<li>If not what would be the correct way to replace them as I'm not real familiar with <code>std::mutex</code> & <code>std::lock_guard</code>? - I'm trying to get a better grasp and understanding of how to use them properly.</li>
<li>Is there anything that I am missing, any corner cases or code smell such as possible data races, dead lock, or live lock?</li>
<li><em>-Note-</em> I'm not really concerned with the commented out code as I know the original class works fine; I'm mainly concerned where I made the replacements.</li>
<li>What can I do to make this code follow modern C++ standards; to make it portable, cross-platform capable etc. </li>
</ul>
<hr>
<p><em>-Edit-</em></p>
<p>One of the major motivations for writing this question is that I have other classes in a decent size library that had previously used <code>CRITICAL_SECTION</code> its related functions and my old <code>BlockThread</code> class. Once I know how to properly replace them with <code>std::mutex</code>, <code>std::lock_guard</code> or any of their variations... Then I should easily be able to replace all thread safety features in my library.</p>
| [] | [
{
"body": "<p>The design that you claim "works" comes with a caveat: <em>it works extremely poorly</em>.</p>\n<p>You might not have noticed it when logging is set to a low level or when only one or two threads do the majority of logging. The threads that log infrequently still stall for many orders of magnitude longer than necessary. <strong>A simple logger should be able to saturate the disk while streaming data from multiple threads.</strong></p>\n<p>When writing any multithreaded code that needs to serialize access to resources, the duration of each serialized or atomic access should be minimal. The implementation of <code>Logger::log</code> is a textbook case of doing it exactly the opposite of how it should be done.</p>\n<blockquote>\n<h4>The Cardinal Rule of Locking</h4>\n<p>Don't hold locks for anything but very simple manipulations of variables you have under full control. Basically: if you do any work while holding a lock, it should be trivial and touch small numbers of cachelines. Ideally you should be able to articulate roughly how many. <strong>I/O, memory allocation, syscalls (crossing user-kernel boundary), accessing many pages of memory, and similar are performance killers</strong>.</p>\n</blockquote>\n<p>Let's now look at the "working" implementation:</p>\n<pre><code>void Logger::log( const char* text, LoggerType type ) {\n if ( nullptr = spLogger_ ) {\n // output error message\n return; \n }\n</code></pre>\n<p>Hopefully that error message is only output once, perhaps with a count of how many times this call has failed. It's not a good way to start your day when the application you're using is dumping thousands of error messages to console or raises popups until it runs out of GDI or X handles...</p>\n<pre><code> BlockThread blockThread( spLogger->criticalSection_ );\n</code></pre>\n<p>Everything from now on is indeed critical and shouldn't be done unless it really <em>is</em> critical.</p>\n<pre><code> std::ostringstream stream;\n // setup logger's text formatting \n // get the date and time \n // push the date and time into the stream\n // push the text message into the stream\n // print stream to console\n</code></pre>\n<p>This allocates memory many times. Each time an allocation is performed, a global heap allocator lock is obtained - in some allocators it won't be for every allocation, but will still happen. That means that you're paying the cost of serializing access repeatedly for the same small chunk of code.</p>\n<p>This code also does kernel calls galore. There's no reason to serialize it, because no shared resources are used. If anything, that <code>BlockThread</code> should be here, not many lines earlier.</p>\n<pre><code> try {\n</code></pre>\n<p>Exceptions are fine as long as they are thrown rarely. In C++, exception handling may allocate memory, perhaps many times in some corner cases.</p>\n<p><em>Since you throw in the critical section</em>, <strong>anytime an exception is thrown the threads that attempt to log revert to single-core operation</strong>: until the exception is processed, the critical section is held locked.</p>\n<pre><code> TextFileWriter file (spLogger_->filename_, true, false );\n</code></pre>\n<p>A file is opened every time something is logged... Have you tried how long will it take to log a million empty lines? After all, it's just a megabyte or two of data. Should take maybe a couple milliseconds at worst, typically way better than that... But here, this won't be the case! On a network file system, this may take minutes!</p>\n<pre><code> file.write( stream.str() );\n</code></pre>\n<p>Bad idea. <code>stream.str()</code> copies the string. This API is basically broken and you need to use lower level methods of the stream buffer to do this efficiently. See <code>void LogSource::write(std::streambuf* buf)</code> further below for a better implementation.</p>\n<pre><code> } catch( ... ) {\n // output error message failed to write to file.\n</code></pre>\n<p>Again: Hopefully this message is output only once for any given file. This sort of "dump the errors on the user" is bad UX. What can the user do if she sees thousands of messages scrolling past, with the application unresponsive?</p>\n<p>OK, so we know that this is totally not the way to do it :)</p>\n<h2>An Example</h2>\n<p>A complete example follows, albeit not always in source file order.</p>\n<p>Let's start with a counterexample to the critique given - the method that actually logs to the file.</p>\n<h3>LogSink::run() Implementation</h3>\n<pre><code>void LogSink::run()\n{\n using std::swap, std::next;\n bool stop = false, wasBusy = true;\n std::string filename;\n while (!stop)\n {\n // Process the global state and newly arrived log sources\n {\n/*l*/ auto l = locked();\n/*l*/ filename = l->filename;\n/*l*/ swap(l->newSources, this->newSources);\n/*l*/\n/*l*/ if (!wasBusy && this->newSources.empty() && !l->stopWorker)\n/*l*/ condVar.wait(l.lock());\n/*l*/\n/*l*/ stop = l->stopWorker;\n }\n\n // Record the newly created sources\n for (auto &newSource : this->newSources)\n sources.emplace_back(std::move(newSource));\n this->newSources.clear();\n\n // Write out the data from all the sources to the file\n wasBusy = false;\n if (filename.empty())\n continue; // no writing if the filename is not set\n ofs.open(filename, std::ios_base::app);\n for (auto it = sources.begin(); it != sources.end(); )\n {\n/*l*/ auto l = (*it)->locked();\n/*l*/ auto& readOnly = l->readOnly;\n/*l*/ bool const finished = l->finished;\n/*l*/ if (!l->writeOnly.empty())\n/*l*/ swap(l->writeOnly, l->readOnly);\n/*l*/ l.unlock();\n\n if (!readOnly.empty())\n {\n ofs.write( readOnly.data(), readOnly.size() );\n readOnly.clear();\n wasBusy = true;\n }\n if (finished)\n it = sources.erase(it);\n else\n it = next(it);\n }\n ofs.close();\n }\n}\n</code></pre>\n<p>First, let's mention two fundamental concepts in this design. Shown above is a part of the log <em>sink</em>: where the logged messages are dumped to be processed. The messages come from threads that do actual work and need to log things - those are the log <em>sources</em>.</p>\n<p>The <code>LogSink::run</code> method runs in a dedicated worker thread, so that file accesses are essentially invisible to the threads that do the logging - by the virtue of minimizing lock contention.</p>\n<hr />\n<p>I've marked the sections of code that hold a lock with '<code>/*l*/</code>' in the margin. Let's analyze why this has a chance of performing decently.</p>\n<pre><code> // Process the global state and newly arrived log sources\n {\n/*l*/ auto l = locked(); <- 1\n/*l*/ filename = l->filename; <- 2\n/*l*/ swap(l->newSources, this->newSources); <- 3\n/*l*/\n/*l*/ if (!wasBusy && this->newSources.empty() && !l->stopWorker) <- 4\n condVar.wait(l.lock()); <- 5\n/*l*/\n/*l*/ stop = l->stopWorker; <- 6\n } <- 7\n</code></pre>\n<p>This part holds a global lock on the event sink's state; the state is accessible via <code>l-></code>.</p>\n<ol>\n<li><p>The lock was acquired with no to very little contention. This will usually be the case, since the lock is held for a small fraction of a μs by the sink thread.</p>\n<p>The contention can only take place when other threads:</p>\n<ul>\n<li><p>create a log source, on the first use of the logger from given thread, and</p>\n</li>\n<li><p>destroy a log source, when a thread that had previously used a logger terminates</p>\n</li>\n</ul>\n<p>These two events happen rarely, and themselves are not low-cost operations, so increasing their overhead just slightly is not going to even be measurable. Well designed applications create and destroy threads very sparingly.</p>\n</li>\n<li><p>The filename is copied. This copies a few cachelines of data but doesn't allocate (except once initially). The cost of this operation is essentially zero, since the local <code>filename</code> variable is not accessed until later, and thus the operations performed on it have every reason to be parallelized by the fancy execution machinery of modern out-of-order CPUs.</p>\n</li>\n<li><p>Two <code>std::vector</code>s are swapped: <code>l->newSources</code> with <code>this->newSources</code>. <code>l->newSources</code> are protected by the lock and would be accessed from other threads by the log sources, the ones in <code>this</code> object are only processed from the log sink's thread.</p>\n<p>The string copy and vector swapping is extremely fast: literally a dozen cachelines worth of data are moved around.</p>\n</li>\n<li><p>If the last iteration of the loop had no work, i.e. didn't write anything out (<code>!wasBusy</code>), and there were no new log sources added (<code>newSources.empty()</code>), and the log sink wasn't finishing work (<code>!l->stopWorker</code>), then the worker thread goes to sleep waiting on a condition variable that will be set by the log <em>sources</em>.</p>\n</li>\n<li><p>When is entered <code>std::condition_variable::wait</code>, the lock on the state view <code>l</code> is removed. As soon as the condition is signaled and the thread resumes, <em>the lock is reacquired</em>. I.e. "inside" of <code>condVar.wait</code> the lock is temporarily suspended, but outside of it the lock is present.</p>\n</li>\n<li><p>As soon as the thread resumes, the local <code>bool stop</code> variable is updated from the locked sink state <code>l-></code>. This takes advantage of the lock being already held, so we get the newest state of the <code>l->stopWorker</code> flag.</p>\n</li>\n<li><p>The lock holder <code>l</code> is destroyed at the end of scope, and the lock is released.</p>\n</li>\n</ol>\n<hr />\n<p>Next comes some code that runs with no locks held (almost).</p>\n<pre><code> // Record the newly created sources\n for (auto &newSource : this->newSources) <- 1\n sources.emplace_back(std::move(newSource)); <- 2\n this->newSources.clear(); <- 3\n\n // Write out the data from all the sources to the file\n wasBusy = false; <- 4\n if (filename.empty()) <- 5\n continue; // no writing if the filename is not set\n ofs.open(filename, std::ios_base::app); <- 6\n</code></pre>\n<ol>\n<li><p>The log sources are moved from the temporary array <code>newSources</code> to the <em>work list</em> <code>[this->]sources</code> that holds all the log sources that need to be processed by the log sink. Note that <code>newSources</code> is not a local variable: it's a member of <code>LogSink</code>, and thus doesn't need to reallocate memory.</p>\n</li>\n<li><p>An extraordinary cost may be due to a potential atomic memory accesses in the moving constructor <code>std::shared_ptr::shared_ptr(std::shared_ptr &&)</code>. That is usually implementation-dependent, but all recent ones behave rather well. This is a hardware-mediated cacheline-based exclusive access done with a special machine opcode, not a syscall.</p>\n</li>\n<li><p>In decent implementations of C++, <code>std::vector::capacity</code> survives the <code>clear()</code>. After a few initial allocations at the startup of the logger, these three lines will not be allocating nor deallocating.</p>\n</li>\n<li><p>The flag that indicates whether any work was done when writing to the file is cleared (<code>wasBusy=false</code>).</p>\n</li>\n<li><p>If the filename is not set, the loop short-circuits and likely will wait on the condition variable. Any changes to the log sink's state made from other threads always signal the condition variable, so that the sink thread will resume and pick up any changes made - such as, for example setting the filename (see one paragraph below the next one).</p>\n</li>\n<li><p>The file is opened for appending. This may allocate buffers within <code>std::basic_filebuf</code>. Since the entire stream and its buffer are members of <code>LogSink</code>, no allocations are made after initial startup. Still, the cost of a userspace-to-kernel transition is not to be discounted, never mind the tens of thousands of instructions needed, in the best case, to process a file opening request, assuming the relevant filesystem pages are in memory, decompressed, etc. Modern kernels perform much of this processing in kernel threads, so the userspace thread is likely to block and go to sleep until the file is opened.</p>\n</li>\n</ol>\n<hr />\n<p>Now an intermission: we've mentioned setting the filename just two paragraphs ago. Let's see how that's done, since this pattern recurs anytime the state of the log sink is modified in any way from other threads:</p>\n<pre><code> void LogSink::setFilename(std::string_view filename)\n {\n if (!filename.empty()) <- 1\n {\n/*l*/ auto l = locked(); <- 2\n/*l*/ l->filename = filename; <- 3\n/*l*/ wakeUp(l); <- 4\n }\n }\n</code></pre>\n<p><code>std::string_view</code> is a C++-17 class that conveniently wraps <code>const char *, size_t</code>. It is very flexible: it efficiently accepts string literals, <code>std::string</code>, and the various string views produced by picking out fragments of strings. A highly recommended class wherever you previously had <code>const std::string &</code>. It is a value type and should be always passed into functions by value.</p>\n<ol>\n<li><p>An empty filename is ignored. This is a "cop out": perhaps not the best design, but for now it can do. After all, this is just an example that would need to be adapted to application requirements.</p>\n</li>\n<li><p><code>LogSink::locked</code> is used to obtain a locked view of the log sink's state.</p>\n</li>\n<li><p>The filename is updated within the locked view. A memory allocation may be done here - but only if the new filename is larger than the previous one. The cost of copying the filename characters is essentially nil, since those characters are used hundreds of clock cycles later, and thus it can be parallelized at a hardware level by fancypants CPUs.</p>\n</li>\n<li><p>The <code>LogSink::wakeUp</code> is used on the locked view. This unlocks the view and signals the <code>LogSink::condVar</code> condition variable, thus waking up the worker thread and resuming <code>LogSink::run</code> if it wasn't running already.</p>\n</li>\n</ol>\n<hr />\n<p>Our discussion is now back to <code>LogSink::run()</code>, resuming right after the output stream <code>LogSink::ofs</code> has been opened.</p>\n<p>We've been looking at the log sink this whole time, now we need to introduce the log sources. There's one log source per any thread that invokes the logging functions. It's created on demand, and is co-owned by the log sink and the source <em>thread</em>. Once the thread terminates, the only owner left is the log sink, and it then discards the source.</p>\n<p>The following is a loop that iterates all log <em>sources</em>, and writes out their data to the output file (via <code>LogStream::ofs</code>).</p>\n<pre><code> for (auto it = sources.begin(); it != sources.end(); ) \n {\n/*l*/ auto l = (*it)->locked(); <- 1\n/*l*/ auto& readOnly = l->readOnly; <- 2\n/*l*/ bool const finished = l->finished; <- 3\n/*l*/ if (!l->writeOnly.empty()) <- 4\n/*l*/ swap(l->writeOnly, l->readOnly);\n/*l*/ l.unlock(); <- 5\n</code></pre>\n<ol>\n<li><p>Just as the log <em>sink state</em> could be locked, so can be the log <em>source state</em>. <code>l-></code> accesses the currently iterated source's state under the lock.</p>\n<p>The contention for this lock is low, since:</p>\n<ul>\n<li><p>there is only one other thread that uses this lock: the source thread,</p>\n</li>\n<li><p>the source thread does a minimal amount of work under the lock: a very fast swap of two strings that takes a fraction of a microsecond.</p>\n</li>\n</ul>\n</li>\n<li><p>Each source contains two string members: <code>writeOnly</code> and <code>readOnly</code>. As their names imply, the <code>writeOnly</code> string is only ever written within the thread the source is in, whereas the <code>readOnly</code> string is only ever read in the thread the sink is in.</p>\n<p>The <code>writeOnly</code> string is where every message logged in a given string is appended to, until the log sink comes around to dumping it to the file.</p>\n</li>\n<li><p>The <code>finished</code> state of the source is captured in a local variable.</p>\n</li>\n<li><p>If the <code>writeOnly</code> string is not empty, we swap the <code>writeOnly</code> and <code>readOnly</code> strings: that's how the sink gets hold of the data written by the log source.</p>\n</li>\n<li><p>Now we're done with the log source - we can unlock its state.</p>\n</li>\n</ol>\n<hr />\n<p>The rest of the per-source work is done without holding locks:</p>\n<pre><code> if (!readOnly.empty()) <- 1\n {\n ofs.write( readOnly.data(), readOnly.size() ); <- 2\n readOnly.clear();\n wasBusy = true; <- 3\n }\n if (finished) <- 4\n it = sources.erase(it);\n else\n it = next(it);\n }\n</code></pre>\n<ol>\n<li><p>The data written by the source is now in the <code>readOnly</code> string. We only need to deal with it if the string is not empty.</p>\n</li>\n<li><p>The data is written to the output file stream <code>ofs</code>. The string is then cleared. That typically preserves the memory allocated by the string, so that no reallocations will be necessary.</p>\n</li>\n<li><p>A flag is set to indicate that we did some work in this iteration through the outer loop.</p>\n</li>\n<li><p>Finally, we have to advance to the next source. If the source has finished (i.e. its thread is done), the source gets erased. <code>std::vector::erase</code> returns the iterator to the next element. Otherwise, <code>std::next(iterator)</code> is used for the same purpose. Instead of <code>std::next</code>, we could also have used <code>it++</code>.</p>\n</li>\n</ol>\n<pre><code> ofs.close(); <- 1\n } <- 2\n</code></pre>\n<ol>\n<li>Now the log file is closed, and</li>\n<li>The outer loop continues for the next iteration.</li>\n</ol>\n<hr />\n<p>A short diversion into the <code>LogSource</code>: how do we add data to the <code>writeOnly</code> string? Like this:</p>\n<pre><code>void LogSource::write(std::string_view str) <- 1\n{\n auto l = locked(); <- 2\n auto const destPos = l->writeOnly.size(); <- 3\n l->writeOnly.reserve(destPos + str.size()); \n std::copy(str.begin(), str.end(), std::back_inserter(l->writeOnly)); <- 4\n wakeUpSink(l); <- 5\n}\n</code></pre>\n<ol>\n<li><p>This <code>write</code> method takes strings in general: <code>std::string_view</code> will accept <code>const std::string &</code>, <code>const char *</code>, and others.</p>\n</li>\n<li><p>Lock the source, so that the sink won't be able to modify the <code>writeOnly</code> while we need it.</p>\n</li>\n<li><p>Get the current size of the write "buffer" string, and reserve enough additional space to fit the string being written.</p>\n</li>\n<li><p>Copy the string to be written to the back of the write buffer.</p>\n</li>\n<li><p>Wake up the sink, so that it has a chance to notice that there is some work to do.</p>\n</li>\n</ol>\n<h2>The Scalable Performance of <code>LogSink</code></h2>\n<p>The design presented above has a very important scalability aspect: it automatically reduces overheads the busier it gets.</p>\n<p>That means that when there's little work to do, the log file will be opened and closed perhaps even once for every message written, and the write sizes are minuscule. This has relatively large overhead, but is appropriate when there's not much pressure on the logger. This is what the original implementation in the question was doing <strong>always</strong>.</p>\n<p>The problem is that this high-overhead approach is <strong>not appropriate</strong> when there's lots of logging messages to write out, whereas it is definitely the right thing to do when there's not much work. Instead, the relative overhead should be reduced to keep up with the demand on the sink.</p>\n<p>When the logger is "inundanted" with data, the overheads get automatically reduced:</p>\n<ol>\n<li><p>The file is only closed when all available work from all sinks has been written out.</p>\n</li>\n<li><p>The write requests keep getting larger as the amount of work available grows. This reduces the relative overhead of file writing system calls.</p>\n</li>\n<li><p>The contention for the per-source lock is almost nil, since the sink is mostly busy writing the data out to the file. It only locks the source to swap the <code>writeOnly</code> buffer with the <code>readOnly</code> buffer. The relative time spent holding the source lock is minuscule compared to the time spent writing.</p>\n<p>Furthermore, each source thread has its own dedicated lock, increasing the number of threads does not raise contention on this often-used lock.</p>\n</li>\n<li><p>The contention for the per-sink lock is also negligible, since it can only happen during a very short section of the sink loop, and only when it coincides with first use of the logger in a newly created thread, or with thread termination. In well designed applications, thread creation and destruction is very rare - and in any case it's such an expensive operation, that adding comparatively minuscule overhead to it has no effect.</p>\n</li>\n</ol>\n<h2>The Interface</h2>\n<p>The <code>Logger</code> class is the singleton sink. This particular implementation shares ownership of the sink, so any number of <code>Logger</code> instances can exist, but they all share the same <code>LogSink</code>. That class is not copyable.</p>\n<p>In addition to the static <code>log</code> methods you suggested, there's also an argument-less method <code>log()</code> that returns a <code>LogStream</code>, which works just like any other output stream. E.g. you can do <code>Logger::log() << 1 << 2 << '\\n'</code>.</p>\n<pre><code>// log.hpp\n#pragma once\n#include <iostream>\n#include <memory>\n#include <string_view>\n\nclass Logger final\n{\npublic:\n explicit Logger(std::string_view filename);\n ~Logger();\n Logger(const Logger&) = delete;\n Logger& operator=(const Logger&) = delete;\n\n static void log(std::ostringstream *stream);\n static void log(const std::ostringstream &stream);\n static void log(std::string_view text);\n static inline class LogStream log();\n\nprivate:\n std::shared_ptr<class LogSink> d;\n};\n\nclass LogStream final\n{\npublic:\n LogStream();\n ~LogStream();\n\n template <typename T>\n friend const LogStream& operator<<(const LogStream& ls, const T& val)\n {\n ls.stream << val;\n return ls;\n }\n operator std::ostream&() { return stream; }\nprivate:\n class LogSource* source;\n std::ostream& stream;\n};\n\ninline LogStream Logger::log() { return {}; }\n</code></pre>\n<h2>The Implementation</h2>\n<p>First, the declarations of the global and per-thread state, as well as declarations of the implementation classes:</p>\n<pre><code>// log.cpp\n#include "log.hpp"\n#include <cassert>\n#include <condition_variable>\n#include <fstream>\n#include <mutex>\n#include <sstream>\n#include <vector>\n\n//\n// Durable Resources\n//\n\nstatic std::mutex globalMutex;\nstatic std::shared_ptr<LogSink> globalSink;\n\nclass LogSourceOwner\n{\n class LogSource *source = {};\npublic:\n LogSource* getOrMake();\n ~LogSourceOwner();\n}\nstatic thread_local localSource;\n\n//\n// Helpers\n//\n\nclass LockedViewBase\n{\n std::unique_lock<std::mutex> _lock;\nprotected:\n void* data;\n LockedViewBase(void* data, std::mutex& mutex) : _lock(mutex), data(data) {}\npublic:\n void unlock() {\n data = nullptr;\n _lock.unlock();\n }\n auto& lock() { return _lock; }\n};\n\ntemplate <typename T>\nclass LockedView : public LockedViewBase\n{\npublic:\n LockedView(T* data, std::mutex& mutex) : LockedViewBase(data, mutex) {}\n T* operator->() const { return reinterpret_cast<T*>(data); }\n};\n\n//\n// LogSink Declaration\n//\n\nstruct LogSinkState\n{\n bool stopWorker = false;\n std::vector<std::shared_ptr<LogSource>> newSources;\n std::string filename;\n};\n\nclass LogSink : public std::enable_shared_from_this<LogSink>\n{\npublic:\n static std::shared_ptr<LogSink> getOrMake(std::string_view filename);\n\n explicit LogSink(std::string_view filename);\n void finish();\n void setFilename(std::string_view filename);\n void wakeUp(LockedViewBase& l) {\n l.unlock();\n condVar.notify_one();\n }\n\n LogSource* createSource();\n\nprivate:\n LogSinkState state;\n std::condition_variable condVar;\n\n std::ofstream ofs;\n std::vector<std::shared_ptr<LogSource>> newSources, sources;\n std::thread worker;\n\n void run();\n auto locked() { return LockedView{&state, globalMutex}; }\n};\n\n//\n// LogSource Declaration\n//\n\nstruct LogSourceState\n{\n bool finished = false;\n std::string writeOnly, readOnly;\n};\n\nclass LogSource\n{\npublic:\n static LogSource* getOrMake() { return localSource.getOrMake(); }\n\n explicit LogSource(std::shared_ptr<LogSink> logger) : logger(std::move(logger)) {}\n auto locked() { return LockedView{&state, sourceMutex}; }\n void wakeUpSink(LockedViewBase& l) { logger->wakeUp(l); }\n\n std::ostream &msgStream() { return message; }\n void write(std::string_view str);\n void write(std::streambuf *buf);\n char* allocWriteBuf(std::size_t size, LockedView<LogSourceState>& l);\n\nprivate:\n std::shared_ptr<LogSink> logger;\n std::ostringstream message;\n\n std::mutex sourceMutex;\n LogSourceState state;\n};\n</code></pre>\n<h3>LogSink Implementation</h3>\n<pre><code>//\n// LogSink\n//\n\nLogSource* LogSink::createSource()\n{\n auto source = std::make_shared<LogSource>(shared_from_this());\n locked()->newSources.push_back(source);\n return source.get();\n}\n\nstd::shared_ptr<LogSink> LogSink::getOrMake(std::string_view filename = {})\n{\n std::unique_lock lock(globalMutex);\n if (!globalSink)\n globalSink = std::make_shared<LogSink>(filename);\n else\n globalSink->setFilename(filename);\n return globalSink;\n}\n\nLogSink::LogSink(std::string_view filename)\n{\n state.filename = filename;\n worker = std::thread(&LogSink::run, this);\n}\n\nvoid LogSink::setFilename(std::string_view filename)\n{\n if (!filename.empty())\n {\n auto l = locked();\n l->filename = filename;\n wakeUp(l);\n }\n}\n\nvoid LogSink::finish()\n{\n auto l = locked();\n l->stopWorker = true;\n wakeUp(l);\n worker.join();\n}\n\n// LogSink::run() is here\n</code></pre>\n<h3>LogSource implementation</h3>\n<pre><code>//\n// Log Source\n//\n\nLogSource* LogSourceOwner::getOrMake()\n{\n if (!source)\n source = LogSink::getOrMake()->createSource();\n return source;\n}\n\nLogSourceOwner::~LogSourceOwner()\n{\n if (source) {\n auto l = source->locked();\n l->finished = true;\n source->wakeUpSink(l);\n }\n source = nullptr;\n}\n\nvoid LogSource::write(std::string_view str)\n{\n auto l = locked();\n auto const destPos = l->writeOnly.size();\n l->writeOnly.reserve(destPos + str.size());\n std::copy(str.begin(), str.end(), std::back_inserter(l->writeOnly));\n wakeUpSink(l);\n}\n\nvoid LogSource::write(std::streambuf* buf)\n{\n if (buf)\n {\n // note: buf->in_avail() does not do what we want\n auto size = std::size_t(buf->pubseekoff(0, std::ios_base::cur, std::ios_base::out));\n {\n auto l = locked();\n buf->sgetn(allocWriteBuf(size, l), size);\n wakeUpSink(l);\n }\n buf->pubseekpos(0);\n }\n}\n\nchar* LogSource::allocWriteBuf(std::size_t size, LockedView<LogSourceState>& l)\n{\n const auto destPos = std::size_t(l->writeOnly.size());\n l->writeOnly.resize(destPos + size);\n return l->writeOnly.data() + destPos;\n}\n</code></pre>\n<h3>Public API Implementation</h3>\n<pre><code>//\n// Public API\n//\n\nLogStream::LogStream() :\n source(LogSource::getOrMake()),\n stream(source->msgStream())\n{}\n\nLogStream::~LogStream()\n{\n source->write(stream.rdbuf());\n stream.flush();\n stream.clear();\n}\n\nLogger::Logger(std::string_view filename) :\n d(LogSink::getOrMake(filename))\n{}\n\nLogger::~Logger()\n{\n d->finish();\n {\n std::unique_lock lock(globalMutex);\n globalSink.reset();\n d.reset();\n }\n}\n\nvoid Logger::log(std::ostringstream *stream)\n{\n if (stream && stream->rdbuf())\n {\n LogSource::getOrMake()->write(stream->rdbuf());\n stream->rdbuf()->pubsync();\n stream->clear();\n }\n}\n\nvoid Logger::log(const std::ostringstream& stream)\n{\n#if __cplusplus >= 202002L\n Logger::log(stream.view());\n#else\n if (stream.rdbuf())\n {\n LogSource::getOrMake()->write(stream.rdbuf());\n stream.rdbuf()->pubsync();\n }\n#endif\n}\n\nvoid Logger::log(std::string_view text)\n{\n LogSource::getOrMake()->write(text);\n}\n</code></pre>\n<h2>Demo</h2>\n<pre><code>#include <thread>\n#include "log.hpp"\n\nint main()\n{\n Logger logger("log.txt");\n std::thread t1([]{ Logger::log() << "tt1\\n"; });\n std::thread t2([]{ Logger::log() << "tt2\\n"; });\n Logger::log("line l1\\n");\n Logger::log("line l2\\n");\n t1.join();\n t2.join();\n return 0;\n}\n\n</code></pre>\n<p>First, a logger (log sink) is created, then two threads that log to it, as well as some logging is done from the main thread.</p>\n<h2>TODOs</h2>\n<p>Even though this is an example, somewhat contrived for brevity, it's not far from a minimal viable logger module. At minimum, the following features would need to be implemented to make it really useful:</p>\n<ol>\n<li><p>Policy of dealing with the log source buffers growing past some maximum size:</p>\n<ul>\n<li>a temporary reduction of logging level for the given source, to reduce the amount of output, if logging levels are in use,</li>\n<li>discarding the buffer, or parts of it (e.g. reduction by half),</li>\n<li>stopping the thread until the logger catches up.</li>\n</ul>\n</li>\n<li><p>Handling of timestamps: the system calls typically used to obtain time and date are relatively expensive. There are many ways of dealing with that, for example:</p>\n<ul>\n<li><p>capture the date-time using usual API, then use a hardware (CPU instruction) high resolution performance timer to add offsets to that, and refresh the date-time say once a minute,</p>\n</li>\n<li><p>capture the date-time into a global atomic variable (e.g. Unix epoch in ms into a <code>uint64_t</code>) in the sink thread, e.g. once per each source while in the source loop, and consume it in the source threads; this has an additional atomic memory access cost roughly equal to the uncontested mutex lock.</p>\n</li>\n</ul>\n</li>\n<li><p>A better string formatting library, <code>std::format</code> in C++20 is a natural choice and performs very well, or use <a href=\"https://github.com/fmtlib/fmt\" rel=\"nofollow noreferrer\">fmtlib/fmt</a> for pre-C++20 code (<code>std::format</code> was essentially adopted from fmtlib/fmt).</p>\n</li>\n<li><p>Platform-specific asynchronous file writing, i.e. use asynchronous file I/O if such is available, and have the per-sink buffers be page-aligned kernel-shared buffers, so that the logged data is not copied from the userspace to the kernel.</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-13T13:28:27.453",
"Id": "528349",
"Score": "0",
"body": "*\"Each time an allocation is performed, a global heap allocator lock is obtained\"* This is most likely not true unless you are on an old operating system. Modern memory allocators have per-thread pools they can allocate from, and a thread might not even need to use a global lock to allocate more if its pool has run out. That said, even if it doesn't serialize, it's still quite bad to perform allocations while holding a lock."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-13T13:53:35.490",
"Id": "528352",
"Score": "0",
"body": "@G.Sliepen \"This is most likely not true unless you are on an old operating system\" - this is true, but it really depends on the language runtime more than the operating system. In most cases, the runtime does its own small block allocation and only gets larger blocks from the OS. The OS has a hierarchy of page table locks for that purpose, usually, so the contention for \"large\" blocks is indeed as small as can be. On some OSes, there's a decently performing heap allocator API (like on Windows), but that's also a mostly userspace mechanism and could be thought of as a \"runtime\" library."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-13T04:49:09.847",
"Id": "267943",
"ParentId": "214004",
"Score": "5"
}
},
{
"body": "<p>Kuba makes excellent points in his answer. I'm going to present some alternatives though:</p>\n<h1>Keep it simple</h1>\n<p>A lot of complexity in your code (and also in Kuba's answer) comes from opening and closing the log file repeatedly. Things simplify greatly if you open it once and keep it open until the <code>Logger</code> is destroyed. Then the code becomes:</p>\n<pre><code>class Logger {\npublic:\n Logger(const std::string &filename): file(filename) {}\n void log( const char* text, LoggerType type);\n void log(/* other variants */);\nprivate:\n std::mutex mutex;\n std::ofstream file;\n};\n\nvoid log(const char* text, LoggerType type)\n{\n std::ostringstream stream;\n\n // Do all the formatting here without a lock\n ...\n\n // Write everything to the file in one go\n std::lock_guard lock(mutex);\n file.write(stream.rdbuf());\n}\n</code></pre>\n<p>The operating system should already buffer writes to files so it's not waiting for the message to actually have been fully written to disk; it should return quite quickly. I therefore think that, unless your program is using this class to log a huge amount of data per second, this simple approach is just as efficient as Kuba's solution.</p>\n<h1>Don't use locks at all if possible</h1>\n<p>You might not need to serialize writing to the log file at all. Either your standard library already makes writes to a file thread-safe, or the operating system provides some lower-level I/O functions that are thread-safe. (In particular, Linux's libstdc++ has thread safe writes to <code>std::ofstream</code>s, and C's <code>fwrite()</code> is thread-safe <a href=\"https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/fwrite?redirectedfrom=MSDN&view=msvc-160\" rel=\"nofollow noreferrer\">even on Windows</a>.)\nThe only requirement is that a whole log message must be written to the file in a single I/O operation, otherwise messages can still be garbled as two threads interleave writing parts of the log message to the same stream.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T17:29:54.040",
"Id": "528462",
"Score": "0",
"body": "*it should return quite quickly* It will syscall in a percentage of cases under the lock, and that's a rather bad idea. Well performing logging code is hardly trivial because the trivial ones can be easily made to perform extremely badly, precisely when it has the worst impact on application performance - under high load. Never mind that `file.write` adds another layer of unnecessary locking - you may as well use `fwrite` and get rid of the explicit lock in your implementation :) And the code I present is nothing compared to any fleshed out app-side logging solution anyway :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T17:31:12.623",
"Id": "528463",
"Score": "0",
"body": "I'd rather say that keeping it simple absolutely requires the use of a logging library, since - presumably - decent logging libraries are implemented with performance in mind and will do it right."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-14T19:43:32.657",
"Id": "528487",
"Score": "0",
"body": "@Kubahasn'tforgottenMonica There are a lot of logging libraries out there, it's hard to tell which are decent. Which ones would you recommend?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-13T14:04:38.530",
"Id": "267964",
"ParentId": "214004",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "267943",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T05:24:30.600",
"Id": "214004",
"Score": "3",
"Tags": [
"c++",
"multithreading",
"thread-safety",
"locking"
],
"Title": "An attempt of replacing CRITICAL_SECTION with std::mutex and std::lock_guard"
} | 214004 |
<blockquote>
<p>Given a sorted list of integers, square the elements and give the
output in sorted order.</p>
<p>For example, given [-9, -2, 0, 2, 3], return [0, 4, 4, 9, 81].</p>
</blockquote>
<p>My solution 1:</p>
<pre><code>const square = el => el * el;
const sortAsc = (a, b) => a - b;
const sortSquare = list => list
.map(square)
.sort(sortAsc);
console.log(sortSquare([-9, -2, 0, 2, 3]));
</code></pre>
<p>My solution 2:</p>
<pre><code>const sortSquare2 = list => {
list.sort((a, b) => Math.abs(a) - Math.abs(b));
for (let i = 0; i < list.length; i++) {
list[i] = Math.pow(list[i], 2);
}
return list;
};
console.log(sortSquare2([-9, -2, 0, 2, 3]));
</code></pre>
<p>Is there a faster solution? I have the feeling you can do something with the fact that the list is sorted to begin with. But I can't think of a good one.</p>
| [] | [
{
"body": "<p>I can give you a functional programming and ES6 related thing instead of a performance improvement </p>\n\n<hr>\n\n<h1><a href=\"https://wiki.haskell.org/Pointfree\" rel=\"nofollow noreferrer\">Pointfree</a></h1>\n\n<p>Pointfree is a programming paradigm in which you try to avoid the argument you want to transform.</p>\n\n<p>So we could avoid <code>sortSquare = list => ...</code></p>\n\n<pre><code>const sortSquare = compose(\n sort(sortAsc), \n map(square)\n)\n</code></pre>\n\n<p>Where <code>sort</code> and <code>map</code> are <a href=\"https://wiki.haskell.org/Currying\" rel=\"nofollow noreferrer\">curried functions</a> and <code>compose</code> is a <a href=\"https://www.khanacademy.org/math/algebra2/manipulating-functions/function-composition/a/finding-and-evaluating-composite-functions\" rel=\"nofollow noreferrer\">composition of two functions</a> in the form of <span class=\"math-container\">\\$f ∘ g\\$</span> which means <span class=\"math-container\">\\$f(g(x))\\$</span></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const map = f => xs => xs.map(f)\nconst sort = f => xs => xs.sort(f)\n\nconst compose = (f, g) => x => f(g(x))\n\nconst square = el => el ** 2\nconst sortAsc = (a, b) => a - b\n\nconst sortSquare = compose(\n sort(sortAsc),\n map(square)\n)\n\nconsole.log(sortSquare([-9, -2, 0, 2, 3]));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<hr>\n\n<h1><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Exponentiation_(**)\" rel=\"nofollow noreferrer\">Exponentiation</a> in ES6</h1>\n\n<p>Since ES6 it is possible to use the <code>**</code>-operator.</p>\n\n<blockquote>\n <pre><code>const square = el => el * el;\n</code></pre>\n</blockquote>\n\n<pre><code>const square = el => el ** 2;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T07:37:47.140",
"Id": "214011",
"ParentId": "214006",
"Score": "2"
}
},
{
"body": "<p>If you start at both ends and compare these values, you can step down towards the center, unshifting the values, squaring them and unshifting them to the resulting array.</p>\n\n<p>You don't need to square the values until you add them to the array. You can compare to find the greater value by negating the left side. </p>\n\n<p>One <span class=\"math-container\">\\$O(n)\\$</span> solution is as follows</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 sortSquares(arr) {\n const res = [];\n var start = 0; end = arr.length - 1, idx = end;\n while (start <= end) {\n res[idx--] = (-arr[start] > arr[end] ? arr[start++] : arr[end--]) ** 2;\n }\n return res;\n}\n\n// Test code\n[\n [-9,-5,-0.5,0.6,1, 2, 3,8],\n [1, 2, 3,8],\n [-10, -8, -3, -1, -1, 1, 1, 1], \n [0.6,1, 2, 3,8],\n [-9,-6,-3,-2,-1],\n [-9,-6,-3,-2,-1,1,2,3,6,9],\n].forEach(a => log(a, sortSquares(a)));\n\n\nfunction log(data, data1) {\n data = \"[\" + data + \"] -=>> [\" + data1 + \"]\";\n info.appendChild(Object.assign(document.createElement(\"div\"),{textContent: data}));\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><code id=\"info\"></code></code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T12:13:56.290",
"Id": "413959",
"Score": "2",
"body": "Is it really a good idea to fill an array with `unshift`? It sounds inefficient. You could easily put each element at its correct position right away. `res[end-start] = ...`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T12:40:22.523",
"Id": "413965",
"Score": "0",
"body": "@Kruga Good point, i was not on the ball."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T18:05:24.147",
"Id": "414011",
"Score": "0",
"body": "The resulting code is simply beautiful and solves the problem efficiently. Masterful I have to say.\n\nHmm....may I have a tiny question? I just noticed, is there a reason why you chose an if/else over a ternary operator?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T19:53:09.243",
"Id": "414024",
"Score": "0",
"body": "@thadeuszlay Eeeck my 3rd stuff up for the day... :(.The original version unshifted to the array rather than assigned to an array index and thus was not suited for a ternary. Good call `res[idx--] = (-arr[start] > arr[end] ? arr[start++] : arr[end--]) ** 2;` is far more concise."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T20:09:39.307",
"Id": "414025",
"Score": "0",
"body": "May I ask what is your favorite language and why?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T23:22:45.773",
"Id": "414038",
"Score": "0",
"body": "@thadeuszlay That changes over time, currently I spend most of my time writing JS, it's a great language. Main reason, no writing overhead (type declarations, casting, etc) It has a great set of API's, including debugging (dev tools) is cross platform and will practically run on anything. It's only downside is its sandboxes environment, and speed, for that I prefer good old C. C gives you a direct link to the hardware and blinding speed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T07:50:38.163",
"Id": "414049",
"Score": "0",
"body": "Since when are writing Software and what do you think is the best way to improve as a software developer?"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T10:33:38.230",
"Id": "214024",
"ParentId": "214006",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "214024",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T06:31:36.900",
"Id": "214006",
"Score": "4",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"functional-programming",
"ecmascript-6"
],
"Title": "square the elements of a sorted list and give the output in sorted order"
} | 214006 |
<p>A an integer permutation <code>array[]</code> is said to be <strong><em>cyclic</em></strong> if and only if we can choose an arbitrary element at position <code>i</code>, move it to the <code>array[i]</code>'s position, move the <code>array[i]</code>'s element to <code>array[array[i]]</code>'s position, and finally end up to the <code>i</code>th position. For example, <span class="math-container">\$\langle 1, 2, 0 \rangle\$</span> is cyclic, whereas <span class="math-container">\$\langle 1, 0, 2 \rangle\$</span> is not since if we start from 2, we sill end up in an infinite loop. My attempt is as follows:</p>
<pre><code>package net.coderodde.math;
import java.util.Objects;
/**
* This class checks that a given permutation consists of a single cycle
* covering the entire sequence. The idea is that if the input array is
* {@code 1, 0, 2}, it returns {@code false} since 2 is in its correct position.
* On the other hand, {@code 1, 2, 0} returns {@code true} since it consists of
* only one permutation cycle.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Feb 22, 2019)
*/
public class PermutationCyclicity {
private static final String NUMBER_OUT_OF_BOUNDS_EXCEPTION_FORMAT =
"array[%d] = %d, array.length = %d";
public boolean isCyclic(int[] array) {
check(array);
int nextNumber = array[array[0]];
int visitedNumbers = 1;
while (nextNumber != array[0]) {
nextNumber = array[nextNumber];
visitedNumbers++;
}
return visitedNumbers == array.length;
}
private void check(int[] array) {
checkArrayHasLength(array);
checkArrayContentsWithinBounds(array);
checkArrayElements(array);
}
private void checkArrayHasLength(int[] array) {
Objects.requireNonNull(array, "The input array is null.");
if (array.length == 0) {
throw new IllegalArgumentException("The array has length zero.");
}
}
private void checkArrayContentsWithinBounds(int[] array) {
for (int i = 0; i < array.length; i++) {
int num = array[i];
if (num < 0 || num >= array.length) {
String exceptionMessage =
String.format(NUMBER_OUT_OF_BOUNDS_EXCEPTION_FORMAT,
i,
num,
array.length);
throw new IllegalArgumentException(exceptionMessage);
}
}
}
private void checkArrayElements(int[] array) {
int[] counts = new int[array.length];
for (int i : array) {
if (++counts[i] > 1) {
throw new IllegalArgumentException(
"The value " + i + " appears more than once.");
}
}
}
public static void main(String[] args) {
PermutationCyclicity pc = new PermutationCyclicity();
System.out.println(pc.isCyclic(new int[] { 1, 2, 3, 0 }));
try {
pc.isCyclic(new int[] { 1, 0, 1 });
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
try {
pc.isCyclic(new int[] { 1 });
} catch (Exception ex) {
System.out.println(ex.getLocalizedMessage());
}
System.out.println(pc.isCyclic(new int[] { 1, 0, 2 }));
}
}
</code></pre>
<p><strong>Critique request</strong></p>
<p>I would like to hear comments regarding exception throwing and naming conventions, yet feel free to tell me anything that comes to mind.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T11:15:39.857",
"Id": "413955",
"Score": "2",
"body": "The description of what the method does in the class-level documentation seems much more accurate than the description given in the question. Given just the definition of the first sentence of the question I would write a method whose body is just ´return true;` because it seems to ask whether the permutation can be decomposed into cycles, and *every* permutation can be."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T12:31:40.120",
"Id": "413963",
"Score": "0",
"body": "@PeterTaylor: Indeed, that confused me first. https://en.wikipedia.org/wiki/Cyclic_permutation offers two definitions: *“A permutation is called a cyclic permutation if and only if it has a single nontrivial cycle”* vs *“Some authors restrict the definition to only those permutations which consist of one nontrivial cycle”.* – From the first sentence in the class-level documentation (and the implementation) it seems that the latter (stricter) definition is meant here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T12:46:08.980",
"Id": "413968",
"Score": "0",
"body": "On the other hand, the identity permutation of a single element (0) is not cyclic according to both definitions, but this code considers it to be cyclic – I am still confused!"
}
] | [
{
"body": "<p>Here</p>\n\n<blockquote>\n<pre><code>int nextNumber = array[array[0]];\nint visitedNumbers = 1;\n\nwhile (nextNumber != array[0]) {\n nextNumber = array[nextNumber];\n visitedNumbers++;\n}\n</code></pre>\n</blockquote>\n\n<p>you determine the length of the orbit starting <code>array[0]</code>. If you start at <code>0</code> instead then some array lookups are saved, and I find it easier to understand:</p>\n\n<pre><code>int nextNumber = array[0];\nint visitedNumbers = 1;\n\nwhile (nextNumber != 0) {\n nextNumber = array[nextNumber];\n visitedNumbers++;\n}\n</code></pre>\n\n<p>And with a do-while loop the initial array lookup can be made part of the loop:</p>\n\n<pre><code>int currentNumber = 0;\nint visitedNumbers = 0;\n\ndo {\n currentNumber = array[currentNumber];\n visitedNumbers++;\n} while (currentNumber != 0);\n</code></pre>\n\n<hr>\n\n<p><em>Further suggestions:</em></p>\n\n<p>Checking for duplicate array elements is not necessary if you <em>limit</em> the number of iterations:</p>\n\n<pre><code>int currentNumber = 0;\nint visitedNumbers = 0;\n\ndo {\n currentNumber = array[currentNumber];\n visitedNumbers++;\n} while (visitedNumbers <= array.length && currentNumber != 0);\n</code></pre>\n\n<p>This saves one array traversal and the additional storage in <code>checkArrayElements()</code>. The only downside is that calling the function with an invalid permutation now possibly returns <code>false</code> instead of throwing an error.</p>\n\n<p>Similarly, the “bounds check” can be made directly in that loop. That might be viewed as a violation of the “separation of concerns” principle, but saves one array traversal.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T08:54:03.627",
"Id": "214014",
"ParentId": "214013",
"Score": "7"
}
},
{
"body": "<p>I would prefer <code>checkArrayValidity</code> over the generic <code>check</code> and <code>PermutationCyclicityChecker</code> checker over <code>PermutationCyclicity</code> as the class implements functionality, not state.</p>\n\n<p>Maybe move exception message formatting to dedicated exception classes and unify the message format in all cases (one provides indexes where error occurs, the other just the offending value).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T10:04:16.130",
"Id": "214019",
"ParentId": "214013",
"Score": "1"
}
},
{
"body": "<p>For the task to check if a permutation is cyclic, the code works. But we have no reusable code because it works only for these task, since the methods <code>checkArrayHasLength</code>, <code>checkArrayContentsWithinBounds</code> and <code>checkArrayElements</code> are <code>private</code>, return <code>void</code> and throw an <code>IllegalArgumentException</code>.</p>\n\n<h1>Null Checking</h1>\n\n<p>The method <code>checkArrayHasLength</code> checks for <code>null</code>, but <code>checkArrayElements</code> doesn`t.</p>\n\n<p>So the method <code>checkArrayElements</code> is dependent on <code>checkArrayHasLength</code> in the method <code>check</code> and you can't call them in an different order without to get your personalized exception message.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>checkArrayHasLength(null); // personalized error message\n</code></pre>\n\n<pre class=\"lang-java prettyprint-override\"><code>checkArrayElements(null); // non personalized error message\n</code></pre>\n\n<h1>Naming</h1>\n\n<p>After I looked into <code>checkArrayHasLength</code> I understand, that it means it checks if an array is not empty. For me, maybe because I'm not a native English speaker, the name <code>checkArrayIsNotEmpty</code> would be better.</p>\n\n<p>The name <code>checkArrayElements</code> is in my eyes useless. This name could use every method that do some validation on an array. I think the name <code>checkArrayForDuplicateElements</code> would be better.</p>\n\n<h2><a href=\"https://blog.codinghorror.com/code-smells/\" rel=\"nofollow noreferrer\">Type Embedded in Name</a></h2>\n\n<blockquote>\n <p>Avoid placing types in method names; it's not only redundant, but it forces you to change the name if the type changes.</p>\n</blockquote>\n\n<p>Each method includes <code>Array</code>, which is redundant because the parameter list already includes the datatype. If you want to switch from an array to a list you need to rename all methods and it could be possible to forget one method..<br>\nNew method names could be: <code>checkIsNotEmpty</code>, <code>checkForElementOutOfBounds</code> and <code>checkForDuplicateElements</code>.</p>\n\n<hr>\n\n<h1>Make it more Abstract</h1>\n\n<p>As already mention you have three methods that are <code>private</code>, but they could be <code>public</code> to.</p>\n\n<h2>Rename <code>PermutationCyclicity</code></h2>\n\n<p>If we rename <code>PermutationCyclicity</code> to <code>Permutation</code> it would make sense to have methods that check for the length, the bounds and the number of occurrence of elements. These methods could now return a <code>boolean</code> instead of <code>void</code> and for that I would suggest to rename again all methods with an <code>is</code>, <code>are</code> or <code>has</code> prefix instead of <code>check</code>.</p>\n\n<h3>As a Utility-Class</h3>\n\n<pre class=\"lang-java prettyprint-override\"><code>class Permutations {\n\n public boolean isCyclic(int[] array) {\n check(array);\n int nextNumber = array[array[0]];\n int visitedNumbers = 1;\n\n while (nextNumber != array[0]) {\n nextNumber = array[nextNumber];\n visitedNumbers++;\n }\n\n return visitedNumbers == array.length;\n }\n\n private void check(int[] array) {\n if (isNotEmpty(array))\n throw new IllegalArgumentException(\"The array has length zero.\");\n if (hasElementOutOfBounds(array))\n throw new IllegalArgumentException(\"Argument contains elements that are not in the bound\");\n if (hasDuplicateElements(array))\n throw new IllegalArgumentException(\"Argument contains elements that occurs multiple times\");\n }\n\n public boolean isNotEmpty(int[] array) {\\* ... *\\}\n\n public boolean hasElementOutOfBounds(int[] array) {\\* ... *\\}\n\n public boolean hasDuplicateElements(int[] array) {\\* ... *\\}\n\n}\n</code></pre>\n\n<h3>As a First Class Collection</h3>\n\n<p>The First Class Collection is an idea of the <a href=\"https://www.cs.helsinki.fi/u/luontola/tdd-2009/ext/ObjectCalisthenics.pdf\" rel=\"nofollow noreferrer\">Object Calisthenics</a>.</p>\n\n<blockquote>\n <p>Any class that contains a collection should contain no other member variables. Each collection gets wrapped in its own class, so now behaviors related to the collection have a home. </p>\n</blockquote>\n\n<pre class=\"lang-java prettyprint-override\"><code>class Permutation {\n\n private int[] values;\n\n public Permutation(int[] values) {\n this.values = Objects.requireNonNull(values, \"The argument is null.\");\n }\n\n public boolean isCyclic() {\n check();\n int nextNumber = values[values[0]];\n int visitedNumbers = 1;\n\n while (nextNumber != values[0]) {\n nextNumber = values[nextNumber];\n visitedNumbers++;\n }\n\n return visitedNumbers == values.length;\n }\n\n private void check() {\n if (isNotEmpty())\n throw new IllegalArgumentException(\"The array has length zero.\");\n\n if (hasElementOutOfBounds())\n throw new IllegalArgumentException(\"Argument contains elements that are not in the bound\");\n\n if (hasDuplicateElements())\n throw new IllegalArgumentException(\"Argument contains elements that occurs multiple times\");\n }\n\n public boolean isNotEmpty() {\\* ... *\\}\n\n public boolean hasElementOutOfBounds() {\\* ... *\\}\n\n public boolean hasDuplicateElements() {\\* ... *\\}\n\n}\n</code></pre>\n\n<h2>Does it need to Throw?</h2>\n\n<p>I'm not if the method <code>isCyclic</code> needs to throw an <code>IllegalArgumentException</code>. From my feelings here a permutation can be cyclic or not - <code>true</code> or <code>false</code>. Additional if a client forgot to catch the <code>IllegalArgumentException</code>, he will never get to know the reason.</p>\n\n<p>If you want to make sure the client should get always the reason use not a <a href=\"https://docs.oracle.com/javase/7/docs/api/java/lang/RuntimeException.html\" rel=\"nofollow noreferrer\"><code>RuntimeException</code></a>, because they don't have to be checked.</p>\n\n<p>A other way would to use an <a href=\"https://en.wikipedia.org/wiki/Algebraic_data_type\" rel=\"nofollow noreferrer\">algebraic data type</a>. The <a href=\"http://www.functionaljava.org/javadoc/4.4/functionaljava/fj/data/Either.html\" rel=\"nofollow noreferrer\"><code>Either</code></a> can be used to get a result or an error message.</p>\n\n<p>Or just simply return false and the client has to find the reason:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>class Permutation {\n\n private int[] values;\n\n public Permutation(int[] values) {\n this.values = Objects.requireNonNull(values, \"The argument is null.\");\n }\n\n public boolean isCyclic() {\n if (isEmpty() || hasElementOutOfBounds() || hasDuplicateElements())\n return false;\n\n // ..\n\n return visitedNumbers == values.length;\n }\n\n public boolean isEmpty() {\\* ... *\\}\n\n public boolean hasElementOutOfBounds() {\\* ... *\\}\n\n public boolean hasDuplicateElements() {\\* ... *\\}\n\n}\n</code></pre>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n Permutation permutation = new Permutation(new int[] {1, 2, 3, 0});\n\n if (permutation.isCyclic())\n System.out.println(\"nice\");\n else {\n if (!permutation.areAllElementsWithinBounds())\n System.out.println(\"not all elements are in bound\");\n // ..\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T11:56:51.967",
"Id": "413957",
"Score": "0",
"body": "The current logic with `&&` is still wrong, and the function names (e.g. “isOccurrenceOfAllElementsMoreThanOnce”) are confusing. – You probably mean `if (isEmpty() || hasElementOutOfBounds() || hasDuplicateElements())`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T12:05:17.657",
"Id": "413958",
"Score": "0",
"body": "@MartinR thank you! The suggested method names are much better"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T15:25:42.533",
"Id": "413996",
"Score": "0",
"body": "For `Permutation` The check should go in the constructor and should throw IllegalArgumentException. For `Permutations` methods should be static."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T10:11:52.963",
"Id": "214021",
"ParentId": "214013",
"Score": "3"
}
},
{
"body": "<blockquote>\n<pre><code>/**\n * This class checks that a given permutation consists of a single cycle \n * covering the entire sequence. The idea is that if the input array is \n * {@code 1, 0, 2}, it returns {@code false} since 2 is in its correct position.\n * On the other hand, {@code 1, 2, 0} returns {@code true} since it consists of\n * only one permutation cycle.\n * \n * @author Rodion \"rodde\" Efremov\n * @version 1.6 (Feb 22, 2019)\n */\n</code></pre>\n</blockquote>\n\n<p>I find the description clear, although I might reword from \"<em>The idea is that...</em>\" to</p>\n\n<pre><code>For example, given {@code 1, 0, 2}, it returns {@code false} because that permutation\nconsists of two disjoint cycles {@code (1, 0), (2)}.\n</code></pre>\n\n<p>I'm not clear on why this check should need a class for itself. I would expect either to have a <code>Permutation</code> class which could have an instance <code>isCyclic</code> method, or to have a <code>PermutationUtils</code> class with a static <code>isCyclic</code> method.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> private static final String NUMBER_OUT_OF_BOUNDS_EXCEPTION_FORMAT = \n \"array[%d] = %d, array.length = %d\";\n</code></pre>\n</blockquote>\n\n<p>Thumbs up for this. I'm always glad to see details in exception messages.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public boolean isCyclic(int[] array) {\n</code></pre>\n</blockquote>\n\n<p>No method-level javadoc? At the very least, I would like to see something telling me that the class considers that the empty array is not a valid permutation, because I think it is.</p>\n\n<p><code>array</code> is not a useful name. I would go with <code>perm</code>; others would prefer to avoid the abbreviation and call it <code>permutation</code>. I can also see an argument for <code>pi</code> as that is the symbol most commonly used to represent a permutation.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> check(array);\n</code></pre>\n</blockquote>\n\n<p>Check what? How about <code>checkIsValidPermutation</code>?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> int nextNumber = array[array[0]];\n int visitedNumbers = 1;\n\n while (nextNumber != array[0]) {\n nextNumber = array[nextNumber];\n visitedNumbers++;\n }\n\n return visitedNumbers == array.length;\n</code></pre>\n</blockquote>\n\n<p>Coming back to my earlier comment about <code>PermutationUtils</code>: I find it hard to envisage a library which has a need for <code>isCyclic</code> but not for finding the cycle decomposition of a permutation, so I'm surprised that the implementation isn't <code>return cycleDecomposition(array).length == 1;</code></p>\n\n<hr>\n\n<blockquote>\n<pre><code> private void check(int[] array) {\n checkArrayHasLength(array);\n checkArrayContentsWithinBounds(array);\n checkArrayElements(array);\n }\n</code></pre>\n</blockquote>\n\n<p>I see this as really two checks: <code>checkNotNullOrEmpty</code> and <code>checkIsPermutation</code>. Of course, if you use a <code>Permutation</code> class then these would be handled by the constructor and at most you'd have to check that the array is not empty.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> public static void main(String[] args) {\n PermutationCyclicity pc = new PermutationCyclicity();\n System.out.println(pc.isCyclic(new int[] { 1, 2, 3, 0 }));\n</code></pre>\n</blockquote>\n\n<p>A good unit test compares the observed value / behaviour against the expected value / behaviour. This test requires you to either remember the expected output or figure it out from first principles when you come back to maintain the code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T11:37:44.547",
"Id": "214028",
"ParentId": "214013",
"Score": "1"
}
},
{
"body": "<p>I see several flaws here:</p>\n\n<ul>\n<li><p>It's wrong. It returns false for [0,1,2] or [1,0,2], which are a valid cyclic permutations. A permutation is cyclic if it contains at most one nontrivial cycle. [1,0,3,2] would be a non-cyclic permutation.</p></li>\n<li><p>It throws on an empty array, which is a valid cyclic permutation. Return true instead.</p></li>\n<li><p>It throws if there are duplicates or out-of-range values. Just return false to indicate it's not a cyclic permutation.</p></li>\n<li><p>There are three passes over the array, which is unneccessary.</p></li>\n<li><p>It allocates O(n) memory to check for duplicates, which is unneccessary.</p></li>\n<li><p>The methods are not declared static, even though they are not stateful.</p></li>\n</ul>\n\n<p>Below is a version that fixes all of the above. Note that duplicate elements always lead to infinite loops (you never get back to zero), so you can abort after you visited more numbers than there are elements.</p>\n\n<pre><code>public class Permutation\n{\n public static bool isCyclic(int[] array)\n {\n // find the first out-of-place element\n int start = 0;\n while (start < array.length && array[start] == start)\n {\n start++;\n }\n\n // find the number of out-of-place elements, also check for out-of-bounds elements\n int length = 0;\n for (int i = start; i < array.length; i++)\n {\n if (array[i] < 0 || array[i] >= array.length)\n {\n return false;\n }\n if (array[i] != i)\n {\n length++;\n }\n }\n\n // no out-of-place elements, cyclic by definition\n if (length == 0)\n {\n return true;\n }\n\n // check if the cycle starting from the first out-of-place element contains\n // all out-of-place elements, which makes it the only cycle\n int visited = 1;\n for (int next = array[start]; next != start; next = array[next], visited++)\n {\n // we cannot have visited all elements without reaching start again, so we\n // must have been caught in an infinite loop due to duplicate elements\n if (visited == length)\n {\n return false;\n }\n }\n return visited == length;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T12:49:33.027",
"Id": "413969",
"Score": "2",
"body": "I am not very familiar with that topic, but there seem to be different definitions of what a cyclic permutation is. https://en.wikipedia.org/wiki/Cyclic_permutation offers “has a single nontrivial cycle” and “consists of one nontrivial cycle.”"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T06:48:07.917",
"Id": "414242",
"Score": "0",
"body": "Wolfram Alpha has a completely different definition from wikipedia."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T11:44:15.190",
"Id": "214029",
"ParentId": "214013",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "214014",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T08:22:30.210",
"Id": "214013",
"Score": "5",
"Tags": [
"java",
"algorithm",
"array",
"combinatorics"
],
"Title": "Checking if an integer permutation is cyclic in Java"
} | 214013 |
<p>I came up with this solution to another exercise out of John Zelle's Programming book.</p>
<pre><code>#bust.py --- Simulates multiple games of blackjack with each possible dealer starting card and estimates
# the probability that the dealer will bust
import random
def intro():
pass
def takecard():
card = random.randint(1, 10)
has_ace = False
#Randomly choose if the 1 is an ace
if card == 1:
has_ace = random.choice([True, False])
return card, has_ace
def sim_one_game(starter):
#For simulating the ace
if starter == 12:
starter = 1
has_ace = True
total = starter
while total <= 17:
card, has_ace = takecard()
total += card
#Ace is valued at 11 when it would produce a stopping total
if has_ace == True and total + 10 >= 17 and total + 10 <= 21:
total += 10
return total
def sim_n_games(starter, game_count):
busts = 0
for i in range(game_count):
score = sim_one_game(starter)
if score > 21:
busts += 1
return busts
def sim_each_card(game_count):
bustsls = []
for i in range(1, 12):
bustsls.append(sim_n_games(i, game_count))
return bustsls
def output(bustsls, game_count):
print("Busts for Starting Card A: {} out of {} games. ({:0.1%})".format(bustsls[10], game_count, bustsls[10] / game_count))
for card in range(1, 11):
print("Busts for Starting Card {}: {} out of {} games. ({:0.1%})".format(card, bustsls[card - 1], game_count, bustsls[card - 1] / game_count))
def main():
intro()
game_count = int(input("\nHow many rounds to simulate? "))
bustsls = sim_each_card(game_count)
output(bustsls, game_count)
if __name__ == "__main__": main()
</code></pre>
<p>It works pretty well, although when profiling it with 100.000 iterations it takes ~5 seconds to finish. When profiling I noticed that all the calls to random take up quite some time. </p>
<p>Anyone know a better way to solve this? Please note that I am a beginner and there are a lot of things I haven't learned anything about yet, but I'll read into all of your suggestions!</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T09:22:59.287",
"Id": "214016",
"Score": "1",
"Tags": [
"python",
"beginner",
"python-3.x",
"playing-cards",
"simulation"
],
"Title": "Blackjack simulator for Probability of a dealer bust for each starting card"
} | 214016 |
<p>This is my React component for looping a component i.e. I don't want to use <code>MAP</code> or <code>FOREACH</code> in React Component's HTML.</p>
<pre><code>import React from 'react';
/**
* @param {items} from props
* @description -> Works with array of items and render only one children object inside it, ith data object will be available in children component props.
*/
const RFor = (props) => {
const { items } = props || [];
return items.map((data, index) => <div key={index}>{React.cloneElement(props.children, data)}</div>)
}
export default RFor;
</code></pre>
<p>And this is how I use to iterate my component.</p>
<pre><code><RFor items={TEMP_DATA_ARRAY}>
<Item />
</RFor>
</code></pre>
<p>What this will do is generate <code><Item /></code> till <code>TEMP_DATA_ARRAY</code> and each object is going to be available with <code>data</code> property inside <code><Item /></code>.
I want to optimize it and this is the best approach I can come up with.</p>
| [] | [
{
"body": "<p>This approach is not bad but I'd highlight a few issues:</p>\n\n<ul>\n<li>You wrap each element with a <code><div></code>, it's unnecessary and for a very long list you create many useless elements. This also prevents <code><RFor></code> to be conveniently used (for example) to generate rows in a table.</li>\n<li>You're assigning <code>data</code> to the properties of each item. While this might be convenient it's also fragile: what if an object as a property named <code>key</code>, or <code>children</code>, <code>ref</code> or...anything else already used? I'd assign <code>data</code> to a single property.</li>\n<li><code>const { items } = props || []</code> does not do what you, probably, think it's doing. <code>[]</code> won't be the default if <code>items</code> is falsy but the default if <code>props</code> is falsy. The correct syntax, if the value is <code>undefined</code> is <code>const { items = [] } = props;</code>. If you want to handle also <code>null</code> then you can't destructure: <code>const items = props.items || [];</code>.</li>\n<li>To use index as <code>key</code> is, more often than not, a terrible idea if the list isn't fixed (for example if you can remove/add elements anywhere in the list). Leave this responsibility to the <em>caller</em> because it's the only one with enough knowledge to pick a sensible unique ID (which in <em>some very specific cases</em> can even be the index).</li>\n<li>You're passing <code>props.children</code> directly to <code>React.cloneElement</code> however it expects a single element and <code>children</code> can be an array. Enforce this rule using <code>React.only()</code>.</li>\n</ul>\n\n<p>To put things together (leaving out the <code>key</code> for the moment):</p>\n\n<pre><code>const RFor = props => {\n const items = props.items || [];\n return items.map(data => React.cloneElement(React.only(props.children), { data });\n};\n</code></pre>\n\n<p>All these said you may start wondering if you even need <code>RFor</code>, let's compare with few alternatives:</p>\n\n<pre><code><RFor items={TEMP_DATA_ARRAY}>\n <Item />\n<RFor>\n</code></pre>\n\n<p>Vs</p>\n\n<pre><code>{TEMP_DATA_ARRAY.map(data => <Item key={data.id} {...data} />)}\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>{TEMP_DATA_ARRAY.map(data => <Item key={data.id} data={data} />)}\n</code></pre>\n\n<p>I don't see any benefit (note that you may, instead of <code>children</code> use a property like:</p>\n\n<pre><code><RFor items={TEMP_DATA_ARRAY} component={Item} />\n</code></pre>\n\n<p>Also note that to solve the <code>key</code> problem you might use a render function:</p>\n\n<pre><code><RFor items={TEMP_DATA_ARRAY}>\n {data => <Item key={data.key} data={data} />}\n<RFor>\n</code></pre>\n\n<p><code>RFor</code> IMHO makes sense only if it adds any other value over <code>map()</code>, it might be filtering or it might be part of an abstraction to build a <em>presentation</em> component with <em>templates</em> (with properties like <code>controlTemplate</code>, <code>headerTemplate</code> and <code>itemTemplate</code> as you often see in WPF).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T12:23:24.443",
"Id": "413960",
"Score": "0",
"body": "Hi! Thanks for your answer. I really appreciate it.\nWell, RFor is just made for abstraction! And you can clearly see the difference between the code you wrote with RFor vs Map. RFor is much readable.\nAnyway thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T12:25:58.690",
"Id": "413961",
"Score": "1",
"body": "Hmmmm well, if there isn't any other added value then I don't _feel_ it's any more readable than a plain simple `map()` (especially because you REALLY have to address the `key` issue then you probably end-up with a render function) but that just my personal POV (even if I appreciate the `dom-repeat` thing in Polymer)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T12:08:23.863",
"Id": "214031",
"ParentId": "214017",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T09:25:07.977",
"Id": "214017",
"Score": "1",
"Tags": [
"react.js",
"jsx"
],
"Title": "React For loop component"
} | 214017 |
<p>I have the following function that is called via signal. 1) check if incluencer exists. 2) Increase discount by +1. Currently, I hit the database twice. Is there a better way to write that? Additionally, I wonder I can check 2) all on a database level so I don't need the for-loop.</p>
<pre><code>@receiver(signal=charge_succeeded)
@transaction.atomic
def create_influencer_transaction(sender, order, charge, **kwargs):
order_exists = Transaction.objects.filter(order=order).exists()
if order_exists:
return None
# 1) Check if influencer exists
first_order_item = order.order_items.first()
influencer = first_order_item.social_referral
if not influencer:
return None
total_points_earned = order.order_items.aggregate(
total=Sum(
F('unit_points_earned') * F('quantity'),
output_field=IntegerField()
)
)['total'] or 0
Transaction.objects.create(
[...]
)
# 2) Redeemed amount + 1
for order_item in order.order_items.all():
social_discount = order_item.social_discount
if social_discount:
social_discount.redeemed_amount = F('redeemed_amount') + 1
social_discount.save(update_fields=['redeemed_amount'])
break
</code></pre>
<p>models.py</p>
<pre><code>class OrderItem(AbstractItem, AbstractDiscountItem, AbstractSocialItem):
order = models.ForeignKey(
[...]
)
social_discount = models.ForeignKey(
'discounts.SocialDiscount',
on_delete=models.PROTECT,
related_name='order_items',
null=True,
blank=True,
) # PROTECT = don't allow to delete the discount if an order_item exists
class SocialDiscount(AbstractDiscount):
event = models.OneToOneField(
[...]
) # CASCADE = delete the discount if the event is deleted
tickets = models.ManyToManyField(
[...]
)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T12:40:17.053",
"Id": "413964",
"Score": "0",
"body": "@MathiasEttinger yes of course. I added the models.py schema. It's handled as `ForeignKey`. Many order_items can have the same `socialdiscount`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T13:04:51.193",
"Id": "413976",
"Score": "0",
"body": "Thanks for that, just one last thing, am I safe assuming `redeemed_amount` is an `IntegerField`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T13:05:37.723",
"Id": "413977",
"Score": "0",
"body": "Yes, that's correct."
}
] | [
{
"body": "<p>Your step 2 can be done entirely in DB by <a href=\"https://docs.djangoproject.com/en/dev/ref/models/querysets/#filter\" rel=\"nofollow noreferrer\">filtering</a> and <a href=\"https://docs.djangoproject.com/en/dev/topics/db/queries/#limiting-querysets\" rel=\"nofollow noreferrer\">limiting</a> your <code>order_items</code>. And then <a href=\"https://docs.djangoproject.com/en/2.1/ref/models/querysets/#update\" rel=\"nofollow noreferrer\">updating</a> it to contain the desired value. Note that the <a href=\"https://docs.djangoproject.com/en/2.1/ref/models/expressions/#django.db.models.F\" rel=\"nofollow noreferrer\"><code>F</code> objects documentation</a> already mention that use of a queryset update method. So we could imagine something like:</p>\n\n<pre><code>order.order_items.filter(social_discount__isnull=False)[:1].update(social_discount__redeemed_amount=F('social_discount__redeemed_amount') + 1)\n</code></pre>\n\n<p>Except this doesn't work:</p>\n\n<ol>\n<li>we cannot use <code>update</code> after slicing a queryset;</li>\n<li>we cannot update fields of related models anyway.</li>\n</ol>\n\n<p>Instead we must use the relationship backwards and filter/update on the <code>SocialDiscount</code> model, the filter being the subset of <code>OrderItem</code>s we are interested in:</p>\n\n<pre><code>order_item = order.order_items.filter(social_discount__isnull=False)[:1]\n# Note that order_item is still a queryset and has not hit the database yet\nSocialDiscount.objects.filter(order_items__in=order_item).update(redeemed_amount=F('redeemed_amount') + 1)\n</code></pre>\n\n<p>Even though this only hit the database once, this will update <strong>all</strong> <code>SocialDiscount</code> objects that are related to the one <code>order_item</code> specified by the queryset above. If it ever can mean that more than one object is updated and you don't want that, you can still remove the <code>for</code> loop using this two-queries code:</p>\n\n<pre><code>social_discount = order.order_items.filter(social_discount__isnull=False).select_related('social_discount').first().social_discount\nsocial_discount.redeemed_amount = F('redeemed_amount') + 1\nsocial_discount.save()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T15:24:49.523",
"Id": "413995",
"Score": "0",
"body": "Thank you so much. One more question for my understanding. `SocialDiscount.objects.filter(order_items` > Will filter then go into the model where my order_items are saved and look for the SocialDiscount used in that specific order_item?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T15:43:25.700",
"Id": "413998",
"Score": "0",
"body": "@JoeyCoder See update."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T13:56:16.897",
"Id": "214037",
"ParentId": "214032",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "214037",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T12:13:19.253",
"Id": "214032",
"Score": "2",
"Tags": [
"python",
"django"
],
"Title": "Django: Database efficiency - currently accessed twice"
} | 214032 |
<p>I've wrote a function which take in a list of ranges (the ranges being tuples) and then returns a list of dictionaries which are a summary of how these ranges overlap with each other</p>
<p>There's not a lot of context to this to take into consideration, I was just aiming to find the overlaps pairwise from a list of ranges. The comments are mostly there for this post. The average amount of ranges I had in mind when developing this was 10.</p>
<p>I'm hoping to get this reviewed mostly just to get other peoples opinions on the function. Another way to do this would be to compare all the ranges individually against each other but I didn't like the idea of that.</p>
<p><strong>Terms:</strong></p>
<ul>
<li><p>encapsulated: These ranges are within this range.</p></li>
<li><p>higherLinked: These ranges overlap, and are more to the right of
this range.</p></li>
<li><p>lowerLinked: These ranges overlap, and are more to the left of this
range.</p></li>
<li><p>matches: Ranges match each other.</p></li>
</ul>
<p><strong>Code:</strong></p>
<pre><code>import collections
# Return a list of dicts.
# Each dict is is a overlap summary of an individual range within the range list parameter.
def do_ranges_overlap_pairwise(rangeTupleList):
sortedRangeTupleList = sorted(rangeTupleList, key=lambda elem: elem[0])
rangeDict = collections.OrderedDict()
overLapDictList = []
def getPartnerKey(key):
if "A" in key:
return key.replace("A", "B")
elif "B" in key:
return key.replace("B", "A")
# Creating an ordered dict and then sorting it by value.
for iteration, rangeTuple in enumerate(sortedRangeTupleList):
sortedRangeTuple = sorted(rangeTuple)
rangeDict["{}A".format(iteration)] = sortedRangeTuple[0]
rangeDict["{}B".format(iteration)] = sortedRangeTuple[1]
sortedRangeDict = collections.OrderedDict(sorted(rangeDict.items(), key=lambda t: t[1]))
keyList = list(sortedRangeDict.keys()) # Ordered list of the keys
# Loop A keys, find the range inbetween itself and it's B pair.
for key in keyList:
if "A" in key:
keyB = getPartnerKey(key)
lowerOverlapIndex = (keyList.index(key) + 1)
higherOverlapIndex = keyList.index(keyB)
overLapRange = keyList[lowerOverlapIndex:higherOverlapIndex]
overlapDict = {
"range": (sortedRangeDict[key], sortedRangeDict[keyB]),
"hasOverlaps": len(overLapRange) > 0,
"encapsulated": [],
"higherLinked": [],
"lowerLinked": [],
"matches": []
}
# Sort the overlapped key into a list based on it's nature.
for overlapKey in overLapRange:
partnerKey = getPartnerKey(overlapKey)
if sorted((sortedRangeDict[overlapKey], sortedRangeDict[partnerKey])) == sorted((sortedRangeDict[key], sortedRangeDict[keyB])):
overlapDict["matches"].append(sorted((sortedRangeDict[overlapKey], sortedRangeDict[partnerKey])))
elif "A" in overlapKey and partnerKey in overLapRange:
overlapDict["encapsulated"].append((sortedRangeDict[overlapKey], sortedRangeDict[partnerKey]))
elif "A" in overlapKey and partnerKey not in overLapRange:
overlapDict["higherLinked"].append((sortedRangeDict[overlapKey], sortedRangeDict[partnerKey]))
elif "B" in overlapKey and partnerKey not in overLapRange:
overlapDict["lowerLinked"].append((sortedRangeDict[partnerKey], sortedRangeDict[overlapKey]))
overLapDictList.append(overlapDict)
return overLapDictList
</code></pre>
<p><strong>Example function call:</strong></p>
<pre><code>import pprint
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(do_ranges_overlap_pairwise([(2, 4), (3, 8), (5, 6), (1, 10), (9, 10), (9, 10)]))
</code></pre>
<p><strong>Example output:</strong></p>
<pre><code>[ { 'encapsulated': [(2, 4), (3, 8), (5, 6)],
'hasOverlaps': True,
'higherLinked': [(9, 10), (9, 10)],
'lowerLinked': [],
'matches': [],
'range': (1, 10)},
{ 'encapsulated': [],
'hasOverlaps': True,
'higherLinked': [(3, 8)],
'lowerLinked': [],
'matches': [],
'range': (2, 4)},
{ 'encapsulated': [(5, 6)],
'hasOverlaps': True,
'higherLinked': [],
'lowerLinked': [(2, 4)],
'matches': [],
'range': (3, 8)},
{ 'encapsulated': [],
'hasOverlaps': False,
'higherLinked': [],
'lowerLinked': [],
'matches': [],
'range': (5, 6)},
{ 'encapsulated': [],
'hasOverlaps': True,
'higherLinked': [],
'lowerLinked': [(1, 10)],
'matches': [[9, 10]],
'range': (9, 10)},
{ 'encapsulated': [],
'hasOverlaps': True,
'higherLinked': [],
'lowerLinked': [(1, 10)],
'matches': [[9, 10]],
'range': (9, 10)}]
</code></pre>
<p><strong>Timing</strong></p>
<pre><code>10 ranges:
real 0m0.045s
user 0m0.032s
sys 0m0.010s
100 ranges:
real 0m0.143s
user 0m0.122s
sys 0m0.015s
250 ranges:
real 0m0.682s
user 0m0.625s
sys 0m0.046s
500 ranges:
real 0m2.812s
user 0m2.636s
sys 0m0.145s
1000 ranges:
real 0m13.607s
user 0m13.033s
sys 0m0.492s
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T12:46:30.490",
"Id": "214033",
"Score": "3",
"Tags": [
"python",
"python-3.x"
],
"Title": "Find overlaps in ranges pairwise"
} | 214033 |
<p>This is my first game.</p>
<p>This header defines the constants:</p>
<p>Constants.h:</p>
<pre><code>#ifndef CONSTANTS_H_INCLUDED
#define CONSTANTS_H_INCLUDED
#define WIN_WIDTH 800
#define WIN_HEIGHT 600
#define BALL_SPEED_X 4
#define BALL_SPEED_MAX_Y 4
#define BAR_FROM_BORDERS 40
#define BAR_SPEED 7
#define MAX_FPS 60
#endif // CONSTANTS_H_INCLUDED
</code></pre>
<p>This is the main class:</p>
<p>PSprite.h:</p>
<pre><code>#ifndef PSPRITE_H
#define PSPRITE_H
/**
*This class inherits the class
*Sprite, and defines some
*attributes to keep track of
*a Sprite's geometry.
*/
#include <SFML/Graphics.hpp>
#include "CollisionManager.h"
#include <string>
#include <vector>
class PSprite : public sf::Sprite
{
public:
PSprite(std::string&, const float& x, const float& y);
const float& getDirectionX();
const float& getDirectionY();
const sf::Vector2f& getLowerRight(); //Getters
const float& getWidth();
const float& getHeight();
void setPosition(float,float);
void setDirectionX(const float&);
void setDirectionY(const float&); //Setters
void setLowerRight();
bool strictlyHigherThan(PSprite&);
bool strictlyLowerThan(PSprite&);
bool strictlyLeftOf(PSprite&); //Relative position verification
bool strictlyRightOf(PSprite&);
PSprite* nextMove(); //Returns a ptr on the sprite after its next movement
protected:
sf::Texture texture; //The sprite's texture
CollisionManager collision; //The Collision manager
float directionX; //The direction on X axis
float directionY; //The direction on Y axis
float width; //The sprite's width
float height; //The Sprite's height
sf::Vector2f lowerRight; //Lower right corner's coordinates
};
#endif // PSPRITE_H
</code></pre>
<p>PSprite.cpp:</p>
<pre><code>#include "PSprite.h"
#include <string>
using namespace sf;
using namespace std;
PSprite::PSprite(std::string& filename,const float& x, const float& y)
{
texture.loadFromFile(filename); //Loading the texture
setTexture(texture); //Setting the sprite
setPosition(x,y);
width=texture.getSize().x; //Setting width and height
height=texture.getSize().y;
//setLowerRight(); //Setting the lower right corner
directionX=0; //Setting the directions to default values
directionY=0;
}
const float& PSprite::getDirectionX()
{
return directionX;
}
const float& PSprite::getDirectionY()
{
return directionY;
}
const Vector2f& PSprite::getLowerRight()
{
return lowerRight;
}
const float& PSprite::getWidth()
{
return width;
}
const float& PSprite::getHeight()
{
return height;
}
void PSprite::setPosition(float x,float y)
{
Sprite::setPosition(x,y);
setLowerRight(); //We set the lower right corner each time we change the position
}
void PSprite::setDirectionX(const float& dirX)
{
directionX=dirX;
}
void PSprite::setDirectionY(const float& dirY)
{
directionY=dirY;
}
void PSprite::setLowerRight()
{
lowerRight.x=getPosition().x+width;
lowerRight.y=getPosition().y+height;
}
bool PSprite::strictlyHigherThan(PSprite& spr)
{
return lowerRight.y<spr.getPosition().y; //If the lowest point of this is higher than spr's highest
}
bool PSprite::strictlyLowerThan(PSprite& spr)
{
return spr.strictlyHigherThan(*this); //If spr is strictly higher than this
}
bool PSprite::strictlyLeftOf(PSprite& spr)
{
return lowerRight.x<spr.getPosition().x; //If the rightest point of this is on spr's leftest left
}
bool PSprite::strictlyRightOf(PSprite& spr)
{
return spr.strictlyLeftOf(*this); //If spr is strictly on the left of this
}
PSprite* PSprite::nextMove() //Returns a pointer on this' position after its next move
{
PSprite *next=new PSprite(*this);
next->setPosition(getPosition().x+directionX,getPosition().y+directionY);
return next;
}
</code></pre>
<p>This class manages collisions:</p>
<p>CollisionManager.h:</p>
<pre><code>#ifndef COLLISIONMANAGER_H
#define COLLISIONMANAGER_H
/**
*Class that manages collisions (!)
*between 2 PSprites or a PSprite
*and the screen borders
*/
#include <SFML/Graphics.hpp>
#include "Constants.h"
class PSprite;
class CollisionManager
{
public:
CollisionManager();
bool CollBorderV(PSprite&); //Managing collision between a PSprite and the vertical borders of the screen
bool CollBorderH(PSprite&); //Managing collision between a PSprite and the horizontal borders of the screen
bool Coll2PSprite(PSprite&,PSprite&); //Managing the collision between two PSprites
};
#endif // COLLISIONMANAGER_H
</code></pre>
<p>CollisionManager.cpp:</p>
<pre><code>#include "CollisionManager.h"
#include "Ball.h"
#include "PSprite.h"
#include <iostream>
using namespace sf;
CollisionManager::CollisionManager()
{
}
bool CollisionManager::Coll2PSprite(PSprite& spr1, PSprite& spr2) //Managing the collision between two PSprites
{
PSprite *nxt=spr1.nextMove();
if(nxt->strictlyHigherThan(spr2) || nxt->strictlyLowerThan(spr2) || nxt->strictlyLeftOf(spr2) || nxt->strictlyRightOf(spr2)) //If they don't collide after spr1's next move
{
delete nxt;
return 0;
}
if(spr1.strictlyHigherThan(spr2))
{
spr1.setPosition(spr1.getPosition().x,spr2.getPosition().y-spr1.getHeight());
//spr1.setLowerRight();
}
else if(spr1.strictlyLowerThan(spr2))
{
spr1.setPosition(spr1.getPosition().x,spr2.getLowerRight().y);
//spr1.setLowerRight();
}
if(spr1.strictlyLeftOf(spr2))
{
spr1.setPosition(spr2.getPosition().x-spr1.getWidth(),spr1.getPosition().y);
//spr1.setLowerRight();
}
else if(spr1.strictlyRightOf(spr2))
{
spr1.setPosition(spr2.getLowerRight().x,spr1.getPosition().y);
//spr1.setLowerRight();
}
delete nxt;
return 1;
}
bool CollisionManager::CollBorderH(PSprite& spr)
{
PSprite *nxt=spr.nextMove();
if(nxt->getPosition().y>0 && nxt->getLowerRight().y<WIN_HEIGHT) //If there is no collision
{
delete nxt;
return 0;
}
if(nxt->getPosition().y<0) //If there is a collision with the upper border
{
spr.setPosition(spr.getPosition().x,0);
//spr.setLowerRight();
}
else if(nxt->getLowerRight().y>WIN_HEIGHT) //If there is a collision with the lower border
{
spr.setPosition(spr.getPosition().x,WIN_HEIGHT-spr.getHeight());
//spr.setLowerRight();
}
delete nxt;
return 1;
}
bool CollisionManager::CollBorderV(PSprite& spr) //Manages collisions between a PSPrite and vertical borders
{
PSprite *nxt=spr.nextMove();
if(nxt->getPosition().x>0 && nxt->getLowerRight().x<WIN_WIDTH)
{
delete nxt;
return 0;
}
if(nxt->getPosition().x<0)
{
spr.setPosition(0,spr.getPosition().y);
}
else if(nxt->getLowerRight().x>WIN_WIDTH)
{
spr.setPosition(WIN_WIDTH-spr.getWidth(),spr.getPosition().y);
}
delete nxt;
return 1;
}
</code></pre>
<p>This is the ball's class:</p>
<p>Ball.h:</p>
<pre><code>#ifndef BALL_H_INCLUDED
#define BALL_H_INCLUDED
/**
*This class inherits from the class
*PSprite and defines the method motion
*that indicates how the Ball moves
*/
#include <SFML/Graphics.hpp>
#include <string>
#include "Bar.h"
#include "CollisionManager.h"
#include "PSprite.h"
class Ball:public PSprite
{
public:
Ball(std::string,float,float);
void motion(std::vector<PSprite*>,bool&);
};
#endif // BALL_H_INCLUDED
</code></pre>
<p>Ball.cpp:</p>
<pre><code>#include "Ball.h"
#include <string>
#include <iostream>
#include <vector>
#include <cstdlib>
#include "Constants.h"
using namespace sf;
using namespace std;
Ball::Ball(string filename,float x, float y):PSprite(filename,x,y)
{
}
void Ball::motion(vector<PSprite*> sprites,bool& paused)
{
for(int i=0;i<sprites.size();i++) //sprites contains pointers on all the sprites on screen, in this case the 2 bars
{
if(collision.Coll2PSprite(*this,*sprites[i])) //If a ball collides with a PSprite it changes directionX
{
directionX*=-1;
directionY=rand()%BALL_SPEED_MAX_Y;
}
}
if(collision.CollBorderH(*this)) //If a ball collides with a horizontal border it changes directionY
{
directionY=directionY*-1;
}
move(directionX,directionY); //Making the next movement
if(collision.CollBorderV(*this)) //If the ball collides with a vertical border we reset the game
{
setPosition(WIN_WIDTH/2,WIN_HEIGHT/2);
directionY=0;
sprites[0]->setPosition(WIN_WIDTH-BAR_FROM_BORDERS,WIN_HEIGHT/2);
sprites[0]->setLowerRight();
sprites[1]->setPosition(BAR_FROM_BORDERS,WIN_HEIGHT/2);
sprites[1]->setLowerRight();
paused=1;
}
setLowerRight();
}
</code></pre>
<p>This is the bars' class:</p>
<p>Bar.h:</p>
<pre><code>#ifndef BAR_H
#define BAR_H
/**
* This class Bar inherits from the class
* PSprite and defines the method motion
* which indicates how the bars move.
*/
#include <string>
#include <SFML/Graphics.hpp>
#include "CollisionManager.h"
#include "PSprite.h"
class Bar:public PSprite
{
public:
Bar(std::string,float,float);
void motion();
};
#endif // BAR_H
</code></pre>
<p>Bar.cpp:</p>
<pre><code>#include "Bar.h"
#include "PSprite.h"
using namespace sf;
using namespace std;
Bar::Bar(string filename,float x,float y):PSprite(filename,x,y)
{
}
void Bar::motion()
{
if(!collision.CollBorderH(*this)) //If a bar collides with a horizontal border it can't move in its direction
{
move(0,directionY);
setLowerRight();
directionY=0;
}
}
</code></pre>
<p>main.cpp:</p>
<pre><code>#include <SFML/Graphics.hpp>
#include "Ball.h"
#include "Bar.h"
#include <vector>
#include "Constants.h"
using namespace sf;
using namespace std;
int main()
{
RenderWindow app(sf::VideoMode(WIN_WIDTH, WIN_HEIGHT), "Pong XI: Tokyo Drift"); // Create the main window
Ball ball("Sprites/ball.png",WIN_WIDTH/2,WIN_HEIGHT/2); //Setting the ball
ball.setDirectionX(BALL_SPEED_X);
Bar blu("Sprites/bluBar.png",WIN_WIDTH-BAR_FROM_BORDERS,WIN_HEIGHT/2); //Setting the bars
Bar red("Sprites/redBar.png",BAR_FROM_BORDERS,WIN_HEIGHT/2);
vector<PSprite*> bars; //Creating the vector and adding the two bars to it
bars.push_back(&blu);
bars.push_back(&red);
bool paused=1;
bool z=0;
bool s=0;
bool up=0;
bool down=0;
Texture background;
background.loadFromFile("Sprites/background.png"); //Setting the background
Sprite sp_bg;
sp_bg.setTexture(background);
app.setFramerateLimit(MAX_FPS);
app.setVerticalSyncEnabled(1);
while (app.isOpen())
{
Event event; // Process events
while (app.pollEvent(event))
{
switch (event.type) // Event's type
{
case Event::Closed : // Close button on the window
app.close();
break;
case Event::KeyPressed : // Event key pressed
{
switch (event.key.code) // The pressed key
{
case Keyboard::Escape : // Escape
app.close();
break;
case Keyboard::Up:
if(!paused)
{
up=1;
}
break;
case Keyboard::Down: //To manage simultaneous key pressing we set booleans
if(!paused) //linked to the pressed buttons and later make movements
{ //based on their values
down=1;
}
break;
case Keyboard::Z:
if(!paused)
{
z=1;
}
break;
case Keyboard::S:
if(!paused)
{
s=1;
}
break;
case Keyboard::Space:
paused=!paused;
break;
default:
break;
}
}
break;
case Event::KeyReleased:
{
switch (event.key.code) // The released key
{
case Keyboard::Up:
if(!paused) //Stopping the movement when the keys are released
{
up=0;
}
break;
case Keyboard::Down:
if(!paused)
{
down=0;
}
break;
case Keyboard::Z:
if(!paused)
{
z=0;
}
break;
case Keyboard::S:
if(!paused)
{
s=0;
}
break;
default:
break;
}
}
break;
default :
break;
}
}
if(paused)
{
z=0; //Stopping the movements if the game is paused
s=0;
up=0;
down=0;
}
if(z) //Verifying the booleans to make movements
{
red.setDirectionY(-BAR_SPEED);
red.motion();
}
if(s)
{
red.setDirectionY(BAR_SPEED);
red.motion();
}
if(up)
{
blu.setDirectionY(-BAR_SPEED);
blu.motion();
}
if(down)
{
blu.setDirectionY(BAR_SPEED);
blu.motion();
}
if(!paused)
{
ball.motion(bars,paused);
}
app.clear(); // Clear screen
app.draw(sp_bg);
app.draw(ball); // Draw the sprite
app.draw(blu);
app.draw(red);
app.display(); // Update the window
}
return EXIT_SUCCESS;
}
</code></pre>
| [] | [
{
"body": "<ol>\n<li><p>Prefer to make the constants proper (i.e., type-safe) constants using <code>const</code> or <code>constexpr</code> instead of a C-style macro. This increases maintainability and protects from unintended errors.</p></li>\n<li><p>In PSprite (and in general), make <em>every</em> member function const if it is not modifying the state of the object. Case in point are your getters.</p></li>\n<li><p>Use the initialization list in a constructor (see e.g., PSprite). So prefer to write along the lines of:</p>\n\n<pre><code>PSprite::PSprite(std::string& filename, const float& x, const float& y)\n : directionX(0), directionY(0)\n{\n texture.loadFromFile(filename); //Loading the texture\n\n setTexture(texture); //Setting the sprite\n setPosition(x, y);\n\n width = texture.getSize().x; //Setting width and height\n height = texture.getSize().y;\n}\n</code></pre></li>\n</ol>\n\n<p>Perhaps there is room for additional members to be initialized in the initialization list as well.</p>\n\n<p>Also, I find your comments too verbose. They should specify more \"why\" and not \"what\". For example, if you set two member variables to zero in a constructor, it is perfectly clear they are initialized to sensible default values without an explicit comment.</p>\n\n<ol start=\"4\">\n<li><p>What is the purpose of CollisionManager as a stateless class? It seems to me that you might as well make the collision detection functionality into free (non-member) functions and get rid of the unnecessary class.</p></li>\n<li><p>In the constructor of Bar, pass the string as const-ref instead of by-value. Cheap-to-copy objects (like ints and floats) are typically passed by-value.</p></li>\n<li><p>Avoid using \"naked pointers\" to avoid leaking memory. Have a look at <a href=\"https://en.cppreference.com/w/cpp/memory\" rel=\"nofollow noreferrer\">std::shared_ptr</a> and others for doing this properly and safely.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T14:14:41.927",
"Id": "214041",
"ParentId": "214035",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "214041",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T13:49:58.203",
"Id": "214035",
"Score": "4",
"Tags": [
"c++",
"beginner",
"game",
"sfml",
"pong"
],
"Title": "PONG XI Platinum Edition"
} | 214035 |
<p>I am trying to write multiple dataframes into an excel file one after another with the same logic. Nothing changes for any of the data frame, except the number of columns or number of records. The functions are still the same.</p>
<p>For example,</p>
<pre><code>writer = pd.ExcelWriter(OutputName)
Emp_ID_df.to_excel(writer,'Sheet1',index = False)
Visa_df.to_excel(writer,'Sheet2',index = False)
custom_df_1.to_excel(writer,'Sheet3',index = False)
writer.save()
</code></pre>
<p>Now then, once written I am trying to highlight a row if any of the Boolean column has False value in it. There is no library in anacondas that I am aware of can highlight cells in excel. So I am going for the native one. </p>
<pre><code>from win32com.client import Dispatch #to work with excel files
Pre_Out_df_ncol = Emp_ID_df.shape[1]
Pre_Out_df_nrow = Emp_ID_df.shape[0]
RequiredCol_let = colnum_num_string(Pre_Out_df_ncol)
arr = (Emp_ID_df.select_dtypes(include=[bool])).eq(False).any(axis=1).values
ReqRows = np.arange(1, len(Emp_ID_df)+ 1)[arr].tolist()
Pre_Out_df_ncol_2 = Visa_df.shape[1]
Pre_Out_df_nrow_2 = Visa_df.shape[0]
RequiredCol_let_2 = colnum_num_string(Pre_Out_df_ncol_2)
arr_2 = (Visa_df.select_dtypes(include=[bool])).eq(False).any(axis=1).values
ReqRows_2 = np.arange(1, len(Visa_df)+ 1)[arr_2].tolist()
Pre_Out_df_ncol_3 = custom_df_1.shape[1]
Pre_Out_df_nrow_3 = custom_df_1.shape[0]
RequiredCol_let_3 = colnum_num_string(Pre_Out_df_ncol_3)
arr_3 = (custom_df_1.select_dtypes(include=[bool])).eq(False).any(axis=1).values
ReqRows_3 = np.arange(1, len(custom_df_1)+ 1)[arr_3].tolist()
xlApp = Dispatch("Excel.Application")
xlwb1 = xlApp.Workbooks.Open(OutputName)
xlApp.visible = False
print ("\n...Highlighting the Output File at " + datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
for i in range(len(ReqRows)):
j = ReqRows[i] + 1
xlwb1.sheets('Sheet1').Range('A' + str(j) + ":" + RequiredCol_let + str(j)).Interior.ColorIndex = 6
xlwb1.sheets('Sheet1').Columns.AutoFit()
for i in range(len(ReqRows_2)):
j = ReqRows_2[i] + 1
xlwb1.sheets('Sheet2').Range('A' + str(j) + ":" + RequiredCol_let_2 + str(j)).Interior.ColorIndex = 6
xlwb1.sheets('Sheet2').Columns.AutoFit()
for i in range(len(ReqRows_3)):
j = ReqRows_3[i] + 1
xlwb1.sheets('Sheet3').Range('A' + str(j) + ":" + RequiredCol_let_3 + str(j)).Interior.ColorIndex = 6
xlwb1.sheets('Sheet3').Columns.AutoFit()
</code></pre>
<p>At last, I am changing the name of the sheet</p>
<pre><code>xlwb1.Sheets("Sheet1").Name = "XXXXA"
xlwb1.Sheets("Sheet2").Name = "XXXXASDAD"
xlwb1.Sheets("Sheet3").Name = "SADAD"
xlwb1.Save()
</code></pre>
<p>Now there are a few problems here</p>
<p>1) My number of dataframe increases and which means I am writing up the same code again and again.</p>
<p>2) The highlighting process works but it is too slow. Sometimes 90 % of the rows needs to be highlighted. There are 1 million rows and doing them one after another takes 35 minutes.</p>
<p>Kindly help me with this.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T15:09:38.730",
"Id": "413993",
"Score": "0",
"body": "Did you have a look at https://xlsxwriter.readthedocs.io/example_pandas_conditional.html and https://xlsxwriter.readthedocs.io/working_with_conditional_formats.html ?"
}
] | [
{
"body": "<p>First, starting from your code, you should realize that you are repeating yourself, three times. This goes against the principle <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"noreferrer\">Don't repeat Yourself (DRY)</a>.</p>\n\n<p>The only real difference between processing your three sheets are their name and the underlying dataframe, so you could make this into two functions:</p>\n\n<pre><code>from win32com.client import Dispatch\nimport pandas as pd\n\ndef highlight_false(df):\n arr = (df.select_dtypes(include=[bool])).eq(False).any(axis=1).values\n return np.arange(1, len(df) + 1)[arr].tolist()\n\n\ndef color_rows(sheet, rows, col):\n for row in rows:\n cells = f\"A{row+1}:{col}{row+1}\"\n sheet.Range(cells).Interior.ColorIndex = 6\n sheet.Columns.AutoFit()\n\n\nif __name__ == \"__main__\":\n Emp_ID_df = ...\n writer = pd.ExcelWriter(OutputName)\n Emp_ID_df.to_excel(writer, 'Sheet1', index=False)\n\n excel_app = Dispatch(\"Excel.Application\")\n workbook = excel_app.Workbooks.Open(OutputName)\n excel_app.visible = False\n\n sheet_names = [\"Sheet1\"]\n dfs = [Emp_ID_df]\n for sheet_name, df in zip(sheet_names, dfs):\n sheet = workbook.Sheets(sheet)\n rows = highlight_false(df)\n col = colnum_num_string(df.shape[1])\n color_rows(sheet, rows, col)\n</code></pre>\n\n<p>However, there is an even easier method using <a href=\"https://xlsxwriter.readthedocs.io/index.html\" rel=\"noreferrer\"><code>xlsxwriter</code></a>:</p>\n\n<pre><code>import pandas as pd\n\nEmp_ID_df = ...\n\nwriter = pd.ExcelWriter(OutputName, engine='xlsxwriter')\nEmp_ID_df.to_excel(writer, sheet_name=\"Sheet1\", index=False)\n\nworkbook = writer.book\nformat1 = workbook.add_format({'bg_color': '#FFC7CE',\n 'font_color': '#9C0006'})\ndfs = [Emp_ID_df]\nfor df, sheet in zip(dfs, writer.sheets.values()):\n nrow, ncol = df.shape\n col_letter = colnum_num_string(ncol + 1)\n cells = f\"A1:{col_letter}{nrow+1}\"\n sheet.conditional_format(cells, {\"type\": \"cell\",\n \"criteria\": \"==\",\n \"value\": 0,\n \"format\": format1})\nwriter.save()\n</code></pre>\n\n<p>You might have to ensure that the sheets do not get out of snyc from the data frames, or just keep track of what name you save each dataframe to.</p>\n\n<p>In addition I used Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a>, which recommends using <code>lower_case</code> for functions and variables as well as renaming your variables so they are a lot clearer.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T16:00:47.693",
"Id": "214044",
"ParentId": "214042",
"Score": "6"
}
},
{
"body": "<blockquote>\n <p>1) My number of dataframe increases and which means I am writing up\n the same code again and again</p>\n</blockquote>\n\n<p>You're repeating a lot of code which is essentially doing the same thing with just a couple of variables.\nI think for this you should wrap it in a function.\nI've taken your code and put it inside a function:</p>\n\n<pre><code>def highlight_false_cells(sheetName, dataFrame, OutputName):\n Pre_Out_df_ncol = dataFrame.shape[1]\n Pre_Out_df_nrow = dataFrame.shape[0] # Is this required? It doesn't look to be used.\n RequiredCol_let = colnum_num_string(Pre_Out_df_ncol)\n arr = (dataFrame.select_dtypes(include=[bool])).eq(False).any(axis=1).values\n ReqRows = np.arange(1, len(dataFrame) + 1)[arr].tolist()\n\n xlApp = Dispatch(\"Excel.Application\")\n xlwb1 = xlApp.Workbooks.Open(OutputName)\n xlApp.visible = False\n print(\"\\n...Highlighting the Output File at \" + datetime.now().strftime('%Y-%m-%d %H:%M:%S'))\n\n for i in range(len(ReqRows)):\n j = ReqRows[i] + 1\n xlwb1.sheets(sheetName).Range('A' + str(j) + \":\" + RequiredCol_let + str(j)).Interior.ColorIndex = 6\n xlwb1.sheets(sheetName).Columns.AutoFit()\n\n xlwb1.Save()\n</code></pre>\n\n<p>To call this for your dataframes:</p>\n\n<pre><code>highlight_false_cells(\"XXXXA\", Emp_ID_df, OutputName)\nhighlight_false_cells(\"XXXXASDAD\", Visa_df, OutputName)\nhighlight_false_cells(\"SADAD\", custom_df_1, OutputName)\n</code></pre>\n\n<p>I'm not really familiar with the packages you're using, so there may be a mistake in logic within there. However hopefully it gives you a good example how to take your work and put it into a function.</p>\n\n<p>I'd also recommend looking into a programming principle called \"DRY\", which stands for \"Don't Repeat Yourself\". If you can learn to spot areas like this where you have a lot of repeated lines then it will make stuff easier I believe.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T16:18:54.003",
"Id": "214045",
"ParentId": "214042",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "214044",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T14:45:53.790",
"Id": "214042",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"pandas"
],
"Title": "Python to write multiple dataframes and highlight rows inside an excel file"
} | 214042 |
<p>This is a very stripped-down version of a crypto library I am writing. There are cryptographic algorithms like RSA, DSA, ECDSA, EdDSA, ... which all have a similar pattern of having a private key, a public key, a signature and operations like sign data with a private key that gives a signature result, verify signature with a public key that gives a bool result.</p>
<p>There are 3 conflicting requirements:</p>
<ul>
<li>The library integrators should be able to implement generic algorithms on top of the library types which are type safe and use only types from 1 crypto</li>
<li>Each cryptography should have its own type family. When the user tries to verify an RSA signature with an EdDSA public key, they should get an error explaining they mixed up different cryptos (so I need type safety)</li>
<li>The library should be able to deserialize input and for example create a strongly typed EdDSA public key without knowing in advance the input will belong to the EdDSA type family</li>
</ul>
<pre class="lang-rust prettyprint-override"><code>trait Family {
type T1: T1<Self>;
type T2: T2<Self>;
fn x() -> Self::T1;
}
trait T1<F: Family + ?Sized> {
fn y(&self) -> F::T2;
}
trait T2<F: Family + ?Sized> {
fn z(&self) -> F::T1;
}
//----------------------------------------------------------------------
struct FamilyImplA {}
impl Family for FamilyImplA {
type T1 = T1ImplA;
type T2 = T2ImplA;
fn x() -> T1ImplA {
println!("FamilyImplA::x was called");
T1ImplA {}
}
}
struct T1ImplA {}
impl T1<FamilyImplA> for T1ImplA {
fn y(&self) -> T2ImplA {
println!("T1ImplA::y was called");
T2ImplA {}
}
}
struct T2ImplA {}
impl T2<FamilyImplA> for T2ImplA {
fn z(&self) -> T1ImplA {
println!("T2ImplA::z was called");
T1ImplA {}
}
}
//----------------------------------------------------------------------
struct FamilyImplB {}
impl Family for FamilyImplB {
type T1 = T1ImplB;
type T2 = T2ImplB;
fn x() -> T1ImplB {
println!("FamilyImplB::x was called");
T1ImplB {}
}
}
struct T1ImplB {}
impl T1<FamilyImplB> for T1ImplB {
fn y(&self) -> T2ImplB {
println!("T1ImplB::y was called");
T2ImplB {}
}
}
struct T2ImplB {}
impl T2<FamilyImplB> for T2ImplB {
fn z(&self) -> T1ImplB {
println!("T2ImplB::z was called");
T1ImplB {}
}
}
//----------------------------------------------------------------------
use std::any::Any;
enum Discriminator {
A,
B,
}
struct ErasedFamily {}
impl ErasedFamily {
fn x_a() -> ErasedT1 {
ErasedT1 { d:Discriminator::A, t1:Box::new( FamilyImplA::x() ) }
}
fn x_b() -> ErasedT1 {
ErasedT1 { d:Discriminator::B, t1:Box::new( FamilyImplB::x() ) }
}
}
impl Family for ErasedFamily {
type T1 = ErasedT1;
type T2 = ErasedT2;
fn x() -> ErasedT1 {
// Cannot decide on what to create without a discriminator
unimplemented!()
}
}
struct ErasedT1 {
d: Discriminator,
t1: Box<Any>,
}
impl T1<ErasedFamily> for ErasedT1 {
fn y(&self) -> ErasedT2 {
match self.d {
Discriminator::A => {
let t1 = self.t1.downcast_ref::<T1ImplA>().unwrap();
let r = t1.y();
ErasedT2 { d:Discriminator::A, t2:Box::new( r ) }
},
Discriminator::B => {
let t1 = self.t1.downcast_ref::<T1ImplB>().unwrap();
let r = t1.y();
ErasedT2 { d:Discriminator::B, t2:Box::new( r ) }
}
}
}
}
struct ErasedT2 {
d: Discriminator,
t2: Box<Any>,
}
impl T2<ErasedFamily> for ErasedT2 {
fn z(&self) -> ErasedT1 {
match self.d {
Discriminator::A => {
let t2 = self.t2.downcast_ref::<T2ImplA>().unwrap();
let r = t2.z();
ErasedT1 { d:Discriminator::A, t1:Box::new( r ) }
},
Discriminator::B => {
let t2 = self.t2.downcast_ref::<T2ImplB>().unwrap();
let r = t2.z();
ErasedT1 { d:Discriminator::B, t1:Box::new( r ) }
}
}
}
}
//----------------------------------------------------------------------
fn generic<F: Family>(t1: F::T1) -> F::T1 {
t1.y().z()
}
fn main() {
let _t1a = generic::<FamilyImplA>(FamilyImplA::x());
let _t1b = generic::<FamilyImplB>(FamilyImplB::x());
let _t1ea = generic::<ErasedFamily>(ErasedFamily::x_a());
let _t1eb = generic::<ErasedFamily>(ErasedFamily::x_b());
}
</code></pre>
<p><a href="https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=566eff77b439a9a2e0d5f965ff058f0a" rel="nofollow noreferrer">Playground</a></p>
<p>In production, I have declarative macros for type erasure and reification at the moment to avoid duplication. Is there another way to do this in Rust 1.32.0?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T15:40:24.243",
"Id": "214043",
"Score": "3",
"Tags": [
"rust",
"variant-type"
],
"Title": "Type erasure in Rust"
} | 214043 |
<p>I have two functions here, each one displays the gradient slightly differently with up to 5 gradients.</p>
<p>Function 1:</p>
<pre><code>Function addCellColor(ByVal c As Range, ByVal color As Long)
Dim c1 As Long, c2 As Long, c3 As Long, c4 As Long
'creates a gradient pattern if one doesn't already exist
With c.Interior
If .color = 16777215 Then
.Pattern = xlPatternLinearGradient
.gradient.Degree = 0
.gradient.ColorStops.Clear
End If
End With
' adds gradient color to cell up to 5 colors
If Not c.Interior.gradient Is Nothing Then
With c.Interior.gradient
' if the cell is already colored
If .ColorStops.count <> 0 Then
Select Case .ColorStops.count
Case 2
If .ColorStops(1).color = .ColorStops(2).color Then
c1 = .ColorStops(1).color
.ColorStops.Clear
.ColorStops.Add(0).color = c1
.ColorStops.Add(0.45).color = c1
.ColorStops.Add(0.55).color = color
.ColorStops.Add(1).color = color
End If
Case 4
If .ColorStops(1).color <> color And .ColorStops(2).color <> color And .ColorStops(3).color <> color And .ColorStops(4).color <> color Then
c1 = .ColorStops(1).color: c2 = .ColorStops(3).color
.ColorStops.Clear
.ColorStops.Add(0).color = c1
.ColorStops.Add(0.28).color = c1
.ColorStops.Add(0.38).color = c2
.ColorStops.Add(0.61).color = c2
.ColorStops.Add(0.71).color = color
.ColorStops.Add(1).color = color
End If
Case 6
If .ColorStops(1).color <> color And .ColorStops(2).color <> color And .ColorStops(3).color <> color _
And .ColorStops(4).color <> color And .ColorStops(5).color <> color And .ColorStops(6).color <> color Then
c1 = .ColorStops(1).color: c2 = .ColorStops(3).color: c3 = .ColorStops(5).color
.ColorStops.Clear
.ColorStops.Add(0).color = c1
.ColorStops.Add(0.2).color = c1
.ColorStops.Add(0.3).color = c2
.ColorStops.Add(0.45).color = c2
.ColorStops.Add(0.55).color = c3
.ColorStops.Add(0.7).color = c3
.ColorStops.Add(0.8).color = color
.ColorStops.Add(1).color = color
End If
Case 8
If .ColorStops(1).color <> color And .ColorStops(2).color <> color And .ColorStops(3).color <> color And .ColorStops(4).color <> color _
And .ColorStops(5).color <> color And .ColorStops(6).color <> color And .ColorStops(7).color <> color And .ColorStops(8).color <> color Then
c1 = .ColorStops(1).color: c2 = .ColorStops(3).color: c3 = .ColorStops(5).color: c4 = .ColorStops(7).color
.ColorStops.Clear
.ColorStops.Add(0).color = c1
.ColorStops.Add(0.15).color = c1
.ColorStops.Add(0.25).color = c2
.ColorStops.Add(0.35).color = c2
.ColorStops.Add(0.45).color = c3
.ColorStops.Add(0.55).color = c3
.ColorStops.Add(0.65).color = c4
.ColorStops.Add(0.75).color = c4
.ColorStops.Add(0.85).color = color
.ColorStops.Add(1).color = color
End If
End Select
' if cell has no colors yet
Else
.ColorStops.Add(0).color = color
.ColorStops.Add(1).color = color
End If
End With
End If
End Function
</code></pre>
<p>Output (completes in 2 minutes and 10 seconds when ran on a collection of ~4500 items):</p>
<p><img src="https://i.stack.imgur.com/xqXCj.png" alt="Function 1 output"></p>
<p>Function 2:</p>
<pre><code>Function addCellColor1(ByVal c As Range, ByVal color As Long)
Dim c1 As Long, c2 As Long, c3 As Long, c4 As Long
'creates a gradient pattern if one doesn't already exist
With c.Interior
If .color = 16777215 Then
.Pattern = xlPatternLinearGradient
.gradient.Degree = 0
.gradient.ColorStops.Clear
End If
End With
' adds gradient color to cell up to 5 colors
If Not c.Interior.gradient Is Nothing Then
With c.Interior.gradient
' if the cell is already colored
If .ColorStops.count <> 0 Then
Select Case .ColorStops.count
Case 2
If .ColorStops(1).color = .ColorStops(2).color Then
.ColorStops(2).color = color
ElseIf .ColorStops(1).color <> color And .ColorStops(2).color <> color Then
c1 = .ColorStops(1).color: c2 = .ColorStops(2).color
.ColorStops.Clear
.ColorStops.Add(0).color = c1
.ColorStops.Add(0.5).color = c2
.ColorStops.Add(1).color = color
End If
Case 3
If .ColorStops(1).color <> color And .ColorStops(2).color <> color And .ColorStops(3).color <> color Then
c1 = .ColorStops(1).color: c2 = .ColorStops(2).color: c3 = .ColorStops(3).color
.ColorStops.Clear
.ColorStops.Add(0).color = c1
.ColorStops.Add(0.33).color = c2
.ColorStops.Add(0.66).color = c3
.ColorStops.Add(1).color = color
End If
Case 4
If .ColorStops(1).color <> color And .ColorStops(2).color <> color And .ColorStops(3).color <> color And .ColorStops(4).color <> color Then
c1 = .ColorStops(1).color: c2 = .ColorStops(2).color: c3 = .ColorStops(3).color: c4 = .ColorStops(4).color
.ColorStops.Clear
.ColorStops.Add(0).color = c1
.ColorStops.Add(0.25).color = c2
.ColorStops.Add(0.5).color = c3
.ColorStops.Add(0.75).color = c4
.ColorStops.Add(1).color = color
End If
End Select
' if cell has no colors yet
Else
.ColorStops.Add(0).color = color
.ColorStops.Add(1).color = color
End If
End With
End If
End Function
</code></pre>
<p>Output (completes in 1 minute and 12 seconds when ran on a collection of ~4500 items):</p>
<p><img src="https://i.stack.imgur.com/G1XAi.png" alt="Function 2 output"></p>
<p>It is recommended to have the below function run before this one</p>
<pre><code>Function Opt_Start()
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
ActiveSheet.DisplayPageBreaks = False
Application.DisplayAlerts = False
End function
</code></pre>
<p>Particularly looking for an optimization review since the functions take a long time to run when it is ran in a loop.</p>
<p>Additional info:</p>
<p>I have collected a large amount of data in a VBA Collection that looks like this:</p>
<p><a href="https://i.stack.imgur.com/t8I1B.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/t8I1B.png" alt="Collection"></a></p>
<p>The data collection for this (approx 4500 items) takes about 5 seconds, the gradient fill takes minutes.</p>
<p>This is all I am permitted to share: This is how the cell colors are determined.</p>
<pre><code>Private Function FormatDocument()
Dim p As FormulaParameter
Dim green As Long, orange As Long, lRed As Long, dRed As Long, magenta As Long, dGrey As Long
Debug.Print ("Formatting Cells")
green = RGB(146, 208, 80)
orange = RGB(255, 192, 0)
lRed = RGB(255, 80, 80)
dRed = RGB(192, 0, 0)
magenta = RGB(252, 117, 255)
dGrey = RGB(120, 120, 120)
For Each p In coll
If Not p Is Nothing Then
With p
' Error 2: Step name not found for the operation parameter
' this error will just be logged no format changes
'Cell is orange if the value in that cell has been modified at all. Overrides others.
' if error says "Parameter was tracked successfully." change the formula and unit level defenition if not = "Operation default"
' if it is an operation default value, change the unit parameter to its default value
If .newValue = "Operation Default" Then
'********************** This block will change UP level parameter ***************************************
'If Not .uParam Is Nothing Then
' .uParam.Offset(0, 1).value = .defValue
' Call addCellColor(.uParam.Offset(0, 1), orange)
' Call ReplaceUnits(.uParam.Offset(0, 2))
'End If
'********************** This block will change UP level parameter ***************************************
'************ This line will change OP level parameter and delete UP parameter **************************
If Not .oParam2 Is Nothing Then
.oParam2.Offset(0, 1).value = .defValue
Call addCellColor(.oParam2.Offset(0, 1), orange)
Call ReplaceUnits(.oParam2.Offset(0, 2))
If Not .uParam Is Nothing Then
.uParam.Offset(0, 1).value = ""
.uParam.value = ""
.uParam.Offset(0, -1).value = "VALUE"
.uParam.Offset(0, -1).Font.color = vbRed
End If
End If
'************ This line will change OP level parameter and delete UP parameter **************************
Else
If Not .fParam Is Nothing And .newValue <> "" Then .fParam.Offset(0, .fOffset).value = .newValue
If Not .fParam Is Nothing And .newValue <> "" Then Call addCellColor(.fParam.Offset(0, .fOffset), orange)
End If
' Error 10: there was not a unit parameter for the corresponding operation parameter on uTab
' This will also have a default value put into the value in UP
If InStr(1, .error, "Error 10:") > 0 And .newValue = "Operation Default" Then
' .uParam.Offset(0, 1).value = .defValue ' this will change if changing at operation level
' If Not .uParam Is Nothing Then Call addCellColor(.uParam.Offset(0, 1), orange)
'************************************************ added for op level change
If Not .oParam2 Is Nothing Then
.oParam2.Offset(0, 1).value = .defValue
Call addCellColor(.oParam2.Offset(0, 1), orange)
Call ReplaceUnits(.oParam2.Offset(0, 2))
If Not .oParam1 Is Nothing Then
.oParam1.Offset(0, 4).value = ""
.oParam1.Offset(0, 2).value = "VALUE"
.oParam1.Offset(0, 2).Font.color = vbRed
End If
End If
'************************************************ added for op level change
End If
'Cell is green if the value, or parameter in that cell was able to be tracked successfully throughout the two documents.
' catches unit level parameters
' if error says "Parameter was tracked successfully."
If .error = "Parameter was tracked successfully." Or .error = "Parameter is a Unit Procedure level defenition" Then
If Not .uParam Is Nothing Then Call addCellColor(.uParam, green)
If Not .oParam1 Is Nothing Then Call addCellColor(.oParam1, green)
If Not .oParam2 Is Nothing Then Call addCellColor(.oParam2, green)
If Not .rParam Is Nothing Then Call addCellColor(.rParam, green)
If Not .pParam Is Nothing Then Call addCellColor(.pParam, green)
If Not .pParam Is Nothing Then Call addCellColor(.pParam.Offset(0, .pOffset), green)
If Not .pParam Is Nothing Then Call addCellColor(.pParam.Offset(0, .dOffset), green)
If .error = "Parameter is a Unit Procedure level defenition" And Not .fParam Is Nothing Then Call addCellColor(.fParam.Offset(0, .fOffset), green)
End If
'Cell is light red due to a possible mismatch in the R_ parameter from the OP tabs to the PH tabs or vice versa.
' Error 1: Parameter in formula was not found in an operation OR
' Error 2: Step name not found for the operation parameter OR
' Error 3: Operation tab was not found
' Error 4: Operation parameter not found in operation tab
' Error 6: Recipe parameter not found in phase tab
' Error 8: Recipe parameter in the phase was not found in the operation
' Error 9: operation parameter from the operation was not found in the Unit procedure
If InStr(1, .error, "Error 1:") > 0 Or InStr(1, .error, "Error 2:") > 0 Or InStr(1, .error, "Error 4:") > 0 _
Or InStr(1, .error, "Error 6:") > 0 Or InStr(1, .error, "Error 8:") > 0 Or InStr(1, .error, "Error 9:") > 0 _
Or InStr(1, .error, "Error 3:") > 0 Then
If Not .pParam Is Nothing Then Call addCellColor(.pParam, lRed)
If Not .pParam Is Nothing Then Call addCellColor(.pParam.Offset(0, .dOffset), lRed)
If Not .pParam Is Nothing Then Call addCellColor(.pParam.Offset(0, .pOffset), lRed)
If Not .rParam Is Nothing Then Call addCellColor(.rParam, lRed)
If Not .oParam1 Is Nothing Then Call addCellColor(.oParam1, lRed)
If Not .oParam2 Is Nothing Then Call addCellColor(.oParam2, lRed)
If Not .uParam Is Nothing Then Call addCellColor(.uParam, lRed)
If Not .fParam Is Nothing Then Call addCellColor(.fParam.Offset(0, .fOffset), lRed)
End If
'Cell is dark red if the parameter is blank in the parameter value document.
' Error 10: there was not a unit parameter for the corresponding operation parameter on uTab
' or the parameter is empty in phase tab
If InStr(1, .error, "Error 10:") > 0 Or (Not .pParam Is Nothing And .newValue = "" And .pOffset <> 0) Then
If Not .pParam Is Nothing Then Call addCellColor(.pParam, dRed)
If Not .pParam Is Nothing Then Call addCellColor(.pParam.Offset(0, .dOffset), dRed)
If Not .pParam Is Nothing Then Call addCellColor(.pParam.Offset(0, .pOffset), dRed)
If Not .rParam Is Nothing Then Call addCellColor(.rParam, dRed)
If Not .uParam Is Nothing Then Call addCellColor(.uParam, dRed)
If Not .oParam1 Is Nothing Then Call addCellColor(.oParam1, dRed)
If Not .oParam2 Is Nothing Then Call addCellColor(.oParam2, dRed)
If Not .fParam Is Nothing Then Call addCellColor(.fParam.Offset(0, .fOffset), dRed)
End If
'Cell is magenta if there were no parameter values found for this phase on this column/formula.
' Error 7: There does not exist parameter value for this phase on this formula
' Error 5: Phase tab was not found
If InStr(1, .error, "Error 5:") > 0 Or InStr(1, .error, "Error 7:") > 0 Then
If Not .fParam Is Nothing Then Call addCellColor(.fParam.Offset(0, .fOffset), magenta)
If Not .uParam Is Nothing Then Call addCellColor(.uParam, magenta)
If Not .oParam1 Is Nothing Then Call addCellColor(.oParam1, magenta)
If Not .oParam2 Is Nothing Then Call addCellColor(.oParam2, magenta)
If Not .rParam Is Nothing Then Call addCellColor(.rParam, magenta)
End If
'Cell is dark grey if the value, or parameter in that cell is operation default. (Some may be light grey)
' para.newValue = operation default
If .newValue = "Operation Default" Then
If Not .rParam Is Nothing Then Call addCellColor(.rParam, dGrey)
If Not .oParam1 Is Nothing Then Call addCellColor(.oParam1, dGrey)
If Not .oParam2 Is Nothing Then Call addCellColor(.oParam2, dGrey)
If Not .uParam Is Nothing Then Call addCellColor(.uParam, dGrey)
If Not .fParam Is Nothing Then Call addCellColor(.fParam.Offset(0, .fOffset), dGrey)
End If
'Cell is white if that cell was not able to be checked across documents, or invalid entries exist. Most commonly the cells are white because
'they did not exist in the formula but they did in the operation, or they did not exist in the parameter document. Cells white in parameter
'document because they were never looked at due to mismatched names.
End With
End If
Next p
End Function
</code></pre>
<p><a href="https://stackoverflow.com/questions/54831083/optimize-my-gradient-fill-function-and-determine-why-is-takes-so-long-to-run?noredirect=1#comment96438436_54831083">Linked question on StackOverflow</a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T17:23:24.930",
"Id": "414006",
"Score": "1",
"body": "Welcome to CR! I've added the runtimes from the linked SO post (I'd recommend removing the SO question) - curious what the inputs are for such times, surely it doesn't take 1-2 minutes to fill up *just one cell*? Feel free to [edit] your post to include the code that uses these functions, too!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T17:42:36.213",
"Id": "414007",
"Score": "0",
"body": "@MathieuGuindon - Thanks for the help you are giving me, much appreciated! I've edited the post with some more info but it is all I am allowed to share. There are MANY cells being filled. My main issue is one function takes longer than the other, but do the same thing really."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T17:48:18.343",
"Id": "414008",
"Score": "0",
"body": "That's perfect! I don't think having the two functions is necessary though - just including the one that's actually being used should be good enough. Side note, you might want to look into what low-hanging fruit [Rubberduck](http://www.github.com/rubberduck-vba/Rubberduck)'s *code inspections* can find & fix. (note: I and a bunch of reviewers monitoring the VBA tag, contribute to this free/open-source project; star us on GitHub if you like! see the [tag:rubberduck] tag for more details)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T18:47:53.990",
"Id": "414020",
"Score": "0",
"body": "@MathieuGuindon - I know about Rubberduck, but I am not able to run it on this work computer, it unfortunately gets blocked. It would be very useful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T01:16:57.703",
"Id": "414042",
"Score": "0",
"body": "Instead of clearing all of the colorstops and re-adding them, you could adjust the position of the existing stops and just add the one new one. That might be faster."
}
] | [
{
"body": "<p>Following my suggestion in the comments, turns out this is only slightly faster: for 5 colors over 5000 cells it's ~6.1 sec vs. ~8.5 sec for your Function 2...</p>\n\n<pre><code>Sub addCellColor2(ByVal c As Range, ByVal color As Long)\n\n Dim step, pos, i As Long, n As Long, cStop As ColorStop\n\n With c.Interior\n If .color = 16777215 Then\n .Pattern = xlPatternLinearGradient\n .Gradient.Degree = 0\n With .Gradient.ColorStops\n .Item(1).color = color\n .Item(2).color = color\n End With\n Exit Sub\n End If\n End With\n\n With c.Interior.Gradient\n\n 'see if this color already exists\n For Each cStop In .ColorStops\n If cStop.color = color Then Exit Sub\n Next cStop\n\n n = .ColorStops.Count\n If n = 2 And .ColorStops(1).color = .ColorStops(2).color Then\n .ColorStops(2).color = color\n Exit Sub\n End If\n\n step = Round(1 / (n), 3)\n pos = step\n For i = 2 To n\n .ColorStops(i).Position = pos\n pos = pos + step\n Next i\n .ColorStops.Add(1).color = color\n\n End With\n\n\nEnd Sub\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T19:29:55.007",
"Id": "414331",
"Score": "0",
"body": "Sped it up a little bit yeah. My boss really wants Function 1 unfortunately and I have not been able to work out the math for just adding these stops easily. I think it will just have to stick to being a time consuming macro. We will only be running it for a few weeks anyways a few times a day, so not too much time is lost."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T05:40:27.833",
"Id": "214095",
"ParentId": "214048",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "214095",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T17:16:16.140",
"Id": "214048",
"Score": "3",
"Tags": [
"vba",
"excel"
],
"Title": "Cell Gradient Fill Macro"
} | 214048 |
<p>This is my first rust program. I don't mind this being a strict review.</p>
<h2>What I want Reviewed?</h2>
<ul>
<li>Idiomatic code.</li>
<li>Performance improvements.</li>
<li>Clean code!</li>
</ul>
<h2>Program Requirements:</h2>
<ul>
<li>Input a unsigned integer and calculate it's factorial.</li>
<li>If <code>q</code> is given as input exit application.</li>
</ul>
<h2>Implementation</h2>
<ul>
<li>Use a big unsigned int implementation with <code>*=</code>, <code>clone</code> and <code>+=</code> implementations. I didn't implement all operators as it is not necessary for factorial.</li>
<li>Formatting: rustfmt</li>
<li>Lint: clippy - returns false positives regarding <code>%</code>, <code>/</code> etc used in operator traits, no other issue was reported.</li>
</ul>
<h2>Manual Testing Code</h2>
<p>I've used below python code to verify my application. It works & there are no compilation errors.</p>
<pre class="lang-py prettyprint-override"><code>from math import factorial
print(factorial(50))
</code></pre>
<p>output:</p>
<pre class="lang-none prettyprint-override"><code>30414093201713378043612608166064768844377641568960512000000000000
</code></pre>
<h2>Program Run Output</h2>
<pre class="lang-none prettyprint-override"><code>Enter n to calculate n!, enter q to exit
n = 0
0! = 1
n = 1
1! = 1
n = 2
2! = 2
n = 3
3! = 6
n = 50
50! = 30414093201713378043612608166064768844377641568960512000000000000
n = -1
Invalid input: -1
n = a
Invalid input: a
n = q
Program end.
</code></pre>
<h2>Code (main.rs)</h2>
<pre><code>use std::cmp;
use std::collections::VecDeque;
use std::fmt;
use std::io;
use std::io::prelude::*;
use std::ops;
const BASE: u8 = 10;
#[derive(Debug, Clone)]
struct BigUInt {
numbers: VecDeque<u8>,
}
impl BigUInt {
fn _carry_mul(&mut self, digit: u8) {
let mut temp: u8;
let mut mul: u8;
let mut carry: u8 = 0;
// multiply all numbers
for i in 0..self.numbers.len() {
temp = carry + (self.numbers[i] * digit);
if temp >= BASE {
mul = temp % BASE;
carry = temp / BASE;
} else {
mul = temp;
carry = 0;
}
self.numbers[i] = mul;
}
// process remaining carry
while carry > 0 {
temp = carry % BASE;
self.numbers.push_back(temp);
carry /= BASE;
}
}
fn _carry_add(&mut self, digit: u8) {
let mut temp: u8;
let mut mul: u8;
let mut carry: u8 = 0;
// add all numbers
for i in 0..self.numbers.len() {
temp = carry + (self.numbers[i] + digit);
if temp >= BASE {
mul = temp % BASE;
carry = temp / BASE;
} else {
mul = temp;
carry = 0;
}
self.numbers[i] = mul;
}
// process remaining carry
while carry > 0 {
temp = carry % BASE;
self.numbers.push_back(temp);
carry /= BASE;
}
}
}
impl fmt::Display for BigUInt {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for num in self.numbers.iter().rev() {
write!(f, "{}", num)?;
}
write!(f, "")
}
}
impl ops::AddAssign<BigUInt> for BigUInt {
fn add_assign(&mut self, rhs: BigUInt) {
if rhs.numbers.len() == 1 && rhs.numbers[0] == 0 {
// do nothing when adding a zero
} else if rhs.numbers.len() == 1 && rhs.numbers[0] < BASE {
self._carry_add(rhs.numbers[0]);
} else {
let l_count = self.numbers.len();
let r_count = rhs.numbers.len();
let count = cmp::min(l_count, r_count);
let mut carry: u8 = 0;
let mut temp: u8;
for i in 0..count {
temp = carry + self.numbers[i] + rhs.numbers[i];
self.numbers[i] = temp % BASE;
carry = temp / BASE;
}
if count == l_count {
// smaller lhs
for i in count..r_count {
temp = carry + rhs.numbers[i];
self.numbers.push_back(temp % BASE);
carry = temp / BASE;
}
} else if count == r_count {
// smaller rhs
for i in count..l_count {
temp = carry + self.numbers[i];
self.numbers[i] = temp % BASE;
carry = temp / BASE;
}
}
while carry > 0 {
temp = carry % BASE;
self.numbers.push_back(temp);
carry /= BASE;
}
}
}
}
impl ops::MulAssign<BigUInt> for BigUInt {
fn mul_assign(&mut self, rhs: BigUInt) {
if rhs.numbers.len() == 1 && rhs.numbers[0] == 0 {
self.numbers.clear();
self.numbers.push_back(0);
} else if rhs.numbers.len() == 1 && rhs.numbers[0] == 1 {
// nothing to do
} else {
let mut level: BigUInt = self.clone();
self.numbers.clear();
self.numbers.push_back(0);
let mut cur: BigUInt;
// do first multiplication
for mul in &rhs.numbers {
cur = level.clone();
cur._carry_mul(*mul);
*self += cur;
level.numbers.push_front(0);
}
}
}
}
fn new_big_u_int(n: u128) -> BigUInt {
let mut x = BigUInt {
numbers: VecDeque::new(),
};
let mut temp = n;
let base = u128::from(BASE);
while temp > 0 {
x.numbers.push_back((temp % base) as u8);
temp /= base;
}
x
}
fn factorial(n: u128) -> BigUInt {
let mut current = new_big_u_int(1);
for i in 2..=n {
current *= new_big_u_int(i);
}
current
}
fn main() {
let mut input_text;
println!("Enter n to calculate n!, enter q to exit");
loop {
print!("n = ");
io::stdout().flush().unwrap();
input_text = String::new();
io::stdin()
.read_line(&mut input_text)
.expect("failed to read input");
let trimmed = input_text.trim();
if trimmed == "q" {
println!("Program end.");
break;
}
match trimmed.parse::<u128>() {
Ok(n) => println!("{}! = {}", n, factorial(n)),
Err(..) => println!("Invalid input: {}", trimmed),
};
}
}
</code></pre>
| [] | [
{
"body": "<p>I didn't look if your code was correct, I just look the style:</p>\n\n<ul>\n<li>use iterator instead of index access</li>\n<li>replace <code>write!(f, \"\")</code> by <code>Ok(())</code></li>\n<li>remove most of type <code>: u8</code> and let the compiler infer the type</li>\n<li>remove a lot of unnecessary <code>let mut</code>, example <code>let mut temp</code></li>\n<li>Add a <code>DecIter</code> that deconstruct a number (need <code>num</code> to be generic)</li>\n<li>Use <code>zip_longest()</code> from <code>itertools</code> to improve <code>add_assign()</code></li>\n<li>Need to add every operation <code>std::ops::Add</code> and <code>std::ops::Mul</code> for example, (that could improve <code>mul_assign()</code> and <code>factorial()</code>)</li>\n</ul>\n\n<pre><code>use std::collections::VecDeque;\nuse std::fmt;\nuse std::ops;\n\n#[derive(Debug, Clone)]\nstruct BigUInt {\n numbers: VecDeque<u8>,\n}\n\nimpl fmt::Display for BigUInt {\n fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {\n for num in self.numbers.iter().rev() {\n write!(f, \"{}\", num)?;\n }\n Ok(())\n }\n}\n\nstruct DecIter<T> {\n n: T,\n base: T,\n}\n\nimpl<T> Iterator for DecIter<T>\nwhere\n T: Copy,\n T: num::Zero,\n T: ops::Rem<Output = T>,\n T: ops::Div<Output = T>,\n{\n type Item = T;\n\n fn next(&mut self) -> Option<Self::Item> {\n if !self.n.is_zero() {\n let next = self.n % self.base;\n self.n = self.n / self.base;\n Some(next)\n } else {\n None\n }\n }\n}\n\ntrait Dec<T> {\n fn dec(self, base: T) -> DecIter<T>;\n}\n\nimpl<T> Dec<T> for T {\n fn dec(self, base: T) -> DecIter<T> {\n DecIter { n: self, base }\n }\n}\n\nimpl BigUInt {\n const BASE: u8 = 10;\n\n fn carry_mul(&mut self, digit: u8) {\n // multiply all numbers\n let carry = self.numbers.iter_mut().fold(0, |carry, n| {\n let temp = carry + (*n * digit);\n let (carry, next) = if temp >= Self::BASE {\n (temp / Self::BASE, temp % Self::BASE)\n } else {\n (0, temp)\n };\n *n = next;\n carry\n });\n\n // process remaining carry\n self.numbers.extend(carry.dec(Self::BASE))\n }\n\n fn carry_add(&mut self, digit: u8) {\n // add all numbers\n let carry = self.numbers.iter_mut().fold(0, |carry, n| {\n let temp = carry + (*n + digit);\n let (carry, next) = if temp >= Self::BASE {\n (temp / Self::BASE, temp % Self::BASE)\n } else {\n (0, temp)\n };\n *n = next;\n carry\n });\n\n // process remaining carry\n self.numbers.extend(carry.dec(Self::BASE))\n }\n}\n\nuse itertools::EitherOrBoth::{Both, Left, Right};\nuse itertools::Itertools;\n\nimpl ops::AddAssign<BigUInt> for BigUInt {\n fn add_assign(&mut self, rhs: BigUInt) {\n if rhs.numbers.len() == 1 && rhs.numbers[0] == 0 {\n // do nothing when adding a zero\n } else if rhs.numbers.len() == 1 && rhs.numbers[0] < Self::BASE {\n self.carry_add(rhs.numbers[0]);\n } else {\n self.numbers.resize(rhs.numbers.len(), 0);\n let carry =\n self.numbers\n .iter_mut()\n .zip_longest(&rhs.numbers)\n .fold(0, |carry, i| match i {\n Both(lhs, rhs) => {\n let temp = carry + *lhs + rhs;\n *lhs = temp % Self::BASE;\n temp / Self::BASE\n }\n Left(lhs) => {\n let temp = carry + *lhs;\n *lhs = temp % Self::BASE;\n temp / Self::BASE\n }\n Right(_) => unreachable!(),\n });\n\n self.numbers.extend(carry.dec(Self::BASE))\n }\n }\n}\n\nimpl ops::MulAssign<BigUInt> for BigUInt {\n fn mul_assign(&mut self, rhs: BigUInt) {\n if rhs.numbers.len() == 1 && rhs.numbers[0] == 0 {\n self.numbers.clear();\n self.numbers.push_back(0);\n } else if rhs.numbers.len() == 1 && rhs.numbers[0] == 1 {\n // nothing to do\n } else {\n let mut level = self.clone();\n self.numbers.clear();\n self.numbers.push_back(0);\n\n // do first multiplication\n for mul in &rhs.numbers {\n let mut cur = level.clone();\n cur.carry_mul(*mul);\n\n *self += cur;\n\n level.numbers.push_front(0);\n }\n }\n }\n}\n\nfn new_big_u_int(n: u128) -> BigUInt {\n BigUInt {\n numbers: n.dec(u128::from(BigUInt::BASE)).map(|x| x as u8).collect(),\n }\n}\n\nfn factorial(n: u128) -> BigUInt {\n (2..=n)\n .map(new_big_u_int)\n .fold(new_big_u_int(1), |mut acc, n| {\n acc *= n;\n acc\n })\n}\n\nfn main() {\n assert_eq!(\n \"30414093201713378043612608166064768844377641568960512000000000000\",\n format!(\"{}\", factorial(50))\n );\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T22:55:19.553",
"Id": "214075",
"ParentId": "214049",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "214075",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T17:20:15.323",
"Id": "214049",
"Score": "1",
"Tags": [
"beginner",
"rust"
],
"Title": "Factorial Calculator with a basic BigUInt"
} | 214049 |
<p>I was asked by a friend to write a simple page for selecting members to various tasks. The members are listed in a textfile, along with how much they are willing to contribute (Usually a number between 0 and 1). Bellow is an example of such a list:</p>
<pre><code>name, mebershipdegree
Noen, 4
John Doe, 1
The rock, 0.5
Ally MacBeal, 0.121212021
</code></pre>
<p>Now my goal was to create a generator that picked one of the names from the list above relative to how much they wanted to contribute. So the leader should show up much more than the other names. My code is working as intended, the ratios seems to work properly. There are however a few things that bugs me</p>
<ul>
<li>Is the JavaScript modern, succint and understandable? </li>
<li>I added a failsaife if the memberlist is not found, is the way to handle this error ok?</li>
<li>How could the JavaScript file be improved?</li>
<li>In firefox the site flashes when one reloads the page. This might be because the JavaScript fires before the CSS is loaded. </li>
<li>Is there a better method to do the fetch part? Now I have to do it twice to be able to reload the page using spacebar (not yet implemented in the live version).</li>
</ul>
<h1>Live version <a href="https://oisov.github.io/Hvem/index.html" rel="nofollow noreferrer">Hvem (Who)</a>. <a href="https://github.com/Oisov/Hvem" rel="nofollow noreferrer">GitHub</a></h1>
<p><strong>HTML: index.html</strong></p>
<pre><code><!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Hvem</title>
<link rel="apple-touch-icon" sizes="180x180" href="./apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="./favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="./favicon-16x16.png">
<link rel="manifest" href="./site.webmanifest">
<link rel="mask-icon" href="./safari-pinned-tab.svg" color="#5bbad5">
<meta name="msapplication-TileColor" content="#da532c">
<meta name="theme-color" content="#ffffff">
<link rel="stylesheet" href="index.css">
</head>
<body>
<div class="center">
<h1 id="Noen"></h1>
</div>
<script type="text/javascript" src="hvem.js"></script>
</body>
</html>
</code></pre>
<p><strong>CSS: main.css</strong></p>
<pre><code>html,
body {
margin: 0;
height: 100%;
overflow: hidden;
overflow-y: hidden;
}
.center {
height: 100%;
position: relative;
}
.center h1 {
text-align: center;
font-size: 12vw;
margin: 0;
position: absolute;
top: 50%;
left: 50%;
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
</code></pre>
<p><strong>Javascript: hvem.js</strong></p>
<pre><code>document.addEventListener('keyup', function(e){
if(e.keyCode == 32)
// Reloads name on spacebar
fetch("medlemsgrad.txt")
.then(handleErrors)
.then(response =>
response.text()
.then(text =>
document.getElementById("Noen").innerHTML = hvem(text))
)
.catch(error => console.log(error));
});
document.addEventListener("DOMContentLoaded", function(event) {
// Uses the built in fetch to read the textfile
fetch("medlemsgrad.txt")
.then(handleErrors)
.then(response =>
response.text()
.then(text =>
document.getElementById("Noen").innerHTML = hvem(text))
)
.catch(error => console.log(error));
});
function handleErrors(response) {
//If medlemsgrad.text not found set hvem to "Noen" and throw an error
if (!response.ok) {
document.getElementById("Noen").innerHTML = "Noen";
throw "medelmsgrad.txt is missing!";
}
return response;
}
function hvem(text) {
let lines = text.split(/\r\n|\n/);
let members = getMembers(lines);
let accumulativeMembers = getAccumulutiveMembers(members);
return getHvem(accumulativeMembers);
}
function getMembers(lines) {
// members = [[John Doe, 0.13], [Jane Roe, 0,23]]
let members = [];
lines.forEach(line => {
let data = line.split(',');
let membershipDegree = parseFloat(data[1]);
// This is to avoid the headers (navn, medlemsgrad),
// if membershipdegree is not a number skip
if (!isNaN(membershipDegree)) {
let name = data[0].trim();
members.push([name, membershipDegree]);
}
});
return members;
}
function getAccumulutiveMembers(members) {
// The next function normalizes the membershipDegree to 1 and order the
// members accumulatively. Example: Let
//
// [noen: 4, a: 1, b, 1]
//
// then the accumululative list looks like
//
// [noen: 4/6, a: 4/6 + 1/6, b: 4/6 + 1/6 + 1/6]
//
// [noen: 4/6, a: 5/6, b: 1]
//
// As it is sorted in ascending order
let totalMembershipDegree = 0;
members.forEach(member => {
totalMembershipDegree += member[1]
});
let accumulative = 0;
let accumulativeMemberlist = [];
members.forEach(member => {
name = member[0];
membershipDegree = member[1];
activity = parseFloat(membershipDegree) / totalMembershipDegree;
accumulative += activity;
accumulativeMemberlist.push([name, accumulative]);
});
// Sorts the accumulative list in ascending order (low to high)
accumulativeMemberlist.sort((a, b) => {
return a[1] > b[1] ? 1 : a[1] < b[1] ? -1 : 0
});
// Sets the last member to 1, as the accumulative total should be 1
// it is not one due to slight round off errors
accumulativeMemberlist[accumulativeMemberlist.length - 1][1] = 1;
return accumulativeMemberlist;
}
function getHvem(accumulativeMembers) {
// Sets hvem as the default name. Tries 100 times to randomly pick someone
// from the accumulatively membership list (including noen)
// Example:
//
// [noen: 4/6, a: 5/6, b: 1]
//
// We then pick a random integer in the range [0, 1]
// If this random number is less than or equal to 4/6 then Noen is choosen.
// If the random number is between 4/6 and 5/6, a is choosen
// If the random number is between 5/6 and 1, b is choosen.
// This means that the chance of picking Noen is 4 times as great as b or a
// which is what we wanted.
console.log(accumulativeMembers);
let randInt = Math.random();
for (const member of accumulativeMembers) {
var name = member[0];
let number = member[1];
if (randInt <= number) {
return name;
}
};
return name;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T18:19:30.503",
"Id": "414012",
"Score": "1",
"body": "Hey, long time no see! A̶l̶s̶o̶ ̶i̶s̶ ̶t̶h̶e̶ ̶'̶l̶i̶v̶e̶ ̶v̶e̶r̶s̶i̶o̶n̶'̶ ̶m̶e̶a̶n̶t̶ ̶t̶o̶ ̶s̶h̶o̶w̶ ̶m̶o̶r̶e̶ ̶t̶h̶a̶n̶ ̶j̶u̶s̶t̶ ̶\"̶N̶o̶e̶n̶\"̶?̶ I just realized that's the result."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T18:28:12.233",
"Id": "414015",
"Score": "0",
"body": "Thanks! In the live version updating the page with spacebar is not yet implemented. However, you can get another result by reloading the page manually (F5 or a similar hotkey)."
}
] | [
{
"body": "<blockquote>\n <p>Is the JavaScript modern, succint and understandable?</p>\n</blockquote>\n\n<p>Provided you can use ES6, you could cut off a lot with, for example, arrow functions and argument destructuring.</p>\n\n<blockquote>\n <p>How could the JavaScript file be improved?</p>\n</blockquote>\n\n<p>I understood you are doing weighted random selection? If so, I did some searching and found another way which simplifies the code a lot; see below.</p>\n\n<blockquote>\n <p>In firefox the site flashes when one reloads the page. This might be because the JavaScript fires before the CSS is loaded.</p>\n</blockquote>\n\n<p>One often seen method is to put the javascript code (external or otherwise) just before the closing <code></body></code> tag, but for some reason it feels wrong to me. Another option would be to use the <code>load</code> event instead of <code>DOMContentLoaded</code>, but again, that feels wrong to me. </p>\n\n<blockquote>\n <p>Is there a better method to do the fetch part? Now I have to do it twice to be able to reload the page using spacebar (not yet implemented in the live version).</p>\n</blockquote>\n\n<p>You can give a name to the function body, and give a reference to it for the event listeners (i.e. <code>fun = evt => {...}; el.addEventListener('whatever', fun)</code></p>\n\n<p>So here’s what I put together from my findings and some of the above suggestions:</p>\n\n<pre><code>const asMembers = txt =>\n txt.split(/\\r\\n|\\n/)\n .slice(1, -1) // drop the header line and the last (empty) split\n .map(line => {\n let [name, weight] = line.split(/, ?/)\n return [name.trim(), Number(weight)]\n }) // you could `.filter(([, n]) => !Number.isNaN(n))` to drop weightless\n\nconst randomBetween = (min, max) =>\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random#Examples\n // NOTE: => [min, max)\n Math.random() * (max - min) + min\n\nconst weightedRandom = ary => {\n // https://medium.com/@peterkellyonline/weighted-random-selection-3ff222917eb6\n let randomWeight = randomBetween(1, ary.reduce((acc, [, n]) => acc + n, 0))\n for(let [name, weight] of ary) {\n randomWeight -= weight\n if(randomWeight <= 0)\n return name\n }\n}\n</code></pre>\n\n<p>and then the calls would go something like <code>fetch(...).then(asMembers).then(weightedRandom)</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T11:57:56.317",
"Id": "414406",
"Score": "0",
"body": "Interesting solution. How would this work when none of my weights are integers?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T17:09:28.693",
"Id": "414444",
"Score": "0",
"body": "@N3buchadnezzar with a quick `times = (n, retval = {}) => { let ppl = asMembers(fileContentsAsString); while(n-- > 0) { let cur = weightedRandom(ppl); retval[cur] = retval[cur] ? retval[cur] + 1 : 1 } return retval }` and running `times(10000)`, I get `{Noen: 6437, 'John Doe': 2169, 'The rock': 1121, 'Ally MacBeal': 273}`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T06:22:32.050",
"Id": "214297",
"ParentId": "214051",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T17:38:17.413",
"Id": "214051",
"Score": "4",
"Tags": [
"javascript"
],
"Title": "Select members based on activity"
} | 214051 |
<p>I'm new to programming. I tried to find a way to convert numbers into letters with Python. I would like to receive some advice to improve myself. This program works for numbers between 1 and 10<sup>6</sup> and I would like to know how the logic of the program can be improved.</p>
<pre><code>def changeNumberIntoLetter(value):
number=numToLetter(value)
return number
def numToLetter(value): #The function converts the numbers into letters.
if value==1: return 'one'
elif value==2: return 'two'
elif value==3: return 'three'
elif value==4: return 'four'
elif value==5: return 'five'
elif value==6: return 'six'
elif value==7: return 'seven'
elif value==8: return 'eight'
elif value==9: return 'nine'
elif value==10: return 'ten'
elif value==11: return 'eleven'
elif value==12: return 'twelve'
elif value==13: return 'thirteen'
elif 13<value<=19: return composeTeen(value)
elif value>19:
if value==20: return 'twenty'
elif value==30: return 'thirty'
elif value==50: return 'fifty'
elif value==10**2: return 'one hundred'
elif value==10**3: return 'one thousand'
elif value==10**5: return 'one hundred thousand'
elif value==10**6: return 'one milion'
elif value>=20: return composeNumbers(value)
else: exit('Out of range')
else: return ''
def composeNumbers(value): #The function build every number biger than 40
if 40<=value<10**2:
value1=int(str(value)[0])
value2= int(str(value)[1])
if value1==2:
value1= 'twen'
return value1 + 'ty' + '-' + numToLetter(value2)
if value1==3:
value1='thir'
return value1 + 'ty' + '-' + numToLetter(value2)
if value1==8:
value1='eigh'
return value1 + 'ty' + '-' + numToLetter(value2)
elif value1==5:
value1='fif'
return value1 + 'ty' + '-' + numToLetter(value2)
return numToLetter(value1) + 'ty' + '-' + numToLetter(value2)
elif 10**2<=value<10**3:
value1=int(str(value)[0])
value2= int(str(value)[1:])
return numToLetter(value1) + ' ' + 'hundred' + ' ' + numToLetter(value2)
elif 10**3<=value<10**4:
value1=int(str(value)[0])
value2=int(str(value)[1:])
elif 10**4<=value<10**5:
value1=int(str(value)[0:2])
value2=int(str(value)[2:])
elif 10**5<=value<10**6:
value1=int(str(value)[0:3])
value2=int(str(value)[3:])
return numToLetter(value1) + ' ' + 'thousand' + ' ' + numToLetter(value2)
def composeTeen(value): #The function takes the unit and then converts it into letter to build the word.
value= int(str(value)[-1]) #It turns elem in string to take the last position and it converts it again in integer to change it in letters. Then it composes the word adding 'teen' at the end.
value= numToLetter(value)
if value=='five': value= 'fif'
value= value + 'teen'
return value
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T17:59:50.800",
"Id": "414009",
"Score": "1",
"body": "Something which could help you make this code effective is if you have a look at this code, https://codereview.stackexchange.com/questions/182833/converting-a-large-number-into-something-like-4-novemnongent, it is not an answer because it doesn't do it just words but it uses techniques which could be good for what you are trying to do"
}
] | [
{
"body": "<p>I did this by <code>inflect</code> <code>pypi</code> library:</p>\n\n<pre><code>import inflect\n\nig = inflect.engine()\nprint(ig.number_to_words(85))\n</code></pre>\n\n<p>Out:</p>\n\n<pre><code>eighty-five\n</code></pre>\n\n<hr>\n\n<p>[<strong>NOTE</strong>]:</p>\n\n<p>Install <code>inflect</code> library by <code>pip</code>:</p>\n\n<pre><code>$ pip install inflect\n</code></pre>\n\n<hr>\n\n<p>Furthermore, I found this method too:</p>\n\n<pre><code>>>> import num2word\n>>> num2word.to_card(15)\n'fifteen'\n>>> num2word.to_card(55)\n'fifty-five'\n>>> num2word.to_card(1555)\n'one thousand, five hundred and fifty-five'\n</code></pre>\n\n<hr>\n\n<p>[<strong>NOTE</strong>]:</p>\n\n<p><sub>These are the Github link of mentioned libraries if you want to know how they implemented:</sub></p>\n\n<ul>\n<li><sub><a href=\"https://github.com/jazzband/inflect\" rel=\"noreferrer\">inflect Github</a></sub></li>\n<li><sub><a href=\"https://github.com/savoirfairelinux/num2words\" rel=\"noreferrer\">num2words Github</a></sub></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T18:26:50.863",
"Id": "414014",
"Score": "9",
"body": "Offloading to others is good, Pythonic even. But this doesn't really help the person improve their own programing abilities."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T18:34:36.977",
"Id": "414016",
"Score": "1",
"body": "I got it, so if he wants to know how these libraries implemented, I'll update my answer with the Github links of these libraries."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T19:46:15.827",
"Id": "414023",
"Score": "2",
"body": "@Peilonrayz - True, good point. I can see it both ways. While it doesn't help OP program the code themselves, it hopefully it shows OP that in Python, there's likely a library already out there to help you so you don't reinvent the wheel (no pun intended!)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T18:19:28.120",
"Id": "214054",
"ParentId": "214053",
"Score": "6"
}
},
{
"body": "<p>This is good work! Well done as a beginner programmer. </p>\n\n<blockquote>\n<pre><code>def changeNumberIntoLetter(value):\n number=numToLetter(value)\n return number\n</code></pre>\n</blockquote>\n\n<p>This function doesn't really do anything useful to be honest. Can't you directly use <code>numToLetter</code>.</p>\n\n<blockquote>\n<pre><code>if value==1: return 'one'\nelif value==2: return 'two'\nelif value==3: return 'three'\nelif value==4: return 'four'\nelif value==5: return 'five'\nelif value==6: return 'six'\n</code></pre>\n</blockquote>\n\n<p>Instead of creating lot of if statements. Try using a dictionary like this:</p>\n\n<pre><code>NUM_TO_WORD_MAPPING = {1: \"one\", 2: \"two\"}\n</code></pre>\n\n<p>and you can refer the string to number using </p>\n\n<pre><code>if value in NUM_TO_WORD_MAPPING:\n return NUM_TO_WORD_MAPPING[value]\nelse:\n # ... special cases.\n</code></pre>\n\n<p>As sergiy-kolodyazhnyy said, you can also use a list or a tuple. </p>\n\n<blockquote>\n<pre><code>int(str(value)[-1])\n</code></pre>\n</blockquote>\n\n<p>use <code>value % 10</code> to extract numbers easily. This is <a href=\"https://en.wikipedia.org/wiki/Modulo_operation\" rel=\"noreferrer\">modulo operator</a> and returns remainder after division. </p>\n\n<hr>\n\n<p><strong>Bonus Content: Code Style</strong></p>\n\n<p>How your code looks like is as equally important as how you implement it. Because you and other programmers will spend time reading it.</p>\n\n<blockquote>\n <p>“Indeed, the ratio of time spent reading versus writing is well over\n 10 to 1. We are constantly reading old code as part of the effort to\n write new code. ...[Therefore,] making it easy to read makes it easier\n to write.”</p>\n \n <p>― Robert C. Martin, Clean Code: A Handbook of Agile Software\n Craftsmanship</p>\n</blockquote>\n\n<p>Let's take a look at your function</p>\n\n<blockquote>\n<pre><code>def numToLetter(value): #The function converts the numbers into letters. \n</code></pre>\n</blockquote>\n\n<p>I recommend that you use <code>snake_case</code> (<code>number_to_letter</code>) as it is considered industry standard for python programs. Comments are better done using <code>\"\"\" comment \"\"\"</code> style.</p>\n\n<p>In this scenario however <em>comment is not really required</em> because your function name says that it's purpose is converting number to letter. People usually forget to update comments and it ends up giving incorrect information. If you want to use documentation comments anyway, make sure that comments are always up to date.</p>\n\n<p>Reading material:</p>\n\n<ol>\n<li><a href=\"https://www.python.org/dev/peps/pep-0287/\" rel=\"noreferrer\">PEP-8 - Coding conventions / standard</a></li>\n<li><a href=\"https://www.python.org/dev/peps/pep-0287/\" rel=\"noreferrer\">PEP-287 - Document comment standard</a></li>\n<li><a href=\"https://stackoverflow.com/questions/3898572/what-is-the-standard-python-docstring-format\">Documentation related SO Question</a></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T20:17:45.267",
"Id": "414027",
"Score": "1",
"body": "Thank you so much! This is really helpful; I'll improve the code with these changes"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T20:34:13.767",
"Id": "414028",
"Score": "1",
"body": "A list or tuple could probably also work, with 0 item being `None`. A number itself would correspond to index position of the word item in list/tuple"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T22:30:19.750",
"Id": "414034",
"Score": "0",
"body": "@RobertaBelladonna, don't forget to accept this answer if you think it answered your question"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T16:31:54.150",
"Id": "414061",
"Score": "1",
"body": "Updated with more info. @SergiyKolodyazhnyy yes you are correct. :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T19:07:56.237",
"Id": "214056",
"ParentId": "214053",
"Score": "19"
}
},
{
"body": "<h1>Process</h1>\n\n<p>I'm relatively new to Python, so this may not be the Pythonic approach, but I think it's useful to use test-driven development for problems like this. Spelling out numbers has lots of special cases, which can be overwhelming, so working incrementally can be one way to get a handle on it.</p>\n\n<p>I started by writing:</p>\n\n<pre><code>def main():\n for i in range(0, 20):\n print(f\"{i}: {spellNumber(i)}\")\n</code></pre>\n\n<p>This isn't literally a test, because it doesn't check the result, but it shows me the output for the first 20 integers, which is where many of the special cases are.</p>\n\n<p>Then I wrote a simple implementation that uses an array to solve it:</p>\n\n<pre><code>def spellNumber(n):\n units = [\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\",\n \"six\", \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\",\n \"twelve\", \"thirteen\", \"fourteen\", \"fifteen\",\n \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"]\n if n < 20: return units[n]\n return \"out of range\"\n</code></pre>\n\n<p>Once that appeared to be working, I extended my \"test\" by sampling values up to 100:</p>\n\n<pre><code> for i in range(20, 100, 12):\n print(f\"{i}: {spellNumber(i)}\")\n</code></pre>\n\n<p>Note that I kept the original part of the test, so that I make sure I don't break the part that was already working when I try to extend it.</p>\n\n<p>As I modified <code>spellNumber</code> to handle each new range of inputs, I sometimes adjusted the code I'd already written to make it easier for the new code to use it. Having all the tests helped me make sure I didn't break the older code in the process.</p>\n\n<p>Along the way, I made mistakes, and had to figure out how to fix outputs like \"thirty-zero\" in a way that still allowed for \"zero.\"</p>\n\n<h1>Style</h1>\n\n<h2>Comments and docstrings</h2>\n\n<p>Your comments on what the functions do are useful, but I think the Pythonic way to document a function is to use a docstring. So, instead of:</p>\n\n<pre><code>def myFunction(): # This is what my function does\n</code></pre>\n\n<p>Write:</p>\n\n<pre><code>def myFunction():\n \"\"\"This is what my function does.\"\"\"\n</code></pre>\n\n<p>It's appropriate to use regular comments for details in your code, but comments that describe how a function (or class or file) is intended to be used should probably be docstrings.</p>\n\n<h2>Cascades of if-statements</h2>\n\n<p>Whenever you have a lot of similarly structured if-statements (<code>if this: blah elif that: blub elif other: ...</code>), consider whether using a data structure would be a better way to represent the problem.</p>\n\n<p>For example, I used a table for the small numbers. \n Another answer had a good idea of using a dictionary in a similar way. A data structure you can index into or a table you can loop through will also be more efficient than a big cascade of if-statements.</p>\n\n<p>More importantly, data is easy to modify and extend and greatly reduces the amount \"logic\" you have to worry about. For me separating the logic from the data, and made it easier to check the spelling of all those words, because they're all clustered nicely together instead of scattered across several helper functions.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T11:28:27.483",
"Id": "414054",
"Score": "0",
"body": "Thank you for the exhaustive answer. But I don't understand why you use '12' in the second for-statement to expand the function: for i in range(20, 100, 12)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T16:36:16.660",
"Id": "414062",
"Score": "1",
"body": "@RobertaBelladonna It's the step value: The value to add to obtain the next value. In that case, the values obtained are 20, 32, 44, 56, 68, 80, and 92."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T22:33:20.440",
"Id": "414085",
"Score": "1",
"body": "@RobertaBelladonna: kiamlaluno is correct. I didn't want to print every single number up to 100, but I wanted a good sampling of them so that I would likely spot any bugs. I chose 12 as a step size because it gives a good sampling of the two digit numbers. If there were any bugs, they would likely show up."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T21:51:40.750",
"Id": "214068",
"ParentId": "214053",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T17:47:18.130",
"Id": "214053",
"Score": "17",
"Tags": [
"python",
"beginner",
"numbers-to-words"
],
"Title": "Converting numbers to words - Python"
} | 214053 |
<p>I created a function that finds internal and external IP addresses, returns them in dict with the keys <code>external_ips</code> and <code>local_ips</code>:</p>
<pre><code>def get_address_types(address_list):
"""
determine whether an IP address is local or external from a given list of ip
addresses
returns a dict containing external and internal IP addresses, the internal
are determined by the start nodes from a private ip space.
for more information see here: https://en.wikipedia.org/wiki/Private_network
example:
>>> addresses = ["127.0.0.1", "10.0.1.1", "26.76.4.56"]
>>> get_address_types(addresses)
# <= {'external_ips': set(['26.76.4.56']), 'local_ips': set(['10.0.1.1'])}
"""
placeholders = ("0.0.0.0", "255.255.255.255", "127.0.0.1", "8.8.8.8")
retval = {"external_ips": set(), "local_ips": set()}
for ip in address_list:
if not any(n == ip for n in placeholders):
if "." in ip:
local_ip_ranges = ('10', '172', '192')
start_node = ip.split(".")[0]
if any(start == start_node for start in local_ip_ranges):
retval["local_ips"].add(ip)
else:
try:
socket.inet_pton(socket.AF_INET, ip)
retval["external_ips"].add(ip)
except AttributeError:
try:
socket.inet_aton(ip)
retval["external_ips"].add(ip)
except socket.error:
pass
except socket.error:
pass
return retval
</code></pre>
<p>So for example if I have a list that looks like this:</p>
<pre><code>['224.0.0.251', '10.0.1.51', '10.0.1.255', '10.0.1.68', '10.0.1.22', '10.0.1.68', '10.0.1.22', '10.0.1.68', '10.0.1.22', '10.0.1.68', '10.0.1.22', '10.0.1.31', '10.0.1.68', '10.0.1.68', '10.0.1.22', '10.0.1.68', '10.0.1.22', '10.0.1.202', '224.0.0.251', '10.0.1.202', '224.0.0.251', '172.18.0.1', '172.18.255.255', '172.18.0.1', '172.18.255.255', '172.19.0.1', '172.19.255.255', '172.19.0.1', '172.19.255.255', '10.0.1.9', '224.0.0.251', '10.0.1.68', '10.0.1.22', '10.0.1.68', '10.0.1.22', '10.0.1.202', '224.0.0.251', '10.0.1.68', '74.125.198.108', '10.0.1.68', '74.125.198.108', '10.0.1.68', '74.125.198.108', '10.0.1.68', '74.125.198.108', '10.0.1.68', '74.125.198.108', '10.0.1.68', '74.125.198.108', '10.0.1.47', '10.0.1.255', '10.0.1.68', '74.125.198.108', '10.0.1.68', '74.125.198.108', '10.0.1.25', '224.0.0.251', '10.0.1.13', '224.0.0.251', '10.0.1.68', '74.125.198.109', '10.0.1.68', '74.125.198.109', '10.0.1.68', '74.125.198.109', '10.0.1.68', '74.125.198.109', '10.0.1.68', '74.125.198.109', '10.0.1.68', '74.125.198.109', '10.0.1.9', '224.0.0.251', '10.0.1.68', '74.125.198.109', '10.0.1.68', '74.125.198.109', '172.18.0.1', '172.18.255.255', '172.19.0.1', '172.19.255.255', '10.0.1.51', '224.0.0.251', '10.0.1.202', '224.0.0.251', '10.0.1.25', '224.0.0.251', '10.0.1.68', '10.0.1.22', '10.0.1.68', '10.0.1.22', '10.0.1.68', '10.0.1.22', '10.0.1.63', '224.0.0.251', '10.0.1.35', '224.0.0.251', '10.0.1.68', '10.0.1.22', '10.0.1.68', '10.0.1.18', '10.0.1.13', '224.0.0.251', '10.0.1.31', '10.0.1.255', '10.0.1.68', '10.0.1.22', '10.0.1.68', '10.0.1.22', '10.0.1.51', '255.255.255.255', '10.0.1.19', '255.255.255.255', '172.18.0.1', '172.18.255.255', '172.18.0.1', '172.18.255.255', '172.19.0.1', '172.19.255.255', '172.19.0.1', '172.19.255.255', '10.0.1.13', '224.0.0.251', '10.0.1.68', '74.125.198.108', '10.0.1.68', '74.125.198.108', '10.0.1.68', '74.125.198.108', '10.0.1.68', '74.125.198.108', '10.0.1.51', '255.255.255.255', '10.0.1.68', '74.125.198.108', '10.0.1.68', '74.125.198.108', '10.0.1.68', '74.125.198.108', '10.0.1.47', '10.0.1.255', '10.0.1.68', '10.0.1.22', '10.0.1.68', '224.0.0.251', '10.0.1.68', '74.125.198.108', '10.0.1.13', '224.0.0.251', '10.0.1.202', '224.0.0.251', '10.0.1.68', '74.125.198.109', '10.0.1.68', '74.125.198.109', '10.0.1.68', '74.125.198.109', '10.0.1.68', '74.125.198.109', '10.0.1.68', '74.125.198.109', '10.0.1.68', '74.125.198.109', '10.0.1.11', '224.0.0.251', '10.0.1.68', '74.125.198.109', '10.0.1.68', '74.125.198.109', '10.0.1.68', '74.125.198.109', '10.0.1.35', '224.0.0.251', '10.0.1.68', '10.0.1.22', '10.0.1.145', '10.0.1.255', '10.0.1.51', '255.255.255.255', '10.0.1.13', '224.0.0.251', '10.0.1.13', '224.0.0.251', '10.0.1.68', '10.0.1.22', '10.0.1.68', '10.0.1.22', '10.0.1.202', '224.0.0.251', '10.0.1.51', '10.0.1.255', '10.0.1.68', '224.0.0.251', '10.0.1.68', '224.0.0.251', '10.0.1.68', '8.8.8.8', '10.0.1.52', '224.0.0.251', '10.0.1.68', '10.0.1.22', '10.0.1.68', '10.0.1.22', '10.0.1.31', '10.0.1.255', '172.18.0.1', '172.18.255.255', '172.18.0.1', '172.18.255.255', '172.19.0.1', '172.19.255.255', '172.19.0.1', '172.19.255.255', '10.0.1.27', '224.0.0.251', '10.0.1.68', '8.8.8.8', '10.0.1.68', '74.125.198.108', '10.0.1.13', '224.0.0.251', '10.0.1.68', '74.125.198.108', '10.0.1.68', '74.125.198.108', '10.0.1.68', '74.125.198.108', '10.0.1.68', '74.125.198.108', '10.0.1.68', '74.125.198.108', '10.0.1.68', '74.125.198.108', '10.0.1.68', '74.125.198.108', '10.0.1.68', '74.125.198.108', '10.0.1.13', '224.0.0.251', '10.0.1.68', '74.125.198.108', '10.0.1.68', '74.125.198.108', '10.0.1.68', '8.8.8.8', '10.0.1.27', '224.0.0.251', '10.0.1.51', '255.255.255.255', '10.0.1.68', '74.125.198.109', '10.0.1.68', '74.125.198.109', '10.0.1.68', '74.125.198.109', '10.0.1.63', '255.255.255.255', '10.0.1.68', '74.125.198.109', '10.0.1.68', '74.125.198.109', '10.0.1.24', '224.0.0.251', '10.0.1.68', '74.125.198.109', '10.0.1.68', '74.125.198.109', '10.0.1.50', '10.0.1.68', '10.0.1.68', '163.172.24.175', '10.0.1.68', '224.0.0.251', '10.0.1.13', '224.0.0.251', '10.0.1.68', '8.8.8.8', '10.0.1.13', '224.0.0.251', '10.0.1.35', '224.0.0.251', '172.17.0.1', '172.17.255.255', '172.17.0.1', '172.17.255.255', '172.18.0.1', '172.18.255.255', '172.19.0.1', '172.19.255.255', '10.0.1.68', '163.172.24.175', '10.0.1.15', '224.0.0.251', '10.0.1.27', '224.0.0.251', '10.0.1.31', '10.0.1.255', '10.0.1.200', '224.0.0.251', '172.18.0.1', '172.18.255.255', '172.18.0.1', '172.18.255.255', '172.19.0.1', '172.19.255.255', '172.19.0.1', '172.19.255.255', '10.0.1.9', '224.0.0.251', '10.0.1.68', '8.8.8.8', '10.0.1.68', '8.8.8.8', '10.0.1.68', '74.125.198.108', '10.0.1.13', '224.0.0.251', '10.0.1.68', '74.125.198.108', '10.0.1.68', '74.125.198.108', '10.0.1.68', '74.125.198.108', '10.0.1.68', '74.125.198.108', '10.0.1.68', '74.125.198.108', '10.0.1.35', '224.0.0.251', '10.0.1.68', '10.0.1.200', '10.0.1.68', '74.125.198.108', '10.0.1.27', '224.0.0.251', '10.0.1.25', '224.0.0.251', '10.0.1.68', '74.125.198.109', '10.0.1.68', '74.125.198.109', '10.0.1.68', '74.125.198.109', '10.0.1.68', '74.125.198.109', '10.0.1.202', '224.0.0.251', '10.0.1.68', '74.125.198.109', '10.0.1.68', '74.125.198.109', '10.0.1.202', '224.0.0.251', '10.0.1.51', '255.255.255.255', '10.0.1.68', '224.0.0.251', '10.0.1.68', '224.0.0.251', '10.0.1.13', '224.0.0.251', '10.0.1.63', '255.255.255.255', '10.0.1.68', '8.8.8.8', '10.0.1.51', '255.255.255.255', '10.0.1.15', '224.0.0.251', '10.0.1.68', '10.0.1.22', '127.0.0.1', '127.0.0.1', '10.0.1.63', '255.255.255.255', '10.0.1.68', '10.0.1.11', '10.0.1.68', '10.0.1.22']
</code></pre>
<p>And I run it through my function, it will return the following results:</p>
<pre><code>{'external_ips': set(['163.172.24.175', '74.125.198.108', '224.0.0.251', '74.125.198.109']), 'local_ips': set(['10.0.1.200', '10.0.1.202', '172.17.0.1', '10.0.1.145', '172.19.255.255', '10.0.1.63', '172.18.0.1', '172.19.0.1', '10.0.1.47', '10.0.1.68', '172.18.255.255', '10.0.1.27', '10.0.1.25', '10.0.1.24', '10.0.1.22', '172.17.255.255', '10.0.1.255', '10.0.1.9', '10.0.1.31', '10.0.1.52', '10.0.1.35', '10.0.1.50', '10.0.1.51', '10.0.1.13', '10.0.1.11', '10.0.1.15', '10.0.1.18', '10.0.1.19'])}
</code></pre>
<p>I would like some critique on this function and to know what I can do better to solve this specific problem, is there anything that can be changed or simplified to make this function shorter? Is there anything I can add to this function to make it better, etc? Thank you ahead of time.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T19:11:23.727",
"Id": "414022",
"Score": "0",
"body": "To clarify this only works with IPv4 addresses"
}
] | [
{
"body": "<p>Sets are a really nice thing if you only care about membership and not order. They have <span class=\"math-container\">\\$\\mathcal{O}(1)\\$</span> membership testing. Which you completely destroy by manually iterating over every element of the set when you do <code>if not any(n == ip for n in placeholders)</code>. Just do <code>if ip not in placeholders</code>.</p>\n\n<p>Similarly for your local IP ranges. Make it into a <code>set</code> and just use <code>in</code>. Even for tuples you can use <code>in</code>, it is just <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span>, the same as your code.</p>\n\n<p>It might make sense to have a third category where you put all IPs which you neither determine to be local nor external.</p>\n\n<p>Instead of using a dictionary with already given keys and empty sets, you can just use a <code>collections.defaultdict(set)</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T08:41:09.490",
"Id": "214103",
"ParentId": "214055",
"Score": "0"
}
},
{
"body": "<p>First, very good job with function documentation! A few minor notes on that:</p>\n\n<ul>\n<li>Convention usually calls for sentence case (capital first letter ended with a period) for sentences in docstrings. This will make them look nice if you ever render them with something like <a href=\"https://docs.python.org/3.7/library/pydoc.html\" rel=\"nofollow noreferrer\">pydoc</a></li>\n<li>Including an example is fantastic! Additionally if you remove the <code># <=</code> from the return value you can use this for <a href=\"https://docs.python.org/3/library/doctest.html\" rel=\"nofollow noreferrer\">doctests</a>, which is a clever way of both documenting and testing your code</li>\n<li>You may want to also lightly comment your function to demarcate each of the phases of processing the IP</li>\n</ul>\n\n<p>Some random comments:</p>\n\n<ul>\n<li>I'd name <code>address_list</code> just <code>addresses</code></li>\n<li>You can use <code>ip not in placeholders</code>; it is preferred to <code>any(p == ip for p in placeholders)</code></li>\n<li>You probably check <code>'.' in ip</code> so that <code>ip.split('.')[0]</code> can't raise an <code>IndexError</code>. In python, we usually prefer just to try <code>ip.split('.')[0]</code> and handle the <code>IndexError</code> if it happens. \"Try first, apologize later.\"</li>\n</ul>\n\n<p>Let's move on to the bigger stuff:</p>\n\n<p>First, your return value is odd. Having a variable named <code>retval</code> is often a sign that you could improve your function. And further, returning a dictionary (from a function that doesn't operate on dictionaries) is <em>very</em> strange. Although your function is documented nicely, it leaves a lot of room for mistakes. What if I forget the name of the field for externals (I try <code>\"externals\"</code> and I get a <code>KeyError</code>)? Further, I can add keys to that dictionary, which is probably not something you want consumers of your function to be able to do. In addition, the dict is going to have some extra cost (above what I'll recommend) for look ups will will surely take up more space in memory. A dict is not the right datastructure.</p>\n\n<p>Here's what I recommend. Inside your function, have two variables <code>external_ips</code> and <code>local_ips</code>. Instead of doing <code>retval['local_ips'].add(...)</code> just do <code>local_ips.add(...)</code>. I'm even going to go as far as recommending that they be <code>list</code>s instead of <code>set</code>s. You don't really need them to be sets, because you don't take advantage of any of the set properties for <code>local_ips</code> or <code>external_ips</code>. Then, create a <a href=\"https://docs.python.org/3/library/collections.html#collections.namedtuple\" rel=\"nofollow noreferrer\"><code>namedtuple</code></a> for the return value:</p>\n\n<pre><code>IpLocalities = namedtuple('IpLocalities', 'external_ips local_ips')\n\n# Then at the end of your function:\nreturn IpLocalities(external_ips=external_ips, local_ips=local_ips)\n</code></pre>\n\n<p>The benefit here is multiple-fold. Printing this gives you the nice labels (like you had with <code>dict</code>):</p>\n\n<pre><code>IpLocalities(external_ips=['26.76.4.56'], local_ips=['10.0.1.1'])\n</code></pre>\n\n<p>But your access to them is now as efficient as tuple access, but is carries a name, so you don't have to remember if <code>external_ips</code> or <code>local_ips</code> is first. With just a tuple it would be easy to do:</p>\n\n<pre><code># Note the order is wrong here\nlocal_ips, external_ips = get_address_types(addresses)\n</code></pre>\n\n<p>With named tuples you can instead do:</p>\n\n<pre><code>localities = get_address_types(addresses)\nprint(localities.external_ips)\n</code></pre>\n\n<hr>\n\n<p>Next, unfortunately the rules for IP addresses are fairly complicated. Fortunately, python already has a library that handles parsing and manipulating IPs: <a href=\"https://docs.python.org/3/library/ipaddress.html\" rel=\"nofollow noreferrer\"><code>ipaddress</code></a>. You should be using it. Even if you weren't, you'd probably want to split your function up. Currently it has multiple responsibilities (although one of those responsibilities is unnecessary, we'll discuss that last). First, it loosely parses an IP to verify it is valid, then it categories the IP into external or local. This is two jobs for one function. Generally, you want to have functions do one thing and do it well. What if later you need to just verify an IP address, but don't want to classify it as local or external? If you pulled out just the verification into a separate function, say <code>parse_ip</code>, you could do this. You can also test this function in isolation, which will make unit testing much easier. Then, your <code>get_address_types</code> just assumes it is given valid IPs (perhaps you wrap them in an object) and implementing/unit testing it becomes so much easier.</p>\n\n<p>Now, <code>ipaddress</code> already does basically all of this. Check it out:</p>\n\n<pre><code>def classify_addresses(ips):\n public_ips = []\n private_ips = []\n\n for ip in ips:\n if ip.is_global:\n public_ips.append(ip)\n if ip.is_private:\n private_ips.append(ip)\n\n\n return IpLocalities(public_ips=public_ips, private_ips=private_ips)\n\n\nfrom ipaddress import ip_address\n\nips = [\n ip_address('224.0.0.251'), \n ip_address('10.0.1.51'),\n]\n\nlocalities = classify_addresses(ips)\n</code></pre>\n\n<p>Note how <code>ip_address</code> handles the parsing for you and raises on an invalid IP. As part of the parsing, <code>ipaddress</code> is capable of identifying if an IP is public or private (this is the proper nomenclature, you should rename your terms). Note that there are some other classifications like <code>is_multicast</code>, <code>is_reserved</code>, and <code>is_loopback</code> that you may want to decide how to handle.</p>\n\n<p>Also note that <code>ip_address</code> already supports IPv6. So you just got IPv6 support by doing absolutely nothing :)</p>\n\n<hr>\n\n<p>Finally, let's address <code>socket.inet_pton</code>. You'll note in my example above, I don't use it. Why is that? <code>inet_pton</code> doesn't make any external network connections. It is only useful to parse an IP and return the packed binary representation of it (which can be sent over the network). You could actually replace your parsing of IPs with <code>socket.inet_pton</code>. It raises <code>OSError</code> if the IP address is invalid. But, that's all it does. And if you did use it, you wouldn't get the nice <code>.is_public</code> nor would you automatically get IPv6 support (without trying it again with <code>AF_INET6</code>). You just don't need it! Python's <code>ipaddress</code> handles all (and more) of what <code>inet_pton</code> or <code>inet_aton</code> would do for you.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T00:40:36.567",
"Id": "214142",
"ParentId": "214055",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "214142",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T19:04:53.473",
"Id": "214055",
"Score": "1",
"Tags": [
"python",
"hash-map",
"socket",
"ip-address"
],
"Title": "Creating a dict with external and internal IP addresses provided a list of candidates"
} | 214055 |
<p>I am supposed to make a basic RSA encryption/decryption code, where I am only given <em>e</em>.</p>
<p>I wrote this code to randomly generate two primes and then find their totient. But the totient is supposed to not be co-prime with e which is given as 65537. So this code would technically return a good value eventually, but in reality it would take ages. Please help me speed it up and/or make suggestions on how it can be improved in general.</p>
<pre><code>def primeGen(lim):
"""Generates all primes up to a certain limit (lim)"""
fnl=[]
primes=[2]
p=0
for n in range(2,lim+1):
fnl.append(n)
for v in fnl:
p=0
for i in range(2,v):
if (v%i==0):
p=1
break
if p==0 and i==(v-1):
primes.append(v)
return primes
import random
def randomPrimeGen(lim):
"""Generates a single random prime number using primeGen(lim)"""
M=(len(primeGen(lim))-1)
randomPrime=(primeGen(lim)[random.randint(int(M/10),M)])
return randomPrime
def modtot():
e=65537
totient=1
GCD=gcd(e,totient)
while GCD==1:
p=randomPrimeGen(30000)
q=randomPrimeGen(30000)
n=p*q
totient=((p-1)*(q-1))
GCD=gcd(e,totient)
print(GCD, totient)
return n, totient
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T19:00:22.113",
"Id": "414021",
"Score": "2",
"body": "Why are you regenerating the list of primes every time you need a random one? Compute `primeGen(30000)` *once*."
}
] | [
{
"body": "<p>One problem, pointed out in comment by @chepner is that you are recomputing the primes twice. Save the primes, so you don't have to recompute. </p>\n\n<p>Also, in your inner loop, you are unnecessarily dividing by every number up to <code>v</code>. Instead, you should skip all non-primes and only test divisibility by the primes, up to your largest known prime (because all other numbers up to there can be factorized into these primes). Only after that do you need to test divisibility for each integer <code>max(primes) < i < v</code>. Skipping all non-primes up to <code>max(primes)</code> saves a lot of looping/divisions/comparisons for large <code>lim</code> (especially given that the <a href=\"https://en.wikipedia.org/wiki/Prime_gap\" rel=\"nofollow noreferrer\">distance between consecutive primes tends to increase</a> as <code>lim</code> increases). Something like this will give you a big speedup:</p>\n\n<pre><code>def primeGenFast(lim):\n fnl=[]\n primes=[2]\n\n fnl = list(range(2,lim+1))\n for v in fnl:\n p=1\n for n in primes:\n if v%n == 0:\n p = 0\n break\n\n if p==1:\n for i in range(primes[-1],v):\n if (v%i==0):\n break\n if i==(v-1):\n primes.append(v)\n\n return primes\n</code></pre>\n\n<p>This gives a speedup of nearly 10-20x on my machine, increasing as the size of <code>lim</code> increases:</p>\n\n<pre><code>In [3]: timeit(primeGenSlow(10000))\n1 loop, best of 5: 465 ms per loop\n\nIn [6]: timeit(primeGenSlow(25000))\n1 loop, best of 5: 3.98 s per loop\n\nIn [8]: timeit(primeGenSlow(100000))\n1 loop, best of 5: 38.1 s per loop\n\n----\n\nIn [2]: timeit(primeGenFast(10000))\n10 loops, best of 5: 29.6 ms per loop\n\nIn [5]: timeit(primeGenFast(25000))\n1 loop, best of 5: 307 ms per loop\n\nIn [7]: timeit(primeGenFast(100000))\n1 loop, best of 5: 1.91 s per loop \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T19:58:31.220",
"Id": "214063",
"ParentId": "214057",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T18:53:41.680",
"Id": "214057",
"Score": "3",
"Tags": [
"python",
"performance",
"primes"
],
"Title": "Generate two random primes and find their totient"
} | 214057 |
<p>Given input such as:</p>
<pre>
foos = [
[],
[{'a': 1}],
[{'a': 1}, {'a': 2}],
[{'a': 1}, {'a': 2}, {'a': None}],
[{'a': 1}, {'a': 2}, {'a': None}, {'a': None}],
[{'a': 1}, {'a': None}, {'a': 2}],
[{'a': 1}, {'a': None}, {'a': 2}, {'a': None}],
[{'a': 1}, {'a': None}, {'a': 2}, {'a': None}, {'a': None}],
]
</pre>
<p>I want a function <code>remove_empty_end_lines</code> that takes a list of dicts and will remove all dicts with null values that only appear at the end of the list, not in between.</p>
<pre>
for foo in foos:
print(foo)
print(remove_empty_end_lines(foo))
print('\n')
[]
[]
[{'a': 1}]
[{'a': 1}]
[{'a': 1}, {'a': 2}]
[{'a': 1}, {'a': 2}]
[{'a': 1}, {'a': 2}, {'a': None}]
[{'a': 1}, {'a': 2}]
[{'a': 1}, {'a': 2}, {'a': None}, {'a': None}]
[{'a': 1}, {'a': 2}]
[{'a': 1}, {'a': None}, {'a': 2}]
[{'a': 1}, {'a': None}, {'a': 2}]
[{'a': 1}, {'a': None}, {'a': 2}, {'a': None}]
[{'a': 1}, {'a': None}, {'a': 2}]
[{'a': 1}, {'a': None}, {'a': 2}, {'a': None}, {'a': None}]
[{'a': 1}, {'a': None}, {'a': 2}]
</pre>
<p>My final solution is:</p>
<pre><code>def remove_empty_end_lines(lst):
i = next(
(
i for i, dct in enumerate(reversed(lst))
if any(v is not None for v in dct.values())
),
len(lst)
)
return lst[: len(lst) - i]
</code></pre>
<p>I'm not going for code golf, rather for performance and readability.</p>
<p>In the input I've listed above, the dicts are always a length of one, butin reality the lengths can be any amount. The lengths of each dict within a list will always be the same.</p>
| [] | [
{
"body": "<p>Some suggestions:</p>\n\n<ul>\n<li>You are using <code>i</code> both inside your list comprehension and outside. This makes the code harder to follow than if the variables were differently named. For example, you could think of the outer <code>i</code> as the count of matching (that is, all <code>None</code> values) dictionaries at the end of the list.</li>\n<li>Hungarian notation abbreviations like <code>lst</code> and <code>dct</code> don't tell me anything about what the variables actually <em>are.</em> In an actual application this should be possible, but more context would be needed for that.</li>\n<li>You say \"remove all dicts with null values\", but you neither specify nor test what happens with a dictionary having some <code>None</code> values and some non-<code>None</code> values at the end of the list. As far as I can tell from your implementation you remove only entries with <em>all</em> <code>None</code> values, but it's not clear whether this is the intention.</li>\n<li>I would pull out the tuple passed to <code>next</code> as a separate variable for clarity.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T22:18:20.577",
"Id": "214071",
"ParentId": "214058",
"Score": "2"
}
},
{
"body": "<p>That statement where you calculate <code>i</code> is too complex. It contains 2 for-loops inside. Consider taking some parts out of it as separate variables or functions.</p>\n\n<p>For example, you could make a function checking if a dict has any values except <code>None</code>:</p>\n\n<pre><code>def has_values(mapping):\n return any(value is not None \n for value in mapping.values())\n</code></pre>\n\n<p>and a function that would return you the index of the first element that would satisfy some condition:</p>\n\n<pre><code>def first_valid_index(predicate, iterable, default):\n return next((index for index, value in enumerate(iterable) \n if predicate(value)), \n default)\n</code></pre>\n\n<p>These functions are pretty general and you can reuse them later in your code. \nYour original function then would look like this:</p>\n\n<pre><code>def remove_empty_end_lines(mappings):\n reversed_mappings = reversed(mappings)\n index = first_valid_index(has_values, \n reversed_mappings,\n default=len(mappings))\n return mappings[:len(mappings) - index]\n</code></pre>\n\n<hr>\n\n<p>Also, the fact that you use lists of dicts with the same keys makes me think that you probably should use more appropriate data structures. </p>\n\n<p>For example, consider this example pandas dataframe:</p>\n\n<pre><code>>>> import pandas as pd \n>>> df = pd.DataFrame(dict(a=[None, 1, 2, None, 3, 4, None, None, None],\n b=[None, 1, 2, None, None, 4, 5, None, None]))\n>>> df\n a b\n0 NaN NaN\n1 1.0 1.0\n2 2.0 2.0\n3 NaN NaN\n4 3.0 NaN\n5 4.0 4.0\n6 NaN 5.0\n7 NaN NaN\n8 NaN NaN\n</code></pre>\n\n<p>To remove the last rows that contain only <code>NaN</code>, you would simply write:</p>\n\n<pre><code>>>> index = df.last_valid_index()\n>>> df.loc[:index]\n a b\n0 NaN NaN\n1 1.0 1.0\n2 2.0 2.0\n3 NaN NaN\n4 3.0 NaN\n5 4.0 4.0\n6 NaN 5.0\n</code></pre>\n\n<p>Much simpler, and ideally it should be faster for a big data.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T10:00:07.737",
"Id": "214156",
"ParentId": "214058",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T19:35:33.423",
"Id": "214058",
"Score": "2",
"Tags": [
"python",
"python-3.x"
],
"Title": "Removing Dicts with Null values from Only the End of a List"
} | 214058 |
<p>I am reading through K&R C 2nd Edition, and I am on exercise 1-13. The exercise is to <em>write a program to print a histogram of the lengths of words in
its input.</em> I wrote a program that successfully does this; however, after looking at the program, I noticed that it was somewhat messy, and I'm sure that there is a better way to implement it. I'm looking for some tips as to how I can improve programs like this in the future. </p>
<p>Here is the code: </p>
<pre><code>#include <stdio.h>
#define IN 1
#define OUT 0
#define MAXVAL 11
int main(){
int i, j, c, state;
int wordLengths[MAXVAL];
int currentWord = 0;
int greaterThanMax = 0;
for(i = 0; i < MAXVAL; i++){
wordLengths[i] = 0;
}
while((c = getchar()) != EOF){
++currentWord;
state = IN;
if(c == '\n' || c == ' ' || c == '\t'){
state = OUT;
--currentWord;
}
if(state == OUT){
if(currentWord < MAXVAL){
++wordLengths[currentWord];
}
else{
++greaterThanMax;
}
currentWord = 0;
}
}
for(i = 1; i < MAXVAL; i++){
printf("%d letter(s): ", i);
for(j = 0; j <= wordLengths[i] - 1; j++){
putchar('=');
}
putchar('\n');
}
printf(">%d: ", MAXVAL - 1);
for(i = 0; i < greaterThanMax; i++){
putchar('=');
}
return 0;
}
</code></pre>
| [] | [
{
"body": "<ul>\n<li><p>Do not be shy on horizontal spacing. Add space after the keywords (e.g. <code>while (</code>, or <code>if (</code>). Insert space into <code>){</code>.</p>\n\n<p>If you place an opening curly bracket on the same line as <code>if</code>, be consistent with <code>else</code>:</p>\n\n<pre><code> if () {\n ....\n } else {\n ....\n }\n</code></pre></li>\n<li><p><code>currentWord</code> actually refers to the current word <em>length</em>. Consider renaming.</p></li>\n<li><p>Instead of testing <code>state == OUT</code>, consider adding a word immediately, as soon as state become <code>OUT</code>:</p>\n\n<pre><code> if (c == '\\n' || c == ' ' || c == '\\t') {\n if (currentWordLength < MAXVAL) {\n ++wordLengths[currentWordLength - 1]; {\n } else {\n ++greaterThanMax;\n }\n currentWord = 0;\n }\n</code></pre>\n\n<p>Notice that with this approach you don't need to maintain state explicitly.</p></li>\n<li><p>Every output line, except last one, starts with a single-digit number, but the last one starts with 10, and looks unaligned. Consider printing letter count with <code>\"%2d\"</code>. </p></li>\n<li><p>The greater-than-max line doesn't end with a newline. Some shells (like <code>cmd.exe</code>) automatically add a newline to the last output. Unixish shells do not. On my system an output looks like</p>\n\n<pre><code>....\n>10: ==vnp>\n</code></pre>\n\n<p>Even on Windows, try to redirect your output into a file.</p>\n\n<p>It is usually a good idea to terminate the output with a newline.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T22:22:23.790",
"Id": "214072",
"ParentId": "214059",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T19:46:33.283",
"Id": "214059",
"Score": "2",
"Tags": [
"beginner",
"c",
"ascii-art",
"data-visualization"
],
"Title": "Create a histogram of the lengths of words"
} | 214059 |
<p>I'm currently working on doing some fundamental practice around Objects after spending years coding in C# but in a very procedural way, I'm also starting to try and learn SOLID. My main concerns on my code are the validation rules inside the Auction class and throwing so many exceptions as it feels wrong, I feel like I should be implementing some sort of <code>List<ValidationResults></code> or even a <code>PlaceBidResult class</code> but then that feels like I'm not encapsulating the logic behind placing a bid in the right class?</p>
<p>Auction Class - This is basically the brain of the whole system and allows for placing and removing bids, setting reserve prices etc.</p>
<pre><code> public class Auction
{
public string ItemName { get; private set; }
public double ReservePrice { get; private set; } = 0;
public DateTime StartDate { get; private set; }
public DateTime EndDate { get; set; }
List<Bid> bids;
public IEnumerable<Bid> Bids
{
get
{
return bids.AsEnumerable();
}
}
public int CurrentHighestBid
{
get
{
return bids.Max(c => (int?)c.Value) ?? 0;
}
}
private const int REPUTATION_REQUIRED_TO_BID = 10;
private const double MAXIMUM_ALLOWED_DURATION = 10;
public Auction(string itemName, DateTime startDate, DateTime endDate)
{
if (string.IsNullOrEmpty(itemName))
throw new NullReferenceException("Must provide a valid item name");
this.ItemName = itemName;
if (startDate < DateTime.Now.AddMinutes(-10)) //Gives a ten minute grace to prevent this failing if DateTime.Now is passed in.
throw new ArgumentOutOfRangeException(nameof(startDate), startDate, "Auctions can't start in the past");
this.StartDate = startDate;
if (endDate < DateTime.Now || endDate > StartDate.AddDays(MAXIMUM_ALLOWED_DURATION))
{
throw new ArgumentOutOfRangeException(nameof(endDate), endDate, $"Auctions can't end in the past and the duration of the auction must be less than {MAXIMUM_ALLOWED_DURATION} days");
}
this.EndDate = endDate;
bids = new List<Bid>();
}
public void PlaceBid(double value, User user)
{
//Check that the bid is valid. I.e are their bids that are higher than us already
ValidateBid(value, user);
bids.Add(new Bid(value, user));
Console.WriteLine("Bid Added " + value);
}
private void ValidateBid(double value, User user)
{
if (CurrentHighestBid > value)
throw new ArgumentException("There are already higher bids than this", nameof(value));
if (value < 0)
throw new ArgumentException("You cannot bid negative amounts", nameof(value));
if (value < ReservePrice)
throw new ArithmeticException("Bid value cannot be lower than the reserve price of an item");
if (StartDate > DateTime.Now)
throw new ArgumentException("Auction hasn't started yet!");
if (user.Reputation < REPUTATION_REQUIRED_TO_BID)
throw new ArgumentException("User does not have enough reputation to bid on these", nameof(user.Reputation)); //Is throwing an exception here the correct way to go?
}
public void RemoveBid(double value, User user)
{
var bid = bids.Where(c => c.Value == value).FirstOrDefault();
if (bid != null)
bids.Remove(bid);
}
public void SetReservePrice(double value)
{
if (value < 0)
throw new ArithmeticException("Reserve price cannot be below zero");
this.ReservePrice = value;
}
}
}
</code></pre>
<p>Bid Class - right now this is basically a data bag or "anemic domain model" could this be improved with some kind of logic of its own?</p>
<pre><code> public class Bid
{
public double Value { get; private set; }
public User User { get; private set; }
public Bid(double value, User user)
{
this.Value = value;
this.User = user;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T11:46:19.733",
"Id": "414055",
"Score": "1",
"body": "I have rolled back your last edit. Please see [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers): _**Do not add an improved version of the code** after receiving an answer. Including revised versions of the code makes the question confusing, especially if someone later reviews the newer code._"
}
] | [
{
"body": "<p>You problem is very open ended and you can implement in many ways so unfortunately my answer will be rather open ended too. To start, a few general remarks:</p>\n\n<ul>\n<li>I normally use <code>string.IsNullOrWhitespace(blah)</code> instead of <code>string.IsNullOrEmpty(blah)</code></li>\n<li>Don't throw <code>NullReferenceException</code>. Throw <code>ArgumentNullException(nameof(argumentName))</code>. That's what it's there for.</li>\n<li>C# typically uses PascalCase for constant names: <code>ReputationRequiredToBid</code>.</li>\n<li><code>ArithmeticException</code> - you're not supposed to use this class as per <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.arithmeticexception?view=netframework-4.7.2#remarks\" rel=\"noreferrer\">documentation</a>.</li>\n<li>While I don't agree with your (over)use of exceptions, you should use <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.invalidoperationexception?view=netframework-4.7.2\" rel=\"noreferrer\"><code>InvalidOperationException</code></a> instead of <code>ArgumentException</code>s when the current state breaks the code, and not the otherwise valid and well formed argument(s). For example a negative <code>value</code> should throw an <code>ArgumentOutOfRangeException</code> or simply an <code>ArgumentException</code>, however <code>CurrentHighestBid > value</code> should throw an <code>InvalidOperationException</code> or a custom exception (I don't like custom exceptions though - keep reading for alternatives). </li>\n</ul>\n\n<p>Anyway you're definitely overusing exceptions in my opinion. Consider creating a separate validation class and moving the validation code there - single responsibility principle. Consider returning a <code>ValidationResult</code> object with details about what went wrong, potentially in a <code>IEnumerable<string> Errors</code> property. I would probably still throw <code>ArgumentException</code>s for nonsensical arguments, like negative bid.</p>\n\n<p>If I need to throw an exception, in 99% of the cases it's a variation of <code>ArgumentException</code>, and occasionally <code>InvalidOperationException</code>. The end result is that the code I write uses them quite rarely, and in predictable places, such as the entry point of the method etc. If I review a piece of code that throws any other exceptions, I'm expecting to see or hear a very strong reason for that. And an even stronger reason if the exception is a custom exception. In short, especially if you don't have experience, stay away from doing anything crazy with exceptions. They're not bad per se, but there are more elegant and readable solutions out there.</p>\n\n<p>Bid class - parameter validation maybe?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T20:41:25.897",
"Id": "414029",
"Score": "0",
"body": "Thanks for the comments. Does creating a separate validator class break any rules around encapsulation as using one would basically be allowing another class to dictate the auction classes state or am I missing something there? In terms of the exception type and const casing I definitely take that on board. Bid class doesn't do validation of its parameters as the auction class validates them before creating a new bis, again I'm worried that this is allowing the auction class to dictate the bid classes state so maybe that should be moved?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T21:00:32.217",
"Id": "414032",
"Score": "0",
"body": "No, I'm not concerned about that. The validation class doesn't really dictate anything. All it does is \"validation\", and then it's up to the `Auction` class to do whatever it wants with the validation result. I do realise a lot of the validation logic is tightly coupled to the current state of the class, so introducing a new `BidValidation` class will require rearchitecting some of the `Auction` class too - maybe think about that as a next step. But you can definitely promote the `if (value < 0)` check to the `PlaceBid` class. Maybe add a null check for `User` too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T11:10:51.330",
"Id": "414053",
"Score": "0",
"body": "Thanks again, I've refactored the `PlaceBid` method to use a validator and added an update to my original answer. It feels a lot cleaner doing it this way and I can see where I can extend my base class to use it in different scenarios too so that's cool too."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T20:38:11.970",
"Id": "214066",
"ParentId": "214060",
"Score": "8"
}
},
{
"body": "<p>You don't check for <code>StartDate > EndDate</code>:</p>\n\n<p>This is not caught: </p>\n\n<pre><code> Auction auction = new Auction(\"AAA\", new DateTime(2019, 3, 2), new DateTime(2019, 3, 1));\n</code></pre>\n\n<hr>\n\n<blockquote>\n<pre><code>public int CurrentHighestBid\n{\n get\n {\n return bids.Max(c => (int?)c.Value) ?? 0;\n }\n}\n</code></pre>\n</blockquote>\n\n<p>Instead of <code>return bids.Max(c => (int?)c.Value) ?? 0;</code>, you can write <code>return bids.Max(c => (int?)c.Value).GetValueOrDefault();</code>. But why do you cast to <code>int</code>?</p>\n\n<hr>\n\n<p>In <code>ValidateBid(double value, User user)</code> you check the start date but you don't check the end date.</p>\n\n<hr>\n\n<p>In</p>\n\n<blockquote>\n<pre><code>public void RemoveBid(double value, User user)\n{\n var bid = bids.Where(c => c.Value == value).FirstOrDefault(); \n if (bid != null)\n bids.Remove(bid);\n}\n</code></pre>\n</blockquote>\n\n<p>you're not using the <code>user</code> argument to anything. I would expect the condition to be something like (you can skip the <code>Where</code>-call):</p>\n\n<pre><code>var bid = bids.FirstOrDefault(b => b.Value == value && b.User == user);\n</code></pre>\n\n<p>Futher: <code>Remove(...)</code> returns a boolean value to indicate if something was removed or not. You could return that value from <code>RemoveBid()</code> to let the client know...:</p>\n\n<pre><code>public bool RemoveBid(double value, User user)\n{\n var bid = bids.Where(c => c.Value == value).FirstOrDefault();\n if (bid != null)\n return bids.Remove(bid);\n return false;\n}\n</code></pre>\n\n<hr>\n\n<p>According to the use of exceptions and validation of input, I think you have to distinguish between input/states that hinders a normal or valid execution of the program, for instance a null reference or a <code>StartDate > EndDate</code>, and violations of business rules that don't cause the program to stop working, but make invalid or unwanted results - like <code>value < ReservePrice</code>. The first type should be thrown as exceptions while the latter should be handled with useful return values and/or messages. Ideally seen.</p>\n\n<p>But it can be difficult to determine the difference (for instance: is <code>StartDate > EndDate</code> a business rule or an exception?), so it is often seen, that exceptions is used in both cases. What ever you choose do it consistently and document which exceptions are thrown where and why. Never fail to throw an exception, just because you feel you have too many :-). If you think you have to throw too many exception, you should maybe consider if the overall design is right.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T11:06:45.667",
"Id": "414051",
"Score": "1",
"body": "Thanks for your comments, I think my reasoning behind casting to an int? max was to do with performance in an Entity Framework situation (not relevant here but that's what I'm used to. Missing the End date thing was basically a Doh! moment. I've refactored my place bid method to give an idea of how I could maybe be doing this without exceptions as an edit to my original answer. My original plan was defintiely to validate the user and use the user and amount to remove a bid but looks like I forgot to do it!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T05:26:21.997",
"Id": "214094",
"ParentId": "214060",
"Score": "4"
}
},
{
"body": "<p>Couple of other thoughts on this:</p>\n\n<p>ValidateBid is probably making some checks which it shouldn't be making. The top 3 conditions are all related to the validation of a bid, but the latter two are not. I would be inclined to move the \"auction not started yet\" check and \"User reputation\" check elsewhere. It seems like they should come before the bid validation just thinking through it procedurally. </p>\n\n<ul>\n<li>If the auction isn't ongoing then nobody can bid.</li>\n<li>If the auction is ongoing but the user hasn't got enough reputation they can't bid.</li>\n<li>If auction is ongoing, the user is good, but their bid is too low they can't bid.</li>\n</ul>\n\n<p>Seems like the natural flow of checks.</p>\n\n<p>The remaining three conditions are all variations on \"bid is below minimum\" so you could just cut out the very specific error messages and include one which states \"bid is below minimum value: $x\"</p>\n\n<p>Your validate bid method then looks something like</p>\n\n<pre><code>private void ValidateBid(double bid)\n{\n var minimumBid = new int[] {(CurrentHighestBid + 0.01), ReservePrice}.Max();\n if (bid < minimumBid)\n throw new ArgumentException($\"Bid is below minimum value ${minimumBid}\");\n}\n</code></pre>\n\n<p>Also note that in the question, you're allowing a user to submit a bid which is the same value as the current highest bid. You're also allowing a user to bid 0 as long as there's no reserve and no bids higher than 0. Might be desired behaviour but I guess probably not.</p>\n\n<p>Last thing - I'd recommend some unit tests for this class. There are a lot of different reasons you may not accept a user's bid and it's gonna be easy for some to slip through the net as you refactor.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-27T00:02:47.990",
"Id": "214364",
"ParentId": "214060",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T19:47:13.633",
"Id": "214060",
"Score": "5",
"Tags": [
"c#"
],
"Title": "Basic Auction Software"
} | 214060 |
<pre><code>import keyboard
import os
import sys
from colorama import Fore, Back, Style, init
init()
clear = lambda: os.system('cls')
cwd = os.getcwd()
header = """
____ _ ____ _ _ _ ___ _
/ ___|___ (_)_ __ / ___|__ _| |_ _| | __ _| |_ ___ _ __ / _ \\ / |
| | / _ \\| | '_ \\ | | / _` | | | | | |/ _` | __/ _ \\| '__| | | | || |
| |__| (_) | | | | | | |__| (_| | | |_| | | (_| | || (_) | | | |_| || |
\\____\\___/|_|_| |_| \\____\\__,_|_|\\__,_|_|\\__,_|\\__\\___/|_| \\___(_)_|
Omar "Michael Abdo" 2019
'Q' to Quit
"""
def end():
print(Style.BRIGHT + Fore.RED + "\n\n\t\tCLOSING.")
os._exit(0)
def commit(cs, vs, opened="CoinCount"):
inp = ""
total = "\n\nTOTAL ${0:.2f}".format(sum(map(lambda x, y: x*y, cs, vs)))
while inp.upper() != "N" and inp.upper() != "Y":
inp = input("{} Save? [Y/N]: ".format(total))
if inp.upper() == "Y":
temp = input("Enter filename or press enter to use default ({}).txt: ".format(opened))
if temp: opened = temp
if not opened.endswith(".txt"): opened += ".txt"
conf = ""
while conf.upper() not in ['Y', 'N']:
conf = input("Saving file as {}\\{} - Confirm? [Y/N]: ".format(cwd, opened))
if conf.upper() == "Y":
with open(opened, "w+") as f:
f.write(",".join(map(lambda x: str(x), cs)))
f.write(total)
clear()
print("Total saved to {}\\{}!\n\n\n\n".format(cwd, opened))
end()
def changeVal(dir, cursor_pos, cs, vs):
ch = (len(cs) - 1) - cursor_pos[0]
if dir == "D":
if cs[ch] >= 1:
cs[ch] -= 1
moveCursor('n', cursor_pos, cs, vs)
elif dir == "U":
cs[ch] += 1
moveCursor('n', cursor_pos, cs, vs)
def moveCursor(dir, cursor_pos, cs, vs):
total = "TOTAL ${0:.2f}".format(sum(map(lambda x, y: x*y, cs, vs)))
neutral = """
0.05 0.10 0.25 1.00 2.00 5.00 10.00 20.00 50.00 100.00
{} {} {} {} {} {} {} {} {} {}
""".format(cs[9], cs[8], cs[7], cs[6], cs[5], cs[4], cs[3], cs[2], cs[1], cs[0])
if dir != 'n':
if cursor_pos[0] != 0 and dir == 'L':
cursor_pos[0] -= 1
elif cursor_pos[0] != 9 and dir == 'R':
cursor_pos[0] += 1
elif cursor_pos[0] == 0 and dir == 'L':
cursor_pos[0] = 9
elif cursor_pos[0] == 9 and dir == 'R':
cursor_pos[0] = 0
clear()
print(total)
if cursor_pos[0] == 0:
print(neutral[:12] + Style.BRIGHT + Fore.GREEN + neutral[12:16] + Style.RESET_ALL + neutral[16:]) #Nickel
elif cursor_pos[0] == 1:
print(neutral[:20] + Style.BRIGHT + Fore.GREEN + neutral[20:24] + Style.RESET_ALL + neutral[24:]) #Dime
elif cursor_pos[0] == 2:
print(neutral[:28] + Style.BRIGHT + Fore.GREEN + neutral[28:32] + Style.RESET_ALL + neutral[32:]) #Quarter
elif cursor_pos[0] == 3:
print(neutral[:36] + Style.BRIGHT + Fore.GREEN + neutral[36:40] + Style.RESET_ALL + neutral[40:]) #loon
elif cursor_pos[0] == 4:
print(neutral[:44] + Style.BRIGHT + Fore.GREEN + neutral[44:48] + Style.RESET_ALL + neutral[48:]) #toon
elif cursor_pos[0] == 5:
print(neutral[:52] + Style.BRIGHT + Fore.GREEN + neutral[52:56] + Style.RESET_ALL + neutral[56:]) #fiver
elif cursor_pos[0] == 6:
print(neutral[:60] + Style.BRIGHT + Fore.GREEN + neutral[60:65] + Style.RESET_ALL + neutral[65:]) #tens
elif cursor_pos[0] == 7:
print(neutral[:68] + Style.BRIGHT + Fore.GREEN + neutral[68:73] + Style.RESET_ALL + neutral[73:]) #twenties
elif cursor_pos[0] == 8:
print(neutral[:76] + Style.BRIGHT + Fore.GREEN + neutral[76:81] + Style.RESET_ALL + neutral[81:]) #fifties
elif cursor_pos[0] == 9:
print(neutral[:84] + Style.BRIGHT + Fore.GREEN + neutral[84:91] + Style.RESET_ALL + neutral[91:]) #hundreds
print("CONTROLS:\n-> / <-\t:\tMOVE\nZ\t:\tINCREMENT\nX\t:\tDECREMENT\nENTER\t:\tSAVE\nQ\t:\tQUIT")
def main():
print(Fore.GREEN + Style.BRIGHT + header)
keyboard.add_hotkey('q', end)
mode = ""
cursor_pos = [0]
cs = [0,0,0,0,0,0,0,0,0,0] #100, 50, 20, 10, 5, 2, 1, 0.25, 0.10, 0.05
vs = [100, 50, 20, 10, 5, 2, 1, 0.25, 0.10, 0.05]
while mode != "C" and mode != "S":
mode = input("Enter mode for entry: C for Counting, S for Static: ")
if mode.upper() == "S":
hund = ""
while not hund.isdigit():
hund = input("Enter # of $100:\t")
fift = ""
while not fift.isdigit():
fift = input("Enter # of $50:\t\t")
twen = ""
while not twen.isdigit():
twen = input("Enter # of $20:\t\t")
tens = ""
while not tens.isdigit():
tens = input("Enter # of $10:\t\t")
five = ""
while not five.isdigit():
five = input("Enter # of $5:\t\t")
toon = ""
while not toon.isdigit():
toon = input("Enter # of $2:\t\t")
loon = ""
while not loon.isdigit():
loon = input("Enter # of $1:\t\t")
quar = ""
while not quar.isdigit():
quar = input("Enter # of $0.25:\t")
dime = ""
while not dime.isdigit():
dime = input("Enter # of $.10:\t")
nick = ""
while not nick.isdigit():
nick = input("Enter # of $0.05:\t")
save = ""
while save.upper() != "Y" and save.upper() != "N":
save = input("Total is ${}. Save amount?\n\n\t\t[Y/N]:\t".format(int(nick)*0.05 + int(dime)*0.10 + int(quar)*0.25 + int(loon)*1 + int(toon)*2 + int(five)*5 + int(tens)*10 + int(twen)*20 + int(fift)*50 + int(hund)*100))
if save.upper() == "Y":
conf = ""
while conf.upper() not in ['Y', 'N']:
if os.path.exists("CoinCount.txt"):
inp = input("File exists. Enter a new name or press enter to overwrite default file CoinCount.txt: ")
else:
inp = input("Enter filename or press enter to use default (CoinCount.txt): ")
if not inp: inp = "CoinCount"
if not inp.endswith(".txt"): inp += ".txt"
conf = input("Saving file as {}\\{}- Confirm? [Y/N]: ".format(cwd, inp))
if conf.upper() == "N":
conf = ""
continue
if conf.upper() == "Y":
with open(inp, "w+") as f:
f.write(",".join(list(map(lambda x: str(x),[hund, fift, twen, tens, five, toon, loon, quar, dime, nick]))))
f.write("\n{}".format(int(nick)*0.05 + int(dime)*0.10 + int(quar)*0.25 + int(loon)*1 + int(toon)*2 + int(five)*5 + int(tens)*10 + int(twen)*20 + int(fift)*50 + int(hund)*100))
clear()
print("Total saved to {}\\{}!\n\n\n\n".format(cwd, inp))
end()
elif mode.upper() == "C":
mode = ""
inp = ""
while mode.upper() != "N" and mode.upper() != "O":
mode = input("Count from New or Open previous total? [N/O]: ")
if mode.upper() == "O":
if os.path.exists("CoinCount.txt"):
inp = input("File(s) exist. Enter a new name or press enter to use the default CoinCount.txt: ")
else:
inp = input("Enter filename: ")
if not inp: inp = "CoinCount"
if not inp.endswith(".txt"): inp += ".txt"
conf = ""
while conf.upper() not in ['Y', 'N']:
conf = input("Open from {}\\{} - Confirm? [Y/N]: ".format(cwd, inp))
if conf.upper() == "Y":
try:
with open(inp) as f:
cs = list(map(lambda x: int(x), f.readline()[:-1].split(",")))
print("Successfully loaded data from {}\\{}".format(cwd, inp))
except:
print("BAD!")
moveCursor('n', cursor_pos, cs, vs)
keyboard.add_hotkey('left', moveCursor, args=('L', cursor_pos, cs, vs))
keyboard.add_hotkey('right', moveCursor, args=('R', cursor_pos, cs, vs))
keyboard.add_hotkey('z', changeVal, args=('U', cursor_pos, cs, vs))
keyboard.add_hotkey('x', changeVal, args=('D', cursor_pos, cs, vs))
keyboard.add_hotkey('enter', commit, args=(cs, vs, inp))
while True:
pass
main()
</code></pre>
<p>Context:
This is a coin calculating Python script that uses PyPi Keyboard to allow a user to use the "Z" and "X" keys to increment a selected coin (Choosen by moving the highlighted coin with arrows) while in "C[ount]" mode. It works! The problem is that when I increment some coins and go to save the result by running "commit" thereby breaking the <code>While True</code> loop...
<a href="https://i.stack.imgur.com/YWLac.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YWLac.png" alt="Shortcut Keys Returned"></a></p>
<p>It prints the keys I was pressing to Increment. Could anyone tell me why? I've narrowed it down to this section in <code>commit</code>:</p>
<pre><code>def commit(cs, vs, opened="CoinCount"):
inp = ""
total = "\n\nTOTAL ${0:.2f}".format(sum(map(lambda x, y: x*y, cs, vs)))
while inp.upper() != "N" and inp.upper() != "Y":
inp = input("{} Save? [Y/N]: ".format(total))
</code></pre>
<p>This because when I add a 'debugging string' like "WWEEEEOOO WWEEEOOO" to that loop I get:
<a href="https://i.stack.imgur.com/YDWIY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YDWIY.png" alt="Alarm Sounding"></a>
Which I take to mean that it has entered my <code>While</code>loop three(?) times in total instead of once. Please let me know if you have insight.</p>
| [] | [
{
"body": "<p>Welcome to CodeReview. I'll point out that posting code and asking questions about a bug you have makes your post <em>Off Topic,</em> since this site is for reviews of working code.</p>\n\n<p>With that out of the way, I'll review your code:</p>\n\n<h1>The bug</h1>\n\n<p>The <code>keyboard</code> functions take a parameter called <code>suppress</code>. I believe that if you set <code>suppress=True</code> on your various hotkey definitions, it will cause the <code>keyboard</code> module to eliminate the key events entirely after calling your callback function. <strong>However,</strong> I was unable to get this working on my machine, so I don't know what's going on. </p>\n\n<p>So, perhaps you would consider abandoning the use of the <code>keyboard</code> module for this purpose. There is another option for doing responsive keyboard-driven terminal work: <a href=\"https://docs.python.org/3.5/library/curses.html\" rel=\"nofollow noreferrer\"><code>curses</code></a>. Or you might consider <a href=\"https://www.pygame.org\" rel=\"nofollow noreferrer\"><code>pygame</code></a> if you just want to catch the keyboard events and use <code>stdout</code> for your output.</p>\n\n<h1>The review:</h1>\n\n<p>I found your code quite dense and not well organized. However, it was fairly straightforward, with the exception of the hotkey mechanism supplied by the <code>keyboard</code> module, and comprehensible.</p>\n\n<h3>1. Follow the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP-8</a> guidelines.</h3>\n\n<p>PEP-8 is the Python style guide. It tells you how to organize <code>import</code> statements and name variables and functions. It gives useful examples of code and coding style. Reformatting and changing some names in this manner will improve your code's readability by 10-20%.</p>\n\n<pre><code>import os\nimport sys\n\nimport keyboard\nfrom colorama import Fore, Back, Style, init\n\nclear = lambda: os.system('cls')\ncwd = os.getcwd(\nheader = \"\"\" ... etc ... \"\"\"\n</code></pre>\n\n<h3>2. Moar functions!</h3>\n\n<p>Your code is split into functions. But it's not split into <em>enough</em> functions. So, write some more! For example:</p>\n\n<pre><code>while inp.upper() != \"N\" and inp.upper() != \"Y\":\n inp = input(\"{} Save? [Y/N]: \".format(total))\nif inp.upper() == \"Y\":\n</code></pre>\n\n<p>This code interrupts whatever you were doing to loop around chasing after a valid answer from the user. Then, it forces you to do one last string-case-conversion to decode what was supplied and branch on it.</p>\n\n<p>How about just writing a function, <code>get_yn(prompt, default=None)</code> that does that looping and case-insensitive comparison for you, and returns a boolean value? And you can even make it accept a default if you want:</p>\n\n<pre><code>if get_yn(\"{} Save?\".format(total)):\n ...\n</code></pre>\n\n<p>Here's another example:</p>\n\n<pre><code>if dir != 'n':\n if cursor_pos[0] != 0 and dir == 'L':\n cursor_pos[0] -= 1\n elif cursor_pos[0] != 9 and dir == 'R':\n cursor_pos[0] += 1\n elif cursor_pos[0] == 0 and dir == 'L':\n cursor_pos[0] = 9\n elif cursor_pos[0] == 9 and dir == 'R':\n cursor_pos[0] = 0\n</code></pre>\n\n<p>This just isn't very good code. First, you're checking if <code>dir != 'n'</code> but inside the block, every conditions <em>checks the value of <code>dir</code> again!</em> So that outer check isn't needed. Second, you have two different cases for handling the <code>L</code> and <code>R</code> directions, and the two cases are separate. Finally, you have just enough complexity that it deserves some functions:</p>\n\n<pre><code>if dir == 'L':\n cursor_pos = move_l(cursor_pos)\nelif dir == 'R':\n cursor_pos = move_r(cursor_pos)\n</code></pre>\n\n<h3>3. Don't use built-in functions or types as variable names:</h3>\n\n<p>Don't do this:</p>\n\n<pre><code>def changeVal(dir, cursor_pos, cs, vs):\n ch = (len(cs) - 1) - cursor_pos[0]\n if dir == \"D\":\n</code></pre>\n\n<p>Add or subtract a letter to avoid using <code>dir</code> as a parameter name. You could use <code>direction</code> or <code>dirn</code> or <code>updown</code>. </p>\n\n<h3>4. Use names to provide appropriate information</h3>\n\n<p>In that same example, </p>\n\n<pre><code>def changeVal(dir, cursor_pos, cs, vs):\n ch = (len(cs) - 1) - cursor_pos[0]\n</code></pre>\n\n<p>What are <code>cs, vs,</code> and <code>ch</code>? For that matter, what is <code>cursor_pos</code> since I notice that its value ranges from 0 to 9. Clearly, it's not actually a cursor position...</p>\n\n<h3>5. Use <a href=\"https://docs.python.org/3.7/library/functions.html?highlight=slice#slice\" rel=\"nofollow noreferrer\"><code>slice</code></a> objects to make your code more data-driven</h3>\n\n<p>You write:</p>\n\n<pre><code>if cursor_pos[0] == 0:\n print(neutral[:12] + Style.BRIGHT + Fore.GREEN + neutral[12:16] + Style.RESET_ALL + neutral[16:]) #Nickel\nelif cursor_pos[0] == 1:\n print(neutral[:20] + Style.BRIGHT + Fore.GREEN + neutral[20:24] + Style.RESET_ALL + neutral[24:]) #Dime\n# ... many more lines ...\n</code></pre>\n\n<p>But what you really want to do is this:</p>\n\n<pre><code>column = cursor_pos[0]\nprint(\"{pre_fields}{hilight}{active_field}{normal}{post_fields}\".format(\n hilight=Style.BRIGHT + Fore.GREEN,\n normal=Style.RESET_ALL,\n pre_fields=neutral[pre_fields[column]],\n active_field=neutral[active_field[column]],\n post_fields=neutral[post_fields[column]]))\n</code></pre>\n\n<p>You can define slice objects like this, which doesn't actually work because the columns are varying width.</p>\n\n<pre><code>pre_fields = [slice(None, 12 + 8 * i) for i in range(10)]\nactive_field = [slice(12 + 8 * i, 16 + 8 * i) for i in range(10)]\npost_fields = [slice(16 + 8 * i, None) for i in range(10)]\n</code></pre>\n\n<p>But if you had an array of column headers, you could use that in the slice expressions.</p>\n\n<h3>6. Support a more dynamic screen size.</h3>\n\n<p>My console is 80 columns wide. See?</p>\n\n<pre><code>austin [ /d/Devel/so ]$ echo $COLUMNS x $LINES\n80 x 40\n</code></pre>\n\n<p>I'm using <code>console</code> and a version of <code>bash.exe</code> for Windows. And it naturally provides the environment variables that indicate screen size. If you're using <code>curses</code>, it figures things out somehow. If you use the python Windows bindings, I think you can determine the size of a <code>cmd</code> window.</p>\n\n<p>So, do that. Instead of hard-coding your app to support 90 columns, or whatever setting you have (it isn't 80 columns, since the $100 column wraps on my console), make yourself an array of column headers, and column positions. Compute the positions when you start up, based on the available screen real estate. </p>\n\n<h3>7. Use collections instead of individual variables</h3>\n\n<p>This code:</p>\n\n<pre><code>save = input(\"Total is ${}. Save amount?\\n\\n\\t\\t[Y/N]:\\t\".format(\n int(nick)*0.05 + int(dime)*0.10 + int(quar)*0.25 + int(loon)*1 \n + int(toon)*2 + int(five)*5 + int(tens)*10 + int(twen)*20 \n + int(fift)*50 + int(hund)*100))\n</code></pre>\n\n<p>is a great opportunity to write a function. But it's also using variables when you could be using a list. You already have lists called <code>vs</code> and <code>cs</code> (which I assume stand for <code>values</code> and <code>counts</code>. So why not use them?</p>\n\n<pre><code>def cash_value(counts, values):\n return sum(count * value for count, value in zip(counts, values))\n</code></pre>\n\n<ol start=\"8\">\n<li>Use <code>pathlib</code></li>\n</ol>\n\n<p>Instead of manually managing file paths, and printing <code>\"{}\\\\{}\".format(cwd, inp)</code>, use the standard library module <a href=\"https://docs.python.org/3.5/library/pathlib.html\" rel=\"nofollow noreferrer\"><code>pathlib</code></a> to do it. It supports Windows and *nix slashes, knows about absolute vs. relative paths, and can be stringified in a nice way.</p>\n\n<pre><code>from pathlib import Path\n\ncwd = Path('.')\nsave_file = cwd / filename\n\nprint(\"Saving data to '{}'\".format(save_file.resolve())\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T01:19:32.303",
"Id": "414043",
"Score": "2",
"body": "Please wait for them to fix their code before reviewing it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T23:26:18.503",
"Id": "214079",
"ParentId": "214061",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "214079",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T19:49:12.557",
"Id": "214061",
"Score": "-2",
"Tags": [
"python"
],
"Title": "PyPi Keyboard - Seeing \"Shortcut\" characters printed on break from their loop?"
} | 214061 |
<p>I have two objects, one <code>input = Array<Type></code> and one <code>stored = Array<{..., Type}></code></p>
<p>What's the best (cleanest) way to put the elements in the first array into the sub-elements of the second? We can assume they're of the same size.</p>
<p>My current code below works, but looks bad due to the double iterator usage.</p>
<pre><code>var count = 0;
stored.forEach((obj)=> {
obj.value = input[count];
count++;
});
</code></pre>
<p>Is there some sort of prototyping that I can use to shorten the code up?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T20:49:17.977",
"Id": "414030",
"Score": "1",
"body": "don't know if this qualifies as an answer but you don't need the `count` variable to increment the index, `Array.forEach` accepts a second ( optional ) parameter which is the current index that you can use : `stored.forEach((obj, ndx) => { obj.value = input[ndx]; });` https://jsfiddle.net/qm6yep5r/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T20:53:34.650",
"Id": "414031",
"Score": "0",
"body": "@Taki That's exactly it. Thanks a lot! If you want to put it as an answer, I'll mark it."
}
] | [
{
"body": "<p>You don't need the count variable to increment the index, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach\" rel=\"nofollow noreferrer\">Array.forEach</a> accepts a second ( optional ) parameter which is the current index that you can use : </p>\n\n<pre><code>stored.forEach((obj, index) => { \n obj.value = input[index]; \n});\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>stored = stored.map((obj, index) => ({...obj, value: input[index]}))\n</code></pre>\n\n<p>example : </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>let stored = [{ name : 'a', value: 2 }, {name : 'b', value: 4 }, { name : 'c', value: 6 }];\nlet input = [10, 11, 12];\n\n\nstored.forEach((obj, index) => { obj.value = input[index]; });\n\n// OR\n// stored = stored.map((obj, index) => ({...obj, value: input[index]}))\n\nconsole.log(stored)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T22:06:41.600",
"Id": "214070",
"ParentId": "214064",
"Score": "1"
}
},
{
"body": "<p>As the existing answer pointed out there is a index argument passed to the array iteration callbacks <code>callback(item, idx, array)</code></p>\n\n<h2>Iterators</h2>\n\n<p>However you could also use an iterator </p>\n\n<p><code>[Array.values()][1]</code> returns an array iterator. You use <code>iterator.next()</code> to step over the items, and <code>iterator.next().value</code> to get an item.</p>\n\n<p>That way you do not need an index and can use the more performant <code>for of</code> loop that does not have a ready idx.</p>\n\n<pre><code>const iterator = input.values();\nfor (const obj of stored) { obj.value = iterator.next().value }\n</code></pre>\n\n<p>However is works equally well in an array iteration function</p>\n\n<pre><code>const iterator = input.values();\nstored.forEach(obj => obj.value = iterator.next().value)\n</code></pre>\n\n<h2>Via a generator</h2>\n\n<p>You can also create a custom iterator using a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*\" rel=\"nofollow noreferrer\">generator function</a>. For example say you wanted to reverse the input order.</p>\n\n<pre><code>function *reversed(array) { // NOTE the * signifies this is a generator \n var i = array.length;\n while (i--) { yield array[i] }\n}\n\nvar iterator = reversed(input); // create reverse iterator of input\nfor (const obj of stored) { obj.value = iterator.next().value }\n\n// or\n\niterator = reversed(input); // restart reverse iterator of input\nstored.forEach(obj => obj.value = iterator.next().value);\n</code></pre>\n\n<p>Note that the iteration assigning to <code>store</code> remained unchanged from above examples.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T03:43:05.337",
"Id": "214090",
"ParentId": "214064",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "214070",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T20:01:42.197",
"Id": "214064",
"Score": "2",
"Tags": [
"javascript",
"array",
"iteration"
],
"Title": "Iterating through two objects with different structures in parallel"
} | 214064 |
<p>I just made this simple XOR encryptor and decryptor.
It needs a file with the "private" key string inside.</p>
<p>usage:<br>
encryptor "file to encrypt/decrypt" "file with the private key" "output file"</p>
<p>To decrypt, just do the same but for the inputfile, use the already encrypted file and the same file with the key.</p>
<pre><code> /*
* Encryptor
* File encryptor/decryptor.
* Works on any kind of file.
* Uses XOR encryption supplying a private key on a separate file
* that very same key file is used for both encrypt and decrypt
* example:
* create a file named key.txt and inside of it, write these characters: mZq4t7w!
* save the file and use it as a key to encrypt and decrypt any file
*
* For encryption:
* Supply the "raw" file to be encrypted, use the key file and name the output file
*
* For decryption:
* Supply the output file (encrypted), use the key file and the output file will be "raw" again.
*/
#include <cstdio>
// TODO:
// Add a command line option to display outputs
static bool consoleOutput = false;
// function that will encrypt/decrypt the file
// gets 3 args., input file, key file and output file
int Encrypt(const char* file_in, const char* keyFile_in, const char* file_out);
int main(int argc, char** argv)
{
// if there's no arguments or the user typed more than 3 arguments, tell user to use help though -h option, exit.
if( (argc == 1) || (argc > 3))
{
printf("\nExecute with %s -h for more information\n", argv[0]);
return 0;
}
// if user uses help, indicate the use of the program, exit.
else if(argc == 2)
{
if((argv[1][0] == '-') && (argv[1][1] == 'h'))
{
printf("\nUso: %s \"in file\" \"file with key\" \"out file\"\n", argv[0]);
return 0;
}
}
// user typed 3 arguments, everything ok, do the magic (encryption/decryption)
Encrypt(argv[1], argv[2], argv[3]);
return 0;
}
int Encrypt(const char* file_in, const char* keyFile_in, const char* file_out)
{
//use 3 file pointers, one for input, one for key and other for output
FILE* mainFile = nullptr;
FILE* keyFile = nullptr;
FILE* outFile = nullptr;
char* inBuffer = nullptr; // buffer to store the whole file contents in memory
char key[100]; // buffer to hold the key characters found in the key file **needs some future work**
int mainFileSize = 0; // variable to hold the size of the input file size
mainFile = fopen(file_in, "rb");
// if can't open for read, close
if(mainFile == nullptr)
{
printf("Couldn't open file %s!", file_in);
return -1;
}
// go to end of file, get the position in bytes, and store it
// the position in bytes will be the file size
fseek(mainFile, 0, SEEK_END);
mainFileSize = ftell(mainFile);
rewind(mainFile); // go to beggining of file
// if the file is 1 byte in size or is empty, exit
if(mainFileSize <= 1)
{
printf("File is empty or the file is really small (not worthy)");
return -2;
}
inBuffer = new char[mainFileSize]; // allocate memory for the file content
if(inBuffer == nullptr)
{
printf("Couldn't allocate %d bytes of memory", mainFileSize);
return -3;
}
// read the whole file on the buffer
fread(inBuffer,sizeof(char), mainFileSize, mainFile);
if(consoleOutput) //TODO: if this option is enabled, display the file contents
{
for(int i = 0; i < mainFileSize; i++)
{
putchar(inBuffer[i]);
}
puts("");
}
fclose(mainFile);
keyFile = fopen(keyFile_in, "rb");
// if can't open for read, close
if(keyFile == nullptr)
{
printf("Couldn't open file %s!", keyFile_in);
return -1;
}
// go to end of file, get the position in bytes, and store it
// the position in bytes will be the file size
fseek(keyFile, 0, SEEK_END);
const int keyFileSize = ftell(keyFile);
rewind(keyFile); // go to beggining of file
// read the key characters on the key buffer variable
fread(key, sizeof(char), keyFileSize, keyFile);
if(consoleOutput) //TODO: if this option is enabled, display the file contents
{
for(int i = 0; i < keyFileSize; i++)
{
putchar(key[i]);
}
printf("\nSize: %i", keyFileSize);
}
fclose(keyFile);
// output decryption/encryption
puts("\n\tStarting to do the magic\n");
// do the XOR encryption
// for each character in the buffer, XOR it using the key characters
// use moddulus on the key character array using the key file size to avoid reading outside of array
// example:
// i = 20 keyFileSize = 8 (8 bytes)
// i % keyFileSize = 4
// character in the 5th position of the key array will be use to XOR the buffer character at 21th position
// write the result in the same buffer
for(int i = 0; i < mainFileSize; ++i)
{
inBuffer[i] = inBuffer[i] ^ key[i%keyFileSize];
}
if(consoleOutput) //TODO: if this option is enabled, display the file contents
{
for(int i = 0; i < mainFileSize; i++)
{
putchar(inBuffer[i]);
}
puts("");
}
outFile = fopen(file_out, "wb");
// if can't open, exit
if(outFile == nullptr)
{
printf("Couldn't open file %s!", file_out);
return -1;
}
// write the whole buffer chunk in the output file
// as data was not added or removed, it is the same size as the input file
fwrite(inBuffer, sizeof(char), mainFileSize, outFile);
fclose(outFile);
// clean up the buffer
delete[] inBuffer;
puts("Finished!");
// bye bye!!
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T21:54:39.443",
"Id": "414033",
"Score": "1",
"body": "Welcome to Code Review! Why not comment it *before* asking for a review, though? Reviewers can review your use of comments, and comments will help reviewers understand your code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T22:48:35.073",
"Id": "414035",
"Score": "0",
"body": "Hi, you're right, editing right now to include comments. Please review :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T15:13:10.853",
"Id": "414427",
"Score": "0",
"body": "Thank you for the response, I edited it already with the suggestions. switched to streams and other major stuff. It should work on large files :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T15:15:40.167",
"Id": "414428",
"Score": "1",
"body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T15:15:51.553",
"Id": "414429",
"Score": "0",
"body": "Feel free to post a follow-up question instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T15:17:06.687",
"Id": "414430",
"Score": "0",
"body": "Sorry!! you're right :)"
}
] | [
{
"body": "<ul>\n<li><p>Any time you feel compelled to put a comment like</p>\n\n<pre><code> // read key file\n</code></pre>\n\n<p>consider factoring the relevant code into a function, e.g. <code>read_key_file(....)</code>. Notice how the comment becomes unnecessary.</p></li>\n<li><p>If you <em>can</em> process a stream, <em>do</em> process a stream. Read <code>stdin</code>, output to <code>stdout</code>. The benefits of stream processing are</p>\n\n<ul>\n<li><p>No need to allocate a (possibly huge) buffer for am input file</p></li>\n<li><p>The program can be part of a pipeline</p></li>\n</ul></li>\n<li><p>The <code>int mainFileSize;</code> is more than questionable. File size may well exceed the limit of <code>int</code>. It may even exceed the limits of <code>long</code> which <code>ftell</code> returns. Use <code>ftello</code> (which returns <code>off_t</code>, wide enough to accommodate <em>any</em> file size).</p></li>\n<li><p>The only place you do need to know the file size, and allocate a buffer dynamically, is reading of the key file. If the key file is larger than 100 bytes, your code faces an out-of-bound access problems.</p></li>\n<li><p>As a side note, I don't see a reason for <code>consoleOutput</code> flag to exist. There are better debugging techniques. In any case, if you want to use it, provide a command line option to control its value.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T23:09:33.683",
"Id": "414036",
"Score": "0",
"body": "Thank you!, I used standard input/ouput to reduce exe size :).\nLet me work on the streams, and use off_t instead of int.\nThanks for all the feedback :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T23:37:11.393",
"Id": "414040",
"Score": "0",
"body": "@JonathanMichel To avoid a confusion, I said streams meaning `stdin` and `stdout` instead of opening named files, so that the program can be called as `encrypt key < infile > outfile`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T15:12:56.353",
"Id": "414426",
"Score": "0",
"body": "Thank you for the response, I edited it already with the suggestions. switched to streams and other major stuff. It should work on large files :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T22:58:40.217",
"Id": "214076",
"ParentId": "214067",
"Score": "5"
}
},
{
"body": "<p>In general, your program is very C-like. I would raise at least the following points:</p>\n\n<ul>\n<li><p>When writing C++, you might prefer <code>std::cout</code> to <code>printf</code>. Some points regarding this are raised for instance in <a href=\"//stackoverflow.com/q/2017489\">this SO question</a>.</p></li>\n<li><p>In contrast to C, when writing C++, you should strive to declare variables as late as possible. This increases readability and advocates efficiency (e.g., if you exit early, was it really worth initializing all those gazillion variables?). For example, don't define <code>keyFile</code> and <code>outFile</code> at the beginning of Encrypt; it's not their place of use. As a C++ programmer, if I see something like <code>keyFile</code> being used, I instinctively look for its type somewhere nearby, perhaps only to discover I have to scroll up considerably before finding it making it harder to understand the code. </p></li>\n<li><p>Luckily, C++ offers classes which do dynamic memory management for you. Instead of using an array of characters (like <code>char key[100]</code>), consider using <code>std::string</code>. With a character array, you have to take care in not overflowing (is 100 characters really sufficient? What happens if not?).</p></li>\n<li><p>Consider avoiding manual memory management via <code>new</code> and <code>delete</code>. Mistakes are easy to make and notoriously hard to catch in larger & more complex systems. Tools like <code>std::shared_ptr</code> and <code>std::vector</code> are specifically designed to help you in these cases.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T14:33:01.940",
"Id": "414058",
"Score": "0",
"body": "Thanks for the comments. I appreciate them. I just wanted to do it right now using c libraries to see the file size (as iostream and string makes big files). It was just the first step :). I'll modify the code to use the c++ STL and streams.\nFor the key char buffer, I just used 100 on the array just for temporary use, I'll make it dynamic with std::string. Now as for the new and delete, let me see std::shared_ptr, I haven't got to that yet (self taught here :) )"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T15:12:52.417",
"Id": "414425",
"Score": "0",
"body": "Thank you for the response, I edited it already with the suggestions. switched to streams and other major stuff. It should work on large files :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T23:08:26.400",
"Id": "214078",
"ParentId": "214067",
"Score": "3"
}
},
{
"body": "<p>I'll not repeat points that are already mentioned by others, so these are additional to existing answers:</p>\n\n<ul>\n<li><p>If you include <code><cstdio></code>, then its identifiers are in the <code>std</code> namespace (i.e. <code>std::printf</code>, <code>std::open</code>, etc). Implementations are <em>allowed</em> to also declare them in the global namespace (and several do), but you can't rely on that in a portable program.</p></li>\n<li><p>Error messages should go to <code>std::cerr</code> or <code>stderr</code>; they should not be mixed in with program output. The same goes for debugging messages (though they should probably be removed, if you've finished debugging).</p></li>\n<li><p>Return a non-zero value from <code>main()</code> if the program is unsuccessful. There's even a handy macro (<code>EXIT_FAILURE</code>) available in <code><cstdlib></code>.</p></li>\n<li><p>Don't ignore the return value from <code>Encrypt()</code> - ideally, you'd return exit status so that <code>main()</code> can simply write</p>\n\n<pre><code> return Encrypt(argv[1], argv[2], argv[3]);\n</code></pre></li>\n<li><p><code>std::fwrite()</code> and <code>std::fclose()</code> can return errors (and their C++ equivalents can be made to throw exceptions). Don't assume that they have succeeded - the program has certainly failed if it couldn't write its output. Hint: use <code>std::perror()</code> to report the reason for failure.</p></li>\n<li><p>Don't call <code>std::putchar()</code> in a loop when you can simply use <code>std::fwrite()</code> once.</p></li>\n<li><p>End format strings with a newline character, except where you intend to combine several output strings into a single line.</p></li>\n<li><p>When modifying values, we can use combined operate+assign to make it clearer that we're modifying elements:</p>\n\n<pre><code>inBuffer[i] ^= key[i%keyFileSize];\n</code></pre></li>\n<li><p><code>sizeof(char)</code> is always 1, since the result is in units of <code>char</code>.</p></li>\n<li><p>Don't leave <code>TODO</code> comments in your code; that's usually a sign that it's not yet ready for review!</p></li>\n<li><p>Consider not measuring either file: the main file can be streamed character by character, and the key file can be treated similarly, but with a <code>std::rewind()</code> call whenever we reach its end.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T15:12:39.927",
"Id": "414424",
"Score": "0",
"body": "Thank you for the response, I edited it already with the suggestions. switched to streams and other major stuff. It should work on large files :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T14:53:51.943",
"Id": "214248",
"ParentId": "214067",
"Score": "3"
}
},
{
"body": "<p>In response on my post, this is the updated version. Thanks to Toby Speight, vnp, Mast and Null for their reviews and suggestions.</p>\n\n<p>Changed:</p>\n\n<ul>\n<li>Switched to streams</li>\n<li>Removed dynamic memory allocation</li>\n<li>It should work on really large files</li>\n<li>Uses the return value of the function</li>\n<li>Have a progress bar if the file size is larger than 5 MB</li>\n</ul>\n\n<p>*blank line</p>\n\n<pre><code>/*\n * Encryptor\n * File encryptor/decryptor.\n * Works on any kind of file.\n * Uses XOR encryption supplying a private key on a separate file\n * that very same key file is used for both encrypt and decrypt\n * example:\n * create a file named key.txt and inside of it, write these characters: mZq4t7w!\n * save the file and use it as a key to encrypt and decrypt any file\n *\n * For encryption:\n * Supply the \"raw\" file to be encrypted, use the key file and name the output file\n *\n * For decryption:\n * Supply the output file (encrypted), use the key file and the output file will be \"raw\" again.\n */\n// Plans for the future:\n// 1.- Add a command line option to display outputs\n// 2.- Create a file and a header file, include the key string length into it and compare values, to avoid\n// any modification or \"hacking\"\n\n#include <iostream>\n#include <fstream>\n#include <string>\n\n// function that will encrypt/decrypt the file\n// gets 3 args., input filename, key filename and output filename\nint Encrypt(const std::string& file_in, const std::string& keyFile_in, const std::string& file_out);\n\nint main(int argc, char** argv)\n{\n // if user uses help, indicate the use of the program, exit.\n if(argc == 2)\n {\n if((argv[1][0] == '-') && (argv[1][1] == 'h'))\n {\n std::cout << \"\\nUso: \" << argv[0] <<\n \" \\\"in file\\\" \\\"file with key\\\" \\\"out file\\\"\\n\" << std::endl;;\n }\n }\n else if(argc == 4)// user typed 3 arguments, everything ok, do the magic\n {\n std::string input(argv[1]);\n std::string key(argv[2]);\n std::string output(argv[3]);\n\n return Encrypt(input, key, output);\n }\n else // if there's no arguments or the user typed more than 3 arguments,\n //tell user to use help though -h option, exit.\n {\n std::cout << \"\\nExecute with \" << argv[0] <<\n \"-h for more information\\n\" << std::endl;\n }\n return 0;\n}\n\nint Encrypt(const std::string& file_in, const std::string& keyFile_in, const std::string& file_out)\n{\n const int FileSizeThreshold = 5 * 1024 * 1024; // initialize to 5 MB\n bool biggerThanThreshold = false;\n\n // Work on the key file\n std::ifstream keyFile(keyFile_in, std::ios_base::in | std::ios_base::binary);\n if(!keyFile.is_open())\n {\n std::cerr << \"Couldn't open file \" << keyFile_in << std::endl;\n return -1;\n }\n\n // get the file size and store it, to use it as string length\n // go to beggining of the file and read its contents into a buffer\n keyFile.seekg(0, std::ios_base::end);\n std::streamsize keyFileSize = keyFile.tellg();\n keyFile.seekg(0, std::ios_base::beg); // go to beggining of file\n\n std::string keyFileBuffer;\n keyFileBuffer.resize(keyFileSize);\n keyFile.read( (char*)&keyFileBuffer[0], keyFileSize);\n keyFile.close();\n // Done working with tye key file\n\n // Work on the input file\n std::ifstream inputFile(file_in, std::ios_base::in | std::ios_base::binary);\n if(!inputFile.is_open())\n {\n std::cerr << \"Couldn't open file \" << file_in << std::endl;\n return -1;\n }\n\n // get the file size and store it, to use it as limit to read and write the files (input / output)\n inputFile.seekg(0, std::ios_base::end);\n std::streamsize inputFileSize = inputFile.tellg();\n inputFile.seekg(0, std::ios_base::beg); // go to beggining of file\n\n // if the file is 1 byte in size or is empty, exit\n if(inputFileSize <= 1)\n {\n std::cerr << \"File is empty or the size is really small (not worthy)\" << std:: endl;\n return -2;\n }\n\n if(inputFileSize > FileSizeThreshold )\n {\n std::cout << \"File size is \" <<\n inputFileSize/1024/1000 << \",\" << (inputFileSize/1024)%1000 << \" MB... \" <<\n \"Activating stream mode.\" << std::endl;\n\n biggerThanThreshold = true;\n }\n\n // do the XOR encryption\n // for each character in the buffer, XOR it using the key characters\n // use moddulus on the key character array using the key file size to avoid reading outside of array\n // example:\n // i = 20 keyFileSize = 8 (8 bytes)\n // i % keyFileSize = 4\n // character in the 5th position of the key array will be use to XOR the buffer character at 21th position\n // write the result directly to the output files\n\n // Work on the output file at the same time as the input file\n // so we can avoid to allocate memory\n std::ofstream outFile(file_out, std::ios_base::out | std::ios_base::binary);\n if(!outFile.is_open())\n {\n std::cerr << \"Couldn't open file \" << file_out << std::endl;\n return -1;\n }\n\n char charBuffer = 0;\n int tick = inputFileSize / 30;\n\n if(biggerThanThreshold)\n {\n std::cout << \"Progress: \";\n }\n\n // write directly from the input file, to the output file, without storing any buffer or allocating extra memory\n // if the app fails or crashes, the output file will be incomplete, not a big deal atm\n // it should work with files more than 1 GB\n for(int i = 0; i < inputFileSize; ++i)\n {\n inputFile.get(charBuffer);\n outFile.put(charBuffer ^ keyFileBuffer[i%keyFileSize]);\n\n // if the file is bigger than the threshold, show some kind of neat progress bar\n if(i % tick == 0 && biggerThanThreshold)\n {\n std::cout << \"#\";\n }\n }\n\n if(biggerThanThreshold)\n {\n std::cout << \" 100%!!\" << std::endl;\n }\n\n // Close both files and get out!\n inputFile.close();\n outFile.close();\n\n std::cout << \"Finished!\" << std::endl;\n\n return 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T15:25:14.323",
"Id": "214332",
"ParentId": "214067",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "214078",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T21:30:37.947",
"Id": "214067",
"Score": "4",
"Tags": [
"c++",
"file"
],
"Title": "Simple command-line XOR encryptor/decryptor for files"
} | 214067 |
<p>I am trying to create a custom WordPress/WooCommerce function in PHP. I am a newbie and would really appreciate some feedback on my code and how to improve the code! Right now it feels like there is a lot of duplication where there probably is a smarter and better way to do it.</p>
<p>Overall the function is used to hide shipping methods. Besides the usual shipping methods then some items is shipped in pallets by either quarter, half or full. When an item with shipping class of full pallet is in the cart, for example, it should hide all other shipping methods and so on.</p>
<pre><code>// SHIPPING METHOD BASED ON SHIPPINGCLASS - FULL PALLET
add_filter('woocommerce_package_rates', 'wtf_hide_shipping_method_based_on_shipping_class', 10, 2);
function wtf_hide_shipping_method_based_on_shipping_class($available_shipping_methods, $package)
{
$hide_when_shipping_class_exist = array(
171 => array(
'pakkelabels_shipping_gls_private',
'pakkelabels_shipping_postnord_private',
'pakkelabels_shipping_gls',
'pakkelabels_shipping_pdk',
'flat_rate:15',
'flat_rate:14'
)
);
$hide_when_shipping_class_not_exist = array(
171 => array(
'flat_rate:12'
)
);
$shipping_class_in_cart = array();
foreach(WC()->cart->get_cart_contents() as $key => $values) {
$shipping_class_in_cart[] = $values['data']->get_shipping_class_id();
}
foreach($hide_when_shipping_class_exist as $class_id => $methods) {
if(in_array($class_id, $shipping_class_in_cart)){
foreach($methods as & $current_method) {
unset($available_shipping_methods[$current_method]);
}
}
}
foreach($hide_when_shipping_class_not_exist as $class_id => $methods) {
if(!in_array($class_id, $shipping_class_in_cart)){
foreach($methods as & $current_method) {
unset($available_shipping_methods[$current_method]);
}
}
}
return $available_shipping_methods;
}
// SHIPPING METHOD BASED ON SHIPPINGCLASS - HALF PALLET
add_filter('woocommerce_package_rates', 'wfe_hide_shipping_method_based_on_shipping_class', 10, 2);
function wfe_hide_shipping_method_based_on_shipping_class($available_shipping_methods, $package)
{
$hide_when_shipping_class_exist = array(
169 => array(
'pakkelabels_shipping_gls_private',
'pakkelabels_shipping_postnord_private',
'pakkelabels_shipping_gls',
'pakkelabels_shipping_pdk',
'flat_rate:15'
)
);
$hide_when_shipping_class_not_exist = array(
169 => array(
'flat_rate:14'
)
);
$shipping_class_in_cart = array();
foreach(WC()->cart->get_cart_contents() as $key => $values) {
$shipping_class_in_cart[] = $values['data']->get_shipping_class_id();
}
foreach($hide_when_shipping_class_exist as $class_id => $methods) {
if(in_array($class_id, $shipping_class_in_cart)){
foreach($methods as & $current_method) {
unset($available_shipping_methods[$current_method]);
}
}
}
foreach($hide_when_shipping_class_not_exist as $class_id => $methods) {
if(!in_array($class_id, $shipping_class_in_cart)){
foreach($methods as & $current_method) {
unset($available_shipping_methods[$current_method]);
}
}
}
return $available_shipping_methods;
}
// SHIPPING METHOD BASED ON SHIPPINGCLASS - QUARTER PALLET
add_filter('woocommerce_package_rates', 'wf_hide_shipping_method_based_on_shipping_class', 10, 2);
function wf_hide_shipping_method_based_on_shipping_class($available_shipping_methods, $package)
{
$hide_when_shipping_class_exist = array(
211 => array(
'pakkelabels_shipping_gls_private',
'pakkelabels_shipping_postnord_private',
'pakkelabels_shipping_gls',
'pakkelabels_shipping_pdk',
)
);
$hide_when_shipping_class_not_exist = array(
211 => array(
'flat_rate:15'
)
);
$shipping_class_in_cart = array();
foreach(WC()->cart->get_cart_contents() as $key => $values) {
$shipping_class_in_cart[] = $values['data']->get_shipping_class_id();
}
foreach($hide_when_shipping_class_exist as $class_id => $methods) {
if(in_array($class_id, $shipping_class_in_cart)){
foreach($methods as & $current_method) {
unset($available_shipping_methods[$current_method]);
}
}
}
foreach($hide_when_shipping_class_not_exist as $class_id => $methods) {
if(!in_array($class_id, $shipping_class_in_cart)){
foreach($methods as & $current_method) {
unset($available_shipping_methods[$current_method]);
}
}
}
return $available_shipping_methods;
}
</code></pre>
| [] | [
{
"body": "<p>I recommend establishing a single \"lookup\" array that groups your three filtering arrays and assigns new, meaningful grouping keys. Something like this:</p>\n\n<pre><code>$method_filters = [\n 'exists' => [\n 'full pallet' => [\n 171 => [\n 'pakkelabels_shipping_gls_private',\n 'pakkelabels_shipping_postnord_private',\n 'pakkelabels_shipping_gls',\n 'pakkelabels_shipping_pdk',\n 'flat_rate:15',\n 'flat_rate:14'\n ],\n ],\n 'half pallet' => [\n 169 => [\n 'pakkelabels_shipping_gls_private',\n 'pakkelabels_shipping_postnord_private',\n 'pakkelabels_shipping_gls',\n 'pakkelabels_shipping_pdk',\n 'flat_rate:15'\n ],\n ],\n 'quarter pallet' => [\n 211 => [\n 'pakkelabels_shipping_gls_private',\n 'pakkelabels_shipping_postnord_private',\n 'pakkelabels_shipping_gls',\n 'pakkelabels_shipping_pdk'\n ],\n ]\n ],\n 'not exists' => [\n 'full pallet' => [\n 171 => [\n 'flat_rate:12'\n ]\n ],\n 'half pallet' => [\n 169 => [\n 'flat_rate:14'\n ]\n ],\n 'quarter pallet' => [\n 211 => [\n 'flat_rate:15'\n ]\n ]\n ]\n];\n</code></pre>\n\n<p>In php7+, you can even <code>define()</code> the array as a constant since your design will never need to mutate the initial values. Constants have the added benefit of being accessible in any scope so you won't need to pass the array into your function.</p>\n\n<p>Now that your data is all in one place, you can write a single function with parameters to drill down to the appropriate subarray or you can use foreach loops to traverse all of the subarrays.</p>\n\n<p>When you are isolating your cart ids with <code>foreach(WC()->cart->get_cart_contents() as $key => $values) {</code>...</p>\n\n<ol>\n<li>You don't use <code>$key</code> so that declaration can be omitted.</li>\n<li>You can enjoy the ease of comparison in your next step by storing the ids as keys in your temporary array.</li>\n</ol>\n\n<p>Something like this:</p>\n\n<pre><code>foreach(WC()->cart->get_cart_contents() as $item) {\n $class_ids[$item['data']->get_shipping_class_id()] = '';\n}\n</code></pre>\n\n<p>Now there are a few different ways to design the iterative <code>unset()</code> task.</p>\n\n<pre><code>foreach ($method_filters as $filter_type => $pallet_filters) { // iterate exists/not exists level\n foreach ($pallet_filters as $pallet_type => $shipping_methods) { // iterate different pallets level\n if ($filter_type == 'exists') {\n $qualifiers = array_intersect_key($shipping_methods, $class_ids);\n } else {\n $qualifiers = array_diff_key($shipping_methods, $class_ids);\n }\n foreach ($qualifiers as $class_id => $method_names) { // only iterate if there are qualifying class ids\n foreach ($method_names as $method_name) {\n unset($available_shipping_methods[$method_name]);\n }\n }\n }\n}\n</code></pre>\n\n<p>Granted there will be a number of ways to set up the lookup array and a number of ways of iterating the lookup array data. I have performed a basic check that my suggestions work - and I think it works as desired - but you should definitely test it on your project data to be absolutely sure. <a href=\"https://3v4l.org/r4WPg\" rel=\"nofollow noreferrer\">https://3v4l.org/r4WPg</a> or with a CONSTANT: <a href=\"https://3v4l.org/uqcte\" rel=\"nofollow noreferrer\">https://3v4l.org/uqcte</a></p>\n\n<p>With such a busy block of language constructs, it is imperative that you practice sensible variable naming so that no one gets blurry-eyed reviewing your script (not that you had that issue in your posted code).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-23T06:56:56.947",
"Id": "216035",
"ParentId": "214080",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "216035",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T23:39:59.167",
"Id": "214080",
"Score": "2",
"Tags": [
"php",
"wordpress"
],
"Title": "Checking if a shipping method exists"
} | 214080 |
<p>I'm trying to return a list of objects called <code>orders</code> based on a string search that the user enters. <code>orders</code> has a <code>title</code> and a <code>description</code>. The function loops through the orders object and tries to find matches between the search string and order titles or descriptions. The search should be able to find matches even if there are words in the string we are comparing to, and then sort the results by how many matches are found for each order.</p>
<pre><code>import { EditOrderComponent } from './edit-order/edit-order.component';
import { DeleteOrderComponent } from './delete-order/delete-order.component';
import { MatDialog } from '@angular/material';
import { YearService } from './../year.service';
import { CreateOrderService } from '../order.service';
import { Component, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { Order } from '../order.model';
import { ActivatedRoute } from '@angular/router';
import { AdminService } from '../admin.service';
@Component({
selector: 'app-view',
templateUrl: './view.component.html',
styleUrls: ['./view.component.css']
})
export class ViewComponent implements OnInit {
orders: Order[] = [];
private orderSub: Subscription;
currentYear: number | string;
urlYear: any;
isAdmin: boolean;
isAdminCreate: boolean;
myModel = true;
order = 'DESC';
titles = 'titleDESC';
pub = 'pubDESC';
enteredSearch = '';
misMatchSearch = '';
searching = false;
orderCount = 0;
constructor(public adminService: AdminService, public orderService: CreateOrderService, public yearsService: YearService,
private route: ActivatedRoute, public dialog: MatDialog) {}
ngOnInit() {
this.yearsService.cast$.subscribe(current => (this.currentYear = current));
this.adminService.isAdminLogin();
this.adminService.cast$.subscribe(admin => {
(this.isAdmin = admin)
});
this.adminService.caseSOA$.subscribe(create => {
(
this.isAdminCreate = create
)
});
this.orderService.getOrders('All Years');
this.orderSub = this.orderService
.getOrdersUpdatedListener()
.subscribe((orders: Order[]) => {
this.orders = orders;
this.orderCount = this.orders.length;
});
}
isOrdersAvailable(): Boolean {
if ( this.orderCount > 0) {
return true;
}
return false;
}
resetSearch() {
this.orderService.getOrders('All Years');
this.orderSub = this.orderService
.getOrdersUpdatedListener()
.subscribe((orders: Order[]) => {
this.orders = orders;
this.orderCount = this.orders.length;
});
this.enteredSearch = null;
this.searching = false;
}
// order {
// title: string,
// descrtion: string,
// ...
// }
onSearch() {
if ( this.enteredSearch && this.enteredSearch.length > 0) {
this.orderService.getOrders('All Years');
this.orderSub = this.orderService
.getOrdersUpdatedListener()
.subscribe((orders: Order[]) => {
this.orders = orders;
this.orders = this.searchOrders(this.enteredSearch, this.orders);
if ( this.orders ) {
this.orderCount = this.orders.length;
}
if ( this.orderCount === 0) {
this.setUnfoundSearch();
}
});
this.searching = true;
}
}
setUnfoundSearch() {
this.misMatchSearch = this.enteredSearch;
}
searchOrders(search: string, orders: Order[]): Order[] {
if ( search ) {
search = search.trim();
// Array passed by reference.
const tempOrders = [...orders];
const unsortedOrders = this.searchDriver(search, tempOrders);
const orderToReturn = this.sortResults(unsortedOrders);
return orderToReturn;
}
}
// Builds string[]s to compare and compares.
searchDriver(search: string, orders: Order[]): any[] {
const tempOrders = [...orders];
const ascOrders = [];
const searchArray = this.splitString(search);
for (let i = 0; i < tempOrders.length; i++) {
// Combine the title and desctiption into one long string[].
const compare = [];
let tempArray = this.splitString(tempOrders[i].title);
for (let j = 0; j < tempArray.length; j++) {
compare.push(tempArray[j]);
}
tempArray = this.splitString(tempOrders[i].description);
for (let k = 0; k < tempArray.length; k++) {
compare.push(tempArray[k]);
}
compare.push(tempOrders[i].orderID);
const amountSame = this.arrayCompare(searchArray, compare);
// If more than one match is found add it to the array.
if (amountSame >= 1) {
const anOrder = tempOrders[i];
const feed = { amountSame, anOrder };
ascOrders.push(feed);
}
}
return ascOrders;
}
// Break down strings into individual words to compare.
splitString(stringToSplit: string): string[] {
const string = stringToSplit;
let stringArray = [];
stringArray = string.split(' ');
return stringArray;
}
// compare two arrays search and title/desc values
arrayCompare(searchArray: string[], compareToArray: string[]): number {
let counter = 0;
for (let searchIndex = 0; searchIndex < searchArray.length; searchIndex++) {
for (let compareToIndex = 0; compareToIndex < compareToArray.length; compareToIndex++) {
if (this.compareStrings(searchArray[searchIndex], compareToArray[compareToIndex])) {
counter++;
}
}
}
return counter;
}
/*
// Meat and potatoes of the code, does the word comparisons.
compareStrings(searchFor: string, compareTo: string): boolean {
searchFor = searchFor.toLowerCase();
// strips numbers and symbols from a word.
compareTo = compareTo.replace(/\W/g, '');
if (searchFor === compareTo.toLowerCase()) {
return true;
}
return false;
}*/
// Meat and potatoes of the code, does the word comparisons by character values instead of whole words.
compareStrings(searchFor: string, compareTo: string): boolean {
searchFor = searchFor.toLowerCase();
// building string to compareTo...
for (let stringIndex = 0; stringIndex <= compareTo.length - searchFor.length; stringIndex++) {
let buildingString = '';
for (let searchLength = 0; searchLength < searchFor.length; searchLength++) {
buildingString = buildingString + compareTo[stringIndex + searchLength];
}
// finished string
const builtString = buildingString.toLowerCase();
if (searchFor === builtString) {
return true;
}
}
return false;
}
// Sort results in relevenace to how many matches were found to be true.
sortResults(ascOrders: any[]): Order[] {
const tempLength = ascOrders.length;
const orderToReturn = [];
for (let j = 0; j < tempLength; j++) {
let index = 0;
let high = 0;
for (let i = 0; i < ascOrders.length; i++) {
if (high < ascOrders[i].amountSame) {
high = ascOrders[i].amountSame;
index = i;
}
}
orderToReturn.push(ascOrders[index].anOrder);
ascOrders.splice(index, 1);
}
return orderToReturn;
}
orderPub() {
if ( this.pub === 'pubDESC' ) {
this.pub = 'pubASC';
} else {
this.pub = 'pubDESC';
}
this.orderService.reOrder(this.pub);
}
orderTitles() {
if (this.titles === 'titleDESC') {
this.titles = 'titleASC';
} else {
this.titles = 'titleDESC';
}
this.orderService.reOrder(this.titles);
}
orderNums() {
if (this.order === 'DESC') {
this.order = 'ASC';
} else {
this.order = 'DESC';
}
this.orderService.reOrder(this.order);
}
openDialog(order: Order): void {
const dialogRef = this.dialog.open(DeleteOrderComponent, {
data: {
anOrder: order
}
});
dialogRef.afterClosed().subscribe(result => {
if ( result === 'Delete') {
this.onDelete(order._id);
}
});
}
editOrder(order: Order): void {
const dialogRef = this.dialog.open(EditOrderComponent, {
data: {
anOrder: order
}
});
dialogRef.afterClosed().subscribe();
}
orderYearsToShow(order: Order): boolean {
if ( (order.isPub || (!order.isPub && this.isAdmin === true)) && order.date.toString().slice(0, 4) === this.currentYear.toString()) {
return true;
} else if ( (order.isPub || (!order.isPub && this.isAdmin === true)) && this.currentYear.toString() === 'All Years' ) {
return true;
} else { return false; }
}
onDelete(_id: number) {
this.orderService.deleteOrder(_id);
}
}
</code></pre>
<p>An example output would be if someone entered: "Sub" the function would match with "Subpoena". There is an alternative method that would require the entire word to match.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T00:28:15.473",
"Id": "214083",
"Score": "2",
"Tags": [
"search",
"typescript"
],
"Title": "String search function in typescript/angular"
} | 214083 |
<p>I've been revamping on my coding puzzles practices. What is the complexity (both time and space) for this method?</p>
<pre><code>public static String reverse(String word) {
if (word == null || "".equals(word) || word.length() == 1) {
throw new IllegalArgumentException("Invalid Entry");
}
StringBuilder result = new StringBuilder();
for (int i=word.length() - 1; i >= 0; i--) {
result.append(word.charAt(i));
}
return result.toString();
}
</code></pre>
<p>Is this a more optimized solution (what is the time and space complexity of this one as well):</p>
<pre><code>public static String reverse ( String s ) {
int length = s.length(), last = length - 1;
char[] chars = s.toCharArray();
for ( int i = 0; i < length/2; i++ ) {
char c = chars[i];
chars[i] = chars[last - i];
chars[last - i] = c;
}
return new String(chars);
}
</code></pre>
<p>I know that there might be duplicate questions similar to this but am not asking for a solution. I'm only seeking how to figure out the two different types of complexities.</p>
| [] | [
{
"body": "<h3>Linear in space</h3>\n\n<p>Both are linear in space. </p>\n\n<p>The first one is linear because the <code>StringBuilder</code> makes a copy of the string. </p>\n\n<p>The second one is linear because <code>toCharArray</code> makes a copy of the string. We know it can't use the backing array of the string, because the string is immutable. Clearly you can modify the character array. We can ignore the swap variable (<code>c</code>), as it is either constant space or </p>\n\n<p>We can consider a Java compiler (even if none currently work this way) that would release the backing array to the <code>toCharArray</code>, but we can't guarantee that. Because the calling code may want to use the string <em>after</em> calling this method. So the assumption in the method is that we are creating a new array. </p>\n\n<p>If the input is a string and the output is a different string (and we can't change the original string, so it has to be different), then linear time is the best we could possibly do. So even without the intermediate variable, these would still be linear in space. Both create new strings. </p>\n\n<h3>Linear in time</h3>\n\n<p>Both are linear in time. </p>\n\n<p>The first one does <span class=\"math-container\">\\$n\\$</span> iterations with one <code>append</code> operation per iteration. The <code>append</code> operations should be constant time. There may be occasional copy operations that can be amortized to be constant time per <code>append</code> operation or linear time overall. That's <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span>. </p>\n\n<p>The second one does <span class=\"math-container\">\\$\\frac{n}{2}\\$</span> iterations with two array assignments per iteration. That's also linear, <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span>. Because <span class=\"math-container\">\\$\\frac{n}{2}\\$</span> grows linearly with <span class=\"math-container\">\\$n\\$</span> and two is a constant. </p>\n\n<h3>Constant space</h3>\n\n<p>To have a method be constant in space, it needs to return the same memory that brings the input. E.g. </p>\n\n<pre><code>public void reverse(char[] chars) {\n for (int i = 0, j = chars.length - 1; i < j; i++, j--) {\n char temp = chars[i];\n chars[i] = chars[j];\n chars[j] = temp;\n }\n}\n</code></pre>\n\n<p>This is constant in space and linear in time. But it neither takes nor returns a string. </p>\n\n<h3>Constant space and time</h3>\n\n<p>There's a sort of backwards way of reversing a string in constant time and space. </p>\n\n<pre><code>class ReversedString {\n\n private String string;\n\n public ReversedString(String string) {\n this.string = string;\n }\n\n public char charAt(int index) {\n return string.charAt(string.length() - 1 - index);\n }\n\n}\n</code></pre>\n\n<p>But we wouldn't be able to just use this as a string without creating a new string. The only operation that works (so far) is <code>charAt</code>. We might be able to make other operations work, but not all of them. In particular, a <code>toString</code> would be linear in time and space, just like the original methods. Because it would have to make a new string of the same length. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T03:07:14.573",
"Id": "214088",
"ParentId": "214084",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T00:55:29.960",
"Id": "214084",
"Score": "0",
"Tags": [
"java",
"strings",
"comparative-review",
"complexity"
],
"Title": "Reverse String in Java"
} | 214084 |
<p>I'm going through the K&R C book (coming from Python) and am on exercise 1-18, which states:</p>
<blockquote>
<p>Write a program to remove trailing blanks and tabs from each line of input, and to delete entirely blank lines.</p>
</blockquote>
<p>I wasn't able to find another solution online that looks quite like mine so I am questioning whether it is truly correct, even though it appears to work on anything I throw at it. I let an ending <code>\n</code> be whitespace, removed it and added a general newline to each printed output, but I'm not sure if that is cheating.</p>
<p>If there are any bad practices (or bugs in the code) for standard C please let me know.</p>
<pre><code>#include <stdio.h>
#define MAXLINE 1000
int getli(char line[], int maxline);
main() {
int len;
int i;
char line[MAXLINE];
while ((len = getli(line, MAXLINE)) > 0) {
i = len-1;
/* replace any trailing whitespace character with null character */
while (line[i] == '\n' || line[i] == '\t' || line[i] == ' ') {
line[i] = '\0';
i--;
}
if (line[0] == '\0') {
printf("Blank line\n");
}
else printf("%s\n", line);
}
return 0;
}
/* function to capture input line as char array */
int getli(char s[], int lim) {
int i, c;
for (i=0; i<lim-1 && (c=getchar()) != EOF && c != '\n'; i++) {
s[i] = c;
}
if (c == '\n') {
s[i] = c;
i++;
}
s[i] = '\0';
return i;
}
</code></pre>
| [] | [
{
"body": "<p>What you've got is very \"old-fashioned-looking\" C code, which is only natural for someone working through K&R. :) For example, declaring <code>main()</code> without a return type (that is, with the implicit <code>int</code> return type) is frowned upon these days.</p>\n\n<p>Declaring all your variables — <em>uninitialized!</em> — at the top of your function is also frowned upon, in every language, because uninitialized variables in general are bad. Because uninitialized variables mean they have to be initialized later, which means assignment, which means mutation, which means more <em>stuff</em> for me to keep track of in my head. It's better to delay defining the variable at all until you know what's going to be put in it.</p>\n\n<p>For example:</p>\n\n<pre><code>int len; \nint i; \nchar line[MAXLINE];\n\nwhile ((len = getli(line, MAXLINE)) > 0) {\n i = len-1;\n</code></pre>\n\n<p>could definitely be written as</p>\n\n<pre><code>int len; \nchar line[MAXLINE];\nwhile ((len = getli(line, MAXLINE)) > 0) {\n int i = len-1;\n</code></pre>\n\n<p>And then personally I'd avoid side effects inside the condition of a <code>while</code> loop. It's very K&R, but it's frequently not very easy to read!</p>\n\n<pre><code>while (true) {\n char line[MAXLINE];\n int len = getli(line, MAXLINE);\n if (len <= 0) break;\n int i = len-1;\n while (line[i] == '\\n' || line[i] == '\\t' || line[i] == ' ') {\n line[i] = '\\0';\n i--;\n }\n</code></pre>\n\n<p>Now we can flatten that whole business with <code>i</code> into a simple for loop:</p>\n\n<pre><code>while (true) {\n char line[MAXLINE];\n int len = getli(line, MAXLINE);\n if (len <= 0) break;\n for (int i = len-1; (line[i] == '\\n' || line[i] == '\\t' || line[i] == ' '); --i) {\n line[i] = '\\0';\n }\n</code></pre>\n\n<p>At this point I wonder whether it is <em>in your function's contract</em> that it zeroes out <em>every</em> char in the buffer after the last nonspace character, or if you could avoid writing a lot of those zeroes. One way to do that would be to re-expand the loop:</p>\n\n<pre><code> int i = len-1;\n while (line[i] == '\\n' || line[i] == '\\t' || line[i] == ' ') {\n --i;\n }\n line[i+1] = '\\0';\n</code></pre>\n\n<p>Another way would be to factor that code out into a helper function... or just use one of the many standard library functions for manipulating char buffers! Unfortunately, the function you're looking for in this case is spelled <a href=\"https://docs.oracle.com/cd/E88353_01/html/E37846/strrspn-3gen.html\" rel=\"nofollow noreferrer\">strrspn</a> and is actually <em>not standard</em>, even though <code>strspn</code> is.</p>\n\n<pre><code> *strrspn(line, \"\\n\\t \") = '\\0';\n</code></pre>\n\n<p>(I also notice that Oracle's documentation for <code>strrspn</code> contradicts itself. I assume that on failure it returns a pointer to the <em>end</em> of the string, as shown in their example code, not a pointer to the beginning of the string, as written in their prose description.)</p>\n\n<p>Anyway, writing <code>strrspn</code> from scratch would be a good K&R-style exercise for you!</p>\n\n<hr>\n\n<p><code>(len = getli(line, MAXLINE))</code> looks like a stutter. I don't know why you wouldn't write out the whole word <code>getline</code>... unless you're avoiding the library function, in which case something like <code>read_one_line</code> or <code>get_a_line</code> would be reasonable names to choose.</p>\n\n<p>Don't write <code>MAXLINE</code> on that line, either. Don't give yourself a chance to misspell it or cut-and-paste-error your way into a bug. If you're calling <code>getli</code> with the buffer <code>line</code>, then the second argument should always be the size of the buffer — that is, <code>sizeof line</code>. Sure, that <em>happens to be</em> <code>MAXLINE</code>, just like <code>MAXLINE</code> <em>happens to be</em> 1000; but you should avoid repeating the word <code>MAXLINE</code> for the same reason you should avoid repeating the word <code>1000</code>. If you call <code>getli(line, sizeof line)</code>, you can see right at the callsite — without inspecting any other code — that the call is correct. It is correct <em>by design</em>.</p>\n\n<hr>\n\n<p>Your <code>getli</code> function has very convoluted control flow. You have a side-effect in the condition again; and then you test for <code>'\\n'</code> both inside and outside the loop.\nHere's an exercise: Rewrite the code using <em>no loops except <code>while (true)</code>.</em> Then see how much clearer you can make the code while preserving that property.</p>\n\n<hr>\n\n<p>Here's the first pass:</p>\n\n<pre><code>int getli(char s[], int lim) {\n int i = 0;\n int c;\n while (true) {\n if (i >= lim - 1) break;\n c = getchar();\n if (c == EOF) break;\n if (c == '\\n') break;\n s[i] = c;\n ++i;\n }\n if (c == '\\n') {\n s[i] = c;\n ++i;\n }\n s[i] = '\\0';\n return i;\n}\n</code></pre>\n\n<p>Do you spot an opportunity to combine codepaths now? Keep going; you'll find that the code ends up shorter than it started out!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T06:36:25.383",
"Id": "214098",
"ParentId": "214086",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "214098",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T01:44:06.403",
"Id": "214086",
"Score": "1",
"Tags": [
"algorithm",
"c"
],
"Title": "Removing trailing whitespace from input lines"
} | 214086 |
<p>I'm trying to work HTML5 canvas video into a React application while making the code as clean as possible. What kind of improvements should be made to improve the performance utilizing the React to its fullest potential?</p>
<pre><code>import React, { Component } from 'react';
import './App.css';
import video from './video.mp4';
import watermark from './watermark.png';
class App extends Component {
constructor() {
super();
this.state = {};
}
componentDidMount() {
const canvas = document.createElement('canvas');
canvas.width = 1280;
canvas.height = 720;
const context = canvas.getContext('2d');
context.drawImage(document.querySelector('video'), 0, 0, 720, 1280);
context.drawImage(
document.querySelector('.watermark'),
parseInt(document.querySelector('select').value),
parseInt(document.querySelector('select').value)
);
if (document.querySelector('input[name=live]').checked) {
this.setState({ image: canvas.toDataURL() });
}
}
render() {
const range = [];
for (let i = 0; i < 1280; i++) {
range.push(i);
}
return (
<div className="app">
<video src={video} controls />
<div>
<div className="watermarkButton" style={{}}>
<span className="watermarkButtonX">Watermark X
<select className="positionX">
{range.map(i => (
<option key={i}>{i}</option>
))} </select></span>
<span className="watermarkButtonY">Watermark Y
<select className="positionY">
{range.map(i => (
<option key={i}>{i}</option>
))} </select></span>
<span>Live</span>
<input type="checkbox" name="live" />
</div>
<button className = "watermarkButton watermarkSubmit"
onClick={() => {
const canvas = document.createElement('canvas');
canvas.width = 1280;
canvas.height = 720;
const context = canvas.getContext('2d');
context.drawImage(document.querySelector('video'), 0, 0, 1280, 720);
context.drawImage(
document.querySelector('.watermark'),
parseInt(document.querySelector('.positionX').value),
parseInt(document.querySelector('.positionY').value)
);
this.setState({ image: canvas.toDataURL() });
}}> Watermark! </button>
<img alt="watermarks" className="watermark" src={watermark} style={{ visibility: 'visible' }} />
<img alt="watermarks" className="imageDisplay" height="405px" width="560px" src={this.state.image} />
</div>
</div>
);
}
}
export default App;
</code></pre>
| [] | [
{
"body": "<p><strong>For loop inside <code>Render()</code></strong></p>\n\n<p>The loop gets called each time the component re-renders, it's a <code>1280</code> pushes to an array and that can be a performance issue, you can set it in <code>componentDidMount</code> or even outside the class since it's not dependent on its data, </p>\n\n<p>Consider <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from\" rel=\"nofollow noreferrer\">Array.from</a> to create and fill the array without creating an intermediate one.</p>\n\n<pre><code>const range = Array.from({length: 1280}, (_, i) => i);\n</code></pre>\n\n<p>And since you're filling it with <code>int</code>s and the <code>select</code> value is an <code>int</code> you don't really need <code>parseInt</code>.</p>\n\n<p><strong>Using <code>document.querySelector</code> to read values</strong></p>\n\n<blockquote>\n <p>Basically, you can't easily rely on the input field because the state needs to come from\n the React app's state, not from the browser's idea of what the value should be.</p>\n</blockquote>\n\n<p>See more explanation in <a href=\"https://www.peterbe.com/plog/onchange-in-reactjs\" rel=\"nofollow noreferrer\">this blog post</a>.</p>\n\n<p>You should instead use the state to store the values of the inputs. ( see code snippet below )</p>\n\n<p><strong>Accessing the DOM using <code>document.querySelector</code></strong></p>\n\n<blockquote>\n <p>In React, we do not directly manipulate the actual DOM. Instead, we must manipulate the virtual representation and let React take care of changing the browser's DOM.</p>\n</blockquote>\n\n<p>Check <a href=\"https://www.fullstackreact.com/p/jsx-and-the-virtual-dom/\" rel=\"nofollow noreferrer\">this article</a> for in depth explanation and the <a href=\"https://davidwalsh.name/get-react-component-element\" rel=\"nofollow noreferrer\">different ways to access the DOM</a>.</p>\n\n<p>Using <code>refs</code>, instead of doing <code>document.querySelector('video')</code>, you can add a <code>ref</code> like : <code><video src={video} controls ref={video => this.video = video}/></code> then use <code>this.video</code> to do what you would do with a regular html element.</p>\n\n<p><a href=\"https://blog.cloudboost.io/using-html5-canvas-with-react-ff7d93f5dc76\" rel=\"nofollow noreferrer\">Using html5 canvas with react</a></p>\n\n<pre><code>import React, { Component } from 'react';\nimport './App.css';\nimport video from './video.mp4';\nimport watermark from './watermark.png';\n\nconst range = Array.from({ length: 1280 }, (_, i) => i);\n\nclass App extends Component {\n constructor() {\n super();\n this.state = {\n select: 0,\n live: false,\n positionX: 0,\n positionY: 0,\n checked: false\n };\n }\n\n componentDidMount() {\n const context = this.canvas1.getContext('2d');\n context.drawImage(this.video, 0, 0, 720, 1280);\n context.drawImage(this.watermark, this.state.select, this.state.select);\n\n if (this.state.live) {\n this.setState({ image: canvas.toDataURL() });\n }\n }\n\n render() {\n return (\n <div className=\"app\">\n <video src={video} controls ref={video => this.video = video} />\n <div>\n <div className=\"watermarkButton\" style={{}}>\n\n <span className=\"watermarkButtonX\">Watermark X\n <select\n className=\"positionX\"\n onChange={value => this.setState({ select: value, positionX: value })}\n value={this.state.positionX}>\n {range.map(i => (\n <option key={i} value={i}>{i}</option>\n ))}\n </select>\n </span>\n\n <span className=\"watermarkButtonY\">Watermark Y\n <select\n className=\"positionY\"\n onChange={value => this.setState({ select: value, positionY: value })}\n value={this.state.positionY}>\n >\n {range.map(i => (\n <option key={i} value={i}>{i}</option>\n ))}\n </select>\n </span>\n\n <span>Live</span>\n <input\n type=\"checkbox\"\n name=\"live\"\n checked={this.state.live}\n onChange={e => this.setState({ live: e.target.value })}\n />\n </div>\n\n\n <button className=\"watermarkButton watermarkSubmit\"\n onClick={() => {\n const context = this.canvas2.getContext('2d');\n context.drawImage(this.video, 0, 0, 1280, 720);\n context.drawImage(this.watermark, this.state.positionX, this.state.positionY);\n this.setState({ image: canvas.toDataURL() });\n }}> Watermark! </button>\n\n <canvas ref={canvas => this.canvas1 = canvas} width={1280} height={720} />\n <canvas ref={canvas => this.canvas2 = canvas} width={1280} height={720} />\n\n <img\n alt=\"watermarks\"\n className=\"watermark\"\n src={watermark}\n style={{ visibility: 'visible' }}\n ref={watermark => this.watermark = watermark}\n />\n <img\n alt=\"watermarks\"\n className=\"imageDisplay\"\n height=\"405px\"\n width=\"560px\"\n src={this.state.image}\n />\n </div>\n </div>\n );\n }\n\n}\n\nexport default App;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T06:57:06.133",
"Id": "214099",
"ParentId": "214087",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T03:02:44.743",
"Id": "214087",
"Score": "3",
"Tags": [
"javascript",
"html5",
"react.js"
],
"Title": "HTML5 canvas video with React"
} | 214087 |
<p>I wanted to create a loan calculator, but the code I could think of was using 3 functions, and calling them and getting result. But I felt it was easy but bad code because I thought this can be written in fewer lines and with more quality. I wanted to ask what are some things to keep in my mind while trying to write better code instead of going in flow and creating many functions.</p>
<pre><code>#include<stdio.h>
#include<stdlib.h>
#include<math.h>
float loanAmount,interestRate,Discount,i,loanPayment; //global variables
int years;
void loanDetails(void); //input from user regarding the loan
float annualRate(void);// interest rate
float discount(void); //discount to be added
int main() //main
{
loanDetails(); //called three functions
annualRate();
discount();
loanPayment = (loanAmount)/(Discount); //formula for monthly payments
printf("\nthe monthly loan payment is %f",loanPayment);
return EXIT_SUCCESS;
}
void loanDetails(void) //taking input from user
{
printf("please enter Total Loan Amount: ");
scanf("%f",&loanAmount);
printf("please enter the number of years: ");
scanf("%d",&years);
printf("please enter the annualrate to be applied: ");
scanf("%f",&interestRate);
}
float annualRate(void) //calculated annual rate
{
float *ann;
ann = &interestRate;
i = ((*ann)/(100))/12;
printf("the value for %d years is %f",years,i);
return i;
}
float discount(void) //calculated dicount
{
float *x,y;
x = &i;
y = 1 + *x;
int n = years*12;
float topD = (pow((y),n)-1);
float botD = (y-1)*pow((y),n);
Discount = topD/botD;
printf("\nthe value of discount is : %f",Discount);
return Discount;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T06:28:29.243",
"Id": "414048",
"Score": "0",
"body": "Welcome to Code Review! While I think the main charm of the traditional C indent of 8 positions is discouraging heavily nested structures, please indent your code consistently."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T01:46:39.340",
"Id": "414113",
"Score": "1",
"body": "Some things are unclear. For example, when calculating the annual interest rate, you do `i = ((*ann)/(100))/12;`, which implies you're calculating a monthly rate because you're dividing by 12. You're also relying too much on global variables instead of utilizing function parameters."
}
] | [
{
"body": "<p>There are a few things to note here. There is extensive referencing and dereferencing of variable addresses, which makes the code less clear. For example, <code>float *x,y; x = &i; y = 1 + *x;</code>. This is unnecessary and seems imposed by thinking related to your use of global variables. </p>\n\n<p>There is nothing wrong with passing pointers as arguments to functions, rather than using global variables. </p>\n\n<p>There is also nothing wrong with using functions. The code below is clearer. Additionally, it removes the need for the function \"annualRate,\" as that is simply a division. </p>\n\n<pre><code>#include<stdio.h>\n#include<stdlib.h> \n#include<math.h>\n\nvoid loanDetails(float * loanAmount, int * years, float* interestRate);\nfloat discount(int years, float i);\n\n\n\nint main (void) {\n float loanAmount, interestRate, disc;\n int years;\n\n loanDetails(&loanAmount, &years, &interestRate);\n disc = discount(years, interestRate/1200);\n\n printf(\"\\nthe value of discount is : %f\",disc);\n\n\n printf(\"\\nthe monthly loan payment is %f\",loanAmount/disc);\n return EXIT_SUCCESS;\n}\n\nvoid loanDetails(float * loanAmount, int * years, float* interestRate) {\n printf(\"please enter Total Loan Amount: \");\n scanf(\"%f\",loanAmount);\n printf(\"please enter the number of years: \");\n scanf(\"%d\",years);\n printf(\"please enter the annualrate to be applied: \");\n scanf(\"%f\",interestRate);\n}\nfloat discount(int years, float i) {\n int months = years*12;\n return (pow((1+i),months)-1)/((i)*pow((1+i),months));\n}\n</code></pre>\n\n<p>If you wanted no functions other than main, you could do the following. Essentially, move the code from the functions to main. This is appropriste, considering that the code is not repeated, runs sequentially, and does not have varied/multiple inputs. </p>\n\n<pre><code>#include<stdio.h>\n#include<stdlib.h> \n#include<math.h>\n\n\nint main (void) {\n float loanAmount, interestRate, disc, i;\n int years, months;\n\n printf(\"please enter Total Loan Amount: \");\n scanf(\"%f\",&loanAmount);\n printf(\"please enter the number of years: \");\n scanf(\"%d\",&years);\n printf(\"please enter the annualrate to be applied: \");\n scanf(\"%f\",&interestRate);\n\n months = years*12;\n i = interestRate/1200;\n\n disc = (pow((1+i),months)-1)/((i)*pow((1+i),months));\n\n printf(\"\\nthe value of discount is : %f\",disc);\n\n printf(\"\\nthe monthly loan payment is %f\",loanAmount/disc);\n return EXIT_SUCCESS;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T20:50:31.210",
"Id": "214132",
"ParentId": "214091",
"Score": "1"
}
},
{
"body": "<p>Prefer the C++ standard library headers <code><cmath></code>, <code><cstdlib></code> and <code><cstdio></code> (though prefer <code><iostream></code> to the latter; it will help avoid some common errors). These place the C names into the <code>std</code> namespace where they belong.</p>\n\n<p>In C++, we normally write <code>()</code> to indicate that a function takes no arguments. <code>(void)</code> is a C style of code.</p>\n\n<p>Prefer <code>double</code> to <code>float</code> for floating-point calculations. <code>double</code> is the \"natural\" type in C and C++; use <code>float</code> only where space is the main concern.</p>\n\n<p>Avoid global variables. In larger programs, global variables make it much harder to reason about parts of the code in isolation, so don't get into bad habits like this in your small programs.</p>\n\n<p>I/O operations can fail. There's no excuse for unchecked <code>scanf()</code>, which can lead to undefined behaviour.</p>\n\n<p>There's no need to take the address of <code>interestRate</code> here, nor to divide separately by 100 and then by 12:</p>\n\n<blockquote>\n<pre><code>float *ann;\nann = &interestRate;\ni = ((*ann)/(100))/12;\n</code></pre>\n</blockquote>\n\n<p>We can just use it:</p>\n\n<pre><code>// convert annual percentage rate to monthly rate as a fraction\ndouble i = interestRate / 1200;\n</code></pre>\n\n<p>Similarly,</p>\n\n<blockquote>\n<pre><code>float *x,y;\nx = &i;\ny = 1 + *x;\n</code></pre>\n</blockquote>\n\n<p>can be simply</p>\n\n<pre><code>double y = 1 + i;\n</code></pre>\n\n<p>When printing output, lines normally <em>end</em> with a newline, rather than beginning with one. Many terminals and/or stdio implementations flush output when they receive a newline (that's certainly true if stdout is a line printer, for example), and we certainly don't want to exit without a final newline (the next shell prompt then appears in an unexpected position).</p>\n\n<p>There's far more parentheses than useful here:</p>\n\n<blockquote>\n<pre><code>float topD = (pow((y),n)-1);\nfloat botD = (y-1)*pow((y),n);\n</code></pre>\n</blockquote>\n\n<p>It's probably worth pulling out the common subexpression <code>std::pow(y,n)</code>, too (and <code>months</code> might be a better name than <code>n</code>).</p>\n\n<p>Why is <code>Discount</code> named with a capital <code>D</code>?</p>\n\n<p>Many of the comments aren't very helpful:</p>\n\n<blockquote>\n<pre><code>int main() //main\n{\n\n loanDetails(); //called three function\n</code></pre>\n</blockquote>\n\n<p>We can see that it's the <code>main()</code> function, and we can see that three functions are called. What we can't see is that the functions interact invisibly (via the global variables), and so must be called exactly in that order. That's the sort of information that comments are useful for.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T15:59:09.500",
"Id": "214251",
"ParentId": "214091",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "214132",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T05:13:02.407",
"Id": "214091",
"Score": "0",
"Tags": [
"c",
"calculator",
"finance"
],
"Title": "Loan calculator in C"
} | 214091 |
<p>I am a newbie to C++ and I want to do some cool stuff with it. Here I have implemented my own getline function which reads from a file. so what do you think of this getline function?</p>
<pre><code>#include <iostream>
#include <fstream>
using namespace std;
class Foo {
private:
char ch;
public:
void getline(fstream& in, string& word, char delimeter ='\n'){
word = "";
while(in.get(ch)){
word += ch;
if(ch==delimeter)
break;
}
}
};
int main(){
Foo one;
string temp;
fstream obj("file.txt", ios::in | ios::out | ios::trunc );
obj<<"this is our$ world";
obj.seekg(0);
one.getline(obj, temp,'$');
cout<<temp<<endl;
}
</code></pre>
| [] | [
{
"body": "<p>This doesn't need to be in a class. It would do just fine as a free function:</p>\n\n<pre><code>void getline(fstream& in, string& word, char delim ='\\n'){\n char ch;\n word = \"\";\n while(in.get(ch)){\n word += ch;\n if(ch==delim)\n break;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T09:02:24.060",
"Id": "214105",
"ParentId": "214092",
"Score": "4"
}
},
{
"body": "<p>I would cleanup the logic slightly by using a for-loop or a do-while:</p>\n\n<pre><code>void getline(std::fstream& in, std::string& word, char delim ='\\n')\n{\n char ch;\n\n do\n {\n in.get(ch);\n word += ch;\n }\n while(ch != delim);\n}\n</code></pre>\n\n<p>I think this version reads more nicely by avoiding the break-statement. By the way, I also wouldn't assign word to be empty inside the function: this could be up to the user. Either you pass in an empty string if you want to start fresh, but maybe you <em>do</em> want to append, which you can't do with your current version.</p>\n\n<p>As also mentioned, there is no reason to have the functionality in a class. Just make it a free function.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T11:23:13.083",
"Id": "214110",
"ParentId": "214092",
"Score": "4"
}
},
{
"body": "<h3>Free the Functions!</h3>\n\n<p>First, as others have pointed out, this gains nothing from being a class--it probably makes more sense as a free function.</p>\n\n<h3>Good Inheritors Would Rather Switch than Fight!</h3>\n\n<p>Second, this specifies that its argument must be an <code>fstream</code>. This seems rather pointless. One of the major points of streams is that most functions can (and do) handle various kinds of streams by working with the base classes--usually <code>std::istream</code> and <code>std::ostream</code>. This lets your code work with any stream that provides the interface you need (in this case, just the ability to read, so an istream suffices).</p>\n\n<h3>Return Status</h3>\n\n<p>With those changed, the big shortcoming I see in this <code>getline</code> compared to <code>std::getline</code> is that it fails to return anything that can be interpreted as the status of the attempt at reading.</p>\n\n<p>For example, in a typical case I might read and process all the lines of text from a file using a loop something like this:</p>\n\n<pre><code>std::ifstream input(\"input.txt\");\nstd::string line;\n\nwhile (std::getline(input, line))\n process(line);\n</code></pre>\n\n<p>If I want to read all the lines from a file with this getline, I guess I can do something like this:</p>\n\n<pre><code>while (getline(input, line), input.good())\n process(line);\n</code></pre>\n\n<p>That should work, but it's a bit clumsy at best, and sufficiently strange that most people would probably find it more difficult to understand. I think it would be better to do like most I/O routines, and return a reference to the stream you read from:</p>\n\n<pre><code>std::istream &getline(std::istream& in, string& word, char delimeter ='\\n'){\n char ch;\n\n word = \"\";\n while(in.get(ch)){\n word += ch;\n if(ch==delimeter)\n break;\n }\n return in;\n}\n</code></pre>\n\n<h3>Spelling</h3>\n\n<p>The word you're spelling as \"delimeter\" is actually spelled \"delimiter\".</p>\n\n<h3>Delimiter Usage</h3>\n\n<p>Your code has behavior that differs from <code>std::getline</code> in a way I think reduces its utility. <code>std::getline</code> normally reads the delimiter from the stream, but does <em>not</em> include that delimiter in the output string (where your code does include the closing delimiter in the output string). At least when I've used it, including that delimiter wouldn't be very useful--I'd usually have to delete it if I read a string with this code. I'd probably omit it, and (if necessary) provide an overload that saved it (but still probably separately from the string it read).</p>\n\n<h3>Delimiter Specification</h3>\n\n<p>Probably the single biggest problem I have with <code>std::getline</code> is that you can only specify one specific character as the delimiter. If I were going to write one, I think I'd allow the user to pass something like a string, so they could (for example) pass <code>\"\\t\\r\\n\\v\"</code> as the delimiter, to have the function read to the next white-space.</p>\n\n<p>Although it's more advanced, you could go even further, and let the user specify the delimiter as a regular expression, so they could specify arbitrarily complex patterns instead of just a few specific characters.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T21:18:30.343",
"Id": "214133",
"ParentId": "214092",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T05:18:16.627",
"Id": "214092",
"Score": "5",
"Tags": [
"c++",
"strings",
"file",
"reinventing-the-wheel",
"io"
],
"Title": "My own getline function for reading strings from files"
} | 214092 |
<p>I wrote this Paginator module that's part of a small application that displays Elixir Github repos in a table.</p>
<p>I'm new to Elixir and looking for code improvements with as much as possible. Best practices. Commenting. Optimizations. The usage of structs for input output. Etc.</p>
<h2>paginator.ex</h2>
<pre><code>defmodule Paginator do
@moduledoc """
A module that implements functions for performing simple pagination functionality
Invoke it using the module's `call` function that takes a struct as parameter.
## Struct key values
- total: The total amount of records (mandatory)
- page: The page currently on (default: 1)
- per_page: The number of records per page (default: 10)
- max_display: The number of pages displayed in the pagination menu (default: 10)
- max_results: Optional argument that limits the total number of records it can paginate
## Examples
iex> Paginator.call %Paginator(total: 1000)
%Paginator.Output{
first: nil,
last: 100,
next: 2,
page: 1,
pages: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
previous: nil
}
"""
# The struct with the pagination info that gets returned
defmodule Output do
defstruct [:page, :first, :last, :previous, :next, :pages]
end
@doc """
# Struct that's passed to the module used to calculate the pagination data
"""
@enforce_keys [:total]
defstruct page: 1, per_page: 10, total: nil, max_display: 10, max_results: nil
@doc """
Invokes the module. Takes a struct with the input and returns a struct with the pagination data
"""
def call(data) do
data = data
|> Map.put(:max_pages, max_pages(data))
|> Map.put(:half, half(data))
%Output{
page: data.page,
first: first(data),
last: last(data),
pages: pages(data),
previous: previous(data),
next: next(data)
}
end
# Returns the maximum pages.
defp max_pages(data) do
cond do
data.total <= data.per_page ->
0
data.max_results !== nil and data.max_results < data.total ->
Kernel.trunc(data.max_results / data.per_page)
true ->
Kernel.trunc(data.total / data.per_page)
end
end
# Returns the first page
defp first(data) do
if data.total >= data.per_page and data.page !== 1, do: 1, else: nil
end
# Returns the last page
defp last(data) do
if data.page < data.max_pages, do: data.max_pages, else: nil
end
# Returns the half value of `max_display` rounded down
defp half(data) do
Kernel.trunc(data.max_display / 2)
end
# Returns the `pages` list. The number of list items depends on the number specified in `max_display`
defp pages(data) do
if data.total === nil or data.total === 0 or data.max_pages === 0 do
[]
else
Enum.to_list begin_pages(data)..end_pages(data)
end
end
# Returns the page that the `pages` list starts on
defp begin_pages(data) do
cond do
data.page + data.half >= data.max_pages ->
# when reaching the end
data.max_pages - (data.max_display - 1)
data.page > data.half ->
# odd vs even pages
if rem(data.max_display, 2) === 0 do
data.page - (data.half - 1)
else
data.page - data.half
end
true ->
1
end
end
# Returns the page that the `pages` list ends on
defp end_pages(data) do
end_page = data.page + data.half
cond do
end_page >= data.max_pages ->
# when reaching the end
data.max_pages
data.page <= data.half ->
data.max_display
true ->
end_page
end
end
# Returns the page number that is prior than the current page.
# If the current page is 1 it returns nil
defp previous(data) do
if data.page > 1, do: data.page - 1, else: nil
end
# Returns the page number that is latter than the current page.
# If the current page is equal to the last it returns nil
defp next(data) do
if data.page < data.max_pages, do: data.page + 1, else: nil
end
end
</code></pre>
<h2>paginator_test.exs</h2>
<pre><code>defmodule PaginatorTest do
use ConnCase
alias Paginator
describe "Test Paginator" do
test "page 1 of 15" do
res = Paginator.call %Paginator{total: 150}
assert res.first == nil
assert res.previous == nil
assert res.next == 2
assert res.last == 15
assert res.pages == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
end
test "page 5 of 15" do
res = Paginator.call %Paginator{page: 5, total: 150}
assert res.first == 1
assert res.previous == 4
assert res.next == 6
assert res.last == 15
assert res.pages == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
end
test "page 6 of 15" do
res = Paginator.call %Paginator{page: 6, total: 150}
assert res.first == 1
assert res.previous == 5
assert res.next == 7
assert res.last == 15
assert res.pages == [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
end
test "page 7 of 15" do
res = Paginator.call %Paginator{page: 7, total: 150}
assert res.pages == [3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
end
test "page 13 of 15" do
res = Paginator.call %Paginator{page: 13, total: 150}
assert res.pages == [6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
end
test "per page 50" do
res = Paginator.call %Paginator{page: 25, per_page: 50, total: 2000}
assert res.first == 1
assert res.previous == 24
assert res.next == 26
assert res.last == 40
assert res.pages == [21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
end
test "last page" do
res = Paginator.call %Paginator{page: 50, total: 500}
assert res.first == 1
assert res.previous == 49
assert res.next == nil
assert res.last == nil
end
test "max display" do
res = Paginator.call %Paginator{page: 8, max_display: 5, total: 2000}
assert res.first == 1
assert res.previous == 7
assert res.next == 9
assert res.pages == [6, 7, 8, 9, 10]
res = Paginator.call %Paginator{page: 9, max_display: 5, total: 2000}
assert res.pages == [7, 8, 9, 10, 11]
end
test "max results - total more than max" do
res = Paginator.call %Paginator{page: 96, total: 2000, max_results: 1000}
assert res.last == 100
assert res.pages == [91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
end
test "max results - max more than total" do
res = Paginator.call %Paginator{page: 96, total: 2000, max_results: 1000}
assert res.last == 100
assert res.pages == [91, 92, 93, 94, 95, 96, 97, 98, 99, 100]
end
test "no pages - zero total" do
res = Paginator.call %Paginator{total: 0}
assert res.first == nil
assert res.previous == nil
assert res.next == nil
assert res.pages == []
end
test "no pages - low total" do
res = Paginator.call %Paginator{total: 5}
assert res.first == nil
assert res.previous == nil
assert res.next == nil
assert res.pages == []
end
end
end
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T06:01:21.993",
"Id": "214097",
"Score": "3",
"Tags": [
"unit-testing",
"pagination",
"elixir"
],
"Title": "Paginator module in Elixir"
} | 214097 |
<p>This question has been asked for other languages, but I haven't seen it for C++. Most notably <a href="https://codereview.stackexchange.com/questions/195449/firstduplicate-finder">here</a> and <a href="https://codereview.stackexchange.com/questions/193610/finding-the-first-duplicate-in-an-array/193616#193616">here</a>.</p>
<blockquote>
<p>Given an array a that contains only numbers in the range from 1 to a.length, find the first duplicate number for which the second occurrence has the minimal index. In other words, if there are more than 1 duplicated numbers, return the number for which the second occurrence has a smaller index than the second occurrence of the other number does. If there are no such elements, return -1.</p>
</blockquote>
<p>My tests are running correctly, but I'm getting a timeout from the website codesignalDotCom. I'm wondering what I'm doing that could be taking so much time, and what could be done to fix it.</p>
<pre><code>int firstDuplicate(std::vector<int> a) {
std::vector<int> newVector;
std::cout << a.size() << std::endl;
for(int i = 0; i < a.size(); i++) {
if(std::find(newVector.begin(), newVector.end(), a.at(i)) != newVector.end()){
return a.at(i);
}
newVector.push_back(a.at(i));
}
return -1;
}
</code></pre>
| [] | [
{
"body": "<h3>Find more appropriate data structures</h3>\n\n<blockquote>\n <p>This question has been asked for other languages, but I haven't seen it for C++.</p>\n</blockquote>\n\n<p>Getting timeout usually indicates an inefficient algorithm.\nThe language doesn't matter, because algorithms are language agnostic.\nSome of the posts you linked mention the word \"performance\",\nand they shed light to the problem,\nwith suggestions that could be applied here too,\neven if the language is different.</p>\n\n<p>The first thing to ask when a solution is too slow,\nwhat's the time complexity of the algorithm?</p>\n\n<blockquote class=\"spoiler\">\n <p> quadratic: <span class=\"math-container\">\\$O(n^2)\\$</span></p>\n</blockquote>\n\n<p>That's not so good. Looping over all elements is a linear operation (<span class=\"math-container\">\\$O(n)\\$</span>),\nand checking if an element is in a vector is also a linear operation.</p>\n\n<p>In other words, the weak spot is using a vector to store the elements already seen.\nA vector doesn't provide a fast way to search for random elements.\nOther data structures can provide faster than linear performance to lookup elements:\na tree set can do it in logarithmic time (<span class=\"math-container\">\\$O(\\log n)\\$</span>, making the overall complexity of your algorithm log-linear <span class=\"math-container\">\\$O(n \\log n)\\$</span>),\nor a hash set can do it in constant time (<span class=\"math-container\">\\$O(1)\\$</span>, making the overall complexity of your algorithm linear <span class=\"math-container\">\\$O(n)\\$</span>).</p>\n\n<h3>Coding style</h3>\n\n<p>The name <code>newVector</code> is not great, for several reasons:</p>\n\n<ul>\n<li>What's \"new\" about it?</li>\n<li>Including the name of the data structure in the name of the variable usually doesn't give much new information to the reader, and therefore doesn't help understand its purpose.</li>\n</ul>\n\n<p>This vector is used to store elements already seen. I would have called it <code>seen</code>.</p>\n\n<hr>\n\n<p>The name <code>a</code> is even worse: it tells nothing to the reader about what it is.</p>\n\n<hr>\n\n<p>The main loop goes over <em>indexes</em> of the input vector.\nYou could loop over the <em>values</em> of the input,\nwhich would read more natural:</p>\n\n<pre><code>for (int value : a) {\n if (std::find(newVector.begin(), newVector.end(), value) != newVector.end()){\n return value;\n }\n newVector.push_back(value);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T11:09:08.913",
"Id": "414052",
"Score": "0",
"body": "In general, it is not true that hash tables give you worst-case constant time lookup. This can only be guaranteed by taking special care, like using FKS hashing in a static case or by using Cuckoo hashing (but then insertion is only O(1) expected)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T08:44:18.740",
"Id": "214104",
"ParentId": "214100",
"Score": "4"
}
},
{
"body": "<pre><code>int firstDuplicate(std::vector<int> a) {\n</code></pre>\n\n<p>You've defined your function to take parameter <code>a</code>. Your program simply inspects the elements of <code>a</code>. <code>a</code> itself isn't mutated, so copying <code>a</code> in the parameter of the function is not necessary. For cheap and impossible to copy parameter types, taking them by copy is fine. For parameters where copies become moderately expensive or the cost is unknown at compile time, prefer passing your parameter by reference-to-<code>const</code>.</p>\n\n<p>Try to give your parameter a name that at least hints what values it expects. In this case, numbers from 1 upto some length. We can call them natural numbers.</p>\n\n<pre><code>int firstDuplicate(const std::vector<int>& natural_numbers)\n</code></pre>\n\n<hr>\n\n<pre><code> std::cout << a.size() << std::endl;\n</code></pre>\n\n<p>Unnecessary debugging artifact.</p>\n\n<hr>\n\n<pre><code> std::vector<int> newVector;\n</code></pre>\n\n<p>Before you push values into this <code>newVector</code>, can any safe assumptions be made about this container? If we encounter the worst case, a set of natural numbers with no duplicates, then the size of <code>newVector</code> after inserting the elements of <code>a</code> will be the same.</p>\n\n<pre><code> std::vector<int> values_seen;\n values_seen.reserve(natural_numbers.size());\n</code></pre>\n\n<hr>\n\n<pre><code> for(int i = 0; i < a.size(); i++) {\n</code></pre>\n\n<p>If you are not doing math that requires indices, then prefer range-based for loops instead of raw loops.</p>\n\n<pre><code> for (auto number : natural_numbers) {\n</code></pre>\n\n<hr>\n\n<pre><code> for(int i = 0; i < a.size(); i++) {\n if(std::find(newVector.begin(), newVector.end(), a.at(i)) != newVector.end()){\n return a.at(i);\n }\n }\n</code></pre>\n\n<p>Since <code>i</code> is known to be a valid index (<span class=\"math-container\">\\$0 \\leq i < size\\$</span>), you do not require bounds-checking from <a href=\"https://en.cppreference.com/w/cpp/container/vector/at\" rel=\"nofollow noreferrer\"><code>std::vector::at</code></a>. Use <a href=\"https://en.cppreference.com/w/cpp/container/vector/operator_at\" rel=\"nofollow noreferrer\"><code>std::vector::operator[]</code></a> When you don't need bounds checking.</p>\n\n<hr>\n\n<p>As for improving the overall algorithmic approach, you could speed up the lookups. Keep the elements seen sorted and binary search the insertion point. Hashing the seen values is another option. Both of those options require extra space. An inplace algorithm does exist. Go back to the problem statement and it describes the set of numbers as being <span class=\"math-container\">\\$1\\$</span> to a length. So you have a bunch of positive values being stored as <code>int</code>. Assuming that the largest value in the set of natural numbers (one-based) is smaller than the size of the array (zero-based), we can map values to the indices and can mark it through the signbit.</p>\n\n<pre><code>for (int value : natural_numbers) {\n const auto original_value = value & std::numeric_limits<int>::max();\n\n // The values in the array are one-based, but index-map zero-based\n if (natural_numbers[original_value - 1] < 0) {\n return original_value;\n }\n\n natural_numbers[original_value - 1] |= (1 << 31);\n}\n</code></pre>\n\n<p><em>Note - The original numbers <strong>must</strong> be natural numbers (1, 2, ..., length). This approach does not work for negative numbers and is undefined behavior for zero.</em></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T15:17:31.187",
"Id": "414294",
"Score": "0",
"body": "As an alternative, we could just negate (with unary `-`) the values at \"seen\" positions, instead of the bit-twiddling (which is UB if `int` is 32 bits or smaller),"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T12:40:50.450",
"Id": "214114",
"ParentId": "214100",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "214104",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T06:57:41.260",
"Id": "214100",
"Score": "3",
"Tags": [
"c++",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "firstDuplicate of array"
} | 214100 |
<p>I am trying to model this:</p>
<ul>
<li>a Map can have multiple child of type Biomes and no parent</li>
<li>a Biome can have multiple child of type Landforms and a Map as its parent</li>
<li>a Landform can have multiple child of type Tiles and a Biome as its parent</li>
<li>a Tile has no child and a Landform as its parent</li>
</ul>
<p>I want it to be generic so I can easily add new links to the chain (like adding a new kind of section between Biome and Landform for example). Here is the less ugly solution I have for now :</p>
<pre><code>public class RootSection<T, TChild> : Section<T>
where T : Section<T>
where TChild : Section<TChild>
{
public List<TChild> ChildSection { get; } // duplicate
}
public class MiddleSection<T, TChild, TParent> : Section<T>
where T : Section<T>
where TChild : Section<TChild>
where TParent : Section<TParent>
{
public List<TChild> ChildSection { get; } // duplicate
public TParent Parent { get; } // duplicate
}
public class BottomSection<T, TParent> : Section<T>
where T : Section<T>
where TParent : Section<TParent>
{
public TParent Parent { get; } // duplicate
}
public class Section<T>
where T : Section<T>
{
List<T> AdjacentSections { get; }
}
public class Map : RootSection<Map, Biome> { } // (T, TChild)
public class Biome : MiddleSection<Biome, Landform, Map> { } // (T, TChild, TParent)
public class Landform : MiddleSection<Landform, Tile, Biome> { } // (T, TChild, TParent)
public class Tile : BottomSection<Tile, Landform> { } // (T, TParent)
</code></pre>
<p>As you can see, there is already duplicate code and I can't think of a solution to get rid of this issue. I feel like I am either missing something obvious or over-complexifying the problem. I also feel like this is close to a classic data structure which I ignore the name preventing me from searching for inspiration on the net. </p>
<p>How can I rewrite this code to look cleaner ? Am I right to think it's close to a well known data structure ? </p>
| [] | [
{
"body": "<blockquote>\n <p>I want it to be generic so I can easily add new links to the chain\n (like adding a new kind of section between Biome and Landform for\n example)</p>\n</blockquote>\n\n<p>Generics work fine for simple <strong>generic</strong> data structures (like a List). Your \"generic\" data structure is actually a very special one which will not be used outside of your model. It is more a try to extract the common parts of your model to a generic structure which may be useful, but based on your question I can not see the value in your case.</p>\n\n<p>In my experience, data stuctures with multiple generic types, which has contraints to other generic types, are hard to understand and make the code more complicated.</p>\n\n<p>In your case, I would just give generics up and write the data structure down as it is:</p>\n\n<pre><code>public class Map \n{\n public List<Biome> Biomes { get; } = new List<Biome>();\n public List<Map> AdjacentMaps { get; } = new List<Map>();\n}\n\npublic class Biome \n{\n public Map Map {get; }\n public List<Landform> Landforms { get; } = new List<Landform>();\n public List<Biome> AdjacentBiomes { get; } = new List<Biome>();\n}\n\npublic class Landform\n{\n public Biome Biome {get; }\n public List<Tile> Tiles { get; } = new List<Tile>();\n public List<Landform> AdjacentLandforms { get; } = new List<Landform>();\n}\n\npublic class Tile\n{\n public Landform Landform {get; }\n public List<Tile> AdjacentTiles { get; } = new List<Tile>();\n}\n</code></pre>\n\n<p>Much more readable! The properties has more descriptive names and it needs a minute to extend this hierachical data structure with other types.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T23:24:23.473",
"Id": "414092",
"Score": "0",
"body": "Besides readable, it is by far more *understandable*. QUESTION: `Parent` / `Child` idea is transformed to `Adjacent`. In as much as \"A `Tile` has no child\", for example, is this bad? Is the P/C relationship explicitly relevant for other code? If this is all about composition - A Biome is composed of LandTypes, then I think \"Parent/Child\" concept is actually misleading."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T07:10:02.520",
"Id": "414136",
"Score": "0",
"body": "If the parent relation is not relevant for other code, it is indeed misleading because it increases the coupling between the objects unnecessarily. If possible I would avoid it, but it dependence on the requirements."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T21:01:24.780",
"Id": "414201",
"Score": "1",
"body": "Well, it's not the kind of answer I was expecting since you just really told me to not do it instead of how to do it. The code you posted is really close to what I had before trying to refactor. But I understand why this answer and I decided to leave generics alone for now, it is indeed much more readable but less flexible. Thank you JanDotNet and @radarbob for your inputs on my question. :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T13:12:44.303",
"Id": "214115",
"ParentId": "214102",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "214115",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T08:17:28.087",
"Id": "214102",
"Score": "3",
"Tags": [
"c#",
"object-oriented",
"generics"
],
"Title": "Map, which contains biomes, which contain landforms, which contain tiles"
} | 214102 |
<p>The Task:</p>
<blockquote>
<p>Given a set of closed intervals, find the smallest set of numbers that
covers all the intervals. If there are multiple smallest sets, return
any of them.</p>
<p>For example, given the intervals [0, 3], [2, 6], [3, 4], [6, 9], one
set of numbers that covers all these intervals is {3, 6}.</p>
</blockquote>
<p>My solution:</p>
<pre><code>const intervalls = [[0, 3], [2, 6], [3, 4], [6, 9]];
const getLargestMinAndSmallestMax = (acc, intervall, _, src) => {
if (src.length === 0) { return []; }
if (src.length === 1) { return intervall; }
if (acc[1] === undefined || intervall[0] > acc[1]) {
acc[1] = intervall[0];
}
if (acc[0] === undefined || intervall[1] < acc[0]) {
acc[0] = intervall[1];
}
return acc;
};
const smallestIntervallCoveringAllIntervalls = list => list.reduce(getLargestMinAndSmallestMax, []);
console.log(smallestIntervallCoveringAllIntervalls(intervalls));
</code></pre>
<p>Is there a faster and cleaner version of it?</p>
| [] | [
{
"body": "<h3>Missing the specs</h3>\n\n<p>I don't think the program answers the question.\nFor input <code>[[1, 2], [3, 4], [5, 6]]</code> it returns <code>[2, 5]</code>.\nI don't see how <code>[2, 5]</code> is a smallest set of numbers that covers all the given intervals, because I don't see by what interpretation it covers <code>[3, 4]</code>.</p>\n\n<h3>Review of the implementation</h3>\n\n<p>I would summarize what the program actually does like this:</p>\n\n<blockquote>\n <p>Find the smallest <em>interval</em> that overlaps with all intervals. (Achieved essentially by finding the largest interval start and smallest interval end values.)</p>\n</blockquote>\n\n<p>Well, almost. If the answer is an interval, I would expect the start and end values in the correct order. For input <code>[[0, 9], [2, 6]]</code> the program gives <code>[6, 2]</code>, and I would expect <code>[2, 6]</code>. (The fix is easy, with a <code>.sort()</code> call, as in <code>const smallestIntervallCoveringAllIntervalls = list => list.reduce(...).sort();</code>.)</p>\n\n<p>Below is a review of the implementation of this different assumed spec,\nand that either there is a <code>.sort()</code> call to make the return values consistently ordered, or else assuming that the ordering is irrelevant.</p>\n\n<hr>\n\n<p>These conditions are unnecessary:</p>\n\n<blockquote>\n<pre><code>if (src.length === 0) { return []; }\nif (src.length === 1) { return intervall; }\n</code></pre>\n</blockquote>\n\n<p>The first should never be true if <code>getLargestMinAndSmallestMax</code> is only invoked from <code>reduce(...)</code>,\nbecause for an empty input it will never get invoked.</p>\n\n<p>The second covers a case that would get naturally handled by the rest of the function. With a small caveat: in case the input has a single interval,\nomitting this condition will return the interval </p>\n\n<hr>\n\n<p>If <code>getLargestMinAndSmallestMax</code> is only invoked from <code>reduce(...)</code>,\nthen when <code>acc[1] === undefined</code>, then at the same time <code>acc[0] === undefined</code> will also be true. Therefore the two conditions can be replaced with one, <code>acc.length === 0</code>, like this:</p>\n\n<pre><code>if (acc.length === 0) {\n return [intervall[1], intervall[0]];\n}\nif (intervall[0] > acc[1]) {\n acc[1] = intervall[0];\n}\nif (intervall[1] < acc[0]) {\n acc[0] = intervall[1];\n}\n</code></pre>\n\n<hr>\n\n<p><code>const intervalls</code> is initialized at the top of the file,\nand used at the bottom, which is far away.\nI suggest to initialize it right before it's used.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T21:22:15.557",
"Id": "414078",
"Score": "0",
"body": "Wouldn’t Sort mean another iteration ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T21:23:08.833",
"Id": "414079",
"Score": "0",
"body": "(2,5) Covers (3,4) completely"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T21:25:28.410",
"Id": "414080",
"Score": "0",
"body": "@thadeuszlay I meant sorting the result array with 2-elements, to make the interval's values ordered. As for covering intervals, the problem statement talks about set of numbers, not examples. Even the notation of the example result is `{3, 6}`, using curly braces instead of `[3, 6]`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T21:35:15.703",
"Id": "414081",
"Score": "1",
"body": "@thadeuszlay take a closer look at the problem statement. It talks about \"set of numbers\" to return. And it implies that there can be multiple smallest sets. Btw, the smallest set to cover `[[0, 3]]`, shouldn't it be for example `{0}`? Or `{1}`? Or `{2}`? Your implementation always returns an array of two numbers. So the smallest set always has 2 elements? Either the wording of the problem is wrong, or the implementation is missing the point."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T18:35:36.910",
"Id": "214129",
"ParentId": "214106",
"Score": "0"
}
},
{
"body": "<h2>Naming</h2>\n<p>First point is that I think the naming is getting a little verbose <code>smallestIntervallCoveringAllIntervalls</code> and <code>getLargestMinAndSmallestMax</code></p>\n<ul>\n<li><p><code>getLargestMinAndSmallestMax</code> get largest min and smallest max, don't you mean get "range"? And its not get, the range is not known, you need to "find" it. <code>findRange</code></p>\n</li>\n<li><p><code>smallestIntervallCoveringAllIntervalls</code> This is when comments come into play. If you were part of a team that functions name would already be defined in the interface spec. However if it was an internal call (your code) you would use a smaller name and add a comment to give it the missing meaning as a reminder to you, or for someone that may later need to modify your code.</p>\n</li>\n</ul>\n<h3>Spelling</h3>\n<p><code>intervalls</code> should be <code>intervals</code></p>\n<p>Bad spelling is a gateway to bug hell. Others can not guess how you have misspelled a name, so always check if you are unsure as to the spelling of a name.</p>\n<h2>The spec</h2>\n<p>No project starts without a detailed specification regarding the problem. Part of a programmers job is to ensure that the spec is unambiguous.</p>\n<p>If you have any questions that the spec can not answer then you should not start working on a solution. Rather a memo to the team leader, or email to the client with the points that need to be resolved.</p>\n<p>So lets restate the problem</p>\n<ol>\n<li><p>Given an array of intervals find the smallest interval that covers all intervals.</p>\n</li>\n<li><p>The intervals array will always contain one or more valid intervals.</p>\n</li>\n<li><p>An interval is covering another interval if one or more values in its range are the same. Examples <code>A = [0, 1]</code>, <code>B = [1, 2]</code>, <code>C = [3, 4]</code>. <code>A</code> covers <code>B</code>, <code>C</code> does not cover <code>A</code> and <code>B</code></p>\n</li>\n<li><p>An interval is an array containing two unsorted integers, that have a range from min to max value inclusive. Examples <code>[0, 1]</code> has a range <code>0, 1</code>. <code>[3, -2]</code> has a range <code>-2, -1, 0, 1, 2, 3</code>. <code>[2, 2]</code> has a range <code>2</code>.</p>\n<p>The following <code>[]</code>, <code>[0]</code>, <code>[1,2,3]</code> are not valid intervals</p>\n</li>\n<li><p>The return must be a valid interval</p>\n</li>\n</ol>\n<h2>Your code</h2>\n<p>You have a bug and return incorrect intervals in some cases.</p>\n<p>Two examples of the bug</p>\n<ol>\n<li><p>Given the intervals <code>[[10, 20], [10, -20]]</code> your function returns <code>[-20,10]</code> which is in fact the largest range, the correct solution is <code>[10, 10]</code> (Yes unfair as [10,-20] is A over T)</p>\n</li>\n<li><p>Given intervals <code>[[10,20]]</code> you incorrectly return <code>[10,20]</code>. There are 11 possible correct solutions. Any of <code>[10,10], [11, 11], ..., [n, n] (n = 20)</code></p>\n</li>\n</ol>\n<p>The reason you are returning incorrect intervals is that you do not treat the first interval correctly, as shown in the second example above.</p>\n<p>When finding min and max values of a set of anything with at least one item, you always treat the first item differently. The first items initializes the min or max.</p>\n<p>You use <code>Array.reduce</code> so that means you need to include a test to see if you have the first interval.</p>\n<p>The interval that covers a single interval always has a range length of one and is any of the values in the intervals range. eg <code>[[10,20]]</code> is covered by <code>[10,10]</code> or <code>[20,20]</code></p>\n<h2>Fix using your logic</h2>\n<pre><code>// int for interval\nconst smallestRange = (res, int) => {\n if (res.length === 0) { return [int[0], int[0]] }\n if (int[0] > res[1]) { res[1] = int[0] }\n if (int[1] < res[0]) { res[0] = int[1] }\n return res;\n};\nconst findSmallestRange = ints => ints.reduce(smallestRange , []);\n</code></pre>\n<p>If we now solve to include intervals that are backward (the other question said use <code>Array.sort</code>. NEVER! use sort for a two item array, in fact you only use sort if you can find no other way to sort any items)</p>\n<h2>Solve new spec</h2>\n<p>Solution using while loop and to spec outlined above.</p>\n<p>Note that I use <code>lowIdx + 1 & 1</code> as it is slightly faster than <code>(lowIdx + 1) % 2</code>. This is not a micro optimization, this is a known optimization, when all things equal always use the fastest method. (also note that <code>%</code> has lower precedence than <code>+</code> so requires the <code>()</code></p>\n<p>Using <code>Math.min</code> and <code>Math.max</code></p>\n<pre><code>"use strict";\n// Renamed interval to set\nfunction findCoveringInterval(sets) { // finds smallest \n var i = 0, min = sets[i][0], max = min;\n while (++i < sets.length) { // must be ++i not i++\n const set = sets[i], lowIdx = set[0] < set[1] ? 0 : 1;\n max = Math.max(set[lowIdx], max); \n min = Math.min(set[lowIdx + 1 & 1], min);\n }\n return [max, min];\n}\n</code></pre>\n<p>I prefer using ternary min max because <code>Math.min/max</code> has additional overhead checking against the length of its argument array. However this makes the function longer so it counts as a micro optimization. (I would need to test performances as I add JS complexity competing against native complexity)</p>\n<pre><code>"use strict";\nfunction findCoveringInterval(sets) {\n var i = 0, min = sets[i][0], max = min;\n while (++i < sets.length) {\n const set = sets[i];\n let idx = set[0] < set[1] ? 0 : 1;\n max = set[idx] > max ? set[idx++] : (idx++, max); \n min = set[idx &= 1] < min ? set[first] : min;\n }\n return [max, min];\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T20:50:01.150",
"Id": "414200",
"Score": "0",
"body": "I only skimmed through but the stuff you are writing is gold. Especially about how to deal it within a team"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T20:38:07.733",
"Id": "214192",
"ParentId": "214106",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "214192",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T10:03:59.327",
"Id": "214106",
"Score": "3",
"Tags": [
"javascript",
"algorithm",
"programming-challenge",
"functional-programming",
"ecmascript-6"
],
"Title": "Given a set of closed intervals, find the smallest set of numbers that covers all the intervals"
} | 214106 |
<p>I have written a random-walk routine that I hope to build upon in the future. Before doing so, I was hoping to get some critique.</p>
<p>I believe the implementation is correct. I noticed that many other implementations found online use for-loops or modules I am unfamiliar with;
my goal was to vectorize the walk in n-dimensional space with the optional use of boundary conditions.</p>
<p>The main idea is to generate an n-dimensional array of random numbers according to the desired distribution. As of now, only the 'normal' distribution is implemented. If a threshold is not set, then the average of the distribution is used as a threshold. Numbers greater than this threshold are taken in the positive direction, whereas numbers less than this threshold are taken in the negative direction. Should the number exactly equal this threshold, then no step is taken. The initial steps array (called <code>base</code> initially consists of all zeros; the indices corresponding to the positive and negative steps are used to mask this array with the respective step vectors (magnitude and direction).</p>
<p>If <code>edge_type</code> is not None, then the boundary conditions corresponding to <code>edge_type</code> will be used. If <code>edge_type='bounded'</code>, then the steps at the boundaries will be zero. If <code>edge_type='pacman'</code>, then the steps at the boundaries will be of magnitude <code>max_edge - min_edge</code> and taken to be in the direction away from the respective edge.</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
class IndicialDistributions():
"""
Steps are taken in a positive or negative direction according
to a random number distribution. The methods of this class
return the indices for positive and negative steps given
a distribution type.
As of now, only the 'normal' distribution type is implemented.
"""
def __init__(self, nshape):
"""
nshape : type <int / tuple / array>
"""
self.nshape = nshape
def get_normal_indices(self, mu, sigma, threshold=None):
"""
mu : type <int / float>
sigma : type <int / float>
threshold : type <int / float> or None
"""
if threshold is None:
threshold = mu
random_values = np.random.normal(mu, sigma, size=self.nshape)
pos = (random_values > threshold)
neg = (random_values < threshold)
return pos, neg
def get_binomial_indices(self, p_success, threshold=None):
"""
p_success : type <float>
threshold : type <int / float> or None
"""
raise ValueError("not yet implemented")
@property
def indicial_function_mapping(self):
res = {}
res['normal'] = self.get_normal_indices
res['binomial'] = self.get_binomial_indices
return res
def dispatch_indices(self, distribution, **kwargs):
"""
distribution : type <str>
"""
available_keys = list(self.indicial_function_mapping.keys())
if distribution not in available_keys:
raise ValueError("unknown distribution: {}; available distributions: {}".format(distribution, available_keys))
f = self.indicial_function_mapping[distribution]
pos, neg = f(**kwargs)
return pos, neg
class BoundaryConditions():
"""
The methods of this class account for steps taken at the
n-dimensional edges.
As of now, 'bounded' and 'pacman' edges are implemented.
"""
def __init__(self, steps, movements, max_edge, min_edge):
"""
steps : type <array>
movements : type <array>
max_edge : type <int / float>
min_edge : type <int / float>
"""
self.steps = steps
self.movements = movements
self.max_edge = max_edge
self.min_edge = min_edge
def get_maximum_edge_indices(self):
indices = (self.movements >= self.max_edge)
return indices
def get_minimum_edge_indices(self):
indices = (self.movements <= self.min_edge)
return indices
def apply_maximum_bounded_edge(self):
indices = self.get_maximum_edge_indices()
self.steps[indices] = 0
def apply_minimum_bounded_edge(self):
indices = self.get_minimum_edge_indices()
self.steps[indices] = 0
def apply_pacman_edges(self):
max_indices = self.get_maximum_edge_indices()
min_indices = self.get_minimum_edge_indices()
self.steps[max_indices] = self.min_edge - self.max_edge
self.steps[min_indices] = self.max_edge - self.min_edge
def apply_to_dimension(self, edge_type):
"""
edge_type : type <str>
"""
if edge_type is not None:
if edge_type == 'bounded':
self.apply_maximum_bounded_edge()
self.apply_minimum_bounded_edge()
elif edge_type == 'pacman':
self.apply_pacman_edges()
else:
raise ValueError("unknown edge_type: {}; available edge_type = 'bounded', 'pacman', or None".format(edge_type))
class CartesianRandomWalker():
"""
This class has methods to perform a random walk in n-dimensional space
with the optional use of boundary conditions.
"""
def __init__(self, initial_position, nsteps, edge_type=None, max_edges=(), min_edges=()):
"""
initial_position : type <tuple / list / array>
nsteps : type <int>
edge_type : type <str>
max_edges : type <tuple / list / array>
min_edges : type <tuple / list / array>
"""
self.initial_position = initial_position
self.nsteps = nsteps
self.edge_type = edge_type
self.max_edges = max_edges
self.min_edges = min_edges
self.ndim = len(initial_position)
self.nshape = (self.ndim, nsteps)
self.base = np.zeros(self.nshape).astype(int)
# self.boundary_crossings = 0
self.current_position = np.array(initial_position)
def __repr__(self):
if np.all(self.base == 0):
string = 'Initial Position:\t{}'.format(self.initial_position)
else:
string = 'Initial Position:\t{}\nNumber of Steps:\t{}\nCurrent Position:\t{}'.format(self.initial_position, self.nsteps, self.current_position)
return string
@property
def position(self):
return tuple(self.current_position)
@property
def movement(self):
return np.cumsum(self.base, axis=1)
def initialize_steps(self, distribution, delta_steps, **kwargs):
"""
distribution : type <str>
delta_steps : type <tuple / list / array>
"""
pos, neg = IndicialDistributions(self.nshape).dispatch_indices(distribution, **kwargs)
self.base[pos] = delta_steps[0]
self.base[neg] = delta_steps[1]
def apply_boundary_conditions(self):
if self.edge_type is not None:
for idx in range(self.ndim):
max_edge, min_edge = self.max_edges[idx], self.min_edges[idx]
steps = self.base[idx]
movements = self.movement[idx] + self.initial_position[idx]
BC = BoundaryConditions(steps, movements, max_edge, min_edge)
BC.apply_to_dimension(self.edge_type)
self.base[idx, :] = BC.steps
def update_positions(self, distribution, delta_steps=(1, -1), **kwargs):
"""
distribution : type <str>
delta_steps : type <tuple / list / array>
"""
self.initialize_steps(distribution, delta_steps, **kwargs)
self.apply_boundary_conditions()
delta_position = self.movement[:, -1]
self.current_position += delta_position
def view(self, ticksize=7, labelsize=8, titlesize=10):
"""
ticksize : type <int>
labelsize : type <int>
titlesize : type <int>
"""
if self.ndim == 1:
raise ValueError("not yet implemented")
elif self.ndim == 2:
fig, ax = plt.subplots()
x_movement = self.movement[0] + self.initial_position[0]
y_movement = self.movement[1] + self.initial_position[1]
ax.scatter(*self.initial_position, color='k', label='Initial Position', marker='x', s=100)
ax.scatter(*self.current_position, color='k', label='Current Position', marker='.', s=100)
ax.plot(x_movement, y_movement, color='r', alpha=1/3, label='Random Walk')
ax.grid(color='k', linestyle=':', alpha=0.3)
ax.set_xlabel('X', fontsize=labelsize)
ax.set_ylabel('Y', fontsize=labelsize)
ax.tick_params(axis='both', labelsize=ticksize)
if self.edge_type is None:
title = r'${}-$D Random Walk in Cartesian Space'.format(self.ndim)
elif self.edge_type in ('bounded', 'pacman'):
title = '${}-$D Random Walk in Cartesian Space\nvia {} Boundary Conditions'.format(self.ndim, self.edge_type.title())
ax.set_title(title, fontsize=titlesize)
plt.subplots_adjust(bottom=0.2)
fig.legend(loc='lower center', mode='expand', fancybox=True, ncol=3, fontsize=labelsize)
plt.show()
plt.close(fig)
elif self.ndim == 3:
raise ValueError("not yet implemented")
else:
raise ValueError("invalid ndim: {}; can only view 1 <= ndim <= 3".format(self.ndim))
</code></pre>
<p>As of now, only the 2-dimensional case is viewable. I can implement something similar for the 1-dimensional and 3-dimensional cases, but I am more concerned with the methods rather than the graph (for now). That said, one can run this algorithm in 10-dimensional space without the graph.</p>
<p>Here is an example call:</p>
<pre><code>np.random.seed(327) ## reproduce random results
## initial position
# pos = (50, 50, 50, 50, 50, 50, 50, 50, 50, 50) ## 10-D
pos = (50, 50) ## 2-D
## number of steps to travel
nsteps = 100
## random number distribution
## average = 50, spread=10
## positive step if random number > 50
## negative step if random number < 50
## no step if random number = 0
distribution = 'normal'
kwargs = {'mu' : 50, 'sigma' : 10} # 'threshold' : 50}
## boundary conditions
max_edges = np.array([60 for element in pos])
min_edges = np.array([40 for element in pos])
edge_type = None
# edge_type = 'pacman'
# edge_type = 'bounded'
RW = CartesianRandomWalker(pos, nsteps, edge_type, max_edges, min_edges)
RW.update_positions(distribution, **kwargs)
print(RW)
RW.view()
</code></pre>
<p>Here is an example output from the 2-D case:</p>
<pre class="lang-none prettyprint-override"><code>Initial Position: (50, 50)
Number of Steps: 100
Current Position: [36 58]
</code></pre>
<p><a href="https://i.stack.imgur.com/ElAz1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ElAz1.png" alt="Random Walk in 2-D"></a></p>
<p>And here is an output from the 10-D case:</p>
<pre class="lang-none prettyprint-override"><code>Initial Position: (50, 50, 50, 50, 50, 50, 50, 50, 50, 50)
Number of Steps: 100
Current Position: [36 58 52 58 38 58 42 78 28 48]
</code></pre>
| [] | [
{
"body": "<p>As a first comment, instead of specifying your types in the comments of each method, you can use the typing module for Python 3.5 and above <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">https://docs.python.org/3/library/typing.html</a> Also, I think the comments on variables should also describe what they represent.</p>\n<p>Then, if I were you, I wouldn't try creating a very generic code, it usually leads to unnecessary over-engineering and more complex code to maintain. If you need more things, then you'll adapt your code to it as soon as you need. You usually first make it work with your new needs anyhow and then try to refactor it to make it better.</p>\n<p>However, I'll try to give my point of view of how I'd change your code so it can be adapted more easily to what you said about multiple distributions.</p>\n<h2><code>IndicalDistributions</code></h2>\n<p>The <code>get_normal_indices</code> and the <code>get_binomial_indices</code> functions don't really belong to this class. <code>IndicalDistributions</code> should not know about all the possible distributions there can be. And you should definitely not store a dictionary with all of them in here, it leads to very messy and hard to maintain code.</p>\n<ul>\n<li>I think the easiest way to fix this, is to have separate implementations for each kind of distribution and choose the class when needed in your code, so you would end up removing <code>IndicalDistributions</code> and having something like <code>NormalIndicalDistribution</code> and <code>BinomialIndicalDistribution</code> classes separately. When you'll have to create <code>BinomialIndicalDistribution</code>, you'll see what are the common parts of <code>NormalIndicalDistribution</code> and <code>BinomialIndicalDistribution</code>, and create some kind of abstraction to do the common stuff (maybe strategy or template method pattern).</li>\n</ul>\n<p>If you want to specify strings to choose the correct distribution class like you do in <code>dispatch_indices</code>, you can just have a function <code>create_indical_distribution(distribution, **kwargs)</code> that's just a bunch of ifs that return the correct object constructed. This is usually called a factory method.</p>\n<p>But again, for now just create one <code>NormalIndicalDistribution</code> class and then you'll see what happens when you need the binomial one.</p>\n<h2><code>BoundaryConditions</code></h2>\n<p>You said nothing about having multiple edge types apart from these 2, so I would not touch this and if I would, the approach would be similar to the class before.</p>\n<h2><code>CartesianRandomWalker</code></h2>\n<p><code>self.base</code> is a reserved name for the Python language, name it something else, it can give you very weird bugs.</p>\n<p>In <code>view</code>, I think it'd be cleaner if you'd do something like</p>\n<pre class=\"lang-py prettyprint-override\"><code>if self.ndim not in (1, 2, 3):\n raise ValueError(f"invalid ndim: {self.ndim}; can only view 1 <= ndim <= 3")\nif self.ndim in (1, 2):\n raise ValueError("not yet implemented")\n\n# Your implementation goes here \n</code></pre>\n<p>However, I think the implementation for each dimension should go to a separate class and maybe have some common utilities for each dimension, it'd be much easier to maintain. Similar approach to what I explained before.</p>\n<p>Usually, instantiating classes in the middle of other classes is not a very good idea, the objects should be passed in <code>__init__</code> (I mean <code>IndicalDistributions</code> and <code>BoundaryConditions</code>). They should be constructed before and passed to <code>CartesianRandomWalker</code>, this will let you use more kinds of indical distributions and edge types, since you just pass whichever you want in the construction and that's it.</p>\n<ul>\n<li><p>For <code>IndicalDistributions</code>, it should be no problem, just remove the distribution string and pass the correct object when constructing.</p>\n</li>\n<li><p>However, the <code>BoundaryConditions</code> object depends on parameters that you can only know in <code>apply_boundary_conditions</code>. This is a bit tricky. Honestly, since you didn't say anything about having more than these two edge types, I'd leave as is, otherwise, look up Builder Pattern.</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T15:14:57.910",
"Id": "214172",
"ParentId": "214108",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "214172",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T10:57:04.523",
"Id": "214108",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"random",
"numpy",
"vectorization"
],
"Title": "Vectorized N-Dimensional Random Walk in Cartesian Coordinates"
} | 214108 |
<p>I'm writing a Python Script for a Raspberry Pi to measure different sensors. We are planning to send the Pi with that Script running to the stratosphere, so the power usage for the Pi is limited.</p>
<p>I excuse myself in advance for the code, I had no prior experience with Python.
Are there any ways I can make this code more battery friendly? Would it be beneficial to write 10 rows at once instead of writing one row at a time?</p>
<pre><code>#!/usr/bin/env python3
from sense_hat import SenseHat
import time
import csv
import datetime
sense = SenseHat()
sense.clear()
sense.set_imu_config(True, True, True)
sense.low_light = True
with open('data.csv', mode='w') as file:
writer = csv.writer(file, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer.writerow(['Zeit','Temperatur1', 'Temperatur2', 'Temperatur3', 'Luftdruck', 'Luftfeuchtigkeit', 'Yaw', 'Pitch', 'Roll', 'Compass X', 'Compass Y', 'Compass Z', 'Gyro X', 'Gyro Y', 'Gyro Z'])
with open('acc.csv', mode='w') as file:
writer = csv.writer(file, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer.writerow(['Zeit','Acc_X','Acc_Y','Acc_Z'])
with open('log.csv', mode='w') as file:
writer = csv.writer(file, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer.writerow(['Zeit','Fehler'])
# Farben definieren
red = (255, 0, 0)
green = (0, 255, 0)
black = (0,0,0)
def writeDataToCsv(temperature, temperature2, temperature3, pressure, humidty, yaw, pitch, roll, mag_x, mag_y, mag_z, gyro_x, gyro_y, gyro_z):
with open('data.csv', mode='a') as file:
writer = csv.writer(file, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer.writerow([datetime.datetime.now(),temperature, temperature2, temperature3, pressure, humidty, yaw, pitch, roll, mag_x, mag_y, mag_z, gyro_x, gyro_y, gyro_z])
def writeAccelerationToCsv(x,y,z):
with open('acc.csv', mode='a') as file:
writer = csv.writer(file, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer.writerow([datetime.datetime.now(),x,y,z])
sense.set_pixel(0, 0, green)
time.sleep(.05)
sense.set_pixel(0, 0, black)
def main():
sense.set_pixel(0, 0, black)
counter = 0
try:
while True:
#Region Acceleration
acceleration = sense.get_accelerometer_raw()
acc_x = acceleration['x']
acc_y = acceleration['y']
acc_z = acceleration['z']
writeAccelerationToCsv(acc_x,acc_y,acc_z)
time.sleep(.250)
counter+=1
#Region Data
if(counter == 4):
temperature = sense.get_temperature()
temperature2 = sense.get_temperature_from_humidity()
temperature3 = sense.get_temperature_from_pressure()
pressure = sense.get_pressure()
humidty = sense.get_humidity()
orientation = sense.get_orientation()
yaw = orientation["yaw"]
pitch = orientation["pitch"]
roll = orientation["roll"]
mag = sense.get_compass_raw()
mag_x = mag["x"]
mag_y = mag["y"]
mag_z = mag["z"]
gyro = sense.get_gyroscope_raw()
gyro_x = gyro["x"]
gyro_y = gyro["y"]
gyro_z = gyro["z"]
writeDataToCsv(temperature, temperature2, temperature3, pressure, humidty, yaw, pitch, roll, mag_x, mag_y, mag_z, gyro_x, gyro_y, gyro_z)
counter = 0;
except Exception as e:
with open('log.csv', mode='a') as file:
writer = csv.writer(file, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer.writerow([datetime.datetime.now(),str(e)])
sense.set_pixel(1, 0, red)
finally:
pass
main()
if __name__ == '__main__':
main()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T05:31:27.737",
"Id": "414129",
"Score": "8",
"body": "The Pi uses quite a lot of power, with only a little of it going to the CPU, so you can't make much of a difference in the code there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T08:27:23.987",
"Id": "414145",
"Score": "2",
"body": "Is there a reason you can't use a lower power device, equip a bigger battery, or use solar panels?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T15:05:56.247",
"Id": "414290",
"Score": "0",
"body": "@forest I havent thought about the solar panels yet, but the weight is probably the biggest limitation for us. We only have a limited size for the balloon and this limits the weight. We decided to use the raspberry as its a cheap and easy to use device. Noone of our team has the knowledge to do this with for example an ardiuno."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-27T09:08:04.167",
"Id": "414562",
"Score": "1",
"body": "Pick a tool suitable for the task. Pi and Arduino are hobbyist boards, unsuitable for pretty much anything beyond tinkering in your free time. Where the former draws quite a bit of current, 100-200mA at least, not counting LEDs etc. This doesn't look like something that needs tons of processing power, so a Cortex M0 would be ideal. I would advise to hire professionals for this job, as no amount of optimization in Python will change the hardware you have picked. If none of your team has any knowledge of embedded systems, then the project is pretty much doomed to fail."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-27T10:38:59.203",
"Id": "414578",
"Score": "1",
"body": "@Lundin Well it's a school project, so we are quite limited by time and money. It's more a proof of concept to see if that would work."
}
] | [
{
"body": "<ul>\n<li><p>Do not call <code>main</code> recursively. You are setting yourself up for stack overflow. Consider instead</p>\n\n<pre><code>def main():\n while True:\n try:\n your_logic_here\n except Exception as e:\n your_logging_here\n</code></pre></li>\n<li><p>Testing for <code>counter == 4</code> is better done in a loop:</p>\n\n<pre><code> for _ in range(4):\n handle_acceleration\n handle_the_rest\n</code></pre></li>\n<li><p>An unattended controller should handle exceptions more diligently. For sure, you want to act differently for the exceptions raised by <code>sense</code> (if any) vs exceptions raised by writing to the file.</p></li>\n<li><p>Regarding battery, avoid binary-to-text conversions. Store your data as binary, and convert them to CSV offline, after the Pi safely returns.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T07:34:39.937",
"Id": "414248",
"Score": "0",
"body": "`> Testing for counter == 4 is better done in a loop`\nWhy exactly is this true?\n\nIt'll save 4 check statements? Wouldn't that equate to a while inside a while now?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T07:40:08.673",
"Id": "414249",
"Score": "0",
"body": "@insidesin Few reasons. 1) Looks better 2) Less total indentation 3) Expresses intention better 4) One failing test versus 3 per four iterations"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T08:00:36.310",
"Id": "414250",
"Score": "0",
"body": "Those are all subjective, it also increases indentation if I can see correctly. If the testing is improved then it would make sense."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T08:25:46.750",
"Id": "414252",
"Score": "0",
"body": "@vnp I also agree with 3), plus it also assures the execution of `handle_the_reast`, after 4 acceleration logs (not regarding possible exceptions). Can you explain what you mean with 4)? Are you talking about unit tests or do you mean the equality checks?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T17:58:20.290",
"Id": "214127",
"ParentId": "214112",
"Score": "17"
}
},
{
"body": "<p>Have you already executed the code to see how it performs and if the battery will last? There is that <a href=\"https://en.wikiquote.org/wiki/Donald_Knuth#Computer_Programming_as_an_Art_(1974)\" rel=\"noreferrer\">famous Donald Knuth</a> quote saying <em>premature optimization is the root of all evil (or at least most of it) in programming</em>.</p>\n\n<p>I never had to think about the energy consumption of a program, so I cannot tell you about the power efficieny. But as vnp already did, I can also share my opinion about the code structure to help you to identify bottlenecks more easily. Also, a different structure should help you to still log some data even in case of exceptions.</p>\n\n<p>Here is what struck me on first read:</p>\n\n<ul>\n<li>most of the code is defined in the main method</li>\n<li>you overwrite the complete data files at the beginning of the program</li>\n<li>very broad exception clause</li>\n<li>repetition of the csv write (violates the zen of python - not dry - <em>dont repeat yourself</em>)</li>\n</ul>\n\n<p>I tried to resolve some of the issues and refactored the structure of the code:</p>\n\n<pre><code>#!/usr/bin/env python3\n\nfrom sense_hat import SenseHat\nimport time \nimport csv\nimport datetime\n\n# defined constants on moduel level and capitalized the names (pep8: https://www.python.org/dev/peps/pep-0008/#constants)\nRED = (255, 0, 0)\nGREEN = (0, 255, 0)\nBLACK = (0,0,0)\n\n\nclass DataLogger(object):\n\n def __init__(self, init_csv_files=False):\n # initalize the commonly ued sensor\n self.sense = SenseHat()\n self.sense.clear()\n self.sense.set_imu_config(True, True, True)\n self.sense.low_light = True\n\n # only initialize the csv files, if intended\n # I would suggest not to init them in the same program though.\n # If - for some reasons - the python interpreter crashes and the script is restarted,\n # the init of the csv_files will overwrite all the data which was logged so far.\n if init_csv_files:\n self.init_csv_files()\n\n def write_data_to_file(self, data, file_name, mode='a', delimiter=';', quotechar='\"', quoting=csv.QUOTE_MINIMAL):\n \"\"\"\n Helper method to write the given data to a csv file. Using 'append' as default mode to avoid accidental overwrites.\n \"\"\"\n with open(file_name, mode=mode) as file:\n writer = csv.writer(file, delimiter=delimiter, quotechar=quotechar, quoting=quoting)\n writer.writerow(data)\n\n def init_csv_files(self):\n # see comment in init method\n data_headings = ['Zeit','Temperatur1', 'Temperatur2', 'Temperatur3', 'Luftdruck', 'Luftfeuchtigkeit', 'Yaw', 'Pitch', 'Roll', 'Compass X', 'Compass Y', 'Compass Z', 'Gyro X', 'Gyro Y', 'Gyro Z']\n self.write_data_to_file(data_headings, 'data.csv', 'w')\n\n acc_headings = ['Zeit','Acc_X','Acc_Y','Acc_Z']\n self.write_data_to_file(acc_headings, 'acc.csv', 'w')\n\n log_headings = ['Zeit','Fehler']\n self.write_data_to_file(log_headings, 'log.csv', 'w') \n\n def start_logging(self):\n # actual execution\n sense.set_pixel(0, 0, BLACK)\n counter = 0\n\n while True:\n # moved the accelleration logging to a different method\n # and catched possible exceptions there, so the counter will still be increase\n # and the rest of the data may still be logged even if the accelleration data\n # always raises exceptions\n self.log_accelleration()\n time.sleep(.250)\n counter += 1\n\n # using counter % 4 == 0 instead of counter == 4\n # this will evaluate to true for every number divisible by 4\n # If you do the strict comparision, you could find yourself in the scenario\n # where the data logging is never executed, if the counter is larger than 4\n # (in this case this is very unlikely, but in threaded scenarios it would be possible,\n # so doing modulo 4 is more defensive)\n if(counter % 4 == 0):\n self.log_data()\n counter = 0\n\n def log_accelleration(self):\n acceleration_data = get_accelleration()\n if acceleration_data:\n try:\n self.write_data_to_file(acceleration_data, 'acc.csv')\n except Exception as e:\n self.log_exception(e)\n pass\n else:\n # no exception occurred\n self.sense.set_pixel(0, 0, green)\n time.sleep(.05)\n finally:\n self.sense.set_pixel(0, 0, black)\n\n def log_data(self):\n # saving datetime first, before reading all the sensor data\n data = [datetime.datetime.now()]\n\n # moved each of the calls to sense in a separate method\n # exceptions will lead to empty entries being logged but\n # if e.g. get_pressure raises an exceptions, the other data may still get logged \n data += self.get_temperature()\n data += self.get_pressure()\n data += self.get_humidity()\n data += self.get_orientation()\n data += self.get_mag()\n data += self.get_gyro()\n\n self.write_data_to_file(data, 'data.csv')\n\n def log_exception(self, exception):\n sense.set_pixel(1, 0, red)\n self.write_data_to_file([datetime.datetime.now(), str(exception)], 'log.csv')\n sense.set_pixel(0, 0, black)\n\n def get_accelleration(self):\n try: \n acceleration = self.sense.get_accelerometer_raw()\n except Exception as e:\n self.log_exception(e)\n return\n\n acc_x = acceleration['x']\n acc_y = acceleration['y']\n acc_z = acceleration['z']\n\n return[datetime.datetime.now(), acc_x, acc_y, acc_z]\n\n def get_temperature(self):\n try:\n temperature1 = sense.get_temperature()\n temperature2 = sense.get_temperature_from_humidity()\n temperature3 = sense.get_temperature_from_pressure()\n except Exception as e:\n return [None, None, None]\n return [temperature1, temperature2, temperature3]\n\n def get_pressure(self):\n try:\n pressure = sense.get_pressure()\n except Exception as e:\n return [None]\n return [pressure]\n\n def get_humidity(self):\n try:\n humidty = sense.get_humidity()\n except Exception as e:\n return [None]\n return [humidty]\n\n def get_orientation(self): \n try:\n orientation = sense.get_orientation()\n except Exception as e:\n return [None, None, None]\n return [orientation[\"yaw\"], orientation[\"pitch\"], orientation[\"roll\"]]\n\n def get_mag(self):\n try:\n mag = sense.get_compass_raw()\n except Exception as e:\n return [None, None, None]\n return [mag[\"x\"], mag[\"y\"], mag[\"z\"]]\n\n def get_gyro(self):\n try:\n gyro = sense.get_gyroscope_raw()\n except Exception as e:\n return [None, None, None]\n return [gyro[\"x\"], gyro[\"y\"], gyro[\"z\"]]\n\n\nif __name__ == '__main__':\n data_logger = DataLogger(init_csv_files=True)\n try:\n data_logger.start_logging()\n except Exception as e:\n data_logger.log_exception(e)\n</code></pre>\n\n<p>Further steps for improvements:</p>\n\n<ul>\n<li>Catch specific exceptions (e.g. IOErrors in the write csv, or SenseHat specific exceptions</li>\n<li>Log exceptions (where needed) and return different defaults in cases of error</li>\n<li>Refactor the write to - as you suggested - log the data in memory and only write every 10th entry to the csv. Attention: If you only log every 10th or even every 100th data entry and the python interpreter crashes, the recently logged data will be lost</li>\n<li>Don't write the csv headers in code, but manually prepare the csv files and put them next to the script</li>\n<li>Use a sqlite database and log the data here instead of in CSVs</li>\n</ul>\n\n<p>In order to figure out where to start with the optimizations, you can now profile the helper methods (<code>write_data_to_file</code>, <code>get_temperature</code> and the other <code>get_...</code> methods) and derive appropriate measurements to take.</p>\n\n<p>PS. Fair warning: I never executed the code in a python shell, so it may not be free from bugs :see_no_evil:.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T20:01:04.290",
"Id": "414187",
"Score": "2",
"body": "In particular, batteries tend to perform poorly when cold, and need to be tested specifically for that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T15:09:27.920",
"Id": "414292",
"Score": "0",
"body": "@200_success I haven't thought about that but we will put the battery in a styrofoam box to insulate it from the outside."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T15:11:17.410",
"Id": "414293",
"Score": "0",
"body": "@Kim Thank you very much for your detailed answer. I would have done something like this if I knew how to do it. You certainly helped a lot (For our project and for my python skills.)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T21:20:33.803",
"Id": "214134",
"ParentId": "214112",
"Score": "11"
}
},
{
"body": "<p>Opening and closing files takes resources:</p>\n\n<pre><code>with open('babar.txt', 'a') as f: f.write('a'*10000)\n</code></pre>\n\n<p>takes 300 micro-seconds while:</p>\n\n<pre><code>for _ in range(10000):\n with open('babar.txt', 'a') as f: f.write('a')\n</code></pre>\n\n<p>takes 648000 micro-seconds</p>\n\n<p>So to answer your question <strong><code>Would it be beneficial to write 10 rows at once instead of writing one row at a time?</code></strong>. The answer, as always is <strong>YES, but...</strong></p>\n\n<p>You shouldn't implement a buffer yourself instead use the third argument of <code>open</code>:</p>\n\n<pre><code>f = open('babar.txt', 'a', 500)\nfor _ in range(10000):\n f.write('a')\nf.close()\n# takes 2200 micro-seconds for a 500 buffer \n# and 3660 micro-seconds for a 50 buffer\n</code></pre>\n\n<p>It is the buffer-size (4096 chars by default I think). Put the <code>close()</code> in a <code>finally</code> block to avoid corruption of your files.</p>\n\n<p>I think less opening and closing would take a lot less resources but implementing a buffer yourself is less safe then letting the built-in function handle it for you. <strong>Beware of the risks you take</strong>, not writing data mean your data is lost if power goes down, and as you can see dividing the buffer by 10 doesn't necessarily mean it takes 10x more resources.</p>\n\n<p><em>note: battery consumption is hard to measure and is not directly related to cpu time.</em></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T22:39:48.670",
"Id": "214139",
"ParentId": "214112",
"Score": "8"
}
},
{
"body": "<p>For a system that will be in stratosphere, you dont need any color or light mechanism. Get rid of all code about visualisation, e.g. Setting colors or setting light value. That way light also wont consume your battery. Once your code is cleared, apply other answers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T20:34:00.093",
"Id": "414197",
"Score": "0",
"body": "Absolutely. And do the same with the hardware. Go for the bare minimum, there are stripped versions of the Raspberry Pi available."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T15:07:41.210",
"Id": "414291",
"Score": "0",
"body": "Thanks for the input. I'll reduce it but probably still keep some small visualisation, as the last thing I want to happen is that the balloon takes off with the raspberry not meassuring anything and us not realizing this."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T16:19:12.237",
"Id": "214178",
"ParentId": "214112",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "214134",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T12:24:34.563",
"Id": "214112",
"Score": "17",
"Tags": [
"python",
"csv",
"logging",
"embedded",
"raspberry-pi"
],
"Title": "Sensor logger for Raspberry Pi in a stratospheric probe"
} | 214112 |
<p>I'm writing web application that uses <a href="https://developers.google.com/beacons/proximity/guides" rel="nofollow noreferrer">Google Proximity Beacon API</a> to interact with beacon data. In order to access that data, I need to grant access to use beacons' information for my web application with my Google account. When my app is authorized, it receives credentials needed to call desired API. Because I don't want to call for these credentials each time I need to call API, I've created SQLAlchemy models for storing them.</p>
<pre class="lang-py prettyprint-override"><code>scopes_m2m = db.Table(
'scopes',
db.Column(
'scope_id',
db.Integer,
db.ForeignKey('oauth2_scopes.id'),
primary_key=True),
db.Column(
'credential_id',
db.Integer,
db.ForeignKey('oauth2_credentials.id'),
primary_key=True),
)
class OAuth2Scope(db.Model):
'''
Google OAuth2 scope for resource
'''
__tablename__ = 'oauth2_scopes'
id = db.Column(db.Integer, primary_key=True)
scope = db.Column(db.String(100), unique=True, nullable=False)
@classmethod
def from_scope(cls, scope):
''' Create OAuth2Scope model object if not exists
:param scope: str - scope name
:return: OAuth2Scope object
'''
scopes = {row.scope: row for row in cls.query.all()}
if not scope in scopes.keys():
return cls(scope=scope)
return scopes[scope]
class OAuth2Credential(db.Model):
'''
Google OAuth2 credentials for accessing Proximity Beacon API
'''
__tablename__ = 'oauth2_credentials'
id = db.Column(db.Integer, primary_key=True)
token_uri = db.Column(db.String(100), nullable=False)
client_id = db.Column(db.String(100), unique=True, nullable=False)
client_secret = db.Column(db.String(100), nullable=False)
token = db.Column(db.String(250), nullable=False)
refresh_token = db.Column(db.String(250), nullable=True)
scopes = db.relationship(
'OAuth2Scope',
secondary=scopes_m2m,
backref=db.backref('credentials', lazy=True),
lazy='subquery')
@classmethod
def from_creds(cls, credentials):
''' Create model object from google.oauth2.credentials.Credentials
:param credentials: google.oauth2.credentials.Credentials object
:return: OAuth2Credential object
'''
client_id = credentials.client_id
scopes = credentials.scopes
token = credentials.token
refresh_token = credentials.refresh_token
client_secret = credentials.client_secret
token_uri = credentials.token_uri
oauth2_credential = OAuth2Credential.query.filter_by(
client_id=client_id).first()
oauth2_scopes = [OAuth2Scope.from_scope(scope) for scope in scopes]
if not oauth2_credential:
oauth2_credential = OAuth2Credential(
client_id=client_id,
token_uri=credentials.token_uri,
client_secret=credentials.client_secret,
token=credentials.token,
refresh_token=credentials.refresh_token)
for oauth2_scope in oauth2_scopes:
oauth2_credential.scopes.append(oauth2_scope)
else:
oauth2_credential.token_uri = token_uri
oauth2_credential.token = token
oauth2_credential.refresh_token = refresh_token
oauth2_credential.client_secret = client_secret
for oauth2_scope in oauth2_scopes:
if oauth2_scope in oauth2_credential.scopes:
oauth2_credential.scopes.append(oauth2_scope)
return oauth2_credential
def get_creds(self):
''' Get google.oauth2.credentials.Credentials object
from model's object
:return: google.oauth2.credentials.Credentials object
'''
data = {
'token_uri': self.token_uri,
'client_id': self.client_id,
'client_secret': self.client_secret,
'token': self.token,
'refresh_token': self.refresh_token,
'scopes': [s.scope for s in self.scopes]
}
return Credentials(**data)
def to_dict(self):
return {
'token_uri': self.token_uri,
'client_id': self.client_id,
'client_secret': self.client_secret,
'token': self.token,
'refresh_token': self.refresh_token,
'scopes': [s.scope for s in self.scopes]
}
</code></pre>
<p>It's important to note that each credential stores list of scopes that are links to particular API that my app has granted access to. Because many scopes can be used by many credentials, I've created many-to-many relationship between my scope <code>OAuth2Scope</code> model and <code>OAuth2Credential</code> model. To create new instance of OAuth2 credentials I call <code>from_creds</code> class method of OAuth2Credential` and here is the place where thinks look a little bit complicated:</p>
<ul>
<li>First, I'm verifying if credentials already exist in db:</li>
</ul>
<pre class="lang-py prettyprint-override"><code>oauth2_credential = OAuth2Credential.query.filter_by(
client_id=client_id).first()
</code></pre>
<ul>
<li>Then I create list of scope objects based from scopes list provided by <code>Credentials</code> object. </li>
<li>If there is credential with provided <code>client_id</code> than I update them (in case there are some changes, for example new scopes are added) if not then I create new <code>OAuth2Credential</code> instance.</li>
</ul>
<p>For me this code looks too complicated because it requires querying data too often which will cause performance issues in the future. </p>
<p>Any suggestions what can be improved here?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T14:49:46.333",
"Id": "214118",
"Score": "2",
"Tags": [
"python",
"performance",
"python-3.x",
"authentication",
"sqlalchemy"
],
"Title": "Saving OAuth2 credentials to database with SQLAlchemy"
} | 214118 |
<p>For self-study homework I made a Java program that takes user input, creates people as objects, and says "Happy Birthday" to each person.</p>
<p>I am just wondering what mistakes I made here or how it could have been better.</p>
<p><strong>PERSON CLASS</strong></p>
<pre><code>public class PeopleObjects{
// For practice, make the people objects rather than just a list of names.
private String name;
private String birthDay;
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setBirthDay(String myBirth){
birthDay = myBirth;
}
public String getBirthDay(){
return birthDay;
}
}
</code></pre>
<p><strong>MAIN</strong></p>
<pre><code>import java.util.Scanner;
import java.util.ArrayList;
public class PeopleObjectsTestDrive{
public static void main(String [] args){
ArrayList<PeopleObjects> listOfPeopleObjects = new ArrayList<PeopleObjects>();
Scanner input = new Scanner(System.in);
int userChoice = 0;
System.out.println("Enter any number other than 1 to start program."+"\n");
while ((userChoice = input.nextInt()) != 1){
PeopleObjects people = new PeopleObjects();
System.out.println("\n###What is the name of the person?###\n");
input.nextLine();//for some reason we have to use this twice to avoid bug
people.setName(input.nextLine());
System.out.println("\n###What is their birthday?###\n");
people.setBirthDay(input.nextLine());
listOfPeopleObjects.add(people);
System.out.println("\nDo you want to quit and see list? Enter 1 for yes and 0 for no\n");
}
System.out.println("\n\n\n\n");
for(int i=0; i < listOfPeopleObjects.size(); i++){
if(listOfPeopleObjects.get(i).getName().equals("Joe")){
System.out.println("Happy Birthday Joe! You are special! Your birthday is on "+listOfPeopleObjects.get(i).getBirthDay()+" \n");
}else if(i%2 == 0){
System.out.println("Happy Birthday to "+listOfPeopleObjects.get(i).getName()+".\n");
}else{
System.out.println("Happy Birthday to "+listOfPeopleObjects.get(i).getName()+" too!!!\n");
}//end if else
}//end for
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T17:11:04.300",
"Id": "414065",
"Score": "0",
"body": "Welcome to code review. This looks interesting to me. Hope you learn a lot here."
}
] | [
{
"body": "<p><code>PeopleObjects</code> is an odd name for a couple reasons:</p>\n\n<ul>\n<li>Both words are plural, even though each instance only represents a single person.</li>\n<li>Having \"object\" in the name is a little redundant. It's implied that the class is representing an object.</li>\n</ul>\n\n<p>I'd just call the class <code>Person</code>.</p>\n\n<p>And you didn't give <code>PeopleObjects</code> a constructor. You're constructing an instance of the class ahead of time, then asking for input and calling the <code>set</code>ters. What if you forgot to set the birthday or name? They would be left as <code>null</code> and potentially cause problems later. If properties are required (which both name and birthday would presumably be), have them supplied by a constructor:</p>\n\n<pre><code>public Person(String name, String birthDay) {\n this.name = name;\n this.birthDay = birthDay;\n}\n\n. . .\n\nList<Person> people = new ArrayList<Person>();\n\nScanner input = new Scanner(System.in);\n\nSystem.out.println(\"Enter any number other than 1 to start program.\"+\"\\n\");\n\nwhile (input.nextInt() != 1){\n // This is needed since nextInt doesn't consume the newline\n input.nextLine();\n\n System.out.println(\"\\n###What is the name of the person?###\\n\");\n String name = input.nextLine();\n\n System.out.println(\"\\n###What is their birthday?###\\n\");\n String birthday = input.nextLine();\n\n Person person = new Person(name, birthday);\n\n people.add(person);\n\n System.out.println(\"\\nDo you want to quit and see list? Enter 1 for yes and 0 for no\\n\");\n}\n</code></pre>\n\n<p>I changed a few things about that loop:</p>\n\n<ul>\n<li><p>As mentioned above, the person isn't constructed until the necessary data is already obtained, and the data is passed directly to the constructor.</p></li>\n<li><p><code>userChoice</code> was never used. It was just storing the users entry, but that choice was only ever used in the condition. If you really wanted it for debugging purposes, it may be appropriate, but I didn't think that it was necessary here.</p></li>\n<li><p>I renamed the list of people to simply <code>people</code>. This was replacing your <code>PeopleObjects people = new PeopleObjects();</code> line. Again, calling a single person <code>people</code> is confusing. I also changed the type of <code>people</code> to <code>List</code>, from <code>ArrayList</code>. Always use the broadest type possible. In this case, you don't need any operations specific to <code>ArrayList</code>; you're only using <code>List</code> methods. To see why this is important, give <a href=\"https://softwareengineering.stackexchange.com/questions/232359/understanding-programming-to-an-interface\">this</a> a read over. Note the example used in the question.</p></li>\n</ul>\n\n<hr>\n\n<p>Your other loop at the bottom is sub-optimal as well. First, you're constantly writing <code>people.get(i)</code>. For an <code>ArrayList</code>, <code>get</code> is very fast, but those calls are causing unneeded bloat. Create an intermediate variable <code>person</code> in the loop to neaten things up:</p>\n\n<pre><code>for(int i = 0; i < people.size(); i++) {\n Person person = people.get(i);\n String name = person.getName();\n\n if(name.equals(\"Joe\")) {\n System.out.println(\"Happy Birthday Joe! You are special! Your birthday is on \"\n + person.getBirthDay() + \" \\n\");\n\n } else if(i % 2 == 0) {\n System.out.println(\"Happy Birthday to \" + name + \".\\n\");\n\n } else {\n System.out.println(\"Happy Birthday to \" + name + \" too!!!\\n\");\n }\n}\n</code></pre>\n\n<p>I ended up creating a <code>name</code> variable as well since the name of the person was needed in multiple places.</p>\n\n<p>You also had inconsistent spacing that I corrected. Some places had everything all smooshed together, and then other places (like with <code>==</code>) had spacing. I added spaces around all the operators, then broke up one of the longer lines. I also added empty lines after each <code>println</code> call so the cases were a little more distinct.</p>\n\n<p>Unless you need the <code>i % 2 == 0</code> check to give a special message to every arbitrary second person, this loop could be slightly simplified by using an enhanced for-loop that doesn't rely on indices:</p>\n\n<pre><code>// Read as \"for each person in people\"\nfor(Person person : people) {\n String name = person.getName();\n\n if(name.equals(\"Joe\")) {\n System.out.println(\"Happy Birthday Joe! You are special! Your birthday is on \"\n + person.getBirthDay() + \" \\n\");\n\n } else {\n System.out.println(\"Happy Birthday to \" + name + \" too!!!\\n\");\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T17:19:57.907",
"Id": "214122",
"ParentId": "214120",
"Score": "6"
}
},
{
"body": "<h3>Why <code>nextLine</code> after <code>nextInt</code>?</h3>\n\n<blockquote>\n<pre><code> while ((userChoice = input.nextInt()) != 1){\n\n PeopleObjects people = new PeopleObjects();\n\n System.out.println(\"\\n###What is the name of the person?###\\n\");\n input.nextLine();//for some reason we have to use this twice to avoid bug\n</code></pre>\n</blockquote>\n\n<p>While an explanatory comment is helpful, you may want to go ahead and search out the <a href=\"https://stackoverflow.com/q/13102045/6660678\">explanation</a>: essentially, the <code>nextInt</code> only reads as far as the end of the number; it does not read the succeeding end-of-line. So if you want to read the next line, you have to first read that end-of-line so that you can start reading after it. Once you do that, you might move that line higher, right after the <code>nextInt</code>. </p>\n\n<p>I prefer comments to be on separate lines, although others disagree. </p>\n\n<h3>Favor interfaces over implementations</h3>\n\n<blockquote>\n<pre><code> ArrayList<PeopleObjects> listOfPeopleObjects = new ArrayList<PeopleObjects>();\n</code></pre>\n</blockquote>\n\n<p>When defining a type, the general preference is to use the interface rather than the implementation. So </p>\n\n<pre><code> List<Person> people = new ArrayList<>();\n</code></pre>\n\n<p>This encourages you to code to the interface, only using methods that are available in the interface. That in turn makes it easier to switch implementations. </p>\n\n<p>In the more recent versions of Java, you don't need to specify the type parameter twice. The second time you can just say <code><></code> and trust the compiler to figure it out. </p>\n\n<p><code>PersonObjects</code> is a plural name for a singular thing. So we can just make that singular. And there's not much point in saying that it is an object (which it actually isn't, it's a class). Every instantiation of a class in Java is an object. It could be just <code>Person</code>. </p>\n\n<p>Similarly, <code>listOfPeopleObjects</code> could be just <code>people</code>. There's some controversy over the <code>list</code>. There is a notation called <a href=\"https://en.wikipedia.org/wiki/Hungarian_notation\" rel=\"nofollow noreferrer\">Hungarian notation</a> where the type is included in the name. I personally prefer to just use plural names for collections of objects. But others disagree. </p>\n\n<h3>Clear prompts</h3>\n\n<blockquote>\n<pre><code> System.out.println(\"\\nDo you want to quit and see list? Enter 1 for yes and 0 for no\\n\");\n</code></pre>\n</blockquote>\n\n<p>Why do you want to indicate yes? Or no? You want to indicate yes to quit and no to continue. So why say yes and no? Consider </p>\n\n<pre><code> System.out.println(\"\\nDo you want to quit and see list? Enter 1 to quit or 0 to continue\\n\");\n</code></pre>\n\n<p>Now we don't have to figure out what yes and no mean in this context (e.g. you could have been asking \"Do you want to continue?\" with everything else the same. </p>\n\n<h3><code>do</code>/<code>while</code></h3>\n\n<p>You may want to read up on the <code>do</code>/<code>while</code> syntax. That would allow you to avoid asking for an initial response. I.e. you wouldn't have to enter anything to start the processing. Only to continue afterwards. </p>\n\n<p>It would disrupt your current <code>nextInt</code>/<code>nextLine</code> pattern though. You might consider how you could make that work. Hint: a custom method could do both commands in one unit of work. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T17:21:06.993",
"Id": "214123",
"ParentId": "214120",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T16:01:25.460",
"Id": "214120",
"Score": "5",
"Tags": [
"java",
"beginner",
"array",
"homework"
],
"Title": "User input happy birthday program"
} | 214120 |
<p>Please can any code experts review and improve my code?</p>
<p>HTML</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>API</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=font1|font2|etc" type="text/css">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1 id="test"></h1>
<div class="weather-container">
<img id="icon">
<h1 id="weather"></h1>
<p>Description: <span id="desc"></span></p>
<p>Temperature: <span id="temp"></span></p>
</div>
<script src="mousetrap.js"></script>
<script src="moment.js"></script>
<script src="jquery.js"></script>
<script src="script.js"></script>
</body>
</html>
</code></pre>
<p>That's the HTML. It is just mostly tags with id to output info.</p>
<p>JavaScript</p>
<pre><code>var ask = prompt("Type in your city or town that you want the weather for. Please make sure you write the first letter as capital letter and you spell it right.");
$.getJSON("https://api.openweathermap.org/data/2.5/weather?q="+ask+"&units=metric&appid=32b8cd17f2ff5d84d72342dd7408bab2", function(data) {
console.log(data);
var icon = "https://openweathermap.org/img/w/" + data.weather[0].icon + ".png";
var weather = data.weather[0].main;
var desc = data.weather[0].description;
var temp = data.main.temp;
var temp1 = temp + "℃"
$("#icon").attr("src", icon);
document.getElementById('weather').innerHTML = weather;
document.getElementById('desc').innerHTML = desc;
document.getElementById('temp').innerHTML = temp1;
});
</code></pre>
<p>If there is any other language than jQquery that I can use to get JSON files from API, please let me know because I find jQuery quite confusing.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T17:20:54.940",
"Id": "414066",
"Score": "0",
"body": "Hello welcome to CR. This looks interesting. *If there is any other language than Jquery* -> well jQuery is not a language it is a library. There are various ways to call APIs see [here](https://medium.com/@mattburgess/how-to-get-data-with-javascript-in-2018-f30ba04ad0da)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T23:08:21.637",
"Id": "414088",
"Score": "0",
"body": "Welcome to Code Review! You can get a line break without a blank line: just append two blanks at the end of the line that shall be followed by the break."
}
] | [
{
"body": "<h2>Response to your question</h2>\n\n<blockquote>\n <p>If there is any other language than Jquery that I can use to get json files from api, please let me know because i find Jquery quite confusing :-).</p>\n</blockquote>\n\n<p>As was mentioned in <a href=\"https://codereview.stackexchange.com/questions/214121/use-weather-api-to-get-information-in-javascript-jquery/214124#comment414066_214121\">a comment</a> (as well as a link-only answer that has since been deleted), there are alternatives, including but not limited to:</p>\n\n<ul>\n<li>vanilla JavaScipt: \n\n<ul>\n<li>with <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest\" rel=\"nofollow noreferrer\"><code>XMLHttpRequest</code></a> - refer to <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest\" rel=\"nofollow noreferrer\"><em>Using <code>XMLHttpRequest</code></em> on MDN</a></li>\n<li>with the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API\" rel=\"nofollow noreferrer\">fetch API</a></li>\n</ul></li>\n<li>other libraries, some of which are listed on <a href=\"http://youmightnotneedjquery.com/\" rel=\"nofollow noreferrer\">youmightnotneedjquery.com/</a>:\n\n<ul>\n<li><a href=\"https://github.com/ded/Reqwest\" rel=\"nofollow noreferrer\">reqwest</a></li>\n<li><a href=\"https://github.com/then/request\" rel=\"nofollow noreferrer\">then-request</a></li>\n<li><a href=\"https://github.com/visionmedia/superagent\" rel=\"nofollow noreferrer\">superagent</a></li>\n</ul></li>\n</ul>\n\n<h2>General review</h2>\n\n<h3>User experience</h3>\n\n<p>You didn't state whether the specification was part of an assignment/task or just something you came up with, but the UX might be improved by having the prompt and Ajax request triggered by an event like a mouse click instead of page load.</p>\n\n<p>If such a change was implemented, then it would be wise to cache the DOM references in variables instead of querying the DOM each time- e.g. </p>\n\n<pre><code>var weatherEl = document.getElementById('weather');\nvar descEl = document.getElementById('desc');\nvar tempEl = document.getElementById('temp');\n\n//function to prompt\n\n//AJAX response callback\nfunction ajaxResponse(data) {\n //parse data\n //...\n weatherEl.innerHTML = data.weather[0].description;\n descEl = data.weather[0].description;\n tempEl.innerHTML = data.main.temp + \"°C\";\n}\n</code></pre>\n\n<p>That way, the lines can be shorter, the DOM won't get queried each time, and you can likely eliminate those variables that are assigned and then only used once. </p>\n\n<p>Perhaps a template system would help improve the process of updating the DOM elements instead of having to update each item individually.</p>\n\n<h3>Handling other responses and errors</h3>\n\n<p>The code above doesn't appear to (gracefully) handle any response other than a successful call to the API endpoint. When the user types in a city that the API doesn't recognize, then a 404 response is returned. If you continue to use the jQuery library, then a <code>.fail()</code> callback could be specified (see the <a href=\"https://api.jquery.com/jQuery.getJSON/#jqxhr-object\" rel=\"nofollow noreferrer\"><code>$.getJSON()</code> documentation for an example</a> to handle that. Also, if a server error occurred, then a 5xx response might be returned.</p>\n\n<p>Additionally, the code assumes that <code>data.weather</code> will be an array and have at least 1 element. What happens if either of those are not true? While it may seem implausible it may be possible and something to guard against.</p>\n\n<h3>Extra libraries</h3>\n\n<p>The code includes <code>mousetrap.js</code> and <code>moment.js</code> - I presume those correspond to the libraries <a href=\"https://craig.is/killing/mice\" rel=\"nofollow noreferrer\">Mousetrap</a> and <a href=\"https://momentjs.com/\" rel=\"nofollow noreferrer\">MomentJS</a>, but it doesn't appear that those libraries are used by the code. Unless those are used by other code not included, those libraries can be removed to save the users time loading the page.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T20:59:25.100",
"Id": "214272",
"ParentId": "214121",
"Score": "1"
}
},
{
"body": "<h1>Variables</h1>\n\n<pre><code>var icon = \"https://openweathermap.org/img/w/\" + data.weather[0].icon + \".png\";\nvar weather = data.weather[0].main;\nvar desc = data.weather[0].description;\nvar temp = data.main.temp;\nvar temp1 = temp + \"℃\"\n$(\"#icon\").attr(\"src\", icon);\ndocument.getElementById('weather').innerHTML = weather;\ndocument.getElementById('desc').innerHTML = desc;\ndocument.getElementById('temp').innerHTML = temp1;\n</code></pre>\n\n<p>None of these variables are really needed. Each variable is only used once and you aren't doing any incredibly complex calculations on them, so they aren't even needed for the sake of understanding. Eliminating variables would also get rid of this <code>temp1</code> variable which is frankly a little ugly -- usually you know you've gone too far when you have to start adding numbers to variable names.</p>\n\n<p>Try something like this instead:</p>\n\n<pre><code>$(\"#icon\").attr(\"src\", \"https://openweathermap.org/img/w/\" + data.weather[0].icon + \".png\";);\ndocument.getElementById('weather').innerHTML = data.weather[0].main;\ndocument.getElementById('desc').innerHTML = data.weather[0].description;\ndocument.getElementById('temp').innerHTML = data.main.temp + \"℃\";\n</code></pre>\n\n<p>No variables, same functionality, just as understandable.</p>\n\n<p>You don't even need the <code>ask</code> variable, but I can understand why you're using it because it is indeed a long question.</p>\n\n<h1>jQuery</h1>\n\n<p>jQuery is not very relevant in today's JavaScript. I would recommend learning about <code>fetch</code> and thus <code>Promise</code>s. This design is much cleaner and much nicer to work with, IMO.</p>\n\n<p>Your code with <code>fetch</code> would look like this:</p>\n\n<pre><code>var ask = prompt(\"Type in your city or town that you want the weather for. Please make sure you write the first letter as capital letter and you spell it right.\");\n\nfetch(*url*).then(r => r.json()).then(data => {\n ...\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T22:29:23.063",
"Id": "214281",
"ParentId": "214121",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "214281",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T17:05:13.440",
"Id": "214121",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"api",
"html5",
"ajax"
],
"Title": "Use weather API to get information in JavaScript + jQuery"
} | 214121 |
<p>After reading "<a href="https://jrsinclair.com/articles/2018/how-to-deal-with-dirty-side-effects-in-your-pure-functional-javascript/" rel="nofollow noreferrer">How to deal with dirty side effects in your pure functional JavaScript</a>," I've decided to take something I do on a regular basis ("Original approach" below)—connect to a Postgres database from Node.JS, perform some operations, and log what is going on—and try to make my code much closer to "purely functional" ("Functional approach" below) by using "Effect functors."</p>
<p>Am I on the right track?</p>
<p>Beyond functional-vs-declarative, are there other ways my code could be better-written?</p>
<hr>
<h2>Original approach - declarative</h2>
<pre><code>const {user, database, host} = require('./mydatabaseconnection') ;
const pg = require('pg') ;
const logging = require('./logging') ;
const pglogging = require('./pglogging') ;
// MODIFIED FROM https://medium.com/@garychambers108/better-logging-in-node-js-b3cc6fd0dafd
["log", "warn", "error"].forEach(method => {
const oldMethod = console[method].bind(console) ;
console[method] = logging.createConsoleMethodOverride({oldMethod, console}) ;
}) ;
const pool = new pg.Pool({
user
, database
, host
, log: pglogging.createPgLogger()
}) ;
pool.query('SELECT 1 ;').then(result => console.log(result)).then(()=>pool.end()) ;
</code></pre>
<h2>Functional approach</h2>
<pre><code>const {user, database, host} = require('./mydatabaseconnection') ;
const pg = require('pg') ;
const logging = require('./logging') ;
const pglogging = require('./pglogging') ;
// MODIFIED FROM https://medium.com/@garychambers108/better-logging-in-node-js-b3cc6fd0dafd
["log", "warn", "error"].forEach(method => {
const oldMethod = console[method].bind(console) ;
console[method] = logging.createConsoleMethodOverride({oldMethod, console}) ;
}) ;
function Effect(f) {
return {
map(g) {
return Effect(x => g(f(x)));
}
, runEffects(x) {
return f(x) ;
}
}
}
function makePool() {
return {pool: new pg.Pool({
user
, database
, host
, log: pglogging.createPgLogger()
})} ;
}
function runQuery({pool}) {
return {query: pool.query('SELECT 1 ;'), pool} ;
}
function logResult({query, pool}) {
return {result: query.then(result => console.log(result)), pool} ;
}
function closePool({pool}) {
return pool.end() ;
}
const poolEffect = Effect(makePool) ;
const select1Logger = poolEffect.map(runQuery).map(logResult).map(closePool) ;
select1Logger.runEffects() ;
</code></pre>
<hr>
<h2>Common to both</h2>
<p>logging.js</p>
<pre><code>const moment = require('moment-timezone') ;
function simpleLogLine({source = '', message = '', objectToLog}) {
const objectToStringify = {date: moment().toISOString(true), source, message} ;
if (typeof objectToLog !== 'undefined') objectToStringify.objectToLog = objectToLog ;
return JSON.stringify(objectToStringify) ;
}
module.exports = {
createConsoleMethodOverride: ({oldMethod, console}) => function() {
oldMethod.apply(
console,
[(
arguments.length > 0
? (
(
arguments.length === 1
&& typeof arguments[0] === 'object'
&& arguments[0] !== null
)
? (
['message', 'objectToLog'].reduce((accumulator, current) => accumulator || Object.keys(arguments[0]).indexOf(current) !== -1, false)
? simpleLogLine(arguments[0])
: simpleLogLine({objectToLog: arguments})
)
: (
arguments.length === 1 && typeof arguments[0] === 'string'
? simpleLogLine({message: arguments[0]})
: simpleLogLine({objectToLog: arguments})
)
)
: simpleLogLine({})
)]
) ;
}
} ;
</code></pre>
<p>pglogging.js</p>
<pre><code>module.exports = {
createPgLogger: () => function() {
console[
typeof arguments[0] !== 'string'
? 'log'
: (
arguments[0].match(/error/i) === null
? 'log'
: 'error'
)
](
arguments.length === 1
? (
typeof arguments[0] !== 'string'
? ({source: 'Postgres pool', object: arguments[0]})
: ({source: 'Postgres pool', message: arguments[0]})
)
: (
typeof arguments[0] !== 'string'
? ({source: 'Postgres pool', object: arguments[0]})
: (
arguments.length === 2
? ({source: 'Postgres pool', message: arguments[0], object: arguments[1]})
: ({source: 'Postgres pool', message: arguments[0], object: [...arguments].slice(1)})
)
)
) ;
}
} ;
</code></pre>
<hr>
<p>Sample output (from either approach):</p>
<pre><code>{"date":"2019-02-23T12:31:02.186-05:00","source":"Postgres pool","message":"checking client timeout"}
{"date":"2019-02-23T12:31:02.193-05:00","source":"Postgres pool","message":"connecting new client"}
{"date":"2019-02-23T12:31:02.195-05:00","source":"Postgres pool","message":"ending"}
{"date":"2019-02-23T12:31:02.196-05:00","source":"Postgres pool","message":"pulse queue"}
{"date":"2019-02-23T12:31:02.196-05:00","source":"Postgres pool","message":"pulse queue on ending"}
{"date":"2019-02-23T12:31:02.203-05:00","source":"Postgres pool","message":"new client connected"}
{"date":"2019-02-23T12:31:02.203-05:00","source":"Postgres pool","message":"dispatching query"}
{"date":"2019-02-23T12:31:02.207-05:00","source":"Postgres pool","message":"query dispatched"}
{"date":"2019-02-23T12:31:02.208-05:00","source":"Postgres pool","message":"pulse queue"}
{"date":"2019-02-23T12:31:02.209-05:00","source":"Postgres pool","message":"pulse queue on ending"}
{"date":"2019-02-23T12:31:02.209-05:00","source":"","message":"","objectToLog":{"0":{"command":"SELECT","rowCount":1,"oid":null,"rows":[{"?column?":1}],"fields":[{"name":"?column?","tableID":0,"columnID":0,"dataTypeID":23,"dataTypeSize":4,"dataTypeModifier":-1,"format":"text"}],"_parsers":[null],"RowCtor":null,"rowAsArray":false}}}
</code></pre>
<hr>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-02T19:16:28.910",
"Id": "415019",
"Score": "0",
"body": "From the answer I've received so far, it appears I've still got a long ways to go to really grok the pure-functional paradigm. Can anyone recommend any tutorial, further reading, etc.? For instance: https://glebbahmutov.com/blog/node-server-with-rx-and-cycle/#what-if-the-network-was-a-function - \"…moving of everything that is outside of our control to inputs or outputs, leaving our main logic inside a pure function\". Do I need to do something like this?"
}
] | [
{
"body": "<h1>Not at all functional.</h1>\n\n<ol>\n<li><p>Functional means no side effects. </p>\n\n<p>You have <code>console[method]</code>, <code>new pg.Pool</code> and <code>pool.query</code> each of which are side effects. </p></li>\n<li><p>Functional means using pure functions.</p>\n\n<ul>\n<li><p>A pure function must be able to do its thing with only its arguments.</p>\n\n<p><code>logResult</code> and <code>makePool</code> require global references.</p></li>\n<li><p>A pure function must always do the same thing for the same input. </p>\n\n<p><code>runQuery</code>, <code>closePool</code>, and <code>makePool</code> depend on the database state not the arguments for the result and are not pure. </p>\n\n<p>Because you pass impure functions to <code>Effect</code> you can not predict its behavior and thus it is impure as well.</p></li>\n</ul></li>\n</ol>\n\n<p>Now you may wonder how to fix these problems and make your code functional.</p>\n\n<p>The best way to picture the problem is to imagine that each function must run on a isolated thread and rely only on its arguments to create a result. The arguments must be transportable and not rely on an external state (Remember the function is totally isolated)</p>\n\n<p>If you break these rules even once in a mile of code you break the tenet that must be maintained to get the benefit that functional programming offers.</p>\n\n<p>There is no half way functional, it's all or nothing.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-02T16:49:15.020",
"Id": "415005",
"Score": "0",
"body": "Thank you for the answer. I will take your advice and reexamine every function with this in mind: \"imagine that each function must run on a isolated thread and rely only on its arguments to create a result.\""
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T11:24:25.643",
"Id": "214232",
"ParentId": "214125",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "214232",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T17:46:40.517",
"Id": "214125",
"Score": "1",
"Tags": [
"javascript",
"node.js",
"functional-programming",
"postgresql"
],
"Title": "Turning simple Node.JS Postgres query and logging into most-functionally-pure-possible code"
} | 214125 |
<h3>Introduction</h3>
<p>I'm writing a script in YAML for building ASP.NET Core 2.2 project using GitLab Continuous Integration. In all YAML samples I could find (and there are not many) for building .NET Core based applications using GitLab CI I could see something like this:</p>
<pre><code>before_script:
- 'dotnet restore'
</code></pre>
<p><a href="https://docs.gitlab.com/ee/ci/yaml/#before_script-and-after_script" rel="nofollow noreferrer"><code>before_script</code></a> is running a dependency restore before every job. It makes sense because if you use free GitLab runners (like I do) every job is executed on a different machine. There is no possibility to preserve state from previous jobs (with exception on cache and artifacts, but I'll get to that later). What that means is that on the next job, all previously restored packages will be gone, and they need to be restored again. And on the next job once again. And again on every job in the pipeline which needs the packages. I noticed a redundancy there. A redundancy that takes precious time, because a huge project with a lot of third-party packages takes a while for a full restore.</p>
<h3>Using job artifacts</h3>
<p>I found a way to preserve those packages and then pass them to the next job via <a href="https://docs.gitlab.com/ee/ci/yaml/#artifacts" rel="nofollow noreferrer">GitLab artifacts</a>:</p>
<pre><code>restore:
stage: restore
script:
- 'dotnet restore --packages .nuget/'
artifacts:
paths:
- 'src/**/obj/*'
- '.nuget/'
</code></pre>
<p>Let's break it down. With <code>dotnet restore --packages .nuget/</code> I explicitly specify a custom directory for packages to be restored. Then I specify two paths which GitLab CI will be interested in when creating a job artifacts. <code>dotnet restore</code> creates a few files with metadata about packages inside a <code>obj/</code> directory, so these will be needed as well. I include them in <code>src/**/obj/*</code>. Finally, I include the <code>.nuget/</code> directory which after <code>dotnet restore</code> should contain all restored dependencies.</p>
<p><strong>Note:</strong> A dependency restore saves the path where the packages will be kept inside <code><PROJECT_NAME>/obj/project.assets.json</code> file. After that, there is no need for explicitly specifying where the restored packages are e.g. when building the project.</p>
<p>Eventually, in the next job I use previously created job artifacts by specifying a <a href="https://docs.gitlab.com/ee/ci/yaml/#dependencies" rel="nofollow noreferrer">job dependecy</a>. In that way, GitLab CI knows that it should download job artifacts from the dependant job.</p>
<pre><code>build:
stage: build
script:
- 'dotnet build --no-restore'
dependencies:
- restore
</code></pre>
<hr>
<h3>Whole YAML script:</h3>
<pre><code>image: microsoft/dotnet:2.2-sdk
variables:
SOURCE_CODE_DIRECTORY: 'src'
BINARIES_DIRECTORY: 'bin'
OBJECTS_DIRECTORY: 'obj'
NUGET_PACKAGES_DIRECTORY: '.nuget'
stages:
- restore
- build
restore:
stage: restore
script:
- 'dotnet restore --packages="$NUGET_PACKAGES_DIRECTORY"'
artifacts:
paths:
- '$SOURCE_CODE_DIRECTORY/**/$OBJECTS_DIRECTORY/*'
- '$NUGET_PACKAGES_DIRECTORY/'
build:
stage: build
script:
- 'dotnet build --no-restore'
dependencies:
- restore
</code></pre>
<hr>
<h3>Feedback</h3>
<p>Please tell me what you think, any weaknesses of my approach, code smells, or maybe a better solution. All kind of constructive feedback appreciated.</p>
| [] | [
{
"body": "<p>I had a wrong concept about GitLab artifacts. After a good read on GitLab docs, especially the section distinguishing <a href=\"https://docs.gitlab.com/ee/ci/caching/#cache-vs-artifacts\" rel=\"nofollow noreferrer\">artifacts and cache</a>, I deduced that I should use cache instead of artifacts as it was designed precisely for storing restored dependencies. Artifacts are meant for passing build output and binaries.</p>\n\n<p>I also removed the <code>restore</code> stage, placing the <code>dotnet restore</code> command in a global <code>before_script</code>. Cache can fail and in such scenario the script should gracefully fallback to default 'download-from-internet' behaviour. With <code>--no-restore</code> option enabled it would not happen. Thus, I removed that option from <code>dotnet build</code> command. It won't make a noticeable difference with successfully download cache as a dependency restore with already downloaded packages will execute in next-to-no-time.</p>\n\n<p>Finally, I added cache key, which will keep cache bundles separate for branches and stages.</p>\n\n<h3>Updated script:</h3>\n\n<pre class=\"lang-none prettyprint-override\"><code>image: microsoft/dotnet:2.2-sdk\n\nvariables:\n SOURCE_CODE_DIRECTORY: 'src'\n BINARIES_DIRECTORY: 'bin'\n OBJECTS_DIRECTORY: 'obj'\n NUGET_PACKAGES_DIRECTORY: '.nuget'\n\nstages:\n - build\n\ncache:\n key: '$CI_JOB_STAGE-$CI_COMMIT_REF_SLUG'\n paths:\n - '$SOURCE_CODE_DIRECTORY/*/$OBJECTS_DIRECTORY/project.assets.json'\n - '$SOURCE_CODE_DIRECTORY/*/$OBJECTS_DIRECTORY/*.csproj.nuget.*'\n - '$NUGET_PACKAGES_DIRECTORY'\n\nbefore_script:\n - 'dotnet restore --packages $NUGET_PACKAGES_DIRECTORY'\n\nbuild:\n stage: build\n script:\n - 'dotnet build --no-restore'\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T08:41:03.650",
"Id": "466943",
"Score": "0",
"body": "Thanks for you post, Is caching `project.assets.json` is necessary?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T17:03:01.843",
"Id": "467012",
"Score": "1",
"body": "`project.assets.json` contains a list of all dependencies, with the dependency tree, packages version, frameworks and quite importantly where to they were restored as the restore destination location can be changed (in fact, I'm doing just the thing in the script above). This file will be created during restore or build, so changes made to your dependencies list will be overwritten by newer version if needed, then uploaded back to cache. Without the file, the CLI tool won't know about the locations of restored dependencies even if you load them from cache, so yes, it is necessary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-28T17:13:38.467",
"Id": "467013",
"Score": "1",
"body": "Some additional good reads on the topic: [Example GitLab CI template for .NET Core project with extensive commentary](https://gitlab.com/gitlab-org/gitlab-foss/blob/master/lib/gitlab/ci/templates/dotNET-Core.yml) and a [good article explaining the reason and purpose of `project.assets.json`](https://kimsereyblog.blogspot.com/2018/08/sdk-style-project-and-projectassetsjson.html)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-29T04:53:58.540",
"Id": "467057",
"Score": "0",
"body": "And how about, `*.csproj.nuget.*`, what is that for?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-29T10:21:04.030",
"Id": "467065",
"Score": "1",
"body": "As the case with `project.assets.json` was quite clear, it is not so with files matched with `*.csproj.nuget.*` expression. It usually matches 4 files. I do not know their entire purpose, but I remember I've experienced some issues when I wasn't caching them. Still, I'm not so sure about this one, so you are free to try without them. Note though, that some parts of the script above I achieved with try and see strategy which is clearly not the best approach to write code, but hey, it works!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T17:21:59.300",
"Id": "217152",
"ParentId": "214128",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "217152",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T18:25:58.977",
"Id": "214128",
"Score": "2",
"Tags": [
"c#",
"asp.net-core",
"yaml"
],
"Title": "Passing restored packages as artefacts in GitLab Continuous Integration"
} | 214128 |
<p>I wrote this after using <code>strtok_r</code> and needing something similar that can copy the input string and handle multiple characters in the delimiter. Its functionally similar to Python's <code>str.split()</code>, as it keeps empty spaces without trimming.</p>
<h1>tokens.h</h1>
<pre><code>#ifndef TOKENS_H
#define TOKENS_H
#include <string.h>
struct Tokens {
char **array;
size_t count;
};
extern struct Tokens *string_split(const char *input,
const char *delim,
const int count);
extern void tokens_free(struct Tokens *tokens);
#endif
</code></pre>
<h1>tokens.c</h1>
<pre><code>#include "tokens.h"
#include <stdbool.h>
#include <stdlib.h>
static bool tokens_add(struct Tokens *tokens, const char *token){
tokens->array = realloc(tokens->array,
++tokens->count * sizeof(char *));
if (!tokens->array){
tokens->count--;
return false;
}
char *dupstr = strdup(token);
if (!dupstr){
tokens->count--;
return false;
}
tokens->array[tokens->count - 1] = dupstr;
return true;
}
struct Tokens *string_split(const char *input,
const char *delim,
const int count){
struct Tokens *tokens = malloc(sizeof(struct Tokens));
if (!tokens){
return NULL;
}
tokens->count = 0;
tokens->array = NULL;
const size_t inputlen = strlen(input);
const size_t delimlen = strlen(delim);
if (count == 0 || delimlen == 0){
tokens_add(tokens, input);
return tokens;
}
int delimcount = 0;
size_t inputpos = 0;
const char *start = NULL;
while ((start = strstr(&input[inputpos], delim))){
const int delimpos = (start - &input[inputpos]);
char token[delimpos + 1];
memcpy(token, &input[inputpos], delimpos);
token[delimpos] = '\0';
if (!tokens_add(tokens, token)){
return NULL;
}
inputpos += (delimpos + delimlen);
if (delimcount++ == count){
break;
}
}
if (inputpos <= inputlen){
const int charcount = (inputlen - inputpos);
char token[charcount + 1];
memcpy(token, &input[inputpos], charcount);
token[charcount] = '\0';
if (!tokens_add(tokens, token)){
return NULL;
}
}
return tokens;
}
void tokens_free(struct Tokens *tokens){
if (!tokens){
return;
}
for (size_t index = 0; index < tokens->count; index++){
free(tokens->array[index]);
}
free(tokens);
}
</code></pre>
<h1>test.c</h1>
<pre><code>#include <stdio.h>
#include "tokens.h"
int main(void){
// <0 = split indefinitely
struct Tokens *tokens = string_split("Hello;world;!;", ";", -1);
if (tokens){
for (size_t index = 0; index < tokens->count; index++){
printf("%s\n", tokens->array[index]);
}
tokens_free(tokens);
}
}
</code></pre>
| [] | [
{
"body": "<p><strong><code>token_add()</code></strong></p>\n\n<ul>\n<li>do not change the struct members before you know that your call will succeed, otherwise you'll end up with inconsistent state (e.g. you're overwriting <code>tokens->array</code> if <code>realloc</code> fails). That means keep the increment of <code>count</code> and the assignment of <code>array</code> until the end of the function.</li>\n<li>Note that <code>strdup</code> is not a C standard function. </li>\n</ul>\n\n<p><strong><code>split_string()</code></strong></p>\n\n<ul>\n<li><p>you're creating a temporary copy in the local variables <code>token</code>. If you'd pass the pointer and the length to <code>token_add</code> and you could safe the program a string copy.</p></li>\n<li><p>there is no need to have <code>delimpos</code> in <code>string_split</code> being <code>const</code>. Same goes for the parameter <code>count</code> and <code>charcount</code>. As a rule of thumb, dont use <code>const</code> for integer types, booleans and floating points.</p></li>\n<li>Note: your comment in <code>test.c</code> states that values less than 0 mean unlimited matching, but your code doesn't contribute to that statement. If you have enough matches you'll eventually increment <code>delimcount</code> to match <code>-1</code>.</li>\n<li>Separate the increment of <code>delimcount</code> from the comparison with <code>count</code>. Some will ask himself if this is correct and right now, I couldn't tell ;-)\nWhy don't you use <code>tokens->count</code>?</li>\n<li>If a call to <code>tokens_add</code> failes, you're returning <code>NULL</code> from <code>split_string</code> without freeing the <code>Tokens</code> struct allocated before, leaking its memory.</li>\n</ul>\n\n<p><strong>misc</strong></p>\n\n<ul>\n<li>Provide more test cases. One test case for handling unlimited matching, one for restricted matching, one for empty delimiters. Best is to write down what your API supports and then add a test for every special case.</li>\n</ul>\n\n<p>For instance, if I test the following:</p>\n\n<pre><code> struct Tokens *tokens = string_split(\"Hello;world;!;\", \";\", 2);\n\n assert(tokens->count == 2);\n assert(strcmp(\"Hello\", tokens->array[0]) == 0);\n assert(strcmp(\"world!\", tokens->array[1]) == 0);\n</code></pre>\n\n<p>I receive: <code>test: test.c:22: test_2: Assertion 'tokens->count == 2' failed.</code></p>\n\n<ul>\n<li>you don't need the include in <code>tokens.h</code>, it's sufficient if you add it to <code>tokens.c</code></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T22:01:18.847",
"Id": "414206",
"Score": "0",
"body": "After going through every point, not only has this been humbling but it helped me fix up stuff I missed in my other projects as well! My only question is why avoid const on those types? Other than that, the assertion failing there is intentional since it's made to follow Python's own implementation which applies the count to how many delimiters it goes through (which ends up with 2 tokens plus the rest of the string). Thank you for the review because it's humbling and helpful!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T06:01:17.097",
"Id": "414234",
"Score": "1",
"body": "For const: clearly readability. In an API or simply in a function prototype you can use const to communicate, that you're not going to change the input value. In function bodies it is rather uncommon, so you're only adding a little moment where the reader struggles and thinks \"moment, why is this const?\"."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T10:53:13.623",
"Id": "214159",
"ParentId": "214136",
"Score": "2"
}
},
{
"body": "<h1>tokens.h</h1>\n\n<p>Instead of <code><string.h></code> use <code><stddef.h></code>, you only need access to <code>size_t</code>.</p>\n\n<h1>tokens.c</h1>\n\n<p>Now you need, <code><string.h></code> :-)</p>\n\n<p>Modify interface to <code>static bool tokens_add(struct Tokens *const tokens, const char *const token, size_t toklen)</code>. This we remove the need for extra copying in <code>split_string</code>.</p>\n\n<p>Instead of the non-standard <code>strdup</code> you now use</p>\n\n<pre><code>char *dupstr = malloc(toklen + 1u);\nif (dupstr == NULL) {\n return false;\n}\nmemcpy(dupstr, token, toklen);\ndupstr[toklen] = '\\0';\n</code></pre>\n\n<p>In <code>string_split</code> possibly start with this check</p>\n\n<pre><code>if (input == NULL || delim == NULL) {\n return NULL;\n}\n</code></pre>\n\n<p>later the check for zero <code>count</code> or <code>delimlen</code> led to a memory leak in the case of <code>tokens_add</code> failure.</p>\n\n<pre><code>if (count == 0 || delimlen == 0) {\n if (tokens_add(tokens, input, inputlen)) {\n return tokens;\n } else {\n tokens_free(tokens);\n return NULL;\n }\n}\n</code></pre>\n\n<p>The start of the <code>while</code>-loop can now be simplified to</p>\n\n<pre><code> const int delimpos = start - &input[inputpos];\n if (!tokens_add(tokens, &input[inputpos], delimpos)) {\n tokens_free(tokens);\n return NULL;\n }\n</code></pre>\n\n<p>since no <code>token</code> temporary buffer copy is needed (using VLA, a risk for stack overflow).</p>\n\n<p>And the end</p>\n\n<pre><code>if (inputpos <= inputlen) {\n if (!tokens_add(tokens, &input[inputpos], inputlen - inputpos)) {\n tokens_free(tokens);\n return NULL;\n }\n}\n</code></pre>\n\n<p>Finally, in <code>tokens_free</code> you have a memory leak. You are missing</p>\n\n<pre><code>free(tokens->array);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T22:04:08.300",
"Id": "414207",
"Score": "0",
"body": "Thanks! I was actually torn between stddef.h and string.h in the header file but I wasn't sure if I should avoid adding another header since I use string.h's functions or not. As for everything else, I combined it with the review from Cornholio and you guys have helped a lot!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T23:07:56.253",
"Id": "414214",
"Score": "1",
"body": "Good, didn't want to add too much of the same."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T18:16:45.380",
"Id": "214184",
"ParentId": "214136",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "214159",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T22:08:47.143",
"Id": "214136",
"Score": "3",
"Tags": [
"c",
"strings"
],
"Title": "Splitting C string without modifying input"
} | 214136 |
<p>The Task:</p>
<blockquote>
<p>The user enters a path to a dictionary file (one word per line) and a phrase as system arguments. My code must then find phrases containing only valid English words, generated by removing one consonant from the user's phrase.</p>
</blockquote>
<p>I wrote this as part of an effort to learn Rust, the task is copied from a piece of homework that I had to answer in Java. As such I have written a solution in both Java and Rust, however I was under the impression that Rust was generally faster than Java, but my Java code is significantly quicker. Being new to Rust I don't know what is slowing down my code.</p>
<pre><code>use std::env;
use std::fs::File;
use std::io::BufReader;
use std::io::BufRead;
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() == 3 {
let dict_path = &args[1];
let mut phrase = args[2].clone();
let dict_file = File::open(dict_path).expect("Failed to open file");
let br = BufReader::new(dict_file);
let dict: Vec<String> = br.lines().map(|l| l.unwrap()
.to_string()
.to_lowercase())
.collect();
let mut num_alter = 0;
for (i, ch) in phrase.clone().chars().enumerate() {
if is_consonant(&ch) {
phrase.remove(i);
num_alter += print_if_word(&phrase, &dict);
phrase.insert(i, ch);
}
}
println!("Number of alternatives: {}", num_alter);
}
}
fn print_if_word(phrase: &String, dict: &Vec<String>) -> u8 {
let words: Vec<&str> = phrase.split(" ").collect();
let all_words_match = words.iter().all(|w| dict.contains(&w.to_string().to_lowercase()));
if all_words_match {println!("{}", phrase); 1} else {0}
}
fn is_consonant(ch: &char) -> bool {
let consonants = vec!['a', 'e', 'i', 'o', 'u'];
ch.is_alphabetic() && !consonants.contains(ch)
}
</code></pre>
<p>Java Code:</p>
<pre><code>import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class LostConsonants {
private static HashSet<String> dict = new HashSet<>();
private static final HashSet<Character> CONSONANTS = new HashSet<>(Arrays.asList('q', 'w', 'r', 't', 'y', 'p', 's', 'd',
'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c', 'v', 'b',
'n', 'm', 'Q', 'W', 'R', 'T', 'Y', 'P', 'S', 'D', 'F',
'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M'
));
public static void main(String[] args) {
if (args.length != 2) {
System.out.printf("Expected 2 command line arguments, but got %d.\n", args.length);
System.out.println("Please provide the path to the dictionary file as the first argument and a sentence as the second argument.");
System.exit(1);
}
String dictPath = args[0];
String phrase = args[1];
vaildWords(dictPath);
int num = 0;
StringBuilder phraseBuilder = new StringBuilder(phrase);
for (int i = 0; i < phrase.length(); i++) {
Character curr = phraseBuilder.charAt(i);
if (CONSONANTS.contains(curr)) {
phraseBuilder.deleteCharAt(i);
num += printIfWord(phraseBuilder);
phraseBuilder.insert(i, curr);
}
}
System.out.println(num > 0 ? "Found " + num + " alternatives." : "Could not find any alternatives.");
}
static int printIfWord(StringBuilder phrase) {
String[] words = phrase.toString()
.replace("[.,]", "")
.toLowerCase()
.split(" ");
if (Stream.of(words).allMatch(dict::contains)) {
System.out.println(phrase);
return 1;
} else {
return 0;
}
}
static void vaildWords(String dictPath) {
try (BufferedReader reader = new BufferedReader(new FileReader(dictPath))) {
reader.lines().map(String::toLowerCase).forEach(dict::add);
} catch (FileNotFoundException e) {
System.out.printf("File not found: %s (No such file or directory)\n", dictPath);
System.out.println("Invalid dictionary, aborting.");
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T05:38:30.457",
"Id": "414131",
"Score": "1",
"body": "while knowing nothing about rust, I will say that `is_consonant` looks inefficient. Use a hash type rather than an array, and store the list of consonants to avoid a call to `is_alphabetic`. Define `consonants` such that it's only initialized once, not on every call. Also make sure that `phrase.remove` + `phrase.insert` is faster than moving `phrase.clone` inside the loop (and discarding the modified phrase)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T06:17:19.827",
"Id": "414238",
"Score": "1",
"body": "I'd say the biggest thing I see is that dict should be a HashSet. Seeing the Java code would make it easier to compare, so we know what to critique regarding the algorithm itself vs how it was translated."
}
] | [
{
"body": "<p>In terms of comparing the two implementations, I only see two differences.</p>\n\n<p>Your Java code uses a HashSet for dict while your Rust code uses a Vec. Since the desired use of dict is simply lookups, a HashSet is indeed the best data structure to use. This change is very easy to make, mostly since <code>collect</code> is a generic method. You can simply change the type of <code>dict</code> to <code>HashSet<String></code> and the words will be collected into a hashset. This should result in a very large improvement, assuming your dictionary is sufficiently large.</p>\n\n<p>The other difference is with <code>is_consonsant</code>. I don't see this change being very significant. I think the way you're doing it in the Rust implementation <em>may</em> actually be faster, especially if you use <code>is_ascii_alphabetic</code> instead. My reasoning for this is that a linear search through an array is typically faster than a hashset when the number of elements is very small. An array-based static lookup table would probably be best anyways. Overall though, this optimization is likely insignificant and only if you need this boost, you should benchmark different approaches.</p>\n\n<p>Here's how I might write this program, with some comments for explanation. (Note: I compiled this but didn't actually test it.) If you have any questions about why I do something a certain way, feel free to ask.</p>\n\n<pre><code>use std::collections::HashSet;\nuse std::env;\nuse std::fs::File;\nuse std::io::BufRead;\nuse std::io::BufReader;\n\npub fn main() {\n let args: Vec<String> = env::args().collect();\n if args.len() != 3 {\n // eprintln prints to stderr\n eprintln!(\"Expected 2 command line arguments, but got {}.\", args.len() - 1);\n eprintln!(\"Please provide the path to the dictionary file as the first argument and a sentence as the second argument.\");\n return;\n }\n\n let dict_path = &args[1];\n let phrase = &args[2];\n\n let dict_file = File::open(dict_path).expect(\"Failed to open file\");\n // You can collect into a hashset\n let dict: HashSet<String> = BufReader::new(dict_file)\n .lines()\n .map(|l| l.unwrap().to_string().to_lowercase())\n .collect();\n\n let mut num_alter = 0;\n let mut phrase_alter = phrase.to_string();\n for (i, ch) in phrase.chars().enumerate() {\n if is_consonant(ch) {\n phrase_alter.remove(i);\n num_alter += print_if_word(&phrase, &dict);\n phrase_alter.insert(i, ch);\n }\n }\n\n println!(\"Number of alternatives: {}\", num_alter);\n}\n\n// &str is almost always prefered over &String\nfn print_if_word(phrase: &str, dict: &HashSet<String>) -> u8 {\n // No need to collect to a vector, just chain iterator methods.\n let all_words_match = phrase\n .split_whitespace()\n .all(|w| dict.contains(&w.to_string().to_lowercase()));\n if all_words_match {\n println!(\"{}\", phrase);\n 1\n } else {\n 0\n }\n}\n\n// prefer taking by value instead of reference whenever the type is Copy and reasonably small\nfn is_consonant(ch: char) -> bool {\n // Since your Java code only allowed ascii consonants, I will do the same here.\n if !ch.is_ascii() {\n return false;\n }\n\n // Fastest solution is most likely a static lookup table like\n // static CONSONANT: [bool; 256] = [false, false, ...];\n // However, the solution below is reasonably fast and is likely\n // dwarfed by other costs in the program.\n\n let b = (ch as u8).to_ascii_lowercase();\n\n b.is_ascii_lowercase()\n && match b {\n b'a' | b'e' | b'i' | b'o' | b'u' => false,\n _ => true,\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T20:31:52.410",
"Id": "214271",
"ParentId": "214138",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "214271",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T22:13:06.933",
"Id": "214138",
"Score": "3",
"Tags": [
"performance",
"strings",
"file",
"rust"
],
"Title": "Find a valid english phrase that is identical to what the user entered, save a missing consonant"
} | 214138 |
<p>I'm learning the Elixir language and the Phoenix web framework. And I had an idea. What if, in a web wizard (multi-step form) scenario, I stored the intermediate data in a ETS table instead of the relational database?</p>
<p>So I wrote this controller:</p>
<pre><code>defmodule PlayPhoenixWeb.ThingsController do
use PlayPhoenixWeb, :controller
require Logger
@moduledoc false
@form_ets :things_forms
alias PlayPhoenixWeb.Router.Helpers, as: Routes
alias PlayPhoenixWeb.Endpoint
def step_1_display(conn, _params) do
render(conn, "form_1.html")
end
def step_1_process(conn, params) do
data = Map.take(params, ["name", "vcode"])
key = make_key()
write_data(key, data)
Logger.debug inspect(data)
redirect(conn, to: Routes.thing_form_2_path(Endpoint, :step_2_display, key))
end
def step_2_display(conn, %{"key" => key}) do
render(conn, "form_2.html", key: key)
end
def step_2_process(conn, %{"key" => key} = params) do
{:ok, data} = get_data(key)
full_data = Map.take(params, ["description", "value"]) |> Map.merge(data)
# In production, processing full data would happen here
Logger.debug inspect(full_data)
redirect(conn, to: Routes.page_path(Endpoint, :index))
end
# This method is called by the Application on startup
def init_ets(), do: :ets.new(@form_ets, [:public, :named_table])
defp make_key(), do: :crypto.hash(:md5, DateTime.utc_now() |> DateTime.to_iso8601) |> :base64.encode
defp get_data(key) do
case :ets.lookup(@form_ets, key) do
[{^key, value}] -> {:ok, value}
_ -> {:not_found}
end
end
defp write_data(key, data) do
:ets.insert(@form_ets, {key, data})
end
defp delete_data(key), do: :ets.delete(@form_ets, key)
end
</code></pre>
<p>(It's purely for the sake of playing/research, and currently doesn't store or process any data).</p>
<p>Is this the Elixir way/the Phoenix way?</p>
<p>Thank you very much.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T18:30:04.183",
"Id": "414469",
"Score": "0",
"body": "Hi, you should try to explain in a little more detail what your code is supposed to do :)"
}
] | [
{
"body": "<p>Can't say much on Elixir, but, <code>make_key</code> - why go through the trouble and use MD5 on a string format of the current time (at what resolution? seconds? so you'll get duplicates whenever this is called quickly enough in rapid succession) when you can just generate a bunch of random numbers of a fixed length instead? Additionally you might just be able to pass in the source of the random numbers too and then suddenly it's way more testable (because 1. you're not relying on the current time, 2. you're not on a global random number generator).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-27T09:33:05.087",
"Id": "414572",
"Score": "1",
"body": "Well, one would probably use UUID or something in production... But frankly, I was going to mostly look at the capabilities of ETS so I needed something quick and not requiring external libraries for generating the key."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-27T14:20:21.717",
"Id": "414595",
"Score": "0",
"body": "Right, I meant something [like this](https://stackoverflow.com/a/32002566/2769043), that looks like it's still all internal."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T17:43:59.830",
"Id": "415662",
"Score": "2",
"body": "`:erlang.unique_integer/0` will do the job for unique keys that are VM loocal."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-27T00:11:17.600",
"Id": "214366",
"ParentId": "214140",
"Score": "0"
}
},
{
"body": "<p>Yes, using ETS for this sort of temporary data is totally fine, as long as you realize of course that all that intermediate state is lost whenever you restart your server. In fact, if you dig into Phoenix and Elixir a bit, you will see a lot of ETS usage - it's not so much a thing you turn to in exceptional circumstances, but more a tool in the extensive toolbox at the same level of, say, <code>GenServer</code>. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-07T17:46:00.457",
"Id": "214939",
"ParentId": "214140",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "214939",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-23T22:53:03.910",
"Id": "214140",
"Score": "1",
"Tags": [
"elixir",
"phoenix-framework"
],
"Title": "Storing temporary data in ETS - for example, using ETS in a web wizard"
} | 214140 |
<p>The goal is to have a function that can transform any python function into a curried version of this function. The code is available <a href="https://repl.it/@ChristianGlacet/Currying-any-function" rel="nofollow noreferrer">here</a>, I'll only update the code on repl.it so everyone can make sense of all the remarks and comments made on the code I'll post on <em>codereview</em>. </p>
<p>To be precise, consider this code:</p>
<pre class="lang-py prettyprint-override"><code>def f(x, y, z, info=None):
if info:
print(info, end=": ")
return x + y + z
g = curry(f)
print("g(2, 3, 4) = ", g(2, 3, 4))
print("g(2, 3)(4) = ", g(2, 3)(4))
print("g(2)(3)(4) = ", g(2)(3)(4))
print("g(2)(3, 4) = "g(2)(3, 4))
print(g(2, info="test A")(3, 4))
print(g(2, info="test A")(3, 4, info="test B"))
print(g(2,3,4)(5))
</code></pre>
<p>The goal is to have the following output: </p>
<pre class="lang-bsh prettyprint-override"><code>g(2, 3, 4) = 9
g(2, 3)(4) = 9
g(2)(3)(4) = 9
g(2)(3, 4) = 9
test A: 9
test B: 9
</code></pre>
<p>And throw an exception on the last line. </p>
<p>My current implementation of <code>curry</code> is the following, I simply wonder if this is as simple as it can be.</p>
<pre><code>from copy import copy
from inspect import signature
import functools
class curry:
def __init__(self, function):
self._partial = functools.partial(function)
def __call__(self, *args, **kwargs):
partial = functools.partial(self._partial, *args, **kwargs)
sign = signature(partial.func)
try:
sign.bind(*partial.args, **partial.keywords)
output = partial()
return output
except TypeError as e:
return curry(copy(partial))
def __str__(self):
text = "partial: "
text += str(self._partial.func.__name__ )
text += str(self._partial.args)
text += str(signature(self._partial))
return text
</code></pre>
<p>I added an <code>__str__</code> method that is useful when you want to debug with partials. For example <code>print(g(2,3))</code> prints:</p>
<pre><code>partial: f(2, 3)(z, info=None)
</code></pre>
<p>Any suggestion to improve this is welcome. </p>
<p><strong>Edit:</strong></p>
<p>If overriding partial's string representation isn't needed then a simple function decorator could be used:</p>
<pre class="lang-py prettyprint-override"><code>from copy import copy
from inspect import signature
import functools
def curry(function):
def inner(*args, **kwargs):
partial = functools.partial(function, *args, **kwargs)
sign = signature(partial.func)
try:
sign.bind(*partial.args, **partial.keywords)
return partial()
except TypeError as e:
return curry(copy(partial))
return inner
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T07:37:08.747",
"Id": "414139",
"Score": "1",
"body": "What's wrong with `partial()` that you need to use `sign.bind` to generate a `TypeError` instead? (Or am I mistakenly considering the purpose of that signature?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T22:34:58.383",
"Id": "414208",
"Score": "1",
"body": "The problem is explained in details [here](https://codereview.stackexchange.com/a/214197/172628). Basically you want to make the difference between partial raising an internal error and partial raising an error because we passed the wrong arguments."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T22:39:35.450",
"Id": "414209",
"Score": "0",
"body": "Absolutely. This is the kind of things I had in mind, but since you're not making a difference (as everything is in the same try) I wanted to be sure."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T22:43:02.160",
"Id": "414210",
"Score": "0",
"body": "That was totally my mistake, I've thought about that at first then I totally forgot about it."
}
] | [
{
"body": "<p>Nice code - I might reuse that pattern!</p>\n\n<p>Some suggestions for the class implementation:</p>\n\n<ul>\n<li>I would recommend <a href=\"https://docs.python.org/3.6/reference/lexical_analysis.html#f-strings\" rel=\"nofollow noreferrer\">formatted string literals</a> in Python 3.6+ over concatenation.</li>\n<li>A linter such as <code>flake8</code> will suggest some changes to make your code more pythonic, such as making the class name CamelCase.</li>\n<li>What causes a <code>TypeError</code> and why do you throw it away?</li>\n<li><code>output</code> might as well be inlined.</li>\n<li>Rather than the ambiguously named <code>sign</code> variable I would prefer <code>signature = inspect.signature(…)</code>.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T01:20:21.587",
"Id": "414104",
"Score": "0",
"body": "I wanted to avoid CamelCasing as this was supposed to look like a function for the user. TypeError is raised when the argument supplied to the partial are not sufficient to actually apply the function. \"output might as well be inlined\" sure thing, if you notice I did it in the function version."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T01:23:06.037",
"Id": "414105",
"Score": "0",
"body": "I'll update the code on repl.it as remarks come and let everything here as is, so this thread still makes sense to new people coming here."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T01:14:52.893",
"Id": "214145",
"ParentId": "214141",
"Score": "1"
}
},
{
"body": "<p>This is interesting! Very good first stab at this.</p>\n\n<p>I'm going to recommend rewriting a lot of this, but I want to call out an important mistake in your code that hides a serious issue. It's your <code>try</code>/<code>except</code> block:</p>\n\n<pre><code>try:\n sign.bind(*partial.args, **partial.keywords)\n return partial()\nexcept TypeError as e:\n return curry(copy(partial))\n</code></pre>\n\n<p>Because your <code>return partial()</code> is inside the <code>try</code>, if actually calling the function produces a <code>TypeError</code> (consider <code>abs('a')</code>), you suppress it and continue to curry. This is incorrect; you only want to catch <code>TypeError</code> from <code>sign.bind(...)</code></p>\n\n<pre><code>try:\n sign.bind(*partial.args, **partial.keywords)\nexcept TypeError as e:\n return curry(copy(partial))\nelse:\n return partial()\n</code></pre>\n\n<p>Okay, now onto the deeper issues:</p>\n\n<p>Currying in Python is tricky (if not maybe undefined in some cases) because of optional args and kwargs. And to complicate things your \"syntax\" for it is inconsistent.</p>\n\n<p>Consider your <code>f</code>. While you can do something like:</p>\n\n<pre><code>curry(f)(2, 3, info='A')(4)\ncurry(f)(2, 3)(info='A')(4)\ncurry(f)(2)(3)(info='A')(4)\n</code></pre>\n\n<p>You <strong>can't</strong> do:</p>\n\n<pre><code>curry(f)(2, 3, 4)(info='A')\ncurry(f)(2)(3, 4)(info='A')\ncurry(f)(2)(3)(4)(info='A')\n</code></pre>\n\n<p>Because providing the 3rd argument (<code>4</code>) you are satisfying the function signature despite perhaps wanting to provide <code>info='A'</code>.</p>\n\n<p>There isn't a good way to work around this. Your curry also behaves unexpectedly with <code>*args</code> or <code>**kwargs</code> functions. Namely, they don't really curry. You can only call them once:</p>\n\n<pre><code>def foo(*args):\n print(args)\n\ndef bar(**kwargs):\n print(kwargs)\n\n# While we can do this...\ncurry(foo)(1, 2, 3)\ncurry(bar)(a=1, b=2, c=3)\n\n# We can't do this, which is perhaps confusing\ncurry(foo)(1)(2)(3)\ncurry(bar)(a=1)(b=2)(c=3)\n</code></pre>\n\n<p>Consider also <code>curry(list)</code> or <code>curry(set)</code>.</p>\n\n<p>Knowing that this won't work relies on you understanding the inner workings of the function you are calling. Some functions opt to take advantage of Python's dynamism and use args/kwargs to accept several different signatures. Some functions are also much more complicated than they let on or are builtin, which leads to the next problem:</p>\n\n<p><code>inspect.signature</code> doesn't work for some builtins (which are very valid candidates for currying):</p>\n\n<pre><code>>>> signature(map)\nValueError: no signature found for builtin type <class 'map'>\n>>> signature(filter)\nValueError: no signature found for builtin type <class 'filter'>\n</code></pre>\n\n<p>While some support it, support is flaky and something unintuitive.</p>\n\n<pre><code>>>> builtin_functions = [x for x in dir(__builtins__) if x[0] == x[0].lower() and x[0] != '_']\n>>> builtin_functions\n['abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable',\n 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir',\n 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset',\n 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance',\n 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min',\n 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr',\n 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super',\n 'tuple', 'type', 'vars', 'zip']\n\n>>> def supports_signature(f):\n... try:\n... signature(f)\n... return True\n... except ValueError:\n... return False\n...\n>>> [x for x in builtin_functions if not supports_signature(getattr(__builtins__, x))]\n['bool', 'breakpoint', 'bytearray', 'bytes', 'classmethod', 'dict', 'dir', 'filter', 'frozenset',\n 'getattr', 'int', 'iter', 'map', 'max', 'min', 'next', 'print', 'range', 'set', 'slice',\n 'staticmethod', 'str', 'super', 'type', 'vars', 'zip']\n</code></pre>\n\n<p>A quick look over this also makes me suspect that some of these signatures may not be correct (or rather, they don't encompass all possible signatures of a function).</p>\n\n<p>Here's another problem: your implementation continues to curry if you pass too many args.</p>\n\n<pre><code>>>> def foo(a, b):\n... print('foo', a, b)\n...\n>>> curry(foo)(1, 2, 3)\n<function curry.<locals>.inner at 0x10ec2ee18>\n</code></pre>\n\n<p>This is almost certainly going to bite you. You definitely want a type error here like you would get if you called it normally:</p>\n\n<pre><code>>>> foo(1, 2, 3)\nTypeError: foo() takes 2 positional arguments but 3 were given\n</code></pre>\n\n<p>Of course, handling this conflicts with allowing <code>*args</code> (or at least makes it more complicated).</p>\n\n<p>All of these problems compounding, I'd say it may not be wise to use such a pattern for anything more than experimentation or a functional exercise.</p>\n\n<p>But let's say you still want to. Hopefully, the above illustrates that you need to greatly simplify <code>curry</code> for it to be at all useful. Because after all, if something is confusing to implement, unless you have been exceedingly clever, the API you expose probably will also be confusing.</p>\n\n<p>With that out of the way, given all of these issues, I'd recommend placing the following reasonable restriction on your currying (which closely matches currying in functional languages):</p>\n\n<blockquote>\n <p>You cannot curry a function with default arguments, <code>*args</code>, or <code>**kwargs</code></p>\n</blockquote>\n\n<p>Implicitly, this includes things that you can't call <code>signature</code> on. I'd recommend one exception to this: required keyword-only arguments.</p>\n\n<pre><code>def foo(a, *, b, c):\n pass\n</code></pre>\n\n<p>This doesn't have the same issue as optional kwargs, because you must provide <code>b</code> and <code>c</code> (but you must do so as <code>b=2, c=3</code>, instead of positionally):</p>\n\n<pre><code>foo(1, b=2, c=3)\n</code></pre>\n\n<p>But note that you cannot include positional arguments after these required kwargs, so we should additionally add this restriction to our currying:</p>\n\n<pre><code>>>> foo(b=2, c=3, 1)\nSyntaxError: positional argument follows keyword argument\n</code></pre>\n\n<p>Also note that we still want to be able to pass any arg as a kwargs (as long as we don't then later pass a positional arg).</p>\n\n<p>Such an approach also allows us to easily check if we need to <code>raise TypeError</code> if too many args are provided.</p>\n\n<p>In keeping with this idea of simplicity, we can also avoid the (unnecessary) call to <code>sign.bind()</code> and <code>signature</code> on every call to the curried function and eliminate <code>partial</code> entirely.</p>\n\n<p>There's one consequence of this approach, though. It requires to reimplement a lot of Python's calling logic. Why? To know if we have been passed too many parameters we have to keep track of what parameters have been passed. And to do that we need to understand what valid combinations of parameters can be passed. This is the only sane approach, though, in my opinion because otherwise you'll get strange errors (likely far away from their source) if <code>curry</code> did not immediately return an error when an invalid parameter was provided (a keyword arg that doesn't exist or too many positionals, for example).</p>\n\n<p>That said, I got a bit nerdsniped by this so I went ahead and implemented all of that logic :) My approach is decently commented and has doctests, I've posted a <a href=\"https://gist.github.com/baileyparker/f7cb4c00298e7947ca7dc89cac190367\" rel=\"nofollow noreferrer\">gist</a> of it so if I plan to update tests, etc. I'll update it there:</p>\n\n<pre><code>from collections import OrderedDict\nfrom inspect import signature, Parameter\nfrom itertools import chain\n\n\ndef curry(func, *args, **kwargs):\n \"\"\"\n Allows a callable to be passed arguments incrementally, executing it only\n once all arguments have been provided--in the style of functional currying.\n\n To avoid corner cases, callables with *args, **kwargs, or default arguments\n cannot be curried. This includes some builtins that have multiple\n signatures.\n\n >>> def print_three(a, b, c):\n ... print(a, b, c)\n\n >>> curry(print_three, 1, 2, 3)\n 1 2 3\n >>> curry(print_three)(1, 2, 3)\n 1 2 3\n >>> curry(print_three)(1)(2, 3)\n 1 2 3\n >>> curry(print_three)(1)(2)(3)\n 1 2 3\n >>> curry(print_three)(1, 2)(3)\n 1 2 3\n >>> curry(print_three)()(1)()(2)()(3)\n 1 2 3\n >>> curry(print_three)(1, 2)(3, 4)\n Traceback (most recent call last):\n ...\n TypeError: print_three() takes 3 positional arguments but 4 were given\n >>> curry(print_three)(1, 2)(c=3)\n 1 2 3\n >>> curry(print_three)(1)(c=3)(b=2)\n 1 2 3\n >>> curry(print_three)(1, 2)(d=3)\n Traceback (most recent call last):\n ...\n TypeError: print_three() got an unexpected keyword argument 'd'\n\n >>> curry(curry(print_three)(1))(2, 3)\n 1 2 3\n\n >>> def required_keyword(a, b, *, c):\n ... print(a, b, c)\n\n >>> curry(required_keyword)(1, 2, 3)\n Traceback (most recent call last):\n ...\n TypeError: required_keyword() takes 2 positional arguments but 3 were given\n >>> curry(required_keyword)(1, 2, c=3)\n 1 2 3\n >>> curry(required_keyword)(1, 2)(c=3)\n 1 2 3\n >>> curry(required_keyword)(c=3)(a=1, b=2)\n 1 2 3\n\n >>> def has_starargs(a, *args):\n ... pass\n >>> curry(has_starargs)\n Traceback (most recent call last):\n ...\n TypeError: cannot curry a function with *args or **kwargs\n\n >>> def has_kwargs(a, **kwargs):\n ... pass\n >>> curry(has_kwargs)\n Traceback (most recent call last):\n ...\n TypeError: cannot curry a function with *args or **kwargs\n\n >>> def has_default(a, b=1):\n ... pass\n >>> curry(has_default)\n Traceback (most recent call last):\n ...\n TypeError: cannot curry a function with default arguments\n \"\"\"\n # Cannot curry an already curried function since our __call__ has *args\n # and **kwargs, which violates our currying rules.\n if isinstance(func, _curry):\n # Since curry objects are immutable, we can return the same curry\n return func\n\n params = signature(func).parameters\n\n if any(_is_star_param(param) for param in params.values()):\n raise TypeError('cannot curry a function with *args or **kwargs')\n\n if any(param.default != Parameter.empty for param in params.values()):\n raise TypeError('cannot curry a function with default arguments')\n\n curried = _curry(func, params, (), OrderedDict())\n\n if args or kwargs:\n return curried(*args, **kwargs)\n\n return curried\n\n\nclass _curry:\n def __init__(self, func, remaining_params, args, kwargs):\n self._func = func\n self._remaining_params = remaining_params\n self._args = args\n self._kwargs = kwargs\n\n def __call__(self, *args, **kwargs):\n if not args and not kwargs:\n return self\n\n if self._kwargs and args:\n raise SyntaxError('positional argument follows keyword argument')\n\n # Ensure we haven't been passed too many positional arguments\n remaining_params_iter = iter(self._remaining_params.items())\n\n try:\n for _, (_, expected) in _zip_first(args, remaining_params_iter):\n if not _is_positional_param(expected):\n raise self._positional_error(len(args))\n except ShortIteratorError:\n raise self._positional_error(len(args))\n\n # _zip_first will have consumed all of the positional arguments passed.\n # What remains is the positional and keyword argument that haven't been\n # provided.\n new_remaining_params = OrderedDict(remaining_params_iter)\n\n # Ensure all passed keyword arguments are expected (and eliminate all\n # remaining parameters that are passed)\n for name in kwargs:\n try:\n del new_remaining_params[name]\n except KeyError:\n raise self._type_error(f'got an unexpected keyword argument '\n f'\\'{name}\\'')\n\n # If all arguments have been provided, call then function\n new_args = self._args + args\n new_kwargs = OrderedDict(chain(self._kwargs.items(), kwargs.items()))\n\n if not new_remaining_params:\n return self._func(*new_args, **new_kwargs)\n\n # Otherwise, add the new arguments and return a new curryable function\n return self.__class__(self._func, new_remaining_params, new_args,\n new_kwargs)\n\n def _positional_error(self, extra_given):\n remaining_positional = filter(_is_positional_param,\n self._remaining_params.values())\n expected = len(self._args) + len(list(remaining_positional))\n s = 's' if expected != 1 else ''\n\n given = len(self._args) + extra_given\n\n return self._type_error(f'takes {expected} positional argument{s} but '\n f'{given} were given')\n\n def _type_error(self, msg):\n return TypeError(f'{self._func.__name__}() {msg}')\n\n\ndef _is_star_param(param):\n return param.kind in (Parameter.VAR_POSITIONAL, Parameter.VAR_KEYWORD)\n\n\ndef _is_positional_param(param):\n return param.kind in (Parameter.POSITIONAL_ONLY,\n Parameter.POSITIONAL_OR_KEYWORD)\n\n\ndef _zip_first(first, *rest):\n \"\"\"Zips arguments until the first iterator is consumed.\n\n Raises ShortIteratorError if any of the other iterators stop before the\n first is finished.\n\n >>> list(_zip_first([1, 2], [3, 4, 5]))\n [(1, 3), (2, 4)]\n\n >>> list(_zip_first([1, 2], [3]))\n Traceback (most recent call last):\n ...\n curry.ShortIteratorError: iterator unexpectedly stopped\n \"\"\"\n first = iter(first)\n rest = tuple(map(iter, rest))\n\n for item in first:\n other_items = tuple(map(next, rest))\n if len(other_items) != len(rest):\n raise ShortIteratorError()\n\n yield (item, *other_items)\n\n\nclass ShortIteratorError(Exception):\n \"\"\"\n Signals that one of the other iterators ended before the first in a call to\n _zip_first.\n \"\"\"\n def __init__(self):\n super().__init__('iterator unexpectedly stopped')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T22:48:42.527",
"Id": "414211",
"Score": "0",
"body": "I wanted to comment here with some code, but there is no way to comment properly in here, so answered [here](https://codereview.stackexchange.com/a/214203/172628). Stackechange is not really optimal for code review to be honest."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T21:24:24.580",
"Id": "214197",
"ParentId": "214141",
"Score": "5"
}
},
{
"body": "<p>This is a long comment to <a href=\"https://codereview.stackexchange.com/a/214197/172628\">this post</a>.</p>\n\n<blockquote>\n <p>Because providing the 3rd argument (4) you are satisfying the function\n signature despite perhaps wanting to provide info='A'.</p>\n</blockquote>\n\n<p>Yes I desperately tried to find a way to make a class instance return a value when \"called\" directly, that would allow to encapsulate both the result and the partial in a class, which would then permit to have <code>g(2, 3, 4)</code> to output the result of the call <code>f(2, 3, 4)</code> and <code>g(2, 3, 4)(info=\"x\")</code> to output the result of the call <code>f(2, 3, 4, info=\"x\")</code>. But I couldn't find a way, I actually had no idea of what to search for (I still don't).</p>\n\n<blockquote>\n <p>There isn't a good way to work around this. Your curry also make behave unexpectedly with *args or **kwargs functions.</p>\n</blockquote>\n\n<p>To be honest I didn't even though about this, I don't even know what <code>curry(bar)(1)(2)(3)</code> should output when applied on:</p>\n\n<pre><code>def bar(**kwargs):\n print(kwargs)\n</code></pre>\n\n<blockquote>\n <p><code>inspect.signature</code> doesn't work for some builtins</p>\n</blockquote>\n\n<p>Hmm, ok, that's very interesting, doesn't this by itself make <code>inspect.signature</code> broken? Shouldn't this be considered to be a bug in python? Is there another (saffer) way of knowing the number of arguments a function takes?</p>\n\n<blockquote>\n <p>your implementation continues to curry if you pass too many args.</p>\n</blockquote>\n\n<p>I missed that, I think this should fix it (but I'm using the signature again):</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>partial = functools.partial(self._partial, *args, **kwargs)\nsignature = inspect.signature(partial.func)\ntry:\n signature.bind(*partial.args, **partial.keywords)\nexcept TypeError as e:\n if len(partial.args) < len(signature.parameters):\n return curry(copy(partial))\nreturn partial.func(*partial.args)\n</code></pre>\n\n<p>Which also has the advantage of having the correct exception raised: </p>\n\n<pre><code>File \"main.py\", line 28, in test_currying\n print(g(2)(3, 4, 5, 6))\nFile \"main.py\", line 43, in __call__\n return partial.func(*partial.args)\nTypeError: f() takes from 3 to 4 positional arguments but 5 were given\n</code></pre>\n\n<blockquote>\n <p>All of these problems compounding, I'd say it may not be wise to use such a pattern for anything more than experimentation or a functional exercise.</p>\n</blockquote>\n\n<p>I should have said that in the first place, but yes the only point of this is to better understand how python work.</p>\n\n<blockquote>\n<pre><code>def foo(a, *, b, c):\n pass\n</code></pre>\n \n <p>This doesn't have the same issue as optional kwargs, because you must provide b and c (but you must do so as b=2, c=3, instead of positionally)</p>\n</blockquote>\n\n<p>I wasn't aware of that form, that's very handy. If I understand correctly, this is more or less equivalent to:</p>\n\n<pre><code>def foo(a, b=None, c=None):\n if b is None or c is None:\n raise TypeError(\"foo is missing some arguments\")\n pass\n</code></pre>\n\n<p>I'll update this with more questions once I'll have read your code. Anyway, thanks for this amazing feedback. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T22:59:27.520",
"Id": "414212",
"Score": "0",
"body": "Certainly :) I'll address in order. (1) Yeah unfortunately there isn't a way to have something that proxies the function call result (but only produces it when required) and also allows more calls. You just can't do that in python. (2) The example you gave would fail because `(2)(3)` is not `**kwargs` it's `*args`. But neither of them work well with currying. (3) No `signature` isn't broken, some functions are just a little magic (multipurpose) and have more than one signature depending on how you use them (although some of the broken ones like `filter` don't make sense)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T23:05:13.660",
"Id": "414213",
"Score": "0",
"body": "(4) Your solution to solve accepting too many params breaks (non-optional) `kwarg` support. Also what if you had `def foo(a, b):` and then did `curry(foo)(1, 2)(a=1, b=2)`. That should fail when you try `a=1`. This is why you must check manually to detect the error as soon as it occurs. Once an argument error has happened you can never reach a state where the function can be run (has enough args) and you get the proper error. (5) Seems reasonable (6) Yes basically. Although `foo(a, b=None, c=None)` still allows you to do `foo(1, 2, 3)`. You also don't need the `pass`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T23:15:02.023",
"Id": "414216",
"Score": "0",
"body": "Hmm, the more you explain your solution, the more I'm convinced that you are right and you have to do almost everything by hand to offer a clean API. I wouldn't have guessed this would be such a hard/complete exercise. I'll keep on reading your code, if you don't see me coming back tomorrow that means you killed me with your magic xD. I feel like I'm reading a python interpreter code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T23:29:01.953",
"Id": "414217",
"Score": "0",
"body": "Your code is actually so well written I don't even have much questions. \nMaybe the only thing I really don't understand is why do you use `self.__class__` instead of just `_curry` on line 149?\n\nThat being said I still need a bit more time to digest lines 120-125 to make sure I really understand what's going on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T23:30:41.180",
"Id": "414218",
"Score": "0",
"body": ":) Ah, that's so if you ever wanted to rename `_curry` you wouldn't have to go in and replace all the times it references itself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T23:32:44.437",
"Id": "414219",
"Score": "0",
"body": "Wow, that's some next level foresight, that's actually smart. I guess you have the habit of always doing this?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T22:47:47.827",
"Id": "214203",
"ParentId": "214141",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "214197",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T00:21:18.407",
"Id": "214141",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"functional-programming"
],
"Title": "Currying a function"
} | 214141 |
<p>iextrading has two APIs (<a href="https://iextrading.com/developer/docs/" rel="nofollow noreferrer">v1</a>, <a href="https://iexcloud.io/docs/api/" rel="nofollow noreferrer">v2</a>) which provide financial market data. Following script records a JSON file with their equity information (using a CRON job). </p>
<p>Would you be kind and review it for any possible improvement or anything that may be incorrect? </p>
<pre><code><?php
date_default_timezone_set("UTC");
ini_set('max_execution_time' , 0);
ini_set('memory_limit','-1');
set_time_limit(0);
$i = new I();
I::scrapeAllStocks($i);
Class I
{
/**
*
* @var an integer for version of iextrading api
*/
private $version;
/**
*
* @var a string of iextrading symbols
*/
private $symbolsPath;
/**
*
* @var a string of our symbols json directory
*/
private $symbolsDir;
/**
*
* @var a string of target path and query
*/
private $targetQuery;
/**
*
* @var a string of iextrading base URL
*/
private $baseUrl;
/**
*
* @var a string of iextrading end point
*/
private $endPoint;
// For version 1, tokens are not required.
// SECRET TOKEN: *********************************
// PUBLISHABLE TOKEN: *********************************
## https://cloud.iexapis.com/beta/iex/tops?symbols=AAPL&token=*********************************
function __construct()
{
$this->version = 2;
$this->symbolsPath = __DIR__ . "/../../config/symobls.md";
$this->symbolsDir = __DIR__ . "/../../a/path/to/your/dir/symbols";
$this->targetQuery = "stock/market/batch?symbols=";
// baseUrl for version 1
$this->baseUrl = "https://api.iextrading.com/1.0/";
// baseUrl for version 2
// $this->baseUrl = "https://cloud.iexapis.com/beta/";
// endPoint for version 1
$this->endPoint = "&types=quote,chart&range=1m&last=10";
// endPoint for version 2
// $this->endPoint = "&token=*********************************&types=quote,chart&range=1m&last=10";
echo "YAAAY! Class I is running \n";
return true;
}
public static function symbs($i){
$fnm= $i->symbolsPath;
$cnt= file_get_contents($fnm);
$sym=preg_split('/\r\n|\r|\n/', $cnt);
$child=array();
$mother=array();
$c=100;
foreach ($sym as $k=>$v){
$c=$c-1;
$sym=preg_split('/[\t]/', $v);
array_push($child,$sym);
if($c<=0){
$c=100;
array_push($mother, $child);
$child=array();
}
}
return $mother;
}
public static function scrapeAllStocks($i){
$vStocks=I::symbs($i);
$baseUrl=$i->baseUrl.$i->targetQuery;
$currentTime=date("Y-m-d-H-i-s");
$allStocks=array();
foreach ($vStocks as $k=>$v) {
$s=array_column($v, 0);
$stockUrl=$baseUrl . implode(",", $s) . $i->endPoint;
$rawStockJson=file_get_contents($stockUrl);
$rawStockArray=json_decode($rawStockJson, true);
$allStocks=array_merge($allStocks, $rawStockArray);
}
$allStocksJson=json_encode($allStocks);
// Write the raw file
$symbolsDir= $i->symbolsDir;
if (!is_dir($symbolsDir)) {mkdir($symbolsDir, 0755,true);}
$rawStockFile=$symbolsDir . "/" . $currentTime . ".json";
$fp=fopen($rawStockFile, "x+");
fwrite($fp, $allStocksJson);
fclose($fp);
echo "YAAAY! stock large json file updated successfully! \n";
}
}
?>
</code></pre>
<p>Example of <code>symobls.md</code>:</p>
<pre><code>A 2019-01-04 AGILENT TECHNOLOGIES INC
AA 2019-01-04 ALCOA CORP
AAAU 2019-01-04 PERTH MINT PHYSICAL GOLD ETF
AABA 2019-01-04 ALTABA INC
AAC 2019-01-04 AAC HOLDINGS INC
AADR 2019-01-04 ADVISORSHARES DORSEY WRIGHT
AAL 2019-01-04 AMERICAN AIRLINES GROUP INC
AAMC 2019-01-04 ALTISOURCE ASSET MANAGEMENT
AAME 2019-01-04 ATLANTIC AMERICAN CORP
AAN 2019-01-04 AARON'S INC
AAOI 2019-01-04 APPLIED OPTOELECTRONICS INC
AAON 2019-01-04 AAON INC
AAP 2019-01-04 ADVANCE AUTO PARTS INC
AAPL 2019-01-04 APPLE INC
AAT 2019-01-04 AMERICAN ASSETS TRUST INC
AAU 2019-01-04 ALMADEN MINERALS LTD - B
AAWW 2019-01-04 ATLAS AIR WORLDWIDE HOLDINGS
AAXJ 2019-01-04 ISHARES MSCI ALL COUNTRY ASI
AAXN 2019-01-04 AXON ENTERPRISE INC
AB 2019-01-04 ALLIANCEBERNSTEIN HOLDING LP
ABAC 2019-01-04 RENMIN TIANLI GROUP INC
ABB 2019-01-04 ABB LTD-SPON ADR
ABBV 2019-01-04 ABBVIE INC
ABC 2019-01-04 AMERISOURCEBERGEN CORP
ABCB 2019-01-04 AMERIS BANCORP
ABDC 2019-01-04 ALCENTRA CAPITAL CORP
ABEO 2019-01-04 ABEONA THERAPEUTICS INC
ABEOW 2019-01-04
ABEV 2019-01-04 AMBEV SA-ADR
ABG 2019-01-04 ASBURY AUTOMOTIVE GROUP
ABIL 2019-01-04 ABILITY INC
ABIO 2019-01-04 ARCA BIOPHARMA INC
ABM 2019-01-04 ABM INDUSTRIES INC
ABMD 2019-01-04 ABIOMED INC
ABR 2019-01-04 ARBOR REALTY TRUST INC
ABR-A 2019-01-04
ABR-B 2019-01-04
ABR-C 2019-01-04
ABT 2019-01-04 ABBOTT LABORATORIES
ABTX 2019-01-04 ALLEGIANCE BANCSHARES INC
ABUS 2019-01-04 ARBUTUS BIOPHARMA CORP
AC 2019-01-04 ASSOCIATED CAPITAL GROUP - A
ACA 2019-01-04 ARCOSA INC
ACAD 2019-01-04 ACADIA PHARMACEUTICALS INC
ACB 2019-01-04 AURORA CANNABIS INC
ACBI 2019-01-04 ATLANTIC CAPITAL BANCSHARES
ACC 2019-01-04 AMERICAN CAMPUS COMMUNITIES
</code></pre>
| [] | [
{
"body": "<p>Why instantiate an object of class <code>I</code> if the only methods called are static? It appears that only private member variables <em>that are never mutated</em> are accessed. Instead of creating an object of class <code>I</code> just to pass to the static methods, you could use <a href=\"http://php.net/manual/en/language.oop5.constants.php\" rel=\"nofollow noreferrer\">class constants</a> or if you really want them kept private, use make those private variables static. </p>\n\n<p>That way, the line the instance (i.e. <code>$i = new I();</code>) can be removed and the parameters (e.g. <code>$i</code>) can be removed from the method signatures, since they are no longer needed. It is up to you if you keep the constructor and destructor (e.g. if you end up needing to instantiate objects of that type then maybe you want those).</p>\n\n<hr>\n\n<p>The class name <code>I</code> is a little vague/non-descriptive. Perhaps a more appropriate name would be something like <code>StockController</code> or <code>StockScraper</code>. Similarly the method name <code>symbs</code> could be better named - perhaps something like <code>getSymbols</code>.</p>\n\n<hr>\n\n<p>What does the value <code>100</code> signify when used in that <code>symbs</code> method? Were you using 100 or more lines in your <em>symbols.md</em> file? If 100 is a special value, it should be stored in a constant or private static property.</p>\n\n<p>I tried using the sample file which has 47 lines and thus when I tried the code, nothing was added to the array returned by <code>symbs()</code>. Perhaps the logic needs to be updated to handle array lengths lower than 100. </p>\n\n<hr>\n\n<p>I presume there is a typo on this line:</p>\n\n<blockquote>\n<pre><code>$this->symbolsPath = __DIR__ . \"/../../config/symobls.md\";\n</code></pre>\n</blockquote>\n\n<p>given you gave a sample </p>\n\n<blockquote>\n <p>Example of <code>symobls.md</code>:</p>\n</blockquote>\n\n<p>So perhaps that line should be:</p>\n\n<pre><code>$this->symbolsPath = __DIR__ . \"/../../config/symbols.md\";\n</code></pre>\n\n<hr>\n\n<p>The last few lines of <code>scrapeAllStocks()</code> uses <code>fopen()</code>, <code>fwrite()</code> and <code>fclose()</code> to write the output file - is there a reason not to use <a href=\"https://php.net/file_put_contents\" rel=\"nofollow noreferrer\"><code>file_put_contents()</code></a> instead of all of those? Maybe you aren't familiar with that function, or else there is some write issue I am unaware of.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T22:38:02.920",
"Id": "214282",
"ParentId": "214146",
"Score": "2"
}
},
{
"body": "<ol>\n<li>You cannot use a <code>return</code> in a <code>__construct()</code> method. If you need to check for any \"badness\", you can use <code>throw</code>/<code>try</code>/<code>catch</code>.<br>Relevant resources: <a href=\"https://stackoverflow.com/q/14295761/2943403\">Return false from __constructor</a> & <a href=\"https://stackoverflow.com/q/5918084/2943403\">PHP - constructor function doesn't return false</a> (In the end, I support Sam's advice about writing class constants.)</li>\n<li>Regarding your regex patterns, they can be simplified.\n\n<ul>\n<li><code>/\\r\\n|\\r|\\n/</code> is more simply expressed as <code>/\\R/</code> (I expect you will never need to contend with a solitary <code>\\r</code> -- you could have also used <code>/\\r?\\n/</code>.)</li>\n<li><code>/[\\t]/</code> does not need to be expressed inside of a character class, so the square brackets can be omitted. (<code>/\\t/</code>)</li>\n</ul></li>\n<li><p>Now I am going to recommend that you completely abandon the contents of your <code>symbs()</code> method. Using regex is a sub-optimal tool for parsing your tab-delimited .md files. Using a combination of <code>file()</code> with iterative calls of <code>str_getcsv()</code> and a declaration of the your delimiting character makes for a concise and robust one-liner. So brief that you may choose to avoid writing the dedicated method entirely.</p>\n\n<pre><code>public static function symbs($i) {\n return array_map(function($line){ return str_getcsv($line, \"\\t\"); }, file($i->symbolsPath));\n // PHP7.4: return array_map(fn($line) => str_getcsv($line, \"\\t\"), file($i->symbolsPath));\n}\n// I tested this code locally using your .md file to make sure it worked as expected\n</code></pre></li>\n<li><p>Try to avoid single-use variable declarations. There are some cases where declaring variables improves the readability, but something straight forward like a datetime string generator is pretty safe to just inject into its final location in your script.</p></li>\n<li>It is best to keep your variable declarations in reasonable proximity to the place(s) they are used. This will save you and other developers from having to do too much scanning to find what they need.</li>\n<li>It would be a good idea for you to get familiar with PSR Coding Standards. \nMost relevant to this question, please obey the <a href=\"https://www.php-fig.org/psr/psr-2/\" rel=\"nofollow noreferrer\">PSR-2 recommendations</a>.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-20T09:59:11.663",
"Id": "215828",
"ParentId": "214146",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "214282",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T01:43:10.970",
"Id": "214146",
"Score": "4",
"Tags": [
"php",
"json",
"web-scraping",
"api",
"client"
],
"Title": "PHP script that writes a JSON file with iextrading API data"
} | 214146 |
<p>I saw a question on Stack Overflow asking for a review of a custom try...catch construct that made use of <code>Optional</code>s, and got the idea to try writing my own version. Mine doesn't use <code>Optional</code>s though. Each supplied <code>catch</code> handler is expected to return a value.</p>
<p>I realized about half way through writing this that this is probably an awful idea that should never be used d in the real world for various reasons. I haven't written Java in a few years though, and I'm curious what can be improved.</p>
<p>Example of use:</p>
<pre><code>Integer i =
new Try<>(()-> Integer.parseInt("f"))
.catching(NumberFormatException.class, (e)-> 2)
.catching(IllegalStateException.class, (e) -> 3)
.andFinally(()-> System.out.println("Finally!"));
// Finally!
Integer j =
new Try<>(()-> Integer.parseInt("1"))
.catching(NumberFormatException.class, (e) -> 2)
.execute();
System.out.println(i); // 2
System.out.println(j); // 1
</code></pre>
<p>Basically how it works is the <code>Try</code> object can have <code>catching</code> methods chained on it that register handlers. When an exception is thrown, it looks for a corresponding handler, and calls it, returning the returned value. If no handler is found, it rethrows the exception.</p>
<p>Major problems:</p>
<ul>
<li><p>The need for <code>.class</code> is unfortunate. I couldn't think of how else to have the caller indicate the class of exception to be caught though.</p></li>
<li><p>Non-exception classes can be registered, although it will have no effect other than the minimal memory and CPU usage.</p></li>
<li><p>The need for <code>execute</code> when <code>andFinally</code> isn't used. I can't see how the class would know that all <code>catch</code>es have been added though.</p></li>
<li><p>The need for <code>new</code> is unfortunate too. I figured I could take a page from Scala and create a static method that acts as a constructor, but then I'd need to do something like <code>Try.tryMethod</code> to reference it, which isn't a whole lot better.</p></li>
<li><p>The check in <code>andFinally</code> seems like it's unnecessary. Unless someone does something bizarre like:</p>
<pre><code>Try t = new Try<>(() -> null);
t.andFinally(() -> {});
t.andFinally(() -> {});
</code></pre>
<p>It shouldn't be possible to add multiple <code>finally</code> blocks. I'm not sure to what extent I should stop the user from doing stupid things. I could make the object immutable, but again, I'm not sure if that's necessary.</p></li>
</ul>
<p>Since this is basically just exercise code, I'd love to <em>anything</em> at all that could be improved here. This is the first Java I've really written in a few years, so I'm sure there's lots that can be improved.</p>
<pre><code>import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
public class Try<T> {
private Supplier<T> tryExpr;
private Map<Class, Function<Exception, T>> handlers = new HashMap<>();
private Runnable finallyExpr;
public Try(Supplier<T> tryExpr) {
this.tryExpr = tryExpr;
}
public Try<T> catching(Class ex, Function<Exception, T> handler) {
if(handlers.containsKey(ex)) {
throw new IllegalStateException("exception " + ex.getSimpleName() + " has already been caught");
} else {
handlers.put(ex, handler);
return this;
}
}
public T execute() {
try {
return tryExpr.get();
} catch (Exception e) {
if(handlers.containsKey(e.getClass())) {
Function<Exception, T> handler = handlers.get(e.getClass());
return handler.apply(e);
} else {
throw e;
}
} finally {
if(finallyExpr != null) {
finallyExpr.run();
}
}
}
public T andFinally (Runnable newFinallyExpr) {
if (finallyExpr == null) {
finallyExpr = newFinallyExpr;
} else {
throw new IllegalStateException("Cannot have multiple finally expressions");
}
return execute();
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T06:24:44.993",
"Id": "414133",
"Score": "0",
"body": "[Javaslang’s Try Monad](http://erajasekar.com/posts/better-exception-handling-java8-streams-using-javaslang/) may be worth looking at."
}
] | [
{
"body": "<p>Your code is <strong>fluent</strong>, and not really <strong>functional</strong>. </p>\n\n<p>It solves a problem that Java’s try block doesn’t return a value, but I don’t see a benefit of it over extracting the try-catch block into a separate method/lambda.</p>\n\n<p>To make it more functional, you need to allow operating on the <code>Try<T></code> object on a higher level. For example, transforming the result before the code is executed. The first step would be extracting the interface. Is it <code>Supplier<T></code>?</p>\n\n<p>Try writing something similar to <a href=\"https://www.baeldung.com/vavr-try\" rel=\"nofollow noreferrer\"><code>Try<T></code> from Vavr</a>.</p>\n\n<p>(Rant mode) This obsession with fluentism and calling it „functional” is in my opinion a sign of a novice Java 8 programmer, leading to monstrocities of <code>flatMapped</code>, <code>orElseGetted</code> <code>Optional</code> constructs. (/Rant mode)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T04:37:26.303",
"Id": "214213",
"ParentId": "214147",
"Score": "2"
}
},
{
"body": "<p><strong>Fact</strong>: To copy regular try-catch functionality, your implementation needs to check if a handler has been registered for exception's superclass and prevent initialization where superclass hides subclass try-block.</p>\n\n<p><strong>Fact</strong>: If you support multiple finally blocks, you should support multiple catch blocks for an exception type. Just for symmetry. This would conflict with previous point, so a design choice has to be made.</p>\n\n<p><strong>Opinion</strong>: The mental load from having to remember how yet another try-catch abstraction library works counteracts all benefit we might get from reduced \"boilerplate\".</p>\n\n<p><strong>Disclaimer</strong>: Facts expressed above may or may not be based on actual facts.</p>\n\n<p>Mental exercises like this are an important part of learning. But we need to evaluate the pros and the cons when we're done and not be afraid to scrap the bad ideas, like Lombok or Vavr should have been.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T06:27:58.700",
"Id": "214219",
"ParentId": "214147",
"Score": "1"
}
},
{
"body": "<p>Thank you for sharing your code and this idea with us! :)</p>\n\n<p>I have just some personal preferences and ideas to some of you \"major problems\" witch should be additional to the answers of <a href=\"https://codereview.stackexchange.com/users/193758/mateusz-stefek\">@Mateusz Stefek</a> and <a href=\"https://codereview.stackexchange.com/users/12866/torbenputkonen\">@TorbenPutkonen</a></p>\n\n<hr>\n\n<h1>Not Functional</h1>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>public Try<T> catching(Class ex, Function<Exception, T> handler) {\n if(/* ... */) {\n throw new IllegalStateException(\"exception \" + ex.getSimpleName() + \" has already been caught\");\n } else {\n /* ... */\n }\n}\n</code></pre>\n</blockquote>\n\n<p>In functional programming attempt not to throw any error instead you would return an <a href=\"http://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Either.html\" rel=\"noreferrer\"><code>Either</code></a>.</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>new Try<>(()-> Integer.parseInt(\"1\"))\n .catching(NumberFormatException.class, (e) -> 2)\n .execute();\n</code></pre>\n</blockquote>\n\n<p>On each method call on <code>Try</code> you modify it, but fp is all about immutability. </p>\n\n<h1>Some Refactoring</h1>\n\n<h2>Naming</h2>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>public Try<T> catching(Class ex, Function<Exception, T> handler)\n</code></pre>\n</blockquote>\n\n<p>I would write out <code>ex</code> to <code>exception</code>. Than we can change the name of</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>private final Map<Class, Function<Exception, T>> handlers\n</code></pre>\n</blockquote>\n\n<p>to <code>exceptionByHandler</code>, which makes it easier to read, because it suggests a <code>Map</code> more intuitively, than <code>handler</code> which could be a <code>List</code>.</p>\n\n<h2><code>Null</code> check</h2>\n\n<p>We have currently two <code>null</code> checks</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>// in execute\nif(finallyExpr != null)\n\n// in andFinally\nif (finallyExpr == null)\n</code></pre>\n</blockquote>\n\n<p>The utility class <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Objects.html\" rel=\"noreferrer\"><code>Objects</code></a> offers the static methods <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Objects.html#isNull-java.lang.Object-\" rel=\"noreferrer\"><code>isNull</code></a> and <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Objects.html#nonNull-java.lang.Object-\" rel=\"noreferrer\"><code>nonNull</code></a> and with an static import it could look like</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>// in execute\nif(nonNull(finallyExpr))\n\n// in andFinally\nif (isNull(finallyExpr))\n</code></pre>\n\n<p>But if we use an <code>Optional</code> in <code>andFinally</code> it could look like </p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public T andFinally(Runnable newFinallyExpr) {\n finallyExpr = Optional.ofNullable(finallyExpr)\n .orElseThrow(() -> new IllegalStateException(\"Cannot have multiple finally expressions\"));\n\n return execute();\n}\n</code></pre>\n\n<h2>Non Intuitiv API</h2>\n\n<blockquote>\n <p>The check in <code>andFinally</code> seems like it's unnecessary. [...]</p>\n</blockquote>\n\n<p>You already mention this as a flaw.. but from an other perspective. For me as a client it is not intuitive to have the method <code>andFinally</code> and <code>execute</code> to fire up the <code>Try</code>.</p>\n\n<p>More natural would be to let the client call the <code>execute</code> itself and override all <code>finally</code> with the next occurring <code>finally</code>.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>new Try<>(()-> Integer.parseInt(\"f\"))\n .catching(NumberFormatException.class, (e)-> 2)\n .catching(IllegalStateException.class, (e) -> 3)\n .andFinally(()-> System.out.println(\"Finally!\"))\n .andFinally(()-> System.out.println(\"Finally #2!\")) // overrides all previous finally\n .execute();\n</code></pre>\n\n<hr>\n\n<h1>Improvement</h1>\n\n<h2>Make <code>Try</code> immutable</h2>\n\n<p>As in functional programming objects are immutable we can do it in Java too. We can let the client modify a <code>Try</code> with methods we provide him and return each time a new <code>Try</code>.</p>\n\n<p>But to build up a <code>Try</code> we can create a <code>TryBuilder</code> witch is mutable. This is a common way which you can find in the Java-World to or example with <code>String</code> and <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html\" rel=\"noreferrer\"><code>StringBuilder</code></a>. </p>\n\n<h2><a href=\"https://en.wikipedia.org/wiki/State_pattern\" rel=\"noreferrer\">State Pattern</a></h2>\n\n<blockquote>\n <p>The need for <code>execute</code> when <code>andFinally</code> isn't used. I can't see how the class would know that all catches have been added though.</p>\n</blockquote>\n\n<p>This is a scenario for the State Pattern. We have our base-state, which allows the client to add multiple <code>catch</code>-cases. After the last <code>catch</code>-case we need to let the client allow <em>only one</em> <code>finally</code>-case. After this our object is in the execution-state.</p>\n\n<h2><a href=\"https://en.wikipedia.org/wiki/Builder_pattern\" rel=\"noreferrer\">Builder Pattern</a></h2>\n\n<p>We can mix the State-Pattern with the Builder-Pattern and on each state we can use a builder, which only let use the methods the client currently needs to make the api more intuitive. </p>\n\n<h2>Replace the Constructor</h2>\n\n<blockquote>\n <p>The need for <code>new</code> is unfortunate too. I figured I could take a page from Scala and create a static method that acts as a constructor, but then I'd need to do something like <code>Try.tryMethod</code> to reference it, which isn't a whole lot better.</p>\n</blockquote>\n\n<p>With a static method as constructor we are allowed to return a different reference type.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>new Try(/* ... */) // can only return an instance of Try\n\nTry.of(/* ... */) // can return everything you can imagine \n</code></pre>\n\n<p>For the use case I have in mind we need to make the constructor private and return a builder that we need to implement. </p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private Try(/* ... */) { /* ... */ }\n\npublic static <T> CatchBuilder of(Supplier<T> tryExpr) {\n return new CatchBuilder<T>(new TryBuilder<T>().withTryExpr(tryExpr));\n}\n</code></pre>\n\n<h2>Example Implementation</h2>\n\n<h3>Try</h3>\n\n<p>The <code>Try</code> is a public class with builds the API to the client. It provides the client outside of the package only a <code>of(Supplier<T> tryExpr)</code> to build up a <code>Try</code>. The constructor is package private therewith <code>TryBuilder</code> can access it. With <code>of(Supplier<T> tryExpr)</code> the clients gets a <code>CatchBuilder</code> (this is the modified State-Pattern mentioned above)</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class Try<T> {\n\n private Supplier<T> tryExpr;\n\n private Map<Class, Function<Exception, T>> handlers;\n\n private Runnable finallyExpr;\n\n Try(Supplier<T> tryExpr,\n Map<Class, Function<Exception, T>> handlers,\n Runnable finallyExpr) {\n this.tryExpr = tryExpr;\n this.handlers = handlers;\n this.finallyExpr = finallyExpr;\n }\n\n public static <T> CatchBuilder of(Supplier<T> tryExpr) {\n return new CatchBuilder<T>(new TryBuilder<T>().withTryExpr(tryExpr));\n }\n\n public T execute() {\n try {\n return tryExpr.get();\n } catch (Exception e) {\n if (handlers.containsKey(e.getClass())) {\n Function<Exception, T> handler = handlers.get(e.getClass());\n return handler.apply(e);\n } else {\n throw e;\n }\n } finally {\n if (finallyExpr != null) {\n finallyExpr.run();\n }\n }\n }\n}\n</code></pre>\n\n<h3>TryBuilder</h3>\n\n<p>This is the mutable way to build up a <code>Try</code>.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>class TryBuilder<T> {\n\n private Supplier<T> tryExpr;\n\n private Map<Class, Function<Exception, T>> handlers;\n\n private Runnable finallyExpr;\n\n public TryBuilder<T> withTryExpr(Supplier<T> tryExpr) {\n this.tryExpr = tryExpr;\n return this;\n }\n\n public TryBuilder<T> withHandlers(Map<Class, Function<Exception, T>> handlers) {\n this.handlers = handlers;\n return this;\n }\n\n public TryBuilder<T> withFinallyExpr(Runnable finallyExpr) {\n this.finallyExpr = finallyExpr;\n return this;\n }\n\n public Try<T> build() {\n return new Try<>(tryExpr, handlers, finallyExpr);\n }\n\n}\n</code></pre>\n\n<h3>CatchBuilder and FinallyBuilder</h3>\n\n<pre class=\"lang-java prettyprint-override\"><code>class CatchBuilder<T> {\n\n private final Map<Class, Function<Exception, T>> handlers = new HashMap<>();\n\n private final TryBuilder<T> tryBuilder;\n\n CatchBuilder(TryBuilder<T> tryBuilder) {\n this.tryBuilder = tryBuilder;\n }\n\n public CatchBuilder<T> withCatch(Class ex, Function<Exception, T> handler) {\n if (handlers.containsKey(ex)) {\n throw new IllegalStateException(\"exception \" + ex.getSimpleName() + \" has already been caught\");\n }\n\n handlers.put(ex, handler);\n return this;\n }\n\n public FinallyBuilder<T> and(Class ex, Function<Exception, T> handler) {\n withCatch(ex, handler);\n return new FinallyBuilder<>(tryBuilder.withHandlers(handlers));\n }\n\n public FinallyBuilder<T> onlyCatch(Class ex, Function<Exception, T> handler) {\n return and(ex, handler);\n }\n\n}\n\nclass FinallyBuilder<T> {\n private final TryBuilder<T> tryBuilder;\n\n public FinallyBuilder(TryBuilder<T> tryBuilder) {\n this.tryBuilder = tryBuilder;\n }\n\n public Try<T> finallyDo(Runnable newFinallyExpr) {\n return tryBuilder.withFinallyExpr(newFinallyExpr)\n .build();\n }\n\n public Try<T> withoutFinally() {\n return tryBuilder.build();\n }\n\n}\n</code></pre>\n\n<h3>Exmaple</h3>\n\n<pre class=\"lang-java prettyprint-override\"><code>public static void main(String[] args) {\n\n Try<Integer> firstTry = Try.of(() -> Integer.parseInt(\"f\"))\n .withCatch(NumberFormatException.class, (e) -> 2)\n .and(IllegalStateException.class, (e) -> 3)\n .finallyDo(() -> System.out.println(\"Finally!\"));\n\n Try<Integer> secondTry = Try.of(() -> Integer.parseInt(\"f\"))\n .onlyCatch(NumberFormatException.class, (e) -> 2)\n .withoutFinally();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T07:54:41.603",
"Id": "214225",
"ParentId": "214147",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "214225",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T02:33:01.517",
"Id": "214147",
"Score": "4",
"Tags": [
"java",
"error-handling"
],
"Title": "A more functional try...catch construct in Java"
} | 214147 |
<p>I'm writing a small class that wraps the existing functionality of <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/history/search" rel="nofollow noreferrer"><code>browser.history.search</code></a> in Firefox's WebExtensions API. The current API only directly searches for unique webpages as a <code>HistoryItem</code> that shows the last visit, but I need to get all visits within a given time frame.</p>
<p>This is done by finding all the <code>HistoryItem</code> results, then getting their associated <code>VisitItem</code> objects and combining their attributes into a result object. All of the history API search methods are asynchronous, so I tried to speed the process up by getting the visits of each history item without waiting for the results of the previous, and returning once all the calls were completed.</p>
<p>The code will work given a properly given a properly setup Firefox Addon. However, I'm not very familiar with promises or asynchronous programming, so I'm not sure if I've structured this in the most appropriate way.</p>
<p>I appreciate any feedback.</p>
<pre><code> function HistoryVisitFinder() {
/* Largest value of `maxResults` property that is accepted by the `query`
argument of browser.history.search().
This is a temporary workaround to the lack of a method for streaming large
number of results. */
const maxResultsCeiling = Math.pow(2, 52);
const msPerDay = 86400000;
function getLocalDateMsBounds(date) {
/* Get the start and end time in milliseconds-since-epoch for the local day
of `date` */
const localDateStart = (new Date(date.getFullYear(), date.getMonth(),
date.getDate())).getTime();
return [localDateStart, localDateStart + msPerDay - 1];
}
this.searchVisits = async function(text, startTime, endTime) {
/*
Find objects representing webpage history visits whose domain and/or url
contain `text` and whose visit times are within the inclusive range of
`startTime` to `endTime`.
Returns an array of objects with the associated HistoryItem and VisitItem
attributes:
{ url, title, id, referringVisitId, transition, visitTime }
*/
const results = [];
const query = {
text,
startTime,
endTime,
maxResults: maxResultsCeiling
};
const historyItemArray = await browser.history.search(query);
const expected = [];
const filterVisitsCallback = function(visit) {
return visit.visitTime <= endTime && visit.visitTime >= startTime;
}
/* Store the visits of each HistoryItem that fall between `startTime` and
`endTime` */
for (let historyItem of historyItemArray) {
const url = historyItem.url;
const title = historyItem.title;
const mapVisitsCallback = function(visit) {
return {
url,
title,
id: visit.visitId,
referringVisitId: visit.referringVisitId,
transition: visit.transition,
visitTime: visit.visitTime
}
}
expected.push(browser.history.getVisits({
url
})
.then(visitItemArray => {
results.push(...(
visitItemArray
.filter(filterVisitsCallback)
.map(mapVisitsCallback)
))
})
.catch(reason => {
console.warn('Could not get visits for HistoryItem', historyItem,
'Reason:', reason);
})
);
}
return await Promise.all(expected).then(() => {
/* Sort results in reverse chronological order */
results.sort((a, b) => b.visitTime - a.visitTime);
return results;
});
}
this.getVisitsOnDate = async function(text, date) {
/*
Find objects representing webpage history visits whose domain and/or url
contain `text` and whose visit times are on the same day as `date`.
Returns an array of objects with the associated HistoryItem and VisitItem
attributes:
{ url, title, id, referringVisitId, transition, visitTime }
*/
const [startTime, endTime] = getLocalDateMsBounds(date);
return await this.searchVisits(text, startTime, endTime);
}
}
</code></pre>
<p>Run using:</p>
<pre><code> const historyFinder = new HistoryVisitFinder();
historyFinder.getVisitsOnDate('', new Date()).then(console.log);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T19:02:55.407",
"Id": "414181",
"Score": "0",
"body": "(I expect code in code blocks, not hidden snippets - that may just be me. My comments were appropriate for code reachable via external hyperlinks.) Welcome to Code Review!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T19:05:35.140",
"Id": "414182",
"Score": "0",
"body": "I put it in the snippet so that the block doesn't instantly push the rest of the question off-screen. If that's unacceptable I can move it to a regular block, but that's less readable in my opinion. What do you mean by \"reachable via external hyperlinks\"? Thanks for your feedback."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T06:10:03.517",
"Id": "214151",
"Score": "1",
"Tags": [
"javascript",
"asynchronous"
],
"Title": "Asynchronous retrieval of WebExtension browser history visits"
} | 214151 |
<p>This script sends the user's shopping list to the recipient's email address. Maybe you can help me correct some mistakes.</p>
<pre><code>import smtplib
from email.message import EmailMessage
from getpass import getpass
from collections import defaultdict
import sys
def get_user_input(message, type=str):
while True:
try:
return type(input(message))
except ValueError:
print(f"Please input a {type}.")
class ShoppingList:
def __init__(self):
self.items = defaultdict(int)
def __str__(self):
return ("\n".join(f"{product} x {quantity}"
for product, quantity in self.items.items()))
def add_item(self, product, quantity):
self.items[product] += quantity
def email_to(self, from_email, password, *recipients):
email = EmailMessage()
email['Subject'] = "Shopping List"
email['From'] = from_email
email['To'] = recipients
message = str(self)
email.set_content(message)
try:
s = smtplib.SMTP_SSL('smtp.gmail.com', 465)
s.ehlo()
s.login(from_email, password)
s.send_message(email)
s.quit()
print("\nThe email has been sent.")
except Exception as e:
print("\nAn error occurred:", e)
if __name__ == '__main__':
name = input("Input your name: ")
print (f"Hi, {name}!")
shopping_list = ShoppingList()
while True:
try:
product = get_user_input("Input the product name (input \"stop\" when you are done): ")
if product == "stop":
break
quantity = get_user_input("Input the product quantity: ", int)
shopping_list.add_item(product, quantity)
except Exception as e:
print("\nAn error occurred:", e)
print("\nThese products have been added to the shopping list:")
print(shopping_list)
email = input("\nEmail: ")
password = getpass("Password: ")
recipient = input("Recipient's email: ")
shopping_list.email_to(email, password, recipient)
print("\nHave a nice day!")
sys.exit()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T19:12:21.830",
"Id": "414183",
"Score": "2",
"body": "It'd help if you could provide a list of changes from your [previous version](https://codereview.stackexchange.com/q/212309/12240)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T23:09:21.243",
"Id": "414215",
"Score": "3",
"body": "What mistakes have you got?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T06:09:36.763",
"Id": "414236",
"Score": "0",
"body": "what is your problem?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T10:26:12.067",
"Id": "414261",
"Score": "0",
"body": "@hjpotter92 The script now uses functions and a class. Also, instead of asking how many products the user want, I made a loop that keeps asking for product name and it's quantity until the user inputs \"stop\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T10:26:56.023",
"Id": "414262",
"Score": "0",
"body": "@YuZhang The script works fine. I was asking if you can identify any code mistake I did (about the style etc.)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T19:17:38.930",
"Id": "414330",
"Score": "0",
"body": "You didn't read @Graipher's reply on last post completely: \"_add a docstring to it to add even more description of what the function does_\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T18:17:00.617",
"Id": "414463",
"Score": "0",
"body": "@close voters, why? The question is correctly formed and respects the format of CR posts. I agree there could be more information regarding the previous post, but I don't think this is a reason to \"close vote\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T18:17:30.840",
"Id": "414464",
"Score": "0",
"body": "@hjpotter92 OP is not obligated to apply every comments in the code review for it to be valid."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T08:39:33.783",
"Id": "214154",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"email"
],
"Title": "Shopping list sent by email using Python 3"
} | 214154 |
<p>My question is more of a "can someone give me tips" rather than "can you do it for me"</p>
<p>I have been writing a C code implementation that takes a 32-char String in the form of binary (supposed to act as a 32-bit instruction) and divides it to four 8-char strings. Those four strings are converted to Hex and fed to a small code program that returns the Rijndael S-box Forward and Inverse equivalent.</p>
<p>When I showed the code to my supervisor, he asked me to optimize the code I have. Even though after many iterations of changing different parts of the code and reducing the performance time slightly, I do not have ideas of how to improve it. So, the code is below, and I would be grateful for any tips and suggestions of how I can improve the performance of the code below. (Also, if you could suggest how to improve the amount of memory the code is using, that would be fabulous as well.)</p>
<pre><code>#include <stdio.h>
#include <string.h>
unsigned char mulinv(unsigned char in) {
// multiplicative inverse in Rijndael's finite field.
unsigned char k = 1, l = 1;
//GF(2^8) = GF(2)[x]/(x8 + x4 + x3 + x + 1)
//this takes the number of times I have to itterate in Rijndael's
//finite field before I get my equivelant
do {
// equals k * 3
k = k ^ (k << 1) ^ (k & 0x80 ? 0x1B : 0);
// equals l / 3
l ^= l << 1; l ^= l << 2; l ^= l << 4; l ^= l & 0x80 ? 0x09 : 0;
} while (k != in);
return l;
}
unsigned char makesbox(unsigned char in) {
unsigned char s, x, l;
l = mulinv(in);
// affine transformation
s = l ^ ((l << 1) | (l >> 7)) ^ ((l << 2) | (l >> 6)) ^ ((l << 3) | (l >> 5)) ^ ((l << 4) | (l >> 4));
x = s ^ 0x63;
return x;
}
unsigned char invsbox(unsigned char in) {
unsigned char x;
// affine transformation
x = ((in << 1) | (in >> 7)) ^ ((in << 3) | (in >> 5)) ^ ((in << 6) | (in >> 2)) ^ 0x05;
x = mulinv(x);
return x;
}
void instSbox(unsigned char inst []) {
// printf("Inst is : ");
int i = 0;
// for (i = 0; i < 32; i++){
// printf("%c", inst[i]);
// }
unsigned char in[9];
printf("\n---------------|Byte|SBox\n");
for (i = 0; i < 33; i++){
if (i%8 == 0 && i != 0) {
in[8] = '\0'; //NUL terminate the string.
unsigned char t = (unsigned char) strtol(in, NULL, 2);
printf("0x%X ", t);
printf("0x%X ", makesbox(t));
printf("0x%X \n", invsbox(t));
}
in[i%8] = inst[i];
printf("%c ", in[i%8]);
}
}
void main(){
unsigned char inst [32] = "10101010101010101111111100111101"; // 32 bits (length of instructions)
instSbox(inst);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T16:29:28.190",
"Id": "414155",
"Score": "2",
"body": "Do you have to use strings, there are better ways to represent binary in C?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T18:36:32.800",
"Id": "414173",
"Score": "0",
"body": "`my supervisor [] asked me to optimize the code` Are you positive she was asking you to *reduce time*? While *symmetric key encryption* necessarily takes its own sweet time, substitution boxes don't get changed around."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T14:06:21.507",
"Id": "414283",
"Score": "0",
"body": "Do be careful when optimizing - sometimes in cryptography, the *fastest* algorithm is insecure, as it leaks information to an adversary that can monitor timing and/or power consumption differences."
}
] | [
{
"body": "<p>The indentation seems to have gone wrong. This may not be entirely your fault - the Stack Exchange backend converts tabs to spaces - but it makes it harder than it should be to match { and } on some blocks.</p>\n\n<hr>\n\n<p>The obvious place to look for optimisation is <code>mulinv</code>. One way to speed it up is a logarithm table - basically, do the loop once to fill a table with all 256 cases, and then just look up values in the table. More sophisticated approaches are to use Euclid's algorithm for GCD on elements of <span class=\"math-container\">\\$GF(2^8)\\$</span>, or to consider the field <span class=\"math-container\">\\$GF(2^8)\\$</span> as a tower of field extensions, <span class=\"math-container\">\\$GF(2)[x]/p(x)/q(x)\\$</span>, which makes it fairly simple to reduce the inversion to one in <span class=\"math-container\">\\$GF(16)\\$</span>. You can find more detailed explanations on another site from this network in a rather unusual challenge format: <a href=\"https://codegolf.stackexchange.com/q/9276/194\">https://codegolf.stackexchange.com/q/9276/194</a></p>\n\n<hr>\n\n<p>The rotations for the affine transforms also look ripe for optimisation. If you use a 16-bit integer then</p>\n\n<blockquote>\n<pre><code> s = l ^ ((l << 1) | (l >> 7)) ^ ((l << 2) | (l >> 6)) ^ ((l << 3) | (l >> 5)) ^ ((l << 4) | (l >> 4));\n</code></pre>\n</blockquote>\n\n<p>can be replaced with</p>\n\n<pre><code> uint16_t l16 = l;\n uint16_t t = l16 ^ (l16 << 1) ^ (l16 << 2) ^ (l16 << 3) ^ (l16 << 4);\n s = (unsigned char)(t ^ (t >> 8));\n</code></pre>\n\n<p>and similarly in <code>invsbox</code>.</p>\n\n<hr>\n\n<p>Finally, a point on names. <code>inst</code> is completely cryptic to me with the context given. Perhaps you could use the full word, comment on the meaning, or consider whether in fact whatever word it abbreviates is inherently what is operated on or merely a specific application.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T15:53:55.323",
"Id": "414297",
"Score": "0",
"body": "I will for sure try the tower of field extensions idea. I just looked at the link you gave and from there found some good resources I can utilize. The affine transformation also looks interesting. the name inst is short of instruction (just to keep it in my mind that I will be feeding 32-bit instructions in form of binary as strings to this algorithm)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T23:56:11.803",
"Id": "214206",
"ParentId": "214157",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "214206",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T10:21:54.693",
"Id": "214157",
"Score": "1",
"Tags": [
"performance",
"c",
"aes"
],
"Title": "Rijndael S-box for a string of bits"
} | 214157 |
<p>Im relatively new in python. I've wrote my "first" script to do some staff for me. I am creating Image dataset for Mashine Lerning. In Photoshop, I select the area I need in the large image and using the Photoshop script I save the selected area to a folder <code>tree_checker</code>. I have different scripts configured in Photoshop, each script saves a file with a specific name. This script takes every new file in directory and moves it in depending directory.</p>
<pre><code>"""
This script provides automatically file ordering.
"""
import os
import time
def get_dir_length(path):
"""
Returns the length of given directory e.g the amount of files inside the folder.
"""
return len([f for f in os.listdir(path)if os.path.isfile(os.path.join(path, f))])
ORC_MALE = 'orc_male.jpg'
ORC_MALE_MAG = 'orc_male_mag.jpg'
ORC_FEMALE = 'orc_female.jpg'
DARKELF_MALE = 'darkelf_male.jpg'
DARKELF_FEMALE = 'darkelf_female.jpg'
HUMAN_MALE = 'human_male.jpg'
HUMAN_MALE_MAG = 'human_male_mag.jpg'
HUMAN_FEMALE = 'human_female.jpg'
ELF_MALE = 'elf_male.jpg'
ELF_FEMALE = 'elf_female.jpg'
DWARF_MALE = 'dwarf_male.jpg'
DWARF_FEMALE = 'dwarf_female.jpg'
PATH_TO_WATCH = './tf_models/tree_checker/'
BEFORE = dict([(f, None) for f in os.listdir(PATH_TO_WATCH)])
COUNT_AMOUNT_OF_FILE_MOVE = 0
try:
while 1:
time.sleep(1)
AFTER = dict([(f, None) for f in os.listdir(PATH_TO_WATCH)])
ADDED = [f for f in AFTER if not f in BEFORE]
REMOVED = [f for f in BEFORE if not f in AFTER]
if ADDED:
if ''.join(ADDED) == ORC_MALE:
DIR_LEN = get_dir_length('./tf_models/orc_male/')
try:
os.rename((PATH_TO_WATCH + ''.join(ADDED)), \
('./tf_models/orc_male/orc_male_' + str(DIR_LEN+1) + '.jpg'))
except FileExistsError:
os.rename((PATH_TO_WATCH + ''.join(ADDED)), \
('./tf_models/orc_male/orc_male_' + str(DIR_LEN+1) + 'a.jpg'))
COUNT_AMOUNT_OF_FILE_MOVE += 1
if ''.join(ADDED) == ORC_MALE_MAG:
DIR_LEN = get_dir_length('./tf_models/orc_male_mag/')
try:
os.rename((PATH_TO_WATCH + ''.join(ADDED)), \
('./tf_models/orc_male_mag/orc_male_mag_' + str(DIR_LEN+1) + '.jpg'))
except FileExistsError:
os.rename((PATH_TO_WATCH + ''.join(ADDED)), \
('./tf_models/orc_male_mag/orc_male_mag_' + str(DIR_LEN+1) + 'a.jpg'))
COUNT_AMOUNT_OF_FILE_MOVE += 1
if ''.join(ADDED) == ORC_FEMALE:
DIR_LEN = get_dir_length('./tf_models/orc_female/')
try:
os.rename((PATH_TO_WATCH + ''.join(ADDED)), \
('./tf_models/orc_female/orc_male_' + str(DIR_LEN+1) + '.jpg'))
except FileExistsError:
os.rename((PATH_TO_WATCH + ''.join(ADDED)), \
('./tf_models/orc_female/orc_male_' + str(DIR_LEN+1) + 'a.jpg'))
COUNT_AMOUNT_OF_FILE_MOVE += 1
if ''.join(ADDED) == DARKELF_MALE:
DIR_LEN = get_dir_length('./tf_models/darkelf_male/')
try:
os.rename((PATH_TO_WATCH + ''.join(ADDED)), \
('./tf_models/darkelf_male/darkelf_male_' + str(DIR_LEN+1) + '.jpg'))
except FileExistsError:
os.rename((PATH_TO_WATCH + ''.join(ADDED)), \
('./tf_models/darkelf_male/darkelf_male_' + str(DIR_LEN+1) + 'a.jpg'))
COUNT_AMOUNT_OF_FILE_MOVE += 1
if ''.join(ADDED) == DARKELF_FEMALE:
DIR_LEN = get_dir_length('./tf_models/darkelf_female/')
try:
os.rename((PATH_TO_WATCH + ''.join(ADDED)), \
('./tf_models/darkelf_female/darkelf_female_' + str(DIR_LEN+1) + '.jpg'))
except FileExistsError:
os.rename((PATH_TO_WATCH + ''.join(ADDED)), \
('./tf_models/darkelf_female/darkelf_female_' + str(DIR_LEN+1) + 'a.jpg'))
COUNT_AMOUNT_OF_FILE_MOVE += 1
if ''.join(ADDED) == HUMAN_MALE:
DIR_LEN = get_dir_length('./tf_models/human_male/')
try:
os.rename((PATH_TO_WATCH + ''.join(ADDED)), \
('./tf_models/human_male/human_male_' + str(DIR_LEN+1) + '.jpg'))
except FileExistsError:
os.rename((PATH_TO_WATCH + ''.join(ADDED)), \
('./tf_models/human_male/human_male_' + str(DIR_LEN+1) + 'a.jpg'))
COUNT_AMOUNT_OF_FILE_MOVE += 1
if ''.join(ADDED) == HUMAN_MALE_MAG:
DIR_LEN = get_dir_length('./tf_models/human_male_mag/')
try:
os.rename((PATH_TO_WATCH + ''.join(ADDED)), \
('./tf_models/human_male_mag/human_male_mag_' + str(DIR_LEN+1) + '.jpg'))
except FileExistsError:
os.rename((PATH_TO_WATCH + ''.join(ADDED)), \
('./tf_models/human_male_mag/human_male_mag_' + str(DIR_LEN+1) + 'a.jpg'))
COUNT_AMOUNT_OF_FILE_MOVE += 1
if ''.join(ADDED) == HUMAN_FEMALE:
DIR_LEN = get_dir_length('./tf_models/human_female/')
try:
os.rename((PATH_TO_WATCH + ''.join(ADDED)), \
('./tf_models/human_female/human_female_' + str(DIR_LEN+1) + '.jpg'))
except FileExistsError:
os.rename((PATH_TO_WATCH + ''.join(ADDED)), \
('./tf_models/human_female/human_female_' + str(DIR_LEN+1) + 'a.jpg'))
COUNT_AMOUNT_OF_FILE_MOVE += 1
if ''.join(ADDED) == ELF_MALE:
DIR_LEN = get_dir_length('./tf_models/elf_male/')
try:
os.rename((PATH_TO_WATCH + ''.join(ADDED)), \
('./tf_models/elf_male/elf_male_' + str(DIR_LEN+1) + '.jpg'))
except FileExistsError:
os.rename((PATH_TO_WATCH + ''.join(ADDED)), \
('./tf_models/elf_male/elf_male_' + str(DIR_LEN+1) + 'a.jpg'))
COUNT_AMOUNT_OF_FILE_MOVE += 1
if ''.join(ADDED) == ELF_FEMALE:
DIR_LEN = get_dir_length('./tf_models/elf_female/')
try:
os.rename((PATH_TO_WATCH + ''.join(ADDED)), \
('./tf_models/elf_female/elf_female_' + str(DIR_LEN+1) + '.jpg'))
except FileExistsError:
os.rename((PATH_TO_WATCH + ''.join(ADDED)), \
('./tf_models/elf_female/elf_female_' + str(DIR_LEN+1) + 'a.jpg'))
COUNT_AMOUNT_OF_FILE_MOVE += 1
if ''.join(ADDED) == DWARF_MALE:
DIR_LEN = get_dir_length('./tf_models/dwarf_male/')
try:
os.rename((PATH_TO_WATCH + ''.join(ADDED)), \
('./tf_models/dwarf_male/dwarf_male_' + str(DIR_LEN+1) + '.jpg'))
except FileExistsError:
os.rename((PATH_TO_WATCH + ''.join(ADDED)), \
('./tf_models/dwarf_male/dwarf_male_' + str(DIR_LEN+1) + 'a.jpg'))
COUNT_AMOUNT_OF_FILE_MOVE += 1
if ''.join(ADDED) == DWARF_FEMALE:
DIR_LEN = get_dir_length('./tf_models/dwarf_female/')
try:
os.rename((PATH_TO_WATCH + ''.join(ADDED)), \
('./tf_models/dwarf_female/dwarf_female_' + str(DIR_LEN+1) + '.jpg'))
except FileExistsError:
os.rename((PATH_TO_WATCH + ''.join(ADDED)), \
('./tf_models/dwarf_female/dwarf_female_' + str(DIR_LEN+1) + 'a.jpg'))
COUNT_AMOUNT_OF_FILE_MOVE += 1
BEFORE = AFTER
if (COUNT_AMOUNT_OF_FILE_MOVE % 10 == 0 and COUNT_AMOUNT_OF_FILE_MOVE > 0):
print('Currently moved ' + str(COUNT_AMOUNT_OF_FILE_MOVE) + \
' files. - ' + str(time.clock))
except KeyboardInterrupt:
print(COUNT_AMOUNT_OF_FILE_MOVE)
</code></pre>
<p>Some of place wich could be refactored is </p>
<blockquote>
<p>"using a dictionary comprehension"</p>
</blockquote>
<p>as my pylint says. But I don't know how to du that. Also Pylint says that is will be faster if I do refactor here.
<a href="https://i.stack.imgur.com/wKqTG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wKqTG.png" alt="enter image description here"></a></p>
<blockquote>
<p>consider-using-dict-comprehension (R1717): Consider using a
dictionary comprehension Although there is nothing syntactically wrong
with this code, it is hard to read and can be simplified to a dict
comprehension.Also it is faster since you don't need to create another
transient list</p>
</blockquote>
<p><strong>What does this code do?</strong></p>
<p>Folders tree:</p>
<pre><code>Project
|-elf_male
|-elf_female
|-darkelf_male
|-darkelf_female
|-dwarf_male
|-dwarf_female
|-human_male
|-human_male_mag
|-human_female
|-orc_male
|-orc_male_mag
|-orc_female
`-tree_checker
</code></pre>
<p>In general this script continuously watching if there is a new image in folder <code>tree_checker</code> as soon as there is new image <em>(images in this folder you have to put manually)</em> script checks the name of the image (e.g <code>orc_male.jpg</code>, <code>orc_male_mag.jpg</code>, <code>orc_female.jpg</code> etc) and moves the image to the folder according to the name of the image.</p>
<p>This script is actually quite slow. If you too quickly insert few images into the <code>tree_checker</code> folder, it breaks.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T13:50:02.720",
"Id": "414150",
"Score": "2",
"body": "You say \"I don't know how to do that\", but searching \"[Python dictionary comprehension](https://duckduckgo.com/?q=Python+dictionary+comprehension&t=ffcm&ia=web)\"'s first result tells you how to, and DDG tells you on the right hand side too."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T14:33:22.577",
"Id": "414151",
"Score": "0",
"body": "Yeah, in most exaples I found, shown the general syntax and what it exactly do. In my case (for me, as I didn't really code too much in python) it looks strang, \"I don't know\" means, I know how to refactor this part of code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T10:31:10.957",
"Id": "414400",
"Score": "2",
"body": "I have rolled back your edit. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. Also, it was very unclear what you were measuring in your \"performance test\" and not clear if lots of function calls was a good or a bad thing, and also all the different versions of the code contains `time.sleep(1)` which is not much point in performance testing."
}
] | [
{
"body": "<p><strong>Warning</strong>: I did not run your code, and the revised version is not tested.</p>\n\n<ol>\n<li>Get familiar with <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> style guide. You violate some of its points, like maximum line length and naming conventions (upper case is for constants).</li>\n<li>Use <a href=\"https://docs.python.org/library/pathlib.html\" rel=\"nofollow noreferrer\">pathlib</a> over <code>os</code>. It has many nice features that will make your life easier. </li>\n<li><p>You use dicts incorrectly in lines like this one:</p>\n\n<blockquote>\n<pre><code>BEFORE = dict([(f, None) for f in os.listdir(PATH_TO_WATCH)])\n</code></pre>\n</blockquote>\n\n<p>There is no point in having the pairs of \"file\"-<code>None</code> and never update the values. Probably, you meant to use <a href=\"https://docs.python.org/tutorial/datastructures.html#sets\" rel=\"nofollow noreferrer\">sets</a> instead.</p></li>\n<li><p><code>while 1:</code> should be <code>while True:</code>.</p></li>\n<li><p><a href=\"https://softwareengineering.stackexchange.com/questions/103233/why-is-dry-important\">Don't repeat yourself</a>. The code following after <code>if ADDED:</code> line has code blocks with the same logic over and over again. Consider putting all those <code>ORC_MALE</code>, <code>ORC_MALE_MAG</code>, etc. in a set, and check if an added file is in that set. If it is, you move the file from one location to another where the path names of both locations can be constructed from the names in the initial set. </p></li>\n<li><p>Don't repeat yourself again. In those lines where you create new names of the files that are going to be moved, you repeat the code in <code>try</code> and <code>except FileExistsError:</code> clauses: </p>\n\n<blockquote>\n<pre><code>try:\n os.rename((PATH_TO_WATCH + ''.join(ADDED)), \\\n ('./tf_models/orc_male/orc_male_' + str(DIR_LEN+1) + '.jpg'))\nexcept FileExistsError:\n os.rename((PATH_TO_WATCH + ''.join(ADDED)), \\\n ('./tf_models/orc_male/orc_male_' + str(DIR_LEN+1) + 'a.jpg'))\n</code></pre>\n</blockquote>\n\n<p>Take the common logic out.</p></li>\n<li><p>Split the logic into smaller functions. Now you have a huge block of code that does too many things.</p></li>\n<li><p>Make use of <a href=\"https://docs.python.org/3/whatsnew/3.6.html#pep-498-formatted-string-literals\" rel=\"nofollow noreferrer\">f-strings</a></p></li>\n</ol>\n\n<p><strong>Revised code:</strong> </p>\n\n<pre><code>\"\"\"This script provides automatically file ordering.\"\"\"\nimport time\nfrom pathlib import Path\nfrom typing import (Any,\n Iterable,\n Iterator,\n Set)\n\nIMAGES_PATHS = {'orc_male.jpg',\n 'orc_male_mag.jpg',\n 'orc_female.jpg',\n 'darkelf_male.jpg',\n 'darkelf_female.jpg',\n 'human_male.jpg',\n 'human_male_mag.jpg',\n 'human_female.jpg',\n 'elf_male.jpg',\n 'elf_female.jpg',\n 'dwarf_male.jpg',\n 'dwarf_female.jpg'}\n\nPATH_TO_WATCH = Path('tf_models', 'tree_checker')\n\n\ndef run_transfer(path: Path,\n *,\n sleep_time: int = 1,\n check_against: Set[str]) -> None:\n \"\"\"TODO: add docstring\"\"\"\n files_before = set(path.iterdir())\n moved_files_count = 0\n try:\n while True:\n time.sleep(sleep_time)\n files_after = set(path.iterdir())\n added_files = files_after - files_before\n for added_file in added_files:\n if added_file.stem in check_against:\n transfer_file(added_file)\n moved_files_count += len(added_files)\n files_before = files_after\n if moved_files_count % 10 == 0 and moved_files_count > 0:\n print(f'Currently moved {str(moved_files_count)} files. '\n f'- {str(time.clock)}')\n except KeyboardInterrupt:\n print(moved_files_count)\n\n\ndef transfer_file(file: Path) -> None:\n \"\"\"TODO: add docstring\"\"\"\n path = Path('tf_models', file.stem)\n dir_len = dir_length(path)\n path_to_rename = PATH_TO_WATCH / file\n new_name = Path('tf_models',\n file.stem,\n f'{file.stem}_{str(dir_len + 1)}.jpg')\n if new_name.exists():\n new_name = new_name.parent / f'{new_name.stem}a.jpg'\n path_to_rename.rename(new_name)\n\n\ndef dir_length(path: Path) -> int:\n \"\"\"\n Returns the length of given directory,\n e.g the amount of files inside the folder.\n \"\"\"\n return capacity(files_paths(path))\n\n\ndef files_paths(path: Path = '.') -> Iterator[Path]:\n yield from filter(Path.is_file, Path(path).iterdir())\n\n\ndef capacity(iterable: Iterable[Any]) -> int:\n return sum(1 for _ in iterable)\n\n\nif __name__ == '__main__':\n run_transfer(PATH_TO_WATCH, check_against=IMAGES_PATHS)\n</code></pre>\n\n<p>Note how simple became the logic of getting newly added files when using sets.</p>\n\n<p>You should also do something with the <code>'tf_models'</code> string. It shouldn't be hardcoded, and it's better to take it out as a constant or a default parameter. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T20:03:18.560",
"Id": "414336",
"Score": "0",
"body": "It didn't moved in first test, I'll debug it and find the problem. I'll check first which of the two implementations are faster in performance perspective."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T14:12:07.410",
"Id": "214244",
"ParentId": "214161",
"Score": "3"
}
},
{
"body": "<blockquote>\n<p>Some of place wich could be refactored is</p>\n<blockquote>\n<p>"using a dictionary comprehension"</p>\n</blockquote>\n<p>as my pylint says. But I don't know how to du that.</p>\n</blockquote>\n<p>Let's start with that as this is the least of this code problems. A dictionary comprehension is roughly like a list-comprehension (that you know of and use well) except:</p>\n<ol>\n<li>it produces a dictionary instead of a list;</li>\n<li>it uses braces instead of brackets;</li>\n<li>it uses a <code>key: value</code> token instead of a single element in front of the <code>for</code> keyword.</li>\n</ol>\n\n<pre><code>BEFORE = {f: None for f in os.listdir(PATH_TO_WATCH)}\n</code></pre>\n<p>But since you’re not changing the value, you can use <a href=\"https://docs.python.org/3/library/stdtypes.html#dict.fromkeys\" rel=\"nofollow noreferrer\"><code>dict.fromkeys</code></a>:</p>\n<pre><code>BEFORE = dict.fromkeys(os.listdir(PATH_TO_WATCH))\n</code></pre>\n<p>However, you never make use of the values of the dictionary anyway. So keep it simple and use <a href=\"https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset\" rel=\"nofollow noreferrer\"><code>set</code></a>s instead. This even let you compute additions and suppressions ways more easily:</p>\n<pre><code>after = set(os.listdir(PATH_TO_WATCH))\nadded = after - before\nremoved = before - after\n</code></pre>\n<hr />\n<p>Now, onto your real problem: this code repeats exactly the same instructions for each of your subfolders! This less than optimal. Instead, write a function that operate on the folder name. It would also be a good idea to list these destination folders automatically instead of hardcoding their names.</p>\n<p>Also your usage of <code>''.join(ADDED)</code> is problematic: if you ever add more than one file every second in the folder you monitor, you will end up with a name that can't be matched againts anything:</p>\n<pre><code>>>> added = ['human_male.jpg', 'elf_female.jpg']\n>>> ''.join(added)\nhuman_male.jpgelf_female.jpg\n</code></pre>\n<p>Instead you should <strong>loop</strong> over <code>ADDED</code> and check if the file names match either of the destination folder.</p>\n<hr />\n<p>Your check for existing file may help catch some overwrite errors, but what if the second filename also already exist? If you want to properly handle such cases, you should try in a loop with increasing attempts to write the new file.</p>\n<hr />\n<p>Lastly, try to separate computation from presentation. Make this a reusable function and move your <code>print</code>s outside of there, into a <code>main</code> part:</p>\n<pre><code>#! /usr/bin/env python3\n\n\n"""This script provides automatic file ordering.\n"""\n\nimport os\nimport time\nimport pathlib\nfrom itertools import count\n\n\ndef get_dir_length(path):\n """Return the amount of files inside a folder"""\n return sum(1 for f in path.iterdir() if f.is_file())\n\n\ndef monitor_folder(path):\n path = pathlib.Path(path).absolute()\n destinations = {f.name for f in path.parent.iterdir() if f.is_dir()}\n destinations.remove(path.name)\n content = {f.name for f in path.iterdir()}\n\n while True:\n time.sleep(1)\n current = {f.name for f in path.iterdir()}\n added = current - content\n # removed = content - current\n\n for filename in added:\n name, suffix = os.path.splitext(filename)\n if suffix != '.jpg':\n continue\n\n if name in destinations:\n size = get_dir_length(path.parent / name)\n new_name = '{}_{}.jpg'.format(name, size)\n for attempt in count():\n try:\n os.rename(str(path / filename), str(path.parent / name / new_name))\n except FileExistsError:\n new_name = '{}_{}({}).jpg'.format(name, size, attempt)\n else:\n break\n yield filename, new_name\n\n content = current\n\n\ndef main(folder_to_watch):\n files_moved = 0\n try:\n for _ in monitor_folder(folder_to_watch):\n files_moved += 1\n if files_moved % 10 == 0:\n print('Currently moved', files_moved, 'files. −', time.process_time())\n except KeyboardInterrupt:\n print('End of script, moved', files_moved, 'files.')\n\n\nif __name__ == '__main__':\n main('./tf_models/tree_checker/')\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T20:01:12.060",
"Id": "414335",
"Score": "0",
"body": "Thanks! Works like a charm! Is there a way to check performance of the script to show which of two answers works faster?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T20:06:29.713",
"Id": "414337",
"Score": "0",
"body": "@khashashin [`timeit`](https://docs.python.org/3/library/timeit.html) and/or [`cProfile`](https://docs.python.org/3/library/profile.html)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T14:19:02.063",
"Id": "214245",
"ParentId": "214161",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "214245",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T11:37:26.287",
"Id": "214161",
"Score": "2",
"Tags": [
"python",
"performance"
],
"Title": "Automatically transferring files between folders depending on the file name"
} | 214161 |
<p>I am writing a function that reads all consecutive blanks in a string, moves the pointer to the next non-blank char, and return a struct "token" that contains the blanks it found.</p>
<p>The main function is defined as</p>
<pre><code>int match_ws(const char** p, struct token* tok)
</code></pre>
<p>where <code>p</code> points to the beginning of the strings to analyze, and <code>tok</code> will contain the result after the function returns. Return value is either 1 (successful), or 0.</p>
<p>[EDIT]</p>
<p><code>match_ws</code> starts analyzing the string given as first input, and reads all consecutive whitespaces, while advancing the pointer too. It stores all blanks it found in the struct (second input) and returns 1. If it didn't find any blank, or too many, returns 0 without modifying <code>tok</code>.</p>
<p>So, if the input is <code>const char* p = " . +"</code> then after <code>match_ws</code> ran the <code>tok</code> structure will contain <code>lexeme = " "</code> (the four spaces at the beginning of <code>p</code>, and <code>type = WS</code> (enum type for "whitespace").
If the input is <code>const char* p = ". ; )"</code> then the function just returns <code>0</code> without modifying <code>tok</code>, because <code>**p</code> is not a whitespace (it's a dot).</p>
<p>Overall, this is part of a parser, and <code>match_ws</code> is the function that "consumes" all whitespaces -- not relevant for the parser. I believe the function behaves correctly, but since I am not experienced with the C language, I would like to have reviews about how I handled allocation of memory, pointer, pointer to pointers, function definition, etc.</p>
<p>[/EDIT]</p>
<p>Overall, my questions are about correct usage of pointers, pointers-to-pointers, good choice in the type of arguments (for the function definitions), and memory management.</p>
<p>I wrote my questions in the comments, but I am not so used to memory management and coding standards in C, so would appreciate a code review and all suggestions welcome.</p>
<p>I also added some boilerplate code so the file can be compiled and executed. As you can guess is part of a larger code, but I reduced it to be a minimal example.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#define MAX_LINE 100
/*
* Some boilerplate code
*/
enum token_type {
WS, // white spaces
Eof
};
struct token{
char* lexeme;
enum token_type type;
};
char consume(const char** p);
/*
* Main function to work on.
* Questions:
* - char ws[MAX_LINE] or using malloc?
* - is it OK to initialize char ws with "" ?
* - Am I appending char into ws in a optimal way?
* - is it OK to return int and modify input argument tok, or should create a new tok and return it?
* - makes sense to have pointer-to-pointer as input? Else what?
*/
int match_ws(const char** p, struct token* tok) {
/*
* Find all consecutives blanks starting from position p
* Modify the input struct token.
* Return 1 if execution was successful, 0 otherwise.
*/
if ( **p != ' ' &&
**p != '\t' &&
**p != '\r' &&
**p != '\n')
{
printf("Bad call to whitespace!!");
return 0;
}
int i = 0;
char c;
char ws[MAX_LINE] = "";
do {
if (i >= MAX_LINE) {
printf("Found more than %d white spaces", MAX_LINE);
return 0;
}
c = consume(p);
printf("WHITESPACE : Current char is |%c|\n", c);
ws[i++] = c;
}
// Here p has been already advanced by the call to consume fn
while (**p == ' ' || **p == '\t' || **p == '\r' || **p == '\n');
tok->lexeme = ws;
tok->type = WS;
return 1;
}
/*
* More boilerplate code to compile
*/
const char* type2char (enum token_type t) {
switch (t)
{
case WS: return "WS";
default: return "UNK";
}
}
void print_token(struct token* p) {
printf("<%s, %s>\n", p->lexeme, type2char(p->type));
}
char consume(const char** p) {
// Advances the pointer while reading the input
char c = **p;
(*p)++;
return c;
}
/*
* Main.
* Questions:
* - is it OK to pass arguments to match_ws via '&' notation?
* - Makes sense to have const char* line? Or just char* ?
* - Should tok be initialized somehow?
* - Is there anything that has to be free() eventually?
*/
int main() {
const char* line = " +";
struct token tok;
match_ws(&line, &tok);
print_token(&tok);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T18:22:52.503",
"Id": "414171",
"Score": "1",
"body": "I find it hard to understand the more exact outcome of `match_ws` interface to look deeper into the code. Possibly if you add some examples get a better grasp of the interface intention."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T12:06:05.387",
"Id": "414266",
"Score": "1",
"body": "You seem to have registered with two different accounts; you'll need to flag for moderator attention to have your accounts [merged](/help/merging-accounts)."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T11:48:54.057",
"Id": "214162",
"Score": "0",
"Tags": [
"c"
],
"Title": "Read consecutive blanks in array"
} | 214162 |
<p>I wrote a simple String class implementation using <code>unique_ptr</code> and move semantics. Is my implementation good enough in terms of design and efficiency?</p>
<h3>Stringy.h</h3>
<pre><code>#pragma once
#include <iostream>
#include <cstring>
#include <memory>
class Stringy {
private:
std::unique_ptr<char[]> p;
std::size_t size;
std::size_t len;
enum {Factor = 3};
static void _debug(const char *x)
{
#if DEBUG
std::cout << "=> " << x << " <=" << std::endl;
#endif
}
public:
Stringy(const char* ptr);
Stringy(const Stringy& Other);
Stringy(Stringy&& Other);
const Stringy& operator=(Stringy Other);
const Stringy& operator=(Stringy&& Other);
void swap(Stringy& Other);
void concat(const Stringy& Other);
void concat(const char* One);
void move(Stringy& Other);
std::size_t length() const;
Stringy operator+(const Stringy& Other) const;
Stringy operator+(const char* ptr) const;
const char& operator[](std::size_t index) const;
char& operator[](std::size_t index);
friend Stringy&& operator+ (Stringy&& Lhs, const char* Rhs);
friend Stringy&& operator+ (Stringy&& Lhs, const Stringy& Rhs);
friend std::ostream& operator<< (std::ostream& cout, const Stringy& Other);
~Stringy();
};
</code></pre>
<h3>Stringy.cpp</h3>
<pre><code>#define DEBUG false
Stringy::Stringy(const char *ptr)
{
_debug("default pointer Ctor");
len = strlen(ptr);
size = len * Factor;
p = std::make_unique<char[]>(size);
std::copy(ptr, ptr + len, p.get());
p[len] = '\0';
}
Stringy::Stringy(const Stringy &Other): size(Other.size), len(0)
{
_debug("Copy Ctor");
p = std::make_unique<char[]>(size);
concat(Other);
}
Stringy::Stringy(Stringy &&Other)
{
_debug("Move Ctor");
move(Other);
}
const Stringy& Stringy::operator=(Stringy Other)
{
_debug("opterator= copy and swap");
swap(Other);
return *this;
}
const Stringy& Stringy::operator=(Stringy &&Other)
{
_debug("Move operator=");
move(Other);
return *this;
}
void Stringy::swap(Stringy &Other)
{
std::swap(size, Other.size);
std::swap(len, Other.len);
std::swap(p, Other.p);
}
//TODO: Reallocate memory if required
void Stringy::concat(const Stringy &Other)
{
std::copy(Other.p.get(), Other.p.get() + Other.len, p.get() + len);
len += Other.len;
p[len] = '\0';
}
//TODO: Reallocate memory if required
void Stringy::concat(const char *One)
{
std::size_t _len = strlen(One);
std::copy(One, One + _len, p.get() + len);
len += _len;
p[len] = '\0';
}
void Stringy::move(Stringy &Other)
{
size = Other.size;
Other.size = 0;
len = Other.len;
Other.len = 0;
p = std::move(Other.p);
Other.p = NULL;
}
std::size_t Stringy::length() const
{
return len;
}
Stringy Stringy::operator+(const Stringy &Other) const
{
_debug("operator+ Other");
Stringy temp(*this);
temp.concat(Other);
return temp;
}
Stringy Stringy::operator+(const char *ptr) const
{
_debug("operator+ ptr");
Stringy temp(*this);
temp.concat(ptr);
return temp;
}
const char& Stringy::operator[](std::size_t index) const
{
return this->p[index];
}
char& Stringy::operator[](std::size_t index)
{
return this->p[index];
}
Stringy::~Stringy()
{
_debug("Dtor");
}
Stringy&& operator+(Stringy &&Lhs, const char *Rhs)
{
Stringy::_debug("operator+ move ptr");
Lhs.concat(Rhs);
return std::move(Lhs);
}
Stringy&& operator+(Stringy &&Lhs, const Stringy &Rhs)
{
Stringy::_debug("operator+ move Other");
Lhs.concat(Rhs);
return std::move(Lhs);
}
std::ostream &operator<<(std::ostream &stream, const Stringy &Other)
{
stream << Other.p.get();
return stream;
}
</code></pre>
<p>I benchmarked the class against <code>std::string</code> on QuickBench and it shows 2.5x worse performance, but that's because gcc now uses SSO. With large string size, my class performed comparably to <code>std::string</code> although I would agree they are little biased.</p>
<h3>main.cpp</h3>
<pre><code>#include <iostream>
#include "Stringy.h"
void custom() {
Stringy firstName = "Sumit";
Stringy lastName = "Dhingra";
Stringy fullName = firstName + "-" + ">" + lastName;
std::cout << fullName << std::endl;
}
void default_() {
std::string firstName = "Sumit";
std::string lastName = "Dhingra";
std::string fullName = firstName + "-" + ">" + lastName;
std::cout << fullName << std::endl;
}
int main() {
#ifdef DEFAULT
default_();
#else
custom();
#endif
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T13:11:26.720",
"Id": "414149",
"Score": "1",
"body": "SSO can mean single sign-on, structure sequence and organization and a boat load of other things. Which do you mean?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T16:32:15.383",
"Id": "414156",
"Score": "1",
"body": "Short String Optimization. Sorry for not clearing it up."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T20:29:42.270",
"Id": "414196",
"Score": "0",
"body": "`stringy.cpp` is obviously incomplete."
}
] | [
{
"body": "<ol>\n<li><p><code>private:</code> is redundant: While <code>union</code> and <code>struct</code> default to <code>public</code>, <code>class</code> already defaults to <code>private</code>.</p></li>\n<li><p>Calling the capacity <code>size</code> is seriously counter-intuitive. <code>std::string</code> has <code>.length()</code> as a legacy-method which is equal to <code>.size()</code>.</p></li>\n<li><p>A factor of two or more when re-allocating is seriously sub-optimal: It inhibits re-use of returned memory-blocks when expanding bit by bit.</p></li>\n<li><p>Unconditionally over-allocating on creation is in general a serious pessimisation.</p></li>\n<li><p>Why does <code>_debug()</code> use <code>cout</code> instead of <code>cerr</code>?</p></li>\n<li><p>Any reason you use your own macro, instead of re-using <a href=\"https://en.cppreference.com/w/cpp/error/assert\" rel=\"nofollow noreferrer\"><code>assert()</code>'s <code>NDEBUG</code></a>?</p></li>\n<li><p>It's curious that assignment accepts an rvalue-reference or a copy, but not a constant reference. Also consider accepting a <code>const char*</code> like the ctor does.</p></li>\n<li><p>Construction from <code>const char*</code> will write out-of-bounds if passed a 0-length string.</p></li>\n<li><p>Why write the nul-terminator in an extra step when you can simply copy that too?</p></li>\n<li><p><a href=\"https://en.cppreference.com/w/cpp/algorithm/copy_n\" rel=\"nofollow noreferrer\"><code>std::copy_n</code></a> seems to fit your use better than <code>std::copy()</code>.</p></li>\n<li><p>Not doing the move in the move-ctor, but delegating to a separate method called <code>move()</code>, is seriously weird.</p></li>\n<li><p><code>+=</code> is the operator for concatenation. Why do you call it <code>concat()</code>?</p></li>\n<li><p>Consider consolidating the methods accepting a non-modifiable range to one using iterators. Excepting those which might use the fact that the source-range <em>is</em> actually already nul-terminated.</p></li>\n<li><p>You can restrict member-functions to only be called on xvalues:</p>\n\n<pre><code>friend Stringy&& operator+ (const char* Other) &&;\nfriend Stringy&& operator+ (const Stringy& Other) &&;\n</code></pre>\n\n<p>If you are at it, consider doing the same for <code>+=</code>.</p></li>\n<li><p>If a function does not <em>need</em> to have the access, don't declare it a <code>friend</code>.</p></li>\n<li><p>Take advantage of templates to run the same code with <code>std::string</code> and your own <code>Stringy</code>.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T13:49:11.060",
"Id": "414281",
"Score": "0",
"body": "`clog` is more appropriate than `cerr` for debugging messages, IMO"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T21:07:30.763",
"Id": "214196",
"ParentId": "214165",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "214196",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T12:42:32.347",
"Id": "214165",
"Score": "3",
"Tags": [
"c++",
"performance",
"strings",
"c++11",
"reinventing-the-wheel"
],
"Title": "C++ String class implementation"
} | 214165 |
<p>Here is my source code:</p>
<pre><code>// start at zero
var count = 0;
// loop through the items
for(var i = 0; i < hours.length; i++) {
// 1. check to see if the current item has a key called "description"
// 2. check to see if the current item's "description" key isn't empty
// NOTE: white-space only values aren't valid
if(hours[i].hasOwnProperty("description") && hours[i].description.replace(/\s/g, "").length > 0) {
// increment the count (by one)
count += 1;
}
}
// return the count
return count;
</code></pre>
<p>When we remove the comments the code looks like this:</p>
<pre><code>var count = 0;
for(var i = 0; i < hours.length; i++) {
if(hours[i].hasOwnProperty("description") && hours[i].description.replace(/\s/g, "").length > 0) {
count += 1;
}
}
return count;
</code></pre>
<p>This appears to be rather expensive (especially with larger arrays). Is there a better (preferably a more concise) way to count the amount of objects in an array that contain a certain key that doesn't have an empty value?</p>
<p><strong>INFO:</strong> I can't use jQuery or LoDash/Underscore, all methods must be natively available in the browser and have good browser support (IE8+).</p>
| [] | [
{
"body": "<p>I'm not a JS performance expert, but you can try this:</p>\n\n<pre><code>var count = 0;\nconst numHours = hours.length; // Don't denominate the length on each loop.\nfor(var i = 0; i < numHours; i++) {\n let description = hours[i].description; // Don't denominate the description two times.\n // Just search for something that isn't a space character (yes, capital \"S\").\n if(description && (description.search(/\\S/g) !== -1)) {\n count++; // May be better too.\n }\n}\nreturn count;\n</code></pre>\n\n<p>Also, RegEx are usually expensive, you can try to get rid of them.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T15:37:09.250",
"Id": "214174",
"ParentId": "214166",
"Score": "1"
}
},
{
"body": "<p>Using <code>String.replace</code> means that you need to step over every character in every string you are testing. Not only that but it needs to allocate memory to hold the resulting new string.</p>\n\n<p>Its much quicker if you test for a non white space characters. That way it need only test to the first non white space, and it needs no additional memory.</p>\n\n<p>Also <code>Object.hasOwnProperty</code> is slow as it must work its way up the prototype chain to get an answer and should only be used if you think that the object you are testing has a prototype chain containing the property name you are testing.</p>\n\n<p>Last point. This is not part of the code you have presented, but to improve the performance the property <code>hour.description</code> should not contain only white spaces. When you set that property vet it eg <code>hour.description = descriptionString.trim();</code></p>\n\n<p>Thus If you have unvetted description strings</p>\n\n<pre><code>var i, count = 0;\nfor (i = 0; i < hours.length; i++) {\n count += hours[i].description && (/\\S/).test(hours[i].description) ? 1 : 0;\n}\nreturn count;\n</code></pre>\n\n<p>Or</p>\n\n<p>If the description has been vetted then the following will be the quickest</p>\n\n<pre><code>var i, count = 0;\nfor (i = 0; i < hours.length; i++) {\n count += hours[i].description ? 1 : 0;\n}\nreturn count;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T00:34:32.763",
"Id": "214207",
"ParentId": "214166",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "214207",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T13:00:23.093",
"Id": "214166",
"Score": "0",
"Tags": [
"javascript",
"performance",
"array",
"hash-map"
],
"Title": "Counting the amount of objects in an array that contain a certain key that doesn't have an empty value"
} | 214166 |
<blockquote>
<p>A unival tree (which stands for "universal value") is a tree where all
nodes under it have the same value.</p>
<p>Given the root to a binary tree, count the number of unival subtrees.</p>
<p>For example, the following tree has 5 unival subtrees:</p>
</blockquote>
<pre><code> 0
/ \
1 0
/ \
1 0
/ \
1 1
class DailyCodingProblem8 {
public static void main(String args[]) {
BinaryTree tree = new BinaryTree();
tree.root = new Node(0);
tree.root.left = new Node(1);
tree.root.right = new Node(0);
tree.root.right.left = new Node(1);
tree.root.right.right = new Node(0);
tree.root.right.left.left = new Node(1);
tree.root.right.left.right = new Node(1);
int res = tree.countUnivalTrees(tree.root);
System.out.println(res);
/*
5
/ \
4 5
/ \ \
4 4 5
*/
tree = new BinaryTree();
tree.root = new Node(5);
tree.root.left = new Node(4);
tree.root.right = new Node(5);
tree.root.left.left= new Node(4);
tree.root.left.right= new Node(4);
tree.root.right.right = new Node(5);
res = tree.countUnivalTrees(tree.root);
System.out.println(res);
}
}
class Node {
public int value;
public Node left, right;
Node(int value) {
this.value = value;
this.left = this.right = null;
}
}
class BinaryTree {
Node root;
int countUnivalTrees(Node root) {
if (root == null) {
return 0;
}
int count = countUnivalTrees(root.left) + countUnivalTrees(root.right);
if (root.left != null && root.value != root.left.value) {
return count;
}
if (root.right != null && root.value != root.right.value) {
return count;
}
// if whole tree is unival tree
return count + 1;
}
}
</code></pre>
<p>What is the best way to supply binary tree as input? Should I be creating a insert method and insert nodes? Will the interviewer feel that I am deviating from the actual problem if I do so?</p>
| [] | [
{
"body": "<p>Allow <code>Node</code> take <code>left</code> and <code>right</code>, and <code>BinaryTree</code> take a <code>node</code>.</p>\n\n<pre><code>new BinaryTree(\n new Node(\n 0,\n new Node(1),\n new Node(\n 0,\n new Node(\n 1,\n new Node(1)\n new Node(1)\n ),\n new Node(0),\n )\n )\n)\n</code></pre>\n\n<p>Takes a fair amount of lines, but clearly shows the shape of the tree and removes the need for the messy <code>tree.root.right.left.right</code> usage.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T14:05:27.207",
"Id": "214168",
"ParentId": "214167",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "214168",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T13:50:51.617",
"Id": "214167",
"Score": "3",
"Tags": [
"java",
"algorithm",
"programming-challenge",
"interview-questions",
"tree"
],
"Title": "Counting subtrees where all nodes have the same value"
} | 214167 |
<p>I have a small python project, which draws graphics and text onto a graphics context using MacOS's Core Graphics APIs. The idea is to make it easy for the user to write a few short lines, in order to add graphics to a page.</p>
<p>Currently, I'm committing the cardinal sin of a global variable for the graphics context, which each function then draws into. I realise that what I probably ought to do is to create some kind of object, and have the functions as object methods.</p>
<p>While I understand the principle of objects and methods, I'm not very good at conceptualising how they ought to work. Any help with the concept would be very welcome.</p>
<pre><code>#!/usr/bin/python
# coding=utf-8
import os, sys
import Quartz as Quartz
from CoreText import (kCTFontAttributeName, CTFontCreateWithName, CTLineDraw, CTLineCreateWithAttributedString, kCTFontAttributeName, CTLineGetImageBounds)
from CoreFoundation import (CFAttributedStringCreate, CFURLCreateFromFileSystemRepresentation, kCFAllocatorDefault)
from math import pi as PI
pageSize = [[0.,0.], [595.28, 841.88]] # A4
whiteSwatch = [1.,1.,1.]
redSwatch = [1.,0.,0.]
blueSwatch = [0.,0.,1.]
greenSwatch = [0.,1.,0.]
blackSwatch = [0.,0.,0.]
# Use inches instead of points e.g. "inch(1.5)"
def inch(x):
return 72.0*x
# Use centimetres instead of points e.g. "cm(2.5)"
def cm(x):
return 28.25*x
def makeRectangle(x, y, xSize, ySize, color, alpha):
red, green, blue = color[:]
Quartz.CGContextSetRGBFillColor (writeContext, red, green, blue, alpha)
Quartz.CGContextFillRect (writeContext, Quartz.CGRectMake(x, y, xSize, ySize))
return
def centerText(y, text, font, pointSize):
typeStyle = CTFontCreateWithName(font, pointSize, None)
astr = CFAttributedStringCreate(kCFAllocatorDefault, text, { kCTFontAttributeName : typeStyle })
line = CTLineCreateWithAttributedString(astr)
textWidth = astr.size().width
if line:
x = (pageSize[1][0]-textWidth)/2
# Quartz.CGContextSetAlpha(writeContext, opacity)
Quartz.CGContextSetTextPosition(writeContext, x, y)
CTLineDraw(line, writeContext)
return
def line(x, y, xSize, ySize, stroke, color, alpha):
red, green, blue = color[:]
Quartz.CGContextSetLineWidth(writeContext, stroke)
Quartz.CGContextSetRGBStrokeColor(writeContext, red, green, blue, alpha)
Quartz.CGContextMoveToPoint(writeContext, x, y)
Quartz.CGContextAddLineToPoint(writeContext, x+xSize, y+ySize)
Quartz.CGContextStrokePath(writeContext)
return
def circle(x, y, radius, color, alpha):
red, green, blue = color[:]
Quartz.CGContextSetRGBStrokeColor(writeContext, red, green, blue, alpha)
Quartz.CGContextSetRGBFillColor(writeContext, red, green, blue, alpha)
Quartz.CGContextAddArc(writeContext, x, y, radius, 0, 2*PI, 1)
Quartz.CGContextClosePath(writeContext)
Quartz.CGContextFillPath(writeContext)
Quartz.CGContextSetLineWidth(writeContext, 2)
Quartz.CGContextStrokePath(writeContext)
return
def addImage(x, y, path):
# CGContextDrawImage(writeContext, rect, CGImageRef image)
return
def contextDone(context):
if context:
Quartz.CGPDFContextClose(context)
del context
def main(argv):
global writeContext
writeFilename = os.path.expanduser("~/Desktop/Test.pdf")
writeContext = Quartz.CGPDFContextCreateWithURL(CFURLCreateFromFileSystemRepresentation(kCFAllocatorDefault, writeFilename, len(writeFilename), False), pageSize, None)
Quartz.CGContextBeginPage(writeContext, pageSize)
# HERE IS WHERE YOU WRITE YOUR PAGE!
# ------------------------------------------------------------------
makeRectangle(100., 100., 400., 50., redSwatch, 0.75)
makeRectangle(100., 700., 400., 50., greenSwatch, 0.75)
line(100, 300, 400, 200, 12, blueSwatch, 1)
circle(300.,400., 150., blueSwatch, 0.5)
centerText(600, "Sample Text", "Helvetica-Bold", 12.0)
# ------------------------------------------------------------------
Quartz.CGContextEndPage(writeContext)
# Do tidying up
contextDone(writeContext)
if __name__ == "__main__":
main(sys.argv[1:])
</code></pre>
<p>The ultimate goal is to turn this into a python library, so that a short script can import the library and then use a few lines to do some drawing. </p>
<p>The project can be found <a href="https://github.com/benwiggy/PDFsuite/blob/ff28aa3f87a2f975708147bc5b3d1e41cddafddf/Shell_Scripts/pagelayout.py" rel="nofollow noreferrer">on github here</a>.</p>
| [] | [
{
"body": "<h3>The code in this answer is not tested and is only there as a guide</h3>\n\n<p><strong>\"A badly constructed object is not better than using globals.\"</strong> – me</p>\n\n<pre><code>def circle_radius_from_circumference(circ):\n return circ / math.tau\n\ndef circle_circumference_from_radius(radius):\n return radius * math.tau\n</code></pre>\n\n<p>How to make an object out of that ?</p>\n\n<pre><code>class Circle:\n @staticmethod\n def radius_from_circumference(circ):\n return circ / math.tau\n\n @staticmethod\n def circumference_from_radius(radius):\n return radius * math.tau\n\nprint(Circle.circumference_from_radius(1))\n</code></pre>\n\n<p>Sure we did it, but what's the point, we don't code Java here, we do Python. A class is as way to organise data, not functions.</p>\n\n<pre><code>class Circle:\n def __init__(self, *, radius=None, circ=None):\n # feel free to add appropriate checks, this is just an example\n self._r = radius if circ is None else circ / math.tau\n\n # if you're a great programmer, you can make the following method properties.\n\n def radius(self):\n return self._r\n\n def circumference(self):\n return self._r * math.tau\n\nprint(Circle(radius=10).circumference(1))\n</code></pre>\n\n<p>Why is that useful ? Because you can add methods and data and it scales.</p>\n\n<p>Why should you care ? Because it relates to how your code is constructed. Your code is like the first example, and you don't want to be in the second example. And the third example has too little use to be in a class, but consider the following:</p>\n\n<pre><code>class Color(tuple): # an example of an immutable object\n\n def __new__(cls, r, g, b, a=1):\n return (r, g, b, a)\n\n r = property(lambda self: self[0])\n g = property(lambda self: self[1])\n b = property(lambda self: self[2])\n a = property(lambda self: self[3])\n\n def darker(self, v=10):\n return Color(*[max(i-v, 0) for i in self[:3]], self.a)\n\n def with_alpha(self, a):\n return Color(*self[:3], a)\n\n # Imagine all the great methods you could add\n\nColor.WHITE = Color(1, 1, 1)\nColor.RED = Color(1, 0, 0)\nColor.BLUE = Color(0, 0, 1)\nColor.GREEN = Color(0, 1, 0)\nColor.BLACK = Color(0, 0, 0)\n</code></pre>\n\n<ol>\n<li>Here, color is an immutable. </li>\n<li>You don't pollute globals with constants.</li>\n<li>You can pass the object around as a single object</li>\n<li>You can apply methods on color instances</li>\n</ol>\n\n<pre><code>class Canvas:\n def __init__(self, pageSize=[[0., 0.], [595.28, 841.88]]):\n self.writeFilename = os.path.expanduser(\"~/Desktop/Test.pdf\")\n writeContext = Quartz.CGPDFContextCreateWithURL(\n CFURLCreateFromFileSystemRepresentation(\n kCFAllocatorDefault,\n self.writeFilename,\n len(self.writeFilename),\n False\n ),\n pageSize,\n None\n )\n Quartz.CGContextBeginPae(writeContext, pageSize)\n self.shapes = set()\n\n def redraw(self):\n for shape in self.shapes:\n shape.draw()\n\n\nclass Shape:\n def __init__(self, canvas=Canvas()):\n self.canvas = canvas\n self.canvas.shapes.add(self)\n\n\nclass Rectangle(Shape):\n def __init__(self, x, y, width, height, color):\n super().__init__()\n self.pos = x, y\n self.shape = width, height\n self.color = color\n self.canvas.redraw()\n\n def draw(self):\n Quartz.CGContextSetRGBFillColor(self.canvas.writeContext, *self.color)\n Quartz.CGContextFillRect(\n self.canvas.writeContext, Quartz.CGRectMake(*self.pos, *self.shape))\n\nclass Circle(Shape):\n def __init__(self, ...):\n super().__init__()\n ...\n self.canvas.redraw()\n\n def draw(self):\n ...\n</code></pre>\n\n<p>The example above can be used like this.</p>\n\n<pre><code>Rectangle(100, 100, 400, 50, Color.RED.with_alpha(0.75))\nRectangle(100, 700, 400, 50, Color.GREEN.with_alpha(0.75))\n\n</code></pre>\n\n<p>But the shape class is kind of dirty in the way it implicitly creates a canvas and redraws.</p>\n\n<pre><code>class Canvas:\n def __init__(self, pageSize=[[0., 0.], [595.28, 841.88]]):\n self.writeFilename = os.path.expanduser(\"~/Desktop/Test.pdf\")\n writeContext = Quartz.CGPDFContextCreateWithURL(\n CFURLCreateFromFileSystemRepresentation(\n kCFAllocatorDefault,\n self.writeFilename,\n len(self.writeFilename),\n False\n ),\n pageSize,\n None\n )\n Quartz.CGContextBeginPae(writeContext, pageSize)\n self.shapes = set()\n\n def redraw(self):\n for shape in self.shapes:\n shape.draw()\n\n def add_children(self, *shapes):\n for shape in shapes:\n self.shapes.add(shape)\n\nclass Shape: pass\n\nclass Rectangle(Shape): # an example of a mutable object\n def __init__(self, x, y, width, height, color):\n super().__init__()\n self.pos = x, y\n self.shape = width, height\n self.color = color\n\n def draw(self):\n Quartz.CGContextSetRGBFillColor(self.canvas.writeContext, *self.color)\n Quartz.CGContextFillRect(\n self.canvas.writeContext, Quartz.CGRectMake(*self.pos, *self.shape))\n\n</code></pre>\n\n<p>can be used like this:</p>\n\n<pre><code>canvas = Canvas()\ncanvas.add_children(\n Rectangle(100, 100, 400, 50, Color.RED.with_alpha(0.75)),\n Rectangle(100, 700, 400, 50, Color.GREEN.with_alpha(0.75))\n)\ncanvas.redraw()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T07:21:13.307",
"Id": "414246",
"Score": "0",
"body": "Thanks. This is incredibly helpful. And a lot to think through! I'm sure I'll be back here with my attempts to make this work."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T09:26:52.330",
"Id": "414393",
"Score": "0",
"body": "One more thing: does every variable inside the Class definition need to be `self.variable`? And do I pass parameters to object methods in the same way as `__init__`?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T18:01:37.627",
"Id": "214182",
"ParentId": "214170",
"Score": "2"
}
},
{
"body": "<p>This is an interesting project. Is your goal to simplify the use of CoreGraphics from Python? What's the advantage of using your python module over just importing Quartz and using it directly? That's not intended as a criticism, but a serious question. The answer will inform how you design the interface for your library.</p>\n<h1>Naming</h1>\n<p>One thing I'd like to point out is that your naming is confusing. For example, you have:</p>\n<pre><code>def inch(x):\n</code></pre>\n<p>From just looking at the function prototype, it's not clear at all what the function returns or what the argument is supposed to be. The comment makes this even less clear. (If I'm using inches, why does the function return points?) A better way to name these would be something like:</p>\n<pre><code> def inchesToPoints(inches):\n ...\n def cmToPoints(cm):\n</code></pre>\n<p>Also, why are you changing the constant name <code>pi</code> to <code>PI</code>?</p>\n<p>Your naming is also inconsistent. You have <code>makeRectangle()</code> (which draws a rectangle rather than making one) and then just <code>line()</code> and <code>circle()</code>. These should all be something like <code>fillRectangle()</code>, <code>strokeLine()</code> and <code>fillAndStrokeCircle()</code>. Also, it would make sense to have the same forms for all shapes - <code>fillRectangle()</code>, <code>strokeRectangle()</code>, <code>fillCircle()</code>, <code>strokeCircle()</code>, etc.</p>\n<h1>API</h1>\n<p>Looking at the Quartz.framework headers, there is an object model immediately suggested to me. The main object in CoreGraphics is the <code>CGContext</code>. The header treats it as an opaque pointer, but we can assume for our purposes that it points to some sort of object behind-the-scenes. You could mimic that, offering a <code>Context</code> or <code>DrawingContext</code> class.</p>\n<p>CoreGraphics also has several data types that it passes around, such as <code>CGPoint</code>, <code>CGRect</code>, and <code>CGColor</code>. These would make good classes, as well. And it turns out that python supports <a href=\"https://www.programiz.com/python-programming/operator-overloading\" rel=\"nofollow noreferrer\">some operator overloading</a> so you can make some useful methods like overloading <code>+</code> and <code>-</code> for easy use of points as vectors.</p>\n<p>Now all of this might not be the right abstraction for your library. (Though it might be useful internally for it.) The right abstraction will depend on your goals. But most modern graphics APIs have a concept of some sort of context to draw into and a set of methods to do the drawing of various types of primitives (shapes, images, text, etc.). So it's a decent model to follow.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T21:51:00.510",
"Id": "414204",
"Score": "0",
"body": "Yes, I'm planning to simplify the CoreGraphics APIs somewhat, so that I (or anyone) can just write a sequence of functions to add graphics and text, without re-writing the same lines over and over. It's \"not quite PostScript\"™. The inches thing was just to make it easy for someone to specify different units, rather than the points required. It's still early stages, so I'd probably have functions for setting stroke and fill independently of the shape or line. But my prime concern is getting the object concept so that I can then build all the methods. Thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T21:37:10.700",
"Id": "214200",
"ParentId": "214170",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "214182",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T14:12:39.870",
"Id": "214170",
"Score": "1",
"Tags": [
"python",
"graphics",
"macos"
],
"Title": "Drawing graphics and text using macOS Core Graphics"
} | 214170 |
<p>I am using a Raspberry Pi 3 model b to control LEDs connected on a breadboard. I want the lights to tell me what chore I have to do today: when to take out the trash, recyclables, vacuum, and clean the bathroom. There's is also another rotation happening every 6 days that I need to keep track of. The code does run and fulfill its purpose, but it is really inconvenient that I have to rewrite the functions <code>Fixed()</code>, <code>vacuum()</code>, and <code>chores()</code> to have the code start in the position I want. My question is how can I make the code run in the right starting position of the cycles without having to rewrite the code itself? </p>
<pre><code>#!/usr/bin/python
# -*- coding: utf-8 -*-
"By Andre Akue"
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(True)
import time
import datetime
from os import system
from multiprocessing import Process
speed = 2 #blinking speed
day_duration = 60*60*24
check_time = 600 #check for day change every 600 secs
class lights: #setting up leds
def __init__(self,color_name,color_pin):
self.name = color_name
self.pin = color_pin
GPIO.setup(self.pin, GPIO.OUT, initial = 0)
def solid(self): #stay on when it's the first day or when the trash is being collected the next day (warning)
GPIO.output(self.pin,1)
time.sleep(check_time)
GPIO.output(self.pin,0)
def flash(self): #blink when it's the second day or when the trash is being collected
stp = time.time() ; etp = time.time() + check_time # stp/etp = starting / ending time pattern
while time.time() < etp:
GPIO.output(self.pin,0)
time.sleep(0.8/speed)
GPIO.output(self.pin,1)
time.sleep(0.2/speed)
GPIO.output(self.pin,0)
L1 = lights("white", 21)
L2 = lights("yellow", 16)
L3 = lights("red", 12)
L4 = lights("blue", 25)
L5 = lights("green", 24)
L6 = lights("snow", 23)
def chores():#a 6 day cycle divided into 3 steps of 2 days each
while 1:
#Sweeping the floor - First Day
L2.solid()#yellow stays on
#Sweeping the floor - Second Day
L2.flash()#yellow keeps blinking
#Setting the table - First Day
L3.solid()#red stays on
#Setting the table - Second Day
L3.flash()#red keeps blinking
#Washing dishes - First Day
GPIO.output((L2.pin,L3.pin),1)#red and yellow stay on
time.sleep(check_time)
GPIO.output((L2.pin,L3.pin),0)
#Washing dishes - Second Day
stp = time.time() ; etp = time.time() + check_time # stp/etp = starting / ending time pattern
while time.time() < etp:#red and yellow keep blinking
GPIO.output((L2.pin,L3.pin),0)
time.sleep(0.8/speed)
GPIO.output((L2.pin,L3.pin),1)
time.sleep(0.2/speed)
GPIO.output((L2.pin,L3.pin),0)
def log():# print weekday and day count in command prompt
count = 0
while 1:
for day in week_order:
count += 1
print ('\nDay: %s\t\tDay of the week: %i' % (day,count))
time.sleep(day_duration)
def vacuum():
while 1:
#only happens Friday to Sunday every 3 weeks
for day in list(range(1,22)):
if day not in [4,5,6]:
time.sleep(day_duration)
elif day == 4:
L5.solid()
elif day == 5:
L5.solid()
elif day == 6:
L5.flash()
def start_tomorrow(): #cycle starts the day after the code has been started
tomorrow = datetime.datetime.now() + datetime.timedelta(days=1)
while datetime.datetime.now() < tomorrow:
time.sleep(60)
print ('\nchore cycle started')
def fixed(): #all weekly, fixed items
while 1:
if datetime.datetime.now().strftime('%a') == 'Mon':
L1.flash()#trash
L6.solid()#recycle
elif datetime.datetime.now().strftime('%a') == 'Tue':
L6.flash()#recycle
elif datetime.datetime.now().strftime('%a') == 'Wed':
L1.solid()#trash
L4.solid()#bath
elif datetime.datetime.now().strftime('%a') == 'Thu':
L1.flash()#trash
L4.flash()#bath
elif datetime.datetime.now().strftime('%a') == 'Fri':
elif datetime.datetime.now().strftime('%a') == 'Sat':
elif datetime.datetime.now().strftime('%a') == 'Sun':
L1.solid()#trash
try:#using processes so that different cycles can run independently
if __name__ == '__main__':
Process(target=log).start()
Process(target=chores).start()
Process(target=bath).start()
Process(target=recycle).start()
Process(target=vacuum).start()
Process(target=trash).start()
except KeyboardInterrupt:
system('clear')
print ("\n\n\texited via keyboard interrupt\n\n")
GPIO.cleanup()
#when resetting:
#3-chore cycle
# place the chore happening tomorrow in first place in the sequence
#'bath','trash','recycle', and 'log'
# place tomorrow in first in the list of weekdays
# 'week_order'
#vaccum cycle
# count the number of days till the next 'first vacuum day',
# and start with this number in the list of the "if" loops
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T18:10:30.893",
"Id": "414165",
"Score": "0",
"body": "Welcome to Code Review! (I'd opt for a WALL-E with same LEDs telling chores taken care of.) I *think* I got that you're dissatisfied with hard coding the entry point into the cycle of events (what about their order?)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T01:30:32.580",
"Id": "414224",
"Score": "0",
"body": "How `fixed` is ever called?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T03:03:31.747",
"Id": "414227",
"Score": "1",
"body": "There are syntax errors and undefined symbols in your code, so obviously it doesn't work. Can you post a version that *does* run?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T15:16:29.080",
"Id": "214173",
"Score": "2",
"Tags": [
"python",
"beginner",
"python-3.x",
"raspberry-pi",
"scheduled-tasks"
],
"Title": "Remembering what chores to do each day with LED patterns"
} | 214173 |
<p>I needed a monadic version of <a href="https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-List.html#v:partition" rel="nofollow noreferrer"><code>partition</code></a> today. I settled on the following version:</p>
<pre><code>partitionM :: Monad m => (a -> m Bool) -> [a] -> m ([a], [a])
partitionM p xs = bimap (map fst) (map fst) . partition snd . zip xs <$> mapM p xs
</code></pre>
<p>Then I realized it's already implemented <a href="https://hackage.haskell.org/package/extra-1.6.14/docs/Control-Monad-Extra.html" rel="nofollow noreferrer">here</a>:</p>
<blockquote>
<pre><code>partitionM :: Monad m => (a -> m Bool) -> [a] -> m ([a], [a])
partitionM f [] = return ([], [])
partitionM f (x:xs) = do
res <- f x
(as,bs) <- partitionM f xs
return ([x | res]++as, [x | not res]++bs)
</code></pre>
</blockquote>
<p>This second version doesn't have to pull in extra packages and doesn't create intermediate lists, but mine is shorter and doesn't have explicit recursion. What do you think of my solution in comparison with the library's implementation? </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T17:15:05.603",
"Id": "414159",
"Score": "0",
"body": "I don't see why you couldn't use `foldM` and get the best of all worlds: no explicit recursion, no extra dependencies, and no need for an extra `<$>` over top of `mapM`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T20:39:00.503",
"Id": "414199",
"Score": "0",
"body": "`foldM` would end up with reversed lists if you appended to the front of the accumulator, would you not?"
}
] | [
{
"body": "<p>This version uses only <code>base</code>, doesn't create extra lists and has no explicit recursion. The amount of plumbing this requires disturbs me - there ought to be a library out there that makes these building blocks fit together without naming <code>acc</code> and <code>res</code>.</p>\n\n<pre><code>partitionM f = foldrM (\\x acc -> (\\res -> bool second first res (x:) acc) <$> f x) ([], [])\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T22:15:59.963",
"Id": "214278",
"ParentId": "214179",
"Score": "0"
}
},
{
"body": "<blockquote>\n <p>This second version doesn't have to pull in extra packages…</p>\n</blockquote>\n\n<p><code>Data.Bifunctor</code> is part of <code>base</code> since 4.8.0.0, so I'm not sure where you get the \"extra packages\" from. Yes, <code>Data.Bifunctor</code> was originally in the <code>bifunctors</code> package, but it was <a href=\"https://github.com/ghc/ghc/blob/master/libraries/base/changelog.md\" rel=\"nofollow noreferrer\">transferred into <code>base</code> in 2015</a>.</p>\n\n<p>However, compared to the <code>extras</code> version, your variant is easy to read, as the <code>[x | res] … [x | not res]</code> slightly obfuscates the result. I'd probably bind <code>map fst</code>, but that's personal preference. </p>\n\n<blockquote>\n <p>and doesn't create intermediate lists</p>\n</blockquote>\n\n<p>It generates <em>a lot</em> of intermediate lists. I haven't checked yet, but as <code>[x|res]++as</code> depends on <code>res</code> cannot get simplified to <code>x:as</code> or <code>as</code> at compile time by rules, so it might create a thunk <code>[…]++as</code>. In the end, you have <span class=\"math-container\">\\$\\mathcal O(n) \\$</span> additional <span class=\"math-container\">\\$\\mathcal O(1)\\$</span>-sized lists.</p>\n\n<p>Since this is a hidden implementation detail, I don't really like Neil's solution too much. Something along</p>\n\n<pre><code>partitionM :: Monad m => (a -> m Bool) -> [a] -> m ([a], [a])\npartitionM f [] = return ([], [])\npartitionM f (x:xs) = do\n res <- f x\n (as,bs) <- partitionM f xs\n return $ if res then (x : as, bs)\n else ( as, x : bs)\n</code></pre>\n\n<p>would at least support the optimizer and get rid of those intermediate lists, but is even more verbose. Your variant uses an additional list, sure, but it's easier to read and to understand IMHO.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T11:56:16.903",
"Id": "214317",
"ParentId": "214179",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "214317",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T16:55:37.550",
"Id": "214179",
"Score": "4",
"Tags": [
"haskell",
"monads"
],
"Title": "Implementation of partitionM"
} | 214179 |
<p>I know the difference between the Entity Framework connected mode vs disconnected mode. In connected mode we do all the stuff inside one single <code>DbContext</code> instance. In disconnected mode we do the stuff and then attach the Entity to a new <code>DbContext</code> instance.</p>
<p>My problem is that I - for a specific reason - had to create the <code>DbContext</code> instance globally in the form class without disposing it (I'm disposing the form after closing) and I'm confused and want to review my code and determine if it's a connected or a disconnected mode and if it's good practice to do this:</p>
<pre><code>public partial class FrmProducts : MetroForm
{
public FrmProducts()
{
InitializeComponent();
}
//The DbContext:
FDB.MFdb db = new FDB.MFdb();
private void sfButton1_Click(object sender, EventArgs e)
{
try
{
//New row:
if (txtID.Text.Trim() == "")
{
short maxID, newID;
if (db.Products.Count() > 0)
{
maxID = db.Products.Max(p => p.PID);
newID = ++maxID;
}
else
newID = 1;
//New Database Entity:
FDB.Product px = new FDB.Product();
//Set entity data:
px.PID = newID;
px.P_Code = txtCode.Text;
px.P_Name = txtName.Text;
px.P_Purchase_Price = Convert.ToDecimal(txtPurchase.Text);
px.P_Sale_Price = Convert.ToDecimal(txtSale.Text);
px.P_Notes = txtNotes.Text;
//Add entity to DbContext:
db.Products.Add(px);
db.SaveChanges();
//This is a BindingSource Control:
binSrc.Add(px);
}
else
{
//Edit row:
int pid = Convert.ToInt16(txtID.Text);
var row = db.Products.Single(b => b.PID == pid);
row.P_Code = txtCode.Text;
row.P_Name = txtName.Text;
row.P_Purchase_Price = Convert.ToDecimal(txtPurchase.Text);
row.P_Sale_Price = Convert.ToDecimal(txtSale.Text);
row.P_Notes = txtNotes.Text;
db.SaveChanges();
}
//Reset BindingSource to reflect updated data:
binSrc.ResetBindings(false);
}
catch (Exception ex)
{
//Discard Db Changes if error occurred:
foreach (var ent in db.ChangeTracker.Entries())
{
if (ent.State == EntityState.Modified)
{
ent.State = EntityState.Unchanged;
}
else if (ent.State == EntityState.Added)
{
ent.State = EntityState.Detached;
}
}
MessageBox.Show(ex.Message + "\nInner Exception:\n" + ex.InnerException);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T04:00:12.687",
"Id": "414229",
"Score": "2",
"body": "The current question title, which states your concerns about the code, is too general to be useful here. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T13:37:12.050",
"Id": "414279",
"Score": "0",
"body": "*in connected mode we do all the stuff inside one single DbContext instance* -- Doesn't that answer you own question *is it a connected or a disconnected mode*? Whether or not it's good practice is opinion-based."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T22:44:44.440",
"Id": "414358",
"Score": "0",
"body": "@GertArnold I know that connected mode means that a single instance handles all data operation, but the famous practice is to use `using { }` and do all the stuff inside it. Here I didn't follow that practice and made the `DbContext` at form level which made me confused. Thanks for reply."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T08:42:53.553",
"Id": "414386",
"Score": "0",
"body": "Working in connected mode in rich client applications is also normal. We can only give opinions here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-28T23:29:44.577",
"Id": "414820",
"Score": "0",
"body": "Judging whether or not disconnected mode is appropriate in a given situation requires a lot of context. As it stands you're just stating \"for reasons\" in the question. That does not constitute sufficient context to meaningfully review the code you presented or even answer your question (which no answer on code review is obligated to in the first place)..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-01T13:13:18.403",
"Id": "414869",
"Score": "0",
"body": "@Vogel612 The main purpose of the Q is to determine is it connected mode or disconnected mode regardless of the review"
}
] | [
{
"body": "<p>It is a best-practice to have a clear separation between UI layer (the forms) and data access, so all your data access logic (opening the connection, issuing quries, closing it etc.) should be handled in a separate class (service) that can be reused by other classes / forms.</p>\n\n<p>This will help you have a single place to handle specific things like logging, reverting changes on error: </p>\n\n<pre><code>catch (Exception ex)\n{\n //Discard Db Changes if error occurred:\n foreach (var ent in db.ChangeTracker.Entries())\n {\n if (ent.State == EntityState.Modified)\n {\n ent.State = EntityState.Unchanged;\n }\n else if (ent.State == EntityState.Added)\n {\n ent.State = EntityState.Detached;\n }\n }\n}\n</code></pre>\n\n<p>Also, EF contexts are typically used for a short period (new + query stuff + save changes + dispose) because a Dispose does not mean a connection close (in most cases) since connection pooling kicks in. So, there is really no significant penalty, but you make sure that there no undisposed context lurking around. </p>\n\n<p>There might be exceptions to this, such as when using a unit of work pattern which uses a connection per \"unit of work\" (e.g. thread, request), but stick the above for the beginning and you will be fine.</p>\n\n<p>Also, try to create separate functions for each semantic part. E.g.: create new entity based on row, update entity based on row.</p>\n\n<p>As a conclusion:</p>\n\n<ul>\n<li>move all database context logic into a separate class</li>\n<li>put all context related logic into a <code>using</code> block that ensures context disposal</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T22:52:16.520",
"Id": "414361",
"Score": "0",
"body": "The specific reason for not using `Using { }` is that I'm binding a `DataGridView` using a `BindingSource` to the same global `DbContext` to make sure that `DbContext` see all modifications made to the `BindingSource`, and if I used two different instances of `DbContext` the changes to `BindingSource` don't commit to the original data source and vice versa..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T04:59:39.370",
"Id": "414373",
"Score": "0",
"body": "@AhmedSuror - yes, this is a valid scenario that I have not used in many years, as I typically work in 3-tier architecture (UI talks to an application server / REST API only and cannot see the database at all)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T17:29:28.827",
"Id": "414446",
"Score": "0",
"body": "So, does my code represent the connected mode? another Q: I noticed that only EF Core edition has the disconnected mode based on [this](http://www.entityframeworktutorial.net/efcore/saving-data-in-disconnected-scenario-in-ef-core.aspx), am I true?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T20:01:19.347",
"Id": "414482",
"Score": "0",
"body": "@AhmedSuror - if I understand correctly from provided link, connected mode means \"tracked\". Looking at your code, you can still short disposable contexts (connected mode). For each operation you can just create a new context, add new item / get entity to change, perform changes and SaveChanges."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T07:31:54.037",
"Id": "214223",
"ParentId": "214186",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T18:53:18.653",
"Id": "214186",
"Score": "-1",
"Tags": [
"c#",
".net",
"database",
"entity-framework",
"entity-framework-core"
],
"Title": "Handling Entity Framework in connected mode within Windows Forms"
} | 214186 |
<p>I am attempting to teach myself C++ by writing a simple multi-line text reader that reports the lengths of each line. What can I do better now that I have something that "works?"</p>
<p><strong>Conventions:</strong></p>
<ul>
<li>variables and members are declared <code>const</code>, if I found it possible</li>
<li>variables and private members are written in <code>camelCase</code></li>
<li>private members are prefixed with <code>m_</code></li>
<li>public members are written in <code>PascalCase</code></li>
</ul>
<p>Please note that I will generally ignore comments regarding conventions because the style used is something I conform to in all of my personal projects, to maintain some sort of consistency across languages. The advice is still greatly appreciated for the times where I might be working on a team that is used to a more idiomatic C++ style.</p>
<p><strong>Code:</strong></p>
<pre><code>#include <errno.h>
#include <stdbool.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define DATA_BUFFER_SIZE 4096
#define DELIMIT_CHAR ','
#define QUOTE_CHAR '"'
#define SOURCE_FILE_PATH "..."
struct FileBuffer {
public:
char* const BufferData;
size_t const BufferLength;
FILE* const FilePointer;
size_t NumBytesRead;
size_t NumBytesUsed;
FileBuffer(char* const bufferData, size_t bufferLength, FILE* const filePointer) : BufferData(bufferData), BufferLength(bufferLength), FilePointer(filePointer), NumBytesRead(0), NumBytesUsed(0) { }
};
struct LineReader {
private:
FileBuffer* const m_fileBuffer;
char const m_quoteChar;
bool FillBuffer() const {
return (m_fileBuffer->NumBytesUsed = 0, m_fileBuffer->NumBytesRead = fread(m_fileBuffer->BufferData, 1, m_fileBuffer->BufferLength, m_fileBuffer->FilePointer));
}
char NextChar() const {
if ((m_fileBuffer->NumBytesUsed < m_fileBuffer->NumBytesRead) || FillBuffer()) {
return m_fileBuffer->BufferData[m_fileBuffer->NumBytesUsed];
}
else {
return '\0';
}
}
public:
LineReader(FileBuffer* const fileBuffer, char const quoteChar) : m_fileBuffer(fileBuffer), m_quoteChar(quoteChar) { }
int operator()() const {
FileBuffer* const fileBuffer = m_fileBuffer;
const char* const BufferData = fileBuffer->BufferData;
bool isQuotedSequence = false;
int lineLength = 0;
char const quoteChar = m_quoteChar;
while ((fileBuffer->NumBytesUsed < fileBuffer->NumBytesRead) || FillBuffer()) {
char const currentChar = BufferData[fileBuffer->NumBytesUsed++];
lineLength++;
if (quoteChar == currentChar) {
if (quoteChar == NextChar()) {
lineLength++;
fileBuffer->NumBytesUsed++;
}
else {
isQuotedSequence = !isQuotedSequence;
}
}
if (isQuotedSequence) {
continue;
}
if ('\n' == currentChar) {
return lineLength;
}
if ('\r' == currentChar) {
if ('\n' == NextChar()) {
lineLength++;
fileBuffer->NumBytesUsed++;
}
return lineLength;
}
}
return ((lineLength == 0) ? -1 : lineLength);
}
};
int main() {
char dataBuffer[DATA_BUFFER_SIZE];
const char* const fileName = SOURCE_FILE_PATH;
FILE* filePointer;
if (NULL != (filePointer = fopen(fileName, "r"))) {
FileBuffer fileBuffer = FileBuffer(dataBuffer, DATA_BUFFER_SIZE, filePointer);
LineReader const lineReader = LineReader(&fileBuffer, QUOTE_CHAR);
int result;
int totalLength = 0;
while (-1 != (result = lineReader())) {
fprintf(stdout, "Length: %d\n", result);
totalLength += result;
}
fclose(filePointer);
fprintf(stdout, "Total Length: %d\n", totalLength);
}
else {
fprintf(stderr, "cannot open file '%s': %s\n", fileName, strerror(errno));
}
printf("Press ENTER key to continue...\n");
getchar();
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T18:57:21.663",
"Id": "414176",
"Score": "1",
"body": "There are a lot of things to improve. It is great that you came here!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T19:00:21.563",
"Id": "414179",
"Score": "0",
"body": "@Incomputable Yeah, coming from a C#/Java/SQL background, I know more than enough to brute force my way through most errors that the compiler throws at me; am certain that I'm violating all kinds of best practices. Problem I'm running into with C and C++ is that their history is so rich... there is all kinds of conflicting advice out there."
}
] | [
{
"body": "<h1>What can I do better now that I have something that \"works?\"</h1>\n\n<p>Great, since your goal is to learn C++, now it is time to replace all the C features with C++ versions. Have a look at the following headers:</p>\n\n<ul>\n<li><a href=\"https://en.cppreference.com/w/cpp/header/fstream\" rel=\"nofollow noreferrer\"><code><fstream></code></a></li>\n<li><a href=\"https://en.cppreference.com/w/cpp/header/iostream\" rel=\"nofollow noreferrer\"><code><iostream></code></a></li>\n<li><a href=\"https://en.cppreference.com/w/cpp/header/string\" rel=\"nofollow noreferrer\"><code><string></code></a></li>\n<li><a href=\"https://en.cppreference.com/w/cpp/header/array\" rel=\"nofollow noreferrer\"><code><array></code></a></li>\n<li><a href=\"https://en.cppreference.com/w/cpp/header/vector\" rel=\"nofollow noreferrer\"><code><vector></code></a></li>\n<li><a href=\"https://en.cppreference.com/w/cpp/header/algorithm\" rel=\"nofollow noreferrer\"><code><algorithm></code></a></li>\n</ul>\n\n<p>Additionally the following features are preferred in C++:</p>\n\n<ul>\n<li><code>nullptr</code> over <code>NULL</code></li>\n<li><code>constexpr</code> over <code>#define</code> </li>\n<li>reference might be better then pointer since references can't be null.</li>\n</ul>\n\n<h1>Resource management</h1>\n\n<p>Think about how your struct/class behave when copied/moved. Start doing resource management with RAII idom. What happens when two copies of <code>FileBuffer</code> end up pointing to the same buffer? Does <code>FileBuffer</code> need to store an external buffer or should the buffer be part of the struct?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T01:06:48.507",
"Id": "214208",
"ParentId": "214187",
"Score": "3"
}
},
{
"body": "<p>The first thing you need to do is you need to know and understand two things. They are related but different.</p>\n\n<ul>\n<li>You want to know how your file is structured for reading in its contents.</li>\n<li>You want to know how your data structure(s) (classes, structs, variables in a namespace, etc.) are designed.</li>\n</ul>\n\n<p>Knowing these two things will help you in parsing any kind of file either it be in text or binary format.</p>\n\n<p>In your case you had explicitly stated:</p>\n\n<blockquote>\n <p>Multi-Line text reader</p>\n</blockquote>\n\n<p>As the name of your question suggests.</p>\n\n<hr>\n\n<p>What you want to do next is just as user: <a href=\"https://codereview.stackexchange.com/users/160161/wooooooooosh\">wooooooooosh</a> had stated. You want to remove all the <code>C</code> library functions from your code and use the C++ libraries instead.</p>\n\n<p>When you write your code, you want to keep the file handling <code>opening, reading contents to some buffer and closing</code> separate from any parsing and or data manipulation. All you want your file handler to do is to extract and read the data. </p>\n\n<p>Now there are several ways to write a function that will open a file if it exists and to read its contents and by two types (text & binary) but we will only focus on text here.</p>\n\n<blockquote>\n <ul>\n <li>You can read a single character from the file.</li>\n <li>You can read a single string up to the first white space you encounter.</li>\n <li>You can read a single line.</li>\n <li>You can do all of the above until no more can be read in.</li>\n <li>You can read all of the contents in one go into a large single buffer; depending on the size of the file.</li>\n </ul>\n</blockquote>\n\n<hr>\n\n<p>In your specific case, you stated a multi line text file so we will use that as a demonstration.</p>\n\n<blockquote>\n <ul>\n <li>First you want to create a structure that will hold many lines from the file. We can do this with:</li>\n </ul>\n</blockquote>\n\n<pre><code>#include <vector>\n#include <string>\n\nstd::vector<std::string> linesFromFile;\n</code></pre>\n\n<blockquote>\n <ul>\n <li>Next we need a file name; this is simple enough:</li>\n </ul>\n</blockquote>\n\n<pre><code>#include <string>\n\n// If you know the name of the file and it is hard coded in the application:\n// then it is best to make this `std::string` `const` as it can not be modified.\nconst std::string filename( \"somefile.txt\" );\n</code></pre>\n\n<blockquote>\n <ul>\n <li>Or we can ask the user for a file name:</li>\n </ul>\n</blockquote>\n\n<pre><code>#include <string>\n#include <iostream>\n\nint main() {\n std::cout << \"Enter the file's name for reading\\n\";\n\n // In this case the user will enter the filename so we don't want it `const`.\n std::string filename;\n std::cin >> filename; // Now you have to be careful with cin and getline and mixing the two; \n // I will not go into the details here but a google search would do the job for you.\n return 0;\n}\n</code></pre>\n\n<hr>\n\n<p>However, none of this will work without a filestream object. There are 3 main types:</p>\n\n<blockquote>\n <ul>\n <li><code>std::fstream</code> - basic filestream can be read from and or written to based on the flags set when opening</li>\n <li><code>std::ifstream</code> - a type of filestream specifically for reading contents in</li>\n <li><code>std::ofstream</code> - a type of filestream specifically for writing contents to</li>\n </ul>\n</blockquote>\n\n<hr>\n\n<p>In your case you have two options to read your file:</p>\n\n<pre><code>#include <fstream>\n#include <string>\n\nint main() {\n std::string filename( \"somefile.txt\" );\n std::fstream file( filename, std::ios::in ); // This will try to open file;\n\n // Or:\n\n std::fstream file2;\n\n file2.open( filename, std::ios::in ); \n\n return 0;\n}\n</code></pre>\n\n<p>The flag option tells <code>fstream</code> that we want to read contents from the file as <code>fstream</code> is a two way stream operation on files.</p>\n\n<p>If you do not want to write to the file as it will be read only then you can do the following:</p>\n\n<pre><code>#include <string>\n#include <ifstream> // <fstream> should work here too\n\nint main() {\n std::string filename( \"somefile.txt\" );\n\n std::ifstream inFile( filename ); // this will try to open the file if it exists.\n\n // or\n std::ifstream inFile2;\n\n inFile2( filename );\n\n return 0;\n}\n</code></pre>\n\n<hr>\n\n<p>Now that we have a file handle, a filename, and a container to hold our contents we can put them together. Instead I'll create a class to handle our data. Then write a function to open the file and save the contents to...</p>\n\n<pre><code>#include <exception>\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nclass FileData {\nprivate:\n std::vector<std::string> fileContents_;\n std::size_t linesInFile_ { 0 };\npublic:\n FileData() = default; // empty base constructor\n explicit FileData( std::vector<std::string>& contents ) : linesInFile( contents.size() ) {}\n\n void addData( std::vector<std::string>& contents ) {\n fileContents = contents;\n linesInFile_ = contents.size();\n }\n\n std::vector<std::string>& getFileContents() { return fileContents_; }\n std::size_t numberOfLinesInFile() const { return linesInFile_; }\n};\n\nvoid getAllLinesFromFile(const char* filename, std::vector<std::string>& output) {\n std::ifstream file(filename);\n if (!file) {\n std::stringstream stream;\n stream << \"failed to open file \" << filename << '\\n';\n throw std::runtime_error(stream.str());\n }\n\n std::string line;\n while (std::getline(file, line)) {\n if (line.size() > 0)\n output.push_back(line);\n }\n file.close();\n}\n\nint main() {\n // my function allows you to do this a couple of ways:\n std::vector<std:string> fileContentsA, fileContentsB;\n // Just by passing the name directly in as a const string literal.\n getAllLinesFromFile( \"somefile.txt\", fileConentsA );\n\n // Or by\n std::string filename( \"somefile2.txt\" );\n getAllLinesFromFile( filename.c_str(), fileContentsB ); \n\n return 0;\n}\n</code></pre>\n\n<p>The above will give us our vector of strings that we need; however we have to parse that for our data structure, but since our data structure's constructor and or add function matches directly as the pattern of the file contents all we need to do is constructor our class object and in this case there is no need to parse the file.</p>\n\n<p>Now if you were reading individual words from a single line of text where specific words had specific meanings and other characters were values, then you would have to write a parser function to break the strings down into individual tokens. However, here is not the case it is a simple read and pass to object operation.</p>\n\n<pre><code>int main() {\n // my function allows you to do this a couple of ways:\n std::vector<std:string> fileContents\n\n std::string filename( \"somefile.txt\" );\n getAllLinesFromFile( filename.c_str(), fileContents );\n\n FileData myData( fileContents ); \n\n // Or\n\n FileData myData2;\n myData2.addData( fileContents );\n\n return 0; \n}\n</code></pre>\n\n<p>Here I have a default empty constructor that will later on require the use of the addData function, but I also have a constructor that will take the data directly. This will give the user flexibility when using the class. If you already have the data ready by the time you are creating the class object you can use the constructor and pass the data in. In some cases you may not be ready for the data, but you have to have the object first to be populated later.</p>\n\n<hr>\n\n<p>One thing to take note of is that my file reading function is throwing and error message so in our main function we need to wrap it into a try catch block. The entire app would look something like this:</p>\n\n<pre><code>#include <exception>\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n\nclass FileData {\nprivate:\n std::vector<std::string> fileContents_;\n std::size_t linesInFile_ { 0 };\npublic:\n FileData() = default; // empty base constructor\n explicit FileData( std::vector<std::string>& contents ) : linesInFile( contents.size() ) {}\n\n void addData( std::vector<std::string>& contents ) {\n fileContents = contents;\n linesInFile_ = contents.size();\n }\n\n std::vector<std::string>& getFileContents() { return fileContents_; }\n std::size_t numberOfLinesInFile() const { return linesInFile_; }\n};\n\nvoid getAllLinesFromFile(const char* filename, std::vector<std::string>& output) {\n std::ifstream file(filename);\n if (!file) {\n std::stringstream stream;\n stream << \"failed to open file \" << filename << '\\n';\n throw std::runtime_error(stream.str());\n }\n\n std::string line;\n while (std::getline(file, line)) {\n if (line.size() > 0)\n output.push_back(line);\n }\n file.close();\n}\n\nint main() {\n try {\n\n std::vector<std:string> fileContents;\n getAllLinesFromFile( \"somefile.txt\", fileConents );\n FileData myFileData( fileContents );\n\n } catch( std::exception& e ) {\n std::cout << \"Exception Thrown: \" << e.what() << std::endl;\n return EXIT_FAILURE;\n } \n return EXIT_SUCCESS;\n}\n</code></pre>\n\n<p>The above works as intended yet there still may be room for improvement, and with C++20 around the corner; there will be many nice new features to learn; especially with the new filesystem.</p>\n\n<hr>\n\n<p><em>-Edit-</em> A user had left a comment stating that unfortunately that this is not a multi line reader. Yes this will not read multiple lines at a time, but it will read a single line of text and store it into a string and for each line of text those strings will be stored into a vector. This was a demonstration only to show the OP how to transition code from C to C++. They can take what I have given them and try to apply their own algorithm to fit their needs.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T14:26:53.007",
"Id": "414284",
"Score": "0",
"body": "Unfortunatly, this isn't a valid multi-line reader."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T00:10:55.193",
"Id": "414370",
"Score": "0",
"body": "@Kittoes0124 It may not be; but it is something that will read each line of code until the entire file has been read. Each line will be stored as a string and the vector of strings would be the entire file. I was demonstrating to the OP what a C++ application would look like compared to a C application. It is up to the OP to take it from here."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T10:14:20.067",
"Id": "214230",
"ParentId": "214187",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T18:55:21.267",
"Id": "214187",
"Score": "7",
"Tags": [
"c++",
"file"
],
"Title": "Multi-Line text reader"
} | 214187 |
<p>I am new to programming and I have made a program to make all repeating numbers in an array 0 and put those all 0s in left side:</p>
<pre><code>import java.util.*;
class ArrayWork
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int arr[],n,i,j,nr[]= new int[5];
System.out.println("Enter the value for n: ");
n = sc.nextInt();
if(n>25)
System.out.println("Invalid input");
else
{
arr = new int[n];
System.out.println("Enter the array elements: ");
for(i=0;i<n;i++)
{
arr[i] = sc.nextInt();
}
int count =0;
for( i=0; i< arr.length-1;i++)
{ for (j=i+1;j<arr.length;j++)
{if(arr[i]==arr[j])
nr[i]=arr[i];
System.out.println(nr[i]);
}}
for(int v=0;v<n;v++){ for(i=0;i<n;i++)
{
if(arr[i]==nr[v])
{
for(j=i-1;j>=0&&arr[j]>0;j--)
{
arr[j+1]=arr[j];
}
arr[j+1]=0;
}
}}
System.out.println("The array is: ");
for(i=0;i<n;i++)
{
System.out.print(arr[i] + " ");
}
}
}
}
</code></pre>
<p>Can I do anything to make this program smaller although the output is coming right and the program is ok
but I have made many loop,
Hope you know any better way?</p>
<p>INPUT:</p>
<pre><code>10,20,20,4,4,6
</code></pre>
<p>OUTPUT:</p>
<pre><code>0,0,0,0,10,6
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T20:11:31.677",
"Id": "414190",
"Score": "1",
"body": "It could be better/simpler and should be properly formatted. Also, just checking: What happens if the input is `1,2,2,2,3`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T20:13:50.227",
"Id": "414191",
"Score": "0",
"body": "The array is: \n0 0 0 1 3"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T20:18:23.747",
"Id": "414193",
"Score": "0",
"body": "Cool. It’s hard to tell due to formatting problems, especially indentation. Use an IDE and get it to reformat the code for you."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T20:22:40.170",
"Id": "414195",
"Score": "0",
"body": "well, i have made it in bluej"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T20:38:09.573",
"Id": "414198",
"Score": "0",
"body": "Oh duplicate numbers are _removed_, not consolidated? Well crap, let me update my answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T07:15:00.383",
"Id": "414245",
"Score": "0",
"body": "@ChildhoodToons Do you want *all duplicate values* to be removed, or only *adjacent duplicates*? For example, should `7` be removed in the following sequence: `2, 7, 3, 4, 7, 5`?"
}
] | [
{
"body": "<p>Use hashmap, in first traversal, gather all values with their counts.\nInitiate an arraylist, do second traversal, if count of that element is 1, append the element to list.\nAt the end, prepend as many number of zeros as the difference the length of list and input array.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T20:15:14.700",
"Id": "414192",
"Score": "0",
"body": "i haven't have used hashmap before just heard but thanks i will try"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T20:20:12.340",
"Id": "414194",
"Score": "0",
"body": "HashMap won’t work. (I *think*) OP only wants *adjacent* dupes removed."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T20:14:17.613",
"Id": "214190",
"ParentId": "214189",
"Score": "0"
}
},
{
"body": "<p>I would do most of this in a single loop:</p>\n\n<pre><code>//if length of the input is < 2, just return it\nint[] input = /* our input array with ANY numbers or amount of them */\nint j = input.length - 2;\nint last = input[input.length - 1]; //the number after ours index-wise\n//i is for search, j is for replacement\nfor (int i = input.length - 2; i >= 0; i--) {\n int current = input[i]; //the number we're comparing\n if (current != last) { //if it's unique\n j--; //move the area we'll zero-fill over one\n continue; //next loop iteration, last is the same\n //below this point assumes the number is a duplicate\n } else if (i > 0) { //if i is 0, the j-loop will handle it\n //rather than search the array for the next number, we'll just shift here\n input[i] = input[i - 1]; //grab the proceeding number and fill it in\n }\n last = current; //update our comparison with the old number that was possibly replaced\n}\nfor (; j >= 0; j--) {\n input[j] = 0; //zero out the area outside our unique numbers\n}\n</code></pre>\n\n<p>There's certainly room for a little improvement, but for phone-typing I'm hoping I got the point across. Let me know if you've got any questions, like the funky j-loop for instance.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T20:36:49.840",
"Id": "214191",
"ParentId": "214189",
"Score": "0"
}
},
{
"body": "<pre><code>final static int MAX_NUMBER = 500;\nfinal static int MAX_SIZE = 25;\nstatic int[] count = new int[MAX_NUMBER];\npublic static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the value for n: \");\n int n = sc.nextInt();\n int[] arr = new int[n];\n if(n > MAX_SIZE) {\n System.out.println(\"Invalid input: \" + n);\n return;\n }\n System.out.println(\"Enter the array elements: \");\n\n for(int i = 0; i < n ; i++) {\n arr[i] = sc.nextInt();\n count[arr[i]]++;\n }\n ArrayList<Integer> result = new ArrayList<Integer>();\n for(int i = 0; i < n ;i++) {\n if(count[arr[i]] == 1) {\n result.add(arr[i]);\n }\n }\n\n System.out.println(\"The array is: \");\n for(int i = 0; i < n - result.size(); i++) {\n System.out.print(\"0 \");\n }\n\n for(int i = 0; i < result.size(); i++) {\n System.out.print(result.get(i) + \" \");\n }\n}\n</code></pre>\n\n<p>Here I tried to simplify your code. As you are new to programming I havent used a hashmap. Basically after reading the input array, in count array you store how many times they occur. Then you iterate the array, if the current element count is 1 you add it to the result list. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T20:42:23.643",
"Id": "214193",
"ParentId": "214189",
"Score": "0"
}
},
{
"body": "<p>It isn't clear that you specifically need to be working with arrays or if you just need to be manipulating a set of numbers. If there's no such requirement, you could use an <code>ArrayList</code> and dynamically allocate your buffer instead. This also gives you some built-in ways to find and move entries around using the <code>List</code> interface. (Technically, if your input and output type is strictly an array, perhaps you still could still convert to an <code>ArrayList</code> to do your work then convert back.)</p>\n\n<p>Other comments:</p>\n\n<ul>\n<li>I'm unsure if there's any particular reason to hard cap your buffer sizes but it can be avoided</li>\n<li><code>Scanner</code> is an object that should be cleaned up (it doesn't matter much in this simple program but generally you should release resources when you no longer need them (consider if this was reading a file stream instead). You can either call <code>close()</code> on the object after you're done reading inputs or wrap the usage in a <a href=\"https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html\" rel=\"nofollow noreferrer\">try-with-resources block</a></li>\n<li>As always, more comments and clearer variable names are appreciated</li>\n</ul>\n\n<p>Here's an example that prioritizes minimizing the number of loops in the code, this one has two loops and an inner loop (input, search, replace):\n</p>\n\n<pre><code>int listSize;\nList<Integer> list;\n\ntry (Scanner scanner = new Scanner(System.in)) {\n System.out.println(\"Enter the array size: \");\n listSize = scanner.nextInt();\n\n list = new ArrayList<>(listSize);\n System.out.println(\"Enter the array elements: \");\n for (int i = 0; i < listSize; ++i) {\n list.add(scanner.nextInt());\n }\n}\n\nfor (int i = 0; i < listSize; ++i) {\n int value = list.get(i);\n int lastIndex = list.lastIndexOf(value);\n if (lastIndex > i) {\n // there's another element of this value after this one\n for (int j = i; j <= lastIndex; ++j) {\n if (list.get(j) == value) {\n // repeated value to zero and move to the beginning of the list\n list.remove(j);\n list.add(0, 0);\n }\n }\n }\n}\n\nSystem.out.println(\"The array is: \");\nfor (int i = 0; i < listSize; i++) {\n System.out.print(list.get(i) + \" \");\n}\n</code></pre>\n\n<p>This example may not be the most efficient but it tries to make the most of built-in functions, and saves you the effort of managing an array directly. In general that would be my advice, see what already exists in standard libraries to do simple operations.</p>\n\n<p>I think this could be reduced further to eliminate the inner loop and only have an input loop, possibly with a second loop afterwards. Constructs like <code>HashMap</code> could also be utilized to detect duplicates and go down to one input loop. I'll leave that as an exercise to someone else to try.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T21:56:18.533",
"Id": "214202",
"ParentId": "214189",
"Score": "1"
}
},
{
"body": "<h1>Declaration</h1>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>int arr[],n,i,j,nr[]= new int[5];\n</code></pre>\n</blockquote>\n\n<p>Consider to declare variables on separate lines. From <em>Code Complete, 2nd Edition, p761</em>:</p>\n\n<blockquote>\n <p><strong>Use only one data declaration per line</strong></p>\n \n <p>[...]</p>\n \n <p>It’s easier to modify declarations because each declaration is self-contained.</p>\n \n <p>[...]</p>\n \n <p>It’s easier to find specific variables because you can scan a single column rather than reading each line. It’s easier to find and fix syntax errors because the line number the compiler gives you has only one declaration >on it.</p>\n</blockquote>\n\n<h1>Unused Variables</h1>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>int count =0;\n</code></pre>\n</blockquote>\n\n<p><code>count</code> gets declared and initialized but is never in use.. Unused variables should be removed. </p>\n\n<h1><a href=\"https://refactoring.guru/replace-magic-number-with-symbolic-constant\" rel=\"nofollow noreferrer\">Magic Number</a></h1>\n\n<blockquote>\n <p>Your code uses a number that has a certain meaning to it.</p>\n</blockquote>\n\n<p>One magic number is hidden in the code.</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>if(n>25) {\n</code></pre>\n</blockquote>\n\n<p>You can create a new constant variable <code>MAX_SIZE</code></p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>if(n>MAX_SIZE) {\n``\n</code></pre>\n</blockquote>\n\n<h1>Formatting</h1>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>for( i=0; i< arr.length-1;i++)\n{ for (j=i+1;j<arr.length;j++)\n {if(arr[i]==arr[j])\n nr[i]=arr[i];\n System.out.println(nr[i]);\n }}\n</code></pre>\n</blockquote>\n\n<p>The code has an inconsistent formatting. Some key words are on a new-line and some times on the same line of a <code>{</code>.</p>\n\n<p>Additional the code is format in a more C-like style, which I respect but you should have a look into <a href=\"https://www.oracle.com/technetwork/java/codeconvtoc-136057.html\" rel=\"nofollow noreferrer\">Oracles Code Conventions for the Java</a>.</p>\n\n<h1>Reduce Code Complexity Via Methods</h1>\n\n<p>When we consider a <a href=\"http://wiki.c2.com/?CodeSmellMetrics\" rel=\"nofollow noreferrer\">Code Smell Metrics</a> and look at the code, we will find at least two points, that apply:</p>\n\n<blockquote>\n <ul>\n <li>Methods with more than 20 lines of code </li>\n <li>Methods with nesting more than 2 (?) levels deep </li>\n <li>Any global or static variables</li>\n </ul>\n</blockquote>\n\n<p>To reduce the complexity we can introduce some new methods. For example</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>for(i=0;i<n;i++)\n{\n arr[i] = sc.nextInt();\n}\n</code></pre>\n</blockquote>\n\n<p>can be wrapped into a method <code>storeUserInput</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T12:26:03.493",
"Id": "214237",
"ParentId": "214189",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T19:59:55.077",
"Id": "214189",
"Score": "1",
"Tags": [
"java"
],
"Title": "Make repeating numbers 0 and putting them at the beginning of array"
} | 214189 |
<p>I have the following code, is there a way to optimize it/reduce the code?</p>
<pre><code> #!/bin/bash
if [[ "${active_gpu}" == 'true' ]]; then
if [[ "${version}" == 'dev-gpu' ]]; then
pip install "${version}"
else
pip install package-gpu=="${version}"
fi
else
if [[ "${version}" == 'nightly' ]]; then
pip install "${version}"
else
pip install package=="${version}"
fi
fi
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T22:00:10.580",
"Id": "414205",
"Score": "2",
"body": "Please explain what this code accomplishes, and what these conditions are. See [ask]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T04:20:06.643",
"Id": "414231",
"Score": "0",
"body": "Install a Python package, based on 2 variables: active_gpu or version. Code is itself explanatory"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T18:26:50.333",
"Id": "414466",
"Score": "0",
"body": "@spicyramen You're setting yourself up for some close votes. You should take the 2 minutes to explain in your post what your code is supposed to do even if it can be clarified by looking at the code :)"
}
] | [
{
"body": "<p>For this kind of problem you want to build a command line with variables, and run it only once. </p>\n\n<p>You only have a few cases but the benefits of this approach become apparent as you add more cases: you don't need an exponential number of branches to keep up.</p>\n\n<p>This code does not <em>exactly</em> follow the logic of your code but it's probably close enough. I'm using an associative array to build the <code>param</code> variable, and bash regular expressions to test for multiple no-param cases.</p>\n\n<pre><code>#!/bin/bash\ndeclare -A gpu_param=( [true]=-gpu )\n[[ $version =~ nightly|dev-gpu ]] || param=package${gpu_param[$active_gpu]}==\npip install $param$version\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T03:21:42.713",
"Id": "214212",
"ParentId": "214195",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "214212",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T20:59:19.093",
"Id": "214195",
"Score": "1",
"Tags": [
"bash",
"shell",
"installer"
],
"Title": "Install a Python package based on active_gpu or version"
} | 214195 |
<p>I am trying to get ordered components of an interface properly without having a local variable orderedComponents outside, and here is my current code.</p>
<p>Reason is because orderedComponents will be in Interface.java and getChildren will be in componentDefinitions.java and I want a more controllable code.</p>
<p>I was also thinking of changing from List to single dimension array and ill soon remove the static ones I separate them.</p>
<pre><code>public static List<Integer> orderedComponents = new ArrayList<Integer>();
/**
* returns the components ordered
*
* @param interfaceId
* @return The components of an interface sorted
*/
public static List<Integer> getOrderedComponents() {
orderedComponents.clear();
for (int i = 0; i < inter.getComponents().length; i++) {
// if all comps are added, stop the loop
if (orderedComponents.size() == inter.getComponents().length)
break;
if (orderedComponents.isEmpty() && inter.getComponent(i).hasParent()
&& !orderedComponents.contains(inter.getComponent(i).getParentId()))
continue;
// do the magic
getAllChildren(i);
}
return orderedComponents;
}
public static void getAllChildren(int componentId) {
// get the current component definitions
ComponentDefinitions component = inter.getComponent(componentId);
// TODO first parent of the parents
// if component has parent and it is not added to the list, add it
if (component.hasParent() && !orderedComponents.contains(component.getParentId())) {
orderedComponents.add(component.getParentId());
}
// if component is not added to the list, add it
if (!orderedComponents.contains(component.componentId)) {
orderedComponents.add(component.componentId);
}
// loop through all childs of the current components and re-add their childs
for (int j = 0; j < inter.getComponent(componentId).getChilds().size(); j++) {
ComponentDefinitions child = inter.getComponent(componentId).getChilds().get(j);
getAllChildren(child.componentId);
}
}
</code></pre>
<p>Please let me know what improvements could be done here and what I am doing wrong or is advisable to be changed.</p>
| [] | [
{
"body": "<p>If I understood correctly, you have to traverse a list of components where each element has a hierarchy-like structure?</p>\n\n<p>Try the visitor pattern <a href=\"https://www.tutorialspoint.com/design_pattern/visitor_pattern.htm\" rel=\"nofollow noreferrer\">https://www.tutorialspoint.com/design_pattern/visitor_pattern.htm</a> it is a very clean solution of what you're trying to do without any static methods.</p>\n\n<p>And for traversing the children of each component, I think you're trying to do a pseudo-BFS, but it's a bit confusing. BFS is very tricky using recursion. The iterative version kf BFS should be something similar to this <a href=\"https://stackoverflow.com/questions/16380026/implementing-bfs-in-java\">https://stackoverflow.com/questions/16380026/implementing-bfs-in-java</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T23:43:17.710",
"Id": "214205",
"ParentId": "214198",
"Score": "1"
}
},
{
"body": "<p>It’s not really clear what you are trying to achieve. Judging from the code smells I see, this code needs a helper method/object. Don’t be afraid of adding private functions, besides the ones defined in the public interface.</p>\n\n<p>During a traversal, a collection of already visited objects needs to be maintained. The entry method should create it locally and pass it to another private method visit(componentId, visited). This way the visited collection will get automatically garbage collected, when you are finished.</p>\n\n<p>From the performance point of view, it seems that you need a <code>LinkedHashMap</code>, not an <code>ArrayList</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T05:15:19.737",
"Id": "214214",
"ParentId": "214198",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-24T21:28:55.497",
"Id": "214198",
"Score": "2",
"Tags": [
"java",
"recursion"
],
"Title": "Listing ordered components, recursively"
} | 214198 |
<p>I am working on Leetcode challenge #3 (<a href="https://leetcode.com/problems/longest-substring-without-repeating-characters/" rel="nofollow noreferrer">https://leetcode.com/problems/longest-substring-without-repeating-characters/</a>)</p>
<p>Here is my solution using sliding window and a dictionary. I specifically added <code>start = seen[s[i]]+1</code> to skip ahead. I am still told I am far slower than most people (for example, given <code>abcdefgdabc</code>, I am skipping <code>abc</code> when I see the second <code>d</code>. I thought this would save ton of time, but apparently this algorithm has a poor run time.</p>
<pre><code> class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
seen = {}
start = 0
max_size = 0
# check whether left pointer has reached the end yet
while start < len(s):
size = 0
for i in range(start, len(s)):
if s[i] in seen:
start = seen[s[i]]+1
seen = {}
break
else:
seen[s[i]] = i
size += 1
max_size = max(size, max_size)
return max_size
</code></pre>
<hr>
<p><em>UPDATE</em></p>
<pre><code> i = 0
j = 0
seen = {}
max_length = 0
while j < len(s):
if s[j] not in seen:
seen[s[j]] = j
j += 1
max_length = max(max_length, j-i)
else:
i = j = seen[s[j]] + 1
seen = {}
return max_length
</code></pre>
| [] | [
{
"body": "<p>In this loop, <code>while start < len(s):</code>, the string <code>s</code> is not changing, so the length of the string is not going to change either. Yet, for each iteration, you will evaluate <code>len(s)</code> in order to evaluate the loop condition. <code>len(s)</code> is undoubtably a fast operation, but you should still cache the result to avoid the function call every iteration.</p>\n\n<pre><code>limit = len(s)\nwhile start < limit:\n # ...\n</code></pre>\n\n<hr>\n\n<p>The loop <code>for i in range(start, len(s)):</code>, you are again calling <code>len(s)</code> for each iteration (of the outer loop). You could replace this with <code>for i in range(start, limit):</code>, but we will still have a different issue...</p>\n\n<p>You are (mostly) not using <code>i</code> inside the loop; you are using <code>s[i]</code>. And you look up the character <code>s[i]</code> in 3 different places inside the loop. Instead of looping over the indices, and looking up the character at the index, you should directly loop over the characters of the string.</p>\n\n<pre><code>for ch in s[start:]:\n # ...\n</code></pre>\n\n<p>Except for that pesky <code>seen[...] = i</code> statement. You still want the index. The <code>enumerate()</code> function can be used to count as you are looping:</p>\n\n<pre><code>for i, ch in enumerate(s[start:], start):\n if ch in seen:\n start = seen[ch]+1\n seen = {}\n break\n else:\n seen[ch] = i\n size += 1\n</code></pre>\n\n<hr>\n\n<h2>Hint</h2>\n\n<p>When scanning the string <code>abcdefgdhijklmn</code>, after encountering the second <code>d</code>, you reset to the character after the first <code>d</code>, and continue your scan. But ...</p>\n\n<p>Do you have to? Aren’t all the characters between the first <code>d</code> and the second <code>d</code> unique? Is there any way you could preserve that information, and continue on, without needing to restart with the <code>e</code>? Maybe you don’t need nested loops!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-27T03:04:38.920",
"Id": "414523",
"Score": "0",
"body": "Thank you. I rewrote the code (the len stuff I didn't to make the code slightly shorter FOR NOW, but good points). WDYT? The runtime is way better."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T06:07:35.080",
"Id": "214218",
"ParentId": "214211",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "214218",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T01:33:05.937",
"Id": "214211",
"Score": "3",
"Tags": [
"python",
"algorithm"
],
"Title": "Length of longest non-repeating substring challenge using sliding window"
} | 214211 |
<p>Pretty obvious what it's doing here, but It seems pretty silly. What's a better way? </p>
<pre><code> public bool DidHitBounds
{
get {
if (hitBounds == true)
{
hitBounds = false;
return true;
} else
{
return false;
}
}
set
{
hitBounds = value;
}
}
</code></pre>
| [] | [
{
"body": "<p>I agree that it looks silly but more about the design and less the code, I would generally consider it an abuse to modify an object’s state with a getter (<a href=\"https://stackoverflow.com/a/13876247\">second opinion from SO</a>). An acceptable exception would be for cache fields, but this isn’t quite that. In this case there’s no documentation that this behavior will happen either. Such behavior would be clearer in a method name that specifies the effect.</p>\n\n<p>There’s not too much to do in terms of making it more elegant. There’s no reason to have the <code>else</code> after the first return, saving a line. Then, you can eliminate another line and the if altogether knowing that the state is always going to be <code>false</code> in the end and just grab the value to return (unconditional set might be less efficient?)</p>\n\n<p>I would scrap <code>DidHitBounds</code> as a property (considering the getter is confusing and the setter adds no value, <code>HitBounds</code> could be an auto-property) and instead name a method <code>GetAndResetHitBoundsState</code>. Then what’s going on is a least a bit more clear when you call that new method.</p>\n\n<p>e.g.\n</p>\n\n<pre><code>public bool HitBounds { get; set; }\n\n///<summary>Return the hit-bounds state, and reset that state to <c>false</c>.</summary>\n///<returns>Pre-reset hit-bounds state.</returns>\npublic bool GetAndResetHitBoundsState()\n{\n bool result = HitBounds;\n HitBounds = false;\n return result;\n}\n</code></pre>\n\n<p>I suspect the true elegant solution involves understanding how your field is set and received, it smells like something that could be “more elegant” with events or threads but that’s obviously not a simple change.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T10:41:39.437",
"Id": "214231",
"ParentId": "214215",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T05:41:51.567",
"Id": "214215",
"Score": "-2",
"Tags": [
"c#"
],
"Title": "Found this deep in a group project. It looks bad and I'm sure there is a super elegant solution"
} | 214215 |
<p>I am using Spring Data JPA with Spring boot application. My requirement is to insert 50K rows in JPA entity table in one hour or less. </p>
<p>I have 3 entities A, B and C. Entity A has a one to many association with entity B and a one to one association with entity C.</p>
<pre><code>@Entity
public class A {
@OneToMany(mappedBy = "chipJobItem", cascade = {
CascadeType.MERGE,
CascadeType.PERSIST,
CascadeType.REFRESH,
CascadeType.DETACH }, orphanRemoval = true, fetch = FetchType.LAZY)
private List<B> values;
}
@Entity
public class B {
@ManyToOne(fetch = FetchType.LAZY, cascade = {
CascadeType.MERGE,
CascadeType.PERSIST,
CascadeType.REFRESH,
CascadeType.DETACH })
@JoinColumn(name = "fk_product_instance_id", referencedColumnName = "id", foreignKey = @ForeignKey(name = "DATAITEMS_FK"))
private A job;
}
@Entity
public class C {
@ManyToOne(fetch = FetchType.LAZY, cascade = {
CascadeType.MERGE,
CascadeType.PERSIST,
CascadeType.REFRESH,
CascadeType.DETACH })
@JoinColumn(name = "fk_product_instance_id", referencedColumnName = "id", foreignKey = @ForeignKey(name = "DATAITEMS_FK"))
private A job;
}
</code></pre>
<p>I have also set the JDBC batch size = 100, it improves the performance a little. </p>
<p>Need help improving the performance of the JPA insert. </p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T06:38:01.287",
"Id": "414240",
"Score": "4",
"body": "Welcome to Code Review! Nothing much to be done at source level is apparent: **please show the code that leads to the insertions**, too, even if non-illuminative. How many indexes need to be kept? What amount of wait can be tolerated due to such `50K` bulk additions (→in a transaction, drop indexes, bulk insert, rebuild indexes)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T10:01:29.000",
"Id": "414255",
"Score": "0",
"body": "See also: [How to do bulk (multi row) inserts with JpaRepository](https://stackoverflow.com/a/50882952)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-09T10:27:42.347",
"Id": "419974",
"Score": "0",
"body": "I'm afraid this question does not match what this site is about. Code Review is about improving existing, working code. The example code that you have posted is not reviewable in this form because it leaves us guessing at your intentions. Unlike Stack Overflow, Code Review needs to look at concrete code in a real context. Please see [Why is hypothetical example code off-topic for CR?](//codereview.meta.stackexchange.com/q/1709)"
}
] | [
{
"body": "<p><strong>To state the problem:</strong>\nYou have a large sum of operations that are repetitive and mostly similar(?) that are long running, and you want to reduce that run time.\n<hr>\n<strong>If I have that right:</strong></p>\n\n<p><strong>If order is not a concern</strong> You could consider inserting in parallel. If you can represent the 50,000 updates as a List, say, <code>List<InsertCriteriaPojo></code>, and can represent the insert as a Consumer lambda, like so: <code>((InsertCriteriaPojo item) -> myDao.insert(item))</code>, then this could be a one line call:</p>\n\n<pre><code>List<InsertCriteriaPojo> items = ...;\n\nitems.stream().parallel().map((InsertCriteriaPojo item) -> myDao.insert(item));\n</code></pre>\n\n<p>This creates a Stream of InsertCriteriaPojos, converts that to a ParallelStream, and them maps each item in the List to a Consumer and runs the Consumer/item tasks in a set of threads belonging to the common ForkJoinPool</p>\n\n<hr>\n\n<p><strong>While short, there are problems with this</strong></p>\n\n<p>The main problem <a href=\"https://dzone.com/articles/think-twice-using-java-8\" rel=\"nofollow noreferrer\">as explained here</a> is that <s>you can't specify an Executor to ParallelStreams (as of Java 1.8*).</s></p>\n\n<p><strong>UPDATE:</strong> The above is inaccurate. This can be done like so:</p>\n\n<pre><code>List<InsertCriteriaPojo> items = ...;\nForkJoinPool customThreadPool = new ForkJoinPool(threadCount);\ncustomThreadPool.submit(\n () -> items.stream().parallel().map(\n (InsertCriteriaPojo item) -> myDao.insert(item)\n )\n).get;\n</code></pre>\n\n<hr>\n\n<p>Another, more complex way to run these tasks in parallel is to use an Executor you configure:</p>\n\n<pre><code>@Bean(name = \"myExecutor\")\npublic Executor executor(){\n ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();\n executor.setCorePoolSize(yourProperties.getCorePoolCount());\n executor.setMaxPoolSize(yourProperties.getMaxPoolCount());\n executor.setQueueCapacity(yourProperties.getMaxQueueSize());\n executor.setThreadNamePrefix(yourProperties.getThreadNamePrefix());\n executor.initialize();\n return threadPoolTaskExecutor;\n}\n</code></pre>\n\n<p>To run your consumers asynchronously:</p>\n\n<pre><code>...\n@Autowire\n@Qualifier(\"myExecutor\")\nExecutor executor;\n...\nList<InsertCriteriaPojo> items = ...\n//Make a Future for each task\nList<CompletableFuture<Void>> asyncTaskFutures = list.stream().map(\n (InsertCriteriaPojo item) ->{\n CompletableFuture.runAsync(\n () -> myDao.insert(item), executor\n ).handle(\n (asyncVoidFuture, possibleError)->{\n if(possibleError != null){ //Handle your errors here }\n else{return asyncVoidFuture;}\n })\n }\n).collect(Collectors.toList());\n\n//Create a Future that is complete when allOf your task futures are complete\nCompletableFuture<Void> process = CompletableFuture.allOf(\n asyncTaskList.toArray(new CompletableFuture[asyncTaskList.size()])\n).thenRun(() -> asyncTaskList.stream().map(future -> future.join()));\n\n//Complete the process-level future, blocks until complete\nprocess.get();\n</code></pre>\n\n<p>While significantly more complex, the second is a more configurable and reusable way to solve your problem, but depending on your case either approach could serve your goal.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-02T15:58:38.677",
"Id": "216730",
"ParentId": "214217",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T05:54:08.013",
"Id": "214217",
"Score": "3",
"Tags": [
"java",
"performance",
"database",
"spring",
"jpa"
],
"Title": "Inserting 50k rows with Spring Data and JPA"
} | 214217 |
<p>I'm an absolute python beginner.</p>
<p>I created a draw poker game that works fine up to about ten thousand hands, at which point it starts to freeze and not generate the hands. Given that straight flushes only generate about once per 70 thousand hands (it may be more common bc my program uses multiple decks for the many hands) and royal flushes once per >600k, I'd like to be able to generate more hands. Is there something in my code that's taking up tons of memory or slowing the process down?</p>
<p>Here's my current code:</p>
<pre><code>import copy
import distutils.core
from random import randint
from math import floor
#Individual Cards
class Card:
def __init__ (self,value,suit):
self.value = value
self.suit = suit
self.vname = ''
self.sname = ''
def valname(self, value):
if self.value == 2:
self.vname = 'Two'
return 'Two'
if self.value == 3:
self.vname = 'Three'
return 'Three'
if self.value == 4:
self.vname = 'Four'
return'Four'
if self.value == 5:
self.vname = 'Five'
return'Five'
if self.value == 6:
self.vname = 'Six'
return'Six'
if self.value == 7:
self.vname = 'Seven'
return'Seven'
if self.value == 8:
self.vname = 'Eight'
return'Eight'
if self.value == 9:
self.vname = 'Nine'
return'Nine'
if self.value == 10:
self.vname = 'Ten'
return'Ten'
if self.value == 11:
self.vname = 'Jack'
return'Jack'
if self.value == 12:
self.vname = 'Queen'
return'Queen'
if self.value == 13:
self.vname = 'King'
return'King'
if self.value == 14:
self.vname = 'Ace'
return'Ace'
def suitname(self, suit):
if self.suit == "hearts":
self.sname = '♥'
return '♥'
if self.suit == "spades":
self.sname = '♠'
return '♠'
if self.suit == "clubs":
self.sname = '♣'
return '♣'
if self.suit == "diamonds":
self.sname = '♦︎'
return '♦︎'
def cardname(self):
return f'{self.sname}{self.vname}{self.sname}'
#All Decks
class Deck:
def __init__(self):
self.cards = []
self.create()
def create(self):
for d in range(decks):
for suit in ["hearts", "spades", "clubs", "diamonds"]:
for val in [2,3,4,5,6,7,8,9,10,11,12,13,14]:
self.cards.append(Card(val,suit)); d+=1
def shuffle(self):
for _ in range(26):
for index in range(len(self.cards)-1,-1,-1):
rindex = randint(0, index)
self.cards[index], self.cards[rindex] = self.cards[rindex], self.cards[index]
def draw(self):
c1 = self.cards.pop()
c2 = self.cards.pop()
c3 = self.cards.pop()
c4 = self.cards.pop()
c5 = self.cards.pop()
return [c1,c2,c3,c4,c5]
def ss():
if show_strength: print(f'[{round(strength/10000,6)}]')
#Evaluation Functions
def evalname(x):
if x == 2:
return 'Two'
if x == 3:
return 'Three'
if x == 4:
return 'Four'
if x == 5:
return 'Five'
if x == 6:
return 'Six'
if x == 7:
return 'Seven'
if x == 8:
return 'Eight'
if x == 9:
return 'Nine'
if x == 10:
return 'Ten'
if x == 11:
return 'Jack'
if x == 12:
return 'Queen'
if x == 13:
return 'King'
if x == 14:
return 'Ace'
def hcard(hand):
global strength
strength = 1000 + 10*vsort[0] + vsort[1] + .1*vsort[2] + .01*vsort[3] + .001*vsort[4]
return f'High-Card {evalname(vsort[0])}'
def numpair(hand):
global strength
pairs = list(dict.fromkeys([val for val in values if values.count(val) == 2]))
if len(pairs) < 1:
return False
if len(pairs) == 1:
vp = vsort.copy()
for _ in range(2):
vp.remove(pairs[0])
strength = 2000 + 10*pairs[0] + vp[0] + .1*vp[1] + .01*vp[2];
return f'Pair of {evalname(pairs[0])}s'
if len(pairs) == 2:
vps = vsort.copy()
for _ in range(2):
vps.remove(pairs[0]); vps.remove(pairs[1])
if pairs[0]>pairs[1]:
strength = (3000 + 10*int(pairs[0]) + int(pairs[1])) + .1*vps[0]
return f'{evalname(pairs[0])}s and {evalname(pairs[1])}s'
else:
strength = (3000 + 10*int(pairs[1]) + int(pairs[0])) + .1*vps[0]
return f'{evalname(pairs[1])}s and {evalname(pairs[0])}s'
def detset(hand):
global strength
detsets = [val for val in values if values.count(val) == 3]
if len(detsets) < 1:
return False
else:
vs = vsort.copy()
for _ in range(3):
vs.remove(detsets[0])
strength = 4000 + 10*detsets[0] + vs[0] + .1*vs[1]
return f'Set of {evalname(detsets[0])}s'
def straight(hand):
global strength
if (max(vset) - min(vset) == 4) and numpair(hand) == False and detset(hand) == False and quads(hand) == False:
strength = 4999 + min(vset)
straight = f'Straight from {evalname(min(vset))} to {evalname(max(vset))}'
elif vset == {14,2,3,4,5}:
strength = 5000
straight = 'Straight from Ace to Five'
else:
straight = False
return straight
def flush(hand):
global strength
suits = [hand[0].suit,hand[1].suit,hand[2].suit,hand[3].suit,hand[4].suit]
flushes = [suit for suit in suits if suits.count(suit) == 5]
if len(flushes) < 5:
flush = False
else:
values.sort(reverse=True)
strength = 6000 + 10*values[0] + values[1] + .1*values[2] + .01*values[3] + .001*values[4]
flush = f'{evalname(max(values))}-High flush of {flushes[0]}'
return flush
def fullhouse(hand):
global strength
pairs = [val for val in values if values.count(val) == 2]
detsets = [val for val in values if values.count(val) == 3]
if detset(hand) != False and numpair(hand) != False:
strength = 7000 + 10*detsets[0] + pairs[0]
fh = f'{evalname(detsets[0])}s full of {evalname(pairs[0])}s'
else:
fh = False
return fh
def quads(hand):
global strength
quads = [val for val in values if values.count(val) == 4]
if len(quads) < 1:
return False
else:
vq = vsort.copy()
for _ in range(4):
vq.remove(quads[0])
strength = 8000 + 10*quads[0] + vq[0]
return f'Quad {evalname(quads[0])}s'
def straightflush(hand):
global strength
if (max(vset) - min(vset) == 4) and numpair(hand) == False and detset(hand) == False and quads(hand) == False and vset != {14,13,12,11,10}:
straight = "True"
elif vset == {14,2,3,4,5}:
straight = 'Wheel'
elif vset == {14,13,12,11,10}:
straight = "Royal"
else:
straight = 'False'
flushes = [suit for suit in suits if suits.count(suit) == 5]
if len(flushes) < 1:
flush = False
else:
flush = True
if straight == "True" and flush == True:
strength = 8999 + min(vset)
sf = f'{evalname(max(values))}-high straight flush of {flushes[0]}'
elif straight == "Wheel" and flush == True:
strength = 9000
sf = f'Five-High straight flush of {flushes[0]}'
elif straight == "Royal" and flush == True:
strength = 10000
sf = f'Royal flush of {flushes[0]}'
else:
sf = False
return sf
#Count Hand Occurence
hand_occurence = {0:0,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0}
ho_names = ['High Card: ','Pair: ','Two-Pair: ','Three of a Kind: ','Straight: ','Flush: ','Full House: ','Four of a Kind: ','Straight Flush: ','Royal Flush: ']
decks = int(input("How many decks are there? "))
deck = Deck(); deck.shuffle()
hnumber = int(input(f"How many players are there (max {floor((decks*52)/5)})? "))
show_strength = distutils.util.strtobool(input("Would you like to show advanced stats? "))
h_inc = 0; h_strength = {}
while h_inc < hnumber:
print(f"\nPlayer {h_inc + 1}'s hand:")
c1,c2,c3,c4,c5 = deck.draw(); hand = c1,c2,c3,c4,c5
values = [hand[0].value,hand[1].value,hand[2].value,hand[3].value,hand[4].value]; vset = {hand[0].value,hand[1].value,hand[2].value,hand[3].value,hand[4].value}; vsort = sorted(values,reverse=True)
suits = [hand[0].suit,hand[1].suit,hand[2].suit,hand[3].suit,hand[4].suit]
c1.valname(c1.value); c2.valname(c2.value); c3.valname(c3.value); c4.valname(c4.value); c5.valname(c5.value);
c1.suitname(c1.suit); c2.suitname(c2.suit); c3.suitname(c3.suit); c4.suitname(c4.suit); c5.suitname(c5.suit);
print(f'| {c1.cardname()} | {c2.cardname()} | {c3.cardname()} | {c4.cardname()} | {c5.cardname()} |')
hcard(hand); numpair(hand); detset(hand); straight(hand); flush(hand); fullhouse(hand); quads(hand); straightflush(hand)
if strength < 2000:
print(hcard(hand),end=" "); ss()
hand_occurence[0]+=1
elif strength < 3000:
print(numpair(hand),end=" "); ss()
hand_occurence[1]+=1
elif strength < 4000:
print(numpair(hand),end=" "); ss()
hand_occurence[2]+=1
elif strength < 5000:
print(detset(hand),end=" "); ss()
hand_occurence[3]+=1
elif strength < 6000:
print(straight(hand),end=" "); ss()
hand_occurence[4]+=1
elif strength < 7000:
print(flush(hand),end=" "); ss()
hand_occurence[5]+=1
elif strength < 8000:
print(fullhouse(hand),end=" "); ss()
hand_occurence[6]+=1
elif strength < 9000:
print(quads(hand),end=" "); ss()
hand_occurence[7]+=1
elif strength < 10000:
print(straightflush(hand),end=" "); ss()
hand_occurence[8]+=1
elif strength == 10000:
print(straightflush(hand),end=" "); ss()
hand_occurence[9]+=1
h_strength[h_inc] = strength
h_inc += 1
hss = sorted(h_strength.items(), key=lambda k: k[1], reverse=True)
print(f'\n\n\nPlayer {hss[0][0]+1} has the strongest hand! [{round(hss[0][1]/10000,6)}]\nPlayer {hss[hnumber-1][0] + 1} has the weakest hand :( [{round(hss[hnumber-1][1]/10000,6)}]') if show_strength else print(f'\nPlayer {hss[0][0] + 1} has the strongest hand!\nPlayer {hss[hnumber-1][0]+1} has the weakest hand :(')
if show_strength:
print('\n\n\n\n\nHand Occurence:\n')
for x in range(10):
print(ho_names[x],hand_occurence[x])
print('\n\n\n\n\nFull Player Ranking:\n')
for x in range(len(hss)):
print(f'{x+1}.',f'Player {hss[x][0]+1}',f'[{round(hss[x][1]/10000,6)}]')
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T07:25:32.343",
"Id": "414247",
"Score": "0",
"body": "Not sure if I used the word 'draw poker' correctly. This is just a 5-card showdown using holdem hand ranking rules"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T11:34:27.317",
"Id": "414264",
"Score": "0",
"body": "Welcome to code review. Absolute beginners are welcome here. Enjoy! Hope you learn a lot."
}
] | [
{
"body": "<p>First, some style-issues. Python has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>. It recommends not putting multiple commands on the same line. In addition trailing <code>;</code> are superfluous.</p>\n\n<p>Now, let's look at the needed structure. You need a <code>Card</code> that contains all information about that card and a <code>Hand</code> which can evaluate a list of cards with respect to the poker rules. You don't actually need a <code>Deck</code> if you just have a list of all cards in the deck and then do <code>random.sample(cards, n_players*5)</code> to get the hands for all players, which you can then distribute to the players.</p>\n\n<p>So, let's have a look at <code>Card</code> first, since you already do have this class. Your <code>valname</code> method is very inefficient. First, it could be that it is called multiple times (this does not seem to be the case). But you also have a chain of <code>if</code>s, however only ever one of them can be true, so use <code>elif</code> instead. Otherwise all conditions will need to be checked, instead of only all conditions until the first true one.</p>\n\n<p>But even easier here is to use a simple <code>tuple</code>:</p>\n\n<pre><code>class Card:\n value_names = (\"Two\", \"Three\", \"Four\", \"Five\", \"Six\", \"Seven\", \"Eight\", \"Nine\", \"Ten\",\n \"Jack\", \"Queen\", \"King\", \"Ace\")\n def __init__(self, value, suit):\n self.value = value\n self.suit = suit\n\n def __str__(self):\n return f\"{self.value_names[self.value - 1]} of {self.suit}\"\n\n def __repr__(self):\n return f\"{self.suit} {self.value}\"\n\n def __lt__(self, other):\n return self.value < other.value\n\n def __eq__(self, other):\n return self.value == other.value\n</code></pre>\n\n<p>The <code>__str__</code> method is a <a href=\"https://rszalski.github.io/magicmethods/\" rel=\"nofollow noreferrer\">magic method</a> that will be called when you do <code>print(card)</code> and <code>__repr__</code> will be called when typing <code>card</code> in an interactive session. The <code>__lt__</code> and <code>__eq__</code> allow cards to be compared by their value, which is used for example by <code>sorted</code> when we have an iterable of cards.</p>\n\n<p>If you want the fancy unicode names for the suits, just use that when constructing the cards:</p>\n\n<pre><code>from itertools import product\n\ndeck = [Card(value, suit) for value, suit in product(range(2, 15), \"♥♠♣♦\")]\n</code></pre>\n\n<p>Now let's get to the meat of the problem, evaluating poker hands, which should be the responsibility of the <code>Hands</code> class:</p>\n\n<pre><code>from collections import Counter\nfrom itertools import tee, chain\n\n\ndef difference(iterable):\n a, b = tee(iterable)\n try:\n item = next(b)\n except StopIteration:\n return iter([])\n return chain([item], map(lambda x: x[1] - x[0], zip(a, b)))\n\n\nclass Hand:\n def __init__(self, cards):\n self.cards = sorted(cards)\n self.values = [card.value for card in self.cards]\n self.values_counter = Counter(self.values)\n self.suits = [card.suit for card in self.cards]\n self.low_card, self.high_card = self.values[0], self.values[-1]\n\n def __repr__(self):\n return \", \".join(repr(card) for card in self.cards)\n\n def flush(self):\n return len(set(self.suits)) == 1\n\n def straight(self):\n diffs = sorted(list(difference(self.values))[1:])\n return diffs in ([1, 1, 1, 1], [-12, 1, 1, 1])\n\n def fullhouse(self):\n candidate = self.values_counter.most_common(2)\n return candidate[0][1] == 3 and candidate[1][1] == 2\n\n def evaluate(self):\n # flush/straight flush/royal flush\n if self.flush():\n if self.straight():\n # royal flush\n if self.high_card == 14 and self.low_card == 10:\n return \"Royal Flush\", 10000\n # straight flush\n return \"Straight Flush\", 8999 + self.low_card\n # flush\n return \"Flush\", 6000 + sum(10**k * x\n for k, x in zip([1, -1, -2, -3], self.values))\n # straight\n elif self.straight():\n if self.high_card == 14 and self.low_card == 2:\n return \"Straight\", 5000\n return \"Straight\", 4999 + self.low_card\n # fullhouse\n elif self.fullhouse():\n triple, pair = self.values_counter.most_common(2)\n return \"Full House\", 7000 + 10 * triple[0] + pair[0]\n # two pair\n candidate1, candidate2, *rest = self.values_counter.most_common()\n rest = sorted(r[0] for r in rest)\n if candidate1[1] == candidate2[1] == 2:\n c0, c1 = sorted([candidate1[0], candidate2[0]])\n return \"Two Pairs\", 3000 + 10* c0 + c1 + sum(10**k * x\n for k, x in zip([-1, -2], rest))\n # quad\n candidate, *rest = self.values_counter.most_common()\n rest = sorted(r[0] for r in rest)\n if candidate[1] == 4:\n return \"Quad\", 8000 + 10 * candidate[0] + rest[0]\n # triple\n elif candidate[1] == 3:\n return \"Triple\", 4000 + 10*candidate[0] + rest[0] + .1*rest[1]\n # pair\n elif candidate[1] == 2:\n return \"Pair\", 2000 + 10*candidate[0] + rest[0] + .1*rest[1] + .01*rest[2]\n # highcard\n return \"High Card\", self.high_card\n</code></pre>\n\n<p>The difference function is taken from the <a href=\"https://more-itertools.readthedocs.io/en/stable/api.html#more_itertools.difference\" rel=\"nofollow noreferrer\"><code>more_itertools</code></a> package.\nA <a href=\"https://docs.python.org/3/library/collections.html#collections.Counter\" rel=\"nofollow noreferrer\"><code>collections.Counter</code></a> object is exactly what it says. If you pass it an iterable it will count how often each object appears and it has some nice methods like <code>most_common</code> which returns tuples of <code>element, count</code>, sorted decreasingly by <code>count</code>.</p>\n\n<p>Now that we have that the main loop becomes quite a bit easier:</p>\n\n<pre><code>from itertools import zip_longest, islice, product\nfrom random import sample\n\ndef grouper(iterable, n, fillvalue=None):\n \"Collect data into fixed-length chunks or blocks\"\n # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx\"\n args = [iter(iterable)] * n\n return zip_longest(*args, fillvalue=fillvalue)\n\nif __name__ == \"__main__\":\n deck = [Card(value, suit) for value, suit in product(range(2, 15), \"♥♠♣♦\")]\n rounds = int(input(\"How many rounds? \"))\n players = int(input(\"How many players (max 10)? \"))\n show_strength = input(\"Show result each round? \").lower()[0] == \"y\"\n assert players <= 10\n hand_occurrence = Counter()\n\n for _ in range(rounds):\n hands = [Hand(cards) for cards in grouper(sample(deck, players * 5), 5)]\n evaluated_hands = [hand.evaluate() for hand in hands]\n hand_occurrence += Counter(hand[0] for hand in evaluated_hands)\n if show_strength:\n strongest = max(evaluated_hands, key=lambda hand: hand[1])\n print(\"Strongest hand:\", strongest)\n print(\"Statistics:\", hand_occurrence.most_common())\n</code></pre>\n\n<p>The <code>grouper</code> function which I used to split the hands into groups of 5 cards each is from the <a href=\"https://docs.python.org/3/library/itertools.html#itertools-recipes\" rel=\"nofollow noreferrer\"><code>itertools</code> recipes</a>.</p>\n\n<p>I did not bother to use nicer user input functions here, but there are plenty examples on this site on how to do it more foolproof (and keep on asking if the supplied input is somehow wrong).</p>\n\n<p>This code takes about 3.14 s ± 82 ms for 10,000 rounds with 10 players and about 34.4 s ± 483 ms for 100,000 rounds on my machine, without printing the results from each round.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T10:20:26.880",
"Id": "414259",
"Score": "1",
"body": "Much better!, I may add that those strengths are still magic numbers. Maybe add them as an `Enum`..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T10:24:04.777",
"Id": "414260",
"Score": "0",
"body": "@Ludisposed: True, there is still some room left for improvement, especially regarding readability. But I think I will stop here with the review. Maybe you want to write an answer taking it further?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T12:31:53.810",
"Id": "414272",
"Score": "0",
"body": "Thanks for this! It performs much better."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T09:32:30.597",
"Id": "214228",
"ParentId": "214221",
"Score": "7"
}
},
{
"body": "<p>To expand on <a href=\"https://codereview.stackexchange.com/questions/214221/allow-console-draw-poker-game-to-output-more-hands/214228#214228\">@Graiphers</a> excellent review,</p>\n\n<p><strong>Adding multiple decks</strong></p>\n\n<p>@Graipher differs from your post as he only uses a single deck, but this can easily be added</p>\n\n<pre><code>deck = [\n Card(value, suit) for value, suit in product(range(2, 15), \"♥♠♣♦\")\n for _ in range(num_of_decks)\n]\n</code></pre>\n\n<p><strong>Avoid magic numbers</strong></p>\n\n<p>Since a number has no special meaning, and you should avoid dedicating chunks of code to a specific number.</p>\n\n<p>If that number changes you would have to change all occurrences of that number which is error-prone</p>\n\n<p>Secondly and I already stressed this, numbers don;t have meaning variables do!</p>\n\n<p>You can use <a href=\"https://docs.python.org/3/library/enum.html\" rel=\"nofollow noreferrer\">Enum</a> which is in the standard library to solve this problem</p>\n\n<pre><code>class PossibleHands(Enum):\n ROYAL_FLUSH = 10000,\n WHEEL_STRAIGHT_FLUSH = 8999,\n STRAIGHT_FLUSH = 90000,\n FLUSH = 6000\n ...\n</code></pre>\n\n<p>And when @Graipher returns the name and the strength value, you could use that Enum value</p>\n\n<blockquote>\n<pre><code>return \"Royal Flush\", 10000\n</code></pre>\n</blockquote>\n\n<p>would be</p>\n\n<pre><code>return PossibleHands.ROYAL_FLUSH , PossibleHands.ROYAL_FLUSH.value\n</code></pre>\n\n<p><strong>Validate your user input</strong></p>\n\n<p>Your program will currently break if the user input some wrong values,</p>\n\n<p>ie </p>\n\n<pre><code>How many decks are there? s\n...\nValueError: invalid literal for int() with base 10: 's'\n</code></pre>\n\n<p>Or if you input more players then is possible</p>\n\n<pre><code>How many decks are there? 1\nHow many players are there (max 10)? 21\n...\nIndexError: pop from empty list\n</code></pre>\n\n<p>This can be avoided by using a function to check the input</p>\n\n<pre><code>def get_value(_max, mess):\n while True:\n try:\n v = int(input(mess))\n if (_max is None or v <= _max) and v > 0:\n return v\n else:\n smaller = '' if _max is None else f'and smaller then {_max}'\n print(f'Value should be greater then 0 {smaller}')\n except ValueError:\n print('Please enter an integer')\n\ndef main():\n num_of_decks = get_value(None, f'How many decks? ')\n deck = [\n Card(value, suit) for value, suit in product(range(2, 15), \"♥♠♣♦\")\n for _ in range(num_of_decks)\n ]\n max_players = floor((num_decks*52) / 5)\n num_players = get_value(max_players, f'How many players are there? (max {max_players}) ')\n ...\n</code></pre>\n\n<p>Now the getting of wrong input is handled correctly</p>\n\n<pre><code>How many decks? s\nPlease enter an integer\nHow many decks? 2\nHow many players are there? (max 20) 22\nValue should be greater then 0 and smaller then 20\nHow many players are there? (max 20) 1\n</code></pre>\n\n<p><strong>Avoid using global variables</strong></p>\n\n<p>You use <code>global val</code> a few times, and this is a bad habit to get into. Because it will make it unclear where a variable is changed. So it makes tracking down that 1 bug a real pain in the ***</p>\n\n<p>@Graipher solves this by having a <code>Hand</code> class</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T12:34:29.800",
"Id": "414273",
"Score": "1",
"body": "Regarding strengths, there's over 7000 distinct strengths a 5 card hand can have. That's why I didn't set individual strengths for each hand (only a baseline plus the other factors). Or am I not understanding what you're trying to say?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T12:38:21.707",
"Id": "414275",
"Score": "0",
"body": "I have removed the sentence, it was more of a self note. And may edit the awnser when I have found a better solution ;)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T12:16:26.090",
"Id": "214235",
"ParentId": "214221",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "214228",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T07:04:09.110",
"Id": "214221",
"Score": "7",
"Tags": [
"python",
"beginner",
"python-3.x",
"playing-cards"
],
"Title": "Allow console draw poker game to output more hands"
} | 214221 |
<p>As <a href="//stackoverflow.com/a/54857675">my answer to <em>Iterating over an odd (even) elements only in a range-based loop</em></a>, I wrote this function, with the following driver program and output:</p>
<pre><code>#include <array>
#include <vector>
#include <iterator>
// Forward iteration from begin to end by step size N.
template<typename Container, typename Function>
void for_each_by_n( Container&& cont, Function f, unsigned increment_by = 1) {
if ( increment_by == 0 ) return; // must check this for no op
using std::begin;
auto it = begin(cont);
using std::end;
auto end_it = end(cont);
while( it != end_it ) {
f(*it);
for ( unsigned n = 0; n < increment_by; ++n ) {
if ( it == end_it ) return;
++it;
}
}
}
int main() {
std::array<int,8> arr{ 0,1,2,3,4,5,6,7 };
std::vector<double> vec{ 1.2, 1.5, 1.9, 2.5, 3.3, 3.7, 4.2, 4.8 };
auto l = [](auto& v) { std::cout << v << ' '; };
for_each_by_n(arr, l); std::cout << '\n';
for_each_by_n(vec, l); std::cout << '\n';
for_each_by_n(arr, l, 2); std::cout << '\n';
for_each_by_n(arr, l, 4); std::cout << '\n';
for_each_by_n(vec, l, 3); std::cout << '\n';
for_each_by_n(vec, l, 5); std::cout << '\n';
for_each_by_n(arr, l, 8); std::cout << '\n';
for_each_by_n(vec, l, 8); std::cout << '\n';
// sanity check to see if it doesn't go past end.
for_each_by_n(arr, l, 9); std::cout << '\n';
for_each_by_n(vec, l, 9); std::cout << '\n';
return 0;
}
</code></pre>
<h2>Output</h2>
<pre class="lang-none prettyprint-override"><code> 0 1 2 3 4 5 6 7
1.2 1.5 1.9 2.5 3.3 3.7 4.2 4.8
0 2 4 6
0 4
1.2 2.5 4.2
1.2 3.7
0
1.2
0
1.2
</code></pre>
<p>I did my best to check for possible bugs, corner cases etc.</p>
<p>What I would like to know about my function above:</p>
<ul>
<li>Does this follow modern C++ standards?</li>
<li>Is there any room for improvements?</li>
<li>Did I miss any possible bugs that I might have overlooked?</li>
<li>Would this be considered readable, reliable, generic, portable, cross-platform and reusable?</li>
<li>Do I have to worry about any const correctness, type deduction, cache misses and the like?</li>
<li><em>-Note-</em>: I know the above function is not in a designated namespace; that is not of concern here. I can do that without hassle or trouble. </li>
</ul>
<p>Let me know what you think; I'm looking forward to any and all feedback.</p>
<p>I would like to know ahead of time for I am thinking about adding a second <code>unsigned integer</code> parameter to this function. It would allow the user to choose the index location they want to use for their starting position. This parameter would default to 0.</p>
| [] | [
{
"body": "<ul>\n<li><p>We could use <code>Container::size_type</code> or <code>std::size_t</code> for the <code>increment_by</code> parameter, or (as standard algorithms like <code>std::for_each_n</code> seem to do) make it a template argument and use the same type while incrementing <code>n</code>.</p></li>\n<li><p>The standard library algorithms take iterators rather than containers. You mention allowing users to specify an \"index location they want to use for their starting position\", which would be accomplished by passing an iterator range instead of calling <code>begin</code> and <code>end</code>.</p></li>\n<li><p>I don't think the default <code>increment_by</code> argument value is useful. If we needed a step size of <code>1</code>, we'd call <code>std::for_each</code> or use a range-based for loop.</p></li>\n<li><p><code>std::for_each</code> returns the function object (which can be helpful for something like summing values). We could do the same.</p></li>\n<li><p>Follow the standard library conventions with naming template arguments (e.g. name the minimum required iterator type, make it clear that the function is a unary function).</p></li>\n</ul>\n\n<hr>\n\n<p>Modified version:</p>\n\n<pre><code>template<class InputIt, class Size, class UnaryFunction>\nUnaryFunction for_each_by_n(InputIt begin, InputIt end, Size step, UnaryFunction f) {\n\n if (step == 0)\n return f;\n\n while (begin != end)\n {\n f(*begin);\n\n for (Size n = 0; n != step; ++n)\n {\n if (begin == end)\n return f;\n\n ++begin;\n }\n }\n\n return f;\n}\n</code></pre>\n\n<p>(edit: removed unnecessary <code>std::move</code> per Juho's comment).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T18:18:51.483",
"Id": "414315",
"Score": "1",
"body": "[It seems like it's a better idea to just return by-copy instead of move](https://stackoverflow.com/questions/32844948/stdmove-and-rvo-optimizations/32845247#32845247); i.e., you gain by nothing by doing it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T18:29:42.770",
"Id": "414317",
"Score": "0",
"body": "@Juho I did vaguely wonder about that. The `std::for_each` reference that I was looking at explicitly mentions `std::move(f)` for the return value, which is kinda weird: https://en.cppreference.com/w/cpp/algorithm/for_each"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T18:32:43.977",
"Id": "414319",
"Score": "1",
"body": "I see, interesting. Then again the \"possible implementation\" again does not use the move."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T18:34:21.573",
"Id": "414320",
"Score": "1",
"body": "Yep. Looks like it's just an odd quirk: https://stackoverflow.com/questions/43163801/why-does-for-each-return-function-by-move"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T18:47:10.047",
"Id": "414323",
"Score": "0",
"body": "The fact that `f` is a parameter of the function, rather than a local variable, adds extra complication here. I'm no longer sure what's correct (reading that answer is certainly useful; making the parameter accept a *forwarding reference* may make a difference, too."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T09:51:00.290",
"Id": "214229",
"ParentId": "214227",
"Score": "5"
}
},
{
"body": "<p>A minor tweak might be to test for <code>end_it</code> within the <em>condition</em> expression of the <code>for</code>:</p>\n\n<pre><code> for (unsigned n = 0; n < increment_by && it != end_it; ++n) {\n ++it;\n }\n</code></pre>\n\n<p>Incorporated into <a href=\"/a/214229\">user673679's version</a>, that becomes (untested):</p>\n\n<pre><code>template<class InputIt, class Size, class UnaryFunction>\nUnaryFunction for_each_by_n(InputIt begin, InputIt end, Size step,\n UnaryFunction&& f)\n{\n if (step > 0) { \n while (begin != end) {\n f(*begin);\n\n for (Size n = 0u; n != step && begin != end; ++n) {\n ++begin;\n }\n }\n }\n\n return f;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T16:10:05.150",
"Id": "214253",
"ParentId": "214227",
"Score": "3"
}
},
{
"body": "<p>Well, there is one thing you should consider, as you aim for genericity and composability:<br>\nDoing things the other way around.</p>\n\n<p>Rather than writing a <code>for_each_by_n()</code> (which would be better named <code>for_each_stride()</code>), use <code>std::for_each()</code> respectively the for-range-loop, and appropriate views to adapt the range.</p>\n\n<p>As an example, with <a href=\"https://ericniebler.github.io/range-v3/index.html\" rel=\"nofollow noreferrer\">range-v3</a>, you would use the view:</p>\n\n<pre><code>auto view = view::stride(container, n);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T22:13:16.620",
"Id": "214277",
"ParentId": "214227",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T08:30:34.640",
"Id": "214227",
"Score": "4",
"Tags": [
"c++",
"iterator",
"collections",
"c++17"
],
"Title": "My implementation of a for_each function that traverses a std::container by some step size integer N"
} | 214227 |
<p>I have following Python code:</p>
<pre class="lang-py prettyprint-override"><code>def get_subject_from_stream_id_and_subject_id(stream_id, subject_id):
#(stream_id, subject_id): ("subject_name")
return {
(1, 1): "Accounts",
(1, 2): "English",
(1, 3): "Organization of Commerce",
(2, 1): "Physics",
(2, 2): "English",
(2, 3): "Biology"
}.get((stream_id, subject_id), "None")
</code></pre>
<p>In this code, I want to get subject name from the integer pair combination i.e. <code>stream_id</code>, <code>subject_id</code> e.g. <code>(1, 2)</code> is for <code>English</code>. It was implemented using a Python tuple.</p>
<p>I want to implement the same piece of code in Java.</p>
<p>Could someone write this in a better way in Java? </p>
<pre><code>public String getSubjectFromStreamIdAndSubjectId(int streamId, int subjectId) {
switch (streamId) {
case 1:
switch (subjectId) {
case 1:
return "Accounts";
case 2:
return "English";
case 3:
return "Organization of Commerce";
default:
return null;
}
case 2:
switch (subjectId) {
case 1:
return "Physics";
case 2:
return "English";
case 3:
return "Biology";
default:
return null;
}
default:
return null;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T12:07:05.950",
"Id": "414267",
"Score": "0",
"body": "That doesn't look like syntactically valid Java code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T12:31:10.093",
"Id": "414270",
"Score": "0",
"body": "It's lacking method parameter types. Otherwise it compiles just great."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T13:18:40.577",
"Id": "414278",
"Score": "0",
"body": "@200_success I updated it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T20:47:43.680",
"Id": "414340",
"Score": "0",
"body": "This looks like a fairly simple 2D array lookup. Just subtract 1 from the indices, and check they're in bounds. Any solution involving a dictionary is inefficient - both in terms of performance and code complexity."
}
] | [
{
"body": "<p>Neither is good, but surely we can all agree that the Java example is way uglier. The biggest problem, however, is that both examples hard code data into code.</p>\n\n<p>Separate data, i.e. stream and subject IDs and their titles into a data class and in that class implement code that accesses the data structure without detailed knowledge about the actual data. Responsibility of setting up the data structure to resemble your stream and subject numbering is left to a separate component (load it from file or set up in static code).</p>\n\n<p>Whether the data class is a recursive structure or just a wrapper for a <code>HashMap</code> depends on the complexity of your data.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T12:50:55.140",
"Id": "214238",
"ParentId": "214234",
"Score": "4"
}
},
{
"body": "<p>Java equivalent of the above Python code goes more like this:</p>\n\n<pre><code>private static final Map<List<Integer>, String> SUBJECT_MAP = createSubjectMap();\n\nprivate static Map<List<Integer>, String> createSubjectMap() {\n Map<List<Integer>, String> map = new HashMap<>();\n map.put(asList(1, 1), \"Accounts\");\n map.put(asList(1, 2), \"English\");\n map.put(asList(1, 3), \"Organization of Commerce\");\n map.put(asList(2, 1), \"Physics\");\n map.put(asList(2, 2), \"English\");\n map.put(asList(2, 3), \"Biology\");\n return map;\n}\n\npublic static String getSubjectFromStreamIdAndSubjectId(int streamId, int subjectId) {\n return SUBJECT_MAP.get(asList(streamId, subjectId));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T16:21:35.183",
"Id": "414300",
"Score": "1",
"body": "Might be better to use a custom `SubjectIdentifier` class since a `List` seems rather inefficient."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T06:54:39.073",
"Id": "414375",
"Score": "0",
"body": "@rath I don't know about efficiency, but it would certainly be more idiomatic java. OP seems to be new to java, and I wanted to show him that `List`s support equals and hashcode thus can be used as keys in maps and sets."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T08:14:26.100",
"Id": "414384",
"Score": "0",
"body": "Why not just concatenate the integers into a String? map.put(\"1.1\", \"Accounts\") ... map.get(streamId + \".\" + subjectId)? I'm aware it's not Pure OOP, but it's \"only an internal data structure.\""
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T15:06:09.110",
"Id": "214249",
"ParentId": "214234",
"Score": "4"
}
},
{
"body": "<p>When something is difficult in Java it's nearly always because there is a better way to do it (in Java, it generally means you are missing a class). In your case, it looks like you need a \"Subject\" class.</p>\n\n<p>Let's say you had a \"Subject\" class, how would it be implemented? Here's one way (Not my favorite)</p>\n\n<pre><code>enum Subject {\n Accounts(1,1),\n English(1,2),\n …;\n public static Subject getSubject(streamId, subjectId) {\n // Iterate over Subject.values and return one that matches\n }\n</code></pre>\n\n<p>This means that your call becomes simple:</p>\n\n<pre><code>assertEquals(Subjects.Accounts, Subject.getSubject(1,1));\n</code></pre>\n\n<p>I don't completely love this because it's still hard-coded. I would personally make the Subjects class a full class and load it from either a database or a data file, but it should still have a getSubject() static. </p>\n\n<p>Just in case you think there is some kind of performance issue caused by looping instead of a switch, note that A) java is 10x faster than python to start and B) premature optimization is the root of all evil (well, lots of evil)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T18:32:43.200",
"Id": "214262",
"ParentId": "214234",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T11:52:32.593",
"Id": "214234",
"Score": "5",
"Tags": [
"java"
],
"Title": "Switch case implementation in Java for an integer pair combination"
} | 214234 |
<p>I am new to programming and I am trying to solve the 8-puzzle using brute force algorithm. The code works for very simple puzzle configuration but freaks out when the even a modest puzzle is input to it.
Initially I was working with a format for board as:</p>
<pre><code>[['1','2','3'],['4','5','6'],['7','0','8']]
</code></pre>
<p>But after some suggestions, I changed it to <code>'123456708'</code></p>
<p>Description of 8-Puzzle Problem: The 15-puzzle (also called Gem Puzzle, Boss Puzzle, Game of Fifteen, Mystic Square and many others) is a sliding puzzle that consists of a frame of numbered square tiles in random order with one tile missing. The puzzle also exists in other sizes, particularly the smaller 8-puzzle. Missing tile space is moved to form a regular pattern such 12345678_, where '_' denotes the missing tile[Wikipedia]</p>
<p><a href="https://i.stack.imgur.com/KSOsK.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KSOsK.jpg" alt="A typical 8-puzzle with Initial configuration and goal configuration"></a></p>
<pre><code>import copy
from collections import deque, namedtuple
node_id = 0
class SlidingPuzzle:
def __init__(self, start_board):
self.start_configuration = str(start_board) + '0'
self.goal_configuration = '123456780'
def get_node_id(self, configuration):#configuration: 123405786999 implies Node 999
string_configuration = str(configuration)
string_node_id = string_configuration[9:]
return string_node_id
def get_node_orientation(self, configuration):
string_configuration = str(configuration)
string_orientation = string_configuration[:9]
return string_orientation
def display_board(self, configuration, arg='new'):
if arg == 'new':
old_configuration = self._get_old_configuration(configuration)
elif arg == 'old':
old_configuration = configuration
# displays the board's configuration.
print("\n")
for row in old_configuration:
print(row)
print("\n")
return
def _get_old_configuration(self, new_configuration):
# @new_configuration: 123045678101; 101 is a number
# returns old_configuration : [['1', '2', '3'], ['0', '4', '5'], ['6', '7', '8']]
string_new_configuration = str(new_configuration)
old_configuration = []
for x in range(0,3):
row_list = []
for element in string_new_configuration[3*x : 3*(x+1)]:
row_list.append(element)
old_configuration.append(row_list)
return old_configuration
def _get_new_configuration(self, old_configuration):
# @old_configuration : [['1', '2', '3'], ['0', '4', '5'], ['6', '7', '8']]
# returns new_configuration: 123045678node_id; node_id is a number
global node_id # Made it Global because everytime its called means we are creating a new_node
node_id +=1
new_configuration = ''
for row in old_configuration:
for each_element in row:
new_configuration += each_element
string_node_id = node_id
string_node_id = str(string_node_id)
new_configuration += string_node_id
return new_configuration
def slider(self, configuration):
configuration = str(configuration)
config = self._get_old_configuration(configuration[:9])
position = [ (row, column.index("0")) for row, column in enumerate(config) if '0' in column ]
return position
def move_up(self, configuration):# The configuration passed to it is the new configuration
# Moves the slider up if it is possible, otherwise returns false.
slider_position = self.slider(configuration) # We need to have updated slider position everytime.
dummy_board = self._get_old_configuration(configuration)
if slider_position[0][0] == 0:# when slider is in first row
print ("\nError: Slider can't move above from current position \n")
return False
else:
(i,j) = slider_position[0]
element = dummy_board[i-1][j]
dummy_board[i-1][j] = '0'
dummy_board[i][j] = element
dummy_board = self._get_new_configuration(dummy_board)
return dummy_board
def move_down(self, configuration):
# Moves the slider down if it is possible, otherwise returns false.
slider_position = self.slider(configuration) # We need to have updated slider position everytime.
dummy_board = self._get_old_configuration(configuration)
if slider_position[0][0] == 2:# when slider is in third row
print ("\nError: Slider can't move down from current position \n")
return False
else:
(i,j) = slider_position[0]
element = dummy_board[i+1][j]
dummy_board[i+1][j] = '0'
dummy_board[i][j] = element
dummy_board = self._get_new_configuration(dummy_board)
return dummy_board
def move_right(self, configuration):
# Moves the slider right if it is possible, otherwise returns false.
slider_position = self.slider(configuration) # We need to have updated slider position everytime.
dummy_board = self._get_old_configuration(configuration)
if slider_position[0][1] == 2: # When slider is in third column
print(slider_position)
print ("\nError: Slider can't move right from current position \n")
print('current_configuration being sent to move_right(): ', configuration)
return False
else:
(i,j) = slider_position[0]
element = dummy_board[i][j+1]
dummy_board[i][j+1] = '0'
dummy_board[i][j] = element
dummy_board = self._get_new_configuration(dummy_board)
return dummy_board
def move_left(self, configuration):
# Moves the slider up if it is possible, otherwise returns false.
slider_position = self.slider(configuration) # We need to have updated slider position everytime.
dummy_board = self._get_old_configuration(configuration)
if slider_position[0][1] == 0: # When slider is in first column
print ("\nError: Slider can't move left from current position \n")
return False
else:
(i,j) = slider_position[0]
element = dummy_board[i-1][j]
dummy_board[i][j-1] = '0'
dummy_board[i][j] = element
dummy_board = self._get_new_configuration(dummy_board)
return dummy_board
def valid_moves(self, configuration):
# @board_orientation format: [['1', '2', '3'], ['0', '4', '5'], ['6', '7', '8']]
# returns valid moves in a list form: ['up', 'down', 'right', 'left']
valid_moves_list = ['up', 'down', 'right', 'left']
board_orientation = self._get_old_configuration(configuration)
[(i, j)] = [ (row, column.index('0')) for row, column in enumerate(board_orientation) if '0' in column ]
if i+1 == 3:
valid_moves_list.remove('down')
if i-1 == -1:
valid_moves_list.remove('up')
if j+1 == 3:
valid_moves_list.remove('right')
if j-1 == -1:
valid_moves_list.remove('left')
return valid_moves_list
def does_solution_exist(self, configuration):
string_config = str(configuration)
temp_list = []
for number in string_config[:9]:
if number != '0':
temp_list.append(int(number))
inversions = 0
for i in range(0,8):
for j in range(i,8):
if temp_list[i] > temp_list[j]:
inversions += 1
return bool(inversions%2 == 0)
# Brute Force Algorithm
def breadth_first_search(self):
start = self.start_configuration
print ('Original Board: ')
self.display_board(start)
nodes_to_be_visited = deque()
nodes_to_be_visited.append(self.get_node_id(start))
visited_nodes = []
node_dictionary = {'0':self.get_node_orientation(start)}
parent_children_dictionary = []# Will update this next time
# Does solution Exists?
if self.does_solution_exist(start) < 1:
print("No Solution exists")
return False
else:
print ('Solution Exists for this Puzzle Configuration\n')
found = False
while (nodes_to_be_visited) and (found == False) > 0:# While queue is not empty
current_node = nodes_to_be_visited.pop()# Pop the queue to get node id
current_configuration = node_dictionary.get(current_node)# Fetch its configuration from the dictionary
# if current visit is our goal configuration:
if current_configuration == self.goal_configuration:
print ("\nWe found the solution: \n")
self.display_board(current_configuration)
break
# If current visit is not the goal configuration
if current_configuration != self.goal_configuration:
# And if it is the first time we are visiting the ndoe... Let's register its children
if current_node not in visited_nodes:
visited_nodes.append(current_node)
possible_moves = self.valid_moves(current_configuration)
for move in possible_moves:
# If moving left is allowed
if move == 'left':
configuration = self.move_left(current_configuration)
node_id_local = self.get_node_id(configuration)
node_configuration_local = self.get_node_orientation(configuration)
node_dictionary[node_id_local] = node_configuration_local
nodes_to_be_visited.append(node_id_local)
if node_configuration_local == self.goal_configuration:
print ("\nWe found the solution: \n")
self.display_board(node_configuration_local)
found = True
break
elif move == 'right':
configuration = self.move_right(current_configuration)
node_id_local = self.get_node_id(configuration)
node_configuration_local = self.get_node_orientation(configuration)
node_dictionary[node_id_local] = node_configuration_local
nodes_to_be_visited.append(node_id_local)
if node_configuration_local == self.goal_configuration:
print ("\nWe found the solution: \n")
self.display_board(node_configuration_local)
found = True
break
elif move == 'up':
configuration = self.move_up(current_configuration)
node_id_local = self.get_node_id(configuration)
node_configuration_local = self.get_node_orientation(configuration)
node_dictionary[node_id_local] = node_configuration_local
nodes_to_be_visited.append(node_id_local)
if node_configuration_local == self.goal_configuration:
print ("\nWe found the solution: \n")
self.display_board(node_configuration_local)
found = True
break
elif move == 'down':
configuration = self.move_down(current_configuration)
node_id_local = self.get_node_id(configuration)
node_configuration_local = self.get_node_orientation(configuration)
node_dictionary[node_id_local] = node_configuration_local
nodes_to_be_visited.append(node_id_local)
if node_configuration_local == self.goal_configuration:
print ("\nWe found the solution: \n")
self.display_board(node_configuration_local)
found = True
break
# Helper Code
access = SlidingPuzzle('123405786')
access.breadth_first_search()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T15:40:38.520",
"Id": "414296",
"Score": "0",
"body": "This looks interesting, Can you add some information regarding what is 8-puzzle?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T16:04:22.900",
"Id": "414299",
"Score": "0",
"body": "@422_unprocessable_entity The 15-puzzle (also called Gem Puzzle, Boss Puzzle, Game of Fifteen, Mystic Square and many others) is a sliding puzzle that consists of a frame of numbered square tiles in random order with one tile missing. The puzzle also exists in other sizes, particularly the smaller 8-puzzle. Missing tile space is moved to form a regular pattern such 12345678_, where '_' denotes the missing tile[Wikipedia]"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T16:25:22.533",
"Id": "414301",
"Score": "0",
"body": "I will agree with \n@422_unprocessable_entity that the questions should be self contained as much as possible and adding a little description in the post itself would be a plus. How about adding [this](https://www.8puzzle.com/images/8%5Fpuzzle%5Fstart%5Fstate%5Fa.png) image."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T11:41:29.600",
"Id": "414405",
"Score": "0",
"body": "@SarveshThakur could you please add comment `The 15-puzzle ....` to question description as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-02T05:44:22.660",
"Id": "477405",
"Score": "0",
"body": "This is a very inefficient 8-puzzle solver. (I have timed it using various configurations.) I believe because BFS algo is used, instead of A* search, which is the standard for 8-puzzle solvers. What is good and original although in this code is the check about its solvability at start. (BTW, don't use `print('\\n')`: it adds an extra, redundant empty line. Use just `print()`.)"
}
] | [
{
"body": "<p>Initial thoughts:</p>\n\n<ol>\n<li><p>Why optimize your code when there are 362 880 possibilities, the best way to optimize is to reduce the number of possibilities. The complexity here is <strong>O(n²!)</strong> meaning that it quickly becomes impossible to compute (4x4 is 20 trillions possibilities and 15 septillions for a 5 by 5).</p></li>\n<li><p>I would argue against using strings in this case because they are immutable, meaning that you need to create new instances all the time. (numpy array ?)</p></li>\n<li><p>The last 50 lines or so feel highly repetitive (as well as the <code>move_xxxx()</code>) and could be improved</p></li>\n</ol>\n\n<pre><code>import sys\nimport itertools\nimport copy\nfrom collections import deque, namedtuple\n\nnode_id = 0\n\n# Wheel to make sure the program is running\n# Yes this function is ugly but hey, that's just a spinning wheel\ndef spin(wheel=itertools.cycle(['–', '/', '|', '\\\\']), rate=1000, spin_count=[0]):\n if not spin_count[0]%rate:\n sys.stdout.write(next(wheel)) # write the next character\n sys.stdout.flush() # flush stdout buffer (actual character display)\n sys.stdout.write('\\b') # erase the last written char\n spin_count[0] += 1\n\n\nclass SlidingPuzzle:\n\n directions = {\n 'up': (-1, 0),\n 'down': (1, 0),\n 'left': (0, -1),\n 'right': (0, 1)\n }\n\n def __init__(self, start_board):\n self.start_configuration = str(start_board) + '0'\n self.goal_configuration = '123456780'\n\n def get_node_id(self, configuration): # configuration: 123405786999 implies Node 999\n string_configuration = str(configuration)\n string_node_id = string_configuration[9:]\n return string_node_id\n\n def get_node_orientation(self, configuration):\n string_configuration = str(configuration)\n string_orientation = string_configuration[:9]\n return string_orientation\n\n def display_board(self, configuration, arg='new'):\n if arg == 'new':\n old_configuration = self._get_old_configuration(configuration)\n elif arg == 'old':\n old_configuration = configuration\n # displays the board's configuration.\n print(\"\\n\")\n for row in old_configuration:\n print(row)\n print(\"\\n\")\n return\n\n def _get_old_configuration(self, new_configuration):\n # @new_configuration: 123045678101; 101 is a number\n # returns old_configuration : [['1', '2', '3'], ['0', '4', '5'], ['6', '7', '8']]\n string_new_configuration = str(new_configuration)\n old_configuration = []\n for x in range(0, 3):\n row_list = []\n for element in string_new_configuration[3*x: 3*(x+1)]:\n row_list.append(element)\n old_configuration.append(row_list)\n return old_configuration\n\n def _get_new_configuration(self, old_configuration):\n # @old_configuration : [['1', '2', '3'], ['0', '4', '5'], ['6', '7', '8']]\n # returns new_configuration: 123045678node_id; node_id is a number\n global node_id # Made it Global because everytime its called means we are creating a new_node\n node_id += 1\n new_configuration = ''\n for row in old_configuration:\n for each_element in row:\n new_configuration += each_element\n string_node_id = node_id\n string_node_id = str(string_node_id)\n\n new_configuration += string_node_id\n return new_configuration\n\n def slider(self, configuration):\n configuration = str(configuration)\n config = self._get_old_configuration(configuration[:9])\n position = [(row, column.index(\"0\"))\n for row, column in enumerate(config) if '0' in column]\n return position\n\n def move(self, configuration, direction):\n # The configuration passed to it is the new configuration\n # Moves the slider up if it is possible, otherwise returns false.\n # We need to have updated slider position everytime.\n slider_position = self.slider(configuration)\n dummy_board = self._get_old_configuration(configuration)\n i, j = slider_position[0]\n di, dj = SlidingPuzzle.directions[direction]\n try:\n element = dummy_board[i+di][j+dj]\n except IndexError:\n raise ValueError(f\"Impossible to move '{direction}'\")\n dummy_board[i+di][j+dj] = '0'\n dummy_board[i][j] = element\n dummy_board = self._get_new_configuration(dummy_board)\n return dummy_board\n\n def valid_moves(self, configuration):\n # @board_orientation format: [['1', '2', '3'], ['0', '4', '5'], ['6', '7', '8']]\n # returns valid moves in a list form: ['up', 'down', 'right', 'left']\n\n valid_moves_list = ['up', 'down', 'right', 'left']\n board_orientation = self._get_old_configuration(configuration)\n [(i, j)] = [(row, column.index('0'))\n for row, column in enumerate(board_orientation) if '0' in column]\n if i+1 == 3:\n valid_moves_list.remove('down')\n if i-1 == -1:\n valid_moves_list.remove('up')\n if j+1 == 3:\n valid_moves_list.remove('right')\n if j-1 == -1:\n valid_moves_list.remove('left')\n\n return valid_moves_list\n\n def does_solution_exist(self, configuration):\n string_config = str(configuration)\n temp_list = []\n for number in string_config[:9]:\n if number != '0':\n temp_list.append(int(number))\n\n inversions = 0\n for i in range(0, 8):\n for j in range(i, 8):\n if temp_list[i] > temp_list[j]:\n inversions += 1\n return bool(inversions % 2 == 0)\n\n # Brute Force Algorithm\n\n def breadth_first_search(self):\n\n start = self.start_configuration\n print('Original Board: ')\n self.display_board(start)\n\n nodes_to_be_visited = deque()\n nodes_to_be_visited.append(self.get_node_id(start))\n visited_nodes = []\n node_dictionary = {'0': self.get_node_orientation(start)}\n\n # Does solution Exists?\n if self.does_solution_exist(start) < 1:\n print(\"No Solution exists\")\n return False\n\n else:\n print('Solution Exists for this Puzzle Configuration\\n')\n\n found = False\n while (nodes_to_be_visited) and not found: # While queue is not empty\n current_node = nodes_to_be_visited.pop() # Pop the queue to get node id\n # Fetch its configuration from the dictionary\n current_configuration = node_dictionary.get(current_node)\n\n # if current visit is our goal configuration:\n if current_configuration == self.goal_configuration:\n print(\"\\nWe found the solution: \\n\")\n self.display_board(current_configuration)\n break\n\n # If current visit is not the goal configuration\n if current_configuration != self.goal_configuration:\n\n # And if it is the first time we are visiting the ndoe... Let's register its children\n if current_node not in visited_nodes:\n visited_nodes.append(current_node)\n possible_moves = self.valid_moves(\n current_configuration)\n\n for move in possible_moves:\n configuration = self.move(\n current_configuration, move)\n node_id_local = self.get_node_id(configuration)\n node_configuration_local = self.get_node_orientation(\n configuration)\n node_dictionary[node_id_local] = node_configuration_local\n nodes_to_be_visited.append(node_id_local)\n if node_configuration_local == self.goal_configuration:\n print(\"\\nWe found the solution: \\n\")\n self.display_board(\n node_configuration_local)\n found = True\n break\n spin() # Just to make sure it is still running\n# Helper Code\n\n\naccess = SlidingPuzzle('123405786')\naccess.breadth_first_search()\n\n</code></pre>\n\n<p>Here is what I have changed (<kbd>></kbd> means added, <kbd><</kbd> means deleted):</p>\n\n<pre><code>0a1,2\n> import sys\n> import itertools\n5a8,16\n> # Wheel to make sure the program is running\n> # Yes this function is ugly but hey, that's just a spinning wheel\n> def spin(wheel=itertools.cycle(['–', '/', '|', '\\\\']), rate=1000, spin_count=[0]):\n> if not spin_count[0]%rate:\n> sys.stdout.write(next(wheel)) # write the next character\n> sys.stdout.flush() # flush stdout buffer (actual character display)\n> sys.stdout.write('\\b') # erase the last written char\n> spin_count[0] += 1\n> \n8a20,26\n> directions = {\n> 'up': (-1, 0),\n> 'down': (1, 0),\n> 'left': (0, -1),\n> 'right': (0, 1)\n> }\n> \n69c87,88\n< def move_up(self, configuration): # The configuration passed to it is the new configuration\n---\n> def move(self, configuration, direction):\n> # The configuration passed to it is the new configuration\n74,131c93,100\n< if slider_position[0][0] == 0: # when slider is in first row\n< print(\"\\nError: Slider can't move above from current position \\n\")\n< return False\n< else:\n< (i, j) = slider_position[0]\n< element = dummy_board[i-1][j]\n< dummy_board[i-1][j] = '0'\n< dummy_board[i][j] = element\n< dummy_board = self._get_new_configuration(dummy_board)\n< return dummy_board\n< \n< def move_down(self, configuration):\n< # Moves the slider down if it is possible, otherwise returns false.\n< # We need to have updated slider position everytime.\n< slider_position = self.slider(configuration)\n< dummy_board = self._get_old_configuration(configuration)\n< if slider_position[0][0] == 2: # when slider is in third row\n< print(\"\\nError: Slider can't move down from current position \\n\")\n< return False\n< else:\n< (i, j) = slider_position[0]\n< element = dummy_board[i+1][j]\n< dummy_board[i+1][j] = '0'\n< dummy_board[i][j] = element\n< dummy_board = self._get_new_configuration(dummy_board)\n< return dummy_board\n< \n< def move_right(self, configuration):\n< # Moves the slider right if it is possible, otherwise returns false.\n< # We need to have updated slider position everytime.\n< slider_position = self.slider(configuration)\n< dummy_board = self._get_old_configuration(configuration)\n< if slider_position[0][1] == 2: # When slider is in third column\n< print(slider_position)\n< print(\"\\nError: Slider can't move right from current position \\n\")\n< print('current_configuration being sent to move_right(): ', configuration)\n< return False\n< else:\n< (i, j) = slider_position[0]\n< element = dummy_board[i][j+1]\n< dummy_board[i][j+1] = '0'\n< dummy_board[i][j] = element\n< dummy_board = self._get_new_configuration(dummy_board)\n< return dummy_board\n< \n< def move_left(self, configuration):\n< # Moves the slider up if it is possible, otherwise returns false.\n< # We need to have updated slider position everytime.\n< slider_position = self.slider(configuration)\n< dummy_board = self._get_old_configuration(configuration)\n< if slider_position[0][1] == 0: # When slider is in first column\n< print(\"\\nError: Slider can't move left from current position \\n\")\n< return False\n< else:\n< (i, j) = slider_position[0]\n< element = dummy_board[i-1][j]\n< dummy_board[i][j-1] = '0'\n< dummy_board[i][j] = element\n---\n> i, j = slider_position[0]\n> di, dj = SlidingPuzzle.directions[direction]\n> try:\n> element = dummy_board[i+di][j+dj]\n> except IndexError:\n> raise ValueError(f\"Impossible to move '{direction}'\")\n> dummy_board[i+di][j+dj] = '0'\n> dummy_board[i][j] = element\n180d148\n< parent_children_dictionary = [] # Will update this next time\n191c159\n< while (nodes_to_be_visited) and (found == False) > 0: # While queue is not empty\n---\n> while (nodes_to_be_visited) and not found: # While queue is not empty\n212,271c180,193\n< # If moving left is allowed\n< if move == 'left':\n< configuration = self.move_left(\n< current_configuration)\n< node_id_local = self.get_node_id(configuration)\n< node_configuration_local = self.get_node_orientation(\n< configuration)\n< node_dictionary[node_id_local] = node_configuration_local\n< nodes_to_be_visited.append(node_id_local)\n< if node_configuration_local == self.goal_configuration:\n< print(\"\\nWe found the solution: \\n\")\n< self.display_board(\n< node_configuration_local)\n< found = True\n< break\n< \n< elif move == 'right':\n< configuration = self.move_right(\n< current_configuration)\n< node_id_local = self.get_node_id(configuration)\n< node_configuration_local = self.get_node_orientation(\n< configuration)\n< node_dictionary[node_id_local] = node_configuration_local\n< nodes_to_be_visited.append(node_id_local)\n< if node_configuration_local == self.goal_configuration:\n< print(\"\\nWe found the solution: \\n\")\n< self.display_board(\n< node_configuration_local)\n< found = True\n< break\n< \n< elif move == 'up':\n< configuration = self.move_up(\n< current_configuration)\n< node_id_local = self.get_node_id(configuration)\n< node_configuration_local = self.get_node_orientation(\n< configuration)\n< node_dictionary[node_id_local] = node_configuration_local\n< nodes_to_be_visited.append(node_id_local)\n< if node_configuration_local == self.goal_configuration:\n< print(\"\\nWe found the solution: \\n\")\n< self.display_board(\n< node_configuration_local)\n< found = True\n< break\n< \n< elif move == 'down':\n< configuration = self.move_down(\n< current_configuration)\n< node_id_local = self.get_node_id(configuration)\n< node_configuration_local = self.get_node_orientation(\n< configuration)\n< node_dictionary[node_id_local] = node_configuration_local\n< nodes_to_be_visited.append(node_id_local)\n< if node_configuration_local == self.goal_configuration:\n< print(\"\\nWe found the solution: \\n\")\n< self.display_board(\n< node_configuration_local)\n< found = True\n< break\n---\n> configuration = self.move(\n> current_configuration, move)\n> node_id_local = self.get_node_id(configuration)\n> node_configuration_local = self.get_node_orientation(\n> configuration)\n> node_dictionary[node_id_local] = node_configuration_local\n> nodes_to_be_visited.append(node_id_local)\n> if node_configuration_local == self.goal_configuration:\n> print(\"\\nWe found the solution: \\n\")\n> self.display_board(\n> node_configuration_local)\n> found = True\n> break\n> spin() # Just to make sure it is still running\n</code></pre>\n\n<p>I will read your code more in depth and update this answer.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T14:29:36.133",
"Id": "214246",
"ParentId": "214239",
"Score": "5"
}
},
{
"body": "<p>Here are a couple of points:</p>\n\n<ol>\n<li><p>You need to move your documentation and your comments into docstrings:</p>\n\n<pre><code>class SlidingPuzzle:\n\n def __init__(self, start_board):\n self.start_configuration = str(start_board) + '0'\n self.goal_configuration = '123456780'\n</code></pre>\n\n<p>becomes:</p>\n\n<pre><code>class SlidingPuzzle:\n \"\"\" The 15-puzzle (also called Gem Puzzle, Boss Puzzle, \n Game of Fifteen, Mystic Square and many others) is \n a sliding puzzle that consists of a frame of numbered\n square tiles in random order with one tile missing. \n The puzzle also exists in other sizes, particularly\n the smaller 8-puzzle. \n \"\"\" \n def __init__(self, start_board):\n \"\"\" Construct a new puzzle from a starting configuration.\n The starting configuration is a string containing all\n the numbers from 1..8, plus 0 or underscore ('_') \n where the empty cell should be. The numbers are \n considered to be in order from top to bottom, left to\n right, so that \"1234_5678\" represents a puzzle like:\n\n 1 2 3\n 4 _ 5\n 6 7 8\n \"\"\"\n self.start_configuration = str(start_board) + '0'\n self.goal_configuration = '123456780'\n</code></pre></li>\n<li><p>Validate your parameters during the <code>__init__</code> call so you won't have to do it again! Check that the right digits, underscore, spaces, etc. are present or deleted or whatever. Make sure nothing is duplicated.</p></li>\n<li><p>You waste a lot of time converting from \"string\" to \"square\" format. Just stop doing that and re-write your code in string terms always.</p>\n\n<pre><code>def slider(self, configuration):\n ...\n config = self._get_old_configuration(configuration[:9])\n ...\n\ndef move_up(self, configuration):\n slider_position = self.slider(configuration) # We need to have updated slider position everytime.\n dummy_board = self._get_old_configuration(configuration)\n</code></pre>\n\n<p>Notice that your <code>move_up</code> called <code>slider</code> (which called <code>_get_old_configuration</code>) and then <code>move_up</code> <em>called <code>_get_old_configuration</code> itself!</em> You just called the function, threw away the result, and called the function again.</p>\n\n<p>What is worse, <code>slider</code> builds a matrix that never gets used. You only use the current position of the slider to check whether you can move up or not.</p>\n\n<p>Think about your board as a string: \"123456789\". The first three values are the top row. The last three values are the bottom row. Now think about the left and right columns: you can just compute an index into the string and use <code>index % 3</code> to determine what column a character is in: <code>index % 3 == 0</code> means left column. <code>== 2</code> means right column.</p>\n\n<p>So knowing the index of the slider (which there's <code>str.index</code> for that) lets you know the row or column as well. Rather than call <code>str.index</code> four times, go ahead and build a <code>Sequence[Sequence[Callable]]</code> that contains the methods to be called:</p>\n\n<pre><code>self.slider_index_to_called_methods = (\n # 0: top left\n (self.move_right, self.move_down),\n # 1: top middle\n (self.move_left, self.move_right, self.move_down),\n ...\n # 8: bottom right\n (self.move_up, self.move_left),\n)\n</code></pre>\n\n<p>Now you can look up the methods to try using a single call to <code>str.index()</code>, iterate over them, and not do any checking or decomposition.</p>\n\n<p>Similarly, you know how to \"move\" in string-only format. Just swap the slider position (index) with a character either one away (left/right) or three away (up/down).</p>\n\n<pre><code>def move_up(self, configuration, index):\n new_index = index - 3\n b = configuration.board\n new_b = b[:new_index] + b[index] + b[new_index+1:index] \\\n + b[new_index] + b[index+1:]\n new_configuration = Configuration(new_b)\n return new_configuration\n</code></pre></li>\n<li><p>You waste a lot of time encoding and decoding the <code>node_id</code> from your strings. Just make a separate data object! <code>collections.namedtuple</code> is perfect for this:</p>\n\n<pre><code>Configuration = collections.namedtuple('Configuration', 'board id')\n</code></pre>\n\n<p>You can subclass the new type to provide your own <code>__init__</code> method, and use that to implement the <code>global node_id += 1</code> logic.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-27T18:22:56.137",
"Id": "214409",
"ParentId": "214239",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "214246",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T13:17:44.507",
"Id": "214239",
"Score": "5",
"Tags": [
"python",
"python-3.x",
"sliding-tile-puzzle"
],
"Title": "Optimizing the code for 8-puzzle in Python"
} | 214239 |
<h1>Introduction</h1>
<p>The Radio Data System (RDS) is a digital signal modulated onto a 57 kHz subcarrier of broadcast FM
radio (above the 19 kHz pilot tone and 38 kHz stereo difference channel). The details of the
modulation scheme are unimportant here; we assume that the output of demodulation is a series of 0
or 1 bits corresponding to the transmitted data stream.</p>
<p>(Aside: it could be useful to receive fuzzy inputs rather than immediately thresholding to straight
binary, but let's assume that's out of scope here.)</p>
<p>The bit stream is structured as a sequence of independent <strong>groups</strong> of four <strong>blocks</strong>; each block
comprises 16 data bits and 10 error-correction bits. Blocks within a group are transmitted in
sequence: A, B, C (or C'), D; one of the bits of B indicates whether C or C' follows.</p>
<p>The error correction bits of each block are computed using the generator polynomial</p>
<pre><code>g(x) = x¹⁰ + x⁸ + x⁷ + x⁵ + x⁴ + x³ + 1
</code></pre>
<p>A <strong>checkword</strong> is then XORed with the block; different checkwords allow the five block types to be
distinguished.</p>
<p>The blocks are not completely opaque to us; there are some features of the content that we can use
to improve our performance:</p>
<ul>
<li>Block <strong>A</strong> contains the station's <em>programme identifier</em>, and is normally the same in every group.</li>
<li>Block <strong>B</strong> contains the <em>programme type</em>, which changes only infrequently. It also contains the
<em>group type</em>, which indicates whether it's followed by C or C'.</li>
<li>Block <strong>C'</strong> is a copy of block A, but with a different checkword.</li>
<li>Blocks <strong>C</strong> and <strong>D</strong> contain no useful information at this level of decoding.</li>
</ul>
<h1>Objective</h1>
<p>Given a demodulated RDS stream from a received broadcast, extract the groups and correct (as far as
possible) the errors found therein.</p>
<p>Some desirable features (in priority order, so later goals must not be achieved at the expense of
earlier ones):</p>
<ol>
<li>Extract and correct as much data as possible in challenging reception conditions.</li>
<li>Minimise latency between reception and reporting.</li>
<li>Minimise computational overhead in good conditions.</li>
<li>Readable and maintainable code.</li>
</ol>
<p>One significant non-goal is portability - I'm compiling this with GCC, and lean heavily on its
<code>__int128</code> type and <code>__builtin_popcount()</code> function. Portable alternatives to these may be
helpful, especially to other reviewers, so I'll upvote answers which contribute to that, but
that's not what I'm really looking for in a review.</p>
<h1>Structure</h1>
<p>Since <code>C'</code> doesn't make for good C++ identifiers, I've used the letter <code>K</code> in the code to refer to
any C' block. Where we examine the A blocks from consecutive groups, I use <code>E</code> to identify the
second; this is not to be confused with RDBS E blocks, which are no longer used.</p>
<p>Although I built the low-level facilities using unit tests, I've omitted the tests here, so as not
to create too big a review.</p>
<p>We rely on a table of corrections of the most likely errors (which tend to occur in bursts rather
than independently). Rather than generating this as an initialisation step, we build it at compile
time by compiling and running a program (<code>corrections</code>) which generates C++ input.</p>
<h1>Test program and inputs</h1>
<p>I've provided a test program which reads files as if received by channel-hopping, and reports
summary information of how many blocks could and couldn't be corrected. It reads input files that
encode the received bits in big-endian order into 8-bit bytes; some suitable input files are
available from the <a href="http://rds-surveyor.jacquet.xyz/samples/" rel="noreferrer">RDS Surveyor</a> site (no affiliation to me).</p>
<h1>Concerns</h1>
<p>I'm comfortable with writing constants intrinsic to the RDS protocol as "magic numbers" in the code
(e.g. bit shifts and masks), but there's a few more subjective numbers, such as threshold error
counts that are more objective and could need tweaking. I can't think of good but short names for
them.</p>
<p>Am I on the right track requiring subclassing and overriding users to subclass <code>Synchronizer</code> and
override its virtual methods? It was the only manageable technique before I realised I needed to
bundle the received blocks and their correction counts into the <code>group</code> structure, but perhaps we
just need to give the synchronizer a callable object instead? I do anticipate using e.g. Qt signals
at a higher level of decoding, but wanted to keep the low-level code as plain C++ without external
libraries, to make it usable in any program.</p>
<p>There's a two-state machine in <code>Synchronizer</code>, where incoming bits go to different functions
depending on whether we're synchronized or still looking to identify group boundaries. Is this
reasonable, or would it be clearer to have a big <code>if</code>/<code>else</code> directly in <code>push()</code>?</p>
<hr />
<h3>rdstypes.hh</h3>
<pre><code>#ifndef RDSTYPES_HH
#define RDSTYPES_HH
#include <cstdint>
namespace rds
{
struct block {
std::uint16_t value;
std::uint8_t err_count = 0xff;
bool is_valid = false;
operator std::uint16_t() const { return value; }
};
struct group {
block a, b, c, d;
};
}
#endif /* RDSTYPES_HH */
</code></pre>
<h3>crc.hh</h3>
<pre><code>#ifndef CRC_HH
#define CRC_HH
#include <cstdint>
namespace rds
{
// Figure B.1, page 61
static constexpr std::uint32_t encode(std::uint16_t x)
{
return ((x >> 15) & 1) * 0b10000000000000000001110111
^ ((x >> 14) & 1) * 0b01000000000000001011100111
^ ((x >> 13) & 1) * 0b00100000000000001110101111
^ ((x >> 12) & 1) * 0b00010000000000001100001011
^ ((x >> 11) & 1) * 0b00001000000000001101011001
^ ((x >> 10) & 1) * 0b00000100000000001101110000
^ ((x >> 9) & 1) * 0b00000010000000000110111000
^ ((x >> 8) & 1) * 0b00000001000000000011011100
^ ((x >> 7) & 1) * 0b00000000100000000001101110
^ ((x >> 6) & 1) * 0b00000000010000000000110111
^ ((x >> 5) & 1) * 0b00000000001000001011000111
^ ((x >> 4) & 1) * 0b00000000000100001110111111
^ ((x >> 3) & 1) * 0b00000000000010001100000011
^ ((x >> 2) & 1) * 0b00000000000001001101011101
^ ((x >> 1) & 1) * 0b00000000000000101101110010
^ ((x >> 0) & 1) * 0b00000000000000010110111001;
}
// Figure B.3, page 63
constexpr std::uint16_t syndrome(std::uint32_t y)
{
return ((y >> 25) & 1) * 0b1000000000
^ ((y >> 24) & 1) * 0b0100000000
^ ((y >> 23) & 1) * 0b0010000000
^ ((y >> 22) & 1) * 0b0001000000
^ ((y >> 21) & 1) * 0b0000100000
^ ((y >> 20) & 1) * 0b0000010000
^ ((y >> 19) & 1) * 0b0000001000
^ ((y >> 18) & 1) * 0b0000000100
^ ((y >> 17) & 1) * 0b0000000010
^ ((y >> 16) & 1) * 0b0000000001
^ ((y >> 15) & 1) * 0b1011011100
^ ((y >> 14) & 1) * 0b0101101110
^ ((y >> 13) & 1) * 0b0010110111
^ ((y >> 12) & 1) * 0b1010000111
^ ((y >> 11) & 1) * 0b1110011111
^ ((y >> 10) & 1) * 0b1100010011
^ ((y >> 9) & 1) * 0b1101010101
^ ((y >> 8) & 1) * 0b1101110110
^ ((y >> 7) & 1) * 0b0110111011
^ ((y >> 6) & 1) * 0b1000000001
^ ((y >> 5) & 1) * 0b1111011100
^ ((y >> 4) & 1) * 0b0111101110
^ ((y >> 3) & 1) * 0b0011110111
^ ((y >> 2) & 1) * 0b1010100111
^ ((y >> 1) & 1) * 0b1110001111
^ ((y >> 0) & 1) * 0b1100011011;
}
}
#endif /* CRC_HH */
</code></pre>
<h3>corrections.cc</h3>
<pre><code>// This program is run as part of the build, to generate the table of
// corrections as C++ source, to be compiled into the program.
#include "crc.hh"
#include <array>
#include <cstdint>
#include <iomanip>
#include <iostream>
struct Correction
{
std::uint16_t correction = 0;
unsigned char distance = ~0;
bool correctable = false;
void update(unsigned int c, unsigned int d)
{
if (d > distance)
return; // already have a better correction
else if (d < distance)
distance = d, correction = c, correctable = true;
else if (c != correction)
correctable = false; // detect only
}
};
int main()
{
std::array<Correction, 1024> t;
// Recieved exactly
t[0] = {0, 0, true};
// 1-9 bit burst errors
for (unsigned int dist = 1; dist < 10; ++dist) {
const std::uint32_t first = (1u << (dist-1)) | 1;
const std::uint32_t last = 1u << dist;
for (std::uint32_t i = first; i < last; i+=2) {
for (std::uint32_t j = i; !(j & 1u<<26); j <<=1)
t[rds::syndrome(j)].update(j>>10, dist);
}
}
// two independent 1-2 bit errors
for (unsigned int dist = 9; dist < 24; ++dist) {
for (std::uint32_t j: { ((1<<dist)+1), ((3<<dist)+1), ((1<<dist)+3), ((3<<dist)+3) }) {
for (unsigned shift = 0; dist+shift < 26; ++shift) {
t[rds::syndrome(j<<shift)].update(j<<shift>>10, 1 + __builtin_popcount(j));
}
}
}
std::cout << "// Generated by corrections.cc - edits may be overwritten without notice\n";
for (auto const& item: t) {
std::cout << "{"
<< item.correction << ','
<< 0u + item.distance << ','
<< item.correctable << "},";
}
}
</code></pre>
<h3>synchronizer.hh</h3>
<pre><code>#ifndef SYNCHRONIZER_HH
#define SYNCHRONIZER_HH
#include "rdstypes.hh"
#include <cstdint>
namespace rds {
class Synchronizer
{
// No valid programme identifier has country code 0, so we can use
// zero to indicate initial condition.
std::uint32_t prog_id = 0;
// Initial state needs to not look like 0BCD0
static constexpr unsigned __int128 initial_state = 0xffff;
// 128 bits can store a whole 104-bit group, plus 24 bits of
// adjacent context.
unsigned __int128 state = initial_state;
static auto constexpr max_loss_blocks = 10;
unsigned int bits_until_a = 0;
unsigned int blocks_since_lock = 0;
std::uint32_t last_good_b = 0;
public:
static constexpr std::uint32_t CHECKWORD_A = 0x0fc;
static constexpr std::uint32_t CHECKWORD_B = 0x198;
static constexpr std::uint32_t CHECKWORD_C = 0x168;
static constexpr std::uint32_t CHECKWORD_K = 0x350;
static constexpr std::uint32_t CHECKWORD_D = 0x1b4;
virtual ~Synchronizer() = default;
std::uint16_t pid() const {
return prog_id >> 10;
}
virtual void reset() {
state = initial_state;
prog_id = 0;
perBitAction = &Synchronizer::search_for_lock;
// other members will be set before we enter the locked state
}
void push(bool bit)
{
state <<= 1;
state += bit;
(this->*perBitAction)();
}
protected:
// @return error weight
static rds::block correct(std::uint16_t checkword, std::uint32_t input);
void (Synchronizer::*perBitAction)() = &Synchronizer::search_for_lock;
void search_for_lock();
void confirm_lock();
void lock_found(std::uint16_t pid, unsigned int bits_to_go);
void lock_lost();
virtual void process_group(const rds::group& group);
};
}
#endif /* SYNCHRONIZER_HH */
</code></pre>
<h3>synchronizer.cc</h3>
<pre><code>#include "synchronizer.hh"
#include "crc.hh"
#include <algorithm>
#include <array>
#include <cstdint>
using rds::Synchronizer;
namespace {
struct Correction
{
std::uint16_t correction;
unsigned char distance;
bool correctable;
};
const std::array<Correction, 1024> corrections{{
#include "corrections.table"
}};
template<unsigned char size, typename... T>
static constexpr int hamming_distance(T... v)
{
auto constexpr mask = (std::common_type_t<T...>(1) << size) - 1;
return __builtin_popcount((mask & (... ^ v)));
}
}
// @return error weight
rds::block Synchronizer::correct(std::uint16_t checkword, std::uint32_t input)
{
input ^= checkword;
auto s = syndrome(input);
rds::block b = {static_cast<std::uint16_t>(input >> 10), 0, true};
if (!s) {
// perfect
return b;
}
auto const& entry = corrections[s];
b.value ^= entry.correction;
b.err_count = entry.distance;
b.is_valid = entry.correctable;
return b;
}
void Synchronizer::search_for_lock()
{
constexpr int MAX_ERR = 8;
// Check self-similarity first, with 0.5% false-positive rate, before examining CRCs
if (hamming_distance<26>(CHECKWORD_A, CHECKWORD_K, state, state >> 52) <= 6) {
rds::block a,b,k,d;
int err;
if ((err = (k = correct(CHECKWORD_K, state)).err_count) <= MAX_ERR
&& (err += (a = correct(CHECKWORD_A, state >> 52)).err_count) <= MAX_ERR
&& a.value == k.value
&& (err += (b = correct(CHECKWORD_B, state >> 26)).err_count) <= MAX_ERR)
{
// we matched A.K
lock_found(a.value, 52);
return;
}
if ((err = (a = correct(CHECKWORD_A, state)).err_count) <= MAX_ERR
&& (err += (k = correct(CHECKWORD_K, state >> 52)).err_count) <= MAX_ERR
&& a.value == k.value
&& (err += (d = correct(CHECKWORD_D, state >> 26)).err_count) <= MAX_ERR)
{
// we matched K.A
lock_found(a.value, 0);
return;
}
}
// Have we got a match with A...A? Again, we require >99.5% certainty before checking CRCs.
// Note that we only have 24 bits remaining of the previous A, so fill in from the new one.
if (hamming_distance<24>(state, state >> 104) <= 5) {
rds::block a,b,c,d,e;
int err;
if ((err = (a = correct(CHECKWORD_A, state)).err_count) <= MAX_ERR
&& (err += (e = correct(CHECKWORD_A, ((state >> 104) & 0xffffff) | (state & 0x3000000))).err_count) <= MAX_ERR
&& e.value == a.value
&& (err += (d = correct(CHECKWORD_D, state >> 26)).err_count) <= MAX_ERR
&& (err += (c = correct(CHECKWORD_C, state >> 52)).err_count) <= MAX_ERR
&& (err += (b = correct(CHECKWORD_B, state >> 78)).err_count) <= MAX_ERR)
{
// we matched A...A
lock_found(a.value, 0);
return;
}
}
}
void Synchronizer::confirm_lock()
{
if (--bits_until_a)
return;
bits_until_a = 104;
rds::block a = correct(CHECKWORD_A, state);
rds::block b = correct(CHECKWORD_B, state >> 78);
rds::block c = correct(CHECKWORD_C, state >> 52);
rds::block k = correct(CHECKWORD_K, state >> 52);
rds::block d = correct(CHECKWORD_D, state >> 26);
unsigned ck = std::min(k.err_count, c.err_count);
if ((a.err_count >= 4 || a.value != prog_id>>10) && b.err_count * ck * d.err_count >= 16) {
if (hamming_distance<25>(std::uint32_t(state), prog_id>>1) <= 5) {
// bit slip - need one more bit
bits_until_a = 1;
} else if (hamming_distance<26>(std::uint32_t(state)>>1, prog_id) <= 5) {
// bit slip - miss one bit
bits_until_a = 103;
} else {
lock_lost();
}
return;
}
if (a.err_count == 0 && a.value != prog_id>>10) {
// prog_id has changed
prog_id = CHECKWORD_A ^ encode(a);
}
// reset counter
blocks_since_lock = 0;
if (b.err_count > 8) {
// attempt to recover block 2 using saved PTY and inferred A/B
// AAAABTPPPPPiiiii..........
static constexpr auto pty_mask = 0b00000011111000000000000000;
static constexpr auto ab_mask = 0b00001000000000000000000000;
std::uint32_t block2 =
((~pty_mask & ~ab_mask) & (state >> 78))
| (pty_mask & last_good_b)
| (ab_mask & (c.err_count == k.err_count ? last_good_b : -1 * (c.err_count >= k.err_count)));
auto b2 = correct(CHECKWORD_B, block2);
if (b2.err_count >= b.err_count) {
// couldn't decode the B block, so the rest is useless
return;
}
} else {
last_good_b = state >> 78;
}
process_group({a, b, c, d});
}
void Synchronizer::lock_found(std::uint16_t pid, unsigned int bits_to_go) {
perBitAction = &Synchronizer::confirm_lock;
prog_id = CHECKWORD_A ^ encode(pid);
blocks_since_lock = 0;
bits_until_a = 1 + bits_to_go;
confirm_lock();
}
void Synchronizer::lock_lost() {
if (++blocks_since_lock >= max_loss_blocks)
perBitAction = &Synchronizer::search_for_lock;
}
void Synchronizer::process_group(const rds::group&)
{
// to be overridden
}
</code></pre>
<h3>decode-file.cc</h3>
<pre><code>#include "synchronizer.hh"
#include <fstream>
#include <iostream>
struct TestSynchronizer : rds::Synchronizer
{
// keep track of some statistics
unsigned long bits = 0;
unsigned long good_blocks = 0;
unsigned long corrected_blocks = 0;
unsigned long bad_blocks = 0;
void push(bool bit) {
++bits;
rds::Synchronizer::push(bit);
}
void process_group(const rds::group& group) override
{
for (auto const& block: {group.a, group.b, group.c, group.d}) {
auto& count
= !block.is_valid ? bad_blocks
: block.err_count ? corrected_blocks
: good_blocks;
++count;
}
}
void read_file(const std::string& filename)
{
reset();
bits = good_blocks = corrected_blocks = bad_blocks = 0;
std::ifstream in(filename, std::ifstream::binary);
int c;
while ((c = in.get()) != EOF) {
for (int m = 0x80; m; m >>= 1)
push(c & m);
}
// Summary statistics
std::clog << filename << ": "
<< good_blocks << " good, "
<< corrected_blocks << " corrected, "
<< bad_blocks << " uncorrectable blocks; "
<< bits - 26 * (good_blocks + corrected_blocks + bad_blocks)
<< " undecoded bits"
<< std::endl;
}
};
int main(int, char **argv)
{
TestSynchronizer s;
while (*++argv) {
s.read_file(*argv);
}
}
</code></pre>
<h3>Makefile</h3>
<pre class="lang-make prettyprint-override"><code>CPPFLAGS += -finput-charset=UTF-8
CXX=g++-8
CXXFLAGS += -std=c++2a
CXXFLAGS += -Wall -Wextra -Werror
CXXFLAGS += -march=native -O3 -g
#CXXFLAGS += -march=native -O0 -g
LINK.o := $(LINK.cc)
# House-keeping build targets.
all: decode-file
clean:
$(RM) *.o *.dep
$(RM) corrections.table
tidy:
$(RM) *~
distclean: clean tidy
$(RM) decode-file corrections
%.dep: %.cc
@echo [dep] $<
@$(CXX) -MM $(CPPFLAGS) $< | sed -e 's,\($*\)\.o[ :]*,\1.o $@ : ,g' > $@
# Actions
run-%: %
./$< $(RUN_ARGS)
valgrind-%: %
valgrind -q --leak-check=full ./$< $(RUN_ARGS)
sources := $(wildcard *.cc)
ifeq ($(filter $(MAKECMDGOALS),clean tidy distclean),)
include $(sources:.cc=.dep)
endif
corrections.table: corrections
./$< >$@
synchronizer.o synchronizer.dep: corrections.table
decode-file: decode-file.o
decode-file: synchronizer.o
run-decode-file valgrind-decode-file: RUN_ARGS += *.rds
.PHONY: run-% valgrind-% clean tidy distclean all
.DELETE_ON_ERROR:
</code></pre>
<hr />
<h1>Single-source version</h1>
<p>This may be useful if you want to experiment with the code (in the case of any discrepancies, the multi-file version is authoritative). Compile using <code>g++ -std=c++17 -Wall -Wextra -Werror</code>.</p>
<pre><code>#include <algorithm>
#include <array>
#include <cstdint>
#include <fstream>
#include <iostream>
namespace rds
{
struct block {
std::uint16_t value;
std::uint8_t err_count = 0xff;
bool is_valid = false;
operator std::uint16_t() const { return value; }
};
struct group {
block a, b, c, d;
};
// Figure B.1, page 61
static constexpr std::uint32_t encode(std::uint16_t x)
{
return ((x >> 15) & 1) * 0b10000000000000000001110111
^ ((x >> 14) & 1) * 0b01000000000000001011100111
^ ((x >> 13) & 1) * 0b00100000000000001110101111
^ ((x >> 12) & 1) * 0b00010000000000001100001011
^ ((x >> 11) & 1) * 0b00001000000000001101011001
^ ((x >> 10) & 1) * 0b00000100000000001101110000
^ ((x >> 9) & 1) * 0b00000010000000000110111000
^ ((x >> 8) & 1) * 0b00000001000000000011011100
^ ((x >> 7) & 1) * 0b00000000100000000001101110
^ ((x >> 6) & 1) * 0b00000000010000000000110111
^ ((x >> 5) & 1) * 0b00000000001000001011000111
^ ((x >> 4) & 1) * 0b00000000000100001110111111
^ ((x >> 3) & 1) * 0b00000000000010001100000011
^ ((x >> 2) & 1) * 0b00000000000001001101011101
^ ((x >> 1) & 1) * 0b00000000000000101101110010
^ ((x >> 0) & 1) * 0b00000000000000010110111001;
}
// Figure B.3, page 63
constexpr std::uint16_t syndrome(std::uint32_t y)
{
return ((y >> 25) & 1) * 0b1000000000
^ ((y >> 24) & 1) * 0b0100000000
^ ((y >> 23) & 1) * 0b0010000000
^ ((y >> 22) & 1) * 0b0001000000
^ ((y >> 21) & 1) * 0b0000100000
^ ((y >> 20) & 1) * 0b0000010000
^ ((y >> 19) & 1) * 0b0000001000
^ ((y >> 18) & 1) * 0b0000000100
^ ((y >> 17) & 1) * 0b0000000010
^ ((y >> 16) & 1) * 0b0000000001
^ ((y >> 15) & 1) * 0b1011011100
^ ((y >> 14) & 1) * 0b0101101110
^ ((y >> 13) & 1) * 0b0010110111
^ ((y >> 12) & 1) * 0b1010000111
^ ((y >> 11) & 1) * 0b1110011111
^ ((y >> 10) & 1) * 0b1100010011
^ ((y >> 9) & 1) * 0b1101010101
^ ((y >> 8) & 1) * 0b1101110110
^ ((y >> 7) & 1) * 0b0110111011
^ ((y >> 6) & 1) * 0b1000000001
^ ((y >> 5) & 1) * 0b1111011100
^ ((y >> 4) & 1) * 0b0111101110
^ ((y >> 3) & 1) * 0b0011110111
^ ((y >> 2) & 1) * 0b1010100111
^ ((y >> 1) & 1) * 0b1110001111
^ ((y >> 0) & 1) * 0b1100011011;
}
class Synchronizer
{
// No valid programme identifier has country code 0, so we can use
// zero to indicate initial condition.
std::uint32_t prog_id = 0;
// Initial state needs to not look like 0BCD0
static constexpr unsigned __int128 initial_state = 0xffff;
// 128 bits can store a whole 104-bit group, plus 24 bits of
// adjacent context.
unsigned __int128 state = initial_state;
static auto constexpr max_loss_blocks = 10;
unsigned int bits_until_a = 0;
unsigned int blocks_since_lock = 0;
std::uint32_t last_good_b = 0;
public:
static constexpr std::uint32_t CHECKWORD_A = 0x0fc;
static constexpr std::uint32_t CHECKWORD_B = 0x198;
static constexpr std::uint32_t CHECKWORD_C = 0x168;
static constexpr std::uint32_t CHECKWORD_K = 0x350;
static constexpr std::uint32_t CHECKWORD_D = 0x1b4;
virtual ~Synchronizer() = default;
std::uint16_t pid() const {
return prog_id >> 10;
}
virtual void reset() {
state = initial_state;
prog_id = 0;
perBitAction = &Synchronizer::search_for_lock;
// other members will be set before we enter the locked state
}
void push(bool bit)
{
state <<= 1;
state += bit;
(this->*perBitAction)();
}
protected:
// @return error weight
static rds::block correct(std::uint16_t checkword, std::uint32_t input);
void (Synchronizer::*perBitAction)() = &Synchronizer::search_for_lock;
void search_for_lock();
void confirm_lock();
void lock_found(std::uint16_t pid, unsigned int bits_to_go);
void lock_lost();
virtual void process_group(const rds::group& group);
};
}
namespace {
struct Correction
{
std::uint16_t correction;
unsigned char distance;
bool correctable;
Correction()
: correction(0), distance(0xf), correctable(false)
{}
void update(unsigned int c, unsigned int d)
{
if (d > distance)
return; // already have a better correction
else if (d < distance)
distance = d, correction = c, correctable = 1;
else if (c != correction)
correctable = 0; // detect only
}
};
static auto const corrections =
[]{
std::array<Correction, 1024> t;
// Recieved exactly
t[0].distance = 0;
// 1-9 bit burst errors
for (unsigned int dist = 1; dist < 10; ++dist) {
const std::uint32_t first = (1u << (dist-1)) | 1;
const std::uint32_t last = 1u << dist;
for (std::uint32_t i = first; i < last; i+=2) {
for (std::uint32_t j = i; !(j & 1u<<26); j <<=1)
t[rds::syndrome(j)].update(j>>10, dist);
}
}
// two independent 1-2 bit errors
for (unsigned int dist = 9; dist < 24; ++dist) {
for (std::uint32_t j: { ((1<<dist)+1), ((3<<dist)+1), ((1<<dist)+3), ((3<<dist)+3) }) {
for (unsigned shift = 0; dist+shift < 26; ++shift) {
t[rds::syndrome(j<<shift)].update(j<<shift>>10, 1 + __builtin_popcount(j));
}
}
}
return t;
}();
template<unsigned char size, typename... T>
static constexpr int hamming_distance(T... v)
{
auto constexpr mask = (std::common_type_t<T...>(1) << size) - 1;
return __builtin_popcount((mask & (... ^ v)));
}
}
// @return error weight
rds::block rds::Synchronizer::correct(std::uint16_t checkword, std::uint32_t input)
{
input ^= checkword;
auto s = syndrome(input);
rds::block b = {static_cast<std::uint16_t>(input >> 10), 0, true};
if (!s) {
// perfect
return b;
}
auto const& entry = corrections[s];
b.value ^= entry.correction;
b.err_count = entry.distance;
b.is_valid = entry.correctable;
return b;
}
void rds::Synchronizer::search_for_lock()
{
constexpr int MAX_ERR = 8;
// Check self-similarity first, with 0.5% false-positive rate, before examining CRCs
if (hamming_distance<26>(CHECKWORD_A, CHECKWORD_K, state, state >> 52) <= 6) {
rds::block a,b,k,d;
int err;
if ((err = (k = correct(CHECKWORD_K, state)).err_count) <= MAX_ERR
&& (err += (a = correct(CHECKWORD_A, state >> 52)).err_count) <= MAX_ERR
&& a.value == k.value
&& (err += (b = correct(CHECKWORD_B, state >> 26)).err_count) <= MAX_ERR)
{
// we matched A.K
lock_found(a.value, 52);
return;
}
if ((err = (a = correct(CHECKWORD_A, state)).err_count) <= MAX_ERR
&& (err += (k = correct(CHECKWORD_K, state >> 52)).err_count) <= MAX_ERR
&& a.value == k.value
&& (err += (d = correct(CHECKWORD_D, state >> 26)).err_count) <= MAX_ERR)
{
// we matched K.A
lock_found(a.value, 0);
return;
}
}
// Have we got a match with A...A? Again, we require >99.5% certainty before checking CRCs.
// Note that we only have 24 bits remaining of the previous A, so fill in from the new one.
if (hamming_distance<24>(state, state >> 104) <= 5) {
rds::block a,b,c,d,e;
int err;
if ((err = (a = correct(CHECKWORD_A, state)).err_count) <= MAX_ERR
&& (err += (e = correct(CHECKWORD_A, ((state >> 104) & 0xffffff) | (state & 0x3000000))).err_count) <= MAX_ERR
&& e.value == a.value
&& (err += (d = correct(CHECKWORD_D, state >> 26)).err_count) <= MAX_ERR
&& (err += (c = correct(CHECKWORD_C, state >> 52)).err_count) <= MAX_ERR
&& (err += (b = correct(CHECKWORD_B, state >> 78)).err_count) <= MAX_ERR)
{
// we matched A...A
lock_found(a.value, 0);
return;
}
}
}
void rds::Synchronizer::confirm_lock()
{
if (--bits_until_a)
return;
bits_until_a = 104;
rds::block a = correct(CHECKWORD_A, state);
rds::block b = correct(CHECKWORD_B, state >> 78);
rds::block c = correct(CHECKWORD_C, state >> 52);
rds::block k = correct(CHECKWORD_K, state >> 52);
rds::block d = correct(CHECKWORD_D, state >> 26);
unsigned ck = std::min(k.err_count, c.err_count);
if ((a.err_count >= 4 || a.value != prog_id>>10) && b.err_count * ck * d.err_count >= 16) {
if (hamming_distance<25>(std::uint32_t(state), prog_id>>1) <= 5) {
// bit slip - need one more bit
bits_until_a = 1;
} else if (hamming_distance<26>(std::uint32_t(state)>>1, prog_id) <= 5) {
// bit slip - miss one bit
bits_until_a = 103;
} else {
lock_lost();
}
return;
}
if (a.err_count == 0 && a.value != prog_id>>10) {
// prog_id has changed
prog_id = CHECKWORD_A ^ encode(a);
}
// reset counter
blocks_since_lock = 0;
if (b.err_count > 8) {
// attempt to recover block 2 using saved PTY and inferred A/B
// AAAABTPPPPPiiiii..........
static constexpr auto pty_mask = 0b00000011111000000000000000;
static constexpr auto ab_mask = 0b00001000000000000000000000;
std::uint32_t block2 =
((~pty_mask & ~ab_mask) & (state >> 78))
| (pty_mask & last_good_b)
| (ab_mask & (c.err_count == k.err_count ? last_good_b : -1 * (c.err_count >= k.err_count)));
auto b2 = correct(CHECKWORD_B, block2);
if (b2.err_count >= b.err_count) {
// couldn't decode the B block, so the rest is useless
return;
}
} else {
last_good_b = state >> 78;
}
process_group({a, b, c, d});
}
void rds::Synchronizer::lock_found(std::uint16_t pid, unsigned int bits_to_go) {
perBitAction = &Synchronizer::confirm_lock;
prog_id = CHECKWORD_A ^ encode(pid);
blocks_since_lock = 0;
bits_until_a = 1 + bits_to_go;
confirm_lock();
}
void rds::Synchronizer::lock_lost() {
if (++blocks_since_lock >= max_loss_blocks)
perBitAction = &Synchronizer::search_for_lock;
}
void rds::Synchronizer::process_group(const rds::group&)
{
// to be overridden
}
struct TestSynchronizer : rds::Synchronizer
{
// keep track of some statistics
unsigned long bits = 0;
unsigned long good_blocks = 0;
unsigned long corrected_blocks = 0;
unsigned long bad_blocks = 0;
void push(bool bit) {
++bits;
rds::Synchronizer::push(bit);
}
void process_group(const rds::group& group) override
{
for (auto const& block: {group.a, group.b, group.c, group.d}) {
auto& count
= !block.is_valid ? bad_blocks
: block.err_count ? corrected_blocks
: good_blocks;
++count;
}
}
void read_file(const std::string& filename)
{
reset();
bits = good_blocks = corrected_blocks = bad_blocks = 0;
std::ifstream in(filename, std::ifstream::binary);
int c;
while ((c = in.get()) != EOF) {
for (int m = 0x80; m; m >>= 1)
push(c & m);
}
// Summary statistics
std::clog << filename << ": "
<< good_blocks << " good, "
<< corrected_blocks << " corrected, "
<< bad_blocks << " uncorrectable blocks; "
<< bits - 26 * (good_blocks + corrected_blocks + bad_blocks)
<< " undecoded bits"
<< std::endl;
}
};
int main(int, char **argv)
{
TestSynchronizer s;
while (*++argv) {
s.read_file(*argv);
}
}
</code></pre>
| [] | [
{
"body": "<h3>No overloaded population counts</h3>\n\n<p>One point is that you should either (i) statically enforce your integer type to have 32 bits, or (ii) call the correct population count function depending on the integer width.</p>\n\n<p>That is, the argument for <code>__builtin_popcount</code> is an <code>unsigned int</code>, but <code>__builtin_popcountl</code> takes an <code>unsigned long</code> and <code>__builtin_popcountll</code> takes an <code>unsigned long long</code>. So in particular, there is no overload for <code>__builtin_popcount</code>, but the functions for different widths are actually different.</p>\n\n<h3>Portability</h3>\n\n<p>As noted, the <code>__builtin_popcount</code> functions are specific to GCC. For portability, you can write the Hamming distance computation with the help of <code>std::bitset</code> as follows:</p>\n\n<pre><code>template<unsigned char size, typename... T>\nstatic constexpr int hamming_distance(T... v)\n{\n return std::bitset<size>((... ^ v)).count();\n}\n</code></pre>\n\n<p>In fact, it seems that (<a href=\"https://godbolt.org/z/5fAKzW\" rel=\"nofollow noreferrer\">on Compiler Explorer</a>) that the above creates object code identical to yours, so there should be absolutely no difference in performance.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T19:30:23.407",
"Id": "214266",
"ParentId": "214240",
"Score": "2"
}
},
{
"body": "<p>The generation of the table was moved to compile time due to very slow startup of the program. But evidently that problem is no longer present:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>$ time ./corrections >/dev/null\nreal 0m0.001s\nuser 0m0.001s\nsys 0m0.000s\n</code></pre>\n\n<p>So the table generator can be inlined into <code>synchronizer.cc</code> just as in the single-file version in the question (using an immediately-invoked lambda to give us a constant).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-27T11:52:30.443",
"Id": "214391",
"ParentId": "214240",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T13:40:05.407",
"Id": "214240",
"Score": "8",
"Tags": [
"c++",
"c++17"
],
"Title": "RDS receiver - synchronization and error correction"
} | 214240 |
<p>The script below is intended to retrieve digital signage data from a server on Linux and Windows systems. The script needs to be <em>copy and run</em>, so I am limited to Python's standard library. The script has two modes:</p>
<ul>
<li>In normal mode it just updates the data and terminates.</li>
<li>In server mode it listens on a TCP socket for incoming synchronization requests and starts them in a thread one at a time.</li>
</ul>
<p>For synchronization, the client sends a JSON-ish list of all SHA-256 sums of all current files to the server (the <em>manifest</em>) to allow the server to only send files back that have changed. The server also sends back a <em>manifest.json</em> file in the tar.xz archive, to allow the client to remove any files that are no longer required.</p>
<p>I'd like to have feedback, especially on the cross-platform implementation for Windows and Linux. I replaced the IP address of the actual server with <code>[undisclosed]</code>.</p>
<pre><code>#! /usr/bin/env python3
#
# digsigclt - Digital Signage data synchronization client.
#
# digsigclt is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# digsigclt is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with digsigclt. If not, see <http://www.gnu.org/licenses/>.
#
# This unit provides a service to automatically login
# the digital signage user to a certain terminal.
#
# (C) 2019: HOMEINFO - Digitale Informationssysteme GmbH
#
# Maintainer: Richard Neumann <r dot neumann at homeinfo period de>
#
####################################################################
"""Digital signage cross-platform client."""
from argparse import ArgumentParser
from contextlib import suppress
from hashlib import sha256
from http.client import IncompleteRead
from http.server import HTTPServer, BaseHTTPRequestHandler
from io import BytesIO
from json import dumps, load, loads
from logging import DEBUG, INFO, basicConfig, getLogger
from pathlib import Path
from platform import architecture, machine, system
from socket import gethostname
from sys import exit # pylint: disable=W0622
from tarfile import open as tar_open
from tempfile import gettempdir, TemporaryDirectory
from threading import Thread
from urllib.error import URLError, HTTPError
from urllib.parse import urlencode, ParseResult
from urllib.request import urlopen, Request
DESCRIPTION = '''HOMEINFO multi-platform digital signage client.
Synchronizes data to the current working directory
or listens on the specified port when in server mode
to be triggered to do so.'''
SERVER = ('http', '[undisclosed]', '/appcmd/digsig')
MAX_RETRIES = 3
REG_KEY = r'SOFTWARE\HOMEINFO\digsigclt'
OS64BIT = {'AMD64', 'x86_64'}
LOCKFILE_NAME = 'digsigclt.sync.lock'
MANIFEST_FILENAME = 'manifest.json'
DEFAULT_DIR_LINUX = '/usr/share/digsig'
DEFAULT_DIR_WINDOWS = 'C:\\HOMEINFOGmbH\\content'
LOG_FORMAT = '[%(levelname)s] %(name)s: %(message)s'
LOGGER = getLogger('digsigclt')
class UnsupportedSystem(Exception):
"""Indicates that this script is running
on an unsupported operating system.
"""
def __init__(self, system): # pylint: disable=W0621
"""Sets the operating system."""
super().__init__()
self.system = system
class MissingConfiguration(Exception):
"""Indicates that the configuration is missing."""
class InvalidContentType(Exception):
"""Indicates that an invalid content type was received."""
def __init__(self, content_type):
"""Sets the content type."""
super().__init__()
self.content_type = content_type
class Locked(Exception):
"""Indicates that the synchronization is currently locked."""
def is32on64():
"""Determines whether we run 32 bit
python on a 64 bit operating system.
"""
py_arch, _ = architecture()
sys_arch = machine()
return py_arch == '32bit' and sys_arch in OS64BIT
def get_files(directory):
"""Lists the current files."""
for inode in directory.iterdir():
if inode.is_dir():
yield from get_files(directory=inode)
elif inode.is_file():
yield inode
def copydir(source_dir, dest_dir):
"""Copies all contents of source_dir
into dest_dir, overwriting all files.
"""
for source_path in source_dir.iterdir():
relpath = source_path.relative_to(source_dir)
dest_path = dest_dir.joinpath(relpath)
if source_path.is_file():
LOGGER.info('Updating: %s.', dest_path)
with dest_path.open('wb') as dst, source_path.open('rb') as src:
dst.write(src.read())
elif source_path.is_dir():
if dest_path.is_file():
dest_path.unlink()
dest_path.mkdir(mode=0o755, parents=True, exist_ok=True)
copydir(source_path, dest_path)
def strip_files(directory, manifest):
"""Removes all files from the directory tree,
whose SHA-256 checksums are not in the manifest.
"""
for path in get_files(directory):
with path.open('rb') as file:
bytes_ = file.read()
sha256sum = sha256(bytes_).hexdigest()
if sha256sum not in manifest:
LOGGER.debug('Removing obsolete file: %s.', path)
path.unlink()
def strip_tree(directory):
"""Removes all empty directory sub-trees."""
def strip_subdir(subdir):
"""Recursively removes empty directory trees."""
for inode in subdir.iterdir():
if inode.is_dir():
strip_subdir(inode)
if not tuple(subdir.iterdir()): # Directory is empty.
LOGGER.debug('Removing empty directory: %s.', subdir)
subdir.rmdir()
for inode in directory.iterdir():
if inode.is_dir():
strip_subdir(inode)
def read_manifest(tmpd):
"""Reads the manifest from the respective temporary directory."""
LOGGER.debug('Reading manifest.')
path = tmpd.joinpath(MANIFEST_FILENAME)
with path.open('r') as file:
manifest = load(file)
path.unlink() # File is no longer needed.
return manifest
def get_directory(directory):
"""Returns the target directory."""
if directory == '--':
return Path.cwd()
return Path(directory)
def get_default_directory():
"""Returns the target directory."""
sys = system()
if sys == 'Linux':
return DEFAULT_DIR_LINUX
if sys == 'Windows':
return DEFAULT_DIR_WINDOWS
raise UnsupportedSystem(sys)
def _get_config_linux():
"""Returns the configuration on a Linux system."""
hostname = gethostname()
try:
tid, cid = hostname.split('.')
except ValueError:
try:
ident = int(hostname) # For future global terminal IDs.
except ValueError:
LOGGER.error('No valid configuration found in /etc/hostname.')
raise MissingConfiguration()
return {'id': ident}
try:
tid = int(tid)
except ValueError:
LOGGER.error('TID is not an integer.')
raise MissingConfiguration()
try:
cid = int(cid)
except ValueError:
LOGGER.error('CID is not an interger.')
raise MissingConfiguration()
return {'tid': tid, 'cid': cid}
def _get_config_windows():
"""Returns the configuration from the windows registry."""
# Import winreg in Windows-specific function
# since it is not available on non-Windows systems.
from winreg import HKEY_LOCAL_MACHINE # pylint: disable=E0401
from winreg import KEY_READ # pylint: disable=E0401
from winreg import KEY_WOW64_64KEY # pylint: disable=E0401
from winreg import OpenKey # pylint: disable=E0401
from winreg import QueryValueEx # pylint: disable=E0401
def read_config(key):
"""Reads the configuration from the respective key."""
for config_option in ('tid', 'cid', 'id'):
try:
value, type_ = QueryValueEx(key, config_option)
except FileNotFoundError:
LOGGER.warning('Key not found: %s.', config_option)
continue
if type_ != 1:
message = 'Unexpected registry type %i for key "%s".'
LOGGER.error(message, type_, config_option)
continue
try:
value = int(value)
except ValueError:
message = 'Expected int value for key %s not "%s".'
LOGGER.error(message, config_option, value)
continue
yield (config_option, value)
access = KEY_READ
if is32on64():
access |= KEY_WOW64_64KEY
try:
with OpenKey(HKEY_LOCAL_MACHINE, REG_KEY, access=access) as key:
configuration = dict(read_config(key))
except FileNotFoundError:
LOGGER.error('Registry key not set: %s.', REG_KEY)
raise MissingConfiguration()
if configuration:
return configuration
raise MissingConfiguration()
def get_config():
"""Returns the respective configuration:"""
sys = system()
LOGGER.debug('Running on %s.', sys)
if sys == 'Linux':
return _get_config_linux()
if sys == 'Windows':
return _get_config_windows()
raise UnsupportedSystem(sys)
def get_sha256sums(directory):
"""Yields the SHA-256 sums in the current working directory."""
for filename in get_files(directory):
with filename.open('rb') as file:
bytes_ = file.read()
sha256sum = sha256(bytes_).hexdigest()
LOGGER.debug('Found file: %s (%s).', filename, sha256sum)
yield sha256sum
def get_manifest(directory):
"""Returns the manifest list."""
LOGGER.debug('Creating manifest of current files.')
sha256sums = list(get_sha256sums(directory))
return dumps(sha256sums)
def process_response(response):
"""Processes the response from the webserver."""
if response.status == 200:
content_type = response.headers.get('Content-Type')
if content_type == 'application/x-xz':
return response.read()
raise InvalidContentType(content_type)
raise ConnectionError(response.status)
def retrieve(directory, retries=0):
"""Retrieves data from the server."""
config = get_config()
params = {key: str(value) for key, value in config.items()}
parse_result = ParseResult(*SERVER, '', urlencode(params), '')
url = parse_result.geturl()
data = get_manifest(directory).encode()
headers = {'Content-Type': 'application/json'}
request = Request(url, data=data, headers=headers)
LOGGER.debug('Retrieving files from %s.', request.full_url)
with urlopen(request) as response:
try:
return process_response(response)
except IncompleteRead:
LOGGER.error('Could not read response from webserver.')
if retries <= MAX_RETRIES:
return retrieve(directory, retries=retries+1)
raise
def update(tar_xz, directory):
"""Updates the digital signage data
from the respective tar.xz archive.
"""
fileobj = BytesIO(tar_xz)
with TemporaryDirectory() as tmpd:
with tar_open(mode='r:xz', fileobj=fileobj) as tar:
tar.extractall(path=tmpd)
tmpd = Path(tmpd)
manifest = read_manifest(tmpd)
copydir(tmpd, directory)
strip_files(directory, manifest)
strip_tree(directory)
def do_sync(directory):
"""Synchronizes the data."""
try:
tar_xz = retrieve(directory)
except MissingConfiguration:
LOGGER.critical('Cannot download data due to missing configuration.')
except HTTPError as http_error:
if http_error.code == 304: # Data unchanged.
LOGGER.info('Data unchanged.')
return True
LOGGER.critical('Could not download data: %s.', http_error)
except URLError as url_error:
LOGGER.critical('Could not download data: %s.', url_error)
except IncompleteRead:
LOGGER.critical('Could not retrieve data.')
except ConnectionError as connection_error:
LOGGER.critical('Connection error: %s.', connection_error)
except InvalidContentType as invalid_content_type:
LOGGER.critical(
'Retrieved invalid content type: %s.',
invalid_content_type.content_type)
else:
update(tar_xz, directory)
return True
return False
def sync_in_thread(directory):
"""Starts the synchronization within a thread."""
try:
do_sync(directory)
finally:
LOCK_FILE.unlink()
def sync(directory):
"""Performs a data synchronization."""
try:
with LOCK_FILE:
return do_sync(directory)
except Locked:
LOGGER.error('Synchronization is locked.')
return False
def server(args):
"""Runs the HTTP server."""
socket = ('0.0.0.0', args.port)
HTTPRequestHandler.directory = args.directory
httpd = HTTPServer(socket, HTTPRequestHandler)
LOGGER.info('Listening on %s:%i.', *socket)
try:
httpd.serve_forever()
except KeyboardInterrupt:
if HTTPRequestHandler.sync_thread is not None:
HTTPRequestHandler.sync_thread.join()
return
def main():
"""Main method to run."""
parser = ArgumentParser(description=DESCRIPTION)
parser.add_argument(
'--server', '-S', action='store_true', help='run in server mode')
parser.add_argument(
'--port', '-p', type=int, default=5000, help='port to listen on')
parser.add_argument(
'--directory', '-d', type=get_directory,
default=get_default_directory(), help='sets the target directory')
parser.add_argument(
'--verbose', '-v', action='store_true', help='turn on verbose logging')
args = parser.parse_args()
basicConfig(level=DEBUG if args.verbose else INFO, format=LOG_FORMAT)
LOGGER.debug('Target directory: %s', args.directory)
if not args.directory.is_dir():
LOGGER.critical('Target directory does not exist: %s.', args.directory)
exit(2)
if args.server:
server(args)
else:
if sync(args.directory):
exit(0)
else:
exit(1)
class HTTPRequestHandler(BaseHTTPRequestHandler):
"""Handles HTTP requests."""
directory = None
sync_thread = None
@classmethod
def sync_pending(cls):
"""Returns wehter a synchronization is currently pending."""
if cls.sync_thread is None:
return False
if cls.sync_thread.is_alive():
return True
cls.sync_thread.join() # Just to be on the safe side.
return False
@classmethod
def start_sync(cls):
"""Starts a synchronization."""
try:
LOCK_FILE.create() # Acquire lock.
except Locked:
return False
if cls.sync_pending():
LOCK_FILE.unlink()
return False
cls.sync_thread = Thread(target=sync_in_thread, args=(cls.directory,))
cls.sync_thread.start()
return True
@property
def content_length(self):
"""Returns the content length."""
return int(self.headers['Content-Length'])
@property
def bytes(self):
"""Returns the POSTed bytes."""
return self.rfile.read(self.content_length)
@property
def json(self):
"""Returns POSTed JSON data."""
return loads(self.bytes)
def do_POST(self): # pylint: disable=C0103
"""Handles POST requests."""
LOGGER.debug('Received POST request.')
if self.json.get('command') == 'sync':
LOGGER.debug('Received sync command.')
if type(self).start_sync():
message = 'Synchronization started.'
status_code = 202
else:
message = 'Synchronization already in progress.'
status_code = 503
else:
message = 'Invalid command.'
status_code = 400
json = {'message': message}
body = dumps(json).encode()
self.send_response(status_code)
self.end_headers()
response = BytesIO()
response.write(body)
self.wfile.write(response.getvalue())
class LockFile:
"""Represents a lock file to lock synchronization."""
def __init__(self, filename):
"""Sets the filename."""
self.filename = filename
def __enter__(self):
"""Creates the lock file."""
self.create()
return self
def __exit__(self, *_):
"""Removes the lock file."""
self.unlink()
@property
def basedir(self):
"""Returns the base directory."""
return Path(gettempdir())
@property
def path(self):
"""Returns the file path."""
return self.basedir.joinpath(self.filename)
@property
def exists(self):
"""Tests whether the lock file exists."""
return self.path.is_file()
def create(self, content=b''):
"""Creates the lock file."""
if self.exists:
raise Locked()
with self.path.open('wb') as file:
file.write(content)
def unlink(self):
"""Removes the lock file."""
with suppress(FileNotFoundError):
self.path.unlink()
LOCK_FILE = LockFile(LOCKFILE_NAME)
if __name__ == '__main__':
main()
<span class="math-container">```</span>
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T13:45:50.623",
"Id": "214241",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"linux",
"windows"
],
"Title": "Cross-platform standard library-only data synchronization script"
} | 214241 |
<p>I have data as follows:</p>
<pre><code>Payment Date 11/01/18 01/01/2019 11/01/09 11/01/20
Total Amount 4536.87 4654.98 4698.63 4687.69
</code></pre>
<p>I need to add up all of the <code>Total Amount</code> starting from <code>11/01/18</code> through <code>11/01/20</code>.</p>
<p>For the months in between dates, I need to use the amount from previous month. I also need to change this to account for bi-weekly and semi-monthly.</p>
<p>For example, for month <code>12/01/2018</code>, I need to use <code>Total Amount</code> from <code>11/01/18</code>, in this case <code>4536.87</code> and so on.</p>
<p>This is what I have so far. Is there a better way to do this?</p>
<pre><code>public void aggretagePaymentAmounts(List<PaymentFields> fieldsType,
Payments payments, int numberOfTrialPayments){
AtomicInteger cnt = new AtomicInteger(1);
Iterator<PaymentFields> fieldsTypeIterator = fieldsType.iterator();
PaymentFields fieldType = fieldsTypeIterator.next();
PaymentFields nextFieldType = null;
if (fieldsTypeIterator.hasNext()) {
nextFieldType = fieldsTypeIterator.next();
}
LocalDate monthDate = LocalDate.parse(fieldType.getPaymentDate());
while (cnt.getAndIncrement() <= numberOfPayments) {
monthDate = monthDate.plusMonths(1);
//what about semi-monthly and bi-weekly?
payments.aggregate(fieldType.getPaymentAmount());
if (nextFieldType != null) {
LocalDate nextFieldTypeDate = LocalDate.parse(nextFieldType.getPaymentDate());
if (nextFieldTypeDate.getMonthValue() == monthDate.getMonthValue()) {
fieldType = nextFieldType;
if (fieldsTypeIterator.hasNext()) {
nextFieldType = fieldsTypeIterator.next();
} else {
nextFieldType = null;
}
}
}
}
}
public class Payments {
private BigDecimal paymentAmount;//getters/setters not shown here
public void aggregate(BigDecimal tmpPaymentAmount){
paymentAmount = add(paymentAmount, tmpPaymentAmount);
}
private static BigDecimal add(BigDecimal... addends) {
return Arrays.stream(addends)
.filter(Objects::nonNull)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T14:48:11.437",
"Id": "414285",
"Score": "1",
"body": "What's with that `AtomicInteger`? It's a local variable that doesn't escape the method. It seems an `int` would do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-27T01:56:01.897",
"Id": "414519",
"Score": "0",
"body": "@Marco it’s just a convenience incrementor, instead of doing I++"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-27T07:32:54.523",
"Id": "414542",
"Score": "1",
"body": "It doesn't seem very convenient and it already threw one reader off their track. So it made the code more complicated, slower and didn't add any value. Use the common ++ operator instead."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T13:48:29.113",
"Id": "214242",
"Score": "3",
"Tags": [
"java"
],
"Title": "Add up values from one field for multiple months"
} | 214242 |
<h1>Business logic</h1>
<p>It would take us too far to explain the whole business case behind this code, so I'll try to be as succinct as possible. </p>
<ul>
<li>There are <code>Person</code>s, </li>
<li>and Persons can have <code>Profile</code>s, </li>
<li>and the combination of those two is a <code>PersonProfile</code>. </li>
<li>There is also a table called <code>ProfilesToReplace</code>, which contains <code>Profile</code>s that in the future will be replaced by updated ones.
<ul>
<li>For compatibility sake these <code>ProfilesToReplace</code> are not linked to the actual <code>Person</code>, but to a "dummy" <code>Person</code>.</li>
</ul></li>
</ul>
<p>Over time, entries in <code>ProfilesToReplace</code> will be deleted (once an outdated <code>Profile</code> has been replaced by a proper one), which means the related <code>Profile</code>s need to be removed. But before that can happen, we need to remove the <code>PersonProfile</code>s that link to these outdated <code>Profile</code>s and remove these first. We also need to remove the "dummy" <code>Person</code>s once they have no related entries in the <code>PersonProfile</code>s table.</p>
<p>This is done via a regularly running job, which is a .NET C# 4.6.2 command line application (but it uses the new csproj format).</p>
<h1>The problem</h1>
<p>There is however a snag. To know which <code>Person</code> is a "dummy" person, we need to look at that <code>Person</code>'s IDF: in the case of a "dummy" <code>Person</code>, it is the same as the IDF of its related "real" <code>Person</code>, except for a single digit. We do have a list of "real" IDFs, but that is in another database, and it is not possible to connect our database to that other database. </p>
<p>The good news: we can retrieve a list of these "valid" IDFs in our application. The bad news: this involves tens of thousands of IDFs, and thus we're confronted with the limits of SQL Server parameters. Moreover, we're working with <a href="https://docs.microsoft.com/en-us/ef/core/" rel="noreferrer">EntityFrameworkCore</a> and I haven't found a way to pass a list of data via <a href="https://docs.microsoft.com/en-us/ef/core/querying/raw-sql" rel="noreferrer"><code>.FromSql()</code></a>. Also, retrieving all data and filtering in code is problematic as well, since <code>PersonProfile</code>s contains more than a million records.</p>
<h1>How I solved it</h1>
<p>However, I found a way around these issues, allowing me to do the filtering in a query: I pass the list of IDFs as an XML string and let the query untangle it into a list of IDFs that can be used in a WHERE clause:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT DISTINCT [Id]
FROM [authorization].[PersonProfile]
WHERE 1 = 1
AND [ProfileId] NOT IN (
SELECT [ProfileId]
FROM [authorization].[ProfilesToReplace]
)
AND [PersonIdf] IN (
SELECT PersonIdf
FROM (
SELECT PersonIdf = XTbl.value('(PersonIdf)[1]', 'bigint')
FROM @PersonIdfs.nodes('/root') AS XD(XTbl)
) AS XmlToData
)
</code></pre>
<p>And this is how I use that SQL and pass it the necessary parameter:</p>
<pre class="lang-cs prettyprint-override"><code>public async Task<ICollection<int?>> Execute(List<long> dummyPersonIdfs)
{
var getDeletablePersonProfilesQuery = QueryRetriever.GetQuery("GetDeletablePersonProfiles.sql");
var personIdfsAsXml = new XDocument(
new XElement("root", dummyPersonIdfs.Select(x => new XElement("PersonIdf", x))))
.ToString();
var personIdfs = new SqlParameter("@PersonIdfs", SqlDbType.Xml) { Value = personIdfsAsXml };
var deletablePersonProfileIds = (await _dbContext.DeletablePersonProfiles
.FromSql(getDeletablePersonProfilesQuery, personIdfs).ToListAsync())
.Select(x => x.Id).ToList();
if (deletablePersonProfileIds.Any())
{
return await _personsRemover.Execute(deletablePersonProfileIds);
}
return new List<int?>();
}
</code></pre>
<p><code>QueryRetriever</code> is simply a class that retrieves the above SQL query from an embedded .sql file:</p>
<pre class="lang-cs prettyprint-override"><code>internal static class QueryRetriever
{
public static string GetQuery(string scriptName)
{
var namespacePrefix = "Badger.Service.BadgeCleaning.";
var resourceName = namespacePrefix + scriptName;
var assembly = Assembly.GetExecutingAssembly();
using (var stream = assembly.GetManifestResourceStream(resourceName))
{
if (stream == null)
{
throw new Exception($"Missing SQL script: {resourceName}");
}
using (var streamReader = new StreamReader(stream))
{
return streamReader.ReadToEnd();
}
}
}
}
</code></pre>
<h1>So all's well?</h1>
<p>While I am happy with the code as is, I'm wondering whether I've made it more complicated than needs to be. Am I overlooking a simpler solution?</p>
<p>I'm also somewhat unsure of how I construct the XML string: is there perhaps a more efficient way? </p>
<p>And is the way I deal with the XML string in my SQL query the best way? Note that I cannot use <a href="https://docs.microsoft.com/en-us/sql/t-sql/functions/string-split-transact-sql" rel="noreferrer"><code>STRING_SPLIT</code></a>, because the application isn't currently running on SQL Server 2016 (or any more recent product).</p>
| [] | [
{
"body": "<p>If you weren't using EntityFrameworkCore, my suggestion would look something like this:</p>\n\n<ol>\n<li>Get the list of values from database 1</li>\n<li>Use <code>SqlBulkCopy</code> to insert a bunch of them into some table on database 2</li>\n<li>Join to that table in your \"GetDeletablePersonProfiles\" query.</li>\n</ol>\n\n<p>Unfortunately, based on some cursory googling, it looks like EntityFrameworkCore <a href=\"https://github.com/aspnet/EntityFrameworkCore/issues/7256\" rel=\"nofollow noreferrer\">doesn't support bulk operations</a> (<a href=\"https://github.com/borisdj/EFCore.BulkExtensions\" rel=\"nofollow noreferrer\">this extension</a> does, however). I'll admit - I don't know a ton about EFC, but based on what you're doing I assume the following is possible:</p>\n\n<ol>\n<li>Get the list of values from database 1 (you're already doing this)</li>\n<li>In the code you execute, dump the values from the XML into a table (better performance than joining to the XML)</li>\n<li>Use that table in your query</li>\n</ol>\n\n<p>Specifically, the main change I would suggest is taking this:</p>\n\n<pre><code>AND [PersonIdf] IN (\n SELECT PersonIdf\n FROM (\n SELECT PersonIdf = XTbl.value('(PersonIdf)[1]', 'bigint')\n FROM @PersonIdfs.nodes('/root') AS XD(XTbl)\n ) AS XmlToData\n)\n</code></pre>\n\n<p>And turn it into this (you'll notice that I've also transformed both of your <code>EXISTS</code> into <code>JOIN</code>s; they're easier to read and accomplish the same task.</p>\n\n<pre><code>SELECT PersonIdf = XTbl.value('(PersonIdf)[1]', 'bigint')\n INTO #MyFunTempTable\n FROM @PersonIdfs.nodes('/root') AS XD(XTbl);\n\nSELECT DISTINCT PersonProfile.[Id]\n FROM [authorization].[PersonProfile]\n INNER JOIN #MyFunTempTable PersonIdfList\n ON PersonProfile.PersonIdf = PersonIdfList.PersonIdf\n LEFT OUTER JOIN [authorization].[ProfilesToReplace]\n ON PersonProfile.ProfileId = ProfilesToReplace.ProfileId\n WHERE ProfilesToReplace.ProfileId IS NULL\n</code></pre>\n\n<p>It would also be good to make this a stored procedure, so that you don't have to worry about GetDeletablePersonProfiles.sql being replaced by a malicious actor.</p>\n\n<p>You could also split it into two stages, using <code>ExecuteSqlCommand</code> to insert the values into a table (can't be a temp table anymore) and then you should really just need LINQ to get the values back.</p>\n\n<p>You can also get an ADO.NET <code>DbConnection</code> object from the database context using <code>_dbContext.Database.GetDbConnection()</code>, and if you know that this is a SQL Server connection I've heard that you can cast that to a <code>SqlConnection</code> object, at which point you have access to the <code>SqlBulkCopy</code> method. This is questionable at best, but it might provide clean enough/performant enough code to be worthwhile. I'm definitely not endorsing this approach, but I'll put it out there.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-22T17:58:38.460",
"Id": "226642",
"ParentId": "214250",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T15:17:57.543",
"Id": "214250",
"Score": "7",
"Tags": [
"c#",
"sql-server",
"t-sql",
"entity-framework-core"
],
"Title": "Retrieving the IDs of entries to be deleted from a table"
} | 214250 |
<p>This is my try on the 99 bottles of beer on the wall lyrics, made in Python 3. I am a beginner willing to learn so be gentle :)</p>
<pre><code>def lyrics():
if count > 1:
print(f"{count} bottles of beer on the wall,")
print("")
print(f"{count} bottles of beer.")
print("")
print("Take one down, pass it around,")
print("")
else:
print(f"{count} bottle of beer on the wall.")
print("")
print(f"{count} bottle of beer on the wall,")
print("")
print(f"{count} bottle of beer.")
print("")
print("Take it down, pass it around,")
print("")
print("No more bottles of beer on the wall.")
def bottles():
global count
while count > 1:
lyrics()
count = count - 1
if count > 1:
print(f"{count} bottles of beer on the wall.")
print("")
else:
lyrics()
if __name__ == '__main__':
count = 99
bottles()
</code></pre>
| [] | [
{
"body": "<p>You can reduce the need to use <code>print(\"\")</code> by adding a <code>\\n</code> after each statement. You can also use a one-line if statement to reduce the four line if statement. </p>\n\n<p><code>count = count - 1</code> is the same as <code>count -= 1</code>, which reduces the amount of code you need to write.</p>\n\n<p>This is assuming you are using <code>Python 3.6</code></p>\n\n<pre><code>def lyrics():\n if count > 1:\n print(f\"{count} bottles of beer on the wall,\\n\")\n print(f\"{count} bottles of beer.\\n\")\n print(\"Take one down, pass it around,\\n\")\n else:\n print(f\"{count} bottle of beer on the wall.\\n\")\n print(f\"{count} bottle of beer on the wall,\\n\")\n print(f\"{count} bottle of beer.\\n\")\n print(\"Take it down, pass it around,\\n\")\n print(\"No more bottles of beer on the wall.\\n\")\n\ndef bottles():\n global count\n while count > 1:\n lyrics()\n count -= 1\n print(f\"{count} bottles of beer on the wall.\\n\") if count > 1 else lyrics()\n\nif __name__ == '__main__':\n count = 99\n bottles()\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T16:33:25.253",
"Id": "214254",
"ParentId": "214252",
"Score": "3"
}
},
{
"body": "<ol>\n<li>You have the wrong version of 99 bottles of beers</li>\n<li>Global variables are bad except for constants (and some special cases)</li>\n<li><code>print()</code> is equal to <code>print('')</code> but there are two other amazing solutions.</li>\n<li>If you come from another language, forget all you know about loops</li>\n</ol>\n\n<hr>\n\n<p>1.</p>\n\n<p>Ok the first fix is easy, just add:</p>\n\n<pre><code>No more bottles of beer on the wall, no more bottles of beer. \nGo to the store and buy some more, 99 bottles of beer on the wall.\n</code></pre>\n\n<p>to the end</p>\n\n<p>2.</p>\n\n<p>The second is very important for all your future projects. Use arguments instead of global variables. Using globals is only ok if you define constants of if your script is short, but as soon as your project grows, it will become unmanageable. Globals are also less performant than locals because locals can only be modified in the function itself, that permits the compiler to do assumptions which can't be done with globals. <strong>Avoid globals as much as possible.</strong></p>\n\n<p>3.</p>\n\n<pre><code>print('hello')\nprint('')\n# is the same as\nprint('hello', end='\\n') # '\\n' is a newline which is the default\nprint()\n# which is the same as\nprint('hello')\nprint()\n# which is the same as\nprint('hello', end='\\n\\n')\n# which is the same as\nprint('hello\\n')\n# which is the same as\nprint('he', end='llo')\nprint()\nprint()\n</code></pre>\n\n<p>In summary, either use <code>end='\\n\\n'</code> or append <code>\\n</code> to your string.</p>\n\n<p>4.</p>\n\n<p>In Python, there is this concept of iterable, <code>for i in range(start, end, step)</code> is the way you do the classic looping over integers. <code>range(10)</code> is an iterator that will take all the values from 0 to 9, you know what, lists, tuple, dictionaries files, and even strings are iterables <code>for i in 'babar': print(i)</code>. That's why <code>while</code> loops are less used in python, it is because <strong>iterables are cool, don't use a while</strong>.</p>\n\n<pre><code>def bottles():\n for i in range(99, 1, -1):\n print(f\"{i} bottles of beer on the wall, {i} bottles of beer.\")\n print(f\"Take one down, pass it around, {i-1} bottles of beer on the wall\\n\")\n i -= 1\n print(f\"{i} bottle of beer on the wall, {i} bottle of beer.\")\n print(\"Take it down, pass it around, No more bottles of beer on the wall.\\n\")\n print(\"No more bottles of beer on the wall, no more bottles of beer.\")\n i = 99\n print(f\"Go to the store and buy some more, {i} bottles of beer on the wall.\\n\")\n bottles() # remove this line if you don't like beers\n\nbottles()\n</code></pre>\n\n<hr>\n\n<h3>Update:</h3>\n\n<p>Apparently, OP can't use numbers, this version doesn't contain numbers:</p>\n\n<pre><code>def bottles(count):\n for i in reversed(range(count+True)):\n s='s' if i-True else ''\n print(f\"{i} bottle{s} of beer on the wall, {i} bottle{s} of beer.\")\n if not i-True: break\n print(f\"Take one down, pass it around, {i-1} bottle{s} of beer on the wall\\n\")\n print(\"Take one down, pass it around, no more bottles of beer on the wall\\n\")\n print(\"No more bottles of beer on the wall, no more bottles of beer.\")\n print(f\"Go to the store and buy some more, {count} bottles of beer on the wall.\\n\")\n bottles(count) # If you don't want to go to the store and buy some more remove this line\n\nbottles(99)\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T18:52:47.107",
"Id": "414325",
"Score": "0",
"body": "Thank you, but in the rules of the challange it says that besides \"take one down\" I shouldn't use any number of name of a number."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T18:54:47.873",
"Id": "414326",
"Score": "0",
"body": "You mean no args ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T19:02:44.357",
"Id": "414327",
"Score": "0",
"body": "Sorry, no number or name of a number inside a string. That means that the lines 5 and 8 are incorrect because I have 1 and 99 inside the print function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T19:34:41.730",
"Id": "414334",
"Score": "0",
"body": "Here are the rules of the challenge http://www.reddit.com/r/beginnerprojects/comments/19kxre/project_99_bottles_of_beer_on_the_wall_lyrics/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T21:20:19.153",
"Id": "414343",
"Score": "0",
"body": "I updated the answer so it doesn't use numbers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T05:06:51.113",
"Id": "414374",
"Score": "0",
"body": "Thank you, but it should sound like this: 99 bottles of beer.... Take one down, pass it around 98 (not 99) bottles of beer on the wall."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T18:28:15.187",
"Id": "214260",
"ParentId": "214252",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T16:00:14.310",
"Id": "214252",
"Score": "1",
"Tags": [
"python",
"beginner",
"python-3.x",
"99-bottles-of-beer"
],
"Title": "99 bottles of beer on the wall in Python 3"
} | 214252 |
<p>I created a <a href="https://github.com/sol404/react-context-api-boilerplate/" rel="nofollow noreferrer">boilerplate</a> from <a href="https://github.com/react-boilerplate/react-boilerplate" rel="nofollow noreferrer">react-boilerplate</a>. I have removed <code>redux</code> and <code>immutable</code> for use context API and <code>immer</code>.</p>
<p>I wonder if I use the context API with a good design pattern.</p>
<p>I use like this:</p>
<pre><code>// ./app/containers/LanguageProvider/index.js
import React from 'react';
import PropTypes from 'prop-types';
import { IntlProvider } from 'react-intl';
import {
Context as ContextLanguageProvider,
Consumer as ConsumerLanguageProvider,
} from './Context';
export const LanguageProvider = props => {
const { children, messages } = props;
return (
<ContextLanguageProvider>
<ConsumerLanguageProvider>
{ctx => (
<IntlProvider
locale={ctx.state.locale}
key={ctx.state.locale}
messages={messages[ctx.state.locale]}
>
{React.Children.only(children)}
</IntlProvider>
)}
</ConsumerLanguageProvider>
</ContextLanguageProvider>
);
};
LanguageProvider.propTypes = {
messages: PropTypes.object,
children: PropTypes.element.isRequired,
};
export default LanguageProvider;
</code></pre>
<p>and I created the context API like this:</p>
<pre><code>// ./app/containers/LanguageProvider/Context.js
import React from 'react';
import PropTypes from 'prop-types';
import { initialState, reducer } from './reducer';
const { Provider, Consumer } = React.createContext('languageProvider');
export const Context = props => {
const [state, dispatch] = React.useReducer(reducer, initialState);
const { children } = props;
return (
<Provider value={{ state, dispatch }}>
{React.Children.only(children)}
</Provider>
);
};
Context.propTypes = {
children: PropTypes.element.isRequired,
};
export { Consumer };
</code></pre>
<p>Here the reducer.js and actions.js:</p>
<pre><code>// ./app/containers/LanguageProvider/reducer.js
/* eslint-disable consistent-return,no-param-reassign */
import produce from 'immer';
import { CHANGE_LOCALE } from './constants';
import { DEFAULT_LOCALE } from '../../i18n';
export const initialState = {
locale: DEFAULT_LOCALE,
};
export const reducer = (state = initialState, action) =>
produce(state, draft => {
switch (action.type) {
case CHANGE_LOCALE:
draft.locale = action.locale;
break;
default:
return state;
}
});
// ./app/containers/LanguageProvider/actions.js
import { CHANGE_LOCALE } from './constants';
export function changeLocale(languageLocale) {
return {
type: CHANGE_LOCALE,
locale: languageLocale,
};
}
</code></pre>
<p>I would like to know your reviews on my strategy and how to optimize.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T16:48:38.337",
"Id": "214255",
"Score": "1",
"Tags": [
"react.js",
"jsx"
],
"Title": "React context API design pattern"
} | 214255 |
<p>I've seen this today on a mock interview and wanted to give it a try. I'd love to hear some feedback from you guys. This is my second attempt at the problem, initially I had a mess of <code>if</code>/<code>else</code> towers and nested loops.</p>
<pre><code>/*
* Write a function that takes two strings s1 and s2 and returns the
* longest common subsequences of s1 and s2.
*
* Examples:
* s1: ABAZDC s2: BACBAD result: ABAD
* s1: AGGTAB s2: GXTXAYB result: GTAB
* s1: aaaa s2: aa result: aa
* s1: aaaa s2: '' result: ''
*/
public class LongestSubsequence {
public static void main(String[] args) {
LongestSubsequence ls = new LongestSubsequence();
assertEquals("ABAD", ls.solve("ABAZDC", "BACBAD"));
assertEquals("GTAB", ls.solve("AGGTAB", "GXTXAYB"));
assertEquals("aa", ls.solve("aaaa", "aa"));
assertEquals("", ls.solve("aaaa", ""));
assertEquals("ABAD", ls.solve("BACBAD", "ABAZDC"));
assertEquals("aaaa", ls.solve("bcaaaa", "aaaabc"));
assertEquals("aaaa", ls.solve("bcaaaade", "deaaaabc"));
}
private String solve(String s1, String s2) {
if (s1.length() == 0 || s2.length() == 0) {
return "";
}
String subSeq1 = getLongestSubsequence(s1, s2);
String subSeq2 = getLongestSubsequence(s2, s1);
return (subSeq1.length() >= subSeq2.length() ? subSeq1 : subSeq2);
}
private String getLongestSubsequence(String first, String second) {
String retValue = "";
int currentIndex = 0;
for (int remaining = first.length(); retValue.length() < remaining; remaining--) {
StringBuilder firstWorker = new StringBuilder(first.substring(currentIndex));
StringBuilder secondWorker = new StringBuilder(second);
StringBuilder possibleSequence = new StringBuilder();
while (firstWorker.length() > 0 && secondWorker.length() > 0) {
String ch = firstWorker.substring(0, 1);
int firstIndex = secondWorker.indexOf(ch);
if (firstIndex != -1) {
possibleSequence.append(ch);
secondWorker.delete(0, firstIndex + 1);
}
firstWorker.delete(0, 1);
}
if (possibleSequence.length() > retValue.length()) {
retValue = possibleSequence.toString();
}
currentIndex++;
}
return retValue;
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T19:31:29.647",
"Id": "414332",
"Score": "0",
"body": "Thank you very much, I have checked that discussion and added a few test cases to the code. It's now passing those as well. The solution became a bit more complex as I can now see that O(n) does not seem possible in this case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T19:33:11.163",
"Id": "414333",
"Score": "0",
"body": "I'm now trying in both directions s1 -> s2 and s2 -> s1. I'm also using string builders for efficiency, and deleting chars on s1 as well. The for loop ensures it does not try to find a solution when there are fewer characters than the current solution."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T21:13:19.263",
"Id": "414487",
"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). 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-02-26T21:36:15.563",
"Id": "414489",
"Score": "0",
"body": "Oh, ok, sorry about that."
}
] | [
{
"body": "<h3>Bug</h3>\n<p>Your program fails on this test:</p>\n<pre><code>ls.solve("abddc", "acddb");\n</code></pre>\n<p>Your program finds <code>"ab"</code> and <code>"ac"</code> as the longest subsequences, but the actual answer should be <code>"add"</code>.</p>\n<p>The problem is that your algorithm is greedy, and it will always use any match, even if the match skips over a part that would produce a better answer. In my test case, the <code>b</code> in the first string matches the <code>b</code> at the end of the second string, thereby skipping over the <code>dd</code> in the middle.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T21:11:39.430",
"Id": "414485",
"Score": "0",
"body": "Thanks, nice catch! I have edited the code to account for that test case. The complexity has now increased considerably from quadratic to cubic. In my tests performance starts to suffer when there are over 300 characters in a word. I need to think a bit more if there's a way to improve performance, or hopefully get it back to quadratic time complexity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-27T09:31:19.567",
"Id": "414571",
"Score": "1",
"body": "@fpezzini maybe you should think about a dynamic programming solution. After all, you tagged this question with \"dynamic programming\" but your solution makes no use of it."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T02:55:36.807",
"Id": "214291",
"ParentId": "214256",
"Score": "4"
}
},
{
"body": "<p>The method name <code>solve</code> does not describe what the method is doing. There should be a method <code>public static String longestCommonSubsequence(String a, String b)</code>, and the class containing that method should be called <code>StringUtils</code>.</p>\n\n<p>After making the method <code>static</code>, there's no reason to call <code>new LongestSubsequence</code> any longer since that object doesn't provide anything useful.</p>\n\n<p>The variable name <code>ch</code> is usually used for characters, not for strings. It creates unnecessary confusion here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T21:12:32.443",
"Id": "414486",
"Score": "0",
"body": "Thanks a lot for the feedback. I have renamed the method to \"find\" which is more descriptive of what it does. When you call longestSubsequence.find it will make sense. I like to have a class having a single responsibility."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T03:38:44.440",
"Id": "214293",
"ParentId": "214256",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T17:26:34.363",
"Id": "214256",
"Score": "3",
"Tags": [
"java",
"interview-questions",
"dynamic-programming"
],
"Title": "Longest common subsequence solution"
} | 214256 |
<p>For my game engine I needed a simple templated array class that can be safely passed across module boundaries. It's not supposed to be a replacement for std::vector and thus doesn't need all of its features. Instead it is intended to be used in the interface where binary compatibility is important.
For malloc and free I use wrapper functions that are exported from my main core library but in order to have a working example I replaced them with the standard functions here.</p>
<pre><code>#pragma once
#include <cstdint>
#include <cassert>
#include <type_traits>
//#include "memory.h"
// memory.h
//==========================================
namespace lel::core{
inline void* checked_malloc(std::size_t size){
auto mem = malloc(size);
if(!mem)
throw std::bad_alloc;
return mem;
}
inline void checked_free(void*& ptr){
if(ptr)
free(ptr);
ptr = nullptr;
}
}
//==========================================
namespace lel::core{
template<typename T>
struct Array{
using SizeType = std::int32_t; // Must be signed because the scripting language has no unsigned integers
using Iterator = T*;
using ConstIterator = const T*;
Array(SizeType initialSize = 0){
assert(initialSize >= 0);
data = checked_malloc(initialSize * sizeof(T) + sizeof(T));
arraySize = initialSize;
capacity = arraySize;
init(0, size());
}
Array(const Array& other){ *this = other; }
Array& operator=(const Array& other){
resize(other.size());
for(SizeType i = 0; i < size(); ++i)
(*this)[i] = other[i];
return *this;
}
~Array(){
deinit(0, size());
checked_free(data);
}
SizeType size() const noexcept{ return arraySize; }
T& operator[](SizeType index) noexcept{ return static_cast<T*>(data)[index]; }
const T& operator[](SizeType index) const noexcept{ return static_cast<T*>(data)[index]; }
void resize(SizeType newSize){
if(newSize > 0){
if(newSize <= arraySize){
arraySize = newSize;
deinit(newSize, arraySize - newSize);
}else{
if(newSize <= capacity){
init(arraySize, newSize - arraySize);
arraySize = newSize;
}else{
auto newCapacity = static_cast<SizeType>(newSize * 1.25f + 1.0f);
Array tmp;
tmp.data = checked_malloc(newCapacity * sizeof(T) + sizeof(T));
tmp.arraySize = newSize;
tmp.capacity = newCapacity;
for(SizeType i = 0; i < size(); ++i)
new(&tmp[i]) T{(*this)[i]};
deinit(0, size());
checked_free(data);
data = tmp.data;
tmp.data = nullptr;
arraySize = tmp.size();
tmp.arraySize = 0;
capacity = tmp.capacity;
tmp.capacity = 0;
}
}
}else{
deinit(0, size());
arraySize = 0;
}
}
void push_back(const T& t){
resize(size() + 1);
back() = t;
}
void clear(){
deinit(0, size());
checked_free(data);
arraySize = 0;
capacity = 0;
data = checked_malloc(sizeof(T)); // For the end iterator
}
T& back() noexcept{ return (*this)[size() - 1]; }
const T& back() const noexcept{ return (*this)[size() - 1]; }
void pop_back(){ resize(size() - 1); }
void emplace_back(){ push_back(T{}); }
Iterator begin() noexcept{ return &(*this)[0]; }
ConstIterator begin() const noexcept{ return &(*this)[0]; }
Iterator end() noexcept{ return &(*this)[size()]; }
ConstIterator end() const noexcept{ return &(*this)[size()]; }
private:
void* data = nullptr;
SizeType arraySize = 0;
SizeType capacity = 0;
void init(SizeType startIndex, SizeType num){
for(SizeType i = 0; i < num; ++i)
new(&(*this)[startIndex + i]) T{};
}
void deinit(SizeType startIndex, SizeType num){
if constexpr(!std::is_trivially_destructible<T>{}){
for(SizeType i = 0; i < num; ++i)
std::destroy_at(&(*this)[startIndex + i]);
}
}
static constexpr void static_assertions() noexcept{
static_assert(std::is_standard_layout<Array<T>>{});
static_assert(std::is_standard_layout<T>{});
}
};
}
<span class="math-container">```</span>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-28T12:52:41.163",
"Id": "414719",
"Score": "0",
"body": "You have a bug in your `resize` function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-28T12:59:33.177",
"Id": "414720",
"Score": "0",
"body": "Hint: check what happens when `newSize` <= `arraySize`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-28T20:09:14.143",
"Id": "414802",
"Score": "0",
"body": "@MikeBorkland You're right! Thanks a lot for pointing that out. It also made me realize that I don't even need the outermost if."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T18:25:24.210",
"Id": "214259",
"Score": "1",
"Tags": [
"c++",
"array",
"template"
],
"Title": "Simple dynamic array template"
} | 214259 |
<p>I have a time series data in long format which looks like as follows:</p>
<pre><code>+======+==========+======+======+
| Name | Date | Val1 | Val2 |
+======+==========+======+======+
| A | 1/1/2018 | 1 | 2 |
+------+----------+------+------+
| B | 1/1/2018 | 2 | 3 |
+------+----------+------+------+
| C | 1/1/2018 | 3 | 4 |
+------+----------+------+------+
| D | 1/4/2018 | 4 | 5 |
+------+----------+------+------+
| A | 1/4/2018 | 5 | 6 |
+------+----------+------+------+
| B | 1/4/2018 | 6 | 7 |
+------+----------+------+------+
| C | 1/4/2018 | 7 | 8 |
+------+----------+------+------+
</code></pre>
<p>I need to convert the above data into wide format which like as follows:</p>
<pre><code>+---+---------------+---------------+---------------+---------------+---------------+---------------+---------------+---------------+
| | Val1.1/1/2018 | Val2.1/1/2018 | Val1.1/2/2018 | Val2.1/2/2018 | Val1.1/3/2018 | Val2.1/3/2018 | Val1.1/4/2018 | Val2.1/4/2018 |
+---+---------------+---------------+---------------+---------------+---------------+---------------+---------------+---------------+
| A | 1 | 2 | NULL | NULL | NULL | NULL | 5 | 6 |
| B | 2 | 3 | NULL | NULL | NULL | NULL | 6 | 7 |
| C | 3 | 4 | NULL | NULL | NULL | NULL | 7 | 8 |
| D | NULL | NULL | NULL | NULL | NULL | NULL | 4 | 5 |
+---+---------------+---------------+---------------+---------------+---------------+---------------+---------------+---------------+
</code></pre>
<p>To achieve that I've followed the following steps</p>
<p>First I've converted my initial data set date column to date format and added dates ranging from <code>01/01/2018</code> to <code>01/04/2018</code> in long format since I am dealing with time series data, I would want dates <code>01/02/2018</code> and <code>01/03/2018</code> to be included in wide format table even though those columns would contain NaNs. </p>
<p>To achieve the above mentioned task I've used the following code:</p>
<pre><code>df = pd.read_csv('data.csv')
df['Date'] = pd.to_datetime(df['Date'], format='%m/%d/%Y')
idx = pd.MultiIndex.from_product([df.Name.unique(), pd.date_range(df.Date.min(), df.Date.max())])
df = df.set_index(['Name','Date']).reindex(idx).reset_index().rename(columns = {'level_0':'Name', 'level_1':'Date'})
df.Date = df.Date.dt.strftime('%m/%d/%Y')
new_df = df.pivot('Name', 'Date', ['Val1', 'Val2'])
new_df.columns = new_df.columns.map('.'.join)
</code></pre>
<p><strong>I think the above code is not optimized to deal with larger data set (1.2 millions rows). How could I go about optimizing this code?</strong></p>
<p>The similar task done in R with the follwing code takes much lesser time:</p>
<pre><code>library(dplyr)
library(tidyr) #complete
library(data.table) #dcast and setDT
df %>% mutate(Date=as.Date(Date,'%m/%d/%Y')) %>%
complete(Name, nesting(Date=full_seq(Date,1))) %>%
setDT(.) %>% dcast(Name ~ Date, value.var=c('Val2','Val1'))
</code></pre>
<p><strong>Credits</strong>: Python code mentioned in this post is taken from <a href="https://stackoverflow.com/questions/54844453/pandas-data-frame-convert-data-in-long-format-to-wide-format-for-specific-date-r">here</a>.
R code mentioned in this post is taken from <a href="https://stackoverflow.com/questions/54780577/creating-time-series-columns-in-r-from-long-to-wide-format-considering-date-rang">here</a>.</p>
| [] | [
{
"body": "<h2>Solution in R</h2>\n\n<p>In your last code snippet, you're mixing code from tidyverse and data.table packages. I don't consider this to be completely wrong, but I would rather avoid it to increase readability and consistency. </p>\n\n<pre class=\"lang-r prettyprint-override\"><code>library(magrittr)\nlibrary(data.table)\nlibrary(bench)\n\n# data copied from OP\ndat <- structure(list(Name = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L),\n .Label = c(\"A\", \"B\", \"C\", \"D\"),\n class = \"factor\"),\n Date = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 2L),\n .Label = c(\"1/1/2018\", \"1/4/2018\"),\n class = \"factor\"), \n Val1 = 1:7,\n Val2 = 2:8),\n class = \"data.frame\", row.names = 1:7)\n\ndat\n#> Name Date Val1 Val2\n#> 1 A 1/1/2018 1 2\n#> 2 B 1/1/2018 2 3\n#> 3 C 1/1/2018 3 4\n#> 4 D 1/4/2018 4 5\n#> 5 A 1/4/2018 5 6\n#> 6 B 1/4/2018 6 7\n#> 7 C 1/4/2018 7 8\nstr(dat)\n#> 'data.frame': 7 obs. of 4 variables:\n#> $ Name: Factor w/ 4 levels \"A\",\"B\",\"C\",\"D\": 1 2 3 4 1 2 3\n#> $ Date: Factor w/ 2 levels \"1/1/2018\",\"1/4/2018\": 1 1 1 2 2 2 2\n#> $ Val1: int 1 2 3 4 5 6 7\n#> $ Val2: int 2 3 4 5 6 7 8\n</code></pre>\n\n<h3>Tidyverse Solution</h3>\n\n<pre class=\"lang-r prettyprint-override\"><code>tidyr::gather(dat, key = \"key\", value = \"value\", -Date, -Name) %>% \n tidyr::unite(\"id\", key, Date, sep = \".\") %>% \n tidyr::spread(id, value)\n#> Name Val1.1/1/2018 Val1.1/4/2018 Val2.1/1/2018 Val2.1/4/2018\n#> 1 A 1 5 2 6\n#> 2 B 2 6 3 7\n#> 3 C 3 7 4 8\n#> 4 D NA 4 NA 5\n</code></pre>\n\n<h3>data.table Solution</h3>\n\n<pre class=\"lang-r prettyprint-override\"><code>dt <- data.table(dat)\ndt_long <- melt(dt, id.vars = c(\"Name\", \"Date\"))\n\ndcast(dt_long, Name ~ variable + Date)\n#> Name Val1_1/1/2018 Val1_1/4/2018 Val2_1/1/2018 Val2_1/4/2018\n#> 1: A 1 5 2 6\n#> 2: B 2 6 3 7\n#> 3: C 3 7 4 8\n#> 4: D NA 4 NA 5\n</code></pre>\n\n<h3>Benchmark</h3>\n\n<p>As you can see, data.table is already much faster with 1,200 rows.</p>\n\n<pre class=\"lang-r prettyprint-override\"><code>nrows <- 1.2e4\n# nrows <- 1.2e6\ndat2 <- expand.grid(Name = LETTERS[1:4],\n Date = seq(as.Date(\"2018-01-01\"), by = \"days\", length.out = nrows/4))\ndat2$Val1 <- sample(1:8, nrow(dat2), TRUE)\ndat2$Val2 <- sample(1:8, nrow(dat2), TRUE)\n\nf1 <- function(dat) {\n tidyr::gather(dat, key = \"key\", value = \"value\", -Date, -Name) %>% \n tidyr::unite(\"id\", key, Date, sep = \".\") %>% \n tidyr::spread(id, value)\n}\n\nf2 <- function(dat) {\n dt <- data.table(dat)\n dt_long <- melt(dt, id.vars = c(\"Name\", \"Date\"))\n dt_wide <- dcast(dt_long, Name ~ variable + Date)\n}\n\nmark(tidyverse = f1(dat2),\n datatable = f2(dat2),\n check = function(x, y) all.equal(x, y, check.attributes = FALSE))\n#> Warning: Some expressions had a GC in every iteration; so filtering is\n#> disabled.\n#> # A tibble: 2 x 10\n#> expression min mean median max `itr/sec` mem_alloc n_gc\n#> <chr> <bch:t> <bch:t> <bch:t> <bch:t> <dbl> <bch:byt> <dbl>\n#> 1 tidyverse 184.4ms 189.7ms 187.9ms 196.7ms 5.27 15.73MB 5\n#> 2 datatable 43.1ms 45.9ms 45.4ms 51.7ms 21.8 5.36MB 2\n#> # ... with 2 more variables: n_itr <int>, total_time <bch:tm>\n</code></pre>\n\n<p><sup>Created on 2019-02-26 by the <a href=\"https://reprex.tidyverse.org\" rel=\"nofollow noreferrer\">reprex package</a> (v0.2.1)</sup></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T09:14:35.587",
"Id": "414389",
"Score": "0",
"body": "I appreciate your response, but I am looking for an optimized version in Python."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T10:13:17.143",
"Id": "414398",
"Score": "0",
"body": "Alright. Then you should mention that in your question. Consider to add a bold one-liner stating what your question actually is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T10:24:16.690",
"Id": "414399",
"Score": "1",
"body": "I suppose it's clearly mentioned in the post as there is only one sentence followed by a question mark. I've added a bold to that line in my edit."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T09:00:16.347",
"Id": "214307",
"ParentId": "214261",
"Score": "-1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T18:31:15.983",
"Id": "214261",
"Score": "3",
"Tags": [
"python",
"pandas"
],
"Title": "Producing a Pandas Data Frame from Long to Wide format Efficiently"
} | 214261 |
<p>Quite often, I find myself measuring how long some part of my code takes to complete. I normally do that by storing current time using <code>time.time()</code> and then subtracting time after the code is done.</p>
<p>This normally gives me a float that I can then format and print for debugging purposes. This is the function that I have for time formatting:</p>
<pre><code>def time_format(delta: float) -> str:
output = []
decimal, integer = math.modf(delta)
if integer:
minutes, seconds = divmod(int(integer), 60)
if minutes:
output.append("%sm" % minutes)
if seconds:
output.append("%ss" % seconds)
decimal, integer = math.modf(decimal * 1000)
if integer:
output.append("%sms" % int(integer))
decimal, integer = math.modf(decimal * 1000)
if integer:
output.append("%sμs" % int(integer))
decimal, integer = math.modf(decimal * 1000)
if integer:
output.append("%sns" % int(integer))
return ", ".join(output)
</code></pre>
<p>I have also been told that the time module has most precision when it comes to time measuring so that's why I'm using it, instead of something like datetime which has nice formatting tools built in.</p>
<p>How could I improve my time formatting function? Are there any built in formatting tools that I'm not aware of? (Searching stack overflow leads me only to questions about datetime.timedelta)</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T20:32:38.630",
"Id": "414338",
"Score": "0",
"body": "Hello and welcome to CR! You might be interested in [this](https://codereview.stackexchange.com/questions/169870/decorator-to-measure-execution-time-of-a-function/169876#169876) as well"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T20:54:37.857",
"Id": "414342",
"Score": "0",
"body": "I agree that timeit is great for measuring the time it takes for a function, but I'm more interested in measuring time between two arbitrary points in my code, sometimes hundred lines appart. My current approach allows to add/remove code to what I'm measuring by simply shifting the time measuring lines around. I'm not sure if that's possible with timeit module."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T21:42:56.030",
"Id": "414347",
"Score": "0",
"body": "It might be overkill but I suggest profilers like [this one](https://github.com/rkern/line_profiler) and [whatever this graph thing is called](https://github.com/jrfonseca/gprof2dot)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T07:10:45.747",
"Id": "414376",
"Score": "0",
"body": "Did you know you can build a `timedelta(seconds=delta)` and work from there?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T07:14:28.770",
"Id": "414377",
"Score": "0",
"body": "Yeah but I'm more interested in the formatting of the float part of the delta which isn't really suported by the timedelta object."
}
] | [
{
"body": "<p>There is indeed a function for that.</p>\n\n<pre><code>>>> from datetime import timedelta \n>>> print(timedelta(seconds=1239.123456))\n0:20:39.123456\n</code></pre>\n\n<p>Now, if I understand you correctly, you want a divider for the millisecond.</p>\n\n<pre><code>from datetime import timedelta \ndef f(secs):\n t=str(timedelta(seconds=secs))\n index = t.find('.') + 4\n return t[:index] + ' ' + t[index:]\nprint(f(1239.123456))\n# 0:20:39.123 456\n</code></pre>\n\n<p>I don't like that everything is hardcoded, if you want to use it for different applications (or even languages), you might want to generalize your bases and names. </p>\n\n<p>Here is a generic way of doing any formatting you want:</p>\n\n<pre><code>def prod(f):\n total = 1\n l = [1]\n for i in range(len(f)-1, 0, -1):\n total *= f[i][0]\n l.append(total)\n return reversed(l)\n\n\ndef format_time(number, f=((24, ':'), (60, ':'), (60, '.'), (1000, ' '), (1000, ''))):\n return ''.join(\n (f\"{(number//div)%base:0>{len(str(base-1))}}\" + delimiter)\n if number//div else ''\n for div, (base, delimiter) in zip(prod(f), f)\n )\n</code></pre>\n\n<pre><code>formatting = (\n (24, ' hours '),\n (60, ' minutes '),\n (60, ' seconds '),\n (1000, ' milliseconds '),\n (1000, ' nanoseconds'),\n)\n\nprint(\n format_time(1551198373998173),\n format_time(1551198373998173, formatting),\n format_time(1551739, formatting),\n sep=\"\\n\"\n)\n</code></pre>\n\n<p>The result is:</p>\n\n<pre><code>16:26:13.998 173\n16 hours 26 minutes 13 seconds 998 milliseconds 173 nanoseconds\n01 seconds 551 milliseconds 739 nanoseconds\n</code></pre>\n\n<p>What are it's advantages, you can do any formatting in any base, with any names. We could even do a base 2 converter.</p>\n\n<pre><code>binary_formatting = (((2, ' '),)+((2, ''),)*3)*10 + ((2, ''),)\n\nprint(\n format_time(155933900, binary_formatting),\n format_time(3279, binary_formatting),\n sep=\"\\n\"\n)\n</code></pre>\n\n<pre><code>1001 0100 1011 0101 1100 1100 1100\n1100 1100 1111\n</code></pre>\n\n<p>Other than that, if your code need to accomplish a single purpose and it does it well, good for you.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T21:59:42.050",
"Id": "414353",
"Score": "0",
"body": "As I wrote in my question, I'm fully aware that you can format the timedelta object, however precision is important for me, which is why I wrote my own formatter since timedelta doesn't have an in-built formatting for small time deltas (<1 sec). There's not much difference between simply printing 0.000123 and 0:00:00.000123 (the \"formatted\" version)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T17:03:55.093",
"Id": "414442",
"Score": "0",
"body": "I updated my answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T17:36:58.710",
"Id": "414449",
"Score": "0",
"body": "Your answer does produce similar behaviour to my formatting function (though hours, minutes etc still appear even if equal to 0) but I'm more or less looking for criticizm about my own formatter instead of writing a brand new one."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T18:01:11.297",
"Id": "414458",
"Score": "0",
"body": "I've updated my code to fix that. If your code does what you want it to do, that's good, I was just showing how I would have done it and why."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T21:53:15.630",
"Id": "214276",
"ParentId": "214268",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "214276",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T20:01:06.347",
"Id": "214268",
"Score": "3",
"Tags": [
"python",
"python-3.x",
"datetime",
"formatting"
],
"Title": "Formatting time delta"
} | 214268 |
<p>This is another review on <a href="https://codereview.stackexchange.com/questions/156651/fixing-medical-claim-files-through-text-file-read-write">a program I've asked about before</a>, with a different target in mind.</p>
<hr>
<p><strong>Program Function</strong></p>
<p>As before, this program makes emergency changes to medical claim files, delivers all the corrected files analysts need, and produces a changelog as well for their review. </p>
<hr>
<p><strong>Core Problem</strong> - <em>tl;dr Use of dictionary containing dozens of different classes is neutering important IDE tools</em></p>
<p>Each medical file fix I develop gets its own class. Originally, every class was initialized and used in the core procedure <code>FixTextFiles</code>.</p>
<p>As the number of fixes expanded into the dozens, this became bothersome. 3/4 of my core procedure (by lines of code) was taken up by initializing dozens of classes, most of which would not even be used that run.</p>
<p>I solved this issue by making an <code>ActiveFixes</code> class with a <code>dictFixClassesByFixName</code> dictionary that took care of class initialization and trimmed things down to the classes that would actually be used that run.</p>
<p>I refer to this dictionary constantly throughout my code, but this design prevents me from using the VBEditor's compilation and <a href="https://github.com/rubberduck-vba/Rubberduck" rel="nofollow noreferrer">Rubberduck VBA</a>'s code analysis tools to spot easy errors, like missing arguments for methods of the classes in the dictionary, before running the actual program. It's making testing way harder than it needs to be.</p>
<hr>
<p><strong>Main Question</strong></p>
<p>How would you redesign this part of the program knowing:</p>
<ul>
<li>There's dozens of fixes, each with its own class, unique methods, etc.</li>
<li>No more than 1-4 will be active at a time (user-selected)</li>
<li>I want the IDE's tools to be able function well enough to throw compile errors if I misspell a method name or if I'm missing arguments</li>
</ul>
<hr>
<p><strong>classActiveFixes</strong> - <em>class names changed to protect the innocent</em></p>
<pre><code>Option Explicit
Private pdictFixClassesByFixName As Scripting.Dictionary
'pdictFixClassesByFixName Properties
Public Property Get dictFixClassesByFixName() As Scripting.Dictionary
Set dictFixClassesByFixName = pdictFixClassesByFixName
End Property
Public Property Set dictFixClassesByFixName(ByVal dictFixClassesByFixName As Scripting.Dictionary)
Set pdictFixClassesByFixName = dictFixClassesByFixName
End Property
Public Sub Setup(ByVal ActiveFixes As classActiveFixes)
Dim dictAllFixClassesByFixName As Scripting.Dictionary
Set dictAllFixClassesByFixName = GetAllFixesDictionary
dictAllFixClassesByFixName.CompareMode = TextCompare
Set ActiveFixes.dictFixClassesByFixName = New Scripting.Dictionary
ActiveFixes.dictFixClassesByFixName.CompareMode = TextCompare
With SelectFixes
Dim rngSelectFixesTable As Range
Set rngSelectFixesTable = .Range(.Cells(5, 1), .Cells(GetLastRowOfSheetInColumn(SelectFixes, 1), 1))
End With
Dim rngFix As Range
For Each rngFix In rngSelectFixesTable
If SelectFixes.Shapes("ToggleBackground" & rngFix.Row - 4).TextFrame.Characters.Text = "On" Then
If ActiveFixes.dictFixClassesByFixName.Exists(rngFix.Value) = False Then
ActiveFixes.dictFixClassesByFixName.Add rngFix.Value, dictAllFixClassesByFixName.Item(rngFix.Value)
If rngFix.Offset(0, 2).Value <> vbNullString Then
Set ActiveFixes.dictFixClassesByFixName.Item(rngFix.Value).shtSettings = ThisWorkbook.Worksheets(rngFix.Offset(0, 2).Value)
End If
End If
End If
Next rngFix
ActiveFixes.dictFixClassesByFixName.Add "Special Always On Fix", dictAllFixClassesByFixName.Item("Special Always On Fix")
PerFixSetup ActiveFixes
End Sub
Private Function GetAllFixesDictionary() As Scripting.Dictionary
Dim dictAllFixes As Scripting.Dictionary
Set dictAllFixes = New Scripting.Dictionary
dictAllFixes.CompareMode = TextCompare
Dim Fix1 As classFix1
Set Fix1 = New classFix1
dictAllFixes.Add "Fix1", Fix1
Dim Fix2 As classFix2
Set Fix2 = New classFix2
dictAllFixes.Add "Fix2", Fix2
...
Dim FixN As classFixN
Set FixN = New classFixN
dictAllFixes.Add "FixN", FixN
Dim FixSpecialAlwaysOn As classFixSpecialAlwaysOn
Set FixSpecialAlwaysOn = New classFixSpecialAlwaysOn
dictAllFixes.Add "Special Always On Fix", FixSpecialAlwaysOn
Set GetAllFixesDictionary = dictAllFixes
End Function
Private Function GetLastRowOfSheetInColumn(ByVal shtInQuestion As Worksheet, ByVal lngColumnInQuestion As Long) As Long
With shtInQuestion
'Using the end up method on a full sheet will go to the top
If .Cells(.Rows.Count, lngColumnInQuestion).Value <> vbNullString Then
GetLastRowOfSheetInColumn = .Rows.Count
Else
GetLastRowOfSheetInColumn = .Cells(.Rows.Count, lngColumnInQuestion).End(xlUp).Row
End If
End With
End Function
Private Sub PerFixSetup(ByVal ActiveFixes As classActiveFixes)
'Not every class has a setup method
If ActiveFixes.dictFixClassesByFixName.Exists("Fix3") = True Then
ActiveFixes.dictFixClassesByFixName("Fix3").Setup ActiveFixes.dictFixClassesByFixName("Fix3")
End If
If ActiveFixes.dictFixClassesByFixName.Exists("Fix5") = True Then
ActiveFixes.dictFixClassesByFixName("Fix5").Setup ActiveFixes.dictFixClassesByFixName("Fix5")
End If
...
If ActiveFixes.dictFixClassesByFixName.Exists("FixN-3") = True Then
ActiveFixes.dictFixClassesByFixName("FixN-3").Setup ActiveFixes.dictFixClassesByFixName("FixN-3")
End If
End Sub
</code></pre>
<hr>
<p><strong>M0FixTextFiles</strong></p>
<pre><code>Public Sub FixTextFiles(Optional ByVal folderSourceFiles As Scripting.Folder = Nothing, Optional ByVal strFixName As String = vbNullString, Optional ByVal strNewLineDelimiter As String = vbNullString, Optional ByVal strNewClaimDelimiter As String = vbNullString, Optional ByVal folderDestination As Scripting.Folder = Nothing)
'
' Keyboard Shortcut: Ctrl+Shift+Q
Dim strLines() As String 'The original file as an array where each line is an array item
Dim strLines2() As String 'The revised file as an array where each line is an array item
Dim lngCurrentLineNumber As Long
Dim strCurrentLine As String
If OkayToDeleteOldResults(folderSourceFiles Is Nothing) = False Then Exit Sub
If Not (folderSourceFiles Is Nothing) Then
TurnOffAllFixesExceptParameterFix strFixName
GetCellWithValueInRange(InstructionsAndOptions.Columns(11), "New Line Delimiter:", True).Offset(0, 1).Value = strNewLineDelimiter
GetCellWithValueInRange(InstructionsAndOptions.Columns(11), "New Claim Delimiter:", True).Offset(0, 1).Value = strNewClaimDelimiter
GetCellWithValueInRange(InstructionsAndOptions.Columns(11), "Create Changelog Sheets:", True).Offset(0, 1).Value = "No"
End If
Dim ActiveFixes As classActiveFixes
Set ActiveFixes = New classActiveFixes
ActiveFixes.Setup ActiveFixes
If ActiveFixes.dictFixClassesByFixName.Count = 0 Then
MsgBox "No fixes active."
Exit Sub
End If
'--- Preparation ---
'Speed Enhancers
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Dim Model As classModel
Set Model = New classModel
Model.Setup
'-- Select Files --
Dim varFiles As Variant
If folderSourceFiles Is Nothing Then
MsgBox "Select all of your files (use Ctrl-A in the folder or Ctrl-left mouse button)."
Dim dialogFilePicker As FileDialog
Set dialogFilePicker = Application.FileDialog(msoFileDialogFilePicker)
With dialogFilePicker
.AllowMultiSelect = True
.Title = "Select files to fix"
If .Show = False Then CancelFixTextFiles
End With
Set varFiles = dialogFilePicker.SelectedItems
Else
Set varFiles = folderSourceFiles.Files
End If
Dim varFile As Variant
For Each varFile In varFiles
Dim FSO As Scripting.FileSystemObject
Set FSO = New Scripting.FileSystemObject
Dim fileCurrent As Scripting.File
Set fileCurrent = FSO.GetFile(varFile)
'--- Parse File ---
Dim strEntireFile As String
strEntireFile = SaveFileToString(fileCurrent)
If strEntireFile <> vbNullString Then
'File not delimited properly
If InStr(1, strEntireFile, Model.strNewLineDelimiter, vbTextCompare) > 0 Then
'Eliminate blank line(s) at end of file, if any, for easier parsing
Do Until Right(strEntireFile, 1) <> Model.strNewLineDelimiter
strEntireFile = Left(strEntireFile, Len(strEntireFile) - 1)
Loop
strLines() = Split(strEntireFile, Model.strNewLineDelimiter)
strLines2() = Split(strEntireFile, Model.strNewLineDelimiter)
'--- Begin File Manipulation ---
For lngCurrentLineNumber = LBound(strLines) To UBound(strLines) 'For some reason is 1-based
'Progress Tracker
Application.StatusBar = lngCurrentLineNumber & " / " & UBound(strLines)
If Right(lngCurrentLineNumber, 3) = "000" Then DoEvents
'--- Ongoing variables ---
'Current line
strCurrentLine = strLines(lngCurrentLineNumber)
'Segment type
Dim strSegmentType As String
If InStr(1, strCurrentLine, "*", vbTextCompare) = 0 Then
strSegmentType = vbNullString
Else
strSegmentType = Left(strCurrentLine, InStr(1, strCurrentLine, "*", vbTextCompare) - 1)
End If
'--- Fixes ---
'Note: the weird structures below occur because VBA doesn't support short-circuit evaluation
If ActiveFixes.dictFixClassesByFixName.Exists("Fix1") = True Then
If strSegmentType = "A" Then
strLines2(lngCurrentLineNumber) = ActiveFixes.dictFixClassesByFixName("Fix1").Fix1Method1(strCurrentLine, lngHLCount, lngLastHLBilling)
End If
End If
...
'Special Always On Fix
If strSegmentType = "B" Then ActiveFixes.dictFixClassesByFixName("Special Always On Fix").FixSpecialAlwaysOnProperty1 = ActiveFixes.dictFixClassesByFixName("Special Always On Fix").GetProperty1Value(strCurrentLine)
End If
Next lngCurrentLineNumber
If Model.boolCreateChangelogSheets = True Then WriteOriginalAndUpdatedSegmentsToWorksheetAndHighlightDifferences strLines, strLines2, fileCurrent
WriteUpdatedSegmentsToNewFile strLines2, Model.strNewLineDelimiter, fileCurrent, folderDestination
Else
Dim strTempDelimiter As String
strTempDelimiter = Model.strNewLineDelimiter
If strTempDelimiter = vbCrLf Then strTempDelimiter = "vbCrLf"
If strTempDelimiter = vbCr Then strTempDelimiter = "vbCr"
If strTempDelimiter = vbLf Then strTempDelimiter = "vbLf"
MsgBox fileCurrent.Name & " was skipped because it is not delimited with " & strTempDelimiter & ". Either wrap the file in this character or change the setting on the " & InstructionsAndOptions.Name & " sheet."
End If
End If
Next varFile
'-- All Done --
If folderSourceFiles Is Nothing Then MsgBox "All files have been fixed and saved to the same folders as the source files with " & """" & "Fixed" & """" & " added to their filenames. No original files have been modified."
Application.StatusBar = False
Application.ScreenUpdating = True
Application.Calculation = xlAutomatic
End Sub
</code></pre>
<hr>
<p><strong>classFix3</strong> - Sample posted per @Comintern's request</p>
<pre><code>Option Explicit
Private pshtSettings As Worksheet
Private pdictReplacementCrosswalk As Scripting.Dictionary
'pshtSettings Properties
Public Property Get shtSettings() As Worksheet
Set shtSettings = pshtSettings
End Property
Public Property Set shtSettings(ByVal shtSettings As Worksheet)
Set pshtSettings = shtSettings
End Property
'pdictReplacementCrosswalk Properties
Public Property Get dictReplacementCrosswalk() As Scripting.Dictionary
Set dictReplacementCrosswalk = pdictReplacementCrosswalk
End Property
Private Property Set dictReplacementCrosswalk(ByVal dictReplacementCrosswalk As Scripting.Dictionary)
Set pdictReplacementCrosswalk = dictReplacementCrosswalk
End Property
Public Sub Setup(ByVal Fix3 As classFix3)
With Fix3.shtSettings
'Dictionary initialization
Set dictReplacementCrosswalk = New Scripting.Dictionary
dictReplacementCrosswalk.CompareMode = vbTextCompare
Dim lngNumberOfClaims As Long
lngNumberOfClaims = WorksheetFunction.CountA(.Columns(1))
'Warning if settings sheet empty
If lngNumberOfClaims < 2 Then 'There are headers on this sheet
MsgBox "Fix 3 option is ON, but a crosswalk cannot be detected when searching Column 1 of the " & Fix3.shtSettings.Name & " sheet."
CancelFixTextFiles
Else
Dim arrSubstitutions As Variant
Set arrSubstitutions = ConvertRangeToArray(.Range(.Cells(2, 1), .Cells(lngNumberOfClaims, 16)))
End If
'Populate dictionary from info
Dim lngIndex As Long
For lngIndex = LBound(arrSegmentSubstitutions, 1) To UBound(arrSegmentSubstitutions, 1)
dictSegmentReplacementCrosswalk.Add Key:=arrSegmentSubstitutions(lngIndex, 1), Item:=arrSegmentSubstitutions(lngIndex, 2)
Next lngIndex
End With
End Sub
Public Function FixLine(ByVal strCurrentLine As String) As String
Dim strFixedLine As String
strFixedLine = strCurrentLine
'XXXXX
If Left(strCurrentLine, 5) = "XXXXX" Then
If Right(strCurrentLine, 2) = "YY" Then
strFixedLine = Left(strFixedLine, Len(strFixedLine) - 2) & "16"
Else
MsgBox "XXXXX segment that doesn't end with YY found"
End If
End If
'Crosswalk replacement
If Left(strCurrentLine, 7) = "XXXXXXX" Then strFixedLine = dictReplacementCrosswalk.Item(strCurrentLine)
FixLine = strFixedLine
End Function
Private Function ConvertRangeToArray(ByVal rngInQuestion As Range) As Variant
Dim arrRangeToArray() As Variant
With rngInQuestion
If .Cells.Count = 1 Then
ReDim arrRangeToArray(1 To 1, 1 To 1)
arrRangeToArray(1, 1) = .Cells(1, 1).Value
Else
arrRangeToArray = .Value
End If
End With
ConvertRangeToArray = arrRangeToArray
End Function
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T21:30:18.553",
"Id": "414344",
"Score": "0",
"body": "Do you have a link to the original code or something similar? What do the ellipses represent? Is there a sample of a \"classFix1\" that you can share?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T21:33:58.530",
"Id": "414345",
"Score": "0",
"body": "@Comintern I'm happy to help however I can. The ellipses represent the same pattern continued through several dozen fixes. I'm happy to expand on the above however you'd like though I don't have a link directly to the original code just because this is for work so I need to be abstract - just let me know what you'd like to see and I'll get you an abstraction. Posting a sample class now per your request."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T21:45:55.170",
"Id": "414348",
"Score": "0",
"body": "Excuse me, not an abstraction unless it just repeats something 3 dozen times - I meant an anonymized form."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T21:46:10.380",
"Id": "414349",
"Score": "0",
"body": "Are the other \"fixes\" similar to that one? I.e., one method that actually performs the fix and maybe a handful of utilities?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T21:54:01.220",
"Id": "414350",
"Score": "0",
"body": "@Comintern It varies. I have about 7 common methods and 95% of the fixes are some mix of those 7 methods. For example, every fix that does 1 to 1 line substitutions has a `FixLine` method, every fix that uses a before/after crosswalk has a `.Setup` method and a `.shtSettings` property, etc. So the components of each fix vary by what mix of things need to be done, and then maybe 5% of the fixes have unique additions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T21:58:20.837",
"Id": "414352",
"Score": "0",
"body": "@Comintern It's possible that a really deep redesign would do something with all that method re-use - that kind of suggestion is welcome too. Currently, I have the common methods that a given fix needs copied directly into its class and then modified. For example, every 1 to 1 line substitution does use a `.FixLine` method as I stated above, but the implementation in what is being read, kept, removed, or replaced varies.\n\nYour fresh eyes and greater skill are welcome :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T22:01:36.067",
"Id": "414354",
"Score": "1",
"body": "It's possible I'll *suggest* a really deep redesign... ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T22:08:29.453",
"Id": "414355",
"Score": "0",
"body": "@Comintern I felt a great disturbance in the Force... as if use of interfaces has suddenly moved violently from my future into my present. I fear something really good has happened.\n\nI'll re-read my interface materials, hopefully I'll understand them better this time."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T21:07:45.380",
"Id": "214273",
"Score": "2",
"Tags": [
"vba",
"excel"
],
"Title": "Fixing Medical Claim Files through Text File Read/Write v2"
} | 214273 |
<p>I'm building an IntelliJ Plugin which will allow a person to select an XML file (and even a snippet of XML in the file, if they like) and, using a really brief GUI, generate classes / code in one of a selection of languages that will read the XML via native functions and generate code to do so on a regular basis.</p>
<p>The idea here is that a user should be able to generate a deserialization function that would not rely on any third-party libraries, but only on the native built-in features of the language and framework. Additionally, this would mean no reflection / introspection would be necessary: just read the XML into a fully strong-typed thing.</p>
<p>I'm going to post this as several "parts", because it's a large project. I'll do so incrementally: starting from the first component and moving towards the last.</p>
<p>The first step in the adventure is to create and use a <code>Parser</code> which can read our XML file into some nodes / objects. The idea here is that it <em>only</em> cares about the structure of the file: node names, keys, and value <strong>types</strong>, not the actual values. (So <code><node attr="test"></code> would say "this is a node named 'node', with an attribute named 'attr', that is a string.")</p>
<p>To start with, we should begin at the, well, beginning: reading the file.</p>
<p>For simplicity, I've built a <code>Reading</code> class that can take a document as a string and attempt to parse the XML out of it:</p>
<pre><code>ArrayList<Node> nodes = Reading.readDocument(document);
</code></pre>
<p>This is a very simple interface, but underneath it starts doing a lot of work:</p>
<pre><code>package Xml;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Iterator;
public class Reading {
public static ArrayList<Node> readDocument(String document) throws XMLStreamException {
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLEventReader reader = factory.createXMLEventReader(new StringReader(document));
ArrayList<Node> nodes = new ArrayList<>();
int indentation = 0;
while (reader.hasNext()) {
XMLEvent event = reader.nextEvent();
if (event.isStartElement()) {
StartElement startElement = event.asStartElement();
Node node = new Node(startElement.getName().getLocalPart());
Iterator attributes = startElement.getAttributes();
while (attributes.hasNext()) {
Attribute attribute = (Attribute)attributes.next();
if (attribute.isSpecified()) {
node.add_attribute(attribute.getName().getLocalPart(), attribute.getValue());
}
}
ArrayList<Node> nodeAddition = getActiveNode(nodes, indentation);
nodeAddition.add(node);
indentation++;
} else if (event.isCharacters()) {
Characters characters = event.asCharacters();
String data = characters.getData();
ArrayList<Node> nodeAddition = getActiveNode(nodes, indentation - 1);
nodeAddition.get(nodeAddition.size() - 1).set_value(data);
} else if (event.isEndElement()) {
indentation--;
}
}
return nodes;
}
private static ArrayList<Node> getActiveNode(ArrayList<Node> nodes, int indentation) {
ArrayList<Node> nodeAddition = nodes;
while (indentation > 0) {
indentation--;
nodeAddition = nodeAddition.get(nodeAddition.size() - 1).get_nodes();
}
return nodeAddition;
}
}
</code></pre>
<p>Here, we read the XML in and start processing it into our list of array nodes. We keep the nested node structure, and we have the following definition of a <code>Node</code> within our program:</p>
<pre><code>package Xml;
import java.util.ArrayList;
import java.util.HashMap;
public class Node {
private String _name;
private String _value;
private ArrayList<Node> _nodes;
private HashMap<String, String> _attributes;
public Node(String name) {
_name = name;
_nodes = new ArrayList<>();
_attributes = new HashMap<>();
}
public String get_name() {
return _name;
}
public String get_value() {
return _value;
}
public void set_value(String _value) {
this._value = _value;
}
public HashMap<String, String> get_attributes() {
return _attributes;
}
public void add_attribute(String key, String value) {
_attributes.put(key, value);
}
public ArrayList<Node> get_nodes() {
return _nodes;
}
}
</code></pre>
<p>Obviously we're reading the value in here, but we'll eliminate that later. <em>That</em> was the easy part.</p>
<p>Next, we need to parse the nodes into some type of "object", here we'll use our <code>Parser</code> to begin doing some <em>real</em> work:</p>
<pre><code>Parser parser = new Parser();
parser.set_integerRule(getIntegerRule(wrapper.getSelectedNumberRule()));
parser.set_nullDefault(wrapper.getUseStringForNull() ? Type.STRING : Type.NULL);
parser.set_dateFormat(wrapper.getDateFormat());
parser.set_allNodesAreArrays(wrapper.getAllNodesAreArrays());
for (Tuple2<String, String> rule : wrapper.getBooleanRules()) {
parser.add_booleanRule(new ParserBooleanRule(rule.getFirst(), rule.getSecond()));
}
ArrayList<CodeObject> codeObjects = parser.parse(nodes);
</code></pre>
<p>The <code>Parser</code> is <em>much</em> more complex, and has a lot more going on. To start: it has a selection of "rules" that determine how and why it parses things, particularly how to handle different "features" of our parser. We have a few major features:</p>
<ol>
<li><strong>Number Rules</strong>: when the parser encounters a number type, how should it treat the type? We can use the minimal data-size, or we can assume the minimum is <code>Int</code>, <code>Long</code>, or <code>Double</code>.</li>
<li><strong>Use String for Null</strong>: when the parser encounters a null value, how should it proceed? If selected, the parser should intrinsically treat the lack of a value as a <code>String</code>.</li>
<li><strong>Date Format</strong>: how should the parser detect dates? If specified, the parser should use the specified format to detect date types.</li>
<li><strong>Boolean Rules</strong>: how should the parser detect true/false values? Three built-in rules exist for true/false respectively: <code>Y</code>/<code>N</code>, <code>Yes</code>/<code>No</code>, <code>True</code>/<code>False</code>.</li>
<li><strong>Result Language</strong>: this is less for the parser, and more for the generator. What is the destination output language?</li>
</ol>
<p>So, with that said, we'll look at the <code>Parser</code>:</p>
<pre><code>package Generation;
import Xml.Node;
import org.jetbrains.annotations.NotNull;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
public class Parser {
private String _dateFormat;
private ParserIntegerRule _integerRule;
private Type _nullDefault;
private ArrayList<ParserBooleanRule> _booleanRules;
private boolean _allNodesAreArrays;
public Parser() {
_integerRule = ParserIntegerRule.Minimal;
_nullDefault = Type.NULL;
_booleanRules = new ArrayList<>();
}
public String get_dateFormat() { return _dateFormat; }
public void set_dateFormat(String _dateFormat) { this._dateFormat = _dateFormat; }
public ParserIntegerRule get_integerRule() { return _integerRule; }
public void set_integerRule(ParserIntegerRule _integerRule) { this._integerRule = _integerRule; }
public Type get_nullDefault() { return _nullDefault; }
public void set_nullDefault(Type _nullDefault) { this._nullDefault = _nullDefault; }
public ArrayList<ParserBooleanRule> get_booleanRules() { return _booleanRules; }
public void add_booleanRule(ParserBooleanRule rule) { _booleanRules.add(rule); }
public boolean is_allNodesAreArrays() { return _allNodesAreArrays; }
public void set_allNodesAreArrays(boolean _allNodesAreArrays) { this._allNodesAreArrays = _allNodesAreArrays; }
private Type getType(String value) {
SimpleDateFormat format = new SimpleDateFormat(_dateFormat);
format.setLenient(false);
if (value == null || value.equals("")) {
return _nullDefault;
}
if (_dateFormat != null) {
try {
format.parse(value);
return Type.DATE;
} catch (ParseException ignored) { }
}
for (ParserBooleanRule rule : _booleanRules) {
String tempValue = value.toLowerCase();
if (tempValue.equals(rule.get_true()) || tempValue.equals(rule.get_false())) {
return Type.BOOLEAN;
}
}
if (_integerRule == ParserIntegerRule.Minimal) {
try {
//noinspection ResultOfMethodCallIgnored
Byte.parseByte(value);
return Type.INT8;
} catch (NumberFormatException ignored) { }
}
if (_integerRule == ParserIntegerRule.Minimal) {
try {
//noinspection ResultOfMethodCallIgnored
Short.parseShort(value);
return Type.INT16;
} catch (NumberFormatException ignored) { }
}
if (_integerRule == ParserIntegerRule.Minimal || _integerRule == ParserIntegerRule.AssumeInt) {
try {
Integer.parseInt(value);
return Type.INT32;
} catch (NumberFormatException ignored) { }
}
if (_integerRule == ParserIntegerRule.Minimal || _integerRule == ParserIntegerRule.AssumeInt || _integerRule == ParserIntegerRule.AssumeLong) {
try {
Long.parseLong(value);
return Type.INT64;
} catch (NumberFormatException ignored) { }
}
try {
Double.parseDouble(value);
return Type.DOUBLE;
} catch (NumberFormatException ignored) { }
return Type.STRING;
}
private boolean isNumeric(Type type) {
switch (type) {
case INT8:
return true;
case INT16:
return true;
case INT32:
return true;
case INT64:
return true;
case DOUBLE:
return true;
default:
return false;
}
}
private Type lowestCommonNumericType(Type type1, Type type2) {
if (type1 == Type.INT8) {
return type2;
}
if (type1 == Type.INT16) {
if (type2 == Type.INT8) {
return Type.INT16;
}
return type2;
}
if (type1 == Type.INT32) {
if (type2 == Type.INT8 || type2 == Type.INT16) {
return Type.INT32;
}
return type2;
}
if (type1 == Type.INT64) {
if (type2 == Type.INT8 || type2 == Type.INT16 || type2 == Type.INT32) {
return Type.INT64;
}
return type2;
}
return Type.DOUBLE;
}
private Type compareTypes(Type type1, Type type2) {
if (type1 == Type.NULL) {
return type2;
}
if (type2 == Type.NULL) {
return type1;
}
if (type1 == Type.OBJECT || type2 == Type.OBJECT) {
return Type.OBJECT;
}
if (_dateFormat != null
&& ((type1 == Type.DATE && isNumeric(type2))
|| (isNumeric(type1) && type2 == Type.DATE))) {
SimpleDateFormat format = new SimpleDateFormat(_dateFormat);
format.setLenient(false);
if (isNumeric(getType(format.format(Date.from(Instant.now()))))) {
return type1 == Type.DATE ? type2 : type1;
}
}
if (type1 == Type.BOOLEAN && type2 == Type.BOOLEAN) {
return Type.BOOLEAN;
}
if (type1 == Type.DATE && type2 == Type.DATE) {
return Type.DATE;
}
if (isNumeric(type1) && isNumeric(type2)) {
return lowestCommonNumericType(type1, type2);
}
return Type.STRING;
}
private CodeObject objectWithName(Collection<CodeObject> codeObjects, String name) {
for (CodeObject codeObject : codeObjects) {
if (codeObject.get_name().equals(name)) {
return codeObject;
}
}
return null;
}
@NotNull
private ArrayList<CodeObject> getMainObjects(@NotNull ArrayList<Node> nodes) {
ArrayList<CodeObject> codeObjects = new ArrayList<>();
for (Node node : nodes) {
CodeObject object = new CodeObject(node.get_name());
codeObjects.add(object);
HashMap<String, String> attributes = node.get_attributes();
for (String key : attributes.keySet()) {
CodeObject attrCodeObject = new CodeObject(key, getType(attributes.get(key)));
object.add_object(attrCodeObject);
attrCodeObject.set_from(From.ATTRIBUTE);
}
ArrayList<Node> subNodes = node.get_nodes();
if (subNodes.size() == 0) {
object.set_type(getType(node.get_value()));
object.set_from(attributes.size() > 0 ? From.NODE : From.VALUE);
if (node.get_value() != null) {
Type myAttrType = getType(attributes.get("_Text"));
if (myAttrType == Type.NULL) {
myAttrType = Type.STRING;
}
CodeObject attrCodeObject = new CodeObject("_Text", myAttrType);
object.add_object(attrCodeObject);
attrCodeObject.set_from(From.RAW_VALUE);
}
} else {
object.add_objects(getMainObjects(subNodes));
object.set_from(From.NODE);
}
if (attributes.size() > 0 || subNodes.size() > 0) {
object.set_type(Type.OBJECT);
}
}
return codeObjects;
}
private void reduceObjects(@NotNull CodeObject existing, @NotNull CodeObject object) {
existing.set_type(compareTypes(existing.get_type(), object.get_type()));
existing.set_isArray(existing.is_isArray() || object.is_isArray());
ArrayList<CodeObject> reducedObjects = reduceObjects(object.get_codeObjects());
for (CodeObject reducedObject : reducedObjects) {
CodeObject existingSubObject = objectWithName(existing.get_codeObjects(), reducedObject.get_name());
if (existingSubObject == null) {
existing.add_object(reducedObject);
continue;
}
reduceObjects(existingSubObject, reducedObject);
}
}
@NotNull
private ArrayList<CodeObject> reduceObjects(@NotNull ArrayList<CodeObject> objects) {
ArrayList<CodeObject> result = new ArrayList<>();
for (CodeObject object : objects) {
CodeObject existingObject = objectWithName(result, object.get_name());
if (existingObject == null) {
existingObject = new CodeObject(object.get_name(), object.get_type());
existingObject.set_from(object.get_from());
existingObject.set_isArray((_allNodesAreArrays && existingObject.get_from() == From.NODE) || object.is_isArray());
existingObject.add_objects(reduceObjects(object.get_codeObjects()));
result.add(existingObject);
} else {
existingObject.set_isArray(true);
object.set_isArray(true);
reduceObjects(existingObject, object);
}
}
return result;
}
@NotNull
public ArrayList<CodeObject> parse(@NotNull ArrayList<Node> nodes) {
ArrayList<CodeObject> objects = getMainObjects(nodes);
return reduceObjects(objects);
}
}
</code></pre>
<p>This class is somewhat long, and has a few other definitions we need to include:</p>
<p>The <code>CodeObject</code>:</p>
<pre><code>package Generation;
import java.util.ArrayList;
import java.util.Collection;
public class CodeObject {
private String _name;
private Type _type;
private From _from;
private boolean _isArray;
private ArrayList<CodeObject> _codeObjects;
public CodeObject(String name) {
_name = name;
_codeObjects = new ArrayList<>();
}
public CodeObject(String name, Type type) {
this(name);
_type = type;
}
public String get_name() {
return _name;
}
public Type get_type() {
return _type;
}
public void set_type(Type _type) {
this._type = _type;
}
public ArrayList<CodeObject> get_codeObjects() {
return _codeObjects;
}
public void add_object(CodeObject codeObject) {
_codeObjects.add(codeObject);
}
public void add_objects(Collection<CodeObject> codeObject) {
_codeObjects.addAll(codeObject);
}
public From get_from() {
return _from;
}
public void set_from(From _from) {
this._from = _from;
}
public boolean is_isArray() {
return _isArray;
}
public void set_isArray(boolean _isArray) {
this._isArray = _isArray;
}
}
</code></pre>
<p>The <code>Type</code>:</p>
<pre><code>package Generation;
public enum Type {
NULL,
STRING,
INT8,
INT16,
INT32,
INT64,
DOUBLE,
DATE,
BOOLEAN,
OBJECT
}
</code></pre>
<p>The <code>From</code>:</p>
<pre><code>package Generation;
public enum From {
ATTRIBUTE,
NODE,
VALUE,
RAW_VALUE
}
</code></pre>
<p>The <code>ParserBooleanRule</code>:</p>
<pre><code>package Generation;
public class ParserBooleanRule {
private String _true;
private String _false;
public ParserBooleanRule(String _true, String _false) {
this._true = _true;
this._false = _false;
}
public String get_true() {
return _true;
}
public String get_false() {
return _false;
}
}
</code></pre>
<p>And the <code>ParserIntegerRule</code>:</p>
<pre><code>package Generation;
public enum ParserIntegerRule {
Minimal,
AssumeInt,
AssumeLong,
AssumeDouble
}
</code></pre>
<p>All these components, together, implement the logic of the parser. Read the <code>Node</code> objects into a <code>CodeObject</code> array.</p>
<p>Additionally, one should note all of the <code>Type</code> functions in the <code>Parser</code>: these help determine type-rules: given two types, which type should the result be? We use these to determine what we need to do with the data-types, and how an attribute of <code>5</code> and <code>14.2</code> and <code>test</code> should be compared, to get the lowest-common type: the one that will accurately represent all values in our input.</p>
<p>Finally, the generation also has three more components relevant to this parser:</p>
<pre><code>private LinkedHashMap<String, ParserIntegerRule> _parserIntegerRules;
public GenerateAction() {
super("Hello");
_parserIntegerRules = new LinkedHashMap<>();
_parserIntegerRules.put("Minimal", ParserIntegerRule.Minimal);
_parserIntegerRules.put("Assume Int", ParserIntegerRule.AssumeInt);
_parserIntegerRules.put("Assume Long", ParserIntegerRule.AssumeLong);
_parserIntegerRules.put("Assume Double", ParserIntegerRule.AssumeDouble);
}
@NotNull
private ParserIntegerRule getIntegerRule(String rule) {
return _parserIntegerRules.getOrDefault(rule, ParserIntegerRule.Minimal);
}
</code></pre>
| [] | [
{
"body": "<h1><a href=\"https://stackoverflow.com/a/384067/8339141\">Program to Interfaces, not Implementations</a></h1>\n\n<p>The code base heavily depends on <code>ArrayList</code>. For example in <code>Reading</code> </p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>ArrayList<Node> readDocument(String document) throws XMLStreamException {\n // ..\n ArrayList<Node> nodes = new ArrayList<>()\n // ..\n ArrayList<Node> nodeAddition = getActiveNode(nodes, indentation)\n}\n\nprivate static ArrayList<Node> getActiveNode(ArrayList<Node> nodes, int indentation) { /* .. */ }\n</code></pre>\n</blockquote>\n\n<p>The only methods that are used on that instances of <code>ArrayList</code> are <code>add</code>, <code>get</code> and <code>size</code>.</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>nodeAddition.add(node);\n</code></pre>\n \n <pre class=\"lang-java prettyprint-override\"><code>nodeAddition.get(nodeAddition.size() - 1)//..\n</code></pre>\n</blockquote>\n\n<p>Since only methods get used that are defined on the interface <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/List.html\" rel=\"nofollow noreferrer\">List</a>, your code should rather depend on the interface than on the implementation:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>List<Node> readDocument(String document) throws XMLStreamException {\n // ..\n List<Node> nodes = new ArrayList<>()\n // ..\n List<Node> nodeAddition = getActiveNode(nodes, indentation)\n}\n\nprivate static List<Node> getActiveNode(List<Node> nodes, int indentation) { /* .. */ }\n</code></pre>\n\n<p>With <em>program to interfaces, not implementations</em> you do not limit your self to a concrete implementation, because now it would be easier to switch from an <code>ArrayList</code> to a <code>LinkedList</code> because of the use of the common interface.</p>\n\n<hr>\n\n<h1><a href=\"http://wiki.c2.com/?AccessorsAreEvil\" rel=\"nofollow noreferrer\">Accessors Are Evil</a></h1>\n\n<blockquote>\n <p>Public accessors indicate that the data and the behavior of a class are not kept together.</p>\n \n <p>This is seen as a an indication of higher coupling and lower coherence. </p>\n</blockquote>\n\n<h3><a href=\"https://hackernoon.com/objects-vs-data-structures-e380b962c1d2\" rel=\"nofollow noreferrer\">Objects vs. Data Structures</a></h3>\n\n<p>The \"objects\" <code>Value</code>, <code>CodeObject</code>, <code>ParserBooleanRule</code> and maybe more make have use of getters and setters. The are not objects in terms of oop - rather they are data structures. </p>\n\n<p>In <code>Parser</code> inside the method <code>getType</code> is the following if-statement</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>if (tempValue.equals(rule.get_true()) || tempValue.equals(rule.get_false())) {\n return Type.BOOLEAN;\n}\n</code></pre>\n</blockquote>\n\n<p>We can see that the <code>Parser</code> uses <code>rule</code> (<code>ParserBooleanRule</code>) as a data structure whilst it uses the methods <code>get_true</code> and <code>get_false</code> to look if a <code>value</code> is a boolean. Much better would be, when <code>ParserBooleanRule</code> knows if a <code>value</code> is a boolean:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>if (rule.fulfilledBy(value)) {\n return Type.BOOLEAN;\n}\n</code></pre>\n\n<hr>\n\n<h1><a href=\"http://wiki.c2.com/?DontUseExceptionsForFlowControl\" rel=\"nofollow noreferrer\">Don't Use Exceptions For Flow Control</a></h1>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>if (_integerRule == ParserIntegerRule.Minimal) {\n try {\n //noinspection ResultOfMethodCallIgnored\n Byte.parseByte(value);\n return Type.INT8;\n } catch (NumberFormatException ignored) { }\n}\n\nif (_integerRule == ParserIntegerRule.Minimal) {\n try {\n //noinspection ResultOfMethodCallIgnored\n Short.parseShort(value);\n return Type.INT16;\n } catch (NumberFormatException ignored) { }\n}\n\n// ..\n</code></pre>\n</blockquote>\n\n<p>At the first time I thought that the second if-statement will never be reached because it has the same condition as the first if-statement. Than I saw that you actually use an try-catch as condition.</p>\n\n<p>Instead of you could check first if a value is a number trough a regex, count the number of figures and parse it to the data type you aspect..</p>\n\n<hr>\n\n<h1><a href=\"http://wiki.c2.com/?FeatureEnvySmell\" rel=\"nofollow noreferrer\">Feature Envy</a></h1>\n\n<p>A classic [code] smell is a method that seems more interested in a class other than the one it is in. The most common focus of the envy is the data.</p>\n\n<p>I already wrote that you have a lot of getter and setter methods witch makes it easy do access the data of an object. The <code>Parser</code> reads the data for many of your objects and do some logic on it - this is a Feature Envy. The object itself should do the operation and the <code>Parser</code> should only ask for it (<a href=\"https://martinfowler.com/bliki/TellDontAsk.html\" rel=\"nofollow noreferrer\">Tell don't ask</a>)</p>\n\n<p>The following loop is inside <code>Parser</code> exist to manipulate a <code>CodeObject</code></p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>for (CodeObject object : objects) {\n CodeObject existingObject = objectWithName(result, object.get_name());\n if (existingObject == null) {\n existingObject = new CodeObject(object.get_name(), object.get_type());\n existingObject.set_from(object.get_from());\n existingObject.set_isArray((_allNodesAreArrays && existingObject.get_from() == From.NODE) || object.is_isArray());\n existingObject.add_objects(reduceObjects(object.get_codeObjects()));\n result.add(existingObject);\n } else {\n existingObject.set_isArray(true);\n object.set_isArray(true);\n reduceObjects(existingObject, object);\n }\n}\n</code></pre>\n</blockquote>\n\n<p>The <code>Parser</code> should request the change by an <code>CodeObject</code> or in this case by an <code>CodeObjectFactory</code></p>\n\n<p>When we look at the following method-names, we will see that they all include the class name on which they interact:</p>\n\n<blockquote>\n <p><code>objectWithName</code>, <code>getMainObjects</code>, <code>reduceObjects</code>, <code>compareTypes</code> and <code>lowestCommonNumericType</code></p>\n</blockquote>\n\n<p>They should go into the classes envied by the <code>parser</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-05T12:21:39.973",
"Id": "214759",
"ParentId": "214275",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-25T21:16:43.620",
"Id": "214275",
"Score": "2",
"Tags": [
"java",
"object-oriented",
"parsing",
"plugin"
],
"Title": "Dynamically Generating XML Deserialization Classes / Code: Part I, Reading"
} | 214275 |
<p>I am making a profile picture selection screen, basically you select a picture pic1, if another picture pic2 is selected, then we cancel the highlight of pic2 and highlight pic1. Here is my code right now for it in React (btw, I am using CSS to take care of the highlighting).</p>
<p>How I am doing it currently (let's say I only have 3 options to choose from), this is the code taking care of determining which one is clicked: </p>
<pre><code>` this.state = {
isClicked1: false,
isClicked2: false,
isClicked3: false
};`
</code></pre>
<p>The JSX code that actually displays everything:</p>
<pre><code><a class={a_class1} onClick={this.profilePicClick1}>
<img src={hero001} />
</a>
<a class={a_class2} onClick={this.profilePicClick2}>
<img src={hero002} />
</a>
<a class={a_class3} onClick={this.profilePicClick3}>
<img src={hero003} />
</a>
</code></pre>
<p>The class is actually what determines if it is highlighted or not (background color in CSS), if the class is animal selected then it has a background else no background. </p>
<pre><code>let a_class1 = this.state.isClicked1 ? "animal selected" : "animal";
let a_class2 = this.state.isClicked2 ? "animal selected" : "animal";
let a_class3 = this.state.isClicked3 ? "animal selected" : "animal";
</code></pre>
<p>And the JS logic: </p>
<pre><code> profilePicClick1 = () => {
this.setState({ isClicked1: !this.state.isClicked1 });
this.setState({ isClicked2: false });
this.setState({ isClicked3: false });
};
profilePicClick2 = () => {
this.setState({ isClicked2: !this.state.isClicked2 });
this.setState({ isclicked3: false });
this.setState({ isClicked1: false });
};
profilePicClick3 = () => {
this.setState({ isClicked3: !this.state.isClicked2 });
this.setState({ isclicked1: false });
this.setState({ isClicked2: false });
};
</code></pre>
<p><strong>Here's a run through sorry if my code is confusing</strong>: on load, the isClicked state for all images is false, that leads to each a_class being "animal", and on render, it will display the images with the a_classes, since it is only animal, we will display the normal image. Onclick of let's say image1, we will turn isClicked1 into true, which will make a_class1 "animal selected", and will thus render the picture with the background selected color. And onClick of another picture other than pic1, we will set all other isClicked to false besides the one just being clicked, and blah blah. </p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T00:53:34.520",
"Id": "214287",
"Score": "1",
"Tags": [
"event-handling",
"jsx"
],
"Title": "ReactJS code that allows at most one profile pic to be selected"
} | 214287 |
<p>I wrote this code about one year ago. I'm looking to refactor it to be solid SOLID and secure, as this is being generated off a custom endpoint. The script is to read parameters from a query and generate custom CSV exports based off categories, tags, and order completion date. These reports can be weekly, monthly, yearly, or for all time. An email or comma separated list of emails can be passed as recipients. </p>
<p>The original flow I had was like this:</p>
<ul>
<li>Enable errors </li>
<li>Check if correct query string set</li>
<li>If not, exit, else continue</li>
<li>Load Wordpress/Woocommerce</li>
<li>Sanitize GET variables and set interpolate things like date ranges from string values.</li>
<li>Create a collection array and loop through all orders, excluding ones that do not meet search params.</li>
<li>Sort by category</li>
<li>If no orders, exit</li>
<li>Else, write to CSV, email the CSV, and unlink files</li>
</ul>
<p><strong>A few questions</strong>
- Should I convert this to OOP?
- What are some design patterns I can use to make the logic more intuitive?</p>
<p>P.S. This is the cron url</p>
<blockquote>
<p>(wget -O- "<a href="https://site.com/wp-content/themes/theme/scripts/auto-export.php?export=GET&filter_units=all&period=month&filter_categories=product&filter_skus=all&email_list=dan@email.com" rel="nofollow noreferrer">https://site.com/wp-content/themes/theme/scripts/auto-export.php?export=GET&filter_units=all&period=month&filter_categories=product&filter_skus=all&email_list=dan@email.com</a>" --no-check-certificate >> log.txt) </p>
</blockquote>
<p>
<pre><code>// Set INI values for testing
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// Exit if export type not set (correctly)
if ( !isset($_GET[ 'export' ]) || $_GET['export'] !== 'GET')
exit;
// load Wordpress
define('WP_USE_THEMES', false);
require($_SERVER['DOCUMENT_ROOT'] . "/wp-load.php");
// Sanititze GET data
$search_data = sanitize_get();
// Get orders sorted
$orders = get_product_purchases( $search_data );
$orders = sort_orders_by( 'category', 'DESC', $orders );
// Exit if no orders
if (count($orders) == 0 ) {
echo "There were no orders given the parameters";
exit;
}
write_to_csv_get([
'search_data' => $search_data,
'orders' => $orders,
]);
echo "Export Successful";
exit;
/**
* get_product_purchases
* Return array of orders
*/
function get_product_purchases( $search_data ) {
// Destructure search data
$cat_data = $search_data['categories'];
$sku_data = $search_data['skus'];
$period = $search_data['period'];
$unit_data = $search_data['units'];
// See set_order_args() doc-block for more details
$args = set_order_args( $search_data );
$WC_Orders = wc_get_orders( $args );
$results = [];
foreach ( $WC_Orders as $WC_Order ) {
if ( empty($WC_Order)) continue;
$order_data = $WC_Order->get_data();
$my_order[ 'order_id' ] = $WC_Order->get_id();
$my_order['order_date'] = $order_data['date_created']->date('Y-m-d');
$my_order['shipping_first_name'] = $order_data['shipping']['first_name'];
$my_order['shipping_last_name'] = $order_data['shipping']['last_name'];
$my_order['shipping_address_1'] = $order_data['shipping']['address_1'];
$my_order['shipping_address_2'] = $order_data['shipping']['address_2'];
$my_order['shipping_city'] = $order_data['shipping']['city'];
$my_order['shipping_state'] = $order_data['shipping']['state'];
$my_order['shipping_postcode'] = $order_data['shipping']['postcode'];
foreach ( $WC_Order->get_items() as $item_key => $item_values ) {
$my_order_copy = $my_order;
## Using WC_Order_Item methods ##
$my_item['id'] = $item_values->get_id(); // Item ID is directly accessible from the $item_key in the foreach loop or
## Access Order Items data properties (in an array of values) ##
$item_data = $item_values->get_data();
$product_id = $item_data['product_id'];
$product['product_name'] = $item_data['name'];
$product['quantity'] = $item_data['quantity'];
// Get data from The WC_product object using methods (examples)
$WC_Product = $item_values->get_product(); // the WC_Product object
if ( empty($WC_Product)) {
continue;
};
$item['item_name'] = preg_replace( '/[\x00-\x1F\x7F-\xFF]/', '', $item_values->get_name() ) ; // Name of the product
$product['sku'] = $WC_Product->get_sku();
$product['price'] = ( $WC_Product->get_price() )
? sprintf( '%.2f', $WC_Product->get_price() )
: '';
// Tags = business units
$product['tag'] = strtolower( get_tag_name( $product_id ) );
// Term names are categories
$terms = get_the_terms( $product_id, 'product_cat' );
$cats = [];
foreach( $terms as $term ) {
array_push( $cats, strtolower( $term->name ));
}
$product['category'] = $cats[0];
/*
Perform condition check on whether or not to push to export
If a filter list is set, check the product property against
the filter list and see if it matches. If it does not,
exclude it from the CSV
*/
$push = check_against_list( $cat_data, $product, 'category' );
if ( $push == 0 ) continue;
$push = check_against_list( $unit_data, $product, 'tag' );
if ( $push == 0 ) continue;
$push = check_against_list( $sku_data, $product, 'sku' );
if ( $push == 0 ) continue;
if ( $push == 1 ) {
$row = array_merge( $my_order_copy, $product );
array_push( $results, $row );
}
}
}
return $results;
}
/**
* @param array $params [search_data & orders]
* @return [void]
*/
function write_to_csv_get( $params ) {
// Destructure params
$period = $params['search_data']['period'];
$orders = $params['orders'];
$date_summary = ( $period['all'] == 0 )
? "from {$period['range']['start_date']} to {$period['range']['end_date']}"
: "Since Beginning";
$breakdown_filename = "company-{$period['type']}-order-details.csv";
$path = "/tmp";
$fp = fopen("$path/$breakdown_filename", 'w');
if ( fopen( "$path/$breakdown_filename", "w+" ) ) {
$totals = []; // Sum of quantities
$placed_header = false;
foreach ( $orders as $index => $row) {
$totals = sum( $row, $totals );
// Old code for writing all details of orders
if (! $placed_header)
{
fputcsv( $fp, array_keys( $row ) );
$placed_header = true;
}
// If row set, write it to CSV
if ( count( $row ) != 0 )
fputcsv( $fp, $row );
}
} else {
fclose( $fp );
unlink("$path/$breakdown_filename");
error_log( "Auto-report: CSV Breakdown - failed to open CSV" );
}
notify( $breakdown_filename, $path, 'Download Order Details Export', 'detailed', $params );
fclose($fp);
unlink("$path/$filename");
$totals_filename = "company-{$period['type']}-orders-totals.csv";
$fp = fopen("$path/$totals_filename", 'w');
if ( fopen( "$path/$totals_filename", "w+" ) ) {
// Send totals email
fputcsv( $fp, [ "Orders - {$date_summary}"] );
fputcsv( $fp, [ 'SKU', 'Name', 'Totals' ] );
// Output two column totals ( name | total )
foreach( $totals as $name => $details ) {
$num = $details[0];
$sku = $details[1];
/*
Excel doesn't like some of the ASCII characters, use 7 bit ASCII
https://stackoverflow.com/questions/1176904/php-how-to-remove-all-non-printable-characters-in-a-string
*/
fputcsv( $fp, [ $sku, $name, $num ]);
}
} else {
fclose( $fp );
unlink("$path/$totals_filename");
error_log( "Auto-report: Totals CSV - Failed to open CSV" );
}
// Send break down CSV
notify( $totals_filename, $path, 'Download Totals Export', 'totals for', $params );
fclose($fp);
unlink("$path/$totals_filename");
return;
}
function sort_orders_by_date( $results, $order = 'DESC' ) {
foreach ($results as $key => $part) {
$sort[$key] = strtotime($part['order_date']);
}
( $order == 'DESC' )
? array_multisort( $sort, SORT_DESC, $results )
: array_multisort( $sort, SORT_ASC, $results );
return $results;
}
function sort_orders_by( $field, $order = 'DESC', $results ) {
if ( count( $results ) > 0 )
{
foreach ($results as $key => $part) {
$sort[$key] = $part[ $field ];
}
( $order == 'DESC' )
? array_multisort( $sort, SORT_DESC, $results )
: array_multisort( $sort, SORT_ASC, $results );
}
return $results;
}
function sanitize_get() {
/*---------------------------------------------
Filter / Sanitize Dates
--------------------------------------------- */
if ( isset( $_GET['period']))
{
$period['all'] = 0;
switch( $_GET['period'])
{
case( 'week' ):
$period['type'] = 'weekly';
$previous_week = strtotime("-1 week +1 day");
$start_week = strtotime( "last sunday", $previous_week );
$end_week = strtotime( "next saturday", $start_week );
$period['range']['start_date'] = filter_var( date( "Y-m-d", $start_week ), FILTER_SANITIZE_STRING );
$period['range']['end_date'] = filter_var( date( "Y-m-d", $end_week), FILTER_SANITIZE_STRING );
break;
case( 'month' ):
$period['type'] = 'monthly';
$period['range']['start_date'] = date('Y-m-d',strtotime('first day of last month'));
$period['range']['end_date'] = date('Y-m-d',strtotime('last day of last month'));
break;
case( 'year'):
$year = date( 'Y' ) - 1;
$period['type'] = 'yearly';
$period['range']['start_date'] = "{$year}-01-01";
$period['range']['end_date'] = "{$year}-12-31";
break;
case( 'forever' ):
$period['type'] = 'full';
$period[ 'all' ] = 1;
break;
}
}
else
{
error_log( 'Autoexport: no period given to auto export');
exit;
}
/*---------------------------------------------
Filter / Sanitize Categories
---------------------------------------------*/
if ( isset( $_GET['filter_categories']))
{
$categories = [];
$categories['all'] = 0;
if ( $_GET['filter_categories'] == 'all' )
{
$categories['all'] = 1;
}
else
{
$categories['list'] = explode( ',', $_GET['filter_categories']);
foreach( $categories['list'] as $i => $cat )
{
$categories['list'][$i] = str_replace( '-', ' ', strtolower( filter_var( $cat, FILTER_SANITIZE_STRING ) ) );
}
if ( $categories['all'] === 0 && count( $categories['list'] ) < 1 )
error_log( 'Empty value for categories was passed' );
}
}
else
{
error_log( 'Autoexport: Empty value for categories was passed' );
exit;
}
/*---------------------------------------------
Filter / Sanitize Business Units
---------------------------------------------*/
if ( isset( $_GET['filter_units']) )
{
if ( $_GET['filter_units'] == 'all' )
{
$units['all'] = 1;
}
else
{
$units = [];
$units['list'] = explode( ',', $_GET['filter_units']);
foreach( $units['list'] as $i => $unit )
{
$units['list'][$i] = str_replace( '-', ' ', strtolower( filter_var( $unit, FILTER_SANITIZE_STRING ) ) );
}
if ( $units['all'] == 0 && count( $units['list'] ) < 1 )
error_log( 'Empty value for business units was passed' );
}
}
else
{
error_log( 'Autoexport: Empty value for business units was passed' );
exit;
}
/*---------------------------------------------
Filter / Sanitize Skus
---------------------------------------------*/
if ( isset( $_GET['filter_skus']) )
{
$skus = [];
if ( $_GET['filter_skus'] == 'all' )
{
$skus['all'] = 1;
}
else
{
$skus['list'] = explode( ',', $_GET['filter_skus'] );
// Filter unit string and push it to the search list
foreach( $skus['list'] as $i => $sku )
{
$skus['list'][$i] = str_replace( '-', ' ', filter_var( $sku, FILTER_SANITIZE_STRING ) );
}
if ( $skus['all'] === 0 && count( $skus['list'] ) < 1 )
error_log( 'Autoexport: Empty value for skus was passed' );
}
}
else
{
error_log( 'Autoexport: Empty value for skus was passed' );
exit;
}
/*---------------------------------------------
Filter / Sanitize Emails
--------------------------------------------- */
// Optionally pass in string of double pipe separated emails to send to
if ( isset( $_GET['email_list']))
{
$email_list = explode( ',', $_GET['email_list'] );
foreach ( $email_list as $i => $email )
{
$email_list[ $i ] = filter_var( $email, FILTER_SANITIZE_EMAIL );
}
$email_list = implode( ',', $email_list );
}
else
{
error_log( 'Autoexport: email given to auto export');
exit;
}
$search_data = [
'validated' => 1,
'period' => $period,
'categories' => $categories,
'units' => $units,
'skus' => $skus,
'email_list' => $email_list,
];
if ( $search_data['validated'] != 1 )
die( 'Sorry, the data you entered is invalid' );
return $search_data;
}
/*
More info on wc_order arguments
https://github.com/woocommerce/woocommerce/wiki/wc_get_orders-and-WC_Order_Query
*/
function set_order_args( $search_data ) {
$period = $search_data['period'];
$args = [
// 'status' => [ 'completed' ],
'status' => 'completed',
'order_by' => 'date',
'order' => 'DESC',
];
if ( isset( $period['range'] ) ) {
if ( isset( $period['range']['start_date']) && isset( $period['range']['end_date'])) {
$args['date_before'] = $period['range']['end_date'];
$args['date_after'] = $period['range']['start_date'];
// Old way WC worked
// WC date range format (2018-08-01...2018-08-31)
// $range = implode( '...', $period['range'] );
// $args[ 'date_created'] = $range;
}
}
return $args;
}
function get_term_names() {
$tags = get_terms( array('product_tag'), "hide_empty=1" );
$tag_list = [];
if ( ! empty( $tags ) && ! is_wp_error( $tags ) ){
foreach ( $tags as $tag ) {
$tag_list[] = $tag->name;
}
}
return $tag_list;
}
/*
Read more here:
https://stackoverflow.com/questions/21858431/woocommerce-get-a-list-for-all-sku-product
*/
function get_sku_list() {
$skus = [];
$args = array( 'post_type' => 'product', 'posts_per_page' => -1 );
query_posts( $args );
if( have_posts() ):
while ( have_posts() ) : the_post();
global $post;
$product = wc_get_product($post->ID);
$sku = $product->get_sku();
if ( $sku != '')
{
array_push( $skus, $sku);
}
endwhile;
endif;
return $skus;
}
function get_tag_name( $product_id ) {
$tags = wp_get_post_terms( $product_id, 'product_tag' );
if ( count($tags) > 0 ) {
foreach ( $tags as $tag ) {
return $tag->name;
}
} else {
return 'blank';
}
}
function check_against_list( $data, $product, $property ) {
$push = (int) true;
if ( $data['all'] == 0 ) {
if ( is_array( $data['list'])) {
if ( ! in_array( htmlspecialchars_decode( $product['tag']), $data['list'] ) ) {
$push = 0;
}
} else {
$push = 0;
}
}
return $push;
}
function sum($row, $totals) {
(empty( $totals[$row['product_name' ]] ))
? $totals[$row['product_name' ]] = [(int) 1, $row['sku']]
: $totals[$row['product_name' ]][0]++;
return $totals;
}
function check_in_range( $start_date, $end_date, $order_date ) {
// Convert to timestamp
$start_ts = strtotime( $start_date );
$end_ts = strtotime( $end_date );
$user_ts = strtotime( $order_date );
// Check that user date is between start & end
return (( $user_ts >= $start_ts) && ( $user_ts <= $end_ts ));
}
// EMAIL
function mail_attachment($filename, $path, $mailto,
$from_mail, $from_name, $replyto,
$subject, $message)
{
$file = $path."/".$filename;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$header = "From: ".$from_name." <".$from_mail.">\r\n";
$header .= "Reply-To: ".$replyto."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n";
$my_message = $message;
$message = "";
$message .= "This is a multi-part message in MIME format.\r\n";
$message .= "--".$uid."\r\n";
$message .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$message .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$message .= $my_message."\r\n\r\n";
$message .= "--".$uid."\r\n";
$message .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use different content types here
$message .= "Content-Transfer-Encoding: base64\r\n";
$message .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$message .= $content."\r\n\r\n";
$message .= "--".$uid."--";
mail($mailto, $subject, $message, $header);
}
function notify( $filename, $path,
$subject = 'Export',
$report_type, $params)
{
$subject = $params['period']['type'] . ' Export';
$recipients = $params['search_data']['email_list'];
$sender_address = "web@thecompanydomain.com";
$sender_name = "Company Web site";
$reply_to = "web@thecompanydomain.com";
$subject = "Brand $subject";
$message = "Attached is the list of $report_type orders.";
mail_attachment( $filename, $path, $recipients,
$sender_address, $sender_name,
$reply_to, $subject, $message);
return 0;
}
if( !function_exists('pre')){
function pre($var = '') {
echo "<pre>";
print_r( $var );
echo "</pre><br>\n";
}
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T01:38:19.510",
"Id": "214289",
"Score": "2",
"Tags": [
"php",
"csv",
"wordpress"
],
"Title": "Generating two Woocommerce Order CSV files based off url query"
} | 214289 |
<p>I created this game in Python as a learning experience and was hoping for advice to make it better. I also used global and was hoping for good alternatives. </p>
<pre><code>import random
import pickle
import os
enemy_count = 0
health_pot_count = 5
level_up_counter = 1
class Player:
def __init__(self, name):
self.name = name
self.level = 1
self.health = 20
self.max_attack = 6
self.min_attack = 2
self.armour = 1
def __repr__(self):
return('Player({})'.format(self.name))
def __str__(self):
return('Name: {}, Level: {}, Health: {}, Max Attack: {}, Min Attack {}, Armour: {}'.format(self.name, self.level, self.health, self.max_attack, self.min_attack, self.armour))
def level_up(self):
global level_up_counter
if level_up_counter == self.level:
level_up_counter = 1
self.level += 1
self.max_attack += 3
self.min_attack += 3
self.armour += 2
else: level_up_counter += 1
def armour_up(self):
self.armour += 1
def weapon_up(self):
self.max_attack += 1
class World:
def __init__(self):
self.isenemy = random.choice([True, True, False])
def enter_room(self):
if self.isenemy:
fight()
else:
if random.choice([True, True, False]):
treasure()
else:
print('The room is empty')
class Enemy:
def __init__(self):
attack_buff = random.randint(-2,4)
self.health = 5 * pc.level + random.randint(-5,5)
self.max_attack = 3 * pc.level + attack_buff
self.min_attack = 2 * pc.level + attack_buff
self.armour = pc.level * random.randint(1,2)
def __str__(self):
return(f'Enemy Health {self.health}')
def save():
save_var = [current_room, rooms, pc, enemy_count, health_pot_count, level_up_counter, pc.name, pc.level, pc.health, pc.max_attack, pc.min_attack, pc.armour]
with open('save.pkl', 'wb') as save_pickle:
pickle.dump(save_var, save_pickle)
def get_save():
global current_room, rooms, pc, enemy_count, health_pot_count, level_up_counter
with open('save.pkl', 'rb') as save_pickle:
current_room, rooms, pc, enemy_count, health_pot_count, level_up_counter, pc.name, pc.level, pc.health, pc.max_attack, pc.min_attack, pc.armour = pickle.load(save_pickle)
def save_clear():
try:
os.remove(os.path.abspath('save.pkl'))
except Exception:
pass
def yn(promt):
loop = True
print (promt)
while loop:
yn_output = input("Y/N: ").lower()
if yn_output == 'y':
loop = False
return True
elif yn_output == 'n':
loop = False
return False
else: print('Invalid input!')
def new_game():
global current_room, rooms, pc, enemy_count, health_pot_count, level_up_counter
enemy_count = 0
health_pot_count = 5
level_up_counter = 1
save_clear()
name = input("What is the name of are brave adventurer: ")
#pc stands for player character.
pc = Player(name)
current_room = 0
rooms = ['start_room']
start_room = World()
def start_up():
print('Welcome to text dungeon')
start_loop = True
while start_loop:
new_game_test = yn('Is this a new game.')
if new_game_test == True:
if yn('Are you sure, this will clear all saves.'):
start_loop = False
new_game()
elif new_game_test == False:
start_loop = False
get_save()
def new_room(room, current_room):
room.append(str(current_room) + '_room')
room[current_room] = World()
def fight():
increment_enemy_count()
print('Starting combat!')
enemys = []
enemys.append('{}_enemy'.format(enemy_count))
enemys[0] = Enemy()
combat = True
while combat:
space()
print(pc)
print('Enemy Stats- Health: {}, Max Attack: {}, Min Attack {}, Armour: {}'.format(enemys[0].health, enemys[0].max_attack, enemys[0].min_attack, enemys[0].armour))
print('What is your move.')
action_wait = True
while action_wait:
action = input('1 = attack, 2 = Use health potion: ')
if action == '1':
attack_damage = random.randint(pc.min_attack, pc.max_attack)
if attack_damage < enemys[0].armour:
print(f'You did 0 damage.')
else:
enemys[0].health = (int(enemys[0].health) + int(enemys[0].armour)) - attack_damage
print(f'You did {int(attack_damage) - int(enemys[0].armour)} damage.')
if enemys[0].health < 1:
combat = False
action_wait = False
elif action == '2':
if health_pot_count > 0:
health_pot_use()
action_wait = False
else:
print('You have none.')
else:
print('Try again')
attack_damage = random.randint(enemys[0].min_attack, enemys[0].max_attack)
if attack_damage < pc.armour:
print(f'You took 0 damage.')
else:
pc.health = int((pc.health) + int(pc.armour) - attack_damage)
print(f'You took {int(attack_damage) - int(pc.armour)} damage.')
if (pc.health < 1):
combat = False
death()
print('You win')
pc.level_up()
treasure()
def treasure():
global health_pot_count
loot = random.randint(1, 5)
if loot == 1:
print('You got a health potion!')
health_pot_count += 1
elif loot == 2:
print('You got a better weapon!')
pc.weapon_up()
elif loot == 3:
print('You got better armour!')
pc.armour_up()
else:
print('No Loot')
def death():
print('You lose')
save_clear()
main()
def increment_enemy_count():
global enemy_count
enemy_count += 1
def health_pot_use():
global health_pot_count
health_pot_count -= 1
health_back = pc.level * 2 + random.randint(-2, 6)
pc.health += health_back
print(f'You got {health_back} health.')
def space():
print()
print()
def main():
global pc, current_room, play
start_up()
save()
play = True
while play:
wait_for_action = True
while wait_for_action:
save_clear()
save()
space()
print(str(pc))
print('What do you want to do.')
action = input("1 = continue, 2 = Use health potion: ")
if action == '1':
play = False
current_room += 1
new_room(rooms, current_room)
rooms[current_room].enter_room()
elif action == '2':
play = False
if health_pot_count > 0:
health_pot_use()
else: print('You have none.')
else: print('Invalid action!')
if __name__ == '__main__':
main()
</code></pre>
| [] | [
{
"body": "<h1>Decision loops</h1>\n\n<p>Your implementation of a decision loop is... interesting to say the least. If you're using <code>python-3.8</code>, you can utilize the <a href=\"https://www.geeksforgeeks.org/walrus-operator-in-python-3-8/\" rel=\"nofollow noreferrer\">walrus operator</a>. It's a way to assign variables within an expression. In this case, the <code>while</code> loop. Have a look:</p>\n\n<pre><code>def choice(prompt: str) -> bool: # replaced \"yn\" with \"choice\" #\n print(prompt)\n while decision := input(\"Y/N: \").lower():\n if decision in \"yn\":\n return decision == \"y\"\n print(\"Invalid input!\")\n</code></pre>\n\n<p>Instead of just returning <code>True</code> or <code>False</code>, you can return the boolean expression that evaluates to a boolean. It's the same thing you're doing, but a lot simpler.</p>\n\n<h1>Type Hints</h1>\n\n<p>Using type hints help you and other people reading your code know what types of parameters are accepted and what types are returned by functions. If you look at the function above, you can see that <code>prompt</code> is a <code>str</code>, and the function returns a <code>bool</code> value.</p>\n\n<h1>Dealing with exceptions</h1>\n\n<pre><code>def save_clear():\n try:\n os.remove(os.path.abspath('save.pkl'))\n except Exception:\n pass\n</code></pre>\n\n<p>Passing on an exception isn't a good idea. An Exception is raised, and you're essentially ignoring it. I would print an error message to the console, such as <code>\"ERROR: File not found!\"</code> or something related. Just to tell you whats wrong, instead of having an exception and not knowing what specifically is wrong. You should also try to catch specific exceptions if you can.</p>\n\n<h1>Consistency</h1>\n\n<p>You use three different ways to concatenate strings in your program. <code>.format</code>, <code>f\"\"</code> and <code>+</code>. Use one method and stick to it. I would recommend <code>f\"\"</code> because it allows you to directly include variables in your strings, rather than having to call a function (<code>.format</code>) to add them.</p>\n\n<h1>Globals</h1>\n\n<p><a href=\"https://stackoverflow.com/a/19158418/8968906\">It's not recommended to use globals</a>. They can have unseen consequences, increase the complexity of your program, and can lead to spaghetti code. I would try to find a way to write this program without using globals.</p>\n\n<h1>Boolean Comparison</h1>\n\n<p>Instead of</p>\n\n<pre><code>if new_game_test == True:\n</code></pre>\n\n<p>do this</p>\n\n<pre><code>if new_game_test:\n</code></pre>\n\n<p><code>new_game_test</code> is a boolean value in itself, so you can just check that value. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-26T20:47:11.050",
"Id": "239466",
"ParentId": "214292",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "239466",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-26T03:14:04.077",
"Id": "214292",
"Score": "5",
"Tags": [
"python",
"beginner",
"python-3.x",
"role-playing-game",
"battle-simulation"
],
"Title": "Text Dungeon in Python"
} | 214292 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.